forge
Explore
Log in

Don't you dare go Hollow

Rewrite editor in Rust and add media with live recording

Browse files at this commit

c49f5e7a2f04ec34bd587878adee93e7782cd41eAhmet Kaan GümüşParent: e100df4
  • feat
    • rewrite editor in Rust and add media with live recording
Show full message
✨ feat: rewrite editor in Rust and add media with live recording

Replace the TypeScript ProseMirror editor with a Rust wasm editor on a
single Loro text document, and remove the bun build.

Add media storage on the raw filesystem: uploads, Range serving, embeds,
paste and drop, import rewriting and zip export.

Add live audio recording. Takes are WebM/Opus with a permanent URL and
stream over a dedicated socket, so a browser crash loses at most about
the last second. A take can be continued later; its parts are joined
with Symphonia and our own WebM writer. The server never edits a note.

296 changed files +133050 -4182

.cargo/config.tomladded+2 -0
@@ -0,0 +1,2 @@
1+[alias]
2+xtask = "run -p xtask --"
.gitignoremodified+4 -1
@@ -1,3 +1,6 @@
1 /target1 /target
2-web/node_modules2+/media/
3 *.db*3 *.db*
4+/assets/editor-*.js
5+/assets/editor-*.wasm
6+/assets/editor.manifest
Cargo.lockmodified+1389 -64

Diff too large; view file

@@ -111,6 +111,12 @@ dependencies = [
111 "libc",111 "libc",
112 ]112 ]
113 113
114+[[package]]
115+name = "anstyle"
116+version = "1.0.14"
117+source = "registry+https://github.com/rust-lang/crates.io-index"
118+checksum = "940b3a0ca603d1eade50a4846a2afffd5ef57a9feac2c0e2ec2e14f9ead76000"
119+
114 [[package]]120 [[package]]
115 name = "antithesis_sdk"121 name = "antithesis_sdk"
116 version = "0.3.0"122 version = "0.3.0"
@@ -201,6 +207,17 @@ version = "0.1.3"
201 source = "registry+https://github.com/rust-lang/crates.io-index"207 source = "registry+https://github.com/rust-lang/crates.io-index"
202 checksum = "bfdc70193dadb9d7287fa4b633f15f90c876915b31f6af17da307fc59c9859a8"208 checksum = "bfdc70193dadb9d7287fa4b633f15f90c876915b31f6af17da307fc59c9859a8"
203 209
210+[[package]]
211+name = "ast_node"
212+version = "5.0.0"
213+source = "registry+https://github.com/rust-lang/crates.io-index"
214+checksum = "2eb025ef00a6da925cf40870b9c8d008526b6004ece399cb0974209720f0b194"
215+dependencies = [
216+ "quote",
217+ "swc_macros_common",
218+ "syn 2.0.119",
219+]
220+
204 [[package]]221 [[package]]
205 name = "async-compression"222 name = "async-compression"
206 version = "0.4.51"223 version = "0.4.51"
@@ -257,6 +274,21 @@ version = "0.23.1"
257 source = "registry+https://github.com/rust-lang/crates.io-index"274 source = "registry+https://github.com/rust-lang/crates.io-index"
258 checksum = "ac07cdecf99051d9a5238b80f35af32cdeba5b336e55d957b318b50137e18da5"275 checksum = "ac07cdecf99051d9a5238b80f35af32cdeba5b336e55d957b318b50137e18da5"
259 276
277+[[package]]
278+name = "beef"
279+version = "0.5.2"
280+source = "registry+https://github.com/rust-lang/crates.io-index"
281+checksum = "3a8241f3ebb85c056b509d4327ad0358fbbba6ffb340bf388f26350aeda225b1"
282+
283+[[package]]
284+name = "better_scoped_tls"
285+version = "1.0.1"
286+source = "registry+https://github.com/rust-lang/crates.io-index"
287+checksum = "7cd228125315b132eed175bf47619ac79b945b26e56b848ba203ae4ea8603609"
288+dependencies = [
289+ "scoped-tls",
290+]
291+
260 [[package]]292 [[package]]
261 name = "bigdecimal"293 name = "bigdecimal"
262 version = "0.4.11"294 version = "0.4.11"
@@ -413,11 +445,24 @@ dependencies = [
413 "alloc-stdlib",445 "alloc-stdlib",
414 ]446 ]
415 447
448+[[package]]
449+name = "bstr"
450+version = "1.13.1"
451+source = "registry+https://github.com/rust-lang/crates.io-index"
452+checksum = "6bb31b46c14244e20ee9984b11bf5c992b91fb6939fea616e3512c8baecdbe5f"
453+dependencies = [
454+ "memchr",
455+ "serde_core",
456+]
457+
416 [[package]]458 [[package]]
417 name = "bumpalo"459 name = "bumpalo"
418 version = "3.20.3"460 version = "3.20.3"
419 source = "registry+https://github.com/rust-lang/crates.io-index"461 source = "registry+https://github.com/rust-lang/crates.io-index"
420 checksum = "72f5acc6cb2ba439de613abc23857ec3d78374d8ed5ac84e9d11336e87da8649"462 checksum = "72f5acc6cb2ba439de613abc23857ec3d78374d8ed5ac84e9d11336e87da8649"
463+dependencies = [
464+ "allocator-api2 0.2.21",
465+]
421 466
422 [[package]]467 [[package]]
423 name = "bytemuck"468 name = "bytemuck"
@@ -451,6 +496,36 @@ version = "1.12.1"
451 source = "registry+https://github.com/rust-lang/crates.io-index"496 source = "registry+https://github.com/rust-lang/crates.io-index"
452 checksum = "fc652a48c352aef3ea3aed32080501cf3ef6ed5da78602a020c991775b0aff04"497 checksum = "fc652a48c352aef3ea3aed32080501cf3ef6ed5da78602a020c991775b0aff04"
453 498
499+[[package]]
500+name = "bytes-str"
501+version = "0.2.9"
502+source = "registry+https://github.com/rust-lang/crates.io-index"
503+checksum = "4dde6d05e75a31ec9610eb6446a6f0a10dd30ff5100d720fee4c7c7a9008b5ba"
504+dependencies = [
505+ "bytes",
506+ "serde",
507+]
508+
509+[[package]]
510+name = "capacity_builder"
511+version = "0.5.0"
512+source = "registry+https://github.com/rust-lang/crates.io-index"
513+checksum = "8f2d24a6dcf0cd402a21b65d35340f3a49ff3475dc5fdac91d22d2733e6641c6"
514+dependencies = [
515+ "capacity_builder_macros",
516+ "itoa",
517+]
518+
519+[[package]]
520+name = "capacity_builder_macros"
521+version = "0.3.0"
522+source = "registry+https://github.com/rust-lang/crates.io-index"
523+checksum = "3b4a6cae9efc04cc6cbb8faf338d2c497c165c83e74509cf4dbedea948bbf6e5"
524+dependencies = [
525+ "quote",
526+ "syn 2.0.119",
527+]
528+
454 [[package]]529 [[package]]
455 name = "cc"530 name = "cc"
456 version = "1.10.0"531 version = "1.10.0"
@@ -530,6 +605,32 @@ dependencies = [
530 "libloading",605 "libloading",
531 ]606 ]
532 607
608+[[package]]
609+name = "clap"
610+version = "4.6.7"
611+source = "registry+https://github.com/rust-lang/crates.io-index"
612+checksum = "aa8876b300ab35ba921adea3dfd70157a46249b33f95c9084ae5709785478946"
613+dependencies = [
614+ "clap_builder",
615+]
616+
617+[[package]]
618+name = "clap_builder"
619+version = "4.6.7"
620+source = "registry+https://github.com/rust-lang/crates.io-index"
621+checksum = "ec0797fb7aeb1406c84efac526901f7ec3ead2124f946b494e72879d4b54704d"
622+dependencies = [
623+ "anstyle",
624+ "clap_lex",
625+ "strsim",
626+]
627+
628+[[package]]
629+name = "clap_lex"
630+version = "1.1.1"
631+source = "registry+https://github.com/rust-lang/crates.io-index"
632+checksum = "1c133bc6a41be0d194c306b5506d15e6feeea7b1d6604bd3f8310dfb2ca96486"
633+
533 [[package]]634 [[package]]
534 name = "cobs"635 name = "cobs"
535 version = "0.3.0"636 version = "0.3.0"
@@ -539,6 +640,17 @@ dependencies = [
539 "thiserror 2.0.21",640 "thiserror 2.0.21",
540 ]641 ]
541 642
643+[[package]]
644+name = "codespan-reporting"
645+version = "0.13.1"
646+source = "registry+https://github.com/rust-lang/crates.io-index"
647+checksum = "af491d569909a7e4dee0ad7db7f5341fef5c614d5b8ec8cf765732aba3cff681"
648+dependencies = [
649+ "serde",
650+ "termcolor",
651+ "unicode-width 0.2.3",
652+]
653+
542 [[package]]654 [[package]]
543 name = "compression-codecs"655 name = "compression-codecs"
544 version = "0.4.46"656 version = "0.4.46"
@@ -596,12 +708,36 @@ dependencies = [
596 "version_check",708 "version_check",
597 ]709 ]
598 710
711+[[package]]
712+name = "cookie_store"
713+version = "0.22.1"
714+source = "registry+https://github.com/rust-lang/crates.io-index"
715+checksum = "15b2c103cf610ec6cae3da84a766285b42fd16aad564758459e6ecf128c75206"
716+dependencies = [
717+ "cookie",
718+ "document-features",
719+ "idna",
720+ "indexmap",
721+ "log",
722+ "serde",
723+ "serde_derive",
724+ "serde_json",
725+ "time",
726+ "url",
727+]
728+
599 [[package]]729 [[package]]
600 name = "core-foundation-sys"730 name = "core-foundation-sys"
601 version = "0.8.7"731 version = "0.8.7"
602 source = "registry+https://github.com/rust-lang/crates.io-index"732 source = "registry+https://github.com/rust-lang/crates.io-index"
603 checksum = "773648b94d0e5d620f64f280777445740e61fe701025087ec8b57f45c791888b"733 checksum = "773648b94d0e5d620f64f280777445740e61fe701025087ec8b57f45c791888b"
604 734
735+[[package]]
736+name = "countme"
737+version = "3.0.1"
738+source = "registry+https://github.com/rust-lang/crates.io-index"
739+checksum = "7704b5fdd17b18ae31c4c1da5a2e0305a2bf17b5249300a9ee9ed7b72114c636"
740+
605 [[package]]741 [[package]]
606 name = "cpufeatures"742 name = "cpufeatures"
607 version = "0.2.17"743 version = "0.2.17"
@@ -704,6 +840,12 @@ dependencies = [
704 "hybrid-array",840 "hybrid-array",
705 ]841 ]
706 842
843+[[package]]
844+name = "css_dataset"
845+version = "0.4.1"
846+source = "registry+https://github.com/rust-lang/crates.io-index"
847+checksum = "25670139e591f1c2869eb8d0d977028f8d05e859132b4c874ecd02a00d3c9174"
848+
707 [[package]]849 [[package]]
708 name = "ctr"850 name = "ctr"
709 version = "0.9.2"851 version = "0.9.2"
@@ -713,6 +855,68 @@ dependencies = [
713 "cipher",855 "cipher",
714 ]856 ]
715 857
858+[[package]]
859+name = "cxx"
860+version = "1.0.205"
861+source = "registry+https://github.com/rust-lang/crates.io-index"
862+checksum = "c8a02bfeba9074b2bbb39492c9b0908ec854f455a3cccdcde7a1de55e2315e40"
863+dependencies = [
864+ "cc",
865+ "cxx-build",
866+ "cxxbridge-cmd",
867+ "cxxbridge-flags",
868+ "cxxbridge-macro",
869+ "foldhash 0.2.0",
870+ "link-cplusplus",
871+]
872+
873+[[package]]
874+name = "cxx-build"
875+version = "1.0.205"
876+source = "registry+https://github.com/rust-lang/crates.io-index"
877+checksum = "bbc2ac76997619d2d888b58ad79488f1c835de41ca4dd3dd7082acf4ecb0a50f"
878+dependencies = [
879+ "cc",
880+ "codespan-reporting",
881+ "indexmap",
882+ "proc-macro2",
883+ "quote",
884+ "scratch",
885+ "syn 3.0.9",
886+]
887+
888+[[package]]
889+name = "cxxbridge-cmd"
890+version = "1.0.205"
891+source = "registry+https://github.com/rust-lang/crates.io-index"
892+checksum = "54a486ed16a3f2a053fe7f5b98db4c1a59846a23e8cb9e49f9d1bd48830d51a2"
893+dependencies = [
894+ "clap",
895+ "codespan-reporting",
896+ "indexmap",
897+ "proc-macro2",
898+ "quote",
899+ "syn 3.0.9",
900+]
901+
902+[[package]]
903+name = "cxxbridge-flags"
904+version = "1.0.205"
905+source = "registry+https://github.com/rust-lang/crates.io-index"
906+checksum = "c72569be94e2283764d334cd285980b747dbe221e27e315484eb6bcd93fa808a"
907+
908+[[package]]
909+name = "cxxbridge-macro"
910+version = "1.0.205"
911+source = "registry+https://github.com/rust-lang/crates.io-index"
912+checksum = "423e795284a7f7b3f843c956a5322c4bc497b60c2dd1a6339da10313cb18d575"
913+dependencies = [
914+ "indexmap",
915+ "proc-macro2",
916+ "quote",
917+ "syn 3.0.9",
918+]
919+
716 [[package]]920 [[package]]
717 name = "darling"921 name = "darling"
718 version = "0.20.11"922 version = "0.20.11"
@@ -788,12 +992,85 @@ version = "2.11.1"
788 source = "registry+https://github.com/rust-lang/crates.io-index"992 source = "registry+https://github.com/rust-lang/crates.io-index"
789 checksum = "4583a4551df46e2792f82ceeac45e850d2e2d5debba0b91f102385cda5b11f06"993 checksum = "4583a4551df46e2792f82ceeac45e850d2e2d5debba0b91f102385cda5b11f06"
790 994
995+[[package]]
996+name = "data-url"
997+version = "0.3.2"
998+source = "registry+https://github.com/rust-lang/crates.io-index"
999+checksum = "be1e0bca6c3637f992fc1cc7cbc52a78c1ef6db076dbf1059c4323d6a2048376"
1000+
791 [[package]]1001 [[package]]
792 name = "datasketches"1002 name = "datasketches"
793 version = "0.2.0"1003 version = "0.2.0"
794 source = "registry+https://github.com/rust-lang/crates.io-index"1004 source = "registry+https://github.com/rust-lang/crates.io-index"
795 checksum = "c286de4e81ea2590afc24d754e0f83810c566f50a1388fa75ebd57928c0d9745"1005 checksum = "c286de4e81ea2590afc24d754e0f83810c566f50a1388fa75ebd57928c0d9745"
796 1006
1007+[[package]]
1008+name = "deno_ast"
1009+version = "0.53.3"
1010+source = "registry+https://github.com/rust-lang/crates.io-index"
1011+checksum = "6f7c1384d87fc0a6439a065312fbef8f6ac6128689dbc2831b28b3a1d4f3a4e6"
1012+dependencies = [
1013+ "capacity_builder",
1014+ "deno_error",
1015+ "deno_media_type",
1016+ "deno_terminal",
1017+ "dprint-swc-ext",
1018+ "percent-encoding",
1019+ "serde",
1020+ "swc_atoms",
1021+ "swc_common",
1022+ "swc_ecma_ast",
1023+ "swc_ecma_lexer",
1024+ "swc_ecma_parser",
1025+ "swc_eq_ignore_macros",
1026+ "text_lines",
1027+ "thiserror 2.0.21",
1028+ "unicode-width 0.2.3",
1029+ "url",
1030+]
1031+
1032+[[package]]
1033+name = "deno_error"
1034+version = "0.7.3"
1035+source = "registry+https://github.com/rust-lang/crates.io-index"
1036+checksum = "3007d3f1ea92ea503324ae15883aac0c2de2b8cf6fead62203ff6a67161007ab"
1037+dependencies = [
1038+ "deno_error_macro",
1039+ "libc",
1040+]
1041+
1042+[[package]]
1043+name = "deno_error_macro"
1044+version = "0.7.3"
1045+source = "registry+https://github.com/rust-lang/crates.io-index"
1046+checksum = "9b565e60a9685cdf312c888665b5f8647ac692a7da7e058a5e2268a466da8eaf"
1047+dependencies = [
1048+ "proc-macro2",
1049+ "quote",
1050+ "syn 2.0.119",
1051+]
1052+
1053+[[package]]
1054+name = "deno_media_type"
1055+version = "0.4.0"
1056+source = "registry+https://github.com/rust-lang/crates.io-index"
1057+checksum = "debab24ecd9f4fd64aa42fb18a02dff20a97d5830b2b85b98ce70b509f790763"
1058+dependencies = [
1059+ "data-url",
1060+ "serde",
1061+ "url",
1062+]
1063+
1064+[[package]]
1065+name = "deno_terminal"
1066+version = "0.2.3"
1067+source = "registry+https://github.com/rust-lang/crates.io-index"
1068+checksum = "f3ba8041ae7319b3ca6a64c399df4112badcbbe0868b4517637647614bede4be"
1069+dependencies = [
1070+ "once_cell",
1071+ "termcolor",
1072+]
1073+
797 [[package]]1074 [[package]]
798 name = "deranged"1075 name = "deranged"
799 version = "0.5.9"1076 version = "0.5.9"
@@ -853,12 +1130,147 @@ dependencies = [
853 "syn 3.0.9",1130 "syn 3.0.9",
854 ]1131 ]
855 1132
1133+[[package]]
1134+name = "document-features"
1135+version = "0.2.12"
1136+source = "registry+https://github.com/rust-lang/crates.io-index"
1137+checksum = "d4b8a88685455ed29a21542a33abd9cb6510b6b129abadabdcef0f4c55bc8f61"
1138+dependencies = [
1139+ "litrs",
1140+]
1141+
856 [[package]]1142 [[package]]
857 name = "downcast-rs"1143 name = "downcast-rs"
858 version = "2.0.2"1144 version = "2.0.2"
859 source = "registry+https://github.com/rust-lang/crates.io-index"1145 source = "registry+https://github.com/rust-lang/crates.io-index"
860 checksum = "117240f60069e65410b3ae1bb213295bd828f707b5bec6596a1afc8793ce0cbc"1146 checksum = "117240f60069e65410b3ae1bb213295bd828f707b5bec6596a1afc8793ce0cbc"
861 1147
1148+[[package]]
1149+name = "dprint-core"
1150+version = "0.67.4"
1151+source = "registry+https://github.com/rust-lang/crates.io-index"
1152+checksum = "2c1d827947704a9495f705d6aeed270fa21a67f825f22902c28f38dc3af7a9ae"
1153+dependencies = [
1154+ "anyhow",
1155+ "bumpalo",
1156+ "hashbrown 0.15.5",
1157+ "indexmap",
1158+ "rustc-hash 2.1.3",
1159+ "serde",
1160+ "unicode-width 0.2.3",
1161+]
1162+
1163+[[package]]
1164+name = "dprint-core"
1165+version = "0.69.1"
1166+source = "registry+https://github.com/rust-lang/crates.io-index"
1167+checksum = "67359cea061dd052fca921d3589a9ce59bc16fa23bfb9d06d5c669a1dbd23915"
1168+dependencies = [
1169+ "bumpalo",
1170+ "hashbrown 0.15.5",
1171+ "indexmap",
1172+ "rustc-hash 2.1.3",
1173+ "serde",
1174+ "unicode-width 0.2.3",
1175+]
1176+
1177+[[package]]
1178+name = "dprint-core"
1179+version = "0.71.1"
1180+source = "registry+https://github.com/rust-lang/crates.io-index"
1181+checksum = "670d3c17cf65d37f5324b4fc198993148beb8c44e56fa4fe3676dd3c033d4e8c"
1182+dependencies = [
1183+ "bumpalo",
1184+ "hashbrown 0.15.5",
1185+ "indexmap",
1186+ "rustc-hash 2.1.3",
1187+ "serde",
1188+ "unicode-width 0.2.3",
1189+]
1190+
1191+[[package]]
1192+name = "dprint-core-macros"
1193+version = "0.1.0"
1194+source = "registry+https://github.com/rust-lang/crates.io-index"
1195+checksum = "1675ad2b358481f3cc46202040d64ac7a36c4ade414a696df32e0e45421a6e9f"
1196+dependencies = [
1197+ "quote",
1198+ "syn 1.0.109",
1199+]
1200+
1201+[[package]]
1202+name = "dprint-plugin-json"
1203+version = "0.25.2"
1204+source = "registry+https://github.com/rust-lang/crates.io-index"
1205+checksum = "1b9ee8da2b2565012674667b147e1f672ec9e897695d4e4a418c63ce6468e466"
1206+dependencies = [
1207+ "dprint-core 0.69.1",
1208+ "dprint-core-macros",
1209+ "jsonc-parser",
1210+ "serde",
1211+ "text_lines",
1212+ "thiserror 2.0.21",
1213+]
1214+
1215+[[package]]
1216+name = "dprint-plugin-markdown"
1217+version = "0.28.2"
1218+source = "registry+https://github.com/rust-lang/crates.io-index"
1219+checksum = "72f77690b7d85d149e7daea5bb83b55a1c7aefb8b9646c805ca70035fd74aa19"
1220+dependencies = [
1221+ "dprint-core 0.71.1",
1222+ "dprint-core-macros",
1223+ "serde",
1224+ "thiserror 2.0.21",
1225+ "unicode-width 0.2.3",
1226+]
1227+
1228+[[package]]
1229+name = "dprint-plugin-typescript"
1230+version = "0.96.1"
1231+source = "registry+https://github.com/rust-lang/crates.io-index"
1232+checksum = "90733c56ab425fc299c25ad81a5924bfc3c0050f25d865da742a6987b1255927"
1233+dependencies = [
1234+ "anyhow",
1235+ "capacity_builder",
1236+ "deno_ast",
1237+ "dprint-core 0.67.4",
1238+ "dprint-core-macros",
1239+ "percent-encoding",
1240+ "rustc-hash 2.1.3",
1241+ "serde",
1242+]
1243+
1244+[[package]]
1245+name = "dprint-swc-ext"
1246+version = "0.26.1"
1247+source = "registry+https://github.com/rust-lang/crates.io-index"
1248+checksum = "661f154a87e7459f54a2f4a1c615661a416a822b4a9e3ad0491dce2bd080421f"
1249+dependencies = [
1250+ "allocator-api2 0.2.21",
1251+ "bumpalo",
1252+ "num-bigint",
1253+ "rustc-hash 2.1.3",
1254+ "swc_atoms",
1255+ "swc_common",
1256+ "swc_ecma_ast",
1257+ "swc_ecma_lexer",
1258+ "swc_ecma_parser",
1259+ "text_lines",
1260+]
1261+
1262+[[package]]
1263+name = "editor"
1264+version = "0.1.0"
1265+dependencies = [
1266+ "js-sys",
1267+ "loro",
1268+ "note-model",
1269+ "wasm-bindgen",
1270+ "wasm-bindgen-futures",
1271+ "web-sys",
1272+]
1273+
862 [[package]]1274 [[package]]
863 name = "either"1275 name = "either"
864 version = "1.19.0"1276 version = "1.19.0"
@@ -1005,7 +1417,7 @@ checksum = "4e7f34442dbe69c60fe8eaf58a8cafff81a1f278816d8ab4db255b3bef4ac3c4"
1005 dependencies = [1417 dependencies = [
1006 "getrandom 0.3.4",1418 "getrandom 0.3.4",
1007 "libm",1419 "libm",
1008- "siphasher",1420+ "siphasher 1.0.4",
1009 ]1421 ]
1010 1422
1011 [[package]]1423 [[package]]
@@ -1043,6 +1455,12 @@ version = "1.0.7"
1043 source = "registry+https://github.com/rust-lang/crates.io-index"1455 source = "registry+https://github.com/rust-lang/crates.io-index"
1044 checksum = "3f9eec918d3f24069decb9af1554cad7c880e2da24a9afd88aca000531ab82c1"1456 checksum = "3f9eec918d3f24069decb9af1554cad7c880e2da24a9afd88aca000531ab82c1"
1045 1457
1458+[[package]]
1459+name = "foldhash"
1460+version = "0.1.5"
1461+source = "registry+https://github.com/rust-lang/crates.io-index"
1462+checksum = "d9c4f5dac5e15c24eb999c26181a6ca40b39fe946cbe4c263c7209467bc83af2"
1463+
1046 [[package]]1464 [[package]]
1047 name = "foldhash"1465 name = "foldhash"
1048 version = "0.2.0"1466 version = "0.2.0"
@@ -1058,6 +1476,16 @@ dependencies = [
1058 "percent-encoding",1476 "percent-encoding",
1059 ]1477 ]
1060 1478
1479+[[package]]
1480+name = "from_variant"
1481+version = "3.0.0"
1482+source = "registry+https://github.com/rust-lang/crates.io-index"
1483+checksum = "e5ff35a391aef949120a0340d690269b3d9f63460a6106e99bd07b961f345ea9"
1484+dependencies = [
1485+ "swc_macros_common",
1486+ "syn 2.0.119",
1487+]
1488+
1061 [[package]]1489 [[package]]
1062 name = "fs4"1490 name = "fs4"
1063 version = "0.13.1"1491 version = "0.13.1"
@@ -1230,12 +1658,36 @@ dependencies = [
1230 "polyval",1658 "polyval",
1231 ]1659 ]
1232 1660
1661+[[package]]
1662+name = "gimli"
1663+version = "0.32.3"
1664+source = "registry+https://github.com/rust-lang/crates.io-index"
1665+checksum = "e629b9b98ef3dd8afe6ca2bd0f89306cec16d43d907889945bc5d6687f2f13c7"
1666+dependencies = [
1667+ "fallible-iterator",
1668+ "indexmap",
1669+ "stable_deref_trait",
1670+]
1671+
1233 [[package]]1672 [[package]]
1234 name = "glob"1673 name = "glob"
1235 version = "0.3.4"1674 version = "0.3.4"
1236 source = "registry+https://github.com/rust-lang/crates.io-index"1675 source = "registry+https://github.com/rust-lang/crates.io-index"
1237 checksum = "e4eba85ea1d0a966a983acd07deee566e67395d2d96b6fb39e62b5a833f1eb0b"1676 checksum = "e4eba85ea1d0a966a983acd07deee566e67395d2d96b6fb39e62b5a833f1eb0b"
1238 1677
1678+[[package]]
1679+name = "globset"
1680+version = "0.4.21"
1681+source = "registry+https://github.com/rust-lang/crates.io-index"
1682+checksum = "f98b0d85522dc0a824cfebbc9594ff4a9b289c568bea0370319dfbdf20ccdd2d"
1683+dependencies = [
1684+ "aho-corasick",
1685+ "bstr",
1686+ "log",
1687+ "regex-automata",
1688+ "regex-syntax 0.8.11",
1689+]
1690+
1239 [[package]]1691 [[package]]
1240 name = "h2"1692 name = "h2"
1241 version = "0.4.20"1693 version = "0.4.20"
@@ -1273,6 +1725,27 @@ dependencies = [
1273 "byteorder",1725 "byteorder",
1274 ]1726 ]
1275 1727
1728+[[package]]
1729+name = "hashbrown"
1730+version = "0.14.5"
1731+source = "registry+https://github.com/rust-lang/crates.io-index"
1732+checksum = "e5274423e17b7c9fc20b6e7e208532f9b19825d82dfd615708b70edd83df41f1"
1733+dependencies = [
1734+ "ahash",
1735+ "allocator-api2 0.2.21",
1736+]
1737+
1738+[[package]]
1739+name = "hashbrown"
1740+version = "0.15.5"
1741+source = "registry+https://github.com/rust-lang/crates.io-index"
1742+checksum = "9229cfe53dfd69f0609a49f65461bd93001ea1ef889cd5529dd176593f5338a1"
1743+dependencies = [
1744+ "allocator-api2 0.2.21",
1745+ "equivalent",
1746+ "foldhash 0.1.5",
1747+]
1748+
1276 [[package]]1749 [[package]]
1277 name = "hashbrown"1750 name = "hashbrown"
1278 version = "0.16.1"1751 version = "0.16.1"
@@ -1281,7 +1754,9 @@ checksum = "841d1cc9bed7f9236f321df977030373f4a4163ae1a7dbfe1a51a2c1a51d9100"
1281 dependencies = [1754 dependencies = [
1282 "allocator-api2 0.2.21",1755 "allocator-api2 0.2.21",
1283 "equivalent",1756 "equivalent",
1284- "foldhash",1757+ "foldhash 0.2.0",
1758+ "serde",
1759+ "serde_core",
1285 ]1760 ]
1286 1761
1287 [[package]]1762 [[package]]
@@ -1289,6 +1764,11 @@ name = "hashbrown"
1289 version = "0.17.1"1764 version = "0.17.1"
1290 source = "registry+https://github.com/rust-lang/crates.io-index"1765 source = "registry+https://github.com/rust-lang/crates.io-index"
1291 checksum = "ed5909b6e89a2db4456e54cd5f673791d7eca6732202bbf2a9cc504fe2f9b84a"1766 checksum = "ed5909b6e89a2db4456e54cd5f673791d7eca6732202bbf2a9cc504fe2f9b84a"
1767+dependencies = [
1768+ "allocator-api2 0.2.21",
1769+ "equivalent",
1770+ "foldhash 0.2.0",
1771+]
1292 1772
1293 [[package]]1773 [[package]]
1294 name = "heapless"1774 name = "heapless"
@@ -1386,6 +1866,20 @@ dependencies = [
1386 "windows-link",1866 "windows-link",
1387 ]1867 ]
1388 1868
1869+[[package]]
1870+name = "hstr"
1871+version = "3.0.6"
1872+source = "registry+https://github.com/rust-lang/crates.io-index"
1873+checksum = "83bb87e4b300d73412f6dcc7022ee7741452b51b155c2b06e5994d0770c2dbe2"
1874+dependencies = [
1875+ "hashbrown 0.14.5",
1876+ "new_debug_unreachable",
1877+ "once_cell",
1878+ "rustc-hash 2.1.3",
1879+ "serde",
1880+ "triomphe",
1881+]
1882+
1389 [[package]]1883 [[package]]
1390 name = "htmlescape"1884 name = "htmlescape"
1391 version = "0.3.1"1885 version = "0.3.1"
@@ -1660,6 +2154,15 @@ dependencies = [
1660 "zerovec",2154 "zerovec",
1661 ]2155 ]
1662 2156
2157+[[package]]
2158+name = "id-arena"
2159+version = "2.3.0"
2160+source = "registry+https://github.com/rust-lang/crates.io-index"
2161+checksum = "3d3067d79b975e8844ca9eb072e16b31c3c1c36928edf9c6789548c524d0d954"
2162+dependencies = [
2163+ "rayon",
2164+]
2165+
1663 [[package]]2166 [[package]]
1664 name = "ident_case"2167 name = "ident_case"
1665 version = "1.0.1"2168 version = "1.0.1"
@@ -1710,6 +2213,8 @@ checksum = "cc4e190f5d26ca7051642629da2c52fc03bde85a03197c99408dcd291734c855"
1710 dependencies = [2213 dependencies = [
1711 "equivalent",2214 "equivalent",
1712 "hashbrown 0.17.1",2215 "hashbrown 0.17.1",
2216+ "serde",
2217+ "serde_core",
1713 ]2218 ]
1714 2219
1715 [[package]]2220 [[package]]
@@ -1756,6 +2261,27 @@ version = "2.12.2"
1756 source = "registry+https://github.com/rust-lang/crates.io-index"2261 source = "registry+https://github.com/rust-lang/crates.io-index"
1757 checksum = "791930b43c0d5973160d90a8f3894509f2b273430f5c5c73b668636d0287c5c0"2262 checksum = "791930b43c0d5973160d90a8f3894509f2b273430f5c5c73b668636d0287c5c0"
1758 2263
2264+[[package]]
2265+name = "is-macro"
2266+version = "0.3.8"
2267+source = "registry+https://github.com/rust-lang/crates.io-index"
2268+checksum = "8267aa6001e25494f3015f9663bbd88a18240c74483afa5f0934a1b3e4c388e9"
2269+dependencies = [
2270+ "heck 0.5.0",
2271+ "proc-macro2",
2272+ "quote",
2273+ "syn 2.0.119",
2274+]
2275+
2276+[[package]]
2277+name = "itertools"
2278+version = "0.10.5"
2279+source = "registry+https://github.com/rust-lang/crates.io-index"
2280+checksum = "b0fd2260e829bddf4cb6ea802289de2f86d6a7a690192fbe91b3f46e0f2c8473"
2281+dependencies = [
2282+ "either",
2283+]
2284+
1759 [[package]]2285 [[package]]
1760 name = "itertools"2286 name = "itertools"
1761 version = "0.11.0"2287 version = "0.11.0"
@@ -1783,6 +2309,15 @@ dependencies = [
1783 "either",2309 "either",
1784 ]2310 ]
1785 2311
2312+[[package]]
2313+name = "itertools"
2314+version = "0.15.0"
2315+source = "registry+https://github.com/rust-lang/crates.io-index"
2316+checksum = "8b4baf93f58d4425749ca49a51c50ebab072c5df6994d08fed93541c331481dc"
2317+dependencies = [
2318+ "either",
2319+]
2320+
1786 [[package]]2321 [[package]]
1787 name = "itoa"2322 name = "itoa"
1788 version = "1.0.18"2323 version = "1.0.18"
@@ -1810,6 +2345,15 @@ dependencies = [
1810 "wasm-bindgen",2345 "wasm-bindgen",
1811 ]2346 ]
1812 2347
2348+[[package]]
2349+name = "jsonc-parser"
2350+version = "0.34.0"
2351+source = "registry+https://github.com/rust-lang/crates.io-index"
2352+checksum = "0ecded084f9b9a718d39668a42657c32253663d1f6afb3fbb9134f0305f73f48"
2353+dependencies = [
2354+ "unicode-width 0.2.3",
2355+]
2356+
1813 [[package]]2357 [[package]]
1814 name = "lazy_static"2358 name = "lazy_static"
1815 version = "1.5.1"2359 version = "1.5.1"
@@ -1828,6 +2372,12 @@ version = "0.2.7"
1828 source = "registry+https://github.com/rust-lang/crates.io-index"2372 source = "registry+https://github.com/rust-lang/crates.io-index"
1829 checksum = "c83bff1d572d6b9aeef67ddfc8448e4a3737909cb28e81f97c791b9018703e52"2373 checksum = "c83bff1d572d6b9aeef67ddfc8448e4a3737909cb28e81f97c791b9018703e52"
1830 2374
2375+[[package]]
2376+name = "leb128fmt"
2377+version = "0.1.0"
2378+source = "registry+https://github.com/rust-lang/crates.io-index"
2379+checksum = "09edd9e8b54e49e587e4f6295a7d29c3ea94d469cb40ab8ca70b288248a81db2"
2380+
1831 [[package]]2381 [[package]]
1832 name = "lettre"2382 name = "lettre"
1833 version = "0.11.23"2383 version = "0.11.23"
@@ -1882,6 +2432,15 @@ dependencies = [
1882 "cc",2432 "cc",
1883 ]2433 ]
1884 2434
2435+[[package]]
2436+name = "link-cplusplus"
2437+version = "1.0.12"
2438+source = "registry+https://github.com/rust-lang/crates.io-index"
2439+checksum = "7f78c730aaa7d0b9336a299029ea49f9ee53b0ed06e9202e8cb7db9bae7b8c82"
2440+dependencies = [
2441+ "cc",
2442+]
2443+
1885 [[package]]2444 [[package]]
1886 name = "linkme"2445 name = "linkme"
1887 version = "0.3.37"2446 version = "0.3.37"
@@ -1920,6 +2479,12 @@ version = "0.8.3"
1920 source = "registry+https://github.com/rust-lang/crates.io-index"2479 source = "registry+https://github.com/rust-lang/crates.io-index"
1921 checksum = "47d9d19d1d6efa0109d2f65ff4c85cddd50bd572e5a00127ab10987290bcefae"2480 checksum = "47d9d19d1d6efa0109d2f65ff4c85cddd50bd572e5a00127ab10987290bcefae"
1922 2481
2482+[[package]]
2483+name = "litrs"
2484+version = "1.0.1"
2485+source = "registry+https://github.com/rust-lang/crates.io-index"
2486+checksum = "4744e383959f0db86ede514b809b1c53251889093803c05267acc7d4e7030d70"
2487+
1923 [[package]]2488 [[package]]
1924 name = "lock_api"2489 name = "lock_api"
1925 version = "0.4.14"2490 version = "0.4.14"
@@ -1935,6 +2500,29 @@ version = "0.4.34"
1935 source = "registry+https://github.com/rust-lang/crates.io-index"2500 source = "registry+https://github.com/rust-lang/crates.io-index"
1936 checksum = "f9f8bd3e56ce4dfc153cf470fffbfa98c7620958b312ca5c3a4b8d5181fd13c6"2501 checksum = "f9f8bd3e56ce4dfc153cf470fffbfa98c7620958b312ca5c3a4b8d5181fd13c6"
1937 2502
2503+[[package]]
2504+name = "logos"
2505+version = "0.12.1"
2506+source = "registry+https://github.com/rust-lang/crates.io-index"
2507+checksum = "bf8b031682c67a8e3d5446840f9573eb7fe26efe7ec8d195c9ac4c0647c502f1"
2508+dependencies = [
2509+ "logos-derive",
2510+]
2511+
2512+[[package]]
2513+name = "logos-derive"
2514+version = "0.12.1"
2515+source = "registry+https://github.com/rust-lang/crates.io-index"
2516+checksum = "a1d849148dbaf9661a6151d1ca82b13bb4c4c128146a88d05253b38d4e2f496c"
2517+dependencies = [
2518+ "beef",
2519+ "fnv",
2520+ "proc-macro2",
2521+ "quote",
2522+ "regex-syntax 0.6.29",
2523+ "syn 1.0.109",
2524+]
2525+
1938 [[package]]2526 [[package]]
1939 name = "loom"2527 name = "loom"
1940 version = "0.7.2"2528 version = "0.7.2"
@@ -1999,8 +2587,6 @@ dependencies = [
1999 [[package]]2587 [[package]]
2000 name = "loro-internal"2588 name = "loro-internal"
2001 version = "1.17.1"2589 version = "1.17.1"
2002-source = "registry+https://github.com/rust-lang/crates.io-index"
2003-checksum = "7e533c1688430aa4fcdd933f00861e331c169a4158ee6d27d054e0558892d447"
2004 dependencies = [2590 dependencies = [
2005 "append-only-bytes",2591 "append-only-bytes",
2006 "arref",2592 "arref",
@@ -2112,6 +2698,34 @@ version = "0.13.1"
2112 source = "registry+https://github.com/rust-lang/crates.io-index"2698 source = "registry+https://github.com/rust-lang/crates.io-index"
2113 checksum = "7ef0d4ed8669f8f8826eb00dc878084aa8f253506c4fd5e8f58f5bce72ddb97e"2699 checksum = "7ef0d4ed8669f8f8826eb00dc878084aa8f253506c4fd5e8f58f5bce72ddb97e"
2114 2700
2701+[[package]]
2702+name = "malva"
2703+version = "0.16.0"
2704+source = "registry+https://github.com/rust-lang/crates.io-index"
2705+checksum = "ed54a855fc80dddeb3518c03d04a2bb06954955297ee514429935149e58eaa75"
2706+dependencies = [
2707+ "aho-corasick",
2708+ "itertools 0.14.0",
2709+ "memchr",
2710+ "raffia",
2711+ "tiny_pretty 0.4.5",
2712+]
2713+
2714+[[package]]
2715+name = "markup_fmt"
2716+version = "0.27.6"
2717+source = "registry+https://github.com/rust-lang/crates.io-index"
2718+checksum = "df2c4bb9a66c59714ba02c074187491e30daaf99127dcb287ce2aa8fa0c1a9fe"
2719+dependencies = [
2720+ "aho-corasick",
2721+ "anyhow",
2722+ "css_dataset",
2723+ "itertools 0.15.0",
2724+ "memchr",
2725+ "regex",
2726+ "tiny_pretty 0.4.5",
2727+]
2728+
2115 [[package]]2729 [[package]]
2116 name = "matchers"2730 name = "matchers"
2117 version = "0.2.0"2731 version = "0.2.0"
@@ -2174,7 +2788,7 @@ checksum = "5f98efec8807c63c752b5bd61f862c165c115b0a35685bdcfd9238c7aeb592b7"
2174 dependencies = [2788 dependencies = [
2175 "cfg-if",2789 "cfg-if",
2176 "miette-derive",2790 "miette-derive",
2177- "unicode-width",2791+ "unicode-width 0.1.14",
2178 ]2792 ]
2179 2793
2180 [[package]]2794 [[package]]
@@ -2247,16 +2861,10 @@ source = "registry+https://github.com/rust-lang/crates.io-index"
2247 checksum = "2195bf6aa996a481483b29d62a7663eed3fe39600c460e323f8ff41e90bdd89b"2861 checksum = "2195bf6aa996a481483b29d62a7663eed3fe39600c460e323f8ff41e90bdd89b"
2248 2862
2249 [[package]]2863 [[package]]
2250-name = "nix"2864+name = "new_debug_unreachable"
2251-version = "0.31.3"2865+version = "1.0.6"
2252 source = "registry+https://github.com/rust-lang/crates.io-index"2866 source = "registry+https://github.com/rust-lang/crates.io-index"
2253-checksum = "cf20d2fde8ff38632c426f1165ed7436270b44f199fc55284c38276f9db47c3d"2867+checksum = "650eef8c711430f1a879fdd01d4745a7deea475becfb90269c06775983bbf086"
2254-dependencies = [
2255- "bitflags",
2256- "cfg-if",
2257- "cfg_aliases",
2258- "libc",
2259-]
2260 2868
2261 [[package]]2869 [[package]]
2262 name = "nom"2870 name = "nom"
@@ -2283,6 +2891,13 @@ version = "0.5.5"
2283 source = "registry+https://github.com/rust-lang/crates.io-index"2891 source = "registry+https://github.com/rust-lang/crates.io-index"
2284 checksum = "610a5acd306ec67f907abe5567859a3c693fb9886eb1f012ab8f2a47bef3db51"2892 checksum = "610a5acd306ec67f907abe5567859a3c693fb9886eb1f012ab8f2a47bef3db51"
2285 2893
2894+[[package]]
2895+name = "note-model"
2896+version = "0.1.0"
2897+dependencies = [
2898+ "loro",
2899+]
2900+
2286 [[package]]2901 [[package]]
2287 name = "nu-ansi-term"2902 name = "nu-ansi-term"
2288 version = "0.50.3"2903 version = "0.50.3"
@@ -2314,6 +2929,7 @@ checksum = "c89e69e7e0f03bea5ef08013795c25018e101932225a656383bd384495ecc367"
2314 dependencies = [2929 dependencies = [
2315 "num-integer",2930 "num-integer",
2316 "num-traits",2931 "num-traits",
2932+ "serde",
2317 ]2933 ]
2318 2934
2319 [[package]]2935 [[package]]
@@ -2509,6 +3125,48 @@ dependencies = [
2509 "stacker",3125 "stacker",
2510 ]3126 ]
2511 3127
3128+[[package]]
3129+name = "phf"
3130+version = "0.11.3"
3131+source = "registry+https://github.com/rust-lang/crates.io-index"
3132+checksum = "1fd6780a80ae0c52cc120a26a1a42c1ae51b247a253e4e06113d23d2c2edd078"
3133+dependencies = [
3134+ "phf_macros",
3135+ "phf_shared",
3136+]
3137+
3138+[[package]]
3139+name = "phf_generator"
3140+version = "0.11.3"
3141+source = "registry+https://github.com/rust-lang/crates.io-index"
3142+checksum = "3c80231409c20246a13fddb31776fb942c38553c51e871f8cbd687a4cfb5843d"
3143+dependencies = [
3144+ "phf_shared",
3145+ "rand 0.8.8",
3146+]
3147+
3148+[[package]]
3149+name = "phf_macros"
3150+version = "0.11.3"
3151+source = "registry+https://github.com/rust-lang/crates.io-index"
3152+checksum = "f84ac04429c13a7ff43785d75ad27569f2951ce0ffd30a3321230db2fc727216"
3153+dependencies = [
3154+ "phf_generator",
3155+ "phf_shared",
3156+ "proc-macro2",
3157+ "quote",
3158+ "syn 2.0.119",
3159+]
3160+
3161+[[package]]
3162+name = "phf_shared"
3163+version = "0.11.3"
3164+source = "registry+https://github.com/rust-lang/crates.io-index"
3165+checksum = "67eabc2ef2a60eb7faa00097bd1ffdb5bd28e62bf39990626a582201b7a754e5"
3166+dependencies = [
3167+ "siphasher 1.0.4",
3168+]
3169+
2512 [[package]]3170 [[package]]
2513 name = "pin-project-lite"3171 name = "pin-project-lite"
2514 version = "0.2.17"3172 version = "0.2.17"
@@ -2596,6 +3254,17 @@ dependencies = [
2596 "yansi",3254 "yansi",
2597 ]3255 ]
2598 3256
3257+[[package]]
3258+name = "pretty_yaml"
3259+version = "0.6.0"
3260+source = "registry+https://github.com/rust-lang/crates.io-index"
3261+checksum = "6f5db2b0044c0dae209c173c6049f210c9449092b07304c9c8b8d555c606e93e"
3262+dependencies = [
3263+ "rowan 0.16.1",
3264+ "tiny_pretty 0.2.1",
3265+ "yaml_parser",
3266+]
3267+
2599 [[package]]3268 [[package]]
2600 name = "prettyplease"3269 name = "prettyplease"
2601 version = "0.2.37"3270 version = "0.2.37"
@@ -2640,16 +3309,35 @@ version = "0.1.0"
2640 dependencies = [3309 dependencies = [
2641 "anyhow",3310 "anyhow",
2642 "blake3",3311 "blake3",
3312+ "bytes",
3313+ "crc32fast",
3314+ "dprint-plugin-json",
3315+ "dprint-plugin-markdown",
3316+ "dprint-plugin-typescript",
3317+ "flate2",
3318+ "hashbrown 0.17.1",
3319+ "http-body",
2643 "loro",3320 "loro",
3321+ "malva",
3322+ "markup_fmt",
3323+ "note-model",
3324+ "pretty_yaml",
3325+ "prettyplease 0.3.0",
2644 "pulldown-cmark",3326 "pulldown-cmark",
2645 "regex",3327 "regex",
3328+ "regex-syntax 0.8.11",
3329+ "rustc-hash 2.1.3",
2646 "serde",3330 "serde",
2647 "serde_json",3331 "serde_json",
3332+ "sqlformat",
3333+ "symphonia",
3334+ "syn 3.0.9",
3335+ "taplo",
3336+ "thread-priority",
2648 "tokio",3337 "tokio",
2649 "topcoat",3338 "topcoat",
2650 "turso",3339 "turso",
2651 "uuid",3340 "uuid",
2652- "zip",
2653 ]3341 ]
2654 3342
2655 [[package]]3343 [[package]]
@@ -2740,6 +3428,27 @@ version = "0.7.0"
2740 source = "registry+https://github.com/rust-lang/crates.io-index"3428 source = "registry+https://github.com/rust-lang/crates.io-index"
2741 checksum = "dc33ff2d4973d518d823d61aa239014831e521c75da58e3df4840d3f47749d09"3429 checksum = "dc33ff2d4973d518d823d61aa239014831e521c75da58e3df4840d3f47749d09"
2742 3430
3431+[[package]]
3432+name = "raffia"
3433+version = "0.12.3"
3434+source = "registry+https://github.com/rust-lang/crates.io-index"
3435+checksum = "a589c5611a5f7713bf0c13e949c4c791a359ff517a9f27552475b470e8873229"
3436+dependencies = [
3437+ "raffia_macro",
3438+ "smallvec",
3439+]
3440+
3441+[[package]]
3442+name = "raffia_macro"
3443+version = "0.2.0"
3444+source = "registry+https://github.com/rust-lang/crates.io-index"
3445+checksum = "8ac21f5e4bc6b29ea5d5e691a9aa08b2b9fd8891f48a99157b9f02d8a48e1318"
3446+dependencies = [
3447+ "heck 0.5.0",
3448+ "quote",
3449+ "syn 2.0.119",
3450+]
3451+
2743 [[package]]3452 [[package]]
2744 name = "rand"3453 name = "rand"
2745 version = "0.8.8"3454 version = "0.8.8"
@@ -2884,7 +3593,7 @@ dependencies = [
2884 "aho-corasick",3593 "aho-corasick",
2885 "memchr",3594 "memchr",
2886 "regex-automata",3595 "regex-automata",
2887- "regex-syntax",3596+ "regex-syntax 0.8.11",
2888 ]3597 ]
2889 3598
2890 [[package]]3599 [[package]]
@@ -2895,9 +3604,21 @@ checksum = "ad8553b9b26413251cbf30e620595c7a41b3887f03da04579c0e6b0d6a06b4b2"
2895 dependencies = [3604 dependencies = [
2896 "aho-corasick",3605 "aho-corasick",
2897 "memchr",3606 "memchr",
2898- "regex-syntax",3607+ "regex-syntax 0.8.11",
2899 ]3608 ]
2900 3609
3610+[[package]]
3611+name = "regex-lite"
3612+version = "0.1.9"
3613+source = "registry+https://github.com/rust-lang/crates.io-index"
3614+checksum = "cab834c73d247e67f4fae452806d17d3c7501756d98c8808d7c9c7aa7d18f973"
3615+
3616+[[package]]
3617+name = "regex-syntax"
3618+version = "0.6.29"
3619+source = "registry+https://github.com/rust-lang/crates.io-index"
3620+checksum = "f162c6dd7b008981e4d40210aca20b4bd0f9b60ca9271061b07f78537722f2e1"
3621+
2901 [[package]]3622 [[package]]
2902 name = "regex-syntax"3623 name = "regex-syntax"
2903 version = "0.8.11"3624 version = "0.8.11"
@@ -2928,6 +3649,31 @@ dependencies = [
2928 "byteorder",3649 "byteorder",
2929 ]3650 ]
2930 3651
3652+[[package]]
3653+name = "rowan"
3654+version = "0.15.19"
3655+source = "registry+https://github.com/rust-lang/crates.io-index"
3656+checksum = "a2441aaccb50f4267d4f0f58b21e0138e96a449f361ed57a2673a83c9bca0772"
3657+dependencies = [
3658+ "countme",
3659+ "hashbrown 0.14.5",
3660+ "memoffset",
3661+ "rustc-hash 1.1.0",
3662+ "text-size",
3663+]
3664+
3665+[[package]]
3666+name = "rowan"
3667+version = "0.16.1"
3668+source = "registry+https://github.com/rust-lang/crates.io-index"
3669+checksum = "417a3a9f582e349834051b8a10c8d71ca88da4211e4093528e36b9845f6b5f21"
3670+dependencies = [
3671+ "countme",
3672+ "hashbrown 0.14.5",
3673+ "rustc-hash 1.1.0",
3674+ "text-size",
3675+]
3676+
2931 [[package]]3677 [[package]]
2932 name = "rust-stemmers"3678 name = "rust-stemmers"
2933 version = "1.2.0"3679 version = "1.2.0"
@@ -2938,6 +3684,12 @@ dependencies = [
2938 "serde_derive",3684 "serde_derive",
2939 ]3685 ]
2940 3686
3687+[[package]]
3688+name = "rustc-demangle"
3689+version = "0.1.28"
3690+source = "registry+https://github.com/rust-lang/crates.io-index"
3691+checksum = "b74b56ffa8bb2830709a538c2cbcae9aa062db0d2a42563bfb09bdaae44020eb"
3692+
2941 [[package]]3693 [[package]]
2942 name = "rustc-hash"3694 name = "rustc-hash"
2943 version = "1.1.0"3695 version = "1.1.0"
@@ -3054,12 +3806,24 @@ version = "1.2.0"
3054 source = "registry+https://github.com/rust-lang/crates.io-index"3806 source = "registry+https://github.com/rust-lang/crates.io-index"
3055 checksum = "94143f37725109f92c262ed2cf5e59bce7498c01bcc1502d7b9afe439a4e9f49"3807 checksum = "94143f37725109f92c262ed2cf5e59bce7498c01bcc1502d7b9afe439a4e9f49"
3056 3808
3809+[[package]]
3810+name = "scratch"
3811+version = "1.0.9"
3812+source = "registry+https://github.com/rust-lang/crates.io-index"
3813+checksum = "d68f2ec51b097e4c1a75b681a8bec621909b5e91f15bb7b840c4f2f7b01148b2"
3814+
3057 [[package]]3815 [[package]]
3058 name = "semver"3816 name = "semver"
3059 version = "1.0.28"3817 version = "1.0.28"
3060 source = "registry+https://github.com/rust-lang/crates.io-index"3818 source = "registry+https://github.com/rust-lang/crates.io-index"
3061 checksum = "8a7852d02fc848982e0c167ef163aaff9cd91dc640ba85e263cb1ce46fae51cd"3819 checksum = "8a7852d02fc848982e0c167ef163aaff9cd91dc640ba85e263cb1ce46fae51cd"
3062 3820
3821+[[package]]
3822+name = "seq-macro"
3823+version = "0.3.6"
3824+source = "registry+https://github.com/rust-lang/crates.io-index"
3825+checksum = "1bc711410fbe7399f390ca1c3b60ad0f53f80e95c5eb935e52268a0e2cd49acc"
3826+
3063 [[package]]3827 [[package]]
3064 name = "serde"3828 name = "serde"
3065 version = "1.0.229"3829 version = "1.0.229"
@@ -3271,6 +4035,12 @@ dependencies = [
3271 "cc",4035 "cc",
3272 ]4036 ]
3273 4037
4038+[[package]]
4039+name = "siphasher"
4040+version = "0.3.11"
4041+source = "registry+https://github.com/rust-lang/crates.io-index"
4042+checksum = "38b58827f4464d87d377d175e90bf58eb00fd8716ff0a62f80356b5e61555d0d"
4043+
3274 [[package]]4044 [[package]]
3275 name = "siphasher"4045 name = "siphasher"
3276 version = "1.0.4"4046 version = "1.0.4"
@@ -3311,6 +4081,17 @@ dependencies = [
3311 "serde",4081 "serde",
3312 ]4082 ]
3313 4083
4084+[[package]]
4085+name = "smartstring"
4086+version = "1.0.1"
4087+source = "registry+https://github.com/rust-lang/crates.io-index"
4088+checksum = "3fb72c633efbaa2dd666986505016c32c3044395ceaf881518399d2f4127ee29"
4089+dependencies = [
4090+ "autocfg",
4091+ "static_assertions",
4092+ "version_check",
4093+]
4094+
3314 [[package]]4095 [[package]]
3315 name = "socket2"4096 name = "socket2"
3316 version = "0.6.5"4097 version = "0.6.5"
@@ -3336,6 +4117,16 @@ dependencies = [
3336 "lock_api",4117 "lock_api",
3337 ]4118 ]
3338 4119
4120+[[package]]
4121+name = "sqlformat"
4122+version = "0.5.0"
4123+source = "registry+https://github.com/rust-lang/crates.io-index"
4124+checksum = "0705994df478b895f05b8e290e0d46e53187b26f8d889d37b2a0881234922d94"
4125+dependencies = [
4126+ "unicode_categories",
4127+ "winnow 0.7.15",
4128+]
4129+
3339 [[package]]4130 [[package]]
3340 name = "stable_deref_trait"4131 name = "stable_deref_trait"
3341 version = "1.2.1"4132 version = "1.2.1"
@@ -3355,19 +4146,55 @@ dependencies = [
3355 "windows-sys 0.61.2",4146 "windows-sys 0.61.2",
3356 ]4147 ]
3357 4148
4149+[[package]]
4150+name = "static_assertions"
4151+version = "1.1.0"
4152+source = "registry+https://github.com/rust-lang/crates.io-index"
4153+checksum = "a2eb9349b6444b326872e140eb1cf5e7c522154d69e7a0ffb0fb81c06b37543f"
4154+
4155+[[package]]
4156+name = "string_enum"
4157+version = "1.0.2"
4158+source = "registry+https://github.com/rust-lang/crates.io-index"
4159+checksum = "ae36a4951ca7bd1cfd991c241584a9824a70f6aff1e7d4f693fb3f2465e4030e"
4160+dependencies = [
4161+ "quote",
4162+ "swc_macros_common",
4163+ "syn 2.0.119",
4164+]
4165+
3358 [[package]]4166 [[package]]
3359 name = "strsim"4167 name = "strsim"
3360 version = "0.11.1"4168 version = "0.11.1"
3361 source = "registry+https://github.com/rust-lang/crates.io-index"4169 source = "registry+https://github.com/rust-lang/crates.io-index"
3362 checksum = "7da8b5736845d9f2fcb837ea5d9e2628564b3b043a70948a3f0b778838c5fb4f"4170 checksum = "7da8b5736845d9f2fcb837ea5d9e2628564b3b043a70948a3f0b778838c5fb4f"
3363 4171
4172+[[package]]
4173+name = "strum"
4174+version = "0.24.1"
4175+source = "registry+https://github.com/rust-lang/crates.io-index"
4176+checksum = "063e6045c0e62079840579a7e47a355ae92f60eb74daaf156fb1e84ba164e63f"
4177+
3364 [[package]]4178 [[package]]
3365 name = "strum"4179 name = "strum"
3366 version = "0.26.3"4180 version = "0.26.3"
3367 source = "registry+https://github.com/rust-lang/crates.io-index"4181 source = "registry+https://github.com/rust-lang/crates.io-index"
3368 checksum = "8fec0f0aef304996cf250b31b5a10dee7980c85da9d759361292b8bca5a18f06"4182 checksum = "8fec0f0aef304996cf250b31b5a10dee7980c85da9d759361292b8bca5a18f06"
3369 dependencies = [4183 dependencies = [
3370- "strum_macros",4184+ "strum_macros 0.26.4",
4185+]
4186+
4187+[[package]]
4188+name = "strum_macros"
4189+version = "0.24.3"
4190+source = "registry+https://github.com/rust-lang/crates.io-index"
4191+checksum = "1e385be0d24f186b4ce2f9982191e7101bb737312ad61c1f2f984f34bcf85d59"
4192+dependencies = [
4193+ "heck 0.4.1",
4194+ "proc-macro2",
4195+ "quote",
4196+ "rustversion",
4197+ "syn 1.0.109",
3371 ]4198 ]
3372 4199
3373 [[package]]4200 [[package]]
@@ -3389,12 +4216,205 @@ version = "2.6.1"
3389 source = "registry+https://github.com/rust-lang/crates.io-index"4216 source = "registry+https://github.com/rust-lang/crates.io-index"
3390 checksum = "13c2bddecc57b384dee18652358fb23172facb8a2c51ccc10d74c157bdea3292"4217 checksum = "13c2bddecc57b384dee18652358fb23172facb8a2c51ccc10d74c157bdea3292"
3391 4218
4219+[[package]]
4220+name = "swc_atoms"
4221+version = "9.0.0"
4222+source = "registry+https://github.com/rust-lang/crates.io-index"
4223+checksum = "d4ccbe2ecad10ad7432100f878a107b1d972a8aee83ca53184d00c23a078bb8a"
4224+dependencies = [
4225+ "hstr",
4226+ "once_cell",
4227+ "serde",
4228+]
4229+
4230+[[package]]
4231+name = "swc_common"
4232+version = "17.0.1"
4233+source = "registry+https://github.com/rust-lang/crates.io-index"
4234+checksum = "259b675d633a26d24efe3802a9d88858c918e6e8f062d3222d3aa02d56a2cf4c"
4235+dependencies = [
4236+ "anyhow",
4237+ "ast_node",
4238+ "better_scoped_tls",
4239+ "bytes-str",
4240+ "either",
4241+ "from_variant",
4242+ "new_debug_unreachable",
4243+ "num-bigint",
4244+ "once_cell",
4245+ "rustc-hash 2.1.3",
4246+ "serde",
4247+ "siphasher 0.3.11",
4248+ "swc_atoms",
4249+ "swc_eq_ignore_macros",
4250+ "swc_visit",
4251+ "tracing",
4252+ "unicode-width 0.2.3",
4253+ "url",
4254+]
4255+
4256+[[package]]
4257+name = "swc_ecma_ast"
4258+version = "18.0.0"
4259+source = "registry+https://github.com/rust-lang/crates.io-index"
4260+checksum = "a573a0c72850dec8d4d8085f152d5778af35a2520c3093b242d2d1d50776da7c"
4261+dependencies = [
4262+ "bitflags",
4263+ "is-macro",
4264+ "num-bigint",
4265+ "once_cell",
4266+ "phf",
4267+ "rustc-hash 2.1.3",
4268+ "serde",
4269+ "string_enum",
4270+ "swc_atoms",
4271+ "swc_common",
4272+ "swc_visit",
4273+ "unicode-id-start",
4274+]
4275+
4276+[[package]]
4277+name = "swc_ecma_lexer"
4278+version = "26.0.0"
4279+source = "registry+https://github.com/rust-lang/crates.io-index"
4280+checksum = "5e82f7747e052c6ff6e111fa4adeb14e33b46ee6e94fe5ef717601f651db48fc"
4281+dependencies = [
4282+ "bitflags",
4283+ "either",
4284+ "num-bigint",
4285+ "rustc-hash 2.1.3",
4286+ "seq-macro",
4287+ "serde",
4288+ "smallvec",
4289+ "smartstring",
4290+ "stacker",
4291+ "swc_atoms",
4292+ "swc_common",
4293+ "swc_ecma_ast",
4294+ "swc_ecma_parser",
4295+ "tracing",
4296+]
4297+
4298+[[package]]
4299+name = "swc_ecma_parser"
4300+version = "27.0.7"
4301+source = "registry+https://github.com/rust-lang/crates.io-index"
4302+checksum = "7f1a51af1a92cd4904c073b293e491bbc0918400a45d58227b34c961dd6f52d7"
4303+dependencies = [
4304+ "bitflags",
4305+ "either",
4306+ "num-bigint",
4307+ "phf",
4308+ "rustc-hash 2.1.3",
4309+ "seq-macro",
4310+ "serde",
4311+ "smartstring",
4312+ "stacker",
4313+ "swc_atoms",
4314+ "swc_common",
4315+ "swc_ecma_ast",
4316+ "tracing",
4317+]
4318+
4319+[[package]]
4320+name = "swc_eq_ignore_macros"
4321+version = "1.0.1"
4322+source = "registry+https://github.com/rust-lang/crates.io-index"
4323+checksum = "c16ce73424a6316e95e09065ba6a207eba7765496fed113702278b7711d4b632"
4324+dependencies = [
4325+ "proc-macro2",
4326+ "quote",
4327+ "syn 2.0.119",
4328+]
4329+
4330+[[package]]
4331+name = "swc_macros_common"
4332+version = "1.0.1"
4333+source = "registry+https://github.com/rust-lang/crates.io-index"
4334+checksum = "aae1efbaa74943dc5ad2a2fb16cbd78b77d7e4d63188f3c5b4df2b4dcd2faaae"
4335+dependencies = [
4336+ "proc-macro2",
4337+ "quote",
4338+ "syn 2.0.119",
4339+]
4340+
4341+[[package]]
4342+name = "swc_visit"
4343+version = "2.0.2"
4344+source = "registry+https://github.com/rust-lang/crates.io-index"
4345+checksum = "e7df72a1be54e379864cebf04f26abb4d7ee637977f62f8ec8387233f7a27e88"
4346+dependencies = [
4347+ "either",
4348+]
4349+
3392 [[package]]4350 [[package]]
3393 name = "symlink"4351 name = "symlink"
3394 version = "0.1.0"4352 version = "0.1.0"
3395 source = "registry+https://github.com/rust-lang/crates.io-index"4353 source = "registry+https://github.com/rust-lang/crates.io-index"
3396 checksum = "a7973cce6668464ea31f176d85b13c7ab3bba2cb3b77a2ed26abd7801688010a"4354 checksum = "a7973cce6668464ea31f176d85b13c7ab3bba2cb3b77a2ed26abd7801688010a"
3397 4355
4356+[[package]]
4357+name = "symphonia"
4358+version = "0.6.1"
4359+source = "registry+https://github.com/rust-lang/crates.io-index"
4360+checksum = "a7edef6a96b696d4e0cab5ee9ebb7ca155ed95f30a6b45bbb8b97d2727f02424"
4361+dependencies = [
4362+ "lazy_static",
4363+ "symphonia-core",
4364+ "symphonia-format-mkv",
4365+ "symphonia-metadata",
4366+]
4367+
4368+[[package]]
4369+name = "symphonia-common"
4370+version = "0.6.1"
4371+source = "registry+https://github.com/rust-lang/crates.io-index"
4372+checksum = "2acc3fcc18ec9b8cdd48614e259c4cf0d27b71d41e5d9b120b42c5adab12d7c4"
4373+dependencies = [
4374+ "log",
4375+ "symphonia-core",
4376+ "symphonia-metadata",
4377+]
4378+
4379+[[package]]
4380+name = "symphonia-core"
4381+version = "0.6.1"
4382+source = "registry+https://github.com/rust-lang/crates.io-index"
4383+checksum = "01c412864d599d4750d0c3d684d7e093ec05e5309681ef5252cc1096a437f6e0"
4384+dependencies = [
4385+ "bitflags",
4386+ "bytemuck",
4387+ "lazy_static",
4388+ "log",
4389+ "num-complex",
4390+ "smallvec",
4391+]
4392+
4393+[[package]]
4394+name = "symphonia-format-mkv"
4395+version = "0.6.1"
4396+source = "registry+https://github.com/rust-lang/crates.io-index"
4397+checksum = "d015c5c0558864665894b3f4cbd95e10abb01b9c868e751c72670f326a56360e"
4398+dependencies = [
4399+ "lazy_static",
4400+ "log",
4401+ "symphonia-common",
4402+ "symphonia-core",
4403+]
4404+
4405+[[package]]
4406+name = "symphonia-metadata"
4407+version = "0.6.1"
4408+source = "registry+https://github.com/rust-lang/crates.io-index"
4409+checksum = "83713a97705d77bdef7cdbc0768fd6e5a54e4cd7e48d60a806ae85639e2c87c6"
4410+dependencies = [
4411+ "lazy_static",
4412+ "log",
4413+ "regex-lite",
4414+ "smallvec",
4415+ "symphonia-core",
4416+]
4417+
3398 [[package]]4418 [[package]]
3399 name = "syn"4419 name = "syn"
3400 version = "1.0.109"4420 version = "1.0.109"
@@ -3543,7 +4563,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index"
3543 checksum = "d60769b80ad7953d8a7b2c70cdfe722bbcdcac6bccc8ac934c40c034d866fc18"4563 checksum = "d60769b80ad7953d8a7b2c70cdfe722bbcdcac6bccc8ac934c40c034d866fc18"
3544 dependencies = [4564 dependencies = [
3545 "byteorder",4565 "byteorder",
3546- "regex-syntax",4566+ "regex-syntax 0.8.11",
3547 "utf8-ranges",4567 "utf8-ranges",
3548 ]4568 ]
3549 4569
@@ -3599,6 +4619,27 @@ version = "1.0.1"
3599 source = "registry+https://github.com/rust-lang/crates.io-index"4619 source = "registry+https://github.com/rust-lang/crates.io-index"
3600 checksum = "55937e1799185b12863d447f42597ed69d9928686b8d88a1df17376a097d8369"4620 checksum = "55937e1799185b12863d447f42597ed69d9928686b8d88a1df17376a097d8369"
3601 4621
4622+[[package]]
4623+name = "taplo"
4624+version = "0.14.0"
4625+source = "registry+https://github.com/rust-lang/crates.io-index"
4626+checksum = "c221a50eef1a5493074f11ca1ed62bef28c05a4d925002944cc686b2e783a5b3"
4627+dependencies = [
4628+ "ahash",
4629+ "arc-swap",
4630+ "either",
4631+ "globset",
4632+ "itertools 0.10.5",
4633+ "logos",
4634+ "once_cell",
4635+ "rowan 0.15.19",
4636+ "serde",
4637+ "serde_json",
4638+ "thiserror 1.0.69",
4639+ "time",
4640+ "tracing",
4641+]
4642+
3602 [[package]]4643 [[package]]
3603 name = "tempfile"4644 name = "tempfile"
3604 version = "3.27.0"4645 version = "3.27.0"
@@ -3612,6 +4653,30 @@ dependencies = [
3612 "windows-sys 0.61.2",4653 "windows-sys 0.61.2",
3613 ]4654 ]
3614 4655
4656+[[package]]
4657+name = "termcolor"
4658+version = "1.4.1"
4659+source = "registry+https://github.com/rust-lang/crates.io-index"
4660+checksum = "06794f8f6c5c898b3275aebefa6b8a1cb24cd2c6c79397ab15774837a0bc5755"
4661+dependencies = [
4662+ "winapi-util",
4663+]
4664+
4665+[[package]]
4666+name = "text-size"
4667+version = "1.1.1"
4668+source = "registry+https://github.com/rust-lang/crates.io-index"
4669+checksum = "f18aa187839b2bdb1ad2fa35ead8c4c2976b64e4363c386d45ac0f7ee85c9233"
4670+
4671+[[package]]
4672+name = "text_lines"
4673+version = "0.6.0"
4674+source = "registry+https://github.com/rust-lang/crates.io-index"
4675+checksum = "7fd5828de7deaa782e1dd713006ae96b3bee32d3279b79eb67ecf8072c059bcf"
4676+dependencies = [
4677+ "serde",
4678+]
4679+
3615 [[package]]4680 [[package]]
3616 name = "thiserror"4681 name = "thiserror"
3617 version = "1.0.69"4682 version = "1.0.69"
@@ -3652,6 +4717,20 @@ dependencies = [
3652 "syn 3.0.9",4717 "syn 3.0.9",
3653 ]4718 ]
3654 4719
4720+[[package]]
4721+name = "thread-priority"
4722+version = "3.1.1"
4723+source = "registry+https://github.com/rust-lang/crates.io-index"
4724+checksum = "8d2e834949be5111506bb252643498af1514f600d9e1dceedaa42afae155b67f"
4725+dependencies = [
4726+ "bitflags",
4727+ "cfg-if",
4728+ "libc",
4729+ "log",
4730+ "rustversion",
4731+ "windows",
4732+]
4733+
3655 [[package]]4734 [[package]]
3656 name = "thread_local"4735 name = "thread_local"
3657 version = "1.1.10"4736 version = "1.1.10"
@@ -3691,6 +4770,21 @@ dependencies = [
3691 "time-core",4770 "time-core",
3692 ]4771 ]
3693 4772
4773+[[package]]
4774+name = "tiny_pretty"
4775+version = "0.2.1"
4776+source = "registry+https://github.com/rust-lang/crates.io-index"
4777+checksum = "650d82e943da333637be9f1567d33d605e76810a26464edfd7ae74f7ef181e95"
4778+
4779+[[package]]
4780+name = "tiny_pretty"
4781+version = "0.4.5"
4782+source = "registry+https://github.com/rust-lang/crates.io-index"
4783+checksum = "58b2d5989bcee0f42e4efffdd6280defe2d0ea91ebbea29c7615412855ef75fa"
4784+dependencies = [
4785+ "unicode-width 0.2.3",
4786+]
4787+
3694 [[package]]4788 [[package]]
3695 name = "tinystr"4789 name = "tinystr"
3696 version = "0.8.5"4790 version = "0.8.5"
@@ -3768,7 +4862,7 @@ dependencies = [
3768 "toml_datetime",4862 "toml_datetime",
3769 "toml_parser",4863 "toml_parser",
3770 "toml_writer",4864 "toml_writer",
3771- "winnow",4865+ "winnow 1.0.4",
3772 ]4866 ]
3773 4867
3774 [[package]]4868 [[package]]
@@ -3789,7 +4883,7 @@ dependencies = [
3789 "indexmap",4883 "indexmap",
3790 "toml_datetime",4884 "toml_datetime",
3791 "toml_parser",4885 "toml_parser",
3792- "winnow",4886+ "winnow 1.0.4",
3793 ]4887 ]
3794 4888
3795 [[package]]4889 [[package]]
@@ -3798,7 +4892,7 @@ version = "1.1.5+spec-1.1.0"
3798 source = "registry+https://github.com/rust-lang/crates.io-index"4892 source = "registry+https://github.com/rust-lang/crates.io-index"
3799 checksum = "baa693a8032d7e1cada7d0041e96126df243179ff061456783ac7f12bda4744c"4893 checksum = "baa693a8032d7e1cada7d0041e96126df243179ff061456783ac7f12bda4744c"
3800 dependencies = [4894 dependencies = [
3801- "winnow",4895+ "winnow 1.0.4",
3802 ]4896 ]
3803 4897
3804 [[package]]4898 [[package]]
@@ -3885,7 +4979,7 @@ dependencies = [
3885 "elsa",4979 "elsa",
3886 "http",4980 "http",
3887 "pin-project-lite",4981 "pin-project-lite",
3888- "siphasher",4982+ "siphasher 1.0.4",
3889 "thiserror 2.0.21",4983 "thiserror 2.0.21",
3890 "tokio",4984 "tokio",
3891 ]4985 ]
@@ -4172,7 +5266,7 @@ dependencies = [
4172 "http",5266 "http",
4173 "memchr",5267 "memchr",
4174 "pin-project-lite",5268 "pin-project-lite",
4175- "siphasher",5269+ "siphasher 1.0.4",
4176 "smallvec",5270 "smallvec",
4177 "topcoat-core",5271 "topcoat-core",
4178 ]5272 ]
@@ -4322,6 +5416,16 @@ dependencies = [
4322 "tracing-log",5416 "tracing-log",
4323 ]5417 ]
4324 5418
5419+[[package]]
5420+name = "triomphe"
5421+version = "0.1.17"
5422+source = "registry+https://github.com/rust-lang/crates.io-index"
5423+checksum = "0d15f4f5898bcfc5d8a8e45ed30b2f108d710c1a2e5489dbf80e078f707181bc"
5424+dependencies = [
5425+ "serde",
5426+ "stable_deref_trait",
5427+]
5428+
4325 [[package]]5429 [[package]]
4326 name = "tungstenite"5430 name = "tungstenite"
4327 version = "0.29.0"5431 version = "0.29.0"
@@ -4402,7 +5506,7 @@ dependencies = [
4402 "rand 0.9.5",5506 "rand 0.9.5",
4403 "rapidhash",5507 "rapidhash",
4404 "regex",5508 "regex",
4405- "regex-syntax",5509+ "regex-syntax 0.8.11",
4406 "roaring",5510 "roaring",
4407 "rustc-hash 2.1.3",5511 "rustc-hash 2.1.3",
4408 "rustix 1.1.6",5512 "rustix 1.1.6",
@@ -4412,8 +5516,8 @@ dependencies = [
4412 "simdutf8",5516 "simdutf8",
4413 "simsimd",5517 "simsimd",
4414 "smallvec",5518 "smallvec",
4415- "strum",5519+ "strum 0.26.3",
4416- "strum_macros",5520+ "strum_macros 0.26.4",
4417 "tantivy",5521 "tantivy",
4418 "tempfile",5522 "tempfile",
4419 "thiserror 2.0.21",5523 "thiserror 2.0.21",
@@ -4459,8 +5563,8 @@ dependencies = [
4459 "bitflags",5563 "bitflags",
4460 "memchr",5564 "memchr",
4461 "miette",5565 "miette",
4462- "strum",5566+ "strum 0.26.3",
4463- "strum_macros",5567+ "strum_macros 0.26.4",
4464 "thiserror 2.0.21",5568 "thiserror 2.0.21",
4465 "turso_macros",5569 "turso_macros",
4466 ]5570 ]
@@ -4544,12 +5648,6 @@ dependencies = [
4544 "rand 0.9.5",5648 "rand 0.9.5",
4545 ]5649 ]
4546 5650
4547-[[package]]
4548-name = "typed-path"
4549-version = "0.13.0"
4550-source = "registry+https://github.com/rust-lang/crates.io-index"
4551-checksum = "9ce898823d8cd0f028662d2f349694b1af0a5cc9be83f1d213a00d3147445e1e"
4552-
4553 [[package]]5651 [[package]]
4554 name = "typeid"5652 name = "typeid"
4555 version = "1.0.3"5653 version = "1.0.3"
@@ -4607,6 +5705,12 @@ version = "2.10.0"
4607 source = "registry+https://github.com/rust-lang/crates.io-index"5705 source = "registry+https://github.com/rust-lang/crates.io-index"
4608 checksum = "357cc3acc6a036009fd6c973ed009037c732d60d0b4f6c673e9041497482a28f"5706 checksum = "357cc3acc6a036009fd6c973ed009037c732d60d0b4f6c673e9041497482a28f"
4609 5707
5708+[[package]]
5709+name = "unicode-id-start"
5710+version = "1.5.0"
5711+source = "registry+https://github.com/rust-lang/crates.io-index"
5712+checksum = "0825d2e09dcae814a4273c1e1435979d414ede25b2ee235b1545da6682483765"
5713+
4610 [[package]]5714 [[package]]
4611 name = "unicode-ident"5715 name = "unicode-ident"
4612 version = "1.0.27"5716 version = "1.0.27"
@@ -4619,6 +5723,18 @@ version = "0.1.14"
4619 source = "registry+https://github.com/rust-lang/crates.io-index"5723 source = "registry+https://github.com/rust-lang/crates.io-index"
4620 checksum = "7dd6e30e90baa6f72411720665d41d89b9a3d039dc45b8faea1ddd07f617f6af"5724 checksum = "7dd6e30e90baa6f72411720665d41d89b9a3d039dc45b8faea1ddd07f617f6af"
4621 5725
5726+[[package]]
5727+name = "unicode-width"
5728+version = "0.2.3"
5729+source = "registry+https://github.com/rust-lang/crates.io-index"
5730+checksum = "ca718471876992059f251e33aafc334346ada08042b7661dd1fe313a9bced557"
5731+
5732+[[package]]
5733+name = "unicode_categories"
5734+version = "0.1.1"
5735+source = "registry+https://github.com/rust-lang/crates.io-index"
5736+checksum = "39ec24b3121d976906ece63c9daad25b85969647682eee313cb5779fdd69e14e"
5737+
4622 [[package]]5738 [[package]]
4623 name = "universal-hash"5739 name = "universal-hash"
4624 version = "0.5.1"5740 version = "0.5.1"
@@ -4642,11 +5758,14 @@ source = "registry+https://github.com/rust-lang/crates.io-index"
4642 checksum = "cde93ff05758a36a851a398a772b0b79a82fbe3c186a46f2696baaeaf84c966b"5758 checksum = "cde93ff05758a36a851a398a772b0b79a82fbe3c186a46f2696baaeaf84c966b"
4643 dependencies = [5759 dependencies = [
4644 "base64 0.23.1",5760 "base64 0.23.1",
5761+ "cookie_store",
4645 "flate2",5762 "flate2",
4646 "log",5763 "log",
4647 "percent-encoding",5764 "percent-encoding",
4648 "rustls",5765 "rustls",
4649 "rustls-pki-types",5766 "rustls-pki-types",
5767+ "serde",
5768+ "serde_json",
4650 "ureq-proto",5769 "ureq-proto",
4651 "utf8-zero",5770 "utf8-zero",
4652 "webpki-roots",5771 "webpki-roots",
@@ -4664,6 +5783,19 @@ dependencies = [
4664 "log",5783 "log",
4665 ]5784 ]
4666 5785
5786+[[package]]
5787+name = "url"
5788+version = "2.5.8"
5789+source = "registry+https://github.com/rust-lang/crates.io-index"
5790+checksum = "ff67a8a4397373c3ef660812acab3268222035010ab8680ec4215f38ba3d0eed"
5791+dependencies = [
5792+ "form_urlencoded",
5793+ "idna",
5794+ "percent-encoding",
5795+ "serde",
5796+ "serde_derive",
5797+]
5798+
4667 [[package]]5799 [[package]]
4668 name = "utf16_iter"5800 name = "utf16_iter"
4669 version = "1.0.5"5801 version = "1.0.5"
@@ -4713,6 +5845,35 @@ version = "0.9.5"
4713 source = "registry+https://github.com/rust-lang/crates.io-index"5845 source = "registry+https://github.com/rust-lang/crates.io-index"
4714 checksum = "0b928f33d975fc6ad9f86c8f283853ad26bdd5b10b7f1542aa2fa15e2289105a"5846 checksum = "0b928f33d975fc6ad9f86c8f283853ad26bdd5b10b7f1542aa2fa15e2289105a"
4715 5847
5848+[[package]]
5849+name = "walrus"
5850+version = "0.27.3"
5851+source = "registry+https://github.com/rust-lang/crates.io-index"
5852+checksum = "5691aeb3546554822fe2c13d63149c26a027cd07d900a72c7c7f37f4321bfaea"
5853+dependencies = [
5854+ "anyhow",
5855+ "gimli",
5856+ "id-arena",
5857+ "leb128",
5858+ "log",
5859+ "rayon",
5860+ "walrus-macro",
5861+ "wasm-encoder",
5862+ "wasmparser",
5863+]
5864+
5865+[[package]]
5866+name = "walrus-macro"
5867+version = "0.26.0"
5868+source = "registry+https://github.com/rust-lang/crates.io-index"
5869+checksum = "1a9b0525d7ea6e5f906aca581a172e5c91b4c595290dfa8ad4a2bc9ffef33b44"
5870+dependencies = [
5871+ "heck 0.5.0",
5872+ "proc-macro2",
5873+ "quote",
5874+ "syn 2.0.119",
5875+]
5876+
4716 [[package]]5877 [[package]]
4717 name = "wasi"5878 name = "wasi"
4718 version = "0.11.1+wasi-snapshot-preview1"5879 version = "0.11.1+wasi-snapshot-preview1"
@@ -4741,6 +5902,35 @@ dependencies = [
4741 "wasm-bindgen-shared",5902 "wasm-bindgen-shared",
4742 ]5903 ]
4743 5904
5905+[[package]]
5906+name = "wasm-bindgen-cli-support"
5907+version = "0.2.129"
5908+source = "registry+https://github.com/rust-lang/crates.io-index"
5909+checksum = "a0724352b96c7779dcfd3f580b9e7e29beac8f4229c9a27cd2ea53e04f1cc65a"
5910+dependencies = [
5911+ "anyhow",
5912+ "base64 0.22.1",
5913+ "leb128",
5914+ "log",
5915+ "rustc-demangle",
5916+ "serde",
5917+ "serde_json",
5918+ "walrus",
5919+ "wasm-bindgen-shared",
5920+ "wasmparser",
5921+]
5922+
5923+[[package]]
5924+name = "wasm-bindgen-futures"
5925+version = "0.4.79"
5926+source = "registry+https://github.com/rust-lang/crates.io-index"
5927+checksum = "3cbab34de2d982e9b48e18d216d04c4a6f641066ff19ffb699980f591ee3610e"
5928+dependencies = [
5929+ "js-sys",
5930+ "tokio",
5931+ "wasm-bindgen",
5932+]
5933+
4744 [[package]]5934 [[package]]
4745 name = "wasm-bindgen-macro"5935 name = "wasm-bindgen-macro"
4746 version = "0.2.129"5936 version = "0.2.129"
@@ -4773,6 +5963,79 @@ dependencies = [
4773 "unicode-ident",5963 "unicode-ident",
4774 ]5964 ]
4775 5965
5966+[[package]]
5967+name = "wasm-encoder"
5968+version = "0.245.1"
5969+source = "registry+https://github.com/rust-lang/crates.io-index"
5970+checksum = "3f9dca005e69bf015e45577e415b9af8c67e8ee3c0e38b5b0add5aa92581ed5c"
5971+dependencies = [
5972+ "leb128fmt",
5973+ "wasmparser",
5974+]
5975+
5976+[[package]]
5977+name = "wasm-opt"
5978+version = "0.116.1"
5979+source = "registry+https://github.com/rust-lang/crates.io-index"
5980+checksum = "2fd87a4c135535ffed86123b6fb0f0a5a0bc89e50416c942c5f0662c645f679c"
5981+dependencies = [
5982+ "anyhow",
5983+ "libc",
5984+ "strum 0.24.1",
5985+ "strum_macros 0.24.3",
5986+ "tempfile",
5987+ "thiserror 1.0.69",
5988+ "wasm-opt-cxx-sys",
5989+ "wasm-opt-sys",
5990+]
5991+
5992+[[package]]
5993+name = "wasm-opt-cxx-sys"
5994+version = "0.116.0"
5995+source = "registry+https://github.com/rust-lang/crates.io-index"
5996+checksum = "8c57b28207aa724318fcec6575fe74803c23f6f266fce10cbc9f3f116762f12e"
5997+dependencies = [
5998+ "anyhow",
5999+ "cxx",
6000+ "cxx-build",
6001+ "wasm-opt-sys",
6002+]
6003+
6004+[[package]]
6005+name = "wasm-opt-sys"
6006+version = "0.116.0"
6007+source = "registry+https://github.com/rust-lang/crates.io-index"
6008+checksum = "8a1cce564dc768dacbdb718fc29df2dba80bd21cb47d8f77ae7e3d95ceb98cbe"
6009+dependencies = [
6010+ "anyhow",
6011+ "cc",
6012+ "cxx",
6013+ "cxx-build",
6014+]
6015+
6016+[[package]]
6017+name = "wasmparser"
6018+version = "0.245.1"
6019+source = "registry+https://github.com/rust-lang/crates.io-index"
6020+checksum = "4f08c9adee0428b7bddf3890fc27e015ac4b761cc608c822667102b8bfd6995e"
6021+dependencies = [
6022+ "bitflags",
6023+ "hashbrown 0.16.1",
6024+ "indexmap",
6025+ "semver",
6026+ "serde",
6027+]
6028+
6029+[[package]]
6030+name = "web-sys"
6031+version = "0.3.106"
6032+source = "registry+https://github.com/rust-lang/crates.io-index"
6033+checksum = "88261b9deccee56594c11a3460c462c41f58d148598fe70ad77070126a68aba4"
6034+dependencies = [
6035+ "js-sys",
6036+ "wasm-bindgen",
6037+]
6038+
4776 [[package]]6039 [[package]]
4777 name = "web-time"6040 name = "web-time"
4778 version = "1.1.0"6041 version = "1.1.0"
@@ -4820,12 +6083,42 @@ version = "0.4.0"
4820 source = "registry+https://github.com/rust-lang/crates.io-index"6083 source = "registry+https://github.com/rust-lang/crates.io-index"
4821 checksum = "ac3b87c63620426dd9b991e5ce0329eff545bccbbb34f3be09ff6fb6ab51b7b6"6084 checksum = "ac3b87c63620426dd9b991e5ce0329eff545bccbbb34f3be09ff6fb6ab51b7b6"
4822 6085
6086+[[package]]
6087+name = "winapi-util"
6088+version = "0.1.11"
6089+source = "registry+https://github.com/rust-lang/crates.io-index"
6090+checksum = "c2a7b1c03c876122aa43f3020e6c3c3ee5c05081c9a00739faf7503aeba10d22"
6091+dependencies = [
6092+ "windows-sys 0.61.2",
6093+]
6094+
4823 [[package]]6095 [[package]]
4824 name = "winapi-x86_64-pc-windows-gnu"6096 name = "winapi-x86_64-pc-windows-gnu"
4825 version = "0.4.0"6097 version = "0.4.0"
4826 source = "registry+https://github.com/rust-lang/crates.io-index"6098 source = "registry+https://github.com/rust-lang/crates.io-index"
4827 checksum = "712e227841d057c1ee1cd2fb22fa7e5a5461ae8e48fa2ca79ec42cfc1931183f"6099 checksum = "712e227841d057c1ee1cd2fb22fa7e5a5461ae8e48fa2ca79ec42cfc1931183f"
4828 6100
6101+[[package]]
6102+name = "windows"
6103+version = "0.62.2"
6104+source = "registry+https://github.com/rust-lang/crates.io-index"
6105+checksum = "527fadee13e0c05939a6a05d5bd6eec6cd2e3dbd648b9f8e447c6518133d8580"
6106+dependencies = [
6107+ "windows-collections",
6108+ "windows-core",
6109+ "windows-future",
6110+ "windows-numerics",
6111+]
6112+
6113+[[package]]
6114+name = "windows-collections"
6115+version = "0.3.2"
6116+source = "registry+https://github.com/rust-lang/crates.io-index"
6117+checksum = "23b2d95af1a8a14a3c7367e1ed4fc9c20e0a26e79551b1454d72583c97cc6610"
6118+dependencies = [
6119+ "windows-core",
6120+]
6121+
4829 [[package]]6122 [[package]]
4830 name = "windows-core"6123 name = "windows-core"
4831 version = "0.62.2"6124 version = "0.62.2"
@@ -4839,6 +6132,17 @@ dependencies = [
4839 "windows-strings",6132 "windows-strings",
4840 ]6133 ]
4841 6134
6135+[[package]]
6136+name = "windows-future"
6137+version = "0.3.2"
6138+source = "registry+https://github.com/rust-lang/crates.io-index"
6139+checksum = "e1d6f90251fe18a279739e78025bd6ddc52a7e22f921070ccdc67dde84c605cb"
6140+dependencies = [
6141+ "windows-core",
6142+ "windows-link",
6143+ "windows-threading",
6144+]
6145+
4842 [[package]]6146 [[package]]
4843 name = "windows-implement"6147 name = "windows-implement"
4844 version = "0.60.2"6148 version = "0.60.2"
@@ -4867,6 +6171,16 @@ version = "0.2.1"
4867 source = "registry+https://github.com/rust-lang/crates.io-index"6171 source = "registry+https://github.com/rust-lang/crates.io-index"
4868 checksum = "f0805222e57f7521d6a62e36fa9163bc891acd422f971defe97d64e70d0a4fe5"6172 checksum = "f0805222e57f7521d6a62e36fa9163bc891acd422f971defe97d64e70d0a4fe5"
4869 6173
6174+[[package]]
6175+name = "windows-numerics"
6176+version = "0.3.1"
6177+source = "registry+https://github.com/rust-lang/crates.io-index"
6178+checksum = "6e2e40844ac143cdb44aead537bbf727de9b044e107a0f1220392177d15b0f26"
6179+dependencies = [
6180+ "windows-core",
6181+ "windows-link",
6182+]
6183+
4870 [[package]]6184 [[package]]
4871 name = "windows-result"6185 name = "windows-result"
4872 version = "0.4.1"6186 version = "0.4.1"
@@ -4928,6 +6242,15 @@ dependencies = [
4928 "windows_x86_64_msvc",6242 "windows_x86_64_msvc",
4929 ]6243 ]
4930 6244
6245+[[package]]
6246+name = "windows-threading"
6247+version = "0.2.1"
6248+source = "registry+https://github.com/rust-lang/crates.io-index"
6249+checksum = "3949bd5b99cafdf1c7ca86b43ca564028dfe27d66958f2470940f73d86d75b37"
6250+dependencies = [
6251+ "windows-link",
6252+]
6253+
4931 [[package]]6254 [[package]]
4932 name = "windows_aarch64_gnullvm"6255 name = "windows_aarch64_gnullvm"
4933 version = "0.52.6"6256 version = "0.52.6"
@@ -4976,6 +6299,15 @@ version = "0.52.6"
4976 source = "registry+https://github.com/rust-lang/crates.io-index"6299 source = "registry+https://github.com/rust-lang/crates.io-index"
4977 checksum = "589f6da84c646204747d1270a2a5661ea66ed1cced2631d546fdfb155959f9ec"6300 checksum = "589f6da84c646204747d1270a2a5661ea66ed1cced2631d546fdfb155959f9ec"
4978 6301
6302+[[package]]
6303+name = "winnow"
6304+version = "0.7.15"
6305+source = "registry+https://github.com/rust-lang/crates.io-index"
6306+checksum = "df79d97927682d2fd8adb29682d1140b343be4ac0f08fd68b7765d9c059d3945"
6307+dependencies = [
6308+ "memchr",
6309+]
6310+
4979 [[package]]6311 [[package]]
4980 name = "winnow"6312 name = "winnow"
4981 version = "1.0.4"6313 version = "1.0.4"
@@ -5012,12 +6344,34 @@ dependencies = [
5012 "tap",6344 "tap",
5013 ]6345 ]
5014 6346
6347+[[package]]
6348+name = "xtask"
6349+version = "0.1.0"
6350+dependencies = [
6351+ "anyhow",
6352+ "blake3",
6353+ "serde_json",
6354+ "ureq",
6355+ "wasm-bindgen-cli-support",
6356+ "wasm-opt",
6357+]
6358+
5015 [[package]]6359 [[package]]
5016 name = "xxhash-rust"6360 name = "xxhash-rust"
5017 version = "0.8.19"6361 version = "0.8.19"
5018 source = "registry+https://github.com/rust-lang/crates.io-index"6362 source = "registry+https://github.com/rust-lang/crates.io-index"
5019 checksum = "550a2b930b62486a393c52d5c3b84bff264b28aa437ed64694d31e93b1757af7"6363 checksum = "550a2b930b62486a393c52d5c3b84bff264b28aa437ed64694d31e93b1757af7"
5020 6364
6365+[[package]]
6366+name = "yaml_parser"
6367+version = "0.3.0"
6368+source = "registry+https://github.com/rust-lang/crates.io-index"
6369+checksum = "71ebb04c72edf699612d543f6c421142527b85ac180156017fa26be49dc0762f"
6370+dependencies = [
6371+ "rowan 0.16.1",
6372+ "winnow 0.7.15",
6373+]
6374+
5021 [[package]]6375 [[package]]
5022 name = "yansi"6376 name = "yansi"
5023 version = "1.0.1"6377 version = "1.0.1"
@@ -5129,23 +6483,6 @@ dependencies = [
5129 "syn 3.0.9",6483 "syn 3.0.9",
5130 ]6484 ]
5131 6485
5132-[[package]]
5133-name = "zip"
5134-version = "9.1.2"
5135-source = "registry+https://github.com/rust-lang/crates.io-index"
5136-checksum = "ec2e3161de27091f18a831d9494e9c53378a34833af5c1dda35ad85849da18d6"
5137-dependencies = [
5138- "crc32fast",
5139- "flate2",
5140- "getrandom 0.4.3",
5141- "indexmap",
5142- "memchr",
5143- "nix",
5144- "typed-path",
5145- "windows-sys 0.61.2",
5146- "zopfli",
5147-]
5148-
5149 [[package]]6486 [[package]]
5150 name = "zlib-rs"6487 name = "zlib-rs"
5151 version = "0.6.8"6488 version = "0.6.8"
@@ -5158,18 +6495,6 @@ version = "1.0.23"
5158 source = "registry+https://github.com/rust-lang/crates.io-index"6495 source = "registry+https://github.com/rust-lang/crates.io-index"
5159 checksum = "29666d0abbfad1e3dc4dcf6144730dd3a3ab225bbbdac83319345b1b44ccfc1b"6496 checksum = "29666d0abbfad1e3dc4dcf6144730dd3a3ab225bbbdac83319345b1b44ccfc1b"
5160 6497
5161-[[package]]
5162-name = "zopfli"
5163-version = "0.8.4"
5164-source = "registry+https://github.com/rust-lang/crates.io-index"
5165-checksum = "aaf7fc5d30c28483d93805c4a5e12b05bbb52407fa67c5f8bd552374cd01fb11"
5166-dependencies = [
Cargo.tomlmodified+50 -1
@@ -3,19 +3,68 @@ name = "project_note"
3 version = "0.1.0"3 version = "0.1.0"
4 edition = "2024"4 edition = "2024"
5 5
6+[workspace]
7+members = [".", "crates/note-model", "crates/editor", "xtask"]
8+resolver = "3"
9+
10+[workspace.lints.rust]
11+unsafe_code = "forbid"
12+
13+[lints]
14+workspace = true
15+
6 [dependencies]16 [dependencies]
17+note-model = { path = "crates/note-model" }
7 anyhow = "1.0.104"18 anyhow = "1.0.104"
8 blake3 = "1.8.7"19 blake3 = "1.8.7"
20+bytes = "1.12.1"
21+http-body = "1.0.1"
9 loro = "1.17.1"22 loro = "1.17.1"
10 tokio = { version = "1.54.1", features = ["full"] }23 tokio = { version = "1.54.1", features = ["full"] }
11 topcoat = { version = "0.11.0", features = ["anyhow", "asset", "discover", "font-fontsource", "fs", "tailwind", "ui", "websocket"] }24 topcoat = { version = "0.11.0", features = ["anyhow", "asset", "discover", "font-fontsource", "fs", "tailwind", "ui", "websocket"] }
12 turso = "0.8.3"25 turso = "0.8.3"
13 uuid = { version = "1.29.0", features = ["v7"] }26 uuid = { version = "1.29.0", features = ["v7"] }
14 serde = { version = "1", features = ["derive"] }27 serde = { version = "1", features = ["derive"] }
15-zip = { version = "9.1.2", default-features = false, features = ["deflate"] }28+flate2 = "1.1.10"
29+crc32fast = "1.5.3"
16 pulldown-cmark = { version = "0.13.5", default-features = false }30 pulldown-cmark = { version = "0.13.5", default-features = false }
17 serde_json = "1.0.154"31 serde_json = "1.0.154"
32+symphonia = { version = "0.6.1", default-features = false, features = ["mkv"] }
18 regex = "1.13.1"33 regex = "1.13.1"
34+regex-syntax = "0.8"
35+prettyplease = "0.3.0"
36+syn = { version = "3.0.9", features = ["full"] }
37+dprint-plugin-typescript = "0.96.1"
38+dprint-plugin-json = "0.25.2"
39+malva = "0.16.0"
40+markup_fmt = "0.27.6"
41+pretty_yaml = "0.6.0"
42+taplo = "0.14.0"
43+sqlformat = "0.5.0"
44+dprint-plugin-markdown = "0.28.2"
45+rustc-hash = "2.1.3"
46+hashbrown = "0.17.1"
47+thread-priority = "3.1.1"
19 48
20 [build-dependencies]49 [build-dependencies]
21 topcoat = { version = "0.11.0", default-features = false, features = ["tailwind"] }50 topcoat = { version = "0.11.0", default-features = false, features = ["tailwind"] }
51+
52+[profile.dev]
53+debug = "line-tables-only"
54+
55+[profile.release]
56+debug = "line-tables-only"
57+
58+# The wasm editor bundle (`cargo xtask editor`): smallest download.
59+[profile.editor]
60+inherits = "release"
61+opt-level = 3
62+lto = "fat"
63+codegen-units = 1
64+panic = "abort"
65+strip = true
66+
67+# Upstream 1.17.1 counts the remaining text per span when decoding a richtext
68+# snapshot (quadratic in marks); vendor/loro-internal bounds that count.
69+[patch.crates-io]
70+loro-internal = { path = "vendor/loro-internal" }
assets/editor.cssmodified+1146 -1
@@ -1 +1,1146 @@
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}}1+/* from prosemirror-view/style/prosemirror.css (MIT) */
2+.ProseMirror {
3+ position: relative;
4+}
5+
6+.ProseMirror {
7+ word-wrap: break-word;
8+ white-space: pre-wrap;
9+ white-space: break-spaces;
10+ -webkit-font-variant-ligatures: none;
11+ font-variant-ligatures: none;
12+ font-feature-settings: "liga" 0; /* the above doesn't seem to work in Edge */
13+}
14+
15+.ProseMirror pre {
16+ white-space: pre-wrap;
17+}
18+
19+.ProseMirror li {
20+ position: relative;
21+}
22+
23+.ProseMirror-hideselection *::selection { background: transparent; }
24+.ProseMirror-hideselection *::-moz-selection { background: transparent; }
25+.ProseMirror-hideselection { caret-color: transparent; }
26+
27+/* See https://code.haverbeke.berlin/prosemirror/prosemirror/issues/1421#issuecomment-1759320191 */
28+.ProseMirror [draggable][contenteditable=false] { user-select: text }
29+
30+.ProseMirror-selectednode {
31+ outline: 2px solid #8cf;
32+}
33+
34+/* Make sure li selections wrap around markers */
35+
36+li.ProseMirror-selectednode {
37+ outline: none;
38+}
39+
40+li.ProseMirror-selectednode:after {
41+ content: "";
42+ position: absolute;
43+ left: -32px;
44+ right: -2px; top: -2px; bottom: -2px;
45+ border: 2px solid #8cf;
46+ pointer-events: none;
47+}
48+
49+/* Protect against generic img rules */
50+
51+img.ProseMirror-separator {
52+ display: inline !important;
53+ border: none !important;
54+ margin: 0 !important;
55+}
56+
57+/* from prosemirror-gapcursor/style/gapcursor.css (MIT) */
58+.ProseMirror-gapcursor {
59+ display: none;
60+ pointer-events: none;
61+ position: absolute;
62+}
63+
64+.ProseMirror-gapcursor:after {
65+ content: "";
66+ display: block;
67+ position: absolute;
68+ top: -2px;
69+ width: 20px;
70+ border-top: 1px solid black;
71+ animation: ProseMirror-cursor-blink 1.1s steps(2, start) infinite;
72+}
73+
74+@keyframes ProseMirror-cursor-blink {
75+ to {
76+ visibility: hidden;
77+ }
78+}
79+
80+.ProseMirror-focused .ProseMirror-gapcursor {
81+ display: block;
82+}
83+
84+/*
85+ * Editor styles, tokens only ("Graphite & Highlighter", see styles.css). Light/dark is
86+ * handled by the theme variables themselves. Fallbacks are the light values.
87+ * Type: Atkinson Hyperlegible Next (UI and body), Atkinson Hyperlegible Mono (meta, keycaps, code).
88+ */
89+
90+.sr-only {
91+ position: absolute;
92+ width: 1px;
93+ height: 1px;
94+ padding: 0;
95+ margin: -1px;
96+ overflow: hidden;
97+ clip: rect(0, 0, 0, 0);
98+ white-space: nowrap;
99+ border: 0;
100+}
101+
102+/* ---- Keycaps (every visible command shows its shortcut as these) ---- */
103+
104+.keycaps {
105+ display: inline-flex;
106+ align-items: center;
107+ gap: 3px;
108+ margin-inline-start: 6px;
109+ vertical-align: middle;
110+}
111+
112+.keycap {
113+ display: inline-flex;
114+ align-items: center;
115+ justify-content: center;
116+ min-width: 18px;
117+ height: 18px;
118+ padding: 0 4px;
119+ border: 1px solid var(--border, #e3e5ea);
120+ border-bottom-width: 2px;
121+ border-radius: 6px;
122+ background: var(--keycap-bg, #ffffff);
123+ color: var(--muted-foreground, #5b6270);
124+ font-family: var(--font-mono, "Atkinson Hyperlegible Mono", ui-monospace, monospace);
125+ font-size: 11px;
126+ font-weight: 500;
127+ line-height: 1;
128+ font-variant-numeric: tabular-nums;
129+}
130+
131+/* ---- Tooltips (toolbar and bubble buttons) ---- */
132+
133+.tip {
134+ position: absolute;
135+ top: calc(100% + 6px);
136+ left: 50%;
137+ z-index: 40;
138+ display: flex;
139+ align-items: center;
140+ flex-wrap: wrap;
141+ gap: 2px;
142+ max-width: 240px;
143+ padding: 4px 6px 4px 8px;
144+ border: 1px solid var(--border, #e3e5ea);
145+ border-radius: 10px;
146+ background: var(--popover, #ffffff);
147+ color: var(--popover-foreground, #16181d);
148+ box-shadow: var(--shadow-float, 0 8px 24px rgb(0 0 0 / 0.12));
149+ font-family: var(--font-sans, "Atkinson Hyperlegible Next", sans-serif);
150+ font-size: 12px;
151+ font-weight: 500;
152+ line-height: 16px;
153+ white-space: nowrap;
154+ pointer-events: none;
155+ opacity: 0;
156+ transform: translate(-50%, -2px);
157+ transition:
158+ opacity 150ms ease-out,
159+ transform 150ms ease-out;
160+}
161+
162+.tip .keycaps {
163+ margin-inline-start: 4px;
164+}
165+
166+.tip-reason {
167+ display: none;
168+ flex-basis: 100%;
169+ color: var(--muted-foreground, #5b6270);
170+ font-weight: 400;
171+}
172+
173+.editor-toolbar-btn:disabled .tip-reason {
174+ display: block;
175+}
176+
177+.editor-toolbar-btn:hover .tip,
178+.editor-toolbar-btn:focus-visible .tip,
179+.bubble-btn:hover .tip,
180+.bubble-btn:focus-visible .tip {
181+ opacity: 1;
182+ transform: translate(-50%, 0);
183+ transition-delay: 300ms;
184+}
185+
186+.bubble .tip {
187+ top: auto;
188+ bottom: calc(100% + 6px);
189+}
190+
191+/* ---- Sync status pill (in the note header's #sync-slot) ---- */
192+
193+#sync-status {
194+ display: inline-flex;
195+ align-items: center;
196+ gap: 6px;
197+ height: 24px;
198+ padding: 0 10px 0 8px;
199+ border: 1px solid var(--border, #e3e5ea);
200+ border-radius: 999px;
201+ background: var(--card, #ffffff);
202+ color: var(--muted-foreground, #5b6270);
203+ font-family: var(--font-mono, "Atkinson Hyperlegible Mono", ui-monospace, monospace);
204+ font-size: 12px;
205+ font-weight: 400;
206+ line-height: 16px;
207+ white-space: nowrap;
208+ /* No transition: the pill changes while the user types, and animating it costs frames. */
209+ contain: layout paint;
210+}
211+
212+#sync-status::before {
213+ content: "";
214+ width: 6px;
215+ height: 6px;
216+ border-radius: 50%;
217+ background: currentColor;
218+ flex: none;
219+}
220+
221+#sync-status .labels {
222+ display: inline-grid;
223+}
224+
225+#sync-status .labels > span {
226+ grid-area: 1 / 1;
227+ visibility: hidden;
228+}
229+
230+#sync-status[data-state="saved"] [data-label="saved"],
231+#sync-status[data-state="saving"] [data-label="saving"],
232+#sync-status[data-state="connecting"] [data-label="connecting"],
233+#sync-status[data-state="reconnecting"] [data-label="reconnecting"],
234+#sync-status[data-state="local"] [data-label="local"] {
235+ visibility: visible;
236+}
237+
238+#sync-status[data-state="saved"] {
239+ color: var(--ok, #1f7a4d);
240+}
241+
242+#sync-status[data-state="saving"] {
243+ color: var(--muted-foreground, #5b6270);
244+}
245+
246+#sync-status[data-state="local"],
247+#sync-status[data-state="reconnecting"] {
248+ color: var(--warn, #9a5b00);
249+}
250+
251+/* ---- Note header: one row, the formatting toolbar sits inside it ---- */
252+
253+#note-header {
254+ container: note-header / inline-size;
255+}
256+
257+/* ---- Toolbar: compact, icons only, one line (groups drop out when the row is narrow) ---- */
258+
259+.editor-toolbar {
260+ display: flex;
261+ flex: 0 0 auto;
262+ flex-wrap: nowrap;
263+ align-items: center;
264+ gap: 2px;
265+}
266+
267+.editor-toolbar-group {
268+ display: flex;
269+ align-items: center;
270+ gap: 2px;
271+}
272+
273+.editor-toolbar-group + .editor-toolbar-group::before {
274+ content: "";
275+ width: 1px;
276+ height: 16px;
277+ margin: 0 4px;
278+ background: var(--border, #e3e5ea);
279+}
280+
281+/* Lower-priority commands leave the bar as the header narrows, so the title keeps
282+ at least 8rem. They stay reachable through the slash menu (/) and markdown shortcuts. */
283+@container note-header (max-width: 879px) {
284+ .note-crumb-notebook {
285+ display: none;
286+ }
287+}
288+
289+@container note-header (max-width: 779px) {
290+ .editor-toolbar-group[data-group="blocks"] {
291+ display: none;
292+ }
293+}
294+
295+@container note-header (max-width: 619px) {
296+ .editor-toolbar-btn[data-command="h1"],
297+ .editor-toolbar-btn[data-command="h2"],
298+ .editor-toolbar-btn[data-command="h3"] {
299+ display: none;
300+ }
301+}
302+
303+@container note-header (max-width: 559px) {
304+ #sync-status {
305+ gap: 0;
306+ padding: 0 8px;
307+ font-size: 0;
308+ }
309+}
310+
311+@container note-header (max-width: 469px) {
312+ .editor-toolbar-group[data-group="history"] {
313+ display: none;
314+ }
315+}
316+
317+@container note-header (max-width: 419px) {
318+ .editor-toolbar-btn[data-command="paragraph"],
319+ .editor-toolbar-group[data-group="headings"] {
320+ display: none;
321+ }
322+ .note-crumb {
323+ min-width: 6rem;
324+ }
325+}
326+
327+.editor-toolbar-btn {
328+ position: relative;
329+ display: inline-grid;
330+ place-items: center;
331+ width: 28px;
332+ height: 28px;
333+ margin: 0;
334+ padding: 0;
335+ border: 0;
336+ border-radius: 6px;
337+ background: transparent;
338+ color: var(--muted-foreground, #5b6270);
339+ cursor: pointer;
340+ transition:
341+ background-color 150ms ease-out,
342+ color 150ms ease-out;
343+}
344+
345+.editor-toolbar-icon {
346+ display: grid;
347+ place-items: center;
348+}
349+
350+.editor-toolbar-icon svg {
351+ display: block;
352+}
353+
354+.editor-toolbar-btn:hover:not(:disabled) {
355+ background: var(--sidebar-accent, #e3e6eb);
356+ color: var(--foreground, #16181d);
357+}
358+
359+.editor-toolbar-btn[aria-pressed="true"] {
360+ background: var(--active-row, #d9ebd3);
361+ color: var(--active-row-foreground, #1f3d22);
362+}
363+
364+/* Recording: the record button turns the destructive token while the mic is live. */
365+.editor-toolbar-btn[data-recording="true"],
366+.editor-toolbar-btn[data-recording="true"]:hover:not(:disabled) {
367+ background: var(--destructive, #b3261e);
368+ color: var(--destructive-foreground, #ffffff);
369+}
370+
371+.editor-rec-time {
372+ font-family: var(--font-mono, "Atkinson Hyperlegible Mono", ui-monospace, monospace);
373+ font-size: 11px;
374+ font-variant-numeric: tabular-nums;
375+ color: var(--muted-foreground, #5b6270);
376+}
377+
378+.editor-rec-time[hidden] {
379+ display: none;
380+}
381+
382+.editor-media-status {
383+ min-width: 0;
384+ overflow: hidden;
385+ font-size: 11px;
386+ color: var(--destructive, #b3261e);
387+ text-overflow: ellipsis;
388+ white-space: nowrap;
389+}
390+
391+.editor-toolbar-btn:disabled {
392+ opacity: 0.4;
393+ cursor: not-allowed;
394+}
395+
396+.editor-toolbar-btn:focus-visible,
397+.bubble-btn:focus-visible,
398+.btn:focus-visible,
399+.link-input:focus-visible,
400+.slash-item:focus-visible {
401+ outline: 2px solid var(--ring, #8a5a00);
402+ outline-offset: 2px;
403+}
404+
405+/* ---- Floating surfaces: bubble, link popover, slash menu ---- */
406+
407+.bubble,
408+.popover {
409+ position: fixed;
410+ z-index: 50;
411+ color: var(--popover-foreground, #16181d);
412+ background: var(--popover, #ffffff);
413+ border: 1px solid var(--border, #e3e5ea);
414+ border-radius: 10px;
415+ box-shadow: var(--shadow-float, 0 8px 24px rgb(0 0 0 / 0.12));
416+ font-family: var(--font-sans, "Atkinson Hyperlegible Next", sans-serif);
417+ font-size: 14px;
418+ line-height: 20px;
419+}
420+
421+.bubble[hidden],
422+.popover[hidden],
423+.link-view[hidden],
424+.link-edit[hidden],
425+.link-error[hidden] {
426+ display: none;
427+}
428+
429+.bubble {
430+ display: flex;
431+ align-items: center;
432+ gap: 2px;
433+ padding: 4px;
434+}
435+
436+.bubble-btn {
437+ position: relative;
438+ display: inline-grid;
439+ place-items: center;
440+ min-width: 28px;
441+ height: 28px;
442+ margin: 0;
443+ padding: 0 6px;
444+ border: 0;
445+ border-radius: 6px;
446+ background: transparent;
447+ color: var(--foreground, #16181d);
448+ font-family: var(--font-sans, "Atkinson Hyperlegible Next", sans-serif);
449+ font-size: 13px;
450+ font-weight: 700;
451+ line-height: 1;
452+ cursor: pointer;
453+ transition: background-color 150ms ease-out;
454+}
455+
456+.bubble-btn:hover:not(:disabled) {
457+ background: var(--sidebar-accent, #e3e6eb);
458+}
459+
460+.bubble-btn[aria-pressed="true"] {
461+ background: var(--active-row, #d9ebd3);
462+}
463+
464+.bubble-btn:disabled {
465+ opacity: 0.4;
466+ cursor: not-allowed;
467+}
468+
469+.bubble-btn[data-command="italic"] .bubble-glyph {
470+ font-style: italic;
471+ font-weight: 500;
472+}
473+
474+.bubble-btn[data-command="bold"] .bubble-glyph {
475+ font-weight: 800;
476+}
477+
478+.bubble-btn[data-command="code"] .bubble-glyph {
479+ font-family: var(--font-mono, "Atkinson Hyperlegible Mono", ui-monospace, monospace);
480+ font-size: 12px;
481+ font-weight: 500;
482+}
483+
484+.link-popover {
485+ width: min(360px, calc(100vw - 16px));
486+ box-sizing: border-box;
487+ padding: 10px;
488+}
489+
490+.link-row {
491+ display: flex;
492+ gap: 6px;
493+}
494+
495+.link-input {
496+ flex: 1;
497+ min-width: 0;
498+ height: 32px;
499+ padding: 0 10px;
500+ border: 1px solid var(--border, #e3e5ea);
501+ border-radius: 6px;
502+ background: var(--card, #ffffff);
503+ color: var(--foreground, #16181d);
504+ font-family: var(--font-mono, "Atkinson Hyperlegible Mono", ui-monospace, monospace);
505+ font-size: 13px;
506+}
507+
508+.link-input[aria-invalid="true"] {
509+ border-color: var(--bad, #b3261e);
510+}
511+
512+.link-input::placeholder {
513+ color: var(--muted-foreground, #5b6270);
514+}
515+
516+.link-error {
517+ margin: 6px 0 0;
518+ color: var(--bad, #b3261e);
519+ font-size: 12px;
520+ line-height: 16px;
521+}
522+
523+.link-actions {
524+ display: flex;
525+ flex-wrap: wrap;
526+ gap: 6px;
527+ margin-top: 8px;
528+}
529+
530+.link-view {
531+ display: grid;
532+ gap: 2px;
533+}
534+
535+.link-href {
536+ display: block;
537+ color: var(--link, #8a5a00);
538+ font-family: var(--font-mono, "Atkinson Hyperlegible Mono", ui-monospace, monospace);
539+ font-size: 13px;
540+ line-height: 18px;
541+ overflow-wrap: anywhere;
542+}
543+
544+.btn {
545+ display: inline-flex;
546+ align-items: center;
547+ gap: 6px;
548+ height: 28px;
549+ padding: 0 10px;
550+ border: 1px solid var(--border, #e3e5ea);
551+ border-radius: 6px;
552+ background: var(--card, #ffffff);
553+ color: var(--foreground, #16181d);
554+ font-family: var(--font-sans, "Atkinson Hyperlegible Next", sans-serif);
555+ font-size: 13px;
556+ font-weight: 500;
557+ line-height: 1;
558+ cursor: pointer;
559+ transition: background-color 150ms ease-out;
560+}
561+
562+.btn:hover:not(:disabled) {
563+ background: var(--sidebar-accent, #e3e6eb);
564+}
565+
566+.btn:disabled {
567+ opacity: 0.45;
568+ cursor: not-allowed;
569+}
570+
571+.btn-primary {
572+ border-color: transparent;
573+ background: var(--primary, #f2b600);
574+ color: var(--primary-foreground, #16181d);
575+}
576+
577+.btn-primary:hover:not(:disabled) {
578+ background: var(--primary, #f2b600);
579+ opacity: 0.9;
580+}
581+
582+.btn-primary .keycaps {
583+ margin-inline-start: 2px;
584+}
585+
586+.btn-primary .keycap {
587+ border-color: transparent;
588+ border-bottom-color: color-mix(in srgb, var(--primary-foreground, #16181d) 35%, transparent);
589+ background: transparent;
590+ color: inherit;
591+}
592+
593+.slash-menu {
594+ width: 264px;
595+ max-width: calc(100vw - 16px);
596+ box-sizing: border-box;
597+ padding: 4px;
598+}
599+
600+.slash-list {
601+ max-height: 288px;
602+ overflow-y: auto;
603+}
604+
605+.slash-item {
606+ display: flex;
607+ align-items: center;
608+ justify-content: space-between;
609+ gap: 12px;
610+ min-height: 32px;
611+ padding: 0 8px;
612+ border-radius: 6px;
613+ color: var(--foreground, #16181d);
614+ cursor: pointer;
615+}
616+
617+.slash-item[aria-selected="true"] {
618+ background: var(--active-row, #d9ebd3);
619+}
620+
621+.slash-item .keycaps {
622+ margin-inline-start: 0;
623+}
624+
625+.slash-empty {
626+ padding: 8px;
627+ color: var(--muted-foreground, #5b6270);
628+ font-size: 13px;
629+}
630+
631+.slash-footer {
632+ display: flex;
633+ flex-wrap: wrap;
634+ align-items: center;
635+ gap: 2px;
636+ margin-top: 4px;
637+ padding: 6px 8px 2px;
638+ border-top: 1px solid var(--border, #e3e5ea);
639+ color: var(--muted-foreground, #5b6270);
640+ font-family: var(--font-mono, "Atkinson Hyperlegible Mono", ui-monospace, monospace);
641+ font-size: 11px;
642+ line-height: 16px;
643+}
644+
645+.slash-footer .keycaps {
646+ margin-inline-start: 0;
647+}
648+
649+/* Note suggestions: long titles are cut with an ellipsis */
650+
651+.note-menu .slash-label {
652+ min-width: 0;
653+ overflow: hidden;
654+ text-overflow: ellipsis;
655+ white-space: nowrap;
656+}
657+
658+/* ---- Editor surface ---- */
659+
660+#editor {
661+ max-width: calc(68ch + 48px);
662+ margin: 0 auto;
663+ padding: 32px 24px 30vh;
664+ box-sizing: border-box;
665+}
666+
667+#editor .ProseMirror {
668+ min-height: 60vh;
669+ max-width: 68ch;
670+ margin: 0 auto;
671+ outline: none;
672+ color: var(--foreground, #16181d);
673+ caret-color: var(--foreground, #16181d);
674+ font-family: var(--font-sans, "Atkinson Hyperlegible Next", sans-serif);
675+ font-size: 17px;
676+ line-height: 1.65;
677+ overflow-wrap: break-word;
678+ word-wrap: break-word;
679+ font-variant-ligatures: common-ligatures;
680+}
681+
682+#editor .ProseMirror:focus,
683+#editor .ProseMirror:focus-visible {
684+ outline: none;
685+}
686+
687+/* Top-level blocks sit in pages (view.rs); spacing runs across page boundaries.
688+ :where keeps the specificity of the plain `.ProseMirror > * + *` rules. */
689+#editor .ProseMirror :where(.pm-page) > * + *,
690+#editor .ProseMirror :where(.pm-page + .pm-page) > :where(:first-child) {
691+ margin-top: 0.75em;
692+}
693+
694+#editor .ProseMirror ::selection,
695+#editor .ProseMirror::selection {
696+ background: var(--mark, #ffe08a);
697+ color: var(--foreground, #16181d);
698+}
699+
700+#editor .ProseMirror p {
701+ margin: 0;
702+}
703+
704+/* Embedded media: images scale to the column, audio and video are their own blocks. */
705+#editor .ProseMirror img {
706+ max-width: 100%;
707+}
708+
709+#editor .ProseMirror audio.note-media {
710+ display: block;
711+ width: 100%;
712+ max-width: 32rem;
713+}
714+
715+#editor .ProseMirror video.note-media {
716+ display: block;
717+ max-width: 100%;
718+}
719+
720+/* A recording take: its audio and continue button, until the take is live or lost. Then the
721+ label stands in for both. The state is an attribute, so the editor never rebuilds the span. */
722+#editor .ProseMirror span.note-take {
723+ display: flex;
724+ flex-wrap: wrap;
725+ align-items: center;
726+ gap: 0.5rem;
727+}
728+
729+#editor .ProseMirror span.note-take audio {
730+ flex: 1 1 16rem;
731+ max-width: 32rem;
732+}
733+
734+#editor .ProseMirror span.note-take .note-take-continue {
735+ font: inherit;
736+ font-size: 0.875rem;
737+ padding: 0.25rem 0.625rem;
738+ border: 1px solid var(--border, #d4d7de);
739+ border-radius: 0.375rem;
740+ background: var(--background, #fff);
741+ color: var(--foreground, #1f2330);
742+ cursor: pointer;
743+}
744+
745+#editor .ProseMirror span.note-take[data-take-state="live"] > audio,
746+#editor .ProseMirror span.note-take[data-take-state="live"] > .note-take-continue,
747+#editor .ProseMirror span.note-take[data-take-state="lost"] > audio,
748+#editor .ProseMirror span.note-take[data-take-state="lost"] > .note-take-continue {
749+ display: none;
750+}
751+
752+#editor .ProseMirror span.note-take[data-take-state="live"]::before,
753+#editor .ProseMirror span.note-take[data-take-state="lost"]::before {
754+ color: var(--muted-foreground, #5b6270);
755+ font-size: 0.875rem;
756+}
757+
758+#editor .ProseMirror span.note-take[data-take-state="live"]::before {
759+ content: attr(data-recording-label);
760+}
761+
762+#editor .ProseMirror span.note-take[data-take-state="lost"]::before {
763+ content: attr(data-lost-label);
764+}
765+
766+/* Placeholder: shown by the placeholder decoration while the note is empty. */
767+#editor .ProseMirror p.is-placeholder::before {
768+ content: attr(data-placeholder);
769+ float: left;
770+ height: 0;
771+ color: var(--muted-foreground, #5b6270);
772+ pointer-events: none;
773+}
774+
775+/* Headings: 30/36, 23/30, 19/26, all bold. */
776+#editor .ProseMirror h1,
777+#editor .ProseMirror h2,
778+#editor .ProseMirror h3 {
779+ margin: 0;
780+ color: var(--foreground, #16181d);
781+ font-weight: 700;
782+ letter-spacing: -0.01em;
783+}
784+
785+#editor .ProseMirror :where(.pm-page) > * + h1,
786+#editor .ProseMirror :where(.pm-page) > * + h2,
787+#editor .ProseMirror :where(.pm-page) > * + h3,
788+#editor .ProseMirror :where(.pm-page + .pm-page) > h1:where(:first-child),
789+#editor .ProseMirror :where(.pm-page + .pm-page) > h2:where(:first-child),
790+#editor .ProseMirror :where(.pm-page + .pm-page) > h3:where(:first-child) {
791+ margin-top: 1.4em;
792+}
793+
794+#editor .ProseMirror h1 {
795+ font-size: 30px;
796+ line-height: 36px;
797+}
798+
799+#editor .ProseMirror h2 {
800+ font-size: 23px;
801+ line-height: 30px;
802+}
803+
804+#editor .ProseMirror h3 {
805+ font-size: 19px;
806+ line-height: 26px;
807+}
808+
809+/* Lists */
810+
811+#editor .ProseMirror ul,
812+#editor .ProseMirror ol {
813+ margin: 0;
814+ padding-left: 1.6em;
815+}
816+
817+#editor .ProseMirror ul {
818+ list-style: disc;
819+}
820+
821+#editor .ProseMirror ol {
822+ list-style: decimal;
823+}
824+
825+#editor .ProseMirror ul ul {
826+ list-style: circle;
827+}
828+
829+#editor .ProseMirror ul ul ul {
830+ list-style: square;
831+}
832+
833+#editor .ProseMirror li {
834+ margin: 0.2em 0;
835+}
836+
837+#editor .ProseMirror li::marker {
838+ color: var(--muted-foreground, #5b6270);
839+}
840+
841+#editor .ProseMirror li > p + p,
842+#editor .ProseMirror li > * + ul,
843+#editor .ProseMirror li > * + ol {
844+ margin-top: 0.2em;
845+}
846+
847+/* A list or quote cut by a page boundary (view.rs): the part on the later page has
848+ pm-cont, the earlier part pm-more; together they look like one element. */
849+#editor .ProseMirror .pm-page > .pm-cont,
850+#editor .ProseMirror li.pm-cont,
851+#editor .ProseMirror .pm-cont > li:first-child {
852+ margin-top: 0;
853+}
854+
855+#editor .ProseMirror li.pm-cont {
856+ list-style-type: none;
857+}
858+
859+#editor .ProseMirror li.pm-more {
860+ margin-bottom: 0;
861+}
862+
863+#editor .ProseMirror blockquote.pm-cont {
864+ padding-top: 0;
865+}
866+
867+#editor .ProseMirror blockquote.pm-more {
868+ padding-bottom: 0;
869+}
870+
871+/* Quote */
872+
873+#editor .ProseMirror blockquote {
874+ margin: 0;
875+ padding: 2px 0 2px 16px;
876+ border-left: 3px solid var(--border, #e3e5ea);
877+ color: var(--muted-foreground, #5b6270);
878+}
879+
880+/* Code: mono on the background token, hairline border */
881+
882+#editor .ProseMirror code {
883+ padding: 1px 5px;
884+ border: 1px solid var(--border, #e3e5ea);
885+ border-radius: 6px;
886+ background: var(--background, #f5f6f8);
887+ color: var(--foreground, #16181d);
888+ font-family: var(--font-mono, "Atkinson Hyperlegible Mono", ui-monospace, monospace);
889+ font-size: 0.88em;
890+}
891+
892+#editor .ProseMirror pre {
893+ margin: 0;
894+ padding: 12px 14px;
895+ border: 1px solid var(--border, #e3e5ea);
896+ border-radius: 10px;
897+ background: var(--background, #f5f6f8);
898+ color: var(--foreground, #16181d);
899+ font-family: var(--font-mono, "Atkinson Hyperlegible Mono", ui-monospace, monospace);
900+ font-size: 14px;
901+ line-height: 22px;
902+ overflow-x: auto;
903+ white-space: pre;
904+}
905+
906+#editor .ProseMirror pre code {
907+ display: block;
908+ padding: 0;
909+ border: 0;
910+ border-radius: 0;
911+ background: none;
912+ font-size: inherit;
913+}
914+
915+/* Long code blocks render as line chunks (view.rs); off-screen ones skip layout,
916+ sized by their line count until first shown. */
917+#editor .ProseMirror .code-chunk {
918+ content-visibility: auto;
919+ contain-intrinsic-size: auto none auto calc(var(--lines) * 22px);
920+}
921+
922+/* A chunk far from the viewport is an empty placeholder of its height. */
923+#editor .ProseMirror .code-chunk:empty {
924+ height: calc(var(--lines) * 22px);
925+}
926+
927+/* Code blocks: a header bar (ui/codeblock.rs) sits over the top 34px of each pre */
928+
929+#editor .ProseMirror pre {
930+ padding-top: 46px;
931+}
932+
933+.code-layer {
934+ position: absolute;
935+ inset: 0;
936+ pointer-events: none;
937+}
938+
939+.code-layer[hidden] {
940+ display: none;
941+}
942+
943+.code-head {
944+ position: absolute;
945+ box-sizing: border-box;
946+ display: flex;
947+ align-items: center;
948+ gap: 4px;
949+ height: 34px;
950+ padding: 0 6px 0 10px;
951+ border-bottom: 1px solid var(--border, #e3e5ea);
952+ border-radius: 9px 9px 0 0;
953+ background: color-mix(in srgb, var(--foreground, #16181d) 3%, transparent);
954+ color: var(--muted-foreground, #5b6270);
955+ font-family: var(--font-sans, "Atkinson Hyperlegible Next", sans-serif);
956+ font-size: 12px;
957+ pointer-events: auto;
958+}
959+
960+.code-head[hidden] {
961+ display: none;
962+}
963+
964+.code-lang {
965+ min-width: 0;
966+ max-width: 14rem;
967+ height: 24px;
968+ margin: 0;
969+ padding: 0 4px;
970+ border: 0;
971+ border-radius: 6px;
972+ background: transparent;
973+ color: inherit;
974+ font: inherit;
975+ cursor: pointer;
976+}
977+
978+.code-lang:hover {
979+ background: var(--sidebar-accent, #e3e6eb);
980+ color: var(--foreground, #16181d);
981+}
982+
983+.code-lang option {
984+ background: var(--background, #f5f6f8);
985+ color: var(--foreground, #16181d);
986+}
987+
988+.code-spacer {
989+ flex: 1;
990+ min-width: 4px;
991+}
992+
993+.code-status {
994+ min-width: 0;
995+ overflow: hidden;
996+ font-size: 11px;
997+ text-overflow: ellipsis;
998+ white-space: nowrap;
999+}
1000+
1001+.code-btn {
1002+ display: inline-grid;
1003+ place-items: center;
1004+ flex: none;
1005+ width: 24px;
1006+ height: 24px;
1007+ margin: 0;
1008+ padding: 0;
1009+ border: 0;
1010+ border-radius: 6px;
1011+ background: transparent;
1012+ color: var(--muted-foreground, #5b6270);
1013+ cursor: pointer;
1014+ transition:
1015+ background-color 150ms ease-out,
1016+ color 150ms ease-out;
1017+}
1018+
1019+.code-btn svg {
1020+ display: block;
1021+}
1022+
1023+.code-btn:hover:not(:disabled) {
1024+ background: var(--sidebar-accent, #e3e6eb);
1025+ color: var(--foreground, #16181d);
1026+}
1027+
1028+.code-btn[aria-pressed="true"] {
1029+ background: var(--active-row, #d9ebd3);
1030+ color: var(--active-row-foreground, #1f3d22);
1031+}
1032+
1033+.code-btn:disabled {
1034+ opacity: 0.4;
1035+ cursor: not-allowed;
1036+}
1037+
1038+.code-btn:focus-visible,
1039+.code-lang:focus-visible {
1040+ outline: 2px solid var(--ring, #8a5a00);
1041+ outline-offset: 2px;
1042+}
1043+
1044+/* Marks: search-style highlight */
1045+
1046+#editor .ProseMirror mark {
1047+ padding: 0 0.1em;
1048+ border-radius: 3px;
1049+ background: var(--mark, #ffe08a);
1050+ color: inherit;
1051+}
1052+
1053+/* Links: accent ink with a quiet underline */
1054+
1055+#editor .ProseMirror a {
1056+ color: var(--link, #8a5a00);
1057+ text-decoration-line: underline;
1058+ text-decoration-thickness: 1px;
1059+ text-decoration-color: color-mix(in srgb, var(--link, #8a5a00) 45%, transparent);
1060+ text-underline-offset: 3px;
1061+ cursor: pointer;
1062+}
1063+
1064+#editor .ProseMirror a:hover {
1065+ text-decoration-color: var(--link, #8a5a00);
1066+}
1067+
1068+/* Note links (href /notes/<id>): a tinted chip, underlined only on hover */
1069+
1070+#editor .ProseMirror a[href^="/notes/"] {
1071+ padding: 0 0.2em;
1072+ border-radius: 4px;
1073+ background: color-mix(in srgb, var(--link, #8a5a00) 12%, transparent);
1074+ text-decoration-line: none;
1075+ box-decoration-break: clone;
1076+ -webkit-box-decoration-break: clone;
1077+}
1078+
1079+#editor .ProseMirror a[href^="/notes/"]:hover {
1080+ text-decoration-line: underline;
1081+}
1082+
1083+/* Horizontal rule */
1084+
1085+#editor .ProseMirror hr {
1086+ margin: 2em 0;
1087+ border: 0;
1088+ border-top: 1px solid var(--border, #e3e5ea);
1089+}
1090+
1091+#editor .ProseMirror hr.ProseMirror-selectednode {
1092+ outline: 2px solid var(--ring, #8a5a00);
1093+ outline-offset: 4px;
1094+ border-radius: 2px;
1095+}
1096+
1097+/* ---- Remote cursors and selections (loro-prosemirror classes) ---- */
1098+
1099+.ProseMirror-loro-cursor {
1100+ position: relative;
1101+ margin-left: -1px;
1102+ margin-right: -1px;
1103+ /* border-color is set inline per user */
1104+ border-left: 2px solid;
1105+ word-break: normal;
1106+ pointer-events: none;
1107+}
1108+
1109+/* Name label in the user's color, mono 11px. */
1110+.ProseMirror-loro-cursor > div {
1111+ position: absolute;
1112+ top: -1.5em;
1113+ left: -2px;
1114+ padding: 0 5px;
1115+ border-radius: 4px 4px 4px 0;
1116+ /* background-color is set inline per user */
1117+ color: #ffffff;
1118+ font-family: var(--font-mono, "Atkinson Hyperlegible Mono", ui-monospace, monospace);
1119+ font-size: 11px;
1120+ font-weight: 500;
1121+ line-height: 16px;
1122+ white-space: nowrap;
1123+ user-select: none;
1124+}
1125+
1126+.loro-selection {
1127+ border-radius: 2px;
1128+}
1129+
1130+@media (prefers-reduced-motion: reduce) {
1131+ .editor-toolbar-btn,
1132+ .bubble-btn,
1133+ .btn,
1134+ .tip {
1135+ transition-duration: 0ms !important;
1136+ transition-delay: 0ms !important;
1137+ }
1138+}
1139+
1140+@media (forced-colors: active) {
1141+ .editor-toolbar-btn[aria-pressed="true"],
1142+ .bubble-btn[aria-pressed="true"],
1143+ .slash-item[aria-selected="true"] {
1144+ outline: 2px solid CanvasText;
1145+ }
1146+}
assets/editor.jsdeleted+0 -16
@@ -1,16 +0,0 @@
1-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(;s<r;s++){let l=t.charCodeAt(s);if(l>127)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;s<i;s++)o+=", "+hi(t[s]);return o+="]",o}let n=/\[object ([^\]]+)\]/.exec(toString.call(t)),r;if(n&&n.length>1)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}
2-${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<t.length;i++)r.setUint32(n+4*i,w(t[i]),!0);return M=t.length,n}var mt=128;function Nt(t){if(mt==1)throw Error("out of js stack");return tt[--mt]=t,mt}function en(t,e){if(!(t instanceof e))throw Error(`expected instance of ${e.name}`)}function te(t,e){t=t>>>0;let n=u(),r=[];for(let i=t;i<t+4*e;i+=4)r.push(_(n.getUint32(i,!0)));return r}function Ic(t,e,n){a._dyn_core_ed718c3d60ebd546___ops__function__FnMut_______Output______as_wasm_bindgen_cfd5deec16e3bd1c___closure__WasmClosure___describe__invoke___wasm_bindgen_cfd5deec16e3bd1c___JsValue_____(t,e,w(n))}function vc(t,e){a._dyn_core_ed718c3d60ebd546___ops__function__FnMut_____Output______as_wasm_bindgen_cfd5deec16e3bd1c___closure__WasmClosure___describe__invoke______(t,e)}var sp=typeof FinalizationRegistry>"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<this.content.length;e+=2)if(this.content[e]===t)return e;return-1},get:function(t){var e=this.find(t);return e==-1?void 0:this.content[e+1]},update:function(t,e,n){var r=n&&n!=t?this.remove(n):this,i=r.find(t),o=r.content.slice();if(i==-1)o.push(n||t,e);else if(o[i+1]=e,n)o[i]=n;return new kt(o)},remove:function(t){var e=this.find(t);if(e==-1)return this;var n=this.content.slice();return n.splice(e,2),new kt(n)},addToStart:function(t,e){return new kt([t,e].concat(this.remove(t).content))},addToEnd:function(t,e){var n=this.remove(t).content.slice();return n.push(t,e),new kt(n)},addBefore:function(t,e,n){var r=this.remove(e),i=r.content.slice(),o=r.find(t);return i.splice(o==-1?i.length:o,0,e,n),new kt(i)},forEach:function(t){for(var e=0;e<this.content.length;e+=2)t(this.content[e],this.content[e+1])},prepend:function(t){if(t=kt.from(t),!t.size)return this;return new kt(t.content.concat(this.subtract(t).content))},append:function(t){if(t=kt.from(t),!t.size)return this;return new kt(this.subtract(t).content.concat(t.content))},subtract:function(t){var e=this;t=kt.from(t);for(var n=0;n<t.content.length;n+=2)e=e.remove(t.content[n]);return e},toObject:function(){var t={};return this.forEach(function(e,n){t[e]=n}),t},get size(){return this.content.length>>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&&c<s.length&&c<l.length&&hs(s.charCodeAt(c-1))&&fs(s.charCodeAt(c)))n--;return n}if(i.content.size||o.content.size){let s=ds(i.content,o.content,n+1);if(s!=null)return s}n+=i.nodeSize}}function us(t,e,n,r){for(let i=t.childCount,o=e.childCount;;){if(i==0||o==0)return i==o?null:{a:n,b:r};let s=t.child(--i),l=e.child(--o),c=s.nodeSize;if(s==l){n-=c,r-=c;continue}if(!s.sameMarkup(l))return{a:n,b:r};if(s.isText&&s.text!=l.text){let d=s.text,f=l.text,h=d.length,p=f.length;while(h>0&&p>0&&d[h-1]==f[p-1])h--,p--,n--,r--;if(h&&p&&h<d.length&&hs(d.charCodeAt(h-1))&&fs(d.charCodeAt(h)))n++,r++;return{a:n,b:r}}if(s.content.size||l.content.size){let d=us(s.content,l.content,n-1,r-1);if(d)return d}n-=c,r-=c}}function fs(t){return t>=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;n<t.length;n++)this.size+=t[n].nodeSize}nodesBetween(t,e,n,r=0,i){for(let o=0,s=0;s<e;o++){let l=this.content[o],c=s+l.nodeSize;if(c>t&&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(;i<t.content.length;i++)r.push(t.content[i]);return new k(r,this.size+t.size)}cut(t,e=this.size){if(t==0&&e==this.size)return this;let n=[],r=0;if(e>t)for(let i=0,o=0;o<e;i++){let s=this.content[i],l=o+s.nodeSize;if(l>t){if(o<t||l>e)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;e<this.content.length;e++)if(!this.content[e].eq(t.content[e]))return!1;return!0}get firstChild(){return this.content.length?this.content[0]:null}get lastChild(){return this.content.length?this.content[this.content.length-1]:null}get childCount(){return this.content.length}child(t){let e=this.content[t];if(!e)throw RangeError("Index "+t+" out of range for "+this);return e}maybeChild(t){return this.content[t]||null}forEach(t){for(let e=0,n=0;e<this.content.length;e++){let r=this.content[e];t(r,n,e),n+=r.nodeSize}}findDiffStart(t,e=0){return ds(this,t,e)}findDiffEnd(t,e=this.size,n=t.size){return us(this,t,e,n)}findIndex(t){if(t==0)return hr(0,t);if(t==this.size)return hr(this.content.length,t);if(t>this.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;r<t.length;r++){let i=t[r];if(n+=i.nodeSize,r&&i.isText&&t[r-1].sameMarkup(i)){if(!e)e=t.slice(0,r);e[e.length-1]=i.withText(e[e.length-1].text+i.text)}else if(e)e.push(i)}return new k(e||t,n)}static from(t){if(!t)return k.empty;if(t instanceof k)return t;if(Array.isArray(t))return this.fromArray(t);if(t.attrs)return new k([t],t.nodeSize);throw RangeError("Can not convert "+t+" to a Fragment"+(t.nodesBetween?" (looks like multiple versions of prosemirror-model were loaded)":""))}}k.empty=new k([],0);var wi={index:0,offset:0};function hr(t,e){return wi.index=t,wi.offset=e,wi}function gr(t,e){if(t===e)return!0;if(!(t&&typeof t=="object")||!(e&&typeof e=="object"))return!1;let n=Array.isArray(t);if(Array.isArray(e)!=n)return!1;if(n){if(t.length!=e.length)return!1;for(let r=0;r<t.length;r++)if(!gr(t[r],e[r]))return!1}else{for(let r in t)if(!(r in e)||!gr(t[r],e[r]))return!1;for(let r in e)if(!(r in t))return!1}return!0}class J{constructor(t,e){this.type=t,this.attrs=e}addToSet(t){let e,n=!1;for(let r=0;r<t.length;r++){let i=t[r];if(this.eq(i))return t;if(this.type.excludes(i.type)){if(!e)e=t.slice(0,r)}else if(i.type.excludes(this.type))return t;else{if(!n&&i.type.rank>this.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;e<t.length;e++)if(this.eq(t[e]))return t.slice(0,e).concat(t.slice(e+1));return t}isInSet(t){for(let e=0;e<t.length;e++)if(this.eq(t[e]))return!0;return!1}eq(t){return this==t||this.type==t.type&&gr(this.attrs,t.attrs)}toJSON(){let t={type:this.type.name};for(let e in this.attrs){t.attrs=this.attrs;break}return t}static fromJSON(t,e){if(!e)throw RangeError("Invalid input for Mark.fromJSON");let n=t.marks[e.type];if(!n)throw RangeError(`There is no mark type ${e.type} in this schema`);return n.create(e.attrs)}static sameSet(t,e){if(t==e)return!0;if(t.length!=e.length)return!1;for(let n=0;n<t.length;n++)if(!t[n].eq(e[n]))return!1;return!0}static setFrom(t){if(!t||Array.isArray(t)&&t.length==0)return J.none;if(t instanceof J)return[t];let e=t.slice();return e.sort((n,r)=>n.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<t.depth-n.openStart){let s=gs(t,e,n,r+1);return o.copy(o.content.replaceChild(i,s))}else if(!n.content.size)return Be(o,mr(t,e,r));else if(!n.openStart&&!n.openEnd&&t.depth==r&&e.depth==r){let s=t.parent,l=s.content;return Be(s,l.cut(0,t.parentOffset).append(n.content).append(l.cut(e.parentOffset)))}else{let{start:s,end:l}=Bc(n,t);return Be(o,bs(t,s,l,e,r))}}function ms(t,e){if(!e.type.compatibleContent(t.type))throw new ze("Cannot join "+e.type.name+" onto "+t.type.name)}function yi(t,e,n){let r=t.node(n);return ms(r,e.node(n)),r}function Pe(t,e){let n=e.length-1;if(n>=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;l<s;l++)Pe(i.child(l),r);if(e&&e.depth==n&&e.textOffset)Pe(e.nodeBefore,r)}function Be(t,e){if(!t.type.validContent(e))throw new ze("Invalid content for node "+t.type.name);return t.copy(e)}function bs(t,e,n,r,i){let o=t.depth>i&&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;i<t;i++)r+=n.child(i).nodeSize;return r}marks(){let t=this.parent,e=this.index();if(t.content.size==0)return J.none;if(this.textOffset)return t.child(e).marks;let n=t.maybeChild(e-1),r=t.maybeChild(e);if(!n){let s=n;n=r,r=s}let i=n.marks;for(var o=0;o<i.length;o++)if(i[o].type.spec.inclusive===!1&&(!r||!i[o].isInSet(r.marks)))i=i[o--].removeFromSet(i);return i}marksAcross(t){let e=this.parent.maybeChild(this.index());if(!e||!e.isInline)return null;let n=e.marks,r=t.parent.maybeChild(t.index());for(var i=0;i<n.length;i++)if(n[i].type.spec.inclusive===!1&&(!r||!n[i].isInSet(r.marks)))n=n[i--].removeFromSet(n);return n}sharedDepth(t){for(let e=this.depth;e>0;e--)if(this.start(e)<=t&&this.end(e)>=t)return e;return 0}blockRange(t=this,e){if(t.pos<this.pos)return t.blockRange(this);for(let n=this.depth-(this.parent.inlineContent||this.pos==t.pos?1:0);n>=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<this.pos?t:this}toString(){let t="";for(let e=1;e<=this.depth;e++)t+=(t?"/":"")+this.node(e).type.name+"_"+this.index(e-1);return t+":"+this.parentOffset}static resolve(t,e){if(!(e>=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;i<n.elts.length;i++){let o=n.elts[i];if(o.pos==e)return o}else Zo.set(t,n=new ws);let r=n.elts[n.i]=Pn.resolve(t,e);return n.i=(n.i+1)%zc,r}}class ws{constructor(){this.elts=[],this.i=0}}var zc=12,Zo=new WeakMap;class on{constructor(t,e,n){this.$from=t,this.$to=e,this.depth=n}get start(){return this.$from.before(this.depth+1)}get end(){return this.$to.after(this.depth+1)}get parent(){return this.$from.node(this.depth)}get startIndex(){return this.$from.index(this.depth)}get endIndex(){return this.$to.indexAfter(this.depth)}}var Fc=Object.create(null);class qt{constructor(t,e,n,r=J.none){this.type=t,this.attrs=e,this.marks=r,this.content=n||k.empty}get children(){return this.content.content}get nodeSize(){return this.isLeaf?1:2+this.content.size}get childCount(){return this.content.childCount}child(t){return this.content.child(t)}maybeChild(t){return this.content.maybeChild(t)}forEach(t){this.content.forEach(t)}nodesBetween(t,e,n,r=0){this.content.nodesBetween(t,e,n,r,this)}descendants(t){this.nodesBetween(0,this.content.size,t)}get textContent(){return this.isLeaf&&this.type.spec.leafText?this.type.spec.leafText(this):this.textBetween(0,this.content.size,"")}textBetween(t,e,n,r){return this.content.textBetween(t,e,n,r)}get firstChild(){return this.content.firstChild}get lastChild(){return this.content.lastChild}eq(t){return this==t||this.sameMarkup(t)&&this.content.eq(t.content)}sameMarkup(t){return this.hasMarkup(t.type,t.attrs,t.marks)}hasMarkup(t,e,n){return this.type==t&&gr(this.attrs,e||t.defaultAttrs||Fc)&&J.sameSet(this.marks,n||J.none)}copy(t=null){if(t==this.content)return this;return new qt(this.type,this.attrs,t,this.marks)}mark(t){return t==this.marks?this:new qt(this.type,this.attrs,this.content,t)}cut(t,e=this.content.size){if(t==0&&e==this.content.size)return this;return this.copy(this.content.cut(t,e))}slice(t,e=this.content.size,n=!1){if(t==e)return I.empty;let r=this.resolve(t),i=this.resolve(e),o=n?0:r.sharedDepth(e),s=r.start(o),c=r.node(o).content.cut(r.pos-s,i.pos-s);return new I(c,r.depth-o,i.depth-o)}replace(t,e,n){return Pc(this.resolve(t),this.resolve(e),n)}nodeAt(t){for(let e=this;;){let{index:n,offset:r}=e.content.findIndex(t);if(e=e.maybeChild(n),!e)return null;if(r==t||e.isText)return e;t-=r+1}}childAfter(t){let{index:e,offset:n}=this.content.findIndex(t);return{node:this.content.maybeChild(e),index:e,offset:n}}childBefore(t){if(t==0)return{node:null,index:0,offset:0};let{index:e,offset:n}=this.content.findIndex(t);if(n<t)return{node:this.content.child(e),index:e,offset:n};let r=this.content.child(e-1);return{node:r,index:e-1,offset:n-r.nodeSize}}resolve(t){return Pn.resolveCached(this,t)}resolveNoCache(t){return Pn.resolve(this,t)}rangeHasMark(t,e,n){let r=!1;if(e>t)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;l<i;l++)if(!this.type.allowsMarks(n.child(l).marks))return!1;return!0}canReplaceWith(t,e,n,r){if(r&&!this.type.allowsMarks(r))return!1;let i=this.contentMatchAt(t).matchType(n),o=i&&i.matchFragment(this.content,e);return o?o.validEnd:!1}canAppend(t){if(t.content.size)return this.canReplace(this.childCount,this.childCount,t.content);else return this.type.compatibleContent(t.type)}check(){this.type.checkContent(this.content),ts(this.type.attrs,this.attrs,"node",this.type.name);let t=J.none;for(let e=0;e<this.marks.length;e++){let n=this.marks[e];ts(n.type.attrs,n.attrs,"mark",n.type.name),t=n.addToSet(t)}if(!J.sameSet(t,this.marks))throw RangeError(`Invalid collection of marks for node ${this.type.name}: ${this.marks.map((e)=>e.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;e<this.next.length;e++)if(this.next[e].type==t)return this.next[e].next;return null}matchFragment(t,e=0,n=t.childCount){let r=this;for(let i=e;r&&i<n;i++)r=r.matchType(t.child(i).type);return r}get inlineContent(){return this.next.length!=0&&this.next[0].type.isInline}get defaultType(){for(let t=0;t<this.next.length;t++){let{type:e}=this.next[t];if(!(e.isText||e.hasRequiredAttrs()))return e}return null}compatible(t){for(let e=0;e<this.next.length;e++)for(let n=0;n<t.next.length;n++)if(this.next[e].type==t.next[n].type)return!0;return!1}fillBefore(t,e=!1,n=0){let r=[this];function i(o,s){let l=o.matchFragment(t,n);if(l&&(!e||l.validEnd))return k.from(s.map((c)=>c.createAndFill()));for(let c=0;c<o.next.length;c++){let{type:d,next:f}=o.next[c];if(!(d.isText||d.hasRequiredAttrs())&&r.indexOf(f)==-1){r.push(f);let h=i(f,s.concat(d));if(h)return h}}return null}return i(this,[])}findWrapping(t){for(let n=0;n<this.wrapCache.length;n+=2)if(this.wrapCache[n]==t)return this.wrapCache[n+1];let e=this.computeWrapping(t);return this.wrapCache.push(t,e),e}computeWrapping(t){let e=Object.create(null),n=[{match:this,type:null,via:null}];while(n.length){let r=n.shift(),i=r.match;if(i.matchType(t)){let o=[];for(let s=r;s.type;s=s.via)o.push(s.type);return o.reverse()}for(let o=0;o<i.next.length;o++){let{type:s,next:l}=i.next[o];if(!s.isLeaf&&!s.hasRequiredAttrs()&&!(s.name in e)&&(!r.type||l.validEnd))n.push({match:s.contentMatch,type:s,via:r}),e[s.name]=!0}}return null}get edgeCount(){return this.next.length}edge(t){if(t>=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<n.next.length;r++)if(t.indexOf(n.next[r].next)==-1)e(n.next[r].next)}return e(this),t.map((n,r)=>{let i=r+(n.validEnd?"*":" ")+" ";for(let o=0;o<n.next.length;o++)i+=(o?", ":"")+n.next[o].type.name+"->"+t.indexOf(n.next[o].next);return i}).join(`
3-`)}}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<s.min;d++){let f=n();i(o(s.expr,c),f),c=f}if(s.max==-1)i(o(s.expr,c),c);else for(let d=s.min;d<s.max;d++){let f=n();r(c,f),i(o(s.expr,c),f),c=f}return[r(c)]}else if(s.type=="name")return[r(l,void 0,s.value)];else throw Error("Unknown expr type")}}function Is(t,e){return e-t}function ns(t,e){let n=[];return r(e),n.sort(Is);function r(i){let o=t[i];if(o.length==1&&!o[0].term)return r(o[0].to);n.push(i);for(let s=0;s<o.length;s++){let{term:l,to:c}=o[s];if(!l&&n.indexOf(c)==-1)r(c)}}}function jc(t){let e=Object.create(null);return n(ns(t,0));function n(r){let i=[];r.forEach((s)=>{t[s].forEach(({term:l,to:c})=>{if(!l)return;let d;for(let f=0;f<i.length;f++)if(i[f][0]==l)d=i[f][1];ns(t,c).forEach((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<i.length;s++){let l=i[s][1].sort(Is);o.next.push({type:i[s][0],next:e[l.join(",")]||n(l)})}return o}}function Hc(t,e){for(let n=0,r=[t];n<r.length;n++){let i=r[n],o=!i.validEnd,s=[];for(let l=0;l<i.next.length;l++){let{type:c,next:d}=i.next[l];if(s.push(c.name),o&&!(c.isText||c.hasRequiredAttrs()))o=!1;if(r.indexOf(d)==-1)r.push(d)}if(o)e.err("Only non-generatable nodes ("+s.join(", ")+") in a required position (see https://prosemirror.net/docs/guide/#generatable)")}}function vs(t){let e=Object.create(null);for(let n in t){let r=t[n];if(!r.hasDefault)return null;e[n]=r.default}return e}function Ss(t,e){let n=Object.create(null);for(let r in t){let i=t[r],o=e&&e[r];if(o===void 0)if(i.hasDefault)o=i.default;else throw RangeError("No value supplied for attribute "+r);else if(i.validate)i.validate(o);n[r]=o}return n}function Cs(t,e){let n=Object.create(null);if(e)for(let r in e)n[r]=new Os(t,r,e[r]);return n}class wr{constructor(t,e,n){this.name=t,this.schema=e,this.spec=n,this.markSet=null,this.groups=n.group?n.group.split(" "):[],this.attrs=Cs(t,n.attrs),this.defaultAttrs=vs(this.attrs),this.contentMatch=null,this.inlineContent=null,this.isBlock=!(n.inline||t=="text"),this.isText=t=="text"}get isInline(){return!this.isBlock}get isTextblock(){return this.isBlock&&this.inlineContent}get isLeaf(){return this.contentMatch==Fe.empty}get isAtom(){return this.isLeaf||!!this.spec.atom}isInGroup(t){return this.groups.indexOf(t)>-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<t.childCount;n++)if(!this.allowsMarks(t.child(n).marks))return!1;return!0}checkContent(t){if(!this.validContent(t))throw RangeError(`Invalid content for node ${this.name}: ${t.toString().slice(0,50)}`)}checkAttrs(t){}allowsMarkType(t){return this.markSet==null||this.markSet.indexOf(t)>-1}allowsMarks(t){if(this.markSet==null)return!0;for(let e=0;e<t.length;e++)if(!this.allowsMarkType(t[e].type))return!1;return!0}allowedMarks(t){if(this.markSet==null)return t;let e;for(let n=0;n<t.length;n++)if(!this.allowsMarkType(t[n].type)){if(!e)e=t.slice(0,n)}else if(e)e.push(t[n]);return!e?t:e.length?e:J.none}static compile(t,e){let n=Object.create(null);t.forEach((i,o)=>n[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<t.length;e++)if(t[e].type==this)t=t.slice(0,e).concat(t.slice(e+1)),e--;return t}isInSet(t){for(let e=0;e<t.length;e++)if(t[e].type==this)return t[e]}excludes(t){return this.excluded.indexOf(t)>-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<e.length;r++){let i=e[r],o=t.marks[i],s=o;if(o)n.push(o);else for(let l in t.marks){let c=t.marks[l];if(i=="_"||c.spec.group&&c.spec.group.split(" ").indexOf(i)>-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;r<this.tags.length;r++){let i=this.tags[r];if(Zc(t,i.tag)&&(i.namespace===void 0||t.namespaceURI==i.namespace)&&(!i.context||e.matchesContext(i.context))){if(i.getAttrs){let o=i.getAttrs(t);if(o===!1)continue;i.attrs=o||void 0}return i}}}matchStyle(t,e,n,r){for(let i=r?this.styles.indexOf(r)+1:0;i<this.styles.length;i++){let o=this.styles[i],s=o.style;if(s.indexOf(t)!=0||o.context&&!n.matchesContext(o.context)||s.length>t.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<e.length;o++){let s=e[o];if((s.priority==null?50:s.priority)<i)break}e.splice(o,0,r)}for(let r in t.marks){let i=t.marks[r].spec.parseDOM;if(i)i.forEach((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,`
4-`);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<s.length;l++){if(l)this.insertNode(o.linebreakReplacement.create(),e,!0);if(s[l])this.insertNode(o.text(s[l]),e,!/\S/.test(s[l]))}n=""}else n=n.replace(/\r?\n|\r/g," ");if(n)this.insertNode(o.text(n),e,!/\S/.test(n));this.findInText(t)}else this.findInside(t)}addElement(t,e,n){let r=this.localPreserveWS,i=this.top;if(t.tagName=="PRE"||/pre/.test(t.style&&t.style.whiteSpace))this.localPreserveWS=!0;let o=t.nodeName.toLowerCase(),s;if(As.hasOwnProperty(o)&&this.parser.normalizeLists)Qc(t);let l=this.options.ruleFromNode&&this.options.ruleFromNode(t)||(s=this.parser.matchTag(t,this,n));t:if(l?l.ignore:Gc.hasOwnProperty(o))this.findInside(t),this.ignoreFallback(t,e);else if(!l||l.skip||l.closeParent){if(l&&l.closeParent)this.open=Math.max(0,this.open-1);else if(l&&l.skip.nodeType)t=l.skip;let c,d=this.needsBlock;if(Ms.hasOwnProperty(o)){if(i.content.length&&i.content[0].isInline&&this.open)this.open--,i=this.top;if(c=!0,!i.type)this.needsBlock=!0}else if(!t.firstChild){this.leafFallback(t,e);break t}let f=l&&l.skip?e:this.readStyles(t,e);if(f)this.addAll(t,f);if(c)this.sync(i);this.needsBlock=d}else{let c=this.readStyles(t,e);if(c)this.addElementByRule(t,l,c,l.consuming===!1?s:void 0)}this.localPreserveWS=r}leafFallback(t,e){if(t.nodeName=="BR"&&this.top.type&&this.top.type.inlineContent)this.addTextNode(t.ownerDocument.createTextNode(`
5-`),e)}ignoreFallback(t,e){if(t.nodeName=="BR"&&(!this.top.type||!this.top.type.inlineContent))this.findPlace(this.parser.schema.text("-"),e,!0)}readStyles(t,e){let n=t.style;if(n&&n.length)for(let r=0;r<this.parser.matchedStyles.length;r++){let i=this.parser.matchedStyles[r],o=n.getPropertyValue(i);if(o)for(let s=void 0;;){let l=this.parser.matchStyle(i,o,this,s);if(!l)break;if(l.ignore)return null;if(l.clearMark)e=e.filter((c)=>!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<r.length;o++)e=this.enterInner(r[o],null,e,!1);return e}insertNode(t,e,n){if(t.isInline&&this.needsBlock&&!this.top.type){let i=this.textblockFromContext();if(i)e=this.enterInner(i,null,e)}let r=this.findPlace(t,e,n);if(r){this.closeExtra();let i=this.top;if(i.match)i.match=i.match.matchType(t.type);let o=J.none;for(let s of r.concat(t.marks))if(i.type?i.type.allowsMarkType(s.type):ls(s.type,t.type))o=s.addToSet(o);return i.content.push(t.mark(o)),!0}return!1}enter(t,e,n,r){let i=this.findPlace(t.create(e),n,!1);if(i)i=this.enterInner(t,e,n,!0,r);return i}enterInner(t,e,n,r=!1,i){this.closeExtra();let o=this.top;o.match=o.match&&o.match.matchType(t);let s=is(t,i,o.options);if(o.options&Ln&&o.content.length==0)s|=Ln;let l=J.none;return n=n.filter((c)=>{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<this.find.length;n++)if(this.find[n].node==t&&this.find[n].offset==e)this.find[n].pos=this.currentPos}}findInside(t){if(this.find){for(let e=0;e<this.find.length;e++)if(this.find[e].pos==null&&t.nodeType==1&&t.contains(this.find[e].node))this.find[e].pos=this.currentPos}}findAround(t,e,n){if(t!=e&&this.find){for(let r=0;r<this.find.length;r++)if(this.find[r].pos==null&&t.nodeType==1&&t.contains(this.find[r].node)){if(e.compareDocumentPosition(this.find[r].node)&(n?2:4))this.find[r].pos=this.currentPos}}}findInText(t){if(this.find){for(let e=0;e<this.find.length;e++)if(this.find[e].node==t)this.find[e].pos=this.currentPos-(t.nodeValue.length-this.find[e].offset)}}matchesContext(t){if(t.indexOf("|")>-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<l.edgeCount;c++){let{type:d,next:f}=l.edge(c);if(d==e)return!0;if(o.indexOf(f)<0&&s(f))return!0}};if(s(i.contentMatch))return!0}}class Ve{constructor(t,e){this.nodes=t,this.marks=e}serializeFragment(t,e={},n){if(!n)n=pr(e).createDocumentFragment();let r=n,i=[];return t.forEach((o)=>{if(i.length||o.marks.length){let s=0,l=0;while(s<i.length&&l<o.marks.length){let c=o.marks[l];if(!this.marks[c.type.name]){l++;continue}if(!c.eq(i[s][0])||c.type.spec.spanning===!1)break;s++,l++}while(s<i.length)r=i.pop()[1];while(l<o.marks.length){let c=o.marks[l++],d=this.serializeMark(c,o.isInline,e);if(d)i.push([c,r]),r.appendChild(d.dom),r=d.contentDOM||d.dom}}r.appendChild(this.serializeNodeInner(o,e))}),n}serializeNodeInner(t,e){if(t.isText)return pr(e).createTextNode(t.text);let{dom:n,contentDOM:r}=_r(pr(e),this.nodes[t.type.name](t),null,t.attrs);if(r){if(t.isLeaf)throw RangeError("Content hole not allowed in a leaf node spec");this.serializeFragment(t.content,e,r)}return n}serializeNode(t,e={}){let n=this.serializeNodeInner(t,e);for(let r=t.marks.length-1;r>=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<r.length;i++)n(r[i]);else for(let i in r)n(r[i])}return n(t),e}function _r(t,e,n,r){if(e.nodeType==1)return{dom:e};if(e.dom&&e.dom.nodeType==1)return e;let i=e[0],o;if(typeof i!="string")throw RangeError("Invalid array passed to renderSpec");if(r&&(o=td(r))&&o.indexOf(e)>-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;h<e.length;h++){let p=e[h];if(p===0){if(h<e.length-1||h>f)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;r<n;r++)e+=this.ranges[r*3+2]-this.ranges[r*3+1];return this.ranges[n*3]+e+rd(t)}mapResult(t,e=1){return this._map(t,e,!1)}map(t,e=1){return this._map(t,e,!0)}_map(t,e,n){let r=0,i=this.inverted?2:1,o=this.inverted?1:2;for(let s=0;s<this.ranges.length;s+=3){let l=this.ranges[s]-(this.inverted?r:0);if(l>t)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;s<this.ranges.length;s+=3){let l=this.ranges[s]-(this.inverted?n:0);if(l>t)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<this.ranges.length;r+=3){let o=this.ranges[r],s=o-(this.inverted?i:0),l=o+(this.inverted?0:i),c=this.ranges[r+e],d=this.ranges[r+n];t(s,s+c,l,l+d),i+=d-c}}invert(){return new Bt(this.ranges,!this.inverted)}toString(){return(this.inverted?"-":"")+JSON.stringify(this.ranges)}static offset(t){return t==0?Bt.empty:new Bt(t<0?[0,-t,0]:[0,0,t])}}Bt.empty=new Bt([]);class xr{constructor(t,e,n=0,r=t?t.length:0){this.mirror=e,this.from=n,this.to=r,this._maps=t||[],this.ownData=!(t||e)}get maps(){return this._maps}slice(t=0,e=this.maps.length){return new xr(this._maps,this.mirror,t,e)}appendMap(t,e){if(!this.ownData)this._maps=this._maps.slice(),this.mirror=this.mirror&&this.mirror.slice(),this.ownData=!0;if(this.to=this._maps.push(t),e!=null)this.setMirror(this._maps.length-1,e)}appendMapping(t){for(let e=0,n=this._maps.length;e<t._maps.length;e++){let r=t.getMirror(e);this.appendMap(t._maps[e],r!=null&&r<e?n+r:void 0)}}getMirror(t){if(this.mirror){for(let e=0;e<this.mirror.length;e++)if(this.mirror[e]==t)return this.mirror[e+(e%2?-1:1)]}}setMirror(t,e){if(!this.mirror)this.mirror=[];this.mirror.push(t,e)}appendMappingInverted(t){for(let e=t.maps.length-1,n=this._maps.length+t._maps.length;e>=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;n<this.to;n++)t=this._maps[n].map(t,e);return t}mapResult(t,e=1){return this._map(t,e,!1)}_map(t,e,n){let r=0;for(let i=this.from;i<this.to;i++){let o=this._maps[i],s=o.mapResult(t,e);if(s.recover!=null){let l=this.getMirror(i);if(l!=null&&l>i&&l<this.to){i=l,t=this._maps[l].recover(s.recover);continue}}r|=s.delInfo,t=s.pos}return n?t:new kr(t,r,null)}}var Ii=Object.create(null);class ht{getMap(){return Bt.empty}merge(t){return null}static fromJSON(t,e){if(!e||!e.stepType)throw RangeError("Invalid input for Step.fromJSON");let n=Ii[e.stepType];if(!n)throw RangeError(`No step type ${e.stepType} defined`);return n.fromJSON(t,e)}static jsonID(t,e){if(t in Ii)throw RangeError("Duplicate use of step JSON ID "+t);return Ii[t]=e,e.prototype.jsonID=t,e}}class ct{constructor(t,e){this.doc=t,this.failed=e}static ok(t){return new ct(t,null)}static fail(t){return new ct(null,t)}static fromReplace(t,e,n,r){try{return ct.ok(t.replace(e,n,r))}catch(i){if(i instanceof ze)return ct.fail(i.message);throw i}}}function Ci(t,e,n){let r=[];for(let i=0;i<t.childCount;i++){let o=t.child(i);if(o.content.size)o=o.copy(Ci(o.content,e,o));if(o.isInline)o=e(o,n,i);r.push(o)}return k.fromArray(r)}class oe 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=t.resolve(this.from),r=n.node(n.sharedDepth(this.to)),i=new I(Ci(e.content,(o,s)=>{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;r<e.marks.length;r++)if(!e.marks[r].isInSet(n))return new be(this.pos,e.marks[r]);return new be(this.pos,this.mark)}}return new qe(this.pos,this.mark)}map(t){let e=t.mapResult(this.pos,1);return e.deletedAfter?null:new be(e.pos,this.mark)}toJSON(){return{stepType:"addNodeMark",pos:this.pos,mark:this.mark.toJSON()}}static fromJSON(t,e){if(typeof e.pos!="number")throw RangeError("Invalid input for AddNodeMarkStep.fromJSON");return new be(e.pos,t.markFromJSON(e.mark))}}ht.jsonID("addNodeMark",be);class qe 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.removeFromSet(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||!this.mark.isInSet(e.marks))return this;return new be(this.pos,this.mark)}map(t){let e=t.mapResult(this.pos,1);return e.deletedAfter?null:new qe(e.pos,this.mark)}toJSON(){return{stepType:"removeNodeMark",pos:this.pos,mark:this.mark.toJSON()}}static fromJSON(t,e){if(typeof e.pos!="number")throw RangeError("Invalid input for RemoveNodeMarkStep.fromJSON");return new qe(e.pos,t.markFromJSON(e.mark))}}ht.jsonID("removeNodeMark",qe);class ut extends ht{constructor(t,e,n,r=!1){super();this.from=t,this.to=e,this.slice=n,this.structure=r}apply(t){if(this.structure&&Si(t,this.from,this.to))return ct.fail("Structure replace would overwrite content");return ct.fromReplace(t,this.from,this.to,this.slice)}getMap(){return new Bt([this.from,this.to-this.from,this.slice.size])}invert(t){return new ut(this.from,this.from+this.slice.size,t.slice(this.from,this.to))}map(t){let e=t.mapResult(this.to,-1),n=this.from==this.to&&ut.MAP_BIAS<0?e:t.mapResult(this.from,1);if(n.deletedAcross&&e.deletedAcross)return null;return new ut(n.pos,Math.max(n.pos,e.pos),this.slice,this.structure)}merge(t){if(!(t instanceof ut)||t.structure||this.structure)return null;if(this.from+this.slice.size==t.from&&!this.slice.openEnd&&!t.slice.openStart){let e=this.slice.size+t.slice.size==0?I.empty:new I(this.slice.content.append(t.slice.content),this.slice.openStart,t.slice.openEnd);return new ut(this.from,this.to+(t.to-t.from),e,this.structure)}else if(t.to==this.from&&!this.slice.openStart&&!t.slice.openEnd){let e=this.slice.size+t.slice.size==0?I.empty:new I(t.slice.content.append(this.slice.content),t.slice.openStart,this.slice.openEnd);return new ut(t.from,this.to,e,this.structure)}else return null}toJSON(){let t={stepType:"replace",from:this.from,to:this.to};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")throw RangeError("Invalid input for ReplaceStep.fromJSON");return new ut(e.from,e.to,I.fromJSON(t,e.slice),!!e.structure)}}ut.MAP_BIAS=1;ht.jsonID("replace",ut);class ft extends ht{constructor(t,e,n,r,i,o,s=!1){super();this.from=t,this.to=e,this.gapFrom=n,this.gapTo=r,this.slice=i,this.insert=o,this.structure=s}apply(t){if(this.structure&&(Si(t,this.from,this.gapFrom)||Si(t,this.gapTo,this.to)))return ct.fail("Structure gap-replace would overwrite content");let e=t.slice(this.gapFrom,this.gapTo);if(e.openStart||e.openEnd)return ct.fail("Gap is not a flat range");let n=this.slice.insertAt(this.insert,e.content);if(!n)return ct.fail("Content does not fit in gap");return ct.fromReplace(t,this.from,this.to,n)}getMap(){return new Bt([this.from,this.gapFrom-this.from,this.insert,this.gapTo,this.to-this.gapTo,this.slice.size-this.insert])}invert(t){let e=this.gapTo-this.gapFrom;return new ft(this.from,this.from+this.slice.size+e,this.from+this.insert,this.from+this.insert+e,t.slice(this.from,this.to).removeBetween(this.gapFrom-this.from,this.gapTo-this.from),this.gapFrom-this.from,this.structure)}map(t){let e=t.mapResult(this.from,1),n=t.mapResult(this.to,-1),r=this.from==this.gapFrom?e.pos:t.map(this.gapFrom,-1),i=this.to==this.gapTo?n.pos:t.map(this.gapTo,1);if(e.deletedAcross&&n.deletedAcross||r<e.pos||i>n.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;f<c.length;f++){let h=c[f],p;for(let m=0;m<i.length;m++){let g=i[m];if(g.step==o-1&&h.eq(i[m].style))p=g}if(p)p.to=d,p.step=o;else i.push({style:h,from:Math.max(l,e),to:d,step:o})}}}),i.forEach((s)=>t.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<o.childCount;c++){let d=o.child(c),f=l+d.nodeSize,h=r.matchType(d.type);if(!h)s.push(new ut(l,f,I.empty));else{r=h;for(let p=0;p<d.marks.length;p++)if(!n.allowsMarkType(d.marks[p].type))t.step(new se(l,f,d.marks[p]));if(i&&d.isText&&n.whitespace!="pre"){let p,m=/\r?\n|\r/g,g;while(p=m.exec(d.text)){if(!g)g=new I(k.from(n.schema.text(" ",n.allowedMarks(d.marks))),0,0);s.push(new ut(l+p.index,l+p.index+p[0].length,g))}}}l=f}if(!r.validEnd){let c=r.fillBefore(k.empty,!0);t.replace(l,l,new I(c,0,0))}for(let c=s.length-1;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(r<t.depth&&s.canReplace(l,c,n))return r;if(r==0||s.type.spec.isolating||!sd(s,l,c))break;if(l)i=1;if(c<s.childCount)o=1}return null}function ld(t,e,n){let{$from:r,$to:i,depth:o}=e,s=r.before(o+1),l=i.after(o+1),c=s,d=l,f=k.empty,h=0;for(let g=o,b=!1;g>n;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)<i.end(g))b=!0,p=k.from(i.node(g).copy(p)),m++;else d++;t.step(new ft(c,d,s,l,new I(f.append(p),h,m),f.size-h,!0))}function cn(t,e,n=null,r=t){let i=ad(t,e),o=i&&cd(r,e);if(!o)return null;return i.map(Ns).concat({type:e,attrs:n}).concat(o.map(Ns))}function Ns(t){return{type:t,attrs:null}}function ad(t,e){let{parent:n,startIndex:r,endIndex:i}=t,o=n.contentMatchAt(r).findWrapping(e);if(!o)return null;let s=o.length?o[0]:e;return n.canReplaceWith(r,i,s)?o:null}function cd(t,e){let{parent:n,startIndex:r,endIndex:i}=t,o=n.child(r),s=e.contentMatch.findWrapping(o.type);if(!s)return null;let c=(s.length?s[s.length-1]:e).contentMatch;for(let d=r;c&&d<i;d++)c=c.matchType(n.child(d).type);if(!c||!c.validEnd)return null;return s}function dd(t,e,n){let r=k.empty;for(let s=n.length-1;s>=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(`
6-`))}})}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<e.childCount;i++){let o=e.child(i),s=o.type==r?t.type.schema.nodes.text:o.type;if(n=n.matchType(s),!n)return!1;if(!t.type.allowsMarks(o.marks))return!1}return n.validEnd}function gd(t,e){return!!(t&&e&&!t.isLeaf&&_d(t,e))}function md(t,e,n){let r=null,{linebreakReplacement:i}=t.doc.type.schema,o=t.doc.resolve(e-n),s=o.node().type;if(i&&s.inlineContent){let f=s.whitespace=="pre",h=!!s.contentMatch.matchType(i);if(f&&!h)r=!1;else if(!f&&h)r=!0}let l=t.steps.length;if(r===!1){let f=t.doc.resolve(e+n);Vs(t,f.node(),f.before(),l)}if(s.inlineContent)Oi(t,e+n-1,s,o.node().contentMatchAt(o.index()),r==null);let c=t.mapping.slice(l),d=c.map(e-n);if(t.step(new ut(d,c.map(e+n,-1),I.empty,!0)),r===!0){let f=t.doc.resolve(d);Fs(t,f.node(),f.before(),t.steps.length)}return t}function bd(t,e,n){let r=t.resolve(e);if(r.parent.canReplaceWith(r.index(),r.index(),n))return e;if(r.parentOffset==0)for(let i=r.depth-1;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<r.node(i).childCount)return null}return null}function vr(t,e,n){let r=t.resolve(e);if(!n.content.size)return e;let i=n.content;for(let o=0;o<n.openStart;o++)i=i.firstChild.content;for(let o=1;o<=(n.openStart==0&&n.size?2:1);o++)for(let s=r.depth;s>=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;n<t;n++){let i=e.firstChild;if(e.childCount>1)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;g<i.length;g++)this.openFrontierNode(i[g]);let o=this.unplaced,s=n?n.content:o.content,l=o.openStart-t,c=0,d=[],{match:f,type:h}=this.frontier[e];if(r){for(let g=0;g<r.childCount;g++)d.push(r.child(g));f=f.matchFragment(r)}let p=s.size+t-(o.content.size-o.openEnd);while(c<s.childCount){let g=s.child(c),b=f.matchType(g.type);if(!b)break;if(c++,c>1||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;g<p;g++){let y=b.lastChild;this.frontier.push({type:y.type,match:y.contentMatchAt(y.childCount)}),b=y.content}this.unplaced=!m?new I(Fn(o.content,t,c),o.openStart,o.openEnd):t==0?I.empty:new I(Fn(o.content,t-1,1),t-1,p<0?o.openEnd:t-1)}mustMoveInline(){if(!this.$to.parent.isTextblock)return-1;let t=this.frontier[this.depth],e;if(!t.type.isTextblock||!vi(this.$to,this.$to.depth,t.type,t.match,!1)||this.$to.depth==this.depth&&(e=this.findCloseLevel(this.$to))&&e.depth==this.depth)return-1;let{depth:n}=this.$to,r=this.$to.after(n);while(n>1&&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<t.depth&&t.end(e+1)==t.pos+(t.depth-(e+1)),o=vi(t,e,r,n,i);if(!o)continue;for(let s=e-1;s>=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;n<e;n++)t=t.firstChild.content;return t}function Us(t,e,n){if(e<=0)return t;let r=t.content;if(e>1)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;r<e.childCount;r++)if(!t.allowsMarks(e.child(r).marks))return!0;return!1}function yd(t){return t.spec.defining||t.spec.definingForContent}function Ts(t,e){for(let n=0;;n++){let r=e<0?t.firstChild:t.lastChild;if(!r||r.isAtom)return n;t=r.content}}function kd(t,e,n,r){if(!r.size)return t.deleteRange(e,n);let i=t.doc.resolve(e),o=t.doc.resolve(n);if(Ws(i,o,r))return t.step(new ut(e,n,r));let s=Js(i,o);if(s[s.length-1]==0)s.pop();let l=-(i.depth+1);s.unshift(l);for(let p=i.depth,m=i.pos-1;p>0;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<s.length;b++){let y=s[(b+c)%s.length],S=!0;if(y<0)S=!1,y=-y;let L=i.node(y-1),U=i.index(y-1);if(L.canReplaceWith(U,U,g.type,g.marks))return t.replace(i.before(y),S?o.after(y):n,new I($s(r.content,0,r.openStart,m),m,r.openEnd))}}let h=t.steps.length;for(let p=s.length-1;p>=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(e<n){let o=t.firstChild;t=t.replaceChild(0,o.copy($s(o.content,e+1,n,r,o)))}if(e>r){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;s<o.length;s++){let l=o[s],c=s==o.length-1;if(c&&l==0||r.node(l).type.contentMatch.validEnd)return t.delete(r.start(l),i.end(l));if(l>0&&(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(o<t.pos-(t.depth-i)||e.end(i)>e.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<this.mapping.maps.length;n++){let r=this.mapping.maps[n];if(n)t=r.map(t,1),e=r.map(e,-1);r.forEach((i,o,s,l)=>{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<t.length;e++)if(t[e].$from.pos!=t[e].$to.pos)return!1;return!0}content(){return this.$from.doc.slice(this.from,this.to,!0)}replace(t,e=I.empty){let n=e.content.lastChild,r=null;for(let s=0;s<e.openEnd;s++)r=n,n=n.lastChild;let i=t.steps.length,o=this.ranges;for(let s=0;s<o.length;s++){let{$from:l,$to:c}=o[s],d=t.mapping.slice(i);if(t.replaceRange(d.map(l.pos),d.map(c.pos),s?I.empty:e),s==0)Ks(t,i,(n?n.isInline:r&&r.isTextblock)?-1:1)}}replaceWith(t,e){let n=t.steps.length,r=this.ranges;for(let i=0;i<r.length;i++){let{$from:o,$to:s}=r[i],l=t.mapping.slice(n),c=l.map(o.pos),d=l.map(s.pos);if(i)t.deleteRange(c,d);else t.replaceRangeWith(c,d,e),Ks(t,n,e.isInline?-1:1)}}static findFrom(t,e,n=!1){let r=t.parent.inlineContent?new R(t):dn(t.node(0),t.parent,t.pos,t.index(),e,n);if(r)return r;for(let i=t.depth-1;i>=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.pos<e.pos!=r<0)t=e}return new R(t,e)}}F.jsonID("text",R);class Mr{constructor(t,e){this.anchor=t,this.head=e}map(t){return new Mr(t.map(this.anchor),t.map(this.head))}resolve(t){return R.between(t.resolve(this.anchor),t.resolve(this.head))}}class T extends F{constructor(t){let e=t.nodeAfter,n=t.node(0).resolve(t.pos+e.nodeSize);super(t,n);this.node=e}map(t,e){let{deleted:n,pos:r}=e.mapResult(this.anchor),i=t.resolve(r);if(n)return F.near(i);return new T(i)}content(){return new I(k.from(this.node),0,0)}eq(t){return t instanceof T&&t.anchor==this.anchor}toJSON(){return{type:"node",anchor:this.anchor}}getBookmark(){return new Ni(this.anchor)}static fromJSON(t,e){if(typeof e.anchor!="number")throw RangeError("Invalid input for NodeSelection.fromJSON");return new T(t.resolve(e.anchor))}static create(t,e){return new T(t.resolve(e))}static isSelectable(t){return!t.isText&&t.type.spec.selectable!==!1}}T.prototype.visible=!1;F.jsonID("node",T);class Ni{constructor(t){this.anchor=t}map(t){let{deleted:e,pos:n}=t.mapResult(this.anchor);return e?new Mr(n,n):new Ni(n)}resolve(t){let e=t.resolve(this.anchor),n=e.nodeAfter;if(n&&T.isSelectable(n))return new T(e);return F.near(e)}}class Ct extends F{constructor(t){super(t.resolve(0),t.resolve(t.content.size))}replace(t,e=I.empty){if(e==I.empty){t.delete(0,t.doc.content.size);let n=F.atStart(t.doc);if(!n.eq(t.selection))t.setSelection(n)}else super.replace(t,e)}toJSON(){return{type:"all"}}static fromJSON(t){return new Ct(t)}map(t){return new Ct(t)}eq(t){return t instanceof Ct}getBookmark(){return vd}}F.jsonID("all",Ct);var vd={map(){return this},resolve(t){return new Ct(t)}};function dn(t,e,n,r,i,o=!1){if(e.inlineContent)return R.create(t,n);for(let s=r-(i>0?0:1);i>0?s<e.childCount: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<e)return;let i=t.steps[r];if(!(i instanceof ut||i instanceof ft))return;let o=t.mapping.maps[r],s;o.forEach((l,c,d,f)=>{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.curSelectionFor<this.steps.length)this.curSelection=this.curSelection.map(this.doc,this.mapping.slice(this.curSelectionFor)),this.curSelectionFor=this.steps.length;return this.curSelection}setSelection(t){if(t.$from.doc!=this.doc)throw RangeError("Selection passed to setSelection must point at the current document");return this.curSelection=t,this.curSelectionFor=this.steps.length,this.updated=(this.updated|Ys)&~Cr,this.storedMarks=null,this}get selectionSet(){return(this.updated&Ys)>0}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;n<this.config.plugins.length;n++)if(n!=e){let r=this.config.plugins[n];if(r.spec.filterTransaction&&!r.spec.filterTransaction.call(r,t,this))return!1}return!0}applyTransaction(t){if(!this.filterTransaction(t))return{state:this,transactions:[]};let e=[t],n=this.applyInner(t),r=null;for(;;){let i=!1;for(let o=0;o<this.config.plugins.length;o++){let s=this.config.plugins[o];if(s.spec.appendTransaction){let l=r?r[o].n:0,c=r?r[o].state:this,d=l<e.length&&s.spec.appendTransaction.call(s,l?e.slice(l):e,c,n);if(d&&n.filterTransaction(d,o)){if(d.setMeta("appendedTransaction",t),!r){r=[];for(let f=0;f<this.config.plugins.length;f++)r.push(f<o?{state:n,n:e.length}:{state:this,n:0})}e.push(d),n=n.applyInner(d),i=!0}if(r)r[o]={state:n,n:e.length}}}if(!i)return{state:n,transactions:e}}}applyInner(t){if(!t.before.eq(this.doc))throw RangeError("Applying a mismatched transaction");let e=new ye(this.config),n=this.config.fields;for(let r=0;r<n.length;r++){let i=n[r];e[i.name]=i.apply(t,this[i.name],this,e)}return e}get tr(){return new Qs(this)}static create(t){let e=new Or(t.doc?t.doc.type.schema:t.schema,t.plugins),n=new ye(e);for(let r=0;r<e.fields.length;r++)n[e.fields[r].name]=e.fields[r].init(t,n);return n}reconfigure(t){let e=new Or(this.schema,t.plugins),n=e.fields,r=new ye(e);for(let i=0;i<n.length;i++){let o=n[i].name;r[o]=this.hasOwnProperty(o)?this[o]:n[i].init(t,r)}return r}toJSON(t){let e={doc:this.doc.toJSON(),selection:this.selection.toJSON()};if(this.storedMarks)e.storedMarks=this.storedMarks.map((n)=>n.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)&&e<t.nodeValue.length)return t;if(E(t)&&e<t.childNodes.length){if(t.contentEditable=="false")return null;t=t.childNodes[e],e=0}else if(t.parentNode&&!Xn(t))e=bt(t)+1,t=t.parentNode;else return null}}function Ed(t,e,n){for(let r=e==0,i=e==It(t);r||i;){if(t==n)return!0;let o=bt(t);if(t=t.parentNode,!t)return!1;r=r&&o==0,i=i&&o==It(t)}}function Xn(t){let e;for(let n=t;n;n=n.parentNode)if(e=n.pmViewDesc)break;return e&&e.node&&e.node.isBlock&&(e.dom==t||e.contentDOM==t)}var Rr=function(t){return t.focusNode&&Xe(t.focusNode,t.focusOffset,t.anchorNode,t.anchorOffset)};function Je(t,e){let n=document.createEvent("Event");return n.initEvent("keydown",!0,!0),n.keyCode=t,n.key=n.code=e,n}function Nd(t){let e=t.activeElement;while(e&&e.shadowRoot)e=e.shadowRoot.activeElement;return e}function Dd(t,e,n){if(t.caretPositionFromPoint)try{let r=t.caretPositionFromPoint(e,n);if(r)return{node:r.offsetNode,offset:Math.min(It(r.offsetNode),r.offset)}}catch(r){}if(t.caretRangeFromPoint){let r=t.caretRangeFromPoint(e,n);if(r)return{node:r.startContainer,offset:Math.min(It(r.startContainer),r.startOffset)}}}var ne=typeof navigator<"u"?navigator:null,nl=typeof document<"u"?document:null,Me=ne&&ne.userAgent||"",Bi=/Edge\/(\d+)/.exec(Me),Nl=/MSIE \d/.exec(Me),zi=/Trident\/(?:[7-9]|\d{2,})\..*rv:(\d+)/.exec(Me),Lt=!!(Nl||zi||Bi),ve=Nl?document.documentMode:zi?+zi[1]:Bi?+Bi[1]:0,zt=!Lt&&/gecko\/(\d+)/i.test(Me);zt&&+(/Firefox\/(\d+)/.exec(Me)||[0,0])[1];var Fi=!Lt&&/Chrome\/(\d+)/.exec(Me),wt=!!Fi,Dl=Fi?+Fi[1]:0,vt=!Lt&&!!ne&&/Apple Computer/.test(ne.vendor),mn=vt&&(/Mobile\/\w+/.test(Me)||!!ne&&ne.maxTouchPoints>2),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.top<c.top+le(r,"top"))f=-(c.top-e.top+le(i,"top"));else if(e.bottom>c.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.left<c.left+le(r,"left"))d=-(c.left-e.left+le(i,"left"));else if(e.right>c.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<Math.min(innerHeight,e.bottom);s+=5){let l=t.root.elementFromPoint(o,s);if(!l||l==t.dom||!t.dom.contains(l))continue;let c=l.getBoundingClientRect();if(c.top>=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<t.length;n++){let{dom:r,top:i,left:o}=t[n];if(r.scrollTop!=i+e)r.scrollTop=i+e;if(r.scrollLeft!=o)r.scrollLeft=o}}var hn=null;function zd(t){if(t.setActive)return t.setActive();if(hn)return t.focus(hn);let e=Rl(t);if(t.focus(hn==null?{get preventScroll(){return hn={preventScroll:!0},!0}}:void 0),!hn)hn=!1,Ll(e,0)}function Pl(t,e){let n,r=200000000,i,o=0,{top:s,top:l}=e,c,d;for(let f=t.firstChild,h=0;f;f=f.nextSibling,h++){let p;if(E(f))p=f.getClientRects();else if(pt(f))p=ae(f).getClientRects();else continue;for(let m=0;m<p.length;m++){let g=p[m];if(g.top<=s&&g.bottom>=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<e.left?e.left-g.right:0;if(b<r){if(n=f,r=b,i=b&&pt(n)?{left:g.right<e.left?g.right:g.left,top:e.top}:e,E(f)&&b)o=h+(e.left>=(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<n;o++){r.setEnd(t,o+1),r.setStart(t,o);let s=ke(r,1);if(s.top==s.bottom)continue;if(Hi(e,s)){i={node:t,offset:o+(e.left>=(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<t.getBoundingClientRect().left)return n;return t}function Wd(t,e,n){let{node:r,offset:i}=Pl(e,n),o=-1;if(E(r)&&!r.firstChild){let s=r.getBoundingClientRect();o=s.left!=s.right&&n.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<r.left||c.bottom<r.top)i=l.posAfter;s=!0}if(!l.contentDOM&&i<0&&!l.node.isText)return(l.node.isBlock?r.top<(c.top+c.bottom)/2:r.left<(c.left+c.right)/2)?l.posBefore:l.posAfter}o=l.dom.parentNode}return i>-1?i:t.docView.posFromDOM(e,n,-1)}function Bl(t,e,n){let r=t.childNodes.length;if(r&&n.top<n.bottom)for(let i=Math.max(0,Math.min(r-1,Math.floor(r*(e.top-n.top)/(n.bottom-n.top))-2)),o=i;;){let s=t.childNodes[o];if(E(s)){let l=s.getClientRects();for(let c=0;c<l.length;c++){let d=l[c];if(Hi(e,d))return Bl(s,e,d)}}if((o=(o+1)%r)==i)break}return t}function Ud(t,e){let n=t.dom.ownerDocument,r,i=0,o=Dd(n,e.left,e.top);if(o)({node:r,offset:i}=o);let s=(t.root.elementFromPoint?t.root:n).elementFromPoint(e.left,e.top),l;if(!s||!t.dom.contains(s)){let d=t.dom.getBoundingClientRect();if(!Hi(e,d))return null;if(s=Bl(t.dom,e,d),!s)return null}if(vt){for(let d=s;r&&d;d=gn(d))if(d.draggable)r=void 0}if(s=Vd(s,e),r){if(zt&&E(r)){if(i=Math.min(i,r.childNodes.length),i<r.childNodes.length){let f=r.childNodes[i],h;if(f.nodeName=="IMG"&&(h=f.getBoundingClientRect()).right<=e.left&&h.bottom>e.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<t.bottom||t.left<t.right}function ke(t,e){let n=t.getClientRects();if(n.length){let r=n[e<0?0:n.length-1];if(Vi(r))return r}return Array.prototype.find.call(n,Vi)||t.getBoundingClientRect()}var $d=/[\u0590-\u05f4\u0600-\u06ff\u0700-\u08ac]/;function zl(t,e,n){let{node:r,offset:i,atom:o}=t.docView.domFromPos(e,n<0?-1:1),s=Lr||zt;if(pt(r))if(s&&($d.test(r.nodeValue)||(n<0?!i:i==r.nodeValue.length))){let c=ke(ae(r,i,i),n);if(zt&&i&&/\s/.test(r.nodeValue[i-1])&&i<r.nodeValue.length){let d=ke(ae(r,i-1,i-1),-1);if(d.top==c.top){let f=ke(ae(r,i,i+1),-1);if(f.top!=c.top)return Un(f,f.left<d.left)}}return c}else{let c=i,d=i,f=n<0?1:-1;if(n<0&&!i)d++,f=-1;else if(n>=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<It(r)){let c=r.childNodes[i];if(E(c))return Di(c.getBoundingClientRect(),!0)}return Di(r.getBoundingClientRect(),n>=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<It(r)){let c=r.childNodes[i];while(c.pmViewDesc&&c.pmViewDesc.ignoreForCoords)c=c.nextSibling;let d=!c?null:pt(c)?ae(c,0,s?0:1):E(c)?c:null;if(d)return Un(ke(d,-1),!0)}return Un(ke(pt(r)?ae(r):r,-n),n>=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;d<c.length;d++){let f=c[d];if(f.bottom>f.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;e<this.children.length;e++)t+=this.children[e].size;return t}get border(){return 0}destroy(){if(this.parent=void 0,this.dom.pmViewDesc==this)this.dom.pmViewDesc=void 0;for(let t=0;t<this.children.length;t++)this.children[t].destroy()}posBeforeChild(t){for(let e=0,n=this.posAtStart;;e++){let r=this.children[e];if(r==t)return n;n+=r.size}}get posBefore(){return this.parent.posBeforeChild(this)}get posAtStart(){return this.parent?this.parent.posBeforeChild(this)+this.border:0}get posAfter(){return this.posBefore+this.size}get posAtEnd(){return this.posAtStart+this.size-2*this.border}localPosFromDOM(t,e,n){if(this.contentDOM&&Ge(this.contentDOM,t))if(n<0){let i,o;if(t==this.contentDOM)i=t.childNodes[e-1];else{while(t.parentNode!=this.contentDOM)t=t.parentNode;i=t.previousSibling}while(i&&!((o=i.pmViewDesc)&&o.parent==this))i=i.previousSibling;return i?this.posBeforeChild(o)+o.size:this.posAtStart}else{let i,o;if(t==this.contentDOM)i=t.childNodes[e];else{while(t.parentNode!=this.contentDOM)t=t.parentNode;i=t.nextSibling}while(i&&!((o=i.pmViewDesc)&&o.parent==this))i=i.nextSibling;return i?this.posBeforeChild(o):this.posAtEnd}let r;if(t==this.dom&&this.contentDOM)r=e>bt(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;e<this.children.length;e++){let r=this.children[e],i=n+r.size;if(n==t&&i!=n){while(!r.border&&r.children.length)for(let o=0;o<r.children.length;o++){let s=r.children[o];if(s.size){r=s;break}}return r}if(t<i)return r.descAt(t-n-r.border);n=i}}domFromPos(t,e){if(!this.contentDOM)return{node:this.dom,offset:0,atom:t+1};let n=0,r=0;for(let i=0;n<this.children.length;n++){let o=this.children[n],s=i+o.size;if(s>t){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<this.children.length?this.children[n]:null,!i||i.dom.parentNode==this.contentDOM)break;if(i&&o&&!i.border&&!i.domAtom)return i.domFromPos(0,e);return{node:this.contentDOM,offset:i?bt(i.dom):this.contentDOM.childNodes.length}}}parseRange(t,e,n=0){if(this.children.length==0)return{node:this.contentDOM,from:t,to:e,fromOffset:0,toOffset:this.contentDOM.childNodes.length};let r=-1,i=-1;for(let o=n,s=0;;s++){let l=this.children[s],c=o+l.size;if(r==-1&&t<=c){let d=o+l.border;if(t>=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;d<this.children.length;d++){let f=this.children[d];if(f.size&&f.dom.parentNode==this.contentDOM&&!f.emptyChildAt(-1)){i=bt(f.dom);break}e+=f.size}if(i==-1)i=this.contentDOM.childNodes.length;break}o=c}return{node:this.contentDOM,from:t,to:e,fromOffset:r,toOffset:i}}emptyChildAt(t){if(this.border||!this.contentDOM||!this.children.length)return!1;let e=this.children[t<0?0:this.children.length-1];return e.size==0||e.emptyChildAt(t)}domAfterPos(t){let{node:e,offset:n}=this.domFromPos(t,0);if(!E(e)||n==e.childNodes.length)throw RangeError("No node after pos "+t);return e.childNodes[n]}setSelection(t,e,n,r=!1){let i=Math.min(t,e),o=Math.max(t,e);for(let p=0,m=0;p<this.children.length;p++){let g=this.children[p],b=m+g.size;if(i>m&&o<b)return g.setSelection(t-m-g.border,e-m-g.border,n,r);m=b}let s=this.domFromPos(t,t?-1:1),l=e==t?s:this.domFromPos(e,e?-1:1),c=n.root.getSelection(),d=n.domSelectionRange(),f=!1;if((zt||vt)&&t==e){let{node:p,offset:m}=s;if(pt(p)){if(f=!!(m&&p.nodeValue[m-1]==`
7-`),f&&m==p.nodeValue.length)for(let g=p,b;g;g=g.parentNode){if(b=g.nextSibling){if(b.nodeName=="BR")s=l={node:b.parentNode,offset:bt(b)+1};break}let y=g.pmViewDesc;if(y&&y.node&&y.node.isBlock)break}}else{let g=p.childNodes[m-1];f=g&&(g.nodeName=="BR"||g.contentEditable=="false")}}if(zt&&d.focusNode&&d.focusNode!=l.node&&E(d.focusNode)){let p=d.focusNode.childNodes[d.focusOffset];if(p&&p.contentEditable=="false")r=!0}if(!(r||f&&vt)&&Xe(s.node,s.offset,d.anchorNode,d.anchorOffset)&&Xe(l.node,l.offset,d.focusNode,d.focusOffset))return;let h=!1;if((c.extend||t==e)&&!(f&&zt)){c.collapse(s.node,s.offset);try{if(t!=e)c.extend(l.node,l.offset);h=!0}catch(p){}}if(!h){if(t>e){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<this.children.length;r++){let i=this.children[r],o=n+i.size;if(n==o?t<=o&&e>=n:t<o&&e>n){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<n)e.dirty=n}}get domAtom(){return!1}get ignoreForCoords(){return!1}get ignoreForSelection(){return!1}isText(t){return!1}}class Ki extends bn{constructor(t,e,n,r){let i,o=e.type.toDOM;if(typeof o=="function")o=o(n,()=>{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.dirty<this.dirty)n.dirty=this.dirty;this.dirty=$t}}slice(t,e,n){let r=Se.create(this.parent,this.mark,!0,n),i=this.children,o=this.size;if(e<o)i=qi(i,e,o,n);if(t>0)i=qi(i,0,t,n);for(let s=0;s<i.length;s++)i[s].parent=r;return r.children=i,r}ignoreMutation(t){return this.spec.ignoreMutation?this.spec.ignoreMutation(t):super.ignoreMutation(t)}destroy(){if(this.spec.destroy)this.spec.destroy();super.destroy()}}class Ce extends bn{constructor(t,e,n,r,i,o,s){super(t,[],i,o);this.node=e,this.outerDeco=n,this.innerDeco=r,this.nodeDOM=s}static create(t,e,n,r,i,o){let s=i.nodeViews[e.type.name],l,c=s&&s(e,i,()=>{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<r+f.nodeSize&&(g=l.findIndexWithChild(i.node))>-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)||n<e||r>e+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<e.length;o++){let s=e[o],l=s.dom;if(l.parentNode==t){while(l!=r)r=cl(r),i=!0;r=r.nextSibling}else i=!0,t.insertBefore(l,r);if(s instanceof Se){let c=r?r.previousSibling:t.lastChild;ql(s.contentDOM,s.children,n),r=c?c.nextSibling:t.firstChild}}while(r)r=cl(r),i=!0;if(i&&n.trackWrites==t)n.trackWrites=null}var Jn=function(t){if(t)this.nodeName=t};Jn.prototype=Object.create(null);var He=[new Jn];function Wi(t,e,n){if(t.length==0)return He;let r=n?He[0]:new Jn,i=[r];for(let o=0;o<t.length;o++){let s=t[o].type.attrs;if(!s)continue;if(s.nodeName)i.push(r=new Jn(s.nodeName));for(let l in s){let c=s[l];if(c==null)continue;if(n&&i.length==1)i.push(r=new Jn(e.isInline?"span":"div"));if(l=="class")r.class=(r.class?r.class+" ":"")+c;else if(l=="style")r.style=(r.style?r.style+";":"")+c;else if(l!="nodeName")r[l]=c}}return i}function Ul(t,e,n,r){if(n==He&&r==He)return e;let i=e;for(let o=0;o<r.length;o++){let s=r[o],l=n[o];if(o){let c;if(l&&l.nodeName==s.nodeName&&i!=t&&(c=i.parentNode)&&c.nodeName.toLowerCase()==s.nodeName)i=c;else c=document.createElement(s.nodeName),c.pmIsDeco=!0,c.appendChild(i),l=He[0],i=c}Yd(i,l||He[0],s)}return i}function Yd(t,e,n){for(let r in e)if(r!="class"&&r!="style"&&r!="nodeName"&&!(r in n))t.removeAttribute(r);for(let r in n)if(r!="class"&&r!="style"&&r!="nodeName"&&n[r]!=e[r])t.setAttribute(r,n[r]);if(e.class!=n.class){let r=e.class?e.class.split(" ").filter(Boolean):[],i=n.class?n.class.split(" ").filter(Boolean):[];for(let o=0;o<r.length;o++)if(i.indexOf(r[o])==-1)t.classList.remove(r[o]);for(let o=0;o<i.length;o++)if(r.indexOf(i[o])==-1)t.classList.add(i[o]);if(t.classList.length==0)t.removeAttribute("class")}if(e.style!=n.style){if(e.style){let r=/\s*([\w\-\xa1-\uffff]+)\s*:(?:"(?:\\.|[^"])*"|'(?:\\.|[^'])*'|\(.*?\)|[^;])*/g,i;while(i=r.exec(e.style))t.style.removeProperty(i[1])}if(n.style)t.style.cssText+=n.style}}function $l(t,e,n){return Ul(t,t,He,Wi(e,n,!E(t)))}function Ar(t,e){if(t.length!=e.length)return!1;for(let n=0;n<t.length;n++)if(!t[n].type.eq(e[n].type))return!1;return!0}function cl(t){let e=t.nextSibling;return t.parentNode.removeChild(t),e}class Jl{constructor(t,e,n){this.lock=e,this.view=n,this.index=0,this.stack=[],this.changed=!1,this.top=t,this.preMatch=Xd(t.node.content,t)}destroyBetween(t,e){if(t==e)return;for(let n=t;n<e;n++)this.top.children[n].destroy();this.top.children.splice(t,e-t),this.changed=!0}destroyRest(){this.destroyBetween(this.index,this.top.children.length)}syncToMarks(t,e,n,r){let i=0,o=this.stack.length>>1,s=Math.min(o,t.length);while(i<s&&(i==o-1?this.top:this.stack[i+1<<1]).matchesMark(t[i])&&t[i].type.spec.spanning!==!1)i++;while(i<o)this.destroyRest(),this.top.dirty=$t,this.index=this.stack.pop(),this.top=this.stack.pop(),o--;while(o<t.length){this.stack.push(this.top,this.index+1);let l=-1,c=this.top.children.length;if(r<this.preMatch.index)c=Math.min(this.index+3,c);for(let d=this.index;d<c;d++){let f=this.top.children[d];if(f.matchesMark(t[o])&&!this.isLocked(f.dom)){l=d;break}}if(l<0&&this.index<this.top.children.length){let d=this.top.children[this.index];if(d instanceof Se&&d.dirty!=Yt&&d.mark.type==t[o].type&&d.spec.update&&!this.isLocked(d.dom)&&d.spec.update(t[o]))d.mark=t[o],l=this.index,this.changed=!0}if(l>-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);s<l;s++){let c=this.top.children[s];if(c.matchesNode(t,e,n)&&!this.preMatch.matched.has(c)){i=s;break}}if(i<0)return!1;return this.destroyBetween(this.index,i),this.index++,!0}updateNodeAt(t,e,n,r,i){let o=this.top.children[r];if(o.dirty==Yt&&o.dom==o.contentDOM)o.dirty=je;if(!o.update(t,e,n,i))return!1;return this.destroyBetween(this.index,r),this.index++,!0}findIndexWithChild(t){for(;;){let e=t.parentNode;if(!e)return-1;if(e==this.top.contentDOM){let n=t.pmViewDesc;if(n){for(let r=this.index;r<this.top.children.length;r++)if(this.top.children[r]==n)return r}return-1}t=e}}updateNextNode(t,e,n,r,i,o){for(let s=this.index;s<this.top.children.length;s++){let l=this.top.children[s];if(l instanceof Ce){let c=this.preMatch.matched.get(l);if(c!=null&&c!=i)return!1;let d=l.dom,f,h=this.isLocked(d)&&!(t.isText&&l.node&&l.node.isText&&l.nodeDOM.nodeValue==t.text&&l.dirty!=Yt&&Ar(e,l.outerDeco));if(!h&&l.update(t,e,n,r)){if(this.destroyBetween(this.index,s),l.dom!=d)this.changed=!0;return this.index++,!0}else if(!h&&(f=this.recreateWrapper(l,t,e,n,r,o))){if(this.destroyBetween(this.index,s),this.top.children[this.index]=f,f.contentDOM)f.dirty=je,f.updateChildren(r,o+1),f.dirty=$t;return this.changed=!0,this.index++,!0}break}}return!1}recreateWrapper(t,e,n,r,i,o){if(t.dirty||e.isAtom||!t.children.length||!t.node.content.eq(e.content)||!Ar(n,t.outerDeco)||!r.eq(t.innerDeco))return null;let s=Ce.create(this.top,e,n,r,i,o);if(s.contentDOM){s.children=t.children,t.children=[];for(let l of s.children)l.parent=s}return t.destroy(),s}addNode(t,e,n,r,i){let o=Ce.create(this.top,t,e,n,r,i);if(o.contentDOM)o.updateChildren(r,i+1);this.top.children.splice(this.index++,0,o),this.changed=!0}placeWidget(t,e,n){let r=this.index<this.top.children.length?this.top.children[this.index]:null;if(r&&r.matchesWidget(t)&&(t==r.widget||!r.widget.type.toDOM.parentNode))this.index++;else{let i=new Ki(this.top,t,e,n);this.top.children.splice(this.index++,0,i),this.changed=!0}}addTextblockHacks(){let t=this.top.children[this.index-1],e=this.top;while(t instanceof Se)e=t,t=e.children[e.children.length-1];if(!t||!(t instanceof Pr)||/\n$/.test(t.node.text)||this.view.requiresGeckoHackNode&&/\s$/.test(t.node.text)){if((vt||wt)&&t&&t.dom.contentEditable=="false")this.addHackNode("IMG",e);this.addHackNode("BR",this.top)}}addHackNode(t,e){if(e==this.top&&this.index<e.children.length&&e.children[this.index].matchesHack(t))this.index++;else{let n=document.createElement(t);if(t=="IMG")n.className="ProseMirror-separator",n.alt="";if(t=="BR")n.className="ProseMirror-trailingBreak";let r=new Yi(this.top,[],n,null);if(e!=this.top)e.children.push(r);else e.children.splice(this.index++,0,r);this.changed=!0}}isLocked(t){return this.lock&&(t==this.lock||E(t)&&t.contains(this.lock.parentNode))}}function Xd(t,e){let n=e,r=n.children.length,i=t.childCount,o=new Map,s=[];t:while(i>0){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;d<t.childCount;d++){let f=t.child(d);r(f,i,e.forChild(o,f),d),o+=f.nodeSize}return}let s=0,l=[],c=null;for(let d=0;;){let f,h;while(s<i.length&&i[s].to==o){let y=i[s++];if(y.widget)if(!f)f=y;else(h||(h=[f])).push(y)}if(f)if(h){h.sort(Gd);for(let y=0;y<h.length;y++)n(h[y],d,!!c)}else n(f,d,!!c);let p,m;if(c)m=-1,p=c,c=null;else if(d<t.childCount)m=d,p=t.child(d++);else break;for(let y=0;y<l.length;y++)if(l[y].to<=o)l.splice(y--,1);while(s<i.length&&i[s].from<=o&&i[s].to>o)l.push(i[s++]);let g=o+p.nodeSize;if(p.isText){let y=g;if(s<i.length&&i[s].from<y)y=i[s].from;for(let S=0;S<l.length;S++)if(l[S].to<y)y=l[S].to;if(y<g)c=p.cut(y-o),p=p.cut(0,y-o),g=y,m=-1}else while(s<i.length&&i[s].to<g)s++;let b=p.isInline&&!p.isLeaf?l.filter((y)=>!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<t.childCount&&o<=r;){let s=t.child(i++),l=o;if(o+=s.nodeSize,!s.isText)continue;let c=s.text;while(i<t.childCount){let d=t.child(i++);if(o+=d.nodeSize,!d.isText)break;c+=d.text}if(o>=n){if(o>=r&&c.slice(r-e.length-l,r-l)==e)return r-e.length;let d=l<r?c.lastIndexOf(e,r-l-1):-1;if(d>=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<t.length;s++){let c=t[s],d=l,f=l+=c.size;if(d>=n||f<=e)o.push(c);else{if(d<e)o.push(c.slice(0,e-d,r));if(i)o.push(i),i=void 0;if(f>n)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<n.rangeCount;m++){let g=n.getRangeAt(m);h=Math.min(h,t.docView.posFromDOM(g.startContainer,g.startOffset,1)),p=Math.max(p,t.docView.posFromDOM(g.endContainer,g.endOffset,-1))}if(h<0)return null;[c,s]=p==t.state.selection.anchor?[p,h]:[h,p],l=r.resolve(s)}else c=t.docView.posFromDOM(n.anchorNode,n.anchorOffset,1);if(c<0)return null}let f=r.resolve(c);if(!d){let h=e=="pointer"||t.state.selection.head<l.pos&&!o?1:-1;d=Gi(t,f,l,h)}return d}function jl(t){return t.editable?t.hasFocus():Kl(t)&&document.activeElement&&document.activeElement.contains(t.dom)}function ue(t,e=!1){let n=t.state.selection;if(Hl(t,n),!jl(t))return;let r=t.input.mouseDown;if(!e&&wt&&r){let i=t.domSelectionRange(),o=t.domObserver.currentSelection;if(i.anchorNode&&o.anchorNode&&Xe(i.anchorNode,i.anchorOffset,o.anchorNode,o.anchorOffset)&&r.delaySelUpdate()){t.domObserver.setCurSelection();return}}if(t.domObserver.disconnectSelection(),t.cursorWrapper)nu(t);else{let{anchor:i,head:o}=n,s,l;if(dl&&!(n instanceof R)){if(!n.$from.parent.inlineContent)s=ul(t,n.from);if(!n.empty&&!n.$from.parent.inlineContent)l=ul(t,n.to)}if(t.docView.setSelection(i,o,t,e),dl){if(s)fl(s);if(l)fl(l)}if(n.visible)t.dom.classList.remove("ProseMirror-hideselection");else if(t.dom.classList.add("ProseMirror-hideselection"),"onselectionchange"in document)eu(t)}t.domObserver.setCurSelection(),t.domObserver.connectSelection()}var dl=vt||wt&&Dl<63;function ul(t,e){let{node:n,offset:r}=t.docView.domFromPos(e,0),i=r<n.childNodes.length?n.childNodes[r]:null,o=r?n.childNodes[r-1]:null;if(vt&&i&&i.contentEditable=="false")return Ti(i);if((!i||i.contentEditable=="false")&&(!o||o.contentEditable=="false")){if(i)return Ti(i);else if(o)return Ti(o)}}function Ti(t){if(t.contentEditable="true",vt&&t.draggable)t.draggable=!1,t.wasDraggable=!0;return t}function fl(t){if(t.contentEditable="false",t.wasDraggable)t.draggable=!0,t.wasDraggable=null}function eu(t){let e=t.dom.ownerDocument;e.removeEventListener("selectionchange",t.input.hideSelectionGuard);let n=t.domSelectionRange(),{anchorNode:r,anchorOffset:i}=n;e.addEventListener("selectionchange",t.input.hideSelectionGuard=()=>{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)&&r<It(n)&&jn(n.childNodes[r],-1))s=!0;for(;;)if(r>0){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<i){if(!E(n))break;let l=n.childNodes[r];if(jn(l,1))o=n,s=++r;else break}else if(Yl(n))break;else{let l=n.nextSibling;while(l&&jn(l,1))o=l.parentNode,s=bt(l)+1,l=l.nextSibling;if(!l){if(n=n.parentNode,n==t.dom)break;r=i=0}else n=l,r=0,i=It(n)}if(o)$i(t,o,s)}function Yl(t){let e=t.pmViewDesc;return e&&e.node&&e.node.isBlock}function su(t,e){while(t&&e==t.childNodes.length&&!Xn(t))e=bt(t)+1,t=t.parentNode;while(t&&e<t.childNodes.length){let n=t.childNodes[e];if(pt(n))return n;if(E(n)&&n.contentEditable=="false")break;t=n,e=0}}function lu(t,e){while(t&&!e&&!Xn(t))e=bt(t),t=t.parentNode;while(t&&e){let n=t.childNodes[e-1];if(pt(n))return n;if(E(n)&&n.contentEditable=="false")break;t=n,e=t.childNodes.length}}function $i(t,e,n){if(!pt(e)){let s,l;if(l=su(e,n))e=l,n=0;else if(s=lu(e,n))e=s,n=s.nodeValue.length}let r=t.domSelection(),i=t.domSelectionRange();if(!r)return;if(Rr(i))r.collapse(e,n);else if(r.extend)r.collapse(i.anchorNode,i.anchorOffset),r.extend(e,n);t.domObserver.setCurSelection();let{state:o}=t;setTimeout(()=>{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&&l<o.bottom&&Math.abs(s.left-o.left)>1)return s.left<o.left?"ltr":"rtl"}if(e<n.end()){let s=t.coordsAtPos(e+1),l=(s.top+s.bottom)/2;if(l>o.top&&l<o.bottom&&Math.abs(s.left-o.left)>1)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,`
8-
9-`);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,`
10-`))),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.openStart&&!m.type.spec.isolating;h++,m=m.firstChild);for(let m=l.content.lastChild;p<l.openEnd&&!m.type.spec.isolating;p++,m=m.lastChild);l=yl(l,h,p)}return t.someProp("transformPasted",(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(i<t.length&&i<e.length&&t[i]==e[i]){let o=Ql(t,e,n,r.lastChild,i+1);if(o)return r.copy(r.content.replaceChild(r.childCount-1,o));if(r.contentMatchAt(r.childCount).matchType(i==t.length-1?n.type:t[i+1]))return r.copy(r.content.append(k.from(Gl(n,t,i+1))))}}function Zl(t,e){if(e==0)return t;let n=t.content.replaceChild(t.childCount-1,Zl(t.lastChild,e-1)),r=t.contentMatchAt(t.childCount).fillBefore(k.empty,!0);return t.copy(n.append(r))}function Ji(t,e,n,r,i,o){let s=e<0?t.firstChild:t.lastChild,l=s.content;if(t.childCount>1)o=0;if(i<r-1)l=Ji(l,e,n,r,i+1,o);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(e<t.openStart)t=new I(Ji(t.content,-1,e,t.openStart,0,t.openEnd),e,t.openEnd);if(n<t.openEnd)t=new I(Ji(t.content,1,n,t.openEnd,0,0),t.openStart,n);return t}var ta={thead:["table"],tbody:["table"],tfoot:["table"],caption:["table"],colgroup:["table"],col:["table","colgroup"],tr:["table","tbody"],td:["table","tbody","tr"],th:["table","tbody","tr"]};function ea(){return document.implementation.createHTMLDocument("title")}var $n=null;function hu(t){let e=window.trustedTypes;if(!e)return t;if(!$n){if($n=e.defaultPolicy)try{return $n.createHTML(t)}catch(n){}$n=e.createPolicy("ProseMirrorClipboard",{createHTML:(n)=>n})}return $n.createHTML(t)}function pu(t){let e=/^(\s*<meta [^>]*>)*/.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)=>"</"+s+">").reverse().join("");if(r.innerHTML=hu(t),o)for(let s=0;s<o.length;s++)r=r.querySelector(o[s])||r;for(let s=0;s<n.styleSheets.length;s++){let l=n.styleSheets[s];for(let c=0;c<l.rules.length;c++){let d=l.rules[c];if(d instanceof CSSStyleRule){let f=r.querySelectorAll(d.selectorText);for(let h=0;h<f.length;h++)f[h].style.cssText+=d.style.cssText}}}return r}function _u(t){let e=t.querySelectorAll(wt?"span:not([class]):not([style])":"span.Apple-converted-space");for(let n=0;n<e.length;n++){let r=e[n];if(r.childNodes.length==1&&r.textContent==" "&&r.parentNode)r.parentNode.replaceChild(t.ownerDocument.createTextNode(" "),r)}}function gu(t,e){if(!t.size)return t;let n=t.content.firstChild.type.schema,r;try{r=JSON.parse(e)}catch(l){return t}let{content:i,openStart:o,openEnd:s}=t;for(let l=r.length-2;l>=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<i.from?[i.to,n.from]:[i.from,n.to];Qn(this.view,R.create(r,o,s))}}Ot.touchstart=(t)=>{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<this.frag.childCount){let e=this.frag.child(this.index);if(this.off==t)return e;this.off+=e.nodeSize,this.index++}return null}}class Dr{constructor(t,e){this.toDOM=t,this.spec=e||Ke,this.side=this.spec.side||0}map(t,e,n,r){let{pos:i,deleted:o}=t.mapResult(e.from+r,this.side<0?-1:1);return o?null:new _t(i-n,i-n,this)}valid(){return!0}eq(t){return this==t||t instanceof Dr&&(this.spec.key&&this.spec.key==t.spec.key||this.toDOM==t.toDOM&&Yn(this.spec,t.spec))}destroy(t){if(this.spec.destroy)this.spec.destroy(t)}}class Oe{constructor(t,e){this.attrs=t,this.spec=e||Ke}map(t,e,n,r){let i=t.map(e.from+r,this.spec.inclusiveStart?-1:1)-n,o=t.map(e.to+r,this.spec.inclusiveEnd?1:-1)-n;return i>=o?null:new _t(i,o,this)}valid(t,e){return e.from<e.to}eq(t){return this==t||t instanceof Oe&&Yn(this.attrs,t.attrs)&&Yn(this.spec,t.spec)}static is(t){return t.type instanceof Oe}destroy(){}}class io{constructor(t,e){this.attrs=t,this.spec=e||Ke}map(t,e,n,r){let i=t.mapResult(e.from+r,1);if(i.deleted)return null;let o=t.mapResult(e.to+r,-1);if(o.deleted||o.pos<=i.pos)return null;return new _t(i.pos-n,o.pos-n,this)}valid(t,e,n){let r=n.nodeAt(e.from);return!!r&&!r.isText&&e.from+r.nodeSize==e.to}eq(t){return this==t||t instanceof io&&Yn(this.attrs,t.attrs)&&Yn(this.spec,t.spec)}destroy(){}}class _t{constructor(t,e,n){this.from=t,this.to=e,this.type=n}copy(t,e){return new _t(t,e,this.type)}eq(t,e=0){return this.type.eq(t.type)&&this.from+e==t.from&&this.to+e==t.to}map(t,e,n){return this.type.map(t,this,e,n)}static widget(t,e,n){return new _t(t,t,new Dr(e,n))}static inline(t,e,n,r){return new _t(t,e,new Oe(n,r))}static node(t,e,n,r){return new _t(t,e,new io(n,r))}get spec(){return this.type.spec}get inline(){return this.type instanceof Oe}get widget(){return this.type instanceof Dr}}var _n=[],Ke={};class G{constructor(t,e){this.local=t.length?t:_n,this.children=e.length?e:_n}static create(t,e){return e.length?Tr(e,t,0,Ke):xt}find(t,e,n){let r=[];return this.findInner(t==null?0:t,e==null?1e9:e,r,0,n),r}findInner(t,e,n,r,i){for(let o=0;o<this.local.length;o++){let s=this.local[o];if(s.from<=e&&s.to>=t&&(!i||i(s.spec)))n.push(s.copy(s.from+r,s.to+r))}for(let o=0;o<this.children.length;o+=3)if(this.children[o]<e&&this.children[o+1]>t){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<this.local.length;l++){let c=this.local[l].map(t,n,r);if(c&&c.type.valid(e,c,s))(o||(o=[])).push(c);else if(i.onRemove)i.onRemove(this.local[l].spec)}}if(this.children.length)return Bu(this.children,o||[],t,e,n,r,i);else return o?new G(o.sort(Ye),_n):xt}add(t,e){if(!e.length)return this;if(this==xt)return G.create(t,e);return this.addInner(t,e,0)}addInner(t,e,n){let r,i=0;t.forEach((s,l)=>{let c=l+n,d;if(!(d=ha(e,s,c)))return;if(!r)r=this.children.slice();while(i<r.length&&r[i]<l)i+=3;if(r[i]==l)r[i+2]=r[i+2].addInner(s,d,c+1);else r.splice(i,0,l,l+s.nodeSize,Tr(d,s,c+1,Ke));i+=3});let o=fa(i?pa(e):e,-n);if(o.length){let s=new Nr(t.content);for(let l=0;l<o.length;l++)if(!o[l].type.valid(t,o[l],s))o.splice(l--,1)}return new G(o.length?this.local.concat(o).sort(Ye):this.local,r||this.children)}remove(t){if(t.length==0||this==xt)return this;return this.removeInner(t,0)}removeInner(t,e){let n=this.children,r=this.local;for(let i=0;i<n.length;i+=3){let o,s=n[i]+e,l=n[i+1]+e;for(let d=0,f;d<t.length;d++)if(f=t[d]){if(f.from>s&&f.to<l)t[d]=null,(o||(o=[])).push(f)}if(!o)continue;if(n==this.children)n=this.children.slice();let c=n[i+2].removeInner(o,s+1);if(c!=xt)n[i+2]=c;else n.splice(i,3),i-=3}if(r.length){for(let i=0,o;i<t.length;i++)if(o=t[i]){for(let s=0;s<r.length;s++)if(r[s].eq(o,e)){if(r==this.local)r=this.local.slice();r.splice(s--,1)}}}if(n==this.children&&r==this.local)return this;return r.length||n.length?new G(r,n):xt}forChild(t,e){if(this==xt)return this;if(e.isLeaf)return G.empty;let n,r;for(let s=0;s<this.children.length;s+=3)if(this.children[s]>=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;s<this.local.length;s++){let l=this.local[s];if(l.from<o&&l.to>i&&l.type instanceof Oe){let c=Math.max(i,l.from)-i,d=Math.min(o,l.to)-i;if(c<d)(r||(r=[])).push(l.copy(c,d))}}if(r){let s=new G(r.sort(Ye),_n);return n?new Ie([s,n]):s}return n||xt}eq(t){if(this==t)return!0;if(!(t instanceof G)||this.local.length!=t.local.length||this.children.length!=t.children.length)return!1;for(let e=0;e<this.local.length;e++)if(!this.local[e].eq(t.local[e]))return!1;for(let e=0;e<this.children.length;e+=3)if(this.children[e]!=t.children[e]||this.children[e+1]!=t.children[e+1]||!this.children[e+2].eq(t.children[e+2]))return!1;return!0}locals(t){return oo(this.localsInner(t))}localsInner(t){if(this==xt)return _n;if(t.inlineContent||!this.local.some(Oe.is))return this.local;let e=[];for(let n=0;n<this.local.length;n++)if(!(this.local[n].type instanceof Oe))e.push(this.local[n]);return e}forEachSet(t){t(this)}}G.empty=new G([],[]);G.removeOverlap=oo;var xt=G.empty;class Ie{constructor(t){this.members=t}map(t,e){let n=this.members.map((r)=>r.map(t,e,Ke));return Ie.from(n)}forChild(t,e){if(e.isLeaf)return G.empty;let n=[];for(let r=0;r<this.members.length;r++){let i=this.members[r].forChild(t,e);if(i==xt)continue;if(i instanceof Ie)n=n.concat(i.members);else n.push(i)}return Ie.from(n)}eq(t){if(!(t instanceof Ie)||t.members.length!=this.members.length)return!1;for(let e=0;e<this.members.length;e++)if(!this.members[e].eq(t.members[e]))return!1;return!0}locals(t){let e,n=!0;for(let r=0;r<this.members.length;r++){let i=this.members[r].localsInner(t);if(!i.length)continue;if(!e)e=i;else{if(n)e=e.slice(),n=!1;for(let o=0;o<i.length;o++)e.push(i[o])}}return e?oo(n?e:e.sort(Ye)):_n}static from(t){switch(t.length){case 0:return xt;case 1:return t[0];default:return new Ie(t.every((e)=>e instanceof G)?t:t.reduce((e,n)=>e.concat(n instanceof G?n:n.members),[]))}}forEachSet(t){for(let e=0;e<this.members.length;e++)this.members[e].forEachSet(t)}}function Bu(t,e,n,r,i,o,s){let l=t.slice();for(let d=0,f=o;d<n.maps.length;d++){let h=0;n.maps[d].forEach((p,m,g,b)=>{let y=b-g-(m-p);for(let S=0;S<l.length;S+=3){let L=l[S+1];if(L<0||p>L+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<l.length;d+=3)if(l[d+1]<0){if(l[d+1]==-2){c=!0,l[d+1]=-1;continue}let f=n.map(t[d]+o),h=f-i;if(h<0||h>=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;h<l.length;h+=3)if(l[h+1]<0)l.splice(h,3),h-=3;for(let h=0,p=0;h<f.children.length;h+=3){let m=f.children[h];while(p<l.length&&l[p]<m)p+=3;l.splice(p,0,f.children[h],f.children[h+1],f.children[h+2])}}return new G(e.sort(Ye),l)}function fa(t,e){if(!e||!t.length)return t;let n=[];for(let r=0;r<t.length;r++){let i=t[r];n.push(new _t(i.from+e,i.to+e,i.type))}return n}function zu(t,e,n,r,i,o,s){function l(c,d){for(let f=0;f<c.local.length;f++){let h=c.local[f].map(r,i,d);if(h)n.push(h);else if(s.onRemove)s.onRemove(c.local[f].spec)}for(let f=0;f<c.children.length;f+=3)l(c.children[f+2],c.children[f]+d+1)}for(let c=0;c<t.length;c+=3)if(t[c+1]==-1)l(t[c+2],e[c]+o+1);return n}function ha(t,e,n){if(e.isLeaf)return null;let r=n+e.nodeSize,i=null;for(let o=0,s;o<t.length;o++)if((s=t[o])&&s.from>n&&s.to<r)(i||(i=[])).push(s),t[o]=null;return i}function pa(t){let e=[];for(let n=0;n<t.length;n++)if(t[n]!=null)e.push(t[n]);return e}function Tr(t,e,n,r){let i=[],o=!1;e.forEach((l,c)=>{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;c<s.length;c++)if(!s[c].type.valid(e,s[c],l)){if(r.onRemove)r.onRemove(s[c].spec);s.splice(c--,1)}}return s.length||i.length?new G(s,i):xt}function Ye(t,e){return t.from-e.from||t.to-e.to}function oo(t){let e=t;for(let n=0;n<e.length-1;n++){let r=e[n];if(r.from!=r.to)for(let i=n+1;i<e.length;i++){let o=e[i];if(o.from==r.from){if(o.to!=r.to){if(e==t)e=t.slice();e[i]=o.copy(o.from,r.to),kl(e,i+1,o.copy(r.to,o.to))}continue}else{if(o.from<r.to){if(e==t)e=t.slice();e[n]=r.copy(r.from,o.from),kl(e,i,r.copy(o.from,r.to))}break}}}return e}function kl(t,e,n){while(e<t.length&&Ye(n,t[e])>0)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;r<n.length;r++)this.queue.push(n[r]);if(Lt&&ve<=11&&n.some((r)=>r.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;e<t.length;e++)this.queue.push(t[e]);window.setTimeout(()=>this.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;d<e.length;d++){let f=this.registerMutation(e[d],l);if(f){if(i=i<0?f.from:Math.min(f.from,i),o=o<0?f.to:Math.max(f.to,o),f.typeOver)s=!0}}if(l.some((d)=>d.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)<Date.now()-300&&Rr(n)&&(c=Xi(t))&&c.eq(F.near(t.state.doc.resolve(0),1)))t.input.lastFocus=0,ue(t),this.currentSelection.set(n),t.scrollToSelection();else if(i>-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;d<t.addedNodes.length;d++){let f=t.addedNodes[d];if(e.push(f),pt(f))this.lastChangedTextNode=f}if(n.contentDOM&&n.contentDOM!=n.dom&&!n.contentDOM.contains(t.target))return{from:n.posBefore,to:n.posAfter};let{previousSibling:r,nextSibling:i}=t;if(Lt&&ve<=11&&t.addedNodes.length)for(let d=0;d<t.addedNodes.length;d++){let{previousSibling:f,nextSibling:h}=t.addedNodes[d];if(!f||Array.prototype.indexOf.call(t.addedNodes,f)<0)r=f;if(!h||Array.prototype.indexOf.call(t.addedNodes,h)<0)i=h}let o=r&&r.parentNode==t.target?bt(r)+1:0,s=n.localPosFromDOM(t.target,o,-1),l=i&&i.parentNode==t.target?bt(i):t.target.childNodes.length,c=n.localPosFromDOM(t.target,l,1);return{from:s,to:c}}else if(t.type=="attributes")return{from:n.posAtStart-n.border,to:n.posAtEnd+n.border};else return this.lastChangedTextNode=t.target,{from:n.posAtStart,to:n.posAtEnd,typeOver:t.target.nodeValue==t.oldValue}}}var xl=new WeakMap,Il=!1;function Wu(t){if(xl.has(t))return;if(xl.set(t,null),["normal","nowrap","pre-line"].indexOf(getComputedStyle(t.dom).whiteSpace)!==-1){if(t.requiresGeckoHackNode=zt,Il)return;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."),Il=!0}}function vl(t,e){let{startContainer:n,startOffset:r,endContainer:i,endOffset:o}=e,s=t.domAtPos(t.state.selection.anchor);if(Xe(s.node,s.offset,i,o))[n,r,i,o]=[i,o,n,r];return{anchorNode:n,anchorOffset:r,focusNode:i,focusOffset:o}}function qu(t,e){if(e.getComposedRanges){let i=e.getComposedRanges(t.root)[0];if(i)return vl(t,i)}let n;function r(i){i.preventDefault(),i.stopImmediatePropagation(),n=i.getTargetRanges()[0]}return t.dom.addEventListener("beforeinput",r,!0),document.execCommand("indent"),t.dom.removeEventListener("beforeinput",r,!0),n?vl(t,n):null}function Uu(t,e){for(let n=e.parentNode;n&&n!=t.dom;n=n.parentNode){let r=t.docView.nearestDesc(n,!0);if(r&&r.node.isBlock)return n}return null}function $u(t,e){var n;let{focusNode:r,focusOffset:i}=t.domSelectionRange();for(let o of e)if(((n=o.parentNode)===null||n===void 0?void 0:n.nodeName)=="TR"){let s=o.nextSibling;while(s&&(s.nodeName!="TD"&&s.nodeName!="TH"))s=s.nextSibling;if(s){let l=s;for(;;){let c=l.firstChild;if(!c||!E(c)||c.contentEditable=="false"||/^(BR|IMG)$/.test(c.nodeName))break;l=c}if(l.insertBefore(o,l.firstChild),r==o)t.domSelection().collapse(o,i)}else o.parentNode.removeChild(o)}}function Ju(t,e,n,r){let{node:i,fromOffset:o,toOffset:s,from:l,to:c}=t.docView.parseRange(e,n),d=t.domSelectionRange(),f,h=d.anchorNode;if(h&&Ge(t.dom,h)){if(f=[{node:h,offset:d.anchorOffset}],!Rr(d))f.push({node:d.focusNode,offset:d.focusOffset})}if(wt&&t.input.lastKeyCode===8)for(let S=s;S>o;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()-100<t.input.lastKeyCodeTime&&t.someProp("handleKeyDown",(P)=>P(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()-100<t.input.lastKeyCodeTime)p=t.state.selection.to,m="end";else p=t.state.selection.from,m="start";t.input.lastKeyCode=null;let g=Qu(h.content,d.doc.content,d.from,p,m);if(g)t.input.domChangeCount++;if((mn&&t.input.lastIOSEnter>Date.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.from<t.state.selection.to&&g.start==g.endB&&t.state.selection instanceof R){if(g.start>t.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&&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.lastChromeDelete<Date.now()-100)&&(Z.head==U||Z.head==Y.mapping.map(et)-1)||Lt&&Z.empty&&Z.head==U))Y.setSelection(Z)}if(o)Y.setMeta("composition",o);return Y.scrollIntoView()},Ft;if(L)if(b.pos==y.pos){if(Lt&&ve<=11&&b.parentOffset==0)t.domObserver.suppressSelectionUpdates(),setTimeout(()=>ue(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;f<r.length;f++)i=r[f].removeFromSet(i);for(let f=0;f<n.length;f++)o=n[f].removeFromSet(o);if(i.length==1&&o.length==0)l=i[0],s="add",c=(f)=>f.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;f<e.childCount;f++)d.push(c(e.child(f)));if(k.from(d).eq(t))return{mark:l,type:s}}function Xu(t,e,n,r,i){if(n-e<=i.pos-r.pos||Li(r,!0,!1)<i.pos)return!1;let o=t.resolve(e);if(!r.parent.inlineContent){let l=o.nodeAfter;return l!=null&&n==e+l.nodeSize}if(o.parentOffset<o.parent.content.size||!o.parent.isTextblock)return!1;let s=t.resolve(Li(o,!0,!0));if(!s.parent.isTextblock||s.pos>n||Li(s,!0,!1)<n)return!1;return r.parent.content.cut(r.parentOffset).eq(s.parent.content)}function Gu(t,e,n){let r=0,i=0;return t.nodesBetween(e,n,(o,s)=>{if(o.isTextblock&&s>=e&&s<n)r++;else if(o.isText?/\S/.test(o.text.slice(Math.max(0,e-s),Math.min(o.nodeSize,n-s))):o.isLeaf)i++}),i==0&&r==1}function Li(t,e,n){let r=t.depth,i=e?t.end():t.pos;while(r>0&&(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<o&&s<l){let f=r<=o&&r>=c?o-r:0;o-=f,d=o+(d-c),c=o}else if(d<o){let f=r<=o&&r>=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;e<this.directPlugins.length;e++){let n=this.directPlugins[e];if(n.spec.view)this.pluginViews.push(n.spec.view(this))}for(let e=0;e<this.state.plugins.length;e++){let n=this.state.plugins[e];if(n.spec.view)this.pluginViews.push(n.spec.view(this))}}else for(let e=0;e<this.pluginViews.length;e++){let n=this.pluginViews[e];if(n.update)n.update(this,t)}}updateDraggedNode(t,e){let n=t.node,r=-1;if(n.from<this.state.doc.content.size&&this.state.doc.nodeAt(n.from)==n.node)r=n.from;else{let i=n.from+(this.state.doc.content.size-e.doc.content.size);if((i>0&&i<this.state.doc.content.size&&this.state.doc.nodeAt(i))==n.node)r=i}this.dragging=new ro(t.slice,t.move,r<0?void 0:T.create(this.state.doc,r))}someProp(t,e){let n=this._props&&this._props[t],r;if(n!=null&&(r=e?e(n):n))return r;for(let o=0;o<this.directPlugins.length;o++){let s=this.directPlugins[o].props[t];if(s!=null&&(r=e?e(s):s))return r}let i=this.state.plugins;if(i)for(let o=0;o<i.length;o++){let s=i[o].props[t];if(s!=null&&(r=e?e(s):s))return r}}hasFocus(){if(Lt){let t=this.root.activeElement;if(t==this.dom)return!0;if(!t||!this.dom.contains(t))return!1;while(t&&this.dom!=t&&this.dom.contains(t)){if(t.contentEditable=="false")return!1;t=t.parentElement}return!0}return this.root.activeElement==this.dom}focus(){if(this.domObserver.stop(),this.editable)zd(this.dom);ue(this),this.domObserver.start()}get root(){let t=this._root;if(t==null){for(let e=this.dom.parentNode;e;e=e.parentNode)if(e.nodeType==9||e.nodeType==11&&e.host){if(!e.getSelection)Object.getPrototypeOf(e).getSelection=()=>e.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<t.length;n++)if(t[n]!==e[n])return!1;break}case Set:{if(t.size!==e.size)return!1;for(let n of t)if(!e.has(n))return!1;break}case Map:{if(t.size!==e.size)return!1;for(let n of t.keys())if(!e.has(n)||!wn(t.get(n),e.get(n)))return!1;break}case void 0:case Object:if(lo(t)!==lo(e))return!1;for(let n in t)if(!ma(t,n)||!wn(t[n],e[n]))return!1;break;case Array:if(t.length!==e.length)return!1;for(let n=0;n<t.length;n++)if(!wn(t[n],e[n]))return!1;break;default:return!1}return!0};var of=/[\uD800-\uDBFF]/,sf=/[\uDC00-\uDFFF]/,lf=(t,e)=>{let n=0,r=0;while(n<t.length&&n<e.length&&t[n]===e[n])n++;if(n>0&&of.test(t[n-1]))n--;while(r+n<t.length&&r+n<e.length&&t[t.length-r-1]===e[e.length-r-1])r++;if(r>0&&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(r<t.length&&o<e.length){let l=t[r],c=e[o];if(l.insert==null){r+=1;continue}let d=Math.min(l.insert.length-i,c.insert.length-s);if(d>0){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<n.length;i++){let o=n[i],s=t[o],l=e[o];r=s===l||typeof s==="object"&&s!==null&&typeof l==="object"&&l!==null&&po(s,l)}return r}function Br(t,e){return!Array.isArray(e)&&t.get("nodeName")===e.type.name}function zr(t,e){if(t===e)return!0;if(!Array.isArray(t)&&!Array.isArray(e)&&e)return t?.eq(e)??!1;if(Array.isArray(t)&&Array.isArray(e)){if(t.length!==e.length)return!1;for(let n=0;n<t.length;n++)if(!e[n].eq(t[n]))return!1;return!0}return!1}function Wr(t){let e=[],n=null;return t.content.forEach((r,i,o)=>{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(;c<l;c++){let h=r.get(c),p=o[c];if(zr(h!=null&&ie(h)?n.get(h.id):void 0,p))f=!0;else if(h==null||p==null||!nr(h,p))break}for(;c+d<l;d++){let h=r.get(i-d-1),p=o[s-d-1];if(zr(h!=null&&ie(h)?n.get(h.id):void 0,p))f=!0;else if(h==null||p==null||!nr(h,p))break}return{factor:c+d,foundMappedChild:f}}function pf(t,e,n,r){let i=t.insertContainer(e??t.length,new St).getAttached();i.set("nodeName",n.type.name);let o=qr(i);for(let[l,c]of Object.entries(n.attrs))if(c!==null)o.set(l,c);let s=or(i);return Wr(n).forEach((l,c)=>ao(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(;c<l;c++){let h=r.get(c),p=o[c];if(h==null||p==null)break;if(ie(h)&&n.get(h.id)!==p)if(zr(n.get(h.id),p)||nr(h,p)){if(!Array.isArray(p))tr(h,p,n)}else break}for(;d+c<l;d++){let h=r.get(i-d-1),p=o[s-d-1];if(h==null||p==null)break;if(ie(h)&&n.get(h.id)!==p)if(zr(n.get(h.id),p)||nr(h,p)){if(!Array.isArray(p))tr(h,p,n)}else break}while(i-c-d>0&&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.factor<L.factor)b=!1;else y=!1}if(b)tr(h,p,n),c+=1;else if(y)tr(m,g,n),d+=1;else{let S=r.get(c);if(ie(S))n.delete(S.id);r.delete(c,1),ao(r,c,p,n),c+=1}}}let f=i-c-d;if(i===1&&s===0&&r.get(0)instanceof Rt){let h=r.get(0);n.delete(h.id),h.delete(0,h.length)}else if(f>0)r.toArray().slice(c,c+f).filter(ie).forEach((h)=>n.delete(h.id)),r.delete(c,f);if(c+d<s)o.slice(c,s-d).forEach((h,p)=>ao(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<c.length){let h=c.get(f);if(f+=1,h instanceof Rt)return h.getCursor(d);else{if(d==0){if(f<c.length)d+=1}d-=1}}}function Vr(t,e,n){let r=t.containerId(),i=-1,o,s,l;if(r.endsWith("List")){let c=e.getContainerById(r);if(!c)return[1,void 0];let d=c.parent();if(!d)return[1,void 0];o=d.id,s=d.parent()?.parent(),i=0}else{let c=e.getText(r),d=e.getCursorPos(t);if(!d)return[1,void 0];l=d.update,i+=d.offset,o=c.id,s=c.parent()?.parent()}while(s!=null){let c=s.get(fo);if(c instanceof ee){let d=c.toArray();for(let f of d){if(f.id===o)break;let h=n.get(f.id);if(Array.isArray(h))h.forEach((p)=>{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<e.parent.childCount)e=new on(e.$from,s.resolve(e.$to.end(e.depth)),e.depth);i=!0}let l=cn(o,n,r,e);if(!l)return!1;if(t)Jf(t,e,l,i,n);return!0}function Jf(t,e,n,r,i){let o=k.empty;for(let f=n.length-1;f>=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<n.length;f++)if(n[f].type==i)s=f+1;let l=n.length-s,c=e.start+n.length-(r?2:0),d=e.parent;for(let{startIndex:f,endIndex:h}=e,p=!0;f<h;f++,p=!1){if(!p&&we(t.doc,c,l))t.split(c,l),c+=2*l;c+=d.child(f).nodeSize}return t}function La(t,e){return function(n,r){let{$from:i,$to:o,node:s}=n.selection;if(s&&s.isBlock||i.depth<2||!i.sameParent(o))return!1;let l=i.node(-1);if(l.type!=t)return!1;if(i.parent.content.size==0&&i.node(-1).childCount==i.indexAfter(-1)){if(i.depth==3||i.node(-3).type!=t||i.index(-2)!=i.node(-2).childCount-1)return!1;if(r){let h=k.empty,p=i.index(-1)?1:i.index(-2)?2:3;for(let S=i.depth-p;S>=i.depth-3;S--)h=k.from(i.node(S).copy(h));let m=i.indexAfter(-1)<i.node(-2).childCount?1:i.indexAfter(-2)<i.node(-3).childCount?2:3;h=h.append(k.from(t.createAndFill()));let g=i.before(i.depth-(p-1)),b=n.tr.replace(g,i.after(-m),new I(h,4-p,0)),y=-1;if(b.doc.nodesBetween(g,b.doc.content.size,(S,L)=>{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(o<s)i.step(new ft(o-1,s,o,s,new I(k.from(n.create(null,r.parent.copy())),1,0),1,!0)),r=new on(i.doc.resolve(r.$from.pos),i.doc.resolve(s),r.depth);let l=Ue(r);if(l==null)return!1;i.lift(r,l);let c=i.doc.resolve(i.mapping.map(o,-1)-1);if($e(i.doc,c.pos)&&c.nodeBefore.type==c.nodeAfter.type)i.join(c.pos);return e(i.scrollIntoView()),!0}function Hf(t,e,n){let r=t.tr,i=n.parent;for(let m=n.end,g=n.endIndex-1,b=n.startIndex;g>b;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<e.length-1;l++){let c=e[l];if(/^(cmd|meta|m)$/i.test(c))s=!0;else if(/^a(lt)?$/i.test(c))r=!0;else if(/^(c|ctrl|control)$/i.test(c))i=!0;else if(/^s(hift)?$/i.test(c))o=!0;else if(/^mod$/i.test(c))if(Xf)s=!0;else i=!0;else throw Error("Unrecognized modifier name: "+c)}if(r)n="Alt-"+n;if(i)n="Ctrl-"+n;if(s)n="Meta-"+n;if(o)n="Shift-"+n;return n}function Zf(t){let e=Object.create(null);for(let n in t)e[Qf(n)]=t[n];return e}function mo(t,e,n=!0){if(e.altKey)t="Alt-"+t;if(e.ctrlKey)t="Ctrl-"+t;if(e.metaKey)t="Meta-"+t;if(n&&e.shiftKey)t="Shift-"+t;return t}function yn(t){return new st({props:{handleKeyDown:bo(t)}})}function bo(t){let e=Zf(t);return function(n,r){let i=Ba(r),o,s=e[mo(i,r)];if(s&&s(n.state,n.dispatch,n))return!0;if(i.length==1&&i!=" "){if(r.shiftKey){let l=e[mo(i,r,!1)];if(l&&l(n.state,n.dispatch,n))return!0}if((r.altKey||r.metaKey||r.ctrlKey)&&!(Gf&&r.ctrlKey&&r.altKey)&&(o=fe[r.keyCode])&&o!=i){let l=e[mo(o,r)];if(l&&l(n.state,n.dispatch,n))return!0}}return!1}}var Fa=(t,e)=>{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.size<l.to-l.from){if(e){let c=t.tr.step(l);c.setSelection(kn(o,"end")?F.findFrom(c.doc.resolve(c.mapping.map(i.pos,-1)),-1):T.create(c.doc,i.pos-o.nodeSize)),e(c.scrollIntoView())}return!0}if(s==1||r.node(s-1).childCount>1)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<n.parent.content.size))return null;return n}var ih=(t,e,n)=>{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<s.to-s.from){if(e){let l=t.tr.step(s);l.setSelection(kn(o,"start")?F.findFrom(l.doc.resolve(l.mapping.map(i.pos)),1):T.create(l.doc,l.mapping.map(i.pos))),e(l.scrollIntoView())}return!0}}if(o.isAtom&&i.depth==r.depth-1){if(e)e(t.tr.delete(i.pos,i.pos+o.nodeSize).scrollIntoView());return!0}return!1},oh=(t,e,n)=>{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<r.parent.content.size)return!1;o=Wa(r)}let s=o&&o.nodeAfter;if(!s||!T.isSelectable(s))return!1;if(e)e(t.tr.setSelection(T.create(t.doc,o.pos)).scrollIntoView());return!0};function Wa(t){if(!t.parent.type.spec.isolating)for(let e=t.depth-1;e>=0;e--){let n=t.node(e);if(t.index(e)+1<n.childCount)return t.doc.resolve(t.after(e+1));if(n.type.spec.isolating)break}return null}var qa=(t,e)=>{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(`
11-`).scrollIntoView());return!0};function yo(t){for(let e=0;e<t.edgeCount;e++){let{type:n}=t.edge(e);if(n.isTextblock&&!n.hasRequiredAttrs())return n}return null}var lh=(t,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()<i.parent.childCount?r:i).pos,l=t.tr.insert(s,o.createAndFill());l.setSelection(R.create(l.doc,s+1)),e(l.scrollIntoView())}return!0},ch=(t,e)=>{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<n.selection.ranges.length&&!i;o++){let{$from:{pos:s},$to:{pos:l}}=n.selection.ranges[o];n.doc.nodesBetween(s,l,(c,d)=>{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<n.selection.ranges.length;s++){let{$from:{pos:l},$to:{pos:c}}=n.selection.ranges[s];o.setBlockType(l,c,t,e)}r(o.scrollIntoView())}return!0}}function gh(t,e,n,r){for(let i=0;i<e.length;i++){let{$from:o,$to:s}=e[i],l=o.depth==0?t.inlineContent&&t.type.allowsMarkType(n):!1;if(t.nodesBetween(o.pos,s.pos,(c,d)=>{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<t.length;n++){let{$from:r,$to:i}=t[n];if(r.doc.nodesBetween(r.pos,i.pos,(o,s)=>{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.pos<i.pos)e.push(new qn(r,i))}return e}function pe(t,e=null,n){let r=(n&&n.removeWhenPresent)!==!1,i=(n&&n.enterInlineAtoms)!==!1,o=!(n&&n.includeWhitespace);return function(s,l){let{empty:c,$cursor:d,ranges:f}=s.selection;if(c&&!d||!gh(s.doc,f,t,i))return!1;if(l)if(d)if(t.isInSet(s.storedMarks||d.marks()))l(s.tr.removeStoredMark(t));else l(s.tr.addStoredMark(t.create(e)));else{let h,p=s.tr;if(!i)f=mh(f);if(r)h=!f.some((m)=>s.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;m<f.length;m++){let{$from:g,$to:b}=f[m];if(!h)p.removeMark(g.pos,b.pos,t);else{let y=g.pos,S=b.pos,L=g.nodeAfter,U=b.nodeBefore,et=o&&L&&L.isText?/^\s*/.exec(L.text)[0].length:0,at=o&&U&&U.isText?/\s*$/.exec(U.text)[0].length:0;if(y+et<S)y+=et,S-=at;p.addMark(y,S,t.create(e))}}l(p.scrollIntoView())}return!0}}function xo(...t){return function(e,n,r){for(let i=0;i<t.length;i++)if(t[i](e,n,r))return!0;return!1}}var wo=xo(Fa,eh,nh),za=xo(Fa,ih,oh),he={Enter:xo(sh,ah,ch,uh),"Mod-Enter":lh,Backspace:wo,"Mod-Backspace":wo,"Shift-Backspace":wo,Delete:za,"Mod-Delete":za,"Mod-a":fh},ja={"Ctrl-h":he.Backspace,"Alt-Backspace":he["Mod-Backspace"],"Ctrl-d":he.Delete,"Ctrl-Alt-Backspace":he["Mod-Delete"],"Alt-Delete":he["Mod-Delete"],"Alt-d":he["Mod-Delete"],"Ctrl-a":ph,"Ctrl-e":_h};for(let t in he)ja[t]=he[t];var bh=typeof navigator<"u"?/Mac|iP(hone|[oa]d)/.test(navigator.platform):typeof os<"u"&&os.platform?os.platform()=="darwin":!1,Ha=bh?ja:he;var wh={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"},yh={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"},kh=(document.documentElement.lang||"en").toLowerCase().startsWith("tr")?"tr":"en";function C(t,e){let n=kh==="tr"?yh[t]:wh[t];return e?n.replace(/\{(\w+)\}/g,(r,i)=>e[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;d<i.length;d++){let f=i[d];if(!f.inCodeMark&&l.marks().some((g)=>g.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<r.length)continue;let p=e-(h[0].length-r.length);if(!f.inCodeMark){let g=!1;if(s.doc.nodesBetween(p,l.pos,(b)=>{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<n.length;r++){let i=n[r],o;if(i.spec.isInputRules&&(o=i.getState(t))){if(e){let s=t.tr,l=o.transform;for(let c=l.steps.length-1;c>=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&&lt.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)<s.childCount:t.index(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&&lt.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,`
12-`),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,`
13-`),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:'<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"/>'};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=`<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">${p.icon}</svg>`,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();
14-
15-//# debugId=0E2F6C17ACB8E4C864756E2164756E21
16-//# sourceMappingURL=editor.js.map
assets/editor.js.mapdeleted+0 -37
@@ -1,37 +0,0 @@
1-{
2- "version": 3,
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"],
4- "sourcesContent": [
5- "\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",
6- "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<any>} 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<PeerID, Change[]>}\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<string>[]);\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<string, ContainerID>}\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<any>}\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<string, ContainerNode>}\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<string, Value>}\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<string>[]} 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<string>[]}\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<string>[]}\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<string>[]}\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<any>}\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<any>}\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<PeerID, number> | 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<PeerID, number>}\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<PeerID, number>} 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",
7- "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",
8- "// ::- 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<Object, OrderedMap>) → 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<Object, OrderedMap>) → 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<Object, OrderedMap>) → 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<Object, OrderedMap>) → 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",
9- "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",
10- "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 <p(\"foo\"), p(\"bar\")>, 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",
11- "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",
12- "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 <input> 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 <input> 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 <br contenteditable=false>\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// \"<td>..</td>\"` 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*<meta [^>]*>)*/.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 => \"</\" + 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",
13- "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<T>} a\n * @param {T} b\n * @return {boolean}\n */\nexport const equals = (a, b) => a === b || !!a?.[EqualityTraitSymbol]?.(b) || false\n",
14- "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<string,any>} 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<string,any>} obj\n */\nexport const keys = Object.keys\n\n/**\n * @template V\n * @param {{[key:string]: V}} obj\n * @return {Array<V>}\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<string,any>} obj\n * @param {function(any,string):R} f\n * @return {Array<R>}\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<string,any>} obj\n * @return {number}\n */\nexport const length = obj => keys(obj).length\n\n/**\n * @param {Object<string,any>} 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<string,any>} a\n * @param {Object<string,any>} 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<T>}\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",
15- "/**\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<function>} fs\n * @param {Array<any>} 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<T>|object} a\n * @param {Array<T>|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<T>} */ (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<OPTS>} 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<TYPE>}\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<TYPE>}\n **/\n n => n && n.constructor === T\n",
16- "/**\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<any>} 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<string>} 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<T>} a The old version of the array\n * @param {Array<T>} b The updated version of the array\n * @param {function(T, T):boolean} [compare]\n * @return {SimpleDiff<Array<T>>} 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",
17- "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",
18- "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 `<p>` element.\n */\n paragraph: {\n content: \"inline*\",\n group: \"block\",\n parseDOM: [{ tag: \"p\" }],\n toDOM() { return pDOM; }\n },\n /**\n A blockquote (`<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 (`<hr>`).\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 `<h1>` to\n `<h6>` 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 `<pre>` element with a\n `<code>` 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 (`<img>`) 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 `<br>`.\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 `<a>`\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 `<em>` element. Has parse rules\n that also match `<i>` 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 `<strong>`, parse rules also match\n `<b>` 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 `<b>`\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 `<code>` 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",
19- "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 `<ol>`\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 `<ul>`.\n*/\nconst bulletList = {\n parseDOM: [{ tag: \"ul\" }],\n toDOM() { return ulDOM; }\n};\n/**\nA list item (`<li>`) spec.\n*/\nconst listItem = {\n parseDOM: [{ tag: \"li\" }],\n toDOM() { return liDOM; },\n defining: true\n};\nfunction add(obj, props) {\n let copy = {};\n for (let prop in obj)\n copy[prop] = obj[prop];\n for (let prop in props)\n copy[prop] = props[prop];\n return copy;\n}\n/**\nConvenience function for adding list-related node types to a map\nspecifying the nodes for a schema. Adds\n[`orderedList`](https://prosemirror.net/docs/ref/#schema-list.orderedList) as `\"ordered_list\"`,\n[`bulletList`](https://prosemirror.net/docs/ref/#schema-list.bulletList) as `\"bullet_list\"`, and\n[`listItem`](https://prosemirror.net/docs/ref/#schema-list.listItem) as `\"list_item\"`.\n\n`itemContent` determines the content expression for the list items.\nIf you want the commands defined in this module to apply to your\nlist structure, it should have a shape like `\"paragraph block*\"` or\n`\"paragraph (ordered_list | bullet_list)*\"`. `listGroup` can be\ngiven to assign a group name to the list node types, for example\n`\"block\"`.\n*/\nfunction addListNodes(nodes, itemContent, listGroup) {\n return nodes.append({\n ordered_list: add(orderedList, { content: \"list_item+\", group: listGroup }),\n bullet_list: add(bulletList, { content: \"list_item+\", group: listGroup }),\n list_item: add(listItem, { content: itemContent })\n });\n}\n/**\nReturns a command function that wraps the selection in a list with\nthe given type an attributes. If `dispatch` is null, only return a\nvalue to indicate whether this is possible, but don't actually\nperform the change.\n*/\nfunction wrapInList(listType, attrs = null) {\n return function (state, dispatch) {\n let { $from, $to } = state.selection;\n let range = $from.blockRange($to);\n if (!range)\n return false;\n let tr = dispatch ? state.tr : null;\n if (!wrapRangeInList(tr, range, listType, attrs))\n return false;\n if (dispatch)\n dispatch(tr.scrollIntoView());\n return true;\n };\n}\n/**\nTry to wrap the given node range in a list of the given type.\nReturn `true` when this is possible, `false` otherwise. When `tr`\nis non-null, the wrapping is added to that transaction. When it is\n`null`, the function only queries whether the wrapping is\npossible.\n*/\nfunction wrapRangeInList(tr, range, listType, attrs = null) {\n let doJoin = false, outerRange = range, doc = range.$from.doc;\n // This is at the top of an existing list item\n if (range.depth >= 2 && range.$from.node(range.depth - 1).type.compatibleContent(listType) && range.startIndex == 0) {\n // Don't do anything if this is the top of the list\n if (range.$from.index(range.depth - 1) == 0)\n return false;\n let $insert = doc.resolve(range.start - 2);\n outerRange = new NodeRange($insert, $insert, range.depth);\n if (range.endIndex < range.parent.childCount)\n range = new NodeRange(range.$from, doc.resolve(range.$to.end(range.depth)), range.depth);\n doJoin = true;\n }\n let wrap = findWrapping(outerRange, listType, attrs, range);\n if (!wrap)\n return false;\n if (tr)\n doWrapInList(tr, range, wrap, doJoin, listType);\n return true;\n}\nfunction doWrapInList(tr, range, wrappers, joinBefore, listType) {\n let content = Fragment.empty;\n for (let i = wrappers.length - 1; i >= 0; i--)\n content = Fragment.from(wrappers[i].type.create(wrappers[i].attrs, content));\n tr.step(new ReplaceAroundStep(range.start - (joinBefore ? 2 : 0), range.end, range.start, range.end, new Slice(content, 0, 0), wrappers.length, true));\n let found = 0;\n for (let i = 0; i < wrappers.length; i++)\n if (wrappers[i].type == listType)\n found = i + 1;\n let splitDepth = wrappers.length - found;\n let splitPos = range.start + wrappers.length - (joinBefore ? 2 : 0), parent = range.parent;\n for (let i = range.startIndex, e = range.endIndex, first = true; i < e; i++, first = false) {\n if (!first && canSplit(tr.doc, splitPos, splitDepth)) {\n tr.split(splitPos, splitDepth);\n splitPos += 2 * splitDepth;\n }\n splitPos += parent.child(i).nodeSize;\n }\n return tr;\n}\n/**\nBuild a command that splits a non-empty textblock at the top level\nof a list item by also splitting that list item.\n*/\nfunction splitListItem(itemType, itemAttrs) {\n return function (state, dispatch) {\n let { $from, $to, node } = state.selection;\n if ((node && node.isBlock) || $from.depth < 2 || !$from.sameParent($to))\n return false;\n let grandParent = $from.node(-1);\n if (grandParent.type != itemType)\n return false;\n if ($from.parent.content.size == 0 && $from.node(-1).childCount == $from.indexAfter(-1)) {\n // In an empty block. If this is a nested list, the wrapping\n // list item should be split. Otherwise, bail out and let next\n // command handle lifting.\n if ($from.depth == 3 || $from.node(-3).type != itemType ||\n $from.index(-2) != $from.node(-2).childCount - 1)\n return false;\n if (dispatch) {\n let wrap = Fragment.empty;\n let depthBefore = $from.index(-1) ? 1 : $from.index(-2) ? 2 : 3;\n // Build a fragment containing empty versions of the structure\n // from the outer list item to the parent node of the cursor\n for (let d = $from.depth - depthBefore; d >= $from.depth - 3; d--)\n wrap = Fragment.from($from.node(d).copy(wrap));\n let depthAfter = $from.indexAfter(-1) < $from.node(-2).childCount ? 1\n : $from.indexAfter(-2) < $from.node(-3).childCount ? 2 : 3;\n // Add a second list item with an empty default start node\n wrap = wrap.append(Fragment.from(itemType.createAndFill()));\n let start = $from.before($from.depth - (depthBefore - 1));\n let tr = state.tr.replace(start, $from.after(-depthAfter), new Slice(wrap, 4 - depthBefore, 0));\n let sel = -1;\n tr.doc.nodesBetween(start, tr.doc.content.size, (node, pos) => {\n if (sel > -1)\n return false;\n if (node.isTextblock && node.content.size == 0)\n sel = pos + 1;\n });\n if (sel > -1)\n tr.setSelection(Selection.near(tr.doc.resolve(sel)));\n dispatch(tr.scrollIntoView());\n }\n return true;\n }\n let nextType = $to.pos == $from.end() ? grandParent.contentMatchAt(0).defaultType : null;\n let tr = state.tr.delete($from.pos, $to.pos);\n let types = nextType ? [itemAttrs ? { type: itemType, attrs: itemAttrs } : null, { type: nextType }] : undefined;\n if (!canSplit(tr.doc, $from.pos, 2, types))\n return false;\n if (dispatch)\n dispatch(tr.split($from.pos, 2, types).scrollIntoView());\n return true;\n };\n}\n/**\nActs like [`splitListItem`](https://prosemirror.net/docs/ref/#schema-list.splitListItem), but\nwithout resetting the set of active marks at the cursor.\n*/\nfunction splitListItemKeepMarks(itemType, itemAttrs) {\n let split = splitListItem(itemType, itemAttrs);\n return (state, dispatch) => {\n return split(state, dispatch && (tr => {\n let marks = state.storedMarks || (state.selection.$to.parentOffset && state.selection.$from.marks());\n if (marks)\n tr.ensureMarks(marks);\n dispatch(tr);\n }));\n };\n}\n/**\nCreate a command to lift the list item around the selection up into\na wrapping list.\n*/\nfunction liftListItem(itemType) {\n return function (state, dispatch) {\n let { $from, $to } = state.selection;\n let range = $from.blockRange($to, node => node.childCount > 0 && node.firstChild.type == itemType);\n if (!range)\n return false;\n if (!dispatch)\n return true;\n if ($from.node(range.depth - 1).type == itemType) // Inside a parent list\n return liftToOuterList(state, dispatch, itemType, range);\n else // Outer list node\n return liftOutOfList(state, dispatch, range);\n };\n}\nfunction liftToOuterList(state, dispatch, itemType, range) {\n let tr = state.tr, end = range.end, endOfList = range.$to.end(range.depth);\n if (end < endOfList) {\n // There are siblings after the lifted items, which must become\n // children of the last item\n tr.step(new ReplaceAroundStep(end - 1, endOfList, end, endOfList, new Slice(Fragment.from(itemType.create(null, range.parent.copy())), 1, 0), 1, true));\n range = new NodeRange(tr.doc.resolve(range.$from.pos), tr.doc.resolve(endOfList), range.depth);\n }\n const target = liftTarget(range);\n if (target == null)\n return false;\n tr.lift(range, target);\n let $after = tr.doc.resolve(tr.mapping.map(end, -1) - 1);\n if (canJoin(tr.doc, $after.pos) && $after.nodeBefore.type == $after.nodeAfter.type)\n tr.join($after.pos);\n dispatch(tr.scrollIntoView());\n return true;\n}\nfunction liftOutOfList(state, dispatch, range) {\n let tr = state.tr, list = range.parent;\n // Merge the list items into a single big item\n for (let pos = range.end, i = range.endIndex - 1, e = range.startIndex; i > e; i--) {\n pos -= list.child(i).nodeSize;\n tr.delete(pos - 1, pos + 1);\n }\n let $start = tr.doc.resolve(range.start), item = $start.nodeAfter;\n if (tr.mapping.map(range.end) != range.start + $start.nodeAfter.nodeSize)\n return false;\n let atStart = range.startIndex == 0, atEnd = range.endIndex == list.childCount;\n let parent = $start.node(-1), indexBefore = $start.index(-1);\n if (!parent.canReplace(indexBefore + (atStart ? 0 : 1), indexBefore + 1, item.content.append(atEnd ? Fragment.empty : Fragment.from(list))))\n return false;\n let start = $start.pos, end = start + item.nodeSize;\n // Strip off the surrounding list. At the sides where we're not at\n // the end of the list, the existing list is closed. At sides where\n // this is the end, it is overwritten to its end.\n tr.step(new ReplaceAroundStep(start - (atStart ? 1 : 0), end + (atEnd ? 1 : 0), start + 1, end - 1, new Slice((atStart ? Fragment.empty : Fragment.from(list.copy(Fragment.empty)))\n .append(atEnd ? Fragment.empty : Fragment.from(list.copy(Fragment.empty))), atStart ? 0 : 1, atEnd ? 0 : 1), atStart ? 0 : 1));\n dispatch(tr.scrollIntoView());\n return true;\n}\n/**\nCreate a command to sink the list item around the selection down\ninto an inner list.\n*/\nfunction sinkListItem(itemType) {\n return function (state, dispatch) {\n let { $from, $to } = state.selection;\n let range = $from.blockRange($to, node => node.childCount > 0 && node.firstChild.type == itemType);\n if (!range)\n return false;\n let startIndex = range.startIndex;\n if (startIndex == 0)\n return false;\n let parent = range.parent, nodeBefore = parent.child(startIndex - 1);\n if (nodeBefore.type != itemType)\n return false;\n if (dispatch) {\n let nestedBefore = nodeBefore.lastChild && nodeBefore.lastChild.type == parent.type;\n let inner = Fragment.from(nestedBefore ? itemType.create() : null);\n let slice = new Slice(Fragment.from(itemType.create(null, Fragment.from(parent.type.create(null, inner)))), nestedBefore ? 3 : 1, 0);\n let before = range.start, after = range.end;\n dispatch(state.tr.step(new ReplaceAroundStep(before - (nestedBefore ? 3 : 1), after, before, after, slice, 1, true))\n .scrollIntoView());\n }\n return true;\n };\n}\n\nexport { addListNodes, bulletList, liftListItem, listItem, orderedList, sinkListItem, splitListItem, splitListItemKeepMarks, wrapInList, wrapRangeInList };\n",
20- "export var base = {\n 8: \"Backspace\",\n 9: \"Tab\",\n 10: \"Enter\",\n 12: \"NumLock\",\n 13: \"Enter\",\n 16: \"Shift\",\n 17: \"Control\",\n 18: \"Alt\",\n 20: \"CapsLock\",\n 27: \"Escape\",\n 32: \" \",\n 33: \"PageUp\",\n 34: \"PageDown\",\n 35: \"End\",\n 36: \"Home\",\n 37: \"ArrowLeft\",\n 38: \"ArrowUp\",\n 39: \"ArrowRight\",\n 40: \"ArrowDown\",\n 44: \"PrintScreen\",\n 45: \"Insert\",\n 46: \"Delete\",\n 59: \";\",\n 61: \"=\",\n 91: \"Meta\",\n 92: \"Meta\",\n 106: \"*\",\n 107: \"+\",\n 108: \",\",\n 109: \"-\",\n 110: \".\",\n 111: \"/\",\n 144: \"NumLock\",\n 145: \"ScrollLock\",\n 160: \"Shift\",\n 161: \"Shift\",\n 162: \"Control\",\n 163: \"Control\",\n 164: \"Alt\",\n 165: \"Alt\",\n 173: \"-\",\n 186: \";\",\n 187: \"=\",\n 188: \",\",\n 189: \"-\",\n 190: \".\",\n 191: \"/\",\n 192: \"`\",\n 219: \"[\",\n 220: \"\\\\\",\n 221: \"]\",\n 222: \"'\"\n}\n\nexport var shift = {\n 48: \")\",\n 49: \"!\",\n 50: \"@\",\n 51: \"#\",\n 52: \"$\",\n 53: \"%\",\n 54: \"^\",\n 55: \"&\",\n 56: \"*\",\n 57: \"(\",\n 59: \":\",\n 61: \"+\",\n 173: \"_\",\n 186: \":\",\n 187: \"+\",\n 188: \"<\",\n 189: \"_\",\n 190: \">\",\n 191: \"?\",\n 192: \"~\",\n 219: \"{\",\n 220: \"|\",\n 221: \"}\",\n 222: \"\\\"\"\n}\n\nvar mac = typeof navigator != \"undefined\" && /Mac/.test(navigator.platform)\nvar ie = typeof navigator != \"undefined\" && /MSIE \\d|Trident\\/(?:[7-9]|\\d{2,})\\..*rv:(\\d+)/.exec(navigator.userAgent)\n\n// Fill in the digit keys\nfor (var i = 0; i < 10; i++) base[48 + i] = base[96 + i] = String(i)\n\n// The function keys\nfor (var i = 1; i <= 24; i++) base[i + 111] = \"F\" + i\n\n// And the alphabetic keys\nfor (var i = 65; i <= 90; i++) {\n base[i] = String.fromCharCode(i + 32)\n shift[i] = String.fromCharCode(i)\n}\n\n// For each code that doesn't have a shift-equivalent, copy the base name\nfor (var code in base) if (!shift.hasOwnProperty(code)) shift[code] = base[code]\n\nexport function keyName(event) {\n // On macOS, keys held with Shift and Cmd don't reflect the effect of Shift in `.key`.\n // On IE, shift effect is never included in `.key`.\n var ignoreKey = mac && event.metaKey && event.shiftKey && !event.ctrlKey && !event.altKey ||\n ie && event.shiftKey && event.key && event.key.length == 1 ||\n event.key == \"Unidentified\"\n var name = (!ignoreKey && event.key) ||\n (event.shiftKey ? shift : base)[event.keyCode] ||\n event.key || \"Unidentified\"\n // Edge sometimes produces wrong names (Issue #3)\n if (name == \"Esc\") name = \"Escape\"\n if (name == \"Del\") name = \"Delete\"\n // https://developer.microsoft.com/en-us/microsoft-edge/platform/issues/8860571/\n if (name == \"Left\") name = \"ArrowLeft\"\n if (name == \"Up\") name = \"ArrowUp\"\n if (name == \"Right\") name = \"ArrowRight\"\n if (name == \"Down\") name = \"ArrowDown\"\n return name\n}\n",
21- "import { keyName, base } from 'w3c-keyname';\nimport { Plugin } from 'prosemirror-state';\n\nconst mac = typeof navigator != \"undefined\" && /Mac|iP(hone|[oa]d)/.test(navigator.platform);\nconst windows = typeof navigator != \"undefined\" && /Win/.test(navigator.platform);\nfunction normalizeKeyName(name) {\n let parts = name.split(/-(?!$)/), result = parts[parts.length - 1];\n if (result == \"Space\")\n result = \" \";\n let alt, ctrl, shift, meta;\n for (let i = 0; i < parts.length - 1; i++) {\n let mod = parts[i];\n if (/^(cmd|meta|m)$/i.test(mod))\n meta = true;\n else if (/^a(lt)?$/i.test(mod))\n alt = true;\n else if (/^(c|ctrl|control)$/i.test(mod))\n ctrl = true;\n else if (/^s(hift)?$/i.test(mod))\n shift = true;\n else if (/^mod$/i.test(mod)) {\n if (mac)\n meta = true;\n else\n ctrl = true;\n }\n else\n throw new Error(\"Unrecognized modifier name: \" + mod);\n }\n if (alt)\n result = \"Alt-\" + result;\n if (ctrl)\n result = \"Ctrl-\" + result;\n if (meta)\n result = \"Meta-\" + result;\n if (shift)\n result = \"Shift-\" + result;\n return result;\n}\nfunction normalize(map) {\n let copy = Object.create(null);\n for (let prop in map)\n copy[normalizeKeyName(prop)] = map[prop];\n return copy;\n}\nfunction modifiers(name, event, shift = true) {\n if (event.altKey)\n name = \"Alt-\" + name;\n if (event.ctrlKey)\n name = \"Ctrl-\" + name;\n if (event.metaKey)\n name = \"Meta-\" + name;\n if (shift && event.shiftKey)\n name = \"Shift-\" + name;\n return name;\n}\n/**\nCreate a keymap plugin for the given set of bindings.\n\nBindings should map key names to [command](https://prosemirror.net/docs/ref/#commands)-style\nfunctions, which will be called with `(EditorState, dispatch,\nEditorView)` arguments, and should return true when they've handled\nthe key. Note that the view argument isn't part of the command\nprotocol, but can be used as an escape hatch if a binding needs to\ndirectly interact with the UI.\n\nKey names may be strings like `\"Shift-Ctrl-Enter\"`—a key\nidentifier prefixed with zero or more modifiers. Key identifiers\nare based on the strings that can appear in\n[`KeyEvent.key`](https:developer.mozilla.org/en-US/docs/Web/API/KeyboardEvent/key).\nUse lowercase letters to refer to letter keys (or uppercase letters\nif you want shift to be held). You may use `\"Space\"` as an alias\nfor the `\" \"` name.\n\nModifiers can be given in any order. `Shift-` (or `s-`), `Alt-` (or\n`a-`), `Ctrl-` (or `c-` or `Control-`) and `Cmd-` (or `m-` or\n`Meta-`) are recognized. For characters that are created by holding\nshift, the `Shift-` prefix is implied, and should not be added\nexplicitly.\n\nYou can use `Mod-` as a shorthand for `Cmd-` on Mac and `Ctrl-` on\nother platforms.\n\nYou can add multiple keymap plugins to an editor. The order in\nwhich they appear determines their precedence (the ones early in\nthe array get to dispatch first).\n*/\nfunction keymap(bindings) {\n return new Plugin({ props: { handleKeyDown: keydownHandler(bindings) } });\n}\n/**\nGiven a set of bindings (using the same format as\n[`keymap`](https://prosemirror.net/docs/ref/#keymap.keymap)), return a [keydown\nhandler](https://prosemirror.net/docs/ref/#view.EditorProps.handleKeyDown) that handles them.\n*/\nfunction keydownHandler(bindings) {\n let map = normalize(bindings);\n return function (view, event) {\n let name = keyName(event), baseName, direct = map[modifiers(name, event)];\n if (direct && direct(view.state, view.dispatch, view))\n return true;\n // A character key\n if (name.length == 1 && name != \" \") {\n if (event.shiftKey) {\n // In case the name was already modified by shift, try looking\n // it up without its shift modifier\n let noShift = map[modifiers(name, event, false)];\n if (noShift && noShift(view.state, view.dispatch, view))\n return true;\n }\n if ((event.altKey || event.metaKey || event.ctrlKey) &&\n // Ctrl-Alt may be used for AltGr on Windows\n !(windows && event.ctrlKey && event.altKey) &&\n (baseName = base[event.keyCode]) && baseName != name) {\n // Try falling back to the keyCode when there's a modifier\n // active or the character produced isn't ASCII, and our table\n // produces a different name from the the keyCode. See #668,\n // #1060, #1529.\n let fromCode = map[modifiers(baseName, event)];\n if (fromCode && fromCode(view.state, view.dispatch, view))\n return true;\n }\n }\n return false;\n };\n}\n\nexport { keydownHandler, keymap };\n",
22- "import { liftTarget, replaceStep, ReplaceStep, canJoin, joinPoint, canSplit, ReplaceAroundStep, findWrapping } from 'prosemirror-transform';\nimport { Slice, Fragment } from 'prosemirror-model';\nimport { NodeSelection, Selection, TextSelection, AllSelection, SelectionRange } from 'prosemirror-state';\n\n/**\nDelete the selection, if there is one.\n*/\nconst deleteSelection = (state, dispatch) => {\n if (state.selection.empty)\n return false;\n if (dispatch)\n dispatch(state.tr.deleteSelection().scrollIntoView());\n return true;\n};\nfunction atBlockStart(state, view) {\n let { $cursor } = state.selection;\n if (!$cursor || (view ? !view.endOfTextblock(\"backward\", state)\n : $cursor.parentOffset > 0))\n return null;\n return $cursor;\n}\n/**\nIf the selection is empty and at the start of a textblock, try to\nreduce the distance between that block and the one before it—if\nthere's a block directly before it that can be joined, join them.\nIf not, try to move the selected block closer to the next one in\nthe document structure by lifting it out of its parent or moving it\ninto a parent of the previous block. Will use the view for accurate\n(bidi-aware) start-of-textblock detection if given.\n*/\nconst joinBackward = (state, dispatch, view) => {\n let $cursor = atBlockStart(state, view);\n if (!$cursor)\n return false;\n let $cut = findCutBefore($cursor);\n // If there is no node before this, try to lift\n if (!$cut) {\n let range = $cursor.blockRange(), target = range && liftTarget(range);\n if (target == null)\n return false;\n if (dispatch)\n dispatch(state.tr.lift(range, target).scrollIntoView());\n return true;\n }\n let before = $cut.nodeBefore;\n // Apply the joining algorithm\n if (deleteBarrier(state, $cut, dispatch, -1))\n return true;\n // If the node below has no content and the node above is\n // selectable, delete the node below and select the one above.\n if ($cursor.parent.content.size == 0 &&\n (textblockAt(before, \"end\") || NodeSelection.isSelectable(before))) {\n for (let depth = $cursor.depth;; depth--) {\n let delStep = replaceStep(state.doc, $cursor.before(depth), $cursor.after(depth), Slice.empty);\n if (delStep && delStep.slice.size < delStep.to - delStep.from) {\n if (dispatch) {\n let tr = state.tr.step(delStep);\n tr.setSelection(textblockAt(before, \"end\")\n ? Selection.findFrom(tr.doc.resolve(tr.mapping.map($cut.pos, -1)), -1)\n : NodeSelection.create(tr.doc, $cut.pos - before.nodeSize));\n dispatch(tr.scrollIntoView());\n }\n return true;\n }\n if (depth == 1 || $cursor.node(depth - 1).childCount > 1)\n break;\n }\n }\n // If the node before is an atom, delete it\n if (before.isAtom && $cut.depth == $cursor.depth - 1) {\n if (dispatch)\n dispatch(state.tr.delete($cut.pos - before.nodeSize, $cut.pos).scrollIntoView());\n return true;\n }\n return false;\n};\n/**\nA more limited form of [`joinBackward`](https://prosemirror.net/docs/ref/#commands.joinBackward)\nthat only tries to join the current textblock to the one before\nit, if the cursor is at the start of a textblock.\n*/\nconst joinTextblockBackward = (state, dispatch, view) => {\n let $cursor = atBlockStart(state, view);\n if (!$cursor)\n return false;\n let $cut = findCutBefore($cursor);\n return $cut ? joinTextblocksAround(state, $cut, dispatch) : false;\n};\n/**\nA more limited form of [`joinForward`](https://prosemirror.net/docs/ref/#commands.joinForward)\nthat only tries to join the current textblock to the one after\nit, if the cursor is at the end of a textblock.\n*/\nconst joinTextblockForward = (state, dispatch, view) => {\n let $cursor = atBlockEnd(state, view);\n if (!$cursor)\n return false;\n let $cut = findCutAfter($cursor);\n return $cut ? joinTextblocksAround(state, $cut, dispatch) : false;\n};\nfunction joinTextblocksAround(state, $cut, dispatch) {\n let before = $cut.nodeBefore, beforeText = before, beforePos = $cut.pos - 1;\n for (; !beforeText.isTextblock; beforePos--) {\n if (beforeText.type.spec.isolating)\n return false;\n let child = beforeText.lastChild;\n if (!child)\n return false;\n beforeText = child;\n }\n let after = $cut.nodeAfter, afterText = after, afterPos = $cut.pos + 1;\n for (; !afterText.isTextblock; afterPos++) {\n if (afterText.type.spec.isolating)\n return false;\n let child = afterText.firstChild;\n if (!child)\n return false;\n afterText = child;\n }\n let step = replaceStep(state.doc, beforePos, afterPos, Slice.empty);\n if (!step || step.from != beforePos ||\n step instanceof ReplaceStep && step.slice.size >= afterPos - beforePos)\n return false;\n if (dispatch) {\n let tr = state.tr.step(step);\n tr.setSelection(TextSelection.create(tr.doc, beforePos));\n dispatch(tr.scrollIntoView());\n }\n return true;\n}\nfunction textblockAt(node, side, only = false) {\n for (let scan = node; scan; scan = (side == \"start\" ? scan.firstChild : scan.lastChild)) {\n if (scan.isTextblock)\n return true;\n if (only && scan.childCount != 1)\n return false;\n }\n return false;\n}\n/**\nWhen the selection is empty and at the start of a textblock, select\nthe node before that textblock, if possible. This is intended to be\nbound to keys like backspace, after\n[`joinBackward`](https://prosemirror.net/docs/ref/#commands.joinBackward) or other deleting\ncommands, as a fall-back behavior when the schema doesn't allow\ndeletion at the selected point.\n*/\nconst selectNodeBackward = (state, dispatch, view) => {\n let { $head, empty } = state.selection, $cut = $head;\n if (!empty)\n return false;\n if ($head.parent.isTextblock) {\n if (view ? !view.endOfTextblock(\"backward\", state) : $head.parentOffset > 0)\n return false;\n $cut = findCutBefore($head);\n }\n let node = $cut && $cut.nodeBefore;\n if (!node || !NodeSelection.isSelectable(node))\n return false;\n if (dispatch)\n dispatch(state.tr.setSelection(NodeSelection.create(state.doc, $cut.pos - node.nodeSize)).scrollIntoView());\n return true;\n};\nfunction findCutBefore($pos) {\n if (!$pos.parent.type.spec.isolating)\n for (let i = $pos.depth - 1; i >= 0; i--) {\n if ($pos.index(i) > 0)\n return $pos.doc.resolve($pos.before(i + 1));\n if ($pos.node(i).type.spec.isolating)\n break;\n }\n return null;\n}\nfunction atBlockEnd(state, view) {\n let { $cursor } = state.selection;\n if (!$cursor || (view ? !view.endOfTextblock(\"forward\", state)\n : $cursor.parentOffset < $cursor.parent.content.size))\n return null;\n return $cursor;\n}\n/**\nIf the selection is empty and the cursor is at the end of a\ntextblock, try to reduce or remove the boundary between that block\nand the one after it, either by joining them or by moving the other\nblock closer to this one in the tree structure. Will use the view\nfor accurate start-of-textblock detection if given.\n*/\nconst joinForward = (state, dispatch, view) => {\n let $cursor = atBlockEnd(state, view);\n if (!$cursor)\n return false;\n let $cut = findCutAfter($cursor);\n // If there is no node after this, there's nothing to do\n if (!$cut)\n return false;\n let after = $cut.nodeAfter;\n // Try the joining algorithm\n if (deleteBarrier(state, $cut, dispatch, 1))\n return true;\n // If the node above has no content and the node below is\n // selectable, delete the node above and select the one below.\n if ($cursor.parent.content.size == 0 &&\n (textblockAt(after, \"start\") || NodeSelection.isSelectable(after))) {\n let delStep = replaceStep(state.doc, $cursor.before(), $cursor.after(), Slice.empty);\n if (delStep && delStep.slice.size < delStep.to - delStep.from) {\n if (dispatch) {\n let tr = state.tr.step(delStep);\n tr.setSelection(textblockAt(after, \"start\") ? Selection.findFrom(tr.doc.resolve(tr.mapping.map($cut.pos)), 1)\n : NodeSelection.create(tr.doc, tr.mapping.map($cut.pos)));\n dispatch(tr.scrollIntoView());\n }\n return true;\n }\n }\n // If the next node is an atom, delete it\n if (after.isAtom && $cut.depth == $cursor.depth - 1) {\n if (dispatch)\n dispatch(state.tr.delete($cut.pos, $cut.pos + after.nodeSize).scrollIntoView());\n return true;\n }\n return false;\n};\n/**\nWhen the selection is empty and at the end of a textblock, select\nthe node coming after that textblock, if possible. This is intended\nto be bound to keys like delete, after\n[`joinForward`](https://prosemirror.net/docs/ref/#commands.joinForward) and similar deleting\ncommands, to provide a fall-back behavior when the schema doesn't\nallow deletion at the selected point.\n*/\nconst selectNodeForward = (state, dispatch, view) => {\n let { $head, empty } = state.selection, $cut = $head;\n if (!empty)\n return false;\n if ($head.parent.isTextblock) {\n if (view ? !view.endOfTextblock(\"forward\", state) : $head.parentOffset < $head.parent.content.size)\n return false;\n $cut = findCutAfter($head);\n }\n let node = $cut && $cut.nodeAfter;\n if (!node || !NodeSelection.isSelectable(node))\n return false;\n if (dispatch)\n dispatch(state.tr.setSelection(NodeSelection.create(state.doc, $cut.pos)).scrollIntoView());\n return true;\n};\nfunction findCutAfter($pos) {\n if (!$pos.parent.type.spec.isolating)\n for (let i = $pos.depth - 1; i >= 0; i--) {\n let parent = $pos.node(i);\n if ($pos.index(i) + 1 < parent.childCount)\n return $pos.doc.resolve($pos.after(i + 1));\n if (parent.type.spec.isolating)\n break;\n }\n return null;\n}\n/**\nJoin the selected block or, if there is a text selection, the\nclosest ancestor block of the selection that can be joined, with\nthe sibling above it.\n*/\nconst joinUp = (state, dispatch) => {\n let sel = state.selection, nodeSel = sel instanceof NodeSelection, point;\n if (nodeSel) {\n if (sel.node.isTextblock || !canJoin(state.doc, sel.from))\n return false;\n point = sel.from;\n }\n else {\n point = joinPoint(state.doc, sel.from, -1);\n if (point == null)\n return false;\n }\n if (dispatch) {\n let tr = state.tr.join(point);\n if (nodeSel)\n tr.setSelection(NodeSelection.create(tr.doc, point - state.doc.resolve(point).nodeBefore.nodeSize));\n dispatch(tr.scrollIntoView());\n }\n return true;\n};\n/**\nJoin the selected block, or the closest ancestor of the selection\nthat can be joined, with the sibling after it.\n*/\nconst joinDown = (state, dispatch) => {\n let sel = state.selection, point;\n if (sel instanceof NodeSelection) {\n if (sel.node.isTextblock || !canJoin(state.doc, sel.to))\n return false;\n point = sel.to;\n }\n else {\n point = joinPoint(state.doc, sel.to, 1);\n if (point == null)\n return false;\n }\n if (dispatch)\n dispatch(state.tr.join(point).scrollIntoView());\n return true;\n};\n/**\nLift the selected block, or the closest ancestor block of the\nselection that can be lifted, out of its parent node.\n*/\nconst lift = (state, dispatch) => {\n let { $from, $to } = state.selection;\n let range = $from.blockRange($to), target = range && liftTarget(range);\n if (target == null)\n return false;\n if (dispatch)\n dispatch(state.tr.lift(range, target).scrollIntoView());\n return true;\n};\n/**\nIf the selection is in a node whose type has a truthy\n[`code`](https://prosemirror.net/docs/ref/#model.NodeSpec.code) property in its spec, replace the\nselection with a newline character.\n*/\nconst newlineInCode = (state, dispatch) => {\n let { $head, $anchor } = state.selection;\n if (!$head.parent.type.spec.code || !$head.sameParent($anchor))\n return false;\n if (dispatch)\n dispatch(state.tr.insertText(\"\\n\").scrollIntoView());\n return true;\n};\nfunction defaultBlockAt(match) {\n for (let i = 0; i < match.edgeCount; i++) {\n let { type } = match.edge(i);\n if (type.isTextblock && !type.hasRequiredAttrs())\n return type;\n }\n return null;\n}\n/**\nWhen the selection is in a node with a truthy\n[`code`](https://prosemirror.net/docs/ref/#model.NodeSpec.code) property in its spec, create a\ndefault block after the code block, and move the cursor there.\n*/\nconst exitCode = (state, dispatch) => {\n let { $head, $anchor } = state.selection;\n if (!$head.parent.type.spec.code || !$head.sameParent($anchor))\n return false;\n let above = $head.node(-1), after = $head.indexAfter(-1), type = defaultBlockAt(above.contentMatchAt(after));\n if (!type || !above.canReplaceWith(after, after, type))\n return false;\n if (dispatch) {\n let pos = $head.after(), tr = state.tr.replaceWith(pos, pos, type.createAndFill());\n tr.setSelection(Selection.near(tr.doc.resolve(pos), 1));\n dispatch(tr.scrollIntoView());\n }\n return true;\n};\n/**\nIf a block node is selected, create an empty paragraph before (if\nit is its parent's first child) or after it.\n*/\nconst createParagraphNear = (state, dispatch) => {\n let sel = state.selection, { $from, $to } = sel;\n if (sel instanceof AllSelection || $from.parent.inlineContent || $to.parent.inlineContent)\n return false;\n let type = defaultBlockAt($to.parent.contentMatchAt($to.indexAfter()));\n if (!type || !type.isTextblock)\n return false;\n if (dispatch) {\n let side = (!$from.parentOffset && $to.index() < $to.parent.childCount ? $from : $to).pos;\n let tr = state.tr.insert(side, type.createAndFill());\n tr.setSelection(TextSelection.create(tr.doc, side + 1));\n dispatch(tr.scrollIntoView());\n }\n return true;\n};\n/**\nIf the cursor is in an empty textblock that can be lifted, lift the\nblock.\n*/\nconst liftEmptyBlock = (state, dispatch) => {\n let { $cursor } = state.selection;\n if (!$cursor || $cursor.parent.content.size)\n return false;\n if ($cursor.depth > 1 && $cursor.after() != $cursor.end(-1)) {\n let before = $cursor.before();\n if (canSplit(state.doc, before)) {\n if (dispatch)\n dispatch(state.tr.split(before).scrollIntoView());\n return true;\n }\n }\n let range = $cursor.blockRange(), target = range && liftTarget(range);\n if (target == null)\n return false;\n if (dispatch)\n dispatch(state.tr.lift(range, target).scrollIntoView());\n return true;\n};\n/**\nCreate a variant of [`splitBlock`](https://prosemirror.net/docs/ref/#commands.splitBlock) that uses\na custom function to determine the type of the newly split off block.\n*/\nfunction splitBlockAs(splitNode) {\n return (state, dispatch) => {\n if (state.selection instanceof NodeSelection && state.selection.node.isBlock) {\n let { $from } = state.selection;\n if (!$from.parentOffset || !canSplit(state.doc, $from.pos))\n return false;\n if (dispatch)\n dispatch(state.tr.split($from.pos).scrollIntoView());\n return true;\n }\n if (!state.selection.$from.depth)\n return false;\n let tr = state.tr;\n if (!state.selection.empty && (state.selection instanceof TextSelection || state.selection instanceof AllSelection))\n tr.deleteSelection();\n let { $from } = tr.selection, mapFrom = tr.steps.length;\n let types = [];\n let splitDepth, deflt, atEnd = false, atStart = false;\n for (let d = $from.depth;; d--) {\n let node = $from.node(d);\n if (node.isBlock) {\n atEnd = $from.end(d) == $from.pos + ($from.depth - d);\n atStart = $from.start(d) == $from.pos - ($from.depth - d);\n deflt = defaultBlockAt($from.node(d - 1).contentMatchAt($from.indexAfter(d - 1)));\n let splitType = splitNode && splitNode($from.parent, atEnd, $from);\n types.unshift(splitType || (atEnd && deflt ? { type: deflt } : null));\n splitDepth = d;\n break;\n }\n else {\n if (d == 1)\n return false;\n types.unshift(null);\n }\n }\n let splitPos = $from.pos;\n let can = canSplit(tr.doc, splitPos, types.length, types);\n if (!can) {\n types[0] = deflt ? { type: deflt } : null;\n can = canSplit(tr.doc, splitPos, types.length, types);\n }\n if (!can)\n return false;\n tr.split(splitPos, types.length, types);\n if (!atEnd && atStart && $from.node(splitDepth).type != deflt) {\n let mapping = tr.mapping.slice(mapFrom);\n let first = mapping.map($from.before(splitDepth)), $first = tr.doc.resolve(first);\n if (deflt && $from.node(splitDepth - 1).canReplaceWith($first.index(), $first.index() + 1, deflt))\n tr.setNodeMarkup(mapping.map($from.before(splitDepth)), deflt);\n }\n if (dispatch)\n dispatch(tr.scrollIntoView());\n return true;\n };\n}\n/**\nSplit the parent block of the selection. If the selection is a text\nselection, also delete its content.\n*/\nconst splitBlock = splitBlockAs();\n/**\nActs like [`splitBlock`](https://prosemirror.net/docs/ref/#commands.splitBlock), but without\nresetting the set of active marks at the cursor.\n*/\nconst splitBlockKeepMarks = (state, dispatch) => {\n return splitBlock(state, dispatch && (tr => {\n let marks = state.storedMarks || (state.selection.$to.parentOffset && state.selection.$from.marks());\n if (marks)\n tr.ensureMarks(marks);\n dispatch(tr);\n }));\n};\n/**\nMove the selection to the node wrapping the current selection, if\nany. (Will not select the document node.)\n*/\nconst selectParentNode = (state, dispatch) => {\n let { $from, to } = state.selection, pos;\n let same = $from.sharedDepth(to);\n if (same == 0)\n return false;\n pos = $from.before(same);\n if (dispatch)\n dispatch(state.tr.setSelection(NodeSelection.create(state.doc, pos)));\n return true;\n};\n/**\nSelect the whole document.\n*/\nconst selectAll = (state, dispatch) => {\n if (dispatch)\n dispatch(state.tr.setSelection(new AllSelection(state.doc)));\n return true;\n};\nfunction joinMaybeClear(state, $pos, dispatch) {\n let before = $pos.nodeBefore, after = $pos.nodeAfter, index = $pos.index();\n if (!before || !after || !before.type.compatibleContent(after.type))\n return false;\n if (!before.content.size && $pos.parent.canReplace(index - 1, index)) {\n if (dispatch)\n dispatch(state.tr.delete($pos.pos - before.nodeSize, $pos.pos).scrollIntoView());\n return true;\n }\n if (!$pos.parent.canReplace(index, index + 1) || !(after.isTextblock || canJoin(state.doc, $pos.pos)))\n return false;\n if (dispatch)\n dispatch(state.tr.join($pos.pos).scrollIntoView());\n return true;\n}\nfunction deleteBarrier(state, $cut, dispatch, dir) {\n let before = $cut.nodeBefore, after = $cut.nodeAfter, conn, match;\n let isolated = before.type.spec.isolating || after.type.spec.isolating;\n if (!isolated && joinMaybeClear(state, $cut, dispatch))\n return true;\n let canDelAfter = !isolated && $cut.parent.canReplace($cut.index(), $cut.index() + 1);\n if (canDelAfter &&\n (conn = (match = before.contentMatchAt(before.childCount)).findWrapping(after.type)) &&\n match.matchType(conn[0] || after.type).validEnd) {\n if (dispatch) {\n let end = $cut.pos + after.nodeSize, wrap = Fragment.empty;\n for (let i = conn.length - 1; i >= 0; i--)\n wrap = Fragment.from(conn[i].create(null, wrap));\n wrap = Fragment.from(before.copy(wrap));\n let tr = state.tr.step(new ReplaceAroundStep($cut.pos - 1, end, $cut.pos, end, new Slice(wrap, 1, 0), conn.length, true));\n let $joinAt = tr.doc.resolve(end + 2 * conn.length);\n if ($joinAt.nodeAfter && $joinAt.nodeAfter.type == before.type &&\n canJoin(tr.doc, $joinAt.pos))\n tr.join($joinAt.pos);\n dispatch(tr.scrollIntoView());\n }\n return true;\n }\n let selAfter = after.type.spec.isolating || (dir > 0 && isolated) ? null : Selection.findFrom($cut, 1);\n let range = selAfter && selAfter.$from.blockRange(selAfter.$to), target = range && liftTarget(range);\n if (target != null && target >= $cut.depth) {\n if (dispatch)\n dispatch(state.tr.lift(range, target).scrollIntoView());\n return true;\n }\n if (canDelAfter && textblockAt(after, \"start\", true) && textblockAt(before, \"end\")) {\n let at = before, wrap = [];\n for (;;) {\n wrap.push(at);\n if (at.isTextblock)\n break;\n at = at.lastChild;\n }\n let afterText = after, afterDepth = 1;\n for (; !afterText.isTextblock; afterText = afterText.firstChild)\n afterDepth++;\n if (at.canReplace(at.childCount, at.childCount, afterText.content)) {\n if (dispatch) {\n let end = Fragment.empty;\n for (let i = wrap.length - 1; i >= 0; i--)\n end = Fragment.from(wrap[i].copy(end));\n let tr = state.tr.step(new ReplaceAroundStep($cut.pos - wrap.length, $cut.pos + after.nodeSize, $cut.pos + afterDepth, $cut.pos + after.nodeSize - afterDepth, new Slice(end, wrap.length, 0), 0, true));\n dispatch(tr.scrollIntoView());\n }\n return true;\n }\n }\n return false;\n}\nfunction selectTextblockSide(side) {\n return function (state, dispatch) {\n let sel = state.selection, $pos = side < 0 ? sel.$from : sel.$to;\n let depth = $pos.depth;\n while ($pos.node(depth).isInline) {\n if (!depth)\n return false;\n depth--;\n }\n if (!$pos.node(depth).isTextblock)\n return false;\n if (dispatch)\n dispatch(state.tr.setSelection(TextSelection.create(state.doc, side < 0 ? $pos.start(depth) : $pos.end(depth))));\n return true;\n };\n}\n/**\nMoves the cursor to the start of current text block.\n*/\nconst selectTextblockStart = selectTextblockSide(-1);\n/**\nMoves the cursor to the end of current text block.\n*/\nconst selectTextblockEnd = selectTextblockSide(1);\n// Parameterized commands\n/**\nWrap the selection in a node of the given type with the given\nattributes.\n*/\nfunction wrapIn(nodeType, attrs = null) {\n return function (state, dispatch) {\n let { $from, $to } = state.selection;\n let range = $from.blockRange($to), wrapping = range && findWrapping(range, nodeType, attrs);\n if (!wrapping)\n return false;\n if (dispatch)\n dispatch(state.tr.wrap(range, wrapping).scrollIntoView());\n return true;\n };\n}\n/**\nReturns a command that tries to set the selected textblocks to the\ngiven node type with the given attributes.\n*/\nfunction setBlockType(nodeType, attrs = null) {\n return function (state, dispatch) {\n let applicable = false;\n for (let i = 0; i < state.selection.ranges.length && !applicable; i++) {\n let { $from: { pos: from }, $to: { pos: to } } = state.selection.ranges[i];\n state.doc.nodesBetween(from, to, (node, pos) => {\n if (applicable)\n return false;\n if (!node.isTextblock || node.hasMarkup(nodeType, attrs))\n return;\n if (node.type == nodeType) {\n applicable = true;\n }\n else {\n let $pos = state.doc.resolve(pos), index = $pos.index();\n applicable = $pos.parent.canReplaceWith(index, index + 1, nodeType);\n }\n });\n }\n if (!applicable)\n return false;\n if (dispatch) {\n let tr = state.tr;\n for (let i = 0; i < state.selection.ranges.length; i++) {\n let { $from: { pos: from }, $to: { pos: to } } = state.selection.ranges[i];\n tr.setBlockType(from, to, nodeType, attrs);\n }\n dispatch(tr.scrollIntoView());\n }\n return true;\n };\n}\nfunction markApplies(doc, ranges, type, enterAtoms) {\n for (let i = 0; i < ranges.length; i++) {\n let { $from, $to } = ranges[i];\n let can = $from.depth == 0 ? doc.inlineContent && doc.type.allowsMarkType(type) : false;\n doc.nodesBetween($from.pos, $to.pos, (node, pos) => {\n if (can || !enterAtoms && node.isAtom && node.isInline && pos >= $from.pos && pos + node.nodeSize <= $to.pos)\n return false;\n can = node.inlineContent && node.type.allowsMarkType(type);\n });\n if (can)\n return true;\n }\n return false;\n}\nfunction removeInlineAtoms(ranges) {\n let result = [];\n for (let i = 0; i < ranges.length; i++) {\n let { $from, $to } = ranges[i];\n $from.doc.nodesBetween($from.pos, $to.pos, (node, pos) => {\n if (node.isAtom && node.content.size && node.isInline && pos >= $from.pos && pos + node.nodeSize <= $to.pos) {\n if (pos + 1 > $from.pos)\n result.push(new SelectionRange($from, $from.doc.resolve(pos + 1)));\n $from = $from.doc.resolve(pos + 1 + node.content.size);\n return false;\n }\n });\n if ($from.pos < $to.pos)\n result.push(new SelectionRange($from, $to));\n }\n return result;\n}\n/**\nCreate a command function that toggles the given mark with the\ngiven attributes. Will return `false` when the current selection\ndoesn't support that mark. This will remove the mark if any marks\nof that type exist in the selection, or add it otherwise. If the\nselection is empty, this applies to the [stored\nmarks](https://prosemirror.net/docs/ref/#state.EditorState.storedMarks) instead of a range of the\ndocument.\n*/\nfunction toggleMark(markType, attrs = null, options) {\n let removeWhenPresent = (options && options.removeWhenPresent) !== false;\n let enterAtoms = (options && options.enterInlineAtoms) !== false;\n let dropSpace = !(options && options.includeWhitespace);\n return function (state, dispatch) {\n let { empty, $cursor, ranges } = state.selection;\n if ((empty && !$cursor) || !markApplies(state.doc, ranges, markType, enterAtoms))\n return false;\n if (dispatch) {\n if ($cursor) {\n if (markType.isInSet(state.storedMarks || $cursor.marks()))\n dispatch(state.tr.removeStoredMark(markType));\n else\n dispatch(state.tr.addStoredMark(markType.create(attrs)));\n }\n else {\n let add, tr = state.tr;\n if (!enterAtoms)\n ranges = removeInlineAtoms(ranges);\n if (removeWhenPresent) {\n add = !ranges.some(r => state.doc.rangeHasMark(r.$from.pos, r.$to.pos, markType));\n }\n else {\n add = !ranges.every(r => {\n let missing = false;\n tr.doc.nodesBetween(r.$from.pos, r.$to.pos, (node, pos, parent) => {\n if (missing)\n return false;\n missing = !markType.isInSet(node.marks) && !!parent && parent.type.allowsMarkType(markType) &&\n !(node.isText && /^\\s*$/.test(node.textBetween(Math.max(0, r.$from.pos - pos), Math.min(node.nodeSize, r.$to.pos - pos))));\n });\n return !missing;\n });\n }\n for (let i = 0; i < ranges.length; i++) {\n let { $from, $to } = ranges[i];\n if (!add) {\n tr.removeMark($from.pos, $to.pos, markType);\n }\n else {\n let from = $from.pos, to = $to.pos, start = $from.nodeAfter, end = $to.nodeBefore;\n let spaceStart = dropSpace && start && start.isText ? /^\\s*/.exec(start.text)[0].length : 0;\n let spaceEnd = dropSpace && end && end.isText ? /\\s*$/.exec(end.text)[0].length : 0;\n if (from + spaceStart < to) {\n from += spaceStart;\n to -= spaceEnd;\n }\n tr.addMark(from, to, markType.create(attrs));\n }\n }\n dispatch(tr.scrollIntoView());\n }\n }\n return true;\n };\n}\nfunction wrapDispatchForJoin(dispatch, isJoinable) {\n return (tr) => {\n if (!tr.isGeneric)\n return dispatch(tr);\n let ranges = [];\n for (let i = 0; i < tr.mapping.maps.length; i++) {\n let map = tr.mapping.maps[i];\n for (let j = 0; j < ranges.length; j++)\n ranges[j] = map.map(ranges[j]);\n map.forEach((_s, _e, from, to) => ranges.push(from, to));\n }\n // Figure out which joinable points exist inside those ranges,\n // by checking all node boundaries in their parent nodes.\n let joinable = [];\n for (let i = 0; i < ranges.length; i += 2) {\n let from = ranges[i], to = ranges[i + 1];\n let $from = tr.doc.resolve(from), depth = $from.sharedDepth(to), parent = $from.node(depth);\n for (let index = $from.indexAfter(depth), pos = $from.after(depth + 1); pos <= to; ++index) {\n let after = parent.maybeChild(index);\n if (!after)\n break;\n if (index && joinable.indexOf(pos) == -1) {\n let before = parent.child(index - 1);\n if (before.type == after.type && isJoinable(before, after))\n joinable.push(pos);\n }\n pos += after.nodeSize;\n }\n }\n // Join the joinable points\n joinable.sort((a, b) => a - b);\n for (let i = joinable.length - 1; i >= 0; i--) {\n if (canJoin(tr.doc, joinable[i]))\n tr.join(joinable[i]);\n }\n dispatch(tr);\n };\n}\n/**\nWrap a command so that, when it produces a transform that causes\ntwo joinable nodes to end up next to each other, those are joined.\nNodes are considered joinable when they are of the same type and\nwhen the `isJoinable` predicate returns true for them or, if an\narray of strings was passed, if their node type name is in that\narray.\n*/\nfunction autoJoin(command, isJoinable) {\n let canJoin = Array.isArray(isJoinable) ? (node) => isJoinable.indexOf(node.type.name) > -1\n : isJoinable;\n return (state, dispatch, view) => command(state, dispatch && wrapDispatchForJoin(dispatch, canJoin), view);\n}\n/**\nCombine a number of command functions into a single function (which\ncalls them one by one until one returns true).\n*/\nfunction chainCommands(...commands) {\n return function (state, dispatch, view) {\n for (let i = 0; i < commands.length; i++)\n if (commands[i](state, dispatch, view))\n return true;\n return false;\n };\n}\nlet backspace = chainCommands(deleteSelection, joinBackward, selectNodeBackward);\nlet del = chainCommands(deleteSelection, joinForward, selectNodeForward);\n/**\nA basic keymap containing bindings not specific to any schema.\nBinds the following keys (when multiple commands are listed, they\nare chained with [`chainCommands`](https://prosemirror.net/docs/ref/#commands.chainCommands)):\n\n* **Enter** to `newlineInCode`, `createParagraphNear`, `liftEmptyBlock`, `splitBlock`\n* **Mod-Enter** to `exitCode`\n* **Backspace** and **Mod-Backspace** to `deleteSelection`, `joinBackward`, `selectNodeBackward`\n* **Delete** and **Mod-Delete** to `deleteSelection`, `joinForward`, `selectNodeForward`\n* **Mod-Delete** to `deleteSelection`, `joinForward`, `selectNodeForward`\n* **Mod-a** to `selectAll`\n*/\nconst pcBaseKeymap = {\n \"Enter\": chainCommands(newlineInCode, createParagraphNear, liftEmptyBlock, splitBlock),\n \"Mod-Enter\": exitCode,\n \"Backspace\": backspace,\n \"Mod-Backspace\": backspace,\n \"Shift-Backspace\": backspace,\n \"Delete\": del,\n \"Mod-Delete\": del,\n \"Mod-a\": selectAll\n};\n/**\nA copy of `pcBaseKeymap` that also binds **Ctrl-h** like Backspace,\n**Ctrl-d** like Delete, **Alt-Backspace** like Ctrl-Backspace, and\n**Ctrl-Alt-Backspace**, **Alt-Delete**, and **Alt-d** like\nCtrl-Delete.\n*/\nconst macBaseKeymap = {\n \"Ctrl-h\": pcBaseKeymap[\"Backspace\"],\n \"Alt-Backspace\": pcBaseKeymap[\"Mod-Backspace\"],\n \"Ctrl-d\": pcBaseKeymap[\"Delete\"],\n \"Ctrl-Alt-Backspace\": pcBaseKeymap[\"Mod-Delete\"],\n \"Alt-Delete\": pcBaseKeymap[\"Mod-Delete\"],\n \"Alt-d\": pcBaseKeymap[\"Mod-Delete\"],\n \"Ctrl-a\": selectTextblockStart,\n \"Ctrl-e\": selectTextblockEnd\n};\nfor (let key in pcBaseKeymap)\n macBaseKeymap[key] = pcBaseKeymap[key];\nconst mac = typeof navigator != \"undefined\" ? /Mac|iP(hone|[oa]d)/.test(navigator.platform)\n // @ts-ignore\n : typeof os != \"undefined\" && os.platform ? os.platform() == \"darwin\" : false;\n/**\nDepending on the detected platform, this will hold\n[`pcBasekeymap`](https://prosemirror.net/docs/ref/#commands.pcBaseKeymap) or\n[`macBaseKeymap`](https://prosemirror.net/docs/ref/#commands.macBaseKeymap).\n*/\nconst baseKeymap = mac ? macBaseKeymap : pcBaseKeymap;\n\nexport { autoJoin, baseKeymap, chainCommands, createParagraphNear, deleteSelection, exitCode, joinBackward, joinDown, joinForward, joinTextblockBackward, joinTextblockForward, joinUp, lift, liftEmptyBlock, macBaseKeymap, newlineInCode, pcBaseKeymap, selectAll, selectNodeBackward, selectNodeForward, selectParentNode, selectTextblockEnd, selectTextblockStart, setBlockType, splitBlock, splitBlockAs, splitBlockKeepMarks, toggleMark, wrapIn };\n",
23- "// Editor UI strings. The language comes from <html lang>; anything but Turkish uses English.\n\nconst en = {\n placeholder: \"Start writing…\",\n toolbarLabel: \"Formatting\",\n bubbleLabel: \"Text formatting\",\n blockMenu: \"Insert block\",\n noMatches: \"No matches\",\n navigate: \"navigate\",\n insert: \"insert\",\n close: \"close\",\n unavailable: \"Not available here\",\n undo: \"Undo\",\n redo: \"Redo\",\n paragraph: \"Paragraph\",\n heading1: \"Heading 1\",\n heading2: \"Heading 2\",\n heading3: \"Heading 3\",\n bold: \"Bold\",\n italic: \"Italic\",\n inlineCode: \"Inline code\",\n link: \"Link\",\n bulletList: \"Bullet list\",\n numberedList: \"Numbered list\",\n quote: \"Quote\",\n codeBlock: \"Code block\",\n divider: \"Divider\",\n text: \"Text\",\n linkDialog: \"Link\",\n linkMenu: \"Link options\",\n linkUrl: \"Link URL\",\n linkInvalid: \"Enter a valid link, such as example.com\",\n linkNeedsLink: \"Add a link first\",\n apply: \"Apply\",\n remove: \"Remove\",\n open: \"Open\",\n edit: \"Edit\",\n statusSaved: \"Saved\",\n statusSaving: \"Saving…\",\n statusLocal: \"Saved on this device\",\n statusReconnecting: \"Reconnecting…\",\n statusConnecting: \"Connecting…\",\n announceOffline: \"You are offline. Changes stay on this device.\",\n announceOnline: \"Back online.\",\n pasteAsText: \"Paste as plain text\",\n noteMenu: \"Link to a note\",\n createNote: \"Create note “{q}”\",\n noNotesFound: \"No notes found\",\n untitled: \"Untitled\",\n} as const;\n\nexport type Key = keyof typeof en;\n\nconst tr: Record<Key, string> = {\n placeholder: \"Yazmaya başla…\",\n toolbarLabel: \"Biçimlendirme\",\n bubbleLabel: \"Metin biçimlendirme\",\n blockMenu: \"Blok ekle\",\n noMatches: \"Eşleşme yok\",\n navigate: \"gezin\",\n insert: \"ekle\",\n close: \"kapat\",\n unavailable: \"Bu alanda kullanılamaz\",\n undo: \"Geri al\",\n redo: \"Yinele\",\n paragraph: \"Metin\",\n heading1: \"Başlık 1\",\n heading2: \"Başlık 2\",\n heading3: \"Başlık 3\",\n bold: \"Kalın\",\n italic: \"İtalik\",\n inlineCode: \"Kod\",\n link: \"Bağlantı\",\n bulletList: \"Madde listesi\",\n numberedList: \"Numaralı liste\",\n quote: \"Alıntı\",\n codeBlock: \"Kod bloğu\",\n divider: \"Ayırıcı\",\n text: \"Metin\",\n linkDialog: \"Bağlantı\",\n linkMenu: \"Bağlantı seçenekleri\",\n linkUrl: \"Bağlantı adresi\",\n linkInvalid: \"Geçerli bir bağlantı girin, ör. example.com\",\n linkNeedsLink: \"Önce bir bağlantı ekleyin\",\n apply: \"Uygula\",\n remove: \"Kaldır\",\n open: \"Aç\",\n edit: \"Düzenle\",\n statusSaved: \"Kaydedildi\",\n statusSaving: \"Kaydediliyor…\",\n statusLocal: \"Bu cihazda kaydedildi\",\n statusReconnecting: \"Yeniden bağlanıyor…\",\n statusConnecting: \"Bağlanıyor…\",\n announceOffline: \"Çevrimdışısınız. Değişiklikler bu cihazda kalır.\",\n announceOnline: \"Yeniden çevrimiçisiniz.\",\n pasteAsText: \"Düz metin olarak yapıştır\",\n noteMenu: \"Nota bağlantısı\",\n createNote: \"“{q}” notunu oluştur\",\n noNotesFound: \"Not bulunamadı\",\n untitled: \"Adsız\",\n};\n\nconst lang: \"en\" | \"tr\" = (document.documentElement.lang || \"en\").toLowerCase().startsWith(\"tr\") ? \"tr\" : \"en\";\n\n/** Looks up a UI string; `{name}` placeholders are filled from `vars`. */\nexport function t(key: Key, vars?: Record<string, string>): string {\n const text: string = lang === \"tr\" ? tr[key] : en[key];\n return vars ? text.replace(/\\{(\\w+)\\}/g, (match, name: string) => vars[name] ?? match) : text;\n}\n",
24- "import { Plugin } from 'prosemirror-state';\nimport { findWrapping, canJoin } from 'prosemirror-transform';\n\n/**\nInput rules are regular expressions describing a piece of text\nthat, when typed, causes something to happen. This might be\nchanging two dashes into an emdash, wrapping a paragraph starting\nwith `\"> \"` into a blockquote, or something entirely different.\n*/\nclass InputRule {\n /**\n Create an input rule. The rule applies when the user typed\n something and the text directly in front of the cursor matches\n `match`, which should end with `$`.\n \n The `handler` can be a string, in which case the matched text, or\n the first matched group in the regexp, is replaced by that\n string.\n \n Or a it can be a function, which will be called with the match\n array produced by\n [`RegExp.exec`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/RegExp/exec),\n as well as the start and end of the matched range, and which can\n return a [transaction](https://prosemirror.net/docs/ref/#state.Transaction) that describes the\n rule's effect, or null to indicate the input was not handled.\n */\n constructor(\n /**\n @internal\n */\n match, handler, options = {}) {\n this.match = match;\n this.match = match;\n this.handler = typeof handler == \"string\" ? stringHandler(handler) : handler;\n this.undoable = options.undoable !== false;\n this.inCode = options.inCode || false;\n this.inCodeMark = options.inCodeMark !== false;\n }\n}\nfunction stringHandler(string) {\n return function (state, match, start, end) {\n let insert = string;\n if (match[1]) {\n let offset = match[0].lastIndexOf(match[1]);\n insert += match[0].slice(offset + match[1].length);\n start += offset;\n let cutOff = start - end;\n if (cutOff > 0) {\n insert = match[0].slice(offset - cutOff, offset) + insert;\n start = end;\n }\n }\n return state.tr.insertText(insert, start, end);\n };\n}\nconst MAX_MATCH = 500;\n/**\nCreate an input rules plugin. When enabled, it will cause text\ninput that matches any of the given rules to trigger the rule's\naction.\n*/\nfunction inputRules({ rules }) {\n let plugin = new Plugin({\n state: {\n init() { return null; },\n apply(tr, prev) {\n let stored = tr.getMeta(this);\n if (stored)\n return stored;\n return tr.selectionSet || tr.docChanged ? null : prev;\n }\n },\n props: {\n handleTextInput(view, from, to, text) {\n return run(view, from, to, text, rules, plugin);\n },\n handleDOMEvents: {\n compositionend: (view) => {\n setTimeout(() => {\n let { $cursor } = view.state.selection;\n if ($cursor)\n run(view, $cursor.pos, $cursor.pos, \"\", rules, plugin);\n });\n }\n }\n },\n isInputRules: true\n });\n return plugin;\n}\nfunction run(view, from, to, text, rules, plugin) {\n if (view.composing)\n return false;\n let state = view.state, $from = state.doc.resolve(from);\n let textBefore = $from.parent.textBetween(Math.max(0, $from.parentOffset - MAX_MATCH), $from.parentOffset, null, \"\\ufffc\") + text;\n for (let i = 0; i < rules.length; i++) {\n let rule = rules[i];\n if (!rule.inCodeMark && $from.marks().some(m => m.type.spec.code))\n continue;\n if ($from.parent.type.spec.code) {\n if (!rule.inCode)\n continue;\n }\n else if (rule.inCode === \"only\") {\n continue;\n }\n let match = rule.match.exec(textBefore);\n if (!match || match[0].length < text.length)\n continue;\n let startPos = from - (match[0].length - text.length);\n if (!rule.inCodeMark) {\n let hasMark = false;\n state.doc.nodesBetween(startPos, $from.pos, node => {\n if (node.isInline && node.marks.some(m => m.type.spec.code))\n hasMark = true;\n });\n if (hasMark)\n continue;\n }\n let tr = rule.handler(state, match, startPos, to);\n if (!tr)\n continue;\n if (rule.undoable)\n tr.setMeta(plugin, { transform: tr, from, to, text });\n view.dispatch(tr);\n return true;\n }\n return false;\n}\n/**\nThis is a command that will undo an input rule, if applying such a\nrule was the last thing that the user did.\n*/\nconst undoInputRule = (state, dispatch) => {\n let plugins = state.plugins;\n for (let i = 0; i < plugins.length; i++) {\n let plugin = plugins[i], undoable;\n if (plugin.spec.isInputRules && (undoable = plugin.getState(state))) {\n if (dispatch) {\n let tr = state.tr, toUndo = undoable.transform;\n for (let j = toUndo.steps.length - 1; j >= 0; j--)\n tr.step(toUndo.steps[j].invert(toUndo.docs[j]));\n if (undoable.text) {\n let marks = tr.doc.resolve(undoable.from).marks();\n tr.replaceWith(undoable.from, undoable.to, state.schema.text(undoable.text, marks));\n }\n else {\n tr.delete(undoable.from, undoable.to);\n }\n dispatch(tr);\n }\n return true;\n }\n }\n return false;\n};\n\n/**\nConverts double dashes to an emdash.\n*/\nconst emDash = new InputRule(/--$/, \"—\", { inCodeMark: false });\n/**\nConverts three dots to an ellipsis character.\n*/\nconst ellipsis = new InputRule(/\\.\\.\\.$/, \"…\", { inCodeMark: false });\n/**\n“Smart” opening double quotes.\n*/\nconst openDoubleQuote = new InputRule(/(?:^|[\\s\\{\\[\\(\\<'\"\\u2018\\u201C])(\")$/, \"“\", { inCodeMark: false });\n/**\n“Smart” closing double quotes.\n*/\nconst closeDoubleQuote = new InputRule(/\"$/, \"”\", { inCodeMark: false });\n/**\n“Smart” opening single quotes.\n*/\nconst openSingleQuote = new InputRule(/(?:^|[\\s\\{\\[\\(\\<'\"\\u2018\\u201C])(')$/, \"‘\", { inCodeMark: false });\n/**\n“Smart” closing single quotes.\n*/\nconst closeSingleQuote = new InputRule(/'$/, \"’\", { inCodeMark: false });\n/**\nSmart-quote related input rules.\n*/\nconst smartQuotes = [openDoubleQuote, closeDoubleQuote, openSingleQuote, closeSingleQuote];\n\n/**\nBuild an input rule for automatically wrapping a textblock when a\ngiven string is typed. The `regexp` argument is\ndirectly passed through to the `InputRule` constructor. You'll\nprobably want the regexp to start with `^`, so that the pattern can\nonly occur at the start of a textblock.\n\n`nodeType` is the type of node to wrap in. If it needs attributes,\nyou can either pass them directly, or pass a function that will\ncompute them from the regular expression match.\n\nBy default, if there's a node with the same type above the newly\nwrapped node, the rule will try to [join](https://prosemirror.net/docs/ref/#transform.Transform.join) those\ntwo nodes. You can pass a join predicate, which takes a regular\nexpression match and the node before the wrapped node, and can\nreturn a boolean to indicate whether a join should happen.\n*/\nfunction wrappingInputRule(regexp, nodeType, getAttrs = null, joinPredicate) {\n return new InputRule(regexp, (state, match, start, end) => {\n let attrs = getAttrs instanceof Function ? getAttrs(match) : getAttrs;\n let tr = state.tr.delete(start, end);\n let $start = tr.doc.resolve(start), range = $start.blockRange(), wrapping = range && findWrapping(range, nodeType, attrs);\n if (!wrapping)\n return null;\n tr.wrap(range, wrapping);\n let before = tr.doc.resolve(start - 1).nodeBefore;\n if (before && before.type == nodeType && canJoin(tr.doc, start - 1) &&\n (!joinPredicate || joinPredicate(match, before)))\n tr.join(start - 1);\n return tr;\n });\n}\n/**\nBuild an input rule that changes the type of a textblock when the\nmatched text is typed into it. You'll usually want to start your\nregexp with `^` to that it is only matched at the start of a\ntextblock. The optional `getAttrs` parameter can be used to compute\nthe new node's attributes, and works the same as in the\n`wrappingInputRule` function.\n*/\nfunction textblockTypeInputRule(regexp, nodeType, getAttrs = null) {\n return new InputRule(regexp, (state, match, start, end) => {\n let $start = state.doc.resolve(start);\n let attrs = getAttrs instanceof Function ? getAttrs(match) : getAttrs;\n if (!$start.node(-1).canReplaceWith($start.index(-1), $start.indexAfter(-1), nodeType))\n return null;\n return state.tr\n .delete(start, end)\n .setBlockType(start, start, nodeType, attrs);\n });\n}\n\nexport { InputRule, closeDoubleQuote, closeSingleQuote, ellipsis, emDash, inputRules, openDoubleQuote, openSingleQuote, smartQuotes, textblockTypeInputRule, undoInputRule, wrappingInputRule };\n",
25- "import { Plugin } from 'prosemirror-state';\nimport { dropPoint } from 'prosemirror-transform';\n\n/**\nCreate a plugin that, when added to a ProseMirror instance,\ncauses a decoration to show up at the drop position when something\nis dragged over the editor.\n\nNodes may add a `disableDropCursor` property to their spec to\ncontrol the showing of a drop cursor inside them. This may be a\nboolean or a function, which will be called with a view and a\nposition, and should return a boolean.\n*/\nfunction dropCursor(options = {}) {\n return new Plugin({\n view(editorView) { return new DropCursorView(editorView, options); }\n });\n}\nclass DropCursorView {\n constructor(editorView, options) {\n var _a;\n this.editorView = editorView;\n this.cursorPos = null;\n this.element = null;\n this.timeout = -1;\n this.lastDragEvent = null;\n this.width = (_a = options.width) !== null && _a !== void 0 ? _a : 1;\n this.color = options.color === false ? undefined : (options.color || \"black\");\n this.class = options.class;\n this.handlers = [\"dragover\", \"dragend\", \"drop\", \"dragleave\"].map(name => {\n let handler = (e) => { this[name](e); };\n editorView.dom.addEventListener(name, handler);\n return { name, handler };\n });\n }\n destroy() {\n this.setCursor(null);\n this.handlers.forEach(({ name, handler }) => this.editorView.dom.removeEventListener(name, handler));\n }\n update(editorView, prevState) {\n if (this.cursorPos != null && prevState.doc != editorView.state.doc) {\n // if we currently have an on-going drag event\n // we need to update the cursor position again and update the overlay\n if (this.lastDragEvent) {\n let target = this.computeTarget(this.lastDragEvent);\n if (target == this.cursorPos)\n this.updateOverlay();\n else\n this.setCursor(target);\n }\n else {\n this.updateOverlay();\n }\n }\n }\n setCursor(pos) {\n if (pos == this.cursorPos)\n return;\n this.cursorPos = pos;\n if (pos == null) {\n this.element.parentNode.removeChild(this.element);\n this.element = null;\n }\n else {\n this.updateOverlay();\n }\n }\n updateOverlay() {\n let $pos = this.editorView.state.doc.resolve(this.cursorPos);\n let isBlock = !$pos.parent.inlineContent, rect;\n let editorDOM = this.editorView.dom, editorRect = editorDOM.getBoundingClientRect();\n let scaleX = editorRect.width / editorDOM.offsetWidth, scaleY = editorRect.height / editorDOM.offsetHeight;\n if (isBlock) {\n let before = $pos.nodeBefore, after = $pos.nodeAfter;\n if (before || after) {\n let node = this.editorView.nodeDOM(this.cursorPos - (before ? before.nodeSize : 0));\n if (node) {\n let nodeRect = node.getBoundingClientRect();\n let top = before ? nodeRect.bottom : nodeRect.top;\n if (before && after)\n top = (top + this.editorView.nodeDOM(this.cursorPos).getBoundingClientRect().top) / 2;\n let halfWidth = (this.width / 2) * scaleY;\n rect = { left: nodeRect.left, right: nodeRect.right, top: top - halfWidth, bottom: top + halfWidth };\n }\n }\n }\n if (!rect) {\n let coords = this.editorView.coordsAtPos(this.cursorPos);\n let halfWidth = (this.width / 2) * scaleX;\n rect = { left: coords.left - halfWidth, right: coords.left + halfWidth, top: coords.top, bottom: coords.bottom };\n }\n let parent = this.editorView.dom.offsetParent;\n if (!this.element) {\n this.element = parent.appendChild(document.createElement(\"div\"));\n if (this.class)\n this.element.className = this.class;\n this.element.style.cssText = \"position: absolute; z-index: 50; pointer-events: none;\";\n if (this.color) {\n this.element.style.backgroundColor = this.color;\n }\n }\n this.element.classList.toggle(\"prosemirror-dropcursor-block\", isBlock);\n this.element.classList.toggle(\"prosemirror-dropcursor-inline\", !isBlock);\n let parentLeft, parentTop;\n if (!parent || parent == document.body && getComputedStyle(parent).position == \"static\") {\n parentLeft = -pageXOffset;\n parentTop = -pageYOffset;\n }\n else {\n let rect = parent.getBoundingClientRect();\n let parentScaleX = rect.width / parent.offsetWidth, parentScaleY = rect.height / parent.offsetHeight;\n parentLeft = rect.left - parent.scrollLeft * parentScaleX;\n parentTop = rect.top - parent.scrollTop * parentScaleY;\n }\n this.element.style.left = (rect.left - parentLeft) / scaleX + \"px\";\n this.element.style.top = (rect.top - parentTop) / scaleY + \"px\";\n this.element.style.width = (rect.right - rect.left) / scaleX + \"px\";\n this.element.style.height = (rect.bottom - rect.top) / scaleY + \"px\";\n }\n scheduleRemoval(timeout) {\n clearTimeout(this.timeout);\n this.timeout = setTimeout(() => this.setCursor(null), timeout);\n }\n computeTarget(event) {\n let pos = this.editorView.posAtCoords({ left: event.clientX, top: event.clientY });\n let node = pos && pos.inside >= 0 && this.editorView.state.doc.nodeAt(pos.inside);\n let disableDropCursor = node && node.type.spec.disableDropCursor;\n let disabled = typeof disableDropCursor == \"function\"\n ? disableDropCursor(this.editorView, pos, event)\n : disableDropCursor;\n if (!pos || disabled)\n return null;\n let target = pos.pos;\n if (this.editorView.dragging && this.editorView.dragging.slice) {\n let point = dropPoint(this.editorView.state.doc, target, this.editorView.dragging.slice);\n if (point != null)\n target = point;\n }\n return target;\n }\n dragover(event) {\n if (!this.editorView.editable)\n return;\n this.lastDragEvent = event;\n let target = this.computeTarget(event);\n if (target != null) {\n this.setCursor(target);\n this.scheduleRemoval(5000);\n }\n }\n dragend() {\n this.scheduleRemoval(20);\n }\n drop() {\n this.scheduleRemoval(20);\n }\n dragleave(event) {\n if (!this.editorView.dom.contains(event.relatedTarget))\n this.setCursor(null);\n }\n}\n\nexport { dropCursor };\n",
26- "import { keydownHandler } from 'prosemirror-keymap';\nimport { Selection, NodeSelection, TextSelection, Plugin } from 'prosemirror-state';\nimport { Slice, Fragment } from 'prosemirror-model';\nimport { DecorationSet, Decoration } from 'prosemirror-view';\n\n/**\nGap cursor selections are represented using this class. Its\n`$anchor` and `$head` properties both point at the cursor position.\n*/\nclass GapCursor extends Selection {\n /**\n Create a gap cursor.\n */\n constructor($pos) {\n super($pos, $pos);\n }\n map(doc, mapping) {\n let $pos = doc.resolve(mapping.map(this.head));\n return GapCursor.valid($pos) ? new GapCursor($pos) : Selection.near($pos);\n }\n content() { return Slice.empty; }\n eq(other) {\n return other instanceof GapCursor && other.head == this.head;\n }\n toJSON() {\n return { type: \"gapcursor\", pos: this.head };\n }\n /**\n @internal\n */\n static fromJSON(doc, json) {\n if (typeof json.pos != \"number\")\n throw new RangeError(\"Invalid input for GapCursor.fromJSON\");\n return new GapCursor(doc.resolve(json.pos));\n }\n /**\n @internal\n */\n getBookmark() { return new GapBookmark(this.anchor); }\n /**\n @internal\n */\n static valid($pos) {\n let parent = $pos.parent;\n if (parent.inlineContent || !closedBefore($pos) || !closedAfter($pos))\n return false;\n let override = parent.type.spec.allowGapCursor;\n if (override != null)\n return override;\n let deflt = parent.contentMatchAt($pos.index()).defaultType;\n return deflt && deflt.isTextblock;\n }\n /**\n @internal\n */\n static findGapCursorFrom($pos, dir, mustMove = false) {\n search: for (;;) {\n if (!mustMove && GapCursor.valid($pos))\n return $pos;\n let pos = $pos.pos, next = null;\n // Scan up from this position\n for (let d = $pos.depth;; d--) {\n let parent = $pos.node(d);\n if (dir > 0 ? $pos.indexAfter(d) < parent.childCount : $pos.index(d) > 0) {\n next = parent.child(dir > 0 ? $pos.indexAfter(d) : $pos.index(d) - 1);\n break;\n }\n else if (d == 0) {\n return null;\n }\n pos += dir;\n let $cur = $pos.doc.resolve(pos);\n if (GapCursor.valid($cur))\n return $cur;\n }\n // And then down into the next node\n for (;;) {\n let inside = dir > 0 ? next.firstChild : next.lastChild;\n if (!inside) {\n if (next.isAtom && !next.isText && !NodeSelection.isSelectable(next)) {\n $pos = $pos.doc.resolve(pos + next.nodeSize * dir);\n mustMove = false;\n continue search;\n }\n break;\n }\n next = inside;\n pos += dir;\n let $cur = $pos.doc.resolve(pos);\n if (GapCursor.valid($cur))\n return $cur;\n }\n return null;\n }\n }\n}\nGapCursor.prototype.visible = false;\nGapCursor.findFrom = GapCursor.findGapCursorFrom;\nSelection.jsonID(\"gapcursor\", GapCursor);\nclass GapBookmark {\n constructor(pos) {\n this.pos = pos;\n }\n map(mapping) {\n return new GapBookmark(mapping.map(this.pos));\n }\n resolve(doc) {\n let $pos = doc.resolve(this.pos);\n return GapCursor.valid($pos) ? new GapCursor($pos) : Selection.near($pos);\n }\n}\nfunction needsGap(type) {\n return type.isAtom || type.spec.isolating || type.spec.createGapCursor;\n}\nfunction closedBefore($pos) {\n for (let d = $pos.depth; d >= 0; d--) {\n let index = $pos.index(d), parent = $pos.node(d);\n // At the start of this parent, look at next one\n if (index == 0) {\n if (parent.type.spec.isolating)\n return true;\n continue;\n }\n // See if the node before (or its first ancestor) is closed\n for (let before = parent.child(index - 1);; before = before.lastChild) {\n if ((before.childCount == 0 && !before.inlineContent) || needsGap(before.type))\n return true;\n if (before.inlineContent)\n return false;\n }\n }\n // Hit start of document\n return true;\n}\nfunction closedAfter($pos) {\n for (let d = $pos.depth; d >= 0; d--) {\n let index = $pos.indexAfter(d), parent = $pos.node(d);\n if (index == parent.childCount) {\n if (parent.type.spec.isolating)\n return true;\n continue;\n }\n for (let after = parent.child(index);; after = after.firstChild) {\n if ((after.childCount == 0 && !after.inlineContent) || needsGap(after.type))\n return true;\n if (after.inlineContent)\n return false;\n }\n }\n return true;\n}\n\n/**\nCreate a gap cursor plugin. When enabled, this will capture clicks\nnear and arrow-key-motion past places that don't have a normally\nselectable position nearby, and create a gap cursor selection for\nthem. The cursor is drawn as an element with class\n`ProseMirror-gapcursor`. You can either include\n`style/gapcursor.css` from the package's directory or add your own\nstyles to make it visible.\n*/\nfunction gapCursor() {\n return new Plugin({\n props: {\n decorations: drawGapCursor,\n createSelectionBetween(_view, $anchor, $head) {\n return $anchor.pos == $head.pos && GapCursor.valid($head) ? new GapCursor($head) : null;\n },\n handleClick,\n handleKeyDown,\n handleDOMEvents: { beforeinput: beforeinput }\n }\n });\n}\nconst handleKeyDown = keydownHandler({\n \"ArrowLeft\": arrow(\"horiz\", -1),\n \"ArrowRight\": arrow(\"horiz\", 1),\n \"ArrowUp\": arrow(\"vert\", -1),\n \"ArrowDown\": arrow(\"vert\", 1)\n});\nfunction arrow(axis, dir) {\n const dirStr = axis == \"vert\" ? (dir > 0 ? \"down\" : \"up\") : (dir > 0 ? \"right\" : \"left\");\n return function (state, dispatch, view) {\n let sel = state.selection;\n let $start = dir > 0 ? sel.$to : sel.$from, mustMove = sel.empty;\n if (sel instanceof TextSelection) {\n if (!view.endOfTextblock(dirStr) || $start.depth == 0)\n return false;\n mustMove = false;\n $start = state.doc.resolve(dir > 0 ? $start.after() : $start.before());\n }\n let $found = GapCursor.findGapCursorFrom($start, dir, mustMove);\n if (!$found)\n return false;\n if (dispatch)\n dispatch(state.tr.setSelection(new GapCursor($found)));\n return true;\n };\n}\nfunction handleClick(view, pos, event) {\n if (!view || !view.editable)\n return false;\n let $pos = view.state.doc.resolve(pos);\n if (!GapCursor.valid($pos))\n return false;\n let clickPos = view.posAtCoords({ left: event.clientX, top: event.clientY });\n if (clickPos && clickPos.inside > -1 && NodeSelection.isSelectable(view.state.doc.nodeAt(clickPos.inside)))\n return false;\n view.dispatch(view.state.tr.setSelection(new GapCursor($pos)));\n return true;\n}\n// This is a hack that, when a composition starts while a gap cursor\n// is active, quickly creates an inline context for the composition to\n// happen in, to avoid it being aborted by the DOM selection being\n// moved into a valid position.\nfunction beforeinput(view, event) {\n if (event.inputType != \"insertCompositionText\" || !(view.state.selection instanceof GapCursor))\n return false;\n let { $from } = view.state.selection;\n let insert = $from.parent.contentMatchAt($from.index()).findWrapping(view.state.schema.nodes.text);\n if (!insert)\n return false;\n let frag = Fragment.empty;\n for (let i = insert.length - 1; i >= 0; i--)\n frag = Fragment.from(insert[i].createAndFill(null, frag));\n let tr = view.state.tr.replace($from.pos, $from.pos, new Slice(frag, 0, 0));\n tr.setSelection(TextSelection.near(tr.doc.resolve($from.pos + 1)));\n view.dispatch(tr);\n return false;\n}\nfunction drawGapCursor(state) {\n if (!(state.selection instanceof GapCursor))\n return null;\n let node = document.createElement(\"div\");\n node.className = \"ProseMirror-gapcursor\";\n return DecorationSet.create(state.doc, [Decoration.widget(state.selection.head, node, { key: \"gapcursor\" })]);\n}\n\nexport { GapCursor, gapCursor };\n",
27- "// Editing behaviour on top of the base schema: block/mark commands, keyboard\n// shortcuts, markdown-style input rules, cursors for gaps and drops, and the\n// empty-note placeholder. The toolbar (toolbar.ts) drives the same commands.\nimport {\n Fragment,\n type Attrs,\n type Mark,\n type MarkType,\n type Node as PMNode,\n type NodeType,\n type Schema,\n} from \"prosemirror-model\";\nimport { Plugin, TextSelection, type Command, type EditorState } from \"prosemirror-state\";\nimport { Decoration, DecorationSet, type EditorView } from \"prosemirror-view\";\nimport { t } from \"./i18n\";\nimport { keymap } from \"prosemirror-keymap\";\nimport { lift, setBlockType, toggleMark, wrapIn } from \"prosemirror-commands\";\nimport { liftListItem, wrapInList } from \"prosemirror-schema-list\";\nimport {\n InputRule,\n inputRules,\n textblockTypeInputRule,\n undoInputRule,\n wrappingInputRule,\n} from \"prosemirror-inputrules\";\nimport { dropCursor } from \"prosemirror-dropcursor\";\nimport { gapCursor } from \"prosemirror-gapcursor\";\n\n/** True when the mark applies at the cursor (stored marks included) or across the selection. */\nexport function isMarkActive(state: EditorState, type: MarkType): boolean {\n const { from, to, empty, $from } = state.selection;\n if (empty) return !!type.isInSet(state.storedMarks || $from.marks());\n return state.doc.rangeHasMark(from, to, type);\n}\n\n/** True when the selection's textblock is of `type` (and matches `attrs`, if given). */\nexport function isBlockActive(state: EditorState, type: NodeType, attrs?: Attrs): boolean {\n const parent = state.selection.$from.parent;\n if (parent.type !== type) return false;\n return !attrs || Object.keys(attrs).every((k) => parent.attrs[k] === attrs[k]);\n}\n\n/** Nearest ancestor of the selection matching `match`, with its document position. */\nexport function findAncestor(\n state: EditorState,\n match: (node: PMNode) => boolean,\n): { node: PMNode; pos: number } | null {\n const { $from } = state.selection;\n for (let d = $from.depth; d > 0; d--) {\n const node = $from.node(d);\n if (match(node)) return { node, pos: $from.before(d) };\n }\n return null;\n}\n\n/**\n * Input rule for inline marks written with delimiters (\"**x**\", \"*x*\", \"`x`\").\n * `pattern` must end with the closing delimiter; capture group 1 is the marked text.\n * The delimiter length is passed explicitly so the text positions are exact.\n */\nfunction markInputRule(pattern: RegExp, markType: MarkType, delimLength: number): InputRule {\n return new InputRule(pattern, (state, match, start, end) => {\n const content = match[1];\n if (!content) return null;\n // Input rules run before the last typed character is inserted, so the closing\n // delimiter is one character short in the doc. Positions come from the match start.\n const textStart = start + match[0].length - delimLength - content.length;\n const textEnd = textStart + content.length;\n const openStart = textStart - delimLength;\n const tr = state.tr;\n tr.delete(textEnd, end);\n tr.delete(openStart, textStart);\n tr.addMark(openStart, openStart + content.length, markType.create());\n tr.removeStoredMark(markType);\n return tr;\n });\n}\n\n/** Range of the mark of `type` that contains `pos` within its textblock, or null. */\nexport function markRangeAt(\n doc: PMNode,\n pos: number,\n type: MarkType,\n): { from: number; to: number; mark: Mark } | null {\n const $pos = doc.resolve(pos);\n if (!$pos.parent.inlineContent) return null;\n const start = $pos.start();\n let found: { from: number; to: number; mark: Mark } | null = null;\n $pos.parent.forEach((child, offset) => {\n if (found) return;\n const from = start + offset;\n const to = from + child.nodeSize;\n const mark = type.isInSet(child.marks);\n if (mark && from <= pos && pos <= to) found = { from, to, mark };\n });\n return found;\n}\n\n/** Accepts plain URLs (adds https://) and http/mailto/relative links; rejects script-like schemes. */\nexport function normalizeHref(raw: string): string | null {\n const href = raw.trim();\n if (!href) return null;\n // Whitespace and control characters are removed before the check, so \"java\\tscript:\" is caught too.\n if (/^(javascript|data|vbscript):/i.test(href.replace(/[\\s\\x00-\\x1f]/g, \"\"))) return null;\n if (/^[a-z][a-z\\d+.-]*:/i.test(href) || href.startsWith(\"/\") || href.startsWith(\"#\")) return href;\n return `https://${href}`;\n}\n\nexport interface Editing {\n /** Keymap, input rules, drop/gap cursors and placeholder. Insert before baseKeymap. */\n plugins: Plugin[];\n paragraph: Command;\n heading(level: number): Command;\n codeBlock: Command;\n bold: Command;\n italic: Command;\n inlineCode: Command;\n link: Command;\n bulletList: Command;\n orderedList: Command;\n blockquote: Command;\n horizontalRule: Command;\n}\n\nexport interface EditingHooks {\n /** Called by Mod-K and the toolbar/bubble link buttons; the floating UI opens the link popover. */\n requestLink(view: EditorView): void;\n}\n\nexport function createEditing(schema: Schema, hooks: EditingHooks): Editing {\n const { paragraph, heading, code_block, blockquote, horizontal_rule, bullet_list, ordered_list, list_item } =\n schema.nodes;\n const { strong, em, code, link: linkMark } = schema.marks;\n\n // Toggling variants: applying the active block type again returns to a paragraph.\n const toParagraph = setBlockType(paragraph);\n const toggleBlock =\n (type: NodeType, attrs?: Attrs): Command =>\n (state, dispatch) =>\n isBlockActive(state, type, attrs)\n ? toParagraph(state, dispatch)\n : setBlockType(type, attrs)(state, dispatch);\n\n const toggleList =\n (type: NodeType): Command =>\n (state, dispatch) => {\n const list = findAncestor(state, (n) => n.type === bullet_list || n.type === ordered_list);\n if (!list) return wrapInList(type)(state, dispatch);\n if (list.node.type === type) return liftListItem(list_item)(state, dispatch);\n // Switching between bullet and ordered: retype the existing list in place.\n if (dispatch) dispatch(state.tr.setNodeMarkup(list.pos, type));\n return true;\n };\n\n const toggleQuote: Command = (state, dispatch) =>\n findAncestor(state, (n) => n.type === blockquote)\n ? lift(state, dispatch)\n : wrapIn(blockquote)(state, dispatch);\n\n // Opens the link popover for a selection, or for the link the cursor is inside.\n const toggleLink: Command = (state, dispatch, view) => {\n const { $from, empty } = state.selection;\n const insideLink = empty && markRangeAt(state.doc, state.selection.from, linkMark) !== null;\n const canLink = !empty && $from.parent.inlineContent && $from.parent.type.allowsMarkType(linkMark);\n if (!insideLink && !canLink) return false;\n if (dispatch && view) hooks.requestLink(view);\n return true;\n };\n\n const insertRule: Command = (state, dispatch) => {\n const { $from } = state.selection;\n if ($from.parent.type.spec.code) return false;\n if (!dispatch) return true;\n const tr = state.tr.replaceSelectionWith(horizontal_rule.create());\n if (!tr.selection.$from.parent.inlineContent) {\n // Keep a text position after a trailing rule so the user can keep typing.\n const pos = tr.selection.from;\n tr.insert(pos, paragraph.create());\n tr.setSelection(TextSelection.create(tr.doc, pos + 1));\n }\n dispatch(tr.scrollIntoView());\n return true;\n };\n\n // \"---\" on its own line becomes a rule followed by an empty paragraph.\n const hrRule = new InputRule(/^---$/, (state, _match, start, end) => {\n const $start = state.doc.resolve(start);\n const depth = $start.depth;\n if (depth < 1 || $start.parent.type.spec.code) return null;\n const index = $start.index(depth - 1);\n const parent = $start.node(depth - 1);\n const replacement = Fragment.from([horizontal_rule.create(), paragraph.create()]);\n if (!parent.canReplace(index, index + 1, replacement)) return null;\n const before = $start.before();\n const tr = state.tr.replaceWith(before, $start.after(), [horizontal_rule.create(), paragraph.create()]);\n tr.setSelection(TextSelection.create(tr.doc, before + horizontal_rule.create().nodeSize + 1));\n return tr;\n });\n\n // Ctrl/Cmd+Shift+V pastes plain text. The keydown sets a short-lived flag, and the paste\n // event the browser fires next reads it. Normal paste keeps basic structure and drops styling.\n let plainPasteUntil = 0;\n const paste = new Plugin({\n props: {\n transformPastedHTML(html) {\n return html.replace(/\\s(?:style|class)\\s*=\\s*(\"[^\"]*\"|'[^']*')/gi, \"\");\n },\n handleKeyDown(_view, event) {\n if ((event.metaKey || event.ctrlKey) && event.shiftKey && event.key.toLowerCase() === \"v\") {\n plainPasteUntil = Date.now() + 1000;\n }\n return false;\n },\n handlePaste(view, event) {\n if (Date.now() > plainPasteUntil) return false;\n plainPasteUntil = 0;\n const text = event.clipboardData?.getData(\"text/plain\");\n if (!text) return false;\n view.pasteText(text);\n return true;\n },\n },\n });\n\n const keys = keymap({\n \"Mod-Alt-0\": toParagraph,\n \"Mod-Alt-1\": toggleBlock(heading, { level: 1 }),\n \"Mod-Alt-2\": toggleBlock(heading, { level: 2 }),\n \"Mod-Alt-3\": toggleBlock(heading, { level: 3 }),\n \"Mod-Shift-8\": toggleList(bullet_list),\n \"Mod-Shift-9\": toggleList(ordered_list),\n \"Mod-k\": toggleLink,\n \"Mod-e\": toggleMark(code),\n Backspace: undoInputRule,\n });\n\n const rules = inputRules({\n rules: [\n textblockTypeInputRule(/^(#{1,3})\\s$/, heading, (m) => ({ level: m[1].length })),\n textblockTypeInputRule(/^```$/, code_block),\n wrappingInputRule(/^\\s*([-*])\\s$/, bullet_list),\n wrappingInputRule(\n /^(\\d+)\\.\\s$/,\n ordered_list,\n (m) => ({ order: Number(m[1]) }),\n (m, node) => node.childCount + node.attrs.order === Number(m[1]),\n ),\n wrappingInputRule(/^\\s*>\\s$/, blockquote),\n markInputRule(/\\*\\*([^*]+)\\*\\*$/, strong, 2),\n markInputRule(/(?:^|[^*])\\*([^*]+)\\*$/, em, 1),\n markInputRule(/`([^`]+)`$/, code, 1),\n hrRule,\n ],\n });\n\n // Shown only while the whole note is one empty paragraph.\n const placeholder = new Plugin({\n props: {\n decorations(state) {\n const { doc } = state;\n const first = doc.firstChild;\n if (doc.childCount !== 1 || !first || first.type !== paragraph || first.content.size > 0) return null;\n return DecorationSet.create(doc, [\n Decoration.node(0, first.nodeSize, {\n class: \"is-placeholder\",\n \"data-placeholder\": t(\"placeholder\"),\n }),\n ]);\n },\n },\n });\n\n return {\n plugins: [\n paste,\n keys,\n rules,\n dropCursor({ color: \"var(--primary)\", width: 2 }),\n gapCursor(),\n placeholder,\n ],\n paragraph: toParagraph,\n heading: (level) => toggleBlock(heading, { level }),\n codeBlock: toggleBlock(code_block),\n bold: toggleMark(strong),\n italic: toggleMark(em),\n inlineCode: toggleMark(code),\n link: toggleLink,\n bulletList: toggleList(bullet_list),\n orderedList: toggleList(ordered_list),\n blockquote: toggleQuote,\n horizontalRule: insertRule,\n };\n}\n",
28- "// Shared DOM helpers for the editor chrome: element builder, keycaps, tooltips and\n// viewport positioning for floating surfaces (position: fixed, from coordsAtPos).\nimport type { EditorView } from \"prosemirror-view\";\n\nexport const isMac = /Mac|iPhone|iPad|iPod/.test(navigator.platform || navigator.userAgent);\nexport const MOD = isMac ? \"⌘\" : \"Ctrl\";\nexport const SHIFT = isMac ? \"⇧\" : \"Shift\";\nexport const ALT = isMac ? \"⌥\" : \"Alt\";\n\n/** Creates an element with string attributes and children. Only pass trusted literals as text. */\nexport function h<K extends keyof HTMLElementTagNameMap>(\n tag: K,\n attrs: Record<string, string> = {},\n ...kids: (Node | string)[]\n): HTMLElementTagNameMap[K] {\n const node = document.createElement(tag);\n for (const [name, value] of Object.entries(attrs)) node.setAttribute(name, value);\n node.append(...kids);\n return node;\n}\n\n/** Mono keycap chips, e.g. keycaps(\"Ctrl\", \"K\"). Decorative: screen readers get aria-keyshortcuts elsewhere. */\nexport function keycaps(...keys: string[]): HTMLSpanElement {\n return h(\n \"span\",\n { class: \"keycaps\", \"aria-hidden\": \"true\" },\n ...keys.map((key) => h(\"kbd\", { class: \"keycap\" }, key)),\n );\n}\n\n/** Tooltip shown on hover/focus of its parent button: label, keycaps, optional reason. */\nexport function tooltip(label: string, keys: string[], reason?: string): HTMLSpanElement {\n const children: (Node | string)[] = [h(\"span\", { class: \"tip-label\" }, label)];\n if (keys.length) children.push(keycaps(...keys));\n if (reason) children.push(h(\"span\", { class: \"tip-reason\" }, reason));\n return h(\"span\", { class: \"tip\", \"aria-hidden\": \"true\", role: \"presentation\" }, ...children);\n}\n\nexport interface Box {\n top: number;\n bottom: number;\n left: number;\n right: number;\n}\n\n/** Viewport box around the text between two positions (spans lines when needed). */\nexport function rangeBox(view: EditorView, from: number, to: number): Box {\n const a = view.coordsAtPos(from);\n const b = view.coordsAtPos(to);\n return {\n top: Math.min(a.top, b.top),\n bottom: Math.max(a.bottom, b.bottom),\n left: Math.min(a.left, b.left),\n right: Math.max(a.right, b.right),\n };\n}\n\nconst GAP = 8;\n\n/**\n * Positions a fixed element next to a box, centred horizontally and clamped to the\n * viewport. \"above\" flips below when there is no room; \"below\" flips above at the bottom.\n */\nexport function placeFloating(el: HTMLElement, box: Box, prefer: \"above\" | \"below\"): void {\n const width = el.offsetWidth;\n const height = el.offsetHeight;\n const above = box.top - height - GAP;\n const below = box.bottom + GAP;\n let top: number;\n if (prefer === \"above\") top = above >= GAP ? above : below;\n else top = below + height <= window.innerHeight - GAP ? below : above;\n const center = (box.left + box.right) / 2;\n const left = Math.min(Math.max(center - width / 2, GAP), window.innerWidth - width - GAP);\n el.style.top = `${Math.max(top, GAP)}px`;\n el.style.left = `${Math.max(left, GAP)}px`;\n}\n",
29- "// Note-to-note links. Typing \"[[\" opens a suggestion menu of note titles. Picking one (or\n// \"Create note\") replaces \"[[query\" with the title as a link mark whose href is /notes/<id>.\n// The menu reuses the slash menu's classes and keyboard model so it looks and behaves the same.\nimport type { MarkType, Schema } from \"prosemirror-model\";\nimport { Plugin, TextSelection, type EditorState } from \"prosemirror-state\";\nimport type { EditorView } from \"prosemirror-view\";\nimport { t } from \"./i18n\";\nimport { h, keycaps, placeFloating, rangeBox } from \"./dom\";\n\ninterface NoteHit {\n id: string;\n title: string;\n}\n\ntype Item = { kind: \"note\"; hit: NoteHit } | { kind: \"create\"; title: string };\n\n/** \"[[\" trigger: `from` is the position of the first bracket, `query` the text after it. */\ninterface Trigger {\n from: number;\n query: string;\n}\n\nconst SEARCH_DEBOUNCE_MS = 120;\n\nexport interface NoteLinks {\n plugins: Plugin[];\n}\n\nexport function isNoteHref(href: string | null | undefined): boolean {\n return !!href && href.startsWith(\"/notes/\");\n}\n\n/** The \"[[query\" right before the cursor, when the cursor is in a textblock outside code. */\nfunction triggerAt(state: EditorState, code: MarkType): Trigger | null {\n const { selection } = state;\n if (!(selection instanceof TextSelection) || !selection.empty) return null;\n const $from = selection.$from;\n if (!$from.parent.isTextblock || $from.parent.type.spec.code) return null;\n if (code.isInSet(state.storedMarks || $from.marks())) return null;\n const before = $from.parent.textBetween(0, $from.parentOffset, undefined, \"\\n\");\n // A closing \"]]\" or a stray bracket ends the match, so the menu closes on its own.\n const match = /\\[\\[([^\\[\\]\\n]*)$/.exec(before);\n if (!match) return null;\n return { from: $from.pos - match[0].length, query: match[1] };\n}\n\nfunction parseHits(data: unknown): NoteHit[] {\n if (!Array.isArray(data)) return [];\n return data.filter(\n (x): x is NoteHit =>\n typeof x === \"object\" && x !== null && typeof x.id === \"string\" && typeof x.title === \"string\",\n );\n}\n\nasync function createNote(title: string): Promise<string> {\n const res = await fetch(\"/notes/quick\", { method: \"POST\", body: new URLSearchParams({ title }) });\n if (!res.ok) throw new Error(`quick ${res.status}`);\n const id = (await res.text()).trim();\n if (!id) throw new Error(\"empty note id\");\n return id;\n}\n\nexport function createNoteLinks(schema: Schema, opts: { currentNoteId: string }): NoteLinks {\n const linkMark = schema.marks.link;\n const codeMark = schema.marks.code;\n const currentId = opts.currentNoteId;\n\n let view: EditorView | null = null;\n let active: Trigger | null = null;\n let dismissedFrom: number | null = null;\n let results: NoteHit[] = [];\n let loaded = false;\n let items: Item[] = [];\n let index = 0;\n let busy = false;\n let fetchTimer: ReturnType<typeof setTimeout> | undefined;\n let controller: AbortController | null = null;\n\n const menu = h(\"div\", { class: \"popover slash-menu note-menu\", role: \"presentation\" });\n menu.hidden = true;\n const list = h(\"div\", { class: \"slash-list\", role: \"listbox\", \"aria-label\": t(\"noteMenu\") });\n const footer = h(\n \"div\",\n { class: \"slash-footer\", \"aria-hidden\": \"true\" },\n keycaps(\"↑\", \"↓\"),\n ` ${t(\"navigate\")} `,\n keycaps(\"↵\"),\n ` ${t(\"insert\")} `,\n keycaps(\"Esc\"),\n ` ${t(\"close\")}`,\n );\n menu.append(list, footer);\n // Keep focus in the editor while clicking menu items.\n menu.addEventListener(\"mousedown\", (e) => e.preventDefault());\n\n function itemText(item: Item): string {\n if (item.kind === \"create\") return item.title;\n return item.hit.title.trim() || t(\"untitled\");\n }\n\n function itemLabel(item: Item): string {\n return item.kind === \"create\" ? t(\"createNote\", { q: item.title }) : itemText(item);\n }\n\n function buildItems(query: string): Item[] {\n const list: Item[] = results.map((hit): Item => ({ kind: \"note\", hit }));\n const q = query.trim();\n const exact = results.some((hit) => hit.title.trim().toLowerCase() === q.toLowerCase());\n if (q && !exact) list.push({ kind: \"create\", title: q });\n return list;\n }\n\n function abortFetch() {\n clearTimeout(fetchTimer);\n controller?.abort();\n controller = null;\n }\n\n function close() {\n abortFetch();\n active = null;\n items = [];\n results = [];\n loaded = false;\n index = 0;\n menu.hidden = true;\n view?.dom.removeAttribute(\"aria-activedescendant\");\n }\n\n async function search(query: string) {\n const ctrl = new AbortController();\n controller = ctrl;\n try {\n const res = await fetch(`/notes/titles.json?q=${encodeURIComponent(query)}`, {\n signal: ctrl.signal,\n headers: { accept: \"application/json\" },\n });\n if (!res.ok) throw new Error(`titles ${res.status}`);\n const data: unknown = await res.json();\n if (ctrl.signal.aborted) return;\n results = parseHits(data).filter((hit) => hit.id !== currentId);\n } catch (err) {\n if (ctrl.signal.aborted) return;\n console.error(\"note search failed\", err);\n results = [];\n }\n if (controller === ctrl) controller = null;\n loaded = true;\n renderList();\n }\n\n function scheduleSearch(query: string) {\n abortFetch();\n loaded = false;\n fetchTimer = setTimeout(() => void search(query), SEARCH_DEBOUNCE_MS);\n }\n\n function markActive() {\n if (!view) return;\n const rows = list.querySelectorAll<HTMLElement>(\".slash-item\");\n rows.forEach((row, i) => row.setAttribute(\"aria-selected\", String(i === index)));\n const row = rows[index];\n if (row) {\n view.dom.setAttribute(\"aria-activedescendant\", row.id);\n row.scrollIntoView({ block: \"nearest\" });\n }\n }\n\n function setIndex(i: number) {\n index = i;\n markActive();\n }\n\n function renderList() {\n if (!view || !active) return;\n items = buildItems(active.query);\n if (index >= items.length) index = 0;\n if (items.length === 0) {\n // Only shown once the search for this query has answered; an empty query with no notes lands here.\n list.replaceChildren(\n ...(loaded ? [h(\"div\", { class: \"slash-empty\", role: \"presentation\" }, t(\"noNotesFound\"))] : []),\n );\n view.dom.removeAttribute(\"aria-activedescendant\");\n return;\n }\n list.replaceChildren(\n ...items.map((item, i) => {\n const el = h(\n \"div\",\n { class: \"slash-item\", role: \"option\", id: `note-opt-${i}`, \"aria-selected\": String(i === index) },\n h(\"span\", { class: \"slash-label\" }, itemLabel(item)),\n );\n el.addEventListener(\"mouseenter\", () => setIndex(i));\n el.addEventListener(\"click\", () => pick(item));\n return el;\n }),\n );\n markActive();\n }\n\n function place(v: EditorView) {\n if (!active) return;\n placeFloating(menu, rangeBox(v, active.from, v.state.selection.from), \"below\");\n }\n\n /** Replaces [from, to) with the link text, a plain space, and the cursor after it. One transaction. */\n function insertLink(v: EditorView, from: number, to: number, text: string, id: string) {\n const tr = v.state.tr.replaceWith(from, to, schema.text(text, [linkMark.create({ href: `/notes/${id}` })]));\n const end = from + text.length;\n tr.insert(end, schema.text(\" \"));\n tr.setSelection(TextSelection.create(tr.doc, end + 1));\n tr.setStoredMarks([]);\n v.dispatch(tr.scrollIntoView());\n v.focus();\n }\n\n async function createAndInsert(v: EditorView, from: number, to: number, title: string) {\n // The range as it reads now; if the user edits it while the request runs, nothing is inserted.\n const before = v.state.doc.textBetween(from, to);\n busy = true;\n let id: string;\n try {\n id = await createNote(title);\n } catch (err) {\n console.error(\"note create failed\", err);\n return;\n } finally {\n busy = false;\n }\n const cur = view;\n if (!cur) return;\n const sel = cur.state.selection;\n if (!sel.empty || sel.from !== to || cur.state.doc.textBetween(from, to) !== before) return;\n insertLink(cur, from, to, title, id);\n }\n\n function pick(item: Item) {\n const v = view;\n if (!v || !active || busy) return;\n const { from } = active;\n const to = v.state.selection.from;\n if (item.kind === \"note\") {\n insertLink(v, from, to, itemText(item), item.hit.id);\n return;\n }\n void createAndInsert(v, from, to, item.title);\n }\n\n /** Opens, refetches or closes the menu from the current selection. */\n function sync(v: EditorView) {\n view = v;\n const trig = triggerAt(v.state, codeMark);\n if (!trig) {\n dismissedFrom = null;\n close();\n return;\n }\n if (trig.from === dismissedFrom) {\n close();\n return;\n }\n const changed = !active || trig.from !== active.from || trig.query !== active.query;\n active = trig;\n if (changed) {\n index = 0;\n scheduleSearch(trig.query);\n }\n menu.hidden = false;\n if (changed) renderList();\n place(v);\n }\n\n const plugin = new Plugin({\n props: {\n handleKeyDown(v, e) {\n if (!active) return false;\n const n = items.length;\n if (e.key === \"Escape\") {\n dismissedFrom = active.from;\n close();\n return true;\n }\n if (e.key === \"ArrowDown\" && n) {\n setIndex((index + 1) % n);\n return true;\n }\n if (e.key === \"ArrowUp\" && n) {\n setIndex((index - 1 + n) % n);\n return true;\n }\n if ((e.key === \"Enter\" || e.key === \"Tab\") && n) {\n if (!busy) pick(items[index]);\n return true;\n }\n return false;\n },\n // Ctrl/Cmd+click on a note link opens the note in this tab.\n handleDOMEvents: {\n click(_view, event) {\n if (!(event.ctrlKey || event.metaKey)) return false;\n const anchor = (event.target as Element | null)?.closest?.(\"a\");\n const href = anchor?.getAttribute(\"href\");\n if (!href || !isNoteHref(href)) return false;\n event.preventDefault();\n location.assign(href);\n return true;\n },\n },\n },\n view(v) {\n view = v;\n document.body.append(menu);\n const onViewport = () => {\n if (view) place(view);\n };\n window.addEventListener(\"scroll\", onViewport, { capture: true, passive: true });\n window.addEventListener(\"resize\", onViewport);\n return {\n update(u) {\n sync(u);\n },\n destroy() {\n window.removeEventListener(\"scroll\", onViewport, { capture: true });\n window.removeEventListener(\"resize\", onViewport);\n abortFetch();\n menu.remove();\n view = null;\n },\n };\n },\n });\n\n return { plugins: [plugin] };\n}\n",
30- "// Floating editor UI, all plain DOM on <body> and positioned from view.coordsAtPos:\n// - selection bubble menu (formatting, shown for a non-empty text selection),\n// - link popover (edit mode for Mod-K / buttons, view mode when a link is clicked),\n// - slash menu (typing \"/\" at the start of a block or after a space).\n// One ProseMirror plugin keeps them in sync with the editor state.\nimport type { MarkType, Schema } from \"prosemirror-model\";\nimport { Plugin, TextSelection, type Command, type EditorState } from \"prosemirror-state\";\nimport type { EditorView } from \"prosemirror-view\";\nimport { t } from \"./i18n\";\nimport { isBlockActive, isMarkActive, markRangeAt, normalizeHref, type Editing } from \"./editing\";\nimport { ALT, MOD, SHIFT, h, keycaps, placeFloating, rangeBox, tooltip } from \"./dom\";\nimport { isNoteHref } from \"./noteLinks\";\n\ninterface BubbleItem {\n id: string;\n label: string;\n glyph: string;\n keys: string[];\n run: Command;\n active: (state: EditorState) => boolean;\n}\n\ninterface SlashItem {\n id: string;\n label: string;\n /** English words the filter also matches, so \"h2\" or \"list\" work in either language. */\n keywords: string;\n keys: string[];\n run: Command;\n}\n\nexport interface Floating {\n plugins: Plugin[];\n /** Opens the link popover for the selection, or for the link the cursor is in. */\n openLink(view: EditorView): void;\n}\n\ninterface LinkState {\n from: number;\n to: number;\n mode: \"edit\" | \"view\";\n /** Existing href at the range, if any. */\n href: string | null;\n}\n\n/** Position of an open \"/query\" trigger and what has been typed after the slash. */\nfunction slashContext(state: EditorState): { from: number; query: string } | null {\n const { selection } = state;\n if (!(selection instanceof TextSelection) || !selection.empty) return null;\n const $from = selection.$from;\n if (!$from.parent.isTextblock || $from.parent.type.spec.code) return null;\n const before = $from.parent.textBetween(0, $from.parentOffset, undefined, \"\\n\");\n const match = /(?:^|\\s)\\/([^\\s/]*)$/.exec(before);\n if (!match) return null;\n return { from: $from.pos - match[1].length - 1, query: match[1] };\n}\n\nfunction hrefInRange(state: EditorState, from: number, to: number, type: MarkType): string | null {\n let href: string | null = null;\n state.doc.nodesBetween(from, to, (node) => {\n if (href !== null) return false;\n const mark = type.isInSet(node.marks);\n if (mark) href = String(mark.attrs.href);\n return href === null;\n });\n return href;\n}\n\nexport function createFloating(schema: Schema, editing: Editing): Floating {\n const { strong, em, code, link: linkMark } = schema.marks;\n const { heading } = schema.nodes;\n\n let view: EditorView | null = null;\n let bubbleDismissed = false;\n let link: LinkState | null = null;\n let slashFrom: number | null = null;\n let slashQuery = \"\";\n let slashIndex = 0;\n let slashFiltered: SlashItem[] = [];\n let slashDismissed: number | null = null;\n\n // ---- Bubble menu ----\n const bubbleItems: BubbleItem[] = [\n { id: \"bold\", label: t(\"bold\"), glyph: \"B\", keys: [MOD, \"B\"], run: editing.bold, active: (s) => isMarkActive(s, strong) },\n { id: \"italic\", label: t(\"italic\"), glyph: \"I\", keys: [MOD, \"I\"], run: editing.italic, active: (s) => isMarkActive(s, em) },\n { id: \"code\", label: t(\"inlineCode\"), glyph: \"</>\", keys: [MOD, \"E\"], run: editing.inlineCode, active: (s) => isMarkActive(s, code) },\n { id: \"link\", label: t(\"link\"), glyph: \"Link\", keys: [MOD, \"K\"], run: editing.link, active: (s) => isMarkActive(s, linkMark) },\n { id: \"h1\", label: t(\"heading1\"), glyph: \"H1\", keys: [MOD, ALT, \"1\"], run: editing.heading(1), active: (s) => isBlockActive(s, heading, { level: 1 }) },\n { id: \"h2\", label: t(\"heading2\"), glyph: \"H2\", keys: [MOD, ALT, \"2\"], run: editing.heading(2), active: (s) => isBlockActive(s, heading, { level: 2 }) },\n { id: \"h3\", label: t(\"heading3\"), glyph: \"H3\", keys: [MOD, ALT, \"3\"], run: editing.heading(3), active: (s) => isBlockActive(s, heading, { level: 3 }) },\n ];\n\n const bubble = h(\"div\", { class: \"bubble\", role: \"toolbar\", \"aria-label\": t(\"bubbleLabel\") });\n bubble.hidden = true;\n const bubbleButtons = bubbleItems.map((item) => {\n const btn = h(\n \"button\",\n { type: \"button\", class: \"bubble-btn\", \"aria-label\": item.label, \"data-command\": item.id },\n h(\"span\", { class: \"bubble-glyph\", \"aria-hidden\": \"true\" }, item.glyph),\n tooltip(item.label, item.keys),\n );\n btn.addEventListener(\"click\", () => {\n if (!view) return;\n item.run(view.state, view.dispatch, view);\n if (item.id !== \"link\") view.focus();\n });\n bubble.append(btn);\n return { btn, item };\n });\n // Keep the text selection while pressing bubble buttons.\n bubble.addEventListener(\"mousedown\", (e) => e.preventDefault());\n\n // ---- Link popover (edit and view panels share one element) ----\n const linkPop = h(\"div\", { class: \"popover link-popover\", role: \"dialog\", \"aria-label\": t(\"linkDialog\") });\n linkPop.hidden = true;\n\n const editPanel = h(\"form\", { class: \"link-edit\", novalidate: \"\" });\n const linkInput = h(\"input\", {\n type: \"text\",\n class: \"link-input\",\n inputmode: \"url\",\n autocomplete: \"off\",\n autocapitalize: \"off\",\n spellcheck: \"false\",\n placeholder: \"https://\",\n \"aria-label\": t(\"linkUrl\"),\n \"aria-describedby\": \"link-error\",\n });\n const linkError = h(\"p\", { class: \"link-error\", id: \"link-error\", role: \"alert\" });\n linkError.hidden = true;\n const applyBtn = h(\"button\", { type: \"submit\", class: \"btn btn-primary\" }, t(\"apply\"), keycaps(\"↵\"));\n const editRemove = h(\"button\", { type: \"button\", class: \"btn\" }, t(\"remove\"));\n const editOpen = h(\"button\", { type: \"button\", class: \"btn\" }, t(\"open\"));\n editPanel.append(\n h(\"div\", { class: \"link-row\" }, linkInput, applyBtn),\n linkError,\n h(\"div\", { class: \"link-actions\" }, editRemove, editOpen),\n );\n\n // View mode is a small menu: href as its label, then Edit / Remove / Open as menu items.\n const viewPanel = h(\"div\", { class: \"link-view\", role: \"menu\", \"aria-label\": t(\"linkMenu\") });\n const linkHref = h(\"span\", { class: \"link-href\" });\n const viewEdit = h(\"button\", { type: \"button\", class: \"btn\", role: \"menuitem\" }, t(\"edit\"));\n const viewRemove = h(\"button\", { type: \"button\", class: \"btn\", role: \"menuitem\" }, t(\"remove\"));\n const viewOpen = h(\"button\", { type: \"button\", class: \"btn\", role: \"menuitem\" }, t(\"open\"));\n viewPanel.append(linkHref, h(\"div\", { class: \"link-actions\", role: \"none\" }, viewEdit, viewRemove, viewOpen));\n\n linkPop.append(editPanel, viewPanel);\n\n function closeLink(restoreFocus: boolean) {\n if (!link) return;\n link = null;\n linkPop.hidden = true;\n if (restoreFocus) view?.focus();\n }\n\n function showLink(v: EditorView, from: number, to: number, mode: \"edit\" | \"view\") {\n closeSlash();\n const href = hrefInRange(v.state, from, to, linkMark);\n link = { from, to, mode, href };\n linkPop.hidden = false;\n editPanel.hidden = mode !== \"edit\";\n viewPanel.hidden = mode !== \"view\";\n linkError.hidden = true;\n linkInput.removeAttribute(\"aria-invalid\");\n linkInput.value = href ?? \"\";\n linkHref.textContent = href ?? \"\";\n for (const btn of [editRemove, editOpen, viewRemove, viewOpen]) {\n btn.disabled = href === null;\n btn.title = href === null ? t(\"linkNeedsLink\") : \"\";\n }\n renderFloating(v);\n if (mode === \"edit\") {\n linkInput.focus();\n linkInput.select();\n } else {\n viewEdit.focus();\n }\n }\n\n function openLink(v: EditorView) {\n const sel = v.state.selection;\n const range = sel.empty ? markRangeAt(v.state.doc, sel.from, linkMark) : { from: sel.from, to: sel.to };\n if (!range) return;\n showLink(v, range.from, range.to, \"edit\");\n }\n\n editPanel.addEventListener(\"submit\", (e) => {\n e.preventDefault();\n if (!link || !view) return;\n const href = normalizeHref(linkInput.value);\n if (!href) {\n linkError.textContent = t(\"linkInvalid\");\n linkError.hidden = false;\n linkInput.setAttribute(\"aria-invalid\", \"true\");\n linkInput.focus();\n return;\n }\n const { from, to } = link;\n closeLink(false);\n view.dispatch(view.state.tr.removeMark(from, to, linkMark).addMark(from, to, linkMark.create({ href })));\n view.focus();\n });\n\n function removeLink() {\n if (!link || !view) return;\n const { from, to } = link;\n closeLink(false);\n view.dispatch(view.state.tr.removeMark(from, to, linkMark));\n view.focus();\n }\n\n function openHref() {\n if (!link?.href) return;\n // Note links open in this tab; external links keep opening in a new one.\n if (isNoteHref(link.href)) {\n location.assign(link.href);\n return;\n }\n window.open(link.href, \"_blank\", \"noopener,noreferrer\");\n }\n\n editRemove.addEventListener(\"click\", removeLink);\n viewRemove.addEventListener(\"click\", removeLink);\n editOpen.addEventListener(\"click\", openHref);\n viewOpen.addEventListener(\"click\", openHref);\n viewEdit.addEventListener(\"click\", () => {\n if (view && link) showLink(view, link.from, link.to, \"edit\");\n });\n\n linkPop.addEventListener(\"keydown\", (e) => {\n if (e.key === \"Escape\") {\n e.preventDefault();\n e.stopPropagation();\n closeLink(true);\n return;\n }\n // Arrow keys move between the menu items in view mode.\n if ((e.key === \"ArrowDown\" || e.key === \"ArrowUp\") && !viewPanel.hidden) {\n const items = [viewEdit, viewRemove, viewOpen].filter((b) => !b.disabled);\n const index = items.indexOf(document.activeElement as HTMLButtonElement);\n const step = e.key === \"ArrowDown\" ? 1 : -1;\n const next = items[(index + step + items.length) % items.length];\n if (next) {\n e.preventDefault();\n next.focus();\n }\n }\n });\n\n // ---- Slash menu ----\n const slashItems: SlashItem[] = [\n { id: \"text\", label: t(\"paragraph\"), keywords: \"text paragraph p\", keys: [MOD, ALT, \"0\"], run: editing.paragraph },\n { id: \"h1\", label: t(\"heading1\"), keywords: \"heading title h1\", keys: [MOD, ALT, \"1\"], run: editing.heading(1) },\n { id: \"h2\", label: t(\"heading2\"), keywords: \"heading subtitle h2\", keys: [MOD, ALT, \"2\"], run: editing.heading(2) },\n { id: \"h3\", label: t(\"heading3\"), keywords: \"heading h3\", keys: [MOD, ALT, \"3\"], run: editing.heading(3) },\n { id: \"bullets\", label: t(\"bulletList\"), keywords: \"list ul bullet unordered\", keys: [MOD, SHIFT, \"8\"], run: editing.bulletList },\n { id: \"ordered\", label: t(\"numberedList\"), keywords: \"list ol number ordered\", keys: [MOD, SHIFT, \"9\"], run: editing.orderedList },\n { id: \"quote\", label: t(\"quote\"), keywords: \"blockquote quote\", keys: [\">\"], run: editing.blockquote },\n { id: \"codeblock\", label: t(\"codeBlock\"), keywords: \"code pre fence\", keys: [\"```\"], run: editing.codeBlock },\n { id: \"divider\", label: t(\"divider\"), keywords: \"hr rule line divider\", keys: [\"---\"], run: editing.horizontalRule },\n ];\n\n const slashMenu = h(\"div\", { class: \"popover slash-menu\", role: \"presentation\" });\n slashMenu.hidden = true;\n const slashList = h(\"div\", { class: \"slash-list\", role: \"listbox\", \"aria-label\": t(\"blockMenu\") });\n const slashFooter = h(\n \"div\",\n { class: \"slash-footer\", \"aria-hidden\": \"true\" },\n keycaps(\"↑\", \"↓\"),\n ` ${t(\"navigate\")} `,\n keycaps(\"↵\"),\n ` ${t(\"insert\")} `,\n keycaps(\"Esc\"),\n ` ${t(\"close\")}`,\n );\n slashMenu.append(slashList, slashFooter);\n // Keep focus in the editor while clicking menu items.\n slashMenu.addEventListener(\"mousedown\", (e) => e.preventDefault());\n\n function closeSlash() {\n slashFrom = null;\n slashMenu.hidden = true;\n view?.dom.removeAttribute(\"aria-activedescendant\");\n }\n\n function renderSlash() {\n if (!view || slashFrom === null) return;\n const q = slashQuery.toLowerCase();\n slashFiltered = slashItems.filter(\n (item) => !q || item.label.toLowerCase().includes(q) || item.keywords.split(\" \").some((w) => w.startsWith(q)),\n );\n if (slashIndex >= slashFiltered.length) slashIndex = 0;\n if (slashFiltered.length === 0) {\n slashList.replaceChildren(h(\"div\", { class: \"slash-empty\", role: \"presentation\" }, t(\"noMatches\")));\n view.dom.removeAttribute(\"aria-activedescendant\");\n return;\n }\n slashList.replaceChildren(\n ...slashFiltered.map((item, i) => {\n const el = h(\n \"div\",\n { class: \"slash-item\", role: \"option\", id: `slash-opt-${item.id}`, \"aria-selected\": String(i === slashIndex) },\n h(\"span\", { class: \"slash-label\" }, item.label),\n keycaps(...item.keys),\n );\n el.addEventListener(\"click\", () => applySlash(item));\n return el;\n }),\n );\n const active = slashFiltered[slashIndex];\n view.dom.setAttribute(\"aria-activedescendant\", `slash-opt-${active.id}`);\n slashList.querySelector<HTMLElement>(`#slash-opt-${active.id}`)?.scrollIntoView({ block: \"nearest\" });\n }\n\n function applySlash(item: SlashItem) {\n const v = view;\n if (!v || slashFrom === null) return;\n const from = slashFrom;\n const to = v.state.selection.from;\n closeSlash();\n v.dispatch(v.state.tr.delete(from, to));\n item.run(v.state, v.dispatch, v);\n v.focus();\n }\n\n /** Opens, filters or closes the slash menu from the current selection. */\n function syncSlash(v: EditorView) {\n const ctx = slashContext(v.state);\n if (!ctx) {\n slashDismissed = null;\n closeSlash();\n return;\n }\n if (ctx.from === slashDismissed || link) {\n closeSlash();\n return;\n }\n if (ctx.from !== slashFrom || ctx.query !== slashQuery) slashIndex = 0;\n slashFrom = ctx.from;\n slashQuery = ctx.query;\n slashMenu.hidden = false;\n renderSlash();\n }\n\n // ---- Positioning and visibility ----\n function bubbleVisible(v: EditorView): boolean {\n const sel = v.state.selection;\n return sel instanceof TextSelection && !sel.empty && !v.composing && !bubbleDismissed && link === null;\n }\n\n function renderFloating(v: EditorView) {\n view = v;\n const state = v.state;\n const show = bubbleVisible(v);\n bubble.hidden = !show;\n if (show) {\n for (const { btn, item } of bubbleButtons) {\n const on = item.active(state);\n btn.dataset.active = String(on);\n btn.setAttribute(\"aria-pressed\", String(on));\n btn.disabled = !item.run(state);\n }\n placeFloating(bubble, rangeBox(v, state.selection.from, state.selection.to), \"above\");\n }\n if (link) {\n placeFloating(linkPop, rangeBox(v, link.from, link.to), \"above\");\n }\n if (slashFrom !== null && !slashMenu.hidden) {\n placeFloating(slashMenu, rangeBox(v, slashFrom, state.selection.from), \"below\");\n }\n }\n\n // ---- Keyboard and mouse ----\n const plugin = new Plugin({\n props: {\n handleKeyDown(v, e) {\n if (slashFrom !== null) {\n const n = slashFiltered.length;\n if (e.key === \"ArrowDown\" && n) {\n slashIndex = (slashIndex + 1) % n;\n renderSlash();\n return true;\n }\n if (e.key === \"ArrowUp\" && n) {\n slashIndex = (slashIndex - 1 + n) % n;\n renderSlash();\n return true;\n }\n if (e.key === \"Enter\" && n) {\n applySlash(slashFiltered[slashIndex]);\n return true;\n }\n if (e.key === \"Escape\") {\n slashDismissed = slashFrom;\n closeSlash();\n return true;\n }\n }\n if (e.key === \"Escape\" && bubbleVisible(v)) {\n bubbleDismissed = true;\n renderFloating(v);\n return true;\n }\n return false;\n },\n handleClick(v, pos, event) {\n const target = event.target as Element | null;\n const anchor = target?.closest?.(\"a\");\n if (!anchor) return false;\n // Ctrl/Cmd+click navigates to a note (noteLinks.ts), so no popover opens for it.\n if ((event.ctrlKey || event.metaKey) && isNoteHref(anchor.getAttribute(\"href\"))) return false;\n const range = markRangeAt(v.state.doc, pos, linkMark);\n if (range) showLink(v, range.from, range.to, \"view\");\n return false;\n },\n },\n view(v) {\n view = v;\n document.body.append(bubble, linkPop, slashMenu);\n const onViewport = () => {\n if (view) renderFloating(view);\n };\n const onOutsideDown = (e: MouseEvent) => {\n if (link && !linkPop.contains(e.target as Node)) closeLink(false);\n };\n window.addEventListener(\"scroll\", onViewport, { capture: true, passive: true });\n window.addEventListener(\"resize\", onViewport);\n document.addEventListener(\"mousedown\", onOutsideDown, true);\n renderFloating(v);\n return {\n update(u, prev) {\n if (!prev.selection.eq(u.state.selection)) bubbleDismissed = false;\n // A popover refers to a fixed range; remote or local edits invalidate it.\n if (link && u.state.doc !== prev.doc) closeLink(false);\n syncSlash(u);\n renderFloating(u);\n },\n destroy() {\n window.removeEventListener(\"scroll\", onViewport, { capture: true });\n window.removeEventListener(\"resize\", onViewport);\n document.removeEventListener(\"mousedown\", onOutsideDown, true);\n bubble.remove();\n linkPop.remove();\n slashMenu.remove();\n view = null;\n },\n };\n },\n });\n\n return { plugins: [plugin], openLink };\n}\n",
31- "// Formatting toolbar: plain DOM, rendered once. A ProseMirror plugin view keeps the\n// active/disabled state of every button in sync with the editor. Icons only, with\n// keycap tooltips; roving tabindex so the bar is one Tab stop.\nimport type { Schema } from \"prosemirror-model\";\nimport { Plugin, type Command, type EditorState } from \"prosemirror-state\";\nimport type { EditorView } from \"prosemirror-view\";\nimport { findAncestor, isBlockActive, isMarkActive, type Editing } from \"./editing\";\nimport { t } from \"./i18n\";\nimport { ALT, MOD, SHIFT, h, tooltip } from \"./dom\";\n\n\n// Lucide-style glyphs (24x24, stroke based). Static strings, safe for innerHTML.\nconst ICONS = {\n undo: '<path d=\"M9 14 4 9l5-5\"/><path d=\"M4 9h10.5a5.5 5.5 0 0 1 0 11H11\"/>',\n redo: '<path d=\"m15 14 5-5-5-5\"/><path d=\"M20 9H9.5a5.5 5.5 0 0 0 0 11H13\"/>',\n paragraph: '<path d=\"M13 4v16\"/><path d=\"M17 4v16\"/><path d=\"M19 4H9.5a4.5 4.5 0 0 0 0 9H13\"/>',\n h1: '<path d=\"M4 12h8\"/><path d=\"M4 18V6\"/><path d=\"M12 18V6\"/><path d=\"m17 12 3-2v8\"/>',\n 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\"/>',\n 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\"/>',\n 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\"/>',\n 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\"/>',\n code: '<polyline points=\"16 18 22 12 16 6\"/><polyline points=\"8 6 2 12 8 18\"/>',\n 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\"/>',\n bullets:\n '<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\"/>',\n ordered:\n '<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\"/>',\n quote: '<path d=\"M17 6H3\"/><path d=\"M21 12H8\"/><path d=\"M21 18H8\"/><path d=\"M3 12v6\"/>',\n 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\"/>',\n rule: '<line x1=\"5\" x2=\"19\" y1=\"12\" y2=\"12\"/>',\n} as const;\n\ninterface Item {\n id: string;\n label: string;\n keys: string[];\n icon: string;\n run: Command;\n /** Present for toggles: drives aria-pressed and the active look. */\n isActive?: (state: EditorState) => boolean;\n}\n\ntype Entry = Item | \"|\";\n\nfunction buildItems(schema: Schema, editing: Editing, history: { undo: Command; redo: Command }): Entry[] {\n const { paragraph, heading, code_block, blockquote, bullet_list, ordered_list } = schema.nodes;\n const { strong, em, code, link } = schema.marks;\n const headingItem = (level: 1 | 2 | 3): Item => ({\n id: `h${level}`,\n label: t(`heading${level}` as \"heading1\"),\n keys: [MOD, ALT, String(level)],\n icon: level === 1 ? ICONS.h1 : level === 2 ? ICONS.h2 : ICONS.h3,\n run: editing.heading(level),\n isActive: (s) => isBlockActive(s, heading, { level }),\n });\n const inList = (type: typeof bullet_list) => (s: EditorState) => findAncestor(s, (n) => n.type === type) !== null;\n\n return [\n { id: \"undo\", label: t(\"undo\"), keys: [MOD, \"Z\"], icon: ICONS.undo, run: history.undo },\n { id: \"redo\", label: t(\"redo\"), keys: [MOD, SHIFT, \"Z\"], icon: ICONS.redo, run: history.redo },\n \"|\",\n {\n id: \"paragraph\",\n label: t(\"paragraph\"),\n keys: [MOD, ALT, \"0\"],\n icon: ICONS.paragraph,\n run: editing.paragraph,\n isActive: (s) => isBlockActive(s, paragraph),\n },\n headingItem(1),\n headingItem(2),\n headingItem(3),\n \"|\",\n {\n id: \"bold\",\n label: t(\"bold\"),\n keys: [MOD, \"B\"],\n icon: ICONS.bold,\n run: editing.bold,\n isActive: (s) => isMarkActive(s, strong),\n },\n {\n id: \"italic\",\n label: t(\"italic\"),\n keys: [MOD, \"I\"],\n icon: ICONS.italic,\n run: editing.italic,\n isActive: (s) => isMarkActive(s, em),\n },\n {\n id: \"code\",\n label: t(\"inlineCode\"),\n keys: [MOD, \"E\"],\n icon: ICONS.code,\n run: editing.inlineCode,\n isActive: (s) => isMarkActive(s, code),\n },\n {\n id: \"link\",\n label: t(\"link\"),\n keys: [MOD, \"K\"],\n icon: ICONS.link,\n run: editing.link,\n isActive: (s) => isMarkActive(s, link),\n },\n \"|\",\n {\n id: \"bullets\",\n label: t(\"bulletList\"),\n keys: [MOD, SHIFT, \"8\"],\n icon: ICONS.bullets,\n run: editing.bulletList,\n isActive: inList(bullet_list),\n },\n {\n id: \"ordered\",\n label: t(\"numberedList\"),\n keys: [MOD, SHIFT, \"9\"],\n icon: ICONS.ordered,\n run: editing.orderedList,\n isActive: inList(ordered_list),\n },\n {\n id: \"quote\",\n label: t(\"quote\"),\n keys: [\">\"],\n icon: ICONS.quote,\n run: editing.blockquote,\n isActive: (s) => findAncestor(s, (n) => n.type === blockquote) !== null,\n },\n {\n id: \"codeblock\",\n label: t(\"codeBlock\"),\n keys: [\"```\"],\n icon: ICONS.codeBlock,\n run: editing.codeBlock,\n isActive: (s) => isBlockActive(s, code_block),\n },\n {\n id: \"rule\",\n label: t(\"divider\"),\n keys: [\"---\"],\n icon: ICONS.rule,\n run: editing.horizontalRule,\n },\n ];\n}\n\n// data-group names, in order: one per run of buttons between the separators of buildItems.\nconst GROUP_NAMES = [\"history\", \"headings\", \"marks\", \"blocks\"] as const;\n\n/**\n * Creates the toolbar DOM (into #editor-toolbar, or just before `mount`) and returns\n * the ProseMirror plugin that drives it. Buttons stay disabled until the view exists.\n */\nexport function createToolbar(\n mount: HTMLElement,\n schema: Schema,\n editing: Editing,\n history: { undo: Command; redo: Command },\n): Plugin {\n let el = document.getElementById(\"editor-toolbar\");\n if (!el) {\n el = document.createElement(\"div\");\n el.id = \"editor-toolbar\";\n mount.before(el);\n }\n el.classList.add(\"editor-toolbar\");\n el.setAttribute(\"role\", \"toolbar\");\n el.setAttribute(\"aria-label\", t(\"toolbarLabel\"));\n\n let current: EditorView | null = null;\n const buttons: { btn: HTMLButtonElement; item: Item; enabled: boolean }[] = [];\n\n // Each run of buttons between separators is a group; CSS hides low-priority groups\n // and draws the dividers between them (see editor.css, container queries).\n let group = h(\"div\", { class: \"editor-toolbar-group\", \"data-group\": GROUP_NAMES[0] });\n el.append(group);\n let groupIndex = 0;\n\n for (const entry of buildItems(schema, editing, history)) {\n if (entry === \"|\") {\n groupIndex += 1;\n group = h(\"div\", { class: \"editor-toolbar-group\", \"data-group\": GROUP_NAMES[groupIndex] });\n el.append(group);\n continue;\n }\n const btn = h(\n \"button\",\n {\n type: \"button\",\n class: \"editor-toolbar-btn\",\n \"aria-label\": entry.label,\n \"aria-keyshortcuts\": ariaKeys(entry.keys),\n \"data-command\": entry.id,\n tabindex: \"-1\",\n },\n h(\"span\", { class: \"editor-toolbar-icon\", \"aria-hidden\": \"true\" }),\n tooltip(entry.label, entry.keys, t(\"unavailable\")),\n );\n // Static icon paths only (see ICONS above).\n 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>`;\n btn.disabled = true;\n btn.addEventListener(\"click\", () => {\n if (!current) return;\n entry.run(current.state, current.dispatch, current);\n current.focus();\n });\n group.append(btn);\n buttons.push({ btn, item: entry, enabled: false });\n }\n\n // Keep the editor's selection and focus when pressing toolbar buttons.\n el.addEventListener(\"mousedown\", (e) => e.preventDefault());\n\n // Roving tabindex: arrows, Home and End move among enabled buttons.\n const enabledButtons = () => buttons.map((b) => b.btn).filter((b) => !b.disabled);\n const setStop = (target: HTMLButtonElement) => {\n for (const { btn } of buttons) btn.tabIndex = btn === target ? 0 : -1;\n };\n el.addEventListener(\"keydown\", (e) => {\n const list = enabledButtons();\n if (!list.length) return;\n const index = list.indexOf(document.activeElement as HTMLButtonElement);\n let next: HTMLButtonElement | undefined;\n if (e.key === \"ArrowRight\") next = list[(index + 1 + list.length) % list.length];\n else if (e.key === \"ArrowLeft\") next = list[(index - 1 + list.length) % list.length];\n else if (e.key === \"Home\") next = list[0];\n else if (e.key === \"End\") next = list[list.length - 1];\n if (!next) return;\n e.preventDefault();\n setStop(next);\n next.focus();\n });\n\n const sync = (state: EditorState) => {\n for (const entry of buttons) {\n // Commands without a dispatch only report whether they would apply.\n entry.enabled = !!entry.item.run(state);\n entry.btn.disabled = !entry.enabled;\n if (entry.item.isActive) {\n const active = entry.item.isActive(state);\n entry.btn.dataset.active = String(active);\n entry.btn.setAttribute(\"aria-pressed\", String(active));\n }\n }\n // Keep one enabled button in the tab order, preferring the last one focused.\n const stop = buttons.find((b) => b.btn.tabIndex === 0 && !b.btn.disabled)?.btn ?? enabledButtons()[0];\n if (stop) setStop(stop);\n };\n\n return new Plugin({\n view(view) {\n current = view;\n sync(view.state);\n return {\n update(v) {\n sync(v.state);\n },\n destroy() {\n current = null;\n },\n };\n },\n });\n}\n\n/** Keyboard shortcut in aria-keyshortcuts form, e.g. \"Control+B\" or \"Meta+Shift+8\". */\nfunction ariaKeys(keys: string[]): string {\n const names: Record<string, string> = {\n Ctrl: \"Control\",\n \"⌘\": \"Meta\",\n Shift: \"Shift\",\n \"⇧\": \"Shift\",\n Alt: \"Alt\",\n \"⌥\": \"Alt\",\n };\n return keys.map((k) => names[k] ?? k).join(\"+\");\n}\n",
32- "// \"loro-crdt/web\" is the entry build.ts bundles for every \"loro-crdt\" import. Its init is the\n// default export of loro_wasm.js, the module web/index.js re-exports, so there is one WASM instance.\nimport { LoroDoc, VersionVector } from \"loro-crdt/web\";\nimport init from \"loro-crdt/web/loro_wasm.js\";\nimport {\n CursorEphemeralStore,\n LoroEphemeralCursorPlugin,\n LoroSyncPlugin,\n LoroUndoPlugin,\n redo,\n undo,\n} from \"loro-prosemirror\";\nimport type { CursorUser, LoroDocType } from \"loro-prosemirror\";\nimport { Schema, type NodeSpec } from \"prosemirror-model\";\nimport { EditorState } from \"prosemirror-state\";\nimport { EditorView } from \"prosemirror-view\";\nimport { schema as basicSchema } from \"prosemirror-schema-basic\";\nimport {\n addListNodes,\n liftListItem,\n sinkListItem,\n splitListItem,\n} from \"prosemirror-schema-list\";\nimport { keymap } from \"prosemirror-keymap\";\nimport { baseKeymap, toggleMark } from \"prosemirror-commands\";\nimport { createEditing } from \"./editing\";\nimport { createFloating } from \"./floating\";\nimport { createNoteLinks } from \"./noteLinks\";\nimport { createToolbar } from \"./toolbar\";\nimport { h } from \"./dom\";\nimport { t, type Key } from \"./i18n\";\n\n// Replaced at build time with the content-hashed name of the WASM file in assets/.\ndeclare const __LORO_WASM_NAME__: string;\n\n// The WASM ships as its own file so browsers can stream-compile and cache it. It must be\n// initialized before the first LoroDoc or ephemeral store exists.\nawait init({ module_or_path: new URL(`/${__LORO_WASM_NAME__}`, location.origin) });\n\n// ---- Wire protocol (must match the Rust server) ----\nconst TAG_SYNC_REQ = 0x01;\nconst TAG_UPDATE = 0x02;\nconst TAG_EPHEMERAL = 0x03;\n\n// ---- Schema: basic nodes/marks + lists ----\n// Code blocks keep the fence language (```rust) so markdown round-trips.\nconst codeBlock: NodeSpec = {\n ...basicSchema.spec.nodes.get(\"code_block\")!,\n attrs: { language: { default: null } },\n parseDOM: [\n {\n tag: \"pre\",\n preserveWhitespace: \"full\",\n getAttrs: (dom) => ({ language: (dom as HTMLElement).dataset.language || null }),\n },\n ],\n toDOM: (node) => [\n \"pre\",\n node.attrs.language ? { \"data-language\": node.attrs.language } : {},\n [\"code\", 0],\n ],\n};\n\nconst schema = new Schema({\n nodes: addListNodes(\n basicSchema.spec.nodes.update(\"code_block\", codeBlock),\n \"paragraph block*\",\n \"block\",\n ),\n marks: basicSchema.spec.marks,\n});\n\n// ---- Per-tab peer identity for cursors ----\nfunction peerIdentity(): CursorUser {\n const key = \"project-note-peer\";\n let stored: CursorUser | null = null;\n try {\n const raw = sessionStorage.getItem(key);\n if (raw) stored = JSON.parse(raw) as CursorUser;\n } catch {\n stored = null;\n }\n if (!stored) {\n const n = 1000 + Math.floor(Math.random() * 9000);\n const hue = Math.floor(Math.random() * 360);\n stored = { name: `user-${n}`, color: `hsl(${hue} 70% 45%)` };\n try {\n sessionStorage.setItem(key, JSON.stringify(stored));\n } catch {\n // sessionStorage unavailable: identity just lasts for this load\n }\n }\n return stored;\n}\n\n// ---- Document, presence, editor ----\nconst mount = document.getElementById(\"editor\");\nif (!mount) throw new Error(\"#editor element not found\");\nconst noteId = mount.dataset.noteId ?? \"\";\nconst noteTitle =\n mount.dataset.noteTitle?.trim() ||\n document.querySelector<HTMLElement>(\"header span.truncate\")?.textContent?.trim() ||\n \"Note\";\n\nconst doc = new LoroDoc() as unknown as LoroDocType;\nconst user = peerIdentity();\nconst presence = new CursorEphemeralStore((doc as unknown as LoroDoc).peerIdStr);\n\nconst statusEl = ensureStatusElement(mount);\nconst liveEl = ensureLiveRegion();\n\n// Remote selections are tinted with the peer's color instead of loro's default yellow.\nfunction peerSelection(peer: string) {\n const all = presence.getAll() as Record<string, { user?: { color?: string } } | undefined>;\n const color = all[peer]?.user?.color ?? \"currentColor\";\n return {\n class: \"loro-selection\",\n \"data-peer\": peer,\n style: `background-color: color-mix(in srgb, ${color} 28%, transparent)`,\n };\n}\n\n// Link commands open the floating popover; the floating UI is created right after.\nconst editing = createEditing(schema, { requestLink: (v) => floating.openLink(v) });\nconst floating = createFloating(schema, editing);\nconst toolbarPlugin = createToolbar(mount, schema, editing, { undo, redo });\n\nconst noteLinks = createNoteLinks(schema, { currentNoteId: noteId });\n\nconst listKeys = keymap({\n Enter: splitListItem(schema.nodes.list_item),\n Tab: sinkListItem(schema.nodes.list_item),\n \"Shift-Tab\": liftListItem(schema.nodes.list_item),\n \"Mod-b\": toggleMark(schema.marks.strong),\n \"Mod-i\": toggleMark(schema.marks.em),\n \"Mod-`\": toggleMark(schema.marks.code),\n});\n\nconst state = EditorState.create({\n schema,\n plugins: [\n LoroSyncPlugin({ doc }),\n LoroUndoPlugin({ doc }),\n keymap({\n \"Mod-z\": undo,\n \"Mod-y\": redo,\n \"Shift-Mod-z\": redo,\n }),\n ...floating.plugins,\n ...noteLinks.plugins,\n listKeys,\n ...editing.plugins,\n keymap(baseKeymap),\n toolbarPlugin,\n LoroEphemeralCursorPlugin(presence, { user, createSelection: peerSelection }),\n ],\n});\n\n// The editor is created only after the server's state is imported. Creating it on an\n// empty doc makes loro-prosemirror write a fresh root that competes with the real one.\nlet view: EditorView | null = null;\nlet serverVersion: VersionVector | null = null;\n\nfunction maybeCreateEditor() {\n if (view || !serverVersion) return;\n const ours = (doc as unknown as LoroDoc).oplogVersion();\n const cmp = serverVersion.compare(ours);\n if (cmp === undefined || cmp > 0) return;\n view = new EditorView(mount!, {\n state,\n attributes: {\n role: \"textbox\",\n \"aria-multiline\": \"true\",\n \"aria-label\": noteTitle,\n },\n });\n}\n\n// ---- Transport ----\nconst url = `${location.protocol === \"https:\" ? \"wss\" : \"ws\"}://${location.host}/notes/${encodeURIComponent(noteId)}/ws`;\nconst BASE_DELAY = 500;\nconst MAX_DELAY = 5000;\nlet socket: WebSocket | null = null;\nlet retryDelay = BASE_DELAY;\n// False until this connection has sent our offline changes. Presence refers to\n// containers inside the doc, so it must not reach peers before those changes do.\nlet presenceReady = false;\n\nfunction frame(tag: number, payload: Uint8Array): Uint8Array<ArrayBuffer> {\n const out = new Uint8Array(payload.length + 1);\n out[0] = tag;\n out.set(payload, 1);\n return out;\n}\n\nfunction isOpen(): boolean {\n return socket !== null && socket.readyState === WebSocket.OPEN;\n}\n\nfunction send(tag: number, payload: Uint8Array) {\n if (isOpen()) socket!.send(frame(tag, payload));\n}\n\n// ---- Sync status ----\n// \"Saving…\" is shown only when local changes stay unsent for more than 1.5s. A change is\n// confirmed sent once the socket's buffer is empty and 300ms have passed without edits.\ntype SyncState = \"connecting\" | \"reconnecting\" | \"saved\" | \"saving\" | \"local\";\nconst STATUS_KEY: Record<SyncState, Key> = {\n connecting: \"statusConnecting\",\n reconnecting: \"statusReconnecting\",\n saved: \"statusSaved\",\n saving: \"statusSaving\",\n local: \"statusLocal\",\n};\n\nlet connected = false;\nlet everConnected = false;\nlet dirty = false;\nlet savingShown = false;\nlet savingTimer: ReturnType<typeof setTimeout> | undefined;\nlet flushTimer: ReturnType<typeof setTimeout> | undefined;\n\nfunction currentSyncState(): SyncState {\n if (navigator.onLine === false) return \"local\";\n if (!connected) return everConnected ? \"reconnecting\" : \"connecting\";\n return savingShown ? \"saving\" : \"saved\";\n}\n\nfunction renderStatus() {\n const syncState = currentSyncState();\n statusEl.dataset.state = syncState;\n statusEl.textContent = t(STATUS_KEY[syncState]);\n}\n\nfunction markLocalChange() {\n if (!dirty) {\n dirty = true;\n clearTimeout(savingTimer);\n savingTimer = setTimeout(() => {\n if (dirty) {\n savingShown = true;\n renderStatus();\n }\n }, 1500);\n }\n clearTimeout(flushTimer);\n flushTimer = setTimeout(checkFlushed, 300);\n}\n\nfunction checkFlushed() {\n if (!dirty) return;\n if (isOpen() && socket!.bufferedAmount > 0) {\n flushTimer = setTimeout(checkFlushed, 100);\n return;\n }\n dirty = false;\n clearTimeout(savingTimer);\n savingShown = false;\n renderStatus();\n}\n\nfunction setConnected(value: boolean) {\n connected = value;\n if (value) everConnected = true;\n renderStatus();\n}\n\n// The pill lives in the note header's #sync-slot (right side, next to the actions menu).\nfunction ensureStatusElement(anchor: HTMLElement): HTMLElement {\n let el = document.getElementById(\"sync-status\");\n if (!el) {\n el = document.createElement(\"span\");\n el.id = \"sync-status\";\n const slot = document.getElementById(\"sync-slot\");\n if (slot) slot.append(el);\n else anchor.before(el);\n }\n return el;\n}\n\n// Visually hidden; only offline/online transitions are announced.\nfunction ensureLiveRegion(): HTMLElement {\n const el = h(\"div\", { class: \"sr-only\", role: \"status\", \"aria-live\": \"polite\" });\n document.body.append(el);\n return el;\n}\n\nfunction announce(message: string) {\n liveEl.textContent = message;\n}\n\nwindow.addEventListener(\"offline\", () => {\n renderStatus();\n announce(t(\"announceOffline\"));\n});\nwindow.addEventListener(\"online\", () => {\n renderStatus();\n announce(t(\"announceOnline\"));\n});\n\n// Local doc changes: only sent while the socket is open.\n// Offline changes are delivered by the SYNC_REQ handshake on reconnect.\n(doc as unknown as LoroDoc).subscribeLocalUpdates((bytes: Uint8Array) => {\n send(TAG_UPDATE, bytes);\n markLocalChange();\n});\n\n// Local presence changes: sent while open.\npresence.subscribeLocalUpdates((bytes: Uint8Array) => {\n if (presenceReady) send(TAG_EPHEMERAL, bytes);\n});\n\nfunction handleMessage(data: ArrayBuffer | string) {\n if (typeof data === \"string\") return;\n const bytes = new Uint8Array(data);\n if (bytes.length === 0) return;\n const tag = bytes[0];\n const payload = bytes.subarray(1);\n switch (tag) {\n case TAG_SYNC_REQ: {\n // Peer asks for what we have beyond its version: reply with an update.\n const from = VersionVector.decode(payload);\n const update = (doc as unknown as LoroDoc).export({ mode: \"update\", from });\n send(TAG_UPDATE, update);\n if (!presenceReady) {\n presenceReady = true;\n send(TAG_EPHEMERAL, presence.encodeAll());\n }\n if (!serverVersion) {\n serverVersion = from;\n maybeCreateEditor();\n }\n break;\n }\n case TAG_UPDATE:\n try {\n (doc as unknown as LoroDoc).import(payload);\n maybeCreateEditor();\n } catch (err) {\n console.error(\"failed to import update\", err);\n }\n break;\n case TAG_EPHEMERAL:\n try {\n presence.apply(payload);\n } catch (err) {\n console.error(\"failed to apply presence\", err);\n }\n break;\n default:\n console.warn(\"unknown frame tag\", tag);\n }\n}\n\nfunction connect() {\n const ws = new WebSocket(url);\n ws.binaryType = \"arraybuffer\";\n socket = ws;\n\n ws.onopen = () => {\n retryDelay = BASE_DELAY;\n setConnected(true);\n // Handshake: ask the server for what we are missing.\n presenceReady = false;\n send(TAG_SYNC_REQ, (doc as unknown as LoroDoc).oplogVersion().encode());\n };\n\n ws.onmessage = (ev: MessageEvent) => handleMessage(ev.data);\n\n ws.onerror = () => {\n ws.close();\n };\n\n ws.onclose = () => {\n if (socket === ws) socket = null;\n if (detached) return;\n setConnected(false);\n setTimeout(connect, retryDelay);\n retryDelay = Math.min(retryDelay * 2, MAX_DELAY);\n };\n}\n\n// Live search swaps the page content without a reload; it fires `note:detach` first so\n// this editor closes its socket instead of syncing a note that is no longer on screen.\nlet detached = false;\nwindow.addEventListener(\"note:detach\", () => {\n detached = true;\n socket?.close();\n view?.destroy();\n view = null;\n});\n\nrenderStatus();\nconnect();\n"
33- ],
34- "mappings": "AACA,IAAM,GAAQ,CAAC,MAAO,OAAQ,cAAe,OAAQ,OAAQ,SAAS,EAC/D,SAAS,EAAY,CAAC,EAAS,EAAU,CAC9C,GAAI,OAAO,IAAY,UAAY,IAAY,MAAQ,MAAM,QAAQ,CAAO,EAAG,MAAU,MAAM,iCAAiC,EAChI,QAAW,KAAO,OAAO,KAAK,CAAO,EACnC,GAAI,IAAQ,QAAU,EAAE,GAAY,IAAQ,SAAU,MAAU,MAAM,mCAAqC,CAAG,EAEhH,GAAI,GAAY,EAAQ,QAAU,QAAa,CAAC,MAAM,QAAQ,EAAQ,KAAK,EAAG,MAAU,MAAM,wBAAwB,EACtH,OAAO,EAEF,SAAS,EAAU,CAAC,EAAM,EAAO,EAAa,CAAE,MAAO,CAAC,IAAI,EAAK,IAAK,QAAO,cAAa,MAAM,EAAK,KAAK,EAC1G,SAAS,EAAc,CAAC,EAAM,EAAK,EAAO,CAAE,MAAO,CAAC,KAAM,GAAM,GAAO,MAAK,OAAK,EACjF,SAAS,EAAQ,CAAC,EAAK,EAAQ,EAAM,CAAE,MAAO,OAAO,E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AO,iBAAiB,cAAe,IAAM,CAC3C,GAAW,GACX,IAAQ,MAAM,EACd,IAAM,QAAQ,EACd,GAAO,KACR,EAED,GAAa,EACb,GAAQ",
35- "debugId": "0E2F6C17ACB8E4C864756E2164756E21",
36- "names": []
37-}
\ No newline at end of file\ No newline at end of file
assets/loro-856987111b05.wasmdeleted+0 -0

Binary file changed

build.rsmodified+2 -0
@@ -1,4 +1,6 @@
1 fn main() {1 fn main() {
2+ println!("cargo:rerun-if-changed=styles.css");
3+ println!("cargo:rerun-if-changed=src");
2 topcoat::tailwind::BuildConfig::new()4 topcoat::tailwind::BuildConfig::new()
3 .input("styles.css")5 .input("styles.css")
4 .render()6 .render()
crates/editor/Cargo.tomladded+108 -0
@@ -0,0 +1,108 @@
1+[package]
2+name = "editor"
3+version = "0.1.0"
4+edition = "2024"
5+publish = false
6+
7+[lib]
8+crate-type = ["cdylib", "rlib"]
9+
10+[dependencies]
11+loro = "1.17.1"
12+note-model = { path = "../note-model" }
13+wasm-bindgen = "0.2.129"
14+js-sys = "0.3"
15+wasm-bindgen-futures = "0.4"
16+web-sys = { version = "0.3", features = [
17+ "AbortController",
18+ "AbortSignal",
19+ "AddEventListenerOptions",
20+ "BinaryType",
21+ "Clipboard",
22+ "ClipboardEvent",
23+ "CompositionEvent",
24+ "CustomEvent",
25+ "CustomEventInit",
26+ "console",
27+ "CssStyleDeclaration",
28+ "DataTransfer",
29+ "Document",
30+ "DomParser",
31+ "DomRect",
32+ "DomRectList",
33+ "DomTokenList",
34+ "Element",
35+ "Event",
36+ "EventTarget",
37+ "FocusEvent",
38+ "Headers",
39+ "HtmlCollection",
40+ "HtmlElement",
41+ "HtmlMediaElement",
42+ "HtmlFormElement",
43+ "HtmlSelectElement",
44+ "HtmlInputElement",
45+ "InputEvent",
46+ "IntersectionObserver",
47+ "IntersectionObserverEntry",
48+ "IntersectionObserverInit",
49+ "KeyboardEvent",
50+ "Location",
51+ "MessageEvent",
52+ "MouseEvent",
53+ "MutationObserver",
54+ "MutationObserverInit",
55+ "MutationRecord",
56+ "Navigator",
57+ "Node",
58+ "NodeList",
59+ "Performance",
60+ "Range",
61+ "Request",
62+ "RequestInit",
63+ "Response",
64+ "Selection",
65+ "StaticRange",
66+ "AbstractRange",
67+ "Storage",
68+ "SupportedType",
69+ "Text",
70+ "CharacterData",
71+ "UrlSearchParams",
72+ "WebSocket",
73+ "Window",
74+ "HtmlButtonElement",
75+ "HtmlAnchorElement",
76+ "HtmlLiElement",
77+ "HtmlUListElement",
78+ "HtmlImageElement",
79+ "HtmlDivElement",
80+ "HtmlSpanElement",
81+ "ScrollIntoViewOptions",
82+ "ScrollLogicalPosition",
83+ "DomStringMap",
84+ "FormData",
85+ "PointerEvent",
86+ "Url",
87+ "ResizeObserver",
88+ "ResizeObserverEntry",
89+ "DragEvent",
90+ "DocumentFragment",
91+ "HtmlTemplateElement",
92+ "Blob",
93+ "BlobEvent",
94+ "BlobPropertyBag",
95+ "BeforeUnloadEvent",
96+ "File",
97+ "FileList",
98+ "MediaDevices",
99+ "MediaRecorder",
100+ "MediaRecorderOptions",
101+ "MediaStream",
102+ "MediaStreamConstraints",
103+ "MediaStreamTrack",
104+ "ReadableStream",
105+] }
106+
107+[lints]
108+workspace = true
crates/editor/src/core/commands.rsadded+1390 -0
@@ -0,0 +1,1390 @@
1+//! Editing commands over the flat body ([`note_model::flat`]): the keymap semantics of
2+//! prosemirror-commands / prosemirror-schema-list and the app's toggles, as edits of
3+//! text, separators and the wrap paths separators carry.
4+//!
5+//! Structure is relative: a block shares [`keep`] levels with the block before it
6+//! (whole containers, and for a list the item), then opens the rest. Commands change
7+//! wraps and keeps of a block range and restore the keep of the block after it, so
8+//! nothing outside the range moves.
9+//!
10+//! A command takes the context and `apply`. With `apply == false` it only reports
11+//! whether it would do something and must not edit (toolbar state). With `apply` it
12+//! edits through the model's primitives and sets `cx.sel`.
13+
14+use note_model::flat::{self, Attrs, FlatBlock, Kind as Leaf, Wrap, default_join};
15+use note_model::write::{Block, Inline};
16+
17+use loro::{LoroValue, TextDelta};
18+
19+use super::doc::Kind;
20+use super::marks::{Link, MarkType, Marks};
21+use super::model::{Blk, INLINE, Model, Seg};
22+use super::pos::{self, Pos, Selection};
23+
24+pub struct Cx<'a> {
25+ pub m: &'a Model,
26+ pub sel: Selection,
27+ /// Marks for the next typed text at a collapsed cursor (PM stored marks).
28+ pub stored: Option<Marks>,
29+}
30+
31+pub type Command = fn(&mut Cx, bool) -> bool;
32+
33+impl<'a> Cx<'a> {
34+ pub fn new(m: &'a Model, sel: Selection) -> Self {
35+ Self { m, sel, stored: None }
36+ }
37+
38+ fn set_caret(&mut self, p: Pos) {
39+ self.sel = Selection::caret(p);
40+ self.stored = None;
41+ }
42+
43+ /// The caret's block and offset when the selection is a collapsed caret in text.
44+ fn caret(&self) -> Option<(Blk, Pos)> {
45+ let p = self.sel.cursor()?;
46+ let b = self.m.at(p);
47+ b.kind().is_text().then_some((b, p))
48+ }
49+
50+ /// The block holding the selection head.
51+ pub fn head_block(&self) -> Option<Blk> {
52+ self.sel.head().map(|h| self.m.at(h))
53+ }
54+}
55+
56+/// Runs the first command that applies.
57+pub fn chain(cx: &mut Cx, cmds: &[Command], apply: bool) -> bool {
58+ cmds.iter().any(|c| c(cx, apply))
59+}
60+
61+// ---------------------------------------------------------------------------
62+// Structure
63+// ---------------------------------------------------------------------------
64+
65+fn common(a: &[Wrap], b: &[Wrap]) -> usize {
66+ a.iter().zip(b).take_while(|(x, y)| x == y).count()
67+}
68+
69+/// Levels `cur` shares with `prev`: whole containers, and at a list level the item.
70+pub fn keep(prev: Option<&Attrs>, cur: &Attrs) -> usize {
71+ let Some(p) = prev else { return 0 };
72+ cur.join.unwrap_or_else(|| default_join(&p.wrap, &cur.wrap)).min(common(&p.wrap, &cur.wrap))
73+}
74+
75+/// The `join` that gives a block with `wrap` keep `k` after `prev`.
76+fn join_for(prev: Option<&Attrs>, wrap: &[Wrap], k: usize) -> Option<usize> {
77+ let p = prev?;
78+ let k = k.min(common(&p.wrap, wrap));
79+ (k != default_join(&p.wrap, wrap)).then_some(k)
80+}
81+
82+fn prev_of(m: &Model, b: &Blk) -> Option<Blk> {
83+ b.index.checked_sub(1).and_then(|i| m.block(i))
84+}
85+
86+fn keep_of(m: &Model, b: &Blk) -> usize {
87+ keep(prev_of(m, b).as_ref().map(|p| &p.attrs), &b.attrs)
88+}
89+
90+/// The keep of the block after `b`, if any.
91+fn next_keep(m: &Model, b: &Blk) -> Option<usize> {
92+ m.block(b.index + 1).map(|n| keep(Some(&b.attrs), &n.attrs))
93+}
94+
95+/// Rewrites blocks `lo..`: each entry's attributes, its join from the wanted keep
96+/// (None: as given). Then gives the following block keep `next` (its old keep).
97+fn relink(m: &Model, lo: usize, new: Vec<(Attrs, Option<usize>)>, next: Option<usize>) {
98+ let mut prev = lo.checked_sub(1).and_then(|i| m.block(i)).map(|b| b.attrs);
99+ let mut out = Vec::with_capacity(new.len() + 1);
100+ for (mut a, k) in new {
101+ if let Some(k) = k {
102+ a.join = join_for(prev.as_ref(), &a.wrap, k);
103+ }
104+ prev = Some(a.clone());
105+ out.push(Some(a));
106+ }
107+ if let (Some(k), Some(b)) = (next, m.block(lo + out.len())) {
108+ let mut a = b.attrs.clone();
109+ a.join = join_for(prev.as_ref(), &a.wrap, k);
110+ out.push(Some(a));
111+ }
112+ m.set_attrs(lo, &out);
113+}
114+
115+/// Whether `cur` stays in the level-`d` node of `prev`: the same item, or with `list`
116+/// the same list.
117+fn same_node(prev: &Attrs, cur: &Attrs, d: usize, list: bool) -> bool {
118+ let k = keep(Some(prev), cur);
119+ k > d || (list && k == d && common(&prev.wrap, &cur.wrap) > d && cur.wrap[d].is_list())
120+}
121+
122+/// Blocks `(first, last)` in the level-`d` node holding block `i`.
123+fn extent(m: &Model, i: usize, d: usize, list: bool) -> (usize, usize) {
124+ let cur = m.block(i).expect("block").attrs;
125+ let (mut s, mut e) = (i, i);
126+ let mut c = cur.clone();
127+ m.scan(i, true, |info, a| {
128+ if same_node(a, &c, d, list) {
129+ s = info.index;
130+ c = a.clone();
131+ true
132+ } else {
133+ false
134+ }
135+ });
136+ let mut p = cur;
137+ m.scan(i + 1, false, |info, a| {
138+ if same_node(&p, a, d, list) {
139+ e = info.index;
140+ p = a.clone();
141+ true
142+ } else {
143+ false
144+ }
145+ });
146+ (s, e)
147+}
148+
149+/// Blocks `lo..=hi` with their old keeps.
150+fn with_keeps(m: &Model, lo: usize, hi: usize) -> Vec<(Blk, usize)> {
151+ let blocks = m.blocks(lo, hi + 1);
152+ let mut prev = lo.checked_sub(1).and_then(|i| m.block(i)).map(|b| b.attrs);
153+ blocks
154+ .into_iter()
155+ .map(|b| {
156+ let k = keep(prev.as_ref(), &b.attrs);
157+ prev = Some(b.attrs.clone());
158+ (b, k)
159+ })
160+ .collect()
161+}
162+
163+/// Deletes block `b` whole; the next block keeps what both shared with the one before.
164+fn remove_block(m: &Model, b: &Blk) {
165+ if m.len() == 1 {
166+ m.delete(b.start, b.sep);
167+ m.set_attrs(0, &[Some(Attrs::default())]);
168+ return;
169+ }
170+ let kb = keep_of(m, b);
171+ let kn = next_keep(m, b);
172+ m.delete(b.start, b.end());
173+ if let Some(kn) = kn {
174+ relink(m, b.index, Vec::new(), Some(kn.min(kb)));
175+ }
176+}
177+
178+/// Inserts a block of `attrs` after `b`, keeping `k` levels with it. Returns its start.
179+fn block_after(m: &Model, b: &Blk, mut attrs: Attrs, k: usize) -> Pos {
180+ let nk = next_keep(m, b);
181+ attrs.join = join_for(Some(&b.attrs), &attrs.wrap, k);
182+ m.insert_blocks(b.end(), &[FlatBlock { attrs, ..Default::default() }]);
183+ if let Some(nk) = nk {
184+ relink(m, b.index + 2, Vec::new(), Some(nk));
185+ }
186+ b.end()
187+}
188+
189+/// Inserts a block of `attrs` before `b`, taking `b`'s place; `b` then shares all its
190+/// levels with it. Returns the new block's start.
191+fn block_before(m: &Model, b: &Blk, mut attrs: Attrs) -> Pos {
192+ let kb = keep_of(m, b);
193+ attrs.join = None;
194+ m.insert_blocks(b.start, &[FlatBlock { attrs: attrs.clone(), ..Default::default() }]);
195+ let d = b.depth();
196+ relink(m, b.index, vec![(attrs, Some(kb)), (b.attrs.clone(), Some(d))], None);
197+ b.start
198+}
199+
200+/// A paragraph in the containers of `b`.
201+fn para_in(b: &Blk) -> Attrs {
202+ Attrs { wrap: b.attrs.wrap.clone(), ..Attrs::default() }
203+}
204+
205+/// Clears inline marks and drops images from `from..to` (text becoming code).
206+fn to_plain(m: &Model, from: Pos, to: Pos) {
207+ if from >= to {
208+ return;
209+ }
210+ let (a, b) = (m.to_u(from), m.to_u(to));
211+ m.restyle(INLINE.iter().map(|k| Seg { from: a, to: b, key: k, value: None }).collect());
212+ let text: Vec<u16> = m.plain(from, to).encode_utf16().collect();
213+ for (i, _) in text.iter().enumerate().rev().filter(|(_, c)| **c == flat::OBJ as u16) {
214+ m.delete(from + i, from + i + 1);
215+ }
216+}
217+
218+// ---------------------------------------------------------------------------
219+// Marks at a position
220+// ---------------------------------------------------------------------------
221+
222+/// Marks of the first run of `from..to`; a break or image carries none.
223+fn run_marks(m: &Model, from: Pos, to: Pos, last: bool) -> Option<Marks> {
224+ let runs = m.slice(from, to);
225+ let run = if last { runs.into_iter().last() } else { runs.into_iter().next() };
226+ let TextDelta::Insert { insert, attributes } = run? else { return None };
227+ let c = if last { insert.chars().last()? } else { insert.chars().next()? };
228+ if c == '\n' || c == flat::OBJ || c == flat::SEP {
229+ return Some(Marks::none());
230+ }
231+ Some(Marks::from_attrs(attributes.as_ref()))
232+}
233+
234+/// PM `ResolvedPos.marks()`: inside a run its marks; at a boundary the marks of the
235+/// run before (after, at the block start), minus a link that does not continue on the
236+/// other side.
237+pub fn marks_at(m: &Model, off: Pos) -> Marks {
238+ let b = m.at(off);
239+ if b.is_empty() || b.kind() != Leaf::Para && !matches!(b.kind(), Leaf::Heading(_)) {
240+ return Marks::none();
241+ }
242+ let before = (off > b.start).then(|| run_marks(m, off.saturating_sub(2).max(b.start), off, true)).flatten();
243+ let after = (off < b.sep).then(|| run_marks(m, off, (off + 2).min(b.sep), false)).flatten();
244+ let (main, other) = match (before, after) {
245+ (Some(x), a) => (x, a),
246+ (None, Some(a)) => (a, None),
247+ (None, None) => return Marks::none(),
248+ };
249+ let mut mk = main;
250+ if mk.link.is_some() && other.is_none_or(|o| o.link != mk.link) {
251+ mk.link = None;
252+ }
253+ mk
254+}
255+
256+/// Marks the next inserted text gets.
257+pub fn pending_marks(cx: &Cx) -> Marks {
258+ if let Some(m) = &cx.stored {
259+ return m.clone();
260+ }
261+ match cx.sel.cursor() {
262+ Some(p) => marks_at(cx.m, p),
263+ None => Marks::none(),
264+ }
265+}
266+
267+// ---------------------------------------------------------------------------
268+// Text input
269+// ---------------------------------------------------------------------------
270+
271+/// Replaces the selection with `text` carrying the pending marks.
272+pub fn insert_text(cx: &mut Cx, text: &str) -> bool {
273+ let marks = if cx.sel.is_empty() {
274+ pending_marks(cx)
275+ } else {
276+ // Typing over a range takes the marks at its start (PM uses $from.marks()).
277+ pos::text_range(cx.m, &cx.sel).map_or(Marks::none(), |(from, _)| {
278+ let b = cx.m.at(from);
279+ if from < b.sep { run_marks(cx.m, from, (from + 2).min(b.sep), false).unwrap_or_default() } else { marks_at(cx.m, from) }
280+ })
281+ };
282+ if !cx.sel.is_empty() && !delete_selection(cx, true) {
283+ return false;
284+ }
285+ let Some((b, off)) = cx.caret() else { return false };
286+ let marks = if b.kind() == Leaf::Code { Marks::none() } else { marks };
287+ let end = cx.m.insert(off, text, &marks);
288+ cx.set_caret(end);
289+ true
290+}
291+
292+/// Inserts inline content (paste) at the selection.
293+pub fn insert_inline(cx: &mut Cx, inl: &[Inline]) -> bool {
294+ if !cx.sel.is_empty() && !delete_selection(cx, true) {
295+ return false;
296+ }
297+ let Some((b, off)) = cx.caret() else { return false };
298+ let end = if b.kind() == Leaf::Code { cx.m.insert(off, &inline_text(inl), &Marks::none()) } else { cx.m.insert_inline(off, inl) };
299+ cx.set_caret(end);
300+ true
301+}
302+
303+fn inline_text(inl: &[Inline]) -> String {
304+ inl.iter()
305+ .map(|i| match i {
306+ Inline::Text(s, _) => s.as_str(),
307+ Inline::HardBreak => "\n",
308+ Inline::Image { .. } => "",
309+ })
310+ .collect()
311+}
312+
313+// ---------------------------------------------------------------------------
314+// Deletion
315+// ---------------------------------------------------------------------------
316+
317+pub fn delete_selection(cx: &mut Cx, apply: bool) -> bool {
318+ match cx.sel {
319+ Selection::Text { anchor, head } if anchor != head => {
320+ if apply {
321+ let (from, to) = (anchor.min(head), anchor.max(head));
322+ delete_range(cx.m, from, to);
323+ cx.set_caret(from);
324+ }
325+ true
326+ }
327+ Selection::All => {
328+ if apply {
329+ let last = cx.m.last();
330+ cx.m.delete(0, last.sep);
331+ cx.m.set_attrs(0, &[Some(Attrs::default())]);
332+ cx.set_caret(0);
333+ }
334+ true
335+ }
336+ Selection::Node(p) => {
337+ let b = cx.m.at(p);
338+ if apply {
339+ if b.kind() == Leaf::Rule {
340+ remove_block(cx.m, &b);
341+ let near = pos::snap(cx.m, b.start.min(cx.m.last().sep));
342+ cx.set_caret(near);
343+ } else {
344+ // An image inside a text block: one char.
345+ cx.m.delete(p, p + 1);
346+ cx.set_caret(p);
347+ }
348+ }
349+ true
350+ }
351+ _ => false,
352+ }
353+}
354+
355+/// Deletes `from..to`. Across blocks the merged block keeps the first block's
356+/// attributes, and the block after the range keeps the levels it shared with the last
357+/// one where those match the first one's.
358+pub fn delete_range(m: &Model, from: Pos, to: Pos) {
359+ let x = m.at(from);
360+ let y = m.at(to);
361+ if x.index == y.index {
362+ m.delete(from, to);
363+ return;
364+ }
365+ let kz = next_keep(m, &y);
366+ let cw = common(&x.attrs.wrap, &y.attrs.wrap);
367+ let tail = y.sep - to;
368+ m.delete(from, to);
369+ if x.kind() == Leaf::Code && y.kind() != Leaf::Code {
370+ to_plain(m, from, from + tail);
371+ }
372+ relink(m, x.index, vec![(x.attrs.clone(), None)], kz.map(|k| k.min(cw)));
373+}
374+
375+/// Merges block `b` into the block `a` before it (same containers). Returns the join point.
376+fn join_into(m: &Model, a: &Blk, b: &Blk) -> Pos {
377+ m.delete(a.sep, a.sep + 1);
378+ m.set_attrs(a.index, &[Some(a.attrs.clone())]);
379+ if a.kind() == Leaf::Code && b.kind() != Leaf::Code {
380+ to_plain(m, a.sep, a.sep + b.len());
381+ }
382+ a.sep
383+}
384+
385+pub fn join_backward(cx: &mut Cx, apply: bool) -> bool {
386+ let Some((b, off)) = cx.caret() else { return false };
387+ if off != b.start {
388+ return false;
389+ }
390+ let m = cx.m;
391+ let Some(a) = prev_of(m, &b) else { return lift(cx, &b, apply) };
392+ let k = keep(Some(&a.attrs), &b.attrs);
393+ let l = b.depth();
394+ if k < l {
395+ // First in a container: join the previous one of its kind, else leave it.
396+ if common(&a.attrs.wrap, &b.attrs.wrap) > k {
397+ if apply {
398+ let nk = next_keep(m, &b);
399+ relink(m, b.index, vec![(b.attrs.clone(), Some(k + 1))], nk);
400+ }
401+ return true;
402+ }
403+ return lift(cx, &b, apply);
404+ }
405+ if a.depth() > l {
406+ // After a container: move into its trailing item or quote.
407+ let mut n = l + 1;
408+ while n < a.depth() && a.attrs.wrap[n] == Wrap::Quote {
409+ n += 1;
410+ }
411+ if apply {
412+ let nk = next_keep(m, &b);
413+ let mut at = b.attrs.clone();
414+ at.wrap = a.attrs.wrap[..n].to_vec();
415+ relink(m, b.index, vec![(at, Some(n))], nk);
416+ }
417+ return true;
418+ }
419+ if !apply {
420+ return true;
421+ }
422+ if a.kind() == Leaf::Rule {
423+ if b.is_empty() {
424+ remove_block(m, &b);
425+ cx.sel = Selection::Node(a.start);
426+ } else {
427+ remove_block(m, &a);
428+ cx.set_caret(a.start);
429+ }
430+ } else if a.is_empty() {
431+ remove_block(m, &a);
432+ cx.set_caret(a.start);
433+ } else {
434+ let at = join_into(m, &a, &b);
435+ cx.set_caret(at);
436+ }
437+ true
438+}
439+
440+pub fn join_forward(cx: &mut Cx, apply: bool) -> bool {
441+ let Some((b, off)) = cx.caret() else { return false };
442+ if off != b.sep {
443+ return false;
444+ }
445+ let m = cx.m;
446+ let Some(c) = m.block(b.index + 1) else { return false };
447+ let k = keep(Some(&b.attrs), &c.attrs);
448+ let l = c.depth();
449+ if b.is_empty() {
450+ if apply {
451+ remove_block(m, &b);
452+ cx.sel = if c.kind() == Leaf::Rule { Selection::Node(b.start) } else { Selection::caret(b.start) };
453+ }
454+ return true;
455+ }
456+ if k < l {
457+ if common(&b.attrs.wrap, &c.attrs.wrap) > k {
458+ if apply {
459+ let nk = next_keep(m, &c);
460+ relink(m, c.index, vec![(c.attrs.clone(), Some(k + 1))], nk);
461+ }
462+ return true;
463+ }
464+ let sel = cx.sel.clone();
465+ let ran = lift(cx, &c, apply);
466+ cx.sel = sel;
467+ return ran;
468+ }
469+ if b.depth() > l {
470+ return false;
471+ }
472+ if apply {
473+ if c.kind() == Leaf::Rule {
474+ remove_block(m, &c);
475+ } else {
476+ join_into(m, &b, &c);
477+ }
478+ cx.set_caret(b.sep);
479+ }
480+ true
481+}
482+
483+pub fn select_node_backward(cx: &mut Cx, apply: bool) -> bool {
484+ let Some((b, off)) = cx.caret() else { return false };
485+ if off != b.start {
486+ return false;
487+ }
488+ match prev_of(cx.m, &b) {
489+ Some(a) if a.kind() == Leaf::Rule => {
490+ if apply {
491+ cx.sel = Selection::Node(a.start);
492+ }
493+ true
494+ }
495+ _ => false,
496+ }
497+}
498+
499+pub fn select_node_forward(cx: &mut Cx, apply: bool) -> bool {
500+ let Some((b, off)) = cx.caret() else { return false };
501+ if off != b.sep {
502+ return false;
503+ }
504+ match cx.m.block(b.index + 1) {
505+ Some(c) if c.kind() == Leaf::Rule => {
506+ if apply {
507+ cx.sel = Selection::Node(c.start);
508+ }
509+ true
510+ }
511+ _ => false,
512+ }
513+}
514+
515+// ---------------------------------------------------------------------------
516+// Enter
517+// ---------------------------------------------------------------------------
518+
519+pub fn newline_in_code(cx: &mut Cx, apply: bool) -> bool {
520+ let Some(b) = cx.head_block() else { return false };
521+ if b.kind() != Leaf::Code {
522+ return false;
523+ }
524+ if let Selection::Text { anchor, .. } = cx.sel
525+ && !b.holds(anchor)
526+ {
527+ return false;
528+ }
529+ !apply || insert_text(cx, "\n")
530+}
531+
532+pub fn create_paragraph_near(cx: &mut Cx, apply: bool) -> bool {
533+ let m = cx.m;
534+ match cx.sel {
535+ Selection::Node(p) => {
536+ let b = m.at(p);
537+ if b.kind() != Leaf::Rule {
538+ return false;
539+ }
540+ if apply {
541+ let at = if b.index == 0 { block_before(m, &b, para_in(&b)) } else { block_after(m, &b, para_in(&b), b.depth()) };
542+ cx.set_caret(at);
543+ }
544+ true
545+ }
546+ Selection::Gap(p) => {
547+ if apply {
548+ let at = if p < m.total() {
549+ let b = m.at(p);
550+ let mut a = para_in(&b);
551+ a.start = b.attrs.start;
552+ block_before(m, &b, a)
553+ } else {
554+ let b = m.last();
555+ block_after(m, &b, para_in(&b), b.depth())
556+ };
557+ cx.set_caret(at);
558+ }
559+ true
560+ }
561+ _ => false,
562+ }
563+}
564+
565+pub fn lift_empty_block(cx: &mut Cx, apply: bool) -> bool {
566+ let Some((b, _)) = cx.caret() else { return false };
567+ if !b.is_empty() || b.depth() == 0 {
568+ return false;
569+ }
570+ lift(cx, &b, apply)
571+}
572+
573+pub fn split_block(cx: &mut Cx, apply: bool) -> bool {
574+ if !matches!(cx.sel, Selection::Text { .. }) {
575+ return false;
576+ }
577+ if !apply {
578+ return true;
579+ }
580+ if !cx.sel.is_empty() {
581+ delete_selection(cx, true);
582+ }
583+ let Some((b, off)) = cx.caret() else { return false };
584+ let at_end = off == b.sep;
585+ let mut first = b.attrs.clone();
586+ if off == b.start && !at_end && b.kind() != Leaf::Para {
587+ // Enter at the start of a heading: the empty first half is a paragraph.
588+ first.kind = Leaf::Para;
589+ first.lang = None;
590+ }
591+ let tail = Attrs {
592+ kind: if at_end { Leaf::Para } else { b.kind() },
593+ lang: if at_end { None } else { b.attrs.lang.clone() },
594+ wrap: b.attrs.wrap.clone(),
595+ join: None,
596+ start: None,
597+ };
598+ let m = cx.m;
599+ m.insert_blocks(off, &[FlatBlock { attrs: first, ..Default::default() }]);
600+ relink(m, b.index + 1, vec![(tail, Some(b.depth()))], None);
601+ cx.set_caret(off + 1);
602+ true
603+}
604+
605+pub fn exit_code(cx: &mut Cx, apply: bool) -> bool {
606+ let Some(b) = cx.head_block() else { return false };
607+ if b.kind() != Leaf::Code {
608+ return false;
609+ }
610+ if apply {
611+ let at = block_after(cx.m, &b, para_in(&b), b.depth());
612+ cx.set_caret(at);
613+ }
614+ true
615+}
616+
617+pub fn select_all(cx: &mut Cx, apply: bool) -> bool {
618+ if apply {
619+ cx.sel = Selection::All;
620+ }
621+ true
622+}
623+
624+// ---------------------------------------------------------------------------
625+// Lists and quotes
626+// ---------------------------------------------------------------------------
627+
628+/// Moves block `b` out of its innermost container: its list item, or its quote.
629+fn lift(cx: &mut Cx, b: &Blk, apply: bool) -> bool {
630+ let l = b.depth();
631+ if l == 0 {
632+ return false;
633+ }
634+ let d = l - 1;
635+ if b.attrs.wrap[d].is_list() {
636+ return lift_item(cx.m, b.index, d, apply);
637+ }
638+ if apply {
639+ pop_level(cx.m, b, d);
640+ }
641+ true
642+}
643+
644+/// Removes the innermost level `d` of a single block; what followed in that
645+/// container opens a new one after it.
646+fn pop_level(m: &Model, b: &Blk, d: usize) {
647+ let kb = keep_of(m, b);
648+ let kn = next_keep(m, b);
649+ let mut a = b.attrs.clone();
650+ a.wrap.truncate(d);
651+ relink(m, b.index, vec![(a, Some(kb.min(d)))], kn.map(|k| k.min(d)));
652+}
653+
654+/// liftListItem for the item at level `d` holding block `i`: the item leaves that
655+/// list. Nested, it becomes an item of the outer list and the items after it a list
656+/// inside it; at the top its blocks replace it and the list continues after them.
657+fn lift_item(m: &Model, i: usize, d: usize, apply: bool) -> bool {
658+ if !apply {
659+ return true;
660+ }
661+ let (s, e) = extent(m, i, d, false);
662+ let blocks = with_keeps(m, s, e);
663+ let first = &blocks[0].0;
664+ let nested = d > 0 && first.attrs.wrap[d - 1].is_list();
665+ let next = m.block(e + 1);
666+ let next_is_item = next.as_ref().is_some_and(|n| same_node(&blocks.last().unwrap().0.attrs, &n.attrs, d, true));
667+ let nk = next.as_ref().map(|n| if next_is_item { d } else { keep(Some(&blocks.last().unwrap().0.attrs), &n.attrs) });
668+ let new = blocks
669+ .iter()
670+ .enumerate()
671+ .map(|(j, (b, k))| {
672+ let mut a = b.attrs.clone();
673+ a.wrap.remove(d);
674+ let k = if j == 0 { (*k).min(if nested { d - 1 } else { d }) } else { k - 1 };
675+ if j == 0 {
676+ a.start = None;
677+ }
678+ (a, Some(k))
679+ })
680+ .collect();
681+ relink(m, s, new, nk);
682+ true
683+}
684+
685+/// The innermost list level of block `b` that it sits in directly.
686+fn item_level(b: &Blk) -> Option<usize> {
687+ let d = b.depth().checked_sub(1)?;
688+ b.attrs.wrap[d].is_list().then_some(d)
689+}
690+
691+pub fn split_list_item(cx: &mut Cx, apply: bool) -> bool {
692+ let Some(b) = cx.head_block() else { return false };
693+ if !matches!(cx.sel, Selection::Text { .. }) || !b.kind().is_text() {
694+ return false;
695+ }
696+ let Some(d) = item_level(&b) else { return false };
697+ let m = cx.m;
698+ let kb = keep_of(m, &b);
699+ let last_in_item = m.block(b.index + 1).is_none_or(|n| keep(Some(&b.attrs), &n.attrs) <= d);
700+ if b.is_empty() && last_in_item && cx.sel.is_empty() {
701+ if kb <= d {
702+ // An empty item: Enter leaves the list.
703+ return lift_item(m, b.index, d, apply);
704+ }
705+ // An empty last paragraph of an item becomes the next item.
706+ if apply {
707+ let nk = next_keep(m, &b);
708+ relink(m, b.index, vec![(b.attrs.clone(), Some(d))], nk);
709+ }
710+ return true;
711+ }
712+ if !apply {
713+ return true;
714+ }
715+ if !cx.sel.is_empty() {
716+ delete_selection(cx, true);
717+ }
718+ let Some((b, off)) = cx.caret() else { return false };
719+ let tail = Attrs { wrap: b.attrs.wrap.clone(), ..Attrs::default() };
720+ m.insert_blocks(off, &[FlatBlock { attrs: b.attrs.clone(), ..Default::default() }]);
721+ relink(m, b.index + 1, vec![(tail, Some(d))], None);
722+ cx.set_caret(off + 1);
723+ true
724+}
725+
726+pub fn sink_list_item(cx: &mut Cx, apply: bool) -> bool {
727+ let Some(b) = cx.head_block() else { return false };
728+ let Some(d) = item_level(&b) else { return false };
729+ let m = cx.m;
730+ let (s, e) = extent(m, b.index, d, false);
731+ let first = m.block(s).unwrap();
732+ // Only an item with an item before it in the same list can sink.
733+ let Some(p) = prev_of(m, &first) else { return false };
734+ if !same_node(&p.attrs, &first.attrs, d, true) {
735+ return false;
736+ }
737+ if !apply {
738+ return true;
739+ }
740+ let w = b.attrs.wrap[d];
741+ let blocks = with_keeps(m, s, e);
742+ let nk = m.block(e + 1).map(|n| keep(Some(&blocks.last().unwrap().0.attrs), &n.attrs));
743+ let new = blocks
744+ .iter()
745+ .enumerate()
746+ .map(|(j, (b, k))| {
747+ let mut a = b.attrs.clone();
748+ a.wrap.insert(d + 1, w);
749+ (a, Some(if j == 0 { d + 1 } else { k + 1 }))
750+ })
751+ .collect();
752+ relink(m, s, new, nk);
753+ true
754+}
755+
756+pub fn lift_list_item(cx: &mut Cx, apply: bool) -> bool {
757+ let Some(b) = cx.head_block() else { return false };
758+ let Some(d) = b.attrs.wrap.iter().rposition(|w| w.is_list()) else { return false };
759+ lift_item(cx.m, b.index, d, apply)
760+}
761+
762+/// Wraps the blocks of the selection (whole nodes at their deepest common level) in a
763+/// new list or quote.
764+fn wrap_range(cx: &mut Cx, w: Wrap, apply: bool) -> bool {
765+ let m = cx.m;
766+ let Some((from, to)) = pos::text_range(m, &cx.sel) else { return false };
767+ let (x, y) = (m.at(from), m.at(to));
768+ let range = with_keeps(m, x.index, y.index);
769+ if range.is_empty() {
770+ return false;
771+ }
772+ let mut d = x.depth();
773+ for (b, k) in &range[1..] {
774+ d = d.min(*k).min(b.depth());
775+ }
776+ let (s, _) = if x.index == 0 || keep_of(m, &x) <= d { (x.index, 0) } else { extent(m, x.index, d, false) };
777+ let (_, e) = if y.depth() <= d { (0, y.index) } else { extent(m, y.index, d, false) };
778+ let blocks = with_keeps(m, s, e);
779+ let first = &blocks[0];
780+ // The first block of a list item stays its first block.
781+ if d > 0 && first.0.attrs.wrap[d - 1].is_list() && first.1 < d {
782+ return false;
783+ }
784+ if w.is_list() {
785+ let mut prev = &blocks[0].0;
786+ for (b, k) in &blocks[1..] {
787+ if *k == d && same_node(&prev.attrs, &b.attrs, d, true) && b.depth() > d {
788+ return false;
789+ }
790+ prev = b;
791+ }
792+ }
793+ if !apply {
794+ return true;
795+ }
796+ let nk = m.block(e + 1).map(|n| keep(Some(&blocks.last().unwrap().0.attrs), &n.attrs));
797+ let new = blocks
798+ .iter()
799+ .enumerate()
800+ .map(|(j, (b, k))| {
801+ let mut a = b.attrs.clone();
802+ a.wrap.insert(d, w);
803+ let k = match j {
804+ 0 => *k,
805+ _ if w.is_list() && *k == d => d,
806+ _ => k + 1,
807+ };
808+ (a, Some(k))
809+ })
810+ .collect();
811+ relink(m, s, new, nk);
812+ true
813+}
814+
815+pub fn wrap_in_list(cx: &mut Cx, kind: Kind, start: Option<i64>, apply: bool) -> bool {
816+ let Some(w) = kind.wrap().filter(|w| w.is_list()) else { return false };
817+ let ran = wrap_range(cx, w, apply);
818+ if ran
819+ && apply
820+ && let Some(n) = start.filter(|&n| n != 1)
821+ && let Some((from, _)) = pos::text_range(cx.m, &cx.sel)
822+ {
823+ let b = cx.m.at(from);
824+ let mut a = b.attrs.clone();
825+ a.start = Some(n);
826+ cx.m.set_attrs(b.index, &[Some(a)]);
827+ }
828+ ran
829+}
830+
831+pub fn wrap_in(cx: &mut Cx, kind: Kind, apply: bool) -> bool {
832+ match kind.wrap() {
833+ Some(w) => wrap_range(cx, w, apply),
834+ None => false,
835+ }
836+}
837+
838+/// Changes the type of the list at level `d` holding block `i`.
839+fn retype_list(m: &Model, i: usize, d: usize, w: Wrap) {
840+ let (s, e) = extent(m, i, d, true);
841+ let blocks = with_keeps(m, s, e);
842+ let nk = m.block(e + 1).map(|n| keep(Some(&blocks.last().unwrap().0.attrs), &n.attrs));
843+ let new = blocks
844+ .into_iter()
845+ .map(|(b, k)| {
846+ let mut a = b.attrs;
847+ a.wrap[d] = w;
848+ (a, Some(k))
849+ })
850+ .collect();
851+ relink(m, s, new, nk);
852+}
853+
854+/// The innermost container of the head block matching `pred`.
855+pub fn ancestor_kind(cx: &Cx, pred: fn(Kind) -> bool) -> Option<Kind> {
856+ let b = cx.head_block()?;
857+ b.attrs.wrap.iter().rev().map(|w| Kind::of_wrap(*w)).find(|k| pred(*k))
858+}
859+
860+pub fn toggle_list(cx: &mut Cx, kind: Kind, apply: bool) -> bool {
861+ let Some(w) = kind.wrap() else { return false };
862+ let Some(b) = cx.head_block() else { return false };
863+ match b.attrs.wrap.iter().rposition(|x| x.is_list()) {
864+ None => wrap_range(cx, w, apply),
865+ Some(d) if b.attrs.wrap[d] == w => lift_item(cx.m, b.index, d, apply),
866+ Some(d) => {
867+ if apply {
868+ retype_list(cx.m, b.index, d, w);
869+ }
870+ true
871+ }
872+ }
873+}
874+
875+pub fn toggle_quote(cx: &mut Cx, apply: bool) -> bool {
876+ let Some(b) = cx.head_block() else { return false };
877+ let Some(q) = b.attrs.wrap.iter().rposition(|w| *w == Wrap::Quote) else { return wrap_range(cx, Wrap::Quote, apply) };
878+ if !apply {
879+ return true;
880+ }
881+ // The quote's child holding the block leaves it; the quote splits around it.
882+ let m = cx.m;
883+ let (s, e) = if b.depth() > q + 1 { extent(m, b.index, q + 1, true) } else { (b.index, b.index) };
884+ let blocks = with_keeps(m, s, e);
885+ let nk = m.block(e + 1).map(|n| keep(Some(&blocks.last().unwrap().0.attrs), &n.attrs).min(q));
886+ let new = blocks
887+ .iter()
888+ .enumerate()
889+ .map(|(j, (b, k))| {
890+ let mut a = b.attrs.clone();
891+ a.wrap.remove(q);
892+ (a, Some(if j == 0 { (*k).min(q) } else { k - 1 }))
893+ })
894+ .collect();
895+ relink(m, s, new, nk);
896+ true
897+}
898+
899+// ---------------------------------------------------------------------------
900+// Block types
901+// ---------------------------------------------------------------------------
902+
903+/// Text blocks from the one holding `from` through the one holding `to`.
904+fn text_blocks(m: &Model, from: Pos, to: Pos) -> Vec<Blk> {
905+ let (x, y) = (m.at(from), m.at(to));
906+ m.blocks(x.index, y.index + 1).into_iter().filter(|b| b.kind().is_text()).collect()
907+}
908+
909+/// Whether block `b` may become `kind`: the first block of a list item stays a paragraph.
910+pub fn can_retype(m: &Model, b: &Blk, kind: Leaf) -> bool {
911+ match item_level(b) {
912+ Some(d) if keep_of(m, b) <= d => kind == Leaf::Para,
913+ _ => true,
914+ }
915+}
916+
917+pub fn set_block_type(cx: &mut Cx, kind: Kind, apply: bool) -> bool {
918+ let Some(leaf) = kind.leaf() else { return false };
919+ let m = cx.m;
920+ let Some((from, to)) = pos::text_range(m, &cx.sel) else { return false };
921+ let (x, y) = (m.at(from), m.at(to));
922+ if !apply {
923+ // A dry run (toolbar state) stops at the first block it could retype.
924+ let mut found = false;
925+ m.scan(x.index, false, |info, a| {
926+ if info.index > y.index {
927+ return false;
928+ }
929+ if a.kind.is_text() && a.kind != leaf {
930+ let b = m.block(info.index).unwrap();
931+ found = can_retype(m, &b, leaf);
932+ }
933+ !found
934+ });
935+ return found;
936+ }
937+ let blocks: Vec<Blk> = text_blocks(m, from, to).into_iter().filter(|b| can_retype(m, b, leaf)).collect();
938+ if !blocks.iter().any(|b| b.kind() != leaf) {
939+ return false;
940+ }
941+ if leaf == Leaf::Code {
942+ // Adjacent blocks in one container become one code block, a line each.
943+ let mut runs: Vec<Vec<Blk>> = Vec::new();
944+ for b in blocks {
945+ match runs.last_mut() {
946+ Some(r) if r.last().is_some_and(|p| p.index + 1 == b.index && p.attrs.wrap == b.attrs.wrap && keep(Some(&p.attrs), &b.attrs) == b.depth()) => r.push(b),
947+ _ => runs.push(vec![b]),
948+ }
949+ }
950+ for run in runs.iter().rev() {
951+ let (first, last) = (&run[0], run.last().unwrap());
952+ to_plain(m, first.start, last.sep);
953+ let seps: Vec<(Pos, Option<Attrs>)> = (first.index..last.index).map(|i| (m.block(i).unwrap().sep, None)).collect();
954+ m.swap_chars(seps);
955+ let mut a = first.attrs.clone();
956+ a.kind = Leaf::Code;
957+ a.lang = None;
958+ m.set_attrs(first.index, &[Some(a)]);
959+ }
960+ } else {
961+ // A code block becomes one block per line.
962+ for b in blocks.iter().rev().filter(|b| b.kind() == Leaf::Code) {
963+ let text: Vec<u16> = m.plain(b.start, b.sep).encode_utf16().collect();
964+ let breaks: Vec<usize> = text.iter().enumerate().filter(|(_, c)| **c == b'\n' as u16).map(|(i, _)| b.start + i).collect();
965+ if breaks.is_empty() {
966+ continue;
967+ }
968+ let mut first = b.attrs.clone();
969+ first.kind = leaf;
970+ first.lang = None;
971+ let rest = Attrs { kind: leaf, wrap: b.attrs.wrap.clone(), join: join_for(Some(&b.attrs), &b.attrs.wrap, b.depth()), ..Attrs::default() };
972+ let mut swaps = vec![(breaks[0], Some(first))];
973+ swaps.extend(breaks[1..].iter().map(|&p| (p, Some(rest.clone()))));
974+ m.swap_chars(swaps);
975+ let last = m.block(b.index + breaks.len()).unwrap();
976+ m.set_attrs(last.index, &[Some(rest.clone())]);
977+ }
978+ let targets: Vec<Blk> = text_blocks(m, from, to).into_iter().filter(|b| b.kind() != leaf && can_retype(m, b, leaf)).collect();
979+ let mut changes: Vec<(usize, Attrs)> = Vec::new();
980+ for b in targets {
981+ let mut a = b.attrs.clone();
982+ a.kind = leaf;
983+ a.lang = None;
984+ changes.push((b.index, a));
985+ }
986+ set_many(m, changes);
987+ }
988+ cx.sel = pos::clamp(m, &cx.sel);
989+ true
990+}
991+
992+/// Sets attributes of scattered blocks (sorted), as few runs as possible.
993+fn set_many(m: &Model, changes: Vec<(usize, Attrs)>) {
994+ let Some(lo) = changes.first().map(|c| c.0) else { return };
995+ let hi = changes.last().unwrap().0;
996+ let mut new = vec![None; hi - lo + 1];
997+ for (i, a) in changes {
998+ new[i - lo] = Some(a);
999+ }
1000+ m.set_attrs(lo, &new);
1001+}
1002+
1003+pub fn is_block_active(cx: &Cx, kind: Kind) -> bool {
1004+ cx.head_block().is_some_and(|b| Some(b.kind()) == kind.leaf())
1005+}
1006+
1007+pub fn toggle_block(cx: &mut Cx, kind: Kind, apply: bool) -> bool {
1008+ if is_block_active(cx, kind) { set_block_type(cx, Kind::Paragraph, apply) } else { set_block_type(cx, kind, apply) }
1009+}
1010+
1011+/// Sets the language of the code block holding `off` (None: detect).
1012+pub fn set_code_language(m: &Model, off: Pos, lang: Option<&str>) -> bool {
1013+ let b = m.at(off);
1014+ if b.kind() != Leaf::Code {
1015+ return false;
1016+ }
1017+ let mut a = b.attrs.clone();
1018+ a.lang = lang.filter(|l| !l.is_empty()).map(str::to_owned);
1019+ if a == b.attrs {
1020+ return false;
1021+ }
1022+ m.set_attrs(b.index, &[Some(a)]);
1023+ true
1024+}
1025+
1026+pub fn insert_rule(cx: &mut Cx, apply: bool) -> bool {
1027+ let Some(b) = cx.head_block() else { return false };
1028+ if b.kind() == Leaf::Code || !b.kind().is_text() {
1029+ return false;
1030+ }
1031+ if !apply {
1032+ return true;
1033+ }
1034+ if !cx.sel.is_empty() {
1035+ delete_selection(cx, true);
1036+ }
1037+ let Some((b, off)) = cx.caret() else { return false };
1038+ let m = cx.m;
1039+ let rule = Attrs { kind: Leaf::Rule, wrap: b.attrs.wrap.clone(), ..Attrs::default() };
1040+ let l = b.depth();
1041+ if off == b.start {
1042+ let at = block_before(m, &b, Attrs { start: b.attrs.start, ..rule });
1043+ cx.set_caret(at + 1);
1044+ } else if off == b.sep {
1045+ block_after(m, &b, rule, l);
1046+ let r = m.block(b.index + 1).unwrap();
1047+ let next = m.block(r.index + 1).filter(|n| n.kind().is_text() && n.attrs.wrap == b.attrs.wrap && keep(Some(&r.attrs), &n.attrs) == l);
1048+ let at = match next {
1049+ Some(n) => n.start,
1050+ None => block_after(m, &r, para_in(&b), l),
1051+ };
1052+ cx.set_caret(at);
1053+ } else {
1054+ // Split, with the rule between the halves.
1055+ let tail = Attrs { kind: b.kind(), lang: b.attrs.lang.clone(), wrap: b.attrs.wrap.clone(), ..Attrs::default() };
1056+ m.insert_blocks(off, &[FlatBlock { attrs: b.attrs.clone(), ..Default::default() }, FlatBlock { attrs: rule.clone(), ..Default::default() }]);
1057+ relink(m, b.index + 1, vec![(rule, Some(l)), (tail, Some(l))], None);
1058+ cx.set_caret(off + 2);
1059+ }
1060+ true
1061+}
1062+
1063+// ---------------------------------------------------------------------------
1064+// Inline marks
1065+// ---------------------------------------------------------------------------
1066+
1067+/// Content ranges of the non-code blocks in `from..to`, one per run of neighbours
1068+/// (a mark may cover the separators between them).
1069+fn mark_ranges(m: &Model, from: Pos, to: Pos) -> Vec<(Pos, Pos)> {
1070+ let (x, y) = (m.at(from), m.at(to));
1071+ let mut out: Vec<(Pos, Pos)> = Vec::new();
1072+ let mut open = false;
1073+ m.scan(x.index, false, |info, a| {
1074+ if info.index > y.index {
1075+ return false;
1076+ }
1077+ if a.kind == Leaf::Code {
1078+ open = false;
1079+ return true;
1080+ }
1081+ let (s, e) = (info.start16.max(from), info.sep16().min(to));
1082+ match out.last_mut() {
1083+ Some(r) if open => r.1 = e,
1084+ _ => out.push((s, e)),
1085+ }
1086+ open = true;
1087+ true
1088+ });
1089+ out.retain(|r| r.0 < r.1);
1090+ out
1091+}
1092+
1093+/// Whether `from..to` holds text outside code blocks.
1094+fn has_markable(m: &Model, from: Pos, to: Pos) -> bool {
1095+ let (x, y) = (m.at(from), m.at(to));
1096+ let mut found = false;
1097+ m.scan(x.index, false, |info, a| {
1098+ if info.index > y.index {
1099+ return false;
1100+ }
1101+ found = a.kind != Leaf::Code && info.start16.max(from) < info.sep16().min(to);
1102+ !found
1103+ });
1104+ found
1105+}
1106+
1107+/// Whether mark `t` is on the stored marks (collapsed) or on any text of the
1108+/// selection, looking at most at `limit` UTF-16 units of it.
1109+pub fn mark_active_within(cx: &Cx, t: MarkType, limit: usize) -> bool {
1110+ if cx.sel.is_empty() {
1111+ return pending_marks(cx).has(t);
1112+ }
1113+ let Some((from, to)) = pos::text_range(cx.m, &cx.sel) else { return false };
1114+ let to = to.min(from.saturating_add(limit));
1115+ mark_ranges(cx.m, from, to).into_iter().any(|(a, b)| {
1116+ cx.m.slice(a, b).into_iter().any(|d| match d {
1117+ TextDelta::Insert { insert, attributes } => {
1118+ Marks::from_attrs(attributes.as_ref()).has(t) && insert.chars().any(|c| c != flat::SEP)
1119+ }
1120+ _ => false,
1121+ })
1122+ })
1123+}
1124+
1125+/// Units of the selection the toolbar looks at for mark state.
1126+pub const MARK_STATE_UNITS: usize = 1 << 16;
1127+
1128+pub fn is_mark_active(cx: &Cx, t: MarkType) -> bool {
1129+ mark_active_within(cx, t, usize::MAX)
1130+}
1131+
1132+fn is_space(c: u16) -> bool {
1133+ c == b' ' as u16 || c == b'\t' as u16 || c == b'\n' as u16 || c == 0xa0 || c == flat::SEP as u16
1134+}
1135+
1136+/// `(a, b)` without surrounding whitespace, reading only near the ends.
1137+fn trim(m: &Model, mut a: Pos, mut b: Pos) -> (Pos, Pos) {
1138+ while a < b {
1139+ let n = (b - a).min(256);
1140+ let s: Vec<u16> = m.plain(a, a + n).encode_utf16().collect();
1141+ let k = s.iter().take_while(|c| is_space(**c)).count();
1142+ a += k;
1143+ if k < n {
1144+ break;
1145+ }
1146+ }
1147+ while b > a {
1148+ let n = (b - a).min(256);
1149+ let s: Vec<u16> = m.plain(b - n, b).encode_utf16().collect();
1150+ let k = s.iter().rev().take_while(|c| is_space(**c)).count();
1151+ b -= k;
1152+ if k < n {
1153+ break;
1154+ }
1155+ }
1156+ (a, b)
1157+}
1158+
1159+fn mark_value(t: MarkType, link: Option<Link>) -> Option<LoroValue> {
1160+ let mut mk = Marks::none();
1161+ match t {
1162+ MarkType::Link => mk.link = link,
1163+ t => mk.set(t, true),
1164+ }
1165+ mk.value_of(t.key())
1166+}
1167+
1168+/// Adds mark `t` over the text of `from..to` (input rules).
1169+pub fn add_mark(m: &Model, from: Pos, to: Pos, t: MarkType) {
1170+ style(m, mark_ranges(m, from, to), t, mark_value(t, None));
1171+}
1172+
1173+fn style(m: &Model, ranges: Vec<(Pos, Pos)>, t: MarkType, value: Option<LoroValue>) {
1174+ let segs = ranges
1175+ .into_iter()
1176+ .filter(|r| r.0 < r.1)
1177+ .map(|(a, b)| Seg { from: m.to_u(a), to: m.to_u(b), key: t.key(), value: value.clone() })
1178+ .collect();
1179+ m.restyle(segs);
1180+}
1181+
1182+pub fn toggle_mark(cx: &mut Cx, t: MarkType, apply: bool) -> bool {
1183+ if cx.sel.is_empty() {
1184+ let Some(b) = cx.head_block() else { return false };
1185+ if b.kind() == Leaf::Code {
1186+ return false;
1187+ }
1188+ if apply {
1189+ let mut mk = pending_marks(cx);
1190+ let on = !mk.has(t);
1191+ mk.set(t, on);
1192+ cx.stored = Some(mk);
1193+ }
1194+ return true;
1195+ }
1196+ let Some((from, to)) = pos::text_range(cx.m, &cx.sel) else { return false };
1197+ if !apply {
1198+ return has_markable(cx.m, from, to);
1199+ }
1200+ let ranges = mark_ranges(cx.m, from, to);
1201+ if ranges.is_empty() {
1202+ return false;
1203+ }
1204+ let remove = is_mark_active(cx, t);
1205+ let ranges = if remove { ranges } else { ranges.into_iter().map(|(a, b)| trim(cx.m, a, b)).collect() };
1206+ style(cx.m, ranges, t, if remove { None } else { mark_value(t, None) });
1207+ true
1208+}
1209+
1210+/// Sets or clears the link over `from..to`.
1211+pub fn set_link(cx: &mut Cx, from: Pos, to: Pos, href: Option<&str>) {
1212+ let link = href.map(|h| Link { href: h.to_owned(), title: None });
1213+ let value = link.is_some().then(|| mark_value(MarkType::Link, link)).flatten();
1214+ style(cx.m, mark_ranges(cx.m, from, to), MarkType::Link, value);
1215+}
1216+
1217+/// The link around `off`, within its block: `(from, to, link)`.
1218+pub fn link_range_at(m: &Model, off: Pos) -> Option<(Pos, Pos, Link)> {
1219+ let b = m.at(off);
1220+ if b.kind() == Leaf::Code || b.is_empty() {
1221+ return None;
1222+ }
1223+ // Most carets touch no link: check the neighbouring units before reading further.
1224+ let near = m.slice(off.saturating_sub(1).max(b.start), (off + 1).min(b.sep));
1225+ let link = near.iter().find_map(|d| match d {
1226+ TextDelta::Insert { attributes, .. } => Marks::from_attrs(attributes.as_ref()).link,
1227+ _ => None,
1228+ })?;
1229+ let mut pos = b.start;
1230+ let mut found: Option<(Pos, Pos)> = None;
1231+ for d in m.slice(b.start, b.sep) {
1232+ let TextDelta::Insert { insert, attributes } = d else { continue };
1233+ let len = insert.encode_utf16().count();
1234+ if Marks::from_attrs(attributes.as_ref()).link.as_ref() == Some(&link) {
1235+ found = match found {
1236+ Some((a, e)) if e == pos => Some((a, pos + len)),
1237+ Some(r) if r.1 >= off => break,
1238+ _ => Some((pos, pos + len)),
1239+ };
1240+ } else if found.is_some_and(|r| r.1 >= off) {
1241+ break;
1242+ }
1243+ pos += len;
1244+ }
1245+ found.filter(|r| r.0 <= off && off <= r.1).map(|(a, e)| (a, e, link))
1246+}
1247+
1248+/// Whether the link popover may open: a text selection in non-code text, or a caret
1249+/// inside a link (the TS `toggleLink`).
1250+pub fn can_link(cx: &Cx) -> bool {
1251+ if let Some(p) = cx.sel.cursor() {
1252+ return link_range_at(cx.m, p).is_some();
1253+ }
1254+ match pos::text_range(cx.m, &cx.sel) {
1255+ Some((from, to)) if from < to => has_markable(cx.m, from, to),
1256+ _ => false,
1257+ }
1258+}
1259+
1260+// ---------------------------------------------------------------------------
1261+// Paste and copy
1262+// ---------------------------------------------------------------------------
1263+
1264+fn block_lines(b: &Block, out: &mut Vec<String>) {
1265+ match b {
1266+ Block::Paragraph(v) | Block::Heading(_, v) => out.push(inline_text(v)),
1267+ Block::Code { text, .. } => out.push(text.clone()),
1268+ Block::Quote(bs) => bs.iter().for_each(|b| block_lines(b, out)),
1269+ Block::List { items, .. } => items.iter().flatten().for_each(|b| block_lines(b, out)),
1270+ Block::Rule => {}
1271+ }
1272+}
1273+
1274+/// Replaces the selection with pasted blocks, like PM's `replaceSelection`: the first
1275+/// block's text joins the caret's block, the rest follow inside the caret block's
1276+/// containers, and the text after the caret joins the last pasted block.
1277+pub fn insert_blocks(cx: &mut Cx, blocks: &[Block]) -> bool {
1278+ if blocks.is_empty() {
1279+ return false;
1280+ }
1281+ if !cx.sel.is_empty() && !delete_selection(cx, true) {
1282+ return false;
1283+ }
1284+ let Some((b, off)) = cx.caret() else { return false };
1285+ if b.kind() == Leaf::Code {
1286+ let mut lines = Vec::new();
1287+ blocks.iter().for_each(|x| block_lines(x, &mut lines));
1288+ return insert_text(cx, &lines.join("\n"));
1289+ }
1290+ let m = cx.m;
1291+ let mut flat = flat::flatten(blocks);
1292+ let inline = |f: &FlatBlock| f.attrs.wrap.is_empty() && matches!(f.attrs.kind, Leaf::Para | Leaf::Heading(_));
1293+ if flat.len() == 1 && inline(&flat[0]) {
1294+ return insert_inline(cx, &flat[0].inl);
1295+ }
1296+ // Keeps inside the paste, then shifted under the caret block's containers.
1297+ let l = b.depth();
1298+ let mut keeps = Vec::with_capacity(flat.len());
1299+ let mut prev: Option<Attrs> = None;
1300+ for f in &flat {
1301+ keeps.push(keep(prev.as_ref(), &f.attrs) + l);
1302+ prev = Some(f.attrs.clone());
1303+ }
1304+ for f in &mut flat {
1305+ let mut w = b.attrs.wrap.clone();
1306+ w.extend_from_slice(&f.attrs.wrap);
1307+ f.attrs.wrap = w;
1308+ f.attrs.join = None;
1309+ }
1310+ let head_inline = inline(&flat[0]);
1311+ let head_empty = off == b.start && !head_inline;
1312+ let tail_empty = off == b.sep;
1313+ let n = flat.len();
1314+ let merge_last = (n > 1 || !head_inline) && (inline(&flat[n - 1]) || tail_empty);
1315+ let nk = next_keep(m, &b);
1316+ let kb = keep_of(m, &b);
1317+
1318+ let mut at = off;
1319+ if head_inline {
1320+ at = m.insert_inline(at, &flat[0].inl);
1321+ }
1322+ let lo = if head_inline { 1 } else { 0 };
1323+ let hi = if merge_last { n - 1 } else { n };
1324+ let mut written: Vec<FlatBlock> = Vec::new();
1325+ // (attrs, keep) of each block from the caret block on, for relink.
1326+ let mut entries: Vec<(Attrs, Option<usize>)> = Vec::new();
1327+ if !head_empty {
1328+ written.push(FlatBlock { attrs: b.attrs.clone(), ..Default::default() });
1329+ entries.push((b.attrs.clone(), None));
1330+ }
1331+ for (j, f) in flat.iter().enumerate().take(hi).skip(lo) {
1332+ written.push(f.clone());
1333+ let k = if j == 0 { if head_empty { kb } else { l } } else { keeps[j] };
1334+ entries.push((f.attrs.clone(), Some(k)));
1335+ }
1336+ at = m.insert_blocks(at, &written);
1337+ let tail_attrs = if merge_last {
1338+ let f = &flat[n - 1];
1339+ if f.attrs.kind == Leaf::Code {
1340+ at = m.insert(at, &f.plain(), &Marks::none());
1341+ } else {
1342+ at = m.insert_inline(at, &f.inl);
1343+ }
1344+ let k = if n == 1 && head_empty { kb } else { keeps[n - 1] };
1345+ (f.attrs.clone(), Some(k))
1346+ } else {
1347+ (Attrs { kind: b.kind(), lang: b.attrs.lang.clone(), wrap: b.attrs.wrap.clone(), ..Attrs::default() }, Some(l))
1348+ };
1349+ entries.push(tail_attrs);
1350+ relink(m, b.index, entries, nk);
1351+ cx.set_caret(pos::snap(m, at));
1352+ true
1353+}
1354+
1355+/// The selected content as blocks. A selection inside one block gives one paragraph
1356+/// (pasting it back merges into the target block).
1357+pub fn selected_blocks(m: &Model, sel: &Selection) -> Vec<Block> {
1358+ if let Selection::Node(p) = *sel {
1359+ let b = m.at(p);
1360+ if b.kind() == Leaf::Rule {
1361+ return vec![Block::Rule];
1362+ }
1363+ let fb = flat::read_delta(m.slice(p, p + 1));
1364+ return vec![Block::Paragraph(fb.into_iter().next().map(|f| f.inl).unwrap_or_default())];
1365+ }
1366+ let Some((from, to)) = pos::text_range(m, sel) else { return Vec::new() };
1367+ let (x, y) = (m.at(from), m.at(to));
1368+ if x.index == y.index {
1369+ let fb = flat::read_delta(m.slice(from, to));
1370+ let inl = fb.into_iter().next().map(|mut f| {
1371+ if x.kind() == Leaf::Code {
1372+ vec![Inline::Text(f.plain(), Default::default())]
1373+ } else {
1374+ std::mem::take(&mut f.inl)
1375+ }
1376+ });
1377+ return vec![Block::Paragraph(inl.unwrap_or_default())];
1378+ }
1379+ let mut blocks = flat::read_delta(m.slice(from, to));
1380+ if to > y.start
1381+ && let Some(last) = blocks.last_mut()
1382+ {
1383+ last.attrs = y.attrs.clone();
1384+ if last.attrs.kind == Leaf::Code {
1385+ let t = last.plain();
1386+ last.inl = vec![Inline::Text(t, Default::default())];
1387+ }
1388+ }
1389+ flat::nest(&blocks)
1390+}
crates/editor/src/core/doc.rsadded+60 -0
@@ -0,0 +1,60 @@
1+//! The block vocabulary of commands and the toolbar: leaf kinds and containers.
2+
3+use note_model::flat::{self, Wrap};
4+
5+#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
6+pub enum Kind {
7+ Paragraph,
8+ Heading(u8),
9+ CodeBlock,
10+ Rule,
11+ Blockquote,
12+ BulletList,
13+ OrderedList,
14+}
15+
16+impl Kind {
17+ pub fn leaf(self) -> Option<flat::Kind> {
18+ Some(match self {
19+ Kind::Paragraph => flat::Kind::Para,
20+ Kind::Heading(n) => flat::Kind::Heading(n),
21+ Kind::CodeBlock => flat::Kind::Code,
22+ Kind::Rule => flat::Kind::Rule,
23+ _ => return None,
24+ })
25+ }
26+
27+ pub fn wrap(self) -> Option<Wrap> {
28+ Some(match self {
29+ Kind::Blockquote => Wrap::Quote,
30+ Kind::BulletList => Wrap::Bullet,
31+ Kind::OrderedList => Wrap::Ordered,
32+ _ => return None,
33+ })
34+ }
35+
36+ pub fn of_leaf(k: flat::Kind) -> Kind {
37+ match k {
38+ flat::Kind::Para => Kind::Paragraph,
39+ flat::Kind::Heading(n) => Kind::Heading(n),
40+ flat::Kind::Code => Kind::CodeBlock,
41+ flat::Kind::Rule => Kind::Rule,
42+ }
43+ }
44+
45+ pub fn of_wrap(w: Wrap) -> Kind {
46+ match w {
47+ Wrap::Quote => Kind::Blockquote,
48+ Wrap::Bullet => Kind::BulletList,
49+ Wrap::Ordered => Kind::OrderedList,
50+ }
51+ }
52+
53+ pub fn is_textblock(self) -> bool {
54+ matches!(self, Kind::Paragraph | Kind::Heading(_) | Kind::CodeBlock)
55+ }
56+
57+ pub fn is_list(self) -> bool {
58+ matches!(self, Kind::BulletList | Kind::OrderedList)
59+ }
60+}
crates/editor/src/core/history.rsadded+89 -0
@@ -0,0 +1,89 @@
1+//! Undo and redo over the model's recorded inverses. A step is one command, or a run
2+//! of commands within [`MERGE_MS`] of each other (typing); [`History::checkpoint`]
3+//! closes the current step.
4+
5+use super::model::{Inverse, Model};
6+use super::pos::{SelAnchors, Selection};
7+
8+pub const MERGE_MS: f64 = 1000.0;
9+/// Steps kept per stack.
10+const MAX_STEPS: usize = 500;
11+
12+struct Step {
13+ ops: Vec<Inverse>,
14+ before: SelAnchors,
15+ after: SelAnchors,
16+ at: f64,
17+}
18+
19+#[derive(Default)]
20+pub struct History {
21+ undo: Vec<Step>,
22+ redo: Vec<Step>,
23+ closed: bool,
24+}
25+
26+impl History {
27+ /// Records the ops `m` collected for one command.
28+ pub fn push(&mut self, m: &Model, before: &Selection, after: &Selection, now: f64) {
29+ let ops = m.take_ops();
30+ if ops.is_empty() {
31+ return;
32+ }
33+ self.redo.clear();
34+ if !self.closed
35+ && let Some(top) = self.undo.last_mut()
36+ && now - top.at < MERGE_MS
37+ {
38+ top.ops.extend(ops);
39+ top.after = SelAnchors::new(m, after);
40+ top.at = now;
41+ return;
42+ }
43+ self.closed = false;
44+ self.undo.push(Step { ops, before: SelAnchors::new(m, before), after: SelAnchors::new(m, after), at: now });
45+ if self.undo.len() > MAX_STEPS {
46+ self.undo.remove(0);
47+ }
48+ }
49+
50+ pub fn checkpoint(&mut self) {
51+ self.closed = true;
52+ }
53+
54+ pub fn can_undo(&self) -> bool {
55+ !self.undo.is_empty()
56+ }
57+
58+ pub fn can_redo(&self) -> bool {
59+ !self.redo.is_empty()
60+ }
61+
62+ /// Undoes the last step; returns the selection to restore.
63+ pub fn undo(&mut self, m: &Model) -> Option<Selection> {
64+ let step = self.undo.pop()?;
65+ let inv = replay(m, &step.ops);
66+ let sel = step.before.resolve(m);
67+ self.redo.push(Step { ops: inv, before: step.after, after: step.before, at: step.at });
68+ self.closed = true;
69+ Some(sel)
70+ }
71+
72+ pub fn redo(&mut self, m: &Model) -> Option<Selection> {
73+ let step = self.redo.pop()?;
74+ let inv = replay(m, &step.ops);
75+ let sel = step.before.resolve(m);
76+ self.undo.push(Step { ops: inv, before: step.after, after: step.before, at: step.at });
77+ self.closed = true;
78+ Some(sel)
79+ }
80+}
81+
82+/// Applies `ops` newest first; returns their inverses.
83+fn replay(m: &Model, ops: &[Inverse]) -> Vec<Inverse> {
84+ m.take_ops();
85+ for op in ops.iter().rev() {
86+ m.apply(op);
87+ }
88+ m.take_ops()
89+}
crates/editor/src/core/marks.rsadded+151 -0
@@ -0,0 +1,151 @@
1+//! The inline mark set and its LoroText encoding: `strong`/`em`/`code` hold `{}`,
2+//! `link` holds `{href, title}` (title null when absent). A null value means unset.
3+
4+use std::collections::HashMap;
5+
6+use loro::{LoroDoc, LoroValue};
7+
8+pub const STRONG: &str = "strong";
9+pub const EM: &str = "em";
10+pub const CODE: &str = "code";
11+pub const LINK: &str = "link";
12+
13+#[derive(Clone, Debug, Default, PartialEq, Eq)]
14+pub struct Link {
15+ pub href: String,
16+ pub title: Option<String>,
17+}
18+
19+#[derive(Clone, Debug, Default, PartialEq, Eq)]
20+pub struct Marks {
21+ pub strong: bool,
22+ pub em: bool,
23+ pub code: bool,
24+ pub link: Option<Link>,
25+}
26+
27+#[derive(Clone, Copy, Debug, PartialEq, Eq)]
28+pub enum MarkType {
29+ Strong,
30+ Em,
31+ Code,
32+ Link,
33+}
34+
35+impl MarkType {
36+ pub fn key(self) -> &'static str {
37+ match self {
38+ MarkType::Strong => STRONG,
39+ MarkType::Em => EM,
40+ MarkType::Code => CODE,
41+ MarkType::Link => LINK,
42+ }
43+ }
44+
45+ /// Whether typing at the end of the mark extends it (PM `inclusive`).
46+ pub fn inclusive(self) -> bool {
47+ !matches!(self, MarkType::Link)
48+ }
49+}
50+
51+/// The body's mark expand rules ([`note_model::schema::text_style_config`]).
52+/// Runtime-only in Loro, so every doc that marks text must call this first.
53+pub fn configure(doc: &LoroDoc) {
54+ doc.config_text_style(note_model::schema::text_style_config());
55+}
56+
57+fn empty_map() -> LoroValue {
58+ LoroValue::from(HashMap::<String, LoroValue>::new())
59+}
60+
61+impl Marks {
62+ pub fn none() -> Self {
63+ Self::default()
64+ }
65+
66+ pub fn is_empty(&self) -> bool {
67+ !self.strong && !self.em && !self.code && self.link.is_none()
68+ }
69+
70+ pub fn has(&self, t: MarkType) -> bool {
71+ match t {
72+ MarkType::Strong => self.strong,
73+ MarkType::Em => self.em,
74+ MarkType::Code => self.code,
75+ MarkType::Link => self.link.is_some(),
76+ }
77+ }
78+
79+ pub fn set(&mut self, t: MarkType, on: bool) {
80+ match t {
81+ MarkType::Strong => self.strong = on,
82+ MarkType::Em => self.em = on,
83+ MarkType::Code => self.code = on,
84+ MarkType::Link => {
85+ if !on {
86+ self.link = None
87+ }
88+ }
89+ }
90+ }
91+
92+ /// Reads the attribute map of a delta run.
93+ pub fn from_attrs<S: std::hash::BuildHasher>(attrs: Option<&HashMap<String, LoroValue, S>>) -> Self {
94+ let mut m = Marks::default();
95+ let Some(attrs) = attrs else { return m };
96+ let on = |k: &str| attrs.get(k).is_some_and(|v| !v.is_null());
97+ m.strong = on(STRONG);
98+ m.em = on(EM);
99+ m.code = on(CODE);
100+ if let Some(LoroValue::Map(map)) = attrs.get(LINK)
101+ && let Some(href) = map.get("href").and_then(|v| v.as_string()) {
102+ let title = map.get("title").and_then(|v| v.as_string()).map(|s| s.to_string());
103+ m.link = Some(Link { href: href.to_string(), title });
104+ }
105+ m
106+ }
107+
108+ /// The value of mark key `key` (None when unset or not a mark key).
109+ pub fn value_of(&self, key: &str) -> Option<LoroValue> {
110+ ALL.into_iter().find(|t| t.key() == key).and_then(|t| self.value(t))
111+ }
112+
113+ fn value(&self, t: MarkType) -> Option<LoroValue> {
114+ match t {
115+ MarkType::Link => self.link.as_ref().map(|l| {
116+ let mut map: HashMap<String, LoroValue> = HashMap::new();
117+ map.insert("href".into(), LoroValue::from(l.href.as_str()));
118+ map.insert(
119+ "title".into(),
120+ l.title.as_deref().map_or(LoroValue::Null, LoroValue::from),
121+ );
122+ LoroValue::from(map)
123+ }),
124+ _ => self.has(t).then(empty_map),
125+ }
126+ }
127+}
128+
129+pub const ALL: [MarkType; 4] = [MarkType::Link, MarkType::Em, MarkType::Strong, MarkType::Code];
130+
131+impl From<&note_model::marks::Marks> for Marks {
132+ fn from(m: &note_model::marks::Marks) -> Self {
133+ Marks {
134+ strong: m.strong,
135+ em: m.em,
136+ code: m.code,
137+ link: m.link.as_ref().map(|(href, title)| Link { href: href.clone(), title: title.clone() }),
138+ }
139+ }
140+}
141+
142+impl From<&Marks> for note_model::marks::Marks {
143+ fn from(m: &Marks) -> Self {
144+ note_model::marks::Marks {
145+ strong: m.strong,
146+ em: m.em,
147+ code: m.code,
148+ link: m.link.as_ref().map(|l| (l.href.clone(), l.title.clone())),
149+ }
150+ }
151+}
crates/editor/src/core/mod.rsadded+11 -0
@@ -0,0 +1,11 @@
1+pub mod commands;
2+pub mod doc;
3+pub mod history;
4+pub mod marks;
5+pub mod model;
6+pub mod pos;
7+
8+#[cfg(test)]
9+mod testutil;
10+#[cfg(test)]
11+mod tests;
crates/editor/src/core/model.rsadded+800 -0
@@ -0,0 +1,800 @@
1+//! The note body as the editor edits it: the Loro text, its [`BlockIndex`] and the
2+//! primitive edits.
3+//!
4+//! The index follows the body's text events, applied right after each commit or
5+//! import ([`Model::commit`], [`Model::import`]), so it is current between edits. Every
6+//! primitive commits, and records its inverse for [`super::history::History`]:
7+//! positions are held by Loro cursors ([`Anchor`]), and anchors on text a delete removes
8+//! move to the copy its undo restores.
9+//!
10+//! Offsets in the public API are UTF-16 from the start of the body (the DOM's unit);
11+//! Loro positions are Unicode scalars and stay internal.
12+
13+use std::cell::{Cell, RefCell};
14+use std::collections::{HashMap, HashSet};
15+use std::rc::{Rc, Weak};
16+use std::sync::{Arc, Mutex};
17+
18+use loro::cursor::{Cursor, PosType, Side};
19+use loro::{ContainerTrait, LoroDoc, LoroText, LoroValue, TextDelta};
20+use note_model::blocks::{BlockIndex, Info, Splice};
21+use note_model::flat::{self, Attrs, FlatBlock, Kind, SEP};
22+use note_model::write::Inline;
23+
24+use super::marks::Marks;
25+
26+/// Origin of the editor's own commits.
27+pub const LOCAL: &str = "local";
28+
29+/// Every mark key the editor writes, inline first.
30+pub const KEYS: [&str; 10] = [
31+ "strong",
32+ "em",
33+ "code",
34+ "link",
35+ flat::KEY_IMAGE,
36+ flat::KEY_KIND,
37+ flat::KEY_LANG,
38+ flat::KEY_WRAP,
39+ flat::KEY_JOIN,
40+ flat::KEY_START,
41+];
42+/// The keys of inline content (marks and images).
43+pub const INLINE: [&str; 5] = ["strong", "em", "code", "link", flat::KEY_IMAGE];
44+
45+fn key(k: &str) -> Option<&'static str> {
46+ KEYS.iter().find(|s| **s == k).copied()
47+}
48+
49+/// One block: UTF-16 and Unicode offsets of its first content unit and its separator.
50+#[derive(Clone, Debug, PartialEq)]
51+pub struct Blk {
52+ pub index: usize,
53+ pub start: usize,
54+ pub sep: usize,
55+ pub startu: usize,
56+ pub sepu: usize,
57+ pub attrs: Attrs,
58+}
59+
60+impl Blk {
61+ fn new(info: Info, attrs: &Attrs) -> Blk {
62+ Blk { index: info.index, start: info.start16, sep: info.sep16(), startu: info.startu, sepu: info.sepu(), attrs: attrs.clone() }
63+ }
64+ /// Start of the next block.
65+ pub fn end(&self) -> usize {
66+ self.sep + 1
67+ }
68+ pub fn len(&self) -> usize {
69+ self.sep - self.start
70+ }
71+ pub fn is_empty(&self) -> bool {
72+ self.sep == self.start
73+ }
74+ pub fn kind(&self) -> Kind {
75+ self.attrs.kind
76+ }
77+ pub fn depth(&self) -> usize {
78+ self.attrs.wrap.len()
79+ }
80+ /// Whether a caret at `off` is inside (content start through the separator).
81+ pub fn holds(&self, off: usize) -> bool {
82+ self.start <= off && off <= self.sep
83+ }
84+}
85+
86+/// A position that follows edits, local and remote.
87+pub type Anchor = Rc<RefCell<Cursor>>;
88+
89+/// A mark change over a Unicode range: `value` None unsets `key`.
90+#[derive(Clone, Debug, PartialEq)]
91+pub struct Seg {
92+ pub from: usize,
93+ pub to: usize,
94+ pub key: &'static str,
95+ pub value: Option<LoroValue>,
96+}
97+
98+/// What undoes one primitive.
99+pub enum Inverse {
100+ /// Undoes an insert: deletes `first` through `last`.
101+ Remove { first: Anchor, last: Anchor },
102+ /// Undoes a delete: inserts `delta` at `at`, and moves each anchor of `revive`
103+ /// (those that were on the deleted text) to its offset in the copy.
104+ Restore { at: Anchor, delta: Vec<TextDelta>, revive: Vec<(Weak<RefCell<Cursor>>, usize)> },
105+ /// Undoes a restyle: segments relative to `at`.
106+ Restyle { at: Anchor, segs: Vec<Seg> },
107+}
108+
109+#[derive(Default)]
110+struct Rec {
111+ ops: Vec<Inverse>,
112+ /// End (Unicode) of the last insert while it is the last op: typing extends it.
113+ typing: Option<usize>,
114+ anchors: Vec<Weak<RefCell<Cursor>>>,
115+ /// Ids of chars known deleted. A deleted char never comes back, and resolving an
116+ /// anchor on one replays history (seconds on a huge note), so it happens once.
117+ dead: HashSet<loro::ID>,
118+}
119+
120+pub struct Model {
121+ pub doc: LoroDoc,
122+ pub text: LoroText,
123+ pending: Arc<Mutex<Vec<Vec<TextDelta>>>>,
124+ index: RefCell<BlockIndex>,
125+ splices: RefCell<Vec<Splice>>,
126+ rec: RefCell<Rec>,
127+ origin: Cell<&'static str>,
128+ _sub: loro::Subscription,
129+}
130+
131+fn plain_len(s: &str) -> (usize, usize) {
132+ note_model::flat::str_lens(s)
133+}
134+
135+impl Model {
136+ pub fn new(doc: LoroDoc) -> Model {
137+ let text = flat::body(&doc);
138+ let pending: Arc<Mutex<Vec<Vec<TextDelta>>>> = Arc::default();
139+ let queue = pending.clone();
140+ let sub = doc.subscribe(
141+ &text.id(),
142+ Arc::new(move |e| {
143+ let mut q = queue.lock().unwrap();
144+ for d in e.events {
145+ if let loro::event::Diff::Text(delta) = d.diff {
146+ q.push(delta);
147+ }
148+ }
149+ }),
150+ );
151+ let index = BlockIndex::read(&text);
152+ Model {
153+ doc,
154+ text,
155+ pending,
156+ index: RefCell::new(index),
157+ splices: RefCell::default(),
158+ rec: RefCell::default(),
159+ origin: Cell::new(LOCAL),
160+ _sub: sub,
161+ }
162+ }
163+
164+ /// Applies queued text events to the index.
165+ pub fn sync(&self) {
166+ let deltas = std::mem::take(&mut *self.pending.lock().unwrap());
167+ for d in deltas {
168+ let sp = self.index.borrow_mut().apply(&d, &self.text);
169+ self.splices.borrow_mut().extend(sp);
170+ }
171+ }
172+
173+ pub fn commit(&self) {
174+ self.doc.set_next_commit_origin(self.origin.get());
175+ self.doc.commit();
176+ self.sync();
177+ }
178+
179+ /// Commits with `origin` instead of [`LOCAL`].
180+ pub fn commit_as(&self, origin: &'static str) {
181+ self.origin.set(origin);
182+ self.commit();
183+ self.origin.set(LOCAL);
184+ }
185+
186+ pub fn import(&self, bytes: &[u8]) -> loro::LoroResult<()> {
187+ self.commit();
188+ let r = self.doc.import(bytes).map(|_| ());
189+ self.sync();
190+ r
191+ }
192+
193+ /// Block changes since the last call, for the view.
194+ pub fn take_splices(&self) -> Vec<Splice> {
195+ self.sync();
196+ std::mem::take(&mut *self.splices.borrow_mut())
197+ }
198+
199+ /// Rebuilds the index from the text (after a checkout or a wholesale change).
200+ pub fn reindex(&self) {
201+ self.pending.lock().unwrap().clear();
202+ let n = self.index.borrow().len();
203+ *self.index.borrow_mut() = BlockIndex::read(&self.text);
204+ let m = self.index.borrow().len();
205+ self.splices.borrow_mut().push(Splice { at: 0, removed: n, inserted: m, edit: None });
206+ }
207+
208+ // -----------------------------------------------------------------------
209+ // Lookups
210+ // -----------------------------------------------------------------------
211+
212+ /// Runs `f` on the index. Don't edit inside `f`.
213+ pub fn with<R>(&self, f: impl FnOnce(&BlockIndex) -> R) -> R {
214+ f(&self.index.borrow())
215+ }
216+
217+ pub fn len(&self) -> usize {
218+ self.index.borrow().len()
219+ }
220+
221+ pub fn is_empty(&self) -> bool {
222+ self.index.borrow().is_empty()
223+ }
224+
225+ /// Whether the body ends without a separator (see [`BlockIndex::open`]).
226+ pub fn open(&self) -> bool {
227+ self.index.borrow().open
228+ }
229+
230+ /// UTF-16 length of the body.
231+ pub fn total(&self) -> usize {
232+ self.index.borrow().total16()
233+ }
234+
235+ pub fn block(&self, i: usize) -> Option<Blk> {
236+ let ix = self.index.borrow();
237+ ix.get(i).map(|info| Blk::new(info, ix.attrs(&info)))
238+ }
239+
240+ /// The block holding `off` (a separator belongs to its block; past the end, the
241+ /// last). An empty body (before the note loads) reads as one empty paragraph.
242+ pub fn at(&self, off: usize) -> Blk {
243+ let ix = self.index.borrow();
244+ match ix.find16(off) {
245+ Some(info) => Blk::new(info, ix.attrs(&info)),
246+ None => Blk { index: 0, start: 0, sep: 0, startu: 0, sepu: 0, attrs: Attrs::default() },
247+ }
248+ }
249+
250+ pub fn last(&self) -> Blk {
251+ self.at(self.total())
252+ }
253+
254+ /// Blocks `lo..hi`.
255+ pub fn blocks(&self, lo: usize, hi: usize) -> Vec<Blk> {
256+ let ix = self.index.borrow();
257+ ix.iter_from(lo).take(hi.saturating_sub(lo)).map(|i| Blk::new(i, ix.attrs(&i))).collect()
258+ }
259+
260+ /// Calls `f` on blocks from `i` on (`back`: from `i - 1` down) until it returns false.
261+ pub fn scan(&self, i: usize, back: bool, mut f: impl FnMut(&Info, &Attrs) -> bool) {
262+ let ix = self.index.borrow();
263+ if back {
264+ for info in ix.iter_back(i) {
265+ if !f(&info, ix.attrs(&info)) {
266+ return;
267+ }
268+ }
269+ } else {
270+ for info in ix.iter_from(i) {
271+ if !f(&info, ix.attrs(&info)) {
272+ return;
273+ }
274+ }
275+ }
276+ }
277+
278+ pub fn to_u(&self, off: usize) -> usize {
279+ if off == 0 {
280+ return 0;
281+ }
282+ self.text.convert_pos(off, PosType::Utf16, PosType::Unicode).unwrap_or_else(|| self.text.len_unicode())
283+ }
284+
285+ pub fn to16(&self, u: usize) -> usize {
286+ if u == 0 {
287+ return 0;
288+ }
289+ self.text.convert_pos(u, PosType::Unicode, PosType::Utf16).unwrap_or_else(|| self.text.len_utf16())
290+ }
291+
292+ /// Rich runs of `from..to` (UTF-16).
293+ pub fn slice(&self, from: usize, to: usize) -> Vec<TextDelta> {
294+ if from >= to {
295+ return Vec::new();
296+ }
297+ self.text.slice_delta(from, to, PosType::Utf16).unwrap_or_default()
298+ }
299+
300+ /// Plain text of `from..to` (UTF-16).
301+ pub fn plain(&self, from: usize, to: usize) -> String {
302+ if from >= to {
303+ return String::new();
304+ }
305+ let (a, b) = (self.to_u(from), self.to_u(to));
306+ self.text.slice(a, b).unwrap_or_default()
307+ }
308+
309+ /// The content of block `b` (inline runs; code as one text run).
310+ pub fn read_block(&self, b: &Blk) -> FlatBlock {
311+ let mut delta = self.slice(b.start, b.end());
312+ if self.open() && b.index + 1 == self.len() {
313+ delta.push(TextDelta::Insert { insert: SEP.to_string(), attributes: None });
314+ }
315+ let mut v = flat::read_delta(delta);
316+ let mut fb = v.pop().unwrap_or_default();
317+ fb.attrs = b.attrs.clone();
318+ if fb.attrs.kind == Kind::Code {
319+ let text = fb.plain();
320+ fb.inl = if text.is_empty() { Vec::new() } else { vec![note_model::write::Inline::Text(text, Default::default())] };
321+ }
322+ fb
323+ }
324+
325+ // -----------------------------------------------------------------------
326+ // Anchors
327+ // -----------------------------------------------------------------------
328+
329+ fn anchor_u(&self, u: usize) -> Anchor {
330+ let c = self.text.get_cursor(u, Side::Left).expect("body is attached");
331+ let a = Rc::new(RefCell::new(c));
332+ let mut rec = self.rec.borrow_mut();
333+ if rec.anchors.len() > 64 && rec.anchors.len().is_power_of_two() {
334+ rec.anchors.retain(|w| w.strong_count() > 0);
335+ }
336+ rec.anchors.push(Rc::downgrade(&a));
337+ a
338+ }
339+
340+ /// An anchor at UTF-16 offset `off`.
341+ pub fn anchor(&self, off: usize) -> Anchor {
342+ self.anchor_u(self.to_u(off))
343+ }
344+
345+ /// Unicode position of an anchor, and whether its char is still there.
346+ fn resolve_u(&self, a: &Anchor) -> (usize, bool) {
347+ match self.doc.get_cursor_pos(&a.borrow()) {
348+ Ok(r) => (r.current.pos.min(self.text.len_unicode()), r.update.is_none()),
349+ Err(_) => (0, false),
350+ }
351+ }
352+
353+ /// A plain cursor at `off`, for the presence wire format.
354+ pub fn cursor(&self, off: usize) -> Option<Cursor> {
355+ self.text.get_cursor(self.to_u(off), Side::Left)
356+ }
357+
358+ /// The offset of a cursor, if it is on the body.
359+ pub fn cursor_pos(&self, c: &Cursor) -> Option<usize> {
360+ if c.container != self.text.id() {
361+ return None;
362+ }
363+ let r = self.doc.get_cursor_pos(c).ok()?;
364+ Some(self.to16(r.current.pos.min(self.text.len_unicode())))
365+ }
366+
367+ /// UTF-16 offset of an anchor.
368+ pub fn resolve(&self, a: &Anchor) -> usize {
369+ self.to16(self.resolve_u(a).0)
370+ }
371+
372+ // -----------------------------------------------------------------------
373+ // Primitives
374+ // -----------------------------------------------------------------------
375+
376+ fn push(&self, op: Inverse) {
377+ let mut rec = self.rec.borrow_mut();
378+ rec.typing = None;
379+ rec.ops.push(op);
380+ }
381+
382+ /// The inverses recorded since the last call, oldest first.
383+ pub fn take_ops(&self) -> Vec<Inverse> {
384+ let mut rec = self.rec.borrow_mut();
385+ rec.typing = None;
386+ std::mem::take(&mut rec.ops)
387+ }
388+
389+ /// Inserts plain text carrying exactly `marks`; separators in `s` become line
390+ /// breaks. Returns the end offset.
391+ pub fn insert(&self, at: usize, s: &str, marks: &Marks) -> usize {
392+ if s.is_empty() {
393+ return at;
394+ }
395+ let s = s.replace(SEP, "\n");
396+ let inl = [Inline::Text(s, marks.into())];
397+ self.insert_inline(at, &inl)
398+ }
399+
400+ /// Inserts inline content (text runs, breaks, images) inside a block. Returns the
401+ /// end offset.
402+ pub fn insert_inline(&self, at: usize, inl: &[Inline]) -> usize {
403+ let u = self.to_u(at);
404+ let fb = FlatBlock { inl: inl.to_vec(), ..Default::default() };
405+ let built = flat::build(std::slice::from_ref(&fb));
406+ let mut s = built.text;
407+ s.pop();
408+ if s.is_empty() {
409+ return at;
410+ }
411+ let (n, n16) = plain_len(&s);
412+ self.text.insert(u, &s).expect("insert");
413+ // Every unit of `s` gets exactly its run's marks, nothing the neighbours lend.
414+ let mut want: Vec<(usize, Vec<(&'static str, Option<LoroValue>)>)> = Vec::new();
415+ let mut pos = 0;
416+ let mut cut = |to: usize, vals: Vec<(&'static str, Option<LoroValue>)>, want: &mut Vec<_>| {
417+ if to > pos {
418+ want.push((to - pos, vals));
419+ pos = to;
420+ }
421+ };
422+ let none = || INLINE.iter().map(|k| (*k, None)).collect::<Vec<_>>();
423+ let mut marks: Vec<(std::ops::Range<usize>, Option<&note_model::marks::Marks>, Option<&LoroValue>)> = Vec::new();
424+ for (r, m) in &built.inline {
425+ marks.push((r.clone(), Some(m), None));
426+ }
427+ for (p, v) in &built.images {
428+ marks.push((*p..*p + 1, None, Some(v)));
429+ }
430+ marks.sort_by_key(|m| m.0.start);
431+ for (r, m, img) in marks {
432+ cut(r.start, none(), &mut want);
433+ let mut vals = none();
434+ if let Some(m) = m {
435+ let m: Marks = m.into();
436+ for v in vals.iter_mut() {
437+ v.1 = m.value_of(v.0);
438+ }
439+ }
440+ if let Some(img) = img {
441+ vals[4].1 = Some(img.clone());
442+ }
443+ cut(r.end, vals, &mut want);
444+ }
445+ cut(n, none(), &mut want);
446+ self.force(u, &want);
447+ let typing = self.rec.borrow().typing;
448+ let extended = typing == Some(u) && {
449+ let rec = self.rec.borrow();
450+ match rec.ops.last() {
451+ Some(Inverse::Remove { last, .. }) => {
452+ *last.borrow_mut() = self.text.get_cursor(u + n - 1, Side::Left).expect("cursor");
453+ true
454+ }
455+ _ => false,
456+ }
457+ };
458+ if !extended {
459+ let (first, last) = (self.anchor_u(u), self.anchor_u(u + n - 1));
460+ self.push(Inverse::Remove { first, last });
461+ }
462+ self.rec.borrow_mut().typing = Some(u + n);
463+ self.commit();
464+ at + n16
465+ }
466+
467+ /// Inserts whole blocks at `at` (a block start, or inside content to split there).
468+ /// Returns the end offset.
469+ pub fn insert_blocks(&self, at: usize, blocks: &[FlatBlock]) -> usize {
470+ let u = self.to_u(at);
471+ let n = self.write_u(u, blocks);
472+ self.commit();
473+ if n == 0 { at } else { self.to16(u + n) }
474+ }
475+
476+ fn write_u(&self, u: usize, blocks: &[FlatBlock]) -> usize {
477+ let n = flat::write(&self.text, u, blocks, true).expect("write blocks");
478+ if n > 0 {
479+ let (first, last) = (self.anchor_u(u), self.anchor_u(u + n - 1));
480+ self.push(Inverse::Remove { first, last });
481+ }
482+ n
483+ }
484+
485+ /// Deletes `from..to` (UTF-16).
486+ pub fn delete(&self, from: usize, to: usize) {
487+ if from < to {
488+ self.delete_u(self.to_u(from), self.to_u(to));
489+ self.commit();
490+ }
491+ }
492+
493+ fn delete_u(&self, a: usize, b: usize) {
494+ if a >= b {
495+ return;
496+ }
497+ let delta = self.text.slice_delta(a, b, PosType::Unicode).expect("slice");
498+ let revive = self.anchors_in(a, b);
499+ self.text.delete(a, b - a).expect("delete");
500+ let at = self.anchor_u(a);
501+ self.push(Inverse::Restore { at, delta, revive });
502+ }
503+
504+ /// Anchors on the chars `a..b` with their offsets. A short range compares char ids
505+ /// (no anchor is resolved); a long one resolves every anchor.
506+ fn anchors_in(&self, a: usize, b: usize) -> Vec<(Weak<RefCell<Cursor>>, usize)> {
507+ let live: Vec<(Weak<RefCell<Cursor>>, Anchor)> =
508+ self.rec.borrow().anchors.iter().filter_map(|w| w.upgrade().map(|x| (w.clone(), x))).collect();
509+ if live.is_empty() {
510+ return Vec::new();
511+ }
512+ let found: Vec<(Weak<RefCell<Cursor>>, usize, Option<loro::ID>)> = if b - a <= 64 {
513+ let ids: HashMap<loro::ID, usize> =
514+ (a..b).filter_map(|p| self.text.get_cursor(p, Side::Left).and_then(|c| c.id).map(|id| (id, p - a))).collect();
515+ live.into_iter().filter_map(|(w, x)| x.borrow().id.and_then(|id| ids.get(&id).map(|off| (w.clone(), *off, Some(id))))).collect()
516+ } else {
517+ let mut gone = Vec::new();
518+ let found = live
519+ .into_iter()
520+ .filter_map(|(w, x)| {
521+ let id = x.borrow().id;
522+ if id.is_some_and(|id| self.rec.borrow().dead.contains(&id)) {
523+ return None;
524+ }
525+ let (p, alive) = self.resolve_u(&x);
526+ if !alive {
527+ gone.extend(id);
528+ }
529+ (alive && (a..b).contains(&p)).then(|| (w, p - a, id))
530+ })
531+ .collect();
532+ self.rec.borrow_mut().dead.extend(gone);
533+ found
534+ };
535+ // These chars are about to be deleted.
536+ self.rec.borrow_mut().dead.extend(found.iter().filter_map(|f| f.2));
537+ found.into_iter().map(|(w, off, _)| (w, off)).collect()
538+ }
539+
540+ /// Replaces single chars (UTF-16 offsets of BMP chars): `Some(attrs)` puts a
541+ /// separator with those attributes there, `None` a line break. One commit.
542+ pub fn swap_chars(&self, mut at: Vec<(usize, Option<Attrs>)>) {
543+ at.sort_by_key(|x| std::cmp::Reverse(x.0));
544+ let us: Vec<usize> = at.iter().map(|x| self.to_u(x.0)).collect();
545+ for ((_, attrs), u) in at.into_iter().zip(us) {
546+ self.delete_u(u, u + 1);
547+ match attrs {
548+ Some(a) => {
549+ self.write_u(u, &[FlatBlock { attrs: a, ..Default::default() }]);
550+ }
551+ None => {
552+ self.text.insert(u, "\n").expect("insert");
553+ self.force(u, &[(1, KEYS.iter().map(|k| (*k, None)).collect())]);
554+ let (first, last) = (self.anchor_u(u), self.anchor_u(u));
555+ self.push(Inverse::Remove { first, last });
556+ }
557+ }
558+ }
559+ self.commit();
560+ }
561+
562+ /// Applies mark changes (Unicode ranges), recording what they replace.
563+ pub fn restyle(&self, segs: Vec<Seg>) {
564+ let segs = merge_segs(segs);
565+ let Some(lo) = segs.iter().map(|s| s.from).min() else { return };
566+ let hi = segs.iter().map(|s| s.to).max().unwrap();
567+ let runs = Runs::new(self.text.slice_delta(lo, hi, PosType::Unicode).unwrap_or_default(), lo);
568+ let mut inverse = Vec::new();
569+ let mut apply = Vec::new();
570+ for s in segs {
571+ let mut changed = false;
572+ runs.each(s.from, s.to, |a, b, attrs| {
573+ let old = attrs.get(s.key).filter(|v| !v.is_null()).cloned();
574+ if old != s.value {
575+ changed = true;
576+ }
577+ inverse.push(Seg { from: a - lo, to: b - lo, key: s.key, value: old });
578+ });
579+ if changed {
580+ apply.push(s);
581+ }
582+ }
583+ if apply.is_empty() {
584+ return;
585+ }
586+ self.apply_raw(&apply);
587+ let at = self.anchor_u(lo);
588+ self.push(Inverse::Restyle { at, segs: merge_segs(inverse) });
589+ self.commit();
590+ }
591+
592+ /// Sets the attributes of blocks `lo..`, one entry per block (None: unchanged).
593+ /// Equal values on consecutive blocks become one mark.
594+ pub fn set_attrs(&self, lo: usize, new: &[Option<Attrs>]) {
595+ if new.iter().all(Option::is_none) {
596+ return;
597+ }
598+ let cur = self.blocks(lo, lo + new.len());
599+ let mut segs = Vec::new();
600+ for (k, key) in flat::BLOCK_KEYS.iter().enumerate() {
601+ let key = self::key(key).unwrap();
602+ let mut i = 0;
603+ while i < cur.len() {
604+ let Some(want) = &new[i] else {
605+ i += 1;
606+ continue;
607+ };
608+ let v = want.values()[k].clone();
609+ let mut j = i + 1;
610+ let mut differs = cur[i].attrs.values()[k] != v;
611+ while j < cur.len() && new[j].as_ref().is_some_and(|w| w.values()[k] == v) {
612+ differs |= cur[j].attrs.values()[k] != v;
613+ j += 1;
614+ }
615+ if differs {
616+ segs.push(Seg { from: cur[i].sepu, to: cur[j - 1].sepu + 1, key, value: v });
617+ }
618+ i = j;
619+ }
620+ }
621+ self.restyle(segs);
622+ }
623+
624+ /// Makes the runs from `u` carry exactly the given values (unrecorded).
625+ fn force(&self, u: usize, want: &[(usize, Vec<(&'static str, Option<LoroValue>)>)]) {
626+ let total: usize = want.iter().map(|w| w.0).sum();
627+ if total == 0 {
628+ return;
629+ }
630+ let runs = Runs::new(self.text.slice_delta(u, u + total, PosType::Unicode).unwrap_or_default(), u);
631+ let mut segs = Vec::new();
632+ let mut pos = u;
633+ for (len, vals) in want {
634+ runs.each(pos, pos + len, |a, b, attrs| {
635+ for (k, v) in vals {
636+ let have = attrs.get(*k).filter(|x| !x.is_null());
637+ if have != v.as_ref() {
638+ segs.push(Seg { from: a, to: b, key: k, value: v.clone() });
639+ }
640+ }
641+ });
642+ pos += len;
643+ }
644+ self.apply_raw(&merge_segs(segs));
645+ }
646+
647+ fn apply_raw(&self, segs: &[Seg]) {
648+ for s in segs {
649+ match &s.value {
650+ Some(v) => self.text.mark(s.from..s.to, s.key, v.clone()).expect("mark"),
651+ None => self.text.unmark(s.from..s.to, s.key).expect("unmark"),
652+ }
653+ }
654+ }
655+
656+ /// Inserts rich runs at Unicode `u` exactly as they were.
657+ fn restore(&self, u: usize, delta: &[TextDelta]) {
658+ let mut s = String::new();
659+ let mut want: Vec<(usize, Vec<(&'static str, Option<LoroValue>)>)> = Vec::new();
660+ for d in delta {
661+ let TextDelta::Insert { insert, attributes } = d else { continue };
662+ s.push_str(insert);
663+ let vals = KEYS.iter().map(|k| (*k, attributes.as_ref().and_then(|a| a.get(*k)).filter(|v| !v.is_null()).cloned())).collect();
664+ want.push((insert.chars().count(), vals));
665+ }
666+ if s.is_empty() {
667+ return;
668+ }
669+ let n = s.chars().count();
670+ self.text.insert(u, &s).expect("insert");
671+ // One insert carries one set of inherited marks: read it off the first char
672+ // instead of slicing the whole range.
673+ let first = self.text.slice_delta(u, u + 1, PosType::Unicode).unwrap_or_default();
674+ let have = |k: &str| match first.first() {
675+ Some(TextDelta::Insert { attributes: Some(a), .. }) => a.get(k).filter(|x| !x.is_null()),
676+ _ => None,
677+ };
678+ let mut segs = Vec::new();
679+ let mut pos = u;
680+ for (len, vals) in &want {
681+ for (k, v) in vals {
682+ if have(k) != v.as_ref() {
683+ segs.push(Seg { from: pos, to: pos + len, key: k, value: v.clone() });
684+ }
685+ }
686+ pos += len;
687+ }
688+ self.apply_raw(&merge_segs(segs));
689+ let (first, last) = (self.anchor_u(u), self.anchor_u(u + n - 1));
690+ self.push(Inverse::Remove { first, last });
691+ }
692+
693+ /// Applies an inverse, recording its own inverse (undo records redo).
694+ pub fn apply(&self, op: &Inverse) {
695+ match op {
696+ Inverse::Remove { first, last } => {
697+ let (a, _) = self.resolve_u(first);
698+ let (b, alive) = self.resolve_u(last);
699+ let b = if alive { b + 1 } else { b };
700+ self.delete_u(a, b.min(self.text.len_unicode()));
701+ self.commit();
702+ }
703+ Inverse::Restore { at, delta, revive } => {
704+ let (u, _) = self.resolve_u(at);
705+ self.restore(u, delta);
706+ for (w, off) in revive {
707+ if let Some(a) = w.upgrade() {
708+ *a.borrow_mut() = self.text.get_cursor(u + off, Side::Left).expect("cursor");
709+ }
710+ }
711+ self.commit();
712+ }
713+ Inverse::Restyle { at, segs } => {
714+ let (base, _) = self.resolve_u(at);
715+ let len = self.text.len_unicode();
716+ let segs = segs
717+ .iter()
718+ .map(|s| Seg { from: (base + s.from).min(len), to: (base + s.to).min(len), key: s.key, value: s.value.clone() })
719+ .filter(|s| s.from < s.to)
720+ .collect();
721+ self.restyle(segs);
722+ }
723+ }
724+ }
725+
726+ /// Asserts the index matches a fresh read of the body.
727+ #[cfg(test)]
728+ pub fn check(&self) {
729+ self.sync();
730+ self.index.borrow().check(&self.text);
731+ }
732+
733+ /// Ends the body with a separator when concurrent edits left content after the
734+ /// last one (unrecorded, origin `sys:init`).
735+ pub fn close_body(&self) {
736+ let len = self.text.len_unicode();
737+ if len == 0 || self.open() {
738+ self.text.insert(len, flat::SEP_STR).expect("insert");
739+ self.force(len, &[(1, KEYS.iter().map(|k| (*k, None)).collect())]);
740+ self.commit_as("sys:init");
741+ }
742+ }
743+}
744+
745+/// Merges touching segments of one key and value.
746+fn merge_segs(mut segs: Vec<Seg>) -> Vec<Seg> {
747+ segs.sort_by(|a, b| a.key.cmp(b.key).then(a.from.cmp(&b.from)));
748+ let mut out: Vec<Seg> = Vec::with_capacity(segs.len());
749+ for s in segs {
750+ if let Some(l) = out.last_mut()
751+ && l.key == s.key
752+ && l.value == s.value
753+ && l.to >= s.from
754+ {
755+ l.to = l.to.max(s.to);
756+ continue;
757+ }
758+ out.push(s);
759+ }
760+ out
761+}
762+
763+/// Rich runs with their absolute Unicode starts.
764+struct Runs {
765+ starts: Vec<usize>,
766+ attrs: Vec<HashMap<&'static str, LoroValue>>,
767+ end: usize,
768+}
769+
770+impl Runs {
771+ fn new(delta: Vec<TextDelta>, at: usize) -> Runs {
772+ let mut r = Runs { starts: Vec::new(), attrs: Vec::new(), end: at };
773+ for d in delta {
774+ let TextDelta::Insert { insert, attributes } = d else { continue };
775+ r.starts.push(r.end);
776+ r.end += insert.chars().count();
777+ let mut m = HashMap::new();
778+ for (k, v) in attributes.into_iter().flatten() {
779+ if let Some(k) = key(&k) {
780+ m.insert(k, v);
781+ }
782+ }
783+ r.attrs.push(m);
784+ }
785+ r
786+ }
787+
788+ /// Calls `f(from, to, attrs)` for each run piece within `from..to`.
789+ fn each(&self, from: usize, to: usize, mut f: impl FnMut(usize, usize, &HashMap<&'static str, LoroValue>)) {
790+ let mut i = self.starts.partition_point(|&s| s <= from).saturating_sub(1);
791+ while i < self.starts.len() && self.starts[i] < to {
792+ let end = self.starts.get(i + 1).copied().unwrap_or(self.end);
793+ let (a, b) = (self.starts[i].max(from), end.min(to));
794+ if a < b {
795+ f(a, b, &self.attrs[i]);
796+ }
797+ i += 1;
798+ }
799+ }
800+}
crates/editor/src/core/pos.rsadded+131 -0
@@ -0,0 +1,131 @@
1+//! Positions and selections: UTF-16 offsets from the start of the body.
2+
3+use super::model::{Anchor, Blk, Model};
4+
5+/// A caret offset. Inside a block it runs from the block's content start through its
6+/// separator's offset (the content end).
7+pub type Pos = usize;
8+
9+#[derive(Clone, Debug, PartialEq, Eq)]
10+pub enum Selection {
11+ /// Text range or caret. `anchor` stays put while extending, `head` moves.
12+ Text { anchor: Pos, head: Pos },
13+ /// A selected leaf: a rule (its block start) or an image (its char).
14+ Node(Pos),
15+ /// A caret before the block starting at the offset (or at the body end).
16+ Gap(Pos),
17+ /// Everything (Mod-a).
18+ All,
19+}
20+
21+impl Selection {
22+ pub fn caret(p: Pos) -> Self {
23+ Selection::Text { anchor: p, head: p }
24+ }
25+
26+ pub fn cursor(&self) -> Option<Pos> {
27+ match *self {
28+ Selection::Text { anchor, head } if anchor == head => Some(head),
29+ _ => None,
30+ }
31+ }
32+
33+ pub fn is_empty(&self) -> bool {
34+ match self {
35+ Selection::Text { anchor, head } => anchor == head,
36+ Selection::Gap(_) => true,
37+ _ => false,
38+ }
39+ }
40+
41+ pub fn head(&self) -> Option<Pos> {
42+ match *self {
43+ Selection::Text { head, .. } => Some(head),
44+ _ => None,
45+ }
46+ }
47+}
48+
49+/// `(from, to)` of a text selection in order; `All` spans the first block's start to
50+/// the last block's content end.
51+pub fn text_range(m: &Model, sel: &Selection) -> Option<(Pos, Pos)> {
52+ match *sel {
53+ Selection::Text { anchor, head } => Some((anchor.min(head), anchor.max(head))),
54+ Selection::All => Some((0, m.last().sep)),
55+ _ => None,
56+ }
57+}
58+
59+/// The selection moved to valid places: carets inside text blocks, nodes on leaves.
60+pub fn clamp(m: &Model, sel: &Selection) -> Selection {
61+ let total = m.total();
62+ match *sel {
63+ Selection::Text { anchor, head } => Selection::Text { anchor: snap(m, anchor.min(total)), head: snap(m, head.min(total)) },
64+ Selection::Node(p) => {
65+ let b = m.at(p);
66+ if b.kind().is_text() && p >= b.sep { Selection::caret(snap(m, p)) } else { Selection::Node(p.min(b.sep)) }
67+ }
68+ Selection::Gap(p) => Selection::Gap(p.min(total)),
69+ Selection::All => Selection::All,
70+ }
71+}
72+
73+/// The nearest caret place: inside the block holding `p`, or next to a rule.
74+pub fn snap(m: &Model, p: Pos) -> Pos {
75+ let b = m.at(p);
76+ if b.kind().is_text() {
77+ return p.clamp(b.start, b.sep);
78+ }
79+ near_text(m, &b).unwrap_or(p)
80+}
81+
82+/// The start of the next text block, else the end of the previous one.
83+pub fn near_text(m: &Model, b: &Blk) -> Option<Pos> {
84+ let mut out = None;
85+ m.scan(b.index + 1, false, |i, a| {
86+ if a.kind.is_text() {
87+ out = Some(i.start16);
88+ return false;
89+ }
90+ true
91+ });
92+ if out.is_none() {
93+ m.scan(b.index, true, |i, a| {
94+ if a.kind.is_text() {
95+ out = Some(i.sep16());
96+ return false;
97+ }
98+ true
99+ });
100+ }
101+ out
102+}
103+
104+/// A selection held by anchors, for undo and remote edits.
105+pub struct SelAnchors {
106+ kind: u8,
107+ a: Option<Anchor>,
108+ b: Option<Anchor>,
109+}
110+
111+impl SelAnchors {
112+ pub fn new(m: &Model, sel: &Selection) -> Self {
113+ match *sel {
114+ Selection::Text { anchor, head } => SelAnchors { kind: 0, a: Some(m.anchor(anchor)), b: Some(m.anchor(head)) },
115+ Selection::Node(p) => SelAnchors { kind: 1, a: Some(m.anchor(p)), b: None },
116+ Selection::Gap(p) => SelAnchors { kind: 2, a: Some(m.anchor(p)), b: None },
117+ Selection::All => SelAnchors { kind: 3, a: None, b: None },
118+ }
119+ }
120+
121+ pub fn resolve(&self, m: &Model) -> Selection {
122+ let r = |x: &Option<Anchor>| x.as_ref().map_or(0, |a| m.resolve(a));
123+ let sel = match self.kind {
124+ 0 => Selection::Text { anchor: r(&self.a), head: r(&self.b) },
125+ 1 => Selection::Node(r(&self.a)),
126+ 2 => Selection::Gap(r(&self.a)),
127+ _ => Selection::All,
128+ };
129+ clamp(m, &sel)
130+ }
131+}
crates/editor/src/core/tests.rsadded+212 -0
@@ -0,0 +1,212 @@
1+use note_model::write::Block;
2+
3+use super::commands::{self as c, Command, Cx};
4+use super::doc::Kind;
5+use super::history::History;
6+use super::marks::{MarkType, Marks};
7+use super::pos::Selection;
8+use super::testutil::*;
9+
10+const BACKSPACE: &[Command] = &[c::delete_selection, c::join_backward, c::select_node_backward];
11+const ENTER: &[Command] = &[c::split_list_item, c::newline_in_code, c::create_paragraph_near, c::lift_empty_block, c::split_block];
12+
13+fn run(m: &super::model::Model, sel: Selection, cmds: &[Command]) -> (bool, Selection) {
14+ let mut cx = Cx::new(m, sel);
15+ let ran = c::chain(&mut cx, cmds, true);
16+ (ran, cx.sel)
17+}
18+
19+#[test]
20+fn insert_text_keeps_marks_exact() {
21+ let m = build(vec![pi(vec![t("ab"), strong("cd")])]);
22+ // At the end of a strong run with plain marks requested: the new text is plain.
23+ m.insert(pos(&m, 0, 4), "x", &Marks::none());
24+ // Inside the plain run, but asking for strong.
25+ m.insert(pos(&m, 0, 1), "y", &Marks { strong: true, ..Marks::none() });
26+ assert_eq!(dump(&m), "p(a{s:y}b{s:cd}x)");
27+}
28+
29+#[test]
30+fn delete_range_across_blocks_and_lists() {
31+ let m = build(vec![p("one"), ul(vec![vec![p("two")], vec![p("three")]]), p("four")]);
32+ c::delete_range(&m, pos(&m, 0, 2), pos(&m, 2, 2));
33+ assert_eq!(dump(&m), "p(onree) p(four)");
34+
35+ let m = build(vec![quote(vec![p("a"), p("b")]), p("c")]);
36+ c::delete_range(&m, pos(&m, 1, 1), pos(&m, 2, 0));
37+ assert_eq!(dump(&m), "quote(p(a) p(bc))");
38+}
39+
40+#[test]
41+fn split_heading() {
42+ let m = build(vec![h(2, "title")]);
43+ run(&m, at(&m, 0, 5), ENTER);
44+ run(&m, at(&m, 0, 2), ENTER);
45+ assert_eq!(dump(&m), "h2(ti) h2(tle) p()");
46+ run(&m, at(&m, 0, 0), ENTER);
47+ assert_eq!(dump(&m), "p() h2(ti) h2(tle) p()");
48+}
49+
50+#[test]
51+fn code_block_merges_lines_and_splits_back() {
52+ let m = build(vec![p("let a"), pi(vec![t(" b"), br(), strong("c")]), p("d")]);
53+ let mut cx = Cx::new(&m, Selection::Text { anchor: pos(&m, 0, 0), head: pos(&m, 1, 1) });
54+ assert!(c::toggle_block(&mut cx, Kind::CodeBlock, true));
55+ assert_eq!(dump(&m), "code(let a\n b\nc) p(d)");
56+ let mut cx = Cx::new(&m, at(&m, 0, 2));
57+ assert!(c::toggle_block(&mut cx, Kind::CodeBlock, true));
58+ assert_eq!(dump(&m), "p(let a) p( b) p(c) p(d)");
59+}
60+
61+#[test]
62+fn backspace() {
63+ let m = build(vec![p("a"), p("b")]);
64+ assert!(!run(&m, at(&m, 0, 0), BACKSPACE).0);
65+
66+ let m = build(vec![p("a"), hr(), p("b")]);
67+ let (_, sel) = run(&m, at(&m, 1, 0), BACKSPACE);
68+ assert_eq!(dump(&m), "p(a) p(b)");
69+ let (_, sel) = run(&m, sel, BACKSPACE);
70+ assert_eq!(dump(&m), "p(ab)");
71+ assert_eq!(sel, at(&m, 0, 1));
72+
73+ let m = build(vec![ul(vec![vec![p("a")], vec![p("b")]])]);
74+ run(&m, at(&m, 1, 0), BACKSPACE);
75+ assert_eq!(dump(&m), "ul(li(p(a) p(b)))");
76+ let m = build(vec![ul(vec![vec![p("a")], vec![p("b")]])]);
77+ run(&m, at(&m, 0, 0), BACKSPACE);
78+ assert_eq!(dump(&m), "p(a) ul(li(p(b)))");
79+
80+ let m = build(vec![p("x"), quote(vec![p("a"), p("b")])]);
81+ run(&m, at(&m, 1, 0), BACKSPACE);
82+ assert_eq!(dump(&m), "p(x) p(a) quote(p(b))");
83+
84+ // After a list: the paragraph moves into its last item.
85+ let m = build(vec![ul(vec![vec![p("a")]]), p("b")]);
86+ run(&m, at(&m, 1, 0), BACKSPACE);
87+ assert_eq!(dump(&m), "ul(li(p(a) p(b)))");
88+}
89+
90+#[test]
91+fn enter_in_lists() {
92+ let m = build(vec![ul(vec![vec![p("ab")]])]);
93+ let (_, sel) = run(&m, at(&m, 0, 1), ENTER);
94+ assert_eq!(dump(&m), "ul(li(p(a)) li(p(b)))");
95+ assert_eq!(sel, at(&m, 1, 0));
96+ // Enter at the end makes an empty item; Enter again lifts it out.
97+ let (_, sel) = run(&m, at(&m, 1, 1), ENTER);
98+ assert_eq!(dump(&m), "ul(li(p(a)) li(p(b)) li(p()))");
99+ run(&m, sel, ENTER);
100+ assert_eq!(dump(&m), "ul(li(p(a)) li(p(b))) p()");
101+}
102+
103+#[test]
104+fn list_items_lift_and_sink() {
105+ let m = build(vec![ul(vec![vec![p("a"), ul(vec![vec![p("b")], vec![p("c")]])]])]);
106+ let mut cx = Cx::new(&m, at(&m, 1, 1));
107+ assert!(c::lift_list_item(&mut cx, true));
108+ assert_eq!(dump(&m), "ul(li(p(a)) li(p(b) ul(li(p(c)))))");
109+ let mut cx = Cx::new(&m, at(&m, 2, 0));
110+ assert!(!c::sink_list_item(&mut cx, false), "c's item has no previous sibling");
111+ let mut cx = Cx::new(&m, at(&m, 1, 0));
112+ assert!(c::sink_list_item(&mut cx, true));
113+ assert_eq!(dump(&m), "ul(li(p(a) ul(li(p(b) ul(li(p(c)))))))");
114+}
115+
116+#[test]
117+fn toggle_list_quote_and_mark() {
118+ let m = build(vec![p("one"), p("two")]);
119+ let mut cx = Cx::new(&m, Selection::Text { anchor: pos(&m, 0, 1), head: pos(&m, 1, 2) });
120+ assert!(c::toggle_list(&mut cx, Kind::BulletList, true));
121+ assert_eq!(dump(&m), "ul(li(p(one)) li(p(two)))");
122+ assert!(c::toggle_list(&mut cx, Kind::OrderedList, true));
123+ assert_eq!(dump(&m), "ol(li(p(one)) li(p(two)))");
124+ assert!(c::toggle_quote(&mut cx, true));
125+ assert_eq!(dump(&m), "quote(ol(li(p(one)) li(p(two))))");
126+ assert!(c::toggle_quote(&mut cx, true));
127+ assert_eq!(dump(&m), "ol(li(p(one)) li(p(two)))");
128+ let mut cx = Cx::new(&m, Selection::Text { anchor: pos(&m, 0, 0), head: pos(&m, 1, 3) });
129+ c::toggle_mark(&mut cx, MarkType::Strong, true);
130+ assert_eq!(dump(&m), "ol(li(p({s:one})) li(p({s:two})))");
131+ c::toggle_mark(&mut cx, MarkType::Strong, true);
132+ assert_eq!(dump(&m), "ol(li(p(one)) li(p(two)))");
133+}
134+
135+#[test]
136+fn paste_and_copy() {
137+ use note_model::write::Inline;
138+ let m = build(vec![p("abcd")]);
139+ let mut cx = Cx::new(&m, at(&m, 0, 2));
140+ let blocks = [Block::Paragraph(vec![t("X")]), Block::Rule, Block::Paragraph(vec![t("Y")])];
141+ assert!(c::insert_blocks(&mut cx, &blocks));
142+ assert_eq!(dump(&m), "p(abX) hr p(Ycd)");
143+ assert_eq!(cx.sel, at(&m, 1, 1));
144+
145+ let src = build(vec![p("one"), ul(vec![vec![p("two")]]), p("three")]);
146+ let blocks = c::selected_blocks(&src, &Selection::Text { anchor: pos(&src, 0, 1), head: pos(&src, 2, 2) });
147+ let dst = build(vec![p("[]")]);
148+ let mut cx = Cx::new(&dst, at(&dst, 0, 1));
149+ c::insert_blocks(&mut cx, &blocks);
150+ assert_eq!(dump(&dst), "p([ne) ul(li(p(two))) p(th])");
151+ let _ = Inline::HardBreak;
152+}
153+
154+#[test]
155+fn undo_redo() {
156+ let m = build(vec![p("ab"), ul(vec![vec![pi(vec![strong("x")])], vec![p("y")]])]);
157+ let before = dump(&m);
158+ let mut h = History::default();
159+ let edit = |h: &mut History, sel: Selection, f: &dyn Fn(&mut Cx), now: f64| {
160+ let mut cx = Cx::new(&m, sel.clone());
161+ f(&mut cx);
162+ h.push(&m, &sel, &cx.sel, now);
163+ };
164+ // Type, close the step, delete the typed char: undo restores it, then removes it.
165+ edit(&mut h, at(&m, 0, 1), &|cx| assert!(c::insert_text(cx, "Q")), 0.0);
166+ h.checkpoint();
167+ edit(&mut h, at(&m, 0, 2), &|cx| assert!(c::chain(cx, &[c::delete_selection, c::join_backward], true) || { cx.m.delete(cx.sel.cursor().unwrap() - 1, cx.sel.cursor().unwrap()); true }), 10.0);
168+ assert_eq!(dump(&m), before);
169+ h.undo(&m);
170+ assert!(dump(&m).starts_with("p(aQb)"));
171+ h.undo(&m);
172+ assert_eq!(dump(&m), before);
173+ h.redo(&m);
174+ h.redo(&m);
175+ assert_eq!(dump(&m), before);
176+ // Select all, delete, undo: everything back with its marks and lists.
177+ edit(&mut h, Selection::All, &|cx| assert!(c::delete_selection(cx, true)), 5000.0);
178+ assert_eq!(dump(&m), "p()");
179+ assert_eq!(h.undo(&m), Some(Selection::All));
180+ assert_eq!(dump(&m), before);
181+}
182+
183+#[test]
184+fn anchor_survives_remote_insert_before() {
185+ let m = build(vec![pi(vec![t("ab"), br(), strong("cd")])]);
186+ let a = m.anchor(4);
187+ let other = loro::LoroDoc::new();
188+ other.import(&m.doc.export(loro::ExportMode::Snapshot).unwrap()).unwrap();
189+ other.get_text("body").insert(0, "xy").unwrap();
190+ other.commit();
191+ m.import(&other.export(loro::ExportMode::updates(&m.doc.oplog_vv())).unwrap()).unwrap();
192+ assert_eq!(m.resolve(&a), 6);
193+ assert_eq!(dump(&m), "p(xyab|{s:cd})");
194+}
195+
196+/// A 5 MB paragraph: Enter and Backspace in its middle stay cheap.
197+#[test]
198+#[ignore]
199+fn huge_block_split_join() {
200+ let big = "lorem ipsum ".repeat(450_000);
201+ let m = build(vec![p(&big)]);
202+ let mid = big.len() / 2;
203+ let t0 = std::time::Instant::now();
204+ let (_, sel) = run(&m, Selection::caret(mid), ENTER);
205+ let split = t0.elapsed();
206+ let t1 = std::time::Instant::now();
207+ run(&m, sel, BACKSPACE);
208+ let join = t1.elapsed();
209+ eprintln!("split {split:?} join {join:?}");
210+ assert!(join.as_millis() < 50, "join {join:?}");
211+ assert_eq!(m.len(), 1);
212+}
crates/editor/src/core/testutil.rsadded+113 -0
@@ -0,0 +1,113 @@
1+//! Compact builders and a dump format for core tests.
2+//! Dump: `p(ab) h2(x) ul(li(p(a)))`, `|` for a hard break, `{s:x}` strong, `{e:x}` em,
3+//! `{c:x}` code, `{l=href:x}` link, `hr`.
4+
5+use loro::LoroDoc;
6+use note_model::flat;
7+use note_model::marks::Marks;
8+use note_model::write::{Block, Inline};
9+
10+use super::model::{Blk, Model};
11+use super::pos::{Pos, Selection};
12+
13+pub fn t(s: &str) -> Inline {
14+ Inline::Text(s.into(), Marks::default())
15+}
16+pub fn strong(s: &str) -> Inline {
17+ Inline::Text(s.into(), Marks { strong: true, ..Marks::default() })
18+}
19+pub fn br() -> Inline {
20+ Inline::HardBreak
21+}
22+pub fn p(s: &str) -> Block {
23+ Block::Paragraph(if s.is_empty() { Vec::new() } else { vec![t(s)] })
24+}
25+pub fn pi(v: Vec<Inline>) -> Block {
26+ Block::Paragraph(v)
27+}
28+pub fn h(n: i64, s: &str) -> Block {
29+ Block::Heading(n, vec![t(s)])
30+}
31+pub fn hr() -> Block {
32+ Block::Rule
33+}
34+pub fn quote(v: Vec<Block>) -> Block {
35+ Block::Quote(v)
36+}
37+pub fn ul(items: Vec<Vec<Block>>) -> Block {
38+ Block::List { ordered: false, start: 1, items }
39+}
40+
41+pub fn build(blocks: Vec<Block>) -> Model {
42+ let doc = LoroDoc::new();
43+ super::marks::configure(&doc);
44+ let text = flat::body(&doc);
45+ if blocks.is_empty() {
46+ flat::init(&doc).unwrap();
47+ } else {
48+ flat::write(&text, 0, &flat::flatten(&blocks), false).unwrap();
49+ }
50+ doc.commit();
51+ Model::new(doc)
52+}
53+
54+pub fn dump(m: &Model) -> String {
55+ m.check();
56+ flat::doc_blocks(&m.doc).iter().map(block).collect::<Vec<_>>().join(" ")
57+}
58+
59+fn block(b: &Block) -> String {
60+ match b {
61+ Block::Paragraph(v) => format!("p({})", inline(v)),
62+ Block::Heading(n, v) => format!("h{n}({})", inline(v)),
63+ Block::Code { text, .. } => format!("code({text})"),
64+ Block::Rule => "hr".into(),
65+ Block::Quote(v) => format!("quote({})", v.iter().map(block).collect::<Vec<_>>().join(" ")),
66+ Block::List { ordered, items, .. } => format!(
67+ "{}({})",
68+ if *ordered { "ol" } else { "ul" },
69+ items.iter().map(|i| format!("li({})", i.iter().map(block).collect::<Vec<_>>().join(" "))).collect::<Vec<_>>().join(" ")
70+ ),
71+ }
72+}
73+
74+fn inline(v: &[Inline]) -> String {
75+ let mut s = String::new();
76+ for i in v {
77+ match i {
78+ Inline::Text(t, m) => {
79+ let mut x = t.clone();
80+ if m.code {
81+ x = format!("{{c:{x}}}");
82+ }
83+ if m.strong {
84+ x = format!("{{s:{x}}}");
85+ }
86+ if m.em {
87+ x = format!("{{e:{x}}}");
88+ }
89+ if let Some((href, _)) = &m.link {
90+ x = format!("{{l={href}:{x}}}");
91+ }
92+ s.push_str(&x);
93+ }
94+ Inline::HardBreak => s.push('|'),
95+ Inline::Image { .. } => s.push_str("[img]"),
96+ }
97+ }
98+ s
99+}
100+
101+/// The n-th text block.
102+pub fn tb(m: &Model, n: usize) -> Blk {
103+ let all = m.blocks(0, m.len());
104+ all.into_iter().filter(|b| b.kind().is_text()).nth(n).expect("text block")
105+}
106+
107+pub fn at(m: &Model, n: usize, off: usize) -> Selection {
108+ Selection::caret(tb(m, n).start + off)
109+}
110+
111+pub fn pos(m: &Model, n: usize, off: usize) -> Pos {
112+ tb(m, n).start + off
113+}
crates/editor/src/editor.rsadded+917 -0
@@ -0,0 +1,917 @@
1+//! Editor state and the input pipeline.
2+//!
3+//! Every change goes through the model: a command (intercepted input, keys) or the
4+//! read-back of text the browser typed natively (plain typing, IME, Android). The
5+//! model's block splices drive `View::flush`, which patches the DOM; then the
6+//! selection goes back.
7+
8+use loro::LoroDoc;
9+use note_model::flat::Kind as Leaf;
10+use note_model::write::Inline;
11+use wasm_bindgen::JsCast;
12+use web_sys::{CompositionEvent, HtmlElement, InputEvent, KeyboardEvent, MutationObserver, MutationRecord, Node as DomNode};
13+
14+use crate::core::commands::{self as c, Command, Cx};
15+use crate::core::doc::Kind;
16+use crate::core::history::History;
17+use crate::core::marks::{MarkType, Marks};
18+use crate::core::model::Model;
19+use crate::core::pos::{self, Pos, SelAnchors, Selection};
20+use crate::view::{RunKind, View};
21+
22+const ENTER: &[Command] = &[c::split_list_item, c::newline_in_code, c::create_paragraph_near, c::lift_empty_block, c::split_block];
23+const BACKSPACE: &[Command] = &[c::delete_selection, c::join_backward, c::select_node_backward];
24+const DELETE: &[Command] = &[c::delete_selection, c::join_forward, c::select_node_forward];
25+
26+/// A structural input the browser would not let us cancel (Android): run it after
27+/// the DOM change is undone.
28+#[derive(Clone, Copy)]
29+enum Intent {
30+ Enter,
31+ Backspace,
32+ Delete,
33+ LineBreak,
34+}
35+
36+/// Text the browser is typing natively into a run with these marks.
37+#[derive(Clone)]
38+struct Native {
39+ block: usize,
40+ marks: Marks,
41+ /// The text node the browser types into, the caret offset in it, its length
42+ /// before typing, the model offset and the typed text: enough to check the edit
43+ /// without reading the whole block back.
44+ node: DomNode,
45+ at: u32,
46+ len: u32,
47+ off: Pos,
48+ data: String,
49+}
50+
51+pub struct Editor {
52+ /// The model's doc (shared), for sync.
53+ pub doc: LoroDoc,
54+ pub m: Model,
55+ pub history: History,
56+ pub view: View,
57+ pub sel: Selection,
58+ pub stored: Option<Marks>,
59+ pub observer: Option<MutationObserver>,
60+ pub editable: bool,
61+ native: Option<Native>,
62+ composition_marks: Option<Marks>,
63+ composition_end: f64,
64+ intent: Option<Intent>,
65+ is_mac: bool,
66+ /// The placeholder text and the element showing it.
67+ pub placeholder_text: String,
68+ placeholder_el: Option<web_sys::Element>,
69+ /// The element marked as the selected node.
70+ selected_el: std::cell::RefCell<Option<web_sys::Element>>,
71+ /// Doc state right after an input rule, and the text it replaced.
72+ pub last_rule: Option<(loro::Frontiers, String)>,
73+ /// Whether the browser's spellchecker is off (a huge note).
74+ spell_off: bool,
75+ /// Called after every change of doc or selection (toolbar, presence, status).
76+ pub listeners: Vec<Box<dyn FnMut(&Editor, bool)>>,
77+}
78+
79+fn now() -> f64 {
80+ js_sys::Date::now()
81+}
82+
83+impl Editor {
84+ pub fn new(doc: LoroDoc, root: HtmlElement) -> Self {
85+ let view = View::new(root);
86+ let is_mac = web_sys::window()
87+ .and_then(|w| w.navigator().platform().ok())
88+ .is_some_and(|p| p.contains("Mac") || p.contains("iP"));
89+ let m = Model::new(doc.clone());
90+ Editor {
91+ doc,
92+ m,
93+ history: History::default(),
94+ view,
95+ sel: Selection::caret(0),
96+ stored: None,
97+ observer: None,
98+ editable: false,
99+ native: None,
100+ composition_marks: None,
101+ composition_end: 0.0,
102+ intent: None,
103+ is_mac,
104+ last_rule: None,
105+ spell_off: false,
106+ placeholder_text: String::new(),
107+ placeholder_el: None,
108+ selected_el: Default::default(),
109+ listeners: Vec::new(),
110+ }
111+ }
112+
113+ pub fn cx(&self) -> Cx<'_> {
114+ Cx { m: &self.m, sel: self.sel.clone(), stored: self.stored.clone() }
115+ }
116+
117+ // -----------------------------------------------------------------------
118+ // Change cycle
119+ // -----------------------------------------------------------------------
120+
121+ /// Runs a command against the current selection and records it for undo.
122+ pub fn run(&mut self, f: impl FnOnce(&mut Cx) -> bool) -> bool {
123+ if self.m.is_empty() {
124+ return false;
125+ }
126+ let before = self.sel.clone();
127+ let mut cx = self.cx();
128+ let ran = f(&mut cx);
129+ let (sel, stored) = (cx.sel, cx.stored);
130+ if ran {
131+ self.m.commit();
132+ self.history.push(&self.m, &before, &sel, now());
133+ self.sel = sel;
134+ self.stored = stored;
135+ self.render(true);
136+ } else {
137+ self.m.take_ops();
138+ }
139+ ran
140+ }
141+
142+ /// Sets (`Some`) or clears (`None`: detect it) the language of the code block at `off`.
143+ pub fn set_code_language(&mut self, off: Pos, lang: Option<&str>) -> bool {
144+ let b = self.m.at(off);
145+ if b.kind() != Leaf::Code || b.attrs.lang.as_deref() == lang {
146+ return false;
147+ }
148+ let start = b.start;
149+ self.run(|cx| c::set_code_language(cx.m, start, lang))
150+ }
151+
152+ /// Replaces the code of the block at `off` with `code`, editing only the part that
153+ /// differs, so carets (ours and remote ones) stay where they were. Does nothing
154+ /// unless the block still holds `expected`: the code may have changed while it was
155+ /// formatted.
156+ pub fn replace_code(&mut self, off: Pos, expected: &str, code: &str) -> bool {
157+ let b = self.m.at(off);
158+ if b.kind() != Leaf::Code || expected == code || self.m.plain(b.start, b.sep) != expected {
159+ return false;
160+ }
161+ let before = self.sel.clone();
162+ let anchors = SelAnchors::new(&self.m, &self.sel);
163+ let (old, new): (Vec<u16>, Vec<u16>) = (expected.encode_utf16().collect(), code.encode_utf16().collect());
164+ let mut p = old.iter().zip(&new).take_while(|(a, b)| a == b).count();
165+ let max = old.len().min(new.len()) - p;
166+ let mut s = old.iter().rev().zip(new.iter().rev()).take(max).take_while(|(a, b)| a == b).count();
167+ // Never split a surrogate pair.
168+ while p > 0 && is_low(old.get(p)) {
169+ p -= 1;
170+ }
171+ while s > 0 && is_low(old.get(old.len() - s)) {
172+ s -= 1;
173+ }
174+ let max = (old.len() - p).min(new.len() - p);
175+ s = s.min(max);
176+ let mid = String::from_utf16_lossy(&new[p..new.len() - s]);
177+ self.m.delete(b.start + p, b.start + old.len() - s);
178+ if !mid.is_empty() {
179+ self.m.insert(b.start + p, &mid, &Marks::none());
180+ }
181+ self.sel = anchors.resolve(&self.m);
182+ self.history.push(&self.m, &before, &self.sel, now());
183+ self.history.checkpoint();
184+ let focused = self.focused();
185+ self.render(focused);
186+ true
187+ }
188+
189+ pub fn chain(&mut self, cmds: &[Command]) -> bool {
190+ self.run(|cx| c::chain(cx, cmds, true))
191+ }
192+
193+ /// Whether a command would apply now (toolbar state).
194+ pub fn can(&self, f: impl FnOnce(&mut Cx) -> bool) -> bool {
195+ if self.m.is_empty() {
196+ return false;
197+ }
198+ let mut cx = self.cx();
199+ f(&mut cx)
200+ }
201+
202+ /// Flushes model changes to the DOM, then the selection.
203+ pub fn render(&mut self, set_dom_sel: bool) {
204+ let changed = self.view.flush(&self.m);
205+ if changed {
206+ self.drain_own_mutations();
207+ self.placeholder();
208+ self.spellcheck();
209+ }
210+ self.sel = pos::clamp(&self.m, &self.sel);
211+ if set_dom_sel {
212+ self.write_dom_selection();
213+ }
214+ self.notify(changed);
215+ }
216+
217+ fn notify(&mut self, changed: bool) {
218+ let mut ls = std::mem::take(&mut self.listeners);
219+ for l in ls.iter_mut() {
220+ l(self, changed);
221+ }
222+ ls.append(&mut self.listeners);
223+ self.listeners = ls;
224+ }
225+
226+ pub(crate) fn drain_own_mutations(&self) {
227+ if let Some(o) = &self.observer {
228+ o.take_records();
229+ }
230+ }
231+
232+ /// Applies remote updates; keeps the local selection anchored.
233+ pub fn import(&mut self, bytes: &[u8]) -> loro::LoroResult<()> {
234+ if !self.editable {
235+ let r = self.m.import(bytes);
236+ self.sel = Selection::caret(pos::snap(&self.m, 0));
237+ return r;
238+ }
239+ let anchors = SelAnchors::new(&self.m, &self.sel);
240+ self.m.import(bytes)?;
241+ self.m.close_body();
242+ self.sel = anchors.resolve(&self.m);
243+ let focused = self.focused();
244+ self.render(focused);
245+ Ok(())
246+ }
247+
248+ /// Turns the pre-rendered page into the live editor.
249+ pub fn make_editable(&mut self) {
250+ if self.editable {
251+ return;
252+ }
253+ self.m.close_body();
254+ self.m.take_ops();
255+ self.view.render_all(&self.m);
256+ self.drain_own_mutations();
257+ self.placeholder();
258+ // Before the root is editable, so the spellchecker never starts on a huge note.
259+ self.spellcheck();
260+ let _ = self.view.root.set_attribute("contenteditable", "true");
261+ self.editable = true;
262+ self.sel = Selection::caret(pos::snap(&self.m, 0));
263+ self.notify(true);
264+ }
265+
266+ /// The `is-placeholder` hint while the note is one empty paragraph.
267+ /// Turns the spellchecker off for a huge note: it rechecks moved text in idle
268+ /// tasks that held the main thread for 70 ms after Enter in a 55 MB paragraph,
269+ /// and checking megabytes of text helps nobody.
270+ fn spellcheck(&mut self) {
271+ const SPELL_MAX: usize = 1 << 20;
272+ let off = self.m.total() > SPELL_MAX;
273+ if off != self.spell_off {
274+ self.spell_off = off;
275+ self.view.root.set_spellcheck(!off);
276+ }
277+ }
278+
279+ fn placeholder(&mut self) {
280+ let target = (self.m.len() == 1)
281+ .then(|| self.m.block(0))
282+ .flatten()
283+ .filter(|b| b.kind() == Leaf::Para && b.is_empty() && b.depth() == 0)
284+ .and_then(|_| self.view.element(0).cloned());
285+ if target == self.placeholder_el {
286+ return;
287+ }
288+ if let Some(old) = self.placeholder_el.take() {
289+ let _ = old.class_list().remove_1("is-placeholder");
290+ let _ = old.remove_attribute("data-placeholder");
291+ }
292+ if let Some(el) = &target {
293+ let _ = el.class_list().add_1("is-placeholder");
294+ let _ = el.set_attribute("data-placeholder", &self.placeholder_text);
295+ }
296+ self.placeholder_el = target;
297+ }
298+
299+ pub fn undo(&mut self) -> bool {
300+ self.history(true)
301+ }
302+
303+ pub fn redo(&mut self) -> bool {
304+ self.history(false)
305+ }
306+
307+ fn history(&mut self, undo: bool) -> bool {
308+ let sel = if undo { self.history.undo(&self.m) } else { self.history.redo(&self.m) };
309+ let Some(sel) = sel else { return false };
310+ self.sel = sel;
311+ self.stored = None;
312+ self.render(true);
313+ true
314+ }
315+
316+ pub fn can_undo(&self) -> bool {
317+ self.history.can_undo()
318+ }
319+
320+ pub fn can_redo(&self) -> bool {
321+ self.history.can_redo()
322+ }
323+
324+ // -----------------------------------------------------------------------
325+ // DOM selection
326+ // -----------------------------------------------------------------------
327+
328+ pub fn focused(&self) -> bool {
329+ let doc = self.view.root.owner_document().unwrap();
330+ doc.active_element().is_some_and(|a| self.view.root.contains(Some(&a)))
331+ }
332+
333+ /// Reads the DOM selection into the model. Returns false when it is outside.
334+ pub fn read_dom_selection(&mut self) -> bool {
335+ let Some(ds) = web_sys::window().and_then(|w| w.get_selection().ok().flatten()) else { return false };
336+ let (Some(an), Some(fo)) = (ds.anchor_node(), ds.focus_node()) else { return false };
337+ let root: &DomNode = self.view.root.as_ref();
338+ if !root.contains(Some(&an)) || !root.contains(Some(&fo)) {
339+ return false;
340+ }
341+ if let Selection::Node(_) | Selection::All = self.sel {
342+ // Kept while the DOM selection is the one we set for it.
343+ if !ds.is_collapsed() {
344+ return true;
345+ }
346+ }
347+ let a = self.view.dom_to_pos(&self.m, &an, ds.anchor_offset());
348+ let f = self.view.dom_to_pos(&self.m, &fo, ds.focus_offset());
349+ if let (Some(anchor), Some(head)) = (a, f) {
350+ let sel = pos::clamp(&self.m, &Selection::Text { anchor, head });
351+ if sel != self.sel {
352+ self.sel = sel;
353+ self.stored = None;
354+ }
355+ }
356+ true
357+ }
358+
359+ /// Puts the model selection into the DOM if it differs.
360+ pub fn write_dom_selection(&mut self) {
361+ match self.sel {
362+ Selection::Text { anchor, head } => {
363+ self.view.show(&self.m, self.m.at(anchor).index);
364+ self.view.show(&self.m, self.m.at(head).index);
365+ self.view.ensure_live(&self.m, &[anchor, head]);
366+ }
367+ Selection::Node(p) => self.view.show(&self.m, self.m.at(p).index),
368+ _ => {}
369+ }
370+ self.drain_own_mutations();
371+ let Some(ds) = web_sys::window().and_then(|w| w.get_selection().ok().flatten()) else { return };
372+ if let Some(old) = self.selected_el.borrow_mut().take() {
373+ let _ = old.class_list().remove_1("ProseMirror-selectednode");
374+ }
375+ match self.sel {
376+ Selection::Text { anchor, head } => {
377+ let (Some((an, ao)), Some((fo, foo))) = (self.view.pos_to_dom(&self.m, anchor), self.view.pos_to_dom(&self.m, head)) else { return };
378+ let same = ds.anchor_node().as_ref() == Some(&an)
379+ && ds.anchor_offset() == ao
380+ && ds.focus_node().as_ref() == Some(&fo)
381+ && ds.focus_offset() == foo;
382+ if !same {
383+ let _ = ds.set_base_and_extent(&an, ao, &fo, foo);
384+ }
385+ }
386+ Selection::Node(p) => {
387+ if let Some(el) = self.node_element(p) {
388+ let _ = el.class_list().add_1("ProseMirror-selectednode");
389+ *self.selected_el.borrow_mut() = Some(el.clone());
390+ if let Some(parent) = el.parent_node() {
391+ let i = index_in(&parent, &el);
392+ let _ = ds.set_base_and_extent(&parent, i, &parent, i + 1);
393+ }
394+ }
395+ }
396+ Selection::All => {
397+ let root: &DomNode = self.view.root.as_ref();
398+ let _ = ds.set_base_and_extent(root, 0, root, root.child_nodes().length());
399+ }
400+ Selection::Gap(_) => {}
401+ }
402+ }
403+
404+ /// The element of a selected node: a rule, or the image at `p`.
405+ pub fn node_element(&self, p: Pos) -> Option<web_sys::Element> {
406+ let b = self.m.at(p);
407+ let v = self.view.bview(b.index)?;
408+ if b.kind() == Leaf::Rule {
409+ return Some(v.el.clone());
410+ }
411+ let mut acc = b.start;
412+ for r in &v.runs {
413+ if acc == p && matches!(r.kind, RunKind::Image { .. }) {
414+ return r.dom.clone().dyn_into().ok();
415+ }
416+ acc += r.len;
417+ }
418+ None
419+ }
420+
421+ /// A click on a rule or image selects it as a node.
422+ pub fn on_mousedown(&mut self, ev: &web_sys::MouseEvent) {
423+ if !self.editable || ev.button() != 0 {
424+ return;
425+ }
426+ let Some(target) = ev.target().and_then(|t| t.dyn_into::<web_sys::Element>().ok()) else { return };
427+ let p = match target.tag_name().as_str() {
428+ "HR" => self.view.owner(&target).and_then(|(i, _)| self.m.block(i)).map(|b| b.start),
429+ "IMG" => target.parent_node().and_then(|parent| {
430+ let i = index_in(&parent, &target);
431+ self.view.dom_to_pos(&self.m, &parent, i)
432+ }),
433+ _ => return,
434+ };
435+ let Some(p) = p else { return };
436+ ev.prevent_default();
437+ let _ = self.view.root.focus();
438+ self.sel = Selection::Node(p);
439+ self.stored = None;
440+ self.write_dom_selection();
441+ self.notify(false);
442+ }
443+
444+ pub fn on_selection_change(&mut self) {
445+ if self.view.composing.is_some() || !self.editable {
446+ return;
447+ }
448+ if self.read_dom_selection() {
449+ self.notify(false);
450+ }
451+ }
452+
453+ // -----------------------------------------------------------------------
454+ // Input
455+ // -----------------------------------------------------------------------
456+
457+ pub fn on_beforeinput(&mut self, ev: &InputEvent) {
458+ if !self.editable {
459+ ev.prevent_default();
460+ return;
461+ }
462+ let kind = ev.input_type();
463+ if kind.contains("Composition") {
464+ return;
465+ }
466+ self.read_dom_selection();
467+ let cancel = ev.cancelable();
468+ match kind.as_str() {
469+ "insertText" => {
470+ let data = ev.data().unwrap_or_default();
471+ if let Some(native) = self.native_insert(&data) {
472+ self.native = Some(native);
473+ return;
474+ }
475+ ev.prevent_default();
476+ self.type_text(&data);
477+ }
478+ "insertReplacementText" => {
479+ ev.prevent_default();
480+ let text = ev
481+ .data_transfer()
482+ .and_then(|d| d.get_data("text/plain").ok())
483+ .or_else(|| ev.data())
484+ .unwrap_or_default();
485+ if let Some((from, to)) = self.target_range(ev) {
486+ self.sel = Selection::Text { anchor: from, head: to };
487+ }
488+ self.run(|cx| c::insert_text(cx, &text));
489+ }
490+ "insertParagraph" => self.structural(ev, cancel, Intent::Enter),
491+ "insertLineBreak" => self.structural(ev, cancel, Intent::LineBreak),
492+ k if k.starts_with("delete") => {
493+ let back = k.contains("Backward");
494+ let intent = if back { Intent::Backspace } else { Intent::Delete };
495+ if !cancel {
496+ self.intent = Some(intent);
497+ return;
498+ }
499+ ev.prevent_default();
500+ if !self.sel.is_empty() {
501+ self.chain(BACKSPACE);
502+ return;
503+ }
504+ match self.target_range(ev) {
505+ Some((from, to)) if from != to && self.m.at(from).index == self.m.at(to).index => {
506+ self.run(|cx| {
507+ cx.sel = Selection::Text { anchor: from, head: to };
508+ c::delete_selection(cx, true)
509+ });
510+ }
511+ _ => self.delete_char(back),
512+ }
513+ }
514+ "historyUndo" => {
515+ ev.prevent_default();
516+ self.undo();
517+ }
518+ "historyRedo" => {
519+ ev.prevent_default();
520+ self.redo();
521+ }
522+ "formatBold" => {
523+ ev.prevent_default();
524+ self.run(|cx| c::toggle_mark(cx, MarkType::Strong, true));
525+ }
526+ "formatItalic" => {
527+ ev.prevent_default();
528+ self.run(|cx| c::toggle_mark(cx, MarkType::Em, true));
529+ }
530+ // Paste and drop are handled by their own events.
531+ _ => ev.prevent_default(),
532+ }
533+ }
534+
535+ fn structural(&mut self, ev: &InputEvent, cancel: bool, intent: Intent) {
536+ if !cancel {
537+ self.intent = Some(intent);
538+ return;
539+ }
540+ ev.prevent_default();
541+ self.run_intent(intent);
542+ }
543+
544+ fn run_intent(&mut self, intent: Intent) {
545+ match intent {
546+ Intent::Enter => {
547+ self.chain(ENTER);
548+ }
549+ Intent::Backspace => self.delete_char(true),
550+ Intent::Delete => self.delete_char(false),
551+ Intent::LineBreak => {
552+ self.run(|cx| {
553+ let code = cx.sel.cursor().is_some_and(|p| cx.m.at(p).kind() == Leaf::Code);
554+ if code { c::insert_text(cx, "\n") } else { c::insert_inline(cx, &[Inline::HardBreak]) }
555+ });
556+ }
557+ }
558+ }
559+
560+ /// One character (surrogate pair aware) backward or forward, else the structural chain.
561+ fn delete_char(&mut self, back: bool) {
562+ if self.chain(if back { BACKSPACE } else { DELETE }) {
563+ return;
564+ }
565+ let Some(p) = self.sel.cursor() else { return };
566+ let b = self.m.at(p);
567+ let u = self.m.to_u(p);
568+ let (from, to) = if back {
569+ if p <= b.start {
570+ return;
571+ }
572+ (self.m.to16(u - 1).max(b.start), p)
573+ } else {
574+ if p >= b.sep {
575+ return;
576+ }
577+ (p, self.m.to16(u + 1).min(b.sep))
578+ };
579+ if from == to {
580+ return;
581+ }
582+ self.run(|cx| {
583+ cx.sel = Selection::Text { anchor: from, head: to };
584+ c::delete_selection(cx, true)
585+ });
586+ }
587+
588+ /// The first target range of an input event, in model offsets, in order.
589+ fn target_range(&self, ev: &InputEvent) -> Option<(Pos, Pos)> {
590+ let ranges = ev.get_target_ranges();
591+ let r: web_sys::StaticRange = ranges.get(0).dyn_into().ok()?;
592+ let a = self.view.dom_to_pos(&self.m, &r.start_container(), r.start_offset())?;
593+ let b = self.view.dom_to_pos(&self.m, &r.end_container(), r.end_offset())?;
594+ Some((a.min(b), a.max(b)))
595+ }
596+
597+ /// Typed text that is not left to the browser.
598+ pub fn type_text(&mut self, data: &str) {
599+ if crate::rules::apply(self, data) {
600+ return;
601+ }
602+ self.run(|cx| c::insert_text(cx, data));
603+ }
604+
605+ /// Ends undo merging, so the next change is its own undo step.
606+ pub fn checkpoint(&mut self) {
607+ self.history.checkpoint();
608+ }
609+
610+ /// Whether the browser may type `data` itself: a collapsed caret inside one of our
611+ /// text nodes whose marks are exactly the marks the text should get.
612+ fn native_insert(&self, data: &str) -> Option<Native> {
613+ if data.is_empty() || data.contains('\n') {
614+ return None;
615+ }
616+ let p = self.sel.cursor()?;
617+ let b = self.m.at(p);
618+ if !b.kind().is_text() {
619+ return None;
620+ }
621+ let ds = web_sys::window()?.get_selection().ok()??;
622+ let an = ds.anchor_node()?;
623+ if an.node_type() != DomNode::TEXT_NODE || !ds.is_collapsed() {
624+ return None;
625+ }
626+ let v = self.view.bview(b.index)?;
627+ let run = v.runs.iter().find(|r| r.text.as_ref().is_some_and(|t| ***t == an))?;
628+ let marks = c::pending_marks(&self.cx());
629+ if Marks::from(&run.marks) != marks {
630+ return None;
631+ }
632+ if b.kind() != Leaf::Code && crate::rules::may_trigger(data) {
633+ return None;
634+ }
635+ let len = an.unchecked_ref::<web_sys::CharacterData>().length();
636+ Some(Native { block: b.index, marks, at: ds.anchor_offset(), len, off: p, data: data.to_owned(), node: an })
637+ }
638+
639+ pub fn on_input(&mut self) {
640+ let records = self.observer.as_ref().map(|o| o.take_records()).unwrap_or_default();
641+ self.on_mutations(&records.iter().filter_map(|r| r.dyn_into::<MutationRecord>().ok()).collect::<Vec<_>>());
642+ }
643+
644+ /// Reconciles DOM changes the browser made with the model.
645+ pub fn on_mutations(&mut self, records: &[MutationRecord]) {
646+ if self.view.composing.is_some() || !self.editable {
647+ return;
648+ }
649+ let mut blocks: Vec<usize> = Vec::new();
650+ let mut containers: Vec<DomNode> = Vec::new();
651+ for r in records {
652+ let Some(target) = r.target() else { continue };
653+ match self.view.owner(&target) {
654+ Some((i, _)) => {
655+ if !blocks.contains(&i) {
656+ blocks.push(i);
657+ }
658+ }
659+ None => containers.push(target),
660+ }
661+ }
662+ if let Some(n) = &self.native
663+ && !blocks.contains(&n.block)
664+ {
665+ blocks.push(n.block);
666+ }
667+ if let Some(intent) = self.intent.take() {
668+ for &i in &blocks {
669+ self.view.repair(&self.m, i);
670+ }
671+ for n in &containers {
672+ self.view.repair_page_of(&self.m, n);
673+ }
674+ self.drain_own_mutations();
675+ self.write_dom_selection();
676+ self.run_intent(intent);
677+ return;
678+ }
679+ if blocks.is_empty() && containers.is_empty() {
680+ return;
681+ }
682+ let before = self.sel.clone();
683+ let mut changed = false;
684+ let native = self.native.take();
685+ for &i in &blocks {
686+ let fast = native.as_ref().is_some_and(|n| n.block == i && self.typed_natively(n, records));
687+ if !fast {
688+ self.native = native.clone();
689+ }
690+ changed |= fast || self.read_back(i);
691+ }
692+ self.native = None;
693+ // The browser's caret is where the text went.
694+ self.read_dom_selection();
695+ if changed {
696+ self.history.push(&self.m, &before, &self.sel, now());
697+ }
698+ self.view.flush(&self.m);
699+ let mut repaired = false;
700+ for &i in &blocks {
701+ if !self.view.intact(i) {
702+ self.view.repair(&self.m, i);
703+ repaired = true;
704+ }
705+ }
706+ for n in &containers {
707+ if n.is_connected() || self.view.root.contains(Some(n)) {
708+ self.view.repair_page_of(&self.m, n);
709+ repaired = true;
710+ }
711+ }
712+ self.drain_own_mutations();
713+ self.placeholder();
714+ self.sel = pos::clamp(&self.m, &self.sel);
715+ if repaired {
716+ self.write_dom_selection();
717+ }
718+ self.notify(changed);
719+ }
720+
721+ /// The browser typed exactly `n.data` at the caret and nothing else: applies it to
722+ /// the model without reading the block back. False when the DOM shows anything else.
723+ fn typed_natively(&mut self, n: &Native, records: &[MutationRecord]) -> bool {
724+ let only_text = records.iter().all(|r| r.type_() == "characterData" && r.target().as_ref() == Some(&n.node));
725+ let t: &web_sys::CharacterData = n.node.unchecked_ref();
726+ let len16 = n.data.encode_utf16().count() as u32;
727+ if !only_text || t.length() != n.len + len16 || t.substring_data(n.at, len16).ok().as_deref() != Some(n.data.as_str()) {
728+ return false;
729+ }
730+ if !self.view.typed(n.block, &n.node, n.at as usize, &n.data) {
731+ return false;
732+ }
733+ self.m.insert(n.off, &n.data, &n.marks);
734+ true
735+ }
736+
737+ /// Applies the difference between a block's DOM text and the model as one
738+ /// replacement. Returns whether the model changed.
739+ fn read_back(&mut self, i: usize) -> bool {
740+ let Some(b) = self.m.block(i) else { return false };
741+ if !b.kind().is_text() {
742+ return false;
743+ }
744+ let Some(dom) = self.view.dom_text(i) else { return false };
745+ let model: Vec<u16> = self.m.plain(b.start, b.sep).encode_utf16().collect();
746+ if dom == model {
747+ return false;
748+ }
749+ // The browser changed the DOM: the run caches follow it before the model does.
750+ self.view.resync(i);
751+ let mut p = 0;
752+ while p < dom.len() && p < model.len() && dom[p] == model[p] {
753+ p += 1;
754+ }
755+ let mut s = 0;
756+ while s < dom.len() - p && s < model.len() - p && dom[dom.len() - 1 - s] == model[model.len() - 1 - s] {
757+ s += 1;
758+ }
759+ // Do not split a surrogate pair.
760+ if p > 0 && is_low(model.get(p)) {
761+ p -= 1;
762+ }
763+ let inserted = &dom[p..dom.len() - s];
764+ if inserted.contains(&0xfffc) {
765+ // The browser made an element we did not ask for; the model wins.
766+ self.view.repair(&self.m, i);
767+ return false;
768+ }
769+ let marks = match (&self.native, &self.composition_marks) {
770+ (Some(n), _) if n.block == i => n.marks.clone(),
771+ (_, Some(mk)) => mk.clone(),
772+ _ if b.kind() == Leaf::Code => Marks::none(),
773+ _ => c::marks_at(&self.m, b.start + p),
774+ };
775+ let text = String::from_utf16_lossy(inserted);
776+ self.m.delete(b.start + p, b.start + model.len() - s);
777+ if !text.is_empty() {
778+ self.m.insert(b.start + p, &text, &marks);
779+ }
780+ true
781+ }
782+
783+ pub fn on_composition_start(&mut self, _ev: &CompositionEvent) {
784+ self.read_dom_selection();
785+ if let Selection::Text { anchor, head } = self.sel
786+ && self.m.at(anchor).index != self.m.at(head).index
787+ {
788+ self.chain(&[c::delete_selection]);
789+ }
790+ self.composition_marks = Some(c::pending_marks(&self.cx()));
791+ self.view.composing = match self.sel {
792+ Selection::Text { head, .. } => Some(self.m.at(head).index),
793+ _ => None,
794+ };
795+ }
796+
797+ pub fn on_composition_end(&mut self, _ev: &CompositionEvent) {
798+ let block = self.view.composing.take();
799+ let deferred = self.view.take_deferred();
800+ let records = self.observer.as_ref().map(|o| o.take_records()).unwrap_or_default();
801+ let mut recs: Vec<MutationRecord> = records.iter().filter_map(|r| r.dyn_into().ok()).collect();
802+ recs.retain(|r| r.target().is_some());
803+ let before = self.sel.clone();
804+ let mut changed = false;
805+ if let Some(i) = block {
806+ changed = self.read_back(i);
807+ }
808+ self.composition_marks = None;
809+ self.read_dom_selection();
810+ if changed {
811+ self.history.push(&self.m, &before, &self.sel, now());
812+ }
813+ self.view.flush(&self.m);
814+ if let Some(i) = block
815+ && (deferred || !self.view.intact(i))
816+ {
817+ self.view.repair(&self.m, i);
818+ self.write_dom_selection();
819+ }
820+ self.drain_own_mutations();
821+ self.placeholder();
822+ self.composition_end = now();
823+ self.notify(changed);
824+ // Mutations outside the composed block still need handling.
825+ if !recs.is_empty() {
826+ self.on_mutations(&recs);
827+ }
828+ }
829+
830+ // -----------------------------------------------------------------------
831+ // Keys
832+ // -----------------------------------------------------------------------
833+
834+ pub fn on_keydown(&mut self, ev: &KeyboardEvent) -> bool {
835+ if ev.is_composing() || ev.key_code() == 229 {
836+ return false;
837+ }
838+ let key = ev.key();
839+ // Safari sends Enter right after compositionend for the commit key.
840+ if key == "Enter" && now() - self.composition_end < 500.0 {
841+ ev.prevent_default();
842+ return true;
843+ }
844+ if !self.editable {
845+ return false;
846+ }
847+ self.read_dom_selection();
848+ let m = if self.is_mac { ev.meta_key() } else { ev.ctrl_key() };
849+ let (shift, alt) = (ev.shift_key(), ev.alt_key());
850+ let lower = key.to_lowercase();
851+ let handled = match (m, shift, alt, lower.as_str()) {
852+ (false, false, false, "enter") => self.chain(ENTER),
853+ (true, false, false, "enter") => self.run(|cx| c::exit_code(cx, true)),
854+ (false, false, false, "backspace") => crate::rules::undo_rule(self) || self.can(|cx| c::chain(cx, BACKSPACE, false)) && self.chain(BACKSPACE),
855+ (false, false, false, "delete") => self.can(|cx| c::chain(cx, DELETE, false)) && self.chain(DELETE),
856+ (true, false, false, "a") => self.run(|cx| c::select_all(cx, true)),
857+ (true, false, false, "k") if self.can(|cx| c::can_link(cx)) => {
858+ crate::ui::request_link(&self.view.root);
859+ true
860+ }
861+ (false, false, false, "tab") => {
862+ self.run(|cx| c::sink_list_item(cx, true));
863+ // Tab never leaves the editor.
864+ true
865+ }
866+ (false, true, false, "tab") => {
867+ self.run(|cx| c::lift_list_item(cx, true));
868+ true
869+ }
870+ (true, false, false, "z") => {
871+ self.undo();
872+ true
873+ }
874+ (true, false, false, "y") | (true, true, false, "z") => {
875+ self.redo();
876+ true
877+ }
878+ (true, false, false, "b") => self.run(|cx| c::toggle_mark(cx, MarkType::Strong, true)),
879+ (true, false, false, "i") => self.run(|cx| c::toggle_mark(cx, MarkType::Em, true)),
880+ (true, false, false, "`") | (true, false, false, "e") => self.run(|cx| c::toggle_mark(cx, MarkType::Code, true)),
881+ (true, false, true, "0") => self.run(|cx| c::set_block_type(cx, Kind::Paragraph, true)),
882+ (true, false, true, d @ ("1" | "2" | "3")) => {
883+ let level = d.parse::<u8>().unwrap();
884+ self.run(|cx| c::toggle_block(cx, Kind::Heading(level), true))
885+ }
886+ (true, true, false, "8" | "*") => self.run(|cx| c::toggle_list(cx, Kind::BulletList, true)),
887+ (true, true, false, "9" | "(") => self.run(|cx| c::toggle_list(cx, Kind::OrderedList, true)),
888+ _ => false,
889+ };
890+ // Ctrl-Alt digits arrive as `key` = the shifted symbol on some layouts.
891+ let handled = handled || (m && alt && self.heading_by_code(&ev.code()));
892+ if handled {
893+ ev.prevent_default();
894+ }
895+ handled
896+ }
897+
898+ fn heading_by_code(&mut self, code: &str) -> bool {
899+ match code {
900+ "Digit0" => self.run(|cx| c::set_block_type(cx, Kind::Paragraph, true)),
901+ "Digit1" | "Digit2" | "Digit3" => {
902+ let level = code[5..].parse::<u8>().unwrap();
903+ self.run(|cx| c::toggle_block(cx, Kind::Heading(level), true))
904+ }
905+ _ => false,
906+ }
907+ }
908+}
909+
910+fn is_low(u: Option<&u16>) -> bool {
911+ u.is_some_and(|u| (0xdc00..0xe000).contains(u))
912+}
913+
914+fn index_in(parent: &DomNode, child: &DomNode) -> u32 {
915+ let kids = parent.child_nodes();
916+ (0..kids.length()).find(|&i| kids.get(i).as_ref() == Some(child)).unwrap_or(0)
917+}
crates/editor/src/lib.rsadded+189 -0
@@ -0,0 +1,189 @@
1+//! The note editor, compiled to wasm32. core is DOM-free and tested natively.
2+
3+pub mod core;
4+pub mod editor;
5+pub mod rules;
6+pub mod strings;
7+pub mod sync;
8+pub mod ui;
9+pub mod view;
10+
11+use std::cell::RefCell;
12+use std::rc::Rc;
13+
14+use loro::LoroDoc;
15+use loro::awareness::EphemeralStore;
16+use wasm_bindgen::prelude::*;
17+use web_sys::{AbortController, AddEventListenerOptions, EventTarget, HtmlElement, MutationObserver, MutationObserverInit};
18+
19+use crate::editor::Editor;
20+
21+/// Presence entries expire after this long without an update (ms).
22+const PRESENCE_TIMEOUT: i64 = 30_000;
23+
24+#[wasm_bindgen(start)]
25+pub fn start() {
26+ std::panic::set_hook(Box::new(|info| web_sys::console::error_1(&info.to_string().into())));
27+ if let Err(e) = boot() {
28+ web_sys::console::error_2(&"editor failed to start".into(), &e);
29+ }
30+}
31+
32+fn boot() -> Result<(), JsValue> {
33+ let window = web_sys::window().ok_or("no window")?;
34+ let document = window.document().ok_or("no document")?;
35+ let Some(mount) = document.get_element_by_id("editor") else { return Ok(()) };
36+ let note_id = mount.get_attribute("data-note-id").unwrap_or_default();
37+ let title = mount.get_attribute("data-note-title").map(|t| t.trim().to_owned()).filter(|t| !t.is_empty()).unwrap_or_else(|| "Note".into());
38+ let root: HtmlElement = match mount.query_selector(".ProseMirror")? {
39+ Some(e) => e.dyn_into()?,
40+ None => {
41+ let e: HtmlElement = document.create_element("div")?.dyn_into()?;
42+ e.set_class_name("ProseMirror");
43+ mount.append_child(&e)?;
44+ e
45+ }
46+ };
47+ root.set_attribute("role", "textbox")?;
48+ root.set_attribute("aria-multiline", "true")?;
49+ root.set_attribute("aria-label", &title)?;
50+ root.set_attribute("translate", "no")?;
51+
52+ let doc = LoroDoc::new();
53+ core::marks::configure(&doc);
54+
55+ let strings = Rc::new(strings::Strings::load(&document));
56+ let ed = Rc::new(RefCell::new(Editor::new(doc, root.clone())));
57+ ed.borrow_mut().placeholder_text = strings.get("placeholder");
58+ let presence = EphemeralStore::new(PRESENCE_TIMEOUT);
59+
60+ let abort = AbortController::new()?;
61+ let opts = AddEventListenerOptions::new();
62+ opts.set_signal(&abort.signal());
63+ let target: &EventTarget = root.as_ref();
64+
65+ listen::<web_sys::InputEvent>(target, "beforeinput", &opts, &ed, |e, ev| e.on_beforeinput(ev));
66+ listen::<web_sys::InputEvent>(target, "input", &opts, &ed, |e, _| e.on_input());
67+ listen::<web_sys::KeyboardEvent>(target, "keydown", &opts, &ed, |e, ev| {
68+ e.on_keydown(ev);
69+ });
70+ listen::<web_sys::CompositionEvent>(target, "compositionstart", &opts, &ed, |e, ev| e.on_composition_start(ev));
71+ listen::<web_sys::CompositionEvent>(target, "compositionend", &opts, &ed, |e, ev| e.on_composition_end(ev));
72+ listen::<web_sys::MouseEvent>(target, "mousedown", &opts, &ed, |e, ev| e.on_mousedown(ev));
73+ listen::<web_sys::Event>(document.as_ref(), "selectionchange", &opts, &ed, |e, _| e.on_selection_change());
74+
75+ let weak = Rc::downgrade(&ed);
76+ let on_mut = Closure::<dyn FnMut(js_sys::Array)>::new(move |records: js_sys::Array| {
77+ let Some(ed) = weak.upgrade() else { return };
78+ let Ok(mut ed) = ed.try_borrow_mut() else { return };
79+ let recs: Vec<web_sys::MutationRecord> = records.iter().filter_map(|r| r.dyn_into().ok()).collect();
80+ ed.on_mutations(&recs);
81+ });
82+ let observer = MutationObserver::new(on_mut.as_ref().unchecked_ref())?;
83+ on_mut.forget();
84+ let init = MutationObserverInit::new();
85+ init.set_child_list(true);
86+ init.set_character_data(true);
87+ init.set_subtree(true);
88+ observer.observe_with_options(&root, &init)?;
89+ ed.borrow_mut().observer = Some(observer.clone());
90+
91+ // Pages and chunks get their content only near the viewport (`View::sync_viewport`),
92+ // checked on the next frame after a scroll, a resize or a change.
93+ let pending = Rc::new(std::cell::Cell::new(false));
94+ let frame: Rc<std::cell::OnceCell<js_sys::Function>> = Rc::default();
95+ let request: Rc<dyn Fn()> = {
96+ let (pending, frame) = (pending.clone(), frame.clone());
97+ Rc::new(move || {
98+ if !pending.replace(true)
99+ && let (Some(w), Some(f)) = (web_sys::window(), frame.get())
100+ {
101+ let _ = w.request_animation_frame(f);
102+ }
103+ })
104+ };
105+ let weak = Rc::downgrade(&ed);
106+ let again = request.clone();
107+ let on_frame = Closure::<dyn FnMut()>::new(move || {
108+ pending.set(false);
109+ let Some(ed) = weak.upgrade() else { return };
110+ let Ok(mut ed) = ed.try_borrow_mut() else {
111+ again();
112+ return;
113+ };
114+ let ed = &mut *ed;
115+ if ed.view.sync_viewport(&ed.m) {
116+ again();
117+ }
118+ ed.drain_own_mutations();
119+ });
120+ let _ = frame.set(on_frame.as_ref().unchecked_ref::<js_sys::Function>().clone());
121+ on_frame.forget();
122+ let scroll_opts = AddEventListenerOptions::new();
123+ scroll_opts.set_signal(&abort.signal());
124+ scroll_opts.set_capture(true);
125+ scroll_opts.set_passive(true);
126+ for (target, name) in [(document.unchecked_ref::<EventTarget>(), "scroll"), (window.unchecked_ref(), "resize")] {
127+ let request = request.clone();
128+ let cb = Closure::<dyn FnMut()>::new(move || request());
129+ let _ = target.add_event_listener_with_callback_and_add_event_listener_options(name, cb.as_ref().unchecked_ref(), &scroll_opts);
130+ cb.forget();
131+ }
132+ {
133+ let request = request.clone();
134+ ed.borrow_mut().listeners.push(Box::new(move |_, changed| {
135+ if changed {
136+ request();
137+ }
138+ }));
139+ }
140+ request();
141+
142+ let net = sync::Net::start(ed.clone(), &note_id, presence, strings.clone());
143+
144+ let ui_cx = ui::Ctx { document: document.clone(), mount: mount.clone(), note_id: note_id.clone(), strings, opts: opts.clone() };
145+ let media = ui::media::install(&ed, &ui_cx);
146+ ui::toolbar::install(&ed, &ui_cx, &media);
147+ ui::floating::install(&ed, &ui_cx);
148+ ui::notelinks::install(&ed, &ui_cx);
149+ ui::clipboard::install(&ed, &ui_cx);
150+ ui::presence::install(&ed, &ui_cx, &net);
151+ ui::codeblock::install(&ed, &ui_cx);
152+
153+ // Live search swaps the page without a reload and fires `note:detach` first.
154+ let ab = abort.clone();
155+ let detach = Closure::<dyn FnMut()>::new(move || {
156+ net.borrow_mut().detach();
157+ observer.disconnect();
158+ ab.abort();
159+ });
160+ let once = AddEventListenerOptions::new();
161+ once.set_once(true);
162+ window.add_event_listener_with_callback_and_add_event_listener_options(
163+ "note:detach",
164+ detach.as_ref().unchecked_ref(),
165+ &once,
166+ )?;
167+ detach.forget();
168+ Ok(())
169+}
170+
171+/// Adds a listener that runs `f` on the editor unless it is already busy.
172+fn listen<E: JsCast + 'static>(
173+ target: &EventTarget,
174+ name: &str,
175+ opts: &AddEventListenerOptions,
176+ ed: &Rc<RefCell<Editor>>,
177+ f: fn(&mut Editor, &E),
178+) {
179+ let weak = Rc::downgrade(ed);
180+ let cb = Closure::<dyn FnMut(web_sys::Event)>::new(move |ev: web_sys::Event| {
181+ let Some(ed) = weak.upgrade() else { return };
182+ let Ok(mut ed) = ed.try_borrow_mut() else { return };
183+ if let Ok(ev) = ev.dyn_into::<E>() {
184+ f(&mut ed, &ev);
185+ }
186+ });
187+ let _ = target.add_event_listener_with_callback_and_add_event_listener_options(name, cb.as_ref().unchecked_ref(), opts);
188+ cb.forget();
189+}
crates/editor/src/rules.rsadded+188 -0
@@ -0,0 +1,188 @@
1+//! Markdown-style input rules (the TS editor's `inputRules`), matched by hand:
2+//! `# `..`### `, "```", `- `/`* `, `1. `, `> `, `---`, `**x**`, `*x*`, `` `x` ``.
3+//! A rule replaces the typed text; Backspace right after it undoes the rule and
4+//! types the text instead.
5+
6+use note_model::flat::Kind as Leaf;
7+
8+use crate::core::commands::{self as c, Cx};
9+use crate::core::doc::Kind;
10+use crate::core::marks::MarkType;
11+use crate::core::model::Blk;
12+use crate::core::pos::{Pos, Selection};
13+use crate::editor::Editor;
14+
15+/// Whether typing `data` could complete a rule (such text is never left to the browser).
16+pub fn may_trigger(data: &str) -> bool {
17+ data.ends_with([' ', '\u{a0}', '`', '*', '-'])
18+}
19+
20+fn is_ws(c: char) -> bool {
21+ c.is_whitespace()
22+}
23+
24+enum Rule {
25+ Block(Kind),
26+ Wrap(Kind, Option<i64>),
27+ Rule,
28+ Mark(MarkType, usize /* content start (utf16) */, usize /* content len */, usize /* delim */),
29+}
30+
31+/// How far back (UTF-16 units) mark rules look for their opening delimiter.
32+const RULE_WINDOW: usize = 2000;
33+
34+fn match_rule(s: &str, whole: bool) -> Option<Rule> {
35+ let chars: Vec<char> = s.chars().collect();
36+ let n = if whole { chars.len() } else { 0 };
37+ // Block rules match the whole text before the caret.
38+ if (2..=4).contains(&n) && is_ws(chars[n - 1]) && chars[..n - 1].iter().all(|&c| c == '#') {
39+ return Some(Rule::Block(Kind::Heading((n - 1) as u8)));
40+ }
41+ if whole && s == "```" {
42+ return Some(Rule::Block(Kind::CodeBlock));
43+ }
44+ if whole && s == "---" {
45+ return Some(Rule::Rule);
46+ }
47+ if n >= 2 && is_ws(chars[n - 1]) {
48+ let head = &chars[..n - 1];
49+ let lead = head.iter().take_while(|c| is_ws(**c)).count();
50+ let rest = &head[lead..];
51+ if rest == ['-'] || rest == ['*'] {
52+ return Some(Rule::Wrap(Kind::BulletList, None));
53+ }
54+ if rest == ['>'] {
55+ return Some(Rule::Wrap(Kind::Blockquote, None));
56+ }
57+ if lead == 0 && rest.len() >= 2 && rest[rest.len() - 1] == '.' && rest[..rest.len() - 1].iter().all(char::is_ascii_digit) {
58+ let num: String = rest[..rest.len() - 1].iter().collect();
59+ let order = num.parse::<i64>().ok()?;
60+ return Some(Rule::Wrap(Kind::OrderedList, Some(order)));
61+ }
62+ }
63+ // Mark rules match the end.
64+ let u: Vec<u16> = s.encode_utf16().collect();
65+ let l = u.len();
66+ let star = b'*' as u16;
67+ let tick = b'`' as u16;
68+ // Start of the run of non-delimiter units ending just before `end`.
69+ let run_start = |end: usize, d: u16| (0..end).rev().take_while(|&i| u[i] != d).last();
70+ if l >= 5 && u[l - 1] == star && u[l - 2] == star {
71+ let ce = l - 2;
72+ if let Some(cs) = run_start(ce, star)
73+ && cs >= 2
74+ && u[cs - 1] == star
75+ && u[cs - 2] == star
76+ && ce > cs
77+ {
78+ return Some(Rule::Mark(MarkType::Strong, cs, ce - cs, 2));
79+ }
80+ }
81+ for (mark, d) in [(MarkType::Em, star), (MarkType::Code, tick)] {
82+ if l >= 3 && u[l - 1] == d && u[l - 2] != d {
83+ let ce = l - 1;
84+ if let Some(cs) = run_start(ce, d)
85+ && cs >= 1
86+ && u[cs - 1] == d
87+ && (mark != MarkType::Em || cs == 1 || u[cs - 2] != star)
88+ {
89+ return Some(Rule::Mark(mark, cs, ce - cs, 1));
90+ }
91+ }
92+ }
93+ None
94+}
95+
96+/// Tries the rules for `data` typed at the caret. Applies one and returns true.
97+pub fn apply(ed: &mut Editor, data: &str) -> bool {
98+ let Some(p) = ed.sel.cursor() else { return false };
99+ let b = ed.m.at(p);
100+ if !b.kind().is_text() || b.kind() == Leaf::Code {
101+ return false;
102+ }
103+ // Mark rules look back within one stretch of text; block rules need the whole
104+ // text before the caret, which is short whenever one can match.
105+ let from = p.saturating_sub(RULE_WINDOW).max(b.start);
106+ let s = ed.m.plain(from, p) + data;
107+ let Some(rule) = match_rule(&s, from == b.start) else { return false };
108+ let rule = match rule {
109+ Rule::Mark(m, cs, len, d) => Rule::Mark(m, cs + from, len, d),
110+ r => r,
111+ };
112+ ed.checkpoint();
113+ let ran = ed.run(|cx| run_rule(cx, &b, p, rule));
114+ if ran {
115+ ed.checkpoint();
116+ ed.last_rule = Some((ed.doc.state_frontiers(), data.to_owned()));
117+ }
118+ ran
119+}
120+
121+/// Whether `b` is the first block of a list item (where PM's rules don't apply).
122+fn starts_item(cx: &Cx, b: &Blk) -> bool {
123+ if !b.attrs.wrap.last().is_some_and(|w| w.is_list()) {
124+ return false;
125+ }
126+ let prev = b.index.checked_sub(1).and_then(|i| cx.m.block(i));
127+ c::keep(prev.as_ref().map(|p| &p.attrs), &b.attrs) < b.depth()
128+}
129+
130+fn run_rule(cx: &mut Cx, b: &Blk, off: Pos, rule: Rule) -> bool {
131+ match rule {
132+ Rule::Block(kind) => {
133+ if !c::can_retype(cx.m, b, kind.leaf().expect("a leaf kind")) {
134+ return false;
135+ }
136+ cx.m.delete(b.start, off);
137+ cx.sel = Selection::caret(b.start);
138+ c::set_block_type(cx, kind, true)
139+ }
140+ Rule::Rule => {
141+ if starts_item(cx, b) {
142+ return false;
143+ }
144+ cx.m.delete(b.start, off);
145+ cx.sel = Selection::caret(b.start);
146+ if b.kind() != Leaf::Para {
147+ c::set_block_type(cx, Kind::Paragraph, true);
148+ }
149+ c::insert_rule(cx, true)
150+ }
151+ Rule::Wrap(kind, start) => {
152+ if starts_item(cx, b) {
153+ return false;
154+ }
155+ cx.m.delete(b.start, off);
156+ cx.sel = Selection::caret(b.start);
157+ if kind == Kind::Blockquote { c::wrap_in(cx, kind, true) } else { c::wrap_in_list(cx, kind, start, true) }
158+ }
159+ Rule::Mark(mark, cs, len, delim) => {
160+ // The closing delimiter is one character short in the doc: the last one was typed.
161+ let close_in_doc = delim - 1;
162+ let ce = cs + len;
163+ cx.m.delete(ce, ce + close_in_doc);
164+ cx.m.delete(cs - delim, cs);
165+ let from = cs - delim;
166+ c::add_mark(cx.m, from, from + len, mark);
167+ cx.sel = Selection::caret(from + len);
168+ cx.stored = None;
169+ let mut m = c::pending_marks(cx);
170+ m.set(mark, false);
171+ cx.stored = Some(m);
172+ true
173+ }
174+ }
175+}
176+
177+/// Backspace right after a rule: undo it and type the text it consumed.
178+pub fn undo_rule(ed: &mut Editor) -> bool {
179+ let Some((frontiers, text)) = ed.last_rule.take() else { return false };
180+ if ed.doc.state_frontiers() != frontiers || !ed.sel.is_empty() {
181+ return false;
182+ }
183+ if !ed.undo() {
184+ return false;
185+ }
186+ ed.run(|cx| c::insert_text(cx, &text));
187+ true
188+}
crates/editor/src/strings.rsadded+24 -0
@@ -0,0 +1,24 @@
1+//! UI strings, rendered by the server into `<script type="application/json" id="editor-strings">`.
2+
3+use wasm_bindgen::JsValue;
4+
5+pub struct Strings(JsValue);
6+
7+impl Strings {
8+ pub fn load(document: &web_sys::Document) -> Self {
9+ let v = document
10+ .get_element_by_id("editor-strings")
11+ .and_then(|e| e.text_content())
12+ .and_then(|t| js_sys::JSON::parse(&t).ok())
13+ .unwrap_or_else(|| js_sys::Object::new().into());
14+ Strings(v)
15+ }
16+
17+ /// The string for `key`, or the key itself when missing.
18+ pub fn get(&self, key: &str) -> String {
19+ js_sys::Reflect::get(&self.0, &key.into())
20+ .ok()
21+ .and_then(|v| v.as_string())
22+ .unwrap_or_else(|| key.to_owned())
23+ }
24+}
crates/editor/src/sync.rsadded+480 -0
@@ -0,0 +1,480 @@
1+//! WebSocket sync with the note's room, ported from the TS editor:
2+//! frames `0x01` SYNC_REQ (version vector), `0x02` UPDATE, `0x03` EPHEMERAL, `0x04` RECORDING.
3+//! The editor turns editable once our oplog has caught up with the server's.
4+//! The sync pill: "Saving…" only when local changes stay unsent for 1.5 s.
5+//! Local changes go out once per frame, after it is painted, as one update since the
6+//! last one sent: encoding inside each commit would hold up every keystroke (a split
7+//! of a huge block encodes megabytes), and makes Loro look up the change block below
8+//! each new change.
9+
10+use std::cell::RefCell;
11+use std::rc::{Rc, Weak};
12+use std::sync::{Arc, Mutex};
13+
14+use loro::awareness::EphemeralStore;
15+use loro::{ExportMode, VersionVector};
16+use wasm_bindgen::prelude::*;
17+use wasm_bindgen::JsCast;
18+use web_sys::{BinaryType, Element, HtmlElement, HtmlMediaElement, MessageEvent, WebSocket};
19+
20+use crate::editor::Editor;
21+use crate::strings::Strings;
22+
23+const SYNC_REQ: u8 = 0x01;
24+const UPDATE: u8 = 0x02;
25+const EPHEMERAL: u8 = 0x03;
26+const RECORDING: u8 = 0x04;
27+const BASE_DELAY: i32 = 500;
28+const MAX_DELAY: i32 = 5000;
29+
30+pub type Outbox = Arc<Mutex<Vec<Vec<u8>>>>;
31+
32+pub struct Net {
33+ me: Weak<RefCell<Net>>,
34+ ed: Rc<RefCell<Editor>>,
35+ pub presence: EphemeralStore,
36+ url: String,
37+ socket: Option<WebSocket>,
38+ retry: i32,
39+ presence_ready: bool,
40+ server_version: Option<VersionVector>,
41+ connected: bool,
42+ ever_connected: bool,
43+ dirty: bool,
44+ saving_shown: bool,
45+ saving_timer: Option<i32>,
46+ flush_timer: Option<i32>,
47+ pub detached: bool,
48+ /// Called after remote presence arrives (the overlay redraws).
49+ pub on_presence: Vec<Box<dyn FnMut(&EphemeralStore)>>,
50+ status: HtmlElement,
51+ live: HtmlElement,
52+ strings: Rc<Strings>,
53+ /// Our oplog's version when local changes were last sent (or remote ones imported).
54+ sent: VersionVector,
55+ send_scheduled: bool,
56+ importing: bool,
57+ ephemeral: Outbox,
58+ _subs: Vec<loro::Subscription>,
59+}
60+
61+fn window() -> web_sys::Window {
62+ web_sys::window().unwrap()
63+}
64+
65+fn timeout(ms: i32, f: impl FnOnce() + 'static) -> i32 {
66+ let cb = Closure::once_into_js(f);
67+ window().set_timeout_with_callback_and_timeout_and_arguments_0(cb.unchecked_ref(), ms).unwrap_or(0)
68+}
69+
70+/// Each `state()` with its label's string key.
71+const STATES: [(&str, &str); 5] = [
72+ ("saved", "statusSaved"),
73+ ("saving", "statusSaving"),
74+ ("connecting", "statusConnecting"),
75+ ("reconnecting", "statusReconnecting"),
76+ ("local", "statusLocal"),
77+];
78+
79+impl Net {
80+ pub fn start(ed: Rc<RefCell<Editor>>, note_id: &str, presence: EphemeralStore, strings: Rc<Strings>) -> Rc<RefCell<Net>> {
81+ let document = window().document().unwrap();
82+ let status = match document.get_element_by_id("sync-status") {
83+ Some(e) => e.dyn_into::<HtmlElement>().unwrap(),
84+ None => {
85+ let e: HtmlElement = document.create_element("span").unwrap().dyn_into().unwrap();
86+ e.set_id("sync-status");
87+ match document.get_element_by_id("sync-slot") {
88+ Some(slot) => {
89+ let _ = slot.append_child(&e);
90+ }
91+ None => {
92+ let _ = ed.borrow().view.root.before_with_node_1(&e);
93+ }
94+ }
95+ e
96+ }
97+ };
98+ // Every label sits in the same grid cell and CSS shows the current one, so the
99+ // pill keeps its width: a resize relayouts the header and costs typing frames.
100+ status.set_text_content(None);
101+ let labels = document.create_element("span").unwrap();
102+ labels.set_class_name("labels");
103+ for (state, key) in STATES {
104+ let label = document.create_element("span").unwrap();
105+ let _ = label.set_attribute("data-label", state);
106+ label.set_text_content(Some(&strings.get(key)));
107+ let _ = labels.append_child(&label);
108+ }
109+ let _ = status.append_child(&labels);
110+ let live: HtmlElement = document.create_element("div").unwrap().dyn_into().unwrap();
111+ live.set_class_name("sr-only");
112+ let _ = live.set_attribute("role", "status");
113+ let _ = live.set_attribute("aria-live", "polite");
114+ let _ = document.body().unwrap().append_child(&live);
115+
116+ let loc = window().location();
117+ let proto = if loc.protocol().unwrap_or_default() == "https:" { "wss" } else { "ws" };
118+ let id: String = js_sys::encode_uri_component(note_id).into();
119+ let url = format!("{proto}://{}/notes/{id}/ws", loc.host().unwrap_or_default());
120+
121+ let ephemeral: Outbox = Arc::default();
122+ let sent = ed.borrow().doc.oplog_vv();
123+ let mut subs = Vec::new();
124+ {
125+ let e = ephemeral.clone();
126+ subs.push(presence.subscribe_local_updates(Box::new(move |b| {
127+ e.lock().unwrap().push(b.clone());
128+ true
129+ })));
130+ }
131+ let net = Rc::new_cyclic(|me| {
132+ RefCell::new(Net {
133+ me: me.clone(),
134+ ed: ed.clone(),
135+ presence,
136+ url,
137+ socket: None,
138+ retry: BASE_DELAY,
139+ presence_ready: false,
140+ server_version: None,
141+ connected: false,
142+ ever_connected: false,
143+ dirty: false,
144+ saving_shown: false,
145+ saving_timer: None,
146+ flush_timer: None,
147+ detached: false,
148+ on_presence: Vec::new(),
149+ status,
150+ live,
151+ strings,
152+ sent,
153+ send_scheduled: false,
154+ importing: false,
155+ ephemeral,
156+ _subs: subs,
157+ })
158+ });
159+ // Every editor change may have produced local updates or presence.
160+ let weak = Rc::downgrade(&net);
161+ ed.borrow_mut().listeners.push(Box::new(move |e, _| {
162+ if let Some(n) = weak.upgrade()
163+ && let Ok(mut n) = n.try_borrow_mut() {
164+ n.local_changes(&e.doc);
165+ n.drain();
166+ }
167+ }));
168+ for (name, offline) in [("offline", true), ("online", false)] {
169+ let weak = Rc::downgrade(&net);
170+ let cb = Closure::<dyn FnMut()>::new(move || {
171+ if let Some(n) = weak.upgrade() {
172+ let n = n.borrow();
173+ n.render_status();
174+ let msg = n.strings.get(if offline { "announceOffline" } else { "announceOnline" });
175+ n.live.set_text_content(Some(&msg));
176+ }
177+ });
178+ let _ = window().add_event_listener_with_callback(name, cb.as_ref().unchecked_ref());
179+ cb.forget();
180+ }
181+ // A tab closed right after typing still sends what was typed.
182+ let me = Rc::downgrade(&net);
183+ let cb = Closure::<dyn FnMut()>::new(move || Net::with(&me, |n| n.send_updates()));
184+ let _ = window().add_event_listener_with_callback("pagehide", cb.as_ref().unchecked_ref());
185+ cb.forget();
186+ net.borrow().render_status();
187+ net.borrow_mut().connect();
188+ net
189+ }
190+
191+ fn is_open(&self) -> bool {
192+ self.socket.as_ref().is_some_and(|s| s.ready_state() == WebSocket::OPEN)
193+ }
194+
195+ fn send(&self, tag: u8, payload: &[u8]) {
196+ if let Some(s) = self.socket.as_ref().filter(|_| self.is_open()) {
197+ let mut f = Vec::with_capacity(payload.len() + 1);
198+ f.push(tag);
199+ f.extend_from_slice(payload);
200+ let _ = s.send_with_u8_array(&f);
201+ }
202+ }
203+
204+ /// Schedules sending the local changes in `doc` (the editor's), if there are any.
205+ fn local_changes(&mut self, doc: &loro::LoroDoc) {
206+ if self.importing || self.send_scheduled || doc.oplog_vv() == self.sent {
207+ return;
208+ }
209+ self.send_scheduled = true;
210+ self.mark_local_change();
211+ // After the next paint; the timeout also covers a hidden tab, which paints
212+ // nothing.
213+ let me = self.me.clone();
214+ let after_paint = Closure::once_into_js(move || {
215+ timeout(0, move || Net::with(&me, |n| n.send_updates()));
216+ });
217+ let _ = window().request_animation_frame(after_paint.unchecked_ref());
218+ let me = self.me.clone();
219+ timeout(100, move || Net::with(&me, |n| n.send_updates()));
220+ }
221+
222+ /// Sends queued presence.
223+ pub fn drain(&mut self) {
224+ let eph = std::mem::take(&mut *self.ephemeral.lock().unwrap());
225+ if self.presence_ready {
226+ for e in &eph {
227+ self.send(EPHEMERAL, e);
228+ }
229+ }
230+ }
231+
232+ /// Sends the local changes made since the last send.
233+ fn send_updates(&mut self) {
234+ let ed = self.ed.clone();
235+ let Ok(ed) = ed.try_borrow() else { return };
236+ self.send_scheduled = false;
237+ let vv = ed.doc.oplog_vv();
238+ if vv == self.sent {
239+ return;
240+ }
241+ // Offline, the next connection's sync request covers them.
242+ if self.is_open()
243+ && let Ok(u) = ed.doc.export(ExportMode::updates(&self.sent))
244+ {
245+ self.send(UPDATE, &u);
246+ }
247+ self.sent = vv;
248+ }
249+
250+ fn state(&self) -> &'static str {
251+ if !window().navigator().on_line() {
252+ "local"
253+ } else if !self.connected {
254+ if self.ever_connected { "reconnecting" } else { "connecting" }
255+ } else if self.saving_shown {
256+ "saving"
257+ } else {
258+ "saved"
259+ }
260+ }
261+
262+ fn render_status(&self) {
263+ let _ = self.status.set_attribute("data-state", self.state());
264+ }
265+
266+ fn with(weak: &Weak<RefCell<Net>>, f: impl FnOnce(&mut Net)) {
267+ if let Some(n) = weak.upgrade()
268+ && let Ok(mut n) = n.try_borrow_mut() {
269+ f(&mut n);
270+ }
271+ }
272+
273+ fn mark_local_change(&mut self) {
274+ if !self.dirty {
275+ self.dirty = true;
276+ if let Some(t) = self.saving_timer.take() {
277+ window().clear_timeout_with_handle(t);
278+ }
279+ let me = self.me.clone();
280+ self.saving_timer = Some(timeout(1500, move || {
281+ Net::with(&me, |n| {
282+ if n.dirty {
283+ n.saving_shown = true;
284+ n.render_status();
285+ }
286+ })
287+ }));
288+ }
289+ if let Some(t) = self.flush_timer.take() {
290+ window().clear_timeout_with_handle(t);
291+ }
292+ let me = self.me.clone();
293+ self.flush_timer = Some(timeout(300, move || Net::with(&me, |n| n.check_flushed())));
294+ }
295+
296+ fn check_flushed(&mut self) {
297+ if !self.dirty {
298+ return;
299+ }
300+ if self.is_open() && self.socket.as_ref().unwrap().buffered_amount() > 0 {
301+ let me = self.me.clone();
302+ self.flush_timer = Some(timeout(100, move || Net::with(&me, |n| n.check_flushed())));
303+ return;
304+ }
305+ self.dirty = false;
306+ if let Some(t) = self.saving_timer.take() {
307+ window().clear_timeout_with_handle(t);
308+ }
309+ self.saving_shown = false;
310+ self.render_status();
311+ }
312+
313+ fn set_connected(&mut self, v: bool) {
314+ self.connected = v;
315+ if v {
316+ self.ever_connected = true;
317+ }
318+ self.render_status();
319+ }
320+
321+ fn maybe_editable(&mut self) {
322+ let Some(server) = &self.server_version else { return };
323+ let mut ed = self.ed.borrow_mut();
324+ let ours = ed.doc.oplog_vv();
325+ if matches!(server.partial_cmp(&ours), Some(std::cmp::Ordering::Less | std::cmp::Ordering::Equal)) {
326+ ed.make_editable();
327+ }
328+ }
329+
330+ fn on_message(&mut self, data: JsValue) {
331+ let Some(buf) = data.dyn_ref::<js_sys::ArrayBuffer>() else { return };
332+ let bytes = js_sys::Uint8Array::new(buf).to_vec();
333+ let Some((&tag, payload)) = bytes.split_first() else { return };
334+ match tag {
335+ SYNC_REQ => {
336+ let Ok(from) = VersionVector::decode(payload) else { return };
337+ let update = self.ed.borrow().doc.export(ExportMode::updates(&from));
338+ if let Ok(u) = update {
339+ self.send(UPDATE, &u);
340+ self.sent = self.ed.borrow().doc.oplog_vv();
341+ }
342+ if !self.presence_ready {
343+ self.presence_ready = true;
344+ self.ephemeral.lock().unwrap().clear();
345+ self.send(EPHEMERAL, &self.presence.encode_all());
346+ }
347+ if self.server_version.is_none() {
348+ self.server_version = Some(from);
349+ self.maybe_editable();
350+ }
351+ }
352+ UPDATE => {
353+ // Ours first, so what the import adds needs no sending.
354+ self.send_updates();
355+ self.importing = true;
356+ let r = self.ed.borrow_mut().import(payload);
357+ self.importing = false;
358+ // Everything new is the server's, except changes of ours made meanwhile.
359+ let ed = self.ed.clone();
360+ let ed = ed.borrow();
361+ let peer = ed.doc.peer_id();
362+ let own = self.sent.get(&peer).copied();
363+ self.sent = ed.doc.oplog_vv();
364+ match own {
365+ Some(c) => {
366+ self.sent.insert(peer, c);
367+ }
368+ None => {
369+ self.sent.remove(&peer);
370+ }
371+ }
372+ self.local_changes(&ed.doc);
373+ drop(ed);
374+ if let Err(e) = r {
375+ web_sys::console::error_2(&"failed to import update".into(), &format!("{e}").into());
376+ }
377+ self.maybe_editable();
378+ }
379+ EPHEMERAL => {
380+ if let Err(e) = self.presence.apply(payload) {
381+ web_sys::console::error_2(&"failed to apply presence".into(), &e.to_string().into());
382+ }
383+ for f in self.on_presence.iter_mut() {
384+ f(&self.presence);
385+ }
386+ }
387+ RECORDING => self.on_recording(payload),
388+ t => web_sys::console::warn_2(&"unknown frame tag".into(), &t.into()),
389+ }
390+ self.drain();
391+ }
392+
393+ /// A take's state, `<session>\t<live|lost|ended>`. `live` and `lost` go on the take's embeds
394+ /// as `data-take-state`. `ended` clears it, and reloads the audio, which now has the whole take.
395+ fn on_recording(&self, payload: &[u8]) {
396+ let Ok(text) = std::str::from_utf8(payload) else { return };
397+ let Some((session, state)) = text.split_once('\t') else { return };
398+ let takes = self.ed.borrow().view.takes.clone();
399+ let (shown, ended) = match state {
400+ "live" | "lost" => {
401+ takes.borrow_mut().insert(session.to_owned(), state.to_owned());
402+ (state, false)
403+ }
404+ "ended" => {
405+ takes.borrow_mut().remove(session);
406+ ("absent", true)
407+ }
408+ _ => return,
409+ };
410+ let Some(doc) = window().document() else { return };
411+ let Ok(spans) = doc.query_selector_all(&format!("[data-take=\"{session}\"]")) else { return };
412+ for span in (0..spans.length()).filter_map(|i| spans.item(i)).filter_map(|n| n.dyn_into::<Element>().ok()) {
413+ let _ = span.set_attribute("data-take-state", shown);
414+ if !ended {
415+ continue;
416+ }
417+ let Ok(audio) = span.query_selector_all("audio") else { continue };
418+ for media in (0..audio.length()).filter_map(|i| audio.item(i)).filter_map(|n| n.dyn_into::<HtmlMediaElement>().ok()) {
419+ media.load();
420+ }
421+ }
422+ }
423+
424+ fn connect(&mut self) {
425+ let Ok(ws) = WebSocket::new(&self.url) else { return };
426+ ws.set_binary_type(BinaryType::Arraybuffer);
427+ let me = self.me.clone();
428+ let onopen = Closure::<dyn FnMut()>::new(move || {
429+ Net::with(&me, |n| {
430+ n.retry = BASE_DELAY;
431+ n.set_connected(true);
432+ n.presence_ready = false;
433+ let vv = n.ed.borrow().doc.oplog_vv().encode();
434+ n.send(SYNC_REQ, &vv);
435+ })
436+ });
437+ let me = self.me.clone();
438+ let onmessage = Closure::<dyn FnMut(MessageEvent)>::new(move |ev: MessageEvent| {
439+ Net::with(&me, |n| n.on_message(ev.data()));
440+ });
441+ let wsc = ws.clone();
442+ let onerror = Closure::<dyn FnMut()>::new(move || {
443+ let _ = wsc.close();
444+ });
445+ let me = self.me.clone();
446+ let wsc = ws.clone();
447+ let onclose = Closure::<dyn FnMut()>::new(move || {
448+ Net::with(&me, |n| {
449+ if n.socket.as_ref() == Some(&wsc) {
450+ n.socket = None;
451+ }
452+ if n.detached {
453+ return;
454+ }
455+ n.set_connected(false);
456+ let again = n.me.clone();
457+ timeout(n.retry, move || Net::with(&again, |n| n.connect()));
458+ n.retry = (n.retry * 2).min(MAX_DELAY);
459+ })
460+ });
461+ ws.set_onopen(Some(onopen.as_ref().unchecked_ref()));
462+ ws.set_onmessage(Some(onmessage.as_ref().unchecked_ref()));
463+ ws.set_onerror(Some(onerror.as_ref().unchecked_ref()));
464+ ws.set_onclose(Some(onclose.as_ref().unchecked_ref()));
465+ onopen.forget();
466+ onmessage.forget();
467+ onerror.forget();
468+ onclose.forget();
469+ self.socket = Some(ws);
470+ }
471+
472+ pub fn detach(&mut self) {
473+ self.send_updates();
474+ self.detached = true;
475+ if let Some(s) = self.socket.take() {
476+ let _ = s.close();
477+ }
478+ self.live.remove();
479+ }
480+}
crates/editor/src/ui/clipboard.rsadded+571 -0
@@ -0,0 +1,571 @@
1+//! Copy, cut, paste and drop. Rich content goes out as `text/html` in the editor's
2+//! own markup and comes back in through a whitelist walk of the parsed HTML.
3+
4+use std::cell::{Cell, RefCell};
5+use std::rc::{Rc, Weak};
6+
7+use wasm_bindgen::closure::Closure;
8+use wasm_bindgen::{JsCast, JsValue};
9+use web_sys::{ClipboardEvent, DataTransfer, DomParser, DragEvent, Document, Element, EventTarget, KeyboardEvent, Node, SupportedType};
10+
11+use super::{listen, media, Ctx, Ed};
12+use crate::core::commands;
13+use crate::core::pos::Selection;
14+use crate::editor::Editor;
15+use note_model::marks::Marks;
16+use note_model::write::{Block, Inline};
17+
18+/// How long after Ctrl/Cmd+Shift+V a paste counts as plain text (as in editing.ts).
19+const PLAIN_PASTE_MS: f64 = 1000.0;
20+
21+pub fn install(ed: &Ed, cx: &Ctx) {
22+ let root = ed.borrow().view.root.clone();
23+ let target: &EventTarget = root.as_ref();
24+
25+ // Ctrl/Cmd+Shift+V arms the plain-text flag. Shift+Insert never does (key is "Insert").
26+ let plain_until = Rc::new(Cell::new(0.0_f64));
27+ {
28+ let plain_until = plain_until.clone();
29+ listen::<KeyboardEvent>(target, "keydown", cx, ed, move |_, ev| {
30+ if (ev.meta_key() || ev.ctrl_key()) && ev.shift_key() && ev.key().eq_ignore_ascii_case("v") {
31+ plain_until.set(js_sys::Date::now() + PLAIN_PASTE_MS);
32+ }
33+ });
34+ }
35+
36+ listen::<ClipboardEvent>(target, "copy", cx, ed, |ed, ev| {
37+ ev.prevent_default();
38+ write_selection(ed, ev);
39+ });
40+
41+ listen::<ClipboardEvent>(target, "cut", cx, ed, |ed, ev| {
42+ ev.prevent_default();
43+ write_selection(ed, ev);
44+ ed.run(|cx| commands::delete_selection(cx, true));
45+ });
46+
47+ {
48+ let plain_until = plain_until.clone();
49+ // Files are uploaded into the editor they were pasted in, held weakly.
50+ let host = Rc::downgrade(ed);
51+ listen::<ClipboardEvent>(target, "paste", cx, ed, move |ed, ev| {
52+ ev.prevent_default();
53+ let plain = plain_until.get() >= js_sys::Date::now();
54+ plain_until.set(0.0);
55+ let dt = ev.clipboard_data();
56+ paste_from(ed, &host, dt.as_ref(), plain);
57+ });
58+ }
59+
60+ listen::<DragEvent>(target, "dragstart", cx, ed, |_, ev| {
61+ // Moving content inside the editor by drag is not supported yet.
62+ ev.prevent_default();
63+ });
64+
65+ // Dragging files over the editor must allow the drop, or the browser opens the file instead.
66+ {
67+ let cb = Closure::<dyn FnMut(web_sys::Event)>::new(|ev: web_sys::Event| {
68+ let Some(dt) = ev.dyn_ref::<DragEvent>().and_then(|e| e.data_transfer()) else { return };
69+ if dt.types().includes(&JsValue::from_str("Files"), 0) {
70+ ev.prevent_default();
71+ }
72+ });
73+ let _ = target.add_event_listener_with_callback_and_add_event_listener_options("dragover", cb.as_ref().unchecked_ref(), &cx.opts);
74+ cb.forget();
75+ }
76+
77+ {
78+ let document = cx.document.clone();
79+ let host = Rc::downgrade(ed);
80+ listen::<DragEvent>(target, "drop", cx, ed, move |ed, ev| {
81+ ev.prevent_default();
82+ let at = caret_at(&document, ev.client_x() as f64, ev.client_y() as f64);
83+ if let Some(pos) = at.and_then(|(node, off)| ed.view.dom_to_pos(&ed.m, &node, off)) {
84+ ed.sel = Selection::caret(pos);
85+ ed.stored = None;
86+ }
87+ let dt = ev.data_transfer();
88+ paste_from(ed, &host, dt.as_ref(), false);
89+ });
90+ }
91+}
92+
93+// ---------------------------------------------------------------------------
94+// Copy and cut
95+// ---------------------------------------------------------------------------
96+
97+fn write_selection(ed: &Editor, ev: &ClipboardEvent) {
98+ let blocks = commands::selected_blocks(&ed.m, &ed.sel);
99+ if blocks.is_empty() {
100+ return;
101+ }
102+ let Some(dt) = ev.clipboard_data() else { return };
103+ let _ = dt.set_data("text/html", &to_html(&blocks));
104+ let _ = dt.set_data("text/plain", &to_text(&blocks));
105+}
106+
107+fn to_html(blocks: &[Block]) -> String {
108+ let mut out = String::new();
109+ for b in blocks {
110+ block_html(b, &mut out);
111+ }
112+ out
113+}
114+
115+fn block_html(b: &Block, out: &mut String) {
116+ match b {
117+ Block::Paragraph(inl) => {
118+ out.push_str("<p>");
119+ inlines_html(inl, out);
120+ out.push_str("</p>");
121+ }
122+ Block::Heading(level, inl) => {
123+ let l = (*level).clamp(1, 6);
124+ out.push_str(&format!("<h{l}>"));
125+ inlines_html(inl, out);
126+ out.push_str(&format!("</h{l}>"));
127+ }
128+ Block::Quote(blocks) => {
129+ out.push_str("<blockquote>");
130+ blocks.iter().for_each(|b| block_html(b, out));
131+ out.push_str("</blockquote>");
132+ }
133+ Block::Code { lang, text } => {
134+ out.push_str("<pre");
135+ if let Some(l) = lang {
136+ out.push_str(&format!(" data-language=\"{}\"", escape(l)));
137+ }
138+ out.push_str("><code>");
139+ out.push_str(&escape(text));
140+ out.push_str("</code></pre>");
141+ }
142+ Block::Rule => out.push_str("<hr>"),
143+ Block::List { ordered, start, items } => {
144+ let tag = if *ordered { "ol" } else { "ul" };
145+ out.push('<');
146+ out.push_str(tag);
147+ if *ordered && *start != 1 {
148+ out.push_str(&format!(" start=\"{start}\""));
149+ }
150+ out.push('>');
151+ for item in items {
152+ out.push_str("<li>");
153+ item.iter().for_each(|b| block_html(b, out));
154+ out.push_str("</li>");
155+ }
156+ out.push_str("</");
157+ out.push_str(tag);
158+ out.push('>');
159+ }
160+ }
161+}
162+
163+fn inlines_html(inl: &[Inline], out: &mut String) {
164+ for i in inl {
165+ match i {
166+ Inline::Text(s, m) => {
167+ // Outermost first: link, em, strong, code.
168+ let mut close = Vec::new();
169+ if let Some((href, title)) = &m.link {
170+ out.push_str(&format!("<a href=\"{}\"", escape(href)));
171+ if let Some(t) = title {
172+ out.push_str(&format!(" title=\"{}\"", escape(t)));
173+ }
174+ out.push('>');
175+ close.push("</a>");
176+ }
177+ if m.em {
178+ out.push_str("<em>");
179+ close.push("</em>");
180+ }
181+ if m.strong {
182+ out.push_str("<strong>");
183+ close.push("</strong>");
184+ }
185+ if m.code {
186+ out.push_str("<code>");
187+ close.push("</code>");
188+ }
189+ out.push_str(&escape(s));
190+ for c in close.iter().rev() {
191+ out.push_str(c);
192+ }
193+ }
194+ Inline::HardBreak => out.push_str("<br>"),
195+ Inline::Image { src, alt, title } => {
196+ out.push_str(&format!("<img src=\"{}\" alt=\"{}\"", escape(src), escape(alt)));
197+ if let Some(t) = title {
198+ out.push_str(&format!(" title=\"{}\"", escape(t)));
199+ }
200+ out.push('>');
201+ }
202+ }
203+ }
204+}
205+
206+fn escape(s: &str) -> String {
207+ let mut out = String::with_capacity(s.len());
208+ for c in s.chars() {
209+ match c {
210+ '&' => out.push_str("&amp;"),
211+ '<' => out.push_str("&lt;"),
212+ '>' => out.push_str("&gt;"),
213+ '"' => out.push_str("&quot;"),
214+ '\'' => out.push_str("&#39;"),
215+ _ => out.push(c),
216+ }
217+ }
218+ out
219+}
220+
221+fn to_text(blocks: &[Block]) -> String {
222+ let mut parts = Vec::new();
223+ blocks.iter().for_each(|b| text_parts(b, &mut parts));
224+ parts.join("\n\n")
225+}
226+
227+fn text_parts(b: &Block, parts: &mut Vec<String>) {
228+ match b {
229+ Block::Paragraph(inl) | Block::Heading(_, inl) => {
230+ let mut s = String::new();
231+ for i in inl {
232+ match i {
233+ Inline::Text(t, _) => s.push_str(t),
234+ Inline::HardBreak => s.push('\n'),
235+ Inline::Image { .. } => {}
236+ }
237+ }
238+ parts.push(s);
239+ }
240+ Block::Quote(blocks) => blocks.iter().for_each(|b| text_parts(b, parts)),
241+ Block::Code { text, .. } => parts.push(text.clone()),
242+ Block::Rule => {}
243+ Block::List { items, .. } => {
244+ for item in items {
245+ item.iter().for_each(|b| text_parts(b, parts));
246+ }
247+ }
248+ }
249+}
250+
251+// ---------------------------------------------------------------------------
252+// Paste and drop
253+// ---------------------------------------------------------------------------
254+
255+/// Inserts what the data transfer holds. `plain` forces text/plain. Files with no text
256+/// beside them are uploaded instead; `host` is the editor they land in.
257+fn paste_from(ed: &mut Editor, host: &Weak<RefCell<Editor>>, dt: Option<&DataTransfer>, plain: bool) {
258+ let Some(dt) = dt else { return };
259+ let text = dt.get_data("text/plain").unwrap_or_default();
260+ let html = if plain { String::new() } else { dt.get_data("text/html").unwrap_or_default() };
261+ // An image copied from a page brings html that holds no text; rich text still wins.
262+ if !plain && text.trim().is_empty() {
263+ let files = media::files_of(dt.files());
264+ if !files.is_empty() && to_text(&html_blocks(&html)).trim().is_empty() {
265+ if let Some(host) = host.upgrade() {
266+ media::insert_files(&host, files);
267+ }
268+ return;
269+ }
270+ }
271+ let mut blocks = if html.trim().is_empty() { Vec::new() } else { html_blocks(&html) };
272+ if blocks.is_empty() {
273+ blocks = plain_blocks(&text);
274+ }
275+ if blocks.is_empty() {
276+ return;
277+ }
278+ ed.run(|cx| commands::insert_blocks(cx, &blocks));
279+}
280+
281+fn plain_blocks(text: &str) -> Vec<Block> {
282+ let text = text.replace("\r\n", "\n").replace('\r', "\n");
283+ let text = text.strip_suffix('\n').unwrap_or(&text);
284+ if text.is_empty() {
285+ return Vec::new();
286+ }
287+ text.split('\n')
288+ .map(|line| {
289+ let inl = if line.is_empty() { Vec::new() } else { vec![Inline::Text(line.to_owned(), Marks::default())] };
290+ Block::Paragraph(inl)
291+ })
292+ .collect()
293+}
294+
295+/// The caret point under the pointer: `caretPositionFromPoint`, else `caretRangeFromPoint`.
296+fn caret_at(document: &Document, x: f64, y: f64) -> Option<(Node, u32)> {
297+ let d: &JsValue = document.as_ref();
298+ let args = (JsValue::from_f64(x), JsValue::from_f64(y));
299+ let pos_fn = js_sys::Reflect::get(d, &"caretPositionFromPoint".into()).ok()?;
300+ if let Ok(f) = pos_fn.dyn_into::<js_sys::Function>() {
301+ let r = f.call2(d, &args.0, &args.1).ok()?;
302+ if r.is_null() || r.is_undefined() {
303+ return None;
304+ }
305+ let node = js_sys::Reflect::get(&r, &"offsetNode".into()).ok()?;
306+ let off = js_sys::Reflect::get(&r, &"offset".into()).ok()?.as_f64()?;
307+ return Some((node.dyn_into::<Node>().ok()?, off as u32));
308+ }
309+ let range_fn = js_sys::Reflect::get(d, &"caretRangeFromPoint".into()).ok()?;
310+ let f = range_fn.dyn_into::<js_sys::Function>().ok()?;
311+ let r = f.call2(d, &args.0, &args.1).ok()?;
312+ if r.is_null() || r.is_undefined() {
313+ return None;
314+ }
315+ let node = js_sys::Reflect::get(&r, &"startContainer".into()).ok()?;
316+ let off = js_sys::Reflect::get(&r, &"startOffset".into()).ok()?.as_f64()?;
317+ Some((node.dyn_into::<Node>().ok()?, off as u32))
318+}
319+
320+// ---------------------------------------------------------------------------
321+// HTML import
322+// ---------------------------------------------------------------------------
323+
324+fn html_blocks(html: &str) -> Vec<Block> {
325+ let Ok(parser) = DomParser::new() else { return Vec::new() };
326+ let Ok(doc) = parser.parse_from_string(html, SupportedType::TextHtml) else { return Vec::new() };
327+ let Some(body) = doc.body() else { return Vec::new() };
328+ let mut acc = Acc::default();
329+ walk_children(&body, &Marks::default(), &mut acc);
330+ acc.finish()
331+}
332+
333+/// Blocks under construction, with the inline run that is not yet in a block.
334+#[derive(Default)]
335+struct Acc {
336+ blocks: Vec<Block>,
337+ inl: Vec<Inline>,
338+}
339+
340+impl Acc {
341+ /// Appends collapsed text the way HTML renders it: runs of whitespace become one
342+ /// space, and no space leads a line.
343+ fn text(&mut self, s: &str, marks: &Marks) {
344+ let mut out = String::with_capacity(s.len());
345+ let mut prev_space = false;
346+ for c in s.chars() {
347+ if matches!(c, ' ' | '\t' | '\n' | '\r' | '\u{0c}') {
348+ if !prev_space {
349+ out.push(' ');
350+ }
351+ prev_space = true;
352+ } else {
353+ out.push(c);
354+ prev_space = false;
355+ }
356+ }
357+ let at_line_start = match self.inl.last() {
358+ None | Some(Inline::HardBreak) | Some(Inline::Image { .. }) => true,
359+ Some(Inline::Text(t, _)) => t.ends_with(' '),
360+ };
361+ if at_line_start {
362+ out = out.trim_start_matches(' ').to_owned();
363+ }
364+ if !out.is_empty() {
365+ self.inl.push(Inline::Text(out, marks.clone()));
366+ }
367+ }
368+
369+ /// Turns the pending inline run into a block (a heading when `level` is set).
370+ fn flush(&mut self, level: Option<i64>) {
371+ let mut inl = std::mem::take(&mut self.inl);
372+ trim_edges(&mut inl);
373+ if inl.is_empty() {
374+ return;
375+ }
376+ self.blocks.push(match level {
377+ Some(l) => Block::Heading(l, inl),
378+ None => Block::Paragraph(inl),
379+ });
380+ }
381+
382+ fn finish(mut self) -> Vec<Block> {
383+ self.flush(None);
384+ self.blocks
385+ }
386+}
387+
388+/// Drops the space at both ends of an inline run (block edges collapse whitespace).
389+fn trim_edges(inl: &mut Vec<Inline>) {
390+ while let Some(Inline::Text(s, _)) = inl.first_mut() {
391+ *s = s.trim_start_matches(' ').to_owned();
392+ if !s.is_empty() {
393+ break;
394+ }
395+ inl.remove(0);
396+ }
397+ while let Some(Inline::Text(s, _)) = inl.last_mut() {
398+ *s = s.trim_end_matches(' ').to_owned();
399+ if !s.is_empty() {
400+ break;
401+ }
402+ inl.pop();
403+ }
404+}
405+
406+fn children(el: &Node) -> Vec<Node> {
407+ let kids = el.child_nodes();
408+ (0..kids.length()).filter_map(|i| kids.item(i)).collect()
409+}
410+
411+fn walk_children(el: &Node, marks: &Marks, acc: &mut Acc) {
412+ for k in children(el) {
413+ walk(&k, marks, acc);
414+ }
415+}
416+
417+/// Tags that only group content: they end the current block and do not style it.
418+const CONTAINERS: &[&str] = &[
419+ "div", "section", "article", "header", "footer", "main", "nav", "aside", "figure", "figcaption", "address", "body",
420+ "html", "table", "thead", "tbody", "tfoot", "tr", "td", "th", "dl", "dt", "dd", "li", "p",
421+];
422+
423+fn walk(node: &Node, marks: &Marks, acc: &mut Acc) {
424+ match node.node_type() {
425+ Node::TEXT_NODE => {
426+ if let Some(s) = node.node_value() {
427+ acc.text(&s, marks);
428+ }
429+ return;
430+ }
431+ Node::ELEMENT_NODE => {}
432+ _ => return,
433+ }
434+ let Some(el) = node.dyn_ref::<Element>() else { return };
435+ let tag = el.tag_name().to_ascii_lowercase();
436+ let tag = tag.as_str();
437+ match tag {
438+ "script" | "style" | "meta" | "head" | "template" | "noscript" | "title" => {}
439+ "br" => acc.inl.push(Inline::HardBreak),
440+ "img" => {
441+ if let Some(src) = el.get_attribute("src").filter(|s| !s.is_empty()) {
442+ acc.inl.push(Inline::Image {
443+ src,
444+ alt: el.get_attribute("alt").unwrap_or_default(),
445+ title: el.get_attribute("title").filter(|t| !t.is_empty()),
446+ });
447+ }
448+ }
449+ "hr" => {
450+ acc.flush(None);
451+ acc.blocks.push(Block::Rule);
452+ }
453+ _ if tag == "pre" || is_preformatted(el) => {
454+ acc.flush(None);
455+ let lang = el
456+ .get_attribute("data-language")
457+ .or_else(|| el.get_attribute("class").and_then(|c| language_class(&c)))
458+ .filter(|l| !l.is_empty());
459+ let mut text = String::new();
460+ pre_text(node, &mut text);
461+ let text = text.strip_suffix('\n').unwrap_or(&text).replace('\u{a0}', " ");
462+ acc.blocks.push(Block::Code { lang, text });
463+ }
464+ "h1" | "h2" | "h3" | "h4" | "h5" | "h6" => {
465+ acc.flush(None);
466+ let level = tag[1..].parse::<i64>().unwrap_or(1);
467+ walk_children(node, marks, acc);
468+ acc.flush(Some(level));
469+ }
470+ "blockquote" => {
471+ acc.flush(None);
472+ let mut sub = Acc::default();
473+ walk_children(node, marks, &mut sub);
474+ let blocks = sub.finish();
475+ if !blocks.is_empty() {
476+ acc.blocks.push(Block::Quote(blocks));
477+ }
478+ }
479+ "ul" | "ol" => {
480+ acc.flush(None);
481+ let items: Vec<Vec<Block>> = children(node)
482+ .iter()
483+ .filter(|c| is_tag(c, "li"))
484+ .map(|li| {
485+ let mut sub = Acc::default();
486+ walk_children(li, marks, &mut sub);
487+ sub.finish()
488+ })
489+ .filter(|v| !v.is_empty())
490+ .collect();
491+ if !items.is_empty() {
492+ let start = if tag == "ol" {
493+ el.get_attribute("start").and_then(|s| s.trim().parse::<i64>().ok()).unwrap_or(1)
494+ } else {
495+ 1
496+ };
497+ acc.blocks.push(Block::List { ordered: tag == "ol", start, items });
498+ }
499+ }
500+ "a" => {
501+ let mut m = marks.clone();
502+ if let Some(href) = el.get_attribute("href").filter(|h| !h.is_empty()) {
503+ let title = el.get_attribute("title").filter(|t| !t.is_empty());
504+ m.link = Some((href, title));
505+ }
506+ walk_children(node, &m, acc);
507+ }
508+ "strong" | "b" => {
509+ let mut m = marks.clone();
510+ m.strong = true;
511+ walk_children(node, &m, acc);
512+ }
513+ "em" | "i" => {
514+ let mut m = marks.clone();
515+ m.em = true;
516+ walk_children(node, &m, acc);
517+ }
518+ "code" => {
519+ let mut m = marks.clone();
520+ m.code = true;
521+ walk_children(node, &m, acc);
522+ }
523+ t if CONTAINERS.contains(&t) => {
524+ acc.flush(None);
525+ walk_children(node, marks, acc);
526+ acc.flush(None);
527+ }
528+ _ => walk_children(node, marks, acc),
529+ }
530+}
531+
532+fn is_tag(n: &Node, want: &str) -> bool {
533+ n.dyn_ref::<Element>().is_some_and(|e| e.tag_name().eq_ignore_ascii_case(want))
534+}
535+
536+/// Code editors (VS Code, JetBrains) copy a `div` styled `white-space: pre`, one
537+/// child `div` per line.
538+fn is_preformatted(el: &Element) -> bool {
539+ el.get_attribute("style").is_some_and(|s| {
540+ let s = s.to_ascii_lowercase().replace(' ', "");
541+ s.contains("white-space:pre")
542+ })
543+}
544+
545+/// Text of preformatted content: line `div`s/`p`s and `br`s become newlines.
546+fn pre_text(node: &Node, out: &mut String) {
547+ for child in children(node) {
548+ match child.node_type() {
549+ Node::TEXT_NODE => out.push_str(&child.text_content().unwrap_or_default()),
550+ Node::ELEMENT_NODE => match child.node_name().to_ascii_lowercase().as_str() {
551+ "br" => out.push('\n'),
552+ "div" | "p" => {
553+ if !out.is_empty() && !out.ends_with('\n') {
554+ out.push('\n');
555+ }
556+ pre_text(&child, out);
557+ if !out.ends_with('\n') {
558+ out.push('\n');
559+ }
560+ }
561+ _ => pre_text(&child, out),
562+ },
563+ _ => {}
564+ }
565+ }
566+}
567+
568+/// `language-x` among the classes of a `pre`, read before the classes are dropped.
569+fn language_class(class: &str) -> Option<String> {
570+ class.split_whitespace().find_map(|c| c.strip_prefix("language-")).map(str::to_owned)
571+}
crates/editor/src/ui/codeblock.rsadded+800 -0
@@ -0,0 +1,800 @@
1+//! Code block headers: a bar over the top strip of every code block with a language picker,
2+//! Format, Copy and a per-user auto-format toggle. The bars live in an overlay on the mount
3+//! (like presence). The editor change listener is O(1): it records state and schedules work.
4+//! Positions are read and written in one animation frame; language detection runs in a
5+//! debounced timer and is cached per block.
6+
7+use std::cell::{Cell, RefCell};
8+use std::collections::{HashMap, HashSet};
9+use std::rc::{Rc, Weak};
10+
11+use wasm_bindgen::prelude::*;
12+use wasm_bindgen::JsCast;
13+use wasm_bindgen_futures::{spawn_local, JsFuture};
14+use web_sys::{
15+ AbortController, AddEventListenerOptions, Document, Event, EventTarget, FocusEvent, Headers, HtmlElement,
16+ HtmlSelectElement, RequestInit, Response,
17+};
18+
19+use super::{h, listen, Ctx, Ed};
20+use crate::core::model::{Blk, Model};
21+use crate::editor::Editor;
22+use crate::strings::Strings;
23+use note_model::flat::Kind;
24+use note_model::lang::{detect, find, Lang, LANGS};
25+
26+/// localStorage key of the per-user auto-format setting ("0" or "1", on by default).
27+const PREF_KEY: &str = "project-note-autoformat";
28+/// Quiet period after a change before languages are detected again.
29+const DETECT_MS: i32 = 300;
30+const FAILED_MS: i32 = 4_000;
31+const COPIED_MS: i32 = 1_500;
32+/// Height of the header, over the top of the block (its 1px border is inset).
33+const HEAD_H: f64 = 34.0;
34+
35+pub fn install(ed: &Ed, cx: &Ctx) {
36+ let Some(window) = web_sys::window() else { return };
37+
38+ let layer = h(&cx.document, "div", &[("class", "code-layer")], None);
39+ set_all(
40+ &layer,
41+ &[
42+ ("position", "absolute".into()),
43+ ("top", "0".into()),
44+ ("left", "0".into()),
45+ ("right", "0".into()),
46+ ("bottom", "0".into()),
47+ ("pointer-events", "none".into()),
48+ ],
49+ );
50+ let _ = cx.mount.append_child(&layer);
51+
52+ let auto = read_pref();
53+ let bars = Rc::new(Bars {
54+ document: cx.document.clone(),
55+ layer,
56+ labels: Labels::load(&cx.strings),
57+ ed: Rc::downgrade(ed),
58+ heads: RefCell::default(),
59+ detected: RefCell::default(),
60+ tracked: RefCell::default(),
61+ leaving: RefCell::default(),
62+ auto: Cell::new(auto),
63+ frame_pending: Cell::new(false),
64+ detect_timer: Cell::new(None),
65+ torn: Cell::new(false),
66+ });
67+
68+ // Every change and caret move: O(1), only records state and schedules work.
69+ {
70+ let weak = Rc::downgrade(&bars);
71+ ed.borrow_mut().listeners.push(Box::new(move |e: &Editor, changed: bool| {
72+ if let Some(b) = weak.upgrade() {
73+ b.on_change(e, changed);
74+ }
75+ }));
76+ }
77+ // Leaving the editor (focus moves anywhere else) ends the tracked block.
78+ let root = ed.borrow().view.root.clone();
79+ let target: &EventTarget = root.as_ref();
80+ let weak = Rc::downgrade(&bars);
81+ listen::<FocusEvent>(target, "focusout", cx, ed, move |e, _| {
82+ if let Some(b) = weak.upgrade() {
83+ b.track(e);
84+ }
85+ });
86+
87+ // Scroll (any container, so capture) and resize move the headers.
88+ for (name, opts) in [("scroll", listen_opts(cx, true, true)), ("resize", listen_opts(cx, false, false))] {
89+ let weak = Rc::downgrade(&bars);
90+ let cb = Closure::<dyn FnMut(Event)>::new(move |_: Event| {
91+ if let Some(b) = weak.upgrade() {
92+ b.schedule_draw();
93+ }
94+ });
95+ let _ = window.add_event_listener_with_callback_and_add_event_listener_options(name, cb.as_ref().unchecked_ref(), &opts);
96+ cb.forget();
97+ }
98+
99+ // Removes the headers and any in-flight format; the editor listener stays inert after this.
100+ {
101+ let bars = bars.clone();
102+ let on_detach = Closure::<dyn FnMut()>::new(move || bars.teardown());
103+ let _ = window.add_event_listener_with_callback_and_add_event_listener_options(
104+ "note:detach",
105+ on_detach.as_ref().unchecked_ref(),
106+ &cx.opts,
107+ );
108+ on_detach.forget();
109+ }
110+
111+ bars.detect_now();
112+ bars.schedule_draw();
113+}
114+
115+/// The strings the headers show, loaded once.
116+struct Labels {
117+ language: String,
118+ auto: String,
119+ format: String,
120+ formatting: String,
121+ format_failed: String,
122+ format_unsupported: String,
123+ copy: String,
124+ copied: String,
125+ auto_format: String,
126+}
127+
128+impl Labels {
129+ fn load(s: &Strings) -> Self {
130+ Labels {
131+ language: s.get("codeLanguage"),
132+ auto: s.get("codeAuto"),
133+ format: s.get("codeFormat"),
134+ formatting: s.get("codeFormatting"),
135+ format_failed: s.get("codeFormatFailed"),
136+ format_unsupported: s.get("codeFormatUnsupported"),
137+ copy: s.get("codeCopy"),
138+ copied: s.get("codeCopied"),
139+ auto_format: s.get("codeAutoFormat"),
140+ }
141+ }
142+}
143+
144+/// One header and the DOM it owns. Dropping it removes its listeners with it.
145+struct Head {
146+ el: HtmlElement,
147+ select: HtmlSelectElement,
148+ /// The first option: "Auto", with the detected language name when there is one.
149+ auto_opt: HtmlElement,
150+ auto_label: String,
151+ /// An option for a `language` attr this build does not know (kept as typed).
152+ extra: Option<HtmlElement>,
153+ format: HtmlElement,
154+ auto: HtmlElement,
155+ status: HtmlElement,
156+ status_timer: Option<i32>,
157+ /// The format request in flight, if any.
158+ job: Option<AbortController>,
159+ _listeners: Vec<Closure<dyn FnMut(Event)>>,
160+}
161+
162+impl Head {
163+ fn dispose(&mut self) {
164+ if let Some(job) = self.job.take() {
165+ job.abort();
166+ }
167+ clear_timer(self.status_timer.take());
168+ self.el.remove();
169+ }
170+}
171+
172+struct Bars {
173+ document: Document,
174+ layer: HtmlElement,
175+ labels: Labels,
176+ ed: Weak<RefCell<Editor>>,
177+ heads: RefCell<HashMap<u32, Head>>,
178+ /// Per code block: the code the language was detected for, and the id found.
179+ detected: RefCell<HashMap<u32, (String, Option<&'static str>)>>,
180+ /// The code block the caret is in, with its code as it was when the caret entered.
181+ tracked: RefCell<Option<(u32, String)>>,
182+ /// Blocks the caret has left since the last check, with the code remembered for them.
183+ leaving: RefCell<Vec<(u32, String)>>,
184+ auto: Cell<bool>,
185+ frame_pending: Cell<bool>,
186+ detect_timer: Cell<Option<i32>>,
187+ torn: Cell<bool>,
188+}
189+
190+/// What a header shows for its block.
191+struct Info {
192+ explicit: Option<String>,
193+ detected: Option<&'static Lang>,
194+ effective: Option<&'static Lang>,
195+}
196+
197+impl Bars {
198+ fn on_change(self: &Rc<Self>, e: &Editor, changed: bool) {
199+ if self.torn.get() {
200+ return;
201+ }
202+ if changed {
203+ self.schedule_detect();
204+ }
205+ self.track(e);
206+ self.schedule_draw();
207+ }
208+
209+ /// Remembers the code of the block the caret is in; when the caret leaves it, the
210+ /// block is checked for a change. Reads one block, and only when the block changes.
211+ fn track(self: &Rc<Self>, e: &Editor) {
212+ let cur = if self.auto.get() && e.focused() { caret_block(e) } else { None };
213+ let mut tracked = self.tracked.borrow_mut();
214+ if tracked.as_ref().map(|(id, _)| id) == cur.as_ref() {
215+ return;
216+ }
217+ let mut left = false;
218+ if let Some(old) = tracked.take() {
219+ self.leaving.borrow_mut().push(old);
220+ left = true;
221+ }
222+ if let Some(id) = cur
223+ && let Some(code) = code_of(e, id)
224+ {
225+ *tracked = Some((id, code));
226+ }
227+ drop(tracked);
228+ if left {
229+ self.schedule_detect();
230+ }
231+ }
232+
233+ /// Runs the detection after a quiet period (restarted by each change).
234+ fn schedule_detect(self: &Rc<Self>) {
235+ let Some(win) = web_sys::window() else { return };
236+ clear_timer(self.detect_timer.take());
237+ let weak = Rc::downgrade(self);
238+ let cb = Closure::once_into_js(move || {
239+ if let Some(b) = weak.upgrade() {
240+ b.detect_timer.set(None);
241+ b.detect_now();
242+ }
243+ });
244+ if let Ok(id) = win.set_timeout_with_callback_and_timeout_and_arguments_0(cb.unchecked_ref(), DETECT_MS) {
245+ self.detect_timer.set(Some(id));
246+ }
247+ }
248+
249+ /// Detects languages of changed blocks, then formats the blocks the caret has left
250+ /// with changed code (when auto-format is on and the language can be formatted).
251+ fn detect_now(self: &Rc<Self>) {
252+ if self.torn.get() {
253+ return;
254+ }
255+ let Some(ed) = self.ed.upgrade() else { return };
256+ let jobs = {
257+ let Ok(e) = ed.try_borrow() else { return };
258+ let live = live_code(&e);
259+ let mut detected = self.detected.borrow_mut();
260+ for (id, b) in &live {
261+ // Detection only reads the start of the code.
262+ let code = code_prefix(&e.m, b);
263+ if detected.get(id).is_some_and(|(seen, _)| *seen == code) {
264+ continue;
265+ }
266+ let found = detect(&code);
267+ detected.insert(*id, (code, found));
268+ }
269+ detected.retain(|id, _| live.iter().any(|(live_id, _)| live_id == id));
270+
271+ let leaving = std::mem::take(&mut *self.leaving.borrow_mut());
272+ if self.auto.get() {
273+ let heads = self.heads.borrow();
274+ leaving
275+ .into_iter()
276+ .filter(|(id, remembered)| {
277+ // A request already in flight (Format was clicked) covers this block.
278+ if heads.get(id).is_some_and(|h| h.job.is_some()) {
279+ return false;
280+ }
281+ let Some(b) = block_of(&e, *id) else { return false };
282+ if b.kind() != Kind::Code || e.m.plain(b.start, b.sep) == *remembered {
283+ return false;
284+ }
285+ let det = detected.get(id).and_then(|(_, d)| *d);
286+ effective(explicit_of(&b).as_deref(), det).is_some_and(|l| l.formattable)
287+ })
288+ .map(|(id, _)| id)
289+ .collect::<Vec<_>>()
290+ } else {
291+ Vec::new()
292+ }
293+ };
294+ for id in jobs {
295+ self.start_format(id);
296+ }
297+ self.schedule_draw();
298+ }
299+
300+ /// Redraws the headers in the next animation frame, at most once per frame.
301+ fn schedule_draw(self: &Rc<Self>) {
302+ if self.torn.get() || self.frame_pending.replace(true) {
303+ return;
304+ }
305+ let Some(win) = web_sys::window() else {
306+ self.frame_pending.set(false);
307+ return;
308+ };
309+ let weak = Rc::downgrade(self);
310+ let cb = Closure::once_into_js(move || {
311+ if let Some(b) = weak.upgrade() {
312+ b.frame_pending.set(false);
313+ b.draw();
314+ }
315+ });
316+ let _ = win.request_animation_frame(cb.unchecked_ref());
317+ }
318+
319+ /// Positions every header over its block and syncs its controls. Only place that reads layout.
320+ fn draw(self: &Rc<Self>) {
321+ if self.torn.get() {
322+ return;
323+ }
324+ let Some(ed) = self.ed.upgrade() else { return };
325+ let Ok(e) = ed.try_borrow() else { return };
326+ self.layer.set_hidden(!e.editable);
327+ if !e.editable {
328+ return;
329+ }
330+ let code = live_code(&e);
331+ let mut heads = self.heads.borrow_mut();
332+ if code.is_empty() {
333+ // No code shown: nothing to place, and measuring would force a layout.
334+ heads.retain(|_, head| {
335+ head.dispose();
336+ false
337+ });
338+ return;
339+ }
340+ let origin = self.layer.get_bounding_client_rect();
341+ let focus = self.document.active_element();
342+ let detected = self.detected.borrow();
343+ let mut live = HashSet::new();
344+
345+ for (id, b) in code {
346+ live.insert(id);
347+ if !heads.contains_key(&id) {
348+ let head = self.build_head(id);
349+ heads.insert(id, head);
350+ }
351+ let Some(head) = heads.get_mut(&id) else { continue };
352+
353+ let det_id = detected.get(&id).and_then(|(_, d)| *d);
354+ let explicit = explicit_of(&b);
355+ let info = Info {
356+ detected: det_id.and_then(find),
357+ effective: effective(explicit.as_deref(), det_id),
358+ explicit,
359+ };
360+
361+ let Some(el) = e.view.element(b.index) else { continue };
362+ let rect = el.get_bounding_client_rect();
363+ head.el.set_hidden(rect.width() <= 0.0 && rect.height() <= 0.0);
364+ set_all(
365+ &head.el,
366+ &[
367+ ("left", px(rect.left() - origin.left() + 1.0)),
368+ ("top", px(rect.top() - origin.top() + 1.0)),
369+ ("width", px((rect.width() - 2.0).max(0.0))),
370+ ("height", px(HEAD_H)),
371+ ],
372+ );
373+ let has_focus = focus.as_ref().is_some_and(|a| head.el.contains(Some(a)));
374+ sync(head, &self.document, &self.labels, &info, has_focus, self.auto.get());
375+ }
376+
377+ heads.retain(|id, head| {
378+ let keep = live.contains(id);
379+ if !keep {
380+ head.dispose();
381+ }
382+ keep
383+ });
384+ }
385+
386+ fn build_head(self: &Rc<Self>, id: u32) -> Head {
387+ let d = &self.document;
388+ let l = &self.labels;
389+ let el = h(d, "div", &[("class", "code-head")], None);
390+
391+ let select: HtmlSelectElement =
392+ h(d, "select", &[("class", "code-lang"), ("aria-label", l.language.as_str())], None).unchecked_into();
393+ let auto_opt = h(d, "option", &[("value", "")], Some(l.auto.as_str()));
394+ let _ = select.append_child(&auto_opt);
395+ for lang in LANGS {
396+ let opt = h(d, "option", &[("value", lang.id)], Some(lang.name));
397+ let _ = select.append_child(&opt);
398+ }
399+
400+ let spacer = h(d, "span", &[("class", "code-spacer"), ("aria-hidden", "true")], None);
401+ let status = h(d, "span", &[("class", "code-status"), ("role", "status"), ("aria-live", "polite")], None);
402+ let format = button(d, "code-btn code-format", &l.format, ICON_FORMAT);
403+ let copy = button(d, "code-btn code-copy", &l.copy, ICON_COPY);
404+ let auto = button(d, "code-btn code-auto", &l.auto_format, ICON_WAND);
405+ let _ = auto.set_attribute("aria-pressed", if self.auto.get() { "true" } else { "false" });
406+
407+ let _ = el.append_child(&select);
408+ let _ = el.append_child(&spacer);
409+ let _ = el.append_child(&status);
410+ let _ = el.append_child(&format);
411+ let _ = el.append_child(&copy);
412+ let _ = el.append_child(&auto);
413+ let _ = self.layer.append_child(&el);
414+
415+ let mut listeners = Vec::new();
416+ {
417+ let (weak, id, sel) = (Rc::downgrade(self), id.clone(), select.clone());
418+ listeners.push(on_el(select.as_ref(), "change", move |_| {
419+ let Some(b) = weak.upgrade() else { return };
420+ let Some(ed) = b.ed.upgrade() else { return };
421+ let v = sel.value();
422+ if let Ok(mut e) = ed.try_borrow_mut()
423+ && let Some(b) = block_of(&e, id)
424+ {
425+ e.set_code_language(b.start, (!v.is_empty()).then_some(v.as_str()));
426+ }
427+ }));
428+ }
429+ {
430+ let (weak, id) = (Rc::downgrade(self), id.clone());
431+ listeners.push(on_el(format.as_ref(), "click", move |_| {
432+ if let Some(b) = weak.upgrade() {
433+ b.start_format(id);
434+ }
435+ }));
436+ }
437+ {
438+ let (weak, id) = (Rc::downgrade(self), id.clone());
439+ listeners.push(on_el(copy.as_ref(), "click", move |_| {
440+ if let Some(b) = weak.upgrade() {
441+ b.copy(id);
442+ }
443+ }));
444+ }
445+ {
446+ let weak = Rc::downgrade(self);
447+ listeners.push(on_el(auto.as_ref(), "click", move |_| {
448+ if let Some(b) = weak.upgrade() {
449+ b.toggle_auto();
450+ }
451+ }));
452+ }
453+
454+ Head {
455+ el,
456+ select,
457+ auto_label: l.auto.clone(),
458+ auto_opt,
459+ extra: None,
460+ format,
461+ auto,
462+ status,
463+ status_timer: None,
464+ job: None,
465+ _listeners: listeners,
466+ }
467+ }
468+
469+ /// Effective language of a block: its `language` attr when set, else the detected one.
470+ fn lang_of(&self, e: &Editor, id: u32) -> Option<&'static Lang> {
471+ let b = block_of(e, id)?;
472+ let det = self.detected.borrow().get(&id).and_then(|(_, d)| *d);
473+ effective(explicit_of(&b).as_deref(), det)
474+ }
475+
476+ /// Sends the block's code to /format and replaces it with the answer.
477+ fn start_format(self: &Rc<Self>, id: u32) {
478+ if self.torn.get() {
479+ return;
480+ }
481+ let Some(ed) = self.ed.upgrade() else { return };
482+ let (code, lang) = {
483+ let Ok(e) = ed.try_borrow() else { return };
484+ let Some(code) = code_of(&e, id) else { return };
485+ (code, self.lang_of(&e, id))
486+ };
487+ let Some(lang) = lang.filter(|l| l.formattable) else { return };
488+ let Ok(ctrl) = AbortController::new() else { return };
489+ {
490+ let mut heads = self.heads.borrow_mut();
491+ let Some(head) = heads.get_mut(&id) else { return };
492+ if let Some(old) = head.job.replace(ctrl.clone()) {
493+ old.abort();
494+ }
495+ }
496+ self.show_status(id, &self.labels.formatting, "", None);
497+ self.schedule_draw();
498+
499+ let weak = Rc::downgrade(self);
500+ let id = id.clone();
501+ spawn_local(async move {
502+ let res = fetch_format(&ctrl, lang.id, &code).await;
503+ // Aborted by a newer request for this block, or by teardown: that one owns the state.
504+ if ctrl.signal().aborted() {
505+ return;
506+ }
507+ if let Some(b) = weak.upgrade() {
508+ b.finish_format(id, &code, res);
509+ }
510+ });
511+ }
512+
513+ fn finish_format(self: &Rc<Self>, id: u32, sent: &str, res: Result<(u16, String), JsValue>) {
514+ self.clear_job(id);
515+ match res {
516+ Ok((200, text)) => {
517+ if let Some(ed) = self.ed.upgrade()
518+ && let Ok(mut e) = ed.try_borrow_mut()
519+ && let Some(b) = block_of(&e, id)
520+ {
521+ e.replace_code(b.start, sent, &text);
522+ }
523+ self.show_status(id, "", "", None);
524+ }
525+ other => {
526+ let msg = match other {
527+ Ok((_, msg)) => msg,
528+ Err(_) => String::new(),
529+ };
530+ self.show_status(id, &self.labels.format_failed, &msg, Some(FAILED_MS));
531+ }
532+ }
533+ self.schedule_draw();
534+ }
535+
536+ fn clear_job(&self, id: u32) {
537+ if let Some(head) = self.heads.borrow_mut().get_mut(&id) {
538+ head.job = None;
539+ }
540+ }
541+
542+ /// Copies the block's code to the clipboard and says so for a moment.
543+ fn copy(self: &Rc<Self>, id: u32) {
544+ let Some(ed) = self.ed.upgrade() else { return };
545+ let Some(code) = ed.try_borrow().ok().and_then(|e| code_of(&e, id)) else { return };
546+ let Some(win) = web_sys::window() else { return };
547+ let nav: JsValue = win.navigator().into();
548+ let Ok(clip) = js_sys::Reflect::get(&nav, &"clipboard".into()) else { return };
549+ let Ok(clip) = clip.dyn_into::<web_sys::Clipboard>() else { return };
550+ let promise = clip.write_text(&code);
551+ let weak = Rc::downgrade(self);
552+ let id = id.clone();
553+ spawn_local(async move {
554+ if JsFuture::from(promise).await.is_ok()
555+ && let Some(b) = weak.upgrade()
556+ {
557+ b.show_status(id, &b.labels.copied, "", Some(COPIED_MS));
558+ }
559+ });
560+ }
561+
562+ fn toggle_auto(self: &Rc<Self>) {
563+ let on = !self.auto.get();
564+ self.auto.set(on);
565+ store_pref(on);
566+ if let Some(ed) = self.ed.upgrade()
567+ && let Ok(e) = ed.try_borrow()
568+ {
569+ self.track(&e);
570+ }
571+ self.schedule_draw();
572+ }
573+
574+ /// Sets a header's status text and tooltip; `hold_ms` clears it again after that long.
575+ fn show_status(self: &Rc<Self>, id: u32, text: &str, title: &str, hold_ms: Option<i32>) {
576+ let mut heads = self.heads.borrow_mut();
577+ let Some(head) = heads.get_mut(&id) else { return };
578+ clear_timer(head.status_timer.take());
579+ head.status.set_text_content(Some(text));
580+ if title.is_empty() {
581+ let _ = head.status.remove_attribute("title");
582+ } else {
583+ let _ = head.status.set_attribute("title", title);
584+ }
585+ if let Some(ms) = hold_ms {
586+ let weak = Rc::downgrade(self);
587+ let id = id.clone();
588+ let cb = Closure::once_into_js(move || {
589+ if let Some(b) = weak.upgrade() {
590+ b.show_status(id, "", "", None);
591+ }
592+ });
593+ head.status_timer = web_sys::window()
594+ .and_then(|w| w.set_timeout_with_callback_and_timeout_and_arguments_0(cb.unchecked_ref(), ms).ok());
595+ }
596+ }
597+
598+ /// Removes every header and aborts requests. Runs on `note:detach`.
599+ fn teardown(&self) {
600+ self.torn.set(true);
601+ clear_timer(self.detect_timer.take());
602+ let mut heads = self.heads.borrow_mut();
603+ for head in heads.values_mut() {
604+ head.dispose();
605+ }
606+ heads.clear();
607+ self.layer.remove();
608+ }
609+}
610+
611+/// Updates one header to match its block. Language controls are left alone while the
612+/// header has focus, so an open dropdown is not disturbed.
613+fn sync(head: &mut Head, d: &Document, l: &Labels, info: &Info, has_focus: bool, auto_on: bool) {
614+ let auto_text = match info.detected {
615+ Some(lang) => format!("{} \u{b7} {}", l.auto, lang.name),
616+ None => l.auto.clone(),
617+ };
618+ if head.auto_label != auto_text {
619+ head.auto_opt.set_text_content(Some(&auto_text));
620+ head.auto_label = auto_text;
621+ }
622+
623+ if !has_focus {
624+ let unknown = info.explicit.as_deref().filter(|raw| find(raw).is_none());
625+ match (unknown, head.extra.take()) {
626+ (Some(raw), Some(opt)) => {
627+ if opt.get_attribute("value").as_deref() != Some(raw) {
628+ let _ = opt.set_attribute("value", raw);
629+ opt.set_text_content(Some(raw));
630+ }
631+ head.extra = Some(opt);
632+ }
633+ (Some(raw), None) => {
634+ let opt = h(d, "option", &[("value", raw)], Some(raw));
635+ let _ = head.select.append_child(&opt);
636+ head.extra = Some(opt);
637+ }
638+ (None, Some(opt)) => opt.remove(),
639+ (None, None) => {}
640+ }
641+ let want = match &info.explicit {
642+ Some(raw) => find(raw).map_or_else(|| raw.clone(), |lang| lang.id.to_owned()),
643+ None => String::new(),
644+ };
645+ if head.select.value() != want {
646+ head.select.set_value(&want);
647+ }
648+ }
649+
650+ let formattable = info.effective.is_some_and(|lang| lang.formattable);
651+ set_flag(&head.format, "disabled", !formattable || head.job.is_some());
652+ let _ = head.format.set_attribute("title", if formattable { l.format.as_str() } else { l.format_unsupported.as_str() });
653+ let _ = head.auto.set_attribute("aria-pressed", if auto_on { "true" } else { "false" });
654+}
655+
656+/// The effective language: the explicit `language` attr when set (unknown values give none),
657+/// else the detected id.
658+fn effective(explicit: Option<&str>, detected: Option<&'static str>) -> Option<&'static Lang> {
659+ match explicit {
660+ Some(raw) => find(raw),
661+ None => detected.and_then(find),
662+ }
663+}
664+
665+/// The block's `language` attr, if set and not blank.
666+fn explicit_of(b: &Blk) -> Option<String> {
667+ b.attrs.lang.clone().filter(|s| !s.trim().is_empty())
668+}
669+
670+/// The first 20 000 characters of a code block: all `detect` looks at.
671+fn code_prefix(m: &Model, b: &Blk) -> String {
672+ m.plain(b.start, (b.start + 20_000).min(b.sep))
673+}
674+
675+/// The block with `key`, if it is rendered.
676+fn block_of(e: &Editor, key: u32) -> Option<Blk> {
677+ e.view.find_key(key).and_then(|i| e.m.block(i))
678+}
679+
680+/// The rendered code blocks, with their keys.
681+fn live_code(e: &Editor) -> Vec<(u32, Blk)> {
682+ e.view
683+ .live_blocks()
684+ .filter(|(_, v)| v.attrs.kind == Kind::Code)
685+ .filter_map(|(i, v)| Some((v.key, e.m.block(i)?)))
686+ .collect()
687+}
688+
689+/// The text of a code block, or None when `id` is not one.
690+fn code_of(e: &Editor, id: u32) -> Option<String> {
691+ let b = block_of(e, id)?;
692+ (b.kind() == Kind::Code).then(|| e.m.plain(b.start, b.sep))
693+}
694+
695+/// The code block the caret is in (the head of the selection), if any.
696+fn caret_block(e: &Editor) -> Option<u32> {
697+ let b = e.m.at(e.sel.head()?);
698+ if b.kind() != Kind::Code {
699+ return None;
700+ }
701+ e.view.bview(b.index).map(|v| v.key)
702+}
703+
704+/// POST /format with the language and code as JSON. Resolves to the status and the body.
705+async fn fetch_format(ctrl: &AbortController, lang: &str, code: &str) -> Result<(u16, String), JsValue> {
706+ let obj: JsValue = js_sys::Object::new().into();
707+ js_sys::Reflect::set(&obj, &"language".into(), &lang.into())?;
708+ js_sys::Reflect::set(&obj, &"code".into(), &code.into())?;
709+ let body: JsValue = js_sys::JSON::stringify(&obj)?.into();
710+
711+ let headers = Headers::new()?;
712+ headers.set("content-type", "application/json")?;
713+ let init = RequestInit::new();
714+ init.set_method("POST");
715+ init.set_headers(&headers);
716+ init.set_body(&body);
717+ init.set_signal(Some(&ctrl.signal()));
718+
719+ let win = web_sys::window().ok_or("no window")?;
720+ let resp: Response = JsFuture::from(win.fetch_with_str_and_init("/format", &init)).await?.dyn_into()?;
721+ let status = resp.status();
722+ let text = JsFuture::from(resp.text()?).await?.as_string().unwrap_or_default();
723+ Ok((status, text))
724+}
725+
726+/// Whether auto-format is on. Missing or unreadable storage counts as on.
727+fn read_pref() -> bool {
728+ let raw = web_sys::window()
729+ .and_then(|w| w.local_storage().ok().flatten())
730+ .and_then(|s| s.get_item(PREF_KEY).ok().flatten());
731+ raw.as_deref() != Some("0")
732+}
733+
734+fn store_pref(on: bool) {
735+ let storage = web_sys::window().and_then(|w| w.local_storage().ok().flatten());
736+ if let Some(s) = storage {
737+ // Storage errors are ignored: the setting then lasts for this page only.
738+ let _ = s.set_item(PREF_KEY, if on { "1" } else { "0" });
739+ }
740+}
741+
742+fn clear_timer(id: Option<i32>) {
743+ if let (Some(id), Some(win)) = (id, web_sys::window()) {
744+ win.clear_timeout_with_handle(id);
745+ }
746+}
747+
748+/// Adds a listener to an element and returns its closure; the caller keeps it alive.
749+fn on_el(target: &EventTarget, name: &str, f: impl FnMut(Event) + 'static) -> Closure<dyn FnMut(Event)> {
750+ let cb = Closure::<dyn FnMut(Event)>::new(f);
751+ let _ = target.add_event_listener_with_callback(name, cb.as_ref().unchecked_ref());
752+ cb
753+}
754+
755+/// Listener options that also carry the detach signal of the UI context.
756+fn listen_opts(cx: &Ctx, capture: bool, passive: bool) -> AddEventListenerOptions {
757+ let o = AddEventListenerOptions::new();
758+ o.set_capture(capture);
759+ o.set_passive(passive);
760+ if let Some(sig) = cx.opts.get_signal() {
761+ o.set_signal(&sig);
762+ }
763+ o
764+}
765+
766+fn button(d: &Document, class: &str, label: &str, inner: &str) -> HtmlElement {
767+ let b = h(d, "button", &[("type", "button"), ("class", class), ("aria-label", label), ("title", label)], None);
768+ b.set_inner_html(&icon(inner));
769+ b
770+}
771+
772+fn icon(inner: &str) -> String {
773+ format!(
774+ r#"<svg viewBox="0 0 24 24" width="14" height="14" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true">{inner}</svg>"#
775+ )
776+}
777+
778+const ICON_FORMAT: &str = r#"<path d="M4 6h16M4 12h10M4 18h14"/>"#;
779+const ICON_COPY: &str = r#"<rect x="9" y="9" width="11" height="11" rx="2"/><path d="M5 15V5a2 2 0 0 1 2-2h10"/>"#;
780+const ICON_WAND: &str = r#"<path d="M12 3l1.8 4.2L18 9l-4.2 1.8L12 15l-1.8-4.2L6 9l4.2-1.8z"/><path d="M19 15l.9 2.1L22 18l-2.1.9L19 21l-.9-2.1L16 18l2.1-.9z"/>"#;
781+
782+fn px(v: f64) -> String {
783+ format!("{v}px")
784+}
785+
786+fn set_flag(el: &HtmlElement, name: &str, on: bool) {
787+ if on {
788+ let _ = el.set_attribute(name, "");
789+ } else {
790+ let _ = el.remove_attribute(name);
791+ }
792+}
793+
794+/// Sets inline style properties. Invalid values are ignored by the browser.
795+fn set_all(el: &HtmlElement, props: &[(&str, String)]) {
796+ let style = el.style();
797+ for (k, v) in props {
798+ let _ = style.set_property(k, v);
799+ }
800+}
crates/editor/src/ui/floating.rsadded+966 -0
@@ -0,0 +1,966 @@
1+//! Floating editor UI (port of `web/src/floating.ts`): the selection bubble menu, the
2+//! link popover (edit mode for Mod-K and the buttons, view mode for a clicked link) and
3+//! the slash "/" block menu. Everything is plain DOM on <body>, positioned from the
4+//! caret boxes.
5+//!
6+//! State lives in `Ui` (DOM handles, item tables, `St`). Editor borrows use
7+//! `try_borrow*` and are released before anything that can re-enter the editor
8+//! (`run`, `focus`, the `editor:link` dispatch), so those calls go through `spawn_local`
9+//! or happen after the borrow is dropped.
10+
11+use std::cell::RefCell;
12+use std::rc::Rc;
13+
14+use wasm_bindgen::prelude::*;
15+use wasm_bindgen_futures::spawn_local;
16+use web_sys::{
17+ AbortSignal, AddEventListenerOptions, Document, Element, Event, EventTarget, HtmlElement, HtmlInputElement, KeyboardEvent,
18+ MouseEvent, Node as DomNode, ScrollIntoViewOptions, ScrollLogicalPosition,
19+};
20+
21+use super::{Ctx, Ed, LINK_EVENT, h, keycaps, mod_keys, place_floating, range_box, request_link, tooltip};
22+use loro::TextDelta;
23+
24+use crate::core::commands::{self as c, Command, Cx};
25+use crate::core::doc::Kind;
26+use crate::core::marks::{MarkType, Marks};
27+use crate::core::pos::{self, Pos, Selection};
28+use crate::editor::Editor;
29+use crate::strings::Strings;
30+
31+struct Bubble {
32+ id: &'static str,
33+ label: String,
34+ glyph: &'static str,
35+ keys: Vec<&'static str>,
36+ run: Command,
37+ active: fn(&Cx) -> bool,
38+}
39+
40+struct SlashItem {
41+ id: &'static str,
42+ label: String,
43+ /// English words the filter also matches, so "h2" or "list" work in either language.
44+ keywords: &'static str,
45+ keys: Vec<&'static str>,
46+ run: Command,
47+}
48+
49+/// Mutable UI state. Never held across a call that can run an editor command.
50+#[derive(Default)]
51+struct St {
52+ bubble_dismissed: bool,
53+ last_sel: Option<Selection>,
54+ link: Option<LinkState>,
55+ slash: Option<SlashState>,
56+ slash_dismissed: Option<Pos>,
57+}
58+
59+struct LinkState {
60+ from: Pos,
61+ to: Pos,
62+ /// Existing href at the range, if any.
63+ href: Option<String>,
64+}
65+
66+struct SlashState {
67+ /// Position of the "/" that opened the menu.
68+ from: Pos,
69+ query: String,
70+ index: usize,
71+ /// Indexes into `Ui::slash_items` that match the query.
72+ filtered: Vec<usize>,
73+}
74+
75+struct Ui {
76+ ed: Ed,
77+ st: RefCell<St>,
78+ document: Document,
79+ root: HtmlElement,
80+ strings: Rc<Strings>,
81+ signal: AbortSignal,
82+ bubble: HtmlElement,
83+ bubble_btns: Vec<HtmlElement>,
84+ bubble_items: Vec<Bubble>,
85+ link_pop: HtmlElement,
86+ edit_panel: HtmlElement,
87+ link_input: HtmlInputElement,
88+ link_error: HtmlElement,
89+ edit_remove: HtmlElement,
90+ edit_open: HtmlElement,
91+ view_panel: HtmlElement,
92+ link_href: HtmlElement,
93+ view_edit: HtmlElement,
94+ view_remove: HtmlElement,
95+ view_open: HtmlElement,
96+ slash_menu: HtmlElement,
97+ slash_list: HtmlElement,
98+ slash_items: Vec<SlashItem>,
99+}
100+
101+pub fn install(ed: &Ed, cx: &Ctx) {
102+ let Some(signal) = js_sys::Reflect::get(&cx.opts, &"signal".into()).ok().and_then(|s| s.dyn_into::<AbortSignal>().ok()) else {
103+ return;
104+ };
105+ let document = cx.document.clone();
106+ let strings = cx.strings.clone();
107+ let root = ed.borrow().view.root.clone();
108+ let s = |k: &str| strings.get(k);
109+ let (m, sh, alt) = mod_keys();
110+
111+ let bubble_items = vec![
112+ Bubble {
113+ id: "bold",
114+ label: s("bold"),
115+ glyph: "B",
116+ keys: vec![m, "B"],
117+ run: |cx, a| c::toggle_mark(cx, MarkType::Strong, a),
118+ active: |cx| c::mark_active_within(cx, MarkType::Strong, c::MARK_STATE_UNITS),
119+ },
120+ Bubble {
121+ id: "italic",
122+ label: s("italic"),
123+ glyph: "I",
124+ keys: vec![m, "I"],
125+ run: |cx, a| c::toggle_mark(cx, MarkType::Em, a),
126+ active: |cx| c::mark_active_within(cx, MarkType::Em, c::MARK_STATE_UNITS),
127+ },
128+ Bubble {
129+ id: "code",
130+ label: s("inlineCode"),
131+ glyph: "</>",
132+ keys: vec![m, "E"],
133+ run: |cx, a| c::toggle_mark(cx, MarkType::Code, a),
134+ active: |cx| c::mark_active_within(cx, MarkType::Code, c::MARK_STATE_UNITS),
135+ },
136+ Bubble {
137+ id: "link",
138+ label: s("link"),
139+ glyph: "Link",
140+ keys: vec![m, "K"],
141+ // Opens the popover (see `bubble_click`); the command only reports availability.
142+ run: |cx, _| c::can_link(cx),
143+ active: |cx| c::mark_active_within(cx, MarkType::Link, c::MARK_STATE_UNITS),
144+ },
145+ Bubble {
146+ id: "h1",
147+ label: s("heading1"),
148+ glyph: "H1",
149+ keys: vec![m, alt, "1"],
150+ run: |cx, a| c::toggle_block(cx, Kind::Heading(1), a),
151+ active: |cx| c::is_block_active(cx, Kind::Heading(1)),
152+ },
153+ Bubble {
154+ id: "h2",
155+ label: s("heading2"),
156+ glyph: "H2",
157+ keys: vec![m, alt, "2"],
158+ run: |cx, a| c::toggle_block(cx, Kind::Heading(2), a),
159+ active: |cx| c::is_block_active(cx, Kind::Heading(2)),
160+ },
161+ Bubble {
162+ id: "h3",
163+ label: s("heading3"),
164+ glyph: "H3",
165+ keys: vec![m, alt, "3"],
166+ run: |cx, a| c::toggle_block(cx, Kind::Heading(3), a),
167+ active: |cx| c::is_block_active(cx, Kind::Heading(3)),
168+ },
169+ ];
170+
171+ let slash_items = vec![
172+ SlashItem {
173+ id: "text",
174+ label: s("paragraph"),
175+ keywords: "text paragraph p",
176+ keys: vec![m, alt, "0"],
177+ run: |cx, a| c::set_block_type(cx, Kind::Paragraph, a),
178+ },
179+ SlashItem {
180+ id: "h1",
181+ label: s("heading1"),
182+ keywords: "heading title h1",
183+ keys: vec![m, alt, "1"],
184+ run: |cx, a| c::toggle_block(cx, Kind::Heading(1), a),
185+ },
186+ SlashItem {
187+ id: "h2",
188+ label: s("heading2"),
189+ keywords: "heading subtitle h2",
190+ keys: vec![m, alt, "2"],
191+ run: |cx, a| c::toggle_block(cx, Kind::Heading(2), a),
192+ },
193+ SlashItem {
194+ id: "h3",
195+ label: s("heading3"),
196+ keywords: "heading h3",
197+ keys: vec![m, alt, "3"],
198+ run: |cx, a| c::toggle_block(cx, Kind::Heading(3), a),
199+ },
200+ SlashItem {
201+ id: "bullets",
202+ label: s("bulletList"),
203+ keywords: "list ul bullet unordered",
204+ keys: vec![m, sh, "8"],
205+ run: |cx, a| c::toggle_list(cx, Kind::BulletList, a),
206+ },
207+ SlashItem {
208+ id: "ordered",
209+ label: s("numberedList"),
210+ keywords: "list ol number ordered",
211+ keys: vec![m, sh, "9"],
212+ run: |cx, a| c::toggle_list(cx, Kind::OrderedList, a),
213+ },
214+ SlashItem { id: "quote", label: s("quote"), keywords: "blockquote quote", keys: vec![">"], run: |cx, a| c::toggle_quote(cx, a) },
215+ SlashItem {
216+ id: "codeblock",
217+ label: s("codeBlock"),
218+ keywords: "code pre fence",
219+ keys: vec!["```"],
220+ run: |cx, a| c::toggle_block(cx, Kind::CodeBlock, a),
221+ },
222+ SlashItem { id: "divider", label: s("divider"), keywords: "hr rule line divider", keys: vec!["---"], run: |cx, a| c::insert_rule(cx, a) },
223+ ];
224+
225+ // Bubble menu.
226+ let bubble_label = s("bubbleLabel");
227+ let bubble = h(&document, "div", &[("class", "bubble"), ("role", "toolbar"), ("aria-label", bubble_label.as_str())], None);
228+ bubble.set_hidden(true);
229+ let mut bubble_btns = Vec::new();
230+ for item in &bubble_items {
231+ let btn = h(
232+ &document,
233+ "button",
234+ &[("type", "button"), ("class", "bubble-btn"), ("aria-label", item.label.as_str()), ("data-command", item.id)],
235+ None,
236+ );
237+ btn.append_child(&h(&document, "span", &[("class", "bubble-glyph"), ("aria-hidden", "true")], Some(item.glyph)))
238+ .ok();
239+ btn.append_child(&tooltip(&document, &item.label, &item.keys, None)).ok();
240+ bubble.append_child(&btn).ok();
241+ bubble_btns.push(btn);
242+ }
243+
244+ // Link popover: the edit and view panels share one element.
245+ let link_dialog = s("linkDialog");
246+ let link_pop = h(&document, "div", &[("class", "popover link-popover"), ("role", "dialog"), ("aria-label", link_dialog.as_str())], None);
247+ link_pop.set_hidden(true);
248+ let edit_panel = h(&document, "form", &[("class", "link-edit"), ("novalidate", "")], None);
249+ let link_url = s("linkUrl");
250+ let link_input: HtmlInputElement = h(
251+ &document,
252+ "input",
253+ &[
254+ ("type", "text"),
255+ ("class", "link-input"),
256+ ("inputmode", "url"),
257+ ("autocomplete", "off"),
258+ ("autocapitalize", "off"),
259+ ("spellcheck", "false"),
260+ ("placeholder", "https://"),
261+ ("aria-label", link_url.as_str()),
262+ ("aria-describedby", "link-error"),
263+ ],
264+ None,
265+ )
266+ .unchecked_into();
267+ let link_error = h(&document, "p", &[("class", "link-error"), ("id", "link-error"), ("role", "alert")], None);
268+ link_error.set_hidden(true);
269+ let apply_btn = h(&document, "button", &[("type", "submit"), ("class", "btn btn-primary")], Some(&s("apply")));
270+ apply_btn.append_child(&keycaps(&document, &["↵"])).ok();
271+ let edit_remove = h(&document, "button", &[("type", "button"), ("class", "btn")], Some(&s("remove")));
272+ let edit_open = h(&document, "button", &[("type", "button"), ("class", "btn")], Some(&s("open")));
273+ let row = h(&document, "div", &[("class", "link-row")], None);
274+ row.append_child(&link_input).ok();
275+ row.append_child(&apply_btn).ok();
276+ let edit_actions = h(&document, "div", &[("class", "link-actions")], None);
277+ edit_actions.append_child(&edit_remove).ok();
278+ edit_actions.append_child(&edit_open).ok();
279+ edit_panel.append_child(&row).ok();
280+ edit_panel.append_child(&link_error).ok();
281+ edit_panel.append_child(&edit_actions).ok();
282+
283+ // View mode is a small menu: the href as its label, then Edit / Remove / Open.
284+ let link_menu = s("linkMenu");
285+ let view_panel = h(&document, "div", &[("class", "link-view"), ("role", "menu"), ("aria-label", link_menu.as_str())], None);
286+ let link_href = h(&document, "span", &[("class", "link-href")], None);
287+ let view_edit = h(&document, "button", &[("type", "button"), ("class", "btn"), ("role", "menuitem")], Some(&s("edit")));
288+ let view_remove = h(&document, "button", &[("type", "button"), ("class", "btn"), ("role", "menuitem")], Some(&s("remove")));
289+ let view_open = h(&document, "button", &[("type", "button"), ("class", "btn"), ("role", "menuitem")], Some(&s("open")));
290+ let view_actions = h(&document, "div", &[("class", "link-actions"), ("role", "none")], None);
291+ view_actions.append_child(&view_edit).ok();
292+ view_actions.append_child(&view_remove).ok();
293+ view_actions.append_child(&view_open).ok();
294+ view_panel.append_child(&link_href).ok();
295+ view_panel.append_child(&view_actions).ok();
296+ link_pop.append_child(&edit_panel).ok();
297+ link_pop.append_child(&view_panel).ok();
298+
299+ // Slash menu.
300+ let slash_menu = h(&document, "div", &[("class", "popover slash-menu"), ("role", "presentation")], None);
301+ slash_menu.set_hidden(true);
302+ let block_menu = s("blockMenu");
303+ let slash_list = h(&document, "div", &[("class", "slash-list"), ("role", "listbox"), ("aria-label", block_menu.as_str())], None);
304+ let footer = h(&document, "div", &[("class", "slash-footer"), ("aria-hidden", "true")], None);
305+ footer.append_child(&keycaps(&document, &["↑", "↓"])).ok();
306+ footer.append_child(&document.create_text_node(&format!(" {} ", s("navigate")))).ok();
307+ footer.append_child(&keycaps(&document, &["↵"])).ok();
308+ footer.append_child(&document.create_text_node(&format!(" {} ", s("insert")))).ok();
309+ footer.append_child(&keycaps(&document, &["Esc"])).ok();
310+ footer.append_child(&document.create_text_node(&format!(" {}", s("close")))).ok();
311+ slash_menu.append_child(&slash_list).ok();
312+ slash_menu.append_child(&footer).ok();
313+
314+ if let Some(body) = document.body() {
315+ body.append_child(&bubble).ok();
316+ body.append_child(&link_pop).ok();
317+ body.append_child(&slash_menu).ok();
318+ }
319+
320+ let ui = Rc::new(Ui {
321+ ed: ed.clone(),
322+ st: RefCell::default(),
323+ document,
324+ root,
325+ strings,
326+ signal,
327+ bubble,
328+ bubble_btns,
329+ bubble_items,
330+ link_pop,
331+ edit_panel,
332+ link_input,
333+ link_error,
334+ edit_remove,
335+ edit_open,
336+ view_panel,
337+ link_href,
338+ view_edit,
339+ view_remove,
340+ view_open,
341+ slash_menu,
342+ slash_list,
343+ slash_items,
344+ });
345+ attach(&ui);
346+
347+ // Keeps the popovers in sync after every doc or selection change.
348+ let l = ui.clone();
349+ ed.borrow_mut().listeners.push(Box::new(move |e: &Editor, changed: bool| {
350+ let mut s = l.st.borrow_mut();
351+ if s.last_sel.as_ref() != Some(&e.sel) {
352+ s.bubble_dismissed = false;
353+ s.last_sel = Some(e.sel.clone());
354+ }
355+ // A popover refers to a fixed range; a doc change invalidates it.
356+ if changed && s.link.is_some() {
357+ s.link = None;
358+ l.link_pop.set_hidden(true);
359+ }
360+ update_slash(e, &mut s, &l);
361+ render(e, &s, &l);
362+ }));
363+}
364+
365+/// Registers the DOM handlers. Every listener uses the editor's abort signal, so it is
366+/// removed on `note:detach`.
367+fn attach(ui: &Rc<Ui>) {
368+ let sig = &ui.signal;
369+
370+ for (i, btn) in ui.bubble_btns.iter().enumerate() {
371+ let (u, is_link, run) = (ui.clone(), ui.bubble_items[i].id == "link", ui.bubble_items[i].run);
372+ on(btn.as_ref(), "click", sig, false, move |_| bubble_click(&u, is_link, run));
373+ }
374+ // Keep the text selection while pressing bubble and slash buttons.
375+ on(ui.bubble.as_ref(), "mousedown", sig, false, |ev| ev.prevent_default());
376+ on(ui.slash_menu.as_ref(), "mousedown", sig, false, |ev| ev.prevent_default());
377+
378+ let u = ui.clone();
379+ on(ui.edit_panel.as_ref(), "submit", sig, false, move |ev| {
380+ ev.prevent_default();
381+ submit_link(&u);
382+ });
383+ // One delegated listener for the slash items, which are rebuilt on every filter change.
384+ let u = ui.clone();
385+ on(ui.slash_list.as_ref(), "click", sig, false, move |ev| {
386+ let item = ev.target().and_then(|t| t.dyn_into::<Element>().ok()).and_then(|t| t.closest(".slash-item").ok().flatten());
387+ let gi = item.and_then(|el| el.get_attribute("data-index")).and_then(|v| v.parse::<usize>().ok());
388+ if let Some(gi) = gi {
389+ slash_click(&u, gi);
390+ }
391+ });
392+ let u = ui.clone();
393+ on(ui.link_pop.as_ref(), "keydown", sig, false, move |ev| link_keydown(&u, ev));
394+
395+ for btn in [&ui.edit_remove, &ui.view_remove] {
396+ let u = ui.clone();
397+ on(btn.as_ref(), "click", sig, false, move |_| remove_link(&u));
398+ }
399+ for btn in [&ui.edit_open, &ui.view_open] {
400+ let u = ui.clone();
401+ on(btn.as_ref(), "click", sig, false, move |_| open_href(&u));
402+ }
403+ let u = ui.clone();
404+ on(ui.view_edit.as_ref(), "click", sig, false, move |_| {
405+ let range = u.st.borrow().link.as_ref().map(|l| (l.from.clone(), l.to.clone()));
406+ if let (Some((from, to)), Ok(e)) = (range, u.ed.try_borrow()) {
407+ show_link(&u, &e, from, to, true);
408+ }
409+ });
410+
411+ // Capture phase so the keys are seen before the editor's own keydown listener.
412+ let u = ui.clone();
413+ on(ui.root.as_ref(), "keydown", sig, true, move |ev| {
414+ let Some(k) = ev.dyn_ref::<KeyboardEvent>() else { return };
415+ if key_down(&u, k) {
416+ ev.prevent_default();
417+ ev.stop_immediate_propagation();
418+ }
419+ });
420+ let u = ui.clone();
421+ on(ui.root.as_ref(), "click", sig, false, move |ev| root_click(&u, ev));
422+ // Mod-K and the toolbar dispatch this synchronously from inside an editor borrow, so
423+ // the popover opens on the next microtask instead.
424+ let u = ui.clone();
425+ on(ui.root.as_ref(), LINK_EVENT, sig, false, move |_| {
426+ let u = u.clone();
427+ spawn_local(async move { open_for_selection(&u) });
428+ });
429+
430+ // Clicking outside the link popover closes it (without moving focus).
431+ let u = ui.clone();
432+ on(ui.document.as_ref(), "mousedown", sig, true, move |ev| {
433+ let target = ev.target().and_then(|t| t.dyn_into::<DomNode>().ok());
434+ let inside = target.as_ref().is_some_and(|t| u.link_pop.contains(Some(t)));
435+ if !inside {
436+ close_link(&u);
437+ }
438+ });
439+
440+ if let Some(win) = web_sys::window() {
441+ let u = ui.clone();
442+ on(win.as_ref(), "scroll", sig, true, move |_| refresh(&u));
443+ let u = ui.clone();
444+ on(win.as_ref(), "resize", sig, false, move |_| refresh(&u));
445+ let u = ui.clone();
446+ on(win.as_ref(), "note:detach", sig, false, move |_| {
447+ u.bubble.remove();
448+ u.link_pop.remove();
449+ u.slash_menu.remove();
450+ });
451+ }
452+}
453+
454+/// Adds a DOM listener that is removed when `signal` aborts.
455+fn on(target: &EventTarget, name: &str, signal: &AbortSignal, capture: bool, f: impl FnMut(&Event) + 'static) {
456+ let opts = AddEventListenerOptions::new();
457+ opts.set_signal(signal);
458+ opts.set_capture(capture);
459+ let mut f = f;
460+ let cb = Closure::<dyn FnMut(Event)>::new(move |ev: Event| f(&ev));
461+ let _ = target.add_event_listener_with_callback_and_add_event_listener_options(name, cb.as_ref().unchecked_ref(), &opts);
462+ cb.forget();
463+}
464+
465+// ---------------------------------------------------------------------------
466+// Visibility and placement
467+// ---------------------------------------------------------------------------
468+
469+fn bool_str(b: bool) -> &'static str {
470+ if b { "true" } else { "false" }
471+}
472+
473+fn set_flag(el: &Element, name: &str, on: bool) {
474+ if on {
475+ let _ = el.set_attribute(name, "");
476+ } else {
477+ let _ = el.remove_attribute(name);
478+ }
479+}
480+
481+fn bubble_visible(e: &Editor, s: &St) -> bool {
482+ let Selection::Text { anchor, head } = &e.sel else { return false };
483+ anchor != head && e.view.composing.is_none() && !s.bubble_dismissed && s.link.is_none()
484+}
485+
486+/// Shows and places every floating surface from the current state.
487+fn render(e: &Editor, s: &St, ui: &Ui) {
488+ let show = bubble_visible(e, s);
489+ ui.bubble.set_hidden(!show);
490+ if show {
491+ let cur = e.cx();
492+ for (btn, item) in ui.bubble_btns.iter().zip(&ui.bubble_items) {
493+ let on = (item.active)(&cur);
494+ let _ = btn.set_attribute("data-active", bool_str(on));
495+ let _ = btn.set_attribute("aria-pressed", bool_str(on));
496+ let enabled = e.can(|cx| (item.run)(cx, false));
497+ set_flag(btn, "disabled", !enabled);
498+ }
499+ if let Some((from, to)) = pos::text_range(&e.m, &e.sel)
500+ && let Some(b) = range_box(e, from, to)
501+ {
502+ place_floating(&ui.bubble, b, true);
503+ }
504+ }
505+ if let Some(l) = &s.link
506+ && let Some(b) = range_box(e, l.from, l.to)
507+ {
508+ place_floating(&ui.link_pop, b, true);
509+ }
510+ if let Some(sl) = &s.slash
511+ && let Some(caret) = e.sel.cursor()
512+ && let Some(b) = range_box(e, sl.from, caret)
513+ {
514+ place_floating(&ui.slash_menu, b, false);
515+ }
516+}
517+
518+/// Re-places the floating UI on scroll and resize.
519+fn refresh(ui: &Ui) {
520+ if let Ok(e) = ui.ed.try_borrow() {
521+ render(&e, &ui.st.borrow(), ui);
522+ }
523+}
524+
525+// ---------------------------------------------------------------------------
526+// Bubble menu
527+// ---------------------------------------------------------------------------
528+
529+fn bubble_click(ui: &Rc<Ui>, is_link: bool, run: Command) {
530+ if is_link {
531+ let can = match ui.ed.try_borrow() {
532+ Ok(e) => e.can(|cx| c::can_link(cx)),
533+ Err(_) => return,
534+ };
535+ if can {
536+ request_link(&ui.root);
537+ }
538+ return;
539+ }
540+ {
541+ let Ok(mut e) = ui.ed.try_borrow_mut() else { return };
542+ e.run(|cx| run(cx, true));
543+ }
544+ let _ = ui.root.focus();
545+}
546+
547+// ---------------------------------------------------------------------------
548+// Link popover
549+// ---------------------------------------------------------------------------
550+
551+/// Removes the popover state and hides it. Returns the state that was open.
552+fn take_link(ui: &Ui) -> Option<LinkState> {
553+ let taken = ui.st.borrow_mut().link.take();
554+ if taken.is_some() {
555+ ui.link_pop.set_hidden(true);
556+ }
557+ taken
558+}
559+
560+fn close_link(ui: &Ui) -> bool {
561+ take_link(ui).is_some()
562+}
563+
564+/// Shows the popover for `[from, to)`. Callers must not hold an editor borrow that a
565+/// focus change could re-enter; this only reads the editor.
566+fn show_link(ui: &Ui, e: &Editor, from: Pos, to: Pos, edit: bool) {
567+ {
568+ let mut s = ui.st.borrow_mut();
569+ s.slash = None;
570+ }
571+ hide_slash(ui);
572+ let href = href_in_range(e, from, to);
573+ ui.st.borrow_mut().link = Some(LinkState { from: from.clone(), to: to.clone(), href: href.clone() });
574+
575+ ui.link_pop.set_hidden(false);
576+ ui.edit_panel.set_hidden(!edit);
577+ ui.view_panel.set_hidden(edit);
578+ ui.link_error.set_hidden(true);
579+ let _ = ui.link_input.remove_attribute("aria-invalid");
580+ let text = href.clone().unwrap_or_default();
581+ ui.link_input.set_value(&text);
582+ ui.link_href.set_text_content(Some(&text));
583+ let needs_link = ui.strings.get("linkNeedsLink");
584+ for btn in [&ui.edit_remove, &ui.edit_open, &ui.view_remove, &ui.view_open] {
585+ let none = href.is_none();
586+ set_flag(btn, "disabled", none);
587+ let _ = btn.set_attribute("title", if none { needs_link.as_str() } else { "" });
588+ }
589+
590+ render(e, &ui.st.borrow(), ui);
591+ if edit {
592+ let _ = ui.link_input.focus();
593+ ui.link_input.select();
594+ } else {
595+ let _ = ui.view_edit.focus();
596+ }
597+}
598+
599+/// Mod-K and the toolbar: edit the selection's link, or the link the caret is in.
600+fn open_for_selection(ui: &Rc<Ui>) {
601+ let Ok(e) = ui.ed.try_borrow() else { return };
602+ let range = match &e.sel {
603+ Selection::Text { anchor, head } if anchor != head => Some(((*anchor).min(*head), (*anchor).max(*head))),
604+ Selection::Text { head, .. } => c::link_range_at(&e.m, *head).map(|(a, b, _)| (a, b)),
605+ _ => None,
606+ };
607+ if let Some((from, to)) = range {
608+ show_link(ui, &e, from, to, true);
609+ }
610+}
611+
612+fn submit_link(ui: &Rc<Ui>) {
613+ let range = ui.st.borrow().link.as_ref().map(|l| (l.from.clone(), l.to.clone()));
614+ let Some((from, to)) = range else { return };
615+ let Some(href) = normalize_href(&ui.link_input.value()) else {
616+ ui.link_error.set_text_content(Some(&ui.strings.get("linkInvalid")));
617+ ui.link_error.set_hidden(false);
618+ let _ = ui.link_input.set_attribute("aria-invalid", "true");
619+ let _ = ui.link_input.focus();
620+ return;
621+ };
622+ close_link(ui);
623+ {
624+ let Ok(mut e) = ui.ed.try_borrow_mut() else { return };
625+ e.run(move |cx| {
626+ c::set_link(cx, from, to, Some(&href));
627+ true
628+ });
629+ }
630+ let _ = ui.root.focus();
631+}
632+
633+fn remove_link(ui: &Rc<Ui>) {
634+ let Some(link) = take_link(ui) else { return };
635+ {
636+ let Ok(mut e) = ui.ed.try_borrow_mut() else { return };
637+ e.run(move |cx| {
638+ c::set_link(cx, link.from, link.to, None);
639+ true
640+ });
641+ }
642+ let _ = ui.root.focus();
643+}
644+
645+fn open_href(ui: &Ui) {
646+ let href = ui.st.borrow().link.as_ref().and_then(|l| l.href.clone());
647+ let Some(href) = href else { return };
648+ let Some(win) = web_sys::window() else { return };
649+ // Note links open in this tab; external links keep opening in a new one.
650+ if is_note_href(&href) {
651+ let _ = win.location().assign(&href);
652+ } else {
653+ let _ = win.open_with_url_and_target_and_features(&href, "_blank", "noopener,noreferrer");
654+ }
655+}
656+
657+/// Escape closes; Up and Down move between the enabled items in view mode.
658+fn link_keydown(ui: &Rc<Ui>, ev: &Event) {
659+ let Some(k) = ev.dyn_ref::<KeyboardEvent>() else { return };
660+ let key = k.key();
661+ if key == "Escape" {
662+ ev.prevent_default();
663+ ev.stop_propagation();
664+ if close_link(ui) {
665+ let _ = ui.root.focus();
666+ }
667+ return;
668+ }
669+ if (key == "ArrowDown" || key == "ArrowUp") && !ui.view_panel.hidden() {
670+ let items: Vec<&HtmlElement> = [&ui.view_edit, &ui.view_remove, &ui.view_open]
671+ .into_iter()
672+ .filter(|b| !b.has_attribute("disabled"))
673+ .collect();
674+ if items.is_empty() {
675+ return;
676+ }
677+ let active = ui.document.active_element();
678+ let index = items.iter().position(|b| {
679+ let el: &Element = b.as_ref();
680+ active.as_ref() == Some(el)
681+ });
682+ let step: i64 = if key == "ArrowDown" { 1 } else { -1 };
683+ let current = index.map_or(-1, |i| i as i64);
684+ let next = (current + step).rem_euclid(items.len() as i64) as usize;
685+ ev.prevent_default();
686+ let _ = items[next].focus();
687+ }
688+}
689+
690+/// Port of ProseMirror's `handleClick`: a click on a link opens the view-mode popover.
691+fn root_click(ui: &Rc<Ui>, ev: &Event) {
692+ let Some(target) = ev.target().and_then(|t| t.dyn_into::<Element>().ok()) else { return };
693+ let Ok(Some(anchor)) = target.closest("a") else { return };
694+ // Ctrl/Cmd+click navigates to a note, so no popover opens for it.
695+ if let Some(m) = ev.dyn_ref::<MouseEvent>()
696+ && (m.ctrl_key() || m.meta_key())
697+ && anchor.get_attribute("href").is_some_and(|h| is_note_href(&h))
698+ {
699+ return;
700+ }
701+ let Ok(e) = ui.ed.try_borrow() else { return };
702+ let Some(node) = anchor.first_child() else { return };
703+ let Some(p) = e.view.dom_to_pos(&e.m, &node, 0) else { return };
704+ let Some((a, b, _)) = c::link_range_at(&e.m, p) else { return };
705+ show_link(ui, &e, a, b, false);
706+}
707+
708+/// The href of the first link mark in `[from, to)`, across the textblocks in between.
709+fn href_in_range(e: &Editor, from: Pos, to: Pos) -> Option<String> {
710+ if from > to {
711+ return None;
712+ }
713+ for d in e.m.slice(from, to) {
714+ if let TextDelta::Insert { attributes, .. } = d
715+ && let Some(link) = Marks::from_attrs(attributes.as_ref()).link
716+ {
717+ return Some(link.href);
718+ }
719+ }
720+ None
721+}
722+
723+/// Accepts plain URLs (adds https://) and http/mailto/relative links; rejects script-like schemes.
724+pub fn normalize_href(raw: &str) -> Option<String> {
725+ let href = raw.trim();
726+ if href.is_empty() {
727+ return None;
728+ }
729+ // Whitespace and control characters are removed before the check, so "java\tscript:" is caught too.
730+ let squashed: String = href.chars().filter(|c| !c.is_whitespace() && !c.is_control()).collect::<String>().to_lowercase();
731+ if ["javascript:", "data:", "vbscript:"].iter().any(|p| squashed.starts_with(p)) {
732+ return None;
733+ }
734+ if has_scheme(href) || href.starts_with('/') || href.starts_with('#') {
735+ return Some(href.to_owned());
736+ }
737+ Some(format!("https://{href}"))
738+}
739+
740+/// `/^[a-z][a-z\d+.-]*:/i`
741+fn has_scheme(s: &str) -> bool {
742+ let mut chars = s.chars();
743+ match chars.next() {
744+ Some(c) if c.is_ascii_alphabetic() => {}
745+ _ => return false,
746+ }
747+ for c in chars {
748+ if c == ':' {
749+ return true;
750+ }
751+ if !(c.is_ascii_alphanumeric() || matches!(c, '+' | '.' | '-')) {
752+ return false;
753+ }
754+ }
755+ false
756+}
757+
758+/// Notes are linked as `/notes/...`; those open in the same tab.
759+fn is_note_href(href: &str) -> bool {
760+ href.starts_with("/notes/")
761+}
762+
763+// ---------------------------------------------------------------------------
764+// Slash menu
765+// ---------------------------------------------------------------------------
766+
767+/// The "/query" before the caret, when the caret is in a textblock outside code.
768+/// The "/" must start the block or follow whitespace.
769+fn slash_context(e: &Editor) -> Option<(Pos, String)> {
770+ let Selection::Text { anchor, head } = &e.sel else { return None };
771+ if anchor != head {
772+ return None;
773+ }
774+ let head = *head;
775+ let block = e.m.at(head);
776+ if !block.kind().is_text() || block.kind() == note_model::flat::Kind::Code {
777+ return None;
778+ }
779+ let from = head.saturating_sub(256).max(block.start);
780+ let before = e.m.plain(from, head);
781+ let chars: Vec<char> = before.chars().collect();
782+ let mut i = chars.len();
783+ while i > 0 && !chars[i - 1].is_whitespace() && chars[i - 1] != '/' {
784+ i -= 1;
785+ }
786+ if i == 0 || chars[i - 1] != '/' {
787+ return None;
788+ }
789+ let slash = i - 1;
790+ if (slash > 0 || from > block.start) && !chars.get(slash.wrapping_sub(1)).is_some_and(|c| c.is_whitespace()) {
791+ return None;
792+ }
793+ let query: String = chars[i..].iter().collect();
794+ let off: usize = from + chars[..slash].iter().map(|c| c.len_utf16()).sum::<usize>();
795+ Some((off, query))
796+}
797+
798+fn filter_items(query: &str, items: &[SlashItem]) -> Vec<usize> {
799+ let q = query.to_lowercase();
800+ (0..items.len())
801+ .filter(|&i| {
802+ let it = &items[i];
803+ q.is_empty() || it.label.to_lowercase().contains(&q) || it.keywords.split(' ').any(|w| w.starts_with(&q))
804+ })
805+ .collect()
806+}
807+
808+/// Opens, filters or closes the slash menu from the current selection.
809+fn update_slash(e: &Editor, s: &mut St, ui: &Rc<Ui>) {
810+ match slash_context(e) {
811+ None => {
812+ s.slash_dismissed = None;
813+ s.slash = None;
814+ }
815+ Some((from, query)) => {
816+ if s.slash_dismissed.as_ref() == Some(&from) || s.link.is_some() {
817+ s.slash = None;
818+ } else {
819+ let index = match &s.slash {
820+ Some(sl) if sl.from == from && sl.query == query => sl.index,
821+ _ => 0,
822+ };
823+ s.slash = Some(SlashState { from, query, index, filtered: Vec::new() });
824+ }
825+ }
826+ }
827+ match s.slash.as_mut() {
828+ Some(sl) => {
829+ sl.filtered = filter_items(&sl.query, &ui.slash_items);
830+ if sl.index >= sl.filtered.len() {
831+ sl.index = 0;
832+ }
833+ draw_slash(sl, ui);
834+ ui.slash_menu.set_hidden(false);
835+ }
836+ None => hide_slash(ui),
837+ }
838+}
839+
840+fn hide_slash(ui: &Ui) {
841+ ui.slash_menu.set_hidden(true);
842+ let _ = ui.root.remove_attribute("aria-activedescendant");
843+}
844+
845+/// Rebuilds the list for the current filter and highlights the active item.
846+fn draw_slash(sl: &SlashState, ui: &Rc<Ui>) {
847+ ui.slash_list.set_text_content(Some(""));
848+ if sl.filtered.is_empty() {
849+ ui.slash_list.append_child(&h(&ui.document, "div", &[("class", "slash-empty"), ("role", "presentation")], Some(&ui.strings.get("noMatches")))).ok();
850+ let _ = ui.root.remove_attribute("aria-activedescendant");
851+ return;
852+ }
853+ let mut active: Option<HtmlElement> = None;
854+ for (pos, &gi) in sl.filtered.iter().enumerate() {
855+ let item = &ui.slash_items[gi];
856+ let selected = pos == sl.index;
857+ let id = format!("slash-opt-{}", item.id);
858+ let index = gi.to_string();
859+ let el = h(
860+ &ui.document,
861+ "div",
862+ &[
863+ ("class", "slash-item"),
864+ ("role", "option"),
865+ ("id", id.as_str()),
866+ ("aria-selected", bool_str(selected)),
867+ ("data-index", index.as_str()),
868+ ],
869+ None,
870+ );
871+ el.append_child(&h(&ui.document, "span", &[("class", "slash-label")], Some(&item.label))).ok();
872+ el.append_child(&keycaps(&ui.document, &item.keys)).ok();
873+ ui.slash_list.append_child(&el).ok();
874+ if selected {
875+ let _ = ui.root.set_attribute("aria-activedescendant", &id);
876+ active = Some(el);
877+ }
878+ }
879+ if let Some(el) = active {
880+ let opts = ScrollIntoViewOptions::new();
881+ opts.set_block(ScrollLogicalPosition::Nearest);
882+ el.scroll_into_view_with_scroll_into_view_options(&opts);
883+ }
884+}
885+
886+fn slash_click(ui: &Rc<Ui>, gi: usize) {
887+ if let Ok(mut e) = ui.ed.try_borrow_mut() {
888+ apply_slash(&mut e, ui, gi);
889+ }
890+ let _ = ui.root.focus();
891+}
892+
893+/// Removes the typed "/query" and runs the chosen block command, as one edit.
894+fn apply_slash(e: &mut Editor, ui: &Rc<Ui>, gi: usize) {
895+ let taken = ui.st.borrow_mut().slash.take();
896+ hide_slash(ui);
897+ let Some(sl) = taken else { return };
898+ let Some(to) = e.sel.cursor() else { return };
899+ if e.m.at(to).index != e.m.at(sl.from).index || to < sl.from {
900+ return;
901+ }
902+ let from = sl.from;
903+ let run = ui.slash_items[gi].run;
904+ e.run(move |cx| {
905+ cx.m.delete(from, to);
906+ cx.sel = Selection::caret(from);
907+ // The deletion is already applied, so the edit commits even if the command declines.
908+ run(cx, true);
909+ true
910+ });
911+}
912+
913+/// Keys while a menu or popover is open. Returns true when the key was consumed.
914+fn key_down(ui: &Rc<Ui>, k: &KeyboardEvent) -> bool {
915+ if k.is_composing() {
916+ return false;
917+ }
918+ let key = k.key();
919+ let (open, n) = {
920+ let s = ui.st.borrow();
921+ (s.slash.is_some(), s.slash.as_ref().map_or(0, |sl| sl.filtered.len()))
922+ };
923+ if open {
924+ match key.as_str() {
925+ "ArrowDown" | "ArrowUp" if n > 0 => {
926+ let mut s = ui.st.borrow_mut();
927+ if let Some(sl) = s.slash.as_mut() {
928+ sl.index = if key == "ArrowDown" { (sl.index + 1) % n } else { (sl.index + n - 1) % n };
929+ draw_slash(sl, ui);
930+ }
931+ return true;
932+ }
933+ "Enter" if n > 0 => {
934+ let gi = {
935+ let s = ui.st.borrow();
936+ s.slash.as_ref().and_then(|sl| sl.filtered.get(sl.index).copied())
937+ };
938+ let Some(gi) = gi else { return false };
939+ let Ok(mut e) = ui.ed.try_borrow_mut() else { return false };
940+ apply_slash(&mut e, ui, gi);
941+ drop(e);
942+ let _ = ui.root.focus();
943+ return true;
944+ }
945+ "Escape" => {
946+ let taken = ui.st.borrow_mut().slash.take();
947+ if let Some(sl) = taken {
948+ ui.st.borrow_mut().slash_dismissed = Some(sl.from);
949+ }
950+ hide_slash(ui);
951+ return true;
952+ }
953+ _ => {}
954+ }
955+ }
956+ if key == "Escape" {
957+ let Ok(e) = ui.ed.try_borrow() else { return false };
958+ if !bubble_visible(&e, &ui.st.borrow()) {
959+ return false;
960+ }
961+ ui.st.borrow_mut().bubble_dismissed = true;
962+ render(&e, &ui.st.borrow(), ui);
963+ return true;
964+ }
965+ false
966+}
crates/editor/src/ui/media.rsadded+777 -0
@@ -0,0 +1,777 @@
1+//! Media in the note: attached files, pasted and dropped files, and microphone recordings.
2+//! A file is POSTed raw to `/media?name=` and comes back as `/media/<hash>.<ext>`. That URL
3+//! becomes an image inline; its extension picks img, audio or video when it is rendered.
4+//! A recording is a take on the server, streamed over a socket part by part. Its URL
5+//! (`/media/rec/<id>`) is placed at the cursor of the press once the first chunk is stored. A
6+//! continuation adds a part to a take and places nothing.
7+
8+use std::cell::{Cell, RefCell};
9+use std::collections::VecDeque;
10+use std::rc::{Rc, Weak};
11+
12+use loro::cursor::Cursor;
13+use wasm_bindgen::closure::Closure;
14+use wasm_bindgen::{JsCast, JsValue};
15+use wasm_bindgen_futures::{JsFuture, spawn_local};
16+use web_sys::{
17+ BeforeUnloadEvent, BinaryType, Blob, BlobEvent, BlobPropertyBag, Element, Event, EventTarget, File, FileList, HtmlButtonElement, HtmlElement,
18+ HtmlInputElement, MediaRecorder, MediaRecorderOptions, MediaStream, MediaStreamConstraints, MediaStreamTrack, MessageEvent, MouseEvent,
19+ RequestInit, Response, WebSocket,
20+};
21+
22+use super::{Ctx, Ed, h};
23+use crate::core::commands;
24+use crate::core::pos::{self, Pos, Selection};
25+use crate::editor::Editor;
26+use crate::strings::Strings;
27+use note_model::marks::Marks;
28+use note_model::render::embed_of;
29+use note_model::write::Inline;
30+
31+/// The toolbar's status line, where a failed upload says so.
32+pub const STATUS_ID: &str = "editor-media-status";
33+
34+/// How long a notice stays in the status line (ms).
35+const NOTICE_MS: i32 = 4000;
36+
37+/// The recorder's format. The server joins only WebM with Opus.
38+const MIME: &str = "audio/webm;codecs=opus";
39+
40+/// A socket that goes this long without an answer, while a chunk waits for its ack or before
41+/// it is ready, is dead (ms).
42+const STALL_MS: f64 = 5000.0;
43+
44+/// The wait before a lost socket is reconnected (ms).
45+const RETRY_MS: i32 = 1000;
46+
47+/// The microphone recording in progress, and everything wired to it. Dropped in a later task
48+/// after the stop, with every handler cleared first.
49+struct Recording {
50+ recorder: MediaRecorder,
51+ stream: MediaStream,
52+ take: Rc<Take>,
53+ tick: Option<i32>,
54+ _on_data: Closure<dyn FnMut(BlobEvent)>,
55+ _on_stop: Closure<dyn FnMut()>,
56+ _ticker: Closure<dyn FnMut()>,
57+}
58+
59+/// One part of a take on its way to the server: the chunks the server does not have yet, and
60+/// every chunk for the local fallback. Shared by the recording and its socket task, so it
61+/// outlives the recording itself.
62+struct Take {
63+ /// The take's id: asked for by the first connection of a new take, then known for good.
64+ session: RefCell<Option<String>>,
65+ /// The part this take's socket is attached to, from the server's `ready`.
66+ part: Cell<Option<u32>>,
67+ /// A new take: its URL is placed in the note once its first chunk is stored.
68+ fresh: bool,
69+ /// Set once the URL is placed.
70+ placed: Cell<bool>,
71+ /// Where the URL goes: the cursor as it was when the button was pressed.
72+ at: Option<Cursor>,
73+ /// The alt text of the embed.
74+ name: String,
75+ mime: String,
76+ chunks: js_sys::Array,
77+ /// Chunks the server does not have yet, the first one at byte `sent`.
78+ queue: RefCell<VecDeque<Blob>>,
79+ /// Bytes of this part the server has stored: the offset of the first queued chunk.
80+ sent: Cell<u64>,
81+ /// Set on stop: no more chunks come.
82+ ended: Cell<bool>,
83+ /// Set when the server rejected the take: nothing more is sent.
84+ failed: Cell<bool>,
85+ /// The beforeunload guard, kept until the take is concluded.
86+ unload: Closure<dyn FnMut(Event)>,
87+}
88+
89+/// What a recording starts: a new take placed at a cursor, or a new part of an earlier take.
90+enum Start {
91+ New(Option<Cursor>),
92+ Continue(String),
93+}
94+
95+struct Inner {
96+ /// Weak, so a closed editor is not kept alive by an upload or a recording.
97+ ed: Weak<RefCell<Editor>>,
98+ note_id: String,
99+ rec: Rc<RefCell<Option<Recording>>>,
100+ /// Set while the microphone is being opened, so a second click does not start another.
101+ starting: Cell<bool>,
102+ /// Set on `note:detach`: the editor is leaving, so a finished recording is kept for later.
103+ detached: Cell<bool>,
104+ /// The record button and its m:ss readout, bound by the toolbar.
105+ ui: RefCell<Option<(HtmlButtonElement, HtmlElement)>>,
106+ input: HtmlInputElement,
107+}
108+
109+/// Handle to the media buttons' behaviour. Clones share the same state.
110+#[derive(Clone)]
111+pub struct Media(Rc<Inner>);
112+
113+impl Media {
114+ /// Opens the file picker; the picked files are uploaded and inserted.
115+ pub fn attach(&self) {
116+ self.0.input.click();
117+ }
118+
119+ /// Starts a recording, or stops the one running.
120+ pub fn toggle_record(&self) {
121+ let inner = self.0.clone();
122+ let recording = inner.rec.borrow().is_some();
123+ if recording {
124+ stop_current(&inner);
125+ } else if !inner.starting.replace(true) {
126+ let at = press_cursor(&inner);
127+ spawn_local(start(inner, Start::New(at)));
128+ }
129+ }
130+
131+ pub fn recording(&self) -> bool {
132+ self.0.rec.borrow().is_some()
133+ }
134+
135+ /// Gives the toolbar's record button and its readout to the recording.
136+ pub fn bind_record(&self, btn: HtmlButtonElement, time: HtmlElement) {
137+ *self.0.ui.borrow_mut() = Some((btn, time));
138+ }
139+}
140+
141+/// Adds the file input and the detach and continue handlers. Call before the toolbar,
142+/// which binds the record button to the returned handle.
143+pub fn install(ed: &Ed, cx: &Ctx) -> Media {
144+ let document = &cx.document;
145+ let input: HtmlInputElement = h(document, "input", &[("type", "file"), ("multiple", ""), ("hidden", "")], None).unchecked_into();
146+ let _ = cx.mount.append_child(&input);
147+ let inner = Rc::new(Inner {
148+ ed: Rc::downgrade(ed),
149+ note_id: cx.note_id.clone(),
150+ rec: Rc::default(),
151+ starting: Cell::new(false),
152+ detached: Cell::new(false),
153+ ui: RefCell::new(None),
154+ input: input.clone(),
155+ });
156+
157+ // Picked files are uploaded; the input is reset so the same file can be picked again.
158+ {
159+ let (host, picker) = (Rc::downgrade(ed), input.clone());
160+ let cb = Closure::<dyn FnMut(Event)>::new(move |_: Event| {
161+ let files = files_of(picker.files());
162+ picker.set_value("");
163+ if let Some(host) = host.upgrade()
164+ && !files.is_empty()
165+ {
166+ insert_files(&host, files);
167+ }
168+ });
169+ let _ = input.add_event_listener_with_callback_and_add_event_listener_options("change", cb.as_ref().unchecked_ref(), &cx.opts);
170+ cb.forget();
171+ }
172+
173+ // Leaving the note: a recording in progress is stopped, and its take is finished by the socket task.
174+ {
175+ let weak = Rc::downgrade(&inner);
176+ let cb = Closure::<dyn FnMut(Event)>::new(move |_: Event| {
177+ let Some(inner) = weak.upgrade() else { return };
178+ inner.detached.set(true);
179+ stop_current(&inner);
180+ });
181+ if let Some(win) = web_sys::window() {
182+ let _ = win.add_event_listener_with_callback_and_add_event_listener_options("note:detach", cb.as_ref().unchecked_ref(), &cx.opts);
183+ }
184+ cb.forget();
185+ }
186+
187+ // The continue button of a take: a press keeps the caret where it is, and a click continues the take.
188+ {
189+ let root = ed.borrow().view.root.clone();
190+ let target: &EventTarget = root.as_ref();
191+ let press = Closure::<dyn FnMut(MouseEvent)>::new(|ev: MouseEvent| {
192+ if continue_target(&ev).is_some() {
193+ ev.prevent_default();
194+ }
195+ });
196+ let _ = target.add_event_listener_with_callback_and_add_event_listener_options("mousedown", press.as_ref().unchecked_ref(), &cx.opts);
197+ press.forget();
198+ let weak = Rc::downgrade(&inner);
199+ let click = Closure::<dyn FnMut(MouseEvent)>::new(move |ev: MouseEvent| {
200+ if let (Some(session), Some(inner)) = (continue_target(&ev), weak.upgrade()) {
201+ continue_take(inner, session);
202+ }
203+ });
204+ let _ = target.add_event_listener_with_callback_and_add_event_listener_options("click", click.as_ref().unchecked_ref(), &cx.opts);
205+ click.forget();
206+ }
207+
208+ Media(inner)
209+}
210+
211+/// The files of a file list (picker or clipboard), in order.
212+pub fn files_of(list: Option<FileList>) -> Vec<File> {
213+ let Some(list) = list else { return Vec::new() };
214+ (0..list.length()).filter_map(|i| list.item(i)).collect()
215+}
216+
217+/// Uploads each file in turn and inserts it at the selection once it is stored. A failed
218+/// upload shows a notice and the rest still go on.
219+pub fn insert_files(ed: &Ed, files: Vec<File>) {
220+ let weak = Rc::downgrade(ed);
221+ spawn_local(async move {
222+ for file in files {
223+ let name = file.name();
224+ let blob: &Blob = file.as_ref();
225+ match upload(blob, &name).await {
226+ Ok(url) => {
227+ if let Some(ed) = weak.upgrade() {
228+ insert(&ed, embed(&url, &name));
229+ }
230+ }
231+ Err(_) => notice("mediaFailed"),
232+ }
233+ }
234+ });
235+}
236+
237+/// POSTs one file as its raw bytes. The answer is the URL of the stored copy.
238+async fn upload(blob: &Blob, name: &str) -> Result<String, JsValue> {
239+ let win = web_sys::window().ok_or("no window")?;
240+ let url = format!("/media?name={}", String::from(js_sys::encode_uri_component(name)));
241+ let body: &JsValue = blob.as_ref();
242+ let init = RequestInit::new();
243+ init.set_method("POST");
244+ init.set_body(body);
245+ let resp: Response = JsFuture::from(win.fetch_with_str_and_init(&url, &init)).await?.dyn_into()?;
246+ if !resp.ok() {
247+ return Err(format!("upload {}", resp.status()).into());
248+ }
249+ let text = JsFuture::from(resp.text()?).await?.as_string().unwrap_or_default();
250+ Ok(text.trim().to_owned())
251+}
252+
253+/// The inline for a stored file: an embed when its extension can show, else a link to it.
254+fn embed(url: &str, name: &str) -> Inline {
255+ if embed_of(url).is_some() {
256+ Inline::Image { src: url.to_owned(), alt: name.to_owned(), title: None }
257+ } else {
258+ let mut marks = Marks::default();
259+ marks.link = Some((url.to_owned(), None));
260+ Inline::Text(name.to_owned(), marks)
261+ }
262+}
263+
264+/// Puts an inline at the selection, the way typing does. False when the editor is busy.
265+fn insert(ed: &Ed, inl: Inline) -> bool {
266+ let Ok(mut e) = ed.try_borrow_mut() else { return false };
267+ e.run(|cx| commands::insert_inline(cx, &[inl]))
268+}
269+
270+/// Puts an inline at the cursor `at`, or at the end of the doc when it no longer resolves, and
271+/// leaves the selection where it was (moved past the inline when it was after it). False when
272+/// the editor is busy.
273+fn insert_at(ed: &Ed, at: Option<&Cursor>, inl: Inline) -> bool {
274+ let Ok(mut e) = ed.try_borrow_mut() else { return false };
275+ e.run(|cx| {
276+ let m = cx.m;
277+ let p = at.and_then(|c| m.cursor_pos(c)).unwrap_or_else(|| m.total());
278+ let p = pos::snap(m, p);
279+ let saved = std::mem::replace(&mut cx.sel, Selection::caret(p));
280+ let ok = commands::insert_inline(cx, &[inl]);
281+ let shift = |q: Pos| if q >= p { q + 1 } else { q };
282+ cx.sel = match saved {
283+ Selection::Text { anchor, head } => Selection::Text { anchor: shift(anchor), head: shift(head) },
284+ Selection::Node(q) => Selection::Node(shift(q)),
285+ Selection::Gap(q) => Selection::Gap(shift(q)),
286+ Selection::All => Selection::All,
287+ };
288+ ok
289+ })
290+}
291+
292+/// Shows a message in the status line, then clears it when it is still the one shown.
293+fn notice(key: &str) {
294+ let Some(win) = web_sys::window() else { return };
295+ let Some(doc) = win.document() else { return };
296+ let Some(el) = doc.get_element_by_id(STATUS_ID) else { return };
297+ let text = Strings::load(&doc).get(key);
298+ el.set_text_content(Some(&text));
299+ let shown = text;
300+ let clear = Closure::once_into_js(move || {
301+ if el.text_content().is_some_and(|t| t == shown) {
302+ el.set_text_content(None);
303+ }
304+ });
305+ let _ = win.set_timeout_with_callback_and_timeout_and_arguments_0(clear.unchecked_ref(), NOTICE_MS);
306+}
307+
308+// ---------------------------------------------------------------------------
309+// Recording
310+// ---------------------------------------------------------------------------
311+
312+/// The cursor at the selection's head, as a Loro cursor so the embed lands there even when the
313+/// text before it changes while the take runs.
314+fn press_cursor(inner: &Inner) -> Option<Cursor> {
315+ let ed = inner.ed.upgrade()?;
316+ let e = ed.try_borrow().ok()?;
317+ let pos = e.sel.head()?;
318+ e.m.cursor(pos)
319+}
320+
321+/// Continues the take `session` with a new part, from its continue button. Refused while a
322+/// recording runs.
323+fn continue_take(inner: Rc<Inner>, session: String) {
324+ if inner.rec.borrow().is_none() && !inner.starting.replace(true) {
325+ spawn_local(start(inner, Start::Continue(session)));
326+ }
327+}
328+
329+/// The take of the continue button under a mouse event, if the event is on one.
330+fn continue_target(ev: &MouseEvent) -> Option<String> {
331+ let el: Element = ev.target()?.dyn_into().ok()?;
332+ let button = el.closest(".note-take-continue").ok()??;
333+ let span = button.closest("[data-take]").ok()??;
334+ span.get_attribute("data-take")
335+}
336+
337+/// Opens the microphone and the recorder, then starts the socket task that sends the take.
338+/// A failure shows a notice and leaves nothing running.
339+async fn start(inner: Rc<Inner>, how: Start) {
340+ let rec = open_take(&inner, how).await;
341+ inner.starting.set(false);
342+ match rec {
343+ Ok(rec) => {
344+ let take = rec.take.clone();
345+ *inner.rec.borrow_mut() = Some(rec);
346+ set_ui(&inner, true);
347+ spawn_local(link(inner.clone(), take));
348+ // The page may have started leaving while the microphone was being opened.
349+ if inner.detached.get() {
350+ stop_current(&inner);
351+ }
352+ }
353+ Err(key) => notice(key),
354+ }
355+}
356+
357+/// Opens the microphone and the recorder for `how`. A failure stops the microphone.
358+async fn open_take(inner: &Rc<Inner>, how: Start) -> Result<Recording, &'static str> {
359+ let stream = request_mic().await.map_err(|_| "micDenied")?;
360+ if !MediaRecorder::is_type_supported(MIME) {
361+ stop_tracks(&stream);
362+ return Err("mediaFailed");
363+ }
364+ let name = format!("recording-{}.weba", stamp());
365+ begin(inner, stream.clone(), how, name).map_err(|_| {
366+ stop_tracks(&stream);
367+ "mediaFailed"
368+ })
369+}
370+
371+async fn request_mic() -> Result<MediaStream, JsValue> {
372+ let devices = web_sys::window().ok_or("no window")?.navigator().media_devices()?;
373+ let constraints = MediaStreamConstraints::new();
374+ constraints.set_audio(&JsValue::TRUE);
375+ let promise = devices.get_user_media_with_constraints(&constraints)?;
376+ JsFuture::from(promise).await?.dyn_into()
377+}
378+
379+/// Builds the recorder with its handlers and starts it with one chunk a second. Each chunk is
380+/// kept in the take and queued for the socket task.
381+fn begin(inner: &Rc<Inner>, stream: MediaStream, how: Start, name: String) -> Result<Recording, JsValue> {
382+ let opts = MediaRecorderOptions::new();
383+ opts.set_mime_type(MIME);
384+ let recorder = MediaRecorder::new_with_media_stream_and_media_recorder_options(&stream, &opts)?;
385+
386+ let (session, at, fresh) = match how {
387+ Start::New(at) => (None, at, true),
388+ Start::Continue(session) => (Some(session), None, false),
389+ };
390+ // A tab close while the take is open asks first; the guard goes when the take is concluded.
391+ let unload = Closure::<dyn FnMut(Event)>::new(|ev: Event| {
392+ ev.prevent_default();
393+ if let Some(e) = ev.dyn_ref::<BeforeUnloadEvent>() {
394+ e.set_return_value("");
395+ }
396+ });
397+ let take = Rc::new(Take {
398+ session: RefCell::new(session),
399+ part: Cell::new(None),
400+ fresh,
401+ placed: Cell::new(false),
402+ at,
403+ name,
404+ mime: recorder.mime_type(),
405+ chunks: js_sys::Array::new(),
406+ queue: RefCell::default(),
407+ sent: Cell::new(0),
408+ ended: Cell::new(false),
409+ failed: Cell::new(false),
410+ unload,
411+ });
412+ let sink = take.clone();
413+ let on_data = Closure::<dyn FnMut(BlobEvent)>::new(move |ev: BlobEvent| {
414+ if let Some(blob) = ev.data().filter(|b| b.size() > 0.0) {
415+ let raw: &JsValue = blob.as_ref();
416+ sink.chunks.push(raw);
417+ sink.queue.borrow_mut().push_back(blob);
418+ }
419+ });
420+ recorder.set_ondataavailable(Some(on_data.as_ref().unchecked_ref()));
421+
422+ // Strong, so the take is still finished when the page leaves. `on_stopped` moves the
423+ // recording, and this closure with it, out of `inner`, which breaks the cycle.
424+ let held = inner.clone();
425+ let on_stop = Closure::<dyn FnMut()>::new(move || on_stopped(&held));
426+ recorder.set_onstop(Some(on_stop.as_ref().unchecked_ref()));
427+
428+ recorder.start_with_time_slice(1000)?;
429+ let win = web_sys::window().ok_or("no window")?;
430+ win.add_event_listener_with_callback("beforeunload", take.unload.as_ref().unchecked_ref())?;
431+
432+ let started = js_sys::Date::now();
433+ let time = inner.ui.borrow().as_ref().map(|(_, t)| t.clone());
434+ let ticker = Closure::<dyn FnMut()>::new(move || {
435+ if let Some(t) = &time {
436+ t.set_text_content(Some(&clock(js_sys::Date::now() - started)));
437+ }
438+ });
439+ let tick = win.set_interval_with_callback_and_timeout_and_arguments_0(ticker.as_ref().unchecked_ref(), 1000)?;
440+
441+ Ok(Recording { recorder, stream, take, tick: Some(tick), _on_data: on_data, _on_stop: on_stop, _ticker: ticker })
442+}
443+
444+/// Asks the recorder to stop. The rest happens in `on_stopped`, once its data is in.
445+fn stop_current(inner: &Inner) {
446+ let recorder = inner.rec.borrow().as_ref().map(|r| r.recorder.clone());
447+ if let Some(recorder) = recorder {
448+ let _ = recorder.stop();
449+ }
450+}
451+
452+/// The recorder stopped: releases the microphone and the timers, and marks the take ended so
453+/// the socket task can send `end` once every chunk is acked. Runs inside the recorder's stop
454+/// event, so the recording is dropped in a later task, not here.
455+fn on_stopped(inner: &Rc<Inner>) {
456+ let taken = inner.rec.borrow_mut().take();
457+ let Some(rec) = taken else { return };
458+ release(&rec);
459+ rec.take.ended.set(true);
460+ set_ui(inner, false);
461+ spawn_local(async move { drop(rec) });
462+}
463+
464+/// Stops the timers and the handlers of a finished recording, and its tracks. The beforeunload
465+/// guard stays until the take is concluded.
466+fn release(rec: &Recording) {
467+ if let Some(win) = web_sys::window()
468+ && let Some(id) = rec.tick
469+ {
470+ win.clear_interval_with_handle(id);
471+ }
472+ rec.recorder.set_ondataavailable(None);
473+ rec.recorder.set_onstop(None);
474+ stop_tracks(&rec.stream);
475+}
476+
477+fn stop_tracks(stream: &MediaStream) {
478+ for track in stream.get_tracks().iter() {
479+ if let Ok(track) = track.dyn_into::<MediaStreamTrack>() {
480+ track.stop();
481+ }
482+ }
483+}
484+
485+/// How one socket of a take ended.
486+enum Link {
487+ /// The server answered `done`: the part is stored.
488+ Done,
489+ /// The socket closed, or went quiet.
490+ Lost,
491+ /// The server answered `reject`.
492+ Rejected,
493+}
494+
495+/// The socket task of a take. Connects, sends each chunk once the last one is acked, and
496+/// reconnects for as long as the tab lives. A reject gives up. Once every chunk is acked after
497+/// the stop, the take is concluded.
498+async fn link(inner: Rc<Inner>, take: Rc<Take>) {
499+ loop {
500+ match connection(&inner, &take).await {
501+ Link::Done => break,
502+ Link::Lost => sleep(RETRY_MS).await,
503+ Link::Rejected => {
504+ take.failed.set(true);
505+ // Nothing more is sent, so the recording is stopped and its chunks gathered.
506+ stop_current(&inner);
507+ while !take.ended.get() {
508+ sleep(200).await;
509+ }
510+ break;
511+ }
512+ }
513+ }
514+ conclude(inner, take).await;
515+}
516+
517+/// The URL of the take's next socket. A new take asks for its note until the server names it,
518+/// then reconnects to its part. A continuation asks for its take until the server gives a part.
519+fn url(inner: &Inner, take: &Take) -> Option<String> {
520+ let session = take.session.borrow().clone();
521+ let query = match (session, take.part.get()) {
522+ (Some(s), Some(part)) => format!("session={}&part={part}", enc(&s)),
523+ (Some(s), None) => format!("session={}", enc(&s)),
524+ (None, _) => format!("note={}", enc(&inner.note_id)),
525+ };
526+ let loc = web_sys::window()?.location();
527+ let proto = if loc.protocol().unwrap_or_default() == "https:" { "wss" } else { "ws" };
528+ Some(format!("{proto}://{}/media/live?{query}", loc.host().unwrap_or_default()))
529+}
530+
531+/// One socket of a take: it attaches to the part, then sends the queued chunks one at a time,
532+/// each once the one before is acked. A stop sends `end` once the queue is empty.
533+async fn connection(inner: &Inner, take: &Take) -> Link {
534+ let Some(socket) = url(inner, take).and_then(|u| Socket::open(&u)) else { return Link::Lost };
535+ let mut ready = false;
536+ let mut waiting = false;
537+ let mut end_sent = false;
538+ let mut last = js_sys::Date::now();
539+ loop {
540+ if ready && !waiting {
541+ let next = take.queue.borrow().front().cloned();
542+ match next {
543+ Some(blob) => {
544+ if socket.ws.send_with_blob(&blob).is_err() {
545+ return Link::Lost;
546+ }
547+ waiting = true;
548+ }
549+ None if take.ended.get() && !end_sent => {
550+ let _ = socket.ws.send_with_str("end");
551+ end_sent = true;
552+ }
553+ None => {}
554+ }
555+ }
556+ let frame = socket.inbox.borrow_mut().pop_front();
557+ let text = match frame {
558+ Some(Frame::Text(text)) => text,
559+ Some(Frame::Closed) => return Link::Lost,
560+ None => {
561+ if (!ready || waiting) && js_sys::Date::now() - last > STALL_MS {
562+ return Link::Lost;
563+ }
564+ sleep(100).await;
565+ continue;
566+ }
567+ };
568+ last = js_sys::Date::now();
569+ let fields: Vec<&str> = text.split(' ').collect();
570+ match fields.as_slice() {
571+ ["ready", session, part, bytes] => {
572+ let (Ok(part), Ok(bytes)) = (part.parse::<u32>(), bytes.parse::<u64>()) else { return Link::Lost };
573+ take.attach(session, part, bytes);
574+ ready = true;
575+ }
576+ ["ack", bytes] if waiting => {
577+ let Ok(bytes) = bytes.parse::<u64>() else { return Link::Lost };
578+ take.acked(bytes);
579+ waiting = false;
580+ if take.fresh && !take.placed.get() {
581+ place(inner, take);
582+ }
583+ }
584+ ["done"] => return Link::Done,
585+ ["reject"] => return Link::Rejected,
586+ _ => {}
587+ }
588+ }
589+}
590+
591+impl Take {
592+ /// The server's `ready`: the take's id and the part, and what the part already holds. Those
593+ /// bytes are not sent again.
594+ fn attach(&self, session: &str, part: u32, bytes: u64) {
595+ *self.session.borrow_mut() = Some(session.to_owned());
596+ self.part.set(Some(part));
597+ let mut queue = self.queue.borrow_mut();
598+ let mut skip = bytes.saturating_sub(self.sent.get());
599+ while skip > 0 {
600+ let Some(front) = queue.front() else { break };
601+ let size = front.size() as u64;
602+ if size <= skip {
603+ skip -= size;
604+ queue.pop_front();
605+ } else {
606+ if let Ok(rest) = front.slice_with_f64_and_f64(skip as f64, size as f64) {
607+ queue[0] = rest;
608+ }
609+ break;
610+ }
611+ }
612+ self.sent.set(bytes);
613+ }
614+
615+ /// A chunk is stored: it leaves the queue, and `bytes` is the new offset.
616+ fn acked(&self, bytes: u64) {
617+ self.queue.borrow_mut().pop_front();
618+ self.sent.set(bytes);
619+ }
620+}
621+
622+/// Places a new take's URL at its cursor. False while the editor is busy or gone or leaving, or
623+/// before the server has named the take.
624+fn place(inner: &Inner, take: &Take) -> bool {
625+ if inner.detached.get() {
626+ return false;
627+ }
628+ let (Some(ed), Some(session)) = (inner.ed.upgrade(), take.session.borrow().clone()) else { return false };
629+ let url = format!("/media/rec/{session}");
630+ let done = insert_at(&ed, take.at.as_ref(), embed(&url, &take.name));
631+ take.placed.set(done);
632+ done
633+}
634+
635+/// Runs once the socket task is done with the take. A rejected take is saved locally, and so is
636+/// a new take whose URL could not be placed (the editor went, or the server never named the
637+/// take), so its recording is not lost. Then the beforeunload guard goes.
638+async fn conclude(inner: Rc<Inner>, take: Rc<Take>) {
639+ if !take.failed.get() && take.fresh && !take.placed.get() {
640+ // The first chunk may have come while the editor was busy.
641+ for _ in 0..5 {
642+ if place(&inner, &take) {
643+ break;
644+ }
645+ sleep(200).await;
646+ }
647+ }
648+ if take.failed.get() {
649+ notice("mediaFailed");
650+ }
651+ if take.failed.get() || (take.fresh && !take.placed.get()) {
652+ if let Some(blob) = take_blob(&take) {
653+ save_locally(&blob, &take.name);
654+ }
655+ }
656+ if let Some(win) = web_sys::window() {
657+ let _ = win.remove_event_listener_with_callback("beforeunload", take.unload.as_ref().unchecked_ref());
658+ }
659+}
660+
661+/// The whole part as one blob. None when there is nothing to save.
662+fn take_blob(take: &Take) -> Option<Blob> {
663+ if take.chunks.length() == 0 {
664+ return None;
665+ }
666+ let bag = BlobPropertyBag::new();
667+ bag.set_type(&take.mime);
668+ let parts: &JsValue = take.chunks.as_ref();
669+ Blob::new_with_blob_sequence_and_options(parts, &bag).ok()
670+}
671+
672+/// A take that could not be uploaded goes to the browser's downloads rather than being lost.
673+fn save_locally(blob: &Blob, name: &str) {
674+ let Some(doc) = web_sys::window().and_then(|w| w.document()) else { return };
675+ let Ok(url) = web_sys::Url::create_object_url_with_blob(blob) else { return };
676+ let link: HtmlElement = h(&doc, "a", &[("href", &url), ("download", name)], None).unchecked_into();
677+ link.click();
678+}
679+
680+/// What a socket hears from the server or the browser.
681+enum Frame {
682+ Text(String),
683+ Closed,
684+}
685+
686+/// A WebSocket with its handlers, which push what arrives into `inbox`. Dropping it clears the
687+/// handlers and closes the socket, so an abandoned socket says nothing more.
688+struct Socket {
689+ ws: WebSocket,
690+ inbox: Rc<RefCell<VecDeque<Frame>>>,
691+ _on_message: Closure<dyn FnMut(MessageEvent)>,
692+ _on_close: Closure<dyn FnMut()>,
693+}
694+
695+impl Socket {
696+ fn open(url: &str) -> Option<Socket> {
697+ let ws = WebSocket::new(url).ok()?;
698+ ws.set_binary_type(BinaryType::Arraybuffer);
699+ let inbox: Rc<RefCell<VecDeque<Frame>>> = Rc::default();
700+ let sink = inbox.clone();
701+ let on_message = Closure::<dyn FnMut(MessageEvent)>::new(move |ev: MessageEvent| {
702+ if let Some(text) = ev.data().as_string() {
703+ sink.borrow_mut().push_back(Frame::Text(text));
704+ }
705+ });
706+ let sink = inbox.clone();
707+ let on_close = Closure::<dyn FnMut()>::new(move || sink.borrow_mut().push_back(Frame::Closed));
708+ ws.set_onmessage(Some(on_message.as_ref().unchecked_ref()));
709+ ws.set_onerror(Some(on_close.as_ref().unchecked_ref()));
710+ ws.set_onclose(Some(on_close.as_ref().unchecked_ref()));
711+ Some(Socket { ws, inbox, _on_message: on_message, _on_close: on_close })
712+ }
713+}
714+
715+impl Drop for Socket {
716+ fn drop(&mut self) {
717+ self.ws.set_onmessage(None);
718+ self.ws.set_onerror(None);
719+ self.ws.set_onclose(None);
720+ let _ = self.ws.close();
721+ }
722+}
723+
724+/// Waits `ms` milliseconds.
725+async fn sleep(ms: i32) {
726+ let Some(win) = web_sys::window() else { return };
727+ let wait = js_sys::Promise::new(&mut |resolve, _reject| {
728+ let _ = win.set_timeout_with_callback_and_timeout_and_arguments_0(&resolve, ms);
729+ });
730+ let _ = JsFuture::from(wait).await;
731+}
732+
733+/// Percent-encodes a query value.
734+fn enc(s: &str) -> String {
735+ String::from(js_sys::encode_uri_component(s))
736+}
737+
738+/// Pressed state, label and the m:ss readout of the record button.
739+fn set_ui(inner: &Inner, on: bool) {
740+ let bound = inner.ui.borrow().clone();
741+ let Some((btn, time)) = bound else { return };
742+ let value = if on { "true" } else { "false" };
743+ let _ = btn.set_attribute("aria-pressed", value);
744+ let _ = btn.set_attribute("data-recording", value);
745+ let label = btn.owner_document().map(|d| Strings::load(&d).get(if on { "stopRecording" } else { "recordAudio" })).unwrap_or_default();
746+ let _ = btn.set_attribute("aria-label", &label);
747+ if let Ok(Some(tip)) = btn.query_selector(".tip-label") {
748+ tip.set_text_content(Some(&label));
749+ }
750+ if on {
751+ let _ = time.remove_attribute("hidden");
752+ time.set_text_content(Some("0:00"));
753+ } else {
754+ let _ = time.set_attribute("hidden", "");
755+ time.set_text_content(None);
756+ }
757+}
758+
759+/// `m:ss` for a span in milliseconds.
760+fn clock(ms: f64) -> String {
761+ let s = (ms / 1000.0).max(0.0) as u64;
762+ format!("{}:{:02}", s / 60, s % 60)
763+}
764+
765+/// Local time as `YYYYMMDD-HHMMSS`, for recording names.
766+fn stamp() -> String {
767+ let d = js_sys::Date::new_0();
768+ format!(
769+ "{:04}{:02}{:02}-{:02}{:02}{:02}",
770+ d.get_full_year(),
771+ d.get_month() + 1,
772+ d.get_date(),
773+ d.get_hours(),
774+ d.get_minutes(),
775+ d.get_seconds()
776+ )
777+}
crates/editor/src/ui/mod.rsadded+170 -0
@@ -0,0 +1,170 @@
1+//! Editor chrome: toolbar, floating menus, note links, clipboard and presence.
2+//! Each module exposes `install`, called once from `lib.rs` after the editor exists.
3+
4+pub mod clipboard;
5+pub mod codeblock;
6+pub mod floating;
7+pub mod media;
8+pub mod notelinks;
9+pub mod presence;
10+pub mod toolbar;
11+
12+use std::cell::RefCell;
13+use std::rc::Rc;
14+
15+use wasm_bindgen::prelude::*;
16+use web_sys::{AddEventListenerOptions, Document, Element, EventTarget, HtmlElement};
17+
18+use crate::core::pos::Pos;
19+use crate::editor::Editor;
20+use crate::strings::Strings;
21+
22+pub type Ed = Rc<RefCell<Editor>>;
23+
24+/// What every `install` gets.
25+pub struct Ctx {
26+ pub document: Document,
27+ /// `#editor`, the element around the editable root.
28+ pub mount: Element,
29+ pub note_id: String,
30+ pub strings: Rc<Strings>,
31+ /// Carries the abort signal that removes every listener on `note:detach`.
32+ pub opts: AddEventListenerOptions,
33+}
34+
35+/// Adds an event listener (removed on `note:detach`) that runs `f` with the editor
36+/// borrowed mutably; skipped when the editor is already busy.
37+pub fn listen<E: JsCast + 'static>(
38+ target: &EventTarget,
39+ name: &str,
40+ cx: &Ctx,
41+ ed: &Ed,
42+ mut f: impl FnMut(&mut Editor, &E) + 'static,
43+) {
44+ let weak = Rc::downgrade(ed);
45+ let cb = Closure::<dyn FnMut(web_sys::Event)>::new(move |ev: web_sys::Event| {
46+ let Some(ed) = weak.upgrade() else { return };
47+ let Ok(mut ed) = ed.try_borrow_mut() else { return };
48+ if let Ok(ev) = ev.dyn_into::<E>() {
49+ f(&mut ed, &ev);
50+ }
51+ });
52+ let _ = target.add_event_listener_with_callback_and_add_event_listener_options(name, cb.as_ref().unchecked_ref(), &cx.opts);
53+ cb.forget();
54+}
55+
56+/// Name of the DOM event (on the editable root) that opens the link popover.
57+pub const LINK_EVENT: &str = "editor:link";
58+
59+/// Asks the floating UI to open the link popover for the current selection.
60+pub fn request_link(root: &HtmlElement) {
61+ if let Ok(ev) = web_sys::CustomEvent::new(LINK_EVENT) {
62+ let _ = root.dispatch_event(&ev);
63+ }
64+}
65+
66+/// Creates an element with attributes and text. Only pass trusted literals as text.
67+pub fn h(document: &Document, tag: &str, attrs: &[(&str, &str)], text: Option<&str>) -> HtmlElement {
68+ let el: HtmlElement = document.create_element(tag).unwrap().unchecked_into();
69+ for (k, v) in attrs {
70+ let _ = el.set_attribute(k, v);
71+ }
72+ if let Some(t) = text {
73+ el.set_text_content(Some(t));
74+ }
75+ el
76+}
77+
78+pub fn is_mac() -> bool {
79+ web_sys::window()
80+ .and_then(|w| w.navigator().platform().ok())
81+ .is_some_and(|p| p.contains("Mac") || p.contains("iP"))
82+}
83+
84+/// Modifier labels for keycaps: (Mod, Shift, Alt).
85+pub fn mod_keys() -> (&'static str, &'static str, &'static str) {
86+ if is_mac() { ("⌘", "⇧", "⌥") } else { ("Ctrl", "Shift", "Alt") }
87+}
88+
89+/// Mono keycap chips, e.g. `keycaps(doc, &["Ctrl", "K"])`. Decorative (aria-hidden).
90+pub fn keycaps(document: &Document, keys: &[&str]) -> HtmlElement {
91+ let wrap = h(document, "span", &[("class", "keycaps"), ("aria-hidden", "true")], None);
92+ for k in keys {
93+ let _ = wrap.append_child(&h(document, "kbd", &[("class", "keycap")], Some(k)));
94+ }
95+ wrap
96+}
97+
98+/// Tooltip shown on hover/focus of its parent button: label, keycaps, optional reason.
99+pub fn tooltip(document: &Document, label: &str, keys: &[&str], reason: Option<&str>) -> HtmlElement {
100+ let tip = h(document, "span", &[("class", "tip"), ("aria-hidden", "true"), ("role", "presentation")], None);
101+ let _ = tip.append_child(&h(document, "span", &[("class", "tip-label")], Some(label)));
102+ if !keys.is_empty() {
103+ let _ = tip.append_child(&keycaps(document, keys));
104+ }
105+ if let Some(r) = reason {
106+ let _ = tip.append_child(&h(document, "span", &[("class", "tip-reason")], Some(r)));
107+ }
108+ tip
109+}
110+
111+/// A viewport box.
112+#[derive(Clone, Copy, Debug, Default)]
113+pub struct Box {
114+ pub top: f64,
115+ pub bottom: f64,
116+ pub left: f64,
117+ pub right: f64,
118+}
119+
120+/// Viewport box of the caret at `p` (zero width), like PM's `coordsAtPos`.
121+pub fn coords_at(ed: &Editor, p: Pos) -> Option<Box> {
122+ let (node, off) = ed.view.pos_to_dom(&ed.m, p)?;
123+ let document = node.owner_document()?;
124+ let range = document.create_range().ok()?;
125+ range.set_start(&node, off).ok()?;
126+ range.set_end(&node, off).ok()?;
127+ let rects = range.get_client_rects()?;
128+ let r = match rects.get(0) {
129+ Some(r) => r,
130+ None => {
131+ // Empty block: use the block element's box.
132+ let el = ed.view.element(ed.m.at(p).index)?;
133+ el.get_bounding_client_rect()
134+ }
135+ };
136+ Some(Box { top: r.top(), bottom: r.bottom(), left: r.left(), right: r.left() })
137+}
138+
139+/// Box around the text between two positions (spans lines when needed).
140+pub fn range_box(ed: &Editor, from: Pos, to: Pos) -> Option<Box> {
141+ let a = coords_at(ed, from)?;
142+ let b = coords_at(ed, to)?;
143+ Some(Box { top: a.top.min(b.top), bottom: a.bottom.max(b.bottom), left: a.left.min(b.left), right: a.right.max(b.right) })
144+}
145+
146+const GAP: f64 = 8.0;
147+
148+/// Positions a fixed element next to a box, centred horizontally and clamped to the
149+/// viewport. `above` flips below when there is no room; below flips above at the bottom.
150+pub fn place_floating(el: &HtmlElement, b: Box, above: bool) {
151+ let w = web_sys::window().unwrap();
152+ let vw = w.inner_width().ok().and_then(|v| v.as_f64()).unwrap_or(0.0);
153+ let vh = w.inner_height().ok().and_then(|v| v.as_f64()).unwrap_or(0.0);
154+ let width = el.offset_width() as f64;
155+ let height = el.offset_height() as f64;
156+ let up = b.top - height - GAP;
157+ let down = b.bottom + GAP;
158+ let top = if above {
159+ if up >= GAP { up } else { down }
160+ } else if down + height <= vh - GAP {
161+ down
162+ } else {
163+ up
164+ };
165+ let center = (b.left + b.right) / 2.0;
166+ let left = (center - width / 2.0).max(GAP).min(vw - width - GAP);
167+ let st = el.style();
168+ let _ = st.set_property("top", &format!("{}px", top.max(GAP)));
169+ let _ = st.set_property("left", &format!("{}px", left.max(GAP)));
170+}
crates/editor/src/ui/notelinks.rsadded+606 -0
@@ -0,0 +1,606 @@
1+//! Note-to-note links. Typing "[[" opens a suggestion menu of note titles. Picking one
2+//! (or "Create note") replaces "[[query" with the title as a link mark whose href is
3+//! /notes/<id>. The menu reuses the slash menu's classes and keyboard model.
4+//! Port of web/src/noteLinks.ts.
5+
6+use std::cell::RefCell;
7+use std::rc::{Rc, Weak};
8+
9+use wasm_bindgen::prelude::*;
10+use wasm_bindgen::JsCast;
11+use wasm_bindgen_futures::{spawn_local, JsFuture};
12+use web_sys::{
13+ AbortController, AddEventListenerOptions, Element, Event, EventTarget, Headers, HtmlElement, KeyboardEvent, MouseEvent,
14+ RequestInit, Response, ScrollIntoViewOptions, ScrollLogicalPosition, UrlSearchParams,
15+};
16+
17+use super::{h, keycaps, place_floating, range_box, Ctx, Ed};
18+use crate::core::commands;
19+use crate::core::marks::{Link, Marks};
20+use crate::core::pos::{Pos, Selection};
21+use crate::editor::Editor;
22+use crate::strings::Strings;
23+use note_model::flat::Kind;
24+
25+const SEARCH_DEBOUNCE_MS: i32 = 120;
26+
27+#[derive(Clone, Debug)]
28+struct NoteHit {
29+ id: String,
30+ title: String,
31+}
32+
33+#[derive(Clone, Debug)]
34+enum Item {
35+ Note(NoteHit),
36+ Create(String),
37+}
38+
39+/// "[[" trigger: `from` is the position of the first bracket, `query` the text after it.
40+#[derive(Clone, Debug, PartialEq)]
41+struct Trigger {
42+ from: Pos,
43+ query: String,
44+}
45+
46+#[derive(Default)]
47+struct St {
48+ active: Option<Trigger>,
49+ dismissed: Option<Pos>,
50+ results: Vec<NoteHit>,
51+ loaded: bool,
52+ items: Vec<Item>,
53+ index: usize,
54+ busy: bool,
55+ timer: Option<i32>,
56+ controller: Option<AbortController>,
57+}
58+
59+struct Menu {
60+ document: web_sys::Document,
61+ root: HtmlElement,
62+ menu: HtmlElement,
63+ list: HtmlElement,
64+ strings: Rc<Strings>,
65+ current_id: String,
66+ ed: Weak<RefCell<Editor>>,
67+ st: RefCell<St>,
68+}
69+
70+pub fn is_note_href(href: &str) -> bool {
71+ href.starts_with("/notes/")
72+}
73+
74+pub fn install(ed: &Ed, cx: &Ctx) {
75+ let root = ed.borrow().view.root.clone();
76+ let me = Menu::new(ed, cx, root.clone());
77+ if let Some(body) = cx.document.body() {
78+ let _ = body.append_child(&me.menu);
79+ }
80+
81+ // Keys go to the menu before the editor's own bubble-phase handler sees them.
82+ let target: &EventTarget = root.as_ref();
83+ let (weak, m) = (Rc::downgrade(ed), me.clone());
84+ on(
85+ target,
86+ "keydown",
87+ &options(cx, true, false),
88+ Closure::new(move |ev: Event| {
89+ let Ok(ev) = ev.dyn_into::<KeyboardEvent>() else { return };
90+ let Some(ed) = weak.upgrade() else { return };
91+ let Ok(mut ed) = ed.try_borrow_mut() else { return };
92+ if m.on_key(&mut ed, &ev.key()) {
93+ ev.prevent_default();
94+ ev.stop_immediate_propagation();
95+ }
96+ }),
97+ );
98+
99+ // Ctrl/Cmd+click on a note link opens the note in this tab.
100+ on(
101+ target,
102+ "click",
103+ &cx.opts,
104+ Closure::new(|ev: Event| {
105+ let Ok(ev) = ev.dyn_into::<MouseEvent>() else { return };
106+ if !(ev.ctrl_key() || ev.meta_key()) {
107+ return;
108+ }
109+ let anchor = ev
110+ .target()
111+ .and_then(|t| t.dyn_into::<Element>().ok())
112+ .and_then(|el| el.closest("a").ok().flatten());
113+ let Some(href) = anchor.and_then(|a| a.get_attribute("href")) else { return };
114+ if !is_note_href(&href) {
115+ return;
116+ }
117+ ev.prevent_default();
118+ if let Some(win) = web_sys::window() {
119+ let _ = win.location().assign(&href);
120+ }
121+ }),
122+ );
123+
124+ // Keep focus in the editor while clicking menu items.
125+ let menu_target: &EventTarget = me.menu.as_ref();
126+ on(menu_target, "mousedown", &cx.opts, Closure::new(|ev: Event| ev.prevent_default()));
127+
128+ // Row hover and click are delegated to the list (rows are rebuilt on every render).
129+ let list_target: &EventTarget = me.list.as_ref();
130+ let m = me.clone();
131+ on(
132+ list_target,
133+ "mouseover",
134+ &cx.opts,
135+ Closure::new(move |ev: Event| {
136+ if let Some(i) = row_of(&ev)
137+ && m.st.borrow().index != i
138+ {
139+ m.set_index(i);
140+ }
141+ }),
142+ );
143+ let (weak, m) = (Rc::downgrade(ed), me.clone());
144+ on(
145+ list_target,
146+ "click",
147+ &cx.opts,
148+ Closure::new(move |ev: Event| {
149+ let Some(i) = row_of(&ev) else { return };
150+ let Some(ed) = weak.upgrade() else { return };
151+ let Ok(mut ed) = ed.try_borrow_mut() else { return };
152+ let item = m.st.borrow().items.get(i).cloned();
153+ if let Some(item) = item {
154+ m.pick(&mut ed, item);
155+ }
156+ }),
157+ );
158+
159+ // Keep the menu anchored while the page scrolls or resizes.
160+ if let Some(win) = web_sys::window() {
161+ let win_target: &EventTarget = win.as_ref();
162+ on(win_target, "scroll", &options(cx, true, true), reposition(ed, &me));
163+ on(win_target, "resize", &cx.opts, reposition(ed, &me));
164+ }
165+
166+ let m = me.clone();
167+ ed.borrow_mut().listeners.push(Box::new(move |ed: &Editor, _changed: bool| m.sync(ed)));
168+}
169+
170+/// A listener that re-places the open menu from the editor's current caret.
171+fn reposition(ed: &Ed, me: &Rc<Menu>) -> Closure<dyn FnMut(Event)> {
172+ let (weak, m) = (Rc::downgrade(ed), me.clone());
173+ Closure::new(move |_ev: Event| {
174+ if let Some(ed) = weak.upgrade()
175+ && let Ok(ed) = ed.try_borrow()
176+ {
177+ m.place(&ed);
178+ }
179+ })
180+}
181+
182+/// Listener options that also carry the detach signal of the UI context. Never mutate
183+/// `cx.opts` itself: web-sys clones share one JS object.
184+fn options(cx: &Ctx, capture: bool, passive: bool) -> AddEventListenerOptions {
185+ let o = AddEventListenerOptions::new();
186+ o.set_capture(capture);
187+ o.set_passive(passive);
188+ if let Some(sig) = cx.opts.get_signal() {
189+ o.set_signal(&sig);
190+ }
191+ o
192+}
193+
194+/// Adds a listener and forgets its closure; the `signal` in `opts` removes it on detach.
195+fn on(target: &EventTarget, name: &str, opts: &AddEventListenerOptions, cb: Closure<dyn FnMut(Event)>) {
196+ let _ = target.add_event_listener_with_callback_and_add_event_listener_options(name, cb.as_ref().unchecked_ref(), opts);
197+ cb.forget();
198+}
199+
200+/// The menu row index for an event on (or inside) a row, from its `note-opt-<i>` id.
201+fn row_of(ev: &Event) -> Option<usize> {
202+ let el = ev.target()?.dyn_into::<Element>().ok()?.closest(".slash-item").ok().flatten()?;
203+ el.id().strip_prefix("note-opt-")?.parse().ok()
204+}
205+
206+/// The "[[query" right before the caret, when the caret is in a textblock outside code.
207+fn trigger_at(ed: &Editor) -> Option<Trigger> {
208+ let p = ed.sel.cursor()?;
209+ let block = ed.m.at(p);
210+ let kind = block.kind();
211+ if !kind.is_text() || kind == Kind::Code {
212+ return None;
213+ }
214+ let cx = ed.cx();
215+ if commands::pending_marks(&cx).code {
216+ return None;
217+ }
218+ // A note query is short; look back a bounded stretch only, never past the block start.
219+ let chars: Vec<char> = ed.m.plain(p.saturating_sub(512).max(block.start), p).chars().collect();
220+ // A closing "]]", a stray bracket, a newline or an inline node ends the match.
221+ let mut j = chars.len();
222+ while j > 0 && !matches!(chars[j - 1], '[' | ']' | '\n' | '\u{FFFC}') {
223+ j -= 1;
224+ }
225+ if j < 2 || chars[j - 1] != '[' || chars[j - 2] != '[' {
226+ return None;
227+ }
228+ let len16: usize = chars[j - 2..].iter().map(|c| c.len_utf16()).sum();
229+ Some(Trigger { from: p - len16, query: chars[j..].iter().collect() })
230+}
231+
232+/// The text of [from, to) as it reads now.
233+fn text_between(ed: &Editor, from: &Pos, to: &Pos) -> String {
234+ ed.m.plain(*from, (*to).max(*from))
235+}
236+
237+/// Replaces [from, to) with the link text, a plain space, and the caret after it. One change.
238+fn insert_link(ed: &mut Editor, from: &Pos, to: &Pos, text: &str, id: &str) {
239+ let link = Marks { link: Some(Link { href: format!("/notes/{id}"), title: None }), ..Marks::default() };
240+ let (from, to) = (*from, *to);
241+ let ran = ed.run(|cx| {
242+ if cx.m.at(from).index != cx.m.at(to).index || from > to {
243+ return false;
244+ }
245+ cx.m.delete(from, to);
246+ let end = cx.m.insert(from, text, &link);
247+ let after = cx.m.insert(end, " ", &Marks::none());
248+ cx.sel = Selection::caret(after);
249+ cx.stored = Some(Marks::none());
250+ true
251+ });
252+ if ran {
253+ if let Some(el) = ed.view.element(ed.m.at(from).index) {
254+ let opts = ScrollIntoViewOptions::new();
255+ opts.set_block(ScrollLogicalPosition::Nearest);
256+ el.scroll_into_view_with_scroll_into_view_options(&opts);
257+ }
258+ let _ = ed.view.root.focus();
259+ }
260+}
261+
262+fn build_items(results: &[NoteHit], query: &str) -> Vec<Item> {
263+ let mut items: Vec<Item> = results.iter().cloned().map(Item::Note).collect();
264+ let q = query.trim();
265+ let exact = results.iter().any(|hit| hit.title.trim().to_lowercase() == q.to_lowercase());
266+ if !q.is_empty() && !exact {
267+ items.push(Item::Create(q.to_owned()));
268+ }
269+ items
270+}
271+
272+fn parse_hits(data: &JsValue) -> Vec<NoteHit> {
273+ if !js_sys::Array::is_array(data) {
274+ return Vec::new();
275+ }
276+ data.clone()
277+ .unchecked_into::<js_sys::Array>()
278+ .iter()
279+ .filter_map(|x| {
280+ let id = js_sys::Reflect::get(&x, &"id".into()).ok()?.as_string()?;
281+ let title = js_sys::Reflect::get(&x, &"title".into()).ok()?.as_string()?;
282+ Some(NoteHit { id, title })
283+ })
284+ .collect()
285+}
286+
287+async fn fetch_titles(ctrl: &AbortController, query: &str) -> Result<Vec<NoteHit>, JsValue> {
288+ let init = RequestInit::new();
289+ init.set_signal(Some(&ctrl.signal()));
290+ let headers = Headers::new()?;
291+ headers.set("accept", "application/json")?;
292+ init.set_headers(&headers);
293+ let url = format!("/notes/titles.json?q={}", String::from(js_sys::encode_uri_component(query)));
294+ let window = web_sys::window().ok_or("no window")?;
295+ let resp: Response = JsFuture::from(window.fetch_with_str_and_init(&url, &init)).await?.dyn_into()?;
296+ if !resp.ok() {
297+ return Err(format!("titles {}", resp.status()).into());
298+ }
299+ let data = JsFuture::from(resp.json()?).await?;
300+ Ok(parse_hits(&data))
301+}
302+
303+async fn create_note(title: &str) -> Result<String, JsValue> {
304+ let params = UrlSearchParams::new()?;
305+ params.append("title", title);
306+ let init = RequestInit::new();
307+ init.set_method("POST");
308+ init.set_body(&params);
309+ let window = web_sys::window().ok_or("no window")?;
310+ let resp: Response = JsFuture::from(window.fetch_with_str_and_init("/notes/quick", &init)).await?.dyn_into()?;
311+ if !resp.ok() {
312+ return Err(format!("quick {}", resp.status()).into());
313+ }
314+ let text = JsFuture::from(resp.text()?).await?.as_string().unwrap_or_default();
315+ let id = text.trim().to_owned();
316+ if id.is_empty() {
317+ return Err("empty note id".into());
318+ }
319+ Ok(id)
320+}
321+
322+impl Menu {
323+ fn new(ed: &Ed, cx: &Ctx, root: HtmlElement) -> Rc<Self> {
324+ let doc = &cx.document;
325+ let menu = h(doc, "div", &[("class", "popover slash-menu note-menu"), ("role", "presentation")], None);
326+ menu.set_hidden(true);
327+ let label = cx.strings.get("noteMenu");
328+ let list = h(doc, "div", &[("class", "slash-list"), ("role", "listbox"), ("aria-label", label.as_str())], None);
329+ let footer = h(doc, "div", &[("class", "slash-footer"), ("aria-hidden", "true")], None);
330+ let (navigate, insert, close) = (cx.strings.get("navigate"), cx.strings.get("insert"), cx.strings.get("close"));
331+ let _ = footer.append_child(&keycaps(doc, &["↑", "↓"]));
332+ let _ = footer.append_child(&doc.create_text_node(&format!(" {navigate} ")));
333+ let _ = footer.append_child(&keycaps(doc, &["↵"]));
334+ let _ = footer.append_child(&doc.create_text_node(&format!(" {insert} ")));
335+ let _ = footer.append_child(&keycaps(doc, &["Esc"]));
336+ let _ = footer.append_child(&doc.create_text_node(&format!(" {close}")));
337+ let _ = menu.append_child(&list);
338+ let _ = menu.append_child(&footer);
339+ Rc::new(Menu {
340+ document: doc.clone(),
341+ root,
342+ menu,
343+ list,
344+ strings: cx.strings.clone(),
345+ current_id: cx.note_id.clone(),
346+ ed: Rc::downgrade(ed),
347+ st: RefCell::default(),
348+ })
349+ }
350+
351+ fn item_text(&self, item: &Item) -> String {
352+ match item {
353+ Item::Create(title) => title.clone(),
354+ Item::Note(hit) => {
355+ let t = hit.title.trim();
356+ if t.is_empty() { self.strings.get("untitled") } else { t.to_owned() }
357+ }
358+ }
359+ }
360+
361+ fn item_label(&self, item: &Item) -> String {
362+ match item {
363+ Item::Create(title) => self.strings.get("createNote").replace("{q}", title),
364+ Item::Note(_) => self.item_text(item),
365+ }
366+ }
367+
368+ fn abort(&self) {
369+ let mut st = self.st.borrow_mut();
370+ if let Some(id) = st.timer.take()
371+ && let Some(win) = web_sys::window()
372+ {
373+ win.clear_timeout_with_handle(id);
374+ }
375+ if let Some(ctrl) = st.controller.take() {
376+ ctrl.abort();
377+ }
378+ }
379+
380+ fn close(&self) {
381+ self.abort();
382+ {
383+ let mut st = self.st.borrow_mut();
384+ st.active = None;
385+ st.items.clear();
386+ st.results.clear();
387+ st.loaded = false;
388+ st.index = 0;
389+ }
390+ self.menu.set_hidden(true);
391+ let _ = self.root.remove_attribute("aria-activedescendant");
392+ }
393+
394+ fn schedule_search(self: &Rc<Self>, query: String) {
395+ self.abort();
396+ self.st.borrow_mut().loaded = false;
397+ let me = self.clone();
398+ let cb = Closure::once_into_js(move || {
399+ me.st.borrow_mut().timer = None;
400+ let search = me.clone();
401+ spawn_local(async move { search.search(query).await });
402+ });
403+ if let Some(win) = web_sys::window()
404+ && let Ok(id) = win.set_timeout_with_callback_and_timeout_and_arguments_0(cb.unchecked_ref(), SEARCH_DEBOUNCE_MS)
405+ {
406+ self.st.borrow_mut().timer = Some(id);
407+ }
408+ }
409+
410+ async fn search(self: Rc<Self>, query: String) {
411+ let Ok(ctrl) = AbortController::new() else { return };
412+ self.st.borrow_mut().controller = Some(ctrl.clone());
413+ let res = fetch_titles(&ctrl, &query).await;
414+ // Aborted by a newer search or by close: that one owns the menu state now.
415+ if ctrl.signal().aborted() {
416+ return;
417+ }
418+ let hits = match res {
419+ Ok(hits) => hits,
420+ Err(e) => {
421+ web_sys::console::error_2(&"note search failed".into(), &e);
422+ Vec::new()
423+ }
424+ };
425+ {
426+ let mut st = self.st.borrow_mut();
427+ st.results = hits.into_iter().filter(|hit| hit.id != self.current_id).collect();
428+ st.controller = None;
429+ st.loaded = true;
430+ }
431+ self.render_list();
432+ }
433+
434+ fn mark_active(&self) {
435+ let index = self.st.borrow().index;
436+ let rows = self.list.children();
437+ for i in 0..rows.length() {
438+ if let Some(row) = rows.item(i) {
439+ let _ = row.set_attribute("aria-selected", if i as usize == index { "true" } else { "false" });
440+ }
441+ }
442+ if let Some(row) = rows.item(index as u32) {
443+ let _ = self.root.set_attribute("aria-activedescendant", &row.id());
444+ let opts = ScrollIntoViewOptions::new();
445+ opts.set_block(ScrollLogicalPosition::Nearest);
446+ row.scroll_into_view_with_scroll_into_view_options(&opts);
447+ }
448+ }
449+
450+ fn set_index(&self, i: usize) {
451+ self.st.borrow_mut().index = i;
452+ self.mark_active();
453+ }
454+
455+ fn render_list(self: &Rc<Self>) {
456+ let (items, index, loaded) = {
457+ let mut st = self.st.borrow_mut();
458+ let Some(query) = st.active.as_ref().map(|t| t.query.clone()) else { return };
459+ st.items = build_items(&st.results, &query);
460+ if st.index >= st.items.len() {
461+ st.index = 0;
462+ }
463+ (st.items.clone(), st.index, st.loaded)
464+ };
465+ self.list.set_text_content(None);
466+ if items.is_empty() {
467+ // Only shown once the search for this query has answered.
468+ if loaded {
469+ let msg = self.strings.get("noNotesFound");
470+ let empty = h(&self.document, "div", &[("class", "slash-empty"), ("role", "presentation")], Some(msg.as_str()));
471+ let _ = self.list.append_child(&empty);
472+ }
473+ let _ = self.root.remove_attribute("aria-activedescendant");
474+ return;
475+ }
476+ for (i, item) in items.iter().enumerate() {
477+ let id = format!("note-opt-{i}");
478+ let selected = if i == index { "true" } else { "false" };
479+ let row = h(
480+ &self.document,
481+ "div",
482+ &[("class", "slash-item"), ("role", "option"), ("id", id.as_str()), ("aria-selected", selected)],
483+ None,
484+ );
485+ let text = self.item_label(item);
486+ let label = h(&self.document, "span", &[("class", "slash-label")], Some(text.as_str()));
487+ let _ = row.append_child(&label);
488+ let _ = self.list.append_child(&row);
489+ }
490+ self.mark_active();
491+ }
492+
493+ fn place(&self, ed: &Editor) {
494+ let Some(from) = self.st.borrow().active.as_ref().map(|t| t.from) else { return };
495+ let Some(to) = ed.sel.cursor() else { return };
496+ if let Some(b) = range_box(ed, from, to) {
497+ place_floating(&self.menu, b, false);
498+ }
499+ }
500+
501+ /// Opens, refetches or closes the menu from the current selection.
502+ fn sync(self: &Rc<Self>, ed: &Editor) {
503+ let Some(trig) = trigger_at(ed) else {
504+ self.st.borrow_mut().dismissed = None;
505+ self.close();
506+ return;
507+ };
508+ let (dismissed, changed) = {
509+ let st = self.st.borrow();
510+ (st.dismissed.as_ref() == Some(&trig.from), st.active.as_ref() != Some(&trig))
511+ };
512+ if dismissed {
513+ self.close();
514+ return;
515+ }
516+ if changed {
517+ {
518+ let mut st = self.st.borrow_mut();
519+ st.active = Some(trig.clone());
520+ st.index = 0;
521+ }
522+ self.schedule_search(trig.query.clone());
523+ }
524+ self.menu.set_hidden(false);
525+ if changed {
526+ self.render_list();
527+ }
528+ self.place(ed);
529+ }
530+
531+ /// Keyboard model while the menu is open. Returns true when the key is consumed.
532+ fn on_key(self: &Rc<Self>, ed: &mut Editor, key: &str) -> bool {
533+ let (active, n, index, busy) = {
534+ let st = self.st.borrow();
535+ (st.active.clone(), st.items.len(), st.index, st.busy)
536+ };
537+ let Some(active) = active else { return false };
538+ match key {
539+ "Escape" => {
540+ self.st.borrow_mut().dismissed = Some(active.from);
541+ self.close();
542+ true
543+ }
544+ "ArrowDown" if n > 0 => {
545+ self.set_index((index + 1) % n);
546+ true
547+ }
548+ "ArrowUp" if n > 0 => {
549+ self.set_index((index + n - 1) % n);
550+ true
551+ }
552+ "Enter" | "Tab" if n > 0 => {
553+ if !busy {
554+ let item = self.st.borrow().items.get(index).cloned();
555+ if let Some(item) = item {
556+ self.pick(ed, item);
557+ }
558+ }
559+ true
560+ }
561+ _ => false,
562+ }
563+ }
564+
565+ fn pick(self: &Rc<Self>, ed: &mut Editor, item: Item) {
566+ let active = {
567+ let st = self.st.borrow();
568+ if st.busy {
569+ return;
570+ }
571+ st.active.clone()
572+ };
573+ let Some(trig) = active else { return };
574+ let Some(to) = ed.sel.cursor() else { return };
575+ let text = self.item_text(&item);
576+ match item {
577+ Item::Note(hit) => insert_link(ed, &trig.from, &to, &text, &hit.id),
578+ Item::Create(_) => self.create_and_insert(ed, trig.from, to, text),
579+ }
580+ }
581+
582+ fn create_and_insert(self: &Rc<Self>, ed: &Editor, from: Pos, to: Pos, title: String) {
583+ // The range as it reads now; if the user edits it while the request runs, nothing is inserted.
584+ let before = text_between(ed, &from, &to);
585+ self.st.borrow_mut().busy = true;
586+ let me = self.clone();
587+ let weak = self.ed.clone();
588+ spawn_local(async move {
589+ let res = create_note(&title).await;
590+ me.st.borrow_mut().busy = false;
591+ let id = match res {
592+ Ok(id) => id,
593+ Err(e) => {
594+ web_sys::console::error_2(&"note create failed".into(), &e);
595+ return;
596+ }
597+ };
598+ let Some(ed) = weak.upgrade() else { return };
599+ let Ok(mut ed) = ed.try_borrow_mut() else { return };
600+ if ed.sel.cursor() != Some(to) || text_between(&ed, &from, &to) != before {
601+ return;
602+ }
603+ insert_link(&mut ed, &from, &to, &title, &id);
604+ });
605+ }
606+}
crates/editor/src/ui/presence.rsadded+399 -0
@@ -0,0 +1,399 @@
1+//! Remote presence: our caret and selection go into the `EphemeralStore`, and an
2+//! overlay draws every other peer's caret, name label and selection tint.
3+//! Wire format matches loro-prosemirror's `CursorEphemeralStore`: per peer
4+//! `{anchor, focus, user: {name, color}}`, cursors as Binary or Null.
5+
6+use std::cell::{Cell, RefCell};
7+use std::collections::HashMap;
8+use std::rc::{Rc, Weak};
9+
10+use loro::awareness::EphemeralStore;
11+use loro::cursor::Cursor;
12+use loro::LoroValue;
13+use wasm_bindgen::prelude::Closure;
14+use wasm_bindgen::{JsCast, JsValue};
15+use web_sys::{AbortSignal, AddEventListenerOptions, Document, FocusEvent, HtmlElement};
16+
17+use super::{coords_at, h, listen, Ctx, Ed};
18+use crate::core::pos::{Pos, Selection};
19+use crate::editor::Editor;
20+use crate::sync::Net;
21+
22+const KEY: &str = "project-note-peer";
23+/// Local state is refreshed this often; the store expires peers after 30 s.
24+const REFRESH_MS: i32 = 10_000;
25+const CARET_FALLBACK: &str = "#888888";
26+
27+/// Our encoded anchor and focus (None when there is no text selection to show).
28+type Cursors = (Option<Vec<u8>>, Option<Vec<u8>>);
29+
30+pub fn install(ed: &Ed, cx: &Ctx, net: &Rc<RefCell<Net>>) {
31+ let Some(window) = web_sys::window() else { return };
32+ let (name, color) = identity();
33+ let own = ed.borrow().doc.peer_id().to_string();
34+
35+ // The overlay is absolute and inset 0, so the mount must be a containing block.
36+ if let Ok(Some(style)) = window.get_computed_style(&cx.mount)
37+ && style.get_property_value("position").unwrap_or_default() == "static"
38+ && let Some(el) = cx.mount.dyn_ref::<HtmlElement>()
39+ {
40+ set_all(el, &[("position", "relative".into())]);
41+ }
42+ let overlay = h(&cx.document, "div", &[("class", "presence-layer"), ("aria-hidden", "true")], None);
43+ set_all(
44+ &overlay,
45+ &[
46+ ("position", "absolute".into()),
47+ ("top", "0".into()),
48+ ("left", "0".into()),
49+ ("right", "0".into()),
50+ ("bottom", "0".into()),
51+ ("pointer-events", "none".into()),
52+ ],
53+ );
54+ let _ = cx.mount.append_child(&overlay);
55+
56+ let layer = Layer { document: cx.document.clone(), overlay: overlay.clone(), own: own.clone() };
57+ let local = Rc::new(Local { net: Rc::downgrade(net), own: own.clone(), name, color, last: RefCell::new(None) });
58+
59+ // Redraw, coalesced to one frame.
60+ let draw: Rc<dyn Fn()> = {
61+ let (ed, net, layer) = (Rc::downgrade(ed), Rc::downgrade(net), layer.clone());
62+ Rc::new(move || {
63+ let (Some(ed), Some(net)) = (ed.upgrade(), net.upgrade()) else { return };
64+ let Ok(ed) = ed.try_borrow() else { return };
65+ let Ok(net) = net.try_borrow() else { return };
66+ draw_remote(&ed, &net.presence, &layer);
67+ })
68+ };
69+ let schedule = scheduler(draw);
70+
71+ net.borrow_mut().on_presence.push(Box::new({
72+ let schedule = schedule.clone();
73+ move |_: &EphemeralStore| schedule()
74+ }));
75+
76+ // Publish our selection after every change, and redraw the remote carets.
77+ {
78+ let (local, schedule) = (local.clone(), schedule.clone());
79+ ed.borrow_mut().listeners.push(Box::new(move |e: &Editor, _: bool| {
80+ local.publish(e, false);
81+ schedule();
82+ }));
83+ }
84+ // Focus decides whether our selection is shown at all.
85+ let root = ed.borrow().view.root.clone();
86+ let target: &web_sys::EventTarget = root.as_ref();
87+ for focus_event in ["focusin", "focusout"] {
88+ let (local, schedule) = (local.clone(), schedule.clone());
89+ listen::<FocusEvent>(target, focus_event, cx, ed, move |e, _| {
90+ local.publish(e, false);
91+ schedule();
92+ });
93+ }
94+
95+ // Keep ours alive in the store and expire stale peers.
96+ let timer = Rc::new(Cell::new(0));
97+ let tick = {
98+ let (local, schedule, timer) = (local.clone(), schedule.clone(), timer.clone());
99+ let (ed, net) = (Rc::downgrade(ed), Rc::downgrade(net));
100+ Closure::<dyn FnMut()>::new(move || {
101+ let (Some(ed), Some(net)) = (ed.upgrade(), net.upgrade()) else { return };
102+ if net.try_borrow().is_ok_and(|n| n.detached) {
103+ if let Some(w) = web_sys::window() {
104+ w.clear_interval_with_handle(timer.get());
105+ }
106+ return;
107+ }
108+ if let Ok(n) = net.try_borrow() {
109+ n.presence.remove_outdated();
110+ }
111+ if let Ok(e) = ed.try_borrow() {
112+ local.publish(&e, true);
113+ }
114+ schedule();
115+ })
116+ };
117+ if let Ok(id) = window.set_interval_with_callback_and_timeout_and_arguments_0(tick.as_ref().unchecked_ref(), REFRESH_MS) {
118+ timer.set(id);
119+ }
120+ tick.forget();
121+
122+ // Scroll (any container, so capture) and resize move the carets.
123+ let on_scroll = Closure::<dyn FnMut()>::new({
124+ let schedule = schedule.clone();
125+ move || schedule()
126+ });
127+ let _ = window.add_event_listener_with_callback_and_add_event_listener_options(
128+ "scroll",
129+ on_scroll.as_ref().unchecked_ref(),
130+ &scroll_opts(cx),
131+ );
132+ on_scroll.forget();
133+ let on_resize = Closure::<dyn FnMut()>::new({
134+ let schedule = schedule.clone();
135+ move || schedule()
136+ });
137+ let _ = window.add_event_listener_with_callback_and_add_event_listener_options(
138+ "resize",
139+ on_resize.as_ref().unchecked_ref(),
140+ &cx.opts,
141+ );
142+ on_resize.forget();
143+
144+ // Runs before the abort that removes listeners, so the socket is still open
145+ // and our entry is sent away before the note detaches.
146+ {
147+ let (own, overlay, net) = (own.clone(), overlay.clone(), Rc::downgrade(net));
148+ let on_detach = Closure::<dyn FnMut()>::new(move || {
149+ if let Some(net) = net.upgrade()
150+ && let Ok(mut n) = net.try_borrow_mut()
151+ {
152+ n.presence.delete(&own);
153+ n.drain();
154+ }
155+ overlay.remove();
156+ });
157+ let _ = window.add_event_listener_with_callback_and_add_event_listener_options(
158+ "note:detach",
159+ on_detach.as_ref().unchecked_ref(),
160+ &cx.opts,
161+ );
162+ on_detach.forget();
163+ }
164+
165+ local.publish(&ed.borrow(), true);
166+}
167+
168+/// Our overlay and the identity-free data needed to draw remote peers.
169+#[derive(Clone)]
170+struct Layer {
171+ document: Document,
172+ overlay: HtmlElement,
173+ own: String,
174+}
175+
176+/// Publishes our own presence state.
177+struct Local {
178+ net: Weak<RefCell<Net>>,
179+ own: String,
180+ name: String,
181+ color: String,
182+ last: RefCell<Option<Cursors>>,
183+}
184+
185+impl Local {
186+ /// Writes our state when it changed (or always when `force`), then sends it.
187+ fn publish(&self, ed: &Editor, force: bool) {
188+ let state = cursors(ed);
189+ if !force && self.last.borrow().as_ref() == Some(&state) {
190+ return;
191+ }
192+ let Some(net) = self.net.upgrade() else { return };
193+ let Ok(mut n) = net.try_borrow_mut() else { return };
194+ if n.detached {
195+ return;
196+ }
197+ n.presence.set(&self.own, self.value(&state));
198+ n.drain();
199+ *self.last.borrow_mut() = Some(state);
200+ }
201+
202+ fn value(&self, (anchor, focus): &Cursors) -> LoroValue {
203+ let bin = |c: &Option<Vec<u8>>| c.clone().map_or(LoroValue::Null, LoroValue::from);
204+ let user: HashMap<&str, LoroValue> = HashMap::from([
205+ ("name", LoroValue::from(self.name.as_str())),
206+ ("color", LoroValue::from(self.color.as_str())),
207+ ]);
208+ LoroValue::from(HashMap::from([
209+ ("anchor", bin(anchor)),
210+ ("focus", bin(focus)),
211+ ("user", LoroValue::from(user)),
212+ ]))
213+ }
214+}
215+
216+type Scheduler = Rc<dyn Fn()>;
217+
218+/// Returns a function that runs `draw` on the next animation frame, at most once per frame.
219+fn scheduler(draw: Rc<dyn Fn()>) -> Scheduler {
220+ let pending = Rc::new(Cell::new(false));
221+ Rc::new(move || {
222+ if pending.replace(true) {
223+ return;
224+ }
225+ let (pending, draw) = (pending.clone(), draw.clone());
226+ let cb = Closure::once_into_js(move || {
227+ pending.set(false);
228+ draw();
229+ });
230+ if let Some(w) = web_sys::window() {
231+ let _ = w.request_animation_frame(cb.unchecked_ref());
232+ }
233+ })
234+}
235+
236+/// Encoded anchor and focus of the local selection; both None unless the editor is focused.
237+fn cursors(ed: &Editor) -> Cursors {
238+ if !ed.focused() {
239+ return (None, None);
240+ }
241+ match &ed.sel {
242+ Selection::Text { anchor, head } => (encode(ed, *anchor), encode(ed, *head)),
243+ _ => (None, None),
244+ }
245+}
246+
247+fn encode(ed: &Editor, p: Pos) -> Option<Vec<u8>> {
248+ ed.m.cursor(p).map(|c| c.encode())
249+}
250+
251+/// Rebuilds the overlay for every other peer in the store.
252+fn draw_remote(ed: &Editor, store: &EphemeralStore, layer: &Layer) {
253+ let overlay = &layer.overlay;
254+ if overlay.first_child().is_some() {
255+ overlay.set_text_content(Some(""));
256+ }
257+ let peers: Vec<_> = store.get_all_states().into_iter().filter(|(peer, _)| *peer != layer.own).collect();
258+ if peers.is_empty() {
259+ // Alone: nothing to draw, and measuring would force a layout every keystroke.
260+ return;
261+ }
262+ let origin = overlay.get_bounding_client_rect();
263+ let origin = (origin.left(), origin.top());
264+
265+ for (peer, state) in peers {
266+ let anchor = decode(ed, field(&state, "anchor"));
267+ let focus = decode(ed, field(&state, "focus"));
268+ let name = text(field(&state, "user"), "name").unwrap_or_else(|| peer.chars().take(6).collect());
269+ let color = text(field(&state, "user"), "color").unwrap_or_else(|| CARET_FALLBACK.into());
270+
271+ if let (Some(a), Some(f)) = (anchor, focus)
272+ && a != f
273+ {
274+ selection(ed, layer, a.min(f), a.max(f), &peer, &color, origin);
275+ }
276+ if let Some(head) = focus.or(anchor) {
277+ caret(ed, layer, head, &peer, &name, &color, origin);
278+ }
279+ }
280+}
281+
282+/// A caret in the peer's color with a name label, the same markup as loro-prosemirror.
283+fn caret(ed: &Editor, layer: &Layer, p: Pos, peer: &str, name: &str, color: &str, (ox, oy): (f64, f64)) {
284+ let Some(b) = coords_at(ed, p) else { return };
285+ let el = h(&layer.document, "span", &[("class", "ProseMirror-loro-cursor"), ("data-peer", peer)], None);
286+ set_all(
287+ &el,
288+ &[
289+ ("position", "absolute".into()),
290+ ("left", px(b.left - ox)),
291+ ("top", px(b.top - oy)),
292+ ("height", px(b.bottom - b.top)),
293+ ("border-color", color.into()),
294+ ],
295+ );
296+ let label = h(&layer.document, "div", &[], Some(name));
297+ set_all(&label, &[("background-color", color.into())]);
298+ let _ = el.append_child(&label);
299+ let _ = layer.overlay.append_child(&el);
300+}
301+
302+/// One tinted box per line of the peer's selection.
303+fn selection(ed: &Editor, layer: &Layer, from: Pos, to: Pos, peer: &str, color: &str, (ox, oy): (f64, f64)) {
304+ let (Some((n1, o1)), Some((n2, o2))) = (ed.view.pos_to_dom(&ed.m, from), ed.view.pos_to_dom(&ed.m, to)) else { return };
305+ let Ok(range) = layer.document.create_range() else { return };
306+ if range.set_start(&n1, o1).is_err() || range.set_end(&n2, o2).is_err() {
307+ return;
308+ }
309+ let Some(rects) = range.get_client_rects() else { return };
310+ for i in 0..rects.length() {
311+ let Some(r) = rects.get(i) else { continue };
312+ let el = h(&layer.document, "div", &[("class", "loro-selection"), ("data-peer", peer)], None);
313+ set_all(
314+ &el,
315+ &[
316+ ("position", "absolute".into()),
317+ ("left", px(r.left() - ox)),
318+ ("top", px(r.top() - oy)),
319+ ("width", px(r.width())),
320+ ("height", px(r.height())),
321+ ("background-color", format!("color-mix(in srgb, {color} 28%, transparent)")),
322+ ],
323+ );
324+ let _ = layer.overlay.append_child(&el);
325+ }
326+}
327+
328+fn decode(ed: &Editor, v: Option<&LoroValue>) -> Option<Pos> {
329+ let Some(LoroValue::Binary(bytes)) = v else { return None };
330+ let cursor = Cursor::decode(bytes).ok()?;
331+ ed.m.cursor_pos(&cursor)
332+}
333+
334+fn field<'a>(v: &'a LoroValue, key: &str) -> Option<&'a LoroValue> {
335+ match v {
336+ LoroValue::Map(m) => m.get(key),
337+ _ => None,
338+ }
339+}
340+
341+/// A string field of a map value, looked up under `key`.
342+fn text(v: Option<&LoroValue>, key: &str) -> Option<String> {
343+ match field(v?, key)? {
344+ LoroValue::String(s) => Some(s.as_str().to_owned()),
345+ _ => None,
346+ }
347+}
348+
349+/// Our identity, kept per tab in sessionStorage. Same key and shape as editor.ts.
350+fn identity() -> (String, String) {
351+ let storage = web_sys::window().and_then(|w| w.session_storage().ok().flatten());
352+ if let Some(raw) = storage.as_ref().and_then(|s| s.get_item(KEY).ok().flatten())
353+ && let Ok(v) = js_sys::JSON::parse(&raw)
354+ {
355+ let get = |k: &str| {
356+ js_sys::Reflect::get(&v, &JsValue::from_str(k))
357+ .ok()
358+ .and_then(|x| x.as_string())
359+ .filter(|s| !s.is_empty())
360+ };
361+ if let (Some(name), Some(color)) = (get("name"), get("color")) {
362+ return (name, color);
363+ }
364+ }
365+ let n = 1000 + (js_sys::Math::random() * 9000.0).floor() as u32;
366+ let hue = (js_sys::Math::random() * 360.0).floor() as u32;
367+ let (name, color) = (format!("user-{n}"), format!("hsl({hue} 70% 45%)"));
368+ if let Some(s) = storage {
369+ // Storage errors are ignored: the identity then lasts for this load only.
370+ let _ = s.set_item(KEY, &format!(r#"{{"name":"{name}","color":"{color}"}}"#));
371+ }
372+ (name, color)
373+}
374+
375+/// Scroll listener options: capture (so inner scroll containers count) and passive,
376+/// with the same abort signal as the rest of the UI.
377+fn scroll_opts(cx: &Ctx) -> AddEventListenerOptions {
378+ let o = AddEventListenerOptions::new();
379+ o.set_capture(true);
380+ o.set_passive(true);
381+ if let Ok(sig) = js_sys::Reflect::get(cx.opts.as_ref(), &JsValue::from_str("signal"))
382+ && let Ok(sig) = sig.dyn_into::<AbortSignal>()
383+ {
384+ o.set_signal(&sig);
385+ }
386+ o
387+}
388+
389+fn px(v: f64) -> String {
390+ format!("{v}px")
391+}
392+
393+/// Sets inline style properties. Invalid values are ignored by the browser.
394+fn set_all(el: &HtmlElement, props: &[(&str, String)]) {
395+ let style = el.style();
396+ for (k, v) in props {
397+ let _ = style.set_property(k, v);
398+ }
399+}
crates/editor/src/ui/toolbar.rsadded+435 -0
@@ -0,0 +1,435 @@
1+//! Formatting toolbar (web/src/toolbar.ts): icon buttons in five groups inside
2+//! `#editor-toolbar`, kept in sync with the editor after every change. Roving tabindex
3+//! keeps the bar to one Tab stop; mousedown is swallowed so the editor keeps its
4+//! selection and focus.
5+
6+use std::rc::Rc;
7+
8+use wasm_bindgen::JsCast;
9+use web_sys::{EventTarget, HtmlButtonElement, HtmlElement, KeyboardEvent};
10+
11+use super::media::{Media, STATUS_ID};
12+use super::{Ctx, Ed, h, mod_keys, request_link, tooltip};
13+use crate::core::commands::{self as c, Cx, can_link, ancestor_kind, is_block_active};
14+use crate::core::doc::Kind;
15+use crate::core::marks::MarkType;
16+use crate::editor::Editor;
17+use note_model::flat;
18+
19+// Lucide-style glyphs (24x24, stroke based). Static strings, safe for innerHTML.
20+const ICON_UNDO: &str = r#"<path d="M9 14 4 9l5-5"/><path d="M4 9h10.5a5.5 5.5 0 0 1 0 11H11"/>"#;
21+const ICON_REDO: &str = r#"<path d="m15 14 5-5-5-5"/><path d="M20 9H9.5a5.5 5.5 0 0 0 0 11H13"/>"#;
22+const ICON_PARAGRAPH: &str = r#"<path d="M13 4v16"/><path d="M17 4v16"/><path d="M19 4H9.5a4.5 4.5 0 0 0 0 9H13"/>"#;
23+const ICON_H1: &str = r#"<path d="M4 12h8"/><path d="M4 18V6"/><path d="M12 18V6"/><path d="m17 12 3-2v8"/>"#;
24+const ICON_H2: &str = r#"<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"/>"#;
25+const ICON_H3: &str = r#"<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"/>"#;
26+const ICON_BOLD: &str = r#"<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"/>"#;
27+const ICON_ITALIC: &str = r#"<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"/>"#;
28+const ICON_CODE: &str = r#"<polyline points="16 18 22 12 16 6"/><polyline points="8 6 2 12 8 18"/>"#;
29+const ICON_LINK: &str = r#"<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"/>"#;
30+const ICON_BULLETS: &str = r#"<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"/>"#;
31+const ICON_ORDERED: &str = r#"<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"/>"#;
32+const ICON_QUOTE: &str = r#"<path d="M17 6H3"/><path d="M21 12H8"/><path d="M21 18H8"/><path d="M3 12v6"/>"#;
33+const ICON_CODE_BLOCK: &str = r#"<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"/>"#;
34+const ICON_RULE: &str = r#"<line x1="5" x2="19" y1="12" y2="12"/>"#;
35+const ICON_ATTACH: &str = r#"<path d="m21.44 11.05-9.19 9.19a6 6 0 0 1-8.49-8.49l8.57-8.57A4 4 0 1 1 18 8.84l-8.59 8.57a2 2 0 0 1-2.83-2.83l8.49-8.48"/>"#;
36+const ICON_MIC: &str = r#"<path d="M12 2a3 3 0 0 0-3 3v7a3 3 0 0 0 6 0V5a3 3 0 0 0-3-3Z"/><path d="M19 10v2a7 7 0 0 1-14 0v-2"/><line x1="12" x2="12" y1="19" y2="22"/>"#;
37+
38+const HEADING_KEYS: [&str; 3] = ["1", "2", "3"];
39+
40+/// What a button does. Mirrors the `run` of the TS items, with the arguments baked in.
41+#[derive(Clone, Copy)]
42+enum Run {
43+ Undo,
44+ Redo,
45+ Paragraph,
46+ /// Toggle the textblock type (headings, code block).
47+ Block(Kind),
48+ /// Toggle an inline mark.
49+ Mark(MarkType),
50+ /// Toggle a list of the given kind.
51+ List(Kind),
52+ Quote,
53+ Rule,
54+ /// Opens the link popover; never dispatches.
55+ Link,
56+ /// Opens the file picker; never dispatches.
57+ Attach,
58+ /// Starts or stops a microphone recording; never dispatches.
59+ Record,
60+}
61+
62+/// What decides the pressed state of a toggle button.
63+#[derive(Clone, Copy)]
64+enum Active {
65+ Block(Kind),
66+ Mark(MarkType),
67+ Ancestor(fn(Kind) -> bool),
68+}
69+
70+fn exec(run: Run, cx: &mut Cx, apply: bool) -> bool {
71+ match run {
72+ Run::Undo | Run::Redo => false,
73+ Run::Paragraph => c::set_block_type(cx, Kind::Paragraph, apply),
74+ Run::Block(k) => c::toggle_block(cx, k, apply),
75+ Run::Mark(t) => c::toggle_mark(cx, t, apply),
76+ Run::List(k) => c::toggle_list(cx, k, apply),
77+ Run::Quote => c::toggle_quote(cx, apply),
78+ Run::Rule => c::insert_rule(cx, apply),
79+ Run::Link => can_link(cx),
80+ // Media lands at the selection, which must be in text outside a code block.
81+ Run::Attach | Run::Record => cx.head_block().is_some_and(|b| b.kind().is_text() && b.kind() != flat::Kind::Code),
82+ }
83+}
84+
85+fn is_active(active: Active, cx: &Cx) -> bool {
86+ match active {
87+ Active::Block(k) => is_block_active(cx, k),
88+ Active::Mark(t) => c::mark_active_within(cx, t, c::MARK_STATE_UNITS),
89+ Active::Ancestor(pred) => ancestor_kind(cx, pred).is_some(),
90+ }
91+}
92+
93+/// One button spec, before its DOM exists.
94+struct Spec {
95+ id: &'static str,
96+ label: String,
97+ keys: Vec<&'static str>,
98+ icon: &'static str,
99+ run: Run,
100+ active: Option<Active>,
101+}
102+
103+/// A button after it was created: the element plus what it drives.
104+struct Btn {
105+ el: HtmlButtonElement,
106+ run: Run,
107+ active: Option<Active>,
108+}
109+
110+fn spec(id: &'static str, label: String, keys: Vec<&'static str>, icon: &'static str, run: Run, active: Option<Active>) -> Spec {
111+ Spec { id, label, keys, icon, run, active }
112+}
113+
114+/// Keyboard shortcut in aria-keyshortcuts form, e.g. "Control+B" or "Meta+Shift+8".
115+fn aria_keys(keys: &[&str]) -> String {
116+ keys.iter()
117+ .map(|k| match *k {
118+ "Ctrl" => "Control",
119+ "⌘" => "Meta",
120+ "Shift" | "⇧" => "Shift",
121+ "Alt" | "⌥" => "Alt",
122+ other => other,
123+ })
124+ .collect::<Vec<_>>()
125+ .join("+")
126+}
127+
128+fn svg(path: &str) -> String {
129+ format!(
130+ r#"<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">{path}</svg>"#
131+ )
132+}
133+
134+/// Adds a listener removed on detach (same abort signal as `ui::listen`). The callback
135+/// gets the raw event and never borrows the editor by itself.
136+fn on(target: &EventTarget, name: &str, cx: &Ctx, cb: wasm_bindgen::closure::Closure<dyn FnMut(web_sys::Event)>) {
137+ let _ = target.add_event_listener_with_callback_and_add_event_listener_options(name, cb.as_ref().unchecked_ref(), &cx.opts);
138+ cb.forget();
139+}
140+
141+fn is_node(a: &web_sys::Node, b: &HtmlButtonElement) -> bool {
142+ let bn: &web_sys::Node = b.as_ref();
143+ a.is_same_node(Some(bn))
144+}
145+
146+fn set_stop(btns: &[Btn], index: usize) {
147+ for (i, b) in btns.iter().enumerate() {
148+ b.el.set_tab_index(if i == index { 0 } else { -1 });
149+ }
150+}
151+
152+/// Updates disabled, pressed and the single tab stop from the editor state.
153+fn sync(btns: &[Btn], ed: &Editor, media: &Media) {
154+ for b in btns {
155+ let enabled = match b.run {
156+ Run::Undo => ed.can_undo(),
157+ Run::Redo => ed.can_redo(),
158+ // A running recording can always be stopped, even when the caret is elsewhere.
159+ Run::Record => media.recording() || ed.can(|cx| exec(b.run, cx, false)),
160+ run => ed.can(|cx| exec(run, cx, false)),
161+ };
162+ b.el.set_disabled(!enabled);
163+ if let Some(active) = b.active {
164+ let on = ed.can(|cx| is_active(active, cx));
165+ let value = if on { "true" } else { "false" };
166+ let _ = b.el.set_attribute("data-active", value);
167+ let _ = b.el.set_attribute("aria-pressed", value);
168+ }
169+ }
170+ // Keep one enabled button in the tab order, preferring the last one focused.
171+ let stop = btns
172+ .iter()
173+ .position(|b| b.el.tab_index() == 0 && !b.el.disabled())
174+ .or_else(|| btns.iter().position(|b| !b.el.disabled()));
175+ if let Some(i) = stop {
176+ set_stop(btns, i);
177+ }
178+}
179+
180+pub fn install(ed: &Ed, cx: &Ctx, media: &Media) {
181+ let document = &cx.document;
182+ let root: HtmlElement = ed.borrow().view.root.clone();
183+ let m = mod_keys();
184+ let (md, sh, al) = (m.0, m.1, m.2);
185+ let s = &cx.strings;
186+
187+ // Reuse the page's #editor-toolbar when present; otherwise create it just before the editor.
188+ let el: HtmlElement = match document.get_element_by_id("editor-toolbar").and_then(|e| e.dyn_into::<HtmlElement>().ok()) {
189+ Some(el) => el,
190+ None => {
191+ let el = h(document, "div", &[("id", "editor-toolbar")], None);
192+ if let Some(parent) = cx.mount.parent_node() {
193+ let mount_node: &web_sys::Node = &cx.mount;
194+ let node: &web_sys::Node = &el;
195+ let _ = parent.insert_before(node, Some(mount_node));
196+ }
197+ el
198+ }
199+ };
200+ let _ = el.class_list().add_1("editor-toolbar");
201+ let _ = el.set_attribute("role", "toolbar");
202+ let _ = el.set_attribute("aria-label", &s.get("toolbarLabel"));
203+
204+ let heading = |level: u8, icon: &'static str| {
205+ spec(
206+ match level {
207+ 1 => "h1",
208+ 2 => "h2",
209+ _ => "h3",
210+ },
211+ s.get(&format!("heading{level}")),
212+ vec![md, al, HEADING_KEYS[usize::from(level) - 1]],
213+ icon,
214+ Run::Block(Kind::Heading(level)),
215+ Some(Active::Block(Kind::Heading(level))),
216+ )
217+ };
218+
219+ // One inner vec per group, in the order of the TS `buildItems` separators.
220+ let groups: [(&str, Vec<Spec>); 5] = [
221+ (
222+ "history",
223+ vec![
224+ spec("undo", s.get("undo"), vec![md, "Z"], ICON_UNDO, Run::Undo, None),
225+ spec("redo", s.get("redo"), vec![md, sh, "Z"], ICON_REDO, Run::Redo, None),
226+ ],
227+ ),
228+ (
229+ "headings",
230+ vec![
231+ spec(
232+ "paragraph",
233+ s.get("paragraph"),
234+ vec![md, al, "0"],
235+ ICON_PARAGRAPH,
236+ Run::Paragraph,
237+ Some(Active::Block(Kind::Paragraph)),
238+ ),
239+ heading(1, ICON_H1),
240+ heading(2, ICON_H2),
241+ heading(3, ICON_H3),
242+ ],
243+ ),
244+ (
245+ "marks",
246+ vec![
247+ spec("bold", s.get("bold"), vec![md, "B"], ICON_BOLD, Run::Mark(MarkType::Strong), Some(Active::Mark(MarkType::Strong))),
248+ spec("italic", s.get("italic"), vec![md, "I"], ICON_ITALIC, Run::Mark(MarkType::Em), Some(Active::Mark(MarkType::Em))),
249+ spec(
250+ "code",
251+ s.get("inlineCode"),
252+ vec![md, "E"],
253+ ICON_CODE,
254+ Run::Mark(MarkType::Code),
255+ Some(Active::Mark(MarkType::Code)),
256+ ),
257+ spec("link", s.get("link"), vec![md, "K"], ICON_LINK, Run::Link, Some(Active::Mark(MarkType::Link))),
258+ ],
259+ ),
260+ (
261+ "blocks",
262+ vec![
263+ spec(
264+ "bullets",
265+ s.get("bulletList"),
266+ vec![md, sh, "8"],
267+ ICON_BULLETS,
268+ Run::List(Kind::BulletList),
269+ Some(Active::Ancestor(|k| k == Kind::BulletList)),
270+ ),
271+ spec(
272+ "ordered",
273+ s.get("numberedList"),
274+ vec![md, sh, "9"],
275+ ICON_ORDERED,
276+ Run::List(Kind::OrderedList),
277+ Some(Active::Ancestor(|k| k == Kind::OrderedList)),
278+ ),
279+ spec(
280+ "quote",
281+ s.get("quote"),
282+ vec![">"],
283+ ICON_QUOTE,
284+ Run::Quote,
285+ Some(Active::Ancestor(|k| k == Kind::Blockquote)),
286+ ),
287+ spec(
288+ "codeblock",
289+ s.get("codeBlock"),
290+ vec!["```"],
291+ ICON_CODE_BLOCK,
292+ Run::Block(Kind::CodeBlock),
293+ Some(Active::Block(Kind::CodeBlock)),
294+ ),
295+ spec("rule", s.get("divider"), vec!["---"], ICON_RULE, Run::Rule, None),
296+ ],
297+ ),
298+ (
299+ "media",
300+ vec![
301+ spec("attach", s.get("attach"), vec![], ICON_ATTACH, Run::Attach, None),
302+ spec("record", s.get("recordAudio"), vec![], ICON_MIC, Run::Record, None),
303+ ],
304+ ),
305+ ];
306+
307+ let reason = s.get("unavailable");
308+ let mut btns: Vec<Btn> = Vec::new();
309+ // The m:ss readout and the status line sit at the end of the media group.
310+ let mut rec_time: Option<HtmlElement> = None;
311+ for (name, specs) in groups {
312+ let group = h(document, "div", &[("class", "editor-toolbar-group"), ("data-group", name)], None);
313+ for sp in specs {
314+ let btn: HtmlButtonElement = h(
315+ document,
316+ "button",
317+ &[
318+ ("type", "button"),
319+ ("class", "editor-toolbar-btn"),
320+ ("aria-label", &sp.label),
321+ ("aria-keyshortcuts", &aria_keys(&sp.keys)),
322+ ("data-command", sp.id),
323+ ("tabindex", "-1"),
324+ ],
325+ None,
326+ )
327+ .unchecked_into();
328+ let icon = h(document, "span", &[("class", "editor-toolbar-icon"), ("aria-hidden", "true")], None);
329+ icon.set_inner_html(&svg(sp.icon));
330+ let _ = btn.append_child(&icon);
331+ let _ = btn.append_child(&tooltip(document, &sp.label, &sp.keys, Some(&reason)));
332+ btn.set_disabled(true);
333+ let _ = group.append_child(&btn);
334+ btns.push(Btn { el: btn, run: sp.run, active: sp.active });
335+ }
336+ if name == "media" {
337+ let time = h(document, "span", &[("class", "editor-rec-time"), ("hidden", ""), ("aria-hidden", "true")], Some("0:00"));
338+ let status = h(document, "span", &[("id", STATUS_ID), ("class", "editor-media-status"), ("role", "status"), ("aria-live", "polite")], None);
339+ let _ = group.append_child(&time);
340+ let _ = group.append_child(&status);
341+ rec_time = Some(time);
342+ }
343+ let _ = el.append_child(&group);
344+ }
345+ if let (Some(rec), Some(time)) = (btns.iter().find(|b| matches!(b.run, Run::Record)), rec_time) {
346+ media.bind_record(rec.el.clone(), time);
347+ }
348+ let btns = Rc::new(btns);
349+
350+ // Mousedown must not steal focus or the selection from the editor.
351+ let target: &EventTarget = el.as_ref();
352+ on(target, "mousedown", cx, wasm_bindgen::closure::Closure::new(|ev: web_sys::Event| ev.prevent_default()));
353+
354+ // Roving tabindex: arrows, Home and End move among enabled buttons.
355+ {
356+ let btns = btns.clone();
357+ let document = document.clone();
358+ let cb = wasm_bindgen::closure::Closure::<dyn FnMut(web_sys::Event)>::new(move |ev: web_sys::Event| {
359+ let Some(key) = ev.dyn_ref::<KeyboardEvent>().map(|k| k.key()) else { return };
360+ let enabled: Vec<usize> = (0..btns.len()).filter(|&i| !btns[i].el.disabled()).collect();
361+ if enabled.is_empty() {
362+ return;
363+ }
364+ let active = document.active_element();
365+ let pos = enabled
366+ .iter()
367+ .position(|&i| active.as_ref().is_some_and(|a| is_node(a, &btns[i].el)))
368+ .map_or(-1, |p| p as isize);
369+ let len = enabled.len() as isize;
370+ let next = match key.as_str() {
371+ "ArrowRight" => (pos + 1).rem_euclid(len),
372+ "ArrowLeft" => (pos - 1).rem_euclid(len),
373+ "Home" => 0,
374+ "End" => len - 1,
375+ _ => return,
376+ } as usize;
377+ ev.prevent_default();
378+ let i = enabled[next];
379+ set_stop(&btns, i);
380+ let _ = btns[i].el.focus();
381+ });
382+ on(target, "keydown", cx, cb);
383+ }
384+
385+ // Clicks run the command, then return focus to the editor. Link is handled apart:
386+ // the popover opens with the editor borrow released, since it reads the editor.
387+ for b in btns.iter() {
388+ let run = b.run;
389+ let weak = Rc::downgrade(ed);
390+ let root = root.clone();
391+ let media = media.clone();
392+ let cb = wasm_bindgen::closure::Closure::<dyn FnMut(web_sys::Event)>::new(move |_: web_sys::Event| {
393+ // Media takes no editor borrow: the file picker and the microphone run on their own.
394+ if matches!(run, Run::Attach | Run::Record) {
395+ if matches!(run, Run::Attach) {
396+ media.attach();
397+ } else {
398+ media.toggle_record();
399+ }
400+ let _ = root.focus();
401+ return;
402+ }
403+ let Some(ed) = weak.upgrade() else { return };
404+ if matches!(run, Run::Link) {
405+ let open = ed.try_borrow().is_ok_and(|e| e.can(|cx| can_link(cx)));
406+ if open {
407+ request_link(&root);
408+ }
409+ } else if let Ok(mut e) = ed.try_borrow_mut() {
410+ match run {
411+ Run::Undo => {
412+ e.undo();
413+ }
414+ Run::Redo => {
415+ e.redo();
416+ }
417+ _ => {
418+ e.run(|cx| exec(run, cx, true));
419+ }
420+ }
421+ }
422+ let _ = root.focus();
423+ });
424+ let target: &EventTarget = b.el.as_ref();
425+ on(target, "click", cx, cb);
426+ }
427+
428+ // Initial state, then after every change of doc or selection.
429+ if let Ok(e) = ed.try_borrow() {
430+ sync(&btns, &e, media);
431+ }
432+ let btns_l = btns.clone();
433+ let media_l = media.clone();
434+ ed.borrow_mut().listeners.push(Box::new(move |e: &Editor, _changed: bool| sync(&btns_l, e, &media_l)));
435+}
crates/editor/src/view.rsadded+1966 -0
@@ -0,0 +1,1966 @@
1+//! The DOM side of the editor: the body's blocks in pages, an incremental flush
2+//! driven by the model's block splices, DOM <-> offset mapping and the read-back of
3+//! text the browser typed natively.
4+//!
5+//! Blocks are flat in the model; the DOM nests them (`ul > li > p`, `blockquote`) per
6+//! page. A container cut by a page boundary is split: the part on the later page has
7+//! `pm-cont` (and the earlier part `pm-more`), which the stylesheet joins seamlessly.
8+
9+use std::collections::HashMap;
10+use std::rc::Rc;
11+
12+use note_model::flat::{Attrs, Kind, OBJ, Wrap};
13+use note_model::marks::Marks;
14+use note_model::render::{self, TRAILING_BREAK};
15+use note_model::write::Inline;
16+use wasm_bindgen::{JsCast, JsValue};
17+use web_sys::{Document, Element, HtmlElement, Node as DomNode, Text};
18+
19+use crate::core::commands::keep;
20+use crate::core::model::{Blk, Model};
21+use crate::core::pos::Pos;
22+use crate::strings::Strings;
23+
24+/// Expando on page elements: the page's uid.
25+const PAGE_KEY: &str = "__pmPage";
26+/// Expando on block elements.
27+const BLOCK_KEY: &str = "__pmBlock";
28+/// Property on a chunk element: its last known index in its block's runs.
29+const RUN_KEY: &str = "__pmRun";
30+
31+/// Blocks per page.
32+const PAGE: usize = 64;
33+/// Assumed height of a block never measured (px).
34+const EST_BLOCK_PX: f64 = 32.0;
35+
36+pub struct BView {
37+ /// Stable while the block's element lives (UI state is keyed by it).
38+ pub key: u32,
39+ pub el: Element,
40+ /// Where the runs go (`code` inside `pre`, else `el`).
41+ pub content: Element,
42+ pub attrs: Attrs,
43+ pub runs: Vec<Run>,
44+ trailing: Option<Element>,
45+ /// Content changed: `Some(range)` for one plain edit (Unicode, from the block
46+ /// start), `None` for anything else (attributes may have changed too).
47+ dirty: Option<Option<(usize, usize)>>,
48+ /// The DOM already matches the model (typed natively): the next dirty mark is moot.
49+ synced: bool,
50+ /// Hidden chunks' spacers are drawn this much shorter (see `MAX_PX`).
51+ scale: f64,
52+ /// For a chunked code block: lines per chunk (see [`code_chunk_lines`]).
53+ lines: usize,
54+}
55+
56+#[derive(Clone, PartialEq, Debug)]
57+pub enum RunKind {
58+ Text,
59+ Break,
60+ Image { src: String, alt: String, title: Option<String> },
61+}
62+
63+pub struct Run {
64+ pub kind: RunKind,
65+ /// UTF-16 length.
66+ pub len: usize,
67+ /// Outermost DOM node of the run (a mark wrapper, the text, or the element).
68+ pub dom: DomNode,
69+ pub text: Option<Text>,
70+ /// The text of `text`, kept equal to the DOM node: patches compare against it
71+ /// instead of reading the DOM, and edits typed natively update it.
72+ pub s: String,
73+ /// Unicode scalars of the run (Loro's text positions).
74+ pub chars: usize,
75+ pub marks: Marks,
76+ /// A piece of a long block, wrapped in its own element (`dom`).
77+ pub chunk: bool,
78+ /// For a chunk: its content is attached. Chunks far from the viewport and the caret
79+ /// are empty placeholders sized by their line count (`inner` stays detached, still
80+ /// holding the text): the browser's per-keystroke cost grows with all editable text.
81+ pub live: bool,
82+ /// For a chunk: the node inside `dom` (the text, or its mark wrapper).
83+ pub inner: Option<DomNode>,
84+ /// For a chunk: last seen near the viewport.
85+ pub near: bool,
86+ /// `dom` is in the block's content element (see `place_runs`).
87+ shown: bool,
88+ /// For a chunk: its height while hidden (px, unscaled).
89+ px: f64,
90+ /// For a hidden chunk shown as a spacer: the height written on it.
91+ styled: Option<i64>,
92+}
93+
94+/// A run of consecutive blocks under one element. Only pages near the viewport (or
95+/// holding the selection) are built; the rest keep their last measured height, and
96+/// each run of them is one empty spacer in the DOM (see `View::layout`). The browser's per-keystroke cost grows with the editable content
97+/// in the DOM, so this keeps typing flat in documents of any length.
98+struct Page {
99+ el: Element,
100+ uid: u32,
101+ n: usize,
102+ live: bool,
103+ height: f64,
104+ /// `el` is in the root: a live page, or the spacer standing for a run of dead ones.
105+ attached: bool,
106+ /// The height written on `el` as a spacer.
107+ styled: Option<i64>,
108+ /// When live, one entry per block; `None` until built.
109+ blocks: Vec<Option<BView>>,
110+ /// What the grouping was built from (see `View::shape`).
111+ shape: Shape,
112+}
113+
114+#[derive(PartialEq, Default)]
115+struct Shape {
116+ prev: Option<Attrs>,
117+ next: Option<Attrs>,
118+ blocks: Vec<(Vec<Wrap>, Option<usize>, Option<i64>)>,
119+ numbers: Vec<i64>,
120+}
121+
122+pub struct View {
123+ pub root: HtmlElement,
124+ document: Document,
125+ pages: Vec<Page>,
126+ /// The first block of each page, and the block count last; empty when stale.
127+ /// Changes to the pages or their block counts clear it (`pages_changed`).
128+ starts: std::cell::RefCell<Vec<usize>>,
129+ next_uid: u32,
130+ page_key: JsValue,
131+ block_key: JsValue,
132+ /// The block being composed into; the flush leaves it alone.
133+ pub composing: Option<usize>,
134+ /// The composed block changed meanwhile: rebuilt when the composition ends.
135+ deferred: bool,
136+ /// Content width when text chunks were last built (see `TEXT_CHAR_AREA`).
137+ text_width: f64,
138+ /// Spacers are drawn this much shorter than the pages they stand for (see `MAX_PX`).
139+ scale: f64,
140+ /// The state of each take on the server, `live` or `lost`; a take not listed is absent.
141+ /// Sync keeps it up to date, and a take's embed reads it when the embed is built.
142+ pub takes: Rc<std::cell::RefCell<HashMap<String, String>>>,
143+}
144+
145+impl View {
146+ pub fn new(root: HtmlElement) -> Self {
147+ let document = root.owner_document().unwrap();
148+ View {
149+ root,
150+ document,
151+ pages: Vec::new(),
152+ starts: Default::default(),
153+ next_uid: 0,
154+ page_key: JsValue::from_str(PAGE_KEY),
155+ block_key: JsValue::from_str(BLOCK_KEY),
156+ composing: None,
157+ deferred: false,
158+ text_width: 800.0,
159+ scale: 1.0,
160+ takes: Rc::default(),
161+ }
162+ }
163+
164+ /// Renders the whole body, replacing what is in the root (the server pre-render).
165+ pub fn render_all(&mut self, m: &Model) {
166+ m.take_splices();
167+ self.pages.clear();
168+ self.pages_changed();
169+ self.root.set_text_content(None);
170+ let n = m.len();
171+ let mut i = 0;
172+ while i < n {
173+ let k = PAGE.min(n - i);
174+ let page = self.new_page(k, k as f64 * EST_BLOCK_PX);
175+ self.pages.push(page);
176+ i += k;
177+ }
178+ self.pages_changed();
179+ self.layout();
180+ // The top shows at once; `sync_viewport` brings in the rest as it scrolls near.
181+ for p in 0..self.pages.len().min(2) {
182+ self.set_page_live(m, p, true);
183+ }
184+ }
185+
186+ fn new_page(&mut self, n: usize, height: f64) -> Page {
187+ let el = self.document.create_element("div").unwrap();
188+ el.set_class_name("pm-page");
189+ let uid = self.next_uid;
190+ self.next_uid += 1;
191+ let _ = js_sys::Reflect::set(&el, &self.page_key, &JsValue::from(uid));
192+ Page { el, uid, n, live: false, height, attached: false, styled: None, blocks: Vec::new(), shape: Shape::default() }
193+ }
194+
195+ fn starts(&self) -> std::cell::Ref<'_, Vec<usize>> {
196+ if self.starts.borrow().is_empty() {
197+ let mut s = self.starts.borrow_mut();
198+ s.reserve(self.pages.len() + 1);
199+ let mut acc = 0;
200+ s.push(0);
201+ for p in &self.pages {
202+ acc += p.n;
203+ s.push(acc);
204+ }
205+ }
206+ self.starts.borrow()
207+ }
208+
209+ fn pages_changed(&mut self) {
210+ self.starts.get_mut().clear();
211+ }
212+
213+ /// The first block of page `pi`.
214+ fn page_start(&self, pi: usize) -> usize {
215+ self.starts()[pi]
216+ }
217+
218+ /// Page and position in it of block `i`.
219+ fn locate(&self, i: usize) -> Option<(usize, usize)> {
220+ let s = self.starts();
221+ if i >= *s.last()? {
222+ return None;
223+ }
224+ let pi = s.partition_point(|&x| x <= i) - 1;
225+ Some((pi, i - s[pi]))
226+ }
227+
228+ fn set_page_live(&mut self, m: &Model, pi: usize, live: bool) {
229+ if self.pages[pi].live == live {
230+ return;
231+ }
232+ if live {
233+ let n = self.pages[pi].n;
234+ self.pages[pi].blocks = (0..n).map(|_| None).collect();
235+ self.pages[pi].live = true;
236+ self.pages[pi].shape = Shape::default();
237+ self.build_missing(m, pi);
238+ self.group(m, pi);
239+ } else {
240+ let p = &mut self.pages[pi];
241+ p.blocks.clear();
242+ p.el.set_text_content(None);
243+ p.live = false;
244+ }
245+ self.layout();
246+ }
247+
248+ /// Puts the live pages in the root, and for each run of dead pages one spacer (the
249+ /// run's first page) as tall as the run: the root holds a few elements however long
250+ /// the note is. Firefox's spellchecker handles every node added to or removed from
251+ /// an editable root right away, 2 s for 15k placeholder pages.
252+ fn layout(&mut self) {
253+ let total: f64 = self.pages.iter().map(|p| p.height).sum();
254+ self.scale = rescale(self.scale, total);
255+ let mut prev: Option<Element> = None;
256+ let mut i = 0;
257+ while i < self.pages.len() {
258+ if self.pages[i].live {
259+ self.attach(i, &mut prev, None);
260+ i += 1;
261+ continue;
262+ }
263+ let mut j = i;
264+ let mut h = 0.0;
265+ while j < self.pages.len() && !self.pages[j].live {
266+ h += self.pages[j].height;
267+ j += 1;
268+ }
269+ self.attach(i, &mut prev, Some((h * self.scale).round() as i64));
270+ for p in &mut self.pages[i + 1..j] {
271+ if p.attached {
272+ p.el.remove();
273+ p.attached = false;
274+ }
275+ }
276+ i = j;
277+ }
278+ }
279+
280+ fn attach(&mut self, i: usize, prev: &mut Option<Element>, height: Option<i64>) {
281+ let p = &mut self.pages[i];
282+ if !p.attached {
283+ let _ = match prev {
284+ Some(e) => e.after_with_node_1(&p.el),
285+ None => self.root.prepend_with_node_1(&p.el),
286+ };
287+ p.attached = true;
288+ }
289+ if p.styled != height {
290+ let _ = match height {
291+ Some(h) => p.el.set_attribute("style", &format!("height:{h}px")),
292+ None => p.el.remove_attribute("style"),
293+ };
294+ p.styled = height;
295+ }
296+ *prev = Some(p.el.clone());
297+ }
298+
299+ /// Viewport top and bottom of page `i`; a dead page's lie within its run's spacer.
300+ fn page_box(&self, i: usize) -> (f64, f64) {
301+ let mut h = 0.0;
302+ let mut head = i;
303+ if !self.pages[i].live {
304+ while head > 0 && !self.pages[head - 1].live {
305+ head -= 1;
306+ h += self.pages[head].height;
307+ }
308+ }
309+ let r = self.pages[head].el.get_bounding_client_rect();
310+ if self.pages[i].live {
311+ (r.top(), r.bottom())
312+ } else {
313+ let k = self.scale;
314+ (r.top() + h * k, r.top() + (h + self.pages[i].height) * k)
315+ }
316+ }
317+
318+ /// Builds the page holding block `i`, so it can take the selection.
319+ pub fn show(&mut self, m: &Model, i: usize) {
320+ if let Some((pi, _)) = self.locate(i) {
321+ self.set_page_live(m, pi, true);
322+ }
323+ }
324+
325+ /// Builds the pages and attaches the chunks within `NEAR_PX` of the viewport, and
326+ /// empties the others, except where the selection or a composition is. Pages and
327+ /// chunks are stacked top to bottom, so binary searches on their boxes find the
328+ /// range: a few layout reads per frame however long the note is. Returns whether
329+ /// anything changed, which moves what follows and needs another pass.
330+ pub fn sync_viewport(&mut self, m: &Model) -> bool {
331+ let Some(win) = web_sys::window() else { return false };
332+ let height = win.inner_height().ok().and_then(|h| h.as_f64()).unwrap_or(800.0);
333+ let (top, bottom) = (-NEAR_PX, height + NEAR_PX);
334+ let ds = win.get_selection().ok().flatten();
335+ let holds_selection = |n: &DomNode| {
336+ ds.as_ref().is_some_and(|ds| {
337+ [ds.anchor_node(), ds.focus_node()].into_iter().flatten().any(|s| n.contains(Some(&s)))
338+ })
339+ };
340+ let mut changed = false;
341+
342+ let composing_page = self.composing.and_then(|c| self.locate(c)).map(|l| l.0);
343+ let (first, last) = near_range(self.pages.len(), |i| self.page_box(i), top, bottom);
344+ for i in 0..self.pages.len() {
345+ let near = (first..last).contains(&i);
346+ if near == self.pages[i].live {
347+ continue;
348+ }
349+ if !near {
350+ let el: DomNode = self.pages[i].el.clone().into();
351+ if holds_selection(&el) || composing_page == Some(i) {
352+ continue;
353+ }
354+ let h = self.pages[i].el.get_bounding_client_rect().height();
355+ if h > 0.0 {
356+ self.pages[i].height = h;
357+ }
358+ }
359+ self.set_page_live(m, i, near);
360+ changed = true;
361+ }
362+
363+ let composing = self.composing;
364+ let mut g = 0;
365+ for pi in 0..self.pages.len() {
366+ let n = self.pages[pi].n;
367+ if !self.pages[pi].live {
368+ g += n;
369+ continue;
370+ }
371+ for k in 0..n {
372+ if composing == Some(g + k) {
373+ continue;
374+ }
375+ let Some(v) = self.pages[pi].blocks[k].as_mut() else { continue };
376+ if !v.runs.first().is_some_and(|r| r.chunk) {
377+ continue;
378+ }
379+ // Shown chunks' heights, read while layout is fresh: a chunk hidden later
380+ // keeps it (wrapped text has no line count to size it by).
381+ for r in v.runs.iter_mut().filter(|r| r.live && r.shown) {
382+ let h = r.dom.unchecked_ref::<Element>().get_bounding_client_rect().height();
383+ if h > 0.0 {
384+ r.px = h;
385+ }
386+ }
387+ let (first, last) = near_range(v.runs.len(), |i| chunk_box(v, i), top, bottom);
388+ for i in 0..v.runs.len() {
389+ let near = (first..last).contains(&i);
390+ let r = &mut v.runs[i];
391+ if r.near == near {
392+ continue;
393+ }
394+ r.near = near;
395+ if near || !holds_selection(&r.dom) {
396+ let was = r.live;
397+ set_live(r, near);
398+ changed |= was != near;
399+ }
400+ }
401+ place_runs(v);
402+ }
403+ g += n;
404+ }
405+ changed
406+ }
407+
408+ // -----------------------------------------------------------------------
409+ // Building
410+ // -----------------------------------------------------------------------
411+
412+ fn el(&self, spec: &render::Spec) -> Element {
413+ let el = self.document.create_element(spec.tag).unwrap();
414+ for (k, v) in &spec.attrs {
415+ let _ = el.set_attribute(k, v);
416+ }
417+ el
418+ }
419+
420+ fn build_block(&mut self, m: &Model, b: &Blk) -> BView {
421+ let mut v = self.block_shell(b);
422+ if b.kind() == Kind::Rule {
423+ let _ = v.el.set_attribute("contenteditable", "false");
424+ } else {
425+ self.patch_runs(m, b, &mut v, true);
426+ }
427+ v
428+ }
429+
430+ /// The element of block `b`, without its content.
431+ fn block_shell(&mut self, b: &Blk) -> BView {
432+ let spec = render::block_spec(&b.attrs);
433+ let el = self.el(&spec);
434+ let content = match spec.inner {
435+ Some(tag) => {
436+ let c = self.document.create_element(tag).unwrap();
437+ el.append_child(&c).unwrap();
438+ c
439+ }
440+ None => el.clone(),
441+ };
442+ let _ = js_sys::Reflect::set(&el, &self.block_key, &JsValue::TRUE);
443+ self.next_uid += 1;
444+ BView { key: self.next_uid, el, content, attrs: b.attrs.clone(), runs: Vec::new(), trailing: None, dirty: None, synced: false, scale: 1.0, lines: CHUNK_LINES }
445+ }
446+
447+ /// Builds the unbuilt blocks of live page `pi` and patches its dirty ones.
448+ fn build_missing(&mut self, m: &Model, pi: usize) {
449+ let n = self.pages[pi].n;
450+ let g0 = self.page_start(pi);
451+ let blks = m.blocks(g0, g0 + n);
452+ for (k, b) in blks.iter().enumerate() {
453+ match self.pages[pi].blocks[k].take() {
454+ None => {
455+ let v = self.build_block(m, b);
456+ self.pages[pi].blocks[k] = Some(v);
457+ }
458+ Some(mut v) => {
459+ if let Some(range) = v.dirty.take() {
460+ if self.composing == Some(b.index) {
461+ self.deferred = true;
462+ } else if v.synced && range.is_some() {
463+ // Typed natively: the DOM already shows it.
464+ } else if v.attrs.kind != b.attrs.kind {
465+ let nv = self.build_block(m, b);
466+ let _ = v.el.replace_with_with_node_1(&nv.el);
467+ v = nv;
468+ } else {
469+ if v.attrs.lang != b.attrs.lang {
470+ match b.attrs.lang.as_deref().filter(|l| !l.is_empty()) {
471+ Some(l) => drop(v.el.set_attribute("data-language", l)),
472+ None => drop(v.el.remove_attribute("data-language")),
473+ }
474+ }
475+ v.attrs = b.attrs.clone();
476+ if b.kind() != Kind::Rule {
477+ let edit = range.and_then(|r| self.chunk_patch(m, b, &v, r));
478+ self.apply_runs(m, b, &mut v, edit, false);
479+ }
480+ }
481+ }
482+ v.synced = false;
483+ self.pages[pi].blocks[k] = Some(v);
484+ }
485+ }
486+ }
487+ }
488+
489+ /// The numbers of ordered lists continued from before the page: for each level of
490+ /// the first block's wrap, the number of its item there (0 when not an ordered
491+ /// list continued).
492+ fn numbers(m: &Model, g0: usize, prev: Option<&Attrs>, first: &Attrs) -> Vec<i64> {
493+ let k = keep(prev, first);
494+ let common = prev.map_or(0, |p| common(&p.wrap, &first.wrap));
495+ let new_item = k < common && first.wrap[k].is_list();
496+ let cont = if new_item { k + 1 } else { k };
497+ (0..cont).map(|l| if first.wrap[l] == Wrap::Ordered { item_number(m, g0, l) } else { 0 }).collect()
498+ }
499+
500+ /// Rebuilds the list and quote elements of live page `pi` around its blocks if
501+ /// anything they depend on changed.
502+ fn group(&mut self, m: &Model, pi: usize) {
503+ let n = self.pages[pi].n;
504+ if n == 0 || self.pages[pi].blocks.iter().any(Option::is_none) {
505+ return;
506+ }
507+ let g0 = self.page_start(pi);
508+ let prev = g0.checked_sub(1).and_then(|i| m.block(i)).map(|b| b.attrs);
509+ let next = m.block(g0 + n).map(|b| b.attrs);
510+ let page = &self.pages[pi];
511+ let first = &page.blocks[0].as_ref().unwrap().attrs;
512+ let numbers = if first.wrap.contains(&Wrap::Ordered) { Self::numbers(m, g0, prev.as_ref(), first) } else { Vec::new() };
513+ let shape = Shape {
514+ blocks: page.blocks.iter().map(|b| {
515+ let a = &b.as_ref().unwrap().attrs;
516+ (a.wrap.clone(), a.join, a.start)
517+ }).collect(),
518+ prev,
519+ next,
520+ numbers,
521+ };
522+ if shape == page.shape {
523+ return;
524+ }
525+ if shape.blocks.iter().all(|b| b.0.is_empty()) && page.el.query_selector("ul,ol,blockquote").ok().flatten().is_none() {
526+ // No containers: the blocks are the page's children; move only what is out
527+ // of place (an Enter is one insertion, not a rebuilt page).
528+ let page_el = page.el.clone();
529+ let mut cursor = page_el.first_child();
530+ for v in page.blocks.iter().flatten() {
531+ let el: &DomNode = v.el.as_ref();
532+ if cursor.as_ref() == Some(el) {
533+ cursor = el.next_sibling();
534+ } else {
535+ page_el.insert_before(el, cursor.as_ref()).unwrap();
536+ }
537+ }
538+ while let Some(c) = cursor {
539+ cursor = c.next_sibling();
540+ page_el.remove_child(&c).unwrap();
541+ }
542+ self.pages[pi].shape = shape;
543+ return;
544+ }
545+ struct Lvl {
546+ el: Element,
547+ item: Option<Element>,
548+ }
549+ let page_el = page.el.clone();
550+ page_el.set_text_content(None);
551+ let mut stack: Vec<Lvl> = Vec::new();
552+ let doc = self.document.clone();
553+ let mk = |w: Wrap, start: i64, cont: bool| -> Element {
554+ let s = render::wrap_spec(w, start);
555+ let el = doc.create_element(s.tag).unwrap();
556+ for (k, v) in &s.attrs {
557+ let _ = el.set_attribute(k, v);
558+ }
559+ if cont {
560+ el.set_class_name("pm-cont");
561+ }
562+ el
563+ };
564+ let li = |cont: bool| -> Element {
565+ let el = doc.create_element("li").unwrap();
566+ if cont {
567+ el.set_class_name("pm-cont");
568+ }
569+ el
570+ };
571+ let parent = |stack: &[Lvl]| -> Element {
572+ match stack.last() {
573+ Some(l) => l.item.clone().unwrap_or_else(|| l.el.clone()),
574+ None => page_el.clone(),
575+ }
576+ };
577+ let mut prev_attrs = shape.prev.clone();
578+ for (idx, b) in self.pages[pi].blocks.iter().enumerate() {
579+ let b = b.as_ref().unwrap();
580+ let wrap = &b.attrs.wrap;
581+ let k = keep(prev_attrs.as_ref(), &b.attrs);
582+ let common = prev_attrs.as_ref().map_or(0, |p| common(&p.wrap, wrap));
583+ let new_item = k < common && wrap[k].is_list();
584+ if idx == 0 {
585+ // Levels continued from the page before.
586+ let cont = if new_item { k + 1 } else { k };
587+ for (l, &w) in wrap.iter().enumerate().take(cont) {
588+ let start = shape.numbers.get(l).copied().filter(|&x| x > 0).unwrap_or(1);
589+ let el = mk(w, start, true);
590+ parent(&stack).append_child(&el).unwrap();
591+ let item = w.is_list().then(|| li(l < k));
592+ if let Some(i) = &item {
593+ el.append_child(i).unwrap();
594+ }
595+ stack.push(Lvl { el, item });
596+ }
597+ } else {
598+ let stay = if new_item { k + 1 } else { k };
599+ stack.truncate(stay);
600+ if new_item {
601+ let i = li(false);
602+ stack[k].el.append_child(&i).unwrap();
603+ stack[k].item = Some(i);
604+ }
605+ }
606+ let deepest = (stack.len()..wrap.len()).rev().find(|&i| wrap[i] == Wrap::Ordered);
607+ for (l, &w) in wrap.iter().enumerate().skip(stack.len()) {
608+ let start = if Some(l) == deepest { b.attrs.start.unwrap_or(1) } else { 1 };
609+ let el = mk(w, start, false);
610+ parent(&stack).append_child(&el).unwrap();
611+ let item = w.is_list().then(|| li(false));
612+ if let Some(i) = &item {
613+ el.append_child(i).unwrap();
614+ }
615+ stack.push(Lvl { el, item });
616+ }
617+ parent(&stack).append_child(&b.el).unwrap();
618+ prev_attrs = Some(b.attrs.clone());
619+ }
620+ // Levels the page after continues.
621+ if let (Some(last), Some(next)) = (&prev_attrs, &shape.next) {
622+ let k = keep(Some(last), next);
623+ let common = common(&last.wrap, &next.wrap);
624+ let new_item = k < common && next.wrap[k].is_list();
625+ for (l, lvl) in stack.iter().enumerate() {
626+ if l < k || l == k && new_item {
627+ let _ = lvl.el.class_list().add_1("pm-more");
628+ if let Some(i) = lvl.item.as_ref().filter(|_| l < k) {
629+ let _ = i.class_list().add_1("pm-more");
630+ }
631+ }
632+ }
633+ }
634+ self.pages[pi].shape = shape;
635+ }
636+
637+ /// Brings a block's runs up to date from the model. With `force` the content is
638+ /// rebuilt from scratch (used when the DOM went foreign).
639+ fn patch_runs(&mut self, m: &Model, b: &Blk, v: &mut BView, force: bool) {
640+ self.apply_runs(m, b, v, None, force);
641+ }
642+
643+ fn apply_runs(&mut self, m: &Model, b: &Blk, v: &mut BView, edit: Option<Vec<MRun>>, force: bool) {
644+ let code = b.kind() == Kind::Code;
645+ let new = match edit {
646+ Some(new) if !force => new,
647+ _ => {
648+ let mut lines = v.lines;
649+ let runs = chunk_text(model_runs(m, b), if force { &[] } else { &v.runs }, code, &mut lines);
650+ v.lines = lines;
651+ runs
652+ }
653+ };
654+ if !code && new.iter().any(|n| matches!(n, MRun::Text(_, _, true))) {
655+ // Hidden text chunks are sized from their length at this width until shown.
656+ self.text_width = self.root.client_width().max(200) as f64;
657+ }
658+ if force {
659+ v.content.set_text_content(None);
660+ v.runs.clear();
661+ v.trailing = None;
662+ }
663+ let old = std::mem::take(&mut v.runs);
664+ let content = v.content.clone();
665+ let same = |i: usize, o: &Run, n: &MRun| -> bool {
666+ match n {
667+ MRun::Keep(k) => *k == i,
668+ // `o.s` always holds what the DOM text node holds (see `Run::s`).
669+ MRun::Text(s, mk, c) => o.kind == RunKind::Text && &o.marks == mk && o.chunk == *c && o.s == *s,
670+ MRun::Other(k) => o.kind == *k,
671+ }
672+ };
673+ let mut pre = 0;
674+ while pre < old.len() && pre < new.len() && same(pre, &old[pre], &new[pre]) {
675+ pre += 1;
676+ }
677+ let mut suf = 0;
678+ while suf < old.len() - pre && suf < new.len() - pre && same(old.len() - 1 - suf, &old[old.len() - 1 - suf], &new[new.len() - 1 - suf]) {
679+ suf += 1;
680+ }
681+ let old_mid = &old[pre..old.len() - suf];
682+ let new_mid = &new[pre..new.len() - suf];
683+ let mut mid: Vec<Run> = Vec::with_capacity(new_mid.len());
684+ // One text run changed in place: keep its node so spellcheck and IME state survive.
685+ let in_place = match (old_mid, new_mid) {
686+ ([o], [MRun::Text(s, mk, c)]) if o.kind == RunKind::Text && &o.marks == mk && o.chunk == *c => Some((o, s)),
687+ _ => None,
688+ };
689+ if let Some((o, s)) = in_place {
690+ let t = o.text.clone().unwrap();
691+ replace_minimal(&t, &o.s, s);
692+ let mut px = o.px;
693+ if o.chunk && code {
694+ px = line_count(s) as f64 * CODE_LINE_PX;
695+ if o.styled.is_none() {
696+ set_lines(&o.dom, s);
697+ }
698+ }
699+ mid.push(Run { kind: RunKind::Text, len: utf16_len(s), dom: o.dom.clone(), text: Some(t), s: s.clone(), chars: s.chars().count(), marks: o.marks.clone(), chunk: o.chunk, live: o.live, inner: o.inner.clone(), near: o.near, shown: o.shown, px, styled: o.styled });
700+ } else {
701+ // New chunks replacing a shown one are shown too (the caret is likely there).
702+ let live = old_mid.iter().any(|o| o.live);
703+ for o in old_mid {
704+ if o.dom.parent_node().is_some_and(|p| p == *content) {
705+ content.remove_child(&o.dom).unwrap();
706+ }
707+ }
708+ for n in new_mid {
709+ mid.push(self.build_run(n, live, code));
710+ }
711+ }
712+ let mut old = old;
713+ let tail: Vec<Run> = old.drain(old.len() - suf..).collect();
714+ let mut runs: Vec<Run> = Vec::with_capacity(new.len());
715+ runs.extend(old.drain(..pre));
716+ runs.extend(mid);
717+ runs.extend(tail);
718+ v.runs = runs;
719+ self.fix_trailing(v);
720+ }
721+
722+ /// Adds or drops the trailing `<br>` an empty block or one ending in a line break needs.
723+ fn fix_trailing(&self, v: &mut BView) {
724+ place_runs(v);
725+ let content = v.content.clone();
726+ let need_trailing = match v.runs.last() {
727+ None => true,
728+ Some(r) => r.kind == RunKind::Break || r.kind == RunKind::Text && r.s.ends_with('\n'),
729+ };
730+ match (&v.trailing, need_trailing) {
731+ (None, true) => {
732+ let br = self.document.create_element("br").unwrap();
733+ br.set_class_name(TRAILING_BREAK);
734+ content.append_child(&br).unwrap();
735+ v.trailing = Some(br);
736+ }
737+ (Some(br), false) => {
738+ br.remove();
739+ v.trailing = None;
740+ }
741+ (Some(br), true) if br.next_sibling().is_some() => {
742+ content.append_child(br).unwrap();
743+ }
744+ _ => {}
745+ }
746+ }
747+
748+ /// The new runs of a chunked block after one plain edit, reading only the changed
749+ /// chunks' text from the model (a huge block is never copied whole per keystroke).
750+ fn chunk_patch(&self, m: &Model, b: &Blk, v: &BView, (lo, hi): (usize, usize)) -> Option<Vec<MRun>> {
751+ let runs = &v.runs;
752+ let plain = Marks::default();
753+ if runs.is_empty() || runs.iter().any(|r| !r.chunk || r.marks != plain || r.kind != RunKind::Text) {
754+ return None;
755+ }
756+ let code = b.kind() == Kind::Code;
757+ let len = b.sepu - b.startu;
758+ let tail = len.checked_sub(hi)?;
759+ let (mut i, mut a) = (0, 0);
760+ while i < runs.len() && a + runs[i].chars <= lo {
761+ a += runs[i].chars;
762+ i += 1;
763+ }
764+ let (mut j, mut kept) = (runs.len(), 0);
765+ while j > i && kept + runs[j - 1].chars <= tail {
766+ kept += runs[j - 1].chars;
767+ j -= 1;
768+ }
769+ let e = len.checked_sub(kept).filter(|&e| e >= a)?;
770+ let mid = m.text.slice(b.startu + a, b.startu + e).ok()?;
771+ if !code && mid.contains(['\n', OBJ]) {
772+ return None;
773+ }
774+ let mut out: Vec<MRun> = (0..i).map(MRun::Keep).collect();
775+ // One edited chunk stays one node until it doubles: Enter then edits it in place
776+ // instead of rebuilding it as two.
777+ let small = if code { mid.bytes().filter(|&c| c == b'\n').count() < 2 * v.lines } else { mid.len() < 2 * CHUNK_BYTES };
778+ if i + 1 == j && small && !mid.is_empty() {
779+ out.push(MRun::Text(mid, plain, true));
780+ } else {
781+ out.extend(split_chunks(&mid, &plain, code, v.lines));
782+ }
783+ out.extend((j..runs.len()).map(MRun::Keep));
784+ Some(out)
785+ }
786+
787+ fn build_run(&self, n: &MRun, live: bool, code: bool) -> Run {
788+ match n {
789+ MRun::Text(s, mk, chunk) => {
790+ let t = self.document.create_text_node(s);
791+ let mut dom: DomNode = t.clone().into();
792+ for spec in render::mark_specs(mk).iter().rev() {
793+ let w = self.el(spec);
794+ w.append_child(&dom).unwrap();
795+ dom = w.into();
796+ }
797+ let mut inner = None;
798+ let mut px = 0.0;
799+ if *chunk {
800+ let w = self.document.create_element("div").unwrap();
801+ if code {
802+ w.set_class_name("code-chunk");
803+ set_lines(&w, s);
804+ px = line_count(s) as f64 * CODE_LINE_PX;
805+ } else {
806+ w.set_class_name("text-chunk");
807+ px = utf16_len(s) as f64 * TEXT_CHAR_AREA / self.text_width;
808+ }
809+ if live {
810+ w.append_child(&dom).unwrap();
811+ }
812+ inner = Some(dom);
813+ dom = w.into();
814+ }
815+ Run { kind: RunKind::Text, len: utf16_len(s), dom, text: Some(t), s: s.clone(), chars: s.chars().count(), marks: mk.clone(), chunk: *chunk, live, inner, near: false, shown: false, px, styled: None }
816+ }
817+ MRun::Keep(_) => unreachable!("kept chunks are never rebuilt"),
818+ MRun::Other(kind) => {
819+ let el = match kind {
820+ RunKind::Image { src, alt, title } => {
821+ let el = self.el(&render::image_spec(src, alt, title.as_deref()));
822+ let _ = el.set_attribute("contenteditable", "false");
823+ match src.strip_prefix("/media/rec/") {
824+ Some(id) => self.take_span(id, el),
825+ None => el,
826+ }
827+ }
828+ _ => self.document.create_element("br").unwrap(),
829+ };
830+ Run { kind: kind.clone(), len: 1, dom: el.into(), text: None, s: String::new(), chars: 1, marks: Marks::default(), chunk: false, live: false, inner: None, near: false, shown: false, px: 0.0, styled: None }
831+ }
832+ }
833+ }
834+
835+ /// The embed of a recording take: its audio, and a button to continue the take. Its state
836+ /// comes from `takes`. Only attributes change after this, never the children or the text,
837+ /// so the editor's observer does not see the state change.
838+ fn take_span(&self, id: &str, audio: Element) -> Element {
839+ let strings = Strings::load(&self.document);
840+ let state = self.takes.borrow().get(id).cloned().unwrap_or_else(|| "absent".to_owned());
841+ let span = self.document.create_element("span").unwrap();
842+ span.set_class_name("note-take");
843+ let _ = span.set_attribute("contenteditable", "false");
844+ let _ = span.set_attribute("data-take", id);
845+ let _ = span.set_attribute("data-take-state", &state);
846+ let _ = span.set_attribute("data-recording-label", &strings.get("recordingNow"));
847+ let _ = span.set_attribute("data-lost-label", &strings.get("recordingLost"));
848+ let _ = span.append_child(&audio);
849+ let button = self.document.create_element("button").unwrap();
850+ let _ = button.set_attribute("type", "button");
851+ button.set_class_name("note-take-continue");
852+ button.set_text_content(Some(&strings.get("continueRecording")));
853+ let _ = span.append_child(&button);
854+ span
855+ }
856+
857+ // -----------------------------------------------------------------------
858+ // Flush
859+ // -----------------------------------------------------------------------
860+
861+ /// Applies the model's block splices to the DOM.
862+ pub fn flush(&mut self, m: &Model) -> bool {
863+ let splices = m.take_splices();
864+ if splices.is_empty() {
865+ return false;
866+ }
867+ let mut structural = false;
868+ for s in &splices {
869+ if let Some(c) = self.composing {
870+ if c >= s.at + s.removed {
871+ self.composing = Some(c + s.inserted - s.removed);
872+ } else if c >= s.at && !(s.removed == 1 && s.inserted == 1) {
873+ self.composing = None;
874+ }
875+ }
876+ if s.removed == 1 && s.inserted == 1 {
877+ if let Some((pi, k)) = self.locate(s.at)
878+ && let Some(Some(v)) = self.pages[pi].blocks.get_mut(k)
879+ {
880+ v.dirty = Some(match (v.dirty, s.edit) {
881+ (None, e) => e,
882+ _ => None,
883+ });
884+ }
885+ structural |= s.edit.is_none();
886+ continue;
887+ }
888+ structural = true;
889+ let quick = splices.len() == 1
890+ && self.composing.is_none()
891+ && match (s.removed, s.inserted) {
892+ (1, 2) => self.split_chunked(m, s.at) || self.keep_first(s.at, 1, 2),
893+ (2, 1) => self.join_chunked(m, s.at) || self.keep_first(s.at, 2, 1),
894+ _ => false,
895+ };
896+ if !quick {
897+ self.remove_blocks(s.at, s.removed);
898+ self.insert_blocks(s.at, s.inserted);
899+ }
900+ }
901+ if self.pages.is_empty() && m.len() > 0 {
902+ self.insert_blocks(0, m.len());
903+ }
904+ if structural {
905+ self.layout();
906+ }
907+ for pi in 0..self.pages.len() {
908+ if self.pages[pi].live {
909+ self.build_missing(m, pi);
910+ }
911+ }
912+ if structural {
913+ for pi in 0..self.pages.len() {
914+ if self.pages[pi].live {
915+ self.group(m, pi);
916+ }
917+ }
918+ }
919+ true
920+ }
921+
922+ /// Enter inside a huge chunked block: the first part keeps the element and its
923+ /// chunks, the second one's chunks move to a new element after it, and only the
924+ /// chunk holding the split is rebuilt; both halves (tens of MB) are never read back
925+ /// and rendered again. Moving a first part with shown chunks instead would take away
926+ /// the browser's scroll anchor (shown text above the caret), and the view would
927+ /// jump megapixels.
928+ fn split_chunked(&mut self, m: &Model, at: usize) -> bool {
929+ let (Some(a), Some(b)) = (m.block(at), m.block(at + 1)) else { return false };
930+ let Some((pi, k)) = self.locate(at) else { return false };
931+ let Some(Some(v)) = self.pages[pi].blocks.get(k) else { return false };
932+ let (la, lb) = (a.sepu - a.startu, b.sepu - b.startu);
933+ let text = |x: &Blk| x.kind().is_text() && x.kind() != Kind::Code;
934+ if !chunked(v) || v.dirty.is_some() || !text(&a) || !text(&b) || (v.attrs.kind != a.attrs.kind && v.attrs.kind != b.attrs.kind) {
935+ return false;
936+ }
937+ if v.runs.iter().map(|r| r.chars).sum::<usize>() != la + lb {
938+ return false;
939+ }
940+ let mut v = self.pages[pi].blocks[k].take().unwrap();
941+ let mut i = 0;
942+ let mut acc = 0;
943+ while i < v.runs.len() && acc + v.runs[i].chars <= la {
944+ acc += v.runs[i].chars;
945+ i += 1;
946+ }
947+ let mut right = v.runs.split_off(i);
948+ let mut left = std::mem::take(&mut v.runs);
949+ if acc < la {
950+ // The split falls inside this chunk: its two parts are new runs.
951+ let r = right.remove(0);
952+ r.dom.unchecked_ref::<Element>().remove();
953+ let cut = r.s.char_indices().nth(la - acc).map_or(r.s.len(), |(o, _)| o);
954+ left.push(self.build_run(&MRun::Text(r.s[..cut].to_owned(), Marks::default(), true), r.live, false));
955+ if cut < r.s.len() {
956+ right.insert(0, self.build_run(&MRun::Text(r.s[cut..].to_owned(), Marks::default(), true), r.live, false));
957+ }
958+ }
959+ // An empty first part (Enter at the block's start) moves for free.
960+ let keep_left = v.attrs.kind == a.attrs.kind && (left.iter().any(|r| r.shown) || v.attrs.kind != b.attrs.kind);
961+ let mut w = self.block_shell(if keep_left { &b } else { &a });
962+ // Both halves keep the spacer scale, so nothing moves.
963+ w.scale = v.scale;
964+ let (stay, mut moved) = if keep_left { (left, right) } else { (right, left) };
965+ unplace(&mut moved);
966+ v.runs = stay;
967+ w.runs = moved;
968+ v.attrs = if keep_left { a.attrs.clone() } else { b.attrs.clone() };
969+ self.fix_trailing(&mut v);
970+ self.fix_trailing(&mut w);
971+ let (first, second) = if keep_left { (v, w) } else { (w, v) };
972+ self.pages[pi].blocks[k] = Some(first);
973+ self.insert_blocks(at + 1, 1);
974+ // On a dead page (the next one) the second block is not shown yet.
975+ if let Some((pj, kj)) = self.locate(at + 1)
976+ && let Some(slot) = self.pages[pj].blocks.get_mut(kj)
977+ {
978+ *slot = Some(second);
979+ } else {
980+ second.el.remove();
981+ }
982+ true
983+ }
984+
985+ /// Enter or Backspace on a built block: it keeps its element, re-rendered from the
986+ /// model, and only the blocks after it are added or removed. Firefox's editor
987+ /// handles every element removed under the root, so replacing it would cost more.
988+ fn keep_first(&mut self, at: usize, removed: usize, inserted: usize) -> bool {
989+ let Some((pi, k)) = self.locate(at) else { return false };
990+ match self.pages[pi].blocks.get_mut(k) {
991+ Some(Some(v)) => v.dirty = Some(None),
992+ _ => return false,
993+ }
994+ self.remove_blocks(at + 1, removed - 1);
995+ if inserted > 1 {
996+ // On the block's own page, which is live, even when it is the page's last.
997+ self.insert_in_page(pi, k + 1, inserted - 1);
998+ }
999+ true
1000+ }
1001+
1002+ /// Backspace or Delete joining a huge chunked block with its neighbour: the one with
1003+ /// more chunks keeps its element, the other's content moves into it.
1004+ fn join_chunked(&mut self, m: &Model, at: usize) -> bool {
1005+ let Some(a) = m.block(at) else { return false };
1006+ let (Some((pi, k)), Some((pj, kj))) = (self.locate(at), self.locate(at + 1)) else { return false };
1007+ let (Some(Some(v)), Some(Some(w))) = (self.pages[pi].blocks.get(k), self.pages[pj].blocks.get(kj)) else { return false };
1008+ let plain = |x: &BView| x.runs.iter().all(|r| r.kind == RunKind::Text && r.marks == Marks::default());
1009+ if !(chunked(v) || chunked(w)) || !plain(v) || !plain(w) || v.dirty.is_some() || w.dirty.is_some() || a.kind() == Kind::Code {
1010+ return false;
1011+ }
1012+ let chars = |x: &BView| x.runs.iter().map(|r| r.chars).sum::<usize>();
1013+ if chars(v) + chars(w) != a.sepu - a.startu {
1014+ return false;
1015+ }
1016+ let host_first = match (v.attrs.kind == a.attrs.kind, w.attrs.kind == a.attrs.kind) {
1017+ (true, true) => v.runs.len() >= w.runs.len(),
1018+ (true, false) => true,
1019+ (false, true) => false,
1020+ (false, false) => return false,
1021+ };
1022+ let v = self.pages[pi].blocks[k].take().unwrap();
1023+ let w = self.pages[pj].blocks[kj].take().unwrap();
1024+ // A short plain block joining a chunked one becomes a chunk too.
1025+ let rechunk = |runs: Vec<Run>, this: &Self| -> Vec<Run> {
1026+ if runs.iter().all(|r| r.chunk) {
1027+ return runs;
1028+ }
1029+ let text: String = runs.iter().map(|r| r.s.as_str()).collect();
1030+ for r in &runs {
1031+ r.dom.unchecked_ref::<Element>().remove();
1032+ }
1033+ if text.is_empty() {
1034+ return Vec::new();
1035+ }
1036+ vec![this.build_run(&MRun::Text(text, Marks::default(), true), true, false)]
1037+ };
1038+ let (mut host, other) = if host_first { (v, w) } else { (w, v) };
1039+ let (host_runs, mut other_runs) = (rechunk(std::mem::take(&mut host.runs), self), rechunk(other.runs, self));
1040+ unplace(&mut other_runs);
1041+ let runs: Vec<Run> = if host_first { host_runs.into_iter().chain(other_runs).collect() } else { other_runs.into_iter().chain(host_runs).collect() };
1042+ other.el.remove();
1043+ host.runs = runs;
1044+ host.attrs = a.attrs.clone();
1045+ self.fix_trailing(&mut host);
1046+ self.pages[pi].blocks[k] = Some(host);
1047+ self.remove_blocks(at + 1, 1);
1048+ true
1049+ }
1050+
1051+ fn remove_blocks(&mut self, at: usize, mut n: usize) {
1052+ let Some((mut pi, mut k)) = self.locate(at) else { return };
1053+ self.pages_changed();
1054+ let mut emptied = false;
1055+ while n > 0 && pi < self.pages.len() {
1056+ let p = &mut self.pages[pi];
1057+ let take = n.min(p.n - k);
1058+ if take == p.n {
1059+ // The whole page goes, its blocks with it.
1060+ if p.attached {
1061+ p.el.remove();
1062+ }
1063+ emptied = true;
1064+ } else if p.live {
1065+ for v in p.blocks.drain(k..k + take).flatten() {
1066+ v.el.remove();
1067+ }
1068+ } else {
1069+ p.height *= (p.n - take) as f64 / p.n as f64;
1070+ }
1071+ p.n -= take;
1072+ p.shape = Shape::default();
1073+ n -= take;
1074+ pi += 1;
1075+ k = 0;
1076+ }
1077+ if emptied {
1078+ self.pages.retain(|p| p.n > 0);
1079+ }
1080+ }
1081+
1082+ fn insert_blocks(&mut self, at: usize, n: usize) {
1083+ if n == 0 {
1084+ return;
1085+ }
1086+ let (pi, k) = match self.locate(at) {
1087+ Some(l) => l,
1088+ None if self.pages.is_empty() => (0, 0),
1089+ None => {
1090+ let last = self.pages.len() - 1;
1091+ (last, self.pages[last].n)
1092+ }
1093+ };
1094+ self.pages_changed();
1095+ if n <= PAGE && !self.pages.is_empty() {
1096+ self.insert_in_page(pi, k, n);
1097+ return;
1098+ }
1099+ // Many blocks (paste, undo of a large delete, a remote import): new placeholder
1100+ // pages between the two halves of the page at the insertion point.
1101+ let mut at_page = pi;
1102+ if self.pages.is_empty() {
1103+ } else if k > 0 && k < self.pages[pi].n {
1104+ self.split_page(pi, k);
1105+ at_page = pi + 1;
1106+ } else if k > 0 {
1107+ at_page = pi + 1;
1108+ }
1109+ let mut new = Vec::with_capacity(n.div_ceil(PAGE));
1110+ let mut left = n;
1111+ while left > 0 {
1112+ let c = PAGE.min(left);
1113+ new.push(self.new_page(c, c as f64 * EST_BLOCK_PX));
1114+ left -= c;
1115+ }
1116+ self.pages.splice(at_page..at_page, new);
1117+ }
1118+
1119+ /// `n` new blocks at position `k` of page `pi`.
1120+ fn insert_in_page(&mut self, pi: usize, k: usize, n: usize) {
1121+ self.pages_changed();
1122+ let p = &mut self.pages[pi];
1123+ if p.live {
1124+ p.blocks.splice(k..k, (0..n).map(|_| None));
1125+ } else {
1126+ p.height += n as f64 * EST_BLOCK_PX;
1127+ }
1128+ p.n += n;
1129+ p.shape = Shape::default();
1130+ if p.n > 2 * PAGE {
1131+ let half = p.n / 2;
1132+ self.split_page(pi, half);
1133+ }
1134+ }
1135+
1136+ /// Splits page `pi` before its block `at`; the new page follows it, same state.
1137+ fn split_page(&mut self, pi: usize, at: usize) {
1138+ self.pages_changed();
1139+ let total = self.pages[pi].n;
1140+ let mut page = self.new_page(total - at, 0.0);
1141+ if self.pages[pi].live {
1142+ page.blocks = self.pages[pi].blocks.split_off(at);
1143+ page.live = true;
1144+ } else {
1145+ page.height = self.pages[pi].height * (total - at) as f64 / total as f64;
1146+ self.pages[pi].height -= page.height;
1147+ }
1148+ self.pages[pi].n = at;
1149+ self.pages[pi].shape = Shape::default();
1150+ self.pages.insert(pi + 1, page);
1151+ }
1152+
1153+ /// Re-renders a block from the model, discarding whatever the browser did to it.
1154+ pub fn repair(&mut self, m: &Model, i: usize) {
1155+ let Some(b) = m.block(i) else { return };
1156+ let Some((pi, k)) = self.locate(i) else { return };
1157+ let Some(mut v) = self.pages[pi].blocks.get_mut(k).and_then(Option::take) else { return };
1158+ if b.kind() != Kind::Rule {
1159+ self.patch_runs(m, &b, &mut v, true);
1160+ }
1161+ self.pages[pi].blocks[k] = Some(v);
1162+ }
1163+
1164+ /// Rebuilds the page holding DOM node `n` (the browser changed its containers).
1165+ pub fn repair_page_of(&mut self, m: &Model, n: &DomNode) {
1166+ let Some(pi) = self.page_of(n) else { return };
1167+ if self.pages[pi].live {
1168+ self.set_page_live(m, pi, false);
1169+ self.set_page_live(m, pi, true);
1170+ }
1171+ }
1172+
1173+ /// Whether the composed block changed while composing (it needs a rebuild).
1174+ pub fn take_deferred(&mut self) -> bool {
1175+ std::mem::take(&mut self.deferred)
1176+ }
1177+
1178+ /// Whether a block's DOM is exactly what the view built (no foreign nodes).
1179+ pub fn intact(&self, i: usize) -> bool {
1180+ let Some(v) = self.bview(i) else { return false };
1181+ let kids = v.content.child_nodes();
1182+ let expect = v.runs.iter().filter(|r| r.shown).count() + v.trailing.is_some() as usize;
1183+ if kids.length() as usize != expect {
1184+ return false;
1185+ }
1186+ for (i, r) in v.runs.iter().filter(|r| r.shown).enumerate() {
1187+ if kids.get(i as u32).as_ref() != Some(&r.dom) {
1188+ return false;
1189+ }
1190+ if r.chunk && !r.live {
1191+ if r.dom.has_child_nodes() {
1192+ return false;
1193+ }
1194+ continue;
1195+ }
1196+ if let Some(t) = &r.text {
1197+ if r.dom != ***t && !r.dom.contains(Some(t)) {
1198+ return false;
1199+ }
1200+ if t.length() == 0 {
1201+ return false;
1202+ }
1203+ }
1204+ }
1205+ true
1206+ }
1207+
1208+ // -----------------------------------------------------------------------
1209+ // Lookup
1210+ // -----------------------------------------------------------------------
1211+
1212+ pub fn bview(&self, i: usize) -> Option<&BView> {
1213+ let (pi, k) = self.locate(i)?;
1214+ self.pages[pi].blocks.get(k)?.as_ref()
1215+ }
1216+
1217+ fn bview_mut(&mut self, i: usize) -> Option<&mut BView> {
1218+ let (pi, k) = self.locate(i)?;
1219+ self.pages[pi].blocks.get_mut(k)?.as_mut()
1220+ }
1221+
1222+ pub fn element(&self, i: usize) -> Option<&Element> {
1223+ self.bview(i).map(|v| &v.el)
1224+ }
1225+
1226+ /// The built blocks, with their indexes.
1227+ pub fn live_blocks(&self) -> impl Iterator<Item = (usize, &BView)> {
1228+ let mut g = 0;
1229+ self.pages.iter().flat_map(move |p| {
1230+ let g0 = g;
1231+ g += p.n;
1232+ p.blocks.iter().enumerate().filter_map(move |(k, v)| v.as_ref().map(|v| (g0 + k, v)))
1233+ })
1234+ }
1235+
1236+ /// The index of the built block with `key`.
1237+ pub fn find_key(&self, key: u32) -> Option<usize> {
1238+ self.live_blocks().find(|(_, v)| v.key == key).map(|(i, _)| i)
1239+ }
1240+
1241+ fn page_index(&self, uid: u32) -> Option<usize> {
1242+ self.pages.iter().position(|p| p.uid == uid)
1243+ }
1244+
1245+ /// The page holding DOM node `n`.
1246+ fn page_of(&self, n: &DomNode) -> Option<usize> {
1247+ let mut cur = Some(n.clone());
1248+ while let Some(c) = cur {
1249+ if c == **self.root {
1250+ return None;
1251+ }
1252+ if let Some(uid) = js_sys::Reflect::get(&c, &self.page_key).ok().and_then(|v| v.as_f64()) {
1253+ return self.page_index(uid as u32);
1254+ }
1255+ cur = c.parent_node();
1256+ }
1257+ None
1258+ }
1259+
1260+ /// The block whose element holds DOM node `n` (or is it), and that element.
1261+ pub fn owner(&self, n: &DomNode) -> Option<(usize, Element)> {
1262+ let mut cur = Some(n.clone());
1263+ while let Some(c) = cur {
1264+ if c == **self.root {
1265+ return None;
1266+ }
1267+ if js_sys::Reflect::get(&c, &self.block_key).ok().is_some_and(|v| v.is_truthy()) {
1268+ let el: Element = c.unchecked_into();
1269+ let pi = self.page_of(&el)?;
1270+ let k = self.pages[pi].blocks.iter().position(|v| v.as_ref().is_some_and(|v| v.el == el))?;
1271+ return Some((self.page_start(pi) + k, el));
1272+ }
1273+ cur = c.parent_node();
1274+ }
1275+ None
1276+ }
1277+
1278+ // -----------------------------------------------------------------------
1279+ // Positions
1280+ // -----------------------------------------------------------------------
1281+
1282+ /// The DOM point for a model offset (its page must be live).
1283+ pub fn pos_to_dom(&self, m: &Model, p: Pos) -> Option<(DomNode, u32)> {
1284+ let b = m.at(p);
1285+ let v = self.bview(b.index)?;
1286+ if b.kind() == Kind::Rule {
1287+ let parent = v.el.parent_node()?;
1288+ let i = index_in(&parent, v.el.as_ref());
1289+ return Some((parent, i + u32::from(p > b.start)));
1290+ }
1291+ let off = p.saturating_sub(b.start);
1292+ let mut acc = 0;
1293+ for (i, r) in v.runs.iter().enumerate() {
1294+ if let Some(t) = &r.text {
1295+ // At a boundary the caret sits at the end of the text before it, except
1296+ // after a chunk's closing newline: that is the next chunk's first line.
1297+ let next_line = r.chunk && off == acc + r.len && i + 1 < v.runs.len();
1298+ if off <= acc + r.len && !next_line {
1299+ return Some((t.clone().into(), (off - acc) as u32));
1300+ }
1301+ } else if off == acc {
1302+ return Some((v.content.clone().into(), i as u32));
1303+ }
1304+ acc += r.len;
1305+ }
1306+ Some((v.content.clone().into(), v.runs.len() as u32))
1307+ }
1308+
1309+ /// The model offset for a DOM point, by walking the DOM (robust to foreign nodes).
1310+ pub fn dom_to_pos(&self, m: &Model, node: &DomNode, offset: u32) -> Option<Pos> {
1311+ if let Some((i, el)) = self.owner(node) {
1312+ let b = m.block(i)?;
1313+ let v = self.bview(i)?;
1314+ if b.kind() == Kind::Rule {
1315+ return Some(b.start);
1316+ }
1317+ let content: &DomNode = v.content.as_ref();
1318+ if node == AsRef::<DomNode>::as_ref(&el) && el != v.content {
1319+ // On `pre` itself: before or after its `code`.
1320+ return Some(if offset == 0 { b.start } else { b.sep });
1321+ }
1322+ let off = if v.runs.iter().any(|r| r.chunk) { chunk_offset(v, node, offset) } else { None };
1323+ let off = match off {
1324+ Some(o) => o,
1325+ None => dom_offset(content, node, offset)?,
1326+ };
1327+ return Some(b.start + off.min(b.len()));
1328+ }
1329+ let root: &DomNode = self.root.as_ref();
1330+ if node == root {
1331+ // The root's children are live pages and spacers.
1332+ let Some(child) = root.child_nodes().get(offset) else { return Some(m.last().sep) };
1333+ let pi = self.page_of(&child)?;
1334+ return m.block(self.page_start(pi)).map(|b| b.start);
1335+ }
1336+ // Between blocks, inside a page's containers.
1337+ let pi = self.page_of(node)?;
1338+ let g0 = self.page_start(pi);
1339+ let page = &self.pages[pi];
1340+ if !page.live {
1341+ return m.block(g0).map(|b| b.start);
1342+ }
1343+ let after = node.child_nodes().get(offset);
1344+ for (k, v) in page.blocks.iter().enumerate() {
1345+ let Some(v) = v else { continue };
1346+ let el: &DomNode = v.el.as_ref();
1347+ let following = match &after {
1348+ Some(a) => a == el || a.contains(Some(el)) || a.compare_document_position(el) & DomNode::DOCUMENT_POSITION_FOLLOWING != 0,
1349+ None => node.compare_document_position(el) & DomNode::DOCUMENT_POSITION_FOLLOWING != 0 && !node.contains(Some(el)),
1350+ };
1351+ if following {
1352+ return m.block(g0 + k).map(|b| b.start);
1353+ }
1354+ }
1355+ m.block(g0 + page.n - 1).map(|b| b.sep)
1356+ }
1357+
1358+ /// After the browser typed `data` into text node `t` at UTF-16 offset `at`: the run
1359+ /// cache follows, and the block's next dirty mark is skipped (DOM and model agree).
1360+ /// Returns false when `t` is not one of the block's runs.
1361+ pub fn typed(&mut self, i: usize, t: &DomNode, at: usize, data: &str) -> bool {
1362+ let Some(v) = self.bview_mut(i) else { return false };
1363+ let Some(r) = v.runs.iter_mut().find(|r| r.text.as_ref().is_some_and(|x| AsRef::<DomNode>::as_ref(x) == t)) else {
1364+ return false;
1365+ };
1366+ let at = byte_at_utf16(&r.s, at);
1367+ r.s.insert_str(at, data);
1368+ r.len += utf16_len(data);
1369+ r.chars += data.chars().count();
1370+ v.synced = true;
1371+ true
1372+ }
1373+
1374+ /// Re-reads the run caches of a block from the DOM, after the browser changed it in
1375+ /// ways only a full read-back understood.
1376+ pub fn resync(&mut self, i: usize) {
1377+ if let Some(v) = self.bview_mut(i) {
1378+ for r in v.runs.iter_mut().filter(|r| !r.chunk || r.live) {
1379+ if let Some(t) = &r.text {
1380+ r.s = t.data();
1381+ r.len = utf16_len(&r.s);
1382+ r.chars = r.s.chars().count();
1383+ }
1384+ }
1385+ }
1386+ }
1387+
1388+ /// The text the DOM shows for a block, UTF-16: our breaks as `\n`, images as
1389+ /// U+FFFC, and any element the browser made as U+FFFC too (the model wins then).
1390+ pub fn dom_text(&self, i: usize) -> Option<Vec<u16>> {
1391+ let v = self.bview(i)?;
1392+ let mut out = Vec::new();
1393+ walk(v.content.as_ref(), &mut |n| {
1394+ if let Some(ri) = v.runs.iter().position(|r| r.dom == *n) {
1395+ let r = &v.runs[ri];
1396+ match r.kind {
1397+ RunKind::Break => {
1398+ out.push(b'\n' as u16);
1399+ return true;
1400+ }
1401+ RunKind::Image { .. } => {
1402+ out.push(OBJ as u16);
1403+ return true;
1404+ }
1405+ RunKind::Text if r.chunk && !r.live => {
1406+ for r in v.runs[ri..].iter().take_while(|x| x.chunk && !x.live && (x.dom == *n || !x.shown)) {
1407+ out.extend(r.s.encode_utf16());
1408+ }
1409+ return true;
1410+ }
1411+ RunKind::Text => {}
1412+ }
1413+ }
1414+ match n.node_type() {
1415+ DomNode::TEXT_NODE => out.extend(n.node_value().unwrap_or_default().encode_utf16()),
1416+ DomNode::ELEMENT_NODE => {
1417+ let e: &Element = n.unchecked_ref();
1418+ match e.tag_name().as_str() {
1419+ "BR" if e.class_name() != TRAILING_BREAK => out.push(OBJ as u16),
1420+ "IMG" => out.push(OBJ as u16),
1421+ _ => {}
1422+ }
1423+ }
1424+ _ => {}
1425+ }
1426+ false
1427+ });
1428+ Some(out)
1429+ }
1430+
1431+ /// Shows the chunks holding (and next to) the selection ends, so the DOM selection
1432+ /// can be placed and arrow keys find text around it.
1433+ pub fn ensure_live(&mut self, m: &Model, positions: &[Pos]) {
1434+ for &p in positions {
1435+ let b = m.at(p);
1436+ let ends: Vec<usize> = positions.iter().filter(|&&q| b.holds(q)).map(|q| q - b.start).collect();
1437+ let Some(v) = self.bview_mut(b.index) else { continue };
1438+ if !v.runs.first().is_some_and(|r| r.chunk) {
1439+ continue;
1440+ }
1441+ let off = p - b.start;
1442+ let mut acc = 0;
1443+ let mut at = v.runs.len() - 1;
1444+ for (i, r) in v.runs.iter().enumerate() {
1445+ if off < acc + r.len || off == acc + r.len && i + 1 == v.runs.len() {
1446+ at = i;
1447+ break;
1448+ }
1449+ acc += r.len;
1450+ }
1451+ // Shown: what the observer reports near, plus the chunks holding a selection
1452+ // end and their neighbours. Everything else goes back to a placeholder.
1453+ let mut start = 0;
1454+ for (i, r) in v.runs.iter_mut().enumerate() {
1455+ let holds = ends.iter().any(|&o| o >= start && o <= start + r.len);
1456+ start += r.len;
1457+ let want = r.near || holds || i + 1 >= at && i <= at + 1;
1458+ set_live(r, want);
1459+ }
1460+ place_runs(v);
1461+ }
1462+ }
1463+}
1464+
1465+fn common(a: &[Wrap], b: &[Wrap]) -> usize {
1466+ a.iter().zip(b).take_while(|(x, y)| x == y).count()
1467+}
1468+
1469+/// The number of the level-`l` ordered list item holding block `g` (counting a new
1470+/// item `g` starts), walking back to where the list starts.
1471+fn item_number(m: &Model, g: usize, l: usize) -> i64 {
1472+ let Some(first) = m.block(g) else { return 1 };
1473+ let mut count = 0;
1474+ let mut cur = first.attrs;
1475+ let mut result = None;
1476+ m.scan(g, true, |_, prev| {
1477+ let k = keep(Some(prev), &cur);
1478+ if k > l {
1479+ // Same item.
1480+ } else if k == l && common(&prev.wrap, &cur.wrap) > l && cur.wrap[l].is_list() {
1481+ count += 1;
1482+ } else {
1483+ result = Some(list_start(prev, &cur, l) + count);
1484+ return false;
1485+ }
1486+ cur = prev.clone();
1487+ true
1488+ });
1489+ // Reached the first block: the list starts there.
1490+ result.unwrap_or_else(|| list_start_first(&cur, l) + count)
1491+}
1492+
1493+/// The first number of the level-`l` list `cur` opens after `prev`.
1494+fn list_start(prev: &Attrs, cur: &Attrs, l: usize) -> i64 {
1495+ let k = keep(Some(prev), cur);
1496+ let common = common(&prev.wrap, &cur.wrap);
1497+ let stay = if k < common && cur.wrap[k].is_list() { k + 1 } else { k };
1498+ let deepest = (stay..cur.wrap.len()).rev().find(|&i| cur.wrap[i] == Wrap::Ordered);
1499+ if deepest == Some(l) { cur.start.unwrap_or(1) } else { 1 }
1500+}
1501+
1502+fn list_start_first(cur: &Attrs, l: usize) -> i64 {
1503+ let deepest = (0..cur.wrap.len()).rev().find(|&i| cur.wrap[i] == Wrap::Ordered);
1504+ if deepest == Some(l) { cur.start.unwrap_or(1) } else { 1 }
1505+}
1506+
1507+fn index_in(parent: &DomNode, child: &DomNode) -> u32 {
1508+ let kids = parent.child_nodes();
1509+ (0..kids.length()).find(|&i| kids.get(i).as_ref() == Some(child)).unwrap_or(0)
1510+}
1511+
1512+/// Attaches or detaches a chunk's content (see `Run::live`).
1513+fn set_live(r: &mut Run, live: bool) {
1514+ if !r.chunk || r.live == live {
1515+ return;
1516+ }
1517+ let Some(inner) = &r.inner else { return };
1518+ if live {
1519+ let _ = r.dom.append_child(inner);
1520+ } else if inner.parent_node().is_some_and(|p| p == r.dom) {
1521+ // It keeps the height `sync_viewport` last saw (measuring here would force a
1522+ // layout in the middle of an edit).
1523+ let _ = r.dom.remove_child(inner);
1524+ }
1525+ r.live = live;
1526+}
1527+
1528+/// Depth-first walk; `f` returns true to skip a node's children.
1529+fn walk(n: &DomNode, f: &mut dyn FnMut(&DomNode) -> bool) {
1530+ let mut c = n.first_child();
1531+ while let Some(k) = c {
1532+ if !f(&k) {
1533+ walk(&k, f);
1534+ }
1535+ c = k.next_sibling();
1536+ }
1537+}
1538+
1539+/// Turns text node `t` (holding `old`) into `new` with one `replaceData` over the
1540+/// part that differs, so the caret and spellcheck state around it survive.
1541+fn replace_minimal(t: &Text, old: &str, new: &str) {
1542+ if old == new {
1543+ return;
1544+ }
1545+ let (a, b) = (old.as_bytes(), new.as_bytes());
1546+ let mut p = a.iter().zip(b).take_while(|(x, y)| x == y).count();
1547+ while !old.is_char_boundary(p) || !new.is_char_boundary(p) {
1548+ p -= 1;
1549+ }
1550+ let max_s = (a.len() - p).min(b.len() - p);
1551+ let mut q = a.iter().rev().zip(b.iter().rev()).take(max_s).take_while(|(x, y)| x == y).count();
1552+ while !old.is_char_boundary(a.len() - q) || !new.is_char_boundary(b.len() - q) {
1553+ q -= 1;
1554+ }
1555+ let at = utf16_len(&old[..p]) as u32;
1556+ let count = utf16_len(&old[p..a.len() - q]) as u32;
1557+ let _ = t.replace_data(at, count, &new[p..b.len() - q]);
1558+}
1559+
1560+/// Byte index of UTF-16 offset `off` in `s` (clamped to the end).
1561+pub fn byte_at_utf16(s: &str, off: usize) -> usize {
1562+ if s.is_ascii() {
1563+ return off.min(s.len());
1564+ }
1565+ let mut n = 0;
1566+ for (i, c) in s.char_indices() {
1567+ if n >= off {
1568+ return i;
1569+ }
1570+ n += c.len_utf16();
1571+ }
1572+ s.len()
1573+}
1574+
1575+fn node_len(n: &DomNode) -> usize {
1576+ match n.node_type() {
1577+ DomNode::TEXT_NODE => n.unchecked_ref::<web_sys::CharacterData>().length() as usize,
1578+ DomNode::ELEMENT_NODE => {
1579+ let e: &Element = n.unchecked_ref();
1580+ match e.tag_name().as_str() {
1581+ "BR" if e.class_name() != TRAILING_BREAK => 1,
1582+ "IMG" => 1,
1583+ _ => {
1584+ let mut s = 0;
1585+ let mut c = n.first_child();
1586+ while let Some(k) = c {
1587+ s += node_len(&k);
1588+ c = k.next_sibling();
1589+ }
1590+ s
1591+ }
1592+ }
1593+ }
1594+ _ => 0,
1595+ }
1596+}
1597+
1598+/// UTF-16 offset of DOM point (node, offset) inside `content`.
1599+fn dom_offset(content: &DomNode, node: &DomNode, offset: u32) -> Option<usize> {
1600+ enum Stop {
1601+ /// Inside a text node, at this offset.
1602+ Text(DomNode, usize),
1603+ /// Just before this node.
1604+ Before(DomNode),
1605+ /// Just after this node's content.
1606+ After(DomNode),
1607+ }
1608+ let stop = if node.node_type() == DomNode::TEXT_NODE {
1609+ Stop::Text(node.clone(), offset as usize)
1610+ } else {
1611+ match node.child_nodes().get(offset) {
1612+ Some(c) => Stop::Before(c),
1613+ None => Stop::After(node.clone()),
1614+ }
1615+ };
1616+ if let Stop::After(n) = &stop
1617+ && n == content
1618+ {
1619+ return Some(node_len(content));
1620+ }
1621+ fn go(n: &DomNode, stop: &Stop, acc: &mut usize) -> bool {
1622+ let mut c = n.first_child();
1623+ while let Some(k) = c {
1624+ match stop {
1625+ Stop::Text(t, o) if *t == k => {
1626+ *acc += (*o).min(node_len(&k));
1627+ return true;
1628+ }
1629+ Stop::Before(b) if *b == k => return true,
1630+ Stop::After(a) if *a == k => {
1631+ *acc += node_len(&k);
1632+ return true;
1633+ }
1634+ _ => {}
1635+ }
1636+ let target = match stop {
1637+ Stop::Text(t, _) => t,
1638+ Stop::Before(t) => t,
1639+ Stop::After(t) => t,
1640+ };
1641+ if k.contains(Some(target)) {
1642+ return go(&k, stop, acc);
1643+ }
1644+ *acc += node_len(&k);
1645+ c = k.next_sibling();
1646+ }
1647+ false
1648+ }
1649+ let mut acc = 0;
1650+ go(content, &stop, &mut acc).then_some(acc)
1651+}
1652+
1653+pub fn utf16_len(s: &str) -> usize {
1654+ note_model::flat::str_lens(s).1
1655+}
1656+
1657+enum MRun {
1658+ /// Text, its marks, and whether it is a chunk.
1659+ Text(String, Marks, bool),
1660+ /// A break or an image.
1661+ Other(RunKind),
1662+ /// Old run `i`, unchanged (chunks reuse their runs without copying text).
1663+ Keep(usize),
1664+}
1665+
1666+/// Line height of code (px), which sizes hidden code chunks.
1667+const CODE_LINE_PX: f64 = 22.0;
1668+
1669+fn line_count(s: &str) -> usize {
1670+ (s.bytes().filter(|&b| b == b'\n').count() + usize::from(!s.ends_with('\n'))).max(1)
1671+}
1672+
1673+/// Puts a block's runs in its content element: every run but hidden chunks, and for
1674+/// each run of hidden chunks one spacer (the first one) as tall as all of them. Only
1675+/// what changed touches the DOM: Firefox's editor handles every node added or removed
1676+/// right away, and lays out every child of the block on each keystroke.
1677+fn place_runs(v: &mut BView) {
1678+ let hidden = |r: &Run| r.chunk && !r.live;
1679+ if v.runs.iter().all(|r| r.shown && !hidden(r)) {
1680+ return;
1681+ }
1682+ let total: f64 = v.runs.iter().filter(|r| hidden(r)).map(|r| r.px).sum();
1683+ v.scale = rescale(v.scale, total);
1684+ let mut prev: Option<usize> = None;
1685+ let mut i = 0;
1686+ while i < v.runs.len() {
1687+ let mut j = i + 1;
1688+ let mut height = None;
1689+ if hidden(&v.runs[i]) {
1690+ let mut h = v.runs[i].px;
1691+ while j < v.runs.len() && hidden(&v.runs[j]) {
1692+ h += v.runs[j].px;
1693+ j += 1;
1694+ }
1695+ height = Some((h * v.scale).round() as i64);
1696+ }
1697+ if !v.runs[i].shown {
1698+ let next = match prev {
1699+ Some(p) => v.runs[p].dom.next_sibling(),
1700+ None => v.content.first_child(),
1701+ };
1702+ let _ = v.content.insert_before(&v.runs[i].dom, next.as_ref());
1703+ }
1704+ let r = &mut v.runs[i];
1705+ r.shown = true;
1706+ if r.chunk && r.styled != height {
1707+ let el: &Element = r.dom.unchecked_ref();
1708+ match height {
1709+ Some(h) => set_height(el, h as f64),
1710+ None if el.class_name() == "code-chunk" => set_lines(&r.dom, &r.s),
1711+ None => {
1712+ let _ = el.remove_attribute("style");
1713+ }
1714+ }
1715+ r.styled = height;
1716+ }
1717+ prev = Some(i);
1718+ for r in &mut v.runs[i + 1..j] {
1719+ if r.shown {
1720+ r.dom.unchecked_ref::<Element>().remove();
1721+ r.shown = false;
1722+ }
1723+ }
1724+ i = j;
1725+ }
1726+}
1727+
1728+/// Takes runs out of the DOM before they move to another block.
1729+fn unplace(runs: &mut [Run]) {
1730+ for r in runs.iter_mut().filter(|r| r.shown) {
1731+ r.dom.unchecked_ref::<Element>().remove();
1732+ r.shown = false;
1733+ }
1734+}
1735+
1736+/// Viewport top and bottom of run `i`; a hidden chunk's lie within its spacer.
1737+fn chunk_box(v: &BView, i: usize) -> (f64, f64) {
1738+ let mut head = i;
1739+ let mut h = 0.0;
1740+ while !v.runs[head].shown && head > 0 {
1741+ head -= 1;
1742+ h += v.runs[head].px;
1743+ }
1744+ let r = v.runs[head].dom.unchecked_ref::<Element>().get_bounding_client_rect();
1745+ if head == i && !(v.runs[i].chunk && !v.runs[i].live) {
1746+ return (r.top(), r.bottom());
1747+ }
1748+ let top = r.top() + h * v.scale;
1749+ (top, top + v.runs[i].px * v.scale)
1750+}
1751+
1752+/// A block shown as plain text chunks.
1753+fn chunked(v: &BView) -> bool {
1754+ !v.runs.is_empty() && v.runs.iter().all(|r| r.chunk && r.kind == RunKind::Text && r.marks == Marks::default())
1755+}
1756+
1757+fn model_runs(m: &Model, b: &Blk) -> Vec<MRun> {
1758+ let fb = m.read_block(b);
1759+ let mut out = Vec::with_capacity(fb.inl.len());
1760+ for i in fb.inl {
1761+ match i {
1762+ Inline::Text(s, mk) if !s.is_empty() => out.push(MRun::Text(s, mk, false)),
1763+ Inline::Text(..) => {}
1764+ Inline::HardBreak => out.push(MRun::Other(RunKind::Break)),
1765+ Inline::Image { src, alt, title } => out.push(MRun::Other(RunKind::Image { src, alt, title })),
1766+ }
1767+ }
1768+ out
1769+}
1770+
1771+/// Most the spacers add up to (px): browsers cap layout lengths (Firefox near 17.9M px),
1772+/// past which a long note could not scroll to its end.
1773+const MAX_PX: f64 = 12_000_000.0;
1774+/// Spacers may add up to this before the scale shrinks again.
1775+const HARD_PX: f64 = 16_000_000.0;
1776+
1777+/// The scale for spacers adding up to `total` px, kept while it still fits and is
1778+/// not far below what is needed: a new scale changes every spacer's height, which
1779+/// moves everything and costs a layout of all that is shown (Enter splitting a huge
1780+/// block halves it; each block added to a long note grows the total).
1781+fn rescale(scale: f64, total: f64) -> f64 {
1782+ let want = if total > MAX_PX { MAX_PX / total } else { 1.0 };
1783+ if total * scale <= HARD_PX && scale * 2.5 > want { scale } else { want }
1784+}
1785+
1786+/// Pages and chunks within this distance of the viewport (px) have their content.
1787+const NEAR_PX: f64 = 1500.0;
1788+
1789+/// The items `first..last` of `n` boxes stacked top to bottom that overlap `top..=bottom`
1790+/// (viewport coordinates). `rect(i)` is item `i`'s top and bottom.
1791+fn near_range(n: usize, rect: impl Fn(usize) -> (f64, f64), top: f64, bottom: f64) -> (usize, usize) {
1792+ let (mut lo, mut hi) = (0, n);
1793+ while lo < hi {
1794+ let mid = (lo + hi) / 2;
1795+ if rect(mid).1 < top {
1796+ lo = mid + 1;
1797+ } else {
1798+ hi = mid;
1799+ }
1800+ }
1801+ let mut last = lo;
1802+ while last < n && rect(last).0 <= bottom {
1803+ last += 1;
1804+ }
1805+ (lo, last)
1806+}
1807+
1808+/// Area (px²) one character of body text takes, for sizing hidden text chunks
1809+/// never shown yet: about 8px wide on a 26px line.
1810+const TEXT_CHAR_AREA: f64 = 8.0 * 26.0;
1811+
1812+fn set_height(el: &Element, px: f64) {
1813+ let _ = el.set_attribute("style", &format!("height:{}px", px.round()));
1814+}
1815+
1816+/// Sizes a chunk's placeholder: its number of lines.
1817+fn set_lines(el: &DomNode, s: &str) {
1818+ let _ = el.unchecked_ref::<Element>().set_attribute("style", &format!("--lines:{}", line_count(s)));
1819+}
1820+
1821+/// UTF-16 offset of DOM point (node, offset) in a chunked block, counting hidden chunks
1822+/// by their cached length. `None` when the point is outside every run.
1823+fn chunk_offset(v: &BView, node: &DomNode, offset: u32) -> Option<usize> {
1824+ let content: &DomNode = v.content.as_ref();
1825+ if node != content {
1826+ if let Some(off) = chunk_offset_hinted(v, node, offset) {
1827+ return Some(off);
1828+ }
1829+ }
1830+ if node == content {
1831+ // A shown node stands for itself and the hidden runs after it.
1832+ let kids = content.child_nodes();
1833+ let mut acc = 0;
1834+ for k in 0..offset.min(kids.length()) {
1835+ let c = kids.get(k)?;
1836+ match v.runs.iter().position(|r| r.dom == c) {
1837+ Some(ri) => {
1838+ let j = ri + 1 + v.runs[ri + 1..].iter().take_while(|r| !r.shown).count();
1839+ acc = v.runs[..j].iter().map(|r| r.len).sum();
1840+ }
1841+ None => acc += node_len(&c),
1842+ }
1843+ }
1844+ return Some(acc);
1845+ }
1846+ let mut acc = 0;
1847+ for r in &v.runs {
1848+ if r.dom == *node {
1849+ return Some(acc + if offset == 0 { 0 } else { r.len });
1850+ }
1851+ if r.dom.contains(Some(node)) {
1852+ return Some(acc + dom_offset(&r.dom, node, offset)?.min(r.len));
1853+ }
1854+ acc += r.len;
1855+ }
1856+ None
1857+}
1858+
1859+/// [`chunk_offset`] inside a run, found from the node's ancestor under the content. The
1860+/// run's index is cached on that element and checked before use: comparing every
1861+/// chunk, thousands of JS calls, took milliseconds a keystroke.
1862+fn chunk_offset_hinted(v: &BView, node: &DomNode, offset: u32) -> Option<usize> {
1863+ let key = &JsValue::from_str(RUN_KEY);
1864+ let content: &DomNode = v.content.as_ref();
1865+ let mut child = node.clone();
1866+ loop {
1867+ let parent = child.parent_node()?;
1868+ if parent == *content {
1869+ break;
1870+ }
1871+ child = parent;
1872+ }
1873+ let hint = js_sys::Reflect::get(&child, key).ok().and_then(|h| h.as_f64()).map(|h| h as usize);
1874+ let ri = match hint.filter(|&h| v.runs.get(h).is_some_and(|r| r.dom == child)) {
1875+ Some(h) => h,
1876+ None => {
1877+ let ri = v.runs.iter().position(|r| r.dom == child)?;
1878+ let _ = js_sys::Reflect::set(&child, key, &JsValue::from_f64(ri as f64));
1879+ ri
1880+ }
1881+ };
1882+ let r = &v.runs[ri];
1883+ let acc: usize = v.runs[..ri].iter().map(|r| r.len).sum();
1884+ if r.dom == *node {
1885+ return Some(acc + if offset == 0 { 0 } else { r.len });
1886+ }
1887+ Some(acc + dom_offset(&r.dom, node, offset)?.min(r.len))
1888+}
1889+
1890+/// Code blocks longer than this many lines render as chunks of at least this size:
1891+/// a line added or removed relays out the chunk it is in, so the smaller the better.
1892+const CHUNK_LINES: usize = 250;
1893+/// Chunks of one code block at most: every keystroke walks them.
1894+const MAX_CHUNKS: usize = 8000;
1895+
1896+/// Lines per chunk of a code block of `total` lines.
1897+fn code_chunk_lines(total: usize) -> usize {
1898+ total.div_ceil(MAX_CHUNKS).max(CHUNK_LINES)
1899+}
1900+/// Other blocks longer than twice this many bytes render as chunks of about this
1901+/// size, cut after a space.
1902+const CHUNK_BYTES: usize = 8 * 1024;
1903+
1904+/// Splits a huge block of one text run into chunks (code at line ends, other text
1905+/// after spaces), reusing the boundaries of the `old` runs wherever their text is
1906+/// unchanged, so an edit rebuilds only its chunk.
1907+/// `lines` is the code block's lines per chunk, set from its length.
1908+fn chunk_text(new: Vec<MRun>, old: &[Run], code: bool, lines: &mut usize) -> Vec<MRun> {
1909+ let [MRun::Text(text, marks, _)] = new.as_slice() else { return new };
1910+ let was_chunked = old.first().is_some_and(|r| r.chunk);
1911+ // Hysteresis: a chunked block goes back to one text node only well below the limit.
1912+ let big = if code {
1913+ let limit = if was_chunked { CHUNK_LINES / 2 } else { CHUNK_LINES };
1914+ text.bytes().filter(|&b| b == b'\n').nth(limit).is_some()
1915+ } else {
1916+ text.len() > if was_chunked { CHUNK_BYTES } else { 2 * CHUNK_BYTES }
1917+ };
1918+ if !big {
1919+ return new;
1920+ }
1921+ if code {
1922+ *lines = code_chunk_lines(text.bytes().filter(|&b| b == b'\n').count());
1923+ }
1924+ let sep = if code { b'\n' } else { b' ' };
1925+ let reusable = |r: &Run| r.chunk && r.kind == RunKind::Text && &r.marks == marks;
1926+ // Unchanged leading and trailing chunks, at boundaries.
1927+ let (mut a, mut i) = (0, 0);
1928+ while i < old.len() && reusable(&old[i]) && text[a..].starts_with(&old[i].s) && old[i].s.as_bytes().last() == Some(&sep) {
1929+ a += old[i].s.len();
1930+ i += 1;
1931+ }
1932+ let (mut b, mut j) = (text.len(), old.len());
1933+ while j > i && reusable(&old[j - 1]) && b - a >= old[j - 1].s.len() && text[..b].ends_with(&old[j - 1].s) {
1934+ let start = b - old[j - 1].s.len();
1935+ if start > 0 && text.as_bytes()[start - 1] != sep {
1936+ break;
1937+ }
1938+ b = start;
1939+ j -= 1;
1940+ }
1941+ let mut out: Vec<MRun> = (0..i).map(MRun::Keep).collect();
1942+ out.extend(split_chunks(&text[a..b], marks, code, *lines));
1943+ out.extend((j..old.len()).map(MRun::Keep));
1944+ out
1945+}
1946+
1947+/// Cuts text into chunks every `per` lines (code) or after CHUNK_BYTES bytes at a space.
1948+fn split_chunks(text: &str, marks: &Marks, code: bool, per: usize) -> Vec<MRun> {
1949+ let sep = if code { b'\n' } else { b' ' };
1950+ let mut out = Vec::new();
1951+ let (mut start, mut lines) = (0, 0);
1952+ for (k, c) in text.bytes().enumerate() {
1953+ if c == sep {
1954+ lines += 1;
1955+ if if code { lines == per } else { k + 1 - start >= CHUNK_BYTES } {
1956+ out.push(MRun::Text(text[start..=k].to_owned(), marks.clone(), true));
1957+ start = k + 1;
1958+ lines = 0;
1959+ }
1960+ }
1961+ }
1962+ if start < text.len() {
1963+ out.push(MRun::Text(text[start..].to_owned(), marks.clone(), true));
1964+ }
1965+ out
1966+}
crates/note-model/Cargo.tomladded+10 -0
@@ -0,0 +1,10 @@
1+[package]
2+name = "note-model"
3+version = "0.1.0"
4+edition = "2024"
5+
6+[dependencies]
7+loro = "1.17.1"
8+
9+[lints]
10+workspace = true
crates/note-model/src/blocks.rsadded+763 -0
@@ -0,0 +1,763 @@
1+//! The block structure of the body: per block its length and attributes, kept in
2+//! chunks. Lookups binary-search the chunks' prefix sums, rebuilt once after an edit,
3+//! so they cost O(log(blocks / CHUNK) + CHUNK) however long the note.
4+//!
5+//! The index follows the text only through Loro's text events (local commits and
6+//! imports alike), so it never disagrees with the doc. Lengths are exact in Unicode
7+//! scalars, Loro's event unit; UTF-16 lengths, the DOM's unit, are exact for text the
8+//! index saw inserted and recomputed from the doc for blocks that may hold astral
9+//! chars after a delete or split.
10+
11+use std::cell::{Ref, RefCell};
12+use std::collections::HashMap;
13+
14+use loro::cursor::PosType;
15+use loro::{LoroText, TextDelta};
16+use crate::flat::{Attrs, FlatBlock, SEP};
17+
18+const CHUNK: usize = 256;
19+
20+#[derive(Clone, Copy, Debug)]
21+struct Entry {
22+ len16: u32,
23+ lenu: u32,
24+ attrs: u32,
25+ /// May hold astral chars (UTF-16 and Unicode lengths can differ).
26+ wide: bool,
27+ /// `len16` must be recomputed from the doc.
28+ stale: bool,
29+}
30+
31+#[derive(Default)]
32+struct Chunk {
33+ e: Vec<Entry>,
34+ len16: usize,
35+ lenu: usize,
36+ stale: bool,
37+}
38+
39+impl Chunk {
40+ fn sum(&mut self) {
41+ self.len16 = self.e.iter().map(|e| e.len16 as usize).sum();
42+ self.lenu = self.e.iter().map(|e| e.lenu as usize).sum();
43+ self.stale = self.e.iter().any(|e| e.stale);
44+ }
45+}
46+
47+/// One block as the index knows it. Offsets are global; lengths include the separator.
48+#[derive(Clone, Copy, Debug, PartialEq, Eq)]
49+pub struct Info {
50+ pub index: usize,
51+ pub start16: usize,
52+ pub startu: usize,
53+ pub len16: usize,
54+ pub lenu: usize,
55+ attrs: u32,
56+}
57+
58+impl Info {
59+ pub fn end16(&self) -> usize {
60+ self.start16 + self.len16
61+ }
62+ pub fn endu(&self) -> usize {
63+ self.startu + self.lenu
64+ }
65+ /// Offset of the separator (the end of the content).
66+ pub fn sep16(&self) -> usize {
67+ self.start16 + self.len16 - 1
68+ }
69+ pub fn sepu(&self) -> usize {
70+ self.startu + self.lenu - 1
71+ }
72+ /// UTF-16 length of the content.
73+ pub fn content16(&self) -> usize {
74+ self.len16 - 1
75+ }
76+}
77+
78+/// Blocks `at..at + removed` were replaced by `at..at + inserted` (indexes after the
79+/// splices before it). `edit` is the range one plain text edit changed inside a single
80+/// block, in Unicode scalars from the block start after the edit.
81+#[derive(Clone, Debug, PartialEq, Eq)]
82+pub struct Splice {
83+ pub at: usize,
84+ pub removed: usize,
85+ pub inserted: usize,
86+ pub edit: Option<(usize, usize)>,
87+}
88+
89+pub struct BlockIndex {
90+ chunks: Vec<Chunk>,
91+ /// Before each chunk and after the last: (blocks, UTF-16 length, Unicode length).
92+ /// Empty when stale; every change to `chunks` clears it.
93+ prefix: RefCell<Vec<[usize; 3]>>,
94+ pool: Vec<Attrs>,
95+ ids: HashMap<Attrs, u32>,
96+ /// The last block has no separator: content after the last one, which concurrent
97+ /// edits can leave until the editor appends one.
98+ pub open: bool,
99+}
100+
101+/// Where a block lives: chunk, entry, and the block's index and start.
102+#[derive(Clone, Copy, Debug)]
103+struct At {
104+ c: usize,
105+ j: usize,
106+ index: usize,
107+ start16: usize,
108+ startu: usize,
109+}
110+
111+impl Default for BlockIndex {
112+ fn default() -> Self {
113+ let mut b = BlockIndex { chunks: Vec::new(), prefix: RefCell::default(), pool: Vec::new(), ids: HashMap::new(), open: false };
114+ b.intern(&Attrs::default());
115+ b
116+ }
117+}
118+
119+impl BlockIndex {
120+ pub fn from_blocks(blocks: &[FlatBlock], open: bool) -> Self {
121+ let mut b = BlockIndex::default();
122+ let mut entries = Vec::with_capacity(blocks.len());
123+ for f in blocks {
124+ let attrs = b.intern(&f.attrs);
125+ entries.push(Entry { len16: f.len16 as u32, lenu: f.lenu as u32, attrs, wide: f.len16 != f.lenu, stale: false });
126+ }
127+ b.open = open;
128+ b.chunks = entries
129+ .chunks(CHUNK)
130+ .map(|c| {
131+ let mut ch = Chunk { e: c.to_vec(), ..Default::default() };
132+ ch.sum();
133+ ch
134+ })
135+ .collect();
136+ b
137+ }
138+
139+ /// Reads the whole body.
140+ pub fn read(text: &LoroText) -> Self {
141+ let blocks = crate::flat::read(text);
142+ let total: usize = blocks.iter().map(|b| b.lenu).sum();
143+ let open = total > 0 && !text_ends_with_sep(text);
144+ BlockIndex::from_blocks(&blocks, open)
145+ }
146+
147+ fn intern(&mut self, a: &Attrs) -> u32 {
148+ if let Some(&i) = self.ids.get(a) {
149+ return i;
150+ }
151+ let i = self.pool.len() as u32;
152+ self.pool.push(a.clone());
153+ self.ids.insert(a.clone(), i);
154+ i
155+ }
156+
157+ fn prefix(&self) -> Ref<'_, Vec<[usize; 3]>> {
158+ if self.prefix.borrow().is_empty() {
159+ let mut p = self.prefix.borrow_mut();
160+ let mut acc = [0; 3];
161+ p.reserve(self.chunks.len() + 1);
162+ p.push(acc);
163+ for ch in &self.chunks {
164+ acc = [acc[0] + ch.e.len(), acc[1] + ch.len16, acc[2] + ch.lenu];
165+ p.push(acc);
166+ }
167+ }
168+ self.prefix.borrow()
169+ }
170+
171+ fn changed(&mut self) {
172+ self.prefix.get_mut().clear();
173+ }
174+
175+ /// The chunk holding block `i`, and the block index it starts at.
176+ fn chunk_of(&self, i: usize) -> Option<(usize, [usize; 3])> {
177+ let p = self.prefix();
178+ if i >= p.last()?[0] {
179+ return None;
180+ }
181+ let c = p.partition_point(|x| x[0] <= i) - 1;
182+ Some((c, p[c]))
183+ }
184+
185+ pub fn len(&self) -> usize {
186+ self.prefix().last().map_or(0, |p| p[0])
187+ }
188+
189+ pub fn is_empty(&self) -> bool {
190+ self.len() == 0
191+ }
192+
193+ pub fn total16(&self) -> usize {
194+ self.prefix().last().map_or(0, |p| p[1])
195+ }
196+
197+ pub fn totalu(&self) -> usize {
198+ self.prefix().last().map_or(0, |p| p[2])
199+ }
200+
201+ pub fn attrs(&self, info: &Info) -> &Attrs {
202+ &self.pool[info.attrs as usize]
203+ }
204+
205+ fn info_at(&self, a: At) -> Info {
206+ let e = self.chunks[a.c].e[a.j];
207+ Info { index: a.index, start16: a.start16, startu: a.startu, len16: e.len16 as usize, lenu: e.lenu as usize, attrs: e.attrs }
208+ }
209+
210+ /// Block `i`.
211+ pub fn get(&self, i: usize) -> Option<Info> {
212+ self.at_index(i).map(|a| self.info_at(a))
213+ }
214+
215+ fn at_index(&self, i: usize) -> Option<At> {
216+ let (c, [index, mut s16, mut su]) = self.chunk_of(i)?;
217+ let j = i - index;
218+ for e in &self.chunks[c].e[..j] {
219+ s16 += e.len16 as usize;
220+ su += e.lenu as usize;
221+ }
222+ Some(At { c, j, index: i, start16: s16, startu: su })
223+ }
224+
225+ /// The block holding UTF-16 offset `off`: a separator's offset belongs to its block
226+ /// (the end of its content). Offsets at or past the end give the last block.
227+ pub fn find16(&self, off: usize) -> Option<Info> {
228+ self.locate(off, 1).map(|a| self.info_at(a))
229+ }
230+
231+ pub fn findu(&self, off: usize) -> Option<Info> {
232+ self.locate(off, 2).map(|a| self.info_at(a))
233+ }
234+
235+ /// The block holding offset `off` in prefix measure `k` (1: UTF-16, 2: Unicode).
236+ fn locate(&self, off: usize, k: usize) -> Option<At> {
237+ let el = |e: &Entry| if k == 1 { e.len16 as usize } else { e.lenu as usize };
238+ let (c, [mut index, mut s16, mut su]) = {
239+ let p = self.prefix();
240+ let last = p.last()?;
241+ if last[0] == 0 {
242+ return None;
243+ }
244+ if off >= last[k] {
245+ let n = last[0];
246+ drop(p);
247+ return self.at_index(n - 1);
248+ }
249+ let c = p.partition_point(|x| x[k] <= off) - 1;
250+ (c, p[c])
251+ };
252+ let mut pos = if k == 1 { s16 } else { su };
253+ for (j, e) in self.chunks[c].e.iter().enumerate() {
254+ if off < pos + el(e) {
255+ return Some(At { c, j, index, start16: s16, startu: su });
256+ }
257+ index += 1;
258+ pos += el(e);
259+ s16 += e.len16 as usize;
260+ su += e.lenu as usize;
261+ }
262+ None
263+ }
264+
265+ /// Blocks from `i` on, in order.
266+ pub fn iter_from(&self, i: usize) -> impl Iterator<Item = Info> + '_ {
267+ let mut cur = self.at_index(i);
268+ std::iter::from_fn(move || {
269+ let a = cur?;
270+ let info = self.info_at(a);
271+ let mut n = At { c: a.c, j: a.j + 1, index: a.index + 1, start16: info.end16(), startu: info.endu() };
272+ while n.c < self.chunks.len() && n.j >= self.chunks[n.c].e.len() {
273+ n.c += 1;
274+ n.j = 0;
275+ }
276+ cur = (n.c < self.chunks.len()).then_some(n);
277+ Some(info)
278+ })
279+ }
280+
281+ /// Blocks before `i`, nearest first.
282+ pub fn iter_back(&self, i: usize) -> impl Iterator<Item = Info> + '_ {
283+ let mut cur = i.checked_sub(1).and_then(|k| self.at_index(k));
284+ std::iter::from_fn(move || {
285+ let a = cur?;
286+ let info = self.info_at(a);
287+ cur = (a.index > 0).then(|| {
288+ let (mut c, mut j) = (a.c, a.j);
289+ while j == 0 {
290+ c -= 1;
291+ j = self.chunks[c].e.len();
292+ }
293+ let e = self.chunks[c].e[j - 1];
294+ At { c, j: j - 1, index: a.index - 1, start16: a.start16 - e.len16 as usize, startu: a.startu - e.lenu as usize }
295+ });
296+ Some(info)
297+ })
298+ }
299+
300+ // -----------------------------------------------------------------------
301+ // Following the text
302+ // -----------------------------------------------------------------------
303+
304+ /// Applies one text event's delta. `text` is the body after the change, for the
305+ /// UTF-16 lengths of blocks that may hold astral chars.
306+ pub fn apply(&mut self, delta: &[TextDelta], text: &LoroText) -> Vec<Splice> {
307+ let mut out: Vec<Splice> = Vec::new();
308+ let mut pos = 0usize;
309+ for d in delta {
310+ match d {
311+ TextDelta::Retain { retain, attributes } => {
312+ if let Some(attrs) = attributes.as_ref().filter(|a| !a.is_empty()) {
313+ self.restyle(pos, *retain, attrs, &mut out);
314+ }
315+ pos += retain;
316+ }
317+ TextDelta::Insert { insert, attributes } => {
318+ let attrs = Attrs::from_map(attributes.as_ref());
319+ self.insert(pos, insert, &attrs, &mut out);
320+ pos += insert.chars().count();
321+ }
322+ TextDelta::Delete { delete } => self.delete(pos, *delete, &mut out),
323+ }
324+ }
325+ // An open last block left empty is no block.
326+ if self.open && self.chunks.iter().rev().find_map(|c| c.e.last()).is_some_and(|e| e.lenu == 0) {
327+ let at = self.len() - 1;
328+ self.splice_entries(at, 1, Vec::new());
329+ self.open = false;
330+ record(&mut out, Splice { at, removed: 1, inserted: 0, edit: None });
331+ }
332+ self.fix_stale(text);
333+ out
334+ }
335+
336+ /// Changes the attributes of separators, and marks blocks whose inline marks
337+ /// changed, within `len` chars from `pos`.
338+ fn restyle<S: std::hash::BuildHasher>(&mut self, pos: usize, len: usize, attrs: &HashMap<String, loro::LoroValue, S>, out: &mut Vec<Splice>) {
339+ let block_keys = attrs.keys().any(|k| crate::flat::BLOCK_KEYS.contains(&k.as_str()));
340+ let inline_keys = attrs.keys().any(|k| !crate::flat::BLOCK_KEYS.contains(&k.as_str()));
341+ let Some(mut a) = self.locate(pos, 2) else { return };
342+ let end = pos + len;
343+ loop {
344+ let e = self.chunks[a.c].e[a.j];
345+ let sep = a.startu + e.lenu as usize - 1;
346+ let has_sep = !(self.open && self.is_last(a));
347+ let mut dirty = inline_keys;
348+ if block_keys && has_sep && sep >= pos && sep < end {
349+ let mut new = self.pool[e.attrs as usize].clone();
350+ for (k, v) in attrs.iter() {
351+ new.set(k, v);
352+ }
353+ let id = self.intern(&new);
354+ if id != e.attrs {
355+ self.chunks[a.c].e[a.j].attrs = id;
356+ dirty = true;
357+ }
358+ }
359+ if dirty {
360+ record(out, Splice { at: a.index, removed: 1, inserted: 1, edit: None });
361+ }
362+ let next = a.startu + e.lenu as usize;
363+ if next >= end {
364+ break;
365+ }
366+ match self.step(a) {
367+ Some(n) => a = n,
368+ None => break,
369+ }
370+ }
371+ }
372+
373+ fn is_last(&self, a: At) -> bool {
374+ a.j + 1 == self.chunks[a.c].e.len() && self.chunks[a.c + 1..].iter().all(|c| c.e.is_empty())
375+ }
376+
377+ fn step(&self, a: At) -> Option<At> {
378+ let e = self.chunks[a.c].e[a.j];
379+ let mut n = At { c: a.c, j: a.j + 1, index: a.index + 1, start16: a.start16 + e.len16 as usize, startu: a.startu + e.lenu as usize };
380+ while n.c < self.chunks.len() && n.j >= self.chunks[n.c].e.len() {
381+ n.c += 1;
382+ n.j = 0;
383+ }
384+ (n.c < self.chunks.len()).then_some(n)
385+ }
386+
387+ fn insert(&mut self, pos: usize, s: &str, attrs: &Attrs, out: &mut Vec<Splice>) {
388+ if s.is_empty() {
389+ return;
390+ }
391+ let total = self.totalu();
392+ let pieces: Vec<&str> = s.split(SEP).collect();
393+ let new_attrs = self.intern(attrs);
394+ let entry = |p: &str| {
395+ let (lenu, len16) = crate::flat::str_lens(p);
396+ Entry { len16: len16 as u32, lenu: lenu as u32, attrs: 0, wide: len16 != lenu, stale: false }
397+ };
398+ if pos >= total && !self.open {
399+ // After the last separator: new blocks, the last one open unless `s` ends a block.
400+ let mut es: Vec<Entry> = pieces.iter().map(|p| entry(p)).collect();
401+ let n = es.len();
402+ for (i, e) in es.iter_mut().enumerate() {
403+ if i + 1 < n {
404+ e.attrs = new_attrs;
405+ e.len16 += 1;
406+ e.lenu += 1;
407+ }
408+ }
409+ if es.last().is_some_and(|e| e.lenu == 0) {
410+ es.pop();
411+ } else {
412+ self.open = true;
413+ }
414+ let at = self.len();
415+ let inserted = es.len();
416+ self.splice_entries(at, 0, es);
417+ record(out, Splice { at, removed: 0, inserted, edit: None });
418+ return;
419+ }
420+ let a = self.locate(pos, 2).expect("insert inside the body");
421+ let old = self.chunks[a.c].e[a.j];
422+ let inner = pos - a.startu;
423+ if pieces.len() == 1 {
424+ let e = &mut self.chunks[a.c].e[a.j];
425+ let add = entry(s);
426+ e.len16 += add.len16;
427+ e.lenu += add.lenu;
428+ e.wide |= add.wide;
429+ let lo = inner;
430+ let hi = inner + add.lenu as usize;
431+ self.chunks[a.c].sum();
432+ self.changed();
433+ record(out, Splice { at: a.index, removed: 1, inserted: 1, edit: Some((lo, hi)) });
434+ return;
435+ }
436+ // The block splits: its head plus the first piece ends at the first new
437+ // separator; the last piece plus its tail keeps its own separator.
438+ let head16 = if old.wide { None } else { Some(inner) };
439+ let mut es: Vec<Entry> = Vec::with_capacity(pieces.len());
440+ for (i, p) in pieces.iter().enumerate() {
441+ let mut e = entry(p);
442+ if i + 1 < pieces.len() {
443+ e.len16 += 1;
444+ e.lenu += 1;
445+ e.attrs = new_attrs;
446+ } else {
447+ e.attrs = old.attrs;
448+ }
449+ es.push(e);
450+ }
451+ let tailu = old.lenu as usize - inner;
452+ {
453+ let first = &mut es[0];
454+ first.lenu += inner as u32;
455+ match head16 {
456+ Some(h) => first.len16 += h as u32,
457+ None => {
458+ first.wide = true;
459+ first.stale = true;
460+ }
461+ }
462+ }
463+ {
464+ let last = es.last_mut().unwrap();
465+ last.lenu += tailu as u32;
466+ match head16 {
467+ Some(h) => last.len16 += old.len16 - h as u32,
468+ None => {
469+ last.wide = true;
470+ last.stale = true;
471+ }
472+ }
473+ }
474+ let inserted = es.len();
475+ self.splice_entries(a.index, 1, es);
476+ record(out, Splice { at: a.index, removed: 1, inserted, edit: None });
477+ }
478+
479+ fn delete(&mut self, pos: usize, mut n: usize, out: &mut Vec<Splice>) {
480+ let Some(a) = self.locate(pos, 2) else { return };
481+ let inner = pos - a.startu;
482+ let first = self.chunks[a.c].e[a.j];
483+ if inner + n < first.lenu as usize {
484+ // Within one block's content.
485+ let e = &mut self.chunks[a.c].e[a.j];
486+ e.lenu -= n as u32;
487+ if e.wide {
488+ e.stale = true;
489+ } else {
490+ e.len16 -= n as u32;
491+ }
492+ self.chunks[a.c].sum();
493+ self.changed();
494+ record(out, Splice { at: a.index, removed: 1, inserted: 1, edit: Some((inner, inner)) });
495+ return;
496+ }
497+ // Spans a separator: the blocks merge into one ending in the last one's.
498+ let mut merged = Entry { len16: 0, lenu: inner as u32, attrs: first.attrs, wide: first.wide, stale: first.wide };
499+ if !first.wide {
500+ merged.len16 = inner as u32;
501+ }
502+ let mut removed = 0;
503+ let (mut c, mut j) = (a.c, a.j);
504+ let mut tail_open = false;
505+ let mut rest_in_block = first.lenu as usize - inner;
506+ let mut cur = first;
507+ loop {
508+ removed += 1;
509+ if n < rest_in_block {
510+ // The deletion ends inside `cur`: its remainder and separator stay.
511+ let keep = rest_in_block - n;
512+ merged.lenu += keep as u32;
513+ merged.attrs = cur.attrs;
514+ if cur.wide || merged.wide {
515+ merged.wide = true;
516+ merged.stale = true;
517+ } else {
518+ merged.len16 += keep as u32;
519+ }
520+ break;
521+ }
522+ n -= rest_in_block;
523+ j += 1;
524+ loop {
525+ // Next block; whole chunks inside the deletion are skipped at once.
526+ while c < self.chunks.len() && j >= self.chunks[c].e.len() {
527+ c += 1;
528+ j = 0;
529+ }
530+ if c >= self.chunks.len() || j > 0 || n < self.chunks[c].lenu {
531+ break;
532+ }
533+ removed += self.chunks[c].e.len();
534+ n -= self.chunks[c].lenu;
535+ j = self.chunks[c].e.len();
536+ }
537+ if c >= self.chunks.len() {
538+ // Deleted through the last separator: the head is left without one.
539+ tail_open = true;
540+ break;
541+ }
542+ cur = self.chunks[c].e[j];
543+ rest_in_block = cur.lenu as usize;
544+ }
545+ if tail_open {
546+ // No separator, so no attributes.
547+ merged.attrs = 0;
548+ }
549+ let es = if tail_open && merged.lenu == 0 { Vec::new() } else { vec![merged] };
550+ if tail_open {
551+ self.open = !es.is_empty();
552+ }
553+ let inserted = es.len();
554+ self.splice_entries(a.index, removed, es);
555+ record(out, Splice { at: a.index, removed, inserted, edit: None });
556+ }
557+
558+ /// Replaces `removed` entries from block `at` with `new`.
559+ fn splice_entries(&mut self, at: usize, removed: usize, new: Vec<Entry>) {
560+ self.changed();
561+ if self.chunks.is_empty() {
562+ self.chunks.push(Chunk::default());
563+ }
564+ let (mut c, mut k) = (0, 0);
565+ while c + 1 < self.chunks.len() && at >= k + self.chunks[c].e.len() {
566+ k += self.chunks[c].e.len();
567+ c += 1;
568+ }
569+ let j = at - k;
570+ let take = removed.min(self.chunks[c].e.len() - j);
571+ self.chunks[c].e.splice(j..j + take, new);
572+ let mut left = removed - take;
573+ let mut d = c + 1;
574+ while left > 0 && d < self.chunks.len() {
575+ let t = left.min(self.chunks[d].e.len());
576+ self.chunks[d].e.drain(..t);
577+ self.chunks[d].sum();
578+ left -= t;
579+ d += 1;
580+ }
581+ if self.chunks[c].e.len() > 2 * CHUNK {
582+ let all = std::mem::take(&mut self.chunks[c].e);
583+ let pieces: Vec<Chunk> = all
584+ .chunks(CHUNK)
585+ .map(|p| {
586+ let mut ch = Chunk { e: p.to_vec(), ..Default::default() };
587+ ch.sum();
588+ ch
589+ })
590+ .collect();
591+ self.chunks.splice(c..c + 1, pieces);
592+ } else {
593+ self.chunks[c].sum();
594+ }
595+ if self.chunks[c..d.min(self.chunks.len())].iter().any(|ch| ch.e.is_empty()) {
596+ self.chunks.retain(|ch| !ch.e.is_empty());
597+ if self.chunks.is_empty() {
598+ self.chunks.push(Chunk::default());
599+ }
600+ }
601+ }
602+
603+ /// Recomputes the UTF-16 lengths marked stale, from the doc.
604+ fn fix_stale(&mut self, text: &LoroText) {
605+ if !self.chunks.iter().any(|c| c.stale) {
606+ return;
607+ }
608+ self.changed();
609+ let mut startu = 0;
610+ for c in 0..self.chunks.len() {
611+ if !self.chunks[c].stale {
612+ startu += self.chunks[c].lenu;
613+ continue;
614+ }
615+ for j in 0..self.chunks[c].e.len() {
616+ let e = self.chunks[c].e[j];
617+ if e.stale {
618+ let conv = |u: usize| text.convert_pos(u, PosType::Unicode, PosType::Utf16).unwrap_or(u);
619+ let len16 = conv(startu + e.lenu as usize) - conv(startu);
620+ let e = &mut self.chunks[c].e[j];
621+ e.len16 = len16 as u32;
622+ e.wide = len16 != e.lenu as usize;
623+ e.stale = false;
624+ }
625+ startu += e.lenu as usize;
626+ }
627+ self.chunks[c].sum();
628+ }
629+ }
630+
631+ /// Checks the index against the doc (tests).
632+ #[doc(hidden)]
633+ pub fn check(&self, text: &LoroText) {
634+ let fresh = BlockIndex::read(text);
635+ let mine: Vec<(usize, usize, Attrs)> = self.iter_from(0).map(|i| (i.len16, i.lenu, self.attrs(&i).clone())).collect();
636+ let theirs: Vec<(usize, usize, Attrs)> = fresh.iter_from(0).map(|i| (i.len16, i.lenu, fresh.attrs(&i).clone())).collect();
637+ assert_eq!(mine, theirs);
638+ assert_eq!(self.open, fresh.open);
639+ let fwd: Vec<Info> = self.iter_from(0).collect();
640+ let mut back: Vec<Info> = self.iter_back(self.len()).collect();
641+ back.reverse();
642+ assert_eq!(fwd, back);
643+ }
644+}
645+
646+fn text_ends_with_sep(text: &LoroText) -> bool {
647+ let n = text.len_unicode();
648+ n > 0 && text.slice(n - 1, n).is_ok_and(|s| s.starts_with(SEP))
649+}
650+
651+/// Appends a splice, merging it into the previous one when they touch.
652+fn record(out: &mut Vec<Splice>, s: Splice) {
653+ if let Some(last) = out.last_mut()
654+ && s.at >= last.at
655+ && s.at <= last.at + last.inserted
656+ {
657+ let ov = (s.at + s.removed).min(last.at + last.inserted) - s.at;
658+ last.removed += s.removed - ov;
659+ last.inserted = last.inserted - ov + s.inserted;
660+ last.edit = None;
661+ return;
662+ }
663+ out.push(s);
664+}
665+
666+#[cfg(test)]
667+mod tests {
668+ use std::sync::{Arc, Mutex};
669+
670+ use loro::{ContainerTrait, LoroDoc, LoroValue};
671+
672+ use super::*;
673+ use crate::flat::{KEY_KIND, KEY_WRAP};
674+
675+ struct Rng(u64);
676+ impl Rng {
677+ fn next(&mut self, n: usize) -> usize {
678+ self.0 ^= self.0 << 13;
679+ self.0 ^= self.0 >> 7;
680+ self.0 ^= self.0 << 17;
681+ (self.0 % n.max(1) as u64) as usize
682+ }
683+ }
684+
685+ #[test]
686+ fn follows_random_edits() {
687+ let doc = LoroDoc::new();
688+ doc.config_text_style(crate::schema::text_style_config());
689+ let text = doc.get_text("body");
690+ text.insert(0, "\u{2029}").unwrap();
691+ doc.commit();
692+ let mut index = BlockIndex::read(&text);
693+ let events: Arc<Mutex<Vec<Vec<TextDelta>>>> = Arc::default();
694+ let ev = events.clone();
695+ let _sub = doc.subscribe(
696+ &text.id(),
697+ Arc::new(move |e| {
698+ for d in e.events {
699+ if let loro::event::Diff::Text(delta) = d.diff {
700+ ev.lock().unwrap().push(delta);
701+ }
702+ }
703+ }),
704+ );
705+ let pieces = ["a", "bc", "\u{2029}", "x\u{2029}y", "😀", "é😀\u{2029}", "\u{2029}\u{2029}", "long text here"];
706+ let mut rng = Rng(0x9e3779b97f4a7c15);
707+ let mut log: Vec<String> = Vec::new();
708+ for step in 0..3000 {
709+ let n = text.len_unicode();
710+ let before = format!("{:?}", text.to_delta());
711+ match rng.next(6) {
712+ 0 | 1 => {
713+ let at = rng.next(n + 1);
714+ let p = pieces[rng.next(pieces.len())];
715+ log.push(format!("insert {at} {p:?}"));
716+ text.insert(at, p).unwrap();
717+ }
718+ 2 if n > 1 => {
719+ let at = rng.next(n);
720+ let len = 1 + rng.next((n - at).min(12));
721+ log.push(format!("delete {at} {len}"));
722+ text.delete(at, len).unwrap();
723+ }
724+ 3 if n > 0 => {
725+ let at = rng.next(n);
726+ let len = 1 + rng.next((n - at).min(20));
727+ let (key, v): (&str, LoroValue) = match rng.next(3) {
728+ 0 => (KEY_KIND, "h2".into()),
729+ 1 => (KEY_WRAP, "uq".into()),
730+ _ => ("strong", true.into()),
731+ };
732+ log.push(format!("mark {at}..{} {key} {v:?}", at + len));
733+ if rng.next(4) == 0 {
734+ text.unmark(at..at + len, key).unwrap();
735+ } else {
736+ text.mark(at..at + len, key, v).unwrap();
737+ }
738+ }
739+ _ => {}
740+ }
741+ doc.commit();
742+ let evs: Vec<Vec<TextDelta>> = events.lock().unwrap().drain(..).collect();
743+ for delta in &evs {
744+ let before = index.len();
745+ let mut count = before;
746+ for sp in index.apply(delta, &text) {
747+ assert!(sp.at + sp.removed <= count, "splice past the end at step {step}");
748+ count = count - sp.removed + sp.inserted;
749+ }
750+ assert_eq!(count, index.len(), "splices add up at step {step}");
751+ }
752+ let fresh = BlockIndex::read(&text);
753+ let a: Vec<_> = index.iter_from(0).map(|i| (i.len16, i.lenu, index.attrs(&i).clone())).collect();
754+ let b: Vec<_> = fresh.iter_from(0).map(|i| (i.len16, i.lenu, fresh.attrs(&i).clone())).collect();
755+ if a != b {
756+ eprintln!("BEFORE {before}\nOP {}\nEVENTS {evs:?}\nAFTER {:?}", log.last().unwrap(), text.to_delta());
757+ }
758+ index.check(&text);
759+ assert_eq!(index.totalu(), text.len_unicode(), "step {step}");
760+ assert_eq!(index.total16(), text.len_utf16(), "step {step}");
761+ }
762+ }
763+}
crates/note-model/src/flat.rsadded+655 -0
@@ -0,0 +1,655 @@
1+//! The note layout: one LoroText, `doc.get_text("body")`.
2+//!
3+//! Every block is its content followed by [`SEP`], so a body always ends with one; a
4+//! fresh note is a single `SEP` (one empty paragraph). Inside a block `'\n'` is a hard
5+//! break, or a newline in code. An image is [`OBJ`] under an `image` mark. Inline marks
6+//! (`strong`, `em`, `code`, `link`) may span separators (one mark over a styled run of
7+//! blocks); readers ignore them there.
8+//!
9+//! Block attributes are marks read from the separator only, all with expand None:
10+//! - `b`: `"h1"`..`"h6"`, `"code"` or `"hr"`; absent for a paragraph.
11+//! - `lang`: the language of a code block.
12+//! - `wrap`: the containers around the block, outermost first, one char per level:
13+//! `q` blockquote, `u` bullet list, `o` ordered list.
14+//! - `join`: how many levels the block shares with the previous one, when that is not
15+//! the default (see [`default_join`]).
16+//! - `start`: the number of an ordered list the block opens, when not 1.
17+//!
18+//! Marks of equal value on consecutive separators are one mark over the whole run, so
19+//! a long list is a single `wrap` mark. Content chars inside that range carry the mark
20+//! too, which readers ignore.
21+
22+use std::collections::HashMap;
23+
24+use loro::{LoroDoc, LoroResult, LoroText, LoroValue, TextDelta};
25+
26+use crate::marks::Marks;
27+use crate::tree::value_str;
28+use crate::write::{Block, Inline, apply_marks};
29+
30+pub const BODY: &str = "body";
31+/// Ends every block.
32+pub const SEP: char = '\u{2029}';
33+pub const SEP_STR: &str = "\u{2029}";
34+/// An image's place in the text; its attributes are the `image` mark.
35+pub const OBJ: char = '\u{FFFC}';
36+
37+pub const KEY_KIND: &str = "b";
38+pub const KEY_LANG: &str = "lang";
39+pub const KEY_WRAP: &str = "wrap";
40+pub const KEY_JOIN: &str = "join";
41+pub const KEY_START: &str = "start";
42+pub const KEY_IMAGE: &str = "image";
43+/// Every key that lives on separators.
44+pub const BLOCK_KEYS: [&str; 5] = [KEY_KIND, KEY_LANG, KEY_WRAP, KEY_JOIN, KEY_START];
45+
46+pub fn body(doc: &LoroDoc) -> LoroText {
47+ doc.get_text(BODY)
48+}
49+
50+#[derive(Clone, Copy, PartialEq, Eq, Hash, Debug, Default)]
51+pub enum Kind {
52+ #[default]
53+ Para,
54+ Heading(u8),
55+ Code,
56+ Rule,
57+}
58+
59+impl Kind {
60+ pub fn from_value(v: Option<&LoroValue>) -> Kind {
61+ let Some(s) = v.and_then(|v| v.as_string()) else { return Kind::Para };
62+ match s.as_str() {
63+ "code" => Kind::Code,
64+ "hr" => Kind::Rule,
65+ h if h.len() == 2 && h.starts_with('h') => match h.as_bytes()[1] {
66+ n @ b'1'..=b'6' => Kind::Heading(n - b'0'),
67+ _ => Kind::Para,
68+ },
69+ _ => Kind::Para,
70+ }
71+ }
72+
73+ pub fn value(self) -> Option<LoroValue> {
74+ let s = match self {
75+ Kind::Para => return None,
76+ Kind::Heading(n) => ["h1", "h2", "h3", "h4", "h5", "h6"][n.clamp(1, 6) as usize - 1],
77+ Kind::Code => "code",
78+ Kind::Rule => "hr",
79+ };
80+ Some(s.into())
81+ }
82+
83+ /// Whether the block holds editable inline content.
84+ pub fn is_text(self) -> bool {
85+ self != Kind::Rule
86+ }
87+}
88+
89+#[derive(Clone, Copy, PartialEq, Eq, Hash, Debug)]
90+pub enum Wrap {
91+ Quote,
92+ Bullet,
93+ Ordered,
94+}
95+
96+impl Wrap {
97+ pub fn is_list(self) -> bool {
98+ self != Wrap::Quote
99+ }
100+
101+ fn char(self) -> char {
102+ match self {
103+ Wrap::Quote => 'q',
104+ Wrap::Bullet => 'u',
105+ Wrap::Ordered => 'o',
106+ }
107+ }
108+
109+ fn from_char(c: char) -> Option<Wrap> {
110+ match c {
111+ 'q' => Some(Wrap::Quote),
112+ 'u' => Some(Wrap::Bullet),
113+ 'o' => Some(Wrap::Ordered),
114+ _ => None,
115+ }
116+ }
117+}
118+
119+pub fn wrap_from_value(v: Option<&LoroValue>) -> Vec<Wrap> {
120+ v.and_then(|v| v.as_string()).map(|s| s.chars().filter_map(Wrap::from_char).collect()).unwrap_or_default()
121+}
122+
123+pub fn wrap_value(wrap: &[Wrap]) -> Option<LoroValue> {
124+ (!wrap.is_empty()).then(|| wrap.iter().map(|w| w.char()).collect::<String>().into())
125+}
126+
127+/// The attributes of a block, from its separator.
128+#[derive(Clone, PartialEq, Eq, Hash, Debug, Default)]
129+pub struct Attrs {
130+ pub kind: Kind,
131+ pub lang: Option<String>,
132+ pub wrap: Vec<Wrap>,
133+ pub join: Option<usize>,
134+ pub start: Option<i64>,
135+}
136+
137+impl Attrs {
138+ pub fn from_map<S: std::hash::BuildHasher>(attrs: Option<&HashMap<String, LoroValue, S>>) -> Attrs {
139+ let mut out = Attrs::default();
140+ for (k, v) in attrs.into_iter().flatten() {
141+ out.set(k, v);
142+ }
143+ out
144+ }
145+
146+ /// Applies one key of a separator's marks; null or a foreign key clears or does
147+ /// nothing. Returns whether `key` is a block key.
148+ pub fn set(&mut self, key: &str, v: &LoroValue) -> bool {
149+ let num = |v: &LoroValue| match v {
150+ LoroValue::I64(i) => Some(*i),
151+ LoroValue::Double(d) => Some(*d as i64),
152+ _ => None,
153+ };
154+ match key {
155+ KEY_KIND => self.kind = Kind::from_value(Some(v)),
156+ KEY_LANG => self.lang = value_str(v).filter(|l| !l.is_empty()),
157+ KEY_WRAP => self.wrap = wrap_from_value(Some(v)),
158+ KEY_JOIN => self.join = num(v).map(|j| j.max(0) as usize),
159+ KEY_START => self.start = num(v),
160+ _ => return false,
161+ }
162+ true
163+ }
164+
165+ /// The value of each of [`BLOCK_KEYS`], None when unset.
166+ pub fn values(&self) -> [Option<LoroValue>; 5] {
167+ [
168+ self.kind.value(),
169+ self.lang.as_deref().map(LoroValue::from),
170+ wrap_value(&self.wrap),
171+ self.join.map(|j| LoroValue::from(j as i64)),
172+ self.start.filter(|&s| s != 1).map(LoroValue::from),
173+ ]
174+ }
175+}
176+
177+/// One block of the body: its attributes and content. Code content is one text run.
178+#[derive(Clone, PartialEq, Debug, Default)]
179+pub struct FlatBlock {
180+ pub attrs: Attrs,
181+ pub inl: Vec<Inline>,
182+ /// UTF-16 length including the separator.
183+ pub len16: usize,
184+ /// Unicode scalars including the separator (Loro's text positions).
185+ pub lenu: usize,
186+}
187+
188+impl FlatBlock {
189+ pub fn plain(&self) -> String {
190+ let mut s = String::new();
191+ for i in &self.inl {
192+ match i {
193+ Inline::Text(t, _) => s.push_str(t),
194+ Inline::HardBreak => s.push('\n'),
195+ Inline::Image { .. } => {}
196+ }
197+ }
198+ s
199+ }
200+}
201+
202+/// How many levels a block shares with the previous one when its `join` is unset:
203+/// within the common wrap prefix, everything above the deepest list, so the block is
204+/// the next item of that list. Without a list in common, the whole common prefix.
205+pub fn default_join(prev: &[Wrap], cur: &[Wrap]) -> usize {
206+ let common = prev.iter().zip(cur).take_while(|(a, b)| a == b).count();
207+ match cur[..common].iter().rposition(|w| w.is_list()) {
208+ Some(d) => d,
209+ None => common,
210+ }
211+}
212+
213+// ---------------------------------------------------------------------------
214+// Reading
215+// ---------------------------------------------------------------------------
216+
217+/// Unicode scalars and UTF-16 units of `s`. ASCII, nearly all text, counts as bytes.
218+pub fn str_lens(s: &str) -> (usize, usize) {
219+ // Lead bytes count chars, 4-byte leads count surrogate pairs; ASCII chunks are skipped.
220+ let (mut unicode, mut wide) = (0, 0);
221+ for c in s.as_bytes().chunks(4096) {
222+ if c.is_ascii() {
223+ unicode += c.len();
224+ continue;
225+ }
226+ for &b in c {
227+ unicode += ((b as i8) >= -0x40) as usize;
228+ wide += (b >= 0xF0) as usize;
229+ }
230+ }
231+ (unicode, unicode + wide)
232+}
233+
234+/// Every block of the body.
235+pub fn read(text: &LoroText) -> Vec<FlatBlock> {
236+ read_delta(text.to_delta())
237+}
238+
239+pub fn read_doc(doc: &LoroDoc) -> Vec<FlatBlock> {
240+ read(&body(doc))
241+}
242+
243+/// Blocks from rich-text delta runs, split at separators. Content after the last
244+/// separator, which concurrent edits can leave, is a last paragraph.
245+pub fn read_delta(delta: Vec<TextDelta>) -> Vec<FlatBlock> {
246+ let mut out = Vec::new();
247+ let mut cur = FlatBlock::default();
248+ // The current block's text in runs of equal marks, split into inlines once its
249+ // separator gives its kind: a code block stays one text however many lines it has.
250+ let mut runs: Vec<(String, Marks, Option<LoroValue>)> = Vec::new();
251+ for d in delta {
252+ let TextDelta::Insert { insert, attributes } = d else { continue };
253+ let attrs = attributes.as_ref();
254+ let marks = attrs.map(Marks::from_attrs).unwrap_or_default();
255+ let image = attrs.and_then(|a| a.get(KEY_IMAGE)).filter(|v| !matches!(v, LoroValue::Null));
256+ for (i, piece) in insert.split(SEP).enumerate() {
257+ if i > 0 {
258+ cur.attrs = Attrs::from_map(attrs);
259+ cur.len16 += 1;
260+ cur.lenu += 1;
261+ finish_block(&mut cur, &mut runs);
262+ out.push(std::mem::take(&mut cur));
263+ }
264+ if piece.is_empty() {
265+ continue;
266+ }
267+ let (u, u16) = str_lens(piece);
268+ cur.len16 += u16;
269+ cur.lenu += u;
270+ match runs.last_mut() {
271+ Some((t, m, img)) if *m == marks && img.as_ref() == image => t.push_str(piece),
272+ _ => runs.push((piece.to_owned(), marks.clone(), image.cloned())),
273+ }
274+ }
275+ }
276+ if !runs.is_empty() {
277+ finish_block(&mut cur, &mut runs);
278+ out.push(cur);
279+ }
280+ out
281+}
282+
283+/// Turns the text `runs` of a block into its inlines. A code block's is its plain text.
284+fn finish_block(b: &mut FlatBlock, runs: &mut Vec<(String, Marks, Option<LoroValue>)>) {
285+ if b.attrs.kind == Kind::Code {
286+ let mut text = String::new();
287+ for (t, _, image) in runs.drain(..) {
288+ match image {
289+ Some(_) => text.extend(t.chars().filter(|&c| c != OBJ)),
290+ None if text.is_empty() => text = t,
291+ None => text.push_str(&t),
292+ }
293+ }
294+ if !text.is_empty() {
295+ b.inl.push(Inline::Text(text, Marks::default()));
296+ }
297+ return;
298+ }
299+ for (t, marks, image) in runs.drain(..) {
300+ push_piece(b, &t, &marks, image.as_ref());
301+ }
302+}
303+
304+fn push_piece(b: &mut FlatBlock, piece: &str, marks: &Marks, image: Option<&LoroValue>) {
305+ let text = |s: &str, b: &mut FlatBlock| {
306+ if s.is_empty() {
307+ return;
308+ }
309+ match b.inl.last_mut() {
310+ Some(Inline::Text(t, m)) if m == marks => t.push_str(s),
311+ _ => b.inl.push(Inline::Text(s.to_owned(), marks.clone())),
312+ }
313+ };
314+ let mut rest = piece;
315+ loop {
316+ let stop = rest.find(|c| c == '\n' || (c == OBJ && image.is_some()));
317+ let Some(at) = stop else {
318+ text(rest, b);
319+ return;
320+ };
321+ text(&rest[..at], b);
322+ let c = rest[at..].chars().next().unwrap();
323+ if c == '\n' {
324+ b.inl.push(Inline::HardBreak);
325+ } else if let Some(v) = image {
326+ let get = |k: &str| v.get_by_key(k).and_then(value_str);
327+ b.inl.push(Inline::Image {
328+ src: get("src").unwrap_or_default(),
329+ alt: get("alt").unwrap_or_default(),
330+ title: get("title").filter(|t| !t.is_empty()),
331+ });
332+ }
333+ rest = &rest[at + c.len_utf8()..];
334+ }
335+}
336+
337+/// Rebuilds the block tree from flat blocks.
338+pub fn nest(blocks: &[FlatBlock]) -> Vec<Block> {
339+ // The open containers, outermost first: their wrap and the blocks so far. A list
340+ // collects items; `Open::items` holds them, the last one open.
341+ struct Open {
342+ wrap: Wrap,
343+ start: i64,
344+ items: Vec<Vec<Block>>,
345+ }
346+ fn close(open: Open) -> Block {
347+ match open.wrap {
348+ Wrap::Quote => Block::Quote(open.items.into_iter().next().unwrap_or_default()),
349+ w => Block::List { ordered: w == Wrap::Ordered, start: open.start, items: open.items },
350+ }
351+ }
352+ fn target<'a>(root: &'a mut Vec<Block>, stack: &'a mut [Open]) -> &'a mut Vec<Block> {
353+ match stack.last_mut() {
354+ Some(o) => o.items.last_mut().unwrap(),
355+ None => root,
356+ }
357+ }
358+ fn pop(root: &mut Vec<Block>, stack: &mut Vec<Open>) {
359+ let o = stack.pop().unwrap();
360+ let b = close(o);
361+ target(root, stack).push(b);
362+ }
363+
364+ let mut root = Vec::new();
365+ let mut stack: Vec<Open> = Vec::new();
366+ for b in blocks {
367+ let wrap = &b.attrs.wrap;
368+ let prev: Vec<Wrap> = stack.iter().map(|o| o.wrap).collect();
369+ let common = prev.iter().zip(wrap).take_while(|(a, c)| a == c).count();
370+ let keep = b.attrs.join.unwrap_or_else(|| default_join(&prev, wrap)).min(common);
371+ // Levels below `keep` stay; at `keep`, a list in common gets a new item.
372+ let new_item = keep < common && wrap[keep].is_list();
373+ let stay = if new_item { keep + 1 } else { keep };
374+ while stack.len() > stay {
375+ pop(&mut root, &mut stack);
376+ }
377+ if new_item {
378+ stack[keep].items.push(Vec::new());
379+ }
380+ let deepest_new_ordered = (stack.len()..wrap.len()).rev().find(|&i| wrap[i] == Wrap::Ordered);
381+ for (i, &w) in wrap.iter().enumerate().skip(stack.len()) {
382+ let start = if Some(i) == deepest_new_ordered { b.attrs.start.unwrap_or(1) } else { 1 };
383+ stack.push(Open { wrap: w, start, items: vec![Vec::new()] });
384+ }
385+ target(&mut root, &mut stack).push(leaf(b));
386+ }
387+ while !stack.is_empty() {
388+ pop(&mut root, &mut stack);
389+ }
390+ root
391+}
392+
393+fn leaf(b: &FlatBlock) -> Block {
394+ match b.attrs.kind {
395+ Kind::Para => Block::Paragraph(b.inl.clone()),
396+ Kind::Heading(n) => Block::Heading(n as i64, b.inl.clone()),
397+ Kind::Code => Block::Code { lang: b.attrs.lang.clone(), text: b.plain() },
398+ Kind::Rule => Block::Rule,
399+ }
400+}
401+
402+/// The note's block tree.
403+pub fn doc_blocks(doc: &LoroDoc) -> Vec<Block> {
404+ nest(&read_doc(doc))
405+}
406+
407+// ---------------------------------------------------------------------------
408+// Writing
409+// ---------------------------------------------------------------------------
410+
411+/// Flattens a block tree. Every container gets at least one block, so an empty quote
412+/// or list item survives as an empty paragraph.
413+pub fn flatten(blocks: &[Block]) -> Vec<FlatBlock> {
414+ // Each level of the path: wrap, container instance, item index.
415+ type Level = (Wrap, usize, usize);
416+ struct Cx {
417+ out: Vec<FlatBlock>,
418+ prev: Vec<Level>,
419+ next_id: usize,
420+ /// The ordered list a block opens, set until its first leaf.
421+ start: Option<i64>,
422+ }
423+ fn walk(cx: &mut Cx, path: &mut Vec<Level>, blocks: &[Block]) {
424+ if blocks.is_empty() {
425+ emit(cx, path, Kind::Para, None, Vec::new());
426+ }
427+ for b in blocks {
428+ match b {
429+ Block::Paragraph(inl) => emit(cx, path, Kind::Para, None, inl.clone()),
430+ Block::Heading(n, inl) => emit(cx, path, Kind::Heading((*n).clamp(1, 6) as u8), None, inl.clone()),
431+ Block::Code { lang, text } => {
432+ let inl = if text.is_empty() { Vec::new() } else { vec![Inline::Text(text.clone(), Marks::default())] };
433+ emit(cx, path, Kind::Code, lang.clone().filter(|l| !l.is_empty()), inl)
434+ }
435+ Block::Rule => emit(cx, path, Kind::Rule, None, Vec::new()),
436+ Block::Quote(inner) => {
437+ cx.next_id += 1;
438+ path.push((Wrap::Quote, cx.next_id, 0));
439+ walk(cx, path, inner);
440+ path.pop();
441+ }
442+ Block::List { ordered, start, items } => {
443+ if items.is_empty() {
444+ continue;
445+ }
446+ cx.next_id += 1;
447+ let w = if *ordered { Wrap::Ordered } else { Wrap::Bullet };
448+ if *ordered && *start != 1 {
449+ cx.start = Some(*start);
450+ }
451+ for (i, item) in items.iter().enumerate() {
452+ path.push((w, cx.next_id, i));
453+ walk(cx, path, item);
454+ path.pop();
455+ }
456+ }
457+ }
458+ }
459+ }
460+ fn emit(cx: &mut Cx, path: &[Level], kind: Kind, lang: Option<String>, inl: Vec<Inline>) {
461+ // Levels in the same container and item as the previous block. At the next level
462+ // `nest` starts a new item when both are lists of one kind, else new containers.
463+ let same = cx.prev.iter().zip(path).take_while(|(a, b)| a == b).count();
464+ let wrap: Vec<Wrap> = path.iter().map(|l| l.0).collect();
465+ let prev: Vec<Wrap> = cx.prev.iter().map(|l| l.0).collect();
466+ let attrs = Attrs {
467+ kind,
468+ lang,
469+ join: (same != default_join(&prev, &wrap)).then_some(same),
470+ start: cx.start.take(),
471+ wrap,
472+ };
473+ cx.out.push(FlatBlock { attrs, inl, len16: 0, lenu: 0 });
474+ cx.prev = path.to_vec();
475+ }
476+ let mut cx = Cx { out: Vec::new(), prev: Vec::new(), next_id: 0, start: None };
477+ walk(&mut cx, &mut Vec::new(), blocks);
478+ cx.out
479+}
480+
481+/// The text of `blocks` and its marks, as [`write`] inserts them. Positions are
482+/// Unicode scalars from the start of the text.
483+pub struct Built {
484+ pub text: String,
485+ /// Inline mark runs: range and marks.
486+ pub inline: Vec<(std::ops::Range<usize>, Marks)>,
487+ pub images: Vec<(usize, LoroValue)>,
488+ /// The separator position and attributes of each block.
489+ pub seps: Vec<(usize, [Option<LoroValue>; 5])>,
490+}
491+
492+pub fn build(blocks: &[FlatBlock]) -> Built {
493+ let mut b = Built { text: String::new(), inline: Vec::new(), images: Vec::new(), seps: Vec::with_capacity(blocks.len()) };
494+ let mut pos = 0usize;
495+ let push = |b: &mut Built, s: &str, pos: &mut usize| {
496+ for c in s.chars() {
497+ b.text.push(if c == SEP { '\n' } else { c });
498+ }
499+ let n = s.chars().count();
500+ *pos += n;
501+ n
502+ };
503+ for block in blocks {
504+ for i in &block.inl {
505+ match i {
506+ Inline::Text(s, m) => {
507+ let start = pos;
508+ let n = push(&mut b, s, &mut pos);
509+ if n > 0 && *m != Marks::default() && block.attrs.kind != Kind::Code {
510+ b.inline.push((start..pos, m.clone()));
511+ }
512+ }
513+ Inline::HardBreak => {
514+ push(&mut b, "\n", &mut pos);
515+ }
516+ Inline::Image { src, alt, title } => {
517+ let mut map: HashMap<String, LoroValue> = HashMap::new();
518+ map.insert("src".into(), src.as_str().into());
519+ map.insert("alt".into(), alt.as_str().into());
520+ if let Some(t) = title {
521+ map.insert("title".into(), t.as_str().into());
522+ }
523+ b.images.push((pos, map.into()));
524+ b.text.push(OBJ);
525+ pos += 1;
526+ }
527+ }
528+ }
529+ b.seps.push((pos, block.attrs.values()));
530+ b.text.push(SEP);
531+ pos += 1;
532+ }
533+ b
534+}
535+
536+/// Inserts `blocks` at Unicode position `at` and returns the inserted length. With
537+/// `clean`, marks the surrounding text would lend the new text are cleared first.
538+pub fn write(text: &LoroText, at: usize, blocks: &[FlatBlock], clean: bool) -> LoroResult<usize> {
539+ let built = build(blocks);
540+ if built.text.is_empty() {
541+ return Ok(0);
542+ }
543+ text.insert(at, &built.text)?;
544+ let end = at + built.seps.last().map_or(0, |s| s.0 + 1);
545+ if clean {
546+ for key in BLOCK_KEYS.iter().chain(&["strong", "em", "code", "link", KEY_IMAGE]) {
547+ text.unmark(at..end, key)?;
548+ }
549+ }
550+ for (range, marks) in &built.inline {
551+ apply_marks(text, at + range.start..at + range.end, marks)?;
552+ }
553+ for (pos, v) in &built.images {
554+ text.mark(at + pos..at + pos + 1, KEY_IMAGE, v.clone())?;
555+ }
556+ mark_seps(text, at, &built.seps)?;
557+ Ok(end - at)
558+}
559+
560+/// Marks block attributes on separators, one mark per run of equal values.
561+pub fn mark_seps(text: &LoroText, at: usize, seps: &[(usize, [Option<LoroValue>; 5])]) -> LoroResult<()> {
562+ for (k, key) in BLOCK_KEYS.iter().enumerate() {
563+ let mut i = 0;
564+ while i < seps.len() {
565+ let Some(v) = &seps[i].1[k] else {
566+ i += 1;
567+ continue;
568+ };
569+ let mut j = i + 1;
570+ while j < seps.len() && seps[j].1[k].as_ref() == Some(v) {
571+ j += 1;
572+ }
573+ text.mark(at + seps[i].0..at + seps[j - 1].0 + 1, key, v.clone())?;
574+ i = j;
575+ }
576+ }
577+ Ok(())
578+}
579+
580+/// A new doc's body: one empty paragraph.
581+pub fn init(doc: &LoroDoc) -> LoroResult<()> {
582+ let text = body(doc);
583+ if text.len_unicode() == 0 {
584+ text.insert(0, SEP_STR)?;
585+ }
586+ Ok(())
587+}
588+
589+// ---------------------------------------------------------------------------
590+// Queries
591+// ---------------------------------------------------------------------------
592+
593+/// Plain text of the first non-blank block. Reads the head of the body first, so a
594+/// huge note costs no more than its start.
595+pub fn first_text(doc: &LoroDoc) -> String {
596+ let text = body(doc);
597+ let len = text.len_unicode();
598+ let mut head = 4096usize;
599+ loop {
600+ let n = head.min(len);
601+ let delta = text.slice_delta(0, n, loro::cursor::PosType::Unicode).unwrap_or_default();
602+ let mut blocks = read_delta(delta);
603+ // The last block may be cut off unless the whole body was read.
604+ if n < len {
605+ blocks.pop();
606+ }
607+ if let Some(b) = blocks.iter().find(|b| b.attrs.kind.is_text() && !b.plain().trim().is_empty()) {
608+ return b.plain();
609+ }
610+ if n == len {
611+ return String::new();
612+ }
613+ head *= 16;
614+ }
615+}
616+
617+#[cfg(test)]
618+mod tests {
619+ use super::*;
620+
621+ fn p(s: &str) -> Block {
622+ Block::Paragraph(vec![Inline::Text(s.into(), Marks::default())])
623+ }
624+ fn ul(items: Vec<Vec<Block>>) -> Block {
625+ Block::List { ordered: false, start: 1, items }
626+ }
627+
628+ #[test]
629+ fn round_trip() {
630+ let bold = Marks { strong: true, ..Marks::default() };
631+ let tree = vec![
632+ Block::Heading(2, vec![Inline::Text("Title".into(), Marks::default())]),
633+ Block::Paragraph(vec![
634+ Inline::Text("a ".into(), Marks::default()),
635+ Inline::Text("bold".into(), bold),
636+ Inline::HardBreak,
637+ Inline::Image { src: "x.png".into(), alt: "x".into(), title: None },
638+ ]),
639+ ul(vec![vec![p("one"), ul(vec![vec![p("nested")], vec![p("nested 2")]])], vec![p("two"), p("two b")], vec![p("three")]]),
640+ Block::List { ordered: true, start: 3, items: vec![vec![p("c")], vec![Block::Quote(vec![p("q1"), p("q2")])], vec![Block::Quote(vec![p("q3")])]] },
641+ Block::Quote(vec![p("quoted"), ul(vec![vec![p("in quote")]])]),
642+ Block::Code { lang: Some("rust".into()), text: "fn main() {\n}\n".into() },
643+ Block::Rule,
644+ Block::Paragraph(Vec::new()),
645+ ];
646+ let doc = LoroDoc::new();
647+ doc.config_text_style(crate::schema::text_style_config());
648+ write(&body(&doc), 0, &flatten(&tree), false).unwrap();
649+ doc.commit();
650+ let copy = LoroDoc::new();
651+ copy.import(&doc.export(loro::ExportMode::Snapshot).unwrap()).unwrap();
652+ assert_eq!(doc_blocks(&copy), tree);
653+ assert_eq!(first_text(&copy), "Title");
654+ }
655+}
crates/note-model/src/lang.rsadded+321 -0
@@ -0,0 +1,321 @@
1+//! Code block languages: the registry the editor offers, and a cheap heuristic that guesses
2+//! the language of an untagged block. Pure string work, so it builds for wasm32 too.
3+
4+/// A language a code block can be tagged with.
5+#[derive(Debug, PartialEq, Eq)]
6+pub struct Lang {
7+ pub id: &'static str,
8+ pub name: &'static str,
9+ pub aliases: &'static [&'static str],
10+ pub formattable: bool,
11+}
12+
13+/// Every language, in display order.
14+pub static LANGS: &[Lang] = &[
15+ Lang { id: "rust", name: "Rust", aliases: &["rs"], formattable: true },
16+ Lang { id: "python", name: "Python", aliases: &["py", "python3"], formattable: false },
17+ Lang { id: "javascript", name: "JavaScript", aliases: &["js", "jsx", "mjs", "cjs", "node"], formattable: true },
18+ Lang { id: "typescript", name: "TypeScript", aliases: &["ts", "tsx"], formattable: true },
19+ Lang { id: "go", name: "Go", aliases: &["golang"], formattable: false },
20+ Lang { id: "java", name: "Java", aliases: &[], formattable: false },
21+ Lang { id: "kotlin", name: "Kotlin", aliases: &["kt", "kts"], formattable: false },
22+ Lang { id: "c", name: "C", aliases: &["h"], formattable: false },
23+ Lang { id: "cpp", name: "C++", aliases: &["c++", "cc", "cxx", "hpp"], formattable: false },
24+ Lang { id: "csharp", name: "C#", aliases: &["cs", "c#"], formattable: false },
25+ Lang { id: "swift", name: "Swift", aliases: &[], formattable: false },
26+ Lang { id: "ruby", name: "Ruby", aliases: &["rb"], formattable: false },
27+ Lang { id: "php", name: "PHP", aliases: &[], formattable: false },
28+ Lang { id: "html", name: "HTML", aliases: &["htm", "xml", "svg", "xhtml"], formattable: true },
29+ Lang { id: "css", name: "CSS", aliases: &["scss", "less"], formattable: true },
30+ Lang { id: "json", name: "JSON", aliases: &["jsonc", "json5"], formattable: true },
31+ Lang { id: "yaml", name: "YAML", aliases: &["yml"], formattable: true },
32+ Lang { id: "toml", name: "TOML", aliases: &[], formattable: true },
33+ Lang { id: "sql", name: "SQL", aliases: &["postgres", "postgresql", "mysql", "sqlite"], formattable: true },
34+ Lang { id: "bash", name: "Shell", aliases: &["sh", "shell", "zsh", "console", "shellscript"], formattable: false },
35+ Lang { id: "markdown", name: "Markdown", aliases: &["md"], formattable: true },
36+ Lang { id: "text", name: "Plain text", aliases: &["plaintext", "txt", "plain"], formattable: false },
37+];
38+
39+/// The language whose id or alias matches `s` (trimmed, ASCII case-insensitive).
40+pub fn find(s: &str) -> Option<&'static Lang> {
41+ let s = s.trim();
42+ LANGS.iter().find(|l| l.id.eq_ignore_ascii_case(s) || l.aliases.iter().any(|a| a.eq_ignore_ascii_case(s)))
43+}
44+
45+const SCAN_LIMIT: usize = 20_000;
46+const MIN_SCORE: i32 = 3;
47+const MARGIN: i32 = 1;
48+
49+/// Substring signals `(language id, weight, pattern)`. A line containing the pattern adds
50+/// the weight once.
51+const SIGNALS: &[(&str, i32, &str)] = &[
52+ ("rust", 3, "fn "), ("rust", 2, "let mut "), ("rust", 1, "mut "), ("rust", 3, "impl "),
53+ ("rust", 1, "pub "), ("rust", 3, "&self"), ("rust", 3, ".await"), ("rust", 2, "?;"),
54+ ("rust", 2, "match "), ("rust", 2, "Some("), ("rust", 2, "Ok("), ("rust", 2, "Err("),
55+ ("rust", 2, "#["), ("rust", 3, "println!"), ("rust", 3, "format!"), ("rust", 3, "vec!"),
56+ ("rust", 2, ".unwrap()"), ("rust", 1, ".clone()"), ("rust", 1, "::"), ("rust", 1, "->"),
57+ ("rust", 1, "=>"), ("rust", 1, "let "), ("rust", 4, "use std::"), ("rust", 3, "crate::"),
58+ ("rust", 2, "&mut "), ("rust", 2, "Vec<"), ("rust", 2, "Option<"), ("rust", 2, "Result<"),
59+ ("rust", 2, "String::"), ("rust", 2, ".collect"),
60+ ("python", 3, "elif "), ("python", 3, "__init__"), ("python", 3, "lambda "),
61+ ("python", 2, "print("), ("python", 2, "True"), ("python", 2, "False"), ("python", 1, "None"),
62+ ("python", 1, "self."),
63+ ("javascript", 2, "const "), ("javascript", 2, "let "), ("javascript", 2, "=>"),
64+ ("javascript", 2, "function"), ("javascript", 3, "console.log"), ("javascript", 2, "==="),
65+ ("javascript", 2, "!=="), ("javascript", 3, "require("), ("javascript", 3, "module.exports"),
66+ ("javascript", 3, "export default"), ("javascript", 1, "export "), ("javascript", 2, "document."),
67+ ("javascript", 2, "window."), ("javascript", 2, "undefined"),
68+ ("typescript", 4, ": string"), ("typescript", 4, ": number"), ("typescript", 4, ": boolean"),
69+ ("typescript", 2, ": void"), ("typescript", 3, "interface "), ("typescript", 2, "readonly "),
70+ ("typescript", 3, "as const"), ("typescript", 2, "implements "), ("typescript", 3, "Promise<"),
71+ ("typescript", 3, "keyof "), ("typescript", 3, "import type"), ("typescript", 3, "export type"),
72+ ("go", 3, "package "), ("go", 2, "func "), ("go", 3, ":="), ("go", 3, "fmt."),
73+ ("go", 3, "err != nil"), ("go", 2, "import ("), ("go", 2, "chan "), ("go", 2, "defer "),
74+ ("go", 2, "interface{}"), ("go", 2, "map["), ("go", 2, "[]byte"), ("go", 2, "go func"),
75+ ("go", 1, "make("),
76+ ("java", 3, "public class"), ("java", 3, "System.out"), ("java", 3, "public static void"),
77+ ("java", 3, "@Override"), ("java", 2, "String[]"), ("java", 1, "public "), ("java", 1, "private "),
78+ ("java", 1, "protected "),
79+ ("kotlin", 3, "fun "), ("kotlin", 2, "val "), ("kotlin", 1, "println("), ("kotlin", 3, "data class"),
80+ ("kotlin", 3, "companion object"), ("kotlin", 3, "lateinit"), ("kotlin", 3, "?.let"),
81+ ("c", 2, "#include"), ("c", 2, ".h>"), ("c", 3, "int main"), ("c", 2, "printf("), ("c", 2, "malloc("),
82+ ("c", 2, "NULL"), ("c", 2, "#define"), ("c", 1, "struct "), ("c", 1, "sizeof("), ("c", 1, "char "),
83+ ("cpp", 1, "#include"), ("cpp", 3, "<iostream>"), ("cpp", 3, "<vector>"), ("cpp", 2, "std::"),
84+ ("cpp", 3, "template<"), ("cpp", 3, "template <"), ("cpp", 2, "cout"), ("cpp", 2, "cin >>"),
85+ ("cpp", 2, "nullptr"), ("cpp", 3, "using namespace"),
86+ ("csharp", 3, "using System"), ("csharp", 2, "namespace "), ("csharp", 3, "Console.Write"),
87+ ("csharp", 1, "public void"), ("csharp", 2, "async Task"), ("csharp", 3, "[HttpGet"),
88+ ("csharp", 3, "get; set;"), ("csharp", 1, "var "),
89+ ("swift", 3, "guard "), ("swift", 2, "var "), ("swift", 3, "import UIKit"),
90+ ("swift", 3, "import SwiftUI"), ("swift", 3, "import Foundation"), ("swift", 2, "func "),
91+ ("swift", 1, "let "), ("swift", 3, "@State"), ("swift", 1, "print("), ("swift", 2, "?? "),
92+ ("swift", 2, "-> Void"),
93+ ("ruby", 3, "puts "), ("ruby", 2, "require '"), ("ruby", 3, "attr_accessor"), ("ruby", 3, "elsif "),
94+ ("ruby", 3, "unless "), ("ruby", 3, "do |"),
95+ ("php", 5, "<?php"), ("php", 3, "$this->"), ("php", 2, "$_"),
96+ ("html", 2, "</"), ("html", 3, "<html"), ("html", 2, "<div"), ("html", 2, "<body"),
97+ ("html", 2, "<head"), ("html", 2, "<script"), ("html", 2, "<img"), ("html", 2, "<a href"),
98+ ("html", 2, "<span"),
99+ ("css", 3, "@media"), ("css", 3, "@keyframes"), ("css", 2, "@import"), ("css", 3, "!important"),
100+ ("css", 2, "px;"), ("css", 2, "rem;"), ("css", 3, "var(--"), ("css", 2, "rgba("),
101+ ("bash", 1, "&&"), ("bash", 3, "; then"), ("bash", 2, "; do"), ("bash", 2, "$("),
102+ ("bash", 1, "${"), ("bash", 2, "| grep"), ("bash", 2, "export "), ("bash", 2, "set -"),
103+ ("markdown", 2, "]("),
104+];
105+
106+/// SQL keywords, matched against the lowercased line.
107+const SQL: &[(&str, i32)] = &[
108+ ("select ", 3), ("insert into", 3), ("create table", 3), ("alter table", 3),
109+ ("delete from", 3), ("where ", 2), ("order by", 2), ("group by", 2), ("join ", 2),
110+ ("values (", 2), ("from ", 1),
111+];
112+
113+/// Shell commands, matched at the start of a line.
114+const SHELL_CMDS: &[&str] = &[
115+ "sudo ", "apt ", "cargo ", "npm ", "bun ", "git ", "cd ", "mkdir ", "chmod ", "echo ", "ls ",
116+ "curl ", "pip ", "docker ", "make ", "rm ", "cp ", "mv ",
117+];
118+
119+/// CSS properties, matched at the start of a `prop: value;` line.
120+const CSS_PROPS: &[&str] = &[
121+ "color", "margin", "padding", "display", "background", "font", "border", "width", "height",
122+ "position", "flex", "grid", "line-height", "text-", "box-",
123+];
124+
125+/// Guesses the language of an untagged code block from weighted line signals. Only the
126+/// first 20 KB are scanned. Returns `None` when no language clearly wins; never `text`.
127+pub fn detect(code: &str) -> Option<&'static str> {
128+ let mut end = code.len().min(SCAN_LIMIT);
129+ while !code.is_char_boundary(end) {
130+ end -= 1;
131+ }
132+ let text = &code[..end];
133+
134+ let mut score = vec![0i32; LANGS.len()];
135+ let mut add = |id: &str, w: i32| {
136+ if let Some(i) = LANGS.iter().position(|l| l.id == id) {
137+ score[i] += w;
138+ }
139+ };
140+
141+ let whole = text.trim();
142+ if whole.starts_with(['{', '[']) && whole.ends_with(['}', ']']) && whole.contains("\": ") && !whole.contains(';') {
143+ add("json", 6);
144+ }
145+
146+ for raw in text.lines() {
147+ let t = raw.trim();
148+ if t.is_empty() {
149+ continue;
150+ }
151+ for &(id, w, pat) in SIGNALS {
152+ if t.contains(pat) {
153+ add(id, w);
154+ }
155+ }
156+ let lower = t.to_ascii_lowercase();
157+ for &(pat, w) in SQL {
158+ if lower.contains(pat) {
159+ add("sql", w);
160+ }
161+ }
162+
163+ // Shapes that need the whole line, not a substring.
164+ if t.starts_with("def ") {
165+ if t.ends_with(':') { add("python", 3) } else { add("ruby", 2) }
166+ }
167+ if t.starts_with("class ") && t.ends_with(':') {
168+ add("python", 3);
169+ }
170+ if t.starts_with("from ") && t.contains(" import ") {
171+ add("python", 3);
172+ }
173+ if let Some(rest) = t.strip_prefix("import ") {
174+ if rest.contains(" from ") {
175+ add("javascript", 3);
176+ } else if rest.starts_with(|c: char| c.is_ascii_lowercase()) && !rest.contains([';', '"', '\'', '{', '(']) {
177+ add("python", 2);
178+ }
179+ }
180+ if t.starts_with("type ") && t.contains(" = ") && !t.ends_with(';') {
181+ add("typescript", 3);
182+ }
183+ if has_closure(t) {
184+ add("rust", 3);
185+ }
186+ // A one-line rule: `a { color: red; }`.
187+ if t.contains('{') && t.ends_with('}') && t.contains(": ") && t.contains(';') && !t.contains('(') && !t.contains('"') {
188+ add("css", 3);
189+ }
190+ if t == "end" {
191+ add("ruby", 2);
192+ }
193+ if matches!(t, "fi" | "done" | "esac") {
194+ add("bash", 2);
195+ }
196+ if t.starts_with("---") {
197+ add("yaml", 3);
198+ }
199+ if t.starts_with("- ") {
200+ add("yaml", 1);
201+ }
202+ if yaml_key(t) {
203+ add("yaml", 2);
204+ }
205+ if t.strip_prefix('[').and_then(|s| s.strip_suffix(']')).is_some_and(ident) {
206+ add("toml", 3);
207+ }
208+ if t.split_once(" = ").is_some_and(|(key, _)| ident(key)) {
209+ add("toml", 1);
210+ }
211+ if t.starts_with('"') && t.contains("\": ") {
212+ add("json", 1);
213+ }
214+ if t.starts_with('$') && t.ends_with(';') {
215+ add("php", 2);
216+ }
217+ if t.ends_with('{')
218+ && !t.contains('(')
219+ && ((t.starts_with(['.', '#', '*']) && !t.starts_with("#[")) || t.starts_with("body") || t.starts_with("html"))
220+ {
221+ add("css", 2);
222+ }
223+ if let Some((prop, _)) = t.strip_suffix(';').and_then(|s| s.split_once(':'))
224+ && !prop.contains(' ') && CSS_PROPS.iter().any(|p| prop.starts_with(p)) {
225+ add("css", 2);
226+ }
227+ if lower.starts_with("<!doctype") {
228+ add("html", 4);
229+ }
230+ if lower.starts_with("<?xml") {
231+ add("html", 3);
232+ }
233+ if t.starts_with('<') && t.ends_with('>') {
234+ add("html", 2);
235+ }
236+ if t.starts_with("#!") && t.contains("sh") {
237+ add("bash", 5);
238+ }
239+ if t.starts_with("$ ") || SHELL_CMDS.iter().any(|c| t.starts_with(c)) {
240+ add("bash", 3);
241+ }
242+ if t.starts_with("# ") || t.starts_with("## ") {
243+ add("markdown", 1);
244+ }
245+ if t.starts_with("```") {
246+ add("markdown", 3);
247+ }
248+ if t.starts_with("- [ ]") || t.starts_with("- [x]") {
249+ add("markdown", 3);
250+ }
251+ if t.matches("**").count() >= 2 {
252+ add("markdown", 2);
253+ }
254+ }
255+
256+ let (mut top, mut best) = (0i32, usize::MAX);
257+ let mut second = 0i32;
258+ for (i, &s) in score.iter().enumerate() {
259+ if s > top {
260+ second = top;
261+ (top, best) = (s, i);
262+ } else if s > second {
263+ second = s;
264+ }
265+ }
266+ (top >= MIN_SCORE && top - second >= MARGIN).then(|| LANGS[best].id)
267+}
268+
269+/// A simple identifier: letters, digits, `_`, `-` or `.`.
270+fn ident(s: &str) -> bool {
271+ !s.is_empty() && s.bytes().all(|c| c.is_ascii_alphanumeric() || matches!(c, b'_' | b'-' | b'.'))
272+}
273+
274+/// A YAML `key: value` or `key:` line.
275+fn yaml_key(t: &str) -> bool {
276+ t.split_once(':').is_some_and(|(key, rest)| ident(key) && (rest.is_empty() || rest.starts_with(' ')))
277+ && !t.ends_with([',', ';', '{', '(', '['])
278+}
279+
280+/// A `|args|` closure head opened after `(`, `,`, `=` or `.`, as in `.map(|s| ...)`.
281+fn has_closure(t: &str) -> bool {
282+ let b = t.as_bytes();
283+ (1..b.len()).any(|i| {
284+ b[i] == b'|'
285+ && matches!(b[i - 1], b'(' | b',' | b'=' | b'.')
286+ && t[i + 1..].split_once('|').is_some_and(|(args, _)| {
287+ !args.is_empty()
288+ && args.len() <= 20
289+ && args.bytes().all(|c| c.is_ascii_alphanumeric() || matches!(c, b'_' | b' ' | b','))
290+ })
291+ })
292+}
293+
294+#[cfg(test)]
295+mod tests {
296+ use super::*;
297+
298+ #[test]
299+ fn detects_snippets_and_finds_langs() {
300+ let cases = [
301+ ("let rows = load_job_rows(state, &viewer.0.id, 50).await?;\nlet skipped = query_params::<JobsQuery>(cx)?\n .skipped\n .clone()\n .filter(|s| !s.is_empty() && s.len() < 2000)\n .map(|s| g::bulk_skipped(lang, &s));", "rust"),
302+ ("import os\n\ndef load(path):\n if not path:\n return None\n return open(path).read()", "python"),
303+ ("const add = (a, b) => a + b;\nconsole.log(add(1, 2));", "javascript"),
304+ ("interface User { id: number; name: string }\nconst greet = (u: User): string => `hi ${u.name}`;", "typescript"),
305+ ("package main\n\nimport \"fmt\"\n\nfunc main() {\n\tfmt.Println(\"hi\")\n}", "go"),
306+ ("{\n \"name\": \"note\",\n \"version\": \"1.0.0\",\n \"private\": true\n}", "json"),
307+ ("<!DOCTYPE html>\n<html>\n <body>\n <p class=\"x\">Hi</p>\n </body>\n</html>", "html"),
308+ (".card {\n display: flex;\n padding: 1rem;\n color: #333;\n}", "css"),
309+ ("SELECT id, name\nFROM users\nWHERE active = 1\nORDER BY name;", "sql"),
310+ ("#!/bin/bash\nset -e\nexport PATH=$HOME/bin:$PATH\ncargo build && sudo cp target/release/app /usr/local/bin/\necho \"done\"", "bash"),
311+ ("name: build\non: push\njobs:\n test:\n runs-on: ubuntu-latest\n steps:\n - uses: actions/checkout@v4", "yaml"),
312+ ("[package]\nname = \"note-model\"\nversion = \"0.1.0\"\nedition = \"2024\"", "toml"),
313+ ];
314+ for (code, id) in cases {
315+ assert_eq!(detect(code), Some(id), "{code}");
316+ }
317+ assert_eq!(detect("hello world"), None);
318+ assert_eq!(find("RS").map(|l| l.id), Some("rust"));
319+ assert_eq!(find("c++").map(|l| l.id), Some("cpp"));
320+ }
321+}
crates/note-model/src/lib.rsadded+14 -0
@@ -0,0 +1,14 @@
1+//! The Loro layout of a note (one rich text, see [`flat`]) and its readers, writers
2+//! and markup.
3+//!
4+//! This crate only depends on `loro` so it can also build for wasm32.
5+
6+pub mod blocks;
7+pub mod flat;
8+pub mod lang;
9+pub mod links;
10+pub mod marks;
11+pub mod render;
12+pub mod schema;
13+pub mod tree;
14+pub mod write;
crates/note-model/src/links.rsadded+80 -0
@@ -0,0 +1,80 @@
1+//! Note links: `/notes/<id>` and `/notes/by-title/<title>` hrefs, and percent encoding.
2+
3+use loro::{LoroDoc, TextDelta};
4+
5+use crate::tree::value_str;
6+
7+/// A link to another note: by id (`/notes/<id>`) or by title (`/notes/by-title/<title>`).
8+#[derive(Clone, Debug, PartialEq, Eq)]
9+pub enum LinkTarget {
10+ Id(String),
11+ Title(String),
12+}
13+
14+/// Every note the doc links to, each target once, in document order. Hrefs that are
15+/// not note links are ignored.
16+pub fn note_links(doc: &LoroDoc) -> Vec<LinkTarget> {
17+ links_in(&crate::flat::body(doc).to_delta())
18+}
19+
20+/// [`note_links`] of a body already read.
21+pub fn links_in(delta: &[TextDelta]) -> Vec<LinkTarget> {
22+ let mut out = Vec::new();
23+ for delta in delta {
24+ let TextDelta::Insert { attributes: Some(attrs), .. } = delta else { continue };
25+ let Some(href) = attrs.get("link").and_then(|link| link.get_by_key("href")).and_then(value_str) else {
26+ continue;
27+ };
28+ if let Some(target) = link_target(&href)
29+ && !out.contains(&target)
30+ {
31+ out.push(target);
32+ }
33+ }
34+ out
35+}
36+
37+/// The note an href points at, when it is a note link.
38+pub fn link_target(href: &str) -> Option<LinkTarget> {
39+ let rest = href.strip_prefix("/notes/")?;
40+ if let Some(encoded) = rest.strip_prefix("by-title/") {
41+ let title = percent_decode(encoded);
42+ return (!title.trim().is_empty()).then_some(LinkTarget::Title(title));
43+ }
44+ let is_id = !rest.is_empty() && !rest.contains(['/', '?', '#']);
45+ is_id.then(|| LinkTarget::Id(rest.to_owned()))
46+}
47+
48+/// Percent-encodes everything except RFC 3986 unreserved characters.
49+pub fn percent_encode(s: &str) -> String {
50+ let mut out = String::with_capacity(s.len());
51+ for b in s.bytes() {
52+ match b {
53+ b'A'..=b'Z' | b'a'..=b'z' | b'0'..=b'9' | b'-' | b'_' | b'.' | b'~' => {
54+ out.push(b as char)
55+ }
56+ _ => out.push_str(&format!("%{b:02X}")),
57+ }
58+ }
59+ out
60+}
61+
62+/// Decodes `%XX` escapes. Malformed escapes are kept as they are.
63+pub fn percent_decode(s: &str) -> String {
64+ let bytes = s.as_bytes();
65+ let mut out = Vec::with_capacity(bytes.len());
66+ let mut i = 0;
67+ while i < bytes.len() {
68+ if bytes[i] == b'%' && i + 2 < bytes.len() {
69+ let hex = std::str::from_utf8(&bytes[i + 1..i + 3]).ok();
70+ if let Some(v) = hex.and_then(|h| u8::from_str_radix(h, 16).ok()) {
71+ out.push(v);
72+ i += 3;
73+ continue;
74+ }
75+ }
76+ out.push(bytes[i]);
77+ i += 1;
78+ }
79+ String::from_utf8_lossy(&out).into_owned()
80+}
crates/note-model/src/marks.rsadded+39 -0
@@ -0,0 +1,39 @@
1+//! Inline marks of a LoroText run, shared by the readers and the writer.
2+
3+use std::collections::HashMap;
4+use std::hash::BuildHasher;
5+
6+use loro::LoroValue;
7+
8+use crate::tree::value_str;
9+
10+/// The marks on one run of text. `link` holds `(href, title)`.
11+#[derive(PartialEq, Clone, Default, Debug)]
12+pub struct Marks {
13+ pub strong: bool,
14+ pub em: bool,
15+ pub code: bool,
16+ pub link: Option<(String, Option<String>)>,
17+}
18+
19+impl Marks {
20+ /// Reads the marks from the attributes of a rich-text delta. A mark counts as on
21+ /// unless its value is null or absent.
22+ pub fn from_attrs<S: BuildHasher>(attrs: &HashMap<String, LoroValue, S>) -> Marks {
23+ let on = |k: &str| attrs.get(k).is_some_and(|v| !matches!(v, LoroValue::Null));
24+ let link = attrs.get("link").map(|v| {
25+ let href = v.get_by_key("href").and_then(value_str).unwrap_or_default();
26+ let title = v
27+ .get_by_key("title")
28+ .and_then(value_str)
29+ .filter(|t| !t.is_empty());
30+ (href, title)
31+ });
32+ Marks {
33+ strong: on("strong"),
34+ em: on("em"),
35+ code: on("code"),
36+ link,
37+ }
38+ }
39+}
crates/note-model/src/render.rsadded+302 -0
@@ -0,0 +1,302 @@
1+//! The editor's markup for a note, the same as ProseMirror's `toDOM` for our schema.
2+//! The server renders it to a string so the note shows before the editor loads, and
3+//! the editor builds its DOM from the same specs.
4+
5+use loro::{LoroDoc, cursor::PosType};
6+
7+use crate::flat::{self, Attrs, Kind, Wrap};
8+use crate::marks::Marks;
9+use crate::write::{Block, Inline};
10+
11+pub type HtmlAttrs = Vec<(&'static str, String)>;
12+
13+/// How a node renders: its element, attributes, and for `pre` the inner `code`
14+/// element that holds the content.
15+pub struct Spec {
16+ pub tag: &'static str,
17+ pub attrs: HtmlAttrs,
18+ pub inner: Option<&'static str>,
19+}
20+
21+impl Spec {
22+ fn new(tag: &'static str) -> Self {
23+ Spec { tag, attrs: Vec::new(), inner: None }
24+ }
25+}
26+
27+/// The class PM puts on the `<br>` that keeps an empty textblock (or a code block
28+/// ending in a newline) one line tall.
29+pub const TRAILING_BREAK: &str = "ProseMirror-trailingBreak";
30+
31+/// The element of a leaf block.
32+pub fn leaf_spec(kind: Kind, lang: Option<&str>) -> Spec {
33+ match kind {
34+ Kind::Para => Spec::new("p"),
35+ Kind::Heading(n) => Spec::new(["h1", "h2", "h3", "h4", "h5", "h6"][n.clamp(1, 6) as usize - 1]),
36+ Kind::Rule => Spec::new("hr"),
37+ Kind::Code => {
38+ let mut s = Spec::new("pre");
39+ s.attrs.push(("spellcheck", "false".into()));
40+ if let Some(lang) = lang.filter(|l| !l.is_empty()) {
41+ s.attrs.push(("data-language", lang.to_owned()));
42+ }
43+ s.inner = Some("code");
44+ s
45+ }
46+ }
47+}
48+
49+pub fn block_spec(attrs: &Attrs) -> Spec {
50+ leaf_spec(attrs.kind, attrs.lang.as_deref())
51+}
52+
53+/// The element of a container: a quote, or a list with its first number.
54+pub fn wrap_spec(wrap: Wrap, start: i64) -> Spec {
55+ match wrap {
56+ Wrap::Quote => Spec::new("blockquote"),
57+ Wrap::Bullet => Spec::new("ul"),
58+ Wrap::Ordered => {
59+ let mut s = Spec::new("ol");
60+ if start != 1 {
61+ s.attrs.push(("start", start.to_string()));
62+ }
63+ s
64+ }
65+ }
66+}
67+
68+pub fn item_spec() -> Spec {
69+ Spec::new("li")
70+}
71+
72+/// What an image node shows as, by the file extension of its source.
73+#[derive(Clone, Copy, PartialEq, Eq, Debug)]
74+pub enum Embed {
75+ Image,
76+ Audio,
77+ Video,
78+}
79+
80+/// The embed of an image source, from its extension: `?query` and `#fragment` are
81+/// ignored. A `data:image/` URI is an image. `None` for an unknown or missing extension.
82+pub fn embed_of(src: &str) -> Option<Embed> {
83+ let src = src.trim();
84+ if src.get(..11).is_some_and(|p| p.eq_ignore_ascii_case("data:image/")) {
85+ return Some(Embed::Image);
86+ }
87+ let path = src.split(['?', '#']).next().unwrap_or("");
88+ let name = path.rsplit('/').next().unwrap_or("");
89+ let (_, ext) = name.rsplit_once('.')?;
90+ match ext.to_ascii_lowercase().as_str() {
91+ "mp3" | "m4a" | "wav" | "flac" | "aac" | "ogg" | "oga" | "opus" | "weba" => Some(Embed::Audio),
92+ "mp4" | "m4v" | "webm" | "mov" | "ogv" => Some(Embed::Video),
93+ "png" | "jpg" | "jpeg" | "gif" | "webp" | "avif" | "bmp" | "svg" => Some(Embed::Image),
94+ _ => None,
95+ }
96+}
97+
98+pub fn image_spec(src: &str, alt: &str, title: Option<&str>) -> Spec {
99+ let media = match embed_of(src) {
100+ Some(Embed::Audio) => Some("audio"),
101+ Some(Embed::Video) => Some("video"),
102+ _ => None,
103+ };
104+ let mut s = Spec::new(media.unwrap_or("img"));
105+ s.attrs.push(("src", src.to_owned()));
106+ match media {
107+ Some(_) => {
108+ s.attrs.push(("controls", String::new()));
109+ s.attrs.push(("preload", "metadata".to_owned()));
110+ s.attrs.push(("aria-label", alt.to_owned()));
111+ s.attrs.push(("class", "note-media".to_owned()));
112+ }
113+ None => s.attrs.push(("alt", alt.to_owned())),
114+ }
115+ if let Some(t) = title {
116+ s.attrs.push(("title", t.to_owned()));
117+ }
118+ s
119+}
120+
121+pub fn is_void(tag: &str) -> bool {
122+ matches!(tag, "hr" | "br" | "img")
123+}
124+
125+/// Mark wrappers of a run, outermost first (schema order: link, em, strong, code).
126+pub fn mark_specs(m: &Marks) -> Vec<Spec> {
127+ let mut out = Vec::new();
128+ if let Some((href, title)) = &m.link {
129+ let mut s = Spec::new("a");
130+ s.attrs.push(("href", href.clone()));
131+ if let Some(t) = title {
132+ s.attrs.push(("title", t.clone()));
133+ }
134+ out.push(s);
135+ }
136+ if m.em {
137+ out.push(Spec::new("em"));
138+ }
139+ if m.strong {
140+ out.push(Spec::new("strong"));
141+ }
142+ if m.code {
143+ out.push(Spec::new("code"));
144+ }
145+ out
146+}
147+
148+/// The top of the note as the editor shows it before it starts: at most `blocks`
149+/// blocks and about `chars` characters of text, in one page element. Reads only the
150+/// head of the body.
151+pub fn preview_html(doc: &LoroDoc, blocks: usize, chars: usize) -> String {
152+ let text = flat::body(doc);
153+ let n = text.len_unicode().min(chars + blocks + 1);
154+ let delta = text.slice_delta(0, n, PosType::Unicode).unwrap_or_default();
155+ let mut flat = flat::read_delta(delta);
156+ flat.truncate(blocks);
157+ let mut out = String::from("<div class=\"pm-page\">");
158+ let mut budget = chars;
159+ blocks_html(&flat::nest(&flat), &mut out, &mut budget);
160+ out.push_str("</div>");
161+ out
162+}
163+
164+/// Blocks as the editor's markup, with at most `budget` characters of text.
165+pub fn blocks_html(blocks: &[Block], out: &mut String, budget: &mut usize) {
166+ for b in blocks {
167+ if *budget == 0 {
168+ return;
169+ }
170+ block_html(b, out, budget);
171+ }
172+}
173+
174+fn block_html(b: &Block, out: &mut String, budget: &mut usize) {
175+ let (spec, inl): (Spec, &[Inline]) = match b {
176+ Block::Paragraph(inl) => (leaf_spec(Kind::Para, None), inl),
177+ Block::Heading(n, inl) => (leaf_spec(Kind::Heading((*n).clamp(1, 6) as u8), None), inl),
178+ Block::Rule => {
179+ open(&leaf_spec(Kind::Rule, None), out);
180+ return;
181+ }
182+ Block::Code { lang, text } => {
183+ let spec = leaf_spec(Kind::Code, lang.as_deref());
184+ open(&spec, out);
185+ out.push_str("<code>");
186+ let s = cut(text, budget);
187+ escape(s, out);
188+ if s.is_empty() || s.ends_with('\n') {
189+ trailing_break(out);
190+ }
191+ out.push_str("</code></pre>");
192+ return;
193+ }
194+ Block::Quote(inner) => {
195+ open(&wrap_spec(Wrap::Quote, 1), out);
196+ blocks_html(inner, out, budget);
197+ close("blockquote", out);
198+ return;
199+ }
200+ Block::List { ordered, start, items } => {
201+ let spec = wrap_spec(if *ordered { Wrap::Ordered } else { Wrap::Bullet }, *start);
202+ open(&spec, out);
203+ for item in items {
204+ out.push_str("<li>");
205+ blocks_html(item, out, budget);
206+ out.push_str("</li>");
207+ }
208+ close(spec.tag, out);
209+ return;
210+ }
211+ };
212+ open(&spec, out);
213+ inline_html(inl, out, budget);
214+ close(spec.tag, out);
215+}
216+
217+/// A textblock's content. An empty one, or one ending in a break, gets a trailing
218+/// `<br>` to show its last line.
219+pub fn inline_html(inl: &[Inline], out: &mut String, budget: &mut usize) {
220+ let mut last_break = true;
221+ for i in inl {
222+ match i {
223+ Inline::Text(s, m) => {
224+ let s = cut(s, budget);
225+ if s.is_empty() {
226+ continue;
227+ }
228+ let wraps = mark_specs(m);
229+ for w in &wraps {
230+ open(w, out);
231+ }
232+ escape(s, out);
233+ for w in wraps.iter().rev() {
234+ close(w.tag, out);
235+ }
236+ last_break = false;
237+ }
238+ Inline::HardBreak => {
239+ out.push_str("<br>");
240+ last_break = true;
241+ }
242+ Inline::Image { src, alt, title } => {
243+ let spec = image_spec(src, alt, title.as_deref());
244+ open(&spec, out);
245+ if !is_void(spec.tag) {
246+ close(spec.tag, out);
247+ }
248+ last_break = false;
249+ }
250+ }
251+ }
252+ if last_break {
253+ trailing_break(out);
254+ }
255+}
256+
257+fn trailing_break(out: &mut String) {
258+ out.push_str("<br class=\"");
259+ out.push_str(TRAILING_BREAK);
260+ out.push_str("\">");
261+}
262+
263+/// The head of `s` that fits the budget, which it takes from.
264+fn cut<'a>(s: &'a str, budget: &mut usize) -> &'a str {
265+ let s = match s.char_indices().nth(*budget) {
266+ Some((at, _)) => &s[..at],
267+ None => s,
268+ };
269+ *budget -= s.chars().count().min(*budget);
270+ s
271+}
272+
273+fn open(spec: &Spec, out: &mut String) {
274+ out.push('<');
275+ out.push_str(spec.tag);
276+ for (k, v) in &spec.attrs {
277+ out.push(' ');
278+ out.push_str(k);
279+ out.push_str("=\"");
280+ escape(v, out);
281+ out.push('"');
282+ }
283+ out.push('>');
284+}
285+
286+fn close(tag: &str, out: &mut String) {
287+ out.push_str("</");
288+ out.push_str(tag);
289+ out.push('>');
290+}
291+
292+pub fn escape(s: &str, out: &mut String) {
293+ for c in s.chars() {
294+ match c {
295+ '&' => out.push_str("&amp;"),
296+ '<' => out.push_str("&lt;"),
297+ '>' => out.push_str("&gt;"),
298+ '"' => out.push_str("&quot;"),
299+ c => out.push(c),
300+ }
301+ }
302+}
crates/note-model/src/schema.rsadded+43 -0
@@ -0,0 +1,43 @@
1+//! Node and mark names of the note layout, and the text style expand rules.
2+
3+use loro::{ExpandType, StyleConfig, StyleConfigMap};
4+
5+pub const NODE_DOC: &str = "doc";
6+pub const NODE_PARAGRAPH: &str = "paragraph";
7+pub const NODE_HEADING: &str = "heading";
8+pub const NODE_CODE_BLOCK: &str = "code_block";
9+pub const NODE_BLOCKQUOTE: &str = "blockquote";
10+pub const NODE_HORIZONTAL_RULE: &str = "horizontal_rule";
11+pub const NODE_BULLET_LIST: &str = "bullet_list";
12+pub const NODE_ORDERED_LIST: &str = "ordered_list";
13+pub const NODE_LIST_ITEM: &str = "list_item";
14+pub const NODE_HARD_BREAK: &str = "hard_break";
15+pub const NODE_IMAGE: &str = "image";
16+
17+pub const MARK_STRONG: &str = "strong";
18+pub const MARK_EM: &str = "em";
19+pub const MARK_CODE: &str = "code";
20+pub const MARK_LINK: &str = "link";
21+
22+/// Expand rules of every mark key: inline marks grow at their end like ProseMirror's.
23+pub fn text_style_config() -> StyleConfigMap {
24+ let mut styles = StyleConfigMap::new();
25+ styles.insert(
26+ MARK_STRONG.into(),
27+ StyleConfig::new().expand(ExpandType::After),
28+ );
29+ styles.insert(MARK_EM.into(), StyleConfig::new().expand(ExpandType::After));
30+ styles.insert(
31+ MARK_CODE.into(),
32+ StyleConfig::new().expand(ExpandType::After),
33+ );
34+ styles.insert(
35+ MARK_LINK.into(),
36+ StyleConfig::new().expand(ExpandType::None),
37+ );
38+ // Block attributes on separators, and images: never lent to inserted text.
39+ for key in crate::flat::BLOCK_KEYS.iter().chain(&[crate::flat::KEY_IMAGE]) {
40+ styles.insert((*key).into(), StyleConfig::new().expand(ExpandType::None));
41+ }
42+ styles
43+}
crates/note-model/src/tree.rsadded+24 -0
@@ -0,0 +1,24 @@
1+//! Small read helpers shared by the readers.
2+
3+use loro::{LoroDoc, LoroValue};
4+
5+pub fn value_str(v: &LoroValue) -> Option<String> {
6+ v.as_string().map(|s| s.as_str().to_owned())
7+}
8+
9+/// Plain text of the first non-empty block, trimmed, max 80 chars. "Untitled" if empty.
10+pub fn title(doc: &LoroDoc) -> String {
11+ title_from(&crate::flat::first_text(doc))
12+}
13+
14+/// A title from a block's plain text, as [`title`] makes it.
15+pub fn title_from(raw: &str) -> String {
16+ let collapsed = raw.split_whitespace().collect::<Vec<_>>().join(" ");
17+ let truncated: String = collapsed.chars().take(80).collect();
18+ let trimmed = truncated.trim_end();
19+ if trimmed.is_empty() {
20+ "Untitled".to_string()
21+ } else {
22+ trimmed.to_string()
23+ }
24+}
crates/note-model/src/write.rsadded+74 -0
@@ -0,0 +1,74 @@
1+//! The plain block and inline tree of a note: what the markdown import produces,
2+//! what `flat::nest` reads back, and what `flat::flatten` writes.
3+
4+use std::collections::HashMap;
5+
6+use loro::{LoroResult, LoroText, LoroValue};
7+
8+use crate::marks::Marks;
9+use crate::schema::{MARK_CODE, MARK_EM, MARK_LINK, MARK_STRONG};
10+
11+#[derive(Clone, PartialEq, Debug)]
12+pub enum Inline {
13+ Text(String, Marks),
14+ HardBreak,
15+ Image {
16+ src: String,
17+ alt: String,
18+ title: Option<String>,
19+ },
20+}
21+
22+#[derive(Clone, PartialEq, Debug)]
23+pub enum Block {
24+ Paragraph(Vec<Inline>),
25+ Heading(i64, Vec<Inline>),
26+ Quote(Vec<Block>),
27+ Code {
28+ lang: Option<String>,
29+ text: String,
30+ },
31+ Rule,
32+ List {
33+ ordered: bool,
34+ start: i64,
35+ items: Vec<Vec<Block>>,
36+ },
37+}
38+
39+/// The peer id of docs the server builds: above every client's, which are random.
40+/// Loro looks up the change store entry at or below a commit's id on every local
41+/// commit, and decodes it: below a big import, that is the import, megabytes for each
42+/// keystroke (loro 1.17).
43+pub const BUILDER_PEER: u64 = u64::MAX - 1;
44+
45+pub fn apply_marks(
46+ text: &LoroText,
47+ range: std::ops::Range<usize>,
48+ marks: &Marks,
49+) -> LoroResult<()> {
50+ if marks.strong {
51+ text.mark(range.clone(), MARK_STRONG, empty_map())?;
52+ }
53+ if marks.em {
54+ text.mark(range.clone(), MARK_EM, empty_map())?;
55+ }
56+ if marks.code {
57+ text.mark(range.clone(), MARK_CODE, empty_map())?;
58+ }
59+ if let Some((href, title)) = &marks.link {
60+ let mut map: HashMap<String, LoroValue> = HashMap::new();
61+ map.insert("href".to_owned(), LoroValue::from(href.as_str()));
62+ let title_value = match title {
63+ Some(t) => LoroValue::from(t.as_str()),
64+ None => LoroValue::Null,
65+ };
66+ map.insert("title".to_owned(), title_value);
67+ text.mark(range, MARK_LINK, LoroValue::from(map))?;
68+ }
69+ Ok(())
70+}
71+
72+fn empty_map() -> LoroValue {
73+ LoroValue::from(HashMap::<String, LoroValue>::new())
74+}
src/app.rsmodified+59 -21
@@ -8,7 +8,8 @@ use topcoat::{
8 cookie::RouterBuilderCookieExt,8 cookie::RouterBuilderCookieExt,
9 font::{Font, RouterBuilderFontExt, font},9 font::{Font, RouterBuilderFontExt, font},
10 router::{10 router::{
11- BodyLimit, Router, RouterBuilderDirectoryExt, Slot, layout, module_router, page,11+ Body, BodyLimit, HeaderValue, Layer, LayerFuture, Next, Path, Router,
12+ RouterBuilderDirectoryExt, Slot, StatusCode, header, layout, module_router, page,
12 query_params,13 query_params,
13 request::uri,14 request::uri,
14 },15 },
@@ -16,9 +17,11 @@ use topcoat::{
16 view::{Unescaped, View, view},17 view::{Unescaped, View, view},
17 };18 };
18 19
20+use crate::editor_assets::{self, EditorAssets};
19 use crate::hub::Hub;21 use crate::hub::Hub;
20 use crate::i18n::{self, Msg, t};22 use crate::i18n::{self, Msg, t};
21-use crate::store::Store;23+use crate::media::Media;
24+use crate::store::{ListFilter, Store};
22 25
23 use self::pane::{ListSpec, Mobile};26 use self::pane::{ListSpec, Mobile};
24 use topcoat::view::Child;27 use topcoat::view::Child;
@@ -26,10 +29,12 @@ use self::shell::{Section, Shelf, SidebarData, notebook_name, sidebar, title_of,
26 use self::palette::palette_dialog;29 use self::palette::palette_dialog;
27 30
28 mod lang;31 mod lang;
32+mod media;
29 mod notebooks;33 mod notebooks;
30 mod notes;34 mod notes;
31 mod pane;35 mod pane;
32 mod export_all;36 mod export_all;
37+mod format;
33 mod import;38 mod import;
34 mod palette;39 mod palette;
35 mod scheme;40 mod scheme;
@@ -38,7 +43,7 @@ mod shell;
38 mod trash;43 mod trash;
39 mod unfiled;44 mod unfiled;
40 45
41-/// Builds the app router. `assets/` (built editor.js and editor.css) is served at the46+/// Builds the app router. `assets/` (editor.css and the hashed editor bundle from `cargo xtask editor`) is served at the
42 /// site root; the Tailwind stylesheet comes from the Topcoat asset bundle, which must be47 /// site root; the Tailwind stylesheet comes from the Topcoat asset bundle, which must be
43 /// built next to the executable with `topcoat asset bundle`.48 /// built next to the executable with `topcoat asset bundle`.
44 /// The theme's fonts, self-hosted from `fonts/` (variable weight, SIL OFL 1.1) and served49 /// The theme's fonts, self-hosted from `fonts/` (variable weight, SIL OFL 1.1) and served
@@ -75,12 +80,49 @@ const ATKINSON_MONO: Font = font! {
75 }80 }
76 };81 };
77 82
78-pub fn router(store: Arc<Store>, hub: Arc<Hub>) -> Router {83+/// Caches the content-hashed editor files for a year. Their names change with their
84+/// contents, so a cached copy never goes stale. Other files in `assets/` are untouched.
85+struct ImmutableEditorFiles;
86+
87+impl Layer for ImmutableEditorFiles {
88+ fn path(&self) -> Option<&Path> {
89+ None
90+ }
91+
92+ fn handle<'a>(&'a self, cx: &'a Cx, body: Body, next: Next<'a>) -> LayerFuture<'a> {
93+ Box::pin(async move {
94+ let mut response = next.run(cx, body).await?;
95+ let name = uri(cx).path().trim_start_matches('/');
96+ if let Some(content_type) = editor_assets::content_type(name) {
97+ let status = response.status();
98+ if status.is_success() || status == StatusCode::NOT_MODIFIED {
99+ let headers = response.headers_mut();
100+ headers.insert(
101+ header::CACHE_CONTROL,
102+ HeaderValue::from_static("public, max-age=31536000, immutable"),
103+ );
104+ headers.insert(header::CONTENT_TYPE, HeaderValue::from_static(content_type));
105+ }
106+ }
107+ Ok(response)
108+ })
109+ }
110+}
111+
112+pub fn router(store: Arc<Store>, hub: Arc<Hub>, media: Arc<Media>) -> Router {
113+ // Read once at startup. `None` leaves the note page without preload hints.
114+ let editor: Arc<Option<EditorAssets>> = Arc::new(EditorAssets::load());
79 module_router!()115 module_router!()
80 .route(export_all::export_zip)116 .route(export_all::export_zip)
81 .route(import::import_file)117 .route(import::import_file)
118+ .route(media::upload_media)
119+ .route(media::serve_media)
120+ .route(media::serve_take)
121+ .route(media::recording_socket)
122+ .route(format::format_code)
82 // Imported files arrive form-encoded, which can grow a file several times over.123 // Imported files arrive form-encoded, which can grow a file several times over.
83- .layer(BodyLimit::max(32 * 1024 * 1024).at("/import/file"))124+ .layer(BodyLimit::max(128 * 1024 * 1024).at("/import/file"))
125+ .layer(ImmutableEditorFiles)
84 .cookies()126 .cookies()
85 .font(ATKINSON_NEXT)127 .font(ATKINSON_NEXT)
86 .font(ATKINSON_MONO)128 .font(ATKINSON_MONO)
@@ -88,6 +130,8 @@ pub fn router(store: Arc<Store>, hub: Arc<Hub>) -> Router {
88 .assets(AssetBundle::load().expect("asset bundle missing: run `topcoat asset bundle`"))130 .assets(AssetBundle::load().expect("asset bundle missing: run `topcoat asset bundle`"))
89 .app_context(store)131 .app_context(store)
90 .app_context(hub)132 .app_context(hub)
133+ .app_context(editor)
134+ .app_context(media)
91 .build()135 .build()
92 }136 }
93 137
@@ -112,13 +156,10 @@ async fn layout(cx: &Cx, slot: Slot<'_>) -> Result<impl View> {
112 let store = app_context::<Arc<Store>>(cx);156 let store = app_context::<Arc<Store>>(cx);
113 let lang = i18n::lang(cx);157 let lang = i18n::lang(cx);
114 let scheme = crate::scheme::scheme(cx);158 let scheme = crate::scheme::scheme(cx);
115- let notes = store.list_notes().await.map_err(topcoat::Error::from_anyhow)?;
116 let notebooks = store.list_notebooks().await.map_err(topcoat::Error::from_anyhow)?;159 let notebooks = store.list_notebooks().await.map_err(topcoat::Error::from_anyhow)?;
117- let trash_count = store160+ let (all_count, unfiled_count, trash_count) =
118- .list_trash()161+ store.count_notes().await.map_err(topcoat::Error::from_anyhow)?;
119- .await162+ let notebook_counts = store.notebook_counts().await.map_err(topcoat::Error::from_anyhow)?;
120- .map_err(topcoat::Error::from_anyhow)?
121- .len();
122 163
123 let (q, toast_key, undo) = match query_params::<ShellQuery>(cx) {164 let (q, toast_key, undo) = match query_params::<ShellQuery>(cx) {
124 Ok(query) => (query.q.clone(), query.toast.clone(), query.undo.clone()),165 Ok(query) => (query.q.clone(), query.toast.clone(), query.undo.clone()),
@@ -174,17 +215,12 @@ async fn layout(cx: &Cx, slot: Slot<'_>) -> Result<impl View> {
174 format!("{page_name} \u{b7} {}", t(lang, Msg::AppName))215 format!("{page_name} \u{b7} {}", t(lang, Msg::AppName))
175 };216 };
176 217
177- let all_count = notes.len();
178- let unfiled_count = notes.iter().filter(|n| n.notebook_id.is_none()).count();
179 let shelves: Vec<Shelf> = notebooks218 let shelves: Vec<Shelf> = notebooks
180 .iter()219 .iter()
181 .map(|nb| Shelf {220 .map(|nb| Shelf {
182 id: nb.id.clone(),221 id: nb.id.clone(),
183 name: nb.name.clone(),222 name: nb.name.clone(),
184- count: notes223+ count: notebook_counts.get(&nb.id).copied().unwrap_or(0),
185- .iter()
186- .filter(|n| n.notebook_id.as_deref() == Some(nb.id.as_str()))
187- .count(),
188 })224 })
189 .collect();225 .collect();
190 226
@@ -288,17 +324,19 @@ async fn index(cx: &Cx) -> Result<impl View> {
288 /// Every note in the list pane, nothing open yet. Also what an empty search shows.324 /// Every note in the list pane, nothing open yet. Also what an empty search shows.
289 async fn all_notes(cx: &Cx) -> Result<impl View> {325 async fn all_notes(cx: &Cx) -> Result<impl View> {
290 let store = app_context::<Arc<Store>>(cx);326 let store = app_context::<Arc<Store>>(cx);
291- let notes = store.list_notes().await.map_err(topcoat::Error::from_anyhow)?;
292 let notebooks = store.list_notebooks().await.map_err(topcoat::Error::from_anyhow)?;327 let notebooks = store.list_notebooks().await.map_err(topcoat::Error::from_anyhow)?;
293- let previews = store.previews().await.map_err(topcoat::Error::from_anyhow)?;328+ let page = pane::load_page(cx, store, ListFilter::All)
329+ .await
330+ .map_err(topcoat::Error::from_anyhow)?;
294 let lang = i18n::lang(cx);331 let lang = i18n::lang(cx);
295 let spec = ListSpec {332 let spec = ListSpec {
296 title: t(lang, Msg::AllNotes).to_owned(),333 title: t(lang, Msg::AllNotes).to_owned(),
297 heading: true,334 heading: true,
298- count: notes.len(),335+ count: page.total,
299 notebook_id: String::new(),336 notebook_id: String::new(),
300- groups: pane::groups(lang, &notes, &notebooks, &previews, None, true),337+ groups: pane::groups(lang, &page.notes, &notebooks, &page.previews, None, true),
301 empty: t(lang, Msg::NoNotesYet),338 empty: t(lang, Msg::NoNotesYet),
339+ more: page.more,
302 };340 };
303 let list = pane::list_pane(cx, lang, spec, Child::new(()));341 let list = pane::list_pane(cx, lang, spec, Child::new(()));
304 Ok(pane::split(342 Ok(pane::split(
src/app/export_all.rsmodified+297 -70
@@ -1,72 +1,58 @@
1-//! GET /export.zip: every note outside the trash, as markdown files in one zip.1+//! GET /export.zip: every note outside the trash, as markdown files in one zip, and the
2+//! media files in a `media` folder that the notes' `/media/` links are pointed at.
2 //! Notes in a notebook go into a folder named after it; unfiled notes sit at the root.3 //! Notes in a notebook go into a folder named after it; unfiled notes sit at the root.
3 4
5+use std::borrow::Cow;
4 use std::collections::{HashMap, HashSet};6 use std::collections::{HashMap, HashSet};
5-use std::io::{Cursor, Write};7+use std::io::{BufWriter, Write};
8+use std::pin::Pin;
6 use std::sync::Arc;9 use std::sync::Arc;
10+use std::task::{Context, Poll};
7 use std::time::{SystemTime, UNIX_EPOCH};11 use std::time::{SystemTime, UNIX_EPOCH};
8 12
13+use bytes::Bytes;
14+use http_body::Frame;
15+use tokio::sync::mpsc;
9 use topcoat::{16 use topcoat::{
10 Result,17 Result,
11 context::{Cx, app_context},18 context::{Cx, app_context},
12- router::{header, route},19+ router::{Body, header, route},
13 };20 };
14-use zip::{CompressionMethod, ZipWriter, write::SimpleFileOptions};21+use loro::LoroDoc;
15 22
16 use crate::export;23 use crate::export;
17-use crate::hub::load_doc;24+use crate::hub::Hub;
18-use crate::store::Store;25+use crate::media::Media;
26+use crate::store::{DocBytes, Notebook, Store};
27+use crate::zipout::{Deflated, ZipOut};
19 28
20 const MAX_NAME_CHARS: usize = 100;29 const MAX_NAME_CHARS: usize = 100;
30+/// Most notes read and rendered together while exporting.
31+const EXPORT_BATCH: usize = 2000;
32+/// Bytes of stored notes read together, about: batches shrink for big notes, or a
33+/// batch of huge notes would not fit in memory.
34+const LOAD_BATCH_BYTES: usize = 64 << 20;
35+/// Bytes of cached export markdown read and rendered together.
36+const EXPORT_BATCH_BYTES: usize = 8 << 20;
37+/// Bytes of the zip sent to the client at a time.
38+const SEND_CHUNK: usize = 256 * 1024;
21 39
22-/// GET /export.zip: a zip of the live markdown of every non-trashed note.40+/// GET /export.zip: a zip of the live markdown of every non-trashed note, and of every
41+/// media file under `media/`. The zip is streamed while it is made, so the download
42+/// starts at once and the server holds one batch of notes at a time, however many there
43+/// are.
23 #[route(GET "/export.zip")]44 #[route(GET "/export.zip")]
24-pub async fn export_zip(cx: &Cx) -> Result<([(&'static str, String); 2], Vec<u8>)> {45+pub async fn export_zip(cx: &Cx) -> Result<([(&'static str, String); 2], Body)> {
25- let store = app_context::<Arc<Store>>(cx);46+ let store = app_context::<Arc<Store>>(cx).clone();
26- let notes = store.list_notes().await.map_err(topcoat::Error::from_anyhow)?;47+ let media = app_context::<Arc<Media>>(cx).clone();
27- let notebooks = store.list_notebooks().await.map_err(topcoat::Error::from_anyhow)?;48+ let hub = app_context::<Arc<Hub>>(cx).clone();
28- let titles: HashMap<String, String> = notes49+ let (tx, rx) = mpsc::channel(8);
29- .iter()50+ tokio::spawn(async move {
30- .map(|note| (note.id.clone(), note.title.clone()))51+ if let Err(err) = write_zip(&store, &media, &hub, tx.clone()).await {
31- .collect();52+ eprintln!("export failed: {err:#}");
32-53+ let _ = tx.send(Err(std::io::Error::other(err))).await;
33- let mut folder_names: HashMap<String, String> = HashMap::new();54+ }
34- let mut folder_taken = HashSet::new();55+ });
35- let mut file_taken = HashSet::new();
36- let mut entries: Vec<(String, String)> = Vec::with_capacity(notes.len());
37-
38- for note in &notes {
39- let folder = match note
40- .notebook_id
41- .as_deref()
42- .and_then(|id| notebooks.iter().find(|nb| nb.id == id))
43- {
44- Some(nb) => folder_names
45- .entry(nb.id.clone())
46- .or_insert_with(|| unique(&mut folder_taken, "", &sanitize(&nb.name)))
47- .clone(),
48- None => String::new(),
49- };
50-
51- let doc = load_doc(store, &note.id).await.map_err(topcoat::Error::from_anyhow)?;
52- let resolve = |id: &str| titles.get(id).cloned();
53- let markdown = export::to_markdown_with(&doc, &resolve);
54-
55- let stem = unique(&mut file_taken, &folder, &sanitize(&note.title));
56- let path = if folder.is_empty() {
57- format!("{stem}.md")
58- } else {
59- format!("{folder}/{stem}.md")
60- };
61- entries.push((path, markdown));
62- }
63-
64- let bytes = tokio::task::spawn_blocking(move || build_zip(entries))
65- .await
66- .map_err(anyhow::Error::from)
67- .and_then(|built| built)
68- .map_err(topcoat::Error::from_anyhow)?;
69-
70 let (year, month, day) = utc_date();56 let (year, month, day) = utc_date();
71 let disposition = format!("attachment; filename=\"notes-{year:04}-{month:02}-{day:02}.zip\"");57 let disposition = format!("attachment; filename=\"notes-{year:04}-{month:02}-{day:02}.zip\"");
72 Ok((58 Ok((
@@ -74,29 +60,270 @@ pub async fn export_zip(cx: &Cx) -> Result<([(&'static str, String); 2], Vec<u8>
74 (header::CONTENT_TYPE.as_str(), "application/zip".to_owned()),60 (header::CONTENT_TYPE.as_str(), "application/zip".to_owned()),
75 (header::CONTENT_DISPOSITION.as_str(), disposition),61 (header::CONTENT_DISPOSITION.as_str(), disposition),
76 ],62 ],
77- bytes,63+ Body::new(ChannelBody(rx)),
78 ))64 ))
79 }65 }
80 66
81-/// Titles of the notes outside the trash, by note id: what wiki-style links resolve to.67+type Chunk = std::io::Result<Bytes>;
82-pub(crate) async fn title_map(store: &Store) -> anyhow::Result<HashMap<String, String>> {68+type Zip = ZipOut<BufWriter<ChannelWriter>>;
83- Ok(store69+/// A note to export: its index in the file list, its path, its id and its stored bytes.
84- .list_notes()70+type Job = (u32, String, String, DocBytes);
85- .await?71+
86- .into_iter()72+/// Writes the export zip into `tx`. Each batch is rendered and compressed on every
87- .map(|note| (note.id, note.title))73+/// core while the next one is read, then appended. The media files follow the notes,
88- .collect())74+/// one at a time.
75+async fn write_zip(store: &Store, media: &Media, hub: &Hub, tx: mpsc::Sender<Chunk>) -> anyhow::Result<()> {
76+ let notes = store.list_notes().await?;
77+ let notebooks = store.list_notebooks().await?;
78+ let notebooks_by_id: HashMap<&str, &Notebook> = notebooks.iter().map(|nb| (nb.id.as_str(), nb)).collect();
79+ // Links resolve by id: only their targets' titles are needed, not every note's.
80+ let titles = store.titles_of(store.link_targets().await?).await?;
81+
82+ // The (id, path) of every note, in list order: the notes themselves are dropped.
83+ let mut files: Vec<(Box<str>, Box<str>)> = Vec::with_capacity(notes.len() + 1);
84+ {
85+ // Dropped before the export starts: at millions of notes they hold every path again.
86+ let mut folder_names: HashMap<String, String> = HashMap::new();
87+ let mut folder_taken = HashSet::new();
88+ let mut file_taken = HashSet::new();
89+ for note in &notes {
90+ let folder = match note.notebook_id.as_deref().and_then(|id| notebooks_by_id.get(id)) {
91+ Some(nb) => folder_names
92+ .entry(nb.id.clone())
93+ .or_insert_with(|| unique(&mut folder_taken, "", &sanitize(&nb.name)))
94+ .clone(),
95+ None => String::new(),
96+ };
97+ let stem = unique(&mut file_taken, &folder, &sanitize(&note.title));
98+ let path = if folder.is_empty() { format!("{stem}.md") } else { format!("{folder}/{stem}.md") };
99+ files.push((note.id.as_str().into(), path.into()));
100+ }
101+ }
102+ drop((notes, notebooks_by_id));
103+
104+ let titles = Arc::new(titles);
105+ let linking = Arc::new(store.linking_notes().await?);
106+ let mut zip: Zip = ZipOut::new(BufWriter::with_capacity(SEND_CHUNK, ChannelWriter(tx)), utc_date());
107+ let mut rendering: Option<tokio::task::JoinHandle<anyhow::Result<Rendered>>> = None;
108+ // Renders `jobs` while the previous batch is appended.
109+ let mut next = async |zip: Zip, jobs: Vec<Job>| -> anyhow::Result<Zip> {
110+ let done = match rendering.take() {
111+ Some(handle) => Some(handle.await??),
112+ None => None,
113+ };
114+ let (titles, linking) = (titles.clone(), linking.clone());
115+ rendering = Some(tokio::task::spawn_blocking(move || render_files(jobs, &titles, &linking)));
116+ match done {
117+ Some(done) => finish_batch(store, zip, done).await,
118+ None => Ok(zip),
119+ }
120+ };
121+
122+ // Notes whose export markdown is cached and current come first, in one read.
123+ let index: HashMap<&str, usize> = files.iter().enumerate().map(|(i, (id, _))| (&**id, i)).collect();
124+ let mut written = vec![false; files.len()];
125+ let stale: HashSet<String> = store.stale_snapshots().await?.into_iter().collect();
126+ let mut cached = store.scan_export_texts(EXPORT_BATCH_BYTES)?;
127+ while let Some(batch) = cached.recv().await {
128+ let jobs: Vec<Job> = batch?
129+ .into_iter()
130+ .filter(|(id, _)| !stale.contains(id))
131+ .filter_map(|(id, md)| {
132+ let i = *index.get(id.as_str())?;
133+ if std::mem::replace(&mut written[i], true) {
134+ return None;
135+ }
136+ let path = files[i].1.to_string();
137+ let doc = DocBytes { snapshot: None, updates: Vec::new(), markdown: None, export: Some(md), upto_seq: 0 };
138+ Some((i as u32, path, id, doc))
139+ })
140+ .collect();
141+ zip = next(zip, jobs).await?;
142+ }
143+ // The rest from their stored docs, in batches.
144+ drop(index);
145+ let rest: Vec<u32> = (0..files.len() as u32).filter(|&i| !written[i as usize]).collect();
146+ drop(written);
147+ // Sized by the notes read so far, starting at one: these are often the few huge ones.
148+ let (mut at, mut size) = (0, 1);
149+ while at < rest.len() {
150+ let batch = &rest[at..(at + size).min(rest.len())];
151+ at += batch.len();
152+ let ids: Vec<String> = batch.iter().map(|&i| files[i as usize].0.to_string()).collect();
153+ let docs = store.load_docs(&ids, &linking).await?;
154+ let bytes: usize = docs.iter().map(DocBytes::stored_len).sum();
155+ size = (LOAD_BATCH_BYTES / (bytes / batch.len()).max(1)).clamp(1, EXPORT_BATCH);
156+ let jobs = batch.iter().zip(ids).zip(docs).map(|((&i, id), doc)| (i, files[i as usize].1.to_string(), id, doc)).collect();
157+ zip = next(zip, jobs).await?;
158+ }
159+ drop(next);
160+ if let Some(handle) = rendering.take() {
161+ zip = finish_batch(store, zip, handle.await??).await?;
162+ }
163+ drop(rest);
164+ // Media, one file in memory at a time: each is read, stored and appended before the next.
165+ for name in media.list().await? {
166+ let bytes = tokio::fs::read(media.path(&name)).await?;
167+ let file = tokio::task::spawn_blocking(move || Deflated::fast(&bytes)).await??;
168+ let path = format!("media/{name}");
169+ let index = files.len() as u32;
170+ files.push((name.as_str().into(), path.as_str().into()));
171+ zip = append(zip, vec![(index, path, file)]).await?;
172+ }
173+ // Takes, each joined from its closed parts, at the URL their embeds use.
174+ for id in media.takes().await? {
175+ let Some((joined, _)) = media.joined_take(&id, &hub.attached(&id)).await? else { continue };
176+ let bytes = tokio::fs::read(&joined).await?;
177+ let file = tokio::task::spawn_blocking(move || Deflated::fast(&bytes)).await??;
178+ let path = format!("media/rec/{id}");
179+ let index = files.len() as u32;
180+ files.push((id.as_str().into(), path.as_str().into()));
181+ zip = append(zip, vec![(index, path, file)]).await?;
182+ }
183+ tokio::task::spawn_blocking(move || -> anyhow::Result<()> {
184+ zip.finish(|i| &files[i as usize].1)?.into_inner().map_err(|e| e.into_error())?;
185+ Ok(())
186+ })
187+ .await?
188+}
189+
190+/// Appends a rendered batch to the zip and caches the export markdown it rendered, so
191+/// the next export of those notes needs no doc.
192+async fn finish_batch(store: &Store, zip: Zip, done: Rendered) -> anyhow::Result<Zip> {
193+ if !done.cache.is_empty() {
194+ store.put_export_texts(&done.cache).await?;
195+ }
196+ append(zip, done.files).await
197+}
198+
199+/// Appends compressed files to the zip on a blocking thread: sending waits for the client.
200+async fn append(mut zip: Zip, files: Vec<(u32, String, Deflated)>) -> anyhow::Result<Zip> {
201+ tokio::task::spawn_blocking(move || {
202+ for (name, path, file) in files {
203+ zip.add(name, &path, file)?;
204+ }
205+ Ok(zip)
206+ })
207+ .await?
208+}
209+
210+/// Renders and compresses every `(path, id, bytes)` job on scoped threads, keeping the
211+/// job order. Threads take the next job when done, so one huge note keeps one thread
212+/// busy rather than holding back a share of the others.
213+fn render_files(jobs: Vec<Job>, titles: &HashMap<String, String>, linking: &HashSet<String>) -> anyhow::Result<Rendered> {
214+ let threads = std::thread::available_parallelism().map_or(1, |n| n.get()).min(jobs.len().max(1));
215+ let next = std::sync::atomic::AtomicUsize::new(0);
216+ let (queue, next) = (&jobs, &next);
217+ let mut done: Vec<(usize, Deflated, Option<String>)> = std::thread::scope(|scope| {
218+ let handles: Vec<_> = (0..threads)
219+ .map(|_| {
220+ scope.spawn(move || -> anyhow::Result<Vec<(usize, Deflated, Option<String>)>> {
221+ let mut out = Vec::new();
222+ loop {
223+ let i = next.fetch_add(1, std::sync::atomic::Ordering::Relaxed);
224+ let Some((_, _, id, bytes)) = queue.get(i) else { return Ok(out) };
225+ let (md, cache) = render(bytes, titles, linking, id)?;
226+ let md = media_links(&md, &queue[i].1);
227+ out.push((i, Deflated::new(md.as_bytes())?, cache));
228+ }
229+ })
230+ })
231+ .collect();
232+ let mut done = Vec::with_capacity(queue.len());
233+ for handle in handles {
234+ done.extend(handle.join().map_err(|_| anyhow::anyhow!("export thread panicked"))??);
235+ }
236+ anyhow::Ok(done)
237+ })?;
238+ done.sort_unstable_by_key(|(i, _, _)| *i);
239+ let mut cache = Vec::new();
240+ let mut files = Vec::with_capacity(done.len());
241+ for ((name, path, id, bytes), (_, file, md)) in jobs.into_iter().zip(done) {
242+ files.push((name, path, file));
243+ if let Some(md) = md {
244+ cache.push((id, bytes.upto_seq, md));
245+ }
246+ }
247+ Ok(Rendered { files, cache })
248+}
249+
250+/// Points a note's `/media/` links at the zip's `media` folder, relative to the note's
251+/// file: `media/` for a note at the root, `../media/` for one in a notebook folder.
252+/// Plain text, so it also works on cached export markdown; the cache keeps `/media/`.
253+fn media_links<'a>(md: &'a str, path: &str) -> Cow<'a, str> {
254+ if !md.contains("](/media/") {
255+ return Cow::Borrowed(md);
256+ }
257+ let to = if path.contains('/') { "../media/" } else { "media/" };
258+ Cow::Owned(md.replace("](/media/", &format!("]({to}")))
259+}
260+
261+/// A batch of the export: its files in order, and export markdown to cache.
262+struct Rendered {
263+ files: Vec<(u32, String, Deflated)>,
264+ cache: Vec<(String, i64, String)>,
265+}
266+
267+/// Sends what is written to it to the response body, waiting while the client is behind.
268+struct ChannelWriter(mpsc::Sender<Chunk>);
269+
270+impl Write for ChannelWriter {
271+ fn write(&mut self, buf: &[u8]) -> std::io::Result<usize> {
272+ self.0
273+ .blocking_send(Ok(Bytes::copy_from_slice(buf)))
274+ .map_err(|_| std::io::Error::new(std::io::ErrorKind::BrokenPipe, "the download was cancelled"))?;
275+ Ok(buf.len())
276+ }
277+
278+ fn flush(&mut self) -> std::io::Result<()> {
279+ Ok(())
280+ }
281+}
282+
283+/// A response body fed by a [`ChannelWriter`].
284+struct ChannelBody(mpsc::Receiver<Chunk>);
285+
286+impl http_body::Body for ChannelBody {
287+ type Data = Bytes;
288+ type Error = std::io::Error;
289+
290+ fn poll_frame(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Option<std::io::Result<Frame<Bytes>>>> {
291+ self.0.poll_recv(cx).map(|chunk| chunk.map(|chunk| chunk.map(Frame::data)))
292+ }
89 }293 }
90 294
91-/// Writes every `(path, markdown)` pair into a deflate-compressed zip held in memory.295+/// One note's markdown, and its export markdown to cache when it was rendered here.
92-fn build_zip(entries: Vec<(String, String)>) -> anyhow::Result<Vec<u8>> {296+/// A cached one only needs the current titles; a note without note links exports as
93- let options = SimpleFileOptions::default().compression_method(CompressionMethod::Deflated);297+/// its stored markdown; any other is imported and rendered.
94- let mut zip = ZipWriter::new(Cursor::new(Vec::new()));298+fn render<'a>(
95- for (path, markdown) in entries {299+ bytes: &'a DocBytes,
96- zip.start_file(path, options)?;300+ titles: &HashMap<String, String>,
97- zip.write_all(markdown.as_bytes())?;301+ linking: &HashSet<String>,
302+ id: &str,
303+) -> anyhow::Result<(Cow<'a, str>, Option<String>)> {
304+ let resolve = |id: &str| titles.get(id).cloned();
305+ if let Some(md) = &bytes.export {
306+ return Ok((export::resolve_deferred(md, &resolve).into(), None));
307+ }
308+ let pending = bytes.snapshot.is_none() && bytes.updates.is_empty();
309+ if let Some(md) = bytes.markdown.as_ref().filter(|_| pending || !linking.contains(id)) {
310+ return Ok((Cow::Borrowed(md), None));
311+ }
312+ let doc = LoroDoc::new();
313+ if let Some(snapshot) = &bytes.snapshot {
314+ doc.import(snapshot)?;
315+ }
316+ for update in &bytes.updates {
317+ doc.import(update)?;
318+ }
319+ match export::to_markdown_deferred(&doc) {
320+ // Cached only for a snapshot with nothing after it, the key of the cache.
321+ Some(md) => {
322+ let out = export::resolve_deferred(&md, &resolve);
323+ Ok((out.into(), (bytes.snapshot.is_some() && bytes.updates.is_empty()).then_some(md)))
324+ }
325+ None => Ok((export::to_markdown_with(&doc, &resolve).into(), None)),
98 }326 }
99- Ok(zip.finish()?.into_inner())
100 }327 }
101 328
102 /// Makes a file or folder name safe on common systems: reserved characters and control329 /// Makes a file or folder name safe on common systems: reserved characters and control
src/app/format.rsadded+34 -0
@@ -0,0 +1,34 @@
1+//! POST /format: formats a code block for the editor. The formatters run on a blocking
2+//! thread, and the answer is the formatted code as plain text.
3+
4+use serde::Deserialize;
5+use topcoat::{
6+ Result,
7+ router::{StatusCode, content::Json, error::content_too_large, route},
8+};
9+
10+/// The most `code` the endpoint accepts, in bytes.
11+const MAX_CODE_BYTES: usize = 256 * 1024;
12+
13+#[derive(Deserialize)]
14+struct FormatInput {
15+ /// Canonical lowercase language id, such as `rust`.
16+ language: String,
17+ /// The code to format.
18+ code: String,
19+}
20+
21+/// POST /format: the formatted code, or 422 with the reason it could not be formatted.
22+#[route(POST "/format")]
23+pub async fn format_code(Json(input): Json<FormatInput>) -> Result<(StatusCode, String)> {
24+ if input.code.len() > MAX_CODE_BYTES {
25+ return Err(content_too_large().into());
26+ }
27+ let result = tokio::task::spawn_blocking(move || crate::format::format(&input.language, &input.code))
28+ .await
29+ .map_err(|err| topcoat::Error::from_anyhow(err.into()))?;
30+ Ok(match result {
31+ Ok(text) => (StatusCode::OK, text),
32+ Err(message) => (StatusCode::UNPROCESSABLE_ENTITY, message),
33+ })
34+}
src/app/import.rsmodified+153 -73
@@ -5,6 +5,7 @@
5 //! with a folder component puts the note in the notebook named by its first segment5 //! with a folder component puts the note in the notebook named by its first segment
6 //! (found by case-insensitive name, else created). A path without one is unfiled.6 //! (found by case-insensitive name, else created). A path without one is unfiled.
7 7
8+use std::collections::HashMap;
8 use std::path::Path;9 use std::path::Path;
9 use std::sync::Arc;10 use std::sync::Arc;
10 11
@@ -20,15 +21,23 @@ use crate::app::export_all::sanitize;
20 use crate::components::button::{ButtonSize, ButtonVariant, button_variants};21 use crate::components::button::{ButtonSize, ButtonVariant, button_variants};
21 use crate::export;22 use crate::export;
22 use crate::i18n::{self, Msg, t};23 use crate::i18n::{self, Msg, t};
23-use crate::import::{markdown_to_doc, markdown_to_update};24+use crate::hub::Hub;
25+use crate::import::{heading_title, markdown_to_doc, rewrite_media, starts_with_heading};
24 use crate::store::Store;26 use crate::store::Store;
25 27
28+/// Files at least this big are stored as markdown first, then get their doc built
29+/// (in the background when another import is building one).
30+const BUILD_LATER_BYTES: usize = 1 << 20;
31+
26 #[derive(Deserialize)]32 #[derive(Deserialize)]
27 struct ImportForm {33 struct ImportForm {
28 /// Path of the file within the chosen folder, or just the file name.34 /// Path of the file within the chosen folder, or just the file name.
29 path: String,35 path: String,
30 /// The file's contents.36 /// The file's contents.
31 text: String,37 text: String,
38+ /// JSON object from a file path within the root to its `/media/` URL. Empty for none.
39+ #[serde(default)]
40+ media: String,
32 }41 }
33 42
34 /// POST /import/file: creates a note from one markdown file and answers with its id.43 /// POST /import/file: creates a note from one markdown file and answers with its id.
@@ -61,68 +70,60 @@ pub async fn import_file(cx: &Cx, Form(input): Form<ImportForm>) -> Result<Strin
61 70
62 // The first folder below the selected root is the notebook. Files directly in the71 // The first folder below the selected root is the notebook. Files directly in the
63 // root are unfiled.72 // root are unfiled.
64- let notebook_id = match segments.len() {73+ let notebook = (segments.len() >= 2).then(|| sanitize(segments[0]));
65- n if n >= 2 => {
66- let name = sanitize(segments[0]);
67- let notebooks = store.list_notebooks().await.map_err(topcoat::Error::from_anyhow)?;
68- let existing = notebooks
69- .iter()
70- .find(|nb| nb.name.to_lowercase() == name.to_lowercase())
71- .map(|nb| nb.id.clone());
72- match existing {
73- Some(id) => Some(id),
74- None => {
75- let nb = store
76- .create_notebook(&name)
77- .await
78- .map_err(topcoat::Error::from_anyhow)?;
79- Some(nb.id)
80- }
81- }
82- }
83- _ => None,
84- };
85 74
86 // A note's title is its first block's text. Without a leading heading, the file75 // A note's title is its first block's text. Without a leading heading, the file
87 // name becomes one, so the note is listed under the file's name.76 // name becomes one, so the note is listed under the file's name.
88 // Front matter goes first, or it would no longer lead the file once a heading is77 // Front matter goes first, or it would no longer lead the file once a heading is
89 // put in front of it.78 // put in front of it.
90- let text = crate::import::strip_front_matter(&input.text);79+ let media: HashMap<String, String> = if input.media.is_empty() {
91- let markdown = if export::to_markdown(80+ HashMap::new()
92- &markdown_to_doc(text).map_err(topcoat::Error::from_anyhow)?,
93- )
94- .starts_with('#')
95- {
96- text.to_owned()
97 } else {81 } else {
98- format!("# {stem}\n\n{text}")82+ match serde_json::from_str(&input.media) {
83+ Ok(map) => map,
84+ Err(_) => return Err(bad_request("malformed media map").into()),
85+ }
99 };86 };
100- let doc = markdown_to_doc(&markdown).map_err(topcoat::Error::from_anyhow)?;87+ let text = crate::import::strip_front_matter(&input.text).to_owned();
101- let title = export::title(&doc);88+ let text = rewrite_media(&text, &segments.join("/"), &media);
102- let body = export::to_markdown(&doc);89+ if text.len() >= BUILD_LATER_BYTES {
103- let update = markdown_to_update(&markdown).map_err(topcoat::Error::from_anyhow)?;90+ let markdown = tokio::task::spawn_blocking(move || {
91+ let markdown = if starts_with_heading(&text) { text } else { format!("# {stem}\n\n{text}") };
92+ let title = heading_title(&markdown);
93+ (markdown, title)
94+ });
95+ let (markdown, title) = markdown.await.map_err(|e| topcoat::Error::from_anyhow(e.into()))?;
96+ let id = store
97+ .import_note(notebook.as_deref(), None, &title, &markdown, &[], None)
98+ .await
99+ .map_err(topcoat::Error::from_anyhow)?;
100+ app_context::<Arc<Hub>>(cx).build_now(store, &id).await;
101+ return Ok(id);
102+ }
103+ // Parsing a big file takes a while: off the async workers.
104+ let (snapshot, title, body, links, export) = tokio::task::spawn_blocking(move || -> anyhow::Result<_> {
105+ let doc = if starts_with_heading(&text) {
106+ markdown_to_doc(&text)?
107+ } else {
108+ markdown_to_doc(&format!("# {stem}\n\n{text}"))?
109+ };
110+ // Stored as a snapshot, which the note's room loads lazily on first open.
111+ let snapshot = doc.export(loro::ExportMode::Snapshot)?;
112+ let body = export::Body::read(&doc);
113+ let links = body.note_links();
114+ // A note with note links exports through its cached export markdown, rendered
115+ // here once rather than by the first export of every note.
116+ let export = if links.is_empty() { None } else { body.markdown_deferred() };
117+ Ok((snapshot, body.title(), body.markdown(), links, export))
118+ })
119+ .await
120+ .map_err(|e| topcoat::Error::from_anyhow(e.into()))?
121+ .map_err(topcoat::Error::from_anyhow)?;
104 122
105- let note = store
106- .create_note(notebook_id.as_deref())
107- .await
108- .map_err(topcoat::Error::from_anyhow)?;
109- store
110- .append_update(&note.id, &update)
111- .await
112- .map_err(topcoat::Error::from_anyhow)?;
113- store
114- .set_title(&note.id, &title)
115- .await
116- .map_err(topcoat::Error::from_anyhow)?;
117- store
118- .put_text(&note.id, &title, &body)
119- .await
120- .map_err(topcoat::Error::from_anyhow)?;
121 store123 store
122- .set_links(&note.id, &export::note_links(&doc))124+ .import_note(notebook.as_deref(), Some(&snapshot), &title, &body, &links, export.as_deref())
123 .await125 .await
124- .map_err(topcoat::Error::from_anyhow)?;126+ .map_err(topcoat::Error::from_anyhow)
125- Ok(note.id)
126 }127 }
127 128
128 /// GET /import: picks markdown files or a folder and imports them one by one.129 /// GET /import: picks markdown files or a folder and imports them one by one.
@@ -159,7 +160,7 @@ async fn import_page(cx: &Cx) -> Result<impl View> {
159 >160 >
160 <div class="flex flex-wrap gap-3">161 <div class="flex flex-wrap gap-3">
161 <label class="relative inline-flex rounded-control has-focus-visible:outline-2 has-focus-visible:outline-offset-2 has-focus-visible:outline-ring">162 <label class="relative inline-flex rounded-control has-focus-visible:outline-2 has-focus-visible:outline-offset-2 has-focus-visible:outline-ring">
162- <input id="import-files" type="file" multiple=(true) accept=".md,.markdown,.txt" class="sr-only">163+ <input id="import-files" type="file" multiple=(true) class="sr-only">
163 <span class=(button_variants(ButtonVariant::Outline, ButtonSize::Md))>(choose_files)</span>164 <span class=(button_variants(ButtonVariant::Outline, ButtonSize::Md))>(choose_files)</span>
164 </label>165 </label>
165 <label class="relative inline-flex rounded-control has-focus-visible:outline-2 has-focus-visible:outline-offset-2 has-focus-visible:outline-ring">166 <label class="relative inline-flex rounded-control has-focus-visible:outline-2 has-focus-visible:outline-offset-2 has-focus-visible:outline-ring">
@@ -177,8 +178,10 @@ async fn import_page(cx: &Cx) -> Result<impl View> {
177 })178 })
178 }179 }
179 180
180-/// Collects the chosen files, keeps markdown and text, and posts them one at a time so181+/// Collects the chosen files, keeps markdown and text as notes and everything else as
181-/// that a notebook created by one file is found by the next. The status line and the182+/// media, and posts the notes one at a time so that a notebook created by one file is
183+/// found by the next. Each note's media references are uploaded first, once per file.
184+/// A selection of media alone becomes one note per media file. The status line and the
182 /// done text come from the data attributes on #import, so the script has no strings.185 /// done text come from the data attributes on #import, so the script has no strings.
183 pub const IMPORT_SCRIPT: &str = r#"186 pub const IMPORT_SCRIPT: &str = r#"
184 (function () {187 (function () {
@@ -189,6 +192,7 @@ pub const IMPORT_SCRIPT: &str = r#"
189 var files = document.getElementById('import-files');192 var files = document.getElementById('import-files');
190 var folder = document.getElementById('import-folder');193 var folder = document.getElementById('import-folder');
191 var supported = /\.(md|markdown|txt)$/i;194 var supported = /\.(md|markdown|txt)$/i;
195+ var embedded = /\.(png|jpg|jpeg|gif|webp|avif|bmp|mp3|m4a|wav|flac|aac|ogg|oga|opus|weba|mp4|m4v|webm|mov|ogv)$/i;
192 var busy = false;196 var busy = false;
193 197
194 function fill(template, values) {198 function fill(template, values) {
@@ -197,11 +201,50 @@ pub const IMPORT_SCRIPT: &str = r#"
197 }, template);201 }, template);
198 }202 }
199 203
200- function run(items) {204+ function baseName(path) {
201- var total = items.length;205+ return path.slice(path.lastIndexOf('/') + 1);
206+ }
207+
208+ function stemOf(name) {
209+ var dot = name.lastIndexOf('.');
210+ return dot > 0 ? name.slice(0, dot) : name;
211+ }
212+
213+ // Dotfiles and files inside dot-folders (such as .obsidian) are not imported.
214+ function hidden(path) {
215+ return path.split('/').some(function (part) { return part.charAt(0) === '.'; });
216+ }
217+
218+ // Whether the note text names the file, raw or percent-encoded. `lower` is lowercased.
219+ function mentions(lower, name) {
220+ return lower.indexOf(name.toLowerCase()) >= 0 ||
221+ lower.indexOf(encodeURI(name).toLowerCase()) >= 0;
222+ }
223+
224+ // The note text that embeds a media file on its own.
225+ function ownText(item) {
226+ var dest = /\s/.test(item.name) ? '<' + item.name + '>' : item.name;
227+ if (embedded.test(item.name)) return '![' + stemOf(item.name) + '](' + dest + ')';
228+ return '[' + item.name + '](' + dest + ')';
229+ }
230+
231+ function upload(item) {
232+ return fetch('/media?name=' + encodeURIComponent(item.file.name), {
233+ method: 'POST',
234+ body: item.file,
235+ credentials: 'same-origin'
236+ }).then(function (res) {
237+ if (!res.ok) throw new Error('upload');
238+ return res.text();
239+ });
240+ }
241+
242+ function run(notes, media) {
243+ var total = notes.length;
202 var imported = 0;244 var imported = 0;
203 var failed = 0;245 var failed = 0;
204 var index = 0;246 var index = 0;
247+ var uploads = {};
205 busy = true;248 busy = true;
206 link.classList.add('hidden');249 link.classList.add('hidden');
207 250
@@ -213,20 +256,44 @@ pub const IMPORT_SCRIPT: &str = r#"
213 busy = false;256 busy = false;
214 }257 }
215 258
259+ // Each media file is uploaded once per run. A failure is counted once and its
260+ // reference is left out of every note.
261+ function uploadOnce(item) {
262+ if (!uploads[item.path]) {
263+ uploads[item.path] = upload(item).catch(function () {
264+ failed++;
265+ return '';
266+ });
267+ }
268+ return uploads[item.path];
269+ }
270+
216 function next() {271 function next() {
217 if (index >= total) return finish();272 if (index >= total) return finish();
218 status.textContent = fill(root.dataset.progress, { done: index + 1, total: total });273 status.textContent = fill(root.dataset.progress, { done: index + 1, total: total });
219- var item = items[index++];274+ var note = notes[index++];
220- item.file.text()275+ note.file.text()
221 .then(function (text) {276 .then(function (text) {
222- var body = new URLSearchParams();277+ var lower = text.toLowerCase();
223- body.set('path', item.path);278+ var refs = media.filter(function (item) { return mentions(lower, item.name); });
224- body.set('text', text);279+ var map = {};
225- return fetch('/import/file', {280+ return refs.reduce(function (chain, item) {
226- method: 'POST',281+ return chain.then(function () {
227- headers: { 'Content-Type': 'application/x-www-form-urlencoded' },282+ return uploadOnce(item).then(function (url) {
228- body: body,283+ if (url) map[item.path] = url;
229- credentials: 'same-origin'284+ });
285+ });
286+ }, Promise.resolve()).then(function () {
287+ var body = new URLSearchParams();
288+ body.set('path', note.path);
289+ body.set('text', text);
290+ body.set('media', JSON.stringify(map));
291+ return fetch('/import/file', {
292+ method: 'POST',
293+ headers: { 'Content-Type': 'application/x-www-form-urlencoded' },
294+ body: body,
295+ credentials: 'same-origin'
296+ });
230 });297 });
231 })298 })
232 .then(function (res) {299 .then(function (res) {
@@ -244,23 +311,36 @@ pub const IMPORT_SCRIPT: &str = r#"
244 if (busy) return;311 if (busy) return;
245 var picked = Array.prototype.slice.call(input.files || []);312 var picked = Array.prototype.slice.call(input.files || []);
246 input.value = '';313 input.value = '';
247- var items = [];314+ var notes = [];
315+ var media = [];
248 picked.forEach(function (file) {316 picked.forEach(function (file) {
249- if (!supported.test(file.name)) return;
250 var path = file.name;317 var path = file.name;
251 if (fromFolder) {318 if (fromFolder) {
252 var rel = file.webkitRelativePath || file.name;319 var rel = file.webkitRelativePath || file.name;
253 var slash = rel.indexOf('/');320 var slash = rel.indexOf('/');
254 path = slash >= 0 ? rel.slice(slash + 1) : rel;321 path = slash >= 0 ? rel.slice(slash + 1) : rel;
255 }322 }
256- items.push({ file: file, path: path });323+ if (hidden(path)) return;
324+ if (supported.test(file.name)) {
325+ notes.push({ file: file, path: path });
326+ } else {
327+ media.push({ file: file, path: path, name: baseName(path) });
328+ }
257 });329 });
258- if (items.length === 0) {330+ if (notes.length === 0) {
331+ notes = media.map(function (item) {
332+ return {
333+ file: new Blob([ownText(item)]),
334+ path: item.path.replace(/(\.[^.\/]*)?$/, '.md')
335+ };
336+ });
337+ }
338+ if (notes.length === 0) {
259 status.textContent = root.dataset.none;339 status.textContent = root.dataset.none;
260 link.classList.add('hidden');340 link.classList.add('hidden');
261 return;341 return;
262 }342 }
263- run(items);343+ run(notes, media);
264 });344 });
265 }345 }
266 346
src/app/media.rsadded+449 -0
@@ -0,0 +1,449 @@
1+//! Media routes: POST /media stores a raw upload, and GET /media/{file} serves it back with
2+//! HTTP Range support, so audio and video can seek. GET /media/rec/{session} serves a recording
3+//! take, and GET /media/live takes the audio of a recording over a WebSocket.
4+
5+use std::io::SeekFrom;
6+use std::path::Path;
7+use std::pin::Pin;
8+use std::sync::Arc;
9+use std::task::{Context, Poll};
10+use std::time::Duration;
11+
12+use bytes::Bytes;
13+use http_body::Frame;
14+use tokio::io::{AsyncRead, AsyncSeekExt, AsyncWriteExt, ReadBuf};
15+use tokio::sync::oneshot;
16+use topcoat::{
17+ Result,
18+ context::{Cx, app_context},
19+ router::{
20+ Body, Method, StatusCode, header, path_param, query_params,
21+ content::websocket::{Message, WebSocket, WebSocketUpgrade},
22+ error::{content_too_large, not_found},
23+ request::{headers, method},
24+ response::Response,
25+ route,
26+ },
27+};
28+
29+use crate::hub::{Attachment, Detach, Hub};
30+use crate::media::{MAX_BYTES, Media, StoreError, content_type, ext_of, part_file, take_bytes, valid_name, valid_session};
31+use crate::store::Store;
32+
33+/// Bytes read from disk per response frame.
34+const CHUNK_SIZE: usize = 64 * 1024;
35+/// Largest frame a recording socket takes: a chunk can grow large after a long retry.
36+const MAX_FRAME: usize = 16 << 20;
37+/// Silence after which a recording socket counts as disconnected.
38+const FRAME_WAIT: Duration = Duration::from_secs(5);
39+/// Cache-Control of a stored file, which never changes under its name.
40+const IMMUTABLE: &str = "public, max-age=31536000, immutable";
41+
42+/// The `name` parameter of an upload: the original file name.
43+#[query_params(error = bad_request)]
44+pub struct MediaQuery {
45+ /// The file's name as the user chose it. Only its extension is kept.
46+ pub name: Option<String>,
47+}
48+
49+/// The parameters of a recording socket. `part` is text so a bad one is refused on the socket.
50+#[query_params(error = bad_request)]
51+pub struct LiveQuery {
52+ /// A note to start a new take of.
53+ pub note: Option<String>,
54+ /// A take to continue, or to reconnect to with `part`.
55+ pub session: Option<String>,
56+ /// The part of `session` to reconnect to.
57+ pub part: Option<String>,
58+}
59+
60+path_param!(file);
61+path_param!(session);
62+
63+/// POST /media?name=...: stores the raw request body and answers with its URL.
64+#[route(POST "/media")]
65+pub async fn upload_media(cx: &Cx, body: Body) -> Result<String> {
66+ let media = app_context::<Arc<Media>>(cx);
67+ let name = query_params::<MediaQuery>(cx)?.name.clone().unwrap_or_default();
68+ match media.store(&ext_of(&name), body).await {
69+ Ok(file) => Ok(format!("/media/{file}")),
70+ Err(StoreError::TooLarge) => Err(content_too_large().into()),
71+ Err(StoreError::Failed(err)) => Err(topcoat::Error::from_anyhow(err)),
72+ }
73+}
74+
75+/// GET /media/{file}: a stored file, inline when its type is safe to show and a download
76+/// otherwise. HEAD gets the headers alone.
77+#[route(GET "/media/{file}")]
78+pub async fn serve_media(cx: &Cx) -> Result<Response> {
79+ let media = app_context::<Arc<Media>>(cx);
80+ let name = path_param::<File>(cx);
81+ if !valid_name(name) {
82+ return Err(not_found().into());
83+ }
84+ let Some((_, ext)) = name.split_once('.') else {
85+ return Err(not_found().into());
86+ };
87+ file_response(cx, &media.path(name), ext, IMMUTABLE, None).await
88+}
89+
90+/// GET /media/rec/{session}: a take, its closed parts joined into one WebM. Parts a socket is
91+/// still writing are left out, and the answer is revalidated against the join key.
92+#[route(GET "/media/rec/{session}")]
93+pub async fn serve_take(cx: &Cx) -> Result<Response> {
94+ let media = app_context::<Arc<Media>>(cx);
95+ let hub = app_context::<Arc<Hub>>(cx);
96+ let id = path_param::<Session>(cx);
97+ if !valid_session(id) {
98+ return take_missing();
99+ }
100+ let joined = media
101+ .joined_take(id, &hub.attached(id))
102+ .await
103+ .map_err(topcoat::Error::from_anyhow)?;
104+ let Some((path, key)) = joined else {
105+ return take_missing();
106+ };
107+ let etag = format!("\"{}\"", blake3::hash(key.as_bytes()).to_hex());
108+ if not_modified(cx, &etag) {
109+ return Ok(Response::builder()
110+ .status(StatusCode::NOT_MODIFIED)
111+ .header(header::CACHE_CONTROL, "no-cache")
112+ .header(header::ETAG, etag)
113+ .body(Body::empty())?);
114+ }
115+ file_response(cx, &path, "weba", "no-cache", Some(&etag)).await
116+}
117+
118+/// The 404 of a take with no audio to serve. Not cached, since audio may arrive.
119+fn take_missing() -> Result<Response> {
120+ Ok(Response::builder()
121+ .status(StatusCode::NOT_FOUND)
122+ .header(header::CACHE_CONTROL, "no-store")
123+ .header("x-content-type-options", "nosniff")
124+ .header("content-security-policy", "sandbox; default-src 'none'")
125+ .body(Body::empty())?)
126+}
127+
128+/// Whether the request's `If-None-Match` names `etag`.
129+fn not_modified(cx: &Cx, etag: &str) -> bool {
130+ headers(cx)
131+ .get(header::IF_NONE_MATCH)
132+ .and_then(|v| v.to_str().ok())
133+ .is_some_and(|list| list.split(',').map(str::trim).any(|tag| tag == etag || tag == "*"))
134+}
135+
136+/// GET /media/live: the audio of a recording. `?note=` starts a take, `?session=` continues one
137+/// with a new part, and `?session=&part=` reconnects to a part. The socket is upgraded first, so a
138+/// refusal arrives as a `reject` frame and is not mistaken for the server being offline.
139+#[route(GET "/media/live")]
140+pub async fn recording_socket(cx: &Cx, upgrade: WebSocketUpgrade) -> Result<Response> {
141+ let store = app_context::<Arc<Store>>(cx).clone();
142+ let hub = app_context::<Arc<Hub>>(cx).clone();
143+ let media = app_context::<Arc<Media>>(cx).clone();
144+ let (note, session, part) = {
145+ let query = query_params::<LiveQuery>(cx)?;
146+ (query.note.clone(), query.session.clone(), query.part.clone())
147+ };
148+ upgrade
149+ .max_message_size(MAX_FRAME)
150+ .max_frame_size(MAX_FRAME)
151+ .on_upgrade(move |socket| async move {
152+ serve_recording(store, hub, media, note, session, part, socket).await;
153+ })
154+}
155+
156+/// Whether `note` is an id of a note that exists.
157+async fn note_exists(store: &Store, note: &str) -> bool {
158+ super::is_note_id(note) && matches!(store.get_note(note).await, Ok(Some(_)))
159+}
160+
161+/// The take and part a recording socket asks for, as `(note, session, part)`. `None` when the
162+/// request is refused: a bad or missing id, an unknown note, or a bad part number. A new take is
163+/// created here, with `part` None.
164+async fn recording_target(
165+ store: &Store,
166+ media: &Media,
167+ note: Option<String>,
168+ session: Option<String>,
169+ part: Option<String>,
170+) -> Option<(String, String, Option<u32>)> {
171+ if let Some(session) = session {
172+ if !valid_session(&session) {
173+ return None;
174+ }
175+ let note = session.split('.').next()?.to_owned();
176+ if !note_exists(store, &note).await {
177+ return None;
178+ }
179+ let part = part.map(|p| p.parse::<u32>()).transpose().ok()?;
180+ return Some((note, session, part));
181+ }
182+ let note = note?;
183+ if !note_exists(store, &note).await {
184+ return None;
185+ }
186+ let session = media.new_take(&note).await.ok()?;
187+ Some((note, session, None))
188+}
189+
190+/// Drives one recording socket: attaches it to a part, then stores the chunks it sends.
191+async fn serve_recording(
192+ store: Arc<Store>,
193+ hub: Arc<Hub>,
194+ media: Arc<Media>,
195+ note: Option<String>,
196+ session: Option<String>,
197+ part: Option<String>,
198+ mut socket: WebSocket,
199+) {
200+ let Some((note, session, part)) = recording_target(&store, &media, note, session, part).await else {
201+ return refuse(socket).await;
202+ };
203+ let dir = media.take_dir(&session);
204+ let Attachment { part, token, mut stop } = match hub.attach(&note, &session, part, &dir) {
205+ Ok(Some(attachment)) => attachment,
206+ _ => return refuse(socket).await,
207+ };
208+ let (mut file, len) = match open_part(&part_file(&dir, part)).await {
209+ Ok(opened) => opened,
210+ Err(err) => {
211+ eprintln!("opening part {part} of take {session} failed: {err:#}");
212+ hub.detach(&note, &session, part, token, Detach::Lost);
213+ return refuse(socket).await;
214+ }
215+ };
216+ if socket.send(Message::text(format!("ready {session} {part} {len}"))).await.is_err() {
217+ hub.detach(&note, &session, part, token, Detach::Lost);
218+ return;
219+ }
220+ match receive_part(&mut socket, &mut file, &dir, len, &mut stop).await {
221+ Exit::Ended => {
222+ let _ = socket.send(Message::text("done")).await;
223+ hub.detach(&note, &session, part, token, Detach::Ended);
224+ }
225+ Exit::Refused => {
226+ let _ = socket.send(Message::text("reject")).await;
227+ hub.detach(&note, &session, part, token, Detach::Lost);
228+ }
229+ // A socket that was taken over no longer matches its token, so this detaches nothing.
230+ Exit::Lost | Exit::Taken => hub.detach(&note, &session, part, token, Detach::Lost),
231+ }
232+ let _ = socket.close().await;
233+}
234+
235+/// How a part's socket came to an end.
236+enum Exit {
237+ /// The client sent `end`.
238+ Ended,
239+ /// The socket closed, broke, or went quiet for [`FRAME_WAIT`].
240+ Lost,
241+ /// Another socket took the part over.
242+ Taken,
243+ /// A chunk could not be stored, or the take is full.
244+ Refused,
245+}
246+
247+/// Refuses a recording socket: `reject`, then close.
248+async fn refuse(mut socket: WebSocket) {
249+ let _ = socket.send(Message::text("reject")).await;
250+ let _ = socket.close().await;
251+}
252+
253+/// Opens a part for writing, with its length.
254+async fn open_part(path: &Path) -> std::io::Result<(tokio::fs::File, u64)> {
255+ let file = tokio::fs::OpenOptions::new().write(true).open(path).await?;
256+ let len = file.metadata().await?.len();
257+ Ok((file, len))
258+}
259+
260+/// Stores the binary chunks of a part from `len` on, acking each one, until the client sends
261+/// `end`, goes quiet, or another socket takes the part over.
262+async fn receive_part(
263+ socket: &mut WebSocket,
264+ file: &mut tokio::fs::File,
265+ dir: &Path,
266+ mut len: u64,
267+ stop: &mut oneshot::Receiver<()>,
268+) -> Exit {
269+ loop {
270+ let message = tokio::select! {
271+ _ = &mut *stop => return Exit::Taken,
272+ message = tokio::time::timeout(FRAME_WAIT, socket.recv()) => message,
273+ };
274+ let message = match message {
275+ Ok(Some(Ok(message))) => message,
276+ _ => return Exit::Lost,
277+ };
278+ match message {
279+ Message::Binary(chunk) => {
280+ if write_chunk(file, dir, len, &chunk).await.is_err() {
281+ return Exit::Refused;
282+ }
283+ len += chunk.len() as u64;
284+ if socket.send(Message::text(format!("ack {len}"))).await.is_err() {
285+ return Exit::Lost;
286+ }
287+ }
288+ Message::Text(text) if text.as_str() == "end" => return Exit::Ended,
289+ Message::Close(_) => return Exit::Lost,
290+ _ => {}
291+ }
292+ }
293+}
294+
295+/// Writes `chunk` at `len` and syncs it. A take that would pass [`MAX_BYTES`] is refused, and a
296+/// failed write cuts the part back to `len`.
297+async fn write_chunk(file: &mut tokio::fs::File, dir: &Path, len: u64, chunk: &[u8]) -> std::io::Result<()> {
298+ if take_bytes(dir)? + chunk.len() as u64 > MAX_BYTES {
299+ return Err(std::io::Error::other("the take is larger than the limit"));
300+ }
301+ let result = write_at(file, len, chunk).await;
302+ if result.is_err() {
303+ let _ = file.set_len(len).await;
304+ }
305+ result
306+}
307+
308+async fn write_at(file: &mut tokio::fs::File, len: u64, chunk: &[u8]) -> std::io::Result<()> {
309+ file.seek(SeekFrom::Start(len)).await?;
310+ file.write_all(chunk).await?;
311+ file.sync_data().await
312+}
313+
314+/// Answers a GET or HEAD for the file at `path`: the whole file, or the range the request asks
315+/// for. `cache` is the Cache-Control value, and `etag` the ETag when there is one.
316+async fn file_response(cx: &Cx, path: &Path, ext: &str, cache: &str, etag: Option<&str>) -> Result<Response> {
317+ let mut file = match tokio::fs::File::open(path).await {
318+ Ok(file) => file,
319+ Err(err) if err.kind() == std::io::ErrorKind::NotFound => return Err(not_found().into()),
320+ Err(err) => return Err(topcoat::Error::from_anyhow(err.into())),
321+ };
322+ let meta = file.metadata().await.map_err(|err| topcoat::Error::from_anyhow(err.into()))?;
323+ if !meta.is_file() {
324+ return Err(not_found().into());
325+ }
326+ let len = meta.len();
327+
328+ let (status, start, count, content_range) = match headers(cx).get(header::RANGE).and_then(|v| v.to_str().ok()) {
329+ Some(range) => match span(range, len) {
330+ Span::Whole => (StatusCode::OK, 0, len, None),
331+ Span::Part(start, end) => (
332+ StatusCode::PARTIAL_CONTENT,
333+ start,
334+ end - start + 1,
335+ Some(format!("bytes {start}-{end}/{len}")),
336+ ),
337+ Span::Unsatisfiable => (StatusCode::RANGE_NOT_SATISFIABLE, 0, 0, Some(format!("bytes */{len}"))),
338+ },
339+ None => (StatusCode::OK, 0, len, None),
340+ };
341+
342+ let (mime, disposition) = match content_type(ext) {
343+ Some(mime) => (mime, "inline"),
344+ None => ("application/octet-stream", "attachment"),
345+ };
346+ let mut builder = Response::builder()
347+ .status(status)
348+ .header(header::CONTENT_TYPE, mime)
349+ .header(header::CONTENT_LENGTH, count.to_string())
350+ .header(header::CONTENT_DISPOSITION, disposition)
351+ .header(header::ACCEPT_RANGES, "bytes")
352+ .header(header::CACHE_CONTROL, cache)
353+ .header("x-content-type-options", "nosniff");
354+ if let Some(etag) = etag {
355+ builder = builder.header(header::ETAG, etag);
356+ }
357+ // Browsers refuse to show a PDF in a sandbox, and a PDF cannot run script on this origin.
358+ if ext != "pdf" {
359+ builder = builder.header("content-security-policy", "sandbox; default-src 'none'");
360+ }
361+ if let Some(range) = content_range {
362+ builder = builder.header(header::CONTENT_RANGE, range);
363+ }
364+ let body = if count == 0 || method(cx) == Method::HEAD {
365+ Body::empty()
366+ } else {
367+ file.seek(SeekFrom::Start(start))
368+ .await
369+ .map_err(|err| topcoat::Error::from_anyhow(err.into()))?;
370+ Body::new(FileBody { file, remaining: count })
371+ };
372+ Ok(builder.body(body)?)
373+}
374+
375+/// What a `Range` header asks for, against a file of some length.
376+#[derive(Debug, PartialEq)]
377+enum Span {
378+ /// No range the server honours: the whole file.
379+ Whole,
380+ /// The bytes `start..=end`.
381+ Part(u64, u64),
382+ /// No byte of the file is asked for.
383+ Unsatisfiable,
384+}
385+
386+/// Reads one `bytes=a-b`, `bytes=a-` or `bytes=-n` range against a file of `len` bytes.
387+/// Multiple ranges and malformed headers are ignored, and the whole file is served.
388+fn span(value: &str, len: u64) -> Span {
389+ let Some((first, last)) = value.trim().strip_prefix("bytes=").and_then(|s| s.split_once('-')) else {
390+ return Span::Whole;
391+ };
392+ let (first, last) = (first.trim(), last.trim());
393+ if first.is_empty() {
394+ // The last `n` bytes.
395+ let Ok(n) = last.parse::<u64>() else { return Span::Whole };
396+ if n == 0 || len == 0 {
397+ return Span::Unsatisfiable;
398+ }
399+ return Span::Part(len.saturating_sub(n), len - 1);
400+ }
401+ let Ok(start) = first.parse::<u64>() else { return Span::Whole };
402+ if start >= len {
403+ return Span::Unsatisfiable;
404+ }
405+ let end = if last.is_empty() {
406+ len - 1
407+ } else {
408+ match last.parse::<u64>() {
409+ Ok(end) if end >= start => end.min(len - 1),
410+ _ => return Span::Whole,
411+ }
412+ };
413+ Span::Part(start, end)
414+}
415+
416+/// Streams the next `remaining` bytes of an open file, a chunk at a time.
417+struct FileBody {
418+ file: tokio::fs::File,
419+ remaining: u64,
420+}
421+
422+impl http_body::Body for FileBody {
423+ type Data = Bytes;
424+ type Error = std::io::Error;
425+
426+ fn poll_frame(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Option<std::io::Result<Frame<Bytes>>>> {
427+ let this = self.get_mut();
428+ if this.remaining == 0 {
429+ return Poll::Ready(None);
430+ }
431+ let want = this.remaining.min(CHUNK_SIZE as u64) as usize;
432+ let mut chunk = vec![0u8; want];
433+ let mut buf = ReadBuf::new(&mut chunk);
434+ match Pin::new(&mut this.file).poll_read(cx, &mut buf) {
435+ Poll::Pending => Poll::Pending,
436+ Poll::Ready(Err(err)) => Poll::Ready(Some(Err(err))),
437+ Poll::Ready(Ok(())) => {
438+ let n = buf.filled().len();
439+ if n == 0 {
440+ let err = std::io::Error::new(std::io::ErrorKind::UnexpectedEof, "media file is shorter than its length");
441+ return Poll::Ready(Some(Err(err)));
442+ }
443+ chunk.truncate(n);
444+ this.remaining -= n as u64;
445+ Poll::Ready(Some(Ok(Frame::data(Bytes::from(chunk)))))
446+ }
447+ }
448+ }
449+}
src/app/notebooks/notebook_id.rsmodified+7 -9
@@ -23,7 +23,7 @@ use crate::components::dropdown_menu::{
23 use crate::components::floating::FloatingAlign;23 use crate::components::floating::FloatingAlign;
24 use crate::components::input::input;24 use crate::components::input::input;
25 use crate::i18n::{self, Msg, t};25 use crate::i18n::{self, Msg, t};
26-use crate::store::Store;26+use crate::store::{ListFilter, Store};
27 27
28 use super::{NameForm, clean_name};28 use super::{NameForm, clean_name};
29 29
@@ -40,22 +40,20 @@ async fn notebook(cx: &Cx) -> Result<impl View> {
40 .await40 .await
41 .map_err(topcoat::Error::from_anyhow)?41 .map_err(topcoat::Error::from_anyhow)?
42 .ok_or_not_found()?;42 .ok_or_not_found()?;
43- let notes = store.list_notes().await.map_err(topcoat::Error::from_anyhow)?;
44 let notebooks = store.list_notebooks().await.map_err(topcoat::Error::from_anyhow)?;43 let notebooks = store.list_notebooks().await.map_err(topcoat::Error::from_anyhow)?;
45- let previews = store.previews().await.map_err(topcoat::Error::from_anyhow)?;44+ let page = pane::load_page(cx, store, ListFilter::Notebook(id.clone()))
46- let in_nb: Vec<_> = notes45+ .await
47- .into_iter()46+ .map_err(topcoat::Error::from_anyhow)?;
48- .filter(|n| n.notebook_id.as_deref() == Some(id.as_str()))
49- .collect();
50 let lang = i18n::lang(cx);47 let lang = i18n::lang(cx);
51- let groups = pane::groups(lang, &in_nb, &notebooks, &previews, None, false);48+ let groups = pane::groups(lang, &page.notes, &notebooks, &page.previews, None, false);
52 let spec = pane::ListSpec {49 let spec = pane::ListSpec {
53 title: nb.name.clone(),50 title: nb.name.clone(),
54 heading: true,51 heading: true,
55- count: in_nb.len(),52+ count: page.total,
56 notebook_id: id.clone(),53 notebook_id: id.clone(),
57 groups,54 groups,
58 empty: t(lang, Msg::EmptyNotebook),55 empty: t(lang, Msg::EmptyNotebook),
56+ more: page.more,
59 };57 };
60 58
61 let rename_action = format!("/notebooks/{id}/rename");59 let rename_action = format!("/notebooks/{id}/rename");
src/app/notes.rsmodified+6 -4
@@ -16,7 +16,7 @@ use crate::components::button::{ButtonSize, ButtonVariant, button};
16 use crate::export;16 use crate::export;
17 use crate::i18n::{self, Msg, t};17 use crate::i18n::{self, Msg, t};
18 use crate::import::{markdown_to_doc, markdown_to_update};18 use crate::import::{markdown_to_doc, markdown_to_update};
19-use crate::store::{Store, title_key};19+use crate::store::{ListFilter, Store, title_key};
20 20
21 mod note_id;21 mod note_id;
22 22
@@ -87,7 +87,10 @@ async fn titles_json(cx: &Cx) -> Result<([(&'static str, String); 1], String)> {
87 };87 };
88 let query = query.trim();88 let query = query.trim();
89 let mut notes = if query.is_empty() {89 let mut notes = if query.is_empty() {
90- store.list_notes().await.map_err(topcoat::Error::from_anyhow)?90+ store
91+ .list_notes_page(ListFilter::All, TITLE_HITS, 0)
92+ .await
93+ .map_err(topcoat::Error::from_anyhow)?
91 } else {94 } else {
92 store95 store
93 .search_titles(query, TITLE_SEARCH_LIMIT)96 .search_titles(query, TITLE_SEARCH_LIMIT)
@@ -186,8 +189,7 @@ async fn note_by_title(cx: &Cx) -> Result<impl View> {
186 let store = app_context::<Arc<Store>>(cx);189 let store = app_context::<Arc<Store>>(cx);
187 let name = path_param::<Title>(cx).to_owned();190 let name = path_param::<Title>(cx).to_owned();
188 let key = title_key(&name);191 let key = title_key(&name);
189- let notes = store.list_notes().await.map_err(topcoat::Error::from_anyhow)?;192+ if let Some(note) = store.note_by_title_key(&key).await.map_err(topcoat::Error::from_anyhow)? {
190- if let Some(note) = notes.iter().find(|note| title_key(&note.title) == key) {
191 return Err(see_other(format!("/notes/{}", note.id)).into());193 return Err(see_other(format!("/notes/{}", note.id)).into());
192 }194 }
193 195
src/app/notes/note_id.rsmodified+107 -29
@@ -9,7 +9,7 @@ use topcoat::{
9 error::{RouterErrorExt, SeeOther, bad_request, see_other},9 error::{RouterErrorExt, SeeOther, bad_request, see_other},
10 header, module_param, page, path_param, route,10 header, module_param, page, path_param, route,
11 },11 },
12- view::{Child, View, attributes, view},12+ view::{Child, Unescaped, View, attributes, view},
13 };13 };
14 14
15 use crate::app::pane::{self, MENU_LINK, Mobile};15 use crate::app::pane::{self, MENU_LINK, Mobile};
@@ -21,21 +21,33 @@ use crate::components::dropdown_menu::{
21 dropdown_menu_sub_trigger, dropdown_menu_trigger,21 dropdown_menu_sub_trigger, dropdown_menu_trigger,
22 };22 };
23 use crate::components::floating::{FloatingAlign, FloatingSide};23 use crate::components::floating::{FloatingAlign, FloatingSide};
24+use crate::components::input::input as text_input;
25+use crate::editor_assets::EditorAssets;
24 use crate::export::html_page;26 use crate::export::html_page;
25 use crate::hub::Hub;27 use crate::hub::Hub;
26 use crate::i18n::{self, Msg, t};28 use crate::i18n::{self, Msg, t};
27-use crate::store::{NoteMeta, Notebook, Store};29+use crate::store::{ListFilter, NoteMeta, Notebook, Store};
28 30
29 mod history;31 mod history;
30 mod ws;32 mod ws;
31 33
32 module_param!(note_id);34 module_param!(note_id);
33 35
36+/// Most notebooks listed in the "Move to" menu. One form per notebook makes the page huge
37+/// with thousands of notebooks; the others are moved to by name.
38+const MOVE_TARGETS: usize = 30;
39+
40+/// How much of a note's imported markdown is previewed while its doc is built.
41+const PREVIEW_MARKDOWN_BYTES: usize = 64 * 1024;
42+
34 #[derive(Deserialize)]43 #[derive(Deserialize)]
35 struct MoveNote {44 struct MoveNote {
36 /// Empty means "no notebook".45 /// Empty means "no notebook".
37 #[serde(default)]46 #[serde(default)]
38 notebook_id: String,47 notebook_id: String,
48+ /// Typed name of the target notebook, from the "Move to" menu's name field.
49+ #[serde(default)]
50+ notebook_name: String,
39 }51 }
40 52
41 /// One note in the "Linked from" list of a note.53 /// One note in the "Linked from" list of a note.
@@ -55,25 +67,20 @@ struct MoveTarget {
55 }67 }
56 68
57 /// Where the note's list goes: the notebook's notes, or every note when it has no69 /// Where the note's list goes: the notebook's notes, or every note when it has no
58-/// notebook. Returns the list's title, the notes, and the list's URL.70+/// notebook. Returns the list's title, the notes it selects, and the list's URL.
59 fn context_list(71 fn context_list(
60 lang: i18n::Lang,72 lang: i18n::Lang,
61 meta: &NoteMeta,73 meta: &NoteMeta,
62 notebooks: &[Notebook],74 notebooks: &[Notebook],
63- notes: Vec<NoteMeta>,75+) -> (String, ListFilter, String, bool) {
64-) -> (String, Vec<NoteMeta>, String, bool) {
65 match shell::notebook_name(notebooks, meta.notebook_id.as_deref()) {76 match shell::notebook_name(notebooks, meta.notebook_id.as_deref()) {
66 Some(name) => {77 Some(name) => {
67 let nb = meta.notebook_id.clone().unwrap_or_default();78 let nb = meta.notebook_id.clone().unwrap_or_default();
68- let inside: Vec<NoteMeta> = notes79+ (name, ListFilter::Notebook(nb.clone()), format!("/notebooks/{nb}"), false)
69- .into_iter()
70- .filter(|n| n.notebook_id.as_deref() == Some(nb.as_str()))
71- .collect();
72- (name, inside, format!("/notebooks/{nb}"), false)
73 }80 }
74 None => (81 None => (
75 t(lang, Msg::AllNotes).to_owned(),82 t(lang, Msg::AllNotes).to_owned(),
76- notes,83+ ListFilter::All,
77 "/".to_owned(),84 "/".to_owned(),
78 true,85 true,
79 ),86 ),
@@ -85,6 +92,7 @@ fn context_list(
85 #[page]92 #[page]
86 async fn note(cx: &Cx) -> Result<impl View> {93 async fn note(cx: &Cx) -> Result<impl View> {
87 let store = app_context::<Arc<Store>>(cx);94 let store = app_context::<Arc<Store>>(cx);
95+ let editor: &Option<EditorAssets> = app_context::<Arc<Option<EditorAssets>>>(cx);
88 let id = path_param::<NoteId>(cx).to_owned();96 let id = path_param::<NoteId>(cx).to_owned();
89 let meta = store97 let meta = store
90 .get_note(&id)98 .get_note(&id)
@@ -92,12 +100,22 @@ async fn note(cx: &Cx) -> Result<impl View> {
92 .map_err(topcoat::Error::from_anyhow)?100 .map_err(topcoat::Error::from_anyhow)?
93 .ok_or_not_found()?;101 .ok_or_not_found()?;
94 let notebooks = store.list_notebooks().await.map_err(topcoat::Error::from_anyhow)?;102 let notebooks = store.list_notebooks().await.map_err(topcoat::Error::from_anyhow)?;
95- let notes = store.list_notes().await.map_err(topcoat::Error::from_anyhow)?;
96- let previews = store.previews().await.map_err(topcoat::Error::from_anyhow)?;
97 let lang = crate::i18n::lang(cx);103 let lang = crate::i18n::lang(cx);
98 104
99 let title = shell::title_of(lang, &meta.title);105 let title = shell::title_of(lang, &meta.title);
100 let trashed = meta.trashed_at.is_some();106 let trashed = meta.trashed_at.is_some();
107+ let prerender = if trashed {
108+ String::new()
109+ } else if let Some(head) = store.pending_head(&id, PREVIEW_MARKDOWN_BYTES).await.map_err(topcoat::Error::from_anyhow)? {
110+ // The doc is still being built from an import: preview the markdown's start.
111+ tokio::task::spawn_blocking(move || crate::import::preview_markdown(&head))
112+ .await
113+ .map_err(|e| topcoat::Error::from_anyhow(e.into()))?
114+ } else {
115+ let hub = app_context::<Arc<Hub>>(cx);
116+ let room = hub.room(store, &id).await.map_err(topcoat::Error::from_anyhow)?;
117+ room.editor_html().await
118+ };
101 let backlinks = if trashed {119 let backlinks = if trashed {
102 Vec::new()120 Vec::new()
103 } else {121 } else {
@@ -125,37 +143,54 @@ async fn note(cx: &Cx) -> Result<impl View> {
125 None => "/unfiled".to_owned(),143 None => "/unfiled".to_owned(),
126 };144 };
127 145
128- let (list_title, list_notes, list_href, show_notebook) =146+ let (list_title, list_filter, list_href, show_notebook) =
129- context_list(lang, &meta, &notebooks, notes);147+ context_list(lang, &meta, &notebooks);
148+ // Only the first page of the list is read. The open note is in it when it is near the top.
149+ let page = pane::load_page(cx, store, list_filter)
150+ .await
151+ .map_err(topcoat::Error::from_anyhow)?;
130 let groups = pane::groups(152 let groups = pane::groups(
131 lang,153 lang,
132- &list_notes,154+ &page.notes,
133 &notebooks,155 &notebooks,
134- &previews,156+ &page.previews,
135 Some(id.as_str()),157 Some(id.as_str()),
136 show_notebook,158 show_notebook,
137 );159 );
138 let spec = pane::ListSpec {160 let spec = pane::ListSpec {
139 title: list_title,161 title: list_title,
140 heading: false,162 heading: false,
141- count: list_notes.len(),163+ count: page.total,
142 notebook_id: current_nb.clone(),164 notebook_id: current_nb.clone(),
143 groups,165 groups,
144 empty: t(lang, Msg::NoNotesYet),166 empty: t(lang, Msg::NoNotesYet),
167+ more: page.more,
145 };168 };
146 let list = pane::list_pane(cx, lang, spec, Child::new(()));169 let list = pane::list_pane(cx, lang, spec, Child::new(()));
147 170
148- let moves: Vec<MoveTarget> = std::iter::once(MoveTarget {171+ let mut moves: Vec<MoveTarget> = std::iter::once(MoveTarget {
149 id: String::new(),172 id: String::new(),
150 name: t(lang, Msg::Unfiled).to_owned(),173 name: t(lang, Msg::Unfiled).to_owned(),
151 current: current_nb.is_empty(),174 current: current_nb.is_empty(),
152 })175 })
153- .chain(notebooks.iter().map(|nb| MoveTarget {176+ .chain(notebooks.iter().take(MOVE_TARGETS).map(|nb| MoveTarget {
154 id: nb.id.clone(),177 id: nb.id.clone(),
155 name: nb.name.clone(),178 name: nb.name.clone(),
156 current: nb.id == current_nb,179 current: nb.id == current_nb,
157 }))180 }))
158 .collect();181 .collect();
182+ // The note's own notebook stays listed even when it is past the first MOVE_TARGETS.
183+ if !current_nb.is_empty() && !moves.iter().any(|m| m.current) {
184+ if let Some(nb) = notebooks.iter().find(|nb| nb.id == current_nb) {
185+ moves.push(MoveTarget {
186+ id: nb.id.clone(),
187+ name: nb.name.clone(),
188+ current: true,
189+ });
190+ }
191+ }
192+ let hidden = notebooks.len() + 1 - moves.len();
193+ let by_name_label = t(lang, Msg::NotebookByName);
159 let already_here = t(lang, Msg::AlreadyHere);194 let already_here = t(lang, Msg::AlreadyHere);
160 let move_reason = if trashed {195 let move_reason = if trashed {
161 t(lang, Msg::RestoreFirst)196 t(lang, Msg::RestoreFirst)
@@ -220,6 +255,23 @@ async fn note(cx: &Cx) -> Result<impl View> {
220 )255 )
221 </form>256 </form>
222 }257 }
258+ if hidden > 0 {
259+ <form method="post" action=(move_action.clone())>
260+ text_input(attrs: attributes! {
261+ type="text"
262+ name="notebook_name"
263+ placeholder=(by_name_label)
264+ aria-label=(by_name_label)
265+ required=(true)
266+ autocomplete="off"
267+ maxlength="120"
268+ disabled=(trashed)
269+ onclick="event.stopPropagation()"
270+ onkeydown="if (event.key !== 'Escape') event.stopPropagation()"
271+ class="h-8 text-sm"
272+ })
273+ </form>
274+ }
223 dropdown_menu_separator()275 dropdown_menu_separator()
224 if !trashed {276 if !trashed {
225 <a href=(history_href) class=(MENU_LINK)>(history_label)</a>277 <a href=(history_href) class=(MENU_LINK)>(history_label)</a>
@@ -291,8 +343,15 @@ async fn note(cx: &Cx) -> Result<impl View> {
291 </form>343 </form>
292 </div>344 </div>
293 } else {345 } else {
294- <div id="editor" class="min-h-0 w-full flex-1" data-note-id=(id.clone()) data-note-title=(title)></div>346+ <div id="editor" class="min-h-0 w-full flex-1" data-note-id=(id.clone()) data-note-title=(title)>
295- <script type="module" src="/editor.js"></script>347+ <div class="ProseMirror" contenteditable="false" translate="no">(Unescaped::new_unchecked(prerender.clone()))</div>
348+ </div>
349+ <script type="application/json" id="editor-strings">(Unescaped::new_unchecked(i18n::editor_strings_json(lang)))</script>
350+ if let Some(assets) = editor {
351+ <link rel="modulepreload" href=(format!("/{}", assets.js))>
352+ <link rel="preload" href=(format!("/{}", assets.wasm)) as="fetch" type="application/wasm" crossorigin="anonymous">
353+ <script type="module" src=(format!("/{}", assets.js))></script>
354+ }
296 if !linked_rows.is_empty() {355 if !linked_rows.is_empty() {
297 <section aria-labelledby="linked-from" class="mx-auto w-full max-w-[calc(68ch+48px)] shrink-0 border-t border-border px-6 pt-4 pb-8">356 <section aria-labelledby="linked-from" class="mx-auto w-full max-w-[calc(68ch+48px)] shrink-0 border-t border-border px-6 pt-4 pb-8">
298 <h2 id="linked-from" class="text-xs font-medium text-muted-foreground">(linked_label)</h2>357 <h2 id="linked-from" class="text-xs font-medium text-muted-foreground">(linked_label)</h2>
@@ -329,7 +388,24 @@ async fn move_note(cx: &Cx, Form(input): Form<MoveNote>) -> Result<SeeOther> {
329 if meta.trashed_at.is_some() {388 if meta.trashed_at.is_some() {
330 return Err(bad_request("the note is in the trash; restore it first").into());389 return Err(bad_request("the note is in the trash; restore it first").into());
331 }390 }
332- let target = input.notebook_id.trim();391+ let typed = input.notebook_name.trim();
392+ let picked = if typed.is_empty() {
393+ None
394+ } else {
395+ let wanted = typed.to_lowercase();
396+ let nb_id = store
397+ .list_notebooks()
398+ .await
399+ .map_err(topcoat::Error::from_anyhow)?
400+ .iter()
401+ .find(|nb| nb.name.trim().to_lowercase() == wanted)
402+ .map(|nb| nb.id.clone());
403+ let Some(nb_id) = nb_id else {
404+ return Err(bad_request(t(i18n::lang(cx), Msg::NoSuchNotebook)).into());
405+ };
406+ Some(nb_id)
407+ };
408+ let target = picked.as_deref().unwrap_or(input.notebook_id.trim());
333 let target = if target.is_empty() {409 let target = if target.is_empty() {
334 None410 None
335 } else {411 } else {
@@ -424,7 +500,7 @@ async fn note_page(cx: &Cx, print: bool) -> Result<(String, String)> {
424 .map_err(topcoat::Error::from_anyhow)?500 .map_err(topcoat::Error::from_anyhow)?
425 .ok_or_not_found()?;501 .ok_or_not_found()?;
426 let room = hub.room(store, &id).await.map_err(topcoat::Error::from_anyhow)?;502 let room = hub.room(store, &id).await.map_err(topcoat::Error::from_anyhow)?;
427- let body = room.html().await;503+ let body = room.html().await.map_err(topcoat::Error::from_anyhow)?;
428 let lang = i18n::lang(cx);504 let lang = i18n::lang(cx);
429 let title = shell::title_of(lang, &meta.title);505 let title = shell::title_of(lang, &meta.title);
430 let page = html_page(&title, &body, lang.code(), print);506 let page = html_page(&title, &body, lang.code(), print);
@@ -442,11 +518,13 @@ async fn export_markdown(cx: &Cx) -> Result<([(&'static str, String); 2], String
442 .await518 .await
443 .map_err(topcoat::Error::from_anyhow)?519 .map_err(topcoat::Error::from_anyhow)?
444 .ok_or_not_found()?;520 .ok_or_not_found()?;
445- let titles = crate::app::export_all::title_map(store)521+ let markdown = match store.pending_markdown(&id).await.map_err(topcoat::Error::from_anyhow)? {
446- .await522+ Some(markdown) => markdown,
447- .map_err(topcoat::Error::from_anyhow)?;523+ None => {
448- let room = hub.room(store, &id).await.map_err(topcoat::Error::from_anyhow)?;524+ let room = hub.room(store, &id).await.map_err(topcoat::Error::from_anyhow)?;
449- let markdown = room.markdown_with(titles).await;525+ room.markdown_with(store).await.map_err(topcoat::Error::from_anyhow)?
526+ }
527+ };
450 let stem = file_stem(&shell::title_of(i18n::lang(cx), &meta.title));528 let stem = file_stem(&shell::title_of(i18n::lang(cx), &meta.title));
451 Ok((529 Ok((
452 [530 [
src/app/notes/note_id/history.rsmodified+1 -1
@@ -79,7 +79,7 @@ async fn history(cx: &Cx) -> Result<impl View> {
79 } else {79 } else {
80 let room = hub.room(store, &id).await.map_err(topcoat::Error::from_anyhow)?;80 let room = hub.room(store, &id).await.map_err(topcoat::Error::from_anyhow)?;
81 match selected {81 match selected {
82- None => room.html().await,82+ None => room.html().await.map_err(topcoat::Error::from_anyhow)?,
83 Some(at) => {83 Some(at) => {
84 let bytes = store84 let bytes = store
85 .get_version(&id, at)85 .get_version(&id, at)
src/app/notes/note_id/ws.rsmodified+3 -1
@@ -24,7 +24,9 @@ async fn websocket(cx: &Cx, upgrade: WebSocketUpgrade) -> Result<Response> {
24 let id = path_param::<NoteId>(cx).to_owned();24 let id = path_param::<NoteId>(cx).to_owned();
25 store.get_note(&id).await.map_err(topcoat::Error::from_anyhow)?.ok_or_not_found()?;25 store.get_note(&id).await.map_err(topcoat::Error::from_anyhow)?.ok_or_not_found()?;
26 let room = hub.room(&store, &id).await.map_err(topcoat::Error::from_anyhow)?;26 let room = hub.room(&store, &id).await.map_err(topcoat::Error::from_anyhow)?;
27- upgrade.on_upgrade(move |socket| async move {27+ // One edit is one message, sent by browsers as one frame: as large as an import.
28+ let max = 128 << 20;
29+ upgrade.max_message_size(max).max_frame_size(max).on_upgrade(move |socket| async move {
28 serve_socket(hub, store, room, socket).await;30 serve_socket(hub, store, room, socket).await;
29 })31 })
30 }32 }
src/app/palette.rsmodified+12 -6
@@ -21,10 +21,12 @@ use crate::components::badge::{BadgeVariant, badge};
21 use crate::components::kbd::{kbd, kbd_group};21 use crate::components::kbd::{kbd, kbd_group};
22 use crate::i18n::{self, Lang, Msg, t};22 use crate::i18n::{self, Lang, Msg, t};
23 use crate::scheme::ALL as SCHEMES;23 use crate::scheme::ALL as SCHEMES;
24-use crate::store::{Notebook, NoteMeta, Store};24+use crate::store::{ListFilter, Notebook, NoteMeta, Store};
25 25
26 /// Most notes, and most notebooks, listed in one result set.26 /// Most notes, and most notebooks, listed in one result set.
27 const LIMIT: usize = 8;27 const LIMIT: usize = 8;
28+/// How long the palette reads long notes for full-text hits; title hits come anyway.
29+const PALETTE_BUDGET: std::time::Duration = std::time::Duration::from_millis(250);
28 30
29 /// Classes of the dialog. It is hidden until `showModal()`, then fades in.31 /// Classes of the dialog. It is hidden until `showModal()`, then fades in.
30 const DIALOG: &str = "m-0 mx-auto top-[15vh] bottom-auto h-auto w-full max-w-none overflow-visible border-0 bg-transparent p-0 text-popover-foreground sm:w-[560px] backdrop:bg-black/40 opacity-0 open:opacity-100 starting:open:opacity-0 transition-[opacity,display] transition-discrete duration-150 ease-out motion-reduce:transition-none";32 const DIALOG: &str = "m-0 mx-auto top-[15vh] bottom-auto h-auto w-full max-w-none overflow-visible border-0 bg-transparent p-0 text-popover-foreground sm:w-[560px] backdrop:bg-black/40 opacity-0 open:opacity-100 starting:open:opacity-0 transition-[opacity,display] transition-discrete duration-150 ease-out motion-reduce:transition-none";
@@ -161,9 +163,12 @@ async fn palette_results(cx: &Cx) -> Result<ViewHandle> {
161 .filter(|c| c.label.to_lowercase().contains(&needle))163 .filter(|c| c.label.to_lowercase().contains(&needle))
162 .collect();164 .collect();
163 let notes: Vec<Item> = if q.is_empty() {165 let notes: Vec<Item> = if q.is_empty() {
164- let all = store.list_notes().await.map_err(topcoat::Error::from_anyhow)?;166+ let recent = store
165- all.iter()167+ .list_notes_page(ListFilter::All, LIMIT, 0)
166- .take(LIMIT)168+ .await
169+ .map_err(topcoat::Error::from_anyhow)?;
170+ recent
171+ .iter()
167 .map(|n| note_item(lang, n, &notebooks, None))172 .map(|n| note_item(lang, n, &notebooks, None))
168 .collect()173 .collect()
169 } else {174 } else {
@@ -171,9 +176,10 @@ async fn palette_results(cx: &Cx) -> Result<ViewHandle> {
171 // "Q4 roadmap"). Full-text hits come first, and a note listed once is not repeated.176 // "Q4 roadmap"). Full-text hits come first, and a note listed once is not repeated.
172 let hits = match crate::matcher::Matcher::simple(&q) {177 let hits = match crate::matcher::Matcher::simple(&q) {
173 Some(matcher) => store178 Some(matcher) => store
174- .search(&matcher, LIMIT)179+ .search(&matcher, LIMIT, Some(PALETTE_BUDGET))
175 .await180 .await
176- .map_err(topcoat::Error::from_anyhow)?,181+ .map_err(topcoat::Error::from_anyhow)?
182+ .hits,
177 None => Vec::new(),183 None => Vec::new(),
178 };184 };
179 let mut seen: HashSet<String> = hits.iter().map(|h| h.note.id.clone()).collect();185 let mut seen: HashSet<String> = hits.iter().map(|h| h.note.id.clone()).collect();
src/app/pane.rsmodified+78 -1
@@ -6,6 +6,7 @@ use std::collections::HashMap;
6 6
7 use topcoat::{7 use topcoat::{
8 context::Cx,8 context::Cx,
9+ router::{query_params, request::uri},
9 view::{Child, View, attributes, view},10 view::{Child, View, attributes, view},
10 };11 };
11 12
@@ -13,10 +14,79 @@ use crate::app::shell::{notebook_name, now_millis, title_of};
13 use crate::components::button::{ButtonSize, ButtonVariant, button};14 use crate::components::button::{ButtonSize, ButtonVariant, button};
14 use crate::components::kbd::kbd;15 use crate::components::kbd::kbd;
15 use crate::i18n::{Lang, Msg, notes_count, relative_time, t};16 use crate::i18n::{Lang, Msg, notes_count, relative_time, t};
16-use crate::store::{Notebook, NoteMeta};17+use crate::store::{ListFilter, Notebook, NoteMeta, Store};
17 18
18 const DAY_MS: i64 = 86_400_000;19 const DAY_MS: i64 = 86_400_000;
19 20
21+/// Rows a list page shows when `?n=` is absent or unreadable.
22+const DEFAULT_ROWS: usize = 100;
23+/// Fewest and most rows a list page shows, whatever `?n=` asks for.
24+const MIN_ROWS: usize = 100;
25+const MAX_ROWS: usize = 5000;
26+
27+/// The `n` query parameter of a list page: how many rows to show.
28+#[query_params(error = bad_request)]
29+pub struct RowsQuery {
30+ pub n: Option<usize>,
31+}
32+
33+/// Rows of the list on this request: `?n=`, clamped to `MIN_ROWS..=MAX_ROWS`.
34+pub fn page_rows(cx: &Cx) -> usize {
35+ query_params::<RowsQuery>(cx)
36+ .ok()
37+ .and_then(|query| query.n)
38+ .unwrap_or(DEFAULT_ROWS)
39+ .clamp(MIN_ROWS, MAX_ROWS)
40+}
41+
42+/// The href of the "Show more" link for a list showing `rows` of `total` rows: this page
43+/// with `n` doubled (up to `MAX_ROWS`) and its other query parameters kept. `None` when
44+/// every row is shown, or when the list is already at `MAX_ROWS`.
45+pub fn more_href(cx: &Cx, rows: usize, total: usize) -> Option<String> {
46+ if total <= rows || rows >= MAX_ROWS {
47+ return None;
48+ }
49+ let target = uri(cx);
50+ let mut pairs: Vec<String> = target
51+ .query()
52+ .unwrap_or("")
53+ .split('&')
54+ .filter(|pair| !pair.is_empty() && pair.split('=').next() != Some("n"))
55+ .map(str::to_owned)
56+ .collect();
57+ pairs.push(format!("n={}", (rows * 2).min(MAX_ROWS)));
58+ Some(format!("{}?{}", target.path(), pairs.join("&")))
59+}
60+
61+/// One page of a list: its rows, their previews, and the list's total count.
62+pub struct ListPage {
63+ pub notes: Vec<NoteMeta>,
64+ pub previews: HashMap<String, String>,
65+ /// Notes the list has in all, not only on this page.
66+ pub total: usize,
67+ /// Href of the "Show more" link, when the list has more rows than this page shows.
68+ pub more: Option<String>,
69+}
70+
71+/// Loads the first page of the notes `filter` selects, sized by `?n=` (see `page_rows`).
72+pub async fn load_page(cx: &Cx, store: &Store, filter: ListFilter) -> anyhow::Result<ListPage> {
73+ let rows = page_rows(cx);
74+ let total = store.count_filter(&filter).await?;
75+ let notes = store.list_notes_page(filter, rows, 0).await?;
76+ let ids: Vec<String> = notes.iter().map(|note| note.id.clone()).collect();
77+ let previews = store.previews_for(&ids).await?;
78+ let more = more_href(cx, rows, total);
79+ Ok(ListPage {
80+ notes,
81+ previews,
82+ total,
83+ more,
84+ })
85+}
86+
87+/// Classes of the "Show more" link under a list, a quiet full-width row.
88+pub const MORE_LINK: &str = "block px-4 py-3 text-sm text-muted-foreground hover:bg-foreground/5";
89+
20 /// Which pane shows below 1024px. Above it, both panes show.90 /// Which pane shows below 1024px. Above it, both panes show.
21 #[derive(Clone, Copy, Debug, PartialEq, Eq)]91 #[derive(Clone, Copy, Debug, PartialEq, Eq)]
22 pub enum Mobile {92 pub enum Mobile {
@@ -53,6 +123,8 @@ pub struct ListSpec {
53 pub groups: Vec<Group>,123 pub groups: Vec<Group>,
54 /// The headline of the empty state, shown when there are no rows.124 /// The headline of the empty state, shown when there are no rows.
55 pub empty: &'static str,125 pub empty: &'static str,
126+ /// Href of a "Show more" link after the rows, when the list has more than it shows.
127+ pub more: Option<String>,
56 }128 }
57 129
58 /// Classes of a note row, and of the selected row (the highlighter swipe).130 /// Classes of a note row, and of the selected row (the highlighter swipe).
@@ -191,10 +263,12 @@ pub fn list_pane<'a>(cx: &'a Cx, lang: Lang, spec: ListSpec, actions: Child<'a>)
191 notebook_id,263 notebook_id,
192 groups,264 groups,
193 empty,265 empty,
266+ more,
194 } = spec;267 } = spec;
195 let count_text = notes_count(lang, count);268 let count_text = notes_count(lang, count);
196 let new_note = t(lang, Msg::NewNote);269 let new_note = t(lang, Msg::NewNote);
197 let create_hint = t(lang, Msg::CreateOneHint);270 let create_hint = t(lang, Msg::CreateOneHint);
271+ let show_more = t(lang, Msg::ShowMore);
198 let is_empty = groups.is_empty();272 let is_empty = groups.is_empty();
199 view! { cx =>273 view! { cx =>
200 <section class="flex min-h-0 min-w-0 flex-1 flex-col">274 <section class="flex min-h-0 min-w-0 flex-1 flex-col">
@@ -239,6 +313,9 @@ pub fn list_pane<'a>(cx: &'a Cx, lang: Lang, spec: ListSpec, actions: Child<'a>)
239 </ul>313 </ul>
240 </div>314 </div>
241 }315 }
316+ if let Some(href) = more {
317+ <a href=(href) class=(MORE_LINK)>(show_more)</a>
318+ }
242 }319 }
243 </div>320 </div>
244 </section>321 </section>
src/app/search.rsmodified+29 -6
@@ -14,9 +14,13 @@ use crate::app::shell::{now_millis, notebook_name, title_of};
14 use crate::i18n::{self, Msg, relative_time, results_for, t};14 use crate::i18n::{self, Msg, relative_time, results_for, t};
15 use crate::matcher::{Matcher, Options};15 use crate::matcher::{Matcher, Options};
16 use crate::store::Store;16 use crate::store::Store;
17+use note_model::links::percent_encode;
17 18
18 /// Most results shown on one page.19 /// Most results shown on one page.
19 const RESULT_LIMIT: usize = 50;20 const RESULT_LIMIT: usize = 50;
21+/// How long a search reads long notes before it shows what it found, with a link to
22+/// search them all.
23+const SEARCH_BUDGET: std::time::Duration = std::time::Duration::from_millis(500);
20 24
21 /// The `q` parameter of the search page and of the sidebar search box, and the search25 /// The `q` parameter of the search page and of the sidebar search box, and the search
22 /// filters, each on when its parameter is "1".26 /// filters, each on when its parameter is "1".
@@ -27,6 +31,8 @@ pub struct SearchQuery {
27 pub word: Option<String>,31 pub word: Option<String>,
28 pub exact: Option<String>,32 pub exact: Option<String>,
29 pub re: Option<String>,33 pub re: Option<String>,
34+ /// "1": read every note, however long it takes.
35+ pub all: Option<String>,
30 }36 }
31 37
32 /// GET /search: notes whose title or text contain every word of `q`.38 /// GET /search: notes whose title or text contain every word of `q`.
@@ -50,13 +56,24 @@ async fn search(cx: &Cx) -> Result<impl View> {
50 return Ok(Child::new(crate::app::all_notes(cx).await?));56 return Ok(Child::new(crate::app::all_notes(cx).await?));
51 }57 }
52 58
53- let hits = match &matcher {59+ let budget = (!flag(&query.all)).then_some(SEARCH_BUDGET);
54- Some(m) => store60+ let (hits, partial) = match &matcher {
55- .search(m, RESULT_LIMIT)61+ Some(m) => {
56- .await62+ let found = store.search(m, RESULT_LIMIT, budget).await.map_err(topcoat::Error::from_anyhow)?;
57- .map_err(topcoat::Error::from_anyhow)?,63+ (found.hits, found.partial)
58- None => Vec::new(),64+ }
65+ None => (Vec::new(), false),
59 };66 };
67+ // The same search without the budget.
68+ let search_all = partial.then(|| {
69+ let mut href = format!("/search?q={}&all=1", percent_encode(&q));
70+ for (on, key) in [(opts.case, "case"), (opts.word, "word"), (opts.exact, "exact"), (opts.regex, "re")] {
71+ if on {
72+ href.push_str(&format!("&{key}=1"));
73+ }
74+ }
75+ href
76+ });
60 let notebooks = store.list_notebooks().await.map_err(topcoat::Error::from_anyhow)?;77 let notebooks = store.list_notebooks().await.map_err(topcoat::Error::from_anyhow)?;
61 let lang = i18n::lang(cx);78 let lang = i18n::lang(cx);
62 let now = now_millis();79 let now = now_millis();
@@ -108,6 +125,12 @@ async fn search(cx: &Cx) -> Result<impl View> {
108 <div class="min-w-0 flex-1">125 <div class="min-w-0 flex-1">
109 <h1 class="truncate text-base font-semibold">(title)</h1>126 <h1 class="truncate text-base font-semibold">(title)</h1>
110 <p class="truncate text-xs text-muted-foreground">(summary)</p>127 <p class="truncate text-xs text-muted-foreground">(summary)</p>
128+ if let Some(href) = search_all {
129+ <p class="text-xs text-muted-foreground">
130+ (t(lang, Msg::SearchPartial))" "
131+ <a href=(href) class="font-medium underline underline-offset-4">(t(lang, Msg::SearchAll))</a>
132+ </p>
133+ }
111 </div>134 </div>
112 </header>135 </header>
113 <div class="min-h-0 flex-1 overflow-y-auto">136 <div class="min-h-0 flex-1 overflow-y-auto">
src/app/shell.rsmodified+19 -1
@@ -580,6 +580,9 @@ async fn scheme_items(current: Scheme, back: String) -> Result<impl View> {
580 const AVATAR: &str = "inline-flex size-8 shrink-0 items-center justify-center rounded-full bg-[var(--active-row)] text-xs font-semibold text-[var(--active-row-foreground)]";580 const AVATAR: &str = "inline-flex size-8 shrink-0 items-center justify-center rounded-full bg-[var(--active-row)] text-xs font-semibold text-[var(--active-row-foreground)]";
581 /// A link row in a menu, with an icon, matching `dropdown_menu_item`.581 /// A link row in a menu, with an icon, matching `dropdown_menu_item`.
582 const MENU_ROW: &str = "flex w-full items-center gap-2 rounded-md px-2 py-1.5 text-left text-sm whitespace-nowrap hover:bg-foreground/5 focus-visible:bg-foreground/5 active:bg-foreground/10";582 const MENU_ROW: &str = "flex w-full items-center gap-2 rounded-md px-2 py-1.5 text-left text-sm whitespace-nowrap hover:bg-foreground/5 focus-visible:bg-foreground/5 active:bg-foreground/10";
583+/// Most notebooks the sidebar lists: a long list makes every page heavy, and the rest are
584+/// found through the command palette.
585+const SIDEBAR_NOTEBOOKS: usize = 100;
583 586
584 /// The sidebar: app name, search, New note, the notes and trash list, notebooks with587 /// The sidebar: app name, search, New note, the notes and trash list, notebooks with
585 /// a new-notebook form, and the theme and language controls. It is a `<nav>` landmark.588 /// a new-notebook form, and the theme and language controls. It is a `<nav>` landmark.
@@ -600,13 +603,20 @@ pub async fn sidebar(lang: Lang, data: SidebarData) -> Result<impl View> {
600 let is_all = section == Section::All;603 let is_all = section == Section::All;
601 let is_unfiled = section == Section::Unfiled;604 let is_unfiled = section == Section::Unfiled;
602 let is_trash = section == Section::Trash;605 let is_trash = section == Section::Trash;
603- let shelves: Vec<(String, String, usize, bool)> = notebooks606+ let mut shelves: Vec<(String, String, usize, bool)> = notebooks
604 .into_iter()607 .into_iter()
605 .map(|shelf| {608 .map(|shelf| {
606 let active = section == Section::Notebook(shelf.id.clone());609 let active = section == Section::Notebook(shelf.id.clone());
607 (format!("/notebooks/{}", shelf.id), shelf.name, shelf.count, active)610 (format!("/notebooks/{}", shelf.id), shelf.name, shelf.count, active)
608 })611 })
609 .collect();612 .collect();
613+ let total_notebooks = shelves.len();
614+ // Keep the first notebooks, plus the open one if it falls past the cut.
615+ let active_past_cap = shelves.iter().skip(SIDEBAR_NOTEBOOKS).find(|shelf| shelf.3).cloned();
616+ shelves.truncate(SIDEBAR_NOTEBOOKS);
617+ shelves.extend(active_past_cap);
618+ let hidden = total_notebooks - shelves.len();
619+ let find_row = format!("{NAV_ITEM} {NAV_IDLE} w-full");
610 let en_pressed = if lang == Lang::En { "true" } else { "false" };620 let en_pressed = if lang == Lang::En { "true" } else { "false" };
611 let tr_pressed = if lang == Lang::Tr { "true" } else { "false" };621 let tr_pressed = if lang == Lang::Tr { "true" } else { "false" };
612 let app = t(lang, Msg::AppName);622 let app = t(lang, Msg::AppName);
@@ -750,6 +760,14 @@ pub async fn sidebar(lang: Lang, data: SidebarData) -> Result<impl View> {
750 nav_item(href: href, label: name, count: count, active: active)760 nav_item(href: href, label: name, count: count, active: active)
751 </li>761 </li>
752 }762 }
763+ if hidden > 0 {
764+ <li>
765+ <button type="button" onclick="window.openPalette && window.openPalette()" class=(find_row)>
766+ <span class="min-w-0 truncate">(t(lang, Msg::FindNotebook))</span>
767+ <span class=(NAV_COUNT)>(hidden)</span>
768+ </button>
769+ </li>
770+ }
753 </ul>771 </ul>
754 <form method="post" action="/notebooks" class="mt-2 flex items-center gap-1.5 px-1">772 <form method="post" action="/notebooks" class="mt-2 flex items-center gap-1.5 px-1">
755 input(attrs: attributes! {773 input(attrs: attributes! {
src/app/trash.rsmodified+15 -5
@@ -12,6 +12,7 @@ use topcoat::{
12 view::{View, attributes, view},12 view::{View, attributes, view},
13 };13 };
14 14
15+use crate::app::pane;
15 use crate::app::shell::now_millis;16 use crate::app::shell::now_millis;
16 use crate::components::button::{ButtonSize, ButtonVariant, button};17 use crate::components::button::{ButtonSize, ButtonVariant, button};
17 use crate::components::dialog::{18 use crate::components::dialog::{
@@ -19,7 +20,7 @@ use crate::components::dialog::{
19 };20 };
20 use crate::hub::Hub;21 use crate::hub::Hub;
21 use crate::i18n::{self, Msg, forever_count, notes_count, relative_time, t};22 use crate::i18n::{self, Msg, forever_count, notes_count, relative_time, t};
22-use crate::store::Store;23+use crate::store::{ListFilter, Store};
23 24
24 mod note_id;25 mod note_id;
25 26
@@ -27,12 +28,18 @@ mod note_id;
27 #[page]28 #[page]
28 async fn trash(cx: &Cx) -> Result<impl View> {29 async fn trash(cx: &Cx) -> Result<impl View> {
29 let store = app_context::<Arc<Store>>(cx);30 let store = app_context::<Arc<Store>>(cx);
30- let trashed = store.list_trash().await.map_err(topcoat::Error::from_anyhow)?;31+ let page = pane::load_page(cx, store, ListFilter::Trash)
31- let previews = store.previews().await.map_err(topcoat::Error::from_anyhow)?;32+ .await
33+ .map_err(topcoat::Error::from_anyhow)?;
32 let lang = i18n::lang(cx);34 let lang = i18n::lang(cx);
33 let now = now_millis();35 let now = now_millis();
34- let count = trashed.len();36+ // The trash's total, not the rows on this page: it decides the empty state and whether
37+ // "Empty trash" shows.
38+ let count = page.total;
39+ let previews = page.previews;
40+ let more = page.more;
35 let title = t(lang, Msg::Trash);41 let title = t(lang, Msg::Trash);
42+ let show_more = t(lang, Msg::ShowMore);
36 let count_text = notes_count(lang, count);43 let count_text = notes_count(lang, count);
37 let retention = t(lang, Msg::TrashRetention);44 let retention = t(lang, Msg::TrashRetention);
38 let empty_label = t(lang, Msg::EmptyTrashAction);45 let empty_label = t(lang, Msg::EmptyTrashAction);
@@ -71,7 +78,7 @@ async fn trash(cx: &Cx) -> Result<impl View> {
71 </div>78 </div>
72 } else {79 } else {
73 <ul class="divide-y divide-border">80 <ul class="divide-y divide-border">
74- for note in trashed {81+ for note in page.notes {
75 <li class="flex flex-wrap items-center gap-3 px-4 py-3 lg:px-8">82 <li class="flex flex-wrap items-center gap-3 px-4 py-3 lg:px-8">
76 <div class="min-w-0 flex-1">83 <div class="min-w-0 flex-1">
77 <p class="truncate text-sm font-medium">(crate::app::shell::title_of(lang, &note.title))</p>84 <p class="truncate text-sm font-medium">(crate::app::shell::title_of(lang, &note.title))</p>
@@ -127,6 +134,9 @@ async fn trash(cx: &Cx) -> Result<impl View> {
127 </li>134 </li>
128 }135 }
129 </ul>136 </ul>
137+ if let Some(href) = more {
138+ <a href=(href) class=(pane::MORE_LINK)>(show_more)</a>
139+ }
130 }140 }
131 if count > 0 {141 if count > 0 {
132 dialog(142 dialog(
src/app/unfiled.rsmodified+7 -6
@@ -9,24 +9,25 @@ use topcoat::{
9 9
10 use crate::app::pane::{self, ListSpec, Mobile};10 use crate::app::pane::{self, ListSpec, Mobile};
11 use crate::i18n::{self, Msg, t};11 use crate::i18n::{self, Msg, t};
12-use crate::store::Store;12+use crate::store::{ListFilter, Store};
13 13
14 /// GET /unfiled: notes that are not in any notebook, beside the list.14 /// GET /unfiled: notes that are not in any notebook, beside the list.
15 #[page]15 #[page]
16 async fn unfiled(cx: &Cx) -> Result<impl View> {16 async fn unfiled(cx: &Cx) -> Result<impl View> {
17 let store = app_context::<Arc<Store>>(cx);17 let store = app_context::<Arc<Store>>(cx);
18- let notes = store.list_notes().await.map_err(topcoat::Error::from_anyhow)?;
19 let notebooks = store.list_notebooks().await.map_err(topcoat::Error::from_anyhow)?;18 let notebooks = store.list_notebooks().await.map_err(topcoat::Error::from_anyhow)?;
20- let previews = store.previews().await.map_err(topcoat::Error::from_anyhow)?;19+ let page = pane::load_page(cx, store, ListFilter::Unfiled)
20+ .await
21+ .map_err(topcoat::Error::from_anyhow)?;
21 let lang = i18n::lang(cx);22 let lang = i18n::lang(cx);
22- let loose: Vec<_> = notes.into_iter().filter(|n| n.notebook_id.is_none()).collect();
23 let spec = ListSpec {23 let spec = ListSpec {
24 title: t(lang, Msg::Unfiled).to_owned(),24 title: t(lang, Msg::Unfiled).to_owned(),
25 heading: true,25 heading: true,
26- count: loose.len(),26+ count: page.total,
27 notebook_id: String::new(),27 notebook_id: String::new(),
28- groups: pane::groups(lang, &loose, &notebooks, &previews, None, false),28+ groups: pane::groups(lang, &page.notes, &notebooks, &page.previews, None, false),
29 empty: t(lang, Msg::EmptyUnfiled),29 empty: t(lang, Msg::EmptyUnfiled),
30+ more: page.more,
30 };31 };
31 let list = pane::list_pane(cx, lang, spec, Child::new(()));32 let list = pane::list_pane(cx, lang, spec, Child::new(()));
32 Ok(pane::split(33 Ok(pane::split(
src/editor_assets.rsadded+60 -0
@@ -0,0 +1,60 @@
1+//! The editor bundle's content-hashed file names, read from `assets/editor.manifest`.
2+//!
3+//! The build tool writes `editor-<16 hex>.js` and `editor-<16 hex>.wasm` into `assets/`
4+//! and a manifest with two lines, `js=<name>` and `wasm=<name>`.
5+
6+/// The names of the current editor files, as served at the site root.
7+#[derive(Debug, Clone, PartialEq, Eq)]
8+pub struct EditorAssets {
9+ pub js: String,
10+ pub wasm: String,
11+}
12+
13+/// The manifest, relative to the working directory like `public_dir`.
14+const MANIFEST: &str = "assets/editor.manifest";
15+
16+impl EditorAssets {
17+ /// Reads the manifest. Returns `None` when it is missing or malformed, logging why.
18+ pub fn load() -> Option<EditorAssets> {
19+ let text = match std::fs::read_to_string(MANIFEST) {
20+ Ok(text) => text,
21+ Err(err) => {
22+ eprintln!("editor assets: cannot read {MANIFEST}: {err}; editor not preloaded");
23+ return None;
24+ }
25+ };
26+ let mut js = None;
27+ let mut wasm = None;
28+ for line in text.lines() {
29+ match line.split_once('=') {
30+ Some(("js", name)) => js = Some(name.trim().to_owned()),
31+ Some(("wasm", name)) => wasm = Some(name.trim().to_owned()),
32+ _ => {}
33+ }
34+ }
35+ match (js, wasm) {
36+ (Some(js), Some(wasm)) if content_type(&js) == Some("text/javascript") && content_type(&wasm) == Some("application/wasm") => {
37+ Some(EditorAssets { js, wasm })
38+ }
39+ _ => {
40+ eprintln!("editor assets: {MANIFEST} must name a hashed js and wasm file; editor not preloaded");
41+ None
42+ }
43+ }
44+ }
45+}
46+
47+/// The content type for a content-hashed editor file name (`editor-<16 hex>.js` or
48+/// `editor-<16 hex>.wasm`), or `None` for any other name.
49+pub fn content_type(name: &str) -> Option<&'static str> {
50+ let (stem, ext) = name.rsplit_once('.')?;
51+ let hash = stem.strip_prefix("editor-")?;
52+ if hash.len() != 16 || !hash.bytes().all(|b| b.is_ascii_hexdigit()) {
53+ return None;
54+ }
55+ match ext {
56+ "js" => Some("text/javascript"),
57+ "wasm" => Some("application/wasm"),
58+ _ => None,
59+ }
60+}
src/export.rsmodified+194 -335
@@ -1,11 +1,12 @@
1-//! Markdown export from a loro-prosemirror shaped LoroDoc.1+//! Markdown export of a note, from its block tree (`note_model::flat`).
2-//!
3-//! Layout (see loro-prosemirror `createLoroMap` / `createLoroText`): the root
4-//! is `doc.get_map("doc")`. Every non-text node is a LoroMap with `nodeName`,
5-//! `attributes` (LoroMap) and `children` (LoroList). Children are either node
6-//! maps or a LoroText whose rich-text deltas carry the marks as attributes.
7 2
8-use loro::{Container, LoroDoc, LoroMap, LoroText, LoroValue, TextDelta, ValueOrContainer};3+use loro::LoroDoc;
4+use note_model::links::{link_target, percent_encode};
5+use note_model::marks::Marks;
6+use note_model::write::{Block, Inline};
7+
8+pub use note_model::links::{LinkTarget, note_links};
9+pub use note_model::tree::title;
9 10
10 mod html;11 mod html;
11 pub use html::{html_page, to_html};12 pub use html::{html_page, to_html};
@@ -18,85 +19,144 @@ pub type Resolve<'a> = &'a dyn Fn(&str) -> Option<String>;
18 #[derive(Clone, Copy)]19 #[derive(Clone, Copy)]
19 struct Ctx<'a> {20 struct Ctx<'a> {
20 wiki: Option<Resolve<'a>>,21 wiki: Option<Resolve<'a>>,
22+ /// Set by `to_markdown_deferred`: links by id become placeholders, counted here.
23+ deferred: Option<&'a std::cell::Cell<usize>>,
21 }24 }
22 25
26+/// Placeholder marks for links by id in `to_markdown_deferred`: Unicode noncharacters,
27+/// which text does not hold.
28+const DEFER_START: char = '\u{FDD0}';
29+const DEFER_SEP: char = '\u{FDD1}';
30+const DEFER_END: char = '\u{FDD2}';
31+
23 /// Full note as CommonMark/GFM. Note links stay ordinary markdown links, which is32 /// Full note as CommonMark/GFM. Note links stay ordinary markdown links, which is
24 /// what the search text wants.33 /// what the search text wants.
25 pub fn to_markdown(doc: &LoroDoc) -> String {34 pub fn to_markdown(doc: &LoroDoc) -> String {
26- render_doc(doc, Ctx { wiki: None })35+ Body::read(doc).markdown()
27 }36 }
28 37
29 /// Full note as markdown with note links written as `[[Title]]` (or `[[Title|text]]`38 /// Full note as markdown with note links written as `[[Title]]` (or `[[Title|text]]`
30 /// when the link text differs). Links by title use the stored title; links by id use39 /// when the link text differs). Links by title use the stored title; links by id use
31 /// `resolve`, and an id it cannot name stays an ordinary link.40 /// `resolve`, and an id it cannot name stays an ordinary link.
32 pub fn to_markdown_with(doc: &LoroDoc, resolve: Resolve<'_>) -> String {41 pub fn to_markdown_with(doc: &LoroDoc, resolve: Resolve<'_>) -> String {
33- render_doc(doc, Ctx { wiki: Some(resolve) })42+ Body::read(doc).markdown_with(resolve)
43+}
44+
45+/// `to_markdown_with` with the titles of links by id left as placeholders, for
46+/// [`resolve_deferred`] to fill in: the result stays right when a linked note is
47+/// renamed. None when the note's text holds the placeholder marks itself.
48+pub fn to_markdown_deferred(doc: &LoroDoc) -> Option<String> {
49+ Body::read(doc).markdown_deferred()
50+}
51+
52+/// A note's body read once. Every whole-note text comes from it without the doc, so
53+/// the hub reads it under the room lock (one pass over the text) and renders off it.
54+pub struct Body {
55+ blocks: Vec<note_model::flat::FlatBlock>,
56+ links: Vec<LinkTarget>,
57+}
58+
59+/// As [`Body::title`], reading only the doc's start when the title is there: the first
60+/// text block with content, when it ends within that start.
61+pub fn title_of(doc: &LoroDoc) -> String {
62+ const START: usize = 64 << 10;
63+ let text = note_model::flat::body(doc);
64+ let len = text.len_unicode();
65+ if len > START {
66+ if let Ok(delta) = text.slice_delta(0, START, loro::cursor::PosType::Unicode) {
67+ let mut blocks = note_model::flat::read_delta(delta);
68+ blocks.pop(); // may be cut short, and its kind unknown
69+ if let Some(b) = blocks.iter().find(|b| b.attrs.kind.is_text() && !b.plain().trim().is_empty()) {
70+ return note_model::tree::title_from(&b.plain());
71+ }
72+ }
73+ }
74+ Body::read(doc).title()
34 }75 }
35 76
36-fn render_doc(doc: &LoroDoc, cx: Ctx<'_>) -> String {77+impl Body {
37- let root = doc.get_map("doc");78+ pub fn read(doc: &LoroDoc) -> Body {
38- let body = render_children(&root, false, cx);79+ let delta = note_model::flat::body(doc).to_delta();
39- if body.is_empty() {80+ let links = note_model::links::links_in(&delta);
40- String::new()81+ Body { blocks: note_model::flat::read_delta(delta), links }
41- } else {
42- format!("{body}\n")
43 }82 }
44-}
45 83
46-/// A link to another note: by id (`/notes/<id>`) or by title (`/notes/by-title/<title>`).84+ /// As [`title`].
47-#[derive(Clone, Debug, PartialEq, Eq)]85+ pub fn title(&self) -> String {
48-pub enum LinkTarget {86+ let first = self.blocks.iter().find(|b| b.attrs.kind.is_text() && !b.plain().trim().is_empty());
49- Id(String),87+ note_model::tree::title_from(&first.map(|b| b.plain()).unwrap_or_default())
50- Title(String),88+ }
89+
90+ /// As [`note_links`].
91+ pub fn note_links(&self) -> Vec<LinkTarget> {
92+ self.links.clone()
93+ }
94+
95+ /// As [`to_markdown`].
96+ pub fn markdown(&self) -> String {
97+ self.render(Ctx { wiki: None, deferred: None })
98+ }
99+
100+ /// As [`to_markdown_with`].
101+ pub fn markdown_with(&self, resolve: Resolve<'_>) -> String {
102+ self.render(Ctx { wiki: Some(resolve), deferred: None })
103+ }
104+
105+ /// As [`to_markdown_deferred`].
106+ pub fn markdown_deferred(&self) -> Option<String> {
107+ let count = std::cell::Cell::new(0);
108+ let none = |_: &str| None;
109+ let md = self.render(Ctx { wiki: Some(&none), deferred: Some(&count) });
110+ let marks = |c: char| md.chars().filter(|&x| x == c).count();
111+ let n = count.get();
112+ (marks(DEFER_START) == n && marks(DEFER_END) == n && marks(DEFER_SEP) == 4 * n).then_some(md)
113+ }
114+
115+ /// As [`to_html`].
116+ pub fn html(&self) -> String {
117+ html::render_blocks(&note_model::flat::nest(&self.blocks))
118+ }
119+
120+ fn render(&self, cx: Ctx<'_>) -> String {
121+ let body = render_blocks(&note_model::flat::nest(&self.blocks), false, cx);
122+ if body.is_empty() { String::new() } else { format!("{body}\n") }
123+ }
51 }124 }
52 125
53-/// Every note the doc links to, each target once, in document order. Hrefs that are126+/// Fills in the links of a `to_markdown_deferred` result with the current titles,
54-/// not note links are ignored.127+/// as `to_markdown_with` would have written them.
55-pub fn note_links(doc: &LoroDoc) -> Vec<LinkTarget> {128+pub fn resolve_deferred(md: &str, resolve: Resolve<'_>) -> String {
56- let mut out = Vec::new();129+ let mut out = String::with_capacity(md.len());
57- collect_links(&doc.get_map("doc"), &mut out);130+ let mut rest = md;
131+ while let Some(at) = rest.find(DEFER_START) {
132+ out.push_str(&rest[..at]);
133+ let after = &rest[at + DEFER_START.len_utf8()..];
134+ let end = after.find(DEFER_END).unwrap_or(after.len());
135+ let mut fields = after[..end].split(DEFER_SEP);
136+ let mut next = || fields.next().unwrap_or("");
137+ let (id, core, flags, inner, dest) = (next(), next(), next(), next(), next());
138+ out.push_str(&deferred_link(resolve(id), core, flags, inner, dest));
139+ rest = after.get(end + DEFER_END.len_utf8()..).unwrap_or("");
140+ }
141+ out.push_str(rest);
58 out142 out
59 }143 }
60 144
61-fn collect_links(node: &LoroMap, out: &mut Vec<LinkTarget>) {145+/// One link by id of `render_group`, given the note's title if it has one.
62- for child in children(node) {146+fn deferred_link(target: Option<String>, core: &str, flags: &str, inner: &str, dest: &str) -> String {
63- match child {147+ let Some(target) = target else { return format!("[{inner}]({dest})") };
64- Child::Text(text) => {148+ if flags.contains('u') {
65- for delta in text.to_delta() {149+ if let Some(mut link) = wiki_link(&target, core) {
66- let TextDelta::Insert {150+ if flags.contains('e') {
67- attributes: Some(attrs),151+ link = format!("*{link}*");
68- ..152+ }
69- } = delta153+ if flags.contains('s') {
70- else {154+ link = format!("**{link}**");
71- continue;
72- };
73- let Some(href) = attrs
74- .get("link")
75- .and_then(|link| link.get_by_key("href"))
76- .and_then(value_str)
77- else {
78- continue;
79- };
80- if let Some(target) = link_target(&href) {
81- if !out.contains(&target) {
82- out.push(target);
83- }
84- }
85- }
86 }155 }
87- Child::Node(m) => collect_links(&m, out),156+ return link;
88 }157 }
89 }158 }
90-}159+ format!("[{inner}]({})", percent_encode(&format!("{target}.md")))
91-
92-fn link_target(href: &str) -> Option<LinkTarget> {
93- let rest = href.strip_prefix("/notes/")?;
94- if let Some(encoded) = rest.strip_prefix("by-title/") {
95- let title = percent_decode(encoded);
96- return (!title.trim().is_empty()).then_some(LinkTarget::Title(title));
97- }
98- let is_id = !rest.is_empty() && !rest.contains(['/', '?', '#']);
99- is_id.then(|| LinkTarget::Id(rest.to_owned()))
100 }160 }
101 161
102 /// The note a link mark points at, as a title, when the link is a note link the162 /// The note a link mark points at, as a title, when the link is a note link the
@@ -123,190 +183,33 @@ fn wiki_link(target: &str, text: &str) -> Option<String> {
123 }183 }
124 }184 }
125 185
126-/// Percent-encodes everything except RFC 3986 unreserved characters.
127-pub fn percent_encode(s: &str) -> String {
128- let mut out = String::with_capacity(s.len());
129- for b in s.bytes() {
130- match b {
131- b'A'..=b'Z' | b'a'..=b'z' | b'0'..=b'9' | b'-' | b'_' | b'.' | b'~' => {
132- out.push(b as char)
133- }
134- _ => out.push_str(&format!("%{b:02X}")),
135- }
136- }
137- out
138-}
139-
140-/// Decodes `%XX` escapes. Malformed escapes are kept as they are.
141-pub fn percent_decode(s: &str) -> String {
142- let bytes = s.as_bytes();
143- let mut out = Vec::with_capacity(bytes.len());
144- let mut i = 0;
145- while i < bytes.len() {
146- if bytes[i] == b'%' && i + 2 < bytes.len() {
147- let hex = std::str::from_utf8(&bytes[i + 1..i + 3]).ok();
148- if let Some(v) = hex.and_then(|h| u8::from_str_radix(h, 16).ok()) {
149- out.push(v);
150- i += 3;
151- continue;
152- }
153- }
154- out.push(bytes[i]);
155- i += 1;
156- }
157- String::from_utf8_lossy(&out).into_owned()
158-}
159-
160-/// Plain text of the first non-empty block, trimmed, max 80 chars. "Untitled" if empty.
161-pub fn title(doc: &LoroDoc) -> String {
162- let root = doc.get_map("doc");
163- let raw = first_text(&root).unwrap_or_default();
164- let collapsed = raw.split_whitespace().collect::<Vec<_>>().join(" ");
165- let truncated: String = collapsed.chars().take(80).collect();
166- let trimmed = truncated.trim_end();
167- if trimmed.is_empty() {
168- "Untitled".to_string()
169- } else {
170- trimmed.to_string()
171- }
172-}
173-
174-// ---------------------------------------------------------------------------
175-// Tree access helpers
176-// ---------------------------------------------------------------------------
177-
178-pub(super) enum Child {
179- Text(LoroText),
180- Node(LoroMap),
181-}
182-
183-pub(super) fn children(node: &LoroMap) -> Vec<Child> {
184- let mut out = Vec::new();
185- let Some(ValueOrContainer::Container(Container::List(list))) = node.get("children") else {
186- return out;
187- };
188- for i in 0..list.len() {
189- match list.get(i) {
190- Some(ValueOrContainer::Container(Container::Text(t))) => out.push(Child::Text(t)),
191- Some(ValueOrContainer::Container(Container::Map(m))) => out.push(Child::Node(m)),
192- _ => {}
193- }
194- }
195- out
196-}
197-
198-pub(super) fn node_name(node: &LoroMap) -> String {
199- match node.get("nodeName") {
200- Some(ValueOrContainer::Value(v)) => value_str(&v).unwrap_or_default(),
201- _ => String::new(),
202- }
203-}
204-
205-pub(super) fn attr(node: &LoroMap, key: &str) -> Option<LoroValue> {
206- match node.get("attributes") {
207- Some(ValueOrContainer::Container(Container::Map(attrs))) => match attrs.get(key) {
208- Some(ValueOrContainer::Value(v)) => Some(v),
209- _ => None,
210- },
211- _ => None,
212- }
213-}
214-
215-pub(super) fn attr_str(node: &LoroMap, key: &str) -> Option<String> {
216- attr(node, key).and_then(|v| value_str(&v))
217-}
218-
219-pub(super) fn attr_num(node: &LoroMap, key: &str) -> Option<i64> {
220- match attr(node, key)? {
221- LoroValue::I64(i) => Some(i),
222- LoroValue::Double(d) => Some(d as i64),
223- _ => None,
224- }
225-}
226-
227-pub(super) fn value_str(v: &LoroValue) -> Option<String> {
228- v.as_string().map(|s| s.as_str().to_owned())
229-}
230-
231-pub(super) fn plain_text(text: &LoroText) -> String {
232- text.to_delta()
233- .into_iter()
234- .filter_map(|d| match d {
235- TextDelta::Insert { insert, .. } => Some(insert),
236- _ => None,
237- })
238- .collect()
239-}
240-
241-pub(super) fn plain_node_text(node: &LoroMap) -> String {
242- children(node)
243- .into_iter()
244- .map(|c| match c {
245- Child::Text(t) => plain_text(&t),
246- Child::Node(m) => plain_node_text(&m),
247- })
248- .collect()
249-}
250-
251-/// First non-blank text of the tree, in document order.
252-fn first_text(node: &LoroMap) -> Option<String> {
253- for child in children(node) {
254- let found = match child {
255- Child::Text(t) => Some(plain_text(&t)),
256- Child::Node(m) => first_text(&m),
257- };
258- if let Some(s) = found {
259- if !s.trim().is_empty() {
260- return Some(s);
261- }
262- }
263- }
264- None
265-}
266-
267 // ---------------------------------------------------------------------------186 // ---------------------------------------------------------------------------
268 // Block rendering187 // Block rendering
269 // ---------------------------------------------------------------------------188 // ---------------------------------------------------------------------------
270 189
271-/// Renders the children of `node` as blocks separated by blank lines.190+/// Renders blocks separated by blank lines. With `tight`, a nested list directly
272-/// With `tight`, a nested list directly follows its sibling with a single191+/// follows its sibling with a single newline instead of a blank line (used inside
273-/// newline instead of a blank line (used inside list items).192+/// list items).
274-fn render_children(node: &LoroMap, tight: bool, cx: Ctx<'_>) -> String {193+fn render_blocks(blocks: &[Block], tight: bool, cx: Ctx<'_>) -> String {
275- let mut blocks: Vec<(String, bool)> = Vec::new();
276- for child in children(node) {
277- match child {
278- Child::Text(t) => {
279- let s = paragraph_text(inline_text(&t, cx));
280- if !s.is_empty() {
281- blocks.push((s, false));
282- }
283- }
284- Child::Node(m) => {
285- let is_list = matches!(node_name(&m).as_str(), "bullet_list" | "ordered_list");
286- if let Some(s) = render_block(&m, cx) {
287- blocks.push((s, is_list));
288- }
289- }
290- }
291- }
292-
293 let mut out = String::new();194 let mut out = String::new();
294- for (i, (block, is_list)) in blocks.iter().enumerate() {195+ let mut first = true;
295- if i > 0 {196+ for b in blocks {
296- out.push_str(if tight && *is_list { "\n" } else { "\n\n" });197+ let Some(s) = render_block(b, cx) else { continue };
198+ if !first {
199+ out.push_str(if tight && matches!(b, Block::List { .. }) { "\n" } else { "\n\n" });
297 }200 }
298- out.push_str(block);201+ first = false;
202+ out.push_str(&s);
299 }203 }
300 out204 out
301 }205 }
302 206
303-fn render_block(node: &LoroMap, cx: Ctx<'_>) -> Option<String> {207+fn render_block(block: &Block, cx: Ctx<'_>) -> Option<String> {
304- let name = node_name(node);208+ let out = match block {
305- let out = match name.as_str() {209+ Block::Paragraph(inl) => paragraph_text(inline(inl, cx)),
306- "paragraph" => paragraph_text(inline_children(node, cx)),210+ Block::Heading(level, inl) => {
307- "heading" => {211+ let level = (*level).clamp(1, 6) as usize;
308- let level = attr_num(node, "level").unwrap_or(1).clamp(1, 6) as usize;212+ let text = inline(inl, cx).replace('\n', " ");
309- let text = inline_children(node, cx).replace('\n', " ");
310 let text = text.trim();213 let text = text.trim();
311 if text.is_empty() {214 if text.is_empty() {
312 String::new()215 String::new()
@@ -314,7 +217,7 @@ fn render_block(node: &LoroMap, cx: Ctx<'_>) -> Option<String> {
314 format!("{} {}", "#".repeat(level), text)217 format!("{} {}", "#".repeat(level), text)
315 }218 }
316 }219 }
317- "blockquote" => render_children(node, false, cx)220+ Block::Quote(inner) => render_blocks(inner, false, cx)
318 .lines()221 .lines()
319 .map(|l| {222 .map(|l| {
320 if l.is_empty() {223 if l.is_empty() {
@@ -325,15 +228,9 @@ fn render_block(node: &LoroMap, cx: Ctx<'_>) -> Option<String> {
325 })228 })
326 .collect::<Vec<_>>()229 .collect::<Vec<_>>()
327 .join("\n"),230 .join("\n"),
328- "code_block" => code_block(node),231+ Block::Code { lang, text } => code_block(lang.as_deref(), text),
329- "horizontal_rule" => "---".to_string(),232+ Block::Rule => "---".to_string(),
330- "bullet_list" => render_list(node, false, cx),233+ Block::List { ordered, start, items } => render_list(items, *ordered, *start, cx),
331- "ordered_list" => render_list(node, true, cx),
332- "list_item" => render_children(node, true, cx),
333- "image" => paragraph_text(image_md(node)),
334- "hard_break" => String::new(),
335- // doc and unknown containers: render their children.
336- _ => render_children(node, false, cx),
337 };234 };
338 235
339 if out.trim().is_empty() {236 if out.trim().is_empty() {
@@ -343,26 +240,17 @@ fn render_block(node: &LoroMap, cx: Ctx<'_>) -> Option<String> {
343 }240 }
344 }241 }
345 242
346-fn render_list(node: &LoroMap, ordered: bool, cx: Ctx<'_>) -> String {243+fn render_list(list: &[Vec<Block>], ordered: bool, start: i64, cx: Ctx<'_>) -> String {
347- let start = if ordered {244+ let start = if ordered { start } else { 1 };
348- attr_num(node, "order").unwrap_or(1)
349- } else {
350- 1
351- };
352 let mut items = Vec::new();245 let mut items = Vec::new();
353- let mut index: i64 = 0;246+ for (index, item) in list.iter().enumerate() {
354- for child in children(node) {
355- let Child::Node(item) = child else {
356- continue;
357- };
358 let marker = if ordered {247 let marker = if ordered {
359- format!("{}. ", start + index)248+ format!("{}. ", start + index as i64)
360 } else {249 } else {
361 "- ".to_string()250 "- ".to_string()
362 };251 };
363- index += 1;
364 252
365- let body = render_children(&item, true, cx);253+ let body = render_blocks(item, true, cx);
366 if body.is_empty() {254 if body.is_empty() {
367 items.push(marker.trim_end().to_string());255 items.push(marker.trim_end().to_string());
368 continue;256 continue;
@@ -382,18 +270,14 @@ fn render_list(node: &LoroMap, ordered: bool, cx: Ctx<'_>) -> String {
382 items.join("\n")270 items.join("\n")
383 }271 }
384 272
385-fn code_block(node: &LoroMap) -> String {273+fn code_block(lang: Option<&str>, content: &str) -> String {
386- let mut content = String::new();
387- for child in children(node) {
388- match child {
389- Child::Text(t) => content.push_str(&plain_text(&t)),
390- Child::Node(m) if node_name(&m) == "hard_break" => content.push('\n'),
391- Child::Node(m) => content.push_str(&plain_node_text(&m)),
392- }
393- }
394 let content = content.trim_end_matches('\n');274 let content = content.trim_end_matches('\n');
395 let fence = "`".repeat((longest_backtick_run(content) + 1).max(3));275 let fence = "`".repeat((longest_backtick_run(content) + 1).max(3));
396- let lang = attr_str(node, "language").unwrap_or_default();276+ // An explicit language wins; without one, the language is detected.
277+ let lang = lang
278+ .filter(|l| !l.trim().is_empty())
279+ .or_else(|| note_model::lang::detect(content))
280+ .unwrap_or_default();
397 if content.is_empty() {281 if content.is_empty() {
398 format!("{fence}{lang}\n{fence}")282 format!("{fence}{lang}\n{fence}")
399 } else {283 } else {
@@ -464,65 +348,34 @@ fn escape_line_start(line: &str) -> String {
464 // Inline rendering348 // Inline rendering
465 // ---------------------------------------------------------------------------349 // ---------------------------------------------------------------------------
466 350
467-/// Concatenated inline content of a node: text runs and inline child nodes.351+/// Inline content as markdown. Each stretch of text between breaks and images merges
468-fn inline_children(node: &LoroMap, cx: Ctx<'_>) -> String {352+/// adjacent runs with identical marks, so e.g. two bold runs become one `**...**` span.
353+fn inline(inl: &[Inline], cx: Ctx<'_>) -> String {
469 let mut out = String::new();354 let mut out = String::new();
470- for child in children(node) {355+ let mut runs: Vec<(String, Marks)> = Vec::new();
471- match child {356+ for i in inl {
472- Child::Text(t) => out.push_str(&inline_text(&t, cx)),357+ match i {
473- Child::Node(m) => out.push_str(&inline_node(&m, cx)),358+ Inline::Text(s, m) => match runs.last_mut() {
359+ Some((t, last)) if last == m => t.push_str(s),
360+ _ => runs.push((s.clone(), m.clone())),
361+ },
362+ Inline::HardBreak => {
363+ out.push_str(&text_runs(&std::mem::take(&mut runs), cx));
364+ out.push_str("\\\n");
365+ }
366+ Inline::Image { src, alt, title } => {
367+ out.push_str(&text_runs(&std::mem::take(&mut runs), cx));
368+ out.push_str(&image_md(src, alt, title.as_deref()));
369+ }
474 }370 }
475 }371 }
372+ out.push_str(&text_runs(&runs, cx));
476 out373 out
477 }374 }
478 375
479-fn inline_node(node: &LoroMap, cx: Ctx<'_>) -> String {376+/// Consecutive runs under the same link render as one link, so a partly bold link
480- match node_name(node).as_str() {377+/// stays a single link.
481- "hard_break" => "\\\n".to_string(),378+fn text_runs(runs: &[(String, Marks)], cx: Ctx<'_>) -> String {
482- "image" => image_md(node),
483- _ => inline_children(node, cx),
484- }
485-}
486-
487-#[derive(PartialEq, Clone, Default)]
488-struct Marks {
489- strong: bool,
490- em: bool,
491- code: bool,
492- link: Option<(String, Option<String>)>,
493-}
494-
495-/// Renders a LoroText as markdown, merging adjacent runs with identical marks
496-/// so that e.g. two bold runs become one `**...**` span.
497-fn inline_text(text: &LoroText, cx: Ctx<'_>) -> String {
498- let mut runs: Vec<(String, Marks)> = Vec::new();
499- for delta in text.to_delta() {
500- let TextDelta::Insert { insert, attributes } = delta else {
501- continue;
502- };
503- let attrs = attributes.unwrap_or_default();
504- let on = |k: &str| attrs.get(k).is_some_and(|v| !matches!(v, LoroValue::Null));
505- let link = attrs.get("link").map(|v| {
506- let href = v.get_by_key("href").and_then(value_str).unwrap_or_default();
507- let title = v
508- .get_by_key("title")
509- .and_then(value_str)
510- .filter(|t| !t.is_empty());
511- (href, title)
512- });
513- let marks = Marks {
514- strong: on("strong"),
515- em: on("em"),
516- code: on("code"),
517- link,
518- };
519- match runs.last_mut() {
520- Some((s, m)) if *m == marks => s.push_str(&insert),
521- _ => runs.push((insert, marks)),
522- }
523- }
524- // Consecutive runs under the same link render as one link, so a partly bold link
525- // stays a single link.
526 let mut out = String::new();379 let mut out = String::new();
527 let mut i = 0;380 let mut i = 0;
528 while i < runs.len() {381 while i < runs.len() {
@@ -538,7 +391,6 @@ fn inline_text(text: &LoroText, cx: Ctx<'_>) -> String {
538 out391 out
539 }392 }
540 393
541-/// One run without a link, or every run of one link.
542 fn render_group(group: &[(String, Marks)], cx: Ctx<'_>) -> String {394 fn render_group(group: &[(String, Marks)], cx: Ctx<'_>) -> String {
543 let Some((href, title)) = group[0].1.link.clone() else {395 let Some((href, title)) = group[0].1.link.clone() else {
544 return render_marks(&group[0].0, &group[0].1);396 return render_marks(&group[0].0, &group[0].1);
@@ -551,11 +403,20 @@ fn render_group(group: &[(String, Marks)], cx: Ctx<'_>) -> String {
551 let lead = &text[..text.len() - text.trim_start().len()];403 let lead = &text[..text.len() - text.trim_start().len()];
552 let trail = &text[lead.len() + core.len()..];404 let trail = &text[lead.len() + core.len()..];
553 405
406+ let first = &group[0].1;
407+ // Marks that cover the whole link go around `[[...]]`, which can't hold any.
408+ let uniform = !first.code && group.iter().all(|(_, m)| m.strong == first.strong && m.em == first.em);
409+ if let (Some(count), Some(LinkTarget::Id(id))) = (cx.deferred, link_target(&href)) {
410+ count.set(count.get() + 1);
411+ let inner: String = group.iter().map(|(s, m)| render_marks(s, m)).collect();
412+ let flags = [(uniform, 'u'), (first.em, 'e'), (first.strong, 's')].iter().filter(|f| f.0).map(|f| f.1).collect::<String>();
413+ let dest = link_dest(&href, title.as_deref());
414+ return format!(
415+ "{lead}{DEFER_START}{id}{DEFER_SEP}{core}{DEFER_SEP}{flags}{DEFER_SEP}{}{DEFER_SEP}{dest}{DEFER_END}{trail}",
416+ inner.trim()
417+ );
418+ }
554 if let Some(target) = wiki_target(&href, cx) {419 if let Some(target) = wiki_target(&href, cx) {
555- // Marks that cover the whole link go around `[[...]]`, which can't hold any.
556- let first = &group[0].1;
557- let uniform = !first.code
558- && group.iter().all(|(_, m)| m.strong == first.strong && m.em == first.em);
559 if uniform {420 if uniform {
560 if let Some(mut link) = wiki_link(&target, core) {421 if let Some(mut link) = wiki_link(&target, core) {
561 if first.em {422 if first.em {
@@ -654,16 +515,14 @@ fn link_dest(href: &str, title: Option<&str>) -> String {
654 }515 }
655 }516 }
656 517
657-fn image_md(node: &LoroMap) -> String {518+fn image_md(src: &str, alt: &str, title: Option<&str>) -> String {
658- let alt = attr_str(node, "alt").unwrap_or_default();
659- let src = attr_str(node, "src").unwrap_or_default();
660 if src.is_empty() {519 if src.is_empty() {
661- return escape_text(&alt);520+ return escape_text(alt);
662 }521 }
663 let alt = alt522 let alt = alt
664 .replace('\\', "\\\\")523 .replace('\\', "\\\\")
665 .replace('[', "\\[")524 .replace('[', "\\[")
666 .replace(']', "\\]");525 .replace(']', "\\]");
667- let title = attr_str(node, "title").filter(|t| !t.is_empty());526+ let title = title.filter(|t| !t.is_empty());
668- format!("![{alt}]({})", link_dest(&src, title.as_deref()))527+ format!("![{alt}]({})", link_dest(src, title))
669 }528 }
src/export/html.rsmodified+66 -128

Diff too large; view file

@@ -1,15 +1,15 @@
1-//! HTML export. Walks the same loro-prosemirror tree as the markdown export in1+//! HTML export. Renders the plain block tree from `note_model::flat` as an HTML
2-//! the parent module and emits an HTML body fragment, plus a standalone page2+//! body fragment, plus a standalone page wrapper for download and print.
3-//! wrapper for download and print.
4 3
5-use loro::{LoroDoc, LoroMap, LoroText, LoroValue, TextDelta};4+use loro::LoroDoc;
6-5+use note_model::marks::Marks;
7-use super::{Child, attr_num, attr_str, children, node_name, plain_node_text, plain_text, value_str};6+use note_model::render::{Embed, embed_of};
7+use note_model::write::{Block, Inline};
8 8
9 /// Note body as an HTML fragment (no surrounding document).9 /// Note body as an HTML fragment (no surrounding document).
10 pub fn to_html(doc: &LoroDoc) -> String {10 pub fn to_html(doc: &LoroDoc) -> String {
11- let root = doc.get_map("doc");11+ let blocks = note_model::flat::doc_blocks(doc);
12- render_children(&root)12+ render_blocks(&blocks)
13 }13 }
14 14
15 /// Standalone HTML document around `body`. With `print`, the page opens the15 /// Standalone HTML document around `body`. With `print`, the page opens the
@@ -42,14 +42,14 @@ code{font-family:ui-monospace,SFMono-Regular,Menlo,Consolas,monospace;font-size:
42 background:#f2f2f4;padding:.1em .3em;border-radius:4px}\42 background:#f2f2f4;padding:.1em .3em;border-radius:4px}\
43 pre{background:#f2f2f4;padding:.75em 1em;border-radius:6px;overflow-x:auto;white-space:pre}\43 pre{background:#f2f2f4;padding:.75em 1em;border-radius:6px;overflow-x:auto;white-space:pre}\
44 pre code{background:none;padding:0;font-size:.875em}\44 pre code{background:none;padding:0;font-size:.875em}\
45-img{max-width:100%;height:auto}\45+img,video,audio{max-width:100%;height:auto}audio{display:block}\
46 hr{border:0;border-top:1px solid #d0d0d5;margin:2em 0}\46 hr{border:0;border-top:1px solid #d0d0d5;margin:2em 0}\
47 a{color:#0a58ca}\47 a{color:#0a58ca}\
48 table{border-collapse:collapse;max-width:100%}\48 table{border-collapse:collapse;max-width:100%}\
49 th,td{border:1px solid #d0d0d5;padding:.4em .6em;text-align:left}\49 th,td{border:1px solid #d0d0d5;padding:.4em .6em;text-align:left}\
50 @page{margin:2cm}\50 @page{margin:2cm}\
51 @media print{body{color:#000}.note{max-width:none;margin:0;padding:0}\51 @media print{body{color:#000}.note{max-width:none;margin:0;padding:0}\
52-a{color:inherit}pre,blockquote,img{break-inside:avoid}pre{background:#f2f2f2}code{background:#f2f2f2}}";52+a{color:inherit}pre,blockquote,img,video,audio{break-inside:avoid}pre{background:#f2f2f2}code{background:#f2f2f2}}";
53 53
54 // ---------------------------------------------------------------------------54 // ---------------------------------------------------------------------------
55 // Escaping and link safety55 // Escaping and link safety
@@ -105,64 +105,50 @@ fn safe_src(src: &str) -> Option<&str> {
105 // Block rendering105 // Block rendering
106 // ---------------------------------------------------------------------------106 // ---------------------------------------------------------------------------
107 107
108-/// Renders the children of `node` as blocks, in order.108+/// Renders `blocks` in order.
109-fn render_children(node: &LoroMap) -> String {109+pub(super) fn render_blocks(blocks: &[Block]) -> String {
110 let mut out = String::new();110 let mut out = String::new();
111- for child in children(node) {111+ for block in blocks {
112- match child {112+ if let Some(html) = render_block(block) {
113- Child::Text(t) => {113+ out.push_str(&html);
114- let inner = inline_text(&t);114+ out.push('\n');
115- if !inner.trim().is_empty() {
116- out.push_str(&format!("<p>{}</p>\n", inner.trim()));
117- }
118- }
119- Child::Node(m) => {
120- if let Some(html) = render_block(&m) {
121- out.push_str(&html);
122- out.push('\n');
123- }
124- }
125 }115 }
126 }116 }
127 out117 out
128 }118 }
129 119
130-fn render_block(node: &LoroMap) -> Option<String> {120+fn render_block(block: &Block) -> Option<String> {
131- let html = match node_name(node).as_str() {121+ let html = match block {
132- "paragraph" => {122+ Block::Paragraph(inlines) => {
133- let inner = inline_children(node);123+ let inner = render_inlines(inlines);
134 if inner.trim().is_empty() {124 if inner.trim().is_empty() {
135 return None;125 return None;
136 }126 }
137 format!("<p>{}</p>", inner.trim())127 format!("<p>{}</p>", inner.trim())
138 }128 }
139- "heading" => {129+ Block::Heading(level, inlines) => {
140- let level = attr_num(node, "level").unwrap_or(1).clamp(1, 6);130+ let level = (*level).clamp(1, 6);
141- let inner = inline_children(node).replace('\n', " ");131+ let inner = render_inlines(inlines).replace('\n', " ");
142 let inner = inner.trim();132 let inner = inner.trim();
143 if inner.is_empty() {133 if inner.is_empty() {
144 return None;134 return None;
145 }135 }
146 format!("<h{level}>{inner}</h{level}>")136 format!("<h{level}>{inner}</h{level}>")
src/format.rsadded+140 -0

Diff too large; view file

src/hub.rsmodified+677 -71

Diff too large; view file

src/i18n.rsmodified+243 -0

Diff too large; view file

src/import.rsmodified+305 -191

Diff too large; view file

src/main.rsmodified+14 -1

Diff too large; view file

src/matcher.rsmodified+253 -28

Diff too large; view file

src/media.rsadded+321 -0

Diff too large; view file

src/media/webm.rsadded+389 -0

Diff too large; view file

src/store.rsmodified+1452 -207

Diff too large; view file

src/store/directory.rsadded+461 -0

Diff too large; view file

src/zipout.rsadded+117 -0

Diff too large; view file

vendor/loro-internal/.gitignoreadded+1 -0

Diff too large; view file

vendor/loro-internal/AGENTS.mdadded+121 -0

Diff too large; view file

vendor/loro-internal/CLAUDE.mdadded+121 -0

Diff too large; view file

vendor/loro-internal/Cargo.lockadded+2060 -0

Diff too large; view file

vendor/loro-internal/Cargo.tomladded+374 -0

Diff too large; view file

vendor/loro-internal/Cargo.toml.origadded+134 -0

Diff too large; view file

vendor/loro-internal/Encoding.mdadded+25 -0

Diff too large; view file

vendor/loro-internal/README.mdadded+5 -0

Diff too large; view file

vendor/loro-internal/VERSIONadded+1 -0

Diff too large; view file

vendor/loro-internal/benches/automerge-paper.json.gzadded+0 -0

Binary file changed

vendor/loro-internal/benches/encode.rsadded+398 -0

Diff too large; view file

vendor/loro-internal/benches/event.rsadded+48 -0

Diff too large; view file

vendor/loro-internal/benches/jsonpath.rsadded+317 -0

Diff too large; view file

vendor/loro-internal/benches/list.rsadded+119 -0

Diff too large; view file

vendor/loro-internal/benches/map.rsadded+85 -0

Diff too large; view file

vendor/loro-internal/benches/pending.rsadded+47 -0

Diff too large; view file

vendor/loro-internal/benches/shallow_export.rsadded+164 -0

Diff too large; view file

vendor/loro-internal/benches/text_r.rsadded+432 -0

Diff too large; view file

vendor/loro-internal/benches/tree.rsadded+166 -0

Diff too large; view file

vendor/loro-internal/deno.jsonadded+10 -0

Diff too large; view file

vendor/loro-internal/deno.lockadded+134 -0

Diff too large; view file

vendor/loro-internal/docs/critical-version-spec.mdadded+705 -0

Diff too large; view file

vendor/loro-internal/docs/diff_calc.mdadded+125 -0

Diff too large; view file

vendor/loro-internal/docs/mergeable-container-id.mdadded+87 -0

Diff too large; view file

vendor/loro-internal/examples/automerge_x100.rsadded+41 -0

Diff too large; view file

vendor/loro-internal/examples/encoding.rsadded+155 -0

Diff too large; view file

vendor/loro-internal/examples/encoding_parallel.rsadded+90 -0

Diff too large; view file

vendor/loro-internal/examples/encoding_refactored.rsadded+115 -0

Diff too large; view file

vendor/loro-internal/examples/event.rsadded+66 -0

Diff too large; view file

vendor/loro-internal/examples/list.rsadded+23 -0

Diff too large; view file

vendor/loro-internal/examples/many_actors.rsadded+60 -0

Diff too large; view file

vendor/loro-internal/examples/mem.rsadded+110 -0

Diff too large; view file

vendor/loro-internal/examples/obs.rsadded+26 -0

Diff too large; view file

vendor/loro-internal/examples/pending.rsadded+33 -0

Diff too large; view file

vendor/loro-internal/examples/state_size.rsadded+127 -0

Diff too large; view file

vendor/loro-internal/examples/tree.rsadded+83 -0

Diff too large; view file

vendor/loro-internal/proptest-regressions/dag/test.txtadded+10 -0

Diff too large; view file

vendor/loro-internal/scripts/fuzz.tsadded+36 -0

Diff too large; view file

vendor/loro-internal/scripts/mem.tsadded+49 -0

Diff too large; view file

vendor/loro-internal/scripts/run_mem.tsadded+9 -0

Diff too large; view file

vendor/loro-internal/src/allocation/bfs.rsadded+386 -0

Diff too large; view file

vendor/loro-internal/src/allocation/dfs.rsadded+416 -0

Diff too large; view file

vendor/loro-internal/src/allocation/mod.rsadded+10 -0

Diff too large; view file

vendor/loro-internal/src/arena.rsadded+1037 -0

Diff too large; view file

vendor/loro-internal/src/arena/str_arena.rsadded+253 -0

Diff too large; view file

vendor/loro-internal/src/awareness.rsadded+873 -0

Diff too large; view file

vendor/loro-internal/src/change.rsadded+329 -0

Diff too large; view file

vendor/loro-internal/src/change_meta.rsadded+98 -0

Diff too large; view file

vendor/loro-internal/src/configure.rsadded+337 -0

Diff too large; view file

vendor/loro-internal/src/container.rsadded+314 -0

Diff too large; view file

vendor/loro-internal/src/container/list/list_op.rsadded+818 -0

Diff too large; view file

vendor/loro-internal/src/container/list/mod.rsadded+1 -0

Diff too large; view file

vendor/loro-internal/src/container/map/map_content.rsadded+42 -0

Diff too large; view file

vendor/loro-internal/src/container/map/mod.rsadded+3 -0

Diff too large; view file

vendor/loro-internal/src/container/richtext.rsadded+300 -0

Diff too large; view file

vendor/loro-internal/src/container/richtext/config.rsadded+133 -0

Diff too large; view file

vendor/loro-internal/src/container/richtext/fugue_span.rsadded+386 -0

Diff too large; view file

vendor/loro-internal/src/container/richtext/richtext_state.rsadded+3690 -0

Diff too large; view file

vendor/loro-internal/src/container/richtext/richtext_state/insert_pos_cache_test.rsadded+172 -0

Diff too large; view file

vendor/loro-internal/src/container/richtext/str_slice.rsadded+48 -0

Diff too large; view file

vendor/loro-internal/src/container/richtext/style_range_map.rsadded+690 -0

Diff too large; view file

vendor/loro-internal/src/container/richtext/tinyvec.rsadded+289 -0

Diff too large; view file

vendor/loro-internal/src/container/richtext/tracker.rsadded+896 -0

Diff too large; view file

vendor/loro-internal/src/container/richtext/tracker/crdt_rope.rsadded+953 -0

Diff too large; view file

vendor/loro-internal/src/container/richtext/tracker/id_to_cursor.rsadded+1222 -0

Diff too large; view file

vendor/loro-internal/src/container/tree/bool_rle_vec.rsadded+442 -0

Diff too large; view file

vendor/loro-internal/src/container/tree/mod.rsadded+3 -0

Diff too large; view file

vendor/loro-internal/src/container/tree/tree_ds.rsadded+115 -0

Diff too large; view file

vendor/loro-internal/src/container/tree/tree_op.rsadded+75 -0

Diff too large; view file

vendor/loro-internal/src/cursor.rsadded+111 -0

Diff too large; view file

vendor/loro-internal/src/dag.rsadded+2024 -0

Diff too large; view file

vendor/loro-internal/src/dag/iter.rsadded+637 -0

Diff too large; view file

vendor/loro-internal/src/dag/mermaid.rsadded+320 -0

Diff too large; view file

vendor/loro-internal/src/dag/test.excalidrawadded+4334 -0

Diff too large; view file

vendor/loro-internal/src/dag/test.rsadded+1467 -0

Diff too large; view file

vendor/loro-internal/src/delta.rsadded+14 -0

Diff too large; view file

vendor/loro-internal/src/delta/map.rsadded+203 -0

Diff too large; view file

vendor/loro-internal/src/delta/map_delta.rsadded+315 -0

Diff too large; view file

vendor/loro-internal/src/delta/movable_list.rsadded+56 -0

Diff too large; view file

vendor/loro-internal/src/delta/seq.rsadded+950 -0

Diff too large; view file

vendor/loro-internal/src/delta/text.rsadded+298 -0

Diff too large; view file

vendor/loro-internal/src/delta/tree.rsadded+209 -0

Diff too large; view file

vendor/loro-internal/src/diff/LICENSEadded+201 -0

Diff too large; view file

vendor/loro-internal/src/diff/diff_impl.rsadded+857 -0

Diff too large; view file

vendor/loro-internal/src/diff/mod.rsadded+4 -0

Diff too large; view file

vendor/loro-internal/src/diff_calc.rsadded+2635 -0

Diff too large; view file

vendor/loro-internal/src/diff_calc/counter.rsadded+63 -0

Diff too large; view file

vendor/loro-internal/src/diff_calc/tracker_texts.rsadded+195 -0

Diff too large; view file

vendor/loro-internal/src/diff_calc/tracker_values.rsadded+128 -0

Diff too large; view file

vendor/loro-internal/src/diff_calc/tree.rsadded+725 -0

Diff too large; view file

vendor/loro-internal/src/diff_calc/unknown.rsadded+32 -0

Diff too large; view file

vendor/loro-internal/src/encoding.rsadded+658 -0

Diff too large; view file

vendor/loro-internal/src/encoding/AGENTS.mdadded+42 -0

Diff too large; view file

vendor/loro-internal/src/encoding/CLAUDE.mdadded+42 -0

Diff too large; view file

vendor/loro-internal/src/encoding/arena.rsadded+277 -0

Diff too large; view file

vendor/loro-internal/src/encoding/fast_snapshot.rsadded+629 -0

Diff too large; view file

vendor/loro-internal/src/encoding/json_schema.rsadded+1911 -0

Diff too large; view file

vendor/loro-internal/src/encoding/outdated_encode_reordered.rsadded+649 -0

Diff too large; view file

vendor/loro-internal/src/encoding/shallow_snapshot.rsadded+1979 -0

Diff too large; view file

vendor/loro-internal/src/encoding/value.rsadded+1535 -0

Diff too large; view file

vendor/loro-internal/src/encoding/value_register.rsadded+52 -0

Diff too large; view file

vendor/loro-internal/src/error.rsadded+1 -0

Diff too large; view file

vendor/loro-internal/src/estimated_size.rsadded+27 -0

Diff too large; view file

vendor/loro-internal/src/event.rsadded+573 -0

Diff too large; view file

vendor/loro-internal/src/fork.rsadded+64 -0

Diff too large; view file

vendor/loro-internal/src/fuzz.rsadded+89 -0

Diff too large; view file

vendor/loro-internal/src/handler.rsadded+6099 -0

Diff too large; view file

vendor/loro-internal/src/handler/full_state.rsadded+377 -0

Diff too large; view file

vendor/loro-internal/src/handler/movable_list_apply_delta.rsadded+361 -0

Diff too large; view file

vendor/loro-internal/src/handler/text_update.rsadded+149 -0

Diff too large; view file

vendor/loro-internal/src/handler/tree.rsadded+1197 -0

Diff too large; view file

vendor/loro-internal/src/history_cache.rsadded+1070 -0

Diff too large; view file

vendor/loro-internal/src/id.rsadded+4 -0

Diff too large; view file

vendor/loro-internal/src/jsonpath/ast.rsadded+458 -0

Diff too large; view file

vendor/loro-internal/src/jsonpath/errors.rsadded+61 -0

Diff too large; view file

vendor/loro-internal/src/jsonpath/jsonpath.pestadded+110 -0

Diff too large; view file

vendor/loro-internal/src/jsonpath/jsonpath_impl.rsadded+1635 -0

Diff too large; view file

vendor/loro-internal/src/jsonpath/mod.rsadded+10 -0

Diff too large; view file

vendor/loro-internal/src/jsonpath/parser.rsadded+708 -0

Diff too large; view file

vendor/loro-internal/src/jsonpath/subscription.rsadded+551 -0

Diff too large; view file

vendor/loro-internal/src/kv_store.rsadded+260 -0

Diff too large; view file

vendor/loro-internal/src/lib.rsadded+185 -0

Diff too large; view file

vendor/loro-internal/src/lock.rsadded+627 -0

Diff too large; view file

vendor/loro-internal/src/loro.rsadded+5041 -0

Diff too large; view file

vendor/loro-internal/src/macros.rsadded+98 -0

Diff too large; view file

vendor/loro-internal/src/op.rsadded+749 -0

Diff too large; view file

vendor/loro-internal/src/op/content.rsadded+470 -0

Diff too large; view file

vendor/loro-internal/src/oplog.rsadded+1759 -0

Diff too large; view file

vendor/loro-internal/src/oplog/change_store.rsadded+3274 -0

Diff too large; view file

vendor/loro-internal/src/oplog/change_store/block_encode.rsadded+1099 -0

Diff too large; view file

vendor/loro-internal/src/oplog/change_store/block_meta_encode.rsadded+247 -0

Diff too large; view file

vendor/loro-internal/src/oplog/change_store/iter.rsadded+139 -0

Diff too large; view file

vendor/loro-internal/src/oplog/known_history.rsadded+976 -0

Diff too large; view file

vendor/loro-internal/src/oplog/loro_dag.rsadded+1619 -0

Diff too large; view file

vendor/loro-internal/src/oplog/pending_changes.rsadded+942 -0

Diff too large; view file

vendor/loro-internal/src/parent.rsadded+151 -0

Diff too large; view file

vendor/loro-internal/src/pre_commit.rsadded+69 -0

Diff too large; view file

vendor/loro-internal/src/span.rsadded+3 -0

Diff too large; view file

vendor/loro-internal/src/state.rsadded+2873 -0

Diff too large; view file

vendor/loro-internal/src/state/AGENTS.mdadded+68 -0

Diff too large; view file

vendor/loro-internal/src/state/CLAUDE.mdadded+68 -0

Diff too large; view file

vendor/loro-internal/src/state/analyzer.rsadded+95 -0

Diff too large; view file

vendor/loro-internal/src/state/container_store.rsadded+1186 -0

Diff too large; view file

vendor/loro-internal/src/state/container_store/container_wrapper.rsadded+843 -0

Diff too large; view file

vendor/loro-internal/src/state/container_store/inner_store.rsadded+821 -0

Diff too large; view file

vendor/loro-internal/src/state/container_tree.rsadded+269 -0

Diff too large; view file

vendor/loro-internal/src/state/counter_state.rsadded+145 -0

Diff too large; view file

vendor/loro-internal/src/state/dead_containers_cache.rsadded+391 -0

Diff too large; view file

vendor/loro-internal/src/state/list_state.rsadded+972 -0

Diff too large; view file

vendor/loro-internal/src/state/map_state.rsadded+721 -0

Diff too large; view file

vendor/loro-internal/src/state/mergeable.rsadded+93 -0

Diff too large; view file

vendor/loro-internal/src/state/movable_list_state.rsadded+2110 -0

Diff too large; view file

vendor/loro-internal/src/state/richtext_state.rsadded+1979 -0

Diff too large; view file

vendor/loro-internal/src/state/tree_state.rsadded+2274 -0

Diff too large; view file

vendor/loro-internal/src/state/unknown_state.rsadded+184 -0

Diff too large; view file

vendor/loro-internal/src/state/value_decode.rsadded+437 -0

Diff too large; view file

vendor/loro-internal/src/subscription.rsadded+232 -0

Diff too large; view file

vendor/loro-internal/src/sync.rsadded+178 -0

Diff too large; view file

vendor/loro-internal/src/tests/import_atomicity.rsadded+1091 -0

Diff too large; view file

vendor/loro-internal/src/tests/mod.rsadded+51 -0

Diff too large; view file

vendor/loro-internal/src/tests/op_count.rsadded+107 -0

Diff too large; view file

vendor/loro-internal/src/tests/replay_base.rsadded+723 -0

Diff too large; view file

vendor/loro-internal/src/tests/text_arena_growth.rsadded+184 -0

Diff too large; view file

vendor/loro-internal/src/tests/undo_atomicity.rsadded+123 -0

Diff too large; view file

vendor/loro-internal/src/txn.rsadded+1221 -0

Diff too large; view file

vendor/loro-internal/src/undo.rsadded+1243 -0

Diff too large; view file

vendor/loro-internal/src/undo/atomicity_tests.rsadded+141 -0

Diff too large; view file

vendor/loro-internal/src/undo/movable_list.rsadded+890 -0

Diff too large; view file

vendor/loro-internal/src/utils/kv_wrapper.rsadded+181 -0

Diff too large; view file

vendor/loro-internal/src/utils/lazy.rsadded+21 -0

Diff too large; view file

vendor/loro-internal/src/utils/mod.rsadded+6 -0

Diff too large; view file

vendor/loro-internal/src/utils/query_by_len.rsadded+200 -0

Diff too large; view file

vendor/loro-internal/src/utils/string_slice.rsadded+466 -0

Diff too large; view file

vendor/loro-internal/src/utils/subscription.rsadded+857 -0

Diff too large; view file

vendor/loro-internal/src/utils/utf16.rsadded+139 -0

Diff too large; view file

vendor/loro-internal/src/value.rsadded+1222 -0

Diff too large; view file

vendor/loro-internal/src/version.rsadded+1221 -0

Diff too large; view file

vendor/loro-internal/src/version/frontiers.rsadded+574 -0

Diff too large; view file

vendor/loro-internal/tests/autocommit.rsadded+78 -0

Diff too large; view file

vendor/loro-internal/tests/contracts.rsadded+14 -0

Diff too large; view file

vendor/loro-internal/tests/contracts/event_diff.rsadded+160 -0

Diff too large; view file

vendor/loro-internal/tests/contracts/handler.rsadded+179 -0

Diff too large; view file

vendor/loro-internal/tests/contracts/jsonpath_value.rsadded+172 -0

Diff too large; view file

vendor/loro-internal/tests/contracts/public_doc.rsadded+243 -0

Diff too large; view file

vendor/loro-internal/tests/contracts/text_richtext_behavior.rsadded+213 -0

Diff too large; view file

vendor/loro-internal/tests/contracts/text_richtext_handler.rsadded+266 -0

Diff too large; view file

vendor/loro-internal/tests/contracts/tree_handler.rsadded+119 -0

Diff too large; view file

vendor/loro-internal/tests/ephemeral_store.rsadded+94 -0

Diff too large; view file

vendor/loro-internal/tests/fugue.rsadded+90 -0

Diff too large; view file

vendor/loro-internal/tests/handle_walk_memory.rsadded+141 -0

Diff too large; view file

vendor/loro-internal/tests/mergeable_cid_encoding.rsadded+314 -0

Diff too large; view file

vendor/loro-internal/tests/mergeable_container.rsadded+19 -0

Diff too large; view file

vendor/loro-internal/tests/mergeable_container/common.rsadded+25 -0

Diff too large; view file

vendor/loro-internal/tests/mergeable_container/convergence.rsadded+285 -0

Diff too large; view file

vendor/loro-internal/tests/mergeable_container/delete.rsadded+383 -0

Diff too large; view file

vendor/loro-internal/tests/mergeable_container/discriminator.rsadded+313 -0

Diff too large; view file

vendor/loro-internal/tests/mergeable_container/events_and_paths.rsadded+266 -0

Diff too large; view file

vendor/loro-internal/tests/mergeable_container/pending.rsadded+53 -0

Diff too large; view file

vendor/loro-internal/tests/mergeable_container/snapshot.rsadded+357 -0

Diff too large; view file

vendor/loro-internal/tests/mergeable_container/type_conflict.rsadded+182 -0

Diff too large; view file

vendor/loro-internal/tests/mergeable_container/undo_redo.rsadded+178 -0

Diff too large; view file

vendor/loro-internal/tests/richtext.mdadded+98 -0

Diff too large; view file

vendor/loro-internal/tests/richtext.rsadded+426 -0

Diff too large; view file

vendor/loro-internal/tests/test.rsadded+1546 -0

Diff too large; view file

vendor/loro-internal/tests/tree.rsadded+35 -0

Diff too large; view file

vendor/loro-internal/tests/undo.rsadded+281 -0

Diff too large; view file

vendor/loro-internal/tests/unknown_parent.rsadded+102 -0

Diff too large; view file

web/build.tsdeleted+0 -48

Diff too large; view file

web/bun.lockdeleted+0 -58

Diff too large; view file

web/package.jsondeleted+0 -23

Diff too large; view file

web/src/dom.tsdeleted+0 -76

Diff too large; view file

web/src/editing.tsdeleted+0 -294

Diff too large; view file

web/src/editor.cssdeleted+0 -800

Diff too large; view file

web/src/editor.tsdeleted+0 -394

Diff too large; view file

web/src/floating.tsdeleted+0 -453

Diff too large; view file

web/src/i18n.tsdeleted+0 -109

Diff too large; view file

web/src/noteLinks.tsdeleted+0 -334

Diff too large; view file

web/src/toolbar.tsdeleted+0 -279

Diff too large; view file

xtask/Cargo.tomladded+16 -0

Diff too large; view file

xtask/src/e2e.rsadded+528 -0

Diff too large; view file

xtask/src/main.rsadded+232 -0

Diff too large; view file

xtask/src/stress.rsadded+756 -0

Diff too large; view file