forge
Explore
Log in

Don't you dare go Hollow

Baseline: server-rendered app with TypeScript ProseMirror editor

Browse files at this commit

e100df49041a27746f177ea532d738199ff124edAhmet Kaan Gümüş and Claude Opus 5.5Root commit (no parents)
.gitignoreadded+3 -0
@@ -0,0 +1,3 @@
1+/target
2+web/node_modules
3+*.db*
Cargo.lockadded+5199 -0

Diff too large; view file

@@ -0,0 +1,5199 @@
1+# This file is automatically @generated by Cargo.
2+# It is not intended for manual editing.
3+version = 4
4+
5+[[package]]
6+name = "adler2"
7+version = "2.0.1"
8+source = "registry+https://github.com/rust-lang/crates.io-index"
9+checksum = "320119579fcad9c21884f5c4861d16174d0e06250625266f50fe6898340abefa"
10+
11+[[package]]
12+name = "aead"
13+version = "0.5.2"
14+source = "registry+https://github.com/rust-lang/crates.io-index"
15+checksum = "d122413f284cf2d62fb1b7db97e02edb8cda96d769b16e443a4f6195e35662b0"
16+dependencies = [
17+ "crypto-common 0.1.7",
18+ "generic-array",
19+]
20+
21+[[package]]
22+name = "aegis"
23+version = "0.9.20"
24+source = "registry+https://github.com/rust-lang/crates.io-index"
25+checksum = "41585f248ed9406567ae6d61ca2a55ed3dc7348e65203a01229881253acb95e3"
26+dependencies = [
27+ "cc",
28+ "softaes",
29+]
30+
31+[[package]]
32+name = "aes"
33+version = "0.8.4"
34+source = "registry+https://github.com/rust-lang/crates.io-index"
35+checksum = "b169f7a6d4742236a0a00c541b845991d0ac43e546831af1249753ab4c3aa3a0"
36+dependencies = [
37+ "cfg-if",
38+ "cipher",
39+ "cpufeatures 0.2.17",
40+]
41+
42+[[package]]
43+name = "aes-gcm"
44+version = "0.10.3"
45+source = "registry+https://github.com/rust-lang/crates.io-index"
46+checksum = "831010a0f742e1209b3bcea8fab6a8e149051ba6099432c8cb2cc117dec3ead1"
47+dependencies = [
48+ "aead",
49+ "aes",
50+ "cipher",
51+ "ctr",
52+ "ghash",
53+ "subtle",
54+]
55+
56+[[package]]
57+name = "ahash"
58+version = "0.8.12"
59+source = "registry+https://github.com/rust-lang/crates.io-index"
60+checksum = "5a15f179cd60c4584b8a8c596927aadc462e27f2ca70c04e0071964a73ba7a75"
61+dependencies = [
62+ "cfg-if",
63+ "getrandom 0.3.4",
64+ "once_cell",
65+ "version_check",
66+ "zerocopy",
67+]
68+
69+[[package]]
70+name = "aho-corasick"
71+version = "1.1.5"
72+source = "registry+https://github.com/rust-lang/crates.io-index"
73+checksum = "c982642fa9e8606056828ee9a8505737230110bb1099153c79efe865c59d12ba"
74+dependencies = [
75+ "memchr",
76+]
77+
78+[[package]]
79+name = "alloc-no-stdlib"
80+version = "3.0.0"
81+source = "registry+https://github.com/rust-lang/crates.io-index"
82+checksum = "c2fb6cfd47bf496ff64095c20eaba0c201404ee38714d4142fcfa1dc334fcc7a"
83+
84+[[package]]
85+name = "alloc-stdlib"
86+version = "0.3.0"
87+source = "registry+https://github.com/rust-lang/crates.io-index"
88+checksum = "0b5c1865780388bfa186411ab5f247819487fc4864c6e9c3106611fa347586e1"
89+dependencies = [
90+ "alloc-no-stdlib",
91+]
92+
93+[[package]]
94+name = "allocator-api2"
95+version = "0.2.21"
96+source = "registry+https://github.com/rust-lang/crates.io-index"
97+checksum = "683d7910e743518b0e34f1186f92494becacb047c7b6bf616c96772180fef923"
98+
99+[[package]]
100+name = "allocator-api2"
101+version = "0.4.0"
102+source = "registry+https://github.com/rust-lang/crates.io-index"
103+checksum = "c880a97d28a3681c0267bd29cff89621202715b065127cd445fa0f0fe0aa2880"
104+
105+[[package]]
106+name = "android_system_properties"
107+version = "0.1.6"
108+source = "registry+https://github.com/rust-lang/crates.io-index"
109+checksum = "ae221649c9976a6f6c56ae1facf410f3ddb33cc661c4b7b61020a912d4237fbc"
110+dependencies = [
111+ "libc",
112+]
113+
114+[[package]]
115+name = "antithesis_sdk"
116+version = "0.3.0"
117+source = "registry+https://github.com/rust-lang/crates.io-index"
118+checksum = "a8ed6751597568a284314fd9e2db420665898600109dedc7d8d9b588f00ae9c4"
119+dependencies = [
120+ "libc",
121+ "libloading",
122+ "linkme",
123+ "once_cell",
124+ "rand 0.8.8",
125+ "rustc_version_runtime",
126+ "serde",
127+ "serde_json",
128+]
129+
130+[[package]]
131+name = "anyhow"
132+version = "1.0.104"
133+source = "registry+https://github.com/rust-lang/crates.io-index"
134+checksum = "330a5ed07fa54e4702c9d6c4174f74427fc0ef6e214bbd677ae50a5099946470"
135+
136+[[package]]
137+name = "anymap3"
138+version = "1.1.0"
139+source = "registry+https://github.com/rust-lang/crates.io-index"
140+checksum = "fb5dfbc6d8d2675589ccbe4d0fd61df2419075625f8c1a62325e718e2b0049f9"
141+
142+[[package]]
143+name = "append-only-bytes"
144+version = "0.1.12"
145+source = "registry+https://github.com/rust-lang/crates.io-index"
146+checksum = "ac436601d6bdde674a0d7fb593e829ffe7b3387c351b356dd20e2d40f5bf3ee5"
147+
148+[[package]]
149+name = "arbitrary"
150+version = "1.5.0"
151+source = "registry+https://github.com/rust-lang/crates.io-index"
152+checksum = "3bc62ac97cc33321f50863d514c3bc38a453947a8f9e781137e47c7401020aed"
153+dependencies = [
154+ "derive_arbitrary",
155+]
156+
157+[[package]]
158+name = "arc-swap"
159+version = "1.9.3"
160+source = "registry+https://github.com/rust-lang/crates.io-index"
161+checksum = "380962b3d93b99642e50b9febf72c071e97e8b32d86eae9cf4ef582bb960ae6e"
162+dependencies = [
163+ "rustversion",
164+]
165+
166+[[package]]
167+name = "aristo"
168+version = "0.4.1"
169+source = "registry+https://github.com/rust-lang/crates.io-index"
170+checksum = "fcdeefa800110050103e2459a2f8dbdbd560ad046e30f1f87e24ce19c2cb8bde"
171+dependencies = [
172+ "aristo-macros",
173+]
174+
175+[[package]]
176+name = "aristo-macros"
177+version = "0.4.1"
178+source = "registry+https://github.com/rust-lang/crates.io-index"
179+checksum = "d64a66d21a80182b35b1741997a6d2456911f54b7eb1918aa4e2382fc205268d"
180+dependencies = [
181+ "proc-macro2",
182+ "quote",
183+ "syn 2.0.119",
184+]
185+
186+[[package]]
187+name = "arrayvec"
188+version = "0.7.8"
189+source = "registry+https://github.com/rust-lang/crates.io-index"
190+checksum = "d3fb67a6e08acf24fdeccbac2cb6ac4305825bd1f117462e0e6f2f193345ad56"
191+
192+[[package]]
193+name = "arref"
194+version = "0.1.0"
195+source = "registry+https://github.com/rust-lang/crates.io-index"
196+checksum = "2ccd462b64c3c72f1be8305905a85d85403d768e8690c9b8bd3b9009a5761679"
197+
198+[[package]]
199+name = "assoc"
200+version = "0.1.3"
201+source = "registry+https://github.com/rust-lang/crates.io-index"
202+checksum = "bfdc70193dadb9d7287fa4b633f15f90c876915b31f6af17da307fc59c9859a8"
203+
204+[[package]]
205+name = "async-compression"
206+version = "0.4.51"
207+source = "registry+https://github.com/rust-lang/crates.io-index"
208+checksum = "9d5755640120b24961f8231e05892e4a4f7e0d04e8aeca161508c9c397946970"
209+dependencies = [
210+ "compression-codecs",
211+ "compression-core",
212+ "pin-project-lite",
213+ "tokio",
214+]
215+
216+[[package]]
217+name = "async-trait"
218+version = "0.1.92"
219+source = "registry+https://github.com/rust-lang/crates.io-index"
220+checksum = "82f6aeea286b8eb4dd3431a1be1b59d290ace00f5bfd8e2a159bc2a05e2c1667"
221+dependencies = [
222+ "proc-macro2",
223+ "quote",
224+ "syn 3.0.9",
225+]
226+
227+[[package]]
228+name = "atomic-polyfill"
229+version = "1.0.3"
230+source = "registry+https://github.com/rust-lang/crates.io-index"
231+checksum = "8cf2bce30dfe09ef0bfaef228b9d414faaf7e563035494d7fe092dba54b300f4"
232+dependencies = [
233+ "critical-section",
234+]
235+
236+[[package]]
237+name = "atomic-waker"
238+version = "1.1.2"
239+source = "registry+https://github.com/rust-lang/crates.io-index"
240+checksum = "1505bd5d3d116872e7271a6d4e16d81d0c8570876c8de68093a09ac269d8aac0"
241+
242+[[package]]
243+name = "autocfg"
244+version = "1.5.1"
245+source = "registry+https://github.com/rust-lang/crates.io-index"
246+checksum = "f2032f911046de80f0a198e0901378627c33f59ea0ac00e363d481118bd70a53"
247+
248+[[package]]
249+name = "base64"
250+version = "0.22.1"
251+source = "registry+https://github.com/rust-lang/crates.io-index"
252+checksum = "72b3254f16251a8381aa12e40e3c4d2f0199f8c6508fbecb9d91f575e0fbb8c6"
253+
254+[[package]]
255+name = "base64"
256+version = "0.23.1"
257+source = "registry+https://github.com/rust-lang/crates.io-index"
258+checksum = "ac07cdecf99051d9a5238b80f35af32cdeba5b336e55d957b318b50137e18da5"
259+
260+[[package]]
261+name = "bigdecimal"
262+version = "0.4.11"
263+source = "registry+https://github.com/rust-lang/crates.io-index"
264+checksum = "8fa3f3d8cbf4dffcfe4991de61d012bef509a409ecbe9dd41049bfe32b4d4653"
265+dependencies = [
266+ "autocfg",
267+ "libm",
268+ "num-bigint",
269+ "num-integer",
270+ "num-traits",
271+]
272+
273+[[package]]
274+name = "bindgen"
275+version = "0.69.5"
276+source = "registry+https://github.com/rust-lang/crates.io-index"
277+checksum = "271383c67ccabffb7381723dea0672a673f292304fcb45c01cc648c7a8d58088"
278+dependencies = [
279+ "bitflags",
280+ "cexpr",
281+ "clang-sys",
282+ "itertools 0.12.1",
283+ "lazy_static",
284+ "lazycell",
285+ "log",
286+ "prettyplease 0.2.37",
287+ "proc-macro2",
288+ "quote",
289+ "regex",
290+ "rustc-hash 1.1.0",
291+ "shlex 1.3.0",
292+ "syn 2.0.119",
293+ "which",
294+]
295+
296+[[package]]
297+name = "bitflags"
298+version = "2.13.2"
299+source = "registry+https://github.com/rust-lang/crates.io-index"
300+checksum = "3ded4057c258ba199e2d26386d3af3780957ecaee6c4ef4041c6b4b8b97c0b06"
301+
302+[[package]]
303+name = "bitmaps"
304+version = "2.1.0"
305+source = "registry+https://github.com/rust-lang/crates.io-index"
306+checksum = "031043d04099746d8db04daf1fa424b2bc8bd69d92b25962dcde24da39ab64a2"
307+dependencies = [
308+ "typenum",
309+]
310+
311+[[package]]
312+name = "bitpacking"
313+version = "0.9.3"
314+source = "registry+https://github.com/rust-lang/crates.io-index"
315+checksum = "96a7139abd3d9cebf8cd6f920a389cf3dc9576172e32f4563f188cae3c3eb019"
316+dependencies = [
317+ "crunchy",
318+]
319+
320+[[package]]
321+name = "bitvec"
322+version = "1.1.1"
323+source = "registry+https://github.com/rust-lang/crates.io-index"
324+checksum = "ddcec3d12c579d40898fe0a9a358a803c23e9c52ca3c425707f81c9436211837"
325+dependencies = [
326+ "funty",
327+ "radium",
328+ "tap",
329+ "wyz",
330+]
331+
332+[[package]]
333+name = "blake3"
334+version = "1.8.7"
335+source = "registry+https://github.com/rust-lang/crates.io-index"
336+checksum = "6d9e454fc11f76977dc803893aff6304ed33d6a26efae8696573bea74baa27ae"
337+dependencies = [
338+ "arrayvec",
339+ "cc",
340+ "cfg-if",
341+ "constant_time_eq",
342+ "cpufeatures 0.3.1",
343+]
344+
345+[[package]]
346+name = "block-buffer"
347+version = "0.10.4"
348+source = "registry+https://github.com/rust-lang/crates.io-index"
349+checksum = "3078c7629b62d3f0439517fa394996acacc5cbc91c5a20d8c658e77abd503a71"
350+dependencies = [
351+ "generic-array",
352+]
353+
354+[[package]]
355+name = "block-buffer"
356+version = "0.12.1"
357+source = "registry+https://github.com/rust-lang/crates.io-index"
358+checksum = "d2f6c7dbe95a6ed67ad9f18e57daf93a2f034c524b99fd2b76d18fdfeb6660aa"
359+dependencies = [
360+ "hybrid-array",
361+]
362+
363+[[package]]
364+name = "bon"
365+version = "3.10.3"
366+source = "registry+https://github.com/rust-lang/crates.io-index"
367+checksum = "a05442cd7005532d0cfedec676b5b9333d2b4c7c3afabe2b1a9ce2742fbe2ee6"
368+dependencies = [
369+ "bon-macros",
370+]
371+
372+[[package]]
373+name = "bon-macros"
374+version = "3.10.3"
375+source = "registry+https://github.com/rust-lang/crates.io-index"
376+checksum = "93833e97ac7c46ba97045afcf247238c27057538fcf2f06344662ddd5f567be6"
377+dependencies = [
378+ "darling 0.24.1",
379+ "ident_case",
380+ "prettyplease 0.3.0",
381+ "proc-macro2",
382+ "quote",
383+ "syn 3.0.9",
384+]
385+
386+[[package]]
387+name = "branches"
388+version = "0.4.6"
389+source = "registry+https://github.com/rust-lang/crates.io-index"
390+checksum = "7436b21fd6195415058eb41c9090e156b556bc7e0377bb57c5c026a421521525"
391+dependencies = [
392+ "rustc_version",
393+]
394+
395+[[package]]
396+name = "brotli"
397+version = "9.1.1"
398+source = "registry+https://github.com/rust-lang/crates.io-index"
399+checksum = "627b7cfb0578f0eafce087a90fcd40add1231900b69e4d4de2d456260a4f5d81"
400+dependencies = [
401+ "alloc-no-stdlib",
402+ "alloc-stdlib",
403+ "brotli-decompressor",
404+]
405+
406+[[package]]
407+name = "brotli-decompressor"
408+version = "6.2.0"
409+source = "registry+https://github.com/rust-lang/crates.io-index"
410+checksum = "34c6783f42c21c952ad7112b354f0ba2f10760e9decea5b1b60523d6e270faaf"
411+dependencies = [
412+ "alloc-no-stdlib",
413+ "alloc-stdlib",
414+]
415+
416+[[package]]
417+name = "bumpalo"
418+version = "3.20.3"
419+source = "registry+https://github.com/rust-lang/crates.io-index"
420+checksum = "72f5acc6cb2ba439de613abc23857ec3d78374d8ed5ac84e9d11336e87da8649"
421+
422+[[package]]
423+name = "bytemuck"
424+version = "1.25.2"
425+source = "registry+https://github.com/rust-lang/crates.io-index"
426+checksum = "95832e849adfb21180ccb6826a99da14e5d266ae5c2e668e1602cf234f153797"
427+dependencies = [
428+ "bytemuck_derive",
429+]
430+
431+[[package]]
432+name = "bytemuck_derive"
433+version = "1.12.1"
434+source = "registry+https://github.com/rust-lang/crates.io-index"
435+checksum = "6a1f896587b6f2c069c73d2f0913e2d590c3990285cd2f0b6aa02b786b4c679c"
436+dependencies = [
437+ "proc-macro2",
438+ "quote",
439+ "syn 3.0.9",
440+]
441+
442+[[package]]
443+name = "byteorder"
444+version = "1.5.0"
445+source = "registry+https://github.com/rust-lang/crates.io-index"
446+checksum = "1fd0f2584146f6f2ef48085050886acf353beff7305ebd1ae69500e27c67f64b"
447+
448+[[package]]
449+name = "bytes"
450+version = "1.12.1"
451+source = "registry+https://github.com/rust-lang/crates.io-index"
452+checksum = "fc652a48c352aef3ea3aed32080501cf3ef6ed5da78602a020c991775b0aff04"
453+
454+[[package]]
455+name = "cc"
456+version = "1.10.0"
457+source = "registry+https://github.com/rust-lang/crates.io-index"
458+checksum = "86e055fa6e3e40ad6187ba25b6855eeb635d5271f8e0f0e1e9a5826b8d75bea0"
459+dependencies = [
460+ "find-msvc-tools",
461+ "jobserver",
462+ "libc",
463+ "shlex 2.0.1",
464+]
465+
466+[[package]]
467+name = "census"
468+version = "0.4.2"
469+source = "registry+https://github.com/rust-lang/crates.io-index"
470+checksum = "4f4c707c6a209cbe82d10abd08e1ea8995e9ea937d2550646e02798948992be0"
471+
472+[[package]]
473+name = "cexpr"
474+version = "0.6.0"
475+source = "registry+https://github.com/rust-lang/crates.io-index"
476+checksum = "6fac387a98bb7c37292057cffc56d62ecb629900026402633ae9160df93a8766"
477+dependencies = [
478+ "nom 7.1.3",
479+]
480+
481+[[package]]
482+name = "cfg-if"
483+version = "1.0.5"
484+source = "registry+https://github.com/rust-lang/crates.io-index"
485+checksum = "4e7648175b45a9a48536d676f68d918270699102aa8dab5496df06904c914600"
486+
487+[[package]]
488+name = "cfg_aliases"
489+version = "0.2.2"
490+source = "registry+https://github.com/rust-lang/crates.io-index"
491+checksum = "f079e83a288787bcd14a6aea84cee5c87a67c5a3e660c30f557a3d24761b3527"
492+
493+[[package]]
494+name = "cfg_block"
495+version = "0.1.1"
496+source = "registry+https://github.com/rust-lang/crates.io-index"
497+checksum = "18758054972164c3264f7c8386f5fc6da6114cb46b619fd365d4e3b2dc3ae487"
498+
499+[[package]]
500+name = "chrono"
501+version = "0.4.45"
502+source = "registry+https://github.com/rust-lang/crates.io-index"
503+checksum = "1aa79e62e7697b8e29b513a68abacf485adcd1fe8284a4316c5ae868e6633327"
504+dependencies = [
505+ "iana-time-zone",
506+ "js-sys",
507+ "num-traits",
508+ "wasm-bindgen",
509+ "windows-link",
510+]
511+
512+[[package]]
513+name = "cipher"
514+version = "0.4.4"
515+source = "registry+https://github.com/rust-lang/crates.io-index"
516+checksum = "773f3b9af64447d2ce9850330c473515014aa235e6a783b02db81ff39e4a3dad"
517+dependencies = [
518+ "crypto-common 0.1.7",
519+ "inout",
520+]
521+
522+[[package]]
523+name = "clang-sys"
524+version = "1.9.1"
525+source = "registry+https://github.com/rust-lang/crates.io-index"
526+checksum = "157a8ba7b480713b56f4c09fd13fc3e0a22a5dfab8097ba61cbc5feef950788a"
527+dependencies = [
528+ "glob",
529+ "libc",
530+ "libloading",
531+]
532+
533+[[package]]
534+name = "cobs"
535+version = "0.3.0"
536+source = "registry+https://github.com/rust-lang/crates.io-index"
537+checksum = "0fa961b519f0b462e3a3b4a34b64d119eeaca1d59af726fe450bbba07a9fc0a1"
538+dependencies = [
539+ "thiserror 2.0.21",
540+]
541+
542+[[package]]
543+name = "compression-codecs"
544+version = "0.4.46"
545+source = "registry+https://github.com/rust-lang/crates.io-index"
546+checksum = "cae36683101b2899f48bd31f8db9839437356188e3b1ff23096e73dab09ba8fe"
547+dependencies = [
548+ "brotli",
549+ "compression-core",
550+ "flate2",
551+ "memchr",
552+]
553+
554+[[package]]
555+name = "compression-core"
556+version = "0.4.34"
557+source = "registry+https://github.com/rust-lang/crates.io-index"
558+checksum = "2ebdda89edc534bf8d5dd2857562633b6495557e5846552ade994b99ed13c36a"
559+
560+[[package]]
561+name = "concurrent-queue"
562+version = "2.5.0"
563+source = "registry+https://github.com/rust-lang/crates.io-index"
564+checksum = "4ca0197aee26d1ae37445ee532fefce43251d24cc7c166799f4d46817f1d3973"
565+dependencies = [
566+ "crossbeam-utils",
567+]
568+
569+[[package]]
570+name = "const-oid"
571+version = "0.10.2"
572+source = "registry+https://github.com/rust-lang/crates.io-index"
573+checksum = "a6ef517f0926dd24a1582492c791b6a4818a4d94e789a334894aa15b0d12f55c"
574+
575+[[package]]
576+name = "constant_time_eq"
577+version = "0.4.2"
578+source = "registry+https://github.com/rust-lang/crates.io-index"
579+checksum = "3d52eff69cd5e647efe296129160853a42795992097e8af39800e1060caeea9b"
580+
581+[[package]]
582+name = "cookie"
583+version = "0.18.2"
584+source = "registry+https://github.com/rust-lang/crates.io-index"
585+checksum = "1a373e3602691c3cdea496d2f0ee5935151e6168fe87739483c463db1b2f2f87"
586+dependencies = [
587+ "aes-gcm",
588+ "base64 0.22.1",
589+ "hkdf",
590+ "hmac",
591+ "percent-encoding",
592+ "rand 0.8.8",
593+ "sha2 0.10.9",
594+ "subtle",
595+ "time",
596+ "version_check",
597+]
598+
599+[[package]]
600+name = "core-foundation-sys"
601+version = "0.8.7"
602+source = "registry+https://github.com/rust-lang/crates.io-index"
603+checksum = "773648b94d0e5d620f64f280777445740e61fe701025087ec8b57f45c791888b"
604+
605+[[package]]
606+name = "cpufeatures"
607+version = "0.2.17"
608+source = "registry+https://github.com/rust-lang/crates.io-index"
609+checksum = "59ed5838eebb26a2bb2e58f6d5b5316989ae9d08bab10e0e6d103e656d1b0280"
610+dependencies = [
611+ "libc",
612+]
613+
614+[[package]]
615+name = "cpufeatures"
616+version = "0.3.1"
617+source = "registry+https://github.com/rust-lang/crates.io-index"
618+checksum = "5ca28b0ae3115b884660db4118d803791fd6756b6e88f39c0f3f7859060d7566"
619+dependencies = [
620+ "libc",
621+]
622+
623+[[package]]
624+name = "crc32c"
625+version = "0.6.8"
626+source = "registry+https://github.com/rust-lang/crates.io-index"
627+checksum = "3a47af21622d091a8f0fb295b88bc886ac74efcc613efc19f5d0b21de5c89e47"
628+dependencies = [
629+ "rustc_version",
630+]
631+
632+[[package]]
633+name = "crc32fast"
634+version = "1.5.3"
635+source = "registry+https://github.com/rust-lang/crates.io-index"
636+checksum = "0ba106e844045ddc02c20768ac4b0b7cb45f2cc2ecbd833ac9f5dacb183c2055"
637+dependencies = [
638+ "cfg-if",
639+]
640+
641+[[package]]
642+name = "critical-section"
643+version = "1.2.0"
644+source = "registry+https://github.com/rust-lang/crates.io-index"
645+checksum = "790eea4361631c5e7d22598ecd5723ff611904e3344ce8720784c93e3d83d40b"
646+
647+[[package]]
648+name = "crossbeam-channel"
649+version = "0.5.17"
650+source = "registry+https://github.com/rust-lang/crates.io-index"
651+checksum = "98b0cc327b5bc766e7fda9c9260cc0fa81b43a8e240440422dff70788e3f9ef1"
652+dependencies = [
653+ "crossbeam-utils",
654+]
655+
656+[[package]]
657+name = "crossbeam-deque"
658+version = "0.8.8"
659+source = "registry+https://github.com/rust-lang/crates.io-index"
660+checksum = "622f3fc73690be383c7214310406f28a90e6edeadc3cea882f9d71e495b9711a"
661+dependencies = [
662+ "crossbeam-epoch",
663+ "crossbeam-utils",
664+]
665+
666+[[package]]
667+name = "crossbeam-epoch"
668+version = "0.9.21"
669+source = "registry+https://github.com/rust-lang/crates.io-index"
670+checksum = "dc74980687109a3b14c72fd458107bf0baa1da1a1a805e178d15501ba9b86d9d"
671+dependencies = [
672+ "crossbeam-utils",
673+]
674+
675+[[package]]
676+name = "crossbeam-utils"
677+version = "0.8.23"
678+source = "registry+https://github.com/rust-lang/crates.io-index"
679+checksum = "a31eee39dddec8330830986fcd7625edb5a24ec90ea038215273bbc3adb08ac6"
680+
681+[[package]]
682+name = "crunchy"
683+version = "0.2.4"
684+source = "registry+https://github.com/rust-lang/crates.io-index"
685+checksum = "460fbee9c2c2f33933d720630a6a0bac33ba7053db5344fac858d4b8952d77d5"
686+
687+[[package]]
688+name = "crypto-common"
689+version = "0.1.7"
690+source = "registry+https://github.com/rust-lang/crates.io-index"
691+checksum = "78c8292055d1c1df0cce5d180393dc8cce0abec0a7102adb6c7b1eef6016d60a"
692+dependencies = [
693+ "generic-array",
694+ "rand_core 0.6.4",
695+ "typenum",
696+]
697+
698+[[package]]
699+name = "crypto-common"
700+version = "0.2.2"
701+source = "registry+https://github.com/rust-lang/crates.io-index"
702+checksum = "ce6e4c961d6cd6c9a86db418387425e8bdeaf05b3c8bc1411e6dca4c252f1453"
703+dependencies = [
704+ "hybrid-array",
705+]
706+
707+[[package]]
708+name = "ctr"
709+version = "0.9.2"
710+source = "registry+https://github.com/rust-lang/crates.io-index"
711+checksum = "0369ee1ad671834580515889b80f2ea915f23b8be8d0daa4bbaf2ac5c7590835"
712+dependencies = [
713+ "cipher",
714+]
715+
716+[[package]]
717+name = "darling"
718+version = "0.20.11"
719+source = "registry+https://github.com/rust-lang/crates.io-index"
720+checksum = "fc7f46116c46ff9ab3eb1597a45688b6715c6e628b5c133e288e709a29bcb4ee"
721+dependencies = [
722+ "darling_core 0.20.11",
723+ "darling_macro 0.20.11",
724+]
725+
726+[[package]]
727+name = "darling"
728+version = "0.24.1"
729+source = "registry+https://github.com/rust-lang/crates.io-index"
730+checksum = "ed17f5901b6630b993ca003def43f2f8ef4014fc13b047b57aad617ff32bc2ec"
731+dependencies = [
732+ "darling_core 0.24.1",
733+ "darling_macro 0.24.1",
734+]
735+
736+[[package]]
737+name = "darling_core"
738+version = "0.20.11"
739+source = "registry+https://github.com/rust-lang/crates.io-index"
740+checksum = "0d00b9596d185e565c2207a0b01f8bd1a135483d02d9b7b0a54b11da8d53412e"
741+dependencies = [
742+ "fnv",
743+ "ident_case",
744+ "proc-macro2",
745+ "quote",
746+ "strsim",
747+ "syn 2.0.119",
748+]
749+
750+[[package]]
751+name = "darling_core"
752+version = "0.24.1"
753+source = "registry+https://github.com/rust-lang/crates.io-index"
754+checksum = "6837e2cf7485aaae18f86181d2f0e9a7ed297a025e220aeabf63fdebd3a2ddff"
755+dependencies = [
756+ "ident_case",
757+ "proc-macro2",
758+ "quote",
759+ "strsim",
760+ "syn 3.0.9",
761+]
762+
763+[[package]]
764+name = "darling_macro"
765+version = "0.20.11"
766+source = "registry+https://github.com/rust-lang/crates.io-index"
767+checksum = "fc34b93ccb385b40dc71c6fceac4b2ad23662c7eeb248cf10d529b7e055b6ead"
768+dependencies = [
769+ "darling_core 0.20.11",
770+ "quote",
771+ "syn 2.0.119",
772+]
773+
774+[[package]]
775+name = "darling_macro"
776+version = "0.24.1"
777+source = "registry+https://github.com/rust-lang/crates.io-index"
778+checksum = "2ac7135c3ef02b2f7833bbeb1be5ba7f966dcde8a87c6b87f65a778d71a02785"
779+dependencies = [
780+ "darling_core 0.24.1",
781+ "quote",
782+ "syn 3.0.9",
783+]
784+
785+[[package]]
786+name = "data-encoding"
787+version = "2.11.1"
788+source = "registry+https://github.com/rust-lang/crates.io-index"
789+checksum = "4583a4551df46e2792f82ceeac45e850d2e2d5debba0b91f102385cda5b11f06"
790+
791+[[package]]
792+name = "datasketches"
793+version = "0.2.0"
794+source = "registry+https://github.com/rust-lang/crates.io-index"
795+checksum = "c286de4e81ea2590afc24d754e0f83810c566f50a1388fa75ebd57928c0d9745"
796+
797+[[package]]
798+name = "deranged"
799+version = "0.5.9"
800+source = "registry+https://github.com/rust-lang/crates.io-index"
801+checksum = "9e9de72ce2ad1f90dc62fa25f0f430ef85eb4b0d8fa0be4f30373bc40a21d28e"
802+dependencies = [
803+ "serde_core",
804+]
805+
806+[[package]]
807+name = "derive_arbitrary"
808+version = "1.5.0"
809+source = "registry+https://github.com/rust-lang/crates.io-index"
810+checksum = "1b034bd7d5f032402a2479444dcc6f74e36a03f31854d41680fb240ef682a1ac"
811+dependencies = [
812+ "proc-macro2",
813+ "quote",
814+ "syn 3.0.9",
815+]
816+
817+[[package]]
818+name = "diff"
819+version = "0.1.13"
820+source = "registry+https://github.com/rust-lang/crates.io-index"
821+checksum = "56254986775e3233ffa9c4d7d3faaf6d36a2c09d30b20687e9f88bc8bafc16c8"
822+
823+[[package]]
824+name = "digest"
825+version = "0.10.7"
826+source = "registry+https://github.com/rust-lang/crates.io-index"
827+checksum = "9ed9a281f7bc9b7576e61468ba615a66a5c8cfdff42420a70aa82701a3b1e292"
828+dependencies = [
829+ "block-buffer 0.10.4",
830+ "crypto-common 0.1.7",
831+ "subtle",
832+]
833+
834+[[package]]
835+name = "digest"
836+version = "0.11.3"
837+source = "registry+https://github.com/rust-lang/crates.io-index"
838+checksum = "f1dd6dbb5841937940781866fa1281a1ff7bd3bf827091440879f9994983d5c2"
839+dependencies = [
840+ "block-buffer 0.12.1",
841+ "const-oid",
842+ "crypto-common 0.2.2",
843+]
844+
845+[[package]]
846+name = "displaydoc"
847+version = "0.2.7"
848+source = "registry+https://github.com/rust-lang/crates.io-index"
849+checksum = "c6232dd377dcc64799954cbd3a9bb882e9cdc1308ccd87b1c098f1fb2eaf82a8"
850+dependencies = [
851+ "proc-macro2",
852+ "quote",
853+ "syn 3.0.9",
854+]
855+
856+[[package]]
857+name = "downcast-rs"
858+version = "2.0.2"
859+source = "registry+https://github.com/rust-lang/crates.io-index"
860+checksum = "117240f60069e65410b3ae1bb213295bd828f707b5bec6596a1afc8793ce0cbc"
861+
862+[[package]]
863+name = "either"
864+version = "1.19.0"
865+source = "registry+https://github.com/rust-lang/crates.io-index"
866+checksum = "0e9c71c2167ca323c882b99918929403426e2373ea17242ff5653e0d5e1058be"
867+
868+[[package]]
869+name = "elsa"
870+version = "1.11.2"
871+source = "registry+https://github.com/rust-lang/crates.io-index"
872+checksum = "9abf33c656a7256451ebb7d0082c5a471820c31269e49d807c538c252352186e"
873+dependencies = [
874+ "stable_deref_trait",
875+]
876+
877+[[package]]
878+name = "email-encoding"
879+version = "0.4.2"
880+source = "registry+https://github.com/rust-lang/crates.io-index"
881+checksum = "420b9da095f052ea597503e39073b5b3c522f7db933fbac202d91d24492693fd"
882+dependencies = [
883+ "base64 0.23.1",
884+ "memchr",
885+]
886+
887+[[package]]
888+name = "email_address"
889+version = "0.2.9"
890+source = "registry+https://github.com/rust-lang/crates.io-index"
891+checksum = "e079f19b08ca6239f47f8ba8509c11cf3ea30095831f7fed61441475edd8c449"
892+
893+[[package]]
894+name = "embedded-io"
895+version = "0.4.0"
896+source = "registry+https://github.com/rust-lang/crates.io-index"
897+checksum = "ef1a6892d9eef45c8fa6b9e0086428a2cca8491aca8f787c534a3d6d0bcb3ced"
898+
899+[[package]]
900+name = "embedded-io"
901+version = "0.6.1"
902+source = "registry+https://github.com/rust-lang/crates.io-index"
903+checksum = "edd0f118536f44f5ccd48bcb8b111bdc3de888b58c74639dfb034a357d0f206d"
904+
905+[[package]]
906+name = "ensure-cov"
907+version = "0.1.0"
908+source = "registry+https://github.com/rust-lang/crates.io-index"
909+checksum = "33753185802e107b8fa907192af1f0eca13b1fb33327a59266d650fef29b2b4e"
910+
911+[[package]]
912+name = "enum-as-inner"
913+version = "0.5.1"
914+source = "registry+https://github.com/rust-lang/crates.io-index"
915+checksum = "c9720bba047d567ffc8a3cba48bf19126600e249ab7f128e9233e6376976a116"
916+dependencies = [
917+ "heck 0.4.1",
918+ "proc-macro2",
919+ "quote",
920+ "syn 1.0.109",
921+]
922+
923+[[package]]
924+name = "enum-as-inner"
925+version = "0.6.1"
926+source = "registry+https://github.com/rust-lang/crates.io-index"
927+checksum = "a1e6a265c649f3f5979b601d26f1d05ada116434c87741c9493cb56218f76cbc"
928+dependencies = [
929+ "heck 0.5.0",
930+ "proc-macro2",
931+ "quote",
932+ "syn 2.0.119",
933+]
934+
935+[[package]]
936+name = "enum_dispatch"
937+version = "0.3.13"
938+source = "registry+https://github.com/rust-lang/crates.io-index"
939+checksum = "aa18ce2bc66555b3218614519ac839ddb759a7d6720732f979ef8d13be147ecd"
940+dependencies = [
941+ "once_cell",
942+ "proc-macro2",
943+ "quote",
944+ "syn 2.0.119",
945+]
946+
947+[[package]]
948+name = "env_filter"
949+version = "2.0.0"
950+source = "registry+https://github.com/rust-lang/crates.io-index"
951+checksum = "900d271a03799a1ee8d1ca9b19893b48ca674a9284fefcfb85f05e74ed314217"
952+dependencies = [
953+ "log",
954+ "regex",
955+]
956+
957+[[package]]
958+name = "env_logger"
959+version = "0.11.11"
960+source = "registry+https://github.com/rust-lang/crates.io-index"
961+checksum = "de671bd27a75a797dc9ae289ba1e77276e75e2026408aab65185384e2d5cd3f6"
962+dependencies = [
963+ "env_filter",
964+ "log",
965+]
966+
967+[[package]]
968+name = "equivalent"
969+version = "1.0.3"
970+source = "registry+https://github.com/rust-lang/crates.io-index"
971+checksum = "00d174d5400e5e8fd687ad1049e2f578285fa914201b1af7e8b112a4546bd826"
972+
973+[[package]]
974+name = "erased-serde"
975+version = "0.4.11"
976+source = "registry+https://github.com/rust-lang/crates.io-index"
977+checksum = "1e59b668157f32d3459d4bd634861a06ffa2503a461ca5f0916b9f0252605e66"
978+dependencies = [
979+ "serde",
980+ "serde_core",
981+ "typeid",
982+]
983+
984+[[package]]
985+name = "errno"
986+version = "0.3.14"
987+source = "registry+https://github.com/rust-lang/crates.io-index"
988+checksum = "39cab71617ae0d63f51a36d69f866391735b51691dbda63cf6f96d042b63efeb"
989+dependencies = [
990+ "libc",
991+ "windows-sys 0.61.2",
992+]
993+
994+[[package]]
995+name = "fallible-iterator"
996+version = "0.3.0"
997+source = "registry+https://github.com/rust-lang/crates.io-index"
998+checksum = "2acce4a10f12dc2fb14a218589d4f1f62ef011b2d0cc4b3cb1bba8e94da14649"
999+
1000+[[package]]
1001+name = "fastbloom"
1002+version = "0.14.1"
1003+source = "registry+https://github.com/rust-lang/crates.io-index"
1004+checksum = "4e7f34442dbe69c60fe8eaf58a8cafff81a1f278816d8ab4db255b3bef4ac3c4"
1005+dependencies = [
1006+ "getrandom 0.3.4",
1007+ "libm",
1008+ "siphasher",
1009+]
1010+
1011+[[package]]
1012+name = "fastdivide"
1013+version = "0.4.2"
1014+source = "registry+https://github.com/rust-lang/crates.io-index"
1015+checksum = "9afc2bd4d5a73106dd53d10d73d3401c2f32730ba2c0b93ddb888a8983680471"
1016+
1017+[[package]]
1018+name = "fastrand"
1019+version = "2.5.0"
1020+source = "registry+https://github.com/rust-lang/crates.io-index"
1021+checksum = "da7c62ceae207dd37ea5b845da6a0696c799f85e97da1ab5b7910be3c1c80223"
1022+
1023+[[package]]
1024+name = "find-msvc-tools"
1025+version = "0.1.15"
1026+source = "registry+https://github.com/rust-lang/crates.io-index"
1027+checksum = "1c66915cc5391097de7a2b0b972e8505aa33c0df401fd3a6811dbdb32881ba48"
1028+
1029+[[package]]
1030+name = "flate2"
1031+version = "1.1.10"
1032+source = "registry+https://github.com/rust-lang/crates.io-index"
1033+checksum = "6e634e2e0ebac1ee034020da1ca582e17ffe4e0f5e985823721e168928136dcb"
1034+dependencies = [
1035+ "crc32fast",
1036+ "miniz_oxide",
1037+ "zlib-rs",
1038+]
1039+
1040+[[package]]
1041+name = "fnv"
1042+version = "1.0.7"
1043+source = "registry+https://github.com/rust-lang/crates.io-index"
1044+checksum = "3f9eec918d3f24069decb9af1554cad7c880e2da24a9afd88aca000531ab82c1"
1045+
1046+[[package]]
1047+name = "foldhash"
1048+version = "0.2.0"
1049+source = "registry+https://github.com/rust-lang/crates.io-index"
1050+checksum = "77ce24cb58228fbb8aa041425bb1050850ac19177686ea6e0f41a70416f56fdb"
1051+
1052+[[package]]
1053+name = "form_urlencoded"
1054+version = "1.2.2"
1055+source = "registry+https://github.com/rust-lang/crates.io-index"
1056+checksum = "cb4cb245038516f5f85277875cdaa4f7d2c9a0fa0468de06ed190163b1581fcf"
1057+dependencies = [
1058+ "percent-encoding",
1059+]
1060+
1061+[[package]]
1062+name = "fs4"
1063+version = "0.13.1"
1064+source = "registry+https://github.com/rust-lang/crates.io-index"
1065+checksum = "8640e34b88f7652208ce9e88b1a37a2ae95227d84abec377ccd3c5cfeb141ed4"
1066+dependencies = [
1067+ "rustix 1.1.6",
1068+ "windows-sys 0.59.0",
1069+]
1070+
1071+[[package]]
1072+name = "funty"
1073+version = "2.0.0"
1074+source = "registry+https://github.com/rust-lang/crates.io-index"
1075+checksum = "e6d5a32815ae3f33302d95fdcb2ce17862f8c65363dcfd29360480ba1001fc9c"
1076+
1077+[[package]]
1078+name = "futures-channel"
1079+version = "0.3.34"
1080+source = "registry+https://github.com/rust-lang/crates.io-index"
1081+checksum = "b1f9e3d69d39e4862ffed03ed071a76f9a13ba1d9109d355b0f0aa6b15e393c4"
1082+dependencies = [
1083+ "futures-core",
1084+]
1085+
1086+[[package]]
1087+name = "futures-core"
1088+version = "0.3.34"
1089+source = "registry+https://github.com/rust-lang/crates.io-index"
1090+checksum = "92d699e522242e69e3003b94ecc1f960f3a5e015aa7c5d7486e65ad01dd94f5e"
1091+
1092+[[package]]
1093+name = "futures-macro"
1094+version = "0.3.34"
1095+source = "registry+https://github.com/rust-lang/crates.io-index"
1096+checksum = "9fb9654ba8355388abeb8dcb4fc62f511300867002afc858860463bdd9fe0c44"
1097+dependencies = [
1098+ "proc-macro2",
1099+ "quote",
1100+ "syn 3.0.9",
1101+]
1102+
1103+[[package]]
1104+name = "futures-sink"
1105+version = "0.3.34"
1106+source = "registry+https://github.com/rust-lang/crates.io-index"
1107+checksum = "1944426bf7d03f1d14f708785e4b33efd750b36d48a157b836b3efc15ede8e1d"
1108+
1109+[[package]]
1110+name = "futures-task"
1111+version = "0.3.34"
1112+source = "registry+https://github.com/rust-lang/crates.io-index"
1113+checksum = "cd417de3d1d015fc3bfd2b1ea46dfc7bab72ef86f1cc7cc9c78e728b34a6d1fd"
1114+
1115+[[package]]
1116+name = "futures-util"
1117+version = "0.3.34"
1118+source = "registry+https://github.com/rust-lang/crates.io-index"
1119+checksum = "0d50a92467f8ba5dd6e3ee5d4bd04d73ab2e4e1c44474a0674821dfce14b79bc"
1120+dependencies = [
1121+ "futures-core",
1122+ "futures-macro",
1123+ "futures-sink",
1124+ "futures-task",
1125+ "pin-project-lite",
1126+ "slab",
1127+]
1128+
1129+[[package]]
1130+name = "genawaiter"
1131+version = "0.99.1"
1132+source = "registry+https://github.com/rust-lang/crates.io-index"
1133+checksum = "c86bd0361bcbde39b13475e6e36cb24c329964aa2611be285289d1e4b751c1a0"
1134+dependencies = [
1135+ "genawaiter-macro",
1136+]
1137+
1138+[[package]]
1139+name = "genawaiter-macro"
1140+version = "0.99.1"
1141+source = "registry+https://github.com/rust-lang/crates.io-index"
1142+checksum = "0b32dfe1fdfc0bbde1f22a5da25355514b5e450c33a6af6770884c8750aedfbc"
1143+
1144+[[package]]
1145+name = "generator"
1146+version = "0.8.11"
1147+source = "registry+https://github.com/rust-lang/crates.io-index"
1148+checksum = "1be81b31c9ce4caf7f3178eeb90662bb1864d3ad363ec6bdada3201adff19c37"
1149+dependencies = [
1150+ "cc",
1151+ "cfg-if",
1152+ "libc",
1153+ "log",
1154+ "rustversion",
1155+ "windows-link",
1156+ "windows-result",
1157+]
1158+
1159+[[package]]
1160+name = "generic-array"
1161+version = "0.14.7"
1162+source = "registry+https://github.com/rust-lang/crates.io-index"
1163+checksum = "85649ca51fd72272d7821adaf274ad91c288277713d9c18820d8499a7ff69e9a"
1164+dependencies = [
1165+ "typenum",
1166+ "version_check",
1167+]
1168+
1169+[[package]]
1170+name = "generic-btree"
1171+version = "0.10.7"
1172+source = "registry+https://github.com/rust-lang/crates.io-index"
1173+checksum = "a0c1bce85c110ab718fd139e0cc89c51b63bd647b14a767e24bdfc77c83df79b"
1174+dependencies = [
1175+ "arref",
1176+ "heapless 0.9.3",
1177+ "itertools 0.11.0",
1178+ "loro-thunderdome",
1179+ "proc-macro2",
1180+ "rustc-hash 2.1.3",
1181+]
1182+
1183+[[package]]
1184+name = "getrandom"
1185+version = "0.2.17"
1186+source = "registry+https://github.com/rust-lang/crates.io-index"
1187+checksum = "ff2abc00be7fca6ebc474524697ae276ad847ad0a6b3faa4bcb027e9a4614ad0"
1188+dependencies = [
1189+ "cfg-if",
1190+ "js-sys",
1191+ "libc",
1192+ "wasi",
1193+ "wasm-bindgen",
1194+]
1195+
1196+[[package]]
1197+name = "getrandom"
1198+version = "0.3.4"
1199+source = "registry+https://github.com/rust-lang/crates.io-index"
1200+checksum = "899def5c37c4fd7b2664648c28120ecec138e4d395b459e5ca34f9cce2dd77fd"
1201+dependencies = [
1202+ "cfg-if",
1203+ "js-sys",
1204+ "libc",
1205+ "r-efi 5.3.0",
1206+ "wasip2",
1207+ "wasm-bindgen",
1208+]
1209+
1210+[[package]]
1211+name = "getrandom"
1212+version = "0.4.3"
1213+source = "registry+https://github.com/rust-lang/crates.io-index"
1214+checksum = "300e883d756b2e4ec94e02791f39b04b522276138852cfc41d9fb7e904106099"
1215+dependencies = [
1216+ "cfg-if",
1217+ "js-sys",
1218+ "libc",
1219+ "r-efi 6.0.0",
1220+ "wasm-bindgen",
1221+]
1222+
1223+[[package]]
1224+name = "ghash"
1225+version = "0.5.1"
1226+source = "registry+https://github.com/rust-lang/crates.io-index"
1227+checksum = "f0d8a4362ccb29cb0b265253fb0a2728f592895ee6854fd9bc13f2ffda266ff1"
1228+dependencies = [
1229+ "opaque-debug",
1230+ "polyval",
1231+]
1232+
1233+[[package]]
1234+name = "glob"
1235+version = "0.3.4"
1236+source = "registry+https://github.com/rust-lang/crates.io-index"
1237+checksum = "e4eba85ea1d0a966a983acd07deee566e67395d2d96b6fb39e62b5a833f1eb0b"
1238+
1239+[[package]]
1240+name = "h2"
1241+version = "0.4.20"
1242+source = "registry+https://github.com/rust-lang/crates.io-index"
1243+checksum = "7d29020232d6aa3fb1daca64c1127cf662cf97f254ae16c18c05b8ab635fc118"
1244+dependencies = [
1245+ "atomic-waker",
1246+ "bytes",
1247+ "fnv",
1248+ "futures-core",
1249+ "futures-sink",
1250+ "http",
1251+ "indexmap",
1252+ "slab",
1253+ "tokio",
1254+ "tokio-util",
1255+ "tracing",
1256+]
1257+
1258+[[package]]
1259+name = "hash32"
1260+version = "0.2.1"
1261+source = "registry+https://github.com/rust-lang/crates.io-index"
1262+checksum = "b0c35f58762feb77d74ebe43bdbc3210f09be9fe6742234d573bacc26ed92b67"
1263+dependencies = [
1264+ "byteorder",
1265+]
1266+
1267+[[package]]
1268+name = "hash32"
1269+version = "0.3.1"
1270+source = "registry+https://github.com/rust-lang/crates.io-index"
1271+checksum = "47d60b12902ba28e2730cd37e95b8c9223af2808df9e902d4df49588d1470606"
1272+dependencies = [
1273+ "byteorder",
1274+]
1275+
1276+[[package]]
1277+name = "hashbrown"
1278+version = "0.16.1"
1279+source = "registry+https://github.com/rust-lang/crates.io-index"
1280+checksum = "841d1cc9bed7f9236f321df977030373f4a4163ae1a7dbfe1a51a2c1a51d9100"
1281+dependencies = [
1282+ "allocator-api2 0.2.21",
1283+ "equivalent",
1284+ "foldhash",
1285+]
1286+
1287+[[package]]
1288+name = "hashbrown"
1289+version = "0.17.1"
1290+source = "registry+https://github.com/rust-lang/crates.io-index"
1291+checksum = "ed5909b6e89a2db4456e54cd5f673791d7eca6732202bbf2a9cc504fe2f9b84a"
1292+
1293+[[package]]
1294+name = "heapless"
1295+version = "0.7.17"
1296+source = "registry+https://github.com/rust-lang/crates.io-index"
1297+checksum = "cdc6457c0eb62c71aac4bc17216026d8410337c4126773b9c5daba343f17964f"
1298+dependencies = [
1299+ "atomic-polyfill",
1300+ "hash32 0.2.1",
1301+ "rustc_version",
1302+ "serde",
1303+ "spin",
1304+ "stable_deref_trait",
1305+]
1306+
1307+[[package]]
1308+name = "heapless"
1309+version = "0.8.0"
1310+source = "registry+https://github.com/rust-lang/crates.io-index"
1311+checksum = "0bfb9eb618601c89945a70e254898da93b13be0388091d42117462b265bb3fad"
1312+dependencies = [
1313+ "hash32 0.3.1",
1314+ "stable_deref_trait",
1315+]
1316+
1317+[[package]]
1318+name = "heapless"
1319+version = "0.9.3"
1320+source = "registry+https://github.com/rust-lang/crates.io-index"
1321+checksum = "25ba4bd83f9415b58b4ed8dc5714c76e626a105be4646c02630ad730ad3b5aa4"
1322+dependencies = [
1323+ "hash32 0.3.1",
1324+ "stable_deref_trait",
1325+]
1326+
1327+[[package]]
1328+name = "heck"
1329+version = "0.4.1"
1330+source = "registry+https://github.com/rust-lang/crates.io-index"
1331+checksum = "95505c38b4572b2d910cecb0281560f54b440a19336cbbcb27bf6ce6adc6f5a8"
1332+
1333+[[package]]
1334+name = "heck"
1335+version = "0.5.0"
1336+source = "registry+https://github.com/rust-lang/crates.io-index"
1337+checksum = "2304e00983f87ffb38b55b444b5e3b60a884b5d30c0fca7d82fe33449bbe55ea"
1338+
1339+[[package]]
1340+name = "hermit-abi"
1341+version = "0.5.3"
1342+source = "registry+https://github.com/rust-lang/crates.io-index"
1343+checksum = "e17592d60ebacc7d5e169f4663c5f84f9161cc90328abcfe8456f41e4dfcb284"
1344+
1345+[[package]]
1346+name = "hex"
1347+version = "0.4.3"
1348+source = "registry+https://github.com/rust-lang/crates.io-index"
1349+checksum = "7f24254aa9a54b5c858eaee2f5bccdb46aaf0e486a595ed5fd8f86ba55232a70"
1350+
1351+[[package]]
1352+name = "hkdf"
1353+version = "0.12.4"
1354+source = "registry+https://github.com/rust-lang/crates.io-index"
1355+checksum = "7b5f8eb2ad728638ea2c7d47a21db23b7b58a72ed6a38256b8a1849f15fbbdf7"
1356+dependencies = [
1357+ "hmac",
1358+]
1359+
1360+[[package]]
1361+name = "hmac"
1362+version = "0.12.1"
1363+source = "registry+https://github.com/rust-lang/crates.io-index"
1364+checksum = "6c49c37c09c17a53d937dfbb742eb3a961d65a994e6bcdcf37e7399d0cc8ab5e"
1365+dependencies = [
1366+ "digest 0.10.7",
1367+]
1368+
1369+[[package]]
1370+name = "home"
1371+version = "0.5.12"
1372+source = "registry+https://github.com/rust-lang/crates.io-index"
1373+checksum = "cc627f471c528ff0c4a49e1d5e60450c8f6461dd6d10ba9dcd3a61d3dff7728d"
1374+dependencies = [
1375+ "windows-sys 0.61.2",
1376+]
1377+
1378+[[package]]
1379+name = "hostname"
1380+version = "0.4.2"
1381+source = "registry+https://github.com/rust-lang/crates.io-index"
1382+checksum = "617aaa3557aef3810a6369d0a99fac8a080891b68bd9f9812a1eeda0c0730cbd"
1383+dependencies = [
1384+ "cfg-if",
1385+ "libc",
1386+ "windows-link",
1387+]
1388+
1389+[[package]]
1390+name = "htmlescape"
1391+version = "0.3.1"
1392+source = "registry+https://github.com/rust-lang/crates.io-index"
1393+checksum = "e9025058dae765dee5070ec375f591e2ba14638c63feff74f13805a72e523163"
1394+
1395+[[package]]
1396+name = "http"
1397+version = "1.5.0"
1398+source = "registry+https://github.com/rust-lang/crates.io-index"
1399+checksum = "918d3568bebf352712bc2ef3d46a8bcf1a75b373be6539de198e9105cbbf9ce0"
1400+dependencies = [
1401+ "bytes",
1402+ "itoa",
1403+]
1404+
1405+[[package]]
1406+name = "http-body"
1407+version = "1.1.0"
1408+source = "registry+https://github.com/rust-lang/crates.io-index"
1409+checksum = "ca2a8f2913ee65f60facd6a5905613afaa448497a0230cc41ce022d93290bc2c"
1410+dependencies = [
1411+ "bytes",
1412+ "http",
1413+]
1414+
1415+[[package]]
1416+name = "http-body-util"
1417+version = "0.1.5"
1418+source = "registry+https://github.com/rust-lang/crates.io-index"
1419+checksum = "23169fe34a5fbcdd3f3862e78fb9b6fccd5f02a6dc6f732547005d45631ce71c"
1420+dependencies = [
1421+ "bytes",
1422+ "futures-core",
1423+ "http",
1424+ "http-body",
1425+ "pin-project-lite",
1426+]
1427+
1428+[[package]]
1429+name = "httparse"
1430+version = "1.10.1"
1431+source = "registry+https://github.com/rust-lang/crates.io-index"
1432+checksum = "6dbf3de79e51f3d586ab4cb9d5c3e2c14aa28ed23d180cf89b4df0454a69cc87"
1433+
1434+[[package]]
1435+name = "httpdate"
1436+version = "1.0.3"
1437+source = "registry+https://github.com/rust-lang/crates.io-index"
1438+checksum = "df3b46402a9d5adb4c86a0cf463f42e19994e3ee891101b1841f30a545cb49a9"
1439+
1440+[[package]]
1441+name = "hybrid-array"
1442+version = "0.4.15"
1443+source = "registry+https://github.com/rust-lang/crates.io-index"
1444+checksum = "27f864f10dfb56725ce5ce5472bc52252c8f93a4ab86327122cebf62c5f59a17"
1445+dependencies = [
1446+ "typenum",
1447+]
1448+
1449+[[package]]
1450+name = "hyper"
1451+version = "1.12.0"
1452+source = "registry+https://github.com/rust-lang/crates.io-index"
1453+checksum = "2c3e324da4c95177d6291d4c8730197c0d1822f8a9766814a4a44fa5ab797c9c"
1454+dependencies = [
1455+ "atomic-waker",
1456+ "bytes",
1457+ "futures-channel",
1458+ "futures-core",
1459+ "h2",
1460+ "http",
1461+ "http-body",
1462+ "httparse",
1463+ "httpdate",
1464+ "itoa",
1465+ "pin-project-lite",
1466+ "smallvec",
1467+ "tokio",
1468+]
1469+
1470+[[package]]
1471+name = "hyper-util"
1472+version = "0.1.21"
1473+source = "registry+https://github.com/rust-lang/crates.io-index"
1474+checksum = "ddc03d96684f9226b8a787cdb71488417b53ab5ea8fdb1dac946cb9431cc8bff"
1475+dependencies = [
1476+ "bytes",
1477+ "http",
1478+ "http-body",
1479+ "hyper",
1480+ "pin-project-lite",
1481+ "tokio",
1482+]
1483+
1484+[[package]]
1485+name = "iana-time-zone"
1486+version = "0.1.65"
1487+source = "registry+https://github.com/rust-lang/crates.io-index"
1488+checksum = "e31bc9ad994ba00e440a8aa5c9ef0ec67d5cb5e5cb0cc7f8b744a35b389cc470"
1489+dependencies = [
1490+ "android_system_properties",
1491+ "core-foundation-sys",
1492+ "iana-time-zone-haiku",
1493+ "js-sys",
1494+ "log",
1495+ "wasm-bindgen",
1496+ "windows-core",
1497+]
1498+
1499+[[package]]
1500+name = "iana-time-zone-haiku"
1501+version = "0.1.2"
1502+source = "registry+https://github.com/rust-lang/crates.io-index"
1503+checksum = "f31827a206f56af32e590ba56d5d2d085f558508192593743f16b2306495269f"
1504+dependencies = [
1505+ "cc",
1506+]
1507+
1508+[[package]]
1509+name = "icu_collator"
1510+version = "2.4.0"
1511+source = "registry+https://github.com/rust-lang/crates.io-index"
1512+checksum = "24cb0205c419b2036da3f9082964905d6849b3f2130dd4a517940c45899a544b"
1513+dependencies = [
1514+ "icu_collator_data",
1515+ "icu_collections",
1516+ "icu_locale_core",
1517+ "icu_locale_fallback",
1518+ "icu_normalizer",
1519+ "icu_properties",
1520+ "icu_provider",
1521+ "smallvec",
1522+ "utf16_iter",
1523+ "utf8_iter",
1524+ "zerovec",
1525+]
1526+
1527+[[package]]
1528+name = "icu_collator_data"
1529+version = "2.4.0"
1530+source = "registry+https://github.com/rust-lang/crates.io-index"
1531+checksum = "183f47e821a327661c1ebe152f61d5b6c2000010d228cadbbf226e0e2b8c2634"
1532+
1533+[[package]]
1534+name = "icu_collections"
1535+version = "2.4.0"
1536+source = "registry+https://github.com/rust-lang/crates.io-index"
1537+checksum = "fe090a42a0d3140fed8c63263ed1fecc02422cb2f4bfe55cd8de2de1b8e105dd"
1538+dependencies = [
1539+ "displaydoc",
1540+ "potential_utf",
1541+ "utf8_iter",
1542+ "yoke",
1543+ "zerofrom",
1544+ "zerovec",
1545+]
1546+
1547+[[package]]
1548+name = "icu_locale"
1549+version = "2.4.0"
1550+source = "registry+https://github.com/rust-lang/crates.io-index"
1551+checksum = "fe8fa57bcddc15cb921582ee5259c5b77da39f946f188ca5213fad24d9241236"
1552+dependencies = [
1553+ "icu_collections",
1554+ "icu_locale_core",
1555+ "icu_locale_data",
1556+ "icu_locale_fallback",
1557+ "icu_provider",
1558+ "tinystr",
1559+ "zerovec",
1560+]
1561+
1562+[[package]]
1563+name = "icu_locale_core"
1564+version = "2.4.0"
1565+source = "registry+https://github.com/rust-lang/crates.io-index"
1566+checksum = "25d29b57c17c6528d0dc4c2141cfa2d08200465acb537a3909c8b9b8a4a984c0"
1567+dependencies = [
1568+ "displaydoc",
1569+ "litemap",
1570+ "serde",
1571+ "tinystr",
1572+ "writeable",
1573+ "zerovec",
1574+]
1575+
1576+[[package]]
1577+name = "icu_locale_data"
1578+version = "2.4.0"
1579+source = "registry+https://github.com/rust-lang/crates.io-index"
1580+checksum = "a64014dac577a11d8d2cee48517c73c1984bd72ab11031e934269bd3cefb2ad9"
1581+
1582+[[package]]
1583+name = "icu_locale_fallback"
1584+version = "2.4.0"
1585+source = "registry+https://github.com/rust-lang/crates.io-index"
1586+checksum = "406e9ae5b95d8aa37db6293405931b766a6172d1848daee22d70eb44aa78a43c"
1587+dependencies = [
1588+ "icu_locale_core",
1589+ "icu_locale_fallback_data",
1590+ "icu_provider",
1591+ "potential_utf",
1592+ "tinystr",
1593+ "zerovec",
1594+]
1595+
1596+[[package]]
1597+name = "icu_locale_fallback_data"
1598+version = "2.4.0"
1599+source = "registry+https://github.com/rust-lang/crates.io-index"
1600+checksum = "3632ebbd0c5c3637ba1a40bdf8288f2cb9d2268e73441a69d5fc73d7cfbaa87c"
1601+
1602+[[package]]
1603+name = "icu_normalizer"
1604+version = "2.4.0"
1605+source = "registry+https://github.com/rust-lang/crates.io-index"
1606+checksum = "404a3b8c486f205c87fe7f23ab6894d84a4ad76d6e4671ae1981ba7def87c599"
1607+dependencies = [
1608+ "icu_collections",
1609+ "icu_normalizer_data",
1610+ "icu_properties",
1611+ "icu_provider",
1612+ "smallvec",
1613+ "utf16_iter",
1614+ "utf8_iter",
1615+ "write16",
1616+ "zerovec",
1617+]
1618+
1619+[[package]]
1620+name = "icu_normalizer_data"
1621+version = "2.4.0"
1622+source = "registry+https://github.com/rust-lang/crates.io-index"
1623+checksum = "20f0088bfb7441f7a37fa0c9e20cb1e9cba1cac6b9ce8cd2a6dc44294f8e8cbc"
1624+
1625+[[package]]
1626+name = "icu_properties"
1627+version = "2.4.0"
1628+source = "registry+https://github.com/rust-lang/crates.io-index"
1629+checksum = "2ea83d991c56158f7cf898bf86436c1dfe7c07ee82fe88951f2695c9f37a379f"
1630+dependencies = [
1631+ "displaydoc",
1632+ "icu_collections",
1633+ "icu_locale_core",
1634+ "icu_properties_data",
1635+ "icu_provider",
1636+ "zerotrie",
1637+ "zerovec",
1638+]
1639+
1640+[[package]]
1641+name = "icu_properties_data"
1642+version = "2.4.0"
1643+source = "registry+https://github.com/rust-lang/crates.io-index"
1644+checksum = "b98f29af82d02b163fe50161388350e743bb3107cc8e8c2f7314cb505faddfcf"
1645+
1646+[[package]]
1647+name = "icu_provider"
1648+version = "2.4.0"
1649+source = "registry+https://github.com/rust-lang/crates.io-index"
1650+checksum = "413099315636c588ee8f011190b329b971a09a8fae9d157e01dcae8379468514"
1651+dependencies = [
1652+ "displaydoc",
1653+ "icu_locale_core",
1654+ "serde",
1655+ "stable_deref_trait",
1656+ "writeable",
1657+ "yoke",
1658+ "zerofrom",
1659+ "zerotrie",
1660+ "zerovec",
1661+]
1662+
1663+[[package]]
1664+name = "ident_case"
1665+version = "1.0.1"
1666+source = "registry+https://github.com/rust-lang/crates.io-index"
1667+checksum = "b9e0384b61958566e926dc50660321d12159025e767c18e043daf26b70104c39"
1668+
1669+[[package]]
1670+name = "idna"
1671+version = "1.1.0"
1672+source = "registry+https://github.com/rust-lang/crates.io-index"
1673+checksum = "3b0875f23caa03898994f6ddc501886a45c7d3d62d04d2d90788d47be1b1e4de"
1674+dependencies = [
1675+ "idna_adapter",
1676+ "smallvec",
1677+ "utf8_iter",
1678+]
1679+
1680+[[package]]
1681+name = "idna_adapter"
1682+version = "1.2.2"
1683+source = "registry+https://github.com/rust-lang/crates.io-index"
1684+checksum = "cb68373c0d6620ef8105e855e7745e18b0d00d3bdb07fb532e434244cdb9a714"
1685+dependencies = [
1686+ "icu_normalizer",
1687+ "icu_properties",
1688+]
1689+
1690+[[package]]
1691+name = "im"
1692+version = "15.1.0"
1693+source = "registry+https://github.com/rust-lang/crates.io-index"
1694+checksum = "d0acd33ff0285af998aaf9b57342af478078f53492322fafc47450e09397e0e9"
1695+dependencies = [
1696+ "bitmaps",
1697+ "rand_core 0.6.4",
1698+ "rand_xoshiro",
1699+ "serde",
1700+ "sized-chunks",
1701+ "typenum",
1702+ "version_check",
1703+]
1704+
1705+[[package]]
1706+name = "indexmap"
1707+version = "2.14.2"
1708+source = "registry+https://github.com/rust-lang/crates.io-index"
1709+checksum = "cc4e190f5d26ca7051642629da2c52fc03bde85a03197c99408dcd291734c855"
1710+dependencies = [
1711+ "equivalent",
1712+ "hashbrown 0.17.1",
1713+]
1714+
1715+[[package]]
1716+name = "inout"
1717+version = "0.1.4"
1718+source = "registry+https://github.com/rust-lang/crates.io-index"
1719+checksum = "879f10e63c20629ecabbb64a8010319738c66a5cd0c29b02d63d272b03751d01"
1720+dependencies = [
1721+ "generic-array",
1722+]
1723+
1724+[[package]]
1725+name = "intrusive-collections"
1726+version = "0.9.7"
1727+source = "registry+https://github.com/rust-lang/crates.io-index"
1728+checksum = "189d0897e4cbe8c75efedf3502c18c887b05046e59d28404d4d8e46cbc4d1e86"
1729+dependencies = [
1730+ "memoffset",
1731+]
1732+
1733+[[package]]
1734+name = "inventory"
1735+version = "0.3.25"
1736+source = "registry+https://github.com/rust-lang/crates.io-index"
1737+checksum = "6928282826c822ad91bf1c9a1cb90a30ba1c26770749929b4656cd6be829cd7c"
1738+dependencies = [
1739+ "rustversion",
1740+]
1741+
1742+[[package]]
1743+name = "io-uring"
1744+version = "0.7.15"
1745+source = "registry+https://github.com/rust-lang/crates.io-index"
1746+checksum = "ed3bd0ecfbb87805f538bb7b32e5239ca0763890c623e349860ecba69469f2bb"
1747+dependencies = [
1748+ "bitflags",
1749+ "cfg-if",
1750+ "libc",
1751+]
1752+
1753+[[package]]
1754+name = "ipnet"
1755+version = "2.12.2"
1756+source = "registry+https://github.com/rust-lang/crates.io-index"
1757+checksum = "791930b43c0d5973160d90a8f3894509f2b273430f5c5c73b668636d0287c5c0"
1758+
1759+[[package]]
1760+name = "itertools"
1761+version = "0.11.0"
1762+source = "registry+https://github.com/rust-lang/crates.io-index"
1763+checksum = "b1c173a5686ce8bfa551b3563d0c2170bf24ca44da99c7ca4bfdab5418c3fe57"
1764+dependencies = [
1765+ "either",
1766+]
1767+
1768+[[package]]
1769+name = "itertools"
1770+version = "0.12.1"
1771+source = "registry+https://github.com/rust-lang/crates.io-index"
1772+checksum = "ba291022dbbd398a455acf126c1e341954079855bc60dfdda641363bd6922569"
1773+dependencies = [
1774+ "either",
1775+]
1776+
1777+[[package]]
1778+name = "itertools"
1779+version = "0.14.0"
1780+source = "registry+https://github.com/rust-lang/crates.io-index"
1781+checksum = "2b192c782037fadd9cfa75548310488aabdbf3d2da73885b31bd0abd03351285"
1782+dependencies = [
1783+ "either",
1784+]
1785+
1786+[[package]]
1787+name = "itoa"
1788+version = "1.0.18"
1789+source = "registry+https://github.com/rust-lang/crates.io-index"
1790+checksum = "8f42a60cbdf9a97f5d2305f08a87dc4e09308d1276d28c869c684d7777685682"
1791+
1792+[[package]]
1793+name = "jobserver"
1794+version = "0.1.35"
1795+source = "registry+https://github.com/rust-lang/crates.io-index"
1796+checksum = "1c00acbd29eabad4a2392fa0e921c874934dbbf4194312ad20f04a0ed67a3cb3"
1797+dependencies = [
1798+ "getrandom 0.4.3",
1799+ "libc",
1800+]
1801+
1802+[[package]]
1803+name = "js-sys"
1804+version = "0.3.106"
1805+source = "registry+https://github.com/rust-lang/crates.io-index"
1806+checksum = "7883d941dae510fb2d978fc3fe018c71c9e2892fd38854de3e8b92c2e5ad9cc5"
1807+dependencies = [
1808+ "cfg-if",
1809+ "futures-util",
1810+ "wasm-bindgen",
1811+]
1812+
1813+[[package]]
1814+name = "lazy_static"
1815+version = "1.5.1"
1816+source = "registry+https://github.com/rust-lang/crates.io-index"
1817+checksum = "20870f649af7073d53e38067b2a84312175d56ea15217e1b15bc83506ec50afb"
1818+
1819+[[package]]
1820+name = "lazycell"
1821+version = "1.3.0"
1822+source = "registry+https://github.com/rust-lang/crates.io-index"
1823+checksum = "830d08ce1d1d941e6b30645f1a0eb5643013d835ce3779a5fc208261dbe10f55"
1824+
1825+[[package]]
1826+name = "leb128"
1827+version = "0.2.7"
1828+source = "registry+https://github.com/rust-lang/crates.io-index"
1829+checksum = "c83bff1d572d6b9aeef67ddfc8448e4a3737909cb28e81f97c791b9018703e52"
1830+
1831+[[package]]
1832+name = "lettre"
1833+version = "0.11.23"
1834+source = "registry+https://github.com/rust-lang/crates.io-index"
1835+checksum = "f2c646bd5cc763b1087b15493e29a64be6147ba8f19342004fa52048ee596eae"
1836+dependencies = [
1837+ "email-encoding",
1838+ "email_address",
1839+ "fastrand",
1840+ "hostname",
1841+ "httpdate",
1842+ "idna",
1843+ "mime",
1844+ "nom 8.0.0",
1845+ "quoted_printable",
1846+]
1847+
1848+[[package]]
1849+name = "levenshtein_automata"
1850+version = "0.2.1"
1851+source = "registry+https://github.com/rust-lang/crates.io-index"
1852+checksum = "0c2cdeb66e45e9f36bfad5bbdb4d2384e70936afbee843c6f6543f0c551ebb25"
1853+
1854+[[package]]
1855+name = "libc"
1856+version = "0.2.191"
1857+source = "registry+https://github.com/rust-lang/crates.io-index"
1858+checksum = "65cd87c9a6d60536580b316ad985726104730a5151c99845f2490428ef91240a"
1859+
1860+[[package]]
1861+name = "libloading"
1862+version = "0.8.9"
1863+source = "registry+https://github.com/rust-lang/crates.io-index"
1864+checksum = "d7c4b02199fee7c5d21a5ae7d8cfa79a6ef5bb2fc834d6e9058e89c825efdc55"
1865+dependencies = [
1866+ "cfg-if",
1867+ "windows-link",
1868+]
1869+
1870+[[package]]
1871+name = "libm"
1872+version = "0.2.16"
1873+source = "registry+https://github.com/rust-lang/crates.io-index"
1874+checksum = "b6d2cec3eae94f9f509c767b45932f1ada8350c4bdb85af2fcab4a3c14807981"
1875+
1876+[[package]]
1877+name = "libmimalloc-sys"
1878+version = "0.1.49"
1879+source = "registry+https://github.com/rust-lang/crates.io-index"
1880+checksum = "6a45a52f43e1c16f667ccfe4dd8c85b7f7c204fd5e3bf46c5b0db9a5c3c0b8e9"
1881+dependencies = [
1882+ "cc",
1883+]
1884+
1885+[[package]]
1886+name = "linkme"
1887+version = "0.3.37"
1888+source = "registry+https://github.com/rust-lang/crates.io-index"
1889+checksum = "3045e122bd98aef8ec3ad58ce84f0791f64e70163d1a02710af4aa11a4d54cc5"
1890+dependencies = [
1891+ "linkme-impl",
1892+]
1893+
1894+[[package]]
1895+name = "linkme-impl"
1896+version = "0.3.37"
1897+source = "registry+https://github.com/rust-lang/crates.io-index"
1898+checksum = "77060ebe535362c3da75682cd17b0431017b6e7c5661e714fc69a7ad017d1301"
1899+dependencies = [
1900+ "proc-macro2",
1901+ "quote",
1902+ "syn 3.0.9",
1903+]
1904+
1905+[[package]]
1906+name = "linux-raw-sys"
1907+version = "0.4.15"
1908+source = "registry+https://github.com/rust-lang/crates.io-index"
1909+checksum = "d26c52dbd32dccf2d10cac7725f8eae5296885fb5703b261f7d0a0739ec807ab"
1910+
1911+[[package]]
1912+name = "linux-raw-sys"
1913+version = "0.12.1"
1914+source = "registry+https://github.com/rust-lang/crates.io-index"
1915+checksum = "32a66949e030da00e8c7d4434b251670a91556f4144941d37452769c25d58a53"
1916+
1917+[[package]]
1918+name = "litemap"
1919+version = "0.8.3"
1920+source = "registry+https://github.com/rust-lang/crates.io-index"
1921+checksum = "47d9d19d1d6efa0109d2f65ff4c85cddd50bd572e5a00127ab10987290bcefae"
1922+
1923+[[package]]
1924+name = "lock_api"
1925+version = "0.4.14"
1926+source = "registry+https://github.com/rust-lang/crates.io-index"
1927+checksum = "224399e74b87b5f3557511d98dff8b14089b3dadafcab6bb93eab67d3aace965"
1928+dependencies = [
1929+ "scopeguard",
1930+]
1931+
1932+[[package]]
1933+name = "log"
1934+version = "0.4.34"
1935+source = "registry+https://github.com/rust-lang/crates.io-index"
1936+checksum = "f9f8bd3e56ce4dfc153cf470fffbfa98c7620958b312ca5c3a4b8d5181fd13c6"
1937+
1938+[[package]]
1939+name = "loom"
1940+version = "0.7.2"
1941+source = "registry+https://github.com/rust-lang/crates.io-index"
1942+checksum = "419e0dc8046cb947daa77eb95ae174acfbddb7673b4151f56d1eed8e93fbfaca"
1943+dependencies = [
1944+ "cfg-if",
1945+ "generator",
1946+ "scoped-tls",
1947+ "serde",
1948+ "serde_json",
1949+ "tracing",
1950+ "tracing-subscriber",
1951+]
1952+
1953+[[package]]
1954+name = "loro"
1955+version = "1.17.1"
1956+source = "registry+https://github.com/rust-lang/crates.io-index"
1957+checksum = "410c939fe3bee34b8ed61f7aea93201fb136629f685ffa557039c4d9952f9988"
1958+dependencies = [
1959+ "enum-as-inner 0.6.1",
1960+ "generic-btree",
1961+ "loro-common",
1962+ "loro-delta",
1963+ "loro-internal",
1964+ "loro-kv-store",
1965+ "rustc-hash 2.1.3",
1966+ "tracing",
1967+]
1968+
1969+[[package]]
1970+name = "loro-common"
1971+version = "1.17.0"
1972+source = "registry+https://github.com/rust-lang/crates.io-index"
1973+checksum = "bd3f7afbafc4db85aefe9620e7e99fa49c974477563904f226ae96fc9674eade"
1974+dependencies = [
1975+ "arbitrary",
1976+ "enum-as-inner 0.6.1",
1977+ "leb128",
1978+ "loro-rle",
1979+ "nonmax",
1980+ "rustc-hash 2.1.3",
1981+ "serde",
1982+ "serde_columnar",
1983+ "serde_json",
1984+ "thiserror 1.0.69",
1985+]
1986+
1987+[[package]]
1988+name = "loro-delta"
1989+version = "1.13.0"
1990+source = "registry+https://github.com/rust-lang/crates.io-index"
1991+checksum = "96f381e7fb5d4bf5605b4f4a9241f3adf61403ded978d757552004c8302cccbb"
1992+dependencies = [
1993+ "arrayvec",
1994+ "enum-as-inner 0.5.1",
1995+ "generic-btree",
1996+ "heapless 0.8.0",
1997+]
1998+
1999+[[package]]
2000+name = "loro-internal"
Cargo.tomladded+21 -0
@@ -0,0 +1,21 @@
1+[package]
2+name = "project_note"
3+version = "0.1.0"
4+edition = "2024"
5+
6+[dependencies]
7+anyhow = "1.0.104"
8+blake3 = "1.8.7"
9+loro = "1.17.1"
10+tokio = { version = "1.54.1", features = ["full"] }
11+topcoat = { version = "0.11.0", features = ["anyhow", "asset", "discover", "font-fontsource", "fs", "tailwind", "ui", "websocket"] }
12+turso = "0.8.3"
13+uuid = { version = "1.29.0", features = ["v7"] }
14+serde = { version = "1", features = ["derive"] }
15+zip = { version = "9.1.2", default-features = false, features = ["deflate"] }
16+pulldown-cmark = { version = "0.13.5", default-features = false }
17+serde_json = "1.0.154"
18+regex = "1.13.1"
19+
20+[build-dependencies]
21+topcoat = { version = "0.11.0", default-features = false, features = ["tailwind"] }
assets/editor.cssadded+1 -0
@@ -0,0 +1 @@
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}}
assets/editor.jsadded+16 -0
@@ -0,0 +1,16 @@
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.mapadded+37 -0
@@ -0,0 +1,37 @@
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,S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K,GACH,GAAI,CACF,GAAS,MAAM,CAAO,EACtB,MAAO,EAAK,CACZ,QAAQ,MAAM,2BAA4B,CAAG,EAE/C,MACF,QACE,QAAQ,KAAK,oBAAqB,CAAG,GAI3C,SAAS,EAAO,EAAG,CACjB,IAAM,EAAK,IAAI,UAAU,EAAG,EAC5B,EAAG,WAAa,cAChB,GAAS,EAET,EAAG,OAAS,IAAM,CAChB,GAAa,GACb,GAAa,EAAI,EAEjB,GAAgB,GAChB,GAAK,GAAe,GAA2B,aAAa,EAAE,OAAO,CAAC,GAGxE,EAAG,UAAY,CAAC,IAAqB,GAAc,EAAG,IAAI,EAE1D,EAAG,QAAU,IAAM,CACjB,EAAG,MAAM,GAGX,EAAG,QAAU,IAAM,CACjB,GAAI,KAAW,EAAI,GAAS,KAC5B,GAAI,GAAU,OACd,GAAa,EAAK,EAClB,WAAW,GAAS,EAAU,EAC9B,GAAa,KAAK,IAAI,GAAa,EAAG,EAAS,GAMnD,IAAI,GAAW,GACf,OAAO,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.wasmadded+0 -0

Binary file changed

build.rsadded+6 -0
@@ -0,0 +1,6 @@
1+fn main() {
2+ topcoat::tailwind::BuildConfig::new()
3+ .input("styles.css")
4+ .render()
5+ .unwrap();
6+}
components.tomladded+45 -0
@@ -0,0 +1,45 @@
1+# Topcoat UI install state. Managed by `topcoat ui`.
2+version = 1
3+components_dir = "src/components"
4+
5+[theme]
6+name = "neutral"
7+registry = "topcoat"
8+hash = "sha256:5e370e648fef95d78c8b048d99be7f7d79fd82132f8c9cc1ce854d3b73024137"
9+file = "styles.css"
10+
11+[registries.topcoat.components.badge]
12+hash = "sha256:bf27385418a098c0003e7acebd2a94aa0d49795bb6ec6d685428da287037fea9"
13+file = "src/components/badge.rs"
14+
15+[registries.topcoat.components.button]
16+hash = "sha256:1b40f815a96997b28f35b8f385f5849d86ca53ba47fb752a3e795bfc24c3a55d"
17+file = "src/components/button.rs"
18+
19+[registries.topcoat.components.dialog]
20+hash = "sha256:97494bc086959953eff0e1a28ba72be8268cd4c38d83b50259c13788a3931e3c"
21+file = "src/components/dialog.rs"
22+
23+[registries.topcoat.components.dropdown_menu]
24+hash = "sha256:f4144823926ae64c0e5f4f89cce141ea2ecca0e423d8640cf8114e84dccb52c9"
25+file = "src/components/dropdown_menu.rs"
26+
27+[registries.topcoat.components.floating]
28+hash = "sha256:66636f7861a3eb370ee736de1a40aff889ec15e491d7aae57b64ad05e25d5cdd"
29+file = "src/components/floating.rs"
30+
31+[registries.topcoat.components.input]
32+hash = "sha256:c96f34a75f49d24388eb854b864033954060896ae008e76a229ab306299185fd"
33+file = "src/components/input.rs"
34+
35+[registries.topcoat.components.kbd]
36+hash = "sha256:959c37779d7c6ac575088ccb4261f1fcce03ec1f16053bc53e67b2cdffbdd2a3"
37+file = "src/components/kbd.rs"
38+
39+[registries.topcoat.components.separator]
40+hash = "sha256:7ba5a7628128e1811e960884bd56da34f754c1d516230b4442dfbc1cb97e73e9"
41+file = "src/components/separator.rs"
42+
43+[registries.topcoat.components.tooltip]
44+hash = "sha256:a38f87af652c7ceb518f53d83478cd9fa4cf3702ba9f9d0df188d0c28c79fab7"
45+file = "src/components/tooltip.rs"
fonts/OFL.txtadded+93 -0
@@ -0,0 +1,93 @@
1+Copyright 2020-2024 The Atkinson Hyperlegible Next Project Authors (https://github.com/googlefonts/atkinson-hyperlegible-next)
2+
3+This Font Software is licensed under the SIL Open Font License, Version 1.1.
4+This license is copied below, and is also available with a FAQ at:
5+https://openfontlicense.org
6+
7+
8+-----------------------------------------------------------
9+SIL OPEN FONT LICENSE Version 1.1 - 26 February 2007
10+-----------------------------------------------------------
11+
12+PREAMBLE
13+The goals of the Open Font License (OFL) are to stimulate worldwide
14+development of collaborative font projects, to support the font creation
15+efforts of academic and linguistic communities, and to provide a free and
16+open framework in which fonts may be shared and improved in partnership
17+with others.
18+
19+The OFL allows the licensed fonts to be used, studied, modified and
20+redistributed freely as long as they are not sold by themselves. The
21+fonts, including any derivative works, can be bundled, embedded,
22+redistributed and/or sold with any software provided that any reserved
23+names are not used by derivative works. The fonts and derivatives,
24+however, cannot be released under any other type of license. The
25+requirement for fonts to remain under this license does not apply
26+to any document created using the fonts or their derivatives.
27+
28+DEFINITIONS
29+"Font Software" refers to the set of files released by the Copyright
30+Holder(s) under this license and clearly marked as such. This may
31+include source files, build scripts and documentation.
32+
33+"Reserved Font Name" refers to any names specified as such after the
34+copyright statement(s).
35+
36+"Original Version" refers to the collection of Font Software components as
37+distributed by the Copyright Holder(s).
38+
39+"Modified Version" refers to any derivative made by adding to, deleting,
40+or substituting -- in part or in whole -- any of the components of the
41+Original Version, by changing formats or by porting the Font Software to a
42+new environment.
43+
44+"Author" refers to any designer, engineer, programmer, technical
45+writer or other person who contributed to the Font Software.
46+
47+PERMISSION & CONDITIONS
48+Permission is hereby granted, free of charge, to any person obtaining
49+a copy of the Font Software, to use, study, copy, merge, embed, modify,
50+redistribute, and sell modified and unmodified copies of the Font
51+Software, subject to the following conditions:
52+
53+1) Neither the Font Software nor any of its individual components,
54+in Original or Modified Versions, may be sold by itself.
55+
56+2) Original or Modified Versions of the Font Software may be bundled,
57+redistributed and/or sold with any software, provided that each copy
58+contains the above copyright notice and this license. These can be
59+included either as stand-alone text files, human-readable headers or
60+in the appropriate machine-readable metadata fields within text or
61+binary files as long as those fields can be easily viewed by the user.
62+
63+3) No Modified Version of the Font Software may use the Reserved Font
64+Name(s) unless explicit written permission is granted by the corresponding
65+Copyright Holder. This restriction only applies to the primary font name as
66+presented to the users.
67+
68+4) The name(s) of the Copyright Holder(s) or the Author(s) of the Font
69+Software shall not be used to promote, endorse or advertise any
70+Modified Version, except to acknowledge the contribution(s) of the
71+Copyright Holder(s) and the Author(s) or with their explicit written
72+permission.
73+
74+5) The Font Software, modified or unmodified, in part or in whole,
75+must be distributed entirely under this license, and must not be
76+distributed under any other license. The requirement for fonts to
77+remain under this license does not apply to any document created
78+using the Font Software.
79+
80+TERMINATION
81+This license becomes null and void if any of the above conditions are
82+not met.
83+
84+DISCLAIMER
85+THE FONT SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
86+EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO ANY WARRANTIES OF
87+MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT
88+OF COPYRIGHT, PATENT, TRADEMARK, OR OTHER RIGHT. IN NO EVENT SHALL THE
89+COPYRIGHT HOLDER BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
90+INCLUDING ANY GENERAL, SPECIAL, INDIRECT, INCIDENTAL, OR CONSEQUENTIAL
91+DAMAGES, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
92+FROM, OUT OF THE USE OR INABILITY TO USE THE FONT SOFTWARE OR FROM
93+OTHER DEALINGS IN THE FONT SOFTWARE.
fonts/atkinson-hyperlegible-mono-latin-ext-wght.woff2added+0 -0

Binary file changed

fonts/atkinson-hyperlegible-mono-latin-wght.woff2added+0 -0

Binary file changed

fonts/atkinson-hyperlegible-next-latin-ext-wght.woff2added+0 -0

Binary file changed

fonts/atkinson-hyperlegible-next-latin-wght.woff2added+0 -0

Binary file changed

src/app.rsadded+310 -0
@@ -0,0 +1,310 @@
1+use std::sync::Arc;
2+
3+use topcoat::{
4+ Result,
5+ asset::{AssetBundle, RouterBuilderAssetExt},
6+ context::{Cx, app_context},
7+ asset::asset,
8+ cookie::RouterBuilderCookieExt,
9+ font::{Font, RouterBuilderFontExt, font},
10+ router::{
11+ BodyLimit, Router, RouterBuilderDirectoryExt, Slot, layout, module_router, page,
12+ query_params,
13+ request::uri,
14+ },
15+ tailwind,
16+ view::{Unescaped, View, view},
17+};
18+
19+use crate::hub::Hub;
20+use crate::i18n::{self, Msg, t};
21+use crate::store::Store;
22+
23+use self::pane::{ListSpec, Mobile};
24+use topcoat::view::Child;
25+use self::shell::{Section, Shelf, SidebarData, notebook_name, sidebar, title_of, toast_region};
26+use self::palette::palette_dialog;
27+
28+mod lang;
29+mod notebooks;
30+mod notes;
31+mod pane;
32+mod export_all;
33+mod import;
34+mod palette;
35+mod scheme;
36+mod search;
37+mod shell;
38+mod trash;
39+mod unfiled;
40+
41+/// Builds the app router. `assets/` (built editor.js and editor.css) is served at the
42+/// site root; the Tailwind stylesheet comes from the Topcoat asset bundle, which must be
43+/// 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 served
45+/// from the asset bundle. Latin Extended covers Turkish. UI and note body use Next;
46+/// metadata, keycaps and code use Mono.
47+const ATKINSON_NEXT: Font = font! {
48+ "Atkinson Hyperlegible Next",
49+ @font-face {
50+ src: url(asset!("fonts/atkinson-hyperlegible-next-latin-wght.woff2")) format("woff2") tech("variations");
51+ font-weight: 200 800;
52+ font-display: swap;
53+ unicode-range: U+0000-00FF, U+0131, U+0152-0153, U+02BB-02BC, U+02C6, U+02DA, U+02DC, U+0304, U+0308, U+0329, U+2000-206F, U+20AC, U+2122, U+2191, U+2193, U+2212, U+2215, U+FEFF, U+FFFD;
54+ }
55+ @font-face {
56+ src: url(asset!("fonts/atkinson-hyperlegible-next-latin-ext-wght.woff2")) format("woff2") tech("variations");
57+ font-weight: 200 800;
58+ font-display: swap;
59+ unicode-range: U+0100-02BA, U+02BD-02C5, U+02C7-02CC, U+02CE-02D7, U+02DD-02FF, U+0304, U+0308, U+0329, U+1D00-1DBF, U+1E00-1E9F, U+2020, U+20A0-20AB, U+20AD-20C0, U+2113, U+2C60-2C7F, U+A720-A7FF;
60+ }
61+};
62+const ATKINSON_MONO: Font = font! {
63+ "Atkinson Hyperlegible Mono",
64+ @font-face {
65+ src: url(asset!("fonts/atkinson-hyperlegible-mono-latin-wght.woff2")) format("woff2") tech("variations");
66+ font-weight: 200 800;
67+ font-display: swap;
68+ unicode-range: U+0000-00FF, U+0131, U+0152-0153, U+02BB-02BC, U+02C6, U+02DA, U+02DC, U+0304, U+0308, U+0329, U+2000-206F, U+20AC, U+2122, U+2191, U+2193, U+2212, U+2215, U+FEFF, U+FFFD;
69+ }
70+ @font-face {
71+ src: url(asset!("fonts/atkinson-hyperlegible-mono-latin-ext-wght.woff2")) format("woff2") tech("variations");
72+ font-weight: 200 800;
73+ font-display: swap;
74+ unicode-range: U+0100-02BA, U+02BD-02C5, U+02C7-02CC, U+02CE-02D7, U+02DD-02FF, U+0304, U+0308, U+0329, U+1D00-1DBF, U+1E00-1E9F, U+2020, U+20A0-20AB, U+20AD-20C0, U+2113, U+2C60-2C7F, U+A720-A7FF;
75+ }
76+};
77+
78+pub fn router(store: Arc<Store>, hub: Arc<Hub>) -> Router {
79+ module_router!()
80+ .route(export_all::export_zip)
81+ .route(import::import_file)
82+ // Imported files arrive form-encoded, which can grow a file several times over.
83+ .layer(BodyLimit::max(32 * 1024 * 1024).at("/import/file"))
84+ .cookies()
85+ .font(ATKINSON_NEXT)
86+ .font(ATKINSON_MONO)
87+ .public_dir("./assets")
88+ .assets(AssetBundle::load().expect("asset bundle missing: run `topcoat asset bundle`"))
89+ .app_context(store)
90+ .app_context(hub)
91+ .build()
92+}
93+
94+/// Query parameters the shell reads on every page: the search text, the toast key, and
95+/// the note to restore for the toast's Undo button.
96+#[query_params(error = bad_request)]
97+pub struct ShellQuery {
98+ pub q: Option<String>,
99+ pub toast: Option<String>,
100+ pub undo: Option<String>,
101+}
102+
103+/// A note id from a query string, safe to put in a URL path.
104+fn is_note_id(id: &str) -> bool {
105+ !id.is_empty() && id.len() <= 64 && id.chars().all(|c| c.is_ascii_alphanumeric() || c == '-')
106+}
107+
108+/// Shell around every page: head, mobile top bar, sidebar, page content, and toasts.
109+/// The page title and the active sidebar section follow the request path.
110+#[layout]
111+async fn layout(cx: &Cx, slot: Slot<'_>) -> Result<impl View> {
112+ let store = app_context::<Arc<Store>>(cx);
113+ let lang = i18n::lang(cx);
114+ 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)?;
117+ let trash_count = store
118+ .list_trash()
119+ .await
120+ .map_err(topcoat::Error::from_anyhow)?
121+ .len();
122+
123+ let (q, toast_key, undo) = match query_params::<ShellQuery>(cx) {
124+ Ok(query) => (query.q.clone(), query.toast.clone(), query.undo.clone()),
125+ Err(_) => (None, None, None),
126+ };
127+ let query = q.unwrap_or_default();
128+
129+ let uri = uri(cx);
130+ let back = uri
131+ .path_and_query()
132+ .map(|pq| pq.as_str().to_owned())
133+ .unwrap_or_else(|| "/".to_owned());
134+ let path = uri.path().to_owned();
135+ let segments: Vec<&str> = path.split('/').filter(|s| !s.is_empty()).collect();
136+
137+ // The section highlighted in the sidebar, the notebook a new note goes to, and the
138+ // name of the page (for the title).
139+ let mut current_notebook = String::new();
140+ let (section, page_name) = match segments.as_slice() {
141+ [] => (Section::All, t(lang, Msg::AllNotes).to_owned()),
142+ ["unfiled"] => (Section::Unfiled, t(lang, Msg::Unfiled).to_owned()),
143+ ["trash"] => (Section::Trash, t(lang, Msg::Trash).to_owned()),
144+ // An empty search shows every note, so it is "All notes".
145+ ["search", ..] if query.trim().is_empty() => (Section::All, t(lang, Msg::AllNotes).to_owned()),
146+ ["search", ..] => (Section::Other, t(lang, Msg::Search).to_owned()),
147+ ["notebooks", id, ..] => {
148+ let name = notebook_name(&notebooks, Some(id));
149+ if name.is_some() {
150+ current_notebook = (*id).to_owned();
151+ }
152+ (Section::Notebook((*id).to_owned()), name.unwrap_or_default())
153+ }
154+ ["notes", id, ..] => match store.get_note(id).await.map_err(topcoat::Error::from_anyhow)? {
155+ Some(meta) => {
156+ current_notebook = meta.notebook_id.clone().unwrap_or_default();
157+ // The same context as the list pane: trash, the note's notebook, or unfiled.
158+ let section = if meta.trashed_at.is_some() {
159+ Section::Trash
160+ } else if let Some(nb) = &meta.notebook_id {
161+ Section::Notebook(nb.clone())
162+ } else {
163+ Section::Unfiled
164+ };
165+ (section, title_of(lang, &meta.title))
166+ }
167+ None => (Section::All, String::new()),
168+ },
169+ _ => (Section::Other, String::new()),
170+ };
171+ let title = if page_name.is_empty() {
172+ t(lang, Msg::AppName).to_owned()
173+ } else {
174+ format!("{page_name} \u{b7} {}", t(lang, Msg::AppName))
175+ };
176+
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> = notebooks
180+ .iter()
181+ .map(|nb| Shelf {
182+ id: nb.id.clone(),
183+ name: nb.name.clone(),
184+ count: notes
185+ .iter()
186+ .filter(|n| n.notebook_id.as_deref() == Some(nb.id.as_str()))
187+ .count(),
188+ })
189+ .collect();
190+
191+ let toast_message = match toast_key.as_deref() {
192+ Some("trashed") => Some(t(lang, Msg::ToastTrashed)),
193+ Some("restored") => Some(t(lang, Msg::ToastRestored)),
194+ Some("notebook_created") => Some(t(lang, Msg::ToastNotebookCreated)),
195+ Some("notebook_deleted") => Some(t(lang, Msg::ToastNotebookDeleted)),
196+ Some("moved") => Some(t(lang, Msg::ToastMoved)),
197+ Some("version-restored") => Some(t(lang, Msg::ToastVersionRestored)),
198+ _ => None,
199+ };
200+ let undo_id = match (toast_key.as_deref(), undo) {
201+ (Some("trashed"), Some(id)) if is_note_id(&id) => Some(id),
202+ _ => None,
203+ };
204+
205+ let sidebar_data = SidebarData {
206+ all: all_count,
207+ unfiled: unfiled_count,
208+ trash: trash_count,
209+ notebooks: shelves,
210+ section,
211+ current_notebook,
212+ query,
213+ back,
214+ scheme,
215+ };
216+ let app_name = t(lang, Msg::AppName);
217+ let skip = t(lang, Msg::SkipToContent);
218+ let open_menu = t(lang, Msg::OpenMenu);
219+ let show_sidebar = t(lang, Msg::ShowSidebar);
220+
221+ Ok(view! {
222+ <!DOCTYPE html>
223+ <html lang=(lang.code()) data-scheme=(scheme.id())>
224+ <head>
225+ <meta charset="utf-8">
226+ <meta name="viewport" content="width=device-width, initial-scale=1, viewport-fit=cover">
227+ <title>(title)</title>
228+ <script>(Unescaped::new_unchecked(shell::THEME_SCRIPT))</script>
229+ <style>(Unescaped::new_unchecked(shell::SHELL_STYLE))</style>
230+ topcoat::font::link(font: ATKINSON_NEXT)
231+ topcoat::font::link(font: ATKINSON_MONO)
232+ <link rel="stylesheet" href=(tailwind::stylesheet!())>
233+ <link rel="stylesheet" href="/editor.css">
234+ </head>
235+ <body class="bg-background text-foreground antialiased">
236+ <a
237+ href="#main"
238+ class="sr-only focus:not-sr-only focus:fixed focus:top-2 focus:left-2 focus:z-[60] focus:rounded-control focus:bg-popover focus:px-3 focus:py-2 focus:text-sm focus:text-popover-foreground focus:shadow-float"
239+ >(skip)</a>
240+ <div class="flex h-dvh flex-col overflow-hidden lg:flex-row">
241+ <header class="flex h-12 shrink-0 items-center gap-2 border-b border-border bg-sidebar pt-[env(safe-area-inset-top)] pr-[max(0.5rem,env(safe-area-inset-right))] pl-[max(0.5rem,env(safe-area-inset-left))] lg:hidden">
242+ <button
243+ id="drawer-open"
244+ type="button"
245+ aria-controls="sidebar"
246+ aria-expanded="false"
247+ aria-label=(open_menu)
248+ class="inline-flex size-10 items-center justify-center rounded-control text-foreground transition-colors hover:bg-foreground/5"
249+ >
250+ <svg class="size-5" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true">
251+ <path d="M4 6h16M4 12h16M4 18h16"></path>
252+ </svg>
253+ </button>
254+ <a href="/" class="text-base font-semibold tracking-tight">(app_name)</a>
255+ </header>
256+ sidebar(lang: lang, data: sidebar_data)
257+ <div id="drawer-backdrop" data-open="false" aria-hidden="true"></div>
258+ <button
259+ id="sidebar-expand"
260+ type="button"
261+ aria-controls="sidebar"
262+ aria-label=(show_sidebar)
263+ class="fixed top-3 left-3 z-20 size-8 items-center justify-center rounded-control border border-border bg-card text-foreground transition-colors hover:bg-foreground/5"
264+ >
265+ <svg class="size-4" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true">
266+ <rect x="3" y="3" width="18" height="18" rx="2"></rect>
267+ <path d="M9 3v18"></path>
268+ </svg>
269+ </button>
270+ <main id="main" tabindex="-1" class="flex min-h-0 min-w-0 flex-1 flex-col overflow-y-auto focus:outline-none">
271+ (slot)
272+ </main>
273+ </div>
274+ toast_region(lang: lang, message: toast_message, undo: undo_id)
275+ palette_dialog(lang: lang)
276+ <script>(Unescaped::new_unchecked(shell::SHELL_SCRIPT))</script>
277+ </body>
278+ </html>
279+ })
280+}
281+
282+/// GET /: all notes, most recently updated first, beside the detail pane.
283+#[page]
284+async fn index(cx: &Cx) -> Result<impl View> {
285+ all_notes(cx).await
286+}
287+
288+/// 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> {
290+ 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)?;
293+ let previews = store.previews().await.map_err(topcoat::Error::from_anyhow)?;
294+ let lang = i18n::lang(cx);
295+ let spec = ListSpec {
296+ title: t(lang, Msg::AllNotes).to_owned(),
297+ heading: true,
298+ count: notes.len(),
299+ notebook_id: String::new(),
300+ groups: pane::groups(lang, &notes, &notebooks, &previews, None, true),
301+ empty: t(lang, Msg::NoNotesYet),
302+ };
303+ let list = pane::list_pane(cx, lang, spec, Child::new(()));
304+ Ok(pane::split(
305+ cx,
306+ Mobile::List,
307+ Child::new(list),
308+ Child::new(pane::empty_detail(cx, lang)),
309+ ))
310+}
src/app/export_all.rsadded+156 -0
@@ -0,0 +1,156 @@
1+//! GET /export.zip: every note outside the trash, as markdown files in one zip.
2+//! Notes in a notebook go into a folder named after it; unfiled notes sit at the root.
3+
4+use std::collections::{HashMap, HashSet};
5+use std::io::{Cursor, Write};
6+use std::sync::Arc;
7+use std::time::{SystemTime, UNIX_EPOCH};
8+
9+use topcoat::{
10+ Result,
11+ context::{Cx, app_context},
12+ router::{header, route},
13+};
14+use zip::{CompressionMethod, ZipWriter, write::SimpleFileOptions};
15+
16+use crate::export;
17+use crate::hub::load_doc;
18+use crate::store::Store;
19+
20+const MAX_NAME_CHARS: usize = 100;
21+
22+/// GET /export.zip: a zip of the live markdown of every non-trashed note.
23+#[route(GET "/export.zip")]
24+pub async fn export_zip(cx: &Cx) -> Result<([(&'static str, String); 2], Vec<u8>)> {
25+ let store = app_context::<Arc<Store>>(cx);
26+ let notes = store.list_notes().await.map_err(topcoat::Error::from_anyhow)?;
27+ let notebooks = store.list_notebooks().await.map_err(topcoat::Error::from_anyhow)?;
28+ let titles: HashMap<String, String> = notes
29+ .iter()
30+ .map(|note| (note.id.clone(), note.title.clone()))
31+ .collect();
32+
33+ let mut folder_names: HashMap<String, String> = HashMap::new();
34+ let mut folder_taken = HashSet::new();
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();
71+ let disposition = format!("attachment; filename=\"notes-{year:04}-{month:02}-{day:02}.zip\"");
72+ Ok((
73+ [
74+ (header::CONTENT_TYPE.as_str(), "application/zip".to_owned()),
75+ (header::CONTENT_DISPOSITION.as_str(), disposition),
76+ ],
77+ bytes,
78+ ))
79+}
80+
81+/// Titles of the notes outside the trash, by note id: what wiki-style links resolve to.
82+pub(crate) async fn title_map(store: &Store) -> anyhow::Result<HashMap<String, String>> {
83+ Ok(store
84+ .list_notes()
85+ .await?
86+ .into_iter()
87+ .map(|note| (note.id, note.title))
88+ .collect())
89+}
90+
91+/// Writes every `(path, markdown)` pair into a deflate-compressed zip held in memory.
92+fn build_zip(entries: Vec<(String, String)>) -> anyhow::Result<Vec<u8>> {
93+ let options = SimpleFileOptions::default().compression_method(CompressionMethod::Deflated);
94+ let mut zip = ZipWriter::new(Cursor::new(Vec::new()));
95+ for (path, markdown) in entries {
96+ zip.start_file(path, options)?;
97+ zip.write_all(markdown.as_bytes())?;
98+ }
99+ Ok(zip.finish()?.into_inner())
100+}
101+
102+/// Makes a file or folder name safe on common systems: reserved characters and control
103+/// characters become "-", edge spaces and dots are trimmed, and the length is capped.
104+pub(crate) fn sanitize(name: &str) -> String {
105+ let replaced: String = name
106+ .chars()
107+ .map(|c| match c {
108+ '/' | '\\' | ':' | '*' | '?' | '"' | '<' | '>' | '|' => '-',
109+ c if c.is_control() => '-',
110+ c => c,
111+ })
112+ .collect();
113+ let capped: String = replaced
114+ .trim_matches(|c: char| c == ' ' || c == '.')
115+ .chars()
116+ .take(MAX_NAME_CHARS)
117+ .collect();
118+ let trimmed = capped.trim_matches(|c: char| c == ' ' || c == '.');
119+ if trimmed.is_empty() {
120+ "Untitled".to_owned()
121+ } else {
122+ trimmed.to_owned()
123+ }
124+}
125+
126+/// Returns `base` if no entry of `dir` uses it yet, else `base (2)`, `base (3)`, and so on.
127+/// The chosen name is recorded in `taken` under the key `dir/name`.
128+fn unique(taken: &mut HashSet<String>, dir: &str, base: &str) -> String {
129+ let mut name = base.to_owned();
130+ let mut n = 2;
131+ while taken.contains(&format!("{dir}/{name}")) {
132+ name = format!("{base} ({n})");
133+ n += 1;
134+ }
135+ taken.insert(format!("{dir}/{name}"));
136+ name
137+}
138+
139+/// The current UTC date as (year, month, day), from the Unix clock.
140+fn utc_date() -> (i64, i64, i64) {
141+ let days = SystemTime::now()
142+ .duration_since(UNIX_EPOCH)
143+ .map(|d| d.as_secs() as i64 / 86_400)
144+ .unwrap_or(0);
145+ // Civil date from days since 1970-01-01 (Howard Hinnant's algorithm).
146+ let z = days + 719_468;
147+ let era = z.div_euclid(146_097);
148+ let doe = z - era * 146_097;
149+ let yoe = (doe - doe / 1_460 + doe / 36_524 - doe / 146_096) / 365;
150+ let doy = doe - (365 * yoe + yoe / 4 - yoe / 100);
151+ let mp = (5 * doy + 2) / 153;
152+ let day = doy - (153 * mp + 2) / 5 + 1;
153+ let month = if mp < 10 { mp + 3 } else { mp - 9 };
154+ let year = yoe + era * 400 + if month <= 2 { 1 } else { 0 };
155+ (year, month, day)
156+}
src/app/import.rsadded+270 -0
@@ -0,0 +1,270 @@
1+//! Markdown import: POST /import/file creates one note from one file, and GET /import is
2+//! the page that picks files or a folder and sends them one at a time.
3+//!
4+//! The browser sends each path with the selected root folder already stripped. A path
5+//! 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.
7+
8+use std::path::Path;
9+use std::sync::Arc;
10+
11+use serde::Deserialize;
12+use topcoat::{
13+ Result,
14+ context::{Cx, app_context},
15+ router::{content::Form, error::bad_request, page, route},
16+ view::{Unescaped, View, view},
17+};
18+
19+use crate::app::export_all::sanitize;
20+use crate::components::button::{ButtonSize, ButtonVariant, button_variants};
21+use crate::export;
22+use crate::i18n::{self, Msg, t};
23+use crate::import::{markdown_to_doc, markdown_to_update};
24+use crate::store::Store;
25+
26+#[derive(Deserialize)]
27+struct ImportForm {
28+ /// Path of the file within the chosen folder, or just the file name.
29+ path: String,
30+ /// The file's contents.
31+ text: String,
32+}
33+
34+/// POST /import/file: creates a note from one markdown file and answers with its id.
35+#[route(POST "/import/file")]
36+pub async fn import_file(cx: &Cx, Form(input): Form<ImportForm>) -> Result<String> {
37+ let store = app_context::<Arc<Store>>(cx);
38+
39+ let path = input.path.replace('\\', "/");
40+ let segments: Vec<&str> = path
41+ .split('/')
42+ .map(str::trim)
43+ .filter(|s| !s.is_empty() && *s != "." && *s != "..")
44+ .collect();
45+ let Some(file_name) = segments.last().copied() else {
46+ return Err(bad_request("missing file name").into());
47+ };
48+ let file = Path::new(file_name);
49+ let is_markdown = file
50+ .extension()
51+ .and_then(|e| e.to_str())
52+ .is_some_and(|e| matches!(e.to_ascii_lowercase().as_str(), "md" | "markdown" | "txt"));
53+ if !is_markdown {
54+ return Err(bad_request("only .md, .markdown and .txt files can be imported").into());
55+ }
56+ let stem = file
57+ .file_stem()
58+ .and_then(|s| s.to_str())
59+ .unwrap_or(file_name)
60+ .to_owned();
61+
62+ // The first folder below the selected root is the notebook. Files directly in the
63+ // root are unfiled.
64+ let notebook_id = match segments.len() {
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+
86+ // 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.
88+ // Front matter goes first, or it would no longer lead the file once a heading is
89+ // put in front of it.
90+ let text = crate::import::strip_front_matter(&input.text);
91+ let markdown = if export::to_markdown(
92+ &markdown_to_doc(text).map_err(topcoat::Error::from_anyhow)?,
93+ )
94+ .starts_with('#')
95+ {
96+ text.to_owned()
97+ } else {
98+ format!("# {stem}\n\n{text}")
99+ };
100+ let doc = markdown_to_doc(&markdown).map_err(topcoat::Error::from_anyhow)?;
101+ let title = export::title(&doc);
102+ let body = export::to_markdown(&doc);
103+ let update = markdown_to_update(&markdown).map_err(topcoat::Error::from_anyhow)?;
104+
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+ store
122+ .set_links(&note.id, &export::note_links(&doc))
123+ .await
124+ .map_err(topcoat::Error::from_anyhow)?;
125+ Ok(note.id)
126+}
127+
128+/// GET /import: picks markdown files or a folder and imports them one by one.
129+#[page]
130+async fn import_page(cx: &Cx) -> Result<impl View> {
131+ let lang = i18n::lang(cx);
132+ let title = t(lang, Msg::Import);
133+ let help = t(lang, Msg::ImportHelp);
134+ let choose_files = t(lang, Msg::ChooseFiles);
135+ let choose_folder = t(lang, Msg::ChooseFolder);
136+ let progress = t(lang, Msg::ImportProgress);
137+ let done_one = t(lang, Msg::ImportDoneOne);
138+ let done_other = t(lang, Msg::ImportDoneMany);
139+ let failed = t(lang, Msg::ImportFailed);
140+ let none = t(lang, Msg::ImportNoFiles);
141+ let go_to_notes = t(lang, Msg::ImportGoToNotes);
142+
143+ Ok(view! {
144+ <div class="mx-auto flex w-full max-w-3xl flex-col">
145+ <header class="sticky top-0 z-10 flex flex-wrap items-start justify-between gap-4 border-b border-border bg-background px-4 py-5 lg:px-8">
146+ <div class="min-w-0">
147+ <h1 class="text-xl font-semibold tracking-tight">(title)</h1>
148+ <p class="mt-1 text-sm text-muted-foreground">(help)</p>
149+ </div>
150+ </header>
151+ <div
152+ id="import"
153+ class="flex flex-col gap-4 px-4 py-6 lg:px-8"
154+ data-progress=(progress)
155+ data-done-one=(done_one)
156+ data-done-other=(done_other)
157+ data-failed=(failed)
158+ data-none=(none)
159+ >
160+ <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+ <input id="import-files" type="file" multiple=(true) accept=".md,.markdown,.txt" class="sr-only">
163+ <span class=(button_variants(ButtonVariant::Outline, ButtonSize::Md))>(choose_files)</span>
164+ </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+ <input id="import-folder" type="file" webkitdirectory=(true) class="sr-only">
167+ <span class=(button_variants(ButtonVariant::Outline, ButtonSize::Md))>(choose_folder)</span>
168+ </label>
169+ </div>
170+ <p id="import-status" aria-live="polite" class="font-mono text-xs tabular-nums text-muted-foreground"></p>
171+ <p id="import-link" class="hidden">
172+ <a href="/" class="text-sm font-medium underline underline-offset-4">(go_to_notes)</a>
173+ </p>
174+ </div>
175+ </div>
176+ <script>(Unescaped::new_unchecked(IMPORT_SCRIPT))</script>
177+ })
178+}
179+
180+/// Collects the chosen files, keeps markdown and text, and posts them one at a time so
181+/// that a notebook created by one file is found by the next. The status line and the
182+/// done text come from the data attributes on #import, so the script has no strings.
183+pub const IMPORT_SCRIPT: &str = r#"
184+(function () {
185+ var root = document.getElementById('import');
186+ if (!root) return;
187+ var status = document.getElementById('import-status');
188+ var link = document.getElementById('import-link');
189+ var files = document.getElementById('import-files');
190+ var folder = document.getElementById('import-folder');
191+ var supported = /\.(md|markdown|txt)$/i;
192+ var busy = false;
193+
194+ function fill(template, values) {
195+ return Object.keys(values).reduce(function (text, key) {
196+ return text.split('{' + key + '}').join(String(values[key]));
197+ }, template);
198+ }
199+
200+ function run(items) {
201+ var total = items.length;
202+ var imported = 0;
203+ var failed = 0;
204+ var index = 0;
205+ busy = true;
206+ link.classList.add('hidden');
207+
208+ function finish() {
209+ var text = fill(imported === 1 ? root.dataset.doneOne : root.dataset.doneOther, { n: imported });
210+ if (failed > 0) text += ' ' + fill(root.dataset.failed, { m: failed });
211+ status.textContent = text;
212+ link.classList.remove('hidden');
213+ busy = false;
214+ }
215+
216+ function next() {
217+ if (index >= total) return finish();
218+ status.textContent = fill(root.dataset.progress, { done: index + 1, total: total });
219+ var item = items[index++];
220+ item.file.text()
221+ .then(function (text) {
222+ var body = new URLSearchParams();
223+ body.set('path', item.path);
224+ body.set('text', text);
225+ return fetch('/import/file', {
226+ method: 'POST',
227+ headers: { 'Content-Type': 'application/x-www-form-urlencoded' },
228+ body: body,
229+ credentials: 'same-origin'
230+ });
231+ })
232+ .then(function (res) {
233+ if (res.ok) imported++; else failed++;
234+ })
235+ .catch(function () { failed++; })
236+ .then(next);
237+ }
238+
239+ next();
240+ }
241+
242+ function onChange(input, fromFolder) {
243+ input.addEventListener('change', function () {
244+ if (busy) return;
245+ var picked = Array.prototype.slice.call(input.files || []);
246+ input.value = '';
247+ var items = [];
248+ picked.forEach(function (file) {
249+ if (!supported.test(file.name)) return;
250+ var path = file.name;
251+ if (fromFolder) {
252+ var rel = file.webkitRelativePath || file.name;
253+ var slash = rel.indexOf('/');
254+ path = slash >= 0 ? rel.slice(slash + 1) : rel;
255+ }
256+ items.push({ file: file, path: path });
257+ });
258+ if (items.length === 0) {
259+ status.textContent = root.dataset.none;
260+ link.classList.add('hidden');
261+ return;
262+ }
263+ run(items);
264+ });
265+ }
266+
267+ onChange(files, false);
268+ onChange(folder, true);
269+})();
270+"#;
src/app/lang.rsadded+41 -0
@@ -0,0 +1,41 @@
1+use serde::Deserialize;
2+use topcoat::{
3+ Result,
4+ context::Cx,
5+ cookie::{Cookies, cookies},
6+ router::{
7+ content::Form,
8+ error::{SeeOther, bad_request, see_other},
9+ route,
10+ },
11+};
12+
13+use crate::i18n::{Lang, lang_cookie};
14+
15+#[derive(Deserialize)]
16+struct LangForm {
17+ lang: String,
18+ /// Where to return to. Only a relative path on this site is accepted.
19+ #[serde(default)]
20+ back: String,
21+}
22+
23+/// Accepts "/..." paths on this site. Rejects "//host" and "/\host", which browsers read as
24+/// other hosts, and anything with control characters.
25+pub(super) fn safe_back(back: &str) -> &str {
26+ let ok = back.starts_with('/')
27+ && !back.starts_with("//")
28+ && !back.starts_with("/\\")
29+ && !back.chars().any(|c| c.is_control());
30+ if ok { back } else { "/" }
31+}
32+
33+/// POST /lang: stores the chosen language in a cookie and returns to the page it was
34+/// chosen on.
35+#[route(POST)]
36+async fn set_lang(cx: &Cx, Form(form): Form<LangForm>) -> Result<SeeOther> {
37+ let lang = Lang::from_code(form.lang.trim())
38+ .ok_or_else(|| bad_request("unsupported language"))?;
39+ cookies(cx).add(lang_cookie(lang));
40+ Ok(see_other(safe_back(&form.back)))
41+}
src/app/notebooks.rsadded+42 -0
@@ -0,0 +1,42 @@
1+use std::sync::Arc;
2+
3+use serde::Deserialize;
4+use topcoat::{
5+ Result,
6+ context::{Cx, app_context},
7+ router::{
8+ content::Form,
9+ error::{SeeOther, bad_request, see_other},
10+ route,
11+ },
12+};
13+
14+use crate::store::Store;
15+
16+mod notebook_id;
17+
18+#[derive(Deserialize)]
19+struct NameForm {
20+ name: String,
21+}
22+
23+/// Trims a notebook name and rejects blank names.
24+fn clean_name(raw: &str) -> Result<String> {
25+ let name = raw.trim();
26+ if name.is_empty() {
27+ return Err(bad_request("notebook name is required").into());
28+ }
29+ Ok(name.chars().take(120).collect())
30+}
31+
32+/// POST /notebooks: creates a notebook and opens it.
33+#[route(POST)]
34+async fn create_notebook(cx: &Cx, Form(form): Form<NameForm>) -> Result<SeeOther> {
35+ let store = app_context::<Arc<Store>>(cx);
36+ let name = clean_name(&form.name)?;
37+ let notebook = store
38+ .create_notebook(&name)
39+ .await
40+ .map_err(topcoat::Error::from_anyhow)?;
41+ Ok(see_other(format!("/notebooks/{}?toast=notebook_created", notebook.id)))
42+}
src/app/notebooks/notebook_id.rsadded+201 -0
@@ -0,0 +1,201 @@
1+use std::sync::Arc;
2+
3+use topcoat::{
4+ Result,
5+ context::{Cx, app_context},
6+ router::{
7+ content::Form,
8+ error::{RouterErrorExt, SeeOther, see_other},
9+ module_param, page, path_param, route,
10+ },
11+ view::{Child, View, attributes, view},
12+};
13+
14+use crate::app::pane::{self, Mobile};
15+use crate::components::button::{ButtonSize, ButtonVariant, button, button_variants};
16+use crate::components::dialog::{
17+ dialog, dialog_content, dialog_description, dialog_footer, dialog_header, dialog_title,
18+};
19+use crate::components::dropdown_menu::{
20+ dropdown_menu, dropdown_menu_content, dropdown_menu_item, dropdown_menu_separator,
21+ dropdown_menu_trigger,
22+};
23+use crate::components::floating::FloatingAlign;
24+use crate::components::input::input;
25+use crate::i18n::{self, Msg, t};
26+use crate::store::Store;
27+
28+use super::{NameForm, clean_name};
29+
30+module_param!(notebook_id);
31+
32+/// GET /notebooks/{notebook_id}: the notes in one notebook beside its list, with a menu
33+/// to rename or delete the notebook.
34+#[page]
35+async fn notebook(cx: &Cx) -> Result<impl View> {
36+ let store = app_context::<Arc<Store>>(cx);
37+ let id = path_param::<NotebookId>(cx).to_owned();
38+ let nb = store
39+ .get_notebook(&id)
40+ .await
41+ .map_err(topcoat::Error::from_anyhow)?
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)?;
45+ let previews = store.previews().await.map_err(topcoat::Error::from_anyhow)?;
46+ let in_nb: Vec<_> = notes
47+ .into_iter()
48+ .filter(|n| n.notebook_id.as_deref() == Some(id.as_str()))
49+ .collect();
50+ let lang = i18n::lang(cx);
51+ let groups = pane::groups(lang, &in_nb, &notebooks, &previews, None, false);
52+ let spec = pane::ListSpec {
53+ title: nb.name.clone(),
54+ heading: true,
55+ count: in_nb.len(),
56+ notebook_id: id.clone(),
57+ groups,
58+ empty: t(lang, Msg::EmptyNotebook),
59+ };
60+
61+ let rename_action = format!("/notebooks/{id}/rename");
62+ let delete_action = format!("/notebooks/{id}/delete");
63+ let options = t(lang, Msg::NotebookOptions);
64+ let rename_label = t(lang, Msg::RenameNotebook);
65+ let rename_short = t(lang, Msg::Rename);
66+ let delete_label = t(lang, Msg::DeleteNotebook);
67+ let delete_title = t(lang, Msg::DeleteNotebookTitle);
68+ let delete_body = t(lang, Msg::DeleteNotebookBody);
69+ let cancel = t(lang, Msg::Cancel);
70+ let name_label = t(lang, Msg::NewNotebookLabel);
71+
72+ let actions = view! {
73+ dropdown_menu(
74+ dropdown_menu_trigger(
75+ target: "notebook-menu",
76+ attrs: attributes! {
77+ class=(button_variants(ButtonVariant::Ghost, ButtonSize::Icon))
78+ aria-label=(options)
79+ },
80+ <svg class="size-4" viewBox="0 0 24 24" fill="currentColor" aria-hidden="true">
81+ <circle cx="5" cy="12" r="1.75"></circle>
82+ <circle cx="12" cy="12" r="1.75"></circle>
83+ <circle cx="19" cy="12" r="1.75"></circle>
84+ </svg>
85+ )
86+ dropdown_menu_content(
87+ id: "notebook-menu",
88+ align: FloatingAlign::End,
89+ dropdown_menu_item(
90+ close: Some("notebook-menu"),
91+ attrs: attributes! { onclick="document.getElementById('rename-notebook').showModal()" },
92+ (rename_label)
93+ )
94+ dropdown_menu_separator()
95+ dropdown_menu_item(
96+ close: Some("notebook-menu"),
97+ attrs: attributes! {
98+ class="text-destructive"
99+ onclick="document.getElementById('delete-notebook').showModal()"
100+ },
101+ (delete_label)
102+ )
103+ )
104+ )
105+ };
106+ let list = pane::list_pane(cx, lang, spec, Child::new(actions));
107+ let content = Child::new(pane::split(
108+ cx,
109+ Mobile::List,
110+ Child::new(list),
111+ Child::new(pane::empty_detail(cx, lang)),
112+ ));
113+
114+ Ok(view! {
115+ (content)
116+ dialog(
117+ open: false,
118+ attrs: attributes! { id="rename-notebook" aria-labelledby="rename-notebook-title" },
119+ dialog_content(
120+ <form method="post" action=(rename_action) class="flex flex-col gap-4">
121+ dialog_header(
122+ dialog_title(attrs: attributes! { id="rename-notebook-title" }, (rename_label))
123+ )
124+ input(attrs: attributes! {
125+ type="text"
126+ name="name"
127+ value=(nb.name.clone())
128+ maxlength="120"
129+ required=(true)
130+ autocomplete="off"
131+ aria-label=(name_label)
132+ class="w-full"
133+ })
134+ dialog_footer(
135+ button(
136+ variant: ButtonVariant::Ghost,
137+ attrs: attributes! { type="submit" formmethod="dialog" },
138+ (cancel)
139+ )
140+ button(
141+ variant: ButtonVariant::Primary,
142+ attrs: attributes! { type="submit" },
143+ (rename_short)
144+ )
145+ )
146+ </form>
147+ )
148+ )
149+ dialog(
150+ open: false,
151+ attrs: attributes! { id="delete-notebook" aria-labelledby="delete-notebook-title" aria-describedby="delete-notebook-body" },
152+ dialog_content(
153+ <form method="post" action=(delete_action) class="flex flex-col gap-4">
154+ dialog_header(
155+ dialog_title(attrs: attributes! { id="delete-notebook-title" }, (delete_title))
156+ dialog_description(attrs: attributes! { id="delete-notebook-body" }, (delete_body))
157+ )
158+ dialog_footer(
159+ button(
160+ variant: ButtonVariant::Outline,
161+ attrs: attributes! { type="submit" formmethod="dialog" autofocus=(true) },
162+ (cancel)
163+ )
164+ button(
165+ variant: ButtonVariant::Destructive,
166+ attrs: attributes! { type="submit" },
167+ (delete_label)
168+ )
169+ )
170+ </form>
171+ )
172+ )
173+ })
174+}
175+
176+/// POST /notebooks/{notebook_id}/rename
177+#[route(POST "./rename")]
178+async fn rename_notebook(cx: &Cx, Form(form): Form<NameForm>) -> Result<SeeOther> {
179+ let store = app_context::<Arc<Store>>(cx);
180+ let id = path_param::<NotebookId>(cx).to_owned();
181+ store.get_notebook(&id).await.map_err(topcoat::Error::from_anyhow)?.ok_or_not_found()?;
182+ let name = clean_name(&form.name)?;
183+ store
184+ .rename_notebook(&id, &name)
185+ .await
186+ .map_err(topcoat::Error::from_anyhow)?;
187+ Ok(see_other(format!("/notebooks/{id}")))
188+}
189+
190+/// POST /notebooks/{notebook_id}/delete: its notes become unfiled.
191+#[route(POST "./delete")]
192+async fn delete_notebook(cx: &Cx) -> Result<SeeOther> {
193+ let store = app_context::<Arc<Store>>(cx);
194+ let id = path_param::<NotebookId>(cx).to_owned();
195+ store.get_notebook(&id).await.map_err(topcoat::Error::from_anyhow)?.ok_or_not_found()?;
196+ store
197+ .delete_notebook(&id)
198+ .await
199+ .map_err(topcoat::Error::from_anyhow)?;
200+ Ok(see_other("/?toast=notebook_deleted"))
201+}
src/app/notes.rsadded+212 -0
@@ -0,0 +1,212 @@
1+use std::sync::Arc;
2+
3+use serde::{Deserialize, Serialize};
4+use topcoat::{
5+ Result,
6+ context::{Cx, app_context},
7+ router::{
8+ content::Form,
9+ error::{SeeOther, bad_request, see_other},
10+ header, page, path_param, query_params, route,
11+ },
12+ view::{View, attributes, view},
13+};
14+
15+use crate::components::button::{ButtonSize, ButtonVariant, button};
16+use crate::export;
17+use crate::i18n::{self, Msg, t};
18+use crate::import::{markdown_to_doc, markdown_to_update};
19+use crate::store::{Store, title_key};
20+
21+mod note_id;
22+
23+path_param!(title);
24+
25+#[derive(Deserialize)]
26+struct NewNote {
27+ /// Empty or absent when the note is created outside any notebook.
28+ #[serde(default)]
29+ notebook_id: String,
30+}
31+
32+/// POST /notes: creates an empty note (in the notebook named by the form, if any)
33+/// and redirects to the editor.
34+#[route(POST)]
35+async fn create_note(cx: &Cx, Form(input): Form<NewNote>) -> Result<SeeOther> {
36+ let store = app_context::<Arc<Store>>(cx);
37+ let notebook_id = input.notebook_id.trim();
38+ let notebook_id = if notebook_id.is_empty() {
39+ None
40+ } else {
41+ let exists = store
42+ .get_notebook(notebook_id)
43+ .await
44+ .map_err(topcoat::Error::from_anyhow)?
45+ .is_some();
46+ if !exists {
47+ return Err(bad_request("unknown notebook").into());
48+ }
49+ Some(notebook_id)
50+ };
51+ let note = store
52+ .create_note(notebook_id)
53+ .await
54+ .map_err(topcoat::Error::from_anyhow)?;
55+ let init = crate::hub::initial_note_update().map_err(topcoat::Error::from_anyhow)?;
56+ store
57+ .append_update(&note.id, &init)
58+ .await
59+ .map_err(topcoat::Error::from_anyhow)?;
60+ Ok(see_other(format!("/notes/{}", note.id)))
61+}
62+
63+#[query_params(error = bad_request)]
64+pub struct TitlesQuery {
65+ pub q: Option<String>,
66+}
67+
68+#[derive(Serialize)]
69+struct TitleHit {
70+ id: String,
71+ title: String,
72+}
73+
74+/// Most notes the link picker is answered with.
75+const TITLE_HITS: usize = 8;
76+/// Most title matches read before the prefix matches are put first.
77+const TITLE_SEARCH_LIMIT: usize = 10_000;
78+
79+/// GET /notes/titles.json?q=...: up to 8 notes outside the trash whose title contains `q`
80+/// (case-insensitive), prefix matches first. Without a query, the most recently updated.
81+#[route(GET "./titles.json")]
82+async fn titles_json(cx: &Cx) -> Result<([(&'static str, String); 1], String)> {
83+ let store = app_context::<Arc<Store>>(cx);
84+ let query = match query_params::<TitlesQuery>(cx) {
85+ Ok(query) => query.q.clone().unwrap_or_default(),
86+ Err(_) => String::new(),
87+ };
88+ let query = query.trim();
89+ let mut notes = if query.is_empty() {
90+ store.list_notes().await.map_err(topcoat::Error::from_anyhow)?
91+ } else {
92+ store
93+ .search_titles(query, TITLE_SEARCH_LIMIT)
94+ .await
95+ .map_err(topcoat::Error::from_anyhow)?
96+ };
97+ let needle = crate::matcher::title_fold(query);
98+ if !needle.is_empty() {
99+ // Stable: within each group the most recently updated notes stay first.
100+ notes.sort_by_key(|note| !crate::matcher::title_fold(&note.title).starts_with(&needle));
101+ }
102+ let hits: Vec<TitleHit> = notes
103+ .into_iter()
104+ .take(TITLE_HITS)
105+ .map(|note| TitleHit {
106+ id: note.id,
107+ title: note.title,
108+ })
109+ .collect();
110+ let body = serde_json::to_string(&hits)
111+ .map_err(anyhow::Error::from)
112+ .map_err(topcoat::Error::from_anyhow)?;
113+ Ok(([(header::CONTENT_TYPE.as_str(), "application/json".to_owned())], body))
114+}
115+
116+#[derive(Deserialize)]
117+struct QuickNote {
118+ title: String,
119+ /// `1` from the by-title page's button: redirect to the new note instead of answering
120+ /// with its id.
121+ #[serde(default)]
122+ go: String,
123+}
124+
125+/// A one-heading markdown document whose heading is `title` as literal text. Markdown
126+/// syntax in the title is escaped and whitespace is collapsed.
127+fn heading_markdown(title: &str) -> String {
128+ let collapsed = title.split_whitespace().collect::<Vec<_>>().join(" ");
129+ let text = if collapsed.is_empty() {
130+ "Untitled".to_owned()
131+ } else {
132+ collapsed
133+ };
134+ let escaped: String = text
135+ .chars()
136+ .flat_map(|c| {
137+ let escape = matches!(c, '\\' | '`' | '*' | '_' | '[' | ']' | '<' | '>' | '~' | '#' | '&');
138+ escape.then_some('\\').into_iter().chain(std::iter::once(c))
139+ })
140+ .collect();
141+ format!("# {escaped}\n")
142+}
143+
144+/// POST /notes/quick: creates an unfiled note titled `title` and answers with its id. With
145+/// `go` set, it redirects to the note instead.
146+#[route(POST "./quick")]
147+async fn quick_note(cx: &Cx, Form(input): Form<QuickNote>) -> Result<String> {
148+ let store = app_context::<Arc<Store>>(cx);
149+ let markdown = heading_markdown(&input.title);
150+ let doc = markdown_to_doc(&markdown).map_err(topcoat::Error::from_anyhow)?;
151+ let update = markdown_to_update(&markdown).map_err(topcoat::Error::from_anyhow)?;
152+ let title = export::title(&doc);
153+ let body = export::to_markdown(&doc);
154+
155+ let note = store
156+ .create_note(None)
157+ .await
158+ .map_err(topcoat::Error::from_anyhow)?;
159+ store
160+ .append_update(&note.id, &update)
161+ .await
162+ .map_err(topcoat::Error::from_anyhow)?;
163+ store
164+ .set_title(&note.id, &title)
165+ .await
166+ .map_err(topcoat::Error::from_anyhow)?;
167+ store
168+ .put_text(&note.id, &title, &body)
169+ .await
170+ .map_err(topcoat::Error::from_anyhow)?;
171+ store
172+ .set_links(&note.id, &export::note_links(&doc))
173+ .await
174+ .map_err(topcoat::Error::from_anyhow)?;
175+
176+ if input.go.is_empty() {
177+ return Ok(note.id);
178+ }
179+ Err(see_other(format!("/notes/{}", note.id)).into())
180+}
181+
182+/// GET /notes/by-title/{title}: redirects to the note with that title (case-insensitive,
183+/// outside the trash). Otherwise offers to create a note with the title.
184+#[page("./by-title/{title}")]
185+async fn note_by_title(cx: &Cx) -> Result<impl View> {
186+ let store = app_context::<Arc<Store>>(cx);
187+ let name = path_param::<Title>(cx).to_owned();
188+ let key = title_key(&name);
189+ let notes = store.list_notes().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());
192+ }
193+
194+ let lang = i18n::lang(cx);
195+ let heading = t(lang, Msg::NoNoteNamed).replace("{title}", &name);
196+ let create = t(lang, Msg::CreateNote);
197+ Ok(view! {
198+ <div class="mx-auto flex w-full max-w-md flex-col gap-4 px-4 py-16 lg:px-8">
199+ <p class="text-base">(heading)</p>
200+ <form method="post" action="/notes/quick" class="flex">
201+ <input type="hidden" name="title" value=(name)>
202+ <input type="hidden" name="go" value="1">
203+ button(
204+ variant: ButtonVariant::Outline,
205+ size: ButtonSize::Md,
206+ attrs: attributes! { type="submit" },
207+ (create)
208+ )
209+ </form>
210+ </div>
211+ })
212+}
src/app/notes/note_id.rsadded+479 -0
@@ -0,0 +1,479 @@
1+use std::sync::Arc;
2+
3+use serde::Deserialize;
4+use topcoat::{
5+ Result,
6+ context::{Cx, app_context},
7+ router::{
8+ content::Form,
9+ error::{RouterErrorExt, SeeOther, bad_request, see_other},
10+ header, module_param, page, path_param, route,
11+ },
12+ view::{Child, View, attributes, view},
13+};
14+
15+use crate::app::pane::{self, MENU_LINK, Mobile};
16+use crate::app::shell;
17+use crate::components::button::{ButtonSize, ButtonVariant, button, button_variants};
18+use crate::components::dropdown_menu::{
19+ dropdown_menu, dropdown_menu_content, dropdown_menu_item, dropdown_menu_label,
20+ dropdown_menu_separator, dropdown_menu_sub, dropdown_menu_sub_content,
21+ dropdown_menu_sub_trigger, dropdown_menu_trigger,
22+};
23+use crate::components::floating::{FloatingAlign, FloatingSide};
24+use crate::export::html_page;
25+use crate::hub::Hub;
26+use crate::i18n::{self, Msg, t};
27+use crate::store::{NoteMeta, Notebook, Store};
28+
29+mod history;
30+mod ws;
31+
32+module_param!(note_id);
33+
34+#[derive(Deserialize)]
35+struct MoveNote {
36+ /// Empty means "no notebook".
37+ #[serde(default)]
38+ notebook_id: String,
39+}
40+
41+/// One note in the "Linked from" list of a note.
42+struct LinkRow {
43+ href: String,
44+ title: String,
45+ /// Empty when the note is not in a notebook.
46+ notebook: String,
47+}
48+
49+/// One entry of the "Move to" menu.
50+#[derive(Clone)]
51+struct MoveTarget {
52+ id: String,
53+ name: String,
54+ current: bool,
55+}
56+
57+/// 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.
59+fn context_list(
60+ lang: i18n::Lang,
61+ meta: &NoteMeta,
62+ notebooks: &[Notebook],
63+ notes: Vec<NoteMeta>,
64+) -> (String, Vec<NoteMeta>, String, bool) {
65+ match shell::notebook_name(notebooks, meta.notebook_id.as_deref()) {
66+ Some(name) => {
67+ let nb = meta.notebook_id.clone().unwrap_or_default();
68+ let inside: Vec<NoteMeta> = notes
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+ }
74+ None => (
75+ t(lang, Msg::AllNotes).to_owned(),
76+ notes,
77+ "/".to_owned(),
78+ true,
79+ ),
80+ }
81+}
82+
83+/// GET /notes/{note_id}: the note's editor beside the list it belongs to. A trashed note
84+/// shows a banner with Restore and no editor.
85+#[page]
86+async fn note(cx: &Cx) -> Result<impl View> {
87+ let store = app_context::<Arc<Store>>(cx);
88+ let id = path_param::<NoteId>(cx).to_owned();
89+ let meta = store
90+ .get_note(&id)
91+ .await
92+ .map_err(topcoat::Error::from_anyhow)?
93+ .ok_or_not_found()?;
94+ 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);
98+
99+ let title = shell::title_of(lang, &meta.title);
100+ let trashed = meta.trashed_at.is_some();
101+ let backlinks = if trashed {
102+ Vec::new()
103+ } else {
104+ store
105+ .backlinks(&id, &meta.title)
106+ .await
107+ .map_err(topcoat::Error::from_anyhow)?
108+ };
109+ let linked_rows: Vec<LinkRow> = backlinks
110+ .iter()
111+ .map(|note| LinkRow {
112+ href: format!("/notes/{}", note.id),
113+ title: shell::title_of(lang, &note.title),
114+ notebook: shell::notebook_name(&notebooks, note.notebook_id.as_deref())
115+ .unwrap_or_default(),
116+ })
117+ .collect();
118+ let current_nb = meta.notebook_id.clone().unwrap_or_default();
119+ let crumb_nb = shell::notebook_name(&notebooks, meta.notebook_id.as_deref());
120+ let crumb_label = crumb_nb
121+ .clone()
122+ .unwrap_or_else(|| t(lang, Msg::Unfiled).to_owned());
123+ let crumb_href = match &meta.notebook_id {
124+ Some(nb) => format!("/notebooks/{nb}"),
125+ None => "/unfiled".to_owned(),
126+ };
127+
128+ let (list_title, list_notes, list_href, show_notebook) =
129+ context_list(lang, &meta, &notebooks, notes);
130+ let groups = pane::groups(
131+ lang,
132+ &list_notes,
133+ &notebooks,
134+ &previews,
135+ Some(id.as_str()),
136+ show_notebook,
137+ );
138+ let spec = pane::ListSpec {
139+ title: list_title,
140+ heading: false,
141+ count: list_notes.len(),
142+ notebook_id: current_nb.clone(),
143+ groups,
144+ empty: t(lang, Msg::NoNotesYet),
145+ };
146+ let list = pane::list_pane(cx, lang, spec, Child::new(()));
147+
148+ let moves: Vec<MoveTarget> = std::iter::once(MoveTarget {
149+ id: String::new(),
150+ name: t(lang, Msg::Unfiled).to_owned(),
151+ current: current_nb.is_empty(),
152+ })
153+ .chain(notebooks.iter().map(|nb| MoveTarget {
154+ id: nb.id.clone(),
155+ name: nb.name.clone(),
156+ current: nb.id == current_nb,
157+ }))
158+ .collect();
159+ let already_here = t(lang, Msg::AlreadyHere);
160+ let move_reason = if trashed {
161+ t(lang, Msg::RestoreFirst)
162+ } else {
163+ ""
164+ };
165+ let trash_reason = if trashed {
166+ t(lang, Msg::AlreadyInTrash)
167+ } else {
168+ ""
169+ };
170+ let move_action = format!("/notes/{id}/move");
171+ let trash_action = format!("/notes/{id}/trash");
172+ let restore_action = format!("/notes/{id}/restore");
173+ let export_href = format!("/notes/{id}/export.md");
174+ let export_html_href = format!("/notes/{id}/export.html");
175+ let print_href = format!("/notes/{id}/print");
176+ let history_href = format!("/notes/{id}/history");
177+ let history_label = t(lang, Msg::VersionHistory);
178+ let export_html_label = t(lang, Msg::ExportHtml);
179+ let export_pdf = t(lang, Msg::ExportPdf);
180+ let back_label = t(lang, Msg::BackToList);
181+ let in_trash = t(lang, Msg::InTrash);
182+ let restore = t(lang, Msg::Restore);
183+ let breadcrumb = t(lang, Msg::Breadcrumb);
184+ let move_to_notebook = t(lang, Msg::MoveToNotebook);
185+ let export_as = t(lang, Msg::ExportAs);
186+ let export_md = t(lang, Msg::ExportMarkdown);
187+ let trash_label = t(lang, Msg::MoveToTrash);
188+ let note_actions = t(lang, Msg::NoteActions);
189+ let linked_label = t(lang, Msg::LinkedFrom);
190+
191+ // The one actions menu, at every width: move, export, trash.
192+ let actions = Child::new(view! {
193+ dropdown_menu(
194+ dropdown_menu_trigger(
195+ target: "note-actions-menu",
196+ attrs: attributes! {
197+ class=(button_variants(ButtonVariant::Outline, ButtonSize::Icon))
198+ aria-label=(note_actions)
199+ },
200+ <svg class="size-4" viewBox="0 0 24 24" fill="currentColor" aria-hidden="true">
201+ <circle cx="5" cy="12" r="1.75"></circle>
202+ <circle cx="12" cy="12" r="1.75"></circle>
203+ <circle cx="19" cy="12" r="1.75"></circle>
204+ </svg>
205+ )
206+ dropdown_menu_content(
207+ id: "note-actions-menu",
208+ align: FloatingAlign::End,
209+ dropdown_menu_label((move_to_notebook))
210+ for target in moves {
211+ <form method="post" action=(move_action.clone())>
212+ <input type="hidden" name="notebook_id" value=(target.id)>
213+ dropdown_menu_item(
214+ attrs: attributes! {
215+ type="submit"
216+ disabled=(trashed || target.current)
217+ title=(if trashed { move_reason } else if target.current { already_here } else { "" })
218+ },
219+ (target.name)
220+ )
221+ </form>
222+ }
223+ dropdown_menu_separator()
224+ if !trashed {
225+ <a href=(history_href) class=(MENU_LINK)>(history_label)</a>
226+ }
227+ dropdown_menu_sub(
228+ dropdown_menu_sub_trigger(target: "note-export-menu", (export_as))
229+ dropdown_menu_sub_content(
230+ id: "note-export-menu",
231+ side: FloatingSide::Left,
232+ <a href=(export_href) class=(MENU_LINK)>(export_md)</a>
233+ <a href=(export_html_href) class=(MENU_LINK)>(export_html_label)</a>
234+ <a href=(print_href) target="_blank" rel="noopener" class=(MENU_LINK)>(export_pdf)</a>
235+ )
236+ )
237+ dropdown_menu_separator()
238+ <form method="post" action=(trash_action)>
239+ dropdown_menu_item(
240+ attrs: attributes! {
241+ type="submit"
242+ class="text-destructive"
243+ disabled=(trashed)
244+ title=(trash_reason)
245+ },
246+ (trash_label)
247+ )
248+ </form>
249+ )
250+ )
251+ });
252+
253+ let detail = Child::new(view! {
254+ <div class="flex min-h-0 min-w-0 flex-1 flex-col">
255+ <header id="note-header" class="sticky top-0 z-10 flex h-11 shrink-0 items-center gap-2 border-b border-border bg-background px-3">
256+ <a
257+ href=(list_href)
258+ aria-label=(back_label)
259+ class="inline-flex size-8 shrink-0 items-center justify-center rounded-control text-muted-foreground transition-colors hover:bg-foreground/5 hover:text-foreground lg:hidden"
260+ >
261+ <svg class="size-4" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true">
262+ <path d="m15 18-6-6 6-6"></path>
263+ </svg>
264+ </a>
265+ <nav aria-label=(breadcrumb) class="note-crumb flex min-w-[8rem] flex-1 items-center gap-2 text-sm text-muted-foreground">
266+ <a href=(crumb_href) class="note-crumb-notebook min-w-0 truncate hover:text-foreground">(crumb_label)</a>
267+ <span class="note-crumb-notebook" aria-hidden="true">"›"</span>
268+ <h1 class="min-w-0 truncate text-sm font-medium text-foreground">(title.clone())</h1>
269+ </nav>
270+ if !trashed {
271+ <span class="h-4 w-px shrink-0 bg-border" aria-hidden="true"></span>
272+ <div id="editor-toolbar" class="flex shrink-0 items-center"></div>
273+ }
274+ <div class="ml-auto flex shrink-0 items-center gap-2">
275+ if !trashed {
276+ <span id="sync-slot" class="flex shrink-0 items-center"></span>
277+ }
278+ (actions)
279+ </div>
280+ </header>
281+ if trashed {
282+ <div role="status" class="flex flex-wrap items-center gap-3 border-b border-border px-4 py-3 text-sm">
283+ <p class="min-w-0 flex-1">(in_trash)</p>
284+ <form method="post" action=(restore_action)>
285+ button(
286+ variant: ButtonVariant::Outline,
287+ size: ButtonSize::Sm,
288+ attrs: attributes! { type="submit" },
289+ (restore)
290+ )
291+ </form>
292+ </div>
293+ } else {
294+ <div id="editor" class="min-h-0 w-full flex-1" data-note-id=(id.clone()) data-note-title=(title)></div>
295+ <script type="module" src="/editor.js"></script>
296+ 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">
298+ <h2 id="linked-from" class="text-xs font-medium text-muted-foreground">(linked_label)</h2>
299+ <ul class="mt-2 flex max-h-48 flex-col gap-1 overflow-y-auto">
300+ for row in linked_rows {
301+ <li>
302+ <a href=(row.href) class="flex min-w-0 items-baseline gap-2 rounded-control px-2 py-1.5 text-sm transition-colors hover:bg-foreground/5">
303+ <span class="min-w-0 truncate">(row.title)</span>
304+ if !row.notebook.is_empty() {
305+ <span class="shrink-0 text-xs text-muted-foreground">(row.notebook)</span>
306+ }
307+ </a>
308+ </li>
309+ }
310+ </ul>
311+ </section>
312+ }
313+ }
314+ </div>
315+ });
316+ Ok(pane::split(cx, Mobile::Detail, Child::new(list), detail))
317+}
318+
319+/// POST /notes/{note_id}/move: moves the note into a notebook, or unfiles it.
320+#[route(POST "./move")]
321+async fn move_note(cx: &Cx, Form(input): Form<MoveNote>) -> Result<SeeOther> {
322+ let store = app_context::<Arc<Store>>(cx);
323+ let id = path_param::<NoteId>(cx).to_owned();
324+ let meta = store
325+ .get_note(&id)
326+ .await
327+ .map_err(topcoat::Error::from_anyhow)?
328+ .ok_or_not_found()?;
329+ if meta.trashed_at.is_some() {
330+ return Err(bad_request("the note is in the trash; restore it first").into());
331+ }
332+ let target = input.notebook_id.trim();
333+ let target = if target.is_empty() {
334+ None
335+ } else {
336+ let exists = store
337+ .get_notebook(target)
338+ .await
339+ .map_err(topcoat::Error::from_anyhow)?
340+ .is_some();
341+ if !exists {
342+ return Err(bad_request("unknown notebook").into());
343+ }
344+ Some(target)
345+ };
346+ store
347+ .move_note(&id, target)
348+ .await
349+ .map_err(topcoat::Error::from_anyhow)?;
350+ Ok(see_other(format!("/notes/{id}?toast=moved")))
351+}
352+
353+/// POST /notes/{note_id}/trash: moves the note to the trash and returns to its list, with
354+/// an Undo toast.
355+#[route(POST "./trash")]
356+async fn trash_note(cx: &Cx) -> Result<SeeOther> {
357+ let store = app_context::<Arc<Store>>(cx);
358+ let id = path_param::<NoteId>(cx).to_owned();
359+ let meta = store
360+ .get_note(&id)
361+ .await
362+ .map_err(topcoat::Error::from_anyhow)?
363+ .ok_or_not_found()?;
364+ store.trash_note(&id).await.map_err(topcoat::Error::from_anyhow)?;
365+ let back = match meta.notebook_id {
366+ Some(nb) => format!("/notebooks/{nb}"),
367+ None => "/".to_owned(),
368+ };
369+ Ok(see_other(format!("{back}?toast=trashed&undo={id}")))
370+}
371+
372+/// POST /notes/{note_id}/restore: takes the note out of the trash and opens it.
373+#[route(POST "./restore")]
374+async fn restore_note(cx: &Cx) -> Result<SeeOther> {
375+ let store = app_context::<Arc<Store>>(cx);
376+ let id = path_param::<NoteId>(cx).to_owned();
377+ store.get_note(&id).await.map_err(topcoat::Error::from_anyhow)?.ok_or_not_found()?;
378+ store.restore_note(&id).await.map_err(topcoat::Error::from_anyhow)?;
379+ Ok(see_other(format!("/notes/{id}?toast=restored")))
380+}
381+
382+/// ASCII-only file name stem from a note title. Falls back to "note".
383+/// The note title as a safe file name, without extension.
384+fn file_stem(title: &str) -> String {
385+ crate::app::export_all::sanitize(title)
386+}
387+
388+/// `Content-Disposition` for a download: an ASCII `filename` for old clients and the
389+/// real title as UTF-8 in `filename*`.
390+fn attachment(stem: &str, ext: &str) -> String {
391+ let ascii: String = stem
392+ .chars()
393+ .map(|c| match c {
394+ 'ı' | 'İ' => 'i',
395+ 'ş' | 'Ş' => 's',
396+ 'ğ' | 'Ğ' => 'g',
397+ 'ü' | 'Ü' => 'u',
398+ 'ö' | 'Ö' => 'o',
399+ 'ç' | 'Ç' => 'c',
400+ c if c.is_ascii_alphanumeric() || c == '-' || c == '_' || c == '.' => c,
401+ _ => '-',
402+ })
403+ .collect();
404+ let ascii = ascii.trim_matches('-');
405+ let ascii = if ascii.is_empty() { "note" } else { ascii };
406+ let encoded: String = format!("{stem}.{ext}")
407+ .bytes()
408+ .map(|b| match b {
409+ b'A'..=b'Z' | b'a'..=b'z' | b'0'..=b'9' | b'-' | b'_' | b'.' | b'~' => (b as char).to_string(),
410+ _ => format!("%{b:02X}"),
411+ })
412+ .collect();
413+ format!("attachment; filename=\"{ascii}.{ext}\"; filename*=UTF-8''{encoded}")
414+}
415+
416+/// Standalone HTML of the live note, and the file name stem to save it under.
417+async fn note_page(cx: &Cx, print: bool) -> Result<(String, String)> {
418+ let store = app_context::<Arc<Store>>(cx);
419+ let hub = app_context::<Arc<Hub>>(cx);
420+ let id = path_param::<NoteId>(cx).to_owned();
421+ let meta = store
422+ .get_note(&id)
423+ .await
424+ .map_err(topcoat::Error::from_anyhow)?
425+ .ok_or_not_found()?;
426+ let room = hub.room(store, &id).await.map_err(topcoat::Error::from_anyhow)?;
427+ let body = room.html().await;
428+ let lang = i18n::lang(cx);
429+ let title = shell::title_of(lang, &meta.title);
430+ let page = html_page(&title, &body, lang.code(), print);
431+ Ok((file_stem(&title), page))
432+}
433+
434+/// GET /notes/{note_id}/export.md: markdown of the live document.
435+#[route(GET "./export.md")]
436+async fn export_markdown(cx: &Cx) -> Result<([(&'static str, String); 2], String)> {
437+ let store = app_context::<Arc<Store>>(cx);
438+ let hub = app_context::<Arc<Hub>>(cx);
439+ let id = path_param::<NoteId>(cx).to_owned();
440+ let meta = store
441+ .get_note(&id)
442+ .await
443+ .map_err(topcoat::Error::from_anyhow)?
444+ .ok_or_not_found()?;
445+ let titles = crate::app::export_all::title_map(store)
446+ .await
447+ .map_err(topcoat::Error::from_anyhow)?;
448+ let room = hub.room(store, &id).await.map_err(topcoat::Error::from_anyhow)?;
449+ let markdown = room.markdown_with(titles).await;
450+ let stem = file_stem(&shell::title_of(i18n::lang(cx), &meta.title));
451+ Ok((
452+ [
453+ (header::CONTENT_TYPE.as_str(), "text/markdown; charset=utf-8".to_owned()),
454+ (header::CONTENT_DISPOSITION.as_str(), attachment(&stem, "md")),
455+ ],
456+ markdown,
457+ ))
458+}
459+
460+/// GET /notes/{note_id}/export.html: standalone HTML file of the live document.
461+#[route(GET "./export.html")]
462+async fn export_html(cx: &Cx) -> Result<([(&'static str, String); 2], String)> {
463+ let (stem, page) = note_page(cx, false).await?;
464+ Ok((
465+ [
466+ (header::CONTENT_TYPE.as_str(), "text/html; charset=utf-8".to_owned()),
467+ (header::CONTENT_DISPOSITION.as_str(), attachment(&stem, "html")),
468+ ],
469+ page,
470+ ))
471+}
472+
473+/// GET /notes/{note_id}/print: the same HTML, shown inline. It opens the print dialog,
474+/// where "Save as PDF" makes the PDF.
475+#[route(GET "./print")]
476+async fn print_note(cx: &Cx) -> Result<([(&'static str, &'static str); 1], String)> {
477+ let (_, page) = note_page(cx, true).await?;
478+ Ok(([(header::CONTENT_TYPE.as_str(), "text/html; charset=utf-8")], page))
479+}
src/app/notes/note_id/history.rsadded+222 -0
@@ -0,0 +1,222 @@
1+use std::sync::Arc;
2+
3+use loro::Frontiers;
4+use serde::Deserialize;
5+use topcoat::{
6+ Result,
7+ context::{Cx, app_context},
8+ router::{
9+ content::Form,
10+ error::{RouterErrorExt, SeeOther, bad_request, see_other},
11+ page, path_param, query_params, route,
12+ },
13+ view::{View, attributes, view},
14+};
15+
16+use super::NoteId;
17+use crate::app::shell;
18+use crate::components::button::{ButtonSize, ButtonVariant, button};
19+use crate::hub::Hub;
20+use crate::i18n::{self, Msg, t};
21+use crate::store::Store;
22+
23+/// Row styling of the version list, the same as the note list's rows.
24+const ROW: &str = "flex min-h-14 flex-col justify-center gap-1 px-4 py-2 transition-colors hover:bg-foreground/5";
25+const ROW_SELECTED: &str = "marker flex min-h-14 flex-col justify-center gap-1 px-4 py-2";
26+
27+#[query_params(error = bad_request)]
28+pub struct HistoryQuery {
29+ /// `current` for the live document, or the `at` millis of a recorded version.
30+ pub v: Option<String>,
31+}
32+
33+#[derive(Deserialize)]
34+struct RestoreForm {
35+ at: i64,
36+}
37+
38+/// One row of the version list: its link, its label, and whether it is selected.
39+struct Entry {
40+ href: String,
41+ label: String,
42+ /// Version time in ms; `None` for the current version.
43+ at: Option<i64>,
44+ selected: bool,
45+}
46+
47+/// GET /notes/{note_id}/history: the note's recorded versions beside a read-only preview
48+/// of the selected one. Without `?v`, the newest recorded version is shown.
49+#[page]
50+async fn history(cx: &Cx) -> Result<impl View> {
51+ let store = app_context::<Arc<Store>>(cx);
52+ let hub = app_context::<Arc<Hub>>(cx);
53+ let id = path_param::<NoteId>(cx).to_owned();
54+ let meta = store
55+ .get_note(&id)
56+ .await
57+ .map_err(topcoat::Error::from_anyhow)?
58+ .ok_or_not_found()?;
59+ let versions = store.list_versions(&id).await.map_err(topcoat::Error::from_anyhow)?;
60+ let requested = match query_params::<HistoryQuery>(cx) {
61+ Ok(query) => query.v.clone(),
62+ Err(_) => None,
63+ };
64+ let lang = i18n::lang(cx);
65+ let trashed = meta.trashed_at.is_some();
66+
67+ // `None` selects the live document; `Some(at)` a recorded version.
68+ let selected: Option<i64> = match requested.as_deref() {
69+ Some("current") => None,
70+ Some(value) => match value.parse::<i64>() {
71+ Ok(at) if versions.iter().any(|(v, _)| *v == at) => Some(at),
72+ _ => versions.first().map(|(at, _)| *at),
73+ },
74+ None => versions.first().map(|(at, _)| *at),
75+ };
76+
77+ let preview = if versions.is_empty() {
78+ String::new()
79+ } else {
80+ let room = hub.room(store, &id).await.map_err(topcoat::Error::from_anyhow)?;
81+ match selected {
82+ None => room.html().await,
83+ Some(at) => {
84+ let bytes = store
85+ .get_version(&id, at)
86+ .await
87+ .map_err(topcoat::Error::from_anyhow)?
88+ .ok_or_not_found()?;
89+ let frontiers = Frontiers::decode(&bytes).map_err(|err| topcoat::Error::from_anyhow(err.into()))?;
90+ room.html_at(&frontiers).await.map_err(topcoat::Error::from_anyhow)?
91+ }
92+ }
93+ };
94+
95+ let title = t(lang, Msg::VersionHistory);
96+ let back_label = t(lang, Msg::BackToNote);
97+ let current_label = t(lang, Msg::CurrentVersion);
98+ let no_versions = t(lang, Msg::NoVersionsYet);
99+ let restore_label = t(lang, Msg::RestoreVersion);
100+ let note_title = shell::title_of(lang, &meta.title);
101+ let back_href = format!("/notes/{id}");
102+ let restore_action = format!("/notes/{id}/history/restore");
103+ let selected_label = match selected {
104+ Some(at) => i18n::date_time(lang, at),
105+ None => current_label.to_owned(),
106+ };
107+ let restore_at = selected.unwrap_or(0);
108+
109+ let mut entries = vec![Entry {
110+ href: format!("/notes/{id}/history?v=current"),
111+ label: current_label.to_owned(),
112+ at: None,
113+ selected: selected.is_none(),
114+ }];
115+ entries.extend(versions.iter().map(|(at, _)| Entry {
116+ href: format!("/notes/{id}/history?v={at}"),
117+ label: i18n::date_time(lang, *at),
118+ at: Some(*at),
119+ selected: selected == Some(*at),
120+ }));
121+ let has_versions = !versions.is_empty();
122+ let show_restore = has_versions && !trashed && selected.is_some();
123+
124+ Ok(view! {
125+ <div class="flex min-h-0 min-w-0 flex-1 flex-col">
126+ <header class="sticky top-0 z-10 flex h-11 shrink-0 items-center gap-2 border-b border-border bg-background px-3">
127+ <a
128+ href=(back_href)
129+ aria-label=(back_label)
130+ class="inline-flex size-8 shrink-0 items-center justify-center rounded-control text-muted-foreground transition-colors hover:bg-foreground/5 hover:text-foreground"
131+ >
132+ <svg class="size-4" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true">
133+ <path d="m15 18-6-6 6-6"></path>
134+ </svg>
135+ </a>
136+ <nav aria-label=(title) class="flex min-w-0 flex-1 items-center gap-2 text-sm text-muted-foreground">
137+ <span class="min-w-0 truncate">(note_title)</span>
138+ <span aria-hidden="true">"›"</span>
139+ <h1 class="shrink-0 text-sm font-medium text-foreground">(title)</h1>
140+ </nav>
141+ </header>
142+ <div class="flex min-h-0 flex-1 flex-col lg:flex-row">
143+ <ul class="max-h-[40vh] shrink-0 divide-y divide-border overflow-y-auto border-b border-border lg:max-h-none lg:w-72 lg:border-b-0 lg:border-r">
144+ for entry in entries {
145+ <li>
146+ <a
147+ href=(entry.href)
148+ class=(if entry.selected { ROW_SELECTED } else { ROW })
149+ aria-current=(if entry.selected { "true" } else { "false" })
150+ >
151+ if let Some(at) = entry.at {
152+ <time data-ms=(at) class="min-w-0 truncate text-sm font-medium">(entry.label)</time>
153+ } else {
154+ <span class="min-w-0 truncate text-sm font-medium">(entry.label)</span>
155+ }
156+ </a>
157+ </li>
158+ }
159+ </ul>
160+ <section class="min-h-0 min-w-0 flex-1 overflow-y-auto">
161+ if has_versions {
162+ <div class="flex flex-wrap items-center gap-3 border-b border-border px-4 py-3 text-sm">
163+ <p class="min-w-0 flex-1 text-xs text-muted-foreground">
164+ if let Some(at) = selected {
165+ <time data-ms=(at)>(selected_label)</time>
166+ } else {
167+ (selected_label)
168+ }
169+ </p>
170+ if show_restore {
171+ <form method="post" action=(restore_action)>
172+ <input type="hidden" name="at" value=(restore_at)>
173+ button(
174+ variant: ButtonVariant::Outline,
175+ size: ButtonSize::Sm,
176+ attrs: attributes! { type="submit" },
177+ (restore_label)
178+ )
179+ </form>
180+ }
181+ </div>
182+ <div id="editor">
183+ <div class="ProseMirror">(topcoat::view::Unescaped::new_unchecked(preview))</div>
184+ </div>
185+ } else {
186+ <div class="flex flex-col items-center gap-2 px-6 py-16 text-center">
187+ <p class="max-w-md text-base text-muted-foreground">(no_versions)</p>
188+ </div>
189+ }
190+ </section>
191+ </div>
192+ </div>
193+ })
194+}
195+
196+/// POST /notes/{note_id}/history/restore: makes the note match the version taken at `at`,
197+/// then opens the note.
198+#[route(POST "./restore")]
199+async fn restore_version(cx: &Cx, Form(input): Form<RestoreForm>) -> Result<SeeOther> {
200+ let store = app_context::<Arc<Store>>(cx);
201+ let hub = app_context::<Arc<Hub>>(cx);
202+ let id = path_param::<NoteId>(cx).to_owned();
203+ let meta = store
204+ .get_note(&id)
205+ .await
206+ .map_err(topcoat::Error::from_anyhow)?
207+ .ok_or_not_found()?;
208+ if meta.trashed_at.is_some() {
209+ return Err(bad_request("the note is in the trash; restore it first").into());
210+ }
211+ let bytes = store
212+ .get_version(&id, input.at)
213+ .await
214+ .map_err(topcoat::Error::from_anyhow)?
215+ .ok_or_not_found()?;
216+ let frontiers = Frontiers::decode(&bytes).map_err(|err| topcoat::Error::from_anyhow(err.into()))?;
217+ let room = hub.room(store, &id).await.map_err(topcoat::Error::from_anyhow)?;
218+ room.restore(store, &frontiers)
219+ .await
220+ .map_err(topcoat::Error::from_anyhow)?;
221+ Ok(see_other(format!("/notes/{id}?toast=version-restored")))
222+}
src/app/notes/note_id/ws.rsadded+30 -0
@@ -0,0 +1,30 @@
1+use std::sync::Arc;
2+
3+use topcoat::{
4+ Result,
5+ context::{Cx, app_context},
6+ router::{
7+ error::RouterErrorExt,
8+ content::websocket::WebSocketUpgrade,
9+ path_param,
10+ response::Response,
11+ route,
12+ },
13+};
14+
15+use super::NoteId;
16+use crate::hub::{Hub, serve_socket};
17+use crate::store::Store;
18+
19+/// GET /notes/{note_id}/ws: live sync for one note.
20+#[route(GET)]
21+async fn websocket(cx: &Cx, upgrade: WebSocketUpgrade) -> Result<Response> {
22+ let store = app_context::<Arc<Store>>(cx).clone();
23+ let hub = app_context::<Arc<Hub>>(cx).clone();
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()?;
26+ let room = hub.room(&store, &id).await.map_err(topcoat::Error::from_anyhow)?;
27+ upgrade.on_upgrade(move |socket| async move {
28+ serve_socket(hub, store, room, socket).await;
29+ })
30+}
src/app/palette.rsadded+527 -0
@@ -0,0 +1,527 @@
1+//! The command palette: the Ctrl/Cmd+K dialog that the layout renders, and `GET /palette`,
2+//! the results fragment the dialog fetches as the user types.
3+//!
4+//! Commands, notes, and notebooks share one `role="listbox"`. Links are `<a>` elements.
5+//! Actions that stay on the page (theme, new notebook) and form posts are `<button>`s that
6+//! the inline script runs. The shortcut itself is handled by `SHELL_SCRIPT` in `shell.rs`,
7+//! which calls `window.openPalette`.
8+
9+use std::collections::HashSet;
10+use std::sync::Arc;
11+
12+use topcoat::{
13+ Result,
14+ context::{Cx, app_context},
15+ router::{query_params, route},
16+ view::{Unescaped, View, ViewExt, ViewHandle, component, view},
17+};
18+
19+use crate::app::shell;
20+use crate::components::badge::{BadgeVariant, badge};
21+use crate::components::kbd::{kbd, kbd_group};
22+use crate::i18n::{self, Lang, Msg, t};
23+use crate::scheme::ALL as SCHEMES;
24+use crate::store::{Notebook, NoteMeta, Store};
25+
26+/// Most notes, and most notebooks, listed in one result set.
27+const LIMIT: usize = 8;
28+
29+/// 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";
31+/// Classes of the panel inside the dialog.
32+const PANEL: &str = "flex flex-col overflow-hidden border border-border bg-popover shadow-float sm:rounded-float";
33+/// Classes of one result row.
34+const OPTION: &str = "flex min-h-9 w-full items-center gap-3 rounded-control px-3 py-1.5 text-left text-sm transition-colors hover:bg-foreground/5";
35+
36+/// Picks the text for `lang`. Every string in the palette goes through here with both
37+/// languages, so a missing Turkish text does not compile.
38+fn pick(lang: Lang, en: &'static str, tr: &'static str) -> &'static str {
39+ match lang {
40+ Lang::En => en,
41+ Lang::Tr => tr,
42+ }
43+}
44+
45+/// The `q` parameter of the palette fragment.
46+#[query_params(error = bad_request)]
47+pub struct PaletteQuery {
48+ pub q: Option<String>,
49+}
50+
51+/// One row of the palette.
52+pub struct Item {
53+ label: String,
54+ /// A secondary line, such as the search snippet of a note.
55+ detail: Option<String>,
56+ /// The notebook name of a note.
57+ notebook: Option<String>,
58+ /// A shortcut shown as a keycap, such as "N".
59+ keycap: Option<&'static str>,
60+ /// Set for links, which render as `<a href>`.
61+ href: Option<String>,
62+ /// For buttons: "post", "theme", "new-notebook", or "scheme".
63+ action: &'static str,
64+ /// For "post": the URL the script submits a form to.
65+ url: &'static str,
66+ /// For "post": the hidden form fields, as a JSON object. For "scheme": the scheme id.
67+ fields: &'static str,
68+}
69+
70+impl Item {
71+ fn link(label: impl Into<String>, href: impl Into<String>) -> Self {
72+ Self {
73+ label: label.into(),
74+ detail: None,
75+ notebook: None,
76+ keycap: None,
77+ href: Some(href.into()),
78+ action: "",
79+ url: "",
80+ fields: "",
81+ }
82+ }
83+
84+ fn action(label: impl Into<String>, action: &'static str) -> Self {
85+ Self {
86+ action,
87+ href: None,
88+ ..Self::link(label, "")
89+ }
90+ }
91+
92+ fn post(label: impl Into<String>, url: &'static str, fields: &'static str, keycap: Option<&'static str>) -> Self {
93+ Self {
94+ action: "post",
95+ url,
96+ fields,
97+ keycap,
98+ href: None,
99+ ..Self::link(label, "")
100+ }
101+ }
102+}
103+
104+/// The commands, in both languages. Labels are matched against the query.
105+fn commands(lang: Lang) -> Vec<Item> {
106+ vec![
107+ Item::post(pick(lang, "New note", "Yeni not"), "/notes", "{}", Some("N")),
108+ Item::action(pick(lang, "New notebook", "Yeni defter"), "new-notebook"),
109+ Item::link(pick(lang, "Go to All notes", "Tüm notlara git"), "/"),
110+ Item::link(pick(lang, "Go to Unfiled", "Dosyalanmamışlara git"), "/unfiled"),
111+ Item::link(pick(lang, "Go to Trash", "Çöp kutusuna git"), "/trash"),
112+ Item::link(t(lang, Msg::ExportAll), "/export.zip"),
113+ Item::link(t(lang, Msg::ImportMarkdown), "/import"),
114+ Item::action(pick(lang, "Toggle theme", "Temayı değiştir"), "theme"),
115+ Item::post(pick(lang, "Switch to English", "İngilizceye geç"), "/lang", r#"{"lang":"en"}"#, None),
116+ Item::post(pick(lang, "Switch to Türkçe", "Türkçeye geç"), "/lang", r#"{"lang":"tr"}"#, None),
117+ ]
118+}
119+
120+/// One command per color scheme, named "Color scheme: <Name>" (the name is not translated).
121+fn scheme_commands(lang: Lang) -> Vec<Item> {
122+ let prefix = t(lang, Msg::ColorScheme);
123+ SCHEMES
124+ .into_iter()
125+ .map(|scheme| Item {
126+ action: "scheme",
127+ href: None,
128+ fields: scheme.id(),
129+ ..Item::link(format!("{prefix}: {}", scheme.name()), "")
130+ })
131+ .collect()
132+}
133+
134+/// A note row. `snippet` is the search excerpt, if this is a search result.
135+fn note_item(lang: Lang, note: &NoteMeta, notebooks: &[Notebook], snippet: Option<&str>) -> Item {
136+ let detail = snippet
137+ .map(|s| s.split_whitespace().collect::<Vec<_>>().join(" "))
138+ .filter(|s| !s.is_empty());
139+ Item {
140+ detail,
141+ notebook: shell::notebook_name(notebooks, note.notebook_id.as_deref()),
142+ ..Item::link(shell::title_of(lang, &note.title), format!("/notes/{}", note.id))
143+ }
144+}
145+
146+/// GET /palette?q=...: the palette's results as an HTML fragment, without the page layout.
147+/// An empty query lists the commands, the 8 most recently updated notes, and all notebooks
148+/// (up to 8). A query lists the matching commands, the search results, and matching notebooks.
149+#[route(GET)]
150+async fn palette_results(cx: &Cx) -> Result<ViewHandle> {
151+ let store = app_context::<Arc<Store>>(cx);
152+ let lang = i18n::lang(cx);
153+ let query = query_params::<PaletteQuery>(cx)?;
154+ let q = query.q.as_deref().unwrap_or("").trim().to_owned();
155+ let needle = q.to_lowercase();
156+
157+ let notebooks = store.list_notebooks().await.map_err(topcoat::Error::from_anyhow)?;
158+ let cmds: Vec<Item> = commands(lang)
159+ .into_iter()
160+ .chain(scheme_commands(lang))
161+ .filter(|c| c.label.to_lowercase().contains(&needle))
162+ .collect();
163+ let notes: Vec<Item> = if q.is_empty() {
164+ let all = store.list_notes().await.map_err(topcoat::Error::from_anyhow)?;
165+ all.iter()
166+ .take(LIMIT)
167+ .map(|n| note_item(lang, n, &notebooks, None))
168+ .collect()
169+ } else {
170+ // Full-text hits match whole words; title hits also match inside a word ("ro" finds
171+ // "Q4 roadmap"). Full-text hits come first, and a note listed once is not repeated.
172+ let hits = match crate::matcher::Matcher::simple(&q) {
173+ Some(matcher) => store
174+ .search(&matcher, LIMIT)
175+ .await
176+ .map_err(topcoat::Error::from_anyhow)?,
177+ None => Vec::new(),
178+ };
179+ let mut seen: HashSet<String> = hits.iter().map(|h| h.note.id.clone()).collect();
180+ let mut items: Vec<Item> = hits
181+ .iter()
182+ .map(|h| note_item(lang, &h.note, &notebooks, Some(&h.snippet)))
183+ .collect();
184+ let titles = store
185+ .search_titles(&q, LIMIT)
186+ .await
187+ .map_err(topcoat::Error::from_anyhow)?;
188+ for note in titles.iter().filter(|n| seen.insert(n.id.clone())) {
189+ items.push(note_item(lang, note, &notebooks, None));
190+ }
191+ items.truncate(LIMIT);
192+ items
193+ };
194+ let books: Vec<Item> = notebooks
195+ .iter()
196+ .filter(|nb| nb.name.to_lowercase().contains(&needle))
197+ .take(LIMIT)
198+ .map(|nb| Item::link(nb.name.clone(), format!("/notebooks/{}", nb.id)))
199+ .collect();
200+
201+ let empty = cmds.is_empty() && notes.is_empty() && books.is_empty();
202+ let no_results = pick(lang, "No results", "Sonuç yok");
203+ let results_label = pick(lang, "Results", "Sonuçlar");
204+
205+ let fragment = view! {
206+ <div id="palette-list" role="listbox" aria-label=(results_label)>
207+ if !cmds.is_empty() {
208+ palette_group(
209+ id: "palette-h-commands".to_owned(),
210+ title: pick(lang, "Commands", "Komutlar").to_owned(),
211+ items: cmds,
212+ )
213+ }
214+ if !notes.is_empty() {
215+ palette_group(
216+ id: "palette-h-notes".to_owned(),
217+ title: pick(lang, "Notes", "Notlar").to_owned(),
218+ items: notes,
219+ )
220+ }
221+ if !books.is_empty() {
222+ palette_group(
223+ id: "palette-h-notebooks".to_owned(),
224+ title: pick(lang, "Notebooks", "Defterler").to_owned(),
225+ items: books,
226+ )
227+ }
228+ </div>
229+ if empty {
230+ <p class="px-3 py-8 text-center text-sm text-muted-foreground">(no_results)</p>
231+ }
232+ };
233+ Ok(fragment.single().await?)
234+}
235+
236+/// A labelled group of options inside the listbox.
237+#[component]
238+async fn palette_group(id: String, title: String, items: Vec<Item>) -> Result<impl View> {
239+ Ok(view! {
240+ <div role="group" aria-labelledby=(id.clone()) class="py-1">
241+ <p id=(id) class="section-label px-3 pt-2 pb-1">(title)</p>
242+ for item in items {
243+ palette_option(item: item)
244+ }
245+ </div>
246+ })
247+}
248+
249+/// One option: a link when it has an `href`, otherwise a button the script runs.
250+#[component]
251+async fn palette_option(item: Item) -> Result<impl View> {
252+ let Item {
253+ label,
254+ detail,
255+ notebook,
256+ keycap,
257+ href,
258+ action,
259+ url,
260+ fields,
261+ } = item;
262+ Ok(view! {
263+ if let Some(href) = href {
264+ <a href=(href) role="option" aria-selected="false" class=(OPTION)>
265+ option_body(label: label, detail: detail, notebook: notebook, keycap: keycap)
266+ </a>
267+ } else {
268+ <button
269+ type="button"
270+ role="option"
271+ aria-selected="false"
272+ class=(OPTION)
273+ data-action=(action)
274+ data-url=(url)
275+ data-fields=(fields)
276+ >
277+ option_body(label: label, detail: detail, notebook: notebook, keycap: keycap)
278+ </button>
279+ }
280+ })
281+}
282+
283+/// The text and badges inside an option.
284+#[component]
285+async fn option_body(
286+ label: String,
287+ detail: Option<String>,
288+ notebook: Option<String>,
289+ keycap: Option<&'static str>,
290+) -> Result<impl View> {
291+ Ok(view! {
292+ <span class="min-w-0 flex-1">
293+ <span class="block truncate font-medium">(label)</span>
294+ if let Some(text) = detail {
295+ <span class="block truncate text-xs text-muted-foreground">(text)</span>
296+ }
297+ </span>
298+ if let Some(name) = notebook {
299+ badge(variant: BadgeVariant::Secondary, (name))
300+ }
301+ if let Some(key) = keycap {
302+ <span class="ml-auto">kbd((key))</span>
303+ }
304+ })
305+}
306+
307+/// The palette dialog, rendered once in the layout. It stays closed until the shortcut
308+/// (or `window.openPalette`) opens it.
309+#[component]
310+pub async fn palette_dialog(lang: Lang) -> Result<impl View> {
311+ let dialog_label = pick(lang, "Command palette", "Komut paleti");
312+ let placeholder = pick(lang, "Search notes or type a command…", "Not ara veya komut yaz…");
313+ let nav = pick(lang, "navigate", "gezin");
314+ let open = pick(lang, "open", "aç");
315+ let close = pick(lang, "close", "kapat");
316+ let in_editor = pick(lang, "in editor", "editörde");
317+
318+ Ok(view! {
319+ <dialog id="palette" aria-label=(dialog_label) class=(DIALOG)>
320+ <div class=(PANEL)>
321+ <div class="flex items-center gap-2 border-b border-border px-3">
322+ <svg class="size-4 shrink-0 text-muted-foreground" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true">
323+ <circle cx="11" cy="11" r="7"></circle>
324+ <path d="m20 20-3.5-3.5"></path>
325+ </svg>
326+ <input
327+ id="palette-input"
328+ type="text"
329+ role="combobox"
330+ aria-expanded="true"
331+ aria-controls="palette-list"
332+ aria-autocomplete="list"
333+ placeholder=(placeholder)
334+ autocomplete="off"
335+ spellcheck="false"
336+ class="h-12 min-w-0 flex-1 bg-transparent text-base placeholder:text-muted-foreground outline-none"
337+ >
338+ kbd("Esc")
339+ </div>
340+ <div id="palette-results" class="max-h-[60vh] overflow-y-auto p-1"></div>
341+ <div class="flex flex-wrap items-center justify-between gap-x-4 gap-y-1 border-t border-border px-3 py-2 font-mono text-[11px] text-muted-foreground">
342+ <div class="flex items-center gap-3">
343+ <span class="inline-flex items-center gap-1">kbd("↑") kbd("↓")</span>
344+ <span>(nav)</span>
345+ <span class="inline-flex items-center gap-1">kbd("↵")</span>
346+ <span>(open)</span>
347+ <span class="inline-flex items-center gap-1">kbd("Esc")</span>
348+ <span>(close)</span>
349+ </div>
350+ <div class="flex items-center gap-2">
351+ kbd_group(kbd("Ctrl") kbd("Shift") kbd("K"))
352+ <span>(in_editor)</span>
353+ </div>
354+ </div>
355+ </div>
356+ </dialog>
357+ <script>(Unescaped::new_unchecked(PALETTE_SCRIPT))</script>
358+ })
359+}
360+
361+/// Palette behaviour. Defines `window.openPalette` (called by the shortcut in `shell.rs`).
362+/// Results load on open and 120ms after each keystroke; a new request aborts the last one.
363+/// Up and Down move the highlight (`aria-activedescendant`), Enter runs it, and Esc closes
364+/// the dialog natively. A click on the backdrop closes it. Closing returns focus to the
365+/// element that was focused before.
366+const PALETTE_SCRIPT: &str = r#"
367+(function () {
368+ var dialog = document.getElementById('palette');
369+ if (!dialog) return;
370+ var input = document.getElementById('palette-input');
371+ var results = document.getElementById('palette-results');
372+ var desktop = window.matchMedia('(min-width: 1024px)');
373+ var opener = null;
374+ var active = -1;
375+ var timer = null;
376+ var controller = null;
377+
378+ function options() {
379+ return Array.prototype.slice.call(results.querySelectorAll('[role="option"]'));
380+ }
381+ function setActive(index) {
382+ var list = options();
383+ if (list.length === 0) {
384+ active = -1;
385+ input.removeAttribute('aria-activedescendant');
386+ return;
387+ }
388+ if (index < 0) index = list.length - 1;
389+ if (index >= list.length) index = 0;
390+ list.forEach(function (opt, i) {
391+ var on = i === index;
392+ opt.setAttribute('aria-selected', on ? 'true' : 'false');
393+ opt.classList.toggle('marker', on);
394+ });
395+ active = index;
396+ input.setAttribute('aria-activedescendant', list[index].id);
397+ list[index].scrollIntoView({ block: 'nearest' });
398+ }
399+ function assignIds() {
400+ options().forEach(function (opt, i) { opt.id = 'palette-opt-' + i; });
401+ }
402+ function load(q) {
403+ if (controller) controller.abort();
404+ controller = new AbortController();
405+ var signal = controller.signal;
406+ fetch('/palette?q=' + encodeURIComponent(q), {
407+ headers: { Accept: 'text/html' },
408+ cache: 'no-store',
409+ signal: signal
410+ })
411+ .then(function (res) {
412+ if (!res.ok) throw new Error('palette ' + res.status);
413+ return res.text();
414+ })
415+ .then(function (html) {
416+ if (signal.aborted) return;
417+ results.innerHTML = html;
418+ assignIds();
419+ setActive(0);
420+ })
421+ .catch(function () { /* aborted or failed: keep the last results */ });
422+ }
423+ function newNotebook() {
424+ if (desktop.matches) {
425+ document.documentElement.dataset.sidebar = 'expanded';
426+ try { localStorage.setItem('sidebar', 'expanded'); } catch (err) {}
427+ } else {
428+ var toggle = document.getElementById('drawer-open');
429+ if (toggle) toggle.click();
430+ }
431+ var field = document.querySelector('#sidebar input[name="name"]');
432+ if (field) setTimeout(function () { field.focus(); }, 0);
433+ }
434+ function post(url, json) {
435+ var fields = JSON.parse(json || '{}');
436+ if (url === '/notes') {
437+ var nb = document.querySelector('#new-note-form input[name="notebook_id"]');
438+ fields.notebook_id = nb ? nb.value : '';
439+ }
440+ if (url === '/lang') fields.back = location.pathname + location.search;
441+ var form = document.createElement('form');
442+ form.method = 'post';
443+ form.action = url;
444+ Object.keys(fields).forEach(function (name) {
445+ var field = document.createElement('input');
446+ field.type = 'hidden';
447+ field.name = name;
448+ field.value = fields[name];
449+ form.appendChild(field);
450+ });
451+ document.body.appendChild(form);
452+ form.submit();
453+ }
454+ function run(opt) {
455+ var action = opt.getAttribute('data-action');
456+ if (action === 'theme') {
457+ if (typeof window.cycleTheme === 'function') window.cycleTheme();
458+ dialog.close();
459+ } else if (action === 'scheme') {
460+ if (typeof window.setScheme === 'function') window.setScheme(opt.getAttribute('data-fields'));
461+ dialog.close();
462+ } else if (action === 'new-notebook') {
463+ opener = null;
464+ dialog.close();
465+ newNotebook();
466+ } else if (action === 'post') {
467+ opener = null;
468+ post(opt.getAttribute('data-url'), opt.getAttribute('data-fields'));
469+ }
470+ }
471+
472+ window.openPalette = function () {
473+ if (dialog.open) {
474+ input.focus();
475+ return;
476+ }
477+ opener = document.activeElement;
478+ input.value = '';
479+ dialog.showModal();
480+ input.focus();
481+ load('');
482+ };
483+
484+ input.addEventListener('input', function () {
485+ clearTimeout(timer);
486+ timer = setTimeout(function () { load(input.value.trim()); }, 120);
487+ });
488+ input.addEventListener('keydown', function (e) {
489+ if (e.isComposing) return;
490+ if (e.key === 'ArrowDown') {
491+ e.preventDefault();
492+ setActive(active + 1);
493+ } else if (e.key === 'ArrowUp') {
494+ e.preventDefault();
495+ setActive(active - 1);
496+ } else if (e.key === 'Enter') {
497+ var opt = options()[active];
498+ if (opt) {
499+ e.preventDefault();
500+ opt.click();
501+ }
502+ }
503+ });
504+ results.addEventListener('mousemove', function (e) {
505+ var opt = e.target.closest('[role="option"]');
506+ if (!opt) return;
507+ var i = options().indexOf(opt);
508+ if (i !== active) setActive(i);
509+ });
510+ results.addEventListener('click', function (e) {
511+ var opt = e.target.closest('[role="option"]');
512+ if (!opt || opt.tagName === 'A') return;
513+ e.preventDefault();
514+ run(opt);
515+ });
516+ dialog.addEventListener('click', function (e) {
517+ if (e.target === dialog) dialog.close();
518+ });
519+ dialog.addEventListener('close', function () {
520+ clearTimeout(timer);
521+ if (controller) controller.abort();
522+ var back = opener;
523+ opener = null;
524+ if (back && back.isConnected && typeof back.focus === 'function') back.focus();
525+ });
526+})();
527+"#;
src/app/pane.rsadded+268 -0
@@ -0,0 +1,268 @@
1+//! The two-pane note layout shared by the note pages: the note list pane (header, rows
2+//! grouped by date, empty state), the detail pane, and the split that shows one pane at
3+//! a time below 1024px.
4+
5+use std::collections::HashMap;
6+
7+use topcoat::{
8+ context::Cx,
9+ view::{Child, View, attributes, view},
10+};
11+
12+use crate::app::shell::{notebook_name, now_millis, title_of};
13+use crate::components::button::{ButtonSize, ButtonVariant, button};
14+use crate::components::kbd::kbd;
15+use crate::i18n::{Lang, Msg, notes_count, relative_time, t};
16+use crate::store::{Notebook, NoteMeta};
17+
18+const DAY_MS: i64 = 86_400_000;
19+
20+/// Which pane shows below 1024px. Above it, both panes show.
21+#[derive(Clone, Copy, Debug, PartialEq, Eq)]
22+pub enum Mobile {
23+ /// A list page: the list shows, the detail is hidden.
24+ List,
25+ /// The note page: the detail shows, the list is hidden.
26+ Detail,
27+}
28+
29+/// One note row. `parts` is the text of the second line as `(text, highlighted)` runs.
30+pub struct Entry {
31+ pub href: String,
32+ pub title: String,
33+ pub when: String,
34+ pub parts: Vec<(String, bool)>,
35+ pub notebook: Option<String>,
36+ pub selected: bool,
37+}
38+
39+/// A date group of rows, with its section label.
40+pub struct Group {
41+ pub label: &'static str,
42+ pub entries: Vec<Entry>,
43+}
44+
45+/// What the list pane shows.
46+pub struct ListSpec {
47+ pub title: String,
48+ /// True on list pages (the page's one `<h1>`), false on the note page.
49+ pub heading: bool,
50+ pub count: usize,
51+ /// The notebook a "New note" from this list goes to. Empty for none.
52+ pub notebook_id: String,
53+ pub groups: Vec<Group>,
54+ /// The headline of the empty state, shown when there are no rows.
55+ pub empty: &'static str,
56+}
57+
58+/// Classes of a note row, and of the selected row (the highlighter swipe).
59+const ROW: &str = "flex min-h-14 flex-col justify-center gap-1 px-4 py-2 transition-colors hover:bg-foreground/5";
60+const ROW_SELECTED: &str = "marker flex min-h-14 flex-col justify-center gap-1 px-4 py-2";
61+const BADGE: &str = "shrink-0 rounded-[4px] border border-border px-1.5 font-mono text-[11px] leading-4 text-muted-foreground";
62+
63+/// Classes of a menu item that is a link, matching the menu items of `dropdown_menu`.
64+pub const MENU_LINK: &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 [&_svg]:size-4 [&_svg]:shrink-0";
65+
66+const LIST_SHOWN: &str = "flex min-h-0 w-full shrink-0 flex-col border-border lg:w-80 lg:border-r";
67+const LIST_HIDDEN: &str = "hidden min-h-0 shrink-0 flex-col border-border lg:flex lg:w-80 lg:border-r";
68+const DETAIL_SHOWN: &str = "flex min-h-0 min-w-0 flex-1 flex-col";
69+const DETAIL_HIDDEN: &str = "hidden min-h-0 min-w-0 flex-1 flex-col lg:flex";
70+
71+/// Splits a page into the list pane and the detail pane. `mobile` picks the pane that
72+/// shows below 1024px; both show above it.
73+pub fn split<'a>(cx: &'a Cx, mobile: Mobile, list: Child<'a>, detail: Child<'a>) -> impl View + 'a {
74+ let (list_class, detail_class) = match mobile {
75+ Mobile::List => (LIST_SHOWN, DETAIL_HIDDEN),
76+ Mobile::Detail => (LIST_HIDDEN, DETAIL_SHOWN),
77+ };
78+ view! { cx =>
79+ <div class="flex min-h-0 min-w-0 flex-1">
80+ <div class=(list_class)>(list)</div>
81+ <div class=(detail_class)>(detail)</div>
82+ </div>
83+ }
84+}
85+
86+/// Builds the rows for `notes` (already filtered and ordered, most recent first), grouped
87+/// by how long ago they were updated: Today, Yesterday, Previous 7 days, Earlier. Groups
88+/// with no rows are left out. Days are UTC.
89+pub fn groups(
90+ lang: Lang,
91+ notes: &[NoteMeta],
92+ notebooks: &[Notebook],
93+ previews: &HashMap<String, String>,
94+ selected: Option<&str>,
95+ show_notebook: bool,
96+) -> Vec<Group> {
97+ let now = now_millis();
98+ let today = now.div_euclid(DAY_MS);
99+ let labels = [
100+ t(lang, Msg::GroupToday),
101+ t(lang, Msg::Yesterday),
102+ t(lang, Msg::GroupPrevious7),
103+ t(lang, Msg::GroupEarlier),
104+ ];
105+ let mut buckets: [Vec<Entry>; 4] = Default::default();
106+ for note in notes {
107+ let age_days = today - note.updated_at.div_euclid(DAY_MS);
108+ let bucket = match age_days {
109+ i64::MIN..=0 => 0,
110+ 1 => 1,
111+ 2..=7 => 2,
112+ _ => 3,
113+ };
114+ let preview = previews.get(&note.id).cloned().unwrap_or_default();
115+ buckets[bucket].push(Entry {
116+ href: format!("/notes/{}", note.id),
117+ title: title_of(lang, &note.title),
118+ when: relative_time(lang, note.updated_at, now),
119+ parts: vec![(preview, false)],
120+ notebook: if show_notebook {
121+ notebook_name(notebooks, note.notebook_id.as_deref())
122+ } else {
123+ None
124+ },
125+ selected: selected == Some(note.id.as_str()),
126+ });
127+ }
128+ buckets
129+ .into_iter()
130+ .zip(labels)
131+ .filter(|(entries, _)| !entries.is_empty())
132+ .map(|(entries, label)| Group { label, entries })
133+ .collect()
134+}
135+
136+/// One note row: title and time on the first line, the excerpt and notebook badge on the
137+/// second. `two_lines` lets the excerpt wrap to two lines (search results) instead of
138+/// truncating it to one.
139+pub fn entry_item<'a>(cx: &'a Cx, entry: Entry, two_lines: bool) -> impl View + 'a {
140+ let Entry {
141+ href,
142+ title,
143+ when,
144+ parts,
145+ notebook,
146+ selected,
147+ } = entry;
148+ let class = if selected { ROW_SELECTED } else { ROW };
149+ let current = if selected { "true" } else { "false" };
150+ let excerpt = if two_lines {
151+ "min-w-0 flex-1 line-clamp-2 text-sm text-muted-foreground"
152+ } else {
153+ "min-w-0 flex-1 truncate text-sm text-muted-foreground"
154+ };
155+ view! { cx =>
156+ <li>
157+ <a href=(href) class=(class) aria-current=(current)>
158+ <span class="flex min-w-0 items-baseline gap-2">
159+ <span class="min-w-0 flex-1 truncate text-sm font-medium">(title)</span>
160+ <span class="shrink-0 font-mono text-xs text-muted-foreground">(when)</span>
161+ </span>
162+ if !parts.is_empty() {
163+ <span class="flex min-w-0 items-center gap-2">
164+ <span class=(excerpt)>
165+ for (text, matched) in parts {
166+ if matched {
167+ <mark class="rounded-[2px] bg-mark text-foreground">(text)</mark>
168+ } else {
169+ (text)
170+ }
171+ }
172+ </span>
173+ if let Some(name) = notebook {
174+ <span class=(BADGE)>(name)</span>
175+ }
176+ </span>
177+ }
178+ </a>
179+ </li>
180+ }
181+}
182+
183+/// The list pane: a header with the title, the count and `actions`, then the rows by
184+/// date group, or the empty state. "New note" shows here only below 1024px; the sidebar
185+/// has it on wide screens.
186+pub fn list_pane<'a>(cx: &'a Cx, lang: Lang, spec: ListSpec, actions: Child<'a>) -> impl View + 'a {
187+ let ListSpec {
188+ title,
189+ heading,
190+ count,
191+ notebook_id,
192+ groups,
193+ empty,
194+ } = spec;
195+ let count_text = notes_count(lang, count);
196+ let new_note = t(lang, Msg::NewNote);
197+ let create_hint = t(lang, Msg::CreateOneHint);
198+ let is_empty = groups.is_empty();
199+ view! { cx =>
200+ <section class="flex min-h-0 min-w-0 flex-1 flex-col">
201+ <header class="sidebar-lead flex shrink-0 items-center gap-2 border-b border-border px-4 py-3">
202+ <div class="min-w-0 flex-1">
203+ if heading {
204+ <h1 class="truncate text-base font-semibold">(title)</h1>
205+ } else {
206+ <h2 class="truncate text-base font-semibold">(title)</h2>
207+ }
208+ <p class="font-mono text-xs tabular-nums text-muted-foreground">(count_text)</p>
209+ </div>
210+ (actions)
211+ <form method="post" action="/notes" class="shrink-0 lg:hidden">
212+ <input type="hidden" name="notebook_id" value=(notebook_id)>
213+ button(
214+ variant: ButtonVariant::Primary,
215+ size: ButtonSize::Md,
216+ attrs: attributes! { type="submit" },
217+ keycap: Child::new(view! { kbd("N") }),
218+ (new_note)
219+ )
220+ </form>
221+ </header>
222+ <div class="min-h-0 flex-1 overflow-y-auto">
223+ if is_empty {
224+ <div class="flex flex-col items-center gap-2 px-6 py-12 text-center">
225+ <p class="text-sm font-medium">(empty)</p>
226+ <p class="flex items-center gap-2 text-sm text-muted-foreground">
227+ kbd("N")
228+ <span>(create_hint)</span>
229+ </p>
230+ </div>
231+ } else {
232+ for group in groups {
233+ <div class="pb-2">
234+ <p class="section-label px-4 pt-4 pb-1">(group.label)</p>
235+ <ul class="divide-y divide-border">
236+ for entry in group.entries {
237+ (Child::new(entry_item(cx, entry, false)))
238+ }
239+ </ul>
240+ </div>
241+ }
242+ }
243+ </div>
244+ </section>
245+ }
246+}
247+
248+/// The detail pane of a list page before a note is chosen: a quiet hint with the
249+/// shortcuts that work here.
250+pub fn empty_detail<'a>(cx: &'a Cx, lang: Lang) -> impl View + 'a {
251+ let new_note = t(lang, Msg::NewNote);
252+ let search = t(lang, Msg::Search);
253+ view! { cx =>
254+ <div class="flex flex-1 flex-col items-center justify-center gap-3 px-6 py-16 text-center">
255+ <p class="text-base font-medium">(t(lang, Msg::SelectNote))</p>
256+ <p class="flex flex-wrap items-center justify-center gap-x-5 gap-y-2 text-sm text-muted-foreground">
257+ <span class="inline-flex items-center gap-2">
258+ kbd("N")
259+ <span>(new_note)</span>
260+ </span>
261+ <span class="inline-flex items-center gap-2">
262+ kbd("/")
263+ <span>(search)</span>
264+ </span>
265+ </p>
266+ </div>
267+ }
268+}
src/app/scheme.rsadded+31 -0
@@ -0,0 +1,31 @@
1+use topcoat::{
2+ Result,
3+ context::Cx,
4+ cookie::{Cookies, cookies},
5+ router::{
6+ content::Form,
7+ error::{SeeOther, bad_request, see_other},
8+ route,
9+ },
10+};
11+
12+use super::lang::safe_back;
13+use crate::scheme::{Scheme, scheme_cookie};
14+
15+#[derive(serde::Deserialize)]
16+struct SchemeForm {
17+ scheme: String,
18+ /// Where to return to. Only a relative path on this site is accepted.
19+ #[serde(default)]
20+ back: String,
21+}
22+
23+/// POST /scheme: stores the chosen color scheme in a cookie and returns to the page it
24+/// was chosen on.
25+#[route(POST)]
26+async fn set_scheme(cx: &Cx, Form(form): Form<SchemeForm>) -> Result<SeeOther> {
27+ let scheme = Scheme::from_id(form.scheme.trim())
28+ .ok_or_else(|| bad_request("unsupported color scheme"))?;
29+ cookies(cx).add(scheme_cookie(scheme));
30+ Ok(see_other(safe_back(&form.back)))
31+}
src/app/search.rsadded+162 -0
@@ -0,0 +1,162 @@
1+//! GET /search?q=...: full-text search across note titles and bodies, inside the app shell.
2+
3+use std::sync::Arc;
4+
5+use topcoat::{
6+ Result,
7+ context::{Cx, app_context},
8+ router::{page, query_params},
9+ view::{Child, View, view},
10+};
11+
12+use crate::app::pane::{self, Entry};
13+use crate::app::shell::{now_millis, notebook_name, title_of};
14+use crate::i18n::{self, Msg, relative_time, results_for, t};
15+use crate::matcher::{Matcher, Options};
16+use crate::store::Store;
17+
18+/// Most results shown on one page.
19+const RESULT_LIMIT: usize = 50;
20+
21+/// 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".
23+#[query_params(error = bad_request)]
24+pub struct SearchQuery {
25+ pub q: Option<String>,
26+ pub case: Option<String>,
27+ pub word: Option<String>,
28+ pub exact: Option<String>,
29+ pub re: Option<String>,
30+}
31+
32+/// GET /search: notes whose title or text contain every word of `q`.
33+#[page]
34+async fn search(cx: &Cx) -> Result<impl View> {
35+ let store = app_context::<Arc<Store>>(cx);
36+ let query = query_params::<SearchQuery>(cx)?;
37+ let q = query.q.as_deref().unwrap_or("").trim().to_owned();
38+ let flag = |v: &Option<String>| v.as_deref() == Some("1");
39+ let opts = Options {
40+ case: flag(&query.case),
41+ word: flag(&query.word),
42+ exact: flag(&query.exact),
43+ regex: flag(&query.re),
44+ };
45+ let (matcher, invalid) = match Matcher::new(&q, opts) {
46+ Ok(m) => (m, false),
47+ Err(_) => (None, true),
48+ };
49+ if matcher.is_none() && !invalid {
50+ return Ok(Child::new(crate::app::all_notes(cx).await?));
51+ }
52+
53+ let hits = match &matcher {
54+ Some(m) => store
55+ .search(m, RESULT_LIMIT)
56+ .await
57+ .map_err(topcoat::Error::from_anyhow)?,
58+ None => Vec::new(),
59+ };
60+ let notebooks = store.list_notebooks().await.map_err(topcoat::Error::from_anyhow)?;
61+ let lang = i18n::lang(cx);
62+ let now = now_millis();
63+ let count = hits.len();
64+ let entries: Vec<Entry> = hits
65+ .into_iter()
66+ .map(|hit| {
67+ let title = title_of(lang, &hit.note.title);
68+ let excerpt = excerpt(&hit.snippet, &title);
69+ Entry {
70+ href: format!("/notes/{}", hit.note.id),
71+ when: relative_time(lang, hit.note.updated_at, now),
72+ parts: matcher.as_ref().map_or_else(Vec::new, |m| highlight(&excerpt, m)),
73+ notebook: notebook_name(&notebooks, hit.note.notebook_id.as_deref()),
74+ title,
75+ selected: false,
76+ }
77+ })
78+ .collect();
79+
80+ let title = t(lang, Msg::Search);
81+ // The filters in use, after the count: "2 results for “x” · Match case, Whole word".
82+ let active: Vec<&str> = [
83+ (opts.case, Msg::MatchCase),
84+ (opts.word, Msg::WholeWord),
85+ (opts.exact, Msg::ExactPhrase),
86+ (opts.regex, Msg::RegexSearch),
87+ ]
88+ .into_iter()
89+ .filter(|(on, _)| *on)
90+ .map(|(_, msg)| t(lang, msg))
91+ .collect();
92+ let summary = if active.is_empty() {
93+ results_for(lang, count, &q)
94+ } else {
95+ format!("{} · {}", results_for(lang, count, &q), active.join(", "))
96+ };
97+ let (no_matches, check) = if invalid {
98+ (t(lang, Msg::InvalidRegex), t(lang, Msg::InvalidRegexHint))
99+ } else {
100+ (t(lang, Msg::NoMatches), t(lang, Msg::CheckSpelling))
101+ };
102+
103+
104+ // Results take the list pane's place, like any other list of notes.
105+ let list = view! {
106+ <section class="flex min-h-0 min-w-0 flex-1 flex-col">
107+ <header class="sidebar-lead flex shrink-0 items-center gap-2 border-b border-border px-4 py-3">
108+ <div class="min-w-0 flex-1">
109+ <h1 class="truncate text-base font-semibold">(title)</h1>
110+ <p class="truncate text-xs text-muted-foreground">(summary)</p>
111+ </div>
112+ </header>
113+ <div class="min-h-0 flex-1 overflow-y-auto">
114+ if entries.is_empty() {
115+ <div class="flex flex-col items-center gap-2 px-6 py-12 text-center">
116+ <p class="text-sm font-medium">(no_matches)</p>
117+ <p class="text-sm text-muted-foreground">(check)</p>
118+ </div>
119+ } else {
120+ <ul class="divide-y divide-border">
121+ for entry in entries {
122+ (Child::new(pane::entry_item(cx, entry, true)))
123+ }
124+ </ul>
125+ }
126+ </div>
127+ </section>
128+ };
129+ Ok(Child::new(pane::split(
130+ cx,
131+ pane::Mobile::List,
132+ Child::new(list),
133+ Child::new(pane::empty_detail(cx, lang)),
134+ )))
135+}
136+
137+/// The excerpt without the note's title line, which the row already shows. When the
138+/// excerpt is only the title, the result is empty.
139+fn excerpt(snippet: &str, title: &str) -> String {
140+ match snippet.strip_prefix(title.trim()) {
141+ Some(rest) => rest.trim_start().to_owned(),
142+ None => snippet.to_owned(),
143+ }
144+}
145+
146+/// Splits `text` into runs, marking where `matcher` matches.
147+fn highlight(text: &str, matcher: &Matcher) -> Vec<(String, bool)> {
148+ let chars: Vec<char> = text.chars().collect();
149+ let mut parts = Vec::new();
150+ let mut at = 0;
151+ for (start, end) in matcher.ranges(text) {
152+ if start > at {
153+ parts.push((chars[at..start].iter().collect(), false));
154+ }
155+ parts.push((chars[start..end].iter().collect(), true));
156+ at = end;
157+ }
158+ if at < chars.len() {
159+ parts.push((chars[at..].iter().collect(), false));
160+ }
161+ parts
162+}
src/app/shell.rsadded+930 -0
@@ -0,0 +1,930 @@
1+//! The app shell pieces shared by every page: the head scripts and styles, the sidebar,
2+//! the toast region, the note rows, and the "New note" form.
3+
4+use std::time::{SystemTime, UNIX_EPOCH};
5+
6+use topcoat::{
7+ Result,
8+ view::{Child, View, attributes, component, view},
9+};
10+
11+use crate::components::button::{ButtonSize, ButtonVariant, button};
12+use crate::components::dropdown_menu::{
13+ dropdown_menu, dropdown_menu_content, dropdown_menu_item, dropdown_menu_label,
14+ dropdown_menu_separator,
15+ dropdown_menu_sub, dropdown_menu_sub_content, dropdown_menu_sub_trigger, dropdown_menu_trigger,
16+};
17+use crate::components::floating::{FloatingAlign, FloatingSide};
18+use crate::components::input::input;
19+use crate::components::kbd::{kbd, kbd_group};
20+use crate::components::segmented::{SEGMENT_ICON, TRACK};
21+use crate::i18n::{Lang, Msg, t};
22+use crate::scheme::{ALL as SCHEMES, Scheme};
23+use crate::store::Notebook;
24+
25+/// Runs before first paint. It applies the theme (light, dark, or system, stored in
26+/// localStorage as "theme") and the sidebar state ("sidebar"). The sidebar theme buttons
27+/// (`data-theme-set`) set the theme on click and keep `aria-pressed` in step with it.
28+/// `window.cycleTheme` steps through light, dark, and system for the command palette.
29+/// `html.no-anim` turns transitions off until the first frame, so a restored sidebar
30+/// state does not animate on load.
31+pub const THEME_SCRIPT: &str = r#"
32+(function () {
33+ var root = document.documentElement;
34+ var order = ['light', 'dark', 'system'];
35+ var mq = window.matchMedia('(prefers-color-scheme: dark)');
36+ root.classList.add('no-anim');
37+ function read(key, valid, fallback) {
38+ try {
39+ var v = localStorage.getItem(key);
40+ return valid.indexOf(v) >= 0 ? v : fallback;
41+ } catch (e) {
42+ return fallback;
43+ }
44+ }
45+ function syncThemeButtons() {
46+ var pref = root.dataset.theme;
47+ document.querySelectorAll('[data-theme-set]').forEach(function (btn) {
48+ btn.setAttribute('aria-pressed', btn.dataset.themeSet === pref ? 'true' : 'false');
49+ });
50+ }
51+ function applyTheme(pref) {
52+ root.dataset.theme = pref;
53+ root.classList.toggle('dark', pref === 'dark' || (pref === 'system' && mq.matches));
54+ syncThemeButtons();
55+ }
56+ function setTheme(pref) {
57+ try { localStorage.setItem('theme', pref); } catch (e) {}
58+ applyTheme(pref);
59+ }
60+ applyTheme(read('theme', order, 'system'));
61+ mq.addEventListener('change', function () {
62+ if (read('theme', order, 'system') === 'system') applyTheme('system');
63+ });
64+ window.cycleTheme = function () {
65+ setTheme(order[(order.indexOf(read('theme', order, 'system')) + 1) % order.length]);
66+ };
67+ window.syncThemeButtons = syncThemeButtons;
68+ document.addEventListener('click', function (e) {
69+ var btn = e.target.closest && e.target.closest('[data-theme-set]');
70+ if (btn) setTheme(btn.dataset.themeSet);
71+ });
72+ root.dataset.sidebar = read('sidebar', ['collapsed', 'expanded'], 'expanded');
73+ requestAnimationFrame(function () {
74+ requestAnimationFrame(function () { root.classList.remove('no-anim'); });
75+ });
76+})();
77+"#;
78+
79+/// Shell styles that depend on the viewport or on `data-*` state. Below 1024px the sidebar
80+/// is an off-canvas drawer that slides in and out with a fading backdrop; it stays
81+/// `visibility: hidden` (and `inert`, set by the script) until the slide-out ends. At
82+/// 1024px and up the sidebar collapses by animating its width to 0, with its fixed-width
83+/// body fading. `html.no-anim` suppresses transitions on the first frame. Reduced motion
84+/// disables all of it. Also: touch target sizes and cross-document view transitions.
85+pub const SHELL_STYLE: &str = r#"
86+@view-transition { navigation: auto; }
87+#sidebar {
88+ position: fixed; top: 0; bottom: 0; left: 0; z-index: 40;
89+ width: 240px; max-width: 85vw; height: 100dvh;
90+ transform: translateX(-100%); visibility: hidden;
91+ transition: transform 220ms cubic-bezier(.2,.8,.2,1), visibility 0s linear 220ms;
92+}
93+#sidebar[data-open="true"] {
94+ transform: none; visibility: visible;
95+ transition: transform 220ms cubic-bezier(.2,.8,.2,1), visibility 0s;
96+}
97+#drawer-backdrop {
98+ position: fixed; inset: 0; z-index: 30;
99+ background: color-mix(in srgb, var(--foreground) 30%, transparent);
100+ opacity: 0; visibility: hidden;
101+ transition: opacity 220ms ease, visibility 0s linear 220ms;
102+}
103+#drawer-backdrop[data-open="true"] {
104+ opacity: 1; visibility: visible;
105+ transition: opacity 220ms ease, visibility 0s;
106+}
107+#sidebar-expand { display: none; }
108+html.no-anim, html.no-anim *, html.no-anim *::before, html.no-anim *::after {
109+ transition: none !important;
110+}
111+@media (min-width: 1024px) {
112+ #sidebar {
113+ position: static; z-index: auto; max-width: none; height: auto; flex-shrink: 0;
114+ width: 240px; transform: none; visibility: visible;
115+ transition:
116+ width 200ms cubic-bezier(.2,.8,.2,1),
117+ border-right-width 200ms cubic-bezier(.2,.8,.2,1),
118+ visibility 200ms linear;
119+ }
120+ #sidebar > .sidebar-body { transition: opacity 150ms ease; }
121+ html[data-sidebar="collapsed"] #sidebar { width: 0; border-right-width: 0; visibility: hidden; }
122+ html[data-sidebar="collapsed"] #sidebar > .sidebar-body { opacity: 0; }
123+ html[data-sidebar="collapsed"] #sidebar-expand { display: inline-flex; }
124+ /* The list pane header reserves room for the floating expand button (12px inset, 32px wide, 8px gap). */
125+ .sidebar-lead { transition: padding-left 200ms cubic-bezier(.2,.8,.2,1); }
126+ html[data-sidebar="collapsed"] .sidebar-lead { padding-left: 3.25rem; }
127+ #drawer-backdrop { display: none; }
128+}
129+@media (max-width: 1023px) {
130+ #sidebar a, #sidebar button, #sidebar input, #sidebar-expand, #drawer-open, [data-close-drawer] { min-height: 40px; }
131+ input, select, textarea { font-size: 16px; }
132+}
133+@media (prefers-reduced-motion: reduce) {
134+ #sidebar, #sidebar[data-open="true"], #sidebar > .sidebar-body, .sidebar-lead, #drawer-backdrop, #drawer-backdrop[data-open="true"] {
135+ transition: none !important;
136+ }
137+}
138+"#;
139+
140+/// Global keyboard shortcuts and the small interactions of the shell: the mobile drawer
141+/// (opened from the top bar, closed by Esc, the backdrop, or its close button), sidebar
142+/// collapse, and toasts that hide after six seconds.
143+///
144+/// Shortcuts: Ctrl/Cmd+K opens the command palette (`window.openPalette`, Ctrl/Cmd+Shift+K
145+/// inside the editor), otherwise focuses the search box. "/" focuses search and "n" submits the New note form, both only when no
146+/// field is being typed in.
147+pub const SHELL_SCRIPT: &str = r#"
148+(function () {
149+ var root = document.documentElement;
150+ // Server renders times in UTC; show them in the viewer's own time zone.
151+ var fmt = new Intl.DateTimeFormat(root.lang || undefined, { dateStyle: 'medium', timeStyle: 'short' });
152+ document.querySelectorAll('time[data-ms]').forEach(function (el) {
153+ el.textContent = fmt.format(new Date(Number(el.dataset.ms)));
154+ });
155+ var sidebar = document.getElementById('sidebar');
156+ var backdrop = document.getElementById('drawer-backdrop');
157+ var openBtn = document.getElementById('drawer-open');
158+ var collapseBtn = document.getElementById('sidebar-collapse');
159+ var expandBtn = document.getElementById('sidebar-expand');
160+ var desktop = window.matchMedia('(min-width: 1024px)');
161+ var opener = null;
162+
163+ function isOpen() { return sidebar.dataset.open === 'true'; }
164+ function syncInert() { sidebar.inert = !desktop.matches && !isOpen(); }
165+ function setDrawer(open) {
166+ if (open === isOpen()) return;
167+ if (open) opener = document.activeElement;
168+ sidebar.dataset.open = open ? 'true' : 'false';
169+ backdrop.dataset.open = open ? 'true' : 'false';
170+ openBtn.setAttribute('aria-expanded', open ? 'true' : 'false');
171+ syncInert();
172+ // The drawer is still sliding in when focus moves, so keep the page from scrolling.
173+ if (open) {
174+ var first = sidebar.querySelector('[data-close-drawer]');
175+ if (first) first.focus({ preventScroll: true });
176+ } else if (opener && !desktop.matches) {
177+ opener.focus({ preventScroll: true });
178+ }
179+ }
180+ function isCollapsed() { return root.dataset.sidebar === 'collapsed'; }
181+ function setCollapsed(collapsed) {
182+ root.dataset.sidebar = collapsed ? 'collapsed' : 'expanded';
183+ try { localStorage.setItem('sidebar', root.dataset.sidebar); } catch (e) {}
184+ }
185+ function focusSearch() {
186+ if (desktop.matches && isCollapsed()) setCollapsed(false);
187+ if (!desktop.matches && !isOpen()) setDrawer(true);
188+ var input = document.getElementById('search-input');
189+ if (input) { input.focus(); input.select(); }
190+ }
191+
192+ // Live search: results replace the page content as you type, without a reload. An
193+ // empty box shows every note again. Enter still submits the form as a fallback.
194+ var searchBox = document.getElementById('search-input');
195+ if (searchBox && window.fetch && window.DOMParser) {
196+ var searchTimer = 0;
197+ var searchCtl = null;
198+ var searchSeq = 0;
199+ // Search filters (match case, whole word, exact phrase, regex). The results page's
200+ // URL says which are on; elsewhere the last choice is remembered.
201+ var OPTS = ['case', 'word', 'exact', 're'];
202+ var opts = {};
203+ var params = new URLSearchParams(location.search);
204+ var saved = {};
205+ try { saved = JSON.parse(localStorage.getItem('search-opts') || '{}'); } catch (e) {}
206+ OPTS.forEach(function (k) {
207+ opts[k] = location.pathname === '/search' ? params.get(k) === '1' : !!saved[k];
208+ });
209+ // The filter menu's checkboxes and the dot on its button follow `opts`.
210+ var syncOpts = function () {
211+ var any = false;
212+ document.querySelectorAll('[data-search-opt]').forEach(function (el) {
213+ el.setAttribute('aria-checked', opts[el.dataset.searchOpt] ? 'true' : 'false');
214+ });
215+ OPTS.forEach(function (k) { if (opts[k]) any = true; });
216+ var btn = document.getElementById('search-filter-button');
217+ if (btn) btn.toggleAttribute('data-active', any);
218+ };
219+ syncOpts();
220+ var runSearch = function () {
221+ var q = searchBox.value.trim();
222+ var url = '/';
223+ if (q) {
224+ url = '/search?q=' + encodeURIComponent(q);
225+ OPTS.forEach(function (k) { if (opts[k]) url += '&' + k + '=1'; });
226+ }
227+ if (searchCtl) searchCtl.abort();
228+ searchCtl = new AbortController();
229+ var seq = ++searchSeq;
230+ fetch(url, { signal: searchCtl.signal, headers: { accept: 'text/html' } })
231+ .then(function (res) { return res.text(); })
232+ .then(function (html) {
233+ if (seq !== searchSeq) return;
234+ var doc = new DOMParser().parseFromString(html, 'text/html');
235+ var next = doc.getElementById('main');
236+ var main = document.getElementById('main');
237+ if (!next || !main) return;
238+ window.dispatchEvent(new Event('note:detach'));
239+ main.innerHTML = next.innerHTML;
240+ document.title = doc.title;
241+ main.querySelectorAll('time[data-ms]').forEach(function (el) {
242+ el.textContent = fmt.format(new Date(Number(el.dataset.ms)));
243+ });
244+ // Keep the sidebar's current section in step with the page.
245+ // Links pair up by position; the sidebar has the same links on every page.
246+ var twins = doc.querySelectorAll('#sidebar a[href]');
247+ document.querySelectorAll('#sidebar a[href]').forEach(function (a, i) {
248+ var twin = twins[i];
249+ if (!twin || twin.getAttribute('href') !== a.getAttribute('href')) return;
250+ a.className = twin.className;
251+ if (twin.hasAttribute('aria-current')) a.setAttribute('aria-current', twin.getAttribute('aria-current'));
252+ else a.removeAttribute('aria-current');
253+ });
254+ // The first keystroke from another page adds a history entry; later ones
255+ // replace it, so Back leaves search in one step.
256+ var onResults = location.pathname === '/search' || history.state === 'live-search';
257+ history[onResults ? 'replaceState' : 'pushState']('live-search', '', url);
258+ })
259+ .catch(function () {});
260+ };
261+ searchBox.addEventListener('input', function () {
262+ clearTimeout(searchTimer);
263+ searchTimer = setTimeout(runSearch, 150);
264+ });
265+ var flip = function (key) {
266+ opts[key] = !opts[key];
267+ try { localStorage.setItem('search-opts', JSON.stringify(opts)); } catch (e) {}
268+ syncOpts();
269+ clearTimeout(searchTimer);
270+ if (searchBox.value.trim()) runSearch();
271+ };
272+ document.addEventListener('click', function (e) {
273+ var btn = e.target.closest && e.target.closest('[data-search-opt]');
274+ if (!btn) return;
275+ e.preventDefault();
276+ flip(btn.dataset.searchOpt);
277+ });
278+ // Alt+C / W / E / R toggle the filters from the search box, as in code editors.
279+ searchBox.addEventListener('keydown', function (e) {
280+ if (!e.altKey || e.ctrlKey || e.metaKey) return;
281+ var key = { KeyC: 'case', KeyW: 'word', KeyE: 'exact', KeyR: 're' }[e.code];
282+ if (!key) return;
283+ e.preventDefault();
284+ flip(key);
285+ });
286+ window.addEventListener('popstate', function () { location.reload(); });
287+ }
288+
289+ openBtn.addEventListener('click', function () { setDrawer(!isOpen()); });
290+ backdrop.addEventListener('click', function () { setDrawer(false); });
291+ document.querySelectorAll('[data-close-drawer]').forEach(function (btn) {
292+ btn.addEventListener('click', function () { setDrawer(false); });
293+ });
294+ if (collapseBtn) {
295+ collapseBtn.addEventListener('click', function () {
296+ setCollapsed(true);
297+ if (expandBtn) expandBtn.focus();
298+ });
299+ }
300+ if (expandBtn) {
301+ expandBtn.addEventListener('click', function () {
302+ setCollapsed(false);
303+ if (collapseBtn) collapseBtn.focus();
304+ });
305+ }
306+ desktop.addEventListener('change', function () {
307+ if (desktop.matches) {
308+ sidebar.dataset.open = 'false';
309+ backdrop.dataset.open = 'false';
310+ openBtn.setAttribute('aria-expanded', 'false');
311+ }
312+ syncInert();
313+ });
314+ syncInert();
315+ if (typeof window.syncThemeButtons === 'function') window.syncThemeButtons();
316+
317+ document.addEventListener('keydown', function (e) {
318+ if (e.key === 'Escape' && isOpen()) {
319+ e.preventDefault();
320+ setDrawer(false);
321+ return;
322+ }
323+ var el = document.activeElement;
324+ var typing = !!el && (el.isContentEditable || /^(INPUT|TEXTAREA|SELECT)$/.test(el.tagName));
325+ var mod = e.ctrlKey || e.metaKey;
326+ if (mod && !e.altKey && e.key.toLowerCase() === 'k') {
327+ // In the editor, Mod-K is the link shortcut; the palette takes Mod-Shift-K there.
328+ if (el && el.closest && el.closest('.ProseMirror') && !e.shiftKey) return;
329+ e.preventDefault();
330+ if (typeof window.openPalette === 'function') {
331+ window.openPalette();
332+ } else {
333+ var palette = document.getElementById('palette');
334+ if (palette) {
335+ if (typeof palette.showModal === 'function') palette.showModal();
336+ else palette.hidden = false;
337+ } else {
338+ focusSearch();
339+ }
340+ }
341+ return;
342+ }
343+ if (typing || mod || e.altKey) return;
344+ if (e.key === '/') {
345+ e.preventDefault();
346+ focusSearch();
347+ } else if (e.key === 'n' || e.key === 'N') {
348+ var form = document.getElementById('new-note-form');
349+ if (form) {
350+ e.preventDefault();
351+ form.requestSubmit();
352+ }
353+ }
354+ });
355+
356+ // Color scheme. The server puts data-scheme on <html> from the cookie. Choosing a scheme
357+ // (picker or palette) applies it at once and saves it with a POST to /scheme. Hovering or
358+ // focusing a picker row previews that scheme; closing the menu without a choice restores
359+ // the saved one. `window.setScheme` is shared with the command palette.
360+ var committed = root.dataset.scheme;
361+ var schemeMenu = document.getElementById('scheme-menu');
362+ function syncScheme() {
363+ var id = root.dataset.scheme;
364+ document.querySelectorAll('[data-scheme-current]').forEach(function (el) {
365+ el.hidden = el.dataset.schemeCurrent !== id;
366+ });
367+ document.querySelectorAll('[data-scheme-choice]').forEach(function (el) {
368+ el.setAttribute('aria-checked', el.dataset.schemeChoice === committed ? 'true' : 'false');
369+ });
370+ }
371+ function preview(id) {
372+ root.dataset.scheme = id;
373+ syncScheme();
374+ }
375+ window.setScheme = function (id) {
376+ committed = id;
377+ preview(id);
378+ fetch('/scheme', {
379+ method: 'POST',
380+ credentials: 'same-origin',
381+ redirect: 'manual',
382+ body: new URLSearchParams({ scheme: id, back: location.pathname + location.search })
383+ }).catch(function () {});
384+ };
385+ function rowScheme(e) {
386+ var item = e.target.closest && e.target.closest('[data-scheme-choice]');
387+ if (item) preview(item.dataset.schemeChoice);
388+ }
389+ if (schemeMenu) {
390+ schemeMenu.addEventListener('pointerover', rowScheme);
391+ schemeMenu.addEventListener('focusin', rowScheme);
392+ schemeMenu.addEventListener('toggle', function (e) {
393+ if (e.newState === 'closed') preview(committed);
394+ });
395+ }
396+ document.addEventListener('submit', function (e) {
397+ var form = e.target;
398+ var field = form.matches && form.matches('[data-scheme-form]') && form.querySelector('input[name="scheme"]');
399+ if (!field) return;
400+ e.preventDefault();
401+ window.setScheme(field.value);
402+ if (schemeMenu && schemeMenu.matches(':popover-open')) schemeMenu.hidePopover();
403+ });
404+ syncScheme();
405+
406+ document.querySelectorAll('#toasts [data-toast]').forEach(function (toast) {
407+ var timer = setTimeout(function () { toast.remove(); }, 6000);
408+ var dismiss = toast.querySelector('[data-dismiss]');
409+ if (dismiss) {
410+ dismiss.addEventListener('click', function () {
411+ clearTimeout(timer);
412+ toast.remove();
413+ });
414+ }
415+ });
416+})();
417+"#;
418+
419+pub fn now_millis() -> i64 {
420+ SystemTime::now()
421+ .duration_since(UNIX_EPOCH)
422+ .map(|d| d.as_millis() as i64)
423+ .unwrap_or(0)
424+}
425+
426+/// The note title, or "Untitled" in `lang` when it is blank.
427+pub fn title_of(lang: Lang, title: &str) -> String {
428+ if title.trim().is_empty() {
429+ t(lang, Msg::Untitled).to_owned()
430+ } else {
431+ title.trim().to_owned()
432+ }
433+}
434+
435+/// The name of the notebook with `id`, if it exists.
436+pub fn notebook_name(notebooks: &[Notebook], id: Option<&str>) -> Option<String> {
437+ let id = id?;
438+ notebooks.iter().find(|nb| nb.id == id).map(|nb| nb.name.clone())
439+}
440+
441+/// Where the user is, as far as the sidebar is concerned.
442+#[derive(Clone, PartialEq, Eq)]
443+pub enum Section {
444+ All,
445+ Unfiled,
446+ Trash,
447+ Notebook(String),
448+ /// A page that has no sidebar entry, such as search.
449+ Other,
450+}
451+
452+/// A notebook entry in the sidebar.
453+pub struct Shelf {
454+ pub id: String,
455+ pub name: String,
456+ pub count: usize,
457+}
458+
459+/// Everything the sidebar shows. Counts exclude trashed notes, except `trash`.
460+pub struct SidebarData {
461+ pub all: usize,
462+ pub unfiled: usize,
463+ pub trash: usize,
464+ pub notebooks: Vec<Shelf>,
465+ pub section: Section,
466+ /// The notebook a new note is created in. Empty for none.
467+ pub current_notebook: String,
468+ /// The search text, shown in the search box.
469+ pub query: String,
470+ /// Path and query to return to after a language change.
471+ pub back: String,
472+ /// The color scheme in effect, for the picker's button and checkmarks.
473+ pub scheme: Scheme,
474+}
475+
476+const NAV_ITEM: &str = "flex h-9 min-w-0 items-center gap-2 rounded-control px-2 text-sm transition-colors";
477+const NAV_IDLE: &str = "text-sidebar-foreground hover:bg-sidebar-accent hover:text-sidebar-accent-foreground";
478+const NAV_ACTIVE: &str = "marker font-medium";
479+const NAV_COUNT: &str = "ml-auto font-mono text-xs tabular-nums text-muted-foreground";
480+
481+/// One sidebar row: a link with an optional count. The active row gets the marker swipe
482+/// and `aria-current="page"`.
483+#[component]
484+async fn nav_item(href: String, label: String, count: usize, active: bool) -> Result<impl View> {
485+ let class = if active {
486+ format!("{NAV_ITEM} {NAV_ACTIVE}")
487+ } else {
488+ format!("{NAV_ITEM} {NAV_IDLE}")
489+ };
490+ let current = if active { "page" } else { "false" };
491+ Ok(view! {
492+ <a href=(href) class=(class) aria-current=(current)>
493+ <span class="min-w-0 truncate">(label)</span>
494+ <span class=(NAV_COUNT)>(count)</span>
495+ </a>
496+ })
497+}
498+
499+/// Three dots showing a scheme's sidebar, accent, and active row colors. The light and
500+/// dark colors go in as custom properties; `.dark` picks the dark one (see `styles.css`).
501+#[component]
502+async fn scheme_dots(scheme: Scheme) -> Result<impl View> {
503+ let dots: Vec<String> = scheme
504+ .dots()
505+ .iter()
506+ .map(|(light, dark)| format!("--dot-light:{light};--dot-dark:{dark}"))
507+ .collect();
508+ Ok(view! {
509+ <span class="scheme-dots" aria-hidden="true">
510+ for style in dots {
511+ <span class="scheme-dot" style=(style)></span>
512+ }
513+ </span>
514+ })
515+}
516+
517+/// The picker's button label: the scheme's name and dots. Every scheme has a label, and
518+/// the script shows the one for the current (or previewed) scheme.
519+#[component]
520+async fn scheme_label(scheme: Scheme, current: Scheme) -> Result<impl View> {
521+ Ok(view! {
522+ if scheme == current {
523+ <span class="flex min-w-0 flex-1 items-center gap-2" data-scheme-current=(scheme.id())>
524+ scheme_dots(scheme: scheme)
525+ <span class="min-w-0 truncate">(scheme.name())</span>
526+ </span>
527+ } else {
528+ <span class="flex min-w-0 flex-1 items-center gap-2" data-scheme-current=(scheme.id()) hidden="">
529+ scheme_dots(scheme: scheme)
530+ <span class="min-w-0 truncate">(scheme.name())</span>
531+ </span>
532+ }
533+ })
534+}
535+
536+/// Every scheme's label in the picker button. Only the current one is shown; the script
537+/// moves the `hidden` attribute when the scheme changes or is previewed.
538+#[component]
539+async fn scheme_names(current: Scheme) -> Result<impl View> {
540+ Ok(view! {
541+ for s in SCHEMES {
542+ scheme_label(scheme: s, current: current)
543+ }
544+ })
545+}
546+
547+/// One row per scheme in the picker's menu. Each row is a form that posts the choice to
548+/// `/scheme`; the script intercepts it and applies the scheme without a reload.
549+#[component]
550+async fn scheme_items(current: Scheme, back: String) -> Result<impl View> {
551+ let rows: Vec<(Scheme, &'static str)> = SCHEMES
552+ .into_iter()
553+ .map(|s| (s, if s == current { "true" } else { "false" }))
554+ .collect();
555+ Ok(view! {
556+ for (scheme, checked) in rows {
557+ <form method="post" action="/scheme" class="contents" data-scheme-form=(true)>
558+ <input type="hidden" name="scheme" value=(scheme.id())>
559+ <input type="hidden" name="back" value=(back.clone())>
560+ dropdown_menu_item(
561+ attrs: attributes! {
562+ type="submit"
563+ role="menuitemradio"
564+ aria-checked=(checked)
565+ data-scheme-choice=(scheme.id())
566+ class="justify-start"
567+ },
568+ scheme_dots(scheme: scheme)
569+ <span class="min-w-0 flex-1 truncate">(scheme.name())</span>
570+ <svg class="scheme-check size-4" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true">
571+ <path d="M20 6 9 17l-5-5"></path>
572+ </svg>
573+ )
574+ </form>
575+ }
576+ })
577+}
578+
579+/// The round initials badge of the profile button.
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`.
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+
584+/// 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.
586+/// Below 1024px it is an off-canvas drawer; above, it can be collapsed.
587+#[component]
588+pub async fn sidebar(lang: Lang, data: SidebarData) -> Result<impl View> {
589+ let SidebarData {
590+ all,
591+ unfiled,
592+ trash,
593+ notebooks,
594+ section,
595+ current_notebook,
596+ query,
597+ back,
598+ scheme,
599+ } = data;
600+ let is_all = section == Section::All;
601+ let is_unfiled = section == Section::Unfiled;
602+ let is_trash = section == Section::Trash;
603+ let shelves: Vec<(String, String, usize, bool)> = notebooks
604+ .into_iter()
605+ .map(|shelf| {
606+ let active = section == Section::Notebook(shelf.id.clone());
607+ (format!("/notebooks/{}", shelf.id), shelf.name, shelf.count, active)
608+ })
609+ .collect();
610+ let en_pressed = if lang == Lang::En { "true" } else { "false" };
611+ let tr_pressed = if lang == Lang::Tr { "true" } else { "false" };
612+ let app = t(lang, Msg::AppName);
613+ let theme_group = t(lang, Msg::Theme);
614+ let theme_light = t(lang, Msg::ThemeLight);
615+ let theme_system = t(lang, Msg::ThemeSystem);
616+ let theme_dark = t(lang, Msg::ThemeDark);
617+ let lang_group = t(lang, Msg::Language);
618+ let export_all = t(lang, Msg::ExportAll);
619+ let import_md = t(lang, Msg::ImportMarkdown);
620+ let color_scheme = t(lang, Msg::ColorScheme);
621+ let search_filters = t(lang, Msg::SearchOptions);
622+ let filters = [
623+ ("case", t(lang, Msg::MatchCase), "Alt+C"),
624+ ("word", t(lang, Msg::WholeWord), "Alt+W"),
625+ ("exact", t(lang, Msg::ExactPhrase), "Alt+E"),
626+ ("re", t(lang, Msg::RegexSearch), "Alt+R"),
627+ ];
628+ let account_menu = t(lang, Msg::AccountMenu);
629+ let guest = t(lang, Msg::GuestName);
630+ let guest_sub = t(lang, Msg::GuestSubtitle);
631+ let initials = &guest[..guest.chars().next().map_or(0, char::len_utf8)];
632+ let lang_code = lang.code().to_uppercase();
633+
634+ // The nav is the animated box (width on desktop, slide on mobile). The body inside
635+ // has a fixed width so its contents never reflow while the box animates.
636+ Ok(view! {
637+ <nav
638+ id="sidebar"
639+ aria-label=(t(lang, Msg::MainNavigation))
640+ class="flex min-h-0 overflow-hidden border-r border-sidebar-border bg-sidebar text-sidebar-foreground"
641+ >
642+ <div class="sidebar-body flex min-h-0 w-[240px] shrink-0 flex-col gap-3 p-3">
643+ <div class="flex h-9 items-center justify-between gap-2 pl-2">
644+ <a href="/" class="text-base font-semibold tracking-tight">(app)</a>
645+ <button
646+ id="sidebar-collapse"
647+ type="button"
648+ aria-controls="sidebar"
649+ aria-label=(t(lang, Msg::HideSidebar))
650+ class="hidden size-8 items-center justify-center rounded-control text-muted-foreground transition-colors hover:bg-foreground/8 hover:text-foreground active:bg-foreground/12 lg:inline-flex"
651+ >
652+ <svg class="size-4" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true">
653+ <rect x="3" y="3" width="18" height="18" rx="2"></rect>
654+ <path d="M9 3v18"></path>
655+ </svg>
656+ </button>
657+ <button
658+ type="button"
659+ data-close-drawer=(true)
660+ aria-label=(t(lang, Msg::CloseMenu))
661+ class="inline-flex size-10 items-center justify-center rounded-control text-foreground transition-colors hover:bg-sidebar-accent lg:hidden"
662+ >
663+ <svg class="size-5" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true">
664+ <path d="M18 6 6 18M6 6l12 12"></path>
665+ </svg>
666+ </button>
667+ </div>
668+
669+ <form method="get" action="/search" role="search" class="relative">
670+ input(attrs: attributes! {
671+ type="search"
672+ name="q"
673+ id="search-input"
674+ value=(query)
675+ placeholder=(t(lang, Msg::SearchPlaceholder))
676+ aria-label=(t(lang, Msg::SearchLabel))
677+ autocomplete="off"
678+ class="h-8 pr-[6.25rem]"
679+ })
680+ <span class="search-hint pointer-events-none absolute top-1/2 right-8 -translate-y-1/2" aria-hidden="true">
681+ kbd_group(kbd("Ctrl") kbd("K"))
682+ </span>
683+ // Search filters: a checkbox menu behind a filter icon, as in mail and
684+ // issue trackers. A dot on the icon says some filter is on.
685+ dropdown_menu(
686+ dropdown_menu_trigger(
687+ target: "search-filters",
688+ attrs: attributes! {
689+ id="search-filter-button"
690+ aria-label=(search_filters)
691+ title=(search_filters)
692+ class="group/filter absolute top-1/2 right-1 inline-flex size-6 -translate-y-1/2 items-center justify-center rounded-[5px] text-muted-foreground transition-colors hover:bg-foreground/8 hover:text-foreground data-active:text-foreground"
693+ },
694+ <svg class="size-3.5" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true">
695+ <path d="M3 6h18M7 12h10M10 18h4"></path>
696+ </svg>
697+ <span class="absolute top-0.5 right-0.5 hidden size-1.5 rounded-full bg-[var(--ring)] group-data-active/filter:block"></span>
698+ )
699+ dropdown_menu_content(
700+ id: "search-filters",
701+ align: FloatingAlign::End,
702+ attrs: attributes! { role="menu" aria-label=(search_filters) class="w-60" },
703+ dropdown_menu_label((search_filters))
704+ for (key, label, keys) in filters {
705+ dropdown_menu_item(
706+ attrs: attributes! {
707+ role="menuitemcheckbox"
708+ aria-checked="false"
709+ data-search-opt=(key)
710+ },
711+ <span class="filter-box">
712+ <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="3" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true"><path d="M20 6 9 17l-5-5"></path></svg>
713+ </span>
714+ <span class="min-w-0 flex-1 truncate">(label)</span>
715+ <span class="font-mono text-[11px] text-muted-foreground">(keys)</span>
716+ )
717+ }
718+ )
719+ )
720+ </form>
721+
722+ <form id="new-note-form" method="post" action="/notes">
723+ <input type="hidden" name="notebook_id" value=(current_notebook)>
724+ button(
725+ variant: ButtonVariant::Primary,
726+ size: ButtonSize::Md,
727+ attrs: attributes! { type="submit" class="w-full justify-between" },
728+ keycap: Child::new(view! { kbd("N") }),
729+ (t(lang, Msg::NewNote))
730+ )
731+ </form>
732+
733+ <ul class="flex flex-col gap-0.5">
734+ <li>
735+ nav_item(href: "/".to_owned(), label: t(lang, Msg::AllNotes).to_owned(), count: all, active: is_all)
736+ </li>
737+ <li>
738+ nav_item(href: "/unfiled".to_owned(), label: t(lang, Msg::Unfiled).to_owned(), count: unfiled, active: is_unfiled)
739+ </li>
740+ <li>
741+ nav_item(href: "/trash".to_owned(), label: t(lang, Msg::Trash).to_owned(), count: trash, active: is_trash)
742+ </li>
743+ </ul>
744+
745+ <div class="flex min-h-0 flex-1 flex-col gap-0.5 overflow-y-auto">
746+ <p class="section-label px-2 pt-2 pb-1">(t(lang, Msg::Notebooks))</p>
747+ <ul class="flex flex-col gap-0.5">
748+ for (href, name, count, active) in shelves {
749+ <li>
750+ nav_item(href: href, label: name, count: count, active: active)
751+ </li>
752+ }
753+ </ul>
754+ <form method="post" action="/notebooks" class="mt-2 flex items-center gap-1.5 px-1">
755+ input(attrs: attributes! {
756+ type="text"
757+ name="name"
758+ maxlength="120"
759+ placeholder=(t(lang, Msg::NewNotebook))
760+ aria-label=(t(lang, Msg::NewNotebookLabel))
761+ autocomplete="off"
762+ class="min-w-0 flex-1"
763+ })
764+ button(
765+ variant: ButtonVariant::Secondary,
766+ size: ButtonSize::Sm,
767+ attrs: attributes! { type="submit" },
768+ (t(lang, Msg::Add))
769+ )
770+ </form>
771+ </div>
772+
773+ // Profile button: everything that isn't navigation lives in its menu.
774+ <div class="border-t border-sidebar-border pt-2">
775+ dropdown_menu(
776+ dropdown_menu_trigger(
777+ target: "account-menu",
778+ attrs: attributes! {
779+ aria-label=(account_menu)
780+ class="flex w-full min-w-0 items-center gap-2.5 rounded-control p-1.5 text-left transition-colors hover:bg-sidebar-accent group-has-[:popover-open]/dropdown-menu:bg-sidebar-accent"
781+ },
782+ <span class=(AVATAR)>(initials)</span>
783+ <span class="flex min-w-0 flex-1 flex-col">
784+ <span class="truncate text-sm font-medium text-sidebar-foreground">(guest)</span>
785+ <span class="truncate text-xs text-muted-foreground">(guest_sub)</span>
786+ </span>
787+ <svg class="size-4 shrink-0 text-muted-foreground" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true"><path d="m9 18 6-6-6-6"></path></svg>
788+ )
789+ dropdown_menu_content(
790+ id: "account-menu",
791+ side: FloatingSide::Right,
792+ align: FloatingAlign::End,
793+ attrs: attributes! { role="menu" aria-label=(account_menu) class="w-64" },
794+ <div class="flex items-center gap-2.5 rounded-md bg-foreground/4 p-2">
795+ <span class=(AVATAR)>(initials)</span>
796+ <span class="flex min-w-0 flex-col">
797+ <span class="truncate text-sm font-medium">(guest)</span>
798+ <span class="truncate text-xs text-muted-foreground">(guest_sub)</span>
799+ </span>
800+ </div>
801+ dropdown_menu_separator()
802+ <a href="/import" role="menuitem" class=(MENU_ROW)>
803+ <svg class="size-4 shrink-0 text-muted-foreground" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true"><path d="M21 15v4a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2v-4"></path><path d="m17 8-5-5-5 5"></path><path d="M12 3v12"></path></svg>
804+ <span class="min-w-0 flex-1 truncate">(import_md)</span>
805+ </a>
806+ <a href="/export.zip" role="menuitem" class=(MENU_ROW)>
807+ <svg class="size-4 shrink-0 text-muted-foreground" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true"><path d="M21 15v4a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2v-4"></path><path d="m7 10 5 5 5-5"></path><path d="M12 15V3"></path></svg>
808+ <span class="min-w-0 flex-1 truncate">(export_all)</span>
809+ </a>
810+ dropdown_menu_separator()
811+ dropdown_menu_sub(
812+ dropdown_menu_sub_trigger(
813+ target: "scheme-menu",
814+ attrs: attributes! { role="menuitem" aria-haspopup="menu" },
815+ <svg class="size-4 shrink-0 text-muted-foreground" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true"><circle cx="13.5" cy="6.5" r="1.5"></circle><circle cx="17.5" cy="10.5" r="1.5"></circle><circle cx="8.5" cy="7.5" r="1.5"></circle><circle cx="6.5" cy="12.5" r="1.5"></circle><path d="M12 2a10 10 0 0 0 0 20 2 2 0 0 0 2-2v-.5a2 2 0 0 1 2-2h1.5A4.5 4.5 0 0 0 22 13 10 10 0 0 0 12 2Z"></path></svg>
816+ <span class="min-w-0 flex-1 truncate">(color_scheme)</span>
817+ <span class="flex max-w-24 min-w-0 items-center text-xs text-muted-foreground">
818+ scheme_names(current: scheme)
819+ </span>
820+ )
821+ dropdown_menu_sub_content(
822+ id: "scheme-menu",
823+ attrs: attributes! { role="menu" aria-label=(color_scheme) class="w-56" },
824+ scheme_items(current: scheme, back: back.clone())
825+ )
826+ )
827+ dropdown_menu_sub(
828+ dropdown_menu_sub_trigger(
829+ target: "lang-menu",
830+ attrs: attributes! { role="menuitem" aria-haspopup="menu" },
831+ <svg class="size-4 shrink-0 text-muted-foreground" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true"><circle cx="12" cy="12" r="10"></circle><path d="M2 12h20M12 2a15.3 15.3 0 0 1 4 10 15.3 15.3 0 0 1-4 10 15.3 15.3 0 0 1-4-10 15.3 15.3 0 0 1 4-10Z"></path></svg>
832+ <span class="min-w-0 flex-1 truncate">(lang_group)</span>
833+ <span class="font-mono text-xs text-muted-foreground">(lang_code)</span>
834+ )
835+ dropdown_menu_sub_content(
836+ id: "lang-menu",
837+ attrs: attributes! { role="menu" aria-label=(lang_group) class="w-44" },
838+ <form method="post" action="/lang" class="contents">
839+ <input type="hidden" name="lang" value="en">
840+ <input type="hidden" name="back" value=(back.clone())>
841+ dropdown_menu_item(
842+ attrs: attributes! { type="submit" role="menuitemradio" aria-checked=(en_pressed) lang="en" },
843+ <span class="min-w-0 flex-1">(t(lang, Msg::LanguageEnglish))</span>
844+ <svg class="scheme-check size-4" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true"><path d="M20 6 9 17l-5-5"></path></svg>
845+ )
846+ </form>
847+ <form method="post" action="/lang" class="contents">
848+ <input type="hidden" name="lang" value="tr">
849+ <input type="hidden" name="back" value=(back.clone())>
850+ dropdown_menu_item(
851+ attrs: attributes! { type="submit" role="menuitemradio" aria-checked=(tr_pressed) lang="tr" },
852+ <span class="min-w-0 flex-1">(t(lang, Msg::LanguageTurkish))</span>
853+ <svg class="scheme-check size-4" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true"><path d="M20 6 9 17l-5-5"></path></svg>
854+ )
855+ </form>
856+ )
857+ )
858+ dropdown_menu_separator()
859+ <div class="flex items-center justify-between gap-2 px-2 py-1">
860+ <span class="text-sm font-semibold tracking-tight">(app)</span>
861+ <div role="group" aria-label=(theme_group) class=(TRACK)>
862+ <button type="button" data-theme-set="light" aria-label=(theme_light) title=(theme_light) aria-pressed="false" class=(SEGMENT_ICON)>
863+ <svg class="size-3.5" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true">
864+ <circle cx="12" cy="12" r="4"></circle>
865+ <path d="M12 2v2M12 20v2M4.93 4.93l1.41 1.41M17.66 17.66l1.41 1.41M2 12h2M20 12h2M6.34 17.66l-1.41 1.41M19.07 4.93l-1.41 1.41"></path>
866+ </svg>
867+ </button>
868+ <button type="button" data-theme-set="system" aria-label=(theme_system) title=(theme_system) aria-pressed="false" class=(SEGMENT_ICON)>
869+ <svg class="size-3.5" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true">
870+ <rect x="2" y="3" width="20" height="14" rx="2"></rect>
871+ <path d="M8 21h8M12 17v4"></path>
872+ </svg>
873+ </button>
874+ <button type="button" data-theme-set="dark" aria-label=(theme_dark) title=(theme_dark) aria-pressed="false" class=(SEGMENT_ICON)>
875+ <svg class="size-3.5" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true">
876+ <path d="M12 3a6 6 0 0 0 9 9 9 9 0 1 1-9-9Z"></path>
877+ </svg>
878+ </button>
879+ </div>
880+ </div>
881+ )
882+ )
883+ </div>
884+ </div>
885+ </nav>
886+ })
887+}
888+
889+/// The toast region: a polite live region in the bottom-right corner. `message` is the
890+/// localized text; `undo` is the note id to restore, shown as an Undo button.
891+#[component]
892+pub async fn toast_region(lang: Lang, message: Option<&'static str>, undo: Option<String>) -> Result<impl View> {
893+ Ok(view! {
894+ <div
895+ id="toasts"
896+ role="status"
897+ aria-live="polite"
898+ class="pointer-events-none fixed inset-x-0 bottom-0 z-50 flex flex-col items-end gap-2 p-4 pb-[max(1rem,env(safe-area-inset-bottom))] pr-[max(1rem,env(safe-area-inset-right))]"
899+ >
900+ if let Some(text) = message {
901+ <div
902+ data-toast=(true)
903+ class="pointer-events-auto flex max-w-sm items-center gap-2 rounded-float border border-border bg-popover px-3 py-2 text-sm text-popover-foreground shadow-float"
904+ >
905+ <span class="min-w-0 flex-1">(text)</span>
906+ if let Some(id) = undo {
907+ <form method="post" action=(format!("/notes/{id}/restore"))>
908+ button(
909+ variant: ButtonVariant::Ghost,
910+ size: ButtonSize::Sm,
911+ attrs: attributes! { type="submit" },
912+ (t(lang, Msg::Undo))
913+ )
914+ </form>
915+ }
916+ <button
917+ type="button"
918+ data-dismiss=(true)
919+ aria-label=(t(lang, Msg::Dismiss))
920+ class="inline-flex size-8 items-center justify-center rounded-control text-muted-foreground transition-colors hover:bg-foreground/5 hover:text-foreground"
921+ >
922+ <svg class="size-4" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true">
923+ <path d="M18 6 6 18M6 6l12 12"></path>
924+ </svg>
925+ </button>
926+ </div>
927+ }
928+ </div>
929+ })
930+}
src/app/trash.rsadded+171 -0
@@ -0,0 +1,171 @@
1+//! The trash: trashed notes with Restore and Delete forever, and Empty trash.
2+
3+use std::sync::Arc;
4+
5+use topcoat::{
6+ Result,
7+ context::{Cx, app_context},
8+ router::{
9+ error::{SeeOther, see_other},
10+ page, route,
11+ },
12+ view::{View, attributes, view},
13+};
14+
15+use crate::app::shell::now_millis;
16+use crate::components::button::{ButtonSize, ButtonVariant, button};
17+use crate::components::dialog::{
18+ dialog, dialog_content, dialog_description, dialog_footer, dialog_header, dialog_title,
19+};
20+use crate::hub::Hub;
21+use crate::i18n::{self, Msg, forever_count, notes_count, relative_time, t};
22+use crate::store::Store;
23+
24+mod note_id;
25+
26+/// GET /trash: trashed notes, most recently trashed first.
27+#[page]
28+async fn trash(cx: &Cx) -> Result<impl View> {
29+ let store = app_context::<Arc<Store>>(cx);
30+ let trashed = store.list_trash().await.map_err(topcoat::Error::from_anyhow)?;
31+ let previews = store.previews().await.map_err(topcoat::Error::from_anyhow)?;
32+ let lang = i18n::lang(cx);
33+ let now = now_millis();
34+ let count = trashed.len();
35+ let title = t(lang, Msg::Trash);
36+ let count_text = notes_count(lang, count);
37+ let retention = t(lang, Msg::TrashRetention);
38+ let empty_label = t(lang, Msg::EmptyTrashAction);
39+ let empty_title = t(lang, Msg::ConfirmEmptyTrashTitle);
40+ let empty_body = forever_count(lang, count);
41+ let cancel = t(lang, Msg::Cancel);
42+ let restore_label = t(lang, Msg::Restore);
43+ let forever_label = t(lang, Msg::DeleteForever);
44+ let forever_title = t(lang, Msg::ConfirmForeverTitle);
45+ let cannot_undo = t(lang, Msg::CannotUndo);
46+ let trashed_word = t(lang, Msg::Trashed);
47+
48+ Ok(view! {
49+ <div class="mx-auto flex w-full max-w-3xl flex-col">
50+ <header class="flex flex-wrap items-start justify-between gap-4 border-b border-border px-4 py-5 lg:px-8">
51+ <div class="min-w-0">
52+ <h1 class="text-xl font-semibold tracking-tight">(title)</h1>
53+ <p class="font-mono text-xs tabular-nums text-muted-foreground">(count_text)</p>
54+ <p class="mt-1 text-sm text-muted-foreground">(retention)</p>
55+ </div>
56+ if count > 0 {
57+ button(
58+ variant: ButtonVariant::Destructive,
59+ size: ButtonSize::Sm,
60+ attrs: attributes! {
61+ type="button"
62+ onclick="document.getElementById('empty-trash').showModal()"
63+ },
64+ (empty_label)
65+ )
66+ }
67+ </header>
68+ if count == 0 {
69+ <div class="flex flex-col items-center gap-2 px-6 py-16 text-center">
70+ <p class="text-base font-medium">(t(lang, Msg::EmptyTrash))</p>
71+ </div>
72+ } else {
73+ <ul class="divide-y divide-border">
74+ for note in trashed {
75+ <li class="flex flex-wrap items-center gap-3 px-4 py-3 lg:px-8">
76+ <div class="min-w-0 flex-1">
77+ <p class="truncate text-sm font-medium">(crate::app::shell::title_of(lang, &note.title))</p>
78+ <p class="truncate text-sm text-muted-foreground">(previews.get(&note.id).cloned().unwrap_or_default())</p>
79+ <p class="font-mono text-xs text-muted-foreground">
80+ (format!("{trashed_word} · {}", relative_time(lang, note.trashed_at.unwrap_or(note.updated_at), now)))
81+ </p>
82+ </div>
83+ <form method="post" action=(format!("/notes/{}/restore", note.id))>
84+ button(
85+ variant: ButtonVariant::Outline,
86+ size: ButtonSize::Sm,
87+ attrs: attributes! { type="submit" },
88+ (restore_label)
89+ )
90+ </form>
91+ button(
92+ variant: ButtonVariant::Destructive,
93+ size: ButtonSize::Sm,
94+ attrs: attributes! {
95+ type="button"
96+ onclick=(format!("document.getElementById('forever-{}').showModal()", note.id))
97+ },
98+ (forever_label)
99+ )
100+ dialog(
101+ open: false,
102+ attrs: attributes! {
103+ id=(format!("forever-{}", note.id))
104+ aria-labelledby=(format!("forever-title-{}", note.id))
105+ },
106+ dialog_content(
107+ <form method="post" action=(format!("/trash/{}/delete", note.id)) class="flex flex-col gap-4">
108+ dialog_header(
109+ dialog_title(attrs: attributes! { id=(format!("forever-title-{}", note.id)) }, (forever_title))
110+ dialog_description((cannot_undo))
111+ )
112+ dialog_footer(
113+ button(
114+ variant: ButtonVariant::Outline,
115+ attrs: attributes! { type="submit" formmethod="dialog" autofocus=(true) },
116+ (cancel)
117+ )
118+ button(
119+ variant: ButtonVariant::Destructive,
120+ attrs: attributes! { type="submit" },
121+ (forever_label)
122+ )
123+ )
124+ </form>
125+ )
126+ )
127+ </li>
128+ }
129+ </ul>
130+ }
131+ if count > 0 {
132+ dialog(
133+ open: false,
134+ attrs: attributes! { id="empty-trash" aria-labelledby="empty-trash-title" aria-describedby="empty-trash-body" },
135+ dialog_content(
136+ <form method="post" action="/trash/empty" class="flex flex-col gap-4">
137+ dialog_header(
138+ dialog_title(attrs: attributes! { id="empty-trash-title" }, (empty_title))
139+ dialog_description(attrs: attributes! { id="empty-trash-body" }, (empty_body))
140+ )
141+ dialog_footer(
142+ button(
143+ variant: ButtonVariant::Outline,
144+ attrs: attributes! { type="submit" formmethod="dialog" autofocus=(true) },
145+ (cancel)
146+ )
147+ button(
148+ variant: ButtonVariant::Destructive,
149+ attrs: attributes! { type="submit" },
150+ (empty_label)
151+ )
152+ )
153+ </form>
154+ )
155+ )
156+ }
157+ </div>
158+ })
159+}
160+
161+/// POST /trash/empty: deletes every trashed note for good.
162+#[route(POST "./empty")]
163+async fn empty_trash(cx: &Cx) -> Result<SeeOther> {
164+ let store = app_context::<Arc<Store>>(cx);
165+ let hub = app_context::<Arc<Hub>>(cx);
166+ let ids = store.empty_trash().await.map_err(topcoat::Error::from_anyhow)?;
167+ for id in &ids {
168+ hub.forget(id);
169+ }
170+ Ok(see_other("/trash"))
171+}
src/app/trash/note_id.rsadded+35 -0
@@ -0,0 +1,35 @@
1+use std::sync::Arc;
2+
3+use topcoat::{
4+ Result,
5+ context::{Cx, app_context},
6+ router::{
7+ error::{RouterErrorExt, SeeOther, bad_request, see_other},
8+ module_param, path_param, route,
9+ },
10+};
11+
12+use crate::hub::Hub;
13+use crate::store::Store;
14+
15+module_param!(note_id);
16+
17+/// POST /trash/{note_id}/delete: deletes a trashed note for good. A note that is not in
18+/// the trash cannot be deleted from here.
19+#[route(POST "./delete")]
20+async fn delete_forever(cx: &Cx) -> Result<SeeOther> {
21+ let store = app_context::<Arc<Store>>(cx);
22+ let hub = app_context::<Arc<Hub>>(cx);
23+ let id = path_param::<NoteId>(cx).to_owned();
24+ let meta = store
25+ .get_note(&id)
26+ .await
27+ .map_err(topcoat::Error::from_anyhow)?
28+ .ok_or_not_found()?;
29+ if meta.trashed_at.is_none() {
30+ return Err(bad_request("the note is not in the trash").into());
31+ }
32+ store.delete_note(&id).await.map_err(topcoat::Error::from_anyhow)?;
33+ hub.forget(&id);
34+ Ok(see_other("/trash"))
35+}
src/app/unfiled.rsadded+38 -0
@@ -0,0 +1,38 @@
1+use std::sync::Arc;
2+
3+use topcoat::{
4+ Result,
5+ context::{Cx, app_context},
6+ router::page,
7+ view::{Child, View},
8+};
9+
10+use crate::app::pane::{self, ListSpec, Mobile};
11+use crate::i18n::{self, Msg, t};
12+use crate::store::Store;
13+
14+/// GET /unfiled: notes that are not in any notebook, beside the list.
15+#[page]
16+async fn unfiled(cx: &Cx) -> Result<impl View> {
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)?;
20+ let previews = store.previews().await.map_err(topcoat::Error::from_anyhow)?;
21+ let lang = i18n::lang(cx);
22+ let loose: Vec<_> = notes.into_iter().filter(|n| n.notebook_id.is_none()).collect();
23+ let spec = ListSpec {
24+ title: t(lang, Msg::Unfiled).to_owned(),
25+ heading: true,
26+ count: loose.len(),
27+ notebook_id: String::new(),
28+ groups: pane::groups(lang, &loose, &notebooks, &previews, None, false),
29+ empty: t(lang, Msg::EmptyUnfiled),
30+ };
31+ let list = pane::list_pane(cx, lang, spec, Child::new(()));
32+ Ok(pane::split(
33+ cx,
34+ Mobile::List,
35+ Child::new(list),
36+ Child::new(pane::empty_detail(cx, lang)),
37+ ))
38+}
src/components.rsadded+10 -0
@@ -0,0 +1,10 @@
1+pub mod button;
2+pub mod input;
3+pub mod badge;
4+pub mod dialog;
5+pub mod dropdown_menu;
6+pub mod tooltip;
7+pub mod separator;
8+pub mod kbd;
9+pub mod floating;
10+pub mod segmented;
src/components/badge.rsadded+78 -0
@@ -0,0 +1,78 @@
1+use topcoat::{
2+ Result,
3+ view::{Attributes, Child, Class, StaticClass, View, class, component, view},
4+};
5+
6+/// The visual style of a [`badge`].
7+///
8+/// [`Default`] is `BadgeVariant::Primary`, used when no variant is given.
9+#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
10+#[allow(dead_code)]
11+pub enum BadgeVariant {
12+ /// The highlighter-filled badge for highlighted statuses.
13+ #[default]
14+ Primary,
15+ /// A quiet tinted badge for neutral labels such as notebook names.
16+ Secondary,
17+ /// A hairline-bordered badge on the card surface.
18+ Outline,
19+ /// A red-tinted badge for errors.
20+ Destructive,
21+}
22+
23+impl BadgeVariant {
24+ /// Classes for the variant, including its border color. Keep border colors out of
25+ /// the shared base to avoid conflicting classes.
26+ fn classes(self) -> StaticClass {
27+ match self {
28+ Self::Primary => class!("border-transparent bg-primary text-primary-foreground"),
29+ Self::Secondary => class!("border-transparent bg-foreground/5 text-muted-foreground"),
30+ Self::Outline => class!("border-border bg-card text-muted-foreground"),
31+ Self::Destructive => class!("border-bad/40 bg-bad/10 text-bad"),
32+ }
33+ }
34+}
35+
36+/// Classes shared by badge variants. Badges use the mono face at 11px.
37+const BASE: StaticClass = class!(
38+ "inline-flex w-fit shrink-0 items-center justify-center gap-1 rounded-control",
39+ "border px-1.5 py-px font-mono text-[11px] leading-4 font-medium whitespace-nowrap",
40+);
41+
42+/// Builds the full class list for a badge of the given `variant`.
43+///
44+/// Use it to give badge styling to another element, such as a link:
45+///
46+/// ```ignore
47+/// view! {
48+/// <a href="/releases/v2" class=(badge_variants(BadgeVariant::Outline))>"v2.0"</a>
49+/// }
50+/// ```
51+#[must_use]
52+pub fn badge_variants(variant: BadgeVariant) -> Class<(StaticClass, StaticClass)> {
53+ class!(BASE, variant.classes())
54+}
55+
56+/// A small mono label for a status or count.
57+///
58+/// `variant` defaults to `Primary`. Pass the label as children and extra attributes
59+/// through `attrs`. Attributes go on the `<span>`, with classes added to its classes.
60+/// Use [`badge_variants`] to apply the same styling to another element.
61+///
62+/// ```ignore
63+/// view! {
64+/// badge(variant: BadgeVariant::Destructive, "Failed")
65+/// }
66+/// ```
67+#[component]
68+pub async fn badge(
69+ #[default] variant: BadgeVariant,
70+ #[default] mut attrs: Attributes,
71+ #[default] child: Child<'_>,
72+) -> Result<impl View> {
73+ Ok(view! {
74+ <span class=(class!(BASE, variant.classes(), attrs.remove("class"))) (attrs)>
75+ (child)
76+ </span>
77+ })
78+}
src/components/button.rsadded+154 -0
@@ -0,0 +1,154 @@
1+use topcoat::{
2+ Result,
3+ view::{Attributes, Child, Class, StaticClass, View, class, component, view},
4+};
5+
6+/// The visual style of a [`button`].
7+///
8+/// [`Default`] is `ButtonVariant::Primary`, used when no variant is given.
9+#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
10+#[allow(dead_code)]
11+pub enum ButtonVariant {
12+ /// The highlighter-filled button for the main action.
13+ #[default]
14+ Primary,
15+ /// A muted tinted fill for secondary actions.
16+ Secondary,
17+ /// A neutral hairline button on the card surface. The everyday button.
18+ Outline,
19+ /// No fill until hovered, for toolbars and inline actions.
20+ Ghost,
21+ /// A red hairline button for actions that delete data.
22+ Destructive,
23+}
24+
25+impl ButtonVariant {
26+ /// Classes for the button variant and its interaction states.
27+ ///
28+ /// Each variant sets its own border color. Keep border colors out of the shared
29+ /// base to avoid conflicting classes.
30+ fn classes(self) -> StaticClass {
31+ match self {
32+ Self::Primary => class!(
33+ "border-transparent bg-primary text-primary-foreground",
34+ "hover:bg-primary/90 active:bg-primary/80",
35+ ),
36+ Self::Secondary => class!(
37+ "border-transparent bg-foreground/5 text-foreground",
38+ "hover:bg-foreground/10 active:bg-foreground/15",
39+ ),
40+ Self::Outline => class!(
41+ "border-border bg-card text-foreground",
42+ "hover:bg-foreground/5 active:bg-foreground/10",
43+ ),
44+ Self::Ghost => class!(
45+ "border-transparent text-foreground hover:bg-foreground/5 active:bg-foreground/10",
46+ ),
47+ Self::Destructive => class!(
48+ "border-destructive bg-card text-destructive",
49+ "hover:bg-destructive/5 active:bg-destructive/10",
50+ ),
51+ }
52+ }
53+}
54+
55+/// The size of a [`button`].
56+///
57+/// [`Default`] is `ButtonSize::Md`, used when no size is given.
58+#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
59+#[allow(dead_code)]
60+pub enum ButtonSize {
61+ /// A compact 28px button.
62+ Sm,
63+ /// The standard 32px button.
64+ #[default]
65+ Md,
66+ /// A prominent 40px button.
67+ Lg,
68+ /// A square 32px button sized for a single icon.
69+ Icon,
70+}
71+
72+impl ButtonSize {
73+ /// Classes for the button dimensions. Text size stays the same across sizes.
74+ fn classes(self) -> StaticClass {
75+ match self {
76+ Self::Sm => class!("h-7 gap-1.5 px-2.5"),
77+ Self::Md => class!("h-8 gap-2 px-3"),
78+ Self::Lg => class!("h-10 gap-2 px-4"),
79+ Self::Icon => class!("size-8"),
80+ }
81+ }
82+}
83+
84+/// Classes shared by button variants and sizes. A border reserves the same space in
85+/// every variant. Focus uses the global `:focus-visible` outline from `styles.css`.
86+const BASE: StaticClass = class!(
87+ "inline-flex shrink-0 items-center justify-center rounded-control border",
88+ "text-sm font-medium whitespace-nowrap select-none transition-colors duration-150 ease-out",
89+ "cursor-pointer disabled:cursor-not-allowed disabled:opacity-50",
90+);
91+
92+/// Builds the full class list for a button of the given `variant` and `size`.
93+///
94+/// Use it to give button styling to an element that is not a `<button>`, such
95+/// as a link styled as a button:
96+///
97+/// ```ignore
98+/// view! {
99+/// <a href="/login" class=(button_variants(ButtonVariant::Outline, ButtonSize::Md))>
100+/// "Sign in"
101+/// </a>
102+/// }
103+/// ```
104+#[must_use]
105+pub fn button_variants(
106+ variant: ButtonVariant,
107+ size: ButtonSize,
108+) -> Class<(StaticClass, StaticClass, StaticClass)> {
109+ class!(BASE, variant.classes(), size.classes())
110+}
111+
112+/// A styled button.
113+///
114+/// `variant` defaults to `Primary` and `size` to `Md`. Pass the content as children.
115+/// `keycap` shows a keyboard shortcut inside the button after the label, for example
116+/// `kbd("Ctrl") kbd("K")`. `attrs` are forwarded to the `<button>`, with extra classes
117+/// added to its classes. Use [`button_variants`] to apply the same styling to another
118+/// element.
119+///
120+/// A disabled button stays visible and greyed out. Pass the reason in `title` or
121+/// `aria-describedby`.
122+///
123+/// ```ignore
124+/// view! {
125+/// button(
126+/// variant: ButtonVariant::Destructive,
127+/// attrs: attributes! { type="submit" },
128+/// "Delete"
129+/// )
130+/// }
131+/// ```
132+#[component]
133+pub async fn button(
134+ #[default] variant: ButtonVariant,
135+ #[default] size: ButtonSize,
136+ #[default] mut attrs: Attributes,
137+ #[default] keycap: Child<'_>,
138+ #[default] child: Child<'_>,
139+) -> Result<impl View> {
140+ Ok(view! {
141+ <button
142+ class=(class!(
143+ BASE,
144+ variant.classes(),
145+ size.classes(),
146+ attrs.remove("class"),
147+ ))
148+ (attrs)
149+ >
150+ (child)
151+ <span class="inline-flex items-center gap-1 empty:hidden">(keycap)</span>
152+ </button>
153+ })
154+}
src/components/dialog.rsadded+177 -0
@@ -0,0 +1,177 @@
1+use topcoat::{
2+ Result,
3+ runtime::Expr,
4+ view::{Attributes, Child, StaticClass, View, class, component, view},
5+};
6+
7+/// Classes for the overlay that covers the viewport.
8+///
9+/// Set `display` only for the open state so the native closed state remains hidden.
10+const OVERLAY: StaticClass = class!(
11+ "fixed inset-0 z-50 size-full max-h-none max-w-none items-start",
12+ "justify-center overflow-y-auto bg-black/50 p-4 text-foreground",
13+ "open:flex",
14+);
15+
16+/// Classes that fade the overlay in and out.
17+///
18+/// `allow-discrete` keeps it displayed through the exit transition. `@starting-style`
19+/// supplies the entry transition's initial opacity.
20+const FADE: StaticClass = class!(
21+ "opacity-0 open:opacity-100 starting:open:opacity-0",
22+ "[transition:opacity_160ms_ease-out,display_160ms_allow-discrete]",
23+);
24+
25+/// A panel displayed over the page.
26+///
27+/// Pass a boolean to `open` for a fixed state, or a runtime expression to control it in
28+/// the browser. The overlay blocks clicks on the page behind it. Focus trapping and
29+/// Escape dismissal require application scripting.
30+///
31+/// Pass a `dialog_content` panel as child content. `attrs` are forwarded to the
32+/// `<dialog>`, with extra classes added to its classes.
33+/// Give the dialog an accessible name with `aria-label`, or use `aria-labelledby`
34+/// to reference its title's ID.
35+///
36+/// ```ignore
37+/// view! {
38+/// dialog(
39+/// open: confirming,
40+/// dialog_content(
41+/// dialog_header(
42+/// dialog_title("Delete workspace")
43+/// dialog_description("This cannot be undone.")
44+/// )
45+/// dialog_footer(
46+/// // Closing the dialog is navigating to a page that
47+/// // renders it closed.
48+/// <a
49+/// href="/workspace"
50+/// class=(button_variants(ButtonVariant::Ghost, ButtonSize::Md))
51+/// >
52+/// "Cancel"
53+/// </a>
54+/// button(variant: ButtonVariant::Destructive, "Delete")
55+/// )
56+/// )
57+/// )
58+/// }
59+/// ```
60+#[component]
61+pub async fn dialog(
62+ /// Whether the dialog shows.
63+ #[into]
64+ open: Expr<bool>,
65+ /// Extra attributes for the `<dialog>` element.
66+ #[default]
67+ mut attrs: Attributes,
68+ /// The dialog's content.
69+ #[default]
70+ child: Child<'_>,
71+) -> Result<impl View> {
72+ Ok(view! {
73+ <dialog
74+ :open=(open)
75+ class=(class!(OVERLAY, FADE, attrs.remove("class")))
76+ (attrs)
77+ >
78+ (child)
79+ </dialog>
80+ })
81+}
82+
83+/// Classes for the dialog panel. Automatic vertical margins center short panels while
84+/// keeping the top of an oversized panel reachable by scrolling.
85+const CONTENT: StaticClass = class!(
86+ "relative my-auto flex w-full max-w-lg flex-col gap-4 rounded-float",
87+ "border border-border bg-popover p-6 text-popover-foreground shadow-float",
88+);
89+
90+/// Classes that scale and fade the panel as the dialog opens or closes.
91+const MOTION: StaticClass = class!(
92+ "scale-95 opacity-0 in-[[open]]:scale-100 in-[[open]]:opacity-100",
93+ "starting:in-[[open]]:scale-95 starting:in-[[open]]:opacity-0",
94+ "[transition:scale_160ms_ease-out,opacity_160ms_ease-out]",
95+);
96+
97+/// The content panel inside a dialog.
98+///
99+/// Pass the dialog's sections as children. To override its maximum width, use a more
100+/// specific class such as `[&]:max-w-xl` in `attrs`, or edit the component's classes.
101+#[component]
102+pub async fn dialog_content(
103+ #[default] mut attrs: Attributes,
104+ #[default] child: Child<'_>,
105+) -> Result<impl View> {
106+ Ok(view! {
107+ <div class=(class!(CONTENT, MOTION, attrs.remove("class"))) (attrs)>
108+ (child)
109+ </div>
110+ })
111+}
112+
113+/// The opening section of a [`dialog_content`], stacking a [`dialog_title`]
114+/// and an optional [`dialog_description`].
115+#[component]
116+pub async fn dialog_header(
117+ #[default] mut attrs: Attributes,
118+ #[default] child: Child<'_>,
119+) -> Result<impl View> {
120+ Ok(view! {
121+ <div class=(class!("flex flex-col gap-1.5", attrs.remove("class"))) (attrs)>
122+ (child)
123+ </div>
124+ })
125+}
126+
127+/// The heading of a [`dialog`], rendered as an `<h2>`.
128+#[component]
129+pub async fn dialog_title(
130+ #[default] mut attrs: Attributes,
131+ #[default] child: Child<'_>,
132+) -> Result<impl View> {
133+ Ok(view! {
134+ <h2
135+ class=(class!("text-lg leading-none font-semibold", attrs.remove("class")))
136+ (attrs)
137+ >
138+ (child)
139+ </h2>
140+ })
141+}
142+
143+/// Text that explains the dialog's purpose or requested action.
144+#[component]
145+pub async fn dialog_description(
146+ #[default] mut attrs: Attributes,
147+ #[default] child: Child<'_>,
148+) -> Result<impl View> {
149+ Ok(view! {
150+ <p
151+ class=(class!("text-sm text-muted-foreground", attrs.remove("class")))
152+ (attrs)
153+ >
154+ (child)
155+ </p>
156+ })
157+}
158+
159+/// A row of actions aligned to the right of the dialog. Actions wrap when they do not
160+/// fit.
161+#[component]
162+pub async fn dialog_footer(
163+ #[default] mut attrs: Attributes,
164+ #[default] child: Child<'_>,
165+) -> Result<impl View> {
166+ Ok(view! {
167+ <div
168+ class=(class!(
169+ "flex flex-wrap items-center justify-end gap-2",
170+ attrs.remove("class"),
171+ ))
172+ (attrs)
173+ >
174+ (child)
175+ </div>
176+ })
177+}
src/components/dropdown_menu.rsadded+327 -0
@@ -0,0 +1,327 @@
1+use topcoat::{
2+ Result,
3+ view::{Attributes, Child, StaticClass, View, attributes, class, component, view},
4+};
5+
6+use super::floating::{FloatingAlign, FloatingAnchor, FloatingSide, floating_variants};
7+
8+/// A floating action menu controlled by a trigger.
9+///
10+/// Add a [`dropdown_menu_trigger`] and a [`dropdown_menu_content`] as children. Create
11+/// an ID with [`element_id`](topcoat::view::element_id) and use it for the trigger's
12+/// `target` and the content's `id`. The button opens and closes the menu without
13+/// JavaScript. Clicking outside or pressing Escape also closes it. The menu appears
14+/// above the page and is not cut off by a parent's overflow settings.
15+///
16+/// `attrs` adds attributes and classes to the wrapper `<div>`, which takes up no space
17+/// in the layout. Use Tab to move between items. Arrow-key menu navigation is not
18+/// provided.
19+///
20+/// ```ignore
21+/// view! {
22+/// let menu = element_id(cx);
23+/// dropdown_menu(
24+/// dropdown_menu_trigger(target: &menu, "Options")
25+/// dropdown_menu_content(
26+/// id: &menu,
27+/// align: FloatingAlign::Start,
28+/// dropdown_menu_item(close: Some(&menu), "Rename")
29+/// dropdown_menu_item(close: Some(&menu), "Duplicate")
30+/// dropdown_menu_separator()
31+/// dropdown_menu_item(
32+/// close: Some(&menu),
33+/// attrs: attributes! { class="text-destructive" },
34+/// "Delete"
35+/// )
36+/// )
37+/// )
38+/// }
39+/// ```
40+#[component]
41+pub async fn dropdown_menu(
42+ #[default] mut attrs: Attributes,
43+ #[default] child: Child<'_>,
44+) -> Result<impl View> {
45+ Ok(view! {
46+ <div
47+ class=(class!("group/dropdown-menu contents", attrs.remove("class")))
48+ (attrs)
49+ >
50+ (child)
51+ </div>
52+ })
53+}
54+
55+/// A button for opening and closing the dropdown menu.
56+///
57+/// Set `target` to the [`dropdown_menu_content`]'s `id` and put the button's label in
58+/// its children. Add [`button_variants`](super::button::button_variants) classes through
59+/// `attrs` to give it the standard button style. All attributes go on the `<button>`.
60+/// Use `group-has-[:popover-open]/dropdown-menu:` classes to change how children look
61+/// while the menu is open.
62+///
63+/// ```ignore
64+/// view! {
65+/// dropdown_menu_trigger(
66+/// target: &menu,
67+/// attrs: attributes! {
68+/// class=(button_variants(ButtonVariant::Outline, ButtonSize::Md))
69+/// },
70+/// "Options"
71+/// icon(
72+/// data: iconify_icon!("lucide:chevron-down"),
73+/// attrs: attributes! {
74+/// class="group-has-[:popover-open]/dropdown-menu:rotate-180"
75+/// }
76+/// )
77+/// )
78+/// }
79+/// ```
80+#[component]
81+pub async fn dropdown_menu_trigger(
82+ /// The menu ID this button controls.
83+ target: &str,
84+ /// Attributes to add to the button.
85+ #[default]
86+ mut attrs: Attributes,
87+ /// Content shown inside the button.
88+ #[default]
89+ child: Child<'_>,
90+) -> Result<impl View> {
91+ Ok(view! {
92+ <button
93+ type="button"
94+ popovertarget=(target)
95+ class=(class!("cursor-pointer", attrs.remove("class")))
96+ (attrs)
97+ >
98+ (child)
99+ </button>
100+ })
101+}
102+
103+/// Classes for floating menu panels with their own background, border, and text color.
104+const PANEL: StaticClass = class!(
105+ "min-w-40 rounded-float border border-border bg-popover p-1",
106+ "text-popover-foreground shadow-float outline-none",
107+);
108+
109+/// The floating panel of a [`dropdown_menu`], holding the menu's items.
110+///
111+/// Use `side` to choose where the menu opens and `align` to line it up with the button.
112+/// By default, it opens below the button and is centered on it. The browser tries other
113+/// positions if there is not enough room in the window.
114+#[component]
115+pub async fn dropdown_menu_content(
116+ /// The menu ID to pass to the trigger's `target`.
117+ id: &str,
118+ /// Where the menu opens relative to the button.
119+ #[default]
120+ side: FloatingSide,
121+ /// Which edge or center of the button the menu lines up with.
122+ #[default]
123+ align: FloatingAlign,
124+ /// Attributes to add to the menu's `<div>`.
125+ #[default]
126+ mut attrs: Attributes,
127+ /// Items shown inside the menu.
128+ #[default]
129+ child: Child<'_>,
130+) -> Result<impl View> {
131+ Ok(view! {
132+ <div
133+ id=(id)
134+ popover="auto"
135+ class=(class!(
136+ floating_variants(FloatingAnchor::Invoker, side, align),
137+ PANEL,
138+ attrs.remove("class"),
139+ ))
140+ (attrs)
141+ >
142+ (child)
143+ </div>
144+ })
145+}
146+
147+/// Classes for a menu item and its interaction states.
148+const ITEM: StaticClass = class!(
149+ "flex w-full items-center gap-2 rounded-md px-2 py-1.5 text-left text-sm",
150+ "whitespace-nowrap hover:bg-foreground/5 focus-visible:bg-foreground/5",
151+ "active:bg-foreground/10 disabled:pointer-events-none disabled:opacity-50",
152+ "[&_svg]:size-4 [&_svg]:shrink-0",
153+);
154+
155+/// A button for an action inside [`dropdown_menu_content`].
156+///
157+/// The button defaults to `type="button"`. Pass the menu's ID to `close` to close the
158+/// menu and its submenus when clicked. Omit `close` to leave them open. If you set
159+/// `type="submit"` through `attrs`, the button submits its form and ignores `close`.
160+#[component]
161+pub async fn dropdown_menu_item(
162+ /// The menu ID to close when this button is clicked.
163+ #[default]
164+ close: Option<&str>,
165+ /// Attributes to add to the button.
166+ #[default]
167+ mut attrs: Attributes,
168+ /// Content shown inside the item.
169+ #[default]
170+ child: Child<'_>,
171+) -> Result<impl View> {
172+ Ok(view! {
173+ <button
174+ type="button"
175+ popovertarget=(close)
176+ popovertargetaction=(close.map(|_| "hide"))
177+ class=(class!(ITEM, attrs.remove("class")))
178+ (attrs)
179+ >
180+ (child)
181+ </button>
182+ })
183+}
184+
185+/// A nested menu that opens from a row in the parent menu.
186+///
187+/// Add a [`dropdown_menu_sub_trigger`] and a [`dropdown_menu_sub_content`] as children.
188+/// Give the trigger's `target` and the content's `id` the same value. The parent menu
189+/// stays open when the submenu opens. Closing the parent closes the submenu too.
190+///
191+/// `attrs` adds attributes and classes to the wrapper `<div>`. The wrapper takes up no
192+/// space in the layout.
193+///
194+/// ```ignore
195+/// view! {
196+/// let menu = element_id(cx);
197+/// let move_to = element_id(cx);
198+/// dropdown_menu_content(
199+/// id: &menu,
200+/// dropdown_menu_item(close: Some(&menu), "Back")
201+/// dropdown_menu_sub(
202+/// dropdown_menu_sub_trigger(target: &move_to, "Move to")
203+/// dropdown_menu_sub_content(
204+/// id: &move_to,
205+/// dropdown_menu_item(close: Some(&menu), "Inbox")
206+/// dropdown_menu_item(close: Some(&menu), "Archive")
207+/// )
208+/// )
209+/// )
210+/// }
211+/// ```
212+#[component]
213+pub async fn dropdown_menu_sub(
214+ #[default] mut attrs: Attributes,
215+ #[default] child: Child<'_>,
216+) -> Result<impl View> {
217+ Ok(view! {
218+ <div
219+ class=(class!("group/dropdown-menu-sub contents", attrs.remove("class")))
220+ (attrs)
221+ >
222+ (child)
223+ </div>
224+ })
225+}
226+
227+/// The row that opens or closes a submenu.
228+///
229+/// Set `target` to the [`dropdown_menu_sub_content`]'s `id` and put the label in the
230+/// children. The row includes a chevron and stays highlighted while the submenu is
231+/// open. `attrs` adds attributes and classes to the row's `<button>`.
232+#[component]
233+pub async fn dropdown_menu_sub_trigger(
234+ /// The submenu ID this button controls.
235+ target: &str,
236+ /// Attributes to add to the button.
237+ #[default]
238+ mut attrs: Attributes,
239+ /// Content shown inside the row.
240+ #[default]
241+ child: Child<'_>,
242+) -> Result<impl View> {
243+ Ok(view! {
244+ <button
245+ type="button"
246+ popovertarget=(target)
247+ class=(class!(
248+ ITEM,
249+ "group-has-[:popover-open]/dropdown-menu-sub:bg-foreground/5",
250+ attrs.remove("class"),
251+ ))
252+ (attrs)
253+ >
254+ (child)
255+ <svg
256+ class="ml-auto size-4 shrink-0"
257+ aria-hidden="true"
258+ viewBox="0 0 24 24"
259+ fill="none"
260+ stroke="currentColor"
261+ stroke-width="2"
262+ stroke-linecap="round"
263+ stroke-linejoin="round"
264+ ><path d="m9 18 6-6-6-6"></path></svg>
265+ </button>
266+ })
267+}
268+
269+/// A submenu that opens beside its button, to the right unless `side` says otherwise.
270+///
271+/// The browser tries other positions if the submenu does not fit in the window.
272+#[component]
273+pub async fn dropdown_menu_sub_content(
274+ /// The submenu ID to pass to the trigger's `target`.
275+ id: &str,
276+ /// Which side of the row the submenu opens on.
277+ #[default(FloatingSide::Right)]
278+ side: FloatingSide,
279+ /// Attributes to add to the submenu's `<div>`.
280+ #[default]
281+ mut attrs: Attributes,
282+ /// Items shown inside the submenu.
283+ #[default]
284+ child: Child<'_>,
285+) -> Result<impl View> {
286+ Ok(view! {
287+ <div
288+ id=(id)
289+ popover="auto"
290+ class=(class!(
291+ floating_variants(FloatingAnchor::Invoker, side, FloatingAlign::Start),
292+ PANEL,
293+ attrs.remove("class"),
294+ ))
295+ (attrs)
296+ >
297+ (child)
298+ </div>
299+ })
300+}
301+
302+/// A non-interactive heading grouping the items after it.
303+#[component]
304+pub async fn dropdown_menu_label(
305+ #[default] mut attrs: Attributes,
306+ #[default] child: Child<'_>,
307+) -> Result<impl View> {
308+ Ok(view! {
309+ <p
310+ class=(class!(
311+ "px-2 py-1.5 text-xs font-medium text-muted-foreground",
312+ attrs.remove("class"),
313+ ))
314+ (attrs)
315+ >
316+ (child)
317+ </p>
318+ })
319+}
320+
321+/// A hairline rule separating groups of items.
322+#[component]
323+pub async fn dropdown_menu_separator(#[default] mut attrs: Attributes) -> Result<impl View> {
324+ Ok(view! {
325+ <hr class=(class!("-mx-1 my-1 border-border", attrs.remove("class"))) (attrs)>
326+ })
327+}
src/components/floating.rsadded+167 -0
@@ -0,0 +1,167 @@
1+use topcoat::view::{Class, StaticClass, class};
2+
3+/// Where a floating panel appears relative to the element it follows.
4+///
5+/// The default is [`Bottom`](Self::Bottom).
6+#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
7+#[allow(dead_code)]
8+pub enum FloatingSide {
9+ /// Place the panel above the anchor.
10+ Top,
11+ /// Place the panel to the anchor's right.
12+ Right,
13+ /// Place the panel below the anchor.
14+ #[default]
15+ Bottom,
16+ /// Place the panel to the anchor's left.
17+ Left,
18+}
19+
20+impl FloatingSide {
21+ /// Sets the gap from the anchor and the fallback positions. If the panel does not
22+ /// fit, the browser tries flipping its side, its alignment, then both. Panels on
23+ /// the left or right can also move above or below the anchor.
24+ fn classes(self) -> StaticClass {
25+ match self {
26+ Self::Top => class!(
27+ "mb-1 [position-try-fallbacks:flip-block,flip-inline,flip-block_flip-inline]",
28+ ),
29+ Self::Right => class!(
30+ "ml-1 [position-try-fallbacks:flip-inline,flip-block,flip-inline_flip-block,",
31+ "top_span-left,bottom_span-left]",
32+ ),
33+ Self::Bottom => class!(
34+ "mt-1 [position-try-fallbacks:flip-block,flip-inline,flip-block_flip-inline]",
35+ ),
36+ Self::Left => class!(
37+ "mr-1 [position-try-fallbacks:flip-inline,flip-block,flip-inline_flip-block,",
38+ "top_span-right,bottom_span-right]",
39+ ),
40+ }
41+ }
42+}
43+
44+/// Which edge or center of the anchor a floating panel lines up with.
45+///
46+/// The default is [`Center`](Self::Center).
47+#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
48+#[allow(dead_code)]
49+pub enum FloatingAlign {
50+ /// Align the panel with the anchor's left or top edge.
51+ Start,
52+ /// Center the panel on the anchor.
53+ #[default]
54+ Center,
55+ /// Align the panel with the anchor's right or bottom edge.
56+ End,
57+}
58+
59+impl FloatingAlign {
60+ /// Chooses the CSS `position-area` for this side and alignment.
61+ fn area(self, side: FloatingSide) -> StaticClass {
62+ match (side, self) {
63+ (FloatingSide::Top, Self::Start) => class!("[position-area:top_span-right]"),
64+ (FloatingSide::Top, Self::Center) => class!("[position-area:top]"),
65+ (FloatingSide::Top, Self::End) => class!("[position-area:top_span-left]"),
66+ (FloatingSide::Right, Self::Start) => class!("[position-area:right_span-bottom]"),
67+ (FloatingSide::Right, Self::Center) => class!("[position-area:right]"),
68+ (FloatingSide::Right, Self::End) => class!("[position-area:right_span-top]"),
69+ (FloatingSide::Bottom, Self::Start) => class!("[position-area:bottom_span-right]"),
70+ (FloatingSide::Bottom, Self::Center) => class!("[position-area:bottom]"),
71+ (FloatingSide::Bottom, Self::End) => class!("[position-area:bottom_span-left]"),
72+ (FloatingSide::Left, Self::Start) => class!("[position-area:left_span-bottom]"),
73+ (FloatingSide::Left, Self::Center) => class!("[position-area:left]"),
74+ (FloatingSide::Left, Self::End) => class!("[position-area:left_span-top]"),
75+ }
76+ }
77+}
78+
79+/// The element a floating panel follows.
80+#[derive(Clone, Copy, Debug, PartialEq, Eq)]
81+#[allow(dead_code)]
82+pub enum FloatingAnchor {
83+ /// Follow the button that opened the panel through `popovertarget`. The panel
84+ /// needs a `popover` attribute. It appears above the page, where parent containers
85+ /// cannot cut it off.
86+ Invoker,
87+ /// Follow the nearest parent or ancestor with [`FLOATING_SCOPE`] classes. Use this
88+ /// for panels shown without the popover API, such as hints shown on hover. Parent
89+ /// overflow settings do not cut off the panel unless a parent also uses a CSS
90+ /// transform, filter, or containment.
91+ Scope,
92+}
93+
94+impl FloatingAnchor {
95+ /// Positions the panel relative to its anchor. For popovers, also removes the
96+ /// browser's default centering and adds a fade when the panel opens.
97+ fn classes(self) -> StaticClass {
98+ match self {
99+ Self::Invoker => class!(
100+ "inset-auto m-0 [position-anchor:auto]",
101+ "transition-opacity starting:open:opacity-0 motion-reduce:transition-none",
102+ ),
103+ Self::Scope => class!("fixed [position-anchor:--floating-anchor]"),
104+ }
105+ }
106+}
107+
108+/// Add these classes to the element that [`FloatingAnchor::Scope`] panels should follow.
109+///
110+/// Place the panels inside this element. Each copy of the element positions its own
111+/// panels independently.
112+pub const FLOATING_SCOPE: StaticClass =
113+ class!("[anchor-name:--floating-anchor] [anchor-scope:--floating-anchor]");
114+
115+/// Returns CSS classes that position a panel next to its anchor.
116+///
117+/// `anchor` chooses the element to follow, `side` chooses where the panel appears,
118+/// and `align` chooses how they line up. The browser tries other positions if the
119+/// panel does not fit in the window. For a panel opened by a button:
120+///
121+/// ```ignore
122+/// view! {
123+/// let filters = element_id(cx);
124+/// <button type="button" popovertarget=(&filters)>"Filters"</button>
125+/// <div
126+/// id=(&filters)
127+/// popover="auto"
128+/// class=(floating_variants(
129+/// FloatingAnchor::Invoker,
130+/// FloatingSide::Right,
131+/// FloatingAlign::Start,
132+/// ))
133+/// >
134+/// (filter_form)
135+/// </div>
136+/// }
137+/// ```
138+///
139+/// To show a hint when its parent is hovered, make that parent the anchor:
140+///
141+/// ```ignore
142+/// view! {
143+/// <span class=(class!("group inline-flex", FLOATING_SCOPE))>
144+/// (trigger)
145+/// <span
146+/// class=(class!(
147+/// floating_variants(
148+/// FloatingAnchor::Scope,
149+/// FloatingSide::Top,
150+/// FloatingAlign::Center,
151+/// ),
152+/// "hidden group-hover:block",
153+/// ))
154+/// >
155+/// (hint)
156+/// </span>
157+/// </span>
158+/// }
159+/// ```
160+#[must_use]
161+pub fn floating_variants(
162+ anchor: FloatingAnchor,
163+ side: FloatingSide,
164+ align: FloatingAlign,
165+) -> Class<(StaticClass, StaticClass, StaticClass)> {
166+ class!(anchor.classes(), side.classes(), align.area(side))
167+}
src/components/input.rsadded+31 -0
@@ -0,0 +1,31 @@
1+use topcoat::{
2+ Result,
3+ view::{Attributes, StaticClass, View, class, component, view},
4+};
5+
6+/// Classes for the input's dimensions, border, and interaction states. Focus uses the
7+/// global `:focus-visible` outline from `styles.css`.
8+const INPUT: StaticClass = class!(
9+ "h-8 w-full min-w-0 rounded-control border border-border bg-card px-2.5",
10+ "text-sm text-foreground transition-colors duration-150 ease-out",
11+ "placeholder:text-muted-foreground",
12+ "file:mr-3 file:h-full file:border-0 file:bg-transparent file:text-sm file:font-medium",
13+ "aria-invalid:border-destructive",
14+ "disabled:cursor-not-allowed disabled:opacity-50",
15+);
16+
17+/// A styled input, 32px tall with a hairline border.
18+///
19+/// Pass input attributes and event handlers through `attrs`. Extra classes are added to
20+/// the input's classes. It fills its container by default. Set `aria-invalid="true"` to
21+/// show the error border.
22+///
23+/// ```ignore
24+/// view! {
25+/// input(attrs: attributes! { type="email" placeholder="you@example.com" })
26+/// }
27+/// ```
28+#[component]
29+pub async fn input(#[default] mut attrs: Attributes) -> Result<impl View> {
30+ Ok(view! { <input class=(class!(INPUT, attrs.remove("class"))) (attrs)> })
31+}
src/components/kbd.rsadded+44 -0
@@ -0,0 +1,44 @@
1+use topcoat::{
2+ Result,
3+ view::{Attributes, Child, StaticClass, View, class, component, view},
4+};
5+
6+/// Classes that draw a key label in a bordered box.
7+const KBD: StaticClass = class!("keycap");
8+
9+/// A keyboard key label rendered as `<kbd>`.
10+///
11+/// Pass the key name as children and use [`kbd_group`] for a shortcut with several
12+/// keys. `attrs` are forwarded to the `<kbd>`, with extra classes added to its classes.
13+///
14+/// ```ignore
15+/// view! {
16+/// kbd_group(kbd("Ctrl") kbd("K"))
17+/// }
18+/// ```
19+#[component]
20+pub async fn kbd(
21+ #[default] mut attrs: Attributes,
22+ #[default] child: Child<'_>,
23+) -> Result<impl View> {
24+ Ok(view! { <kbd class=(class!(KBD, attrs.remove("class"))) (attrs)>(child)</kbd> })
25+}
26+
27+/// A row of key labels for one keyboard shortcut. The keys stay on one line.
28+#[component]
29+pub async fn kbd_group(
30+ #[default] mut attrs: Attributes,
31+ #[default] child: Child<'_>,
32+) -> Result<impl View> {
33+ Ok(view! {
34+ <span
35+ class=(class!(
36+ "inline-flex items-center gap-1 whitespace-nowrap",
37+ attrs.remove("class"),
38+ ))
39+ (attrs)
40+ >
41+ (child)
42+ </span>
43+ })
44+}
src/components/segmented.rsadded+15 -0
@@ -0,0 +1,15 @@
1+//! Segmented controls: a short row of buttons where one is pressed, such as the theme
2+//! and language switches in the sidebar.
3+//!
4+//! The look lives in `styles.css` (`.segmented`, `.segment`) and keys the raised pressed
5+//! segment on `aria-pressed="true"`. That keeps it correct for controls whose state is set
6+//! by script (the theme) as well as by the server (the language).
7+
8+/// The track around the segments. It is 28px tall.
9+pub const TRACK: &str = "segmented";
10+
11+/// A segment with a text label. It is 24px tall.
12+pub const SEGMENT: &str = "segment";
13+
14+/// A square segment for a single icon.
15+pub const SEGMENT_ICON: &str = "segment segment-icon";
src/components/separator.rsadded+77 -0
@@ -0,0 +1,77 @@
1+use topcoat::{
2+ Result,
3+ view::{Attributes, PromotedStr, StaticClass, View, class, component, view},
4+};
5+
6+/// The direction a [`separator`] runs in.
7+///
8+/// [`Default`] is `SeparatorOrientation::Horizontal`, used when no
9+/// orientation is given.
10+#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
11+#[allow(dead_code)]
12+pub enum SeparatorOrientation {
13+ /// A rule across the full width of its container.
14+ #[default]
15+ Horizontal,
16+ /// A rule down the full height of its container.
17+ Vertical,
18+}
19+
20+impl SeparatorOrientation {
21+ /// Classes that set the rule's thickness and stretch it along its orientation.
22+ fn classes(self) -> StaticClass {
23+ match self {
24+ Self::Horizontal => class!("h-px w-full"),
25+ Self::Vertical => class!("h-full w-px"),
26+ }
27+ }
28+
29+ /// The value of the `aria-orientation` attribute, or `None` for the
30+ /// horizontal default assistive technology already assumes.
31+ fn aria(self) -> Option<PromotedStr> {
32+ match self {
33+ Self::Horizontal => None,
34+ Self::Vertical => Some(PromotedStr(&"vertical")),
35+ }
36+ }
37+}
38+
39+/// Classes for a separator that keeps its thickness in a flex layout.
40+const SEPARATOR: StaticClass = class!("shrink-0 border-0 bg-border");
41+
42+/// A thin rule between groups of content.
43+///
44+/// Uses an `<hr>` element. Its length comes from its container, so a vertical separator
45+/// needs a container with a height. Pass `aria-hidden="true"` for a purely decorative
46+/// rule. `attrs` are forwarded to the `<hr>`, with extra classes added to its classes.
47+///
48+/// ```ignore
49+/// view! {
50+/// <div class="flex flex-col gap-4">
51+/// <p>"Everyone with access to this workspace."</p>
52+/// separator()
53+/// <div class="flex h-5 items-center gap-3">
54+/// <a href="/docs">"Docs"</a>
55+/// separator(orientation: SeparatorOrientation::Vertical)
56+/// <a href="/blog">"Blog"</a>
57+/// </div>
58+/// </div>
59+/// }
60+/// ```
61+#[component]
62+pub async fn separator(
63+ /// The direction the rule runs in.
64+ #[default]
65+ orientation: SeparatorOrientation,
66+ /// Extra attributes for the `<hr>` element.
67+ #[default]
68+ mut attrs: Attributes,
69+) -> Result<impl View> {
70+ Ok(view! {
71+ <hr
72+ class=(class!(SEPARATOR, orientation.classes(), attrs.remove("class")))
73+ aria-orientation=(orientation.aria())
74+ (attrs)
75+ >
76+ })
77+}
src/components/tooltip.rsadded+92 -0
@@ -0,0 +1,92 @@
1+use topcoat::{
2+ Result,
3+ view::{Attributes, Child, StaticClass, View, class, component, view},
4+};
5+
6+use super::floating::{
7+ FLOATING_SCOPE, FloatingAlign, FloatingAnchor, FloatingSide, floating_variants,
8+};
9+
10+/// A short hint shown when its trigger is hovered or focused.
11+///
12+/// Add the trigger and a [`tooltip_content`] as children.
13+///
14+/// Give the trigger its own text or accessible label. The tooltip must not be the only
15+/// way to learn what the trigger does. To associate the hint with the trigger, give
16+/// `tooltip_content` an `id` from [`element_id`](topcoat::view::element_id) and
17+/// reference it with the trigger's `aria-describedby`.
18+///
19+/// ```ignore
20+/// view! {
21+/// tooltip(
22+/// button(
23+/// size: ButtonSize::Icon,
24+/// variant: ButtonVariant::Outline,
25+/// icon(data: iconify_icon!("lucide:copy"), label: "Copy link")
26+/// )
27+/// tooltip_content("Copy link")
28+/// )
29+/// }
30+/// ```
31+#[component]
32+pub async fn tooltip(
33+ #[default] mut attrs: Attributes,
34+ #[default] child: Child<'_>,
35+) -> Result<impl View> {
36+ Ok(view! {
37+ <span
38+ class=(class!("group inline-flex", FLOATING_SCOPE, attrs.remove("class")))
39+ (attrs)
40+ >
41+ (child)
42+ </span>
43+ })
44+}
45+
46+/// Styles for a hint that fades in and out and lets pointer events pass through.
47+/// Using `display: none` while hidden makes the browser recalculate its position when
48+/// it appears. `@starting-style` starts the fade from transparent.
49+const BUBBLE: StaticClass = class!(
50+ "pointer-events-none hidden z-50 rounded-md bg-foreground px-2.5 py-1",
51+ "text-xs font-medium text-background",
52+ "opacity-0 shadow-float whitespace-nowrap",
53+ "[transition:opacity_150ms_ease-out,display_150ms_allow-discrete]",
54+ "group-hover:block group-hover:opacity-100 starting:group-hover:opacity-0",
55+ "group-focus-within:block group-focus-within:opacity-100",
56+ "starting:group-focus-within:opacity-0",
57+);
58+
59+/// The hint shown beside a [`tooltip`]'s trigger.
60+///
61+/// Use `side` to choose where the hint appears and `align` to line it up with the
62+/// trigger. By default, it appears above the trigger and is centered on it. The browser
63+/// tries other positions if there is not enough room in the window.
64+#[component]
65+pub async fn tooltip_content(
66+ /// Where the hint appears relative to the trigger.
67+ #[default(FloatingSide::Top)]
68+ side: FloatingSide,
69+ /// Which edge or center of the trigger the hint lines up with.
70+ #[default]
71+ align: FloatingAlign,
72+ /// Attributes to add to the hint's `<span>`.
73+ #[default]
74+ mut attrs: Attributes,
75+ /// Content shown in the hint.
76+ #[default]
77+ child: Child<'_>,
78+) -> Result<impl View> {
79+ Ok(view! {
80+ <span
81+ role="tooltip"
82+ class=(class!(
83+ floating_variants(FloatingAnchor::Scope, side, align),
84+ BUBBLE,
85+ attrs.remove("class"),
86+ ))
87+ (attrs)
88+ >
89+ (child)
90+ </span>
91+ })
92+}
src/export.rsadded+669 -0
@@ -0,0 +1,669 @@
1+//! Markdown export from a loro-prosemirror shaped LoroDoc.
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+
8+use loro::{Container, LoroDoc, LoroMap, LoroText, LoroValue, TextDelta, ValueOrContainer};
9+
10+mod html;
11+pub use html::{html_page, to_html};
12+
13+/// Maps a note id to its current title, for wiki-style links in `to_markdown_with`.
14+pub type Resolve<'a> = &'a dyn Fn(&str) -> Option<String>;
15+
16+/// Rendering options. `wiki` is set by `to_markdown_with`: note links then render as
17+/// `[[Title]]`, and ids the resolver cannot name stay ordinary markdown links.
18+#[derive(Clone, Copy)]
19+struct Ctx<'a> {
20+ wiki: Option<Resolve<'a>>,
21+}
22+
23+/// Full note as CommonMark/GFM. Note links stay ordinary markdown links, which is
24+/// what the search text wants.
25+pub fn to_markdown(doc: &LoroDoc) -> String {
26+ render_doc(doc, Ctx { wiki: None })
27+}
28+
29+/// 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 use
31+/// `resolve`, and an id it cannot name stays an ordinary link.
32+pub fn to_markdown_with(doc: &LoroDoc, resolve: Resolve<'_>) -> String {
33+ render_doc(doc, Ctx { wiki: Some(resolve) })
34+}
35+
36+fn render_doc(doc: &LoroDoc, cx: Ctx<'_>) -> String {
37+ let root = doc.get_map("doc");
38+ let body = render_children(&root, false, cx);
39+ if body.is_empty() {
40+ String::new()
41+ } else {
42+ format!("{body}\n")
43+ }
44+}
45+
46+/// A link to another note: by id (`/notes/<id>`) or by title (`/notes/by-title/<title>`).
47+#[derive(Clone, Debug, PartialEq, Eq)]
48+pub enum LinkTarget {
49+ Id(String),
50+ Title(String),
51+}
52+
53+/// Every note the doc links to, each target once, in document order. Hrefs that are
54+/// not note links are ignored.
55+pub fn note_links(doc: &LoroDoc) -> Vec<LinkTarget> {
56+ let mut out = Vec::new();
57+ collect_links(&doc.get_map("doc"), &mut out);
58+ out
59+}
60+
61+fn collect_links(node: &LoroMap, out: &mut Vec<LinkTarget>) {
62+ for child in children(node) {
63+ match child {
64+ Child::Text(text) => {
65+ for delta in text.to_delta() {
66+ let TextDelta::Insert {
67+ attributes: Some(attrs),
68+ ..
69+ } = delta
70+ else {
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+ }
87+ Child::Node(m) => collect_links(&m, out),
88+ }
89+ }
90+}
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+}
101+
102+/// The note a link mark points at, as a title, when the link is a note link the
103+/// resolver can name. Links by title need no resolver.
104+fn wiki_target(href: &str, cx: Ctx<'_>) -> Option<String> {
105+ let resolve = cx.wiki?;
106+ match link_target(href)? {
107+ LinkTarget::Title(title) => Some(title),
108+ LinkTarget::Id(id) => resolve(&id),
109+ }
110+}
111+
112+/// `[[target]]`, or `[[target|text]]` when the link text differs. None when the title or
113+/// the text holds wiki syntax (`[ ] | #` or a line break), so the link stays a markdown link.
114+fn wiki_link(target: &str, text: &str) -> Option<String> {
115+ let reserved = |s: &str| s.contains(['[', ']', '|', '#', '\n']);
116+ if target.trim().is_empty() || reserved(target) || reserved(text) {
117+ return None;
118+ }
119+ if text == target {
120+ Some(format!("[[{target}]]"))
121+ } else {
122+ Some(format!("[[{target}|{text}]]"))
123+ }
124+}
125+
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+// ---------------------------------------------------------------------------
268+// Block rendering
269+// ---------------------------------------------------------------------------
270+
271+/// Renders the children of `node` as blocks separated by blank lines.
272+/// With `tight`, a nested list directly follows its sibling with a single
273+/// newline instead of a blank line (used inside list items).
274+fn render_children(node: &LoroMap, 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();
294+ for (i, (block, is_list)) in blocks.iter().enumerate() {
295+ if i > 0 {
296+ out.push_str(if tight && *is_list { "\n" } else { "\n\n" });
297+ }
298+ out.push_str(block);
299+ }
300+ out
301+}
302+
303+fn render_block(node: &LoroMap, cx: Ctx<'_>) -> Option<String> {
304+ let name = node_name(node);
305+ let out = match name.as_str() {
306+ "paragraph" => paragraph_text(inline_children(node, cx)),
307+ "heading" => {
308+ let level = attr_num(node, "level").unwrap_or(1).clamp(1, 6) as usize;
309+ let text = inline_children(node, cx).replace('\n', " ");
310+ let text = text.trim();
311+ if text.is_empty() {
312+ String::new()
313+ } else {
314+ format!("{} {}", "#".repeat(level), text)
315+ }
316+ }
317+ "blockquote" => render_children(node, false, cx)
318+ .lines()
319+ .map(|l| {
320+ if l.is_empty() {
321+ ">".to_string()
322+ } else {
323+ format!("> {l}")
324+ }
325+ })
326+ .collect::<Vec<_>>()
327+ .join("\n"),
328+ "code_block" => code_block(node),
329+ "horizontal_rule" => "---".to_string(),
330+ "bullet_list" => render_list(node, false, 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+ };
338+
339+ if out.trim().is_empty() {
340+ None
341+ } else {
342+ Some(out.trim_end().to_string())
343+ }
344+}
345+
346+fn render_list(node: &LoroMap, ordered: bool, cx: Ctx<'_>) -> String {
347+ let start = if ordered {
348+ attr_num(node, "order").unwrap_or(1)
349+ } else {
350+ 1
351+ };
352+ let mut items = Vec::new();
353+ let mut index: i64 = 0;
354+ for child in children(node) {
355+ let Child::Node(item) = child else {
356+ continue;
357+ };
358+ let marker = if ordered {
359+ format!("{}. ", start + index)
360+ } else {
361+ "- ".to_string()
362+ };
363+ index += 1;
364+
365+ let body = render_children(&item, true, cx);
366+ if body.is_empty() {
367+ items.push(marker.trim_end().to_string());
368+ continue;
369+ }
370+ let pad = " ".repeat(marker.len());
371+ let mut lines = body.lines();
372+ let mut text = format!("{marker}{}", lines.next().unwrap_or(""));
373+ for line in lines {
374+ text.push('\n');
375+ if !line.is_empty() {
376+ text.push_str(&pad);
377+ text.push_str(line);
378+ }
379+ }
380+ items.push(text);
381+ }
382+ items.join("\n")
383+}
384+
385+fn code_block(node: &LoroMap) -> 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');
395+ let fence = "`".repeat((longest_backtick_run(content) + 1).max(3));
396+ let lang = attr_str(node, "language").unwrap_or_default();
397+ if content.is_empty() {
398+ format!("{fence}{lang}\n{fence}")
399+ } else {
400+ format!("{fence}{lang}\n{content}\n{fence}")
401+ }
402+}
403+
404+fn longest_backtick_run(s: &str) -> usize {
405+ let mut best = 0;
406+ let mut cur = 0;
407+ for c in s.chars() {
408+ if c == '`' {
409+ cur += 1;
410+ best = best.max(cur);
411+ } else {
412+ cur = 0;
413+ }
414+ }
415+ best
416+}
417+
418+/// Trims the inline output and protects the start of each line from being
419+/// read as block syntax (heading, list, blockquote, ordered list marker).
420+fn paragraph_text(inline: String) -> String {
421+ inline
422+ .trim()
423+ .split('\n')
424+ .map(escape_line_start)
425+ .collect::<Vec<_>>()
426+ .join("\n")
427+}
428+
429+fn escape_line_start(line: &str) -> String {
430+ let mut chars = line.chars();
431+ match chars.next() {
432+ Some('>') => format!("\\>{}", chars.as_str()),
433+ Some('-') | Some('+') => {
434+ let next = line.chars().nth(1);
435+ if next.is_none() || next == Some(' ') || next == Some('-') {
436+ format!("\\{line}")
437+ } else {
438+ line.to_string()
439+ }
440+ }
441+ Some('#') => {
442+ let hashes = line.chars().take_while(|&c| c == '#').count();
443+ let after = line.chars().nth(hashes);
444+ if (1..=6).contains(&hashes) && (after.is_none() || after == Some(' ')) {
445+ format!("\\{line}")
446+ } else {
447+ line.to_string()
448+ }
449+ }
450+ Some(c) if c.is_ascii_digit() => {
451+ let digits = line.chars().take_while(|c| c.is_ascii_digit()).count();
452+ let rest = &line[digits..];
453+ if rest.starts_with('.') || rest.starts_with(')') {
454+ format!("{}\\{}", &line[..digits], rest)
455+ } else {
456+ line.to_string()
457+ }
458+ }
459+ _ => line.to_string(),
460+ }
461+}
462+
463+// ---------------------------------------------------------------------------
464+// Inline rendering
465+// ---------------------------------------------------------------------------
466+
467+/// Concatenated inline content of a node: text runs and inline child nodes.
468+fn inline_children(node: &LoroMap, cx: Ctx<'_>) -> String {
469+ let mut out = String::new();
470+ for child in children(node) {
471+ match child {
472+ Child::Text(t) => out.push_str(&inline_text(&t, cx)),
473+ Child::Node(m) => out.push_str(&inline_node(&m, cx)),
474+ }
475+ }
476+ out
477+}
478+
479+fn inline_node(node: &LoroMap, cx: Ctx<'_>) -> String {
480+ match node_name(node).as_str() {
481+ "hard_break" => "\\\n".to_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();
527+ let mut i = 0;
528+ while i < runs.len() {
529+ let mut j = i + 1;
530+ if runs[i].1.link.is_some() {
531+ while j < runs.len() && runs[j].1.link == runs[i].1.link {
532+ j += 1;
533+ }
534+ }
535+ out.push_str(&render_group(&runs[i..j], cx));
536+ i = j;
537+ }
538+ out
539+}
540+
541+/// One run without a link, or every run of one link.
542+fn render_group(group: &[(String, Marks)], cx: Ctx<'_>) -> String {
543+ let Some((href, title)) = group[0].1.link.clone() else {
544+ return render_marks(&group[0].0, &group[0].1);
545+ };
546+ let text: String = group.iter().map(|(s, _)| s.as_str()).collect();
547+ let core = text.trim();
548+ if core.is_empty() || href.is_empty() {
549+ return group.iter().map(|(s, m)| render_marks(s, m)).collect();
550+ }
551+ let lead = &text[..text.len() - text.trim_start().len()];
552+ let trail = &text[lead.len() + core.len()..];
553+
554+ 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 {
560+ if let Some(mut link) = wiki_link(&target, core) {
561+ if first.em {
562+ link = format!("*{link}*");
563+ }
564+ if first.strong {
565+ link = format!("**{link}**");
566+ }
567+ return format!("{lead}{link}{trail}");
568+ }
569+ }
570+ // Mixed marks: a markdown link to the note's file, which Obsidian also follows.
571+ let inner: String = group.iter().map(|(s, m)| render_marks(s, m)).collect();
572+ let file = percent_encode(&format!("{target}.md"));
573+ return format!("{lead}[{}]({file}){trail}", inner.trim());
574+ }
575+
576+ let inner: String = group.iter().map(|(s, m)| render_marks(s, m)).collect();
577+ format!(
578+ "{lead}[{}]({}){trail}",
579+ inner.trim(),
580+ link_dest(&href, title.as_deref())
581+ )
582+}
583+
584+/// A run's text with its emphasis and code marks; links are handled by `render_group`.
585+fn render_marks(s: &str, m: &Marks) -> String {
586+ let core = s.trim();
587+ if core.is_empty() {
588+ return s.to_string();
589+ }
590+ // Keep surrounding whitespace outside the emphasis markers.
591+ let lead_len = s.len() - s.trim_start().len();
592+ let lead = &s[..lead_len];
593+ let trail = &s[lead_len + core.len()..];
594+
595+ let mut out = if m.code {
596+ code_span(core)
597+ } else {
598+ escape_text(core)
599+ };
600+ if m.em {
601+ out = format!("*{out}*");
602+ }
603+ if m.strong {
604+ out = format!("**{out}**");
605+ }
606+ format!("{lead}{out}{trail}")
607+}
608+
609+/// Escapes markdown-significant characters in plain text. Underscores inside
610+/// a word (snake_case) are left alone.
611+fn escape_text(s: &str) -> String {
612+ let chars: Vec<char> = s.chars().collect();
613+ let mut out = String::with_capacity(s.len());
614+ for (i, &c) in chars.iter().enumerate() {
615+ let escape = match c {
616+ '\\' | '`' | '*' | '[' | ']' | '<' | '~' => true,
617+ '_' => {
618+ let prev = i.checked_sub(1).map(|p| chars[p]);
619+ let next = chars.get(i + 1).copied();
620+ !(prev.is_some_and(char::is_alphanumeric) && next.is_some_and(char::is_alphanumeric))
621+ }
622+ _ => false,
623+ };
624+ if escape {
625+ out.push('\\');
626+ }
627+ out.push(c);
628+ }
629+ out
630+}
631+
632+fn code_span(s: &str) -> String {
633+ let fence = "`".repeat(longest_backtick_run(s) + 1);
634+ let pad = if s.starts_with('`') || s.ends_with('`') {
635+ " "
636+ } else {
637+ ""
638+ };
639+ format!("{fence}{pad}{s}{pad}{fence}")
640+}
641+
642+fn link_dest(href: &str, title: Option<&str>) -> String {
643+ let dest = if href.chars().any(|c| c.is_whitespace() || c == '(' || c == ')') {
644+ format!("<{}>", href.replace('<', "\\<").replace('>', "\\>"))
645+ } else {
646+ href.to_string()
647+ };
648+ match title.filter(|t| !t.is_empty()) {
649+ Some(t) => format!(
650+ "{dest} \"{}\"",
651+ t.replace('\\', "\\\\").replace('"', "\\\"")
652+ ),
653+ None => dest,
654+ }
655+}
656+
657+fn image_md(node: &LoroMap) -> 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() {
661+ return escape_text(&alt);
662+ }
663+ let alt = alt
664+ .replace('\\', "\\\\")
665+ .replace('[', "\\[")
666+ .replace(']', "\\]");
667+ let title = attr_str(node, "title").filter(|t| !t.is_empty());
668+ format!("![{alt}]({})", link_dest(&src, title.as_deref()))
669+}
src/export/html.rsadded+324 -0
@@ -0,0 +1,324 @@
1+//! HTML export. Walks the same loro-prosemirror tree as the markdown export in
2+//! the parent module and emits an HTML body fragment, plus a standalone page
3+//! wrapper for download and print.
4+
5+use loro::{LoroDoc, LoroMap, LoroText, LoroValue, TextDelta};
6+
7+use super::{Child, attr_num, attr_str, children, node_name, plain_node_text, plain_text, value_str};
8+
9+/// Note body as an HTML fragment (no surrounding document).
10+pub fn to_html(doc: &LoroDoc) -> String {
11+ let root = doc.get_map("doc");
12+ render_children(&root)
13+}
14+
15+/// Standalone HTML document around `body`. With `print`, the page opens the
16+/// browser's print dialog on load (Save as PDF).
17+pub fn html_page(title: &str, body: &str, lang: &str, print: bool) -> String {
18+ let script = if print {
19+ "<script>addEventListener('load',()=>print())</script>"
20+ } else {
21+ ""
22+ };
23+ format!(
24+ "<!DOCTYPE html>\n<html lang=\"{lang}\">\n<head>\n<meta charset=\"utf-8\">\n\
25+ <meta name=\"viewport\" content=\"width=device-width, initial-scale=1\">\n\
26+ <title>{title}</title>\n<style>{STYLE}</style>\n</head>\n<body>\n\
27+ <main class=\"note\">\n{body}\n</main>\n{script}\n</body>\n</html>\n",
28+ lang = esc(lang),
29+ title = esc(title),
30+ )
31+}
32+
33+const STYLE: &str = "\
34+body{margin:0;font-family:system-ui,-apple-system,\"Segoe UI\",Roboto,sans-serif;\
35+font-size:16px;line-height:1.6;color:#1c1c1e;background:#fff}\
36+.note{max-width:42rem;margin:2.5rem auto;padding:0 1.25rem}\
37+h1,h2,h3,h4,h5,h6{line-height:1.25;margin:1.6em 0 .5em}\
38+p,ul,ol,blockquote,pre,table{margin:0 0 1em}\
39+ul,ol{padding-left:1.5em}\
40+blockquote{margin-left:0;padding-left:1em;border-left:3px solid #d0d0d5;color:#555}\
41+code{font-family:ui-monospace,SFMono-Regular,Menlo,Consolas,monospace;font-size:.9em;\
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}\
44+pre code{background:none;padding:0;font-size:.875em}\
45+img{max-width:100%;height:auto}\
46+hr{border:0;border-top:1px solid #d0d0d5;margin:2em 0}\
47+a{color:#0a58ca}\
48+table{border-collapse:collapse;max-width:100%}\
49+th,td{border:1px solid #d0d0d5;padding:.4em .6em;text-align:left}\
50+@page{margin:2cm}\
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}}";
53+
54+// ---------------------------------------------------------------------------
55+// Escaping and link safety
56+// ---------------------------------------------------------------------------
57+
58+fn esc(s: &str) -> String {
59+ let mut out = String::with_capacity(s.len());
60+ for c in s.chars() {
61+ match c {
62+ '&' => out.push_str("&amp;"),
63+ '<' => out.push_str("&lt;"),
64+ '>' => out.push_str("&gt;"),
65+ '"' => out.push_str("&quot;"),
66+ '\'' => out.push_str("&#39;"),
67+ _ => out.push(c),
68+ }
69+ }
70+ out
71+}
72+
73+/// Accepts http(s), mailto and scheme-less (relative) URLs. Anything else,
74+/// including javascript: and data:, is rejected.
75+fn safe_href(href: &str) -> Option<&str> {
76+ let h = href.trim();
77+ if h.is_empty() {
78+ return None;
79+ }
80+ let lower = h.to_ascii_lowercase();
81+ if lower.starts_with("http://") || lower.starts_with("https://") || lower.starts_with("mailto:") {
82+ return Some(h);
83+ }
84+ // A colon before any path, query or fragment delimiter starts a scheme.
85+ match h.find(':') {
86+ Some(i) if !h[..i].contains(['/', '?', '#']) => None,
87+ _ => Some(h),
88+ }
89+}
90+
91+/// Image sources: the link rules, plus inline raster data URIs.
92+fn safe_src(src: &str) -> Option<&str> {
93+ let lower = src.trim().to_ascii_lowercase();
94+ if lower.starts_with("data:image/png")
95+ || lower.starts_with("data:image/jpeg")
96+ || lower.starts_with("data:image/gif")
97+ || lower.starts_with("data:image/webp")
98+ {
99+ return Some(src.trim());
100+ }
101+ safe_href(src)
102+}
103+
104+// ---------------------------------------------------------------------------
105+// Block rendering
106+// ---------------------------------------------------------------------------
107+
108+/// Renders the children of `node` as blocks, in order.
109+fn render_children(node: &LoroMap) -> String {
110+ let mut out = String::new();
111+ for child in children(node) {
112+ match child {
113+ Child::Text(t) => {
114+ let inner = inline_text(&t);
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+ }
126+ }
127+ out
128+}
129+
130+fn render_block(node: &LoroMap) -> Option<String> {
131+ let html = match node_name(node).as_str() {
132+ "paragraph" => {
133+ let inner = inline_children(node);
134+ if inner.trim().is_empty() {
135+ return None;
136+ }
137+ format!("<p>{}</p>", inner.trim())
138+ }
139+ "heading" => {
140+ let level = attr_num(node, "level").unwrap_or(1).clamp(1, 6);
141+ let inner = inline_children(node).replace('\n', " ");
142+ let inner = inner.trim();
143+ if inner.is_empty() {
144+ return None;
145+ }
146+ format!("<h{level}>{inner}</h{level}>")
147+ }
148+ "blockquote" => {
149+ let inner = render_children(node);
150+ if inner.trim().is_empty() {
151+ return None;
152+ }
153+ format!("<blockquote>\n{inner}</blockquote>")
154+ }
155+ "code_block" => code_block(node),
156+ "horizontal_rule" => "<hr>".to_string(),
157+ "bullet_list" => render_list(node, false)?,
158+ "ordered_list" => render_list(node, true)?,
159+ "image" => {
160+ let inner = image_html(node);
161+ format!("<p>{inner}</p>")
162+ }
163+ "hard_break" => return None,
164+ // doc and unknown containers: render their children.
165+ _ => render_children(node),
166+ };
167+ if html.trim().is_empty() {
168+ None
169+ } else {
170+ Some(html)
171+ }
172+}
173+
174+fn render_list(node: &LoroMap, ordered: bool) -> Option<String> {
175+ let mut items = String::new();
176+ for child in children(node) {
177+ let Child::Node(item) = child else {
178+ continue;
179+ };
180+ items.push_str(&format!("<li>{}</li>\n", render_children(&item).trim_end()));
181+ }
182+ if items.is_empty() {
183+ return None;
184+ }
185+ if ordered {
186+ let start = attr_num(node, "order").unwrap_or(1);
187+ let start_attr = if start == 1 {
188+ String::new()
189+ } else {
190+ format!(" start=\"{start}\"")
191+ };
192+ Some(format!("<ol{start_attr}>\n{items}</ol>"))
193+ } else {
194+ Some(format!("<ul>\n{items}</ul>"))
195+ }
196+}
197+
198+fn code_block(node: &LoroMap) -> String {
199+ let mut content = String::new();
200+ for child in children(node) {
201+ match child {
202+ Child::Text(t) => content.push_str(&plain_text(&t)),
203+ Child::Node(m) if node_name(&m) == "hard_break" => content.push('\n'),
204+ Child::Node(m) => content.push_str(&plain_node_text(&m)),
205+ }
206+ }
207+ let content = content.trim_end_matches('\n');
208+ let lang = attr_str(node, "language").unwrap_or_default();
209+ let class = if lang.trim().is_empty() {
210+ String::new()
211+ } else {
212+ format!(" class=\"language-{}\"", esc(lang.trim()))
213+ };
214+ format!("<pre><code{class}>{}</code></pre>", esc(content))
215+}
216+
217+// ---------------------------------------------------------------------------
218+// Inline rendering
219+// ---------------------------------------------------------------------------
220+
221+/// Concatenated inline content of a node: text runs and inline child nodes.
222+fn inline_children(node: &LoroMap) -> String {
223+ let mut out = String::new();
224+ for child in children(node) {
225+ match child {
226+ Child::Text(t) => out.push_str(&inline_text(&t)),
227+ Child::Node(m) => out.push_str(&inline_node(&m)),
228+ }
229+ }
230+ out
231+}
232+
233+fn inline_node(node: &LoroMap) -> String {
234+ match node_name(node).as_str() {
235+ "hard_break" => "<br>".to_string(),
236+ "image" => image_html(node),
237+ _ => inline_children(node),
238+ }
239+}
240+
241+fn image_html(node: &LoroMap) -> String {
242+ let alt = attr_str(node, "alt").unwrap_or_default();
243+ let src = attr_str(node, "src").unwrap_or_default();
244+ let Some(src) = safe_src(&src) else {
245+ return esc(&alt);
246+ };
247+ let title = attr_str(node, "title")
248+ .filter(|t| !t.is_empty())
249+ .map(|t| format!(" title=\"{}\"", esc(&t)))
250+ .unwrap_or_default();
251+ format!("<img src=\"{}\" alt=\"{}\"{title}>", esc(src), esc(&alt))
252+}
253+
254+#[derive(PartialEq, Clone, Default)]
255+struct Marks {
256+ strong: bool,
257+ em: bool,
258+ code: bool,
259+ link: Option<(String, Option<String>)>,
260+}
261+
262+/// Renders a LoroText as HTML, merging adjacent runs with identical marks.
263+fn inline_text(text: &LoroText) -> String {
264+ let mut runs: Vec<(String, Marks)> = Vec::new();
265+ for delta in text.to_delta() {
266+ let TextDelta::Insert { insert, attributes } = delta else {
267+ continue;
268+ };
269+ let attrs = attributes.unwrap_or_default();
270+ let on = |k: &str| attrs.get(k).is_some_and(|v| !matches!(v, LoroValue::Null));
271+ let link = attrs.get("link").map(|v| {
272+ let href = v.get_by_key("href").and_then(value_str).unwrap_or_default();
273+ let title = v
274+ .get_by_key("title")
275+ .and_then(value_str)
276+ .filter(|t| !t.is_empty());
277+ (href, title)
278+ });
279+ let marks = Marks {
280+ strong: on("strong"),
281+ em: on("em"),
282+ code: on("code"),
283+ link,
284+ };
285+ match runs.last_mut() {
286+ Some((s, m)) if *m == marks => s.push_str(&insert),
287+ _ => runs.push((insert, marks)),
288+ }
289+ }
290+ runs.iter().map(|(s, m)| render_run(s, m)).collect()
291+}
292+
293+fn render_run(s: &str, m: &Marks) -> String {
294+ let core = s.trim();
295+ if core.is_empty() {
296+ return esc(s);
297+ }
298+ // Keep surrounding whitespace outside the tags.
299+ let lead_len = s.len() - s.trim_start().len();
300+ let lead = &s[..lead_len];
301+ let trail = &s[lead_len + core.len()..];
302+
303+ let mut out = if m.code {
304+ format!("<code>{}</code>", esc(core))
305+ } else {
306+ esc(core)
307+ };
308+ if m.em {
309+ out = format!("<em>{out}</em>");
310+ }
311+ if m.strong {
312+ out = format!("<strong>{out}</strong>");
313+ }
314+ if let Some((href, title)) = &m.link {
315+ if let Some(href) = safe_href(href) {
316+ let title = title
317+ .as_deref()
318+ .map(|t| format!(" title=\"{}\"", esc(t)))
319+ .unwrap_or_default();
320+ out = format!("<a href=\"{}\"{title}>{out}</a>", esc(href));
321+ }
322+ }
323+ format!("{}{out}{}", esc(lead), esc(trail))
324+}
src/hub.rsadded+441 -0
@@ -0,0 +1,441 @@
1+//! Per-note live state: one in-memory `LoroDoc` per note, shared by every
2+//! WebSocket connection editing that note.
3+//!
4+//! Wire protocol (binary frames, first byte is the tag):
5+//! - `0x01` SYNC_REQ: payload is an encoded `VersionVector`. The receiver
6+//! answers with an UPDATE containing what the requester is missing.
7+//! - `0x02` UPDATE: payload is Loro update bytes. Imported, persisted and
8+//! broadcast to the other connections when it changed the doc.
9+//! - `0x03` EPHEMERAL: opaque bytes, broadcast only, never persisted.
10+
11+use std::collections::HashMap;
12+use std::sync::Mutex;
13+use std::sync::atomic::{AtomicU64, Ordering};
14+use std::time::Duration;
15+
16+use loro::{ExportMode, Frontiers, LoroDoc, LoroList, LoroMap, VersionVector};
17+use tokio::sync::{Mutex as AsyncMutex, broadcast};
18+use topcoat::router::content::websocket::{Message, WebSocket};
19+
20+use crate::export;
21+use crate::store::{Store, now_millis};
22+
23+pub const SYNC_REQ: u8 = 0x01;
24+pub const UPDATE: u8 = 0x02;
25+pub const EPHEMERAL: u8 = 0x03;
26+
27+const SNAPSHOT_EVERY: u64 = 50;
28+/// Least time between two versions recorded while the note is being edited.
29+const VERSION_EVERY_MS: i64 = 10 * 60 * 1000;
30+/// Quiet time after the last applied update before the searchable text is written.
31+const TEXT_FLUSH_DELAY: Duration = Duration::from_secs(2);
32+const CHANNEL_CAPACITY: usize = 256;
33+
34+/// A broadcast item: the connection id that sent it, and the full frame.
35+type Frame = (u64, Vec<u8>);
36+
37+pub struct Hub {
38+ rooms: Mutex<HashMap<String, std::sync::Arc<Room>>>,
39+ next_conn: AtomicU64,
40+}
41+
42+impl Hub {
43+ pub fn new() -> Self {
44+ Self {
45+ rooms: Mutex::new(HashMap::new()),
46+ next_conn: AtomicU64::new(1),
47+ }
48+ }
49+
50+ /// Returns the live room for `note_id`, loading it from the store on first use.
51+ /// Rooms are kept in memory after their last connection leaves, so a room is
52+ /// never orphaned while a connection still holds it.
53+ pub async fn room(&self, store: &Store, note_id: &str) -> anyhow::Result<std::sync::Arc<Room>> {
54+ let existing = self
55+ .rooms
56+ .lock()
57+ .unwrap()
58+ .get(note_id)
59+ .cloned();
60+ if let Some(room) = existing {
61+ return Ok(room);
62+ }
63+
64+ // Load without holding the map lock: this awaits the store.
65+ let doc = load_doc(store, note_id).await?;
66+ let last_version = load_last_version(store, note_id).await?;
67+ let room = std::sync::Arc::new(Room::new(note_id, doc, last_version));
68+
69+ // Another task may have loaded the same note meanwhile; keep the first one.
70+ let mut rooms = self.rooms.lock().unwrap();
71+ Ok(rooms
72+ .entry(note_id.to_owned())
73+ .or_insert(room)
74+ .clone())
75+ }
76+
77+ /// Drops the in-memory room for a deleted note. Connections still holding the
78+ /// room keep working until they leave; nothing new is loaded for this id.
79+ pub fn forget(&self, note_id: &str) {
80+ self.rooms.lock().unwrap().remove(note_id);
81+ }
82+
83+ fn next_conn_id(&self) -> u64 {
84+ self.next_conn.fetch_add(1, Ordering::Relaxed)
85+ }
86+}
87+
88+impl Default for Hub {
89+ fn default() -> Self {
90+ Self::new()
91+ }
92+}
93+
94+/// Update holding the root structure loro-prosemirror expects: a `doc` node with
95+/// one empty paragraph. Written once at note creation so clients never race to
96+/// initialise the root.
97+pub fn initial_note_update() -> anyhow::Result<Vec<u8>> {
98+ let doc = LoroDoc::new();
99+ let root = doc.get_map("doc");
100+ root.insert("nodeName", "doc")?;
101+ root.insert_container("attributes", LoroMap::new())?;
102+ let children = root.insert_container("children", LoroList::new())?;
103+ let paragraph = children.push_container(LoroMap::new())?;
104+ paragraph.insert("nodeName", "paragraph")?;
105+ paragraph.insert_container("attributes", LoroMap::new())?;
106+ paragraph.insert_container("children", LoroList::new())?;
107+ doc.commit();
108+ Ok(doc.export(ExportMode::all_updates())?)
109+}
110+
111+/// The newest recorded version of a note, with its time in millis.
112+async fn load_last_version(store: &Store, note_id: &str) -> anyhow::Result<Option<(i64, Frontiers)>> {
113+ match store.list_versions(note_id).await?.into_iter().next() {
114+ Some((at, bytes)) => Ok(Some((at, Frontiers::decode(&bytes)?))),
115+ None => Ok(None),
116+ }
117+}
118+
119+pub async fn load_doc(store: &Store, note_id: &str) -> anyhow::Result<LoroDoc> {
120+ let bytes = store.load_doc(note_id).await?;
121+ let doc = LoroDoc::new();
122+ if let Some(snapshot) = bytes.snapshot {
123+ doc.import(&snapshot)?;
124+ }
125+ for update in bytes.updates {
126+ doc.import(&update)?;
127+ }
128+ Ok(doc)
129+}
130+
131+struct RoomState {
132+ doc: LoroDoc,
133+ /// Live WebSocket connections on this room.
134+ conns: usize,
135+ updates_since_snapshot: u64,
136+ /// A searchable-text flush is scheduled and has not read the doc yet.
137+ text_pending: bool,
138+ /// Time in millis and frontiers of the newest recorded version.
139+ last_version: Option<(i64, Frontiers)>,
140+}
141+
142+pub struct Room {
143+ note_id: String,
144+ tx: broadcast::Sender<Frame>,
145+ state: AsyncMutex<RoomState>,
146+}
147+
148+impl Room {
149+ fn new(note_id: &str, doc: LoroDoc, last_version: Option<(i64, Frontiers)>) -> Self {
150+ let (tx, _) = broadcast::channel(CHANNEL_CAPACITY);
151+ Self {
152+ note_id: note_id.to_owned(),
153+ tx,
154+ state: AsyncMutex::new(RoomState {
155+ doc,
156+ conns: 0,
157+ updates_since_snapshot: 0,
158+ text_pending: false,
159+ last_version,
160+ }),
161+ }
162+ }
163+
164+ /// Registers a connection. The receiver is created under the same lock as the
165+ /// connection count, so no broadcast can be missed between join and first recv.
166+ async fn join(&self) -> broadcast::Receiver<Frame> {
167+ let mut state = self.state.lock().await;
168+ state.conns += 1;
169+ self.tx.subscribe()
170+ }
171+
172+ /// Records a version and persists a snapshot when the last connection leaves.
173+ async fn leave(&self, store: &Store) {
174+ let mut state = self.state.lock().await;
175+ state.conns = state.conns.saturating_sub(1);
176+ if state.conns == 0 {
177+ if let Err(err) = record_version(&mut state, store, &self.note_id).await {
178+ eprintln!("version record failed for note {}: {err:#}", self.note_id);
179+ }
180+ if let Err(err) = write_snapshot(&mut state, store, &self.note_id).await {
181+ eprintln!("snapshot failed for note {}: {err:#}", self.note_id);
182+ }
183+ }
184+ }
185+
186+ /// Frame announcing our version vector, so the peer can send what we lack.
187+ pub async fn sync_req_frame(&self) -> Vec<u8> {
188+ let state = self.state.lock().await;
189+ frame(SYNC_REQ, &state.doc.oplog_vv().encode())
190+ }
191+
192+ /// Answers a SYNC_REQ payload with an UPDATE frame of what the peer lacks.
193+ async fn sync_reply(&self, payload: &[u8]) -> anyhow::Result<Vec<u8>> {
194+ let state = self.state.lock().await;
195+ let vv = VersionVector::decode(payload)?;
196+ let updates = state.doc.export(ExportMode::updates(&vv))?;
197+ Ok(frame(UPDATE, &updates))
198+ }
199+
200+ async fn all_updates_frame(&self) -> anyhow::Result<Vec<u8>> {
201+ let state = self.state.lock().await;
202+ Ok(frame(UPDATE, &state.doc.export(ExportMode::all_updates())?))
203+ }
204+
205+ /// Imports an UPDATE payload. Returns `true` when it changed the doc, in which
206+ /// case the update has been persisted and should be broadcast.
207+ async fn apply_update(self: &std::sync::Arc<Self>, store: &std::sync::Arc<Store>, payload: &[u8]) -> anyhow::Result<bool> {
208+ let mut state = self.state.lock().await;
209+ let before = state.doc.oplog_vv();
210+ state.doc.import(payload)?;
211+ if state.doc.oplog_vv() == before {
212+ return Ok(false);
213+ }
214+ persist_update(self, &mut state, store, payload).await?;
215+ Ok(true)
216+ }
217+
218+ /// The document as it was at `frontiers`, as HTML. The live doc is not changed.
219+ pub async fn html_at(&self, frontiers: &Frontiers) -> anyhow::Result<String> {
220+ let state = self.state.lock().await;
221+ let forked = state.doc.fork_at(frontiers)?;
222+ Ok(export::to_html(&forked))
223+ }
224+
225+ /// Makes the doc match an earlier version. The change is a new edit on top of the
226+ /// history, so it is persisted and broadcast like a client update. The state before
227+ /// and after the restore are both recorded as versions, so the restore can be undone.
228+ pub async fn restore(self: &std::sync::Arc<Self>, store: &std::sync::Arc<Store>, frontiers: &Frontiers) -> anyhow::Result<()> {
229+ let mut state = self.state.lock().await;
230+ let vv_before = state.doc.oplog_vv();
231+ record_version(&mut state, store, &self.note_id).await?;
232+ state.doc.revert_to(frontiers)?;
233+ state.doc.commit();
234+ if state.doc.oplog_vv() == vv_before {
235+ return Ok(());
236+ }
237+ let update = state.doc.export(ExportMode::updates(&vv_before))?;
238+ persist_update(self, &mut state, store, &update).await?;
239+ // Connection 0 never exists, so every connection receives the restore.
240+ self.broadcast(0, frame(UPDATE, &update));
241+ record_version(&mut state, store, &self.note_id).await
242+ }
243+
244+ fn broadcast(&self, conn_id: u64, frame: Vec<u8>) {
245+ // Err only means there are no receivers, which is fine.
246+ let _ = self.tx.send((conn_id, frame));
247+ }
248+
249+ /// Live markdown of the in-memory doc, with note links written as `[[Title]]`.
250+ /// `titles` maps note ids to their titles.
251+ pub async fn markdown_with(&self, titles: HashMap<String, String>) -> String {
252+ let state = self.state.lock().await;
253+ let resolve = |id: &str| titles.get(id).cloned();
254+ export::to_markdown_with(&state.doc, &resolve)
255+ }
256+
257+ pub async fn html(&self) -> String {
258+ let state = self.state.lock().await;
259+ export::to_html(&state.doc)
260+ }
261+}
262+
263+/// Stores a changed update, counts it towards the next snapshot, and schedules the
264+/// searchable-text flush. The caller has already imported the update into `state`.
265+async fn persist_update(
266+ room: &std::sync::Arc<Room>,
267+ state: &mut RoomState,
268+ store: &std::sync::Arc<Store>,
269+ payload: &[u8],
270+) -> anyhow::Result<()> {
271+ store.append_update(&room.note_id, payload).await?;
272+ state.updates_since_snapshot += 1;
273+ if state.updates_since_snapshot >= SNAPSHOT_EVERY {
274+ write_snapshot(state, store, &room.note_id).await?;
275+ }
276+ if !state.text_pending {
277+ state.text_pending = true;
278+ tokio::spawn(flush_text(room.clone(), store.clone()));
279+ }
280+ Ok(())
281+}
282+
283+/// Records the doc's current frontiers as a version, unless they are the same as the
284+/// newest recorded version.
285+async fn record_version(state: &mut RoomState, store: &Store, note_id: &str) -> anyhow::Result<()> {
286+ let frontiers = state.doc.oplog_frontiers();
287+ if state.last_version.as_ref().is_some_and(|(_, last)| *last == frontiers) {
288+ return Ok(());
289+ }
290+ let at = now_millis();
291+ store.add_version(note_id, at, &frontiers.encode()).await?;
292+ state.last_version = Some((at, frontiers));
293+ Ok(())
294+}
295+
296+/// Writes the note's title and searchable text after typing pauses. The flag is
297+/// cleared before the doc is read, so an update that arrives during the write
298+/// schedules a new flush. A version is recorded when the last one is 10 minutes old.
299+async fn flush_text(room: std::sync::Arc<Room>, store: std::sync::Arc<Store>) {
300+ tokio::time::sleep(TEXT_FLUSH_DELAY).await;
301+ let (title, body, links) = {
302+ let mut state = room.state.lock().await;
303+ state.text_pending = false;
304+ let due = state
305+ .last_version
306+ .as_ref()
307+ .is_none_or(|(at, _)| now_millis() - at >= VERSION_EVERY_MS);
308+ if due {
309+ if let Err(err) = record_version(&mut state, &store, &room.note_id).await {
310+ eprintln!("version record failed for note {}: {err:#}", room.note_id);
311+ }
312+ }
313+ (
314+ export::title(&state.doc),
315+ export::to_markdown(&state.doc),
316+ export::note_links(&state.doc),
317+ )
318+ };
319+ if let Err(err) = store.set_title(&room.note_id, &title).await {
320+ eprintln!("title write failed for note {}: {err:#}", room.note_id);
321+ }
322+ if let Err(err) = store.put_text(&room.note_id, &title, &body).await {
323+ eprintln!("text write failed for note {}: {err:#}", room.note_id);
324+ }
325+ if let Err(err) = store.set_links(&room.note_id, &links).await {
326+ eprintln!("link index write failed for note {}: {err:#}", room.note_id);
327+ }
328+}
329+
330+async fn write_snapshot(
331+ state: &mut RoomState,
332+ store: &Store,
333+ note_id: &str,
334+) -> anyhow::Result<()> {
335+ let snapshot = state.doc.export(ExportMode::Snapshot)?;
336+ let markdown = export::to_markdown(&state.doc);
337+ let title = export::title(&state.doc);
338+ store
339+ .put_snapshot(note_id, &snapshot, &markdown, &title)
340+ .await?;
341+ store
342+ .set_links(note_id, &export::note_links(&state.doc))
343+ .await?;
344+ state.updates_since_snapshot = 0;
345+ Ok(())
346+}
347+
348+fn frame(tag: u8, payload: &[u8]) -> Vec<u8> {
349+ let mut out = Vec::with_capacity(payload.len() + 1);
350+ out.push(tag);
351+ out.extend_from_slice(payload);
352+ out
353+}
354+
355+/// Drives one WebSocket connection until either side closes it.
356+pub async fn serve_socket(hub: std::sync::Arc<Hub>, store: std::sync::Arc<Store>, room: std::sync::Arc<Room>, mut socket: WebSocket) {
357+ let conn_id = hub.next_conn_id();
358+ let mut rx = room.join().await;
359+
360+ if socket
361+ .send(Message::binary(room.sync_req_frame().await))
362+ .await
363+ .is_err()
364+ {
365+ room.leave(&store).await;
366+ return;
367+ }
368+
369+ loop {
370+ tokio::select! {
371+ incoming = socket.recv() => {
372+ let message = match incoming {
373+ Some(Ok(message)) => message,
374+ _ => break,
375+ };
376+ match message {
377+ Message::Binary(bytes) => {
378+ if !handle_frame(&room, &store, conn_id, &bytes, &mut socket).await {
379+ break;
380+ }
381+ }
382+ Message::Close(_) => break,
383+ // Text frames are not part of the protocol; ping/pong are handled by topcoat.
384+ _ => {}
385+ }
386+ }
387+ event = rx.recv() => match event {
388+ Ok((from, frame)) => {
389+ if from != conn_id && socket.send(Message::binary(frame)).await.is_err() {
390+ break;
391+ }
392+ }
393+ Err(broadcast::error::RecvError::Lagged(_)) => {
394+ // Missed frames: push every update; importing known ops is a no-op.
395+ let Ok(frame) = room.all_updates_frame().await else { break };
396+ if socket.send(Message::binary(frame)).await.is_err() {
397+ break;
398+ }
399+ }
400+ Err(broadcast::error::RecvError::Closed) => break,
401+ }
402+ }
403+ }
404+
405+ room.leave(&store).await;
406+}
407+
408+/// Handles one inbound binary frame. Returns `false` when the socket is unusable.
409+async fn handle_frame(
410+ room: &std::sync::Arc<Room>,
411+ store: &std::sync::Arc<Store>,
412+ conn_id: u64,
413+ bytes: &[u8],
414+ socket: &mut WebSocket,
415+) -> bool {
416+ let Some((&tag, payload)) = bytes.split_first() else {
417+ return true;
418+ };
419+ match tag {
420+ SYNC_REQ => match room.sync_reply(payload).await {
421+ Ok(reply) => socket.send(Message::binary(reply)).await.is_ok(),
422+ Err(err) => {
423+ eprintln!("bad sync request on note {}: {err:#}", room.note_id);
424+ true
425+ }
426+ },
427+ UPDATE => {
428+ match room.apply_update(store, payload).await {
429+ Ok(true) => room.broadcast(conn_id, frame(UPDATE, payload)),
430+ Ok(false) => {}
431+ Err(err) => eprintln!("bad update on note {}: {err:#}", room.note_id),
432+ }
433+ true
434+ }
435+ EPHEMERAL => {
436+ room.broadcast(conn_id, frame(EPHEMERAL, payload));
437+ true
438+ }
439+ _ => true,
440+ }
441+}
src/i18n.rsadded+414 -0
@@ -0,0 +1,414 @@
1+//! Localization: the supported languages, the message catalogue, count and date
2+//! formatting, and language resolution from the request.
3+//!
4+//! Every message is one arm of [`t`]'s single `match` over [`Msg`], and each arm gives
5+//! both languages. A message without a Turkish text does not compile.
6+
7+use topcoat::{
8+ context::Cx,
9+ cookie::{Cookie, Cookies, SameSite, cookies, time::Duration},
10+ router::request::headers,
11+};
12+
13+/// Name of the cookie that stores the language choice.
14+pub const LANG_COOKIE: &str = "lang";
15+
16+/// How long the language choice is remembered.
17+pub const LANG_COOKIE_DAYS: i64 = 365;
18+
19+/// A supported interface language.
20+#[derive(Clone, Copy, Debug, PartialEq, Eq)]
21+pub enum Lang {
22+ En,
23+ Tr,
24+}
25+
26+impl Lang {
27+ /// The value stored in the cookie and used in the `lang` attribute of `<html>`.
28+ pub fn code(self) -> &'static str {
29+ match self {
30+ Self::En => "en",
31+ Self::Tr => "tr",
32+ }
33+ }
34+
35+ /// Parses a cookie or form value. Returns `None` for unsupported languages.
36+ pub fn from_code(code: &str) -> Option<Self> {
37+ match code {
38+ "en" => Some(Self::En),
39+ "tr" => Some(Self::Tr),
40+ _ => None,
41+ }
42+ }
43+}
44+
45+/// Every interface message. Add a variant here, then its texts in [`t`].
46+#[derive(Clone, Copy, Debug, PartialEq, Eq)]
47+pub enum Msg {
48+ AppName,
49+ MainNavigation,
50+ SkipToContent,
51+ Search,
52+ SearchLabel,
53+ SearchPlaceholder,
54+ NewNote,
55+ NewNotebook,
56+ NewNotebookLabel,
57+ Add,
58+ AllNotes,
59+ Unfiled,
60+ Trash,
61+ Notebooks,
62+ Theme,
63+ ThemeLight,
64+ ThemeDark,
65+ ThemeSystem,
66+ ColorScheme,
67+ Language,
68+ LanguageEnglish,
69+ LanguageTurkish,
70+ HideSidebar,
71+ ShowSidebar,
72+ OpenMenu,
73+ CloseMenu,
74+ Undo,
75+ Dismiss,
76+ ToastTrashed,
77+ ToastRestored,
78+ ToastNotebookCreated,
79+ ToastNotebookDeleted,
80+ ToastMoved,
81+ Untitled,
82+ JustNow,
83+ Yesterday,
84+ NoNotesYet,
85+ CreateOneHint,
86+ EmptyNotebook,
87+ EmptyUnfiled,
88+ EmptyTrash,
89+ SelectNote,
90+ GroupToday,
91+ GroupPrevious7,
92+ GroupEarlier,
93+ BackToList,
94+ MoveToNotebook,
95+ AlreadyHere,
96+ ExportAs,
97+ ExportMarkdown,
98+ ExportHtml,
99+ ExportPdf,
100+ ExportAll,
101+ MoveToTrash,
102+ InTrash,
103+ AlreadyInTrash,
104+ RestoreFirst,
105+ Restore,
106+ DeleteForever,
107+ EmptyTrashAction,
108+ TrashRetention,
109+ Trashed,
110+ ConfirmEmptyTrashTitle,
111+ ConfirmForeverTitle,
112+ CannotUndo,
113+ Cancel,
114+ Rename,
115+ RenameNotebook,
116+ NotebookOptions,
117+ DeleteNotebook,
118+ DeleteNotebookTitle,
119+ DeleteNotebookBody,
120+ Breadcrumb,
121+ NoMatches,
122+ GuestName,
123+ GuestSubtitle,
124+ AccountMenu,
125+ SearchOptions,
126+ MatchCase,
127+ WholeWord,
128+ ExactPhrase,
129+ RegexSearch,
130+ InvalidRegex,
131+ InvalidRegexHint,
132+ CheckSpelling,
133+ NoteActions,
134+ VersionHistory,
135+ CurrentVersion,
136+ NoVersionsYet,
137+ RestoreVersion,
138+ BackToNote,
139+ ToastVersionRestored,
140+ Import,
141+ ImportMarkdown,
142+ ImportHelp,
143+ ChooseFiles,
144+ ChooseFolder,
145+ ImportProgress,
146+ ImportDoneOne,
147+ ImportDoneMany,
148+ ImportFailed,
149+ ImportNoFiles,
150+ ImportGoToNotes,
151+ LinkedFrom,
152+ NoNoteNamed,
153+ CreateNote,
154+}
155+
156+/// The text of `msg` in `lang`.
157+pub fn t(lang: Lang, msg: Msg) -> &'static str {
158+ // (English, Turkish) for every message.
159+ let (en, tr) = match msg {
160+ Msg::AppName => ("Notes", "Notlar"),
161+ Msg::MainNavigation => ("Main navigation", "Ana gezinme"),
162+ Msg::SkipToContent => ("Skip to content", "İçeriğe geç"),
163+ Msg::Search => ("Search", "Ara"),
164+ Msg::SearchLabel => ("Search notes", "Notlarda ara"),
165+ Msg::SearchPlaceholder => ("Search notes", "Notlarda ara"),
166+ Msg::NewNote => ("New note", "Yeni not"),
167+ Msg::NewNotebook => ("New notebook", "Yeni defter"),
168+ Msg::NewNotebookLabel => ("Notebook name", "Defter adı"),
169+ Msg::Add => ("Add", "Ekle"),
170+ Msg::AllNotes => ("All notes", "Tüm notlar"),
171+ Msg::Unfiled => ("Unfiled", "Dosyalanmamış"),
172+ Msg::Trash => ("Trash", "Çöp kutusu"),
173+ Msg::Notebooks => ("Notebooks", "Defterler"),
174+ Msg::Theme => ("Theme", "Tema"),
175+ Msg::ThemeLight => ("Light", "Açık"),
176+ Msg::ThemeDark => ("Dark", "Koyu"),
177+ Msg::ThemeSystem => ("System", "Sistem"),
178+ Msg::ColorScheme => ("Color scheme", "Renk şeması"),
179+ Msg::Language => ("Language", "Dil"),
180+ Msg::LanguageEnglish => ("English", "English"),
181+ Msg::LanguageTurkish => ("Türkçe", "Türkçe"),
182+ Msg::HideSidebar => ("Hide sidebar", "Kenar çubuğunu gizle"),
183+ Msg::ShowSidebar => ("Show sidebar", "Kenar çubuğunu göster"),
184+ Msg::OpenMenu => ("Open menu", "Menüyü aç"),
185+ Msg::CloseMenu => ("Close menu", "Menüyü kapat"),
186+ Msg::Undo => ("Undo", "Geri al"),
187+ Msg::Dismiss => ("Dismiss", "Kapat"),
188+ Msg::ToastTrashed => ("Note moved to trash.", "Not çöp kutusuna taşındı."),
189+ Msg::ToastRestored => ("Note restored.", "Not geri yüklendi."),
190+ Msg::ToastNotebookCreated => ("Notebook created.", "Defter oluşturuldu."),
191+ Msg::ToastNotebookDeleted => ("Notebook deleted.", "Defter silindi."),
192+ Msg::ToastMoved => ("Note moved.", "Not taşındı."),
193+ Msg::Untitled => ("Untitled", "Adsız"),
194+ Msg::JustNow => ("Just now", "Az önce"),
195+ Msg::Yesterday => ("Yesterday", "Dün"),
196+ Msg::NoNotesYet => ("No notes yet.", "Henüz not yok."),
197+ Msg::CreateOneHint => ("to create one.", "ile yeni not oluştur."),
198+ Msg::EmptyNotebook => ("Nothing in this notebook.", "Bu defterde not yok."),
199+ Msg::EmptyUnfiled => ("Nothing unfiled.", "Dosyalanmamış not yok."),
200+ Msg::EmptyTrash => ("Trash is empty.", "Çöp kutusu boş."),
201+ Msg::SelectNote => ("Select a note", "Bir not seçin"),
202+ Msg::GroupToday => ("Today", "Bugün"),
203+ Msg::GroupPrevious7 => ("Previous 7 days", "Önceki 7 gün"),
204+ Msg::GroupEarlier => ("Earlier", "Daha önce"),
205+ Msg::BackToList => ("Back to list", "Listeye dön"),
206+ Msg::MoveToNotebook => ("Move to notebook", "Defterine taşı"),
207+ Msg::AlreadyHere => ("Already in this notebook.", "Zaten bu defterde."),
208+ Msg::ExportAs => ("Export as", "Şu biçimde dışa aktar"),
209+ Msg::ExportMarkdown => ("Markdown (.md)", "Markdown (.md)"),
210+ Msg::ExportHtml => ("HTML (.html)", "HTML (.html)"),
211+ Msg::ExportPdf => ("PDF (print)", "PDF (yazdır)"),
212+ Msg::ExportAll => ("Export all notes (.zip)", "Tüm notları dışa aktar (.zip)"),
213+ Msg::MoveToTrash => ("Move to trash", "Çöp kutusuna taşı"),
214+ Msg::InTrash => ("This note is in the trash.", "Bu not çöp kutusunda."),
215+ Msg::AlreadyInTrash => ("Already in the trash.", "Zaten çöp kutusunda."),
216+ Msg::RestoreFirst => ("Restore the note to move it.", "Notu taşımak için geri yükleyin."),
217+ Msg::Restore => ("Restore", "Geri yükle"),
218+ Msg::DeleteForever => ("Delete forever", "Kalıcı olarak sil"),
219+ Msg::EmptyTrashAction => ("Empty trash", "Çöp kutusunu boşalt"),
220+ Msg::TrashRetention => (
221+ "Notes in the trash are deleted after 30 days.",
222+ "Çöp kutusundaki notlar 30 gün sonra silinir.",
223+ ),
224+ Msg::Trashed => ("Trashed", "Çöpe taşındı"),
225+ Msg::ConfirmEmptyTrashTitle => ("Empty trash?", "Çöp kutusu boşaltılsın mı?"),
226+ Msg::ConfirmForeverTitle => ("Delete this note forever?", "Bu not kalıcı olarak silinsin mi?"),
227+ Msg::CannotUndo => ("This cannot be undone.", "Bu işlem geri alınamaz."),
228+ Msg::Cancel => ("Cancel", "İptal"),
229+ Msg::Rename => ("Rename", "Yeniden adlandır"),
230+ Msg::RenameNotebook => ("Rename notebook", "Defteri yeniden adlandır"),
231+ Msg::NotebookOptions => ("Notebook options", "Defter seçenekleri"),
232+ Msg::DeleteNotebook => ("Delete notebook", "Defteri sil"),
233+ Msg::DeleteNotebookTitle => ("Delete notebook?", "Defter silinsin mi?"),
234+ Msg::DeleteNotebookBody => ("Its notes move to Unfiled.", "Notları Dosyalanmamış bölümüne taşınır."),
235+ Msg::Breadcrumb => ("Breadcrumb", "Konum"),
236+ Msg::NoMatches => ("No notes match.", "Eşleşen not yok."),
237+ Msg::GuestName => ("Guest", "Misafir"),
238+ Msg::GuestSubtitle => ("Personal library", "Kişisel kitaplık"),
239+ Msg::AccountMenu => ("Account menu", "Hesap menüsü"),
240+ Msg::SearchOptions => ("Search options", "Arama seçenekleri"),
241+ Msg::MatchCase => ("Match case", "Büyük/küçük harfe duyarlı"),
242+ Msg::WholeWord => ("Whole word", "Tam kelime"),
243+ Msg::ExactPhrase => ("Exact phrase", "Tam ifade"),
244+ Msg::RegexSearch => ("Regular expression", "Düzenli ifade"),
245+ Msg::InvalidRegex => ("Not a valid regular expression.", "Geçerli bir düzenli ifade değil."),
246+ Msg::InvalidRegexHint => ("Check the brackets and escapes.", "Parantezleri ve kaçış karakterlerini kontrol edin."),
247+ Msg::CheckSpelling => (
248+ "Check the spelling or try fewer words.",
249+ "Yazımı kontrol edin ya da daha az kelime deneyin.",
250+ ),
251+ Msg::NoteActions => ("Note actions", "Not işlemleri"),
252+ Msg::Import => ("Import Markdown", "Markdown içe aktar"),
253+ Msg::ImportMarkdown => ("Import Markdown…", "Markdown içe aktar…"),
254+ Msg::ImportHelp => (
255+ "Import .md files or a whole folder (e.g. an Obsidian vault). Each subfolder becomes a notebook.",
256+ "Tek tek .md dosyaları ya da bütün bir klasörü (ör. bir Obsidian kasası) içe aktarın. Her alt klasör bir deftere dönüşür.",
257+ ),
258+ Msg::ChooseFiles => ("Choose files", "Dosya seç"),
259+ Msg::ChooseFolder => ("Choose folder", "Klasör seç"),
260+ Msg::ImportProgress => ("Importing {done} of {total}…", "{done} / {total} içe aktarılıyor…"),
261+ Msg::ImportDoneOne => ("Imported {n} note.", "{n} not içe aktarıldı."),
262+ Msg::ImportDoneMany => ("Imported {n} notes.", "{n} not içe aktarıldı."),
263+ Msg::ImportFailed => ("{m} failed.", "{m} başarısız."),
264+ Msg::ImportNoFiles => (
265+ "No .md, .markdown or .txt files found.",
266+ ".md, .markdown ya da .txt dosyası bulunamadı.",
267+ ),
268+ Msg::ImportGoToNotes => ("Go to notes", "Notlara git"),
269+ Msg::LinkedFrom => ("Linked from", "Bağlantı veren notlar"),
270+ Msg::NoNoteNamed => ("No note named \u{201c}{title}\u{201d}.", "\u{201c}{title}\u{201d} adlı not yok."),
271+ Msg::CreateNote => ("Create note", "Not oluştur"),
272+ Msg::VersionHistory => ("Version history", "Sürüm geçmişi"),
273+ Msg::CurrentVersion => ("Current version", "Güncel sürüm"),
274+ Msg::NoVersionsYet => (
275+ "No earlier versions yet. Versions are saved every 10 minutes while you write.",
276+ "Henüz önceki sürüm yok. Yazarken sürümler her 10 dakikada bir kaydedilir.",
277+ ),
278+ Msg::RestoreVersion => ("Restore this version", "Bu sürümü geri yükle"),
279+ Msg::BackToNote => ("Back to note", "Nota dön"),
280+ Msg::ToastVersionRestored => ("Version restored.", "Sürüm geri yüklendi."),
281+ };
282+ match lang {
283+ Lang::En => en,
284+ Lang::Tr => tr,
285+ }
286+}
287+
288+/// "1 note" / "3 notes". Turkish does not inflect the noun after a number: "1 not", "3 not".
289+pub fn notes_count(lang: Lang, n: usize) -> String {
290+ match lang {
291+ Lang::En if n == 1 => "1 note".to_owned(),
292+ Lang::En => format!("{n} notes"),
293+ Lang::Tr => format!("{n} not"),
294+ }
295+}
296+
297+/// "1 result for “rust”" / "3 results for “rust”", or the Turkish "3 sonuç “rust” için".
298+pub fn results_for(lang: Lang, n: usize, query: &str) -> String {
299+ match lang {
300+ Lang::En if n == 1 => format!("1 result for \u{201c}{query}\u{201d}"),
301+ Lang::En => format!("{n} results for \u{201c}{query}\u{201d}"),
302+ Lang::Tr => format!("{n} sonuç \u{201c}{query}\u{201d} için"),
303+ }
304+}
305+
306+/// The consequence line of the empty-trash dialog: "This deletes 3 notes forever." /
307+/// "3 not kalıcı olarak silinecek."
308+pub fn forever_count(lang: Lang, n: usize) -> String {
309+ match lang {
310+ Lang::En => format!("This deletes {} forever.", notes_count(lang, n)),
311+ Lang::Tr => format!("{} kalıcı olarak silinecek.", notes_count(lang, n)),
312+ }
313+}
314+
315+/// A relative time such as "5 min ago" or "5 dk önce", a day name, or a date for older
316+/// times. `now_ms` is the current time in Unix milliseconds.
317+pub fn relative_time(lang: Lang, updated_ms: i64, now_ms: i64) -> String {
318+ let secs = (now_ms - updated_ms).max(0) / 1000;
319+ let mins = secs / 60;
320+ let hours = secs / 3600;
321+ let days = secs / 86_400;
322+ if secs < 60 {
323+ t(lang, Msg::JustNow).to_owned()
324+ } else if secs < 3600 {
325+ match lang {
326+ Lang::En => format!("{mins} min ago"),
327+ Lang::Tr => format!("{mins} dk önce"),
328+ }
329+ } else if secs < 86_400 {
330+ match lang {
331+ Lang::En => format!("{hours} h ago"),
332+ Lang::Tr => format!("{hours} sa önce"),
333+ }
334+ } else if days == 1 {
335+ t(lang, Msg::Yesterday).to_owned()
336+ } else if days < 7 {
337+ match lang {
338+ Lang::En => format!("{days} days ago"),
339+ Lang::Tr => format!("{days} gün önce"),
340+ }
341+ } else {
342+ date(lang, updated_ms)
343+ }
344+}
345+
346+/// A calendar date in UTC: "Oct 27, 2026" in English, "27 Eki 2026" in Turkish.
347+pub fn date(lang: Lang, ms: i64) -> String {
348+ const EN: [&str; 12] = [
349+ "Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec",
350+ ];
351+ const TR: [&str; 12] = [
352+ "Oca", "Şub", "Mar", "Nis", "May", "Haz", "Tem", "Ağu", "Eyl", "Eki", "Kas", "Ara",
353+ ];
354+ // Civil-from-days (Howard Hinnant's algorithm).
355+ let z = ms.div_euclid(86_400_000) + 719_468;
356+ let era = z.div_euclid(146_097);
357+ let doe = z - era * 146_097;
358+ let yoe = (doe - doe / 1460 + doe / 36_524 - doe / 146_096) / 365;
359+ let doy = doe - (365 * yoe + yoe / 4 - yoe / 100);
360+ let mp = (5 * doy + 2) / 153;
361+ let day = doy - (153 * mp + 2) / 5 + 1;
362+ let month = if mp < 10 { mp + 3 } else { mp - 9 };
363+ let year = yoe + era * 400 + if month <= 2 { 1 } else { 0 };
364+ let idx = (month - 1) as usize;
365+ match lang {
366+ Lang::En => format!("{} {}, {}", EN[idx], day, year),
367+ Lang::Tr => format!("{} {} {}", day, TR[idx], year),
368+ }
369+}
370+
371+/// A date and UTC time: "Oct 27, 2026 14:05" in English, "27 Eki 2026 14:05" in Turkish.
372+pub fn date_time(lang: Lang, ms: i64) -> String {
373+ let minutes = ms.rem_euclid(86_400_000) / 60_000;
374+ format!("{} {:02}:{:02}", date(lang, ms), minutes / 60, minutes % 60)
375+}
376+
377+/// Picks the language from an `Accept-Language` header: the first listed language that is
378+/// English or Turkish. Anything else falls back to English.
379+pub fn from_accept_language(header: &str) -> Lang {
380+ for part in header.split(',') {
381+ let tag = part.split(';').next().unwrap_or("").trim().to_ascii_lowercase();
382+ if tag.starts_with("tr") {
383+ return Lang::Tr;
384+ }
385+ if tag.starts_with("en") {
386+ return Lang::En;
387+ }
388+ }
389+ Lang::En
390+}
391+
392+/// The language of this request. The `lang` cookie wins; without it, the browser's
393+/// `Accept-Language` decides; otherwise English.
394+pub fn lang(cx: &Cx) -> Lang {
395+ if let Some(cookie) = cookies(cx).get(LANG_COOKIE) {
396+ if let Some(lang) = Lang::from_code(cookie.value()) {
397+ return lang;
398+ }
399+ }
400+ let header = headers(cx)
401+ .get("accept-language")
402+ .and_then(|value| value.to_str().ok())
403+ .unwrap_or("");
404+ from_accept_language(header)
405+}
406+
407+/// The cookie that remembers `lang` for a year.
408+pub fn lang_cookie(lang: Lang) -> Cookie<'static> {
409+ Cookie::build((LANG_COOKIE, lang.code()))
410+ .path("/")
411+ .same_site(SameSite::Lax)
412+ .max_age(Duration::days(LANG_COOKIE_DAYS))
413+ .build()
414+}
src/import.rsadded+743 -0
@@ -0,0 +1,743 @@
1+//! Markdown import: the inverse of `export.rs`. Parses CommonMark into a
2+//! loro-prosemirror shaped LoroDoc (same layout as `export::to_markdown` reads).
3+//!
4+//! Degradations (GFM bits that the schema cannot represent):
5+//! - strikethrough: content kept, no mark
6+//! - tables: one paragraph per row, cells joined with " | "
7+//! - task list items: normal list items with a "[ ] " / "[x] " text prefix
8+//! - raw HTML (block or inline): its text, as plain text
9+//! - footnotes: not enabled, so `[^x]` stays literal text
10+//! - soft breaks become a space, hard breaks become `hard_break` nodes
11+//! - wiki links `[[Title]]`, `[[Title|text]]`, `[[Title#heading]]` in plain text become
12+//! links to `/notes/by-title/<Title>`; embeds `![[...]]` stay plain text
13+
14+use std::collections::HashMap;
15+
16+use anyhow::Result;
17+use loro::{
18+ ExpandType, ExportMode, LoroDoc, LoroList, LoroMap, LoroResult, LoroText, LoroValue,
19+ StyleConfig, StyleConfigMap,
20+};
21+use pulldown_cmark::{CodeBlockKind, Event, HeadingLevel, Options, Parser, Tag};
22+
23+/// Parses markdown into a fresh LoroDoc with the note layout.
24+pub fn markdown_to_doc(md: &str) -> Result<LoroDoc> {
25+ let body = strip_front_matter(md);
26+ let mut options = Options::empty();
27+ options.insert(Options::ENABLE_STRIKETHROUGH);
28+ options.insert(Options::ENABLE_TABLES);
29+ options.insert(Options::ENABLE_TASKLISTS);
30+ let events: Vec<Event> = Parser::new_ext(body, options).collect();
31+ let mut pos = 0;
32+ let blocks = parse_blocks(&events, &mut pos, false);
33+ build(&blocks)
34+}
35+
36+/// Same as `markdown_to_doc`, exported as a full Loro update.
37+pub fn markdown_to_update(md: &str) -> Result<Vec<u8>> {
38+ let doc = markdown_to_doc(md)?;
39+ Ok(doc.export(ExportMode::all_updates())?)
40+}
41+
42+/// A relative link to a `.md` file (`[text](Some%20Note.md)`, also what export writes for
43+/// note links with mixed formatting) becomes a link to the note with that file's name.
44+/// Any other destination is kept.
45+fn note_file_href(dest: &str) -> String {
46+ let path = dest.split('#').next().unwrap_or(dest);
47+ let relative = !path.contains("://") && !path.starts_with(['/', '?']) && !path.starts_with("mailto:");
48+ let Some(stem) = path.strip_suffix(".md").filter(|_| relative) else {
49+ return dest.to_string();
50+ };
51+ let decoded = crate::export::percent_decode(stem);
52+ let title = decoded.rsplit('/').next().unwrap_or(&decoded).trim();
53+ if title.is_empty() {
54+ return dest.to_string();
55+ }
56+ format!("/notes/by-title/{}", crate::export::percent_encode(title))
57+}
58+
59+/// Drops a leading `---` ... `---` YAML block. Unclosed blocks are kept as text.
60+pub fn strip_front_matter(md: &str) -> &str {
61+ let mut lines = md.split_inclusive('\n');
62+ let Some(first) = lines.next() else {
63+ return md;
64+ };
65+ if first.trim_end() != "---" {
66+ return md;
67+ }
68+ let mut offset = first.len();
69+ for line in lines {
70+ offset += line.len();
71+ if line.trim_end() == "---" {
72+ return &md[offset..];
73+ }
74+ }
75+ md
76+}
77+
78+// ---------------------------------------------------------------------------
79+// Intermediate tree
80+// ---------------------------------------------------------------------------
81+
82+#[derive(Clone, Default, PartialEq)]
83+struct Marks {
84+ strong: bool,
85+ em: bool,
86+ code: bool,
87+ link: Option<(String, Option<String>)>,
88+}
89+
90+#[derive(Clone)]
91+enum Inline {
92+ Text(String, Marks),
93+ HardBreak,
94+ Image {
95+ src: String,
96+ alt: String,
97+ title: Option<String>,
98+ },
99+}
100+
101+enum Block {
102+ Paragraph(Vec<Inline>),
103+ Heading(i64, Vec<Inline>),
104+ Quote(Vec<Block>),
105+ Code { lang: Option<String>, text: String },
106+ Rule,
107+ List {
108+ ordered: bool,
109+ start: i64,
110+ items: Vec<Vec<Block>>,
111+ },
112+}
113+
114+// ---------------------------------------------------------------------------
115+// Event -> tree
116+// ---------------------------------------------------------------------------
117+
118+/// Parses block events starting at `pos`. In `nested` mode it returns after
119+/// consuming the End event of its container.
120+fn parse_blocks(ev: &[Event<'_>], pos: &mut usize, nested: bool) -> Vec<Block> {
121+ let mut out = Vec::new();
122+ while let Some(event) = ev.get(*pos) {
123+ match event {
124+ Event::End(_) => {
125+ *pos += 1;
126+ if nested {
127+ break;
128+ }
129+ }
130+ Event::Start(Tag::Paragraph) => {
131+ *pos += 1;
132+ let inl = inlines(ev, pos);
133+ skip_end(ev, pos);
134+ out.push(Block::Paragraph(inl));
135+ }
136+ Event::Start(Tag::Heading { level, .. }) => {
137+ *pos += 1;
138+ let inl = inlines(ev, pos);
139+ skip_end(ev, pos);
140+ out.push(Block::Heading(heading_level(*level), inl));
141+ }
142+ Event::Start(Tag::BlockQuote(_)) => {
143+ *pos += 1;
144+ let inner = parse_blocks(ev, pos, true);
145+ out.push(Block::Quote(inner));
146+ }
147+ Event::Start(Tag::CodeBlock(kind)) => {
148+ let lang = match kind {
149+ CodeBlockKind::Fenced(info) => {
150+ info.split_whitespace().next().map(str::to_owned)
151+ }
152+ CodeBlockKind::Indented => None,
153+ };
154+ *pos += 1;
155+ let mut text = String::new();
156+ while let Some(e) = ev.get(*pos) {
157+ *pos += 1;
158+ match e {
159+ Event::End(_) => break,
160+ Event::Text(t) => text.push_str(t),
161+ _ => {}
162+ }
163+ }
164+ out.push(Block::Code {
165+ lang,
166+ text: text.trim_end_matches('\n').to_owned(),
167+ });
168+ }
169+ Event::Start(Tag::HtmlBlock) => {
170+ *pos += 1;
171+ let mut text = String::new();
172+ while let Some(e) = ev.get(*pos) {
173+ *pos += 1;
174+ match e {
175+ Event::End(_) => break,
176+ Event::Html(t) | Event::Text(t) => text.push_str(t),
177+ _ => {}
178+ }
179+ }
180+ let t = text.trim();
181+ if !t.is_empty() {
182+ out.push(Block::Paragraph(vec![Inline::Text(
183+ t.to_owned(),
184+ Marks::default(),
185+ )]));
186+ }
187+ }
188+ Event::Start(Tag::List(start)) => {
189+ *pos += 1;
190+ let mut items = Vec::new();
191+ while let Some(e) = ev.get(*pos) {
192+ match e {
193+ Event::End(_) => {
194+ *pos += 1;
195+ break;
196+ }
197+ Event::Start(Tag::Item) => {
198+ *pos += 1;
199+ let mut blocks = parse_blocks(ev, pos, true);
200+ // Schema: list_item content is "paragraph block*".
201+ if !matches!(blocks.first(), Some(Block::Paragraph(_))) {
202+ blocks.insert(0, Block::Paragraph(Vec::new()));
203+ }
204+ items.push(blocks);
205+ }
206+ _ => *pos += 1,
207+ }
208+ }
209+ out.push(Block::List {
210+ ordered: start.is_some(),
211+ start: (*start).unwrap_or(1) as i64,
212+ items,
213+ });
214+ }
215+ Event::Start(Tag::Table(_)) => {
216+ *pos += 1;
217+ parse_table(ev, pos, &mut out);
218+ }
219+ Event::Start(Tag::Item) => {
220+ // Item outside a list: keep its content.
221+ *pos += 1;
222+ out.extend(parse_blocks(ev, pos, true));
223+ }
224+ Event::Rule => {
225+ out.push(Block::Rule);
226+ *pos += 1;
227+ }
228+ // Inline content outside a paragraph (tight list items, table-less
229+ // loose text): wrap the run in a paragraph.
230+ Event::Text(_)
231+ | Event::Code(_)
232+ | Event::SoftBreak
233+ | Event::HardBreak
234+ | Event::InlineHtml(_)
235+ | Event::Html(_)
236+ | Event::TaskListMarker(_)
237+ | Event::FootnoteReference(_)
238+ | Event::InlineMath(_)
239+ | Event::DisplayMath(_)
240+ | Event::Start(
241+ Tag::Emphasis
242+ | Tag::Strong
243+ | Tag::Strikethrough
244+ | Tag::Superscript
245+ | Tag::Subscript
246+ | Tag::Link { .. }
247+ | Tag::Image { .. },
248+ ) => {
249+ let inl = inlines(ev, pos);
250+ if !is_blank(&inl) {
251+ out.push(Block::Paragraph(inl));
252+ }
253+ }
254+ // Unknown containers (footnote definitions, metadata, ...): keep content.
255+ Event::Start(_) => {
256+ *pos += 1;
257+ out.extend(parse_blocks(ev, pos, true));
258+ }
259+ }
260+ }
261+ out
262+}
263+
264+/// Tables: each row becomes a paragraph with cells joined by " | ".
265+/// Assumes `pos` is just past `Start(Table)`; consumes the table's End.
266+fn parse_table(ev: &[Event<'_>], pos: &mut usize, out: &mut Vec<Block>) {
267+ while let Some(e) = ev.get(*pos) {
268+ match e {
269+ Event::End(_) => {
270+ *pos += 1;
271+ break;
272+ }
273+ Event::Start(Tag::TableHead | Tag::TableRow) => {
274+ *pos += 1;
275+ let mut cells = Vec::new();
276+ while let Some(c) = ev.get(*pos) {
277+ match c {
278+ Event::End(_) => {
279+ *pos += 1;
280+ break;
281+ }
282+ Event::Start(Tag::TableCell) => {
283+ *pos += 1;
284+ let mut inl = Vec::new();
285+ parse_inlines(ev, pos, &Marks::default(), &mut inl, true);
286+ cells.push(inl);
287+ }
288+ _ => *pos += 1,
289+ }
290+ }
291+ out.extend(table_row(cells));
292+ }
293+ _ => *pos += 1,
294+ }
295+ }
296+}
297+
298+fn table_row(cells: Vec<Vec<Inline>>) -> Option<Block> {
299+ let mut inl = Vec::new();
300+ for (i, cell) in cells.into_iter().enumerate() {
301+ if i > 0 {
302+ inl.push(Inline::Text(" | ".to_owned(), Marks::default()));
303+ }
304+ inl.extend(cell);
305+ }
306+ if is_blank(&inl) {
307+ None
308+ } else {
309+ Some(Block::Paragraph(inl))
310+ }
311+}
312+
313+fn inlines(ev: &[Event<'_>], pos: &mut usize) -> Vec<Inline> {
314+ let mut out = Vec::new();
315+ parse_inlines(ev, pos, &Marks::default(), &mut out, false);
316+ out
317+}
318+
319+/// Collects inline content. With `closing`, it also consumes the End event that
320+/// closes the current inline span. Without it, it stops before the first
321+/// non-inline event (the caller handles that event).
322+fn parse_inlines(
323+ ev: &[Event<'_>],
324+ pos: &mut usize,
325+ marks: &Marks,
326+ out: &mut Vec<Inline>,
327+ closing: bool,
328+) {
329+ while let Some(event) = ev.get(*pos) {
330+ match event {
331+ Event::End(_) => {
332+ if closing {
333+ *pos += 1;
334+ }
335+ return;
336+ }
337+ Event::Text(s)
338+ | Event::Html(s)
339+ | Event::InlineHtml(s)
340+ | Event::InlineMath(s)
341+ | Event::DisplayMath(s) => {
342+ out.push(Inline::Text(s.to_string(), marks.clone()));
343+ *pos += 1;
344+ }
345+ Event::FootnoteReference(s) => {
346+ out.push(Inline::Text(format!("[^{s}]"), marks.clone()));
347+ *pos += 1;
348+ }
349+ Event::Code(s) => {
350+ let mut m = marks.clone();
351+ m.code = true;
352+ out.push(Inline::Text(s.to_string(), m));
353+ *pos += 1;
354+ }
355+ Event::SoftBreak => {
356+ out.push(Inline::Text(" ".to_owned(), marks.clone()));
357+ *pos += 1;
358+ }
359+ Event::HardBreak => {
360+ out.push(Inline::HardBreak);
361+ *pos += 1;
362+ }
363+ Event::TaskListMarker(done) => {
364+ let s = if *done { "[x] " } else { "[ ] " };
365+ out.push(Inline::Text(s.to_owned(), Marks::default()));
366+ *pos += 1;
367+ }
368+ Event::Start(Tag::Emphasis) => {
369+ *pos += 1;
370+ let mut m = marks.clone();
371+ m.em = true;
372+ parse_inlines(ev, pos, &m, out, true);
373+ }
374+ Event::Start(Tag::Strong) => {
375+ *pos += 1;
376+ let mut m = marks.clone();
377+ m.strong = true;
378+ parse_inlines(ev, pos, &m, out, true);
379+ }
380+ // Degraded: content kept, no mark.
381+ Event::Start(Tag::Strikethrough | Tag::Superscript | Tag::Subscript) => {
382+ *pos += 1;
383+ parse_inlines(ev, pos, marks, out, true);
384+ }
385+ Event::Start(Tag::Link {
386+ dest_url, title, ..
387+ }) => {
388+ *pos += 1;
389+ let mut m = marks.clone();
390+ let title = (!title.is_empty()).then(|| title.to_string());
391+ m.link = Some((note_file_href(&dest_url), title));
392+ parse_inlines(ev, pos, &m, out, true);
393+ }
394+ Event::Start(Tag::Image {
395+ dest_url, title, ..
396+ }) => {
397+ *pos += 1;
398+ let mut alt = Vec::new();
399+ parse_inlines(ev, pos, marks, &mut alt, true);
400+ let title = (!title.is_empty()).then(|| title.to_string());
401+ out.push(Inline::Image {
402+ src: dest_url.to_string(),
403+ alt: plain(&alt),
404+ title,
405+ });
406+ }
407+ // Block-level event: the inline run ends here.
408+ _ => return,
409+ }
410+ }
411+}
412+
413+fn skip_end(ev: &[Event<'_>], pos: &mut usize) {
414+ if matches!(ev.get(*pos), Some(Event::End(_))) {
415+ *pos += 1;
416+ }
417+}
418+
419+fn is_blank(inl: &[Inline]) -> bool {
420+ inl.iter()
421+ .all(|i| matches!(i, Inline::Text(s, _) if s.trim().is_empty()))
422+}
423+
424+fn plain(inl: &[Inline]) -> String {
425+ inl.iter()
426+ .map(|i| match i {
427+ Inline::Text(s, _) => s.as_str(),
428+ Inline::HardBreak => " ",
429+ Inline::Image { alt, .. } => alt.as_str(),
430+ })
431+ .collect()
432+}
433+
434+fn heading_level(level: HeadingLevel) -> i64 {
435+ match level {
436+ HeadingLevel::H1 => 1,
437+ HeadingLevel::H2 => 2,
438+ HeadingLevel::H3 => 3,
439+ HeadingLevel::H4 => 4,
440+ HeadingLevel::H5 => 5,
441+ HeadingLevel::H6 => 6,
442+ }
443+}
444+
445+// ---------------------------------------------------------------------------
446+// Tree -> LoroDoc
447+// ---------------------------------------------------------------------------
448+
449+/// Builds the document. Mirrors `hub::initial_note_update`: an empty input
450+/// yields a single empty paragraph.
451+fn build(blocks: &[Block]) -> Result<LoroDoc> {
452+ let doc = LoroDoc::new();
453+
454+ // Same expand rules as loro-prosemirror's getLoroTextStyle.
455+ let mut styles = StyleConfigMap::new();
456+ styles.insert(
457+ "strong".into(),
458+ StyleConfig::new().expand(ExpandType::After),
459+ );
460+ styles.insert("em".into(), StyleConfig::new().expand(ExpandType::After));
461+ styles.insert("code".into(), StyleConfig::new().expand(ExpandType::After));
462+ styles.insert("link".into(), StyleConfig::new().expand(ExpandType::None));
463+ doc.config_text_style(styles);
464+
465+ let root = doc.get_map("doc");
466+ root.insert("nodeName", "doc")?;
467+ root.insert_container("attributes", LoroMap::new())?;
468+ let children = root.insert_container("children", LoroList::new())?;
469+ if blocks.is_empty() {
470+ push_node(&children, "paragraph", Vec::new())?;
471+ } else {
472+ for block in blocks {
473+ write_block(&children, block)?;
474+ }
475+ }
476+ doc.commit();
477+ Ok(doc)
478+}
479+
480+/// Appends a node to `list` and returns its `children` list. Null attributes
481+/// are not written.
482+fn push_node(list: &LoroList, name: &str, attrs: Vec<(&str, LoroValue)>) -> LoroResult<LoroList> {
483+ let node = list.push_container(LoroMap::new())?;
484+ node.insert("nodeName", name)?;
485+ let attributes = node.insert_container("attributes", LoroMap::new())?;
486+ for (key, value) in attrs {
487+ attributes.insert(key, value)?;
488+ }
489+ node.insert_container("children", LoroList::new())
490+}
491+
492+fn write_block(list: &LoroList, block: &Block) -> LoroResult<()> {
493+ match block {
494+ Block::Paragraph(inl) => {
495+ let children = push_node(list, "paragraph", Vec::new())?;
496+ write_inlines(&children, inl)?;
497+ }
498+ Block::Heading(level, inl) => {
499+ let children = push_node(list, "heading", vec![("level", (*level).into())])?;
500+ write_inlines(&children, inl)?;
501+ }
502+ Block::Quote(blocks) => {
503+ let children = push_node(list, "blockquote", Vec::new())?;
504+ for b in blocks {
505+ write_block(&children, b)?;
506+ }
507+ }
508+ Block::Code { lang, text } => {
509+ let attrs: Vec<(&str, LoroValue)> = lang
510+ .iter()
511+ .map(|l| ("language", LoroValue::from(l.as_str())))
512+ .collect();
513+ let children = push_node(list, "code_block", attrs)?;
514+ if !text.is_empty() {
515+ let t = children.push_container(LoroText::new())?;
516+ t.insert(0, text)?;
517+ }
518+ }
519+ Block::Rule => {
520+ push_node(list, "horizontal_rule", Vec::new())?;
521+ }
522+ Block::List {
523+ ordered,
524+ start,
525+ items,
526+ } => {
527+ let children = if *ordered {
528+ push_node(list, "ordered_list", vec![("order", (*start).into())])?
529+ } else {
530+ push_node(list, "bullet_list", Vec::new())?
531+ };
532+ for item in items {
533+ let item_children = push_node(&children, "list_item", Vec::new())?;
534+ for b in item {
535+ write_block(&item_children, b)?;
536+ }
537+ }
538+ }
539+ }
540+ Ok(())
541+}
542+
543+/// Consecutive text runs share one LoroText; inline nodes get their own child.
544+fn write_inlines(list: &LoroList, inl: &[Inline]) -> LoroResult<()> {
545+ let owned = wikilinks(inl);
546+ let inl = owned.as_slice();
547+ let mut i = 0;
548+ while let Some(item) = inl.get(i) {
549+ match item {
550+ Inline::Text(..) => {
551+ let mut j = i;
552+ let mut full = String::new();
553+ let mut spans: Vec<(std::ops::Range<usize>, Marks)> = Vec::new();
554+ while let Some(Inline::Text(s, m)) = inl.get(j) {
555+ let start = full.chars().count();
556+ full.push_str(s);
557+ let end = full.chars().count();
558+ if end > start {
559+ spans.push((start..end, m.clone()));
560+ }
561+ j += 1;
562+ }
563+ if !full.is_empty() {
564+ let text = list.push_container(LoroText::new())?;
565+ text.insert(0, &full)?;
566+ for (range, marks) in spans {
567+ apply_marks(&text, range, &marks)?;
568+ }
569+ }
570+ i = j;
571+ }
572+ Inline::HardBreak => {
573+ push_node(list, "hard_break", Vec::new())?;
574+ i += 1;
575+ }
576+ Inline::Image { src, alt, title } => {
577+ let mut attrs: Vec<(&str, LoroValue)> =
578+ vec![("src", LoroValue::from(src.as_str())), ("alt", LoroValue::from(alt.as_str()))];
579+ if let Some(t) = title {
580+ attrs.push(("title", LoroValue::from(t.as_str())));
581+ }
582+ push_node(list, "image", attrs)?;
583+ i += 1;
584+ }
585+ }
586+ }
587+ Ok(())
588+}
589+
590+/// Turns `[[Title]]`, `[[Title|text]]` and `[[Title#heading]]` in plain text into links
591+/// to `/notes/by-title/<Title>`, showing the text (or the title). Code, existing links and
592+/// embeds (`![[...]]`, kept as text) are left alone.
593+fn wikilinks(inl: &[Inline]) -> Vec<Inline> {
594+ // Adjacent runs with the same marks are joined first, since a `[[` can be split
595+ // across parser events.
596+ let mut merged: Vec<Inline> = Vec::new();
597+ for item in inl {
598+ if let Inline::Text(s, m) = item {
599+ if let Some(Inline::Text(prev, pm)) = merged.last_mut() {
600+ if *pm == *m {
601+ prev.push_str(s);
602+ continue;
603+ }
604+ }
605+ }
606+ merged.push(item.clone());
607+ }
608+
609+ let mut out = Vec::with_capacity(merged.len());
610+ for item in merged {
611+ match item {
612+ Inline::Text(s, m) if !m.code && m.link.is_none() => split_wikilinks(&s, &m, &mut out),
613+ other => out.push(other),
614+ }
615+ }
616+ out
617+}
618+
619+fn split_wikilinks(s: &str, marks: &Marks, out: &mut Vec<Inline>) {
620+ let mut rest = s;
621+ while let Some(open) = rest.find("[[") {
622+ let after = &rest[open + 2..];
623+ let embed = rest[..open].ends_with('!');
624+ let parsed = after
625+ .find("]]")
626+ .and_then(|close| wikilink_parts(&after[..close]).map(|parts| (close, parts)));
627+ match parsed {
628+ Some((close, (target, text))) if !embed => {
629+ push_text(out, &rest[..open], marks);
630+ let href = format!("/notes/by-title/{}", crate::export::percent_encode(&target));
631+ let link = Marks {
632+ link: Some((href, None)),
633+ ..marks.clone()
634+ };
635+ out.push(Inline::Text(text, link));
636+ rest = &after[close + 2..];
637+ }
638+ _ => {
639+ push_text(out, &rest[..open + 2], marks);
640+ rest = after;
641+ }
642+ }
643+ }
644+ push_text(out, rest, marks);
645+}
646+
647+fn push_text(out: &mut Vec<Inline>, s: &str, marks: &Marks) {
648+ if !s.is_empty() {
649+ out.push(Inline::Text(s.to_owned(), marks.clone()));
650+ }
651+}
652+
653+/// The target title and the shown text of a wiki link's inside. The heading part of
654+/// the target is dropped, and the text falls back to the target.
655+fn wikilink_parts(inner: &str) -> Option<(String, String)> {
656+ if inner.contains(['\n', '[', ']']) {
657+ return None;
658+ }
659+ let (target_part, alias) = match inner.split_once('|') {
660+ Some((target, alias)) => (target, Some(alias.trim())),
661+ None => (inner, None),
662+ };
663+ let target = target_part.split('#').next().unwrap_or_default().trim();
664+ if target.is_empty() {
665+ return None;
666+ }
667+ let text = match alias {
668+ Some(alias) if !alias.is_empty() => alias,
669+ _ => target,
670+ };
671+ Some((target.to_owned(), text.to_owned()))
672+}
673+
674+fn apply_marks(text: &LoroText, range: std::ops::Range<usize>, marks: &Marks) -> LoroResult<()> {
675+ if marks.strong {
676+ text.mark(range.clone(), "strong", empty_map())?;
677+ }
678+ if marks.em {
679+ text.mark(range.clone(), "em", empty_map())?;
680+ }
681+ if marks.code {
682+ text.mark(range.clone(), "code", empty_map())?;
683+ }
684+ if let Some((href, title)) = &marks.link {
685+ let mut map: HashMap<String, LoroValue> = HashMap::new();
686+ map.insert("href".to_owned(), LoroValue::from(href.as_str()));
687+ let title_value = match title {
688+ Some(t) => LoroValue::from(t.as_str()),
689+ None => LoroValue::Null,
690+ };
691+ map.insert("title".to_owned(), title_value);
692+ text.mark(range, "link", LoroValue::from(map))?;
693+ }
694+ Ok(())
695+}
696+
697+fn empty_map() -> LoroValue {
698+ LoroValue::from(HashMap::<String, LoroValue>::new())
699+}
700+
701+#[cfg(test)]
702+mod tests {
703+ use super::*;
704+
705+ const SAMPLE: &str = r#"# Title
706+
707+Some **bold**, *italic*, `code` and [link](https://example.com "Example").
708+
709+- Bullet one
710+ - Nested bullet
711+- Bullet two
712+
713+1. First
714+2. Second
715+
716+> A quoted line
717+
718+```rust
719+fn main() {}
720+```
721+
722+---
723+
724+![A cat](https://example.com/cat.png)
725+
726+line one\
727+line two
728+"#;
729+
730+ #[test]
731+ fn round_trip_and_front_matter() {
732+ let doc = markdown_to_doc(SAMPLE).unwrap();
733+ assert_eq!(crate::export::to_markdown(&doc), SAMPLE);
734+
735+ let with_front_matter = format!("---\ntitle: Test\ntags: [a]\n---\n\n{SAMPLE}");
736+ let doc = markdown_to_doc(&with_front_matter).unwrap();
737+ assert_eq!(crate::export::to_markdown(&doc), SAMPLE);
738+
739+ let wiki = "See **[[Alpha]]**, [**Be**ta](My%20Beta.md) and [[Gamma|g]].\n";
740+ let doc = markdown_to_doc(wiki).unwrap();
741+ assert_eq!(crate::export::to_markdown_with(&doc, &|_| None), wiki);
742+ }
743+}
src/main.rsadded+46 -0
@@ -0,0 +1,46 @@
1+mod app;
2+mod components;
3+mod export;
4+mod hub;
5+mod i18n;
6+mod matcher;
7+mod import;
8+mod scheme;
9+mod store;
10+
11+use std::sync::Arc;
12+use std::time::Duration;
13+
14+/// Notes stay in the trash this long before they are deleted for good.
15+const TRASH_RETENTION_MS: i64 = 30 * 24 * 60 * 60 * 1000;
16+/// How often expired trash is purged.
17+const PURGE_EVERY: Duration = Duration::from_secs(60 * 60);
18+
19+/// Deletes notes that have been in the trash for 30 days, hourly, and drops their live
20+/// rooms. The first run happens at startup.
21+fn spawn_trash_purge(store: Arc<store::Store>, hub: Arc<hub::Hub>) {
22+ tokio::spawn(async move {
23+ let mut tick = tokio::time::interval(PURGE_EVERY);
24+ loop {
25+ tick.tick().await;
26+ match store.purge_trash(TRASH_RETENTION_MS).await {
27+ Ok(ids) => {
28+ for id in ids {
29+ hub.forget(&id);
30+ }
31+ }
32+ Err(err) => eprintln!("trash purge failed: {err:#}"),
33+ }
34+ }
35+ });
36+}
37+
38+#[tokio::main]
39+async fn main() -> anyhow::Result<()> {
40+ let db_path = std::env::var("NOTE_DB").unwrap_or_else(|_| "notes.db".to_owned());
41+ let store = Arc::new(store::Store::open(&db_path).await?);
42+ let hub = Arc::new(hub::Hub::new());
43+ spawn_trash_purge(store.clone(), hub.clone());
44+ topcoat::start(app::router(store, hub)).await?;
45+ Ok(())
46+}
src/matcher.rsadded+320 -0
@@ -0,0 +1,320 @@
1+//! Matching a search query against note text: case and Turkish-letter folding, typo
2+//! tolerance, and the search filters (match case, whole word, exact phrase, regex).
3+//!
4+//! Positions are char indices into the original text. Folding maps one char to one
5+//! char, so they line up.
6+
7+use regex::{Regex, RegexBuilder};
8+
9+/// Most words used from one query; longer queries are cut down.
10+const MAX_TERMS: usize = 16;
11+/// Longest word kept from a query.
12+const MAX_TERM_CHARS: usize = 64;
13+/// Longest query kept as an exact phrase or a regular expression.
14+const MAX_PATTERN_CHARS: usize = 256;
15+
16+/// The search filters. All off is the forgiving default: any case, Turkish letters as
17+/// plain ones, inside words, typos allowed.
18+#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
19+pub struct Options {
20+ /// Letters must match in case (and Turkish letters exactly).
21+ pub case: bool,
22+ /// Matches must be whole words.
23+ pub word: bool,
24+ /// The query is one phrase, matched as written. No typos.
25+ pub exact: bool,
26+ /// The query is a regular expression.
27+ pub regex: bool,
28+}
29+
30+impl Options {
31+ /// Typos are only forgiven with every filter off; any filter asks for precision.
32+ fn typos(self) -> bool {
33+ !(self.case || self.word || self.exact)
34+ }
35+}
36+
37+/// A compiled query.
38+pub enum Matcher {
39+ Terms { terms: Vec<Vec<char>>, opts: Options },
40+ Regex(Regex),
41+}
42+
43+/// The query is not a valid regular expression.
44+#[derive(Debug)]
45+pub struct InvalidRegex;
46+
47+impl Matcher {
48+ /// None when the query holds nothing to search for.
49+ pub fn new(query: &str, opts: Options) -> Result<Option<Self>, InvalidRegex> {
50+ let query = query.trim();
51+ if query.is_empty() {
52+ return Ok(None);
53+ }
54+ if opts.regex {
55+ let pattern: String = query.chars().take(MAX_PATTERN_CHARS).collect();
56+ let pattern = if opts.word {
57+ format!(r"\b(?:{pattern})\b")
58+ } else {
59+ pattern
60+ };
61+ return RegexBuilder::new(&pattern)
62+ .case_insensitive(!opts.case)
63+ .size_limit(1 << 20)
64+ .build()
65+ .map(|re| Some(Self::Regex(re)))
66+ .map_err(|_| InvalidRegex);
67+ }
68+ let fold = |c: char| if opts.case { c } else { match_fold(c) };
69+ let mut terms: Vec<Vec<char>> = if opts.exact {
70+ let phrase = query.split_whitespace().collect::<Vec<_>>().join(" ");
71+ vec![phrase.chars().take(MAX_PATTERN_CHARS).map(fold).collect()]
72+ } else {
73+ query
74+ .split(|c: char| !c.is_alphanumeric())
75+ .filter(|w| !w.is_empty())
76+ .map(|w| w.chars().take(MAX_TERM_CHARS).map(fold).collect())
77+ .collect()
78+ };
79+ terms.sort();
80+ terms.dedup();
81+ terms.truncate(MAX_TERMS);
82+ Ok((!terms.is_empty()).then_some(Self::Terms { terms, opts }))
83+ }
84+
85+ /// The default matcher for `query`, as the palette and `[[` use it.
86+ pub fn simple(query: &str) -> Option<Self> {
87+ Self::new(query, Options::default()).ok().flatten()
88+ }
89+
90+ /// The cheapest match of each term in `text`, by term (None where it doesn't occur).
91+ /// See [`occurrences`] for costs.
92+ pub fn term_costs(&self, text: &str) -> Vec<Option<usize>> {
93+ match self {
94+ Self::Terms { terms, opts } => {
95+ let hay = fold_text(text, *opts);
96+ terms
97+ .iter()
98+ .map(|t| occurrences(&hay, t, *opts).into_iter().map(|o| o.2).min())
99+ .collect()
100+ }
101+ Self::Regex(re) => vec![re.find_iter(text).any(|m| !m.is_empty()).then_some(0)],
102+ }
103+ }
104+
105+ /// The summed cost of every term in `text`, or None if some term doesn't occur.
106+ pub fn cost(&self, text: &str) -> Option<usize> {
107+ self.term_costs(text).into_iter().sum()
108+ }
109+
110+ /// Char ranges `(start, end)` of the matches in `text`, merged and sorted.
111+ pub fn ranges(&self, text: &str) -> Vec<(usize, usize)> {
112+ let mut ranges: Vec<(usize, usize)> = match self {
113+ Self::Terms { terms, opts } => {
114+ let hay = fold_text(text, *opts);
115+ terms
116+ .iter()
117+ .flat_map(|t| occurrences(&hay, t, *opts))
118+ .map(|(s, e, _)| (s, e))
119+ .collect()
120+ }
121+ Self::Regex(re) => {
122+ // Byte offsets to char indices.
123+ let mut ranges = Vec::new();
124+ for m in re.find_iter(text).filter(|m| !m.is_empty()) {
125+ let start = text[..m.start()].chars().count();
126+ ranges.push((start, start + m.as_str().chars().count()));
127+ }
128+ ranges
129+ }
130+ };
131+ ranges.sort_unstable();
132+ let mut merged: Vec<(usize, usize)> = Vec::new();
133+ for (start, end) in ranges {
134+ match merged.last_mut() {
135+ Some(last) if start <= last.1 => last.1 = last.1.max(end),
136+ _ => merged.push((start, end)),
137+ }
138+ }
139+ merged
140+ }
141+}
142+
143+/// Lowercase form of one char.
144+fn fold(c: char) -> char {
145+ c.to_lowercase().next().unwrap_or(c)
146+}
147+
148+/// One char as the default search compares it: lowercase, Turkish letters as plain ones.
149+fn match_fold(c: char) -> char {
150+ match fold(c) {
151+ 'ı' => 'i',
152+ 'ş' => 's',
153+ 'ğ' => 'g',
154+ 'ç' => 'c',
155+ 'ö' => 'o',
156+ 'ü' => 'u',
157+ c => c,
158+ }
159+}
160+
161+/// A title folded for matching: lowercase, with Turkish letters as their plain forms,
162+/// so "izmir" finds "İzmir" and "isik", "ışık" and "Işık" find each other.
163+pub fn title_fold(title: &str) -> String {
164+ title.chars().map(match_fold).collect()
165+}
166+
167+fn fold_text(text: &str, opts: Options) -> Vec<char> {
168+ if opts.case {
169+ text.chars().collect()
170+ } else {
171+ text.chars().map(match_fold).collect()
172+ }
173+}
174+
175+/// Typos a term of `len` chars may have and still match: none up to 4 chars (except one
176+/// swap of neighbours, see [`occurrences`]), one up to 8, two beyond. Short words with any
177+/// other typo match too much else.
178+fn max_typos(len: usize) -> usize {
179+ match len {
180+ 0..=4 => 0,
181+ 5..=8 => 1,
182+ _ => 2,
183+ }
184+}
185+
186+/// Where `term` occurs in `hay` (both already folded). Exact occurrences (whole words
187+/// only with `opts.word`), or, when there are none and typos are allowed, word
188+/// beginnings within [`max_typos`] edits of the term (insertions, deletions,
189+/// substitutions and swapped neighbours). The `usize` is the match's cost: 0 exact at a
190+/// word start, 1 exact inside a word, 1 + typos otherwise.
191+fn occurrences(hay: &[char], term: &[char], opts: Options) -> Vec<(usize, usize, usize)> {
192+ let n = term.len();
193+ if n == 0 {
194+ return Vec::new();
195+ }
196+ let word_start = |i: usize| i == 0 || !hay[i - 1].is_alphanumeric();
197+ let word_end = |i: usize| i == hay.len() || !hay[i].is_alphanumeric();
198+ let mut found = Vec::new();
199+ if n <= hay.len() {
200+ for start in 0..=hay.len() - n {
201+ let end = start + n;
202+ if hay[start..end] != term[..] {
203+ continue;
204+ }
205+ if opts.word && !(word_start(start) && word_end(end)) {
206+ continue;
207+ }
208+ found.push((start, end, usize::from(!word_start(start))));
209+ }
210+ }
211+ if !found.is_empty() || !opts.typos() {
212+ return found;
213+ }
214+ let d = max_typos(n);
215+ // Short words only forgive swapped neighbours: "mlik" finds "milk".
216+ let swap_only = d == 0;
217+ if swap_only && n < 3 {
218+ return found;
219+ }
220+ let mut i = 0;
221+ while i < hay.len() {
222+ if !hay[i].is_alphanumeric() {
223+ i += 1;
224+ continue;
225+ }
226+ let mut end = i;
227+ while end < hay.len() && hay[end].is_alphanumeric() {
228+ end += 1;
229+ }
230+ if swap_only {
231+ let word = &hay[i..end];
232+ let swapped = word.len() >= n
233+ && (1..n).any(|k| {
234+ word[k - 1] == term[k]
235+ && word[k] == term[k - 1]
236+ && term[k] != term[k - 1]
237+ && (0..n).all(|x| x == k || x == k - 1 || word[x] == term[x])
238+ });
239+ if swapped {
240+ found.push((i, i + n, 2));
241+ }
242+ } else if let Some((typos, len)) = prefix_distance(term, &hay[i..end.min(i + n + d)], d) {
243+ found.push((i, i + len, 1 + typos));
244+ }
245+ i = end;
246+ }
247+ found
248+}
249+
250+/// The fewest edits turning `term` into some prefix of `word`, and that prefix's length,
251+/// if at most `max`. Optimal string alignment distance, so a swap counts as one edit.
252+fn prefix_distance(term: &[char], word: &[char], max: usize) -> Option<(usize, usize)> {
253+ let (n, m) = (term.len(), word.len());
254+ if m + max < n {
255+ return None;
256+ }
257+ let mut d = vec![vec![0usize; m + 1]; n + 1];
258+ for (i, row) in d.iter_mut().enumerate() {
259+ row[0] = i;
260+ }
261+ for j in 0..=m {
262+ d[0][j] = j;
263+ }
264+ for i in 1..=n {
265+ for j in 1..=m {
266+ let cost = usize::from(term[i - 1] != word[j - 1]);
267+ let mut v = (d[i - 1][j] + 1).min(d[i][j - 1] + 1).min(d[i - 1][j - 1] + cost);
268+ if i > 1 && j > 1 && term[i - 1] == word[j - 2] && term[i - 2] == word[j - 1] {
269+ v = v.min(d[i - 2][j - 2] + 1);
270+ }
271+ d[i][j] = v;
272+ }
273+ }
274+ (n.saturating_sub(max).max(1)..=m)
275+ .map(|j| (d[n][j], j))
276+ .min_by_key(|&(dist, j)| (dist, j.abs_diff(n)))
277+ .filter(|&(dist, _)| dist <= max)
278+}
279+
280+#[cfg(test)]
281+mod tests {
282+ use super::*;
283+
284+ fn cost(text: &str, q: &str, opts: Options) -> Option<usize> {
285+ Matcher::new(q, opts).unwrap().unwrap().cost(text)
286+ }
287+
288+ #[test]
289+ fn typo_tolerance() {
290+ let d = Options::default();
291+ assert_eq!(cost("Groceries list", "groc", d), Some(0));
292+ assert_eq!(cost("Groceries list", "grcoeries", d), Some(2)); // swapped letters
293+ assert_eq!(cost("Groceries list", "grocerues", d), Some(2)); // one substitution
294+ assert_eq!(cost("Project kickoff", "porject kikcoff", d), Some(4));
295+ assert_eq!(cost("İzmir gezisi", "izmr", d), None); // 4 chars: only a swap
296+ assert_eq!(cost("Plan", "plna", d), Some(2));
297+ assert_eq!(cost("Plan", "plen", d), None);
298+ assert_eq!(cost("Işık listesi", "isik listsi", d), Some(2));
299+ }
300+
301+ #[test]
302+ fn filters() {
303+ let case = Options { case: true, ..Default::default() };
304+ let word = Options { word: true, ..Default::default() };
305+ let exact = Options { exact: true, ..Default::default() };
306+ let regex = Options { regex: true, ..Default::default() };
307+ assert_eq!(cost("Groceries", "groceries", case), None);
308+ assert_eq!(cost("Groceries", "Groceries", case), Some(0));
309+ assert_eq!(cost("Groceries", "Groc", word), None);
310+ assert_eq!(cost("milk, eggs", "milk", word), Some(0));
311+ assert_eq!(cost("buy milk and eggs", "milk eggs", exact), None);
312+ assert_eq!(cost("buy milk and eggs", "milk and", exact), None); // text not collapsed
313+ assert_eq!(cost("buy milk and eggs", "MILK AND", exact), Some(0));
314+ assert_eq!(cost("Groceries", "grcoeries", exact), None); // no typos
315+ assert_eq!(cost("order #42", r"#\d+", regex), Some(0));
316+ assert!(Matcher::new("(", regex).is_err());
317+ let m = Matcher::new("ş", Options::default()).unwrap().unwrap();
318+ assert_eq!(m.ranges("Işık"), vec![(1, 2)]);
319+ }
320+}
src/scheme.rsadded+117 -0
@@ -0,0 +1,117 @@
1+//! Color schemes: the nine palettes the user can pick, the cookie that remembers the
2+//! choice, and the swatch colors the picker shows. The palettes themselves are CSS
3+//! custom properties in `styles.css`, keyed by `<html data-scheme="...">`.
4+
5+use topcoat::{
6+ context::Cx,
7+ cookie::{Cookie, Cookies, SameSite, cookies, time::Duration},
8+};
9+
10+/// Name of the cookie that stores the color scheme.
11+pub const SCHEME_COOKIE: &str = "scheme";
12+
13+/// How long the color scheme choice is remembered.
14+pub const SCHEME_COOKIE_DAYS: i64 = 365;
15+
16+/// A color scheme. Each one is a palette of light and dark tokens in `styles.css`.
17+#[derive(Clone, Copy, Debug, PartialEq, Eq)]
18+pub enum Scheme {
19+ Graphite,
20+ Cobalt,
21+ Oxblood,
22+ Teal,
23+ Plum,
24+ Mono,
25+ Tangerine,
26+ Sage,
27+ Spark,
28+}
29+
30+/// Every scheme, in the order the picker lists them.
31+pub const ALL: [Scheme; 9] = [
32+ Scheme::Graphite,
33+ Scheme::Cobalt,
34+ Scheme::Oxblood,
35+ Scheme::Teal,
36+ Scheme::Plum,
37+ Scheme::Mono,
38+ Scheme::Tangerine,
39+ Scheme::Sage,
40+ Scheme::Spark,
41+];
42+
43+/// The scheme used when no valid cookie is set.
44+pub const DEFAULT: Scheme = Scheme::Sage;
45+
46+impl Scheme {
47+ /// The value stored in the cookie and in `data-scheme` on `<html>`.
48+ pub fn id(self) -> &'static str {
49+ match self {
50+ Self::Graphite => "graphite",
51+ Self::Cobalt => "cobalt",
52+ Self::Oxblood => "oxblood",
53+ Self::Teal => "teal",
54+ Self::Plum => "plum",
55+ Self::Mono => "mono",
56+ Self::Tangerine => "tangerine",
57+ Self::Sage => "sage",
58+ Self::Spark => "spark",
59+ }
60+ }
61+
62+ /// Parses a cookie or form value. Returns `None` for unknown schemes.
63+ pub fn from_id(id: &str) -> Option<Self> {
64+ ALL.into_iter().find(|s| s.id() == id)
65+ }
66+
67+ /// The proper name of the scheme. Names are not translated.
68+ pub fn name(self) -> &'static str {
69+ match self {
70+ Self::Graphite => "Graphite & Highlighter",
71+ Self::Cobalt => "Cobalt Ink",
72+ Self::Oxblood => "Oxblood",
73+ Self::Teal => "Teal Ledger",
74+ Self::Plum => "Plum",
75+ Self::Mono => "Monochrome",
76+ Self::Tangerine => "Tangerine",
77+ Self::Sage => "Sage",
78+ Self::Spark => "Spark",
79+ }
80+ }
81+
82+ /// Three swatch colors as `(light, dark)` pairs: the sidebar, the accent, and the
83+ /// active row. The picker draws them as dots.
84+ pub fn dots(self) -> [(&'static str, &'static str); 3] {
85+ match self {
86+ // @dots:begin
87+ Self::Graphite => [("#eceef2", "#1d2026"), ("#f2b600", "#ffc93c"), ("#ffe08a", "#5c4700")],
88+ Self::Cobalt => [("#eef3fb", "#121a2c"), ("#1f4fd1", "#5b8bff"), ("#dce7ff", "#1d2f5c")],
89+ Self::Oxblood => [("#eeeae8", "#1c1818"), ("#8e1b22", "#d85c63"), ("#f8dcd9", "#4a1d21")],
90+ Self::Teal => [("#e8f0f0", "#121d1c"), ("#0f5e5a", "#3fb3a6"), ("#cdeee9", "#15403b")],
91+ Self::Plum => [("#efeaf3", "#1a1620"), ("#7b2d6e", "#d27ac4"), ("#f1d9ee", "#4a2446")],
92+ Self::Mono => [("#f0f0f0", "#161616"), ("#111111", "#f2f2f2"), ("#e4e4e4", "#2e2e2e")],
93+ Self::Tangerine => [("#eceef0", "#16191c"), ("#f59e0b", "#ffb347"), ("#fde9c4", "#4f3412")],
94+ Self::Sage => [("#e9efe6", "#111211"), ("#567752", "#4a6847"), ("#d9ebd3", "#233024")],
95+ Self::Spark => [("#eeeef0", "#1a1512"), ("#ff8205", "#ff9a2e"), ("#ffe8c7", "#58320a")],
96+ // @dots:end
97+ }
98+ }
99+}
100+
101+/// The scheme of this request. The `scheme` cookie wins; an unknown or missing value
102+/// means the default.
103+pub fn scheme(cx: &Cx) -> Scheme {
104+ cookies(cx)
105+ .get(SCHEME_COOKIE)
106+ .and_then(|cookie| Scheme::from_id(cookie.value()))
107+ .unwrap_or(DEFAULT)
108+}
109+
110+/// The cookie that remembers `scheme` for a year.
111+pub fn scheme_cookie(scheme: Scheme) -> Cookie<'static> {
112+ Cookie::build((SCHEME_COOKIE, scheme.id()))
113+ .path("/")
114+ .same_site(SameSite::Lax)
115+ .max_age(Duration::days(SCHEME_COOKIE_DAYS))
116+ .build()
117+}
src/store.rsadded+976 -0
@@ -0,0 +1,976 @@
1+//! Persistence. The only module that talks to turso.
2+
3+use std::collections::HashMap;
4+use std::time::{SystemTime, UNIX_EPOCH};
5+
6+use anyhow::{Context, anyhow};
7+
8+use crate::matcher::Matcher;
9+use tokio::sync::Mutex;
10+
11+use crate::export::LinkTarget;
12+
13+pub struct NoteMeta {
14+ pub id: String,
15+ pub title: String,
16+ pub created_at: i64,
17+ pub updated_at: i64,
18+ /// `None` when the note is not in any notebook.
19+ pub notebook_id: Option<String>,
20+ /// `None` when the note is not in the trash. Millis when it was trashed.
21+ pub trashed_at: Option<i64>,
22+}
23+
24+pub struct Notebook {
25+ pub id: String,
26+ pub name: String,
27+ pub created_at: i64,
28+}
29+
30+/// Snapshot (if any) plus every update stored after it, in insertion order.
31+pub struct DocBytes {
32+ pub snapshot: Option<Vec<u8>>,
33+ pub updates: Vec<Vec<u8>>,
34+}
35+
36+pub struct Store {
37+ /// Single connection shared by all tasks. Calls are serialized by the mutex,
38+ /// which also keeps transactions from interleaving on one connection.
39+ conn: Mutex<turso::Connection>,
40+ /// Keeps the database handle alive for as long as the connection is used.
41+ _db: turso::Database,
42+}
43+
44+pub(crate) fn now_millis() -> i64 {
45+ SystemTime::now()
46+ .duration_since(UNIX_EPOCH)
47+ .map(|d| d.as_millis() as i64)
48+ .unwrap_or(0)
49+}
50+
51+/// The form of a title that links match on: whitespace collapsed and lowercased.
52+pub fn title_key(title: &str) -> String {
53+ title
54+ .split_whitespace()
55+ .collect::<Vec<_>>()
56+ .join(" ")
57+ .to_lowercase()
58+}
59+
60+fn text_col(row: &turso::Row, idx: usize) -> anyhow::Result<String> {
61+ match row.get_value(idx)? {
62+ turso::Value::Text(s) => Ok(s),
63+ other => Err(anyhow!("column {idx}: expected TEXT, got {other:?}")),
64+ }
65+}
66+
67+fn opt_text_col(row: &turso::Row, idx: usize) -> anyhow::Result<Option<String>> {
68+ match row.get_value(idx)? {
69+ turso::Value::Null => Ok(None),
70+ turso::Value::Text(s) => Ok(Some(s)),
71+ other => Err(anyhow!("column {idx}: expected TEXT or NULL, got {other:?}")),
72+ }
73+}
74+
75+fn int_col(row: &turso::Row, idx: usize) -> anyhow::Result<i64> {
76+ match row.get_value(idx)? {
77+ turso::Value::Integer(i) => Ok(i),
78+ other => Err(anyhow!("column {idx}: expected INTEGER, got {other:?}")),
79+ }
80+}
81+
82+fn opt_int_col(row: &turso::Row, idx: usize) -> anyhow::Result<Option<i64>> {
83+ match row.get_value(idx)? {
84+ turso::Value::Null => Ok(None),
85+ turso::Value::Integer(i) => Ok(Some(i)),
86+ other => Err(anyhow!("column {idx}: expected INTEGER or NULL, got {other:?}")),
87+ }
88+}
89+
90+fn blob_col(row: &turso::Row, idx: usize) -> anyhow::Result<Vec<u8>> {
91+ match row.get_value(idx)? {
92+ turso::Value::Blob(b) => Ok(b),
93+ other => Err(anyhow!("column {idx}: expected BLOB, got {other:?}")),
94+ }
95+}
96+
97+fn note_from_row(row: &turso::Row) -> anyhow::Result<NoteMeta> {
98+ Ok(NoteMeta {
99+ id: text_col(row, 0)?,
100+ title: text_col(row, 1)?,
101+ created_at: int_col(row, 2)?,
102+ updated_at: int_col(row, 3)?,
103+ notebook_id: opt_text_col(row, 4)?,
104+ trashed_at: opt_int_col(row, 5)?,
105+ })
106+}
107+
108+/// Deletes one note's rows inside an open transaction.
109+async fn delete_note_rows(
110+ tx: &turso::transaction::Transaction<'_>,
111+ note_id: &str,
112+) -> anyhow::Result<()> {
113+ tx.execute("DELETE FROM updates WHERE note_id = ?1", (note_id.to_string(),))
114+ .await?;
115+ tx.execute("DELETE FROM snapshots WHERE note_id = ?1", (note_id.to_string(),))
116+ .await?;
117+ tx.execute("DELETE FROM note_text WHERE note_id = ?1", (note_id.to_string(),))
118+ .await?;
119+ tx.execute("DELETE FROM note_versions WHERE note_id = ?1", (note_id.to_string(),))
120+ .await?;
121+ tx.execute("DELETE FROM note_links WHERE src = ?1", (note_id.to_string(),))
122+ .await?;
123+ tx.execute("DELETE FROM notes WHERE id = ?1", (note_id.to_string(),))
124+ .await?;
125+ Ok(())
126+}
127+
128+fn notebook_from_row(row: &turso::Row) -> anyhow::Result<Notebook> {
129+ Ok(Notebook {
130+ id: text_col(row, 0)?,
131+ name: text_col(row, 1)?,
132+ created_at: int_col(row, 2)?,
133+ })
134+}
135+
136+/// A note matched by [`Store::search`], with a plain-text excerpt of its body.
137+pub struct SearchHit {
138+ pub note: NoteMeta,
139+ pub snippet: String,
140+}
141+
142+/// Characters of body text shown around the first match.
143+const SNIPPET_CHARS: usize = 160;
144+/// Characters of body text shown as a note's preview in a list.
145+const PREVIEW_CHARS: usize = 140;
146+/// Markdown as plain text. Code fences are dropped, block markers (headings, quotes,
147+/// list and task markers, rules) and inline syntax (emphasis, code spans, escapes) are
148+/// removed, link and image text is kept, and lines are joined with single spaces.
149+fn plain_text(markdown: &str) -> String {
150+ let mut lines: Vec<String> = Vec::new();
151+ let mut in_fence = false;
152+ for line in markdown.lines() {
153+ let trimmed = line.trim();
154+ if trimmed.starts_with("```") || trimmed.starts_with("~~~") {
155+ in_fence = !in_fence;
156+ continue;
157+ }
158+ let text = if in_fence {
159+ trimmed.to_owned()
160+ } else {
161+ strip_inline(strip_block(trimmed))
162+ };
163+ if !text.trim().is_empty() {
164+ lines.push(text);
165+ }
166+ }
167+ lines.join(" ").split_whitespace().collect::<Vec<_>>().join(" ")
168+}
169+
170+/// Removes the block syntax at the start of one trimmed line: quote marks, heading
171+/// hashes, list and task markers, and thematic breaks.
172+fn strip_block(line: &str) -> &str {
173+ let mut s = line;
174+ if s.len() >= 3 && s.chars().all(|c| matches!(c, '-' | '*' | '_' | ' ')) {
175+ return "";
176+ }
177+ while let Some(rest) = s.strip_prefix('>') {
178+ s = rest.trim_start();
179+ }
180+ let hashes = s.len() - s.trim_start_matches('#').len();
181+ if hashes > 0 && (hashes == s.len() || s[hashes..].starts_with(' ')) {
182+ s = s[hashes..].trim_start();
183+ }
184+ if let Some(rest) = s.strip_prefix(['-', '*', '+']) {
185+ if rest.is_empty() || rest.starts_with(' ') {
186+ s = rest.trim_start();
187+ }
188+ }
189+ let digits = s.len() - s.trim_start_matches(|c: char| c.is_ascii_digit()).len();
190+ if digits > 0 {
191+ if let Some(rest) = s[digits..].strip_prefix(['.', ')']) {
192+ if rest.is_empty() || rest.starts_with(' ') {
193+ s = rest.trim_start();
194+ }
195+ }
196+ }
197+ for checkbox in ["[ ]", "[x]", "[X]"] {
198+ if let Some(rest) = s.strip_prefix(checkbox) {
199+ s = rest.trim_start();
200+ break;
201+ }
202+ }
203+ s
204+}
205+
206+/// Removes inline syntax from one line: `[text](url)` and `![alt](url)` become their
207+/// text, emphasis and code markers are dropped, `_` is kept inside words only, and a
208+/// backslash escape yields the escaped character.
209+fn strip_inline(text: &str) -> String {
210+ let chars: Vec<char> = text.chars().collect();
211+ let mut out = String::with_capacity(text.len());
212+ let mut i = 0;
213+ while i < chars.len() {
214+ let c = chars[i];
215+ if c == '!' && chars.get(i + 1) == Some(&'[') {
216+ if let Some((label, end)) = link_at(&chars, i + 1) {
217+ out.push_str(&label);
218+ i = end;
219+ continue;
220+ }
221+ }
222+ if c == '[' {
223+ if let Some((label, end)) = link_at(&chars, i) {
224+ out.push_str(&label);
225+ i = end;
226+ continue;
227+ }
228+ }
229+ if c == '\\' && chars.get(i + 1).is_some_and(|next| next.is_ascii_punctuation()) {
230+ out.push(chars[i + 1]);
231+ i += 2;
232+ continue;
233+ }
234+ match c {
235+ '*' | '`' | '~' => {}
236+ '_' => {
237+ let inside_word = i > 0
238+ && chars[i - 1].is_alphanumeric()
239+ && chars.get(i + 1).is_some_and(|next| next.is_alphanumeric());
240+ if inside_word {
241+ out.push(c);
242+ }
243+ }
244+ _ => out.push(c),
245+ }
246+ i += 1;
247+ }
248+ out
249+}
250+
251+/// Parses `[label](target)` whose `[` is at `open`. Returns the label and the index just
252+/// after the closing `)`.
253+fn link_at(chars: &[char], open: usize) -> Option<(String, usize)> {
254+ let close = open + 1 + chars[open + 1..].iter().position(|&c| c == ']')?;
255+ if chars.get(close + 1) != Some(&'(') {
256+ return None;
257+ }
258+ let end = close + 2 + chars[close + 2..].iter().position(|&c| c == ')')?;
259+ Some((chars[open + 1..close].iter().collect(), end + 1))
260+}
261+
262+/// The first `PREVIEW_CHARS` characters of a note's text after its title. The first
263+/// non-blank line of the markdown is the title, so it is skipped.
264+fn preview(markdown: &str) -> String {
265+ let body = markdown
266+ .lines()
267+ .skip_while(|line| line.trim().is_empty())
268+ .skip(1)
269+ .collect::<Vec<_>>()
270+ .join("\n");
271+ plain_text(&body).chars().take(PREVIEW_CHARS).collect()
272+}
273+
274+/// About `SNIPPET_CHARS` characters of plain text around the first term match.
275+/// Cut ends get an ellipsis.
276+fn snippet(markdown: &str, matcher: &Matcher) -> String {
277+ let plain = plain_text(markdown);
278+ let chars: Vec<char> = plain.chars().collect();
279+ if chars.is_empty() {
280+ return String::new();
281+ }
282+ let center = matcher.ranges(&plain).first().map_or(0, |range| range.0);
283+ let mut start = center.saturating_sub(SNIPPET_CHARS / 3);
284+ let end = (start + SNIPPET_CHARS).min(chars.len());
285+ if end - start < SNIPPET_CHARS {
286+ start = end.saturating_sub(SNIPPET_CHARS);
287+ }
288+ let body: String = chars[start..end].iter().collect();
289+ let mut out = String::new();
290+ if start > 0 {
291+ out.push('…');
292+ }
293+ out.push_str(body.trim());
294+ if end < chars.len() {
295+ out.push('…');
296+ }
297+ out
298+}
299+
300+impl Store {
301+ /// Opens (or creates) the database file and runs schema setup.
302+ pub async fn open(path: &str) -> anyhow::Result<Self> {
303+ // The FTS index method is gated behind this flag in turso 0.8.
304+ let db = turso::Builder::new_local(path)
305+ .experimental_index_method(true)
306+ .build()
307+ .await
308+ .with_context(|| format!("opening database at {path}"))?;
309+ let conn = db.connect()?;
310+
311+ conn.execute_batch(
312+ "CREATE TABLE IF NOT EXISTS notes (
313+ id TEXT PRIMARY KEY,
314+ title TEXT NOT NULL DEFAULT 'Untitled',
315+ created_at INTEGER NOT NULL,
316+ updated_at INTEGER NOT NULL,
317+ notebook_id TEXT,
318+ trashed_at INTEGER
319+ );
320+ CREATE TABLE IF NOT EXISTS notebooks (
321+ id TEXT PRIMARY KEY,
322+ name TEXT NOT NULL,
323+ created_at INTEGER NOT NULL
324+ );
325+ CREATE TABLE IF NOT EXISTS updates (
326+ seq INTEGER PRIMARY KEY AUTOINCREMENT,
327+ note_id TEXT NOT NULL,
328+ hash BLOB NOT NULL,
329+ data BLOB NOT NULL,
330+ UNIQUE(note_id, hash)
331+ );
332+ CREATE TABLE IF NOT EXISTS snapshots (
333+ note_id TEXT PRIMARY KEY,
334+ data BLOB NOT NULL,
335+ upto_seq INTEGER NOT NULL,
336+ markdown TEXT NOT NULL
337+ );
338+ CREATE TABLE IF NOT EXISTS note_text (
339+ note_id TEXT PRIMARY KEY,
340+ title TEXT NOT NULL,
341+ body TEXT NOT NULL
342+ );
343+ CREATE TABLE IF NOT EXISTS note_versions (
344+ note_id TEXT NOT NULL,
345+ at INTEGER NOT NULL,
346+ frontiers BLOB NOT NULL,
347+ PRIMARY KEY(note_id, at)
348+ );
349+ CREATE INDEX IF NOT EXISTS note_text_fts ON note_text USING fts(title, body);
350+ CREATE TABLE IF NOT EXISTS note_links (
351+ src TEXT NOT NULL,
352+ dst_id TEXT,
353+ dst_title TEXT
354+ );
355+ CREATE INDEX IF NOT EXISTS note_links_src ON note_links(src);
356+ CREATE INDEX IF NOT EXISTS note_links_dst_id ON note_links(dst_id);
357+ CREATE INDEX IF NOT EXISTS note_links_dst_title ON note_links(dst_title);",
358+ )
359+ .await
360+ .context("running schema setup")?;
361+
362+ // Databases created before notebooks have a notes table without notebook_id.
363+ // CREATE TABLE IF NOT EXISTS does not add columns, so add it when missing.
364+ if !Self::notes_columns(&conn).await?.iter().any(|c| c == "notebook_id") {
365+ conn.execute("ALTER TABLE notes ADD COLUMN notebook_id TEXT", ())
366+ .await
367+ .context("adding notes.notebook_id")?;
368+ }
369+
370+ // Databases created before the trash existed lack notes.trashed_at.
371+ if !Self::notes_columns(&conn).await?.iter().any(|c| c == "trashed_at") {
372+ conn.execute("ALTER TABLE notes ADD COLUMN trashed_at INTEGER", ())
373+ .await
374+ .context("adding notes.trashed_at")?;
375+ }
376+
377+ // Notes saved before note_text existed: copy their snapshot markdown once.
378+ conn.execute(
379+ "INSERT INTO note_text (note_id, title, body)
380+ SELECT s.note_id, n.title, s.markdown FROM snapshots s
381+ JOIN notes n ON n.id = s.note_id
382+ WHERE NOT EXISTS (SELECT 1 FROM note_text t WHERE t.note_id = s.note_id)",
383+ (),
384+ )
385+ .await
386+ .context("backfilling note_text")?;
387+
388+ Ok(Self {
389+ conn: Mutex::new(conn),
390+ _db: db,
391+ })
392+ }
393+
394+ /// Column names of the notes table, read from `PRAGMA table_info`.
395+ async fn notes_columns(conn: &turso::Connection) -> anyhow::Result<Vec<String>> {
396+ let mut rows = conn.query("PRAGMA table_info(notes)", ()).await?;
397+ let mut names = Vec::new();
398+ while let Some(row) = rows.next().await? {
399+ names.push(text_col(&row, 1)?);
400+ }
401+ Ok(names)
402+ }
403+
404+ pub async fn create_note(&self, notebook_id: Option<&str>) -> anyhow::Result<NoteMeta> {
405+ let now = now_millis();
406+ let note = NoteMeta {
407+ id: uuid::Uuid::now_v7().to_string(),
408+ title: "Untitled".to_string(),
409+ created_at: now,
410+ updated_at: now,
411+ notebook_id: notebook_id.map(str::to_string),
412+ trashed_at: None,
413+ };
414+
415+ let conn = self.conn.lock().await;
416+ conn.execute(
417+ "INSERT INTO notes (id, title, created_at, updated_at, notebook_id) VALUES (?1, ?2, ?3, ?4, ?5)",
418+ (
419+ note.id.clone(),
420+ note.title.clone(),
421+ note.created_at,
422+ note.updated_at,
423+ note.notebook_id.clone(),
424+ ),
425+ )
426+ .await?;
427+ Ok(note)
428+ }
429+
430+ pub async fn create_notebook(&self, name: &str) -> anyhow::Result<Notebook> {
431+ let notebook = Notebook {
432+ id: uuid::Uuid::now_v7().to_string(),
433+ name: name.to_string(),
434+ created_at: now_millis(),
435+ };
436+
437+ let conn = self.conn.lock().await;
438+ conn.execute(
439+ "INSERT INTO notebooks (id, name, created_at) VALUES (?1, ?2, ?3)",
440+ (
441+ notebook.id.clone(),
442+ notebook.name.clone(),
443+ notebook.created_at,
444+ ),
445+ )
446+ .await?;
447+ Ok(notebook)
448+ }
449+
450+ pub async fn list_notebooks(&self) -> anyhow::Result<Vec<Notebook>> {
451+ let conn = self.conn.lock().await;
452+ let mut rows = conn
453+ .query(
454+ "SELECT id, name, created_at FROM notebooks ORDER BY name COLLATE NOCASE, id",
455+ (),
456+ )
457+ .await?;
458+ let mut notebooks = Vec::new();
459+ while let Some(row) = rows.next().await? {
460+ notebooks.push(notebook_from_row(&row)?);
461+ }
462+ Ok(notebooks)
463+ }
464+
465+ pub async fn get_notebook(&self, id: &str) -> anyhow::Result<Option<Notebook>> {
466+ let conn = self.conn.lock().await;
467+ let mut rows = conn
468+ .query(
469+ "SELECT id, name, created_at FROM notebooks WHERE id = ?1",
470+ (id.to_string(),),
471+ )
472+ .await?;
473+ match rows.next().await? {
474+ Some(row) => Ok(Some(notebook_from_row(&row)?)),
475+ None => Ok(None),
476+ }
477+ }
478+
479+ pub async fn rename_notebook(&self, id: &str, name: &str) -> anyhow::Result<()> {
480+ let conn = self.conn.lock().await;
481+ conn.execute(
482+ "UPDATE notebooks SET name = ?2 WHERE id = ?1",
483+ (id.to_string(), name.to_string()),
484+ )
485+ .await?;
486+ Ok(())
487+ }
488+
489+ /// Deletes the notebook. Its notes are kept and become unfiled.
490+ pub async fn delete_notebook(&self, id: &str) -> anyhow::Result<()> {
491+ let mut conn = self.conn.lock().await;
492+ let tx = conn.transaction().await?;
493+ tx.execute(
494+ "UPDATE notes SET notebook_id = NULL WHERE notebook_id = ?1",
495+ (id.to_string(),),
496+ )
497+ .await?;
498+ tx.execute("DELETE FROM notebooks WHERE id = ?1", (id.to_string(),))
499+ .await?;
500+ tx.commit().await?;
501+ Ok(())
502+ }
503+
504+ pub async fn move_note(&self, note_id: &str, notebook_id: Option<&str>) -> anyhow::Result<()> {
505+ let conn = self.conn.lock().await;
506+ conn.execute(
507+ "UPDATE notes SET notebook_id = ?2 WHERE id = ?1",
508+ (note_id.to_string(), notebook_id.map(str::to_string)),
509+ )
510+ .await?;
511+ Ok(())
512+ }
513+
514+ /// Deletes the note together with its updates, snapshot and searchable text.
515+ pub async fn delete_note(&self, note_id: &str) -> anyhow::Result<()> {
516+ let mut conn = self.conn.lock().await;
517+ let tx = conn.transaction().await?;
518+ delete_note_rows(&tx, note_id).await?;
519+ tx.commit().await?;
520+ Ok(())
521+ }
522+
523+ /// Moves the note to the trash. It stays readable by `get_note` and is hidden
524+ /// from lists and search until restored or purged.
525+ pub async fn trash_note(&self, note_id: &str) -> anyhow::Result<()> {
526+ let conn = self.conn.lock().await;
527+ conn.execute(
528+ "UPDATE notes SET trashed_at = ?2 WHERE id = ?1",
529+ (note_id.to_string(), now_millis()),
530+ )
531+ .await?;
532+ Ok(())
533+ }
534+
535+ /// Takes the note out of the trash.
536+ pub async fn restore_note(&self, note_id: &str) -> anyhow::Result<()> {
537+ let conn = self.conn.lock().await;
538+ conn.execute(
539+ "UPDATE notes SET trashed_at = NULL WHERE id = ?1",
540+ (note_id.to_string(),),
541+ )
542+ .await?;
543+ Ok(())
544+ }
545+
546+ /// Permanently deletes notes trashed more than `older_than_ms` milliseconds ago.
547+ /// Returns the ids of the deleted notes.
548+ pub async fn purge_trash(&self, older_than_ms: i64) -> anyhow::Result<Vec<String>> {
549+ let cutoff = now_millis().saturating_sub(older_than_ms);
550+ self.delete_trashed(cutoff).await
551+ }
552+
553+ /// Permanently deletes every trashed note. Returns the ids of the deleted notes.
554+ pub async fn empty_trash(&self) -> anyhow::Result<Vec<String>> {
555+ self.delete_trashed(i64::MAX).await
556+ }
557+
558+ /// Deletes trashed notes with `trashed_at < before` in one transaction.
559+ async fn delete_trashed(&self, before: i64) -> anyhow::Result<Vec<String>> {
560+ let mut conn = self.conn.lock().await;
561+ let tx = conn.transaction().await?;
562+ let mut rows = tx
563+ .query(
564+ "SELECT id FROM notes WHERE trashed_at IS NOT NULL AND trashed_at < ?1 ORDER BY trashed_at, id",
565+ (before,),
566+ )
567+ .await?;
568+ let mut ids = Vec::new();
569+ while let Some(row) = rows.next().await? {
570+ ids.push(text_col(&row, 0)?);
571+ }
572+ drop(rows);
573+ for id in &ids {
574+ delete_note_rows(&tx, id).await?;
575+ }
576+ tx.commit().await?;
577+ Ok(ids)
578+ }
579+
580+ /// Trashed notes, most recently trashed first.
581+ pub async fn list_trash(&self) -> anyhow::Result<Vec<NoteMeta>> {
582+ let conn = self.conn.lock().await;
583+ let mut rows = conn
584+ .query(
585+ "SELECT id, title, created_at, updated_at, notebook_id, trashed_at FROM notes
586+ WHERE trashed_at IS NOT NULL ORDER BY trashed_at DESC, id",
587+ (),
588+ )
589+ .await?;
590+ let mut notes = Vec::new();
591+ while let Some(row) = rows.next().await? {
592+ notes.push(note_from_row(&row)?);
593+ }
594+ Ok(notes)
595+ }
596+
597+ /// Notes that are not in the trash, most recently updated first.
598+ pub async fn list_notes(&self) -> anyhow::Result<Vec<NoteMeta>> {
599+ let conn = self.conn.lock().await;
600+ let mut rows = conn
601+ .query(
602+ "SELECT id, title, created_at, updated_at, notebook_id, trashed_at FROM notes
603+ WHERE trashed_at IS NULL ORDER BY updated_at DESC, id",
604+ (),
605+ )
606+ .await?;
607+ let mut notes = Vec::new();
608+ while let Some(row) = rows.next().await? {
609+ notes.push(note_from_row(&row)?);
610+ }
611+ Ok(notes)
612+ }
613+
614+ pub async fn get_note(&self, id: &str) -> anyhow::Result<Option<NoteMeta>> {
615+ let conn = self.conn.lock().await;
616+ let mut rows = conn
617+ .query(
618+ "SELECT id, title, created_at, updated_at, notebook_id, trashed_at FROM notes WHERE id = ?1",
619+ (id.to_string(),),
620+ )
621+ .await?;
622+ match rows.next().await? {
623+ Some(row) => Ok(Some(note_from_row(&row)?)),
624+ None => Ok(None),
625+ }
626+ }
627+
628+ /// Appends a Loro update. Idempotent: the same bytes stored twice are kept once.
629+ pub async fn append_update(&self, note_id: &str, update: &[u8]) -> anyhow::Result<()> {
630+ let hash = blake3::hash(update).as_bytes().to_vec();
631+ let mut conn = self.conn.lock().await;
632+ let tx = conn.transaction().await?;
633+ let inserted = tx
634+ .execute(
635+ "INSERT OR IGNORE INTO updates (note_id, hash, data) VALUES (?1, ?2, ?3)",
636+ (note_id.to_string(), hash, update.to_vec()),
637+ )
638+ .await?;
639+ if inserted > 0 {
640+ tx.execute(
641+ "UPDATE notes SET updated_at = ?2 WHERE id = ?1",
642+ (note_id.to_string(), now_millis()),
643+ )
644+ .await?;
645+ }
646+ tx.commit().await?;
647+ Ok(())
648+ }
649+
650+ pub async fn load_doc(&self, note_id: &str) -> anyhow::Result<DocBytes> {
651+ let conn = self.conn.lock().await;
652+
653+ let mut rows = conn
654+ .query(
655+ "SELECT data, upto_seq FROM snapshots WHERE note_id = ?1",
656+ (note_id.to_string(),),
657+ )
658+ .await?;
659+ let (snapshot, upto_seq) = match rows.next().await? {
660+ Some(row) => (Some(blob_col(&row, 0)?), int_col(&row, 1)?),
661+ None => (None, 0),
662+ };
663+ drop(rows);
664+
665+ let mut rows = conn
666+ .query(
667+ "SELECT data FROM updates WHERE note_id = ?1 AND seq > ?2 ORDER BY seq",
668+ (note_id.to_string(), upto_seq),
669+ )
670+ .await?;
671+ let mut updates = Vec::new();
672+ while let Some(row) = rows.next().await? {
673+ updates.push(blob_col(&row, 0)?);
674+ }
675+
676+ Ok(DocBytes { snapshot, updates })
677+ }
678+
679+ /// Stores a full snapshot plus the derived markdown and title.
680+ /// Updates are never deleted; later loads only read updates newer than the snapshot.
681+ pub async fn put_snapshot(
682+ &self,
683+ note_id: &str,
684+ snapshot: &[u8],
685+ markdown: &str,
686+ title: &str,
687+ ) -> anyhow::Result<()> {
688+ let mut conn = self.conn.lock().await;
689+ let tx = conn.transaction().await?;
690+
691+ let mut rows = tx
692+ .query(
693+ "SELECT COALESCE(MAX(seq), 0) FROM updates WHERE note_id = ?1",
694+ (note_id.to_string(),),
695+ )
696+ .await?;
697+ let max_seq = match rows.next().await? {
698+ Some(row) => int_col(&row, 0)?,
699+ None => 0,
700+ };
701+ drop(rows);
702+
703+ tx.execute(
704+ "INSERT INTO snapshots (note_id, data, upto_seq, markdown) VALUES (?1, ?2, ?3, ?4)
705+ ON CONFLICT(note_id) DO UPDATE SET
706+ data = excluded.data,
707+ upto_seq = excluded.upto_seq,
708+ markdown = excluded.markdown",
709+ (
710+ note_id.to_string(),
711+ snapshot.to_vec(),
712+ max_seq,
713+ markdown.to_string(),
714+ ),
715+ )
716+ .await?;
717+ tx.execute(
718+ "UPDATE notes SET title = ?2 WHERE id = ?1",
719+ (note_id.to_string(), title.to_string()),
720+ )
721+ .await?;
722+
723+ tx.commit().await?;
724+ Ok(())
725+ }
726+
727+ pub async fn set_title(&self, note_id: &str, title: &str) -> anyhow::Result<()> {
728+ let conn = self.conn.lock().await;
729+ conn.execute(
730+ "UPDATE notes SET title = ?2 WHERE id = ?1",
731+ (note_id.to_string(), title.to_string()),
732+ )
733+ .await?;
734+ Ok(())
735+ }
736+
737+ /// Upserts the searchable text of a note. Does nothing when the note no longer
738+ /// exists, so a flush that races a delete cannot bring the text back.
739+ pub async fn put_text(&self, note_id: &str, title: &str, body: &str) -> anyhow::Result<()> {
740+ let conn = self.conn.lock().await;
741+ let mut rows = conn
742+ .query("SELECT 1 FROM notes WHERE id = ?1", (note_id.to_string(),))
743+ .await?;
744+ let exists = rows.next().await?.is_some();
745+ drop(rows);
746+ if !exists {
747+ return Ok(());
748+ }
749+ conn.execute(
750+ "INSERT INTO note_text (note_id, title, body) VALUES (?1, ?2, ?3)
751+ ON CONFLICT(note_id) DO UPDATE SET title = excluded.title, body = excluded.body",
752+ (note_id.to_string(), title.to_string(), body.to_string()),
753+ )
754+ .await?;
755+ Ok(())
756+ }
757+
758+ /// Replaces the note links of `src`. Does nothing when the note no longer exists, like
759+ /// `put_text`. Title targets are stored by `title_key`.
760+ pub async fn set_links(&self, src: &str, targets: &[LinkTarget]) -> anyhow::Result<()> {
761+ let mut conn = self.conn.lock().await;
762+ let mut rows = conn
763+ .query("SELECT 1 FROM notes WHERE id = ?1", (src.to_string(),))
764+ .await?;
765+ let exists = rows.next().await?.is_some();
766+ drop(rows);
767+ if !exists {
768+ return Ok(());
769+ }
770+ let tx = conn.transaction().await?;
771+ tx.execute("DELETE FROM note_links WHERE src = ?1", (src.to_string(),))
772+ .await?;
773+ for target in targets {
774+ match target {
775+ LinkTarget::Id(id) => {
776+ tx.execute(
777+ "INSERT INTO note_links (src, dst_id, dst_title) VALUES (?1, ?2, NULL)",
778+ (src.to_string(), id.clone()),
779+ )
780+ .await?;
781+ }
782+ LinkTarget::Title(title) => {
783+ let key = title_key(title);
784+ if key.is_empty() {
785+ continue;
786+ }
787+ tx.execute(
788+ "INSERT INTO note_links (src, dst_id, dst_title) VALUES (?1, NULL, ?2)",
789+ (src.to_string(), key),
790+ )
791+ .await?;
792+ }
793+ }
794+ }
795+ tx.commit().await?;
796+ Ok(())
797+ }
798+
799+ /// Non-trashed notes, other than `note_id`, that link to the note by its id or by
800+ /// its title. Most recently updated first.
801+ pub async fn backlinks(&self, note_id: &str, title: &str) -> anyhow::Result<Vec<NoteMeta>> {
802+ let conn = self.conn.lock().await;
803+ let mut rows = conn
804+ .query(
805+ "SELECT id, title, created_at, updated_at, notebook_id, trashed_at FROM notes
806+ WHERE trashed_at IS NULL AND id <> ?1 AND id IN
807+ (SELECT src FROM note_links WHERE dst_id = ?1 OR dst_title = ?2)
808+ ORDER BY updated_at DESC, id",
809+ (note_id.to_string(), title_key(title)),
810+ )
811+ .await?;
812+ let mut notes = Vec::new();
813+ while let Some(row) = rows.next().await? {
814+ notes.push(note_from_row(&row)?);
815+ }
816+ Ok(notes)
817+ }
818+
819+ /// Search over titles and bodies with `matcher` (see [`crate::matcher`]): every term
820+ /// must match the title or the text. Closest matches first, then more terms in the
821+ /// title, then most recently updated.
822+ pub async fn search(&self, matcher: &Matcher, limit: usize) -> anyhow::Result<Vec<SearchHit>> {
823+ if limit == 0 {
824+ return Ok(Vec::new());
825+ }
826+ // A scan rather than the FTS index: the index matches whole words only, and
827+ // typing "asd" has to find "asdadasxd" (and "isik" find "Işık").
828+ let conn = self.conn.lock().await;
829+ let mut rows = conn
830+ .query(
831+ "SELECT n.id, n.title, n.created_at, n.updated_at, n.notebook_id, n.trashed_at,
832+ COALESCE(t.body, '')
833+ FROM notes n LEFT JOIN note_text t ON t.note_id = n.id
834+ WHERE n.trashed_at IS NULL",
835+ (),
836+ )
837+ .await?;
838+ let mut hits = Vec::new();
839+ while let Some(row) = rows.next().await? {
840+ let note = note_from_row(&row)?;
841+ let body = text_col(&row, 6)?;
842+ let in_title = matcher.term_costs(&note.title);
843+ let in_text = matcher.term_costs(&plain_text(&body));
844+ // Each term matches the title or the text, whichever is closer. Cheaper
845+ // matches first (exact before typos), then more terms in the title.
846+ let mut cost = 0;
847+ let mut title_terms = 0;
848+ let mut matched = true;
849+ for (t, x) in in_title.into_iter().zip(in_text) {
850+ match (t, x) {
851+ (Some(t), Some(x)) if t <= x => (cost += t, title_terms += 1),
852+ (Some(t), None) => (cost += t, title_terms += 1),
853+ (_, Some(x)) => (cost += x, ()),
854+ (None, None) => {
855+ matched = false;
856+ break;
857+ }
858+ };
859+ }
860+ if !matched {
861+ continue;
862+ }
863+ hits.push((
864+ (cost, std::cmp::Reverse(title_terms)),
865+ SearchHit {
866+ snippet: snippet(&body, matcher),
867+ note,
868+ },
869+ ));
870+ }
871+ hits.sort_by(|a, b| a.0.cmp(&b.0).then(b.1.note.updated_at.cmp(&a.1.note.updated_at)));
872+ hits.truncate(limit);
873+ Ok(hits.into_iter().map(|(_, hit)| hit).collect())
874+ }
875+
876+ /// Notes, not in the trash, whose title holds every word of `query`, typos allowed
877+ /// (see [`crate::matcher`]). Closest matches first, then most recently updated.
878+ pub async fn search_titles(&self, query: &str, limit: usize) -> anyhow::Result<Vec<NoteMeta>> {
879+ let Some(matcher) = Matcher::simple(query) else {
880+ return Ok(Vec::new());
881+ };
882+ if limit == 0 {
883+ return Ok(Vec::new());
884+ }
885+ // Matched in Rust, not with SQL LIKE, which folds only ASCII case and has no
886+ // typo tolerance: "izmir" and "izmr" have to find "İzmir".
887+ let conn = self.conn.lock().await;
888+ let mut rows = conn
889+ .query(
890+ "SELECT id, title, created_at, updated_at, notebook_id, trashed_at FROM notes
891+ WHERE trashed_at IS NULL ORDER BY updated_at DESC, id",
892+ (),
893+ )
894+ .await?;
895+ let mut notes = Vec::new();
896+ while let Some(row) = rows.next().await? {
897+ let note = note_from_row(&row)?;
898+ if let Some(cost) = matcher.cost(&note.title) {
899+ notes.push((cost, note));
900+ }
901+ }
902+ // Stable: equal costs stay most recent first.
903+ notes.sort_by_key(|(cost, _)| *cost);
904+ notes.truncate(limit);
905+ Ok(notes.into_iter().map(|(_, note)| note).collect())
906+ }
907+
908+ /// Previews of every note's text, keyed by note id, for list rows. Trashed notes are
909+ /// included; callers look up only the notes they show.
910+ pub async fn previews(&self) -> anyhow::Result<HashMap<String, String>> {
911+ let conn = self.conn.lock().await;
912+ let mut rows = conn.query("SELECT note_id, body FROM note_text", ()).await?;
913+ let mut previews = HashMap::new();
914+ while let Some(row) = rows.next().await? {
915+ previews.insert(text_col(&row, 0)?, preview(&text_col(&row, 1)?));
916+ }
917+ Ok(previews)
918+ }
919+
920+ /// Stores a version of a note: the time in millis and the encoded frontiers of the doc.
921+ pub async fn add_version(&self, note_id: &str, at_ms: i64, frontiers: &[u8]) -> anyhow::Result<()> {
922+ let conn = self.conn.lock().await;
923+ conn.execute(
924+ "INSERT OR REPLACE INTO note_versions (note_id, at, frontiers) VALUES (?1, ?2, ?3)",
925+ (note_id.to_string(), at_ms, frontiers.to_vec()),
926+ )
927+ .await?;
928+ Ok(())
929+ }
930+
931+ /// Recorded versions of a note as `(at, frontiers)`, newest first.
932+ pub async fn list_versions(&self, note_id: &str) -> anyhow::Result<Vec<(i64, Vec<u8>)>> {
933+ let conn = self.conn.lock().await;
934+ let mut rows = conn
935+ .query(
936+ "SELECT at, frontiers FROM note_versions WHERE note_id = ?1 ORDER BY at DESC",
937+ (note_id.to_string(),),
938+ )
939+ .await?;
940+ let mut versions = Vec::new();
941+ while let Some(row) = rows.next().await? {
942+ versions.push((int_col(&row, 0)?, blob_col(&row, 1)?));
943+ }
944+ Ok(versions)
945+ }
946+
947+ /// The encoded frontiers of the version of a note taken at `at`, if it exists.
948+ pub async fn get_version(&self, note_id: &str, at: i64) -> anyhow::Result<Option<Vec<u8>>> {
949+ let conn = self.conn.lock().await;
950+ let mut rows = conn
951+ .query(
952+ "SELECT frontiers FROM note_versions WHERE note_id = ?1 AND at = ?2",
953+ (note_id.to_string(), at),
954+ )
955+ .await?;
956+ match rows.next().await? {
957+ Some(row) => Ok(Some(blob_col(&row, 0)?)),
958+ None => Ok(None),
959+ }
960+ }
961+
962+ pub async fn get_markdown(&self, note_id: &str) -> anyhow::Result<Option<String>> {
963+ let conn = self.conn.lock().await;
964+ let mut rows = conn
965+ .query(
966+ "SELECT markdown FROM snapshots WHERE note_id = ?1",
967+ (note_id.to_string(),),
968+ )
969+ .await?;
970+ match rows.next().await? {
971+ Some(row) => Ok(Some(text_col(&row, 0)?)),
972+ None => Ok(None),
973+ }
974+ }
975+}
976+
styles.cssadded+1006 -0
@@ -0,0 +1,1006 @@
1+/* The theme is a small set of design tokens. Components refer to tokens only, never
2+ to raw colors. Each color scheme (see the nine `:root[data-scheme="..."]` blocks
3+ below) sets every color token for light and for `.dark`. With no `data-scheme`, the
4+ Sage values in `:root` and `.dark` apply.
5+
6+ --background the page background
7+ --foreground text and iconography on the background
8+ --card editor page, list pane, cards
9+ --card-foreground text on cards
10+ --popover floating menus and dialogs (lifted in dark)
11+ --popover-foreground text on floating surfaces
12+ --muted-foreground secondary text, metadata, placeholders
13+ --primary highlighter fill: primary buttons, active marker
14+ --primary-foreground text on the highlighter fill
15+ --destructive destructive actions and error states
16+ --destructive-foreground text on a destructive-filled surface
17+ --border hairline borders and dividers
18+ --ring the focus outline
19+ --sidebar the sidebar background
20+ --sidebar-foreground sidebar text and icons
21+ --sidebar-primary primary actions inside the sidebar
22+ --sidebar-primary-foreground text on sidebar primary actions
23+ --sidebar-accent sidebar hover and selected backgrounds
24+ --sidebar-accent-foreground text on sidebar accents
25+ --sidebar-border sidebar borders and dividers
26+ --sidebar-ring sidebar focus rings
27+ --link links and accent ink
28+ --mark text selection and search matches
29+ --active-row the selected row: sidebar item, note, palette option
30+ --active-row-foreground text on the selected row
31+ --ok connected, saved
32+ --warn offline, reconnecting
33+ --bad errors (same role as --destructive)
34+ --keycap-bg keycap chips
35+ --shadow-xs, --shadow-sm raised controls and cards: none by default
36+ --shadow-float floating surfaces only (menus, dialogs, tooltips)
37+
38+ Fonts are declared in Rust with topcoat-font (Atkinson Hyperlegible Next for
39+ UI and body text, Atkinson Hyperlegible Mono for metadata and keycaps). */
40+
41+@import "tailwindcss";
42+
43+/* Scan the project's Rust sources for the Tailwind classes they use. This
44+ file is installed at the project root, so `./src` is the crate's source. */
45+@source "./src/**/*.rs";
46+
47+/* Dark mode is opted into by putting the `dark` class on an ancestor,
48+ typically <html>. */
49+@custom-variant dark (&:is(.dark *));
50+
51+/* Expose the tokens as Tailwind utilities (`bg-background`, `text-primary`,
52+ `border-border`, `text-link`, `bg-mark`, ...). The indirection through plain
53+ variables on `:root` and `.dark` is what lets the values swap when the color
54+ scheme changes. */
55+@theme inline {
56+ --font-sans: "Atkinson Hyperlegible Next", sans-serif;
57+ --font-mono: "Atkinson Hyperlegible Mono", ui-monospace, monospace;
58+
59+ --color-background: var(--background);
60+ --color-foreground: var(--foreground);
61+ --color-card: var(--card);
62+ --color-card-foreground: var(--card-foreground);
63+ --color-popover: var(--popover);
64+ --color-popover-foreground: var(--popover-foreground);
65+ --color-muted-foreground: var(--muted-foreground);
66+ --color-primary: var(--primary);
67+ --color-primary-foreground: var(--primary-foreground);
68+ --color-destructive: var(--destructive);
69+ --color-destructive-foreground: var(--destructive-foreground);
70+ --color-border: var(--border);
71+ --color-ring: var(--ring);
72+ --color-sidebar: var(--sidebar);
73+ --color-sidebar-foreground: var(--sidebar-foreground);
74+ --color-sidebar-primary: var(--sidebar-primary);
75+ --color-sidebar-primary-foreground: var(--sidebar-primary-foreground);
76+ --color-sidebar-accent: var(--sidebar-accent);
77+ --color-sidebar-accent-foreground: var(--sidebar-accent-foreground);
78+ --color-sidebar-border: var(--sidebar-border);
79+ --color-sidebar-ring: var(--sidebar-ring);
80+ --color-link: var(--link);
81+ --color-mark: var(--mark);
82+ --color-active-row: var(--active-row);
83+ --color-active-row-foreground: var(--active-row-foreground);
84+ --color-ok: var(--ok);
85+ --color-warn: var(--warn);
86+ --color-bad: var(--bad);
87+ --color-keycap: var(--keycap-bg);
88+
89+ --radius-control: 6px;
90+ --radius-float: 10px;
91+ --radius-pill: 999px;
92+
93+ --shadow-xs: var(--shadow-xs);
94+ --shadow-sm: var(--shadow-sm);
95+ --shadow-float: var(--shadow-float);
96+}
97+
98+:root {
99+ --background: #f5f7f4;
100+ --foreground: #18201a;
101+ --card: #ffffff;
102+ --card-foreground: #18201a;
103+ --popover: #ffffff;
104+ --popover-foreground: #18201a;
105+ --muted-foreground: #56625a;
106+ --primary: #567752;
107+ --primary-foreground: #ffffff;
108+ --destructive: #b3261e;
109+ --destructive-foreground: #ffffff;
110+ --border: #d2dbd0;
111+ --ring: #2f6b3a;
112+ --sidebar: #e9efe6;
113+ --sidebar-foreground: #18201a;
114+ --sidebar-primary: #567752;
115+ --sidebar-primary-foreground: #ffffff;
116+ --sidebar-accent: color-mix(in srgb, var(--sidebar) 60%, var(--border));
117+ --sidebar-accent-foreground: #18201a;
118+ --sidebar-border: #d2dbd0;
119+ --sidebar-ring: #2f6b3a;
120+ --link: #2f6b3a;
121+ --mark: #ffe9a3;
122+ --active-row: #d9ebd3;
123+ --active-row-foreground: #1f3d22;
124+ --ok: #1f7a4a;
125+ --warn: #9a5b00;
126+ --bad: #b3261e;
127+ --keycap-bg: #e1e9de;
128+ --shadow-xs: 0 1px 2px rgb(0 0 0 / 0.08);
129+ --shadow-sm: 0 0 #0000;
130+ --shadow-float: 0 8px 24px rgb(0 0 0 / 0.12);
131+}
132+
133+.dark {
134+ --background: #151615;
135+ --foreground: #e6e6e1;
136+ --card: #1b1c1b;
137+ --card-foreground: #e6e6e1;
138+ --popover: #1b1c1b;
139+ --popover-foreground: #e6e6e1;
140+ --muted-foreground: #9f9f98;
141+ --primary: #4a6847;
142+ --primary-foreground: #eef4ea;
143+ --destructive: #f08a80;
144+ --destructive-foreground: #151615;
145+ --border: #2b2d2b;
146+ --ring: #a7c49f;
147+ --sidebar: #111211;
148+ --sidebar-foreground: #e6e6e1;
149+ --sidebar-primary: #4a6847;
150+ --sidebar-primary-foreground: #eef4ea;
151+ --sidebar-accent: color-mix(in srgb, var(--sidebar) 60%, var(--border));
152+ --sidebar-accent-foreground: #e6e6e1;
153+ --sidebar-border: #2b2d2b;
154+ --sidebar-ring: #a7c49f;
155+ --link: #a7c49f;
156+ --mark: #5e5216;
157+ --active-row: #233024;
158+ --active-row-foreground: #d8e6d4;
159+ --ok: #8cc79a;
160+ --warn: #f2b45a;
161+ --bad: #f08a80;
162+ --keycap-bg: #252625;
163+ --shadow-xs: 0 1px 2px rgb(0 0 0 / 0.5);
164+ --shadow-sm: 0 0 #0000;
165+ --shadow-float: 0 8px 24px rgb(0 0 0 / 0.5);
166+}
167+
168+/* Color schemes. Each palette: a light block for the default mode and a dark block
169+ for `.dark`. The `:not(.dark)` keeps the light block from winning in dark mode. */
170+:root[data-scheme="graphite"]:not(.dark) {
171+ --background: #f6f7f9;
172+ --foreground: #15181d;
173+ --card: #ffffff;
174+ --card-foreground: #15181d;
175+ --popover: #ffffff;
176+ --popover-foreground: #15181d;
177+ --muted-foreground: #5a616d;
178+ --primary: #f2b600;
179+ --primary-foreground: #15181d;
180+ --destructive: #b42318;
181+ --destructive-foreground: #ffffff;
182+ --border: #d5d9e0;
183+ --ring: #1d4ed8;
184+ --sidebar: #eceef2;
185+ --sidebar-foreground: #15181d;
186+ --sidebar-primary: #f2b600;
187+ --sidebar-primary-foreground: #15181d;
188+ --sidebar-accent: color-mix(in srgb, var(--sidebar) 60%, var(--border));
189+ --sidebar-accent-foreground: #15181d;
190+ --sidebar-border: #d5d9e0;
191+ --sidebar-ring: #1d4ed8;
192+ --link: #1d4ed8;
193+ --mark: #ffe9a0;
194+ --active-row: #ffe08a;
195+ --active-row-foreground: #15181d;
196+ --ok: #1e7a46;
197+ --warn: #9a5b00;
198+ --bad: #b42318;
199+ --keycap-bg: #e3e6eb;
200+}
201+
202+:root[data-scheme="graphite"].dark {
203+ --background: #16181c;
204+ --foreground: #eceef2;
205+ --card: #22262d;
206+ --card-foreground: #eceef2;
207+ --popover: #22262d;
208+ --popover-foreground: #eceef2;
209+ --muted-foreground: #9aa3b2;
210+ --primary: #ffc93c;
211+ --primary-foreground: #15181d;
212+ --destructive: #ff8a80;
213+ --destructive-foreground: #16181c;
214+ --border: #343a45;
215+ --ring: #8ab4ff;
216+ --sidebar: #1d2026;
217+ --sidebar-foreground: #eceef2;
218+ --sidebar-primary: #ffc93c;
219+ --sidebar-primary-foreground: #15181d;
220+ --sidebar-accent: color-mix(in srgb, var(--sidebar) 60%, var(--border));
221+ --sidebar-accent-foreground: #eceef2;
222+ --sidebar-border: #343a45;
223+ --sidebar-ring: #8ab4ff;
224+ --link: #8ab4ff;
225+ --mark: #7a5f00;
226+ --active-row: #5c4700;
227+ --active-row-foreground: #fff3c4;
228+ --ok: #5fcf8f;
229+ --warn: #f2b45a;
230+ --bad: #ff8a80;
231+ --keycap-bg: #2b3038;
232+}
233+
234+:root[data-scheme="cobalt"]:not(.dark) {
235+ --background: #fbfcff;
236+ --foreground: #0e1830;
237+ --card: #ffffff;
238+ --card-foreground: #0e1830;
239+ --popover: #ffffff;
240+ --popover-foreground: #0e1830;
241+ --muted-foreground: #4a5772;
242+ --primary: #1f4fd1;
243+ --primary-foreground: #ffffff;
244+ --destructive: #b3261e;
245+ --destructive-foreground: #ffffff;
246+ --border: #d3dcea;
247+ --ring: #1f4fd1;
248+ --sidebar: #eef3fb;
249+ --sidebar-foreground: #0e1830;
250+ --sidebar-primary: #1f4fd1;
251+ --sidebar-primary-foreground: #ffffff;
252+ --sidebar-accent: color-mix(in srgb, var(--sidebar) 60%, var(--border));
253+ --sidebar-accent-foreground: #0e1830;
254+ --sidebar-border: #d3dcea;
255+ --sidebar-ring: #1f4fd1;
256+ --link: #1f4fd1;
257+ --mark: #fff0a6;
258+ --active-row: #dce7ff;
259+ --active-row-foreground: #0b2a80;
260+ --ok: #137a4a;
261+ --warn: #9a5b00;
262+ --bad: #b3261e;
263+ --keycap-bg: #e2e9f7;
264+}
265+
266+:root[data-scheme="cobalt"].dark {
267+ --background: #0c1120;
268+ --foreground: #e6ecfb;
269+ --card: #17213a;
270+ --card-foreground: #e6ecfb;
271+ --popover: #17213a;
272+ --popover-foreground: #e6ecfb;
273+ --muted-foreground: #97a4c2;
274+ --primary: #5b8bff;
275+ --primary-foreground: #0a1024;
276+ --destructive: #ff8b84;
277+ --destructive-foreground: #0c1120;
278+ --border: #2a3756;
279+ --ring: #8fb0ff;
280+ --sidebar: #121a2c;
281+ --sidebar-foreground: #e6ecfb;
282+ --sidebar-primary: #5b8bff;
283+ --sidebar-primary-foreground: #0a1024;
284+ --sidebar-accent: color-mix(in srgb, var(--sidebar) 60%, var(--border));
285+ --sidebar-accent-foreground: #e6ecfb;
286+ --sidebar-border: #2a3756;
287+ --sidebar-ring: #8fb0ff;
288+ --link: #8fb0ff;
289+ --mark: #6b5a00;
290+ --active-row: #1d2f5c;
291+ --active-row-foreground: #cfdcff;
292+ --ok: #5fd39a;
293+ --warn: #f2b45a;
294+ --bad: #ff8b84;
295+ --keycap-bg: #1f2a45;
296+}
297+
298+:root[data-scheme="oxblood"]:not(.dark) {
299+ --background: #f7f5f4;
300+ --foreground: #201a19;
301+ --card: #ffffff;
302+ --card-foreground: #201a19;
303+ --popover: #ffffff;
304+ --popover-foreground: #201a19;
305+ --muted-foreground: #625a57;
306+ --primary: #8e1b22;
307+ --primary-foreground: #ffffff;
308+ --destructive: #a4161a;
309+ --destructive-foreground: #ffffff;
310+ --border: #d9d2cf;
311+ --ring: #9c2a2a;
312+ --sidebar: #eeeae8;
313+ --sidebar-foreground: #201a19;
314+ --sidebar-primary: #8e1b22;
315+ --sidebar-primary-foreground: #ffffff;
316+ --sidebar-accent: color-mix(in srgb, var(--sidebar) 60%, var(--border));
317+ --sidebar-accent-foreground: #201a19;
318+ --sidebar-border: #d9d2cf;
319+ --sidebar-ring: #9c2a2a;
320+ --link: #9c2a2a;
321+ --mark: #ffe9a3;
322+ --active-row: #f8dcd9;
323+ --active-row-foreground: #6b1218;
324+ --ok: #2d6a3e;
325+ --warn: #9a5b00;
326+ --bad: #a4161a;
327+ --keycap-bg: #e7e2e0;
328+}
329+
330+:root[data-scheme="oxblood"].dark {
331+ --background: #141111;
332+ --foreground: #f1eceb;
333+ --card: #221d1d;
334+ --card-foreground: #f1eceb;
335+ --popover: #221d1d;
336+ --popover-foreground: #f1eceb;
337+ --muted-foreground: #a89f9c;
338+ --primary: #d85c63;
339+ --primary-foreground: #140e0e;
340+ --destructive: #ff8a8a;
341+ --destructive-foreground: #141111;
342+ --border: #3a3332;
343+ --ring: #f09a94;
344+ --sidebar: #1c1818;
345+ --sidebar-foreground: #f1eceb;
346+ --sidebar-primary: #d85c63;
347+ --sidebar-primary-foreground: #140e0e;
348+ --sidebar-accent: color-mix(in srgb, var(--sidebar) 60%, var(--border));
349+ --sidebar-accent-foreground: #f1eceb;
350+ --sidebar-border: #3a3332;
351+ --sidebar-ring: #f09a94;
352+ --link: #f09a94;
353+ --mark: #6e5a10;
354+ --active-row: #4a1d21;
355+ --active-row-foreground: #ffd9d6;
356+ --ok: #7ccf96;
357+ --warn: #f2b45a;
358+ --bad: #ff8a8a;
359+ --keycap-bg: #2e2828;
360+}
361+
362+:root[data-scheme="teal"]:not(.dark) {
363+ --background: #f4f8f8;
364+ --foreground: #13201f;
365+ --card: #ffffff;
366+ --card-foreground: #13201f;
367+ --popover: #ffffff;
368+ --popover-foreground: #13201f;
369+ --muted-foreground: #4f6663;
370+ --primary: #0f5e5a;
371+ --primary-foreground: #ffffff;
372+ --destructive: #b42318;
373+ --destructive-foreground: #ffffff;
374+ --border: #cbdad8;
375+ --ring: #0b6b66;
376+ --sidebar: #e8f0f0;
377+ --sidebar-foreground: #13201f;
378+ --sidebar-primary: #0f5e5a;
379+ --sidebar-primary-foreground: #ffffff;
380+ --sidebar-accent: color-mix(in srgb, var(--sidebar) 60%, var(--border));
381+ --sidebar-accent-foreground: #13201f;
382+ --sidebar-border: #cbdad8;
383+ --sidebar-ring: #0b6b66;
384+ --link: #0b6b66;
385+ --mark: #ffe27a;
386+ --active-row: #cdeee9;
387+ --active-row-foreground: #073b38;
388+ --ok: #1b7340;
389+ --warn: #9a5b00;
390+ --bad: #b42318;
391+ --keycap-bg: #dde8e7;
392+}
393+
394+:root[data-scheme="teal"].dark {
395+ --background: #0d1514;
396+ --foreground: #e3efed;
397+ --card: #172624;
398+ --card-foreground: #e3efed;
399+ --popover: #172624;
400+ --popover-foreground: #e3efed;
401+ --muted-foreground: #98b1ad;
402+ --primary: #3fb3a6;
403+ --primary-foreground: #06201e;
404+ --destructive: #ff8a80;
405+ --destructive-foreground: #0d1514;
406+ --border: #2a3d3b;
407+ --ring: #7fd6cc;
408+ --sidebar: #121d1c;
409+ --sidebar-foreground: #e3efed;
410+ --sidebar-primary: #3fb3a6;
411+ --sidebar-primary-foreground: #06201e;
412+ --sidebar-accent: color-mix(in srgb, var(--sidebar) 60%, var(--border));
413+ --sidebar-accent-foreground: #e3efed;
414+ --sidebar-border: #2a3d3b;
415+ --sidebar-ring: #7fd6cc;
416+ --link: #7fd6cc;
417+ --mark: #6b5a10;
418+ --active-row: #15403b;
419+ --active-row-foreground: #c4f2eb;
420+ --ok: #5fcf8f;
421+ --warn: #f2b45a;
422+ --bad: #ff8a80;
423+ --keycap-bg: #1f3431;
424+}
425+
426+:root[data-scheme="plum"]:not(.dark) {
427+ --background: #f8f6fa;
428+ --foreground: #1f1a26;
429+ --card: #ffffff;
430+ --card-foreground: #1f1a26;
431+ --popover: #ffffff;
432+ --popover-foreground: #1f1a26;
433+ --muted-foreground: #5f5570;
434+ --primary: #7b2d6e;
435+ --primary-foreground: #ffffff;
436+ --destructive: #b3261e;
437+ --destructive-foreground: #ffffff;
438+ --border: #d9d1e2;
439+ --ring: #6a2fb0;
440+ --sidebar: #efeaf3;
441+ --sidebar-foreground: #1f1a26;
442+ --sidebar-primary: #7b2d6e;
443+ --sidebar-primary-foreground: #ffffff;
444+ --sidebar-accent: color-mix(in srgb, var(--sidebar) 60%, var(--border));
445+ --sidebar-accent-foreground: #1f1a26;
446+ --sidebar-border: #d9d1e2;
447+ --sidebar-ring: #6a2fb0;
448+ --link: #6a2fb0;
449+ --mark: #ffe9a3;
450+ --active-row: #f1d9ee;
451+ --active-row-foreground: #5a1a4f;
452+ --ok: #1f7a4a;
453+ --warn: #9a5b00;
454+ --bad: #b3261e;
455+ --keycap-bg: #e8e2ee;
456+}
457+
458+:root[data-scheme="plum"].dark {
459+ --background: #120f16;
460+ --foreground: #ece8f2;
461+ --card: #201b27;
462+ --card-foreground: #ece8f2;
463+ --popover: #201b27;
464+ --popover-foreground: #ece8f2;
465+ --muted-foreground: #a79fb6;
466+ --primary: #d27ac4;
467+ --primary-foreground: #1a0d18;
468+ --destructive: #ff8a8a;
469+ --destructive-foreground: #120f16;
470+ --border: #3a3246;
471+ --ring: #c9a6ff;
472+ --sidebar: #1a1620;
473+ --sidebar-foreground: #ece8f2;
474+ --sidebar-primary: #d27ac4;
475+ --sidebar-primary-foreground: #1a0d18;
476+ --sidebar-accent: color-mix(in srgb, var(--sidebar) 60%, var(--border));
477+ --sidebar-accent-foreground: #ece8f2;
478+ --sidebar-border: #3a3246;
479+ --sidebar-ring: #c9a6ff;
480+ --link: #c9a6ff;
481+ --mark: #6b5a10;
482+ --active-row: #4a2446;
483+ --active-row-foreground: #f5d6ef;
484+ --ok: #7ccf96;
485+ --warn: #f2b45a;
486+ --bad: #ff8a8a;
487+ --keycap-bg: #2e2739;
488+}
489+
490+:root[data-scheme="mono"]:not(.dark) {
491+ --background: #fafafa;
492+ --foreground: #111111;
493+ --card: #ffffff;
494+ --card-foreground: #111111;
495+ --popover: #ffffff;
496+ --popover-foreground: #111111;
497+ --muted-foreground: #5c5c5c;
498+ --primary: #111111;
499+ --primary-foreground: #ffffff;
500+ --destructive: #9b1c1c;
501+ --destructive-foreground: #ffffff;
502+ --border: #d8d8d8;
503+ --ring: #222222;
504+ --sidebar: #f0f0f0;
505+ --sidebar-foreground: #111111;
506+ --sidebar-primary: #111111;
507+ --sidebar-primary-foreground: #ffffff;
508+ --sidebar-accent: color-mix(in srgb, var(--sidebar) 60%, var(--border));
509+ --sidebar-accent-foreground: #111111;
510+ --sidebar-border: #d8d8d8;
511+ --sidebar-ring: #222222;
512+ --link: #222222;
513+ --mark: #fff1a8;
514+ --active-row: #e4e4e4;
515+ --active-row-foreground: #111111;
516+ --ok: #2e6b3a;
517+ --warn: #9a5b00;
518+ --bad: #9b1c1c;
519+ --keycap-bg: #e6e6e6;
520+}
521+
522+:root[data-scheme="mono"].dark {
523+ --background: #0e0e0e;
524+ --foreground: #f2f2f2;
525+ --card: #1c1c1c;
526+ --card-foreground: #f2f2f2;
527+ --popover: #1c1c1c;
528+ --popover-foreground: #f2f2f2;
529+ --muted-foreground: #a3a3a3;
530+ --primary: #f2f2f2;
531+ --primary-foreground: #111111;
532+ --destructive: #ff8a8a;
533+ --destructive-foreground: #0e0e0e;
534+ --border: #333333;
535+ --ring: #e6e6e6;
536+ --sidebar: #161616;
537+ --sidebar-foreground: #f2f2f2;
538+ --sidebar-primary: #f2f2f2;
539+ --sidebar-primary-foreground: #111111;
540+ --sidebar-accent: color-mix(in srgb, var(--sidebar) 60%, var(--border));
541+ --sidebar-accent-foreground: #f2f2f2;
542+ --sidebar-border: #333333;
543+ --sidebar-ring: #e6e6e6;
544+ --link: #e6e6e6;
545+ --mark: #5e4f12;
546+ --active-row: #2e2e2e;
547+ --active-row-foreground: #f2f2f2;
548+ --ok: #7ccf96;
549+ --warn: #f2b45a;
550+ --bad: #ff8a8a;
551+ --keycap-bg: #262626;
552+}
553+
554+:root[data-scheme="tangerine"]:not(.dark) {
555+ --background: #f6f7f8;
556+ --foreground: #161a1f;
557+ --card: #ffffff;
558+ --card-foreground: #161a1f;
559+ --popover: #ffffff;
560+ --popover-foreground: #161a1f;
561+ --muted-foreground: #5a626c;
562+ --primary: #f59e0b;
563+ --primary-foreground: #1a0d00;
564+ --destructive: #b3261e;
565+ --destructive-foreground: #ffffff;
566+ --border: #d6dadf;
567+ --ring: #a85200;
568+ --sidebar: #eceef0;
569+ --sidebar-foreground: #161a1f;
570+ --sidebar-primary: #f59e0b;
571+ --sidebar-primary-foreground: #1a0d00;
572+ --sidebar-accent: color-mix(in srgb, var(--sidebar) 60%, var(--border));
573+ --sidebar-accent-foreground: #161a1f;
574+ --sidebar-border: #d6dadf;
575+ --sidebar-ring: #a85200;
576+ --link: #a85200;
577+ --mark: #fff1a8;
578+ --active-row: #fde9c4;
579+ --active-row-foreground: #6b3d00;
580+ --ok: #1f7a4a;
581+ --warn: #9a5b00;
582+ --bad: #b3261e;
583+ --keycap-bg: #e3e6ea;
584+}
585+
586+:root[data-scheme="tangerine"].dark {
587+ --background: #0f1113;
588+ --foreground: #eef0f2;
589+ --card: #1c2024;
590+ --card-foreground: #eef0f2;
591+ --popover: #1c2024;
592+ --popover-foreground: #eef0f2;
593+ --muted-foreground: #a4acb6;
594+ --primary: #ffb347;
595+ --primary-foreground: #1a0d00;
596+ --destructive: #ff8a8a;
597+ --destructive-foreground: #0f1113;
598+ --border: #343a42;
599+ --ring: #ffc27a;
600+ --sidebar: #16191c;
601+ --sidebar-foreground: #eef0f2;
602+ --sidebar-primary: #ffb347;
603+ --sidebar-primary-foreground: #1a0d00;
604+ --sidebar-accent: color-mix(in srgb, var(--sidebar) 60%, var(--border));
605+ --sidebar-accent-foreground: #eef0f2;
606+ --sidebar-border: #343a42;
607+ --sidebar-ring: #ffc27a;
608+ --link: #ffc27a;
609+ --mark: #5e4f12;
610+ --active-row: #4f3412;
611+ --active-row-foreground: #ffe2b8;
612+ --ok: #7ccf96;
613+ --warn: #f2b45a;
614+ --bad: #ff8a8a;
615+ --keycap-bg: #2a2f35;
616+}
617+
618+:root[data-scheme="sage"]:not(.dark) {
619+ --background: #f5f7f4;
620+ --foreground: #18201a;
621+ --card: #ffffff;
622+ --card-foreground: #18201a;
623+ --popover: #ffffff;
624+ --popover-foreground: #18201a;
625+ --muted-foreground: #56625a;
626+ --primary: #567752;
627+ --primary-foreground: #ffffff;
628+ --destructive: #b3261e;
629+ --destructive-foreground: #ffffff;
630+ --border: #d2dbd0;
631+ --ring: #2f6b3a;
632+ --sidebar: #e9efe6;
633+ --sidebar-foreground: #18201a;
634+ --sidebar-primary: #567752;
635+ --sidebar-primary-foreground: #ffffff;
636+ --sidebar-accent: color-mix(in srgb, var(--sidebar) 60%, var(--border));
637+ --sidebar-accent-foreground: #18201a;
638+ --sidebar-border: #d2dbd0;
639+ --sidebar-ring: #2f6b3a;
640+ --link: #2f6b3a;
641+ --mark: #ffe9a3;
642+ --active-row: #d9ebd3;
643+ --active-row-foreground: #1f3d22;
644+ --ok: #1f7a4a;
645+ --warn: #9a5b00;
646+ --bad: #b3261e;
647+ --keycap-bg: #e1e9de;
648+}
649+
650+:root[data-scheme="sage"].dark {
651+ --background: #151615;
652+ --foreground: #e6e6e1;
653+ --card: #1b1c1b;
654+ --card-foreground: #e6e6e1;
655+ --popover: #1b1c1b;
656+ --popover-foreground: #e6e6e1;
657+ --muted-foreground: #9f9f98;
658+ --primary: #4a6847;
659+ --primary-foreground: #eef4ea;
660+ --destructive: #f08a80;
661+ --destructive-foreground: #151615;
662+ --border: #2b2d2b;
663+ --ring: #a7c49f;
664+ --sidebar: #111211;
665+ --sidebar-foreground: #e6e6e1;
666+ --sidebar-primary: #4a6847;
667+ --sidebar-primary-foreground: #eef4ea;
668+ --sidebar-accent: color-mix(in srgb, var(--sidebar) 60%, var(--border));
669+ --sidebar-accent-foreground: #e6e6e1;
670+ --sidebar-border: #2b2d2b;
671+ --sidebar-ring: #a7c49f;
672+ --link: #a7c49f;
673+ --mark: #5e5216;
674+ --active-row: #233024;
675+ --active-row-foreground: #d8e6d4;
676+ --ok: #8cc79a;
677+ --warn: #f2b45a;
678+ --bad: #f08a80;
679+ --keycap-bg: #252625;
680+}
681+
682+:root[data-scheme="spark"]:not(.dark) {
683+ --background: #f6f6f7;
684+ --foreground: #1a1a1d;
685+ --card: #ffffff;
686+ --card-foreground: #1a1a1d;
687+ --popover: #ffffff;
688+ --popover-foreground: #1a1a1d;
689+ --muted-foreground: #5b5b63;
690+ --primary: #ff8205;
691+ --primary-foreground: #1a0e00;
692+ --destructive: #b3261e;
693+ --destructive-foreground: #ffffff;
694+ --border: #d8d8dd;
695+ --ring: #a34c00;
696+ --sidebar: #eeeef0;
697+ --sidebar-foreground: #1a1a1d;
698+ --sidebar-primary: #ff8205;
699+ --sidebar-primary-foreground: #1a0e00;
700+ --sidebar-accent: color-mix(in srgb, var(--sidebar) 60%, var(--border));
701+ --sidebar-accent-foreground: #1a1a1d;
702+ --sidebar-border: #d8d8dd;
703+ --sidebar-ring: #a34c00;
704+ --link: #a34c00;
705+ --mark: #fff1a8;
706+ --active-row: #ffe8c7;
707+ --active-row-foreground: #753a00;
708+ --ok: #1f7a4a;
709+ --warn: #9a5b00;
710+ --bad: #b3261e;
711+ --keycap-bg: #e5e5ea;
712+}
713+
714+:root[data-scheme="spark"].dark {
715+ --background: #120f0d;
716+ --foreground: #f3ebe6;
717+ --card: #211b17;
718+ --card-foreground: #f3ebe6;
719+ --popover: #211b17;
720+ --popover-foreground: #f3ebe6;
721+ --muted-foreground: #ab9d94;
722+ --primary: #ff9a2e;
723+ --primary-foreground: #1a0e00;
724+ --destructive: #ff8a8a;
725+ --destructive-foreground: #120f0d;
726+ --border: #3d322b;
727+ --ring: #ffaa5c;
728+ --sidebar: #1a1512;
729+ --sidebar-foreground: #f3ebe6;
730+ --sidebar-primary: #ff9a2e;
731+ --sidebar-primary-foreground: #1a0e00;
732+ --sidebar-accent: color-mix(in srgb, var(--sidebar) 60%, var(--border));
733+ --sidebar-accent-foreground: #f3ebe6;
734+ --sidebar-border: #3d322b;
735+ --sidebar-ring: #ffaa5c;
736+ --link: #ffaa5c;
737+ --mark: #6b5a10;
738+ --active-row: #58320a;
739+ --active-row-foreground: #ffe0bd;
740+ --ok: #7ccf96;
741+ --warn: #f2b45a;
742+ --bad: #ff8a8a;
743+ --keycap-bg: #2e2520;
744+}
745+
746+
747+@layer base {
748+ /* Tailwind's preflight resets buttons to the default cursor; every clickable control gets the pointer. */
749+ button:not(:disabled),
750+ [role="button"]:not([aria-disabled="true"]),
751+ [role="menuitem"],
752+ [role="menuitemradio"],
753+ [role="option"],
754+ summary,
755+ select,
756+ label[for] {
757+ cursor: pointer;
758+ }
759+ body {
760+ @apply bg-background font-sans text-foreground antialiased;
761+ font-size: 14px;
762+ line-height: 20px;
763+ }
764+
765+ ::selection {
766+ background-color: var(--mark);
767+ color: var(--foreground);
768+ }
769+
770+ :focus-visible {
771+ outline: 2px solid var(--ring);
772+ outline-offset: 2px;
773+ }
774+
775+ @media (prefers-reduced-motion: reduce) {
776+ *,
777+ *::before,
778+ *::after {
779+ transition: none !important;
780+ animation: none !important;
781+ scroll-behavior: auto !important;
782+ }
783+ }
784+
785+ @media (forced-colors: active) {
786+ :focus-visible {
787+ outline: 2px solid CanvasText;
788+ outline-offset: 2px;
789+ }
790+
791+ ::selection {
792+ background-color: Highlight;
793+ color: HighlightText;
794+ }
795+ }
796+}
797+
798+@layer components {
799+ /* Highlighter swipe behind the active sidebar item or selected note row. */
800+ .marker {
801+ border-radius: 6px;
802+ color: var(--active-row-foreground);
803+ background-image: linear-gradient(transparent 15%, var(--active-row) 15% 85%, transparent 85%);
804+ background-repeat: no-repeat;
805+ background-size: 100% 100%;
806+ animation: marker-swipe 160ms ease-out;
807+ }
808+
809+ @keyframes marker-swipe {
810+ from {
811+ background-size: 0% 100%;
812+ }
813+ to {
814+ background-size: 100% 100%;
815+ }
816+ }
817+
818+ @media (forced-colors: active) {
819+ .marker {
820+ background: Highlight;
821+ color: HighlightText;
822+ }
823+ }
824+
825+ /* The three swatch dots in the color scheme picker. The inline style sets each dot's
826+ light and dark colors; `.dark` picks the dark one. */
827+ .scheme-dots {
828+ display: inline-flex;
829+ flex-shrink: 0;
830+ align-items: center;
831+ gap: 3px;
832+ }
833+
834+ .scheme-dot {
835+ width: 8px;
836+ height: 8px;
837+ border-radius: var(--radius-pill);
838+ background-color: var(--dot-light);
839+ box-shadow: inset 0 0 0 1px color-mix(in srgb, var(--foreground) 18%, transparent);
840+ }
841+
842+ .dark .scheme-dot {
843+ background-color: var(--dot-dark);
844+ }
845+
846+ /* The checkmark on the chosen scheme in the picker menu. */
847+ [role="menuitemradio"] .scheme-check {
848+ flex-shrink: 0;
849+ opacity: 0;
850+ }
851+
852+ [role="menuitemradio"][aria-checked="true"] .scheme-check {
853+ opacity: 1;
854+ }
855+
856+ /* A keyboard key label, such as Ctrl, K, or Esc. */
857+ .keycap {
858+ display: inline-flex;
859+ align-items: center;
860+ justify-content: center;
861+ gap: 4px;
862+ min-width: 20px;
863+ padding: 1px 5px;
864+ font-family: var(--font-mono);
865+ font-size: 11px;
866+ line-height: 16px;
867+ white-space: nowrap;
868+ color: var(--muted-foreground);
869+ background-color: var(--keycap-bg);
870+ border: 1px solid var(--border);
871+ border-bottom-width: 2px;
872+ border-radius: 4px;
873+ }
874+
875+ /* Segmented control: a track of mutually exclusive buttons. The pressed segment
876+ (aria-pressed="true") is raised on the card surface. Both controls in the sidebar
877+ footer use these, so they share height and visual language. */
878+ .segmented {
879+ display: inline-flex;
880+ flex-shrink: 0;
881+ align-items: center;
882+ gap: 2px;
883+ height: 28px;
884+ padding: 2px;
885+ border-radius: var(--radius-control);
886+ background-color: color-mix(in srgb, var(--foreground) 5%, transparent);
887+ }
888+
889+ .segment {
890+ display: inline-flex;
891+ flex-shrink: 0;
892+ align-items: center;
893+ justify-content: center;
894+ height: 24px;
895+ min-width: 24px;
896+ padding: 0 8px;
897+ border: 1px solid transparent;
898+ border-radius: 4px;
899+ font-size: 12px;
900+ font-weight: 500;
901+ line-height: 16px;
902+ color: var(--muted-foreground);
903+ background-color: transparent;
904+ cursor: pointer;
905+ transition: background-color 150ms ease-out, color 150ms ease-out, box-shadow 150ms ease-out;
906+ }
907+
908+ .segment:hover {
909+ color: var(--foreground);
910+ background-color: color-mix(in srgb, var(--foreground) 6%, transparent);
911+ }
912+
913+ .segment:active {
914+ background-color: color-mix(in srgb, var(--foreground) 12%, transparent);
915+ }
916+
917+ .segment-icon {
918+ width: 24px;
919+ padding: 0;
920+ }
921+
922+ /* Declared after the hover and active rules so the pressed segment keeps its look. */
923+ .segment[aria-pressed="true"] {
924+ color: var(--foreground);
925+ background-color: var(--card);
926+ border-color: var(--border);
927+ box-shadow: var(--shadow-xs);
928+ }
929+
930+ .segment:disabled {
931+ cursor: not-allowed;
932+ opacity: 0.5;
933+ }
934+
935+ /* One-pixel rules between rows and panes. */
936+ .hairline-t {
937+ border-top: 1px solid var(--border);
938+ }
939+ .hairline-b {
940+ border-bottom: 1px solid var(--border);
941+ }
942+ .hairline-l {
943+ border-left: 1px solid var(--border);
944+ }
945+ .hairline-r {
946+ border-right: 1px solid var(--border);
947+ }
948+
949+ /* Tiny mono labels that group a list or a pane. */
950+ .section-label {
951+ font-family: var(--font-mono);
952+ font-size: 11px;
953+ line-height: 16px;
954+ letter-spacing: 0.06em;
955+ text-transform: uppercase;
956+ color: var(--muted-foreground);
957+ }
958+}
959+
960+/* The browser's own clear button on search fields is drawn in its accent color (blue
961+ in dark mode). Redraw it as a muted cross, and drop the shortcut hint while there is
962+ text so the cross sits at the edge. */
963+input[type="search"]::-webkit-search-cancel-button {
964+ -webkit-appearance: none;
965+ appearance: none;
966+ width: 14px;
967+ height: 14px;
968+ cursor: pointer;
969+ background-color: var(--muted-foreground);
970+ -webkit-mask: url("data:image/svg+xml,%3Csvg xmlns='http://www.w3.org/2000/svg' viewBox='0 0 24 24' fill='none' stroke='black' stroke-width='2.5' stroke-linecap='round'%3E%3Cpath d='M18 6 6 18M6 6l12 12'/%3E%3C/svg%3E") center / contain no-repeat;
971+ mask: url("data:image/svg+xml,%3Csvg xmlns='http://www.w3.org/2000/svg' viewBox='0 0 24 24' fill='none' stroke='black' stroke-width='2.5' stroke-linecap='round'%3E%3Cpath d='M18 6 6 18M6 6l12 12'/%3E%3C/svg%3E") center / contain no-repeat;
972+}
973+input[type="search"]::-webkit-search-cancel-button:hover {
974+ background-color: var(--foreground);
975+}
976+#search-input:not(:placeholder-shown) {
977+ padding-right: 2rem;
978+}
979+form:has(#search-input:not(:placeholder-shown)) .search-hint {
980+ display: none;
981+}
982+
983+/* Checkbox of a search filter row: an empty box, filled with a tick when on. */
984+.filter-box {
985+ display: inline-flex;
986+ flex-shrink: 0;
987+ align-items: center;
988+ justify-content: center;
989+ width: 16px;
990+ height: 16px;
991+ border: 1px solid var(--border);
992+ border-radius: 4px;
993+}
994+.filter-box svg {
995+ display: none;
996+ width: 12px;
997+ height: 12px;
998+}
999+[aria-checked="true"] > .filter-box {
1000+ border-color: transparent;
1001+ background: var(--primary);
1002+ color: var(--primary-foreground);
1003+}
1004+[aria-checked="true"] > .filter-box svg {
1005+ display: block;
1006+}
web/build.tsadded+48 -0
@@ -0,0 +1,48 @@
1+// Bundles the editor into ../assets: editor.js (+ map), editor.css, and the Loro WASM as
2+// a separate content-hashed file (loro-<hash>.wasm). The server serves assets/ with
3+// mime_guess, so the .wasm goes out as application/wasm and can be stream-compiled.
4+import { readdirSync, unlinkSync } from "node:fs";
5+import { dirname } from "node:path";
6+import type { BunPlugin } from "bun";
7+
8+const outdir = `${import.meta.dir}/../assets`;
9+
10+// loro-crdt's "web" entry takes the WASM URL in its default init(), so nothing is inlined.
11+// Aliasing the bare specifier makes loro-prosemirror share the same Loro instance.
12+const loroWeb: BunPlugin = {
13+ name: "loro-crdt-web",
14+ setup(build) {
15+ build.onResolve({ filter: /^loro-crdt$/ }, () => ({
16+ path: Bun.resolveSync("loro-crdt/web", import.meta.dir),
17+ }));
18+ },
19+};
20+
21+// Copy the WASM out under a name that changes with its bytes; remove older copies we made.
22+const wasmSource = `${dirname(Bun.resolveSync("loro-crdt/web", import.meta.dir))}/loro_wasm_bg.wasm`;
23+const wasmBytes = new Uint8Array(await Bun.file(wasmSource).arrayBuffer());
24+const digest = new Bun.CryptoHasher("sha256").update(wasmBytes).digest("hex").slice(0, 12);
25+const wasmName = `loro-${digest}.wasm`;
26+for (const file of readdirSync(outdir)) {
27+ if (/^loro-[0-9a-f]{12}\.wasm$/.test(file) && file !== wasmName) unlinkSync(`${outdir}/${file}`);
28+}
29+await Bun.write(`${outdir}/${wasmName}`, wasmBytes);
30+console.log(`${outdir}/${wasmName} ${(wasmBytes.length / 1024).toFixed(1)} KiB`);
31+
32+for (const entry of ["src/editor.ts", "src/editor.css"]) {
33+ const result = await Bun.build({
34+ entrypoints: [`${import.meta.dir}/${entry}`],
35+ outdir,
36+ target: "browser",
37+ format: "esm",
38+ minify: true,
39+ sourcemap: "linked",
40+ define: { __LORO_WASM_NAME__: JSON.stringify(wasmName) },
41+ plugins: [loroWeb],
42+ });
43+ if (!result.success) {
44+ for (const log of result.logs) console.error(log);
45+ process.exit(1);
46+ }
47+ for (const out of result.outputs) console.log(`${out.path} ${(out.size / 1024).toFixed(1)} KiB`);
48+}
web/bun.lockadded+58 -0
@@ -0,0 +1,58 @@
1+{
2+ "lockfileVersion": 2,
3+ "configVersion": 1,
4+ "workspaces": {
5+ "": {
6+ "name": "project-note-editor",
7+ "dependencies": {
8+ "loro-crdt": "1.17.1",
9+ "loro-prosemirror": "0.4.4",
10+ "prosemirror-commands": "1.7.2",
11+ "prosemirror-dropcursor": "^1.8.4",
12+ "prosemirror-gapcursor": "^1.4.1",
13+ "prosemirror-inputrules": "^1.5.1",
14+ "prosemirror-keymap": "1.2.3",
15+ "prosemirror-model": "1.25.12",
16+ "prosemirror-schema-basic": "1.2.5",
17+ "prosemirror-schema-list": "1.5.1",
18+ "prosemirror-state": "1.4.4",
19+ "prosemirror-view": "1.42.8",
20+ },
21+ },
22+ },
23+ "packages": {
24+ "isomorphic.js": ["isomorphic.js@0.2.5", "", {}, "sha512-PIeMbHqMt4DnUP3MA/Flc0HElYjMXArsw1qwJZcm9sqR8mq3l8NYizFMty0pWwE/tzIGH3EKK5+jes5mAr85yw=="],
25+
26+ "lib0": ["lib0@0.2.119", "", { "dependencies": { "isomorphic.js": "^0.2.4" }, "bin": { "0serve": "bin/0serve.js", "0gentesthtml": "bin/gentesthtml.js", "0ecdsa-generate-keypair": "bin/0ecdsa-generate-keypair.js" } }, "sha512-vh+TiejVy8Xm+hCdnRfn9BthGNvNUZdEXltNjVZL3TzRIKP3s1lnQh8pWd/Q0wCgY0FPAGVVjFF4ZiHUV3LFgA=="],
27+
28+ "loro-crdt": ["loro-crdt@1.17.1", "", {}, "sha512-83hWRYG6eMMpPezm+yXWlOqCuUsC0BYY1MVCPW9x2zlikgkHhL7GC7Q6JFH+Hjvauyn287Q1MiwTuRW0lUOUag=="],
29+
30+ "loro-prosemirror": ["loro-prosemirror@0.4.4", "", { "dependencies": { "lib0": "^0.2.42", "prosemirror-model": "^1.18.1", "prosemirror-state": "^1.4.1", "prosemirror-view": "^1.28.0" }, "peerDependencies": { "loro-crdt": "^1.10.2" } }, "sha512-9Ttd3yHcb6Y+qxsqiS+fNMy9c9bNeimlLd7FShbVwRUBer8iosI9txWZlegzKnNjUUqIRyV15ybM6w3c2zS+Jg=="],
31+
32+ "orderedmap": ["orderedmap@2.1.1", "", {}, "sha512-TvAWxi0nDe1j/rtMcWcIj94+Ffe6n7zhow33h40SKxmsmozs6dz/e+EajymfoFcHd7sxNn8yHM8839uixMOV6g=="],
33+
34+ "prosemirror-commands": ["prosemirror-commands@1.7.2", "", { "dependencies": { "prosemirror-model": "^1.0.0", "prosemirror-state": "^1.0.0", "prosemirror-transform": "^1.10.2" } }, "sha512-q6Q6szxqdu9Xd6EcdKsqXghu5nQdZTpB4Q9yd04WRc7/jt763e/rT60Owh0L1GYY+T46o5rD+9lEN36dZS43tw=="],
35+
36+ "prosemirror-dropcursor": ["prosemirror-dropcursor@1.8.4", "", { "dependencies": { "prosemirror-state": "^1.0.0", "prosemirror-transform": "^1.1.0", "prosemirror-view": "^1.1.0" } }, "sha512-VmKxhcA6a+h5oPSYmfF1ZNeQqPbyYaIxqZsKqeYCyTlPtrjUgNaHL3P8vVaO19oqAV0zuaM/axkowZHrB1P3Tg=="],
37+
38+ "prosemirror-gapcursor": ["prosemirror-gapcursor@1.4.1", "", { "dependencies": { "prosemirror-keymap": "^1.0.0", "prosemirror-model": "^1.0.0", "prosemirror-state": "^1.0.0", "prosemirror-view": "^1.0.0" } }, "sha512-pMdYaEnjNMSwl11yjEGtgTmLkR08m/Vl+Jj443167p9eB3HVQKhYCc4gmHVDsLPODfZfjr/MmirsdyZziXbQKw=="],
39+
40+ "prosemirror-inputrules": ["prosemirror-inputrules@1.5.1", "", { "dependencies": { "prosemirror-state": "^1.0.0", "prosemirror-transform": "^1.0.0" } }, "sha512-7wj4uMjKaXWAQ1CDgxNzNtR9AlsuwzHfdFH1ygEHA2KHF2DOEaXl1CJfNPAKCg9qNEh4rum975QLaCiQPyY6Fw=="],
41+
42+ "prosemirror-keymap": ["prosemirror-keymap@1.2.3", "", { "dependencies": { "prosemirror-state": "^1.0.0", "w3c-keyname": "^2.2.0" } }, "sha512-4HucRlpiLd1IPQQXNqeo81BGtkY8Ai5smHhKW9jjPKRc2wQIxksg7Hl1tTI2IfT2B/LgX6bfYvXxEpJl7aKYKw=="],
43+
44+ "prosemirror-model": ["prosemirror-model@1.25.12", "", { "dependencies": { "orderedmap": "^2.0.0" } }, "sha512-Ue2gTmXMa7EhpLNhC7J+h4+ykD8ha12K6rrZFFKKJHBForfIStw5gJ6Zrf1mqqAa9NmpmEB4wp9bKmA4eUVjWg=="],
45+
46+ "prosemirror-schema-basic": ["prosemirror-schema-basic@1.2.5", "", { "dependencies": { "prosemirror-model": "^1.25.0" } }, "sha512-McBWhfgOfThyu3Nltbs8SOUbM4t/h0pxteibaaHd1QR4S+F1t0u7M1ETaCE6/cveFoF+2fowTIBNkJOyeZQjNg=="],
47+
48+ "prosemirror-schema-list": ["prosemirror-schema-list@1.5.1", "", { "dependencies": { "prosemirror-model": "^1.0.0", "prosemirror-state": "^1.0.0", "prosemirror-transform": "^1.7.3" } }, "sha512-927lFx/uwyQaGwJxLWCZRkjXG0p48KpMj6ueoYiu4JX05GGuGcgzAy62dfiV8eFZftgyBUvLx76RsMe20fJl+Q=="],
49+
50+ "prosemirror-state": ["prosemirror-state@1.4.4", "", { "dependencies": { "prosemirror-model": "^1.0.0", "prosemirror-transform": "^1.0.0", "prosemirror-view": "^1.27.0" } }, "sha512-6jiYHH2CIGbCfnxdHbXZ12gySFY/fz/ulZE333G6bPqIZ4F+TXo9ifiR86nAHpWnfoNjOb3o5ESi7J8Uz1jXHw=="],
51+
52+ "prosemirror-transform": ["prosemirror-transform@1.12.4", "", { "dependencies": { "prosemirror-model": "^1.21.0" } }, "sha512-2/WuPum3pn+O/Vi2vzpi8210ICUe2kIPXdLYjQ09Pv5DtT5bcKWMJhAKPBwvpPjpp5iOYUVwVEr0gOM1BY1Mgw=="],
53+
54+ "prosemirror-view": ["prosemirror-view@1.42.8", "", { "dependencies": { "prosemirror-model": "^1.25.12", "prosemirror-state": "^1.0.0", "prosemirror-transform": "^1.1.0" } }, "sha512-ftDZjCs9AjAekXmCfJRn2U3IdlRCl0Yc4tZT1/jJWCsz4DiSifEBXtWmpJpw/4f1Rg328uAUQ+u2lCJ0+AVZkw=="],
55+
56+ "w3c-keyname": ["w3c-keyname@2.2.8", "", {}, "sha512-dpojBhNsCNN7T82Tm7k26A6G9ML3NkhDsnw9n/eoxSRlVBB4CEtIQ/KTCLI2Fwf3ataSXRhYFkQi3SlnFwPvPQ=="],
57+ }
58+}
web/package.jsonadded+23 -0
@@ -0,0 +1,23 @@
1+{
2+ "name": "project-note-editor",
3+ "version": "0.1.0",
4+ "private": true,
5+ "type": "module",
6+ "scripts": {
7+ "build": "bun build.ts"
8+ },
9+ "dependencies": {
10+ "loro-crdt": "1.17.1",
11+ "loro-prosemirror": "0.4.4",
12+ "prosemirror-commands": "1.7.2",
13+ "prosemirror-dropcursor": "^1.8.4",
14+ "prosemirror-gapcursor": "^1.4.1",
15+ "prosemirror-inputrules": "^1.5.1",
16+ "prosemirror-keymap": "1.2.3",
17+ "prosemirror-model": "1.25.12",
18+ "prosemirror-schema-basic": "1.2.5",
19+ "prosemirror-schema-list": "1.5.1",
20+ "prosemirror-state": "1.4.4",
21+ "prosemirror-view": "1.42.8"
22+ }
23+}
web/src/dom.tsadded+76 -0
@@ -0,0 +1,76 @@
1+// Shared DOM helpers for the editor chrome: element builder, keycaps, tooltips and
2+// viewport positioning for floating surfaces (position: fixed, from coordsAtPos).
3+import type { EditorView } from "prosemirror-view";
4+
5+export const isMac = /Mac|iPhone|iPad|iPod/.test(navigator.platform || navigator.userAgent);
6+export const MOD = isMac ? "⌘" : "Ctrl";
7+export const SHIFT = isMac ? "⇧" : "Shift";
8+export const ALT = isMac ? "⌥" : "Alt";
9+
10+/** Creates an element with string attributes and children. Only pass trusted literals as text. */
11+export function h<K extends keyof HTMLElementTagNameMap>(
12+ tag: K,
13+ attrs: Record<string, string> = {},
14+ ...kids: (Node | string)[]
15+): HTMLElementTagNameMap[K] {
16+ const node = document.createElement(tag);
17+ for (const [name, value] of Object.entries(attrs)) node.setAttribute(name, value);
18+ node.append(...kids);
19+ return node;
20+}
21+
22+/** Mono keycap chips, e.g. keycaps("Ctrl", "K"). Decorative: screen readers get aria-keyshortcuts elsewhere. */
23+export function keycaps(...keys: string[]): HTMLSpanElement {
24+ return h(
25+ "span",
26+ { class: "keycaps", "aria-hidden": "true" },
27+ ...keys.map((key) => h("kbd", { class: "keycap" }, key)),
28+ );
29+}
30+
31+/** Tooltip shown on hover/focus of its parent button: label, keycaps, optional reason. */
32+export function tooltip(label: string, keys: string[], reason?: string): HTMLSpanElement {
33+ const children: (Node | string)[] = [h("span", { class: "tip-label" }, label)];
34+ if (keys.length) children.push(keycaps(...keys));
35+ if (reason) children.push(h("span", { class: "tip-reason" }, reason));
36+ return h("span", { class: "tip", "aria-hidden": "true", role: "presentation" }, ...children);
37+}
38+
39+export interface Box {
40+ top: number;
41+ bottom: number;
42+ left: number;
43+ right: number;
44+}
45+
46+/** Viewport box around the text between two positions (spans lines when needed). */
47+export function rangeBox(view: EditorView, from: number, to: number): Box {
48+ const a = view.coordsAtPos(from);
49+ const b = view.coordsAtPos(to);
50+ return {
51+ top: Math.min(a.top, b.top),
52+ bottom: Math.max(a.bottom, b.bottom),
53+ left: Math.min(a.left, b.left),
54+ right: Math.max(a.right, b.right),
55+ };
56+}
57+
58+const GAP = 8;
59+
60+/**
61+ * Positions a fixed element next to a box, centred horizontally and clamped to the
62+ * viewport. "above" flips below when there is no room; "below" flips above at the bottom.
63+ */
64+export function placeFloating(el: HTMLElement, box: Box, prefer: "above" | "below"): void {
65+ const width = el.offsetWidth;
66+ const height = el.offsetHeight;
67+ const above = box.top - height - GAP;
68+ const below = box.bottom + GAP;
69+ let top: number;
70+ if (prefer === "above") top = above >= GAP ? above : below;
71+ else top = below + height <= window.innerHeight - GAP ? below : above;
72+ const center = (box.left + box.right) / 2;
73+ const left = Math.min(Math.max(center - width / 2, GAP), window.innerWidth - width - GAP);
74+ el.style.top = `${Math.max(top, GAP)}px`;
75+ el.style.left = `${Math.max(left, GAP)}px`;
76+}
web/src/editing.tsadded+294 -0
@@ -0,0 +1,294 @@
1+// Editing behaviour on top of the base schema: block/mark commands, keyboard
2+// shortcuts, markdown-style input rules, cursors for gaps and drops, and the
3+// empty-note placeholder. The toolbar (toolbar.ts) drives the same commands.
4+import {
5+ Fragment,
6+ type Attrs,
7+ type Mark,
8+ type MarkType,
9+ type Node as PMNode,
10+ type NodeType,
11+ type Schema,
12+} from "prosemirror-model";
13+import { Plugin, TextSelection, type Command, type EditorState } from "prosemirror-state";
14+import { Decoration, DecorationSet, type EditorView } from "prosemirror-view";
15+import { t } from "./i18n";
16+import { keymap } from "prosemirror-keymap";
17+import { lift, setBlockType, toggleMark, wrapIn } from "prosemirror-commands";
18+import { liftListItem, wrapInList } from "prosemirror-schema-list";
19+import {
20+ InputRule,
21+ inputRules,
22+ textblockTypeInputRule,
23+ undoInputRule,
24+ wrappingInputRule,
25+} from "prosemirror-inputrules";
26+import { dropCursor } from "prosemirror-dropcursor";
27+import { gapCursor } from "prosemirror-gapcursor";
28+
29+/** True when the mark applies at the cursor (stored marks included) or across the selection. */
30+export function isMarkActive(state: EditorState, type: MarkType): boolean {
31+ const { from, to, empty, $from } = state.selection;
32+ if (empty) return !!type.isInSet(state.storedMarks || $from.marks());
33+ return state.doc.rangeHasMark(from, to, type);
34+}
35+
36+/** True when the selection's textblock is of `type` (and matches `attrs`, if given). */
37+export function isBlockActive(state: EditorState, type: NodeType, attrs?: Attrs): boolean {
38+ const parent = state.selection.$from.parent;
39+ if (parent.type !== type) return false;
40+ return !attrs || Object.keys(attrs).every((k) => parent.attrs[k] === attrs[k]);
41+}
42+
43+/** Nearest ancestor of the selection matching `match`, with its document position. */
44+export function findAncestor(
45+ state: EditorState,
46+ match: (node: PMNode) => boolean,
47+): { node: PMNode; pos: number } | null {
48+ const { $from } = state.selection;
49+ for (let d = $from.depth; d > 0; d--) {
50+ const node = $from.node(d);
51+ if (match(node)) return { node, pos: $from.before(d) };
52+ }
53+ return null;
54+}
55+
56+/**
57+ * Input rule for inline marks written with delimiters ("**x**", "*x*", "`x`").
58+ * `pattern` must end with the closing delimiter; capture group 1 is the marked text.
59+ * The delimiter length is passed explicitly so the text positions are exact.
60+ */
61+function markInputRule(pattern: RegExp, markType: MarkType, delimLength: number): InputRule {
62+ return new InputRule(pattern, (state, match, start, end) => {
63+ const content = match[1];
64+ if (!content) return null;
65+ // Input rules run before the last typed character is inserted, so the closing
66+ // delimiter is one character short in the doc. Positions come from the match start.
67+ const textStart = start + match[0].length - delimLength - content.length;
68+ const textEnd = textStart + content.length;
69+ const openStart = textStart - delimLength;
70+ const tr = state.tr;
71+ tr.delete(textEnd, end);
72+ tr.delete(openStart, textStart);
73+ tr.addMark(openStart, openStart + content.length, markType.create());
74+ tr.removeStoredMark(markType);
75+ return tr;
76+ });
77+}
78+
79+/** Range of the mark of `type` that contains `pos` within its textblock, or null. */
80+export function markRangeAt(
81+ doc: PMNode,
82+ pos: number,
83+ type: MarkType,
84+): { from: number; to: number; mark: Mark } | null {
85+ const $pos = doc.resolve(pos);
86+ if (!$pos.parent.inlineContent) return null;
87+ const start = $pos.start();
88+ let found: { from: number; to: number; mark: Mark } | null = null;
89+ $pos.parent.forEach((child, offset) => {
90+ if (found) return;
91+ const from = start + offset;
92+ const to = from + child.nodeSize;
93+ const mark = type.isInSet(child.marks);
94+ if (mark && from <= pos && pos <= to) found = { from, to, mark };
95+ });
96+ return found;
97+}
98+
99+/** Accepts plain URLs (adds https://) and http/mailto/relative links; rejects script-like schemes. */
100+export function normalizeHref(raw: string): string | null {
101+ const href = raw.trim();
102+ if (!href) return null;
103+ // Whitespace and control characters are removed before the check, so "java\tscript:" is caught too.
104+ if (/^(javascript|data|vbscript):/i.test(href.replace(/[\s\x00-\x1f]/g, ""))) return null;
105+ if (/^[a-z][a-z\d+.-]*:/i.test(href) || href.startsWith("/") || href.startsWith("#")) return href;
106+ return `https://${href}`;
107+}
108+
109+export interface Editing {
110+ /** Keymap, input rules, drop/gap cursors and placeholder. Insert before baseKeymap. */
111+ plugins: Plugin[];
112+ paragraph: Command;
113+ heading(level: number): Command;
114+ codeBlock: Command;
115+ bold: Command;
116+ italic: Command;
117+ inlineCode: Command;
118+ link: Command;
119+ bulletList: Command;
120+ orderedList: Command;
121+ blockquote: Command;
122+ horizontalRule: Command;
123+}
124+
125+export interface EditingHooks {
126+ /** Called by Mod-K and the toolbar/bubble link buttons; the floating UI opens the link popover. */
127+ requestLink(view: EditorView): void;
128+}
129+
130+export function createEditing(schema: Schema, hooks: EditingHooks): Editing {
131+ const { paragraph, heading, code_block, blockquote, horizontal_rule, bullet_list, ordered_list, list_item } =
132+ schema.nodes;
133+ const { strong, em, code, link: linkMark } = schema.marks;
134+
135+ // Toggling variants: applying the active block type again returns to a paragraph.
136+ const toParagraph = setBlockType(paragraph);
137+ const toggleBlock =
138+ (type: NodeType, attrs?: Attrs): Command =>
139+ (state, dispatch) =>
140+ isBlockActive(state, type, attrs)
141+ ? toParagraph(state, dispatch)
142+ : setBlockType(type, attrs)(state, dispatch);
143+
144+ const toggleList =
145+ (type: NodeType): Command =>
146+ (state, dispatch) => {
147+ const list = findAncestor(state, (n) => n.type === bullet_list || n.type === ordered_list);
148+ if (!list) return wrapInList(type)(state, dispatch);
149+ if (list.node.type === type) return liftListItem(list_item)(state, dispatch);
150+ // Switching between bullet and ordered: retype the existing list in place.
151+ if (dispatch) dispatch(state.tr.setNodeMarkup(list.pos, type));
152+ return true;
153+ };
154+
155+ const toggleQuote: Command = (state, dispatch) =>
156+ findAncestor(state, (n) => n.type === blockquote)
157+ ? lift(state, dispatch)
158+ : wrapIn(blockquote)(state, dispatch);
159+
160+ // Opens the link popover for a selection, or for the link the cursor is inside.
161+ const toggleLink: Command = (state, dispatch, view) => {
162+ const { $from, empty } = state.selection;
163+ const insideLink = empty && markRangeAt(state.doc, state.selection.from, linkMark) !== null;
164+ const canLink = !empty && $from.parent.inlineContent && $from.parent.type.allowsMarkType(linkMark);
165+ if (!insideLink && !canLink) return false;
166+ if (dispatch && view) hooks.requestLink(view);
167+ return true;
168+ };
169+
170+ const insertRule: Command = (state, dispatch) => {
171+ const { $from } = state.selection;
172+ if ($from.parent.type.spec.code) return false;
173+ if (!dispatch) return true;
174+ const tr = state.tr.replaceSelectionWith(horizontal_rule.create());
175+ if (!tr.selection.$from.parent.inlineContent) {
176+ // Keep a text position after a trailing rule so the user can keep typing.
177+ const pos = tr.selection.from;
178+ tr.insert(pos, paragraph.create());
179+ tr.setSelection(TextSelection.create(tr.doc, pos + 1));
180+ }
181+ dispatch(tr.scrollIntoView());
182+ return true;
183+ };
184+
185+ // "---" on its own line becomes a rule followed by an empty paragraph.
186+ const hrRule = new InputRule(/^---$/, (state, _match, start, end) => {
187+ const $start = state.doc.resolve(start);
188+ const depth = $start.depth;
189+ if (depth < 1 || $start.parent.type.spec.code) return null;
190+ const index = $start.index(depth - 1);
191+ const parent = $start.node(depth - 1);
192+ const replacement = Fragment.from([horizontal_rule.create(), paragraph.create()]);
193+ if (!parent.canReplace(index, index + 1, replacement)) return null;
194+ const before = $start.before();
195+ const tr = state.tr.replaceWith(before, $start.after(), [horizontal_rule.create(), paragraph.create()]);
196+ tr.setSelection(TextSelection.create(tr.doc, before + horizontal_rule.create().nodeSize + 1));
197+ return tr;
198+ });
199+
200+ // Ctrl/Cmd+Shift+V pastes plain text. The keydown sets a short-lived flag, and the paste
201+ // event the browser fires next reads it. Normal paste keeps basic structure and drops styling.
202+ let plainPasteUntil = 0;
203+ const paste = new Plugin({
204+ props: {
205+ transformPastedHTML(html) {
206+ return html.replace(/\s(?:style|class)\s*=\s*("[^"]*"|'[^']*')/gi, "");
207+ },
208+ handleKeyDown(_view, event) {
209+ if ((event.metaKey || event.ctrlKey) && event.shiftKey && event.key.toLowerCase() === "v") {
210+ plainPasteUntil = Date.now() + 1000;
211+ }
212+ return false;
213+ },
214+ handlePaste(view, event) {
215+ if (Date.now() > plainPasteUntil) return false;
216+ plainPasteUntil = 0;
217+ const text = event.clipboardData?.getData("text/plain");
218+ if (!text) return false;
219+ view.pasteText(text);
220+ return true;
221+ },
222+ },
223+ });
224+
225+ const keys = keymap({
226+ "Mod-Alt-0": toParagraph,
227+ "Mod-Alt-1": toggleBlock(heading, { level: 1 }),
228+ "Mod-Alt-2": toggleBlock(heading, { level: 2 }),
229+ "Mod-Alt-3": toggleBlock(heading, { level: 3 }),
230+ "Mod-Shift-8": toggleList(bullet_list),
231+ "Mod-Shift-9": toggleList(ordered_list),
232+ "Mod-k": toggleLink,
233+ "Mod-e": toggleMark(code),
234+ Backspace: undoInputRule,
235+ });
236+
237+ const rules = inputRules({
238+ rules: [
239+ textblockTypeInputRule(/^(#{1,3})\s$/, heading, (m) => ({ level: m[1].length })),
240+ textblockTypeInputRule(/^```$/, code_block),
241+ wrappingInputRule(/^\s*([-*])\s$/, bullet_list),
242+ wrappingInputRule(
243+ /^(\d+)\.\s$/,
244+ ordered_list,
245+ (m) => ({ order: Number(m[1]) }),
246+ (m, node) => node.childCount + node.attrs.order === Number(m[1]),
247+ ),
248+ wrappingInputRule(/^\s*>\s$/, blockquote),
249+ markInputRule(/\*\*([^*]+)\*\*$/, strong, 2),
250+ markInputRule(/(?:^|[^*])\*([^*]+)\*$/, em, 1),
251+ markInputRule(/`([^`]+)`$/, code, 1),
252+ hrRule,
253+ ],
254+ });
255+
256+ // Shown only while the whole note is one empty paragraph.
257+ const placeholder = new Plugin({
258+ props: {
259+ decorations(state) {
260+ const { doc } = state;
261+ const first = doc.firstChild;
262+ if (doc.childCount !== 1 || !first || first.type !== paragraph || first.content.size > 0) return null;
263+ return DecorationSet.create(doc, [
264+ Decoration.node(0, first.nodeSize, {
265+ class: "is-placeholder",
266+ "data-placeholder": t("placeholder"),
267+ }),
268+ ]);
269+ },
270+ },
271+ });
272+
273+ return {
274+ plugins: [
275+ paste,
276+ keys,
277+ rules,
278+ dropCursor({ color: "var(--primary)", width: 2 }),
279+ gapCursor(),
280+ placeholder,
281+ ],
282+ paragraph: toParagraph,
283+ heading: (level) => toggleBlock(heading, { level }),
284+ codeBlock: toggleBlock(code_block),
285+ bold: toggleMark(strong),
286+ italic: toggleMark(em),
287+ inlineCode: toggleMark(code),
288+ link: toggleLink,
289+ bulletList: toggleList(bullet_list),
290+ orderedList: toggleList(ordered_list),
291+ blockquote: toggleQuote,
292+ horizontalRule: insertRule,
293+ };
294+}
web/src/editor.cssadded+800 -0
@@ -0,0 +1,800 @@
1+@import "prosemirror-view/style/prosemirror.css";
2+@import "prosemirror-gapcursor/style/gapcursor.css";
3+
4+/*
5+ * Editor styles, tokens only ("Graphite & Highlighter", see styles.css). Light/dark is
6+ * handled by the theme variables themselves. Fallbacks are the light values.
7+ * Type: Atkinson Hyperlegible Next (UI and body), Atkinson Hyperlegible Mono (meta, keycaps, code).
8+ */
9+
10+.sr-only {
11+ position: absolute;
12+ width: 1px;
13+ height: 1px;
14+ padding: 0;
15+ margin: -1px;
16+ overflow: hidden;
17+ clip: rect(0, 0, 0, 0);
18+ white-space: nowrap;
19+ border: 0;
20+}
21+
22+/* ---- Keycaps (every visible command shows its shortcut as these) ---- */
23+
24+.keycaps {
25+ display: inline-flex;
26+ align-items: center;
27+ gap: 3px;
28+ margin-inline-start: 6px;
29+ vertical-align: middle;
30+}
31+
32+.keycap {
33+ display: inline-flex;
34+ align-items: center;
35+ justify-content: center;
36+ min-width: 18px;
37+ height: 18px;
38+ padding: 0 4px;
39+ border: 1px solid var(--border, #e3e5ea);
40+ border-bottom-width: 2px;
41+ border-radius: 6px;
42+ background: var(--keycap-bg, #ffffff);
43+ color: var(--muted-foreground, #5b6270);
44+ font-family: var(--font-mono, "Atkinson Hyperlegible Mono", ui-monospace, monospace);
45+ font-size: 11px;
46+ font-weight: 500;
47+ line-height: 1;
48+ font-variant-numeric: tabular-nums;
49+}
50+
51+/* ---- Tooltips (toolbar and bubble buttons) ---- */
52+
53+.tip {
54+ position: absolute;
55+ top: calc(100% + 6px);
56+ left: 50%;
57+ z-index: 40;
58+ display: flex;
59+ align-items: center;
60+ flex-wrap: wrap;
61+ gap: 2px;
62+ max-width: 240px;
63+ padding: 4px 6px 4px 8px;
64+ border: 1px solid var(--border, #e3e5ea);
65+ border-radius: 10px;
66+ background: var(--popover, #ffffff);
67+ color: var(--popover-foreground, #16181d);
68+ box-shadow: var(--shadow-float, 0 8px 24px rgb(0 0 0 / 0.12));
69+ font-family: var(--font-sans, "Atkinson Hyperlegible Next", sans-serif);
70+ font-size: 12px;
71+ font-weight: 500;
72+ line-height: 16px;
73+ white-space: nowrap;
74+ pointer-events: none;
75+ opacity: 0;
76+ transform: translate(-50%, -2px);
77+ transition:
78+ opacity 150ms ease-out,
79+ transform 150ms ease-out;
80+}
81+
82+.tip .keycaps {
83+ margin-inline-start: 4px;
84+}
85+
86+.tip-reason {
87+ display: none;
88+ flex-basis: 100%;
89+ color: var(--muted-foreground, #5b6270);
90+ font-weight: 400;
91+}
92+
93+.editor-toolbar-btn:disabled .tip-reason {
94+ display: block;
95+}
96+
97+.editor-toolbar-btn:hover .tip,
98+.editor-toolbar-btn:focus-visible .tip,
99+.bubble-btn:hover .tip,
100+.bubble-btn:focus-visible .tip {
101+ opacity: 1;
102+ transform: translate(-50%, 0);
103+ transition-delay: 300ms;
104+}
105+
106+.bubble .tip {
107+ top: auto;
108+ bottom: calc(100% + 6px);
109+}
110+
111+/* ---- Sync status pill (in the note header's #sync-slot) ---- */
112+
113+#sync-status {
114+ display: inline-flex;
115+ align-items: center;
116+ gap: 6px;
117+ height: 24px;
118+ padding: 0 10px 0 8px;
119+ border: 1px solid var(--border, #e3e5ea);
120+ border-radius: 999px;
121+ background: var(--card, #ffffff);
122+ color: var(--muted-foreground, #5b6270);
123+ font-family: var(--font-mono, "Atkinson Hyperlegible Mono", ui-monospace, monospace);
124+ font-size: 12px;
125+ font-weight: 400;
126+ line-height: 16px;
127+ white-space: nowrap;
128+ transition: color 150ms ease-out;
129+}
130+
131+#sync-status::before {
132+ content: "";
133+ width: 6px;
134+ height: 6px;
135+ border-radius: 50%;
136+ background: currentColor;
137+ flex: none;
138+}
139+
140+#sync-status[data-state="saved"] {
141+ color: var(--ok, #1f7a4d);
142+}
143+
144+#sync-status[data-state="saving"] {
145+ color: var(--muted-foreground, #5b6270);
146+}
147+
148+#sync-status[data-state="local"],
149+#sync-status[data-state="reconnecting"] {
150+ color: var(--warn, #9a5b00);
151+}
152+
153+/* ---- Note header: one row, the formatting toolbar sits inside it ---- */
154+
155+#note-header {
156+ container: note-header / inline-size;
157+}
158+
159+/* ---- Toolbar: compact, icons only, one line (groups drop out when the row is narrow) ---- */
160+
161+.editor-toolbar {
162+ display: flex;
163+ flex: 0 0 auto;
164+ flex-wrap: nowrap;
165+ align-items: center;
166+ gap: 2px;
167+}
168+
169+.editor-toolbar-group {
170+ display: flex;
171+ align-items: center;
172+ gap: 2px;
173+}
174+
175+.editor-toolbar-group + .editor-toolbar-group::before {
176+ content: "";
177+ width: 1px;
178+ height: 16px;
179+ margin: 0 4px;
180+ background: var(--border, #e3e5ea);
181+}
182+
183+/* Lower-priority commands leave the bar as the header narrows, so the title keeps
184+ at least 8rem. They stay reachable through the slash menu (/) and markdown shortcuts. */
185+@container note-header (max-width: 879px) {
186+ .note-crumb-notebook {
187+ display: none;
188+ }
189+}
190+
191+@container note-header (max-width: 779px) {
192+ .editor-toolbar-group[data-group="blocks"] {
193+ display: none;
194+ }
195+}
196+
197+@container note-header (max-width: 619px) {
198+ .editor-toolbar-btn[data-command="h1"],
199+ .editor-toolbar-btn[data-command="h2"],
200+ .editor-toolbar-btn[data-command="h3"] {
201+ display: none;
202+ }
203+}
204+
205+@container note-header (max-width: 559px) {
206+ #sync-status {
207+ gap: 0;
208+ padding: 0 8px;
209+ font-size: 0;
210+ }
211+}
212+
213+@container note-header (max-width: 469px) {
214+ .editor-toolbar-group[data-group="history"] {
215+ display: none;
216+ }
217+}
218+
219+@container note-header (max-width: 419px) {
220+ .editor-toolbar-btn[data-command="paragraph"],
221+ .editor-toolbar-group[data-group="headings"] {
222+ display: none;
223+ }
224+ .note-crumb {
225+ min-width: 6rem;
226+ }
227+}
228+
229+.editor-toolbar-btn {
230+ position: relative;
231+ display: inline-grid;
232+ place-items: center;
233+ width: 28px;
234+ height: 28px;
235+ margin: 0;
236+ padding: 0;
237+ border: 0;
238+ border-radius: 6px;
239+ background: transparent;
240+ color: var(--muted-foreground, #5b6270);
241+ cursor: pointer;
242+ transition:
243+ background-color 150ms ease-out,
244+ color 150ms ease-out;
245+}
246+
247+.editor-toolbar-icon {
248+ display: grid;
249+ place-items: center;
250+}
251+
252+.editor-toolbar-icon svg {
253+ display: block;
254+}
255+
256+.editor-toolbar-btn:hover:not(:disabled) {
257+ background: var(--sidebar-accent, #e3e6eb);
258+ color: var(--foreground, #16181d);
259+}
260+
261+.editor-toolbar-btn[aria-pressed="true"] {
262+ background: var(--active-row, #d9ebd3);
263+ color: var(--active-row-foreground, #1f3d22);
264+}
265+
266+.editor-toolbar-btn:disabled {
267+ opacity: 0.4;
268+ cursor: not-allowed;
269+}
270+
271+.editor-toolbar-btn:focus-visible,
272+.bubble-btn:focus-visible,
273+.btn:focus-visible,
274+.link-input:focus-visible,
275+.slash-item:focus-visible {
276+ outline: 2px solid var(--ring, #8a5a00);
277+ outline-offset: 2px;
278+}
279+
280+/* ---- Floating surfaces: bubble, link popover, slash menu ---- */
281+
282+.bubble,
283+.popover {
284+ position: fixed;
285+ z-index: 50;
286+ color: var(--popover-foreground, #16181d);
287+ background: var(--popover, #ffffff);
288+ border: 1px solid var(--border, #e3e5ea);
289+ border-radius: 10px;
290+ box-shadow: var(--shadow-float, 0 8px 24px rgb(0 0 0 / 0.12));
291+ font-family: var(--font-sans, "Atkinson Hyperlegible Next", sans-serif);
292+ font-size: 14px;
293+ line-height: 20px;
294+}
295+
296+.bubble[hidden],
297+.popover[hidden],
298+.link-view[hidden],
299+.link-edit[hidden],
300+.link-error[hidden] {
301+ display: none;
302+}
303+
304+.bubble {
305+ display: flex;
306+ align-items: center;
307+ gap: 2px;
308+ padding: 4px;
309+}
310+
311+.bubble-btn {
312+ position: relative;
313+ display: inline-grid;
314+ place-items: center;
315+ min-width: 28px;
316+ height: 28px;
317+ margin: 0;
318+ padding: 0 6px;
319+ border: 0;
320+ border-radius: 6px;
321+ background: transparent;
322+ color: var(--foreground, #16181d);
323+ font-family: var(--font-sans, "Atkinson Hyperlegible Next", sans-serif);
324+ font-size: 13px;
325+ font-weight: 700;
326+ line-height: 1;
327+ cursor: pointer;
328+ transition: background-color 150ms ease-out;
329+}
330+
331+.bubble-btn:hover:not(:disabled) {
332+ background: var(--sidebar-accent, #e3e6eb);
333+}
334+
335+.bubble-btn[aria-pressed="true"] {
336+ background: var(--active-row, #d9ebd3);
337+}
338+
339+.bubble-btn:disabled {
340+ opacity: 0.4;
341+ cursor: not-allowed;
342+}
343+
344+.bubble-btn[data-command="italic"] .bubble-glyph {
345+ font-style: italic;
346+ font-weight: 500;
347+}
348+
349+.bubble-btn[data-command="bold"] .bubble-glyph {
350+ font-weight: 800;
351+}
352+
353+.bubble-btn[data-command="code"] .bubble-glyph {
354+ font-family: var(--font-mono, "Atkinson Hyperlegible Mono", ui-monospace, monospace);
355+ font-size: 12px;
356+ font-weight: 500;
357+}
358+
359+.link-popover {
360+ width: min(360px, calc(100vw - 16px));
361+ box-sizing: border-box;
362+ padding: 10px;
363+}
364+
365+.link-row {
366+ display: flex;
367+ gap: 6px;
368+}
369+
370+.link-input {
371+ flex: 1;
372+ min-width: 0;
373+ height: 32px;
374+ padding: 0 10px;
375+ border: 1px solid var(--border, #e3e5ea);
376+ border-radius: 6px;
377+ background: var(--card, #ffffff);
378+ color: var(--foreground, #16181d);
379+ font-family: var(--font-mono, "Atkinson Hyperlegible Mono", ui-monospace, monospace);
380+ font-size: 13px;
381+}
382+
383+.link-input[aria-invalid="true"] {
384+ border-color: var(--bad, #b3261e);
385+}
386+
387+.link-input::placeholder {
388+ color: var(--muted-foreground, #5b6270);
389+}
390+
391+.link-error {
392+ margin: 6px 0 0;
393+ color: var(--bad, #b3261e);
394+ font-size: 12px;
395+ line-height: 16px;
396+}
397+
398+.link-actions {
399+ display: flex;
400+ flex-wrap: wrap;
401+ gap: 6px;
402+ margin-top: 8px;
403+}
404+
405+.link-view {
406+ display: grid;
407+ gap: 2px;
408+}
409+
410+.link-href {
411+ display: block;
412+ color: var(--link, #8a5a00);
413+ font-family: var(--font-mono, "Atkinson Hyperlegible Mono", ui-monospace, monospace);
414+ font-size: 13px;
415+ line-height: 18px;
416+ overflow-wrap: anywhere;
417+}
418+
419+.btn {
420+ display: inline-flex;
421+ align-items: center;
422+ gap: 6px;
423+ height: 28px;
424+ padding: 0 10px;
425+ border: 1px solid var(--border, #e3e5ea);
426+ border-radius: 6px;
427+ background: var(--card, #ffffff);
428+ color: var(--foreground, #16181d);
429+ font-family: var(--font-sans, "Atkinson Hyperlegible Next", sans-serif);
430+ font-size: 13px;
431+ font-weight: 500;
432+ line-height: 1;
433+ cursor: pointer;
434+ transition: background-color 150ms ease-out;
435+}
436+
437+.btn:hover:not(:disabled) {
438+ background: var(--sidebar-accent, #e3e6eb);
439+}
440+
441+.btn:disabled {
442+ opacity: 0.45;
443+ cursor: not-allowed;
444+}
445+
446+.btn-primary {
447+ border-color: transparent;
448+ background: var(--primary, #f2b600);
449+ color: var(--primary-foreground, #16181d);
450+}
451+
452+.btn-primary:hover:not(:disabled) {
453+ background: var(--primary, #f2b600);
454+ opacity: 0.9;
455+}
456+
457+.btn-primary .keycaps {
458+ margin-inline-start: 2px;
459+}
460+
461+.btn-primary .keycap {
462+ border-color: transparent;
463+ border-bottom-color: color-mix(in srgb, var(--primary-foreground, #16181d) 35%, transparent);
464+ background: transparent;
465+ color: inherit;
466+}
467+
468+.slash-menu {
469+ width: 264px;
470+ max-width: calc(100vw - 16px);
471+ box-sizing: border-box;
472+ padding: 4px;
473+}
474+
475+.slash-list {
476+ max-height: 288px;
477+ overflow-y: auto;
478+}
479+
480+.slash-item {
481+ display: flex;
482+ align-items: center;
483+ justify-content: space-between;
484+ gap: 12px;
485+ min-height: 32px;
486+ padding: 0 8px;
487+ border-radius: 6px;
488+ color: var(--foreground, #16181d);
489+ cursor: pointer;
490+}
491+
492+.slash-item[aria-selected="true"] {
493+ background: var(--active-row, #d9ebd3);
494+}
495+
496+.slash-item .keycaps {
497+ margin-inline-start: 0;
498+}
499+
500+.slash-empty {
501+ padding: 8px;
502+ color: var(--muted-foreground, #5b6270);
503+ font-size: 13px;
504+}
505+
506+.slash-footer {
507+ display: flex;
508+ flex-wrap: wrap;
509+ align-items: center;
510+ gap: 2px;
511+ margin-top: 4px;
512+ padding: 6px 8px 2px;
513+ border-top: 1px solid var(--border, #e3e5ea);
514+ color: var(--muted-foreground, #5b6270);
515+ font-family: var(--font-mono, "Atkinson Hyperlegible Mono", ui-monospace, monospace);
516+ font-size: 11px;
517+ line-height: 16px;
518+}
519+
520+.slash-footer .keycaps {
521+ margin-inline-start: 0;
522+}
523+
524+/* Note suggestions: long titles are cut with an ellipsis */
525+
526+.note-menu .slash-label {
527+ min-width: 0;
528+ overflow: hidden;
529+ text-overflow: ellipsis;
530+ white-space: nowrap;
531+}
532+
533+/* ---- Editor surface ---- */
534+
535+#editor {
536+ max-width: calc(68ch + 48px);
537+ margin: 0 auto;
538+ padding: 32px 24px 30vh;
539+ box-sizing: border-box;
540+}
541+
542+#editor .ProseMirror {
543+ min-height: 60vh;
544+ max-width: 68ch;
545+ margin: 0 auto;
546+ outline: none;
547+ color: var(--foreground, #16181d);
548+ caret-color: var(--foreground, #16181d);
549+ font-family: var(--font-sans, "Atkinson Hyperlegible Next", sans-serif);
550+ font-size: 17px;
551+ line-height: 1.65;
552+ overflow-wrap: break-word;
553+ word-wrap: break-word;
554+ font-variant-ligatures: common-ligatures;
555+}
556+
557+#editor .ProseMirror:focus,
558+#editor .ProseMirror:focus-visible {
559+ outline: none;
560+}
561+
562+#editor .ProseMirror > * + * {
563+ margin-top: 0.75em;
564+}
565+
566+#editor .ProseMirror ::selection,
567+#editor .ProseMirror::selection {
568+ background: var(--mark, #ffe08a);
569+ color: var(--foreground, #16181d);
570+}
571+
572+#editor .ProseMirror p {
573+ margin: 0;
574+}
575+
576+/* Placeholder: shown by the placeholder decoration while the note is empty. */
577+#editor .ProseMirror p.is-placeholder::before {
578+ content: attr(data-placeholder);
579+ float: left;
580+ height: 0;
581+ color: var(--muted-foreground, #5b6270);
582+ pointer-events: none;
583+}
584+
585+/* Headings: 30/36, 23/30, 19/26, all bold. */
586+#editor .ProseMirror h1,
587+#editor .ProseMirror h2,
588+#editor .ProseMirror h3 {
589+ margin: 0;
590+ color: var(--foreground, #16181d);
591+ font-weight: 700;
592+ letter-spacing: -0.01em;
593+}
594+
595+#editor .ProseMirror > * + h1,
596+#editor .ProseMirror > * + h2,
597+#editor .ProseMirror > * + h3 {
598+ margin-top: 1.4em;
599+}
600+
601+#editor .ProseMirror h1 {
602+ font-size: 30px;
603+ line-height: 36px;
604+}
605+
606+#editor .ProseMirror h2 {
607+ font-size: 23px;
608+ line-height: 30px;
609+}
610+
611+#editor .ProseMirror h3 {
612+ font-size: 19px;
613+ line-height: 26px;
614+}
615+
616+/* Lists */
617+
618+#editor .ProseMirror ul,
619+#editor .ProseMirror ol {
620+ margin: 0;
621+ padding-left: 1.6em;
622+}
623+
624+#editor .ProseMirror ul {
625+ list-style: disc;
626+}
627+
628+#editor .ProseMirror ol {
629+ list-style: decimal;
630+}
631+
632+#editor .ProseMirror ul ul {
633+ list-style: circle;
634+}
635+
636+#editor .ProseMirror ul ul ul {
637+ list-style: square;
638+}
639+
640+#editor .ProseMirror li {
641+ margin: 0.2em 0;
642+}
643+
644+#editor .ProseMirror li::marker {
645+ color: var(--muted-foreground, #5b6270);
646+}
647+
648+#editor .ProseMirror li > p + p,
649+#editor .ProseMirror li > * + ul,
650+#editor .ProseMirror li > * + ol {
651+ margin-top: 0.2em;
652+}
653+
654+/* Quote */
655+
656+#editor .ProseMirror blockquote {
657+ margin: 0;
658+ padding: 2px 0 2px 16px;
659+ border-left: 3px solid var(--border, #e3e5ea);
660+ color: var(--muted-foreground, #5b6270);
661+}
662+
663+/* Code: mono on the background token, hairline border */
664+
665+#editor .ProseMirror code {
666+ padding: 1px 5px;
667+ border: 1px solid var(--border, #e3e5ea);
668+ border-radius: 6px;
669+ background: var(--background, #f5f6f8);
670+ color: var(--foreground, #16181d);
671+ font-family: var(--font-mono, "Atkinson Hyperlegible Mono", ui-monospace, monospace);
672+ font-size: 0.88em;
673+}
674+
675+#editor .ProseMirror pre {
676+ margin: 0;
677+ padding: 12px 14px;
678+ border: 1px solid var(--border, #e3e5ea);
679+ border-radius: 10px;
680+ background: var(--background, #f5f6f8);
681+ color: var(--foreground, #16181d);
682+ font-family: var(--font-mono, "Atkinson Hyperlegible Mono", ui-monospace, monospace);
683+ font-size: 14px;
684+ line-height: 22px;
685+ overflow-x: auto;
686+ white-space: pre;
687+}
688+
689+#editor .ProseMirror pre code {
690+ padding: 0;
691+ border: 0;
692+ border-radius: 0;
693+ background: none;
694+ font-size: inherit;
695+}
696+
697+/* Marks: search-style highlight */
698+
699+#editor .ProseMirror mark {
700+ padding: 0 0.1em;
701+ border-radius: 3px;
702+ background: var(--mark, #ffe08a);
703+ color: inherit;
704+}
705+
706+/* Links: accent ink with a quiet underline */
707+
708+#editor .ProseMirror a {
709+ color: var(--link, #8a5a00);
710+ text-decoration-line: underline;
711+ text-decoration-thickness: 1px;
712+ text-decoration-color: color-mix(in srgb, var(--link, #8a5a00) 45%, transparent);
713+ text-underline-offset: 3px;
714+ cursor: pointer;
715+}
716+
717+#editor .ProseMirror a:hover {
718+ text-decoration-color: var(--link, #8a5a00);
719+}
720+
721+/* Note links (href /notes/<id>): a tinted chip, underlined only on hover */
722+
723+#editor .ProseMirror a[href^="/notes/"] {
724+ padding: 0 0.2em;
725+ border-radius: 4px;
726+ background: color-mix(in srgb, var(--link, #8a5a00) 12%, transparent);
727+ text-decoration-line: none;
728+ box-decoration-break: clone;
729+ -webkit-box-decoration-break: clone;
730+}
731+
732+#editor .ProseMirror a[href^="/notes/"]:hover {
733+ text-decoration-line: underline;
734+}
735+
736+/* Horizontal rule */
737+
738+#editor .ProseMirror hr {
739+ margin: 2em 0;
740+ border: 0;
741+ border-top: 1px solid var(--border, #e3e5ea);
742+}
743+
744+#editor .ProseMirror hr.ProseMirror-selectednode {
745+ outline: 2px solid var(--ring, #8a5a00);
746+ outline-offset: 4px;
747+ border-radius: 2px;
748+}
749+
750+/* ---- Remote cursors and selections (loro-prosemirror classes) ---- */
751+
752+.ProseMirror-loro-cursor {
753+ position: relative;
754+ margin-left: -1px;
755+ margin-right: -1px;
756+ /* border-color is set inline per user */
757+ border-left: 2px solid;
758+ word-break: normal;
759+ pointer-events: none;
760+}
761+
762+/* Name label in the user's color, mono 11px. */
763+.ProseMirror-loro-cursor > div {
764+ position: absolute;
765+ top: -1.5em;
766+ left: -2px;
767+ padding: 0 5px;
768+ border-radius: 4px 4px 4px 0;
769+ /* background-color is set inline per user */
770+ color: #ffffff;
771+ font-family: var(--font-mono, "Atkinson Hyperlegible Mono", ui-monospace, monospace);
772+ font-size: 11px;
773+ font-weight: 500;
774+ line-height: 16px;
775+ white-space: nowrap;
776+ user-select: none;
777+}
778+
779+.loro-selection {
780+ border-radius: 2px;
781+}
782+
783+@media (prefers-reduced-motion: reduce) {
784+ .editor-toolbar-btn,
785+ .bubble-btn,
786+ .btn,
787+ .tip,
788+ #sync-status {
789+ transition-duration: 0ms !important;
790+ transition-delay: 0ms !important;
791+ }
792+}
793+
794+@media (forced-colors: active) {
795+ .editor-toolbar-btn[aria-pressed="true"],
796+ .bubble-btn[aria-pressed="true"],
797+ .slash-item[aria-selected="true"] {
798+ outline: 2px solid CanvasText;
799+ }
800+}
web/src/editor.tsadded+394 -0
@@ -0,0 +1,394 @@
1+// "loro-crdt/web" is the entry build.ts bundles for every "loro-crdt" import. Its init is the
2+// default export of loro_wasm.js, the module web/index.js re-exports, so there is one WASM instance.
3+import { LoroDoc, VersionVector } from "loro-crdt/web";
4+import init from "loro-crdt/web/loro_wasm.js";
5+import {
6+ CursorEphemeralStore,
7+ LoroEphemeralCursorPlugin,
8+ LoroSyncPlugin,
9+ LoroUndoPlugin,
10+ redo,
11+ undo,
12+} from "loro-prosemirror";
13+import type { CursorUser, LoroDocType } from "loro-prosemirror";
14+import { Schema, type NodeSpec } from "prosemirror-model";
15+import { EditorState } from "prosemirror-state";
16+import { EditorView } from "prosemirror-view";
17+import { schema as basicSchema } from "prosemirror-schema-basic";
18+import {
19+ addListNodes,
20+ liftListItem,
21+ sinkListItem,
22+ splitListItem,
23+} from "prosemirror-schema-list";
24+import { keymap } from "prosemirror-keymap";
25+import { baseKeymap, toggleMark } from "prosemirror-commands";
26+import { createEditing } from "./editing";
27+import { createFloating } from "./floating";
28+import { createNoteLinks } from "./noteLinks";
29+import { createToolbar } from "./toolbar";
30+import { h } from "./dom";
31+import { t, type Key } from "./i18n";
32+
33+// Replaced at build time with the content-hashed name of the WASM file in assets/.
34+declare const __LORO_WASM_NAME__: string;
35+
36+// The WASM ships as its own file so browsers can stream-compile and cache it. It must be
37+// initialized before the first LoroDoc or ephemeral store exists.
38+await init({ module_or_path: new URL(`/${__LORO_WASM_NAME__}`, location.origin) });
39+
40+// ---- Wire protocol (must match the Rust server) ----
41+const TAG_SYNC_REQ = 0x01;
42+const TAG_UPDATE = 0x02;
43+const TAG_EPHEMERAL = 0x03;
44+
45+// ---- Schema: basic nodes/marks + lists ----
46+// Code blocks keep the fence language (```rust) so markdown round-trips.
47+const codeBlock: NodeSpec = {
48+ ...basicSchema.spec.nodes.get("code_block")!,
49+ attrs: { language: { default: null } },
50+ parseDOM: [
51+ {
52+ tag: "pre",
53+ preserveWhitespace: "full",
54+ getAttrs: (dom) => ({ language: (dom as HTMLElement).dataset.language || null }),
55+ },
56+ ],
57+ toDOM: (node) => [
58+ "pre",
59+ node.attrs.language ? { "data-language": node.attrs.language } : {},
60+ ["code", 0],
61+ ],
62+};
63+
64+const schema = new Schema({
65+ nodes: addListNodes(
66+ basicSchema.spec.nodes.update("code_block", codeBlock),
67+ "paragraph block*",
68+ "block",
69+ ),
70+ marks: basicSchema.spec.marks,
71+});
72+
73+// ---- Per-tab peer identity for cursors ----
74+function peerIdentity(): CursorUser {
75+ const key = "project-note-peer";
76+ let stored: CursorUser | null = null;
77+ try {
78+ const raw = sessionStorage.getItem(key);
79+ if (raw) stored = JSON.parse(raw) as CursorUser;
80+ } catch {
81+ stored = null;
82+ }
83+ if (!stored) {
84+ const n = 1000 + Math.floor(Math.random() * 9000);
85+ const hue = Math.floor(Math.random() * 360);
86+ stored = { name: `user-${n}`, color: `hsl(${hue} 70% 45%)` };
87+ try {
88+ sessionStorage.setItem(key, JSON.stringify(stored));
89+ } catch {
90+ // sessionStorage unavailable: identity just lasts for this load
91+ }
92+ }
93+ return stored;
94+}
95+
96+// ---- Document, presence, editor ----
97+const mount = document.getElementById("editor");
98+if (!mount) throw new Error("#editor element not found");
99+const noteId = mount.dataset.noteId ?? "";
100+const noteTitle =
101+ mount.dataset.noteTitle?.trim() ||
102+ document.querySelector<HTMLElement>("header span.truncate")?.textContent?.trim() ||
103+ "Note";
104+
105+const doc = new LoroDoc() as unknown as LoroDocType;
106+const user = peerIdentity();
107+const presence = new CursorEphemeralStore((doc as unknown as LoroDoc).peerIdStr);
108+
109+const statusEl = ensureStatusElement(mount);
110+const liveEl = ensureLiveRegion();
111+
112+// Remote selections are tinted with the peer's color instead of loro's default yellow.
113+function peerSelection(peer: string) {
114+ const all = presence.getAll() as Record<string, { user?: { color?: string } } | undefined>;
115+ const color = all[peer]?.user?.color ?? "currentColor";
116+ return {
117+ class: "loro-selection",
118+ "data-peer": peer,
119+ style: `background-color: color-mix(in srgb, ${color} 28%, transparent)`,
120+ };
121+}
122+
123+// Link commands open the floating popover; the floating UI is created right after.
124+const editing = createEditing(schema, { requestLink: (v) => floating.openLink(v) });
125+const floating = createFloating(schema, editing);
126+const toolbarPlugin = createToolbar(mount, schema, editing, { undo, redo });
127+
128+const noteLinks = createNoteLinks(schema, { currentNoteId: noteId });
129+
130+const listKeys = keymap({
131+ Enter: splitListItem(schema.nodes.list_item),
132+ Tab: sinkListItem(schema.nodes.list_item),
133+ "Shift-Tab": liftListItem(schema.nodes.list_item),
134+ "Mod-b": toggleMark(schema.marks.strong),
135+ "Mod-i": toggleMark(schema.marks.em),
136+ "Mod-`": toggleMark(schema.marks.code),
137+});
138+
139+const state = EditorState.create({
140+ schema,
141+ plugins: [
142+ LoroSyncPlugin({ doc }),
143+ LoroUndoPlugin({ doc }),
144+ keymap({
145+ "Mod-z": undo,
146+ "Mod-y": redo,
147+ "Shift-Mod-z": redo,
148+ }),
149+ ...floating.plugins,
150+ ...noteLinks.plugins,
151+ listKeys,
152+ ...editing.plugins,
153+ keymap(baseKeymap),
154+ toolbarPlugin,
155+ LoroEphemeralCursorPlugin(presence, { user, createSelection: peerSelection }),
156+ ],
157+});
158+
159+// The editor is created only after the server's state is imported. Creating it on an
160+// empty doc makes loro-prosemirror write a fresh root that competes with the real one.
161+let view: EditorView | null = null;
162+let serverVersion: VersionVector | null = null;
163+
164+function maybeCreateEditor() {
165+ if (view || !serverVersion) return;
166+ const ours = (doc as unknown as LoroDoc).oplogVersion();
167+ const cmp = serverVersion.compare(ours);
168+ if (cmp === undefined || cmp > 0) return;
169+ view = new EditorView(mount!, {
170+ state,
171+ attributes: {
172+ role: "textbox",
173+ "aria-multiline": "true",
174+ "aria-label": noteTitle,
175+ },
176+ });
177+}
178+
179+// ---- Transport ----
180+const url = `${location.protocol === "https:" ? "wss" : "ws"}://${location.host}/notes/${encodeURIComponent(noteId)}/ws`;
181+const BASE_DELAY = 500;
182+const MAX_DELAY = 5000;
183+let socket: WebSocket | null = null;
184+let retryDelay = BASE_DELAY;
185+// False until this connection has sent our offline changes. Presence refers to
186+// containers inside the doc, so it must not reach peers before those changes do.
187+let presenceReady = false;
188+
189+function frame(tag: number, payload: Uint8Array): Uint8Array<ArrayBuffer> {
190+ const out = new Uint8Array(payload.length + 1);
191+ out[0] = tag;
192+ out.set(payload, 1);
193+ return out;
194+}
195+
196+function isOpen(): boolean {
197+ return socket !== null && socket.readyState === WebSocket.OPEN;
198+}
199+
200+function send(tag: number, payload: Uint8Array) {
201+ if (isOpen()) socket!.send(frame(tag, payload));
202+}
203+
204+// ---- Sync status ----
205+// "Saving…" is shown only when local changes stay unsent for more than 1.5s. A change is
206+// confirmed sent once the socket's buffer is empty and 300ms have passed without edits.
207+type SyncState = "connecting" | "reconnecting" | "saved" | "saving" | "local";
208+const STATUS_KEY: Record<SyncState, Key> = {
209+ connecting: "statusConnecting",
210+ reconnecting: "statusReconnecting",
211+ saved: "statusSaved",
212+ saving: "statusSaving",
213+ local: "statusLocal",
214+};
215+
216+let connected = false;
217+let everConnected = false;
218+let dirty = false;
219+let savingShown = false;
220+let savingTimer: ReturnType<typeof setTimeout> | undefined;
221+let flushTimer: ReturnType<typeof setTimeout> | undefined;
222+
223+function currentSyncState(): SyncState {
224+ if (navigator.onLine === false) return "local";
225+ if (!connected) return everConnected ? "reconnecting" : "connecting";
226+ return savingShown ? "saving" : "saved";
227+}
228+
229+function renderStatus() {
230+ const syncState = currentSyncState();
231+ statusEl.dataset.state = syncState;
232+ statusEl.textContent = t(STATUS_KEY[syncState]);
233+}
234+
235+function markLocalChange() {
236+ if (!dirty) {
237+ dirty = true;
238+ clearTimeout(savingTimer);
239+ savingTimer = setTimeout(() => {
240+ if (dirty) {
241+ savingShown = true;
242+ renderStatus();
243+ }
244+ }, 1500);
245+ }
246+ clearTimeout(flushTimer);
247+ flushTimer = setTimeout(checkFlushed, 300);
248+}
249+
250+function checkFlushed() {
251+ if (!dirty) return;
252+ if (isOpen() && socket!.bufferedAmount > 0) {
253+ flushTimer = setTimeout(checkFlushed, 100);
254+ return;
255+ }
256+ dirty = false;
257+ clearTimeout(savingTimer);
258+ savingShown = false;
259+ renderStatus();
260+}
261+
262+function setConnected(value: boolean) {
263+ connected = value;
264+ if (value) everConnected = true;
265+ renderStatus();
266+}
267+
268+// The pill lives in the note header's #sync-slot (right side, next to the actions menu).
269+function ensureStatusElement(anchor: HTMLElement): HTMLElement {
270+ let el = document.getElementById("sync-status");
271+ if (!el) {
272+ el = document.createElement("span");
273+ el.id = "sync-status";
274+ const slot = document.getElementById("sync-slot");
275+ if (slot) slot.append(el);
276+ else anchor.before(el);
277+ }
278+ return el;
279+}
280+
281+// Visually hidden; only offline/online transitions are announced.
282+function ensureLiveRegion(): HTMLElement {
283+ const el = h("div", { class: "sr-only", role: "status", "aria-live": "polite" });
284+ document.body.append(el);
285+ return el;
286+}
287+
288+function announce(message: string) {
289+ liveEl.textContent = message;
290+}
291+
292+window.addEventListener("offline", () => {
293+ renderStatus();
294+ announce(t("announceOffline"));
295+});
296+window.addEventListener("online", () => {
297+ renderStatus();
298+ announce(t("announceOnline"));
299+});
300+
301+// Local doc changes: only sent while the socket is open.
302+// Offline changes are delivered by the SYNC_REQ handshake on reconnect.
303+(doc as unknown as LoroDoc).subscribeLocalUpdates((bytes: Uint8Array) => {
304+ send(TAG_UPDATE, bytes);
305+ markLocalChange();
306+});
307+
308+// Local presence changes: sent while open.
309+presence.subscribeLocalUpdates((bytes: Uint8Array) => {
310+ if (presenceReady) send(TAG_EPHEMERAL, bytes);
311+});
312+
313+function handleMessage(data: ArrayBuffer | string) {
314+ if (typeof data === "string") return;
315+ const bytes = new Uint8Array(data);
316+ if (bytes.length === 0) return;
317+ const tag = bytes[0];
318+ const payload = bytes.subarray(1);
319+ switch (tag) {
320+ case TAG_SYNC_REQ: {
321+ // Peer asks for what we have beyond its version: reply with an update.
322+ const from = VersionVector.decode(payload);
323+ const update = (doc as unknown as LoroDoc).export({ mode: "update", from });
324+ send(TAG_UPDATE, update);
325+ if (!presenceReady) {
326+ presenceReady = true;
327+ send(TAG_EPHEMERAL, presence.encodeAll());
328+ }
329+ if (!serverVersion) {
330+ serverVersion = from;
331+ maybeCreateEditor();
332+ }
333+ break;
334+ }
335+ case TAG_UPDATE:
336+ try {
337+ (doc as unknown as LoroDoc).import(payload);
338+ maybeCreateEditor();
339+ } catch (err) {
340+ console.error("failed to import update", err);
341+ }
342+ break;
343+ case TAG_EPHEMERAL:
344+ try {
345+ presence.apply(payload);
346+ } catch (err) {
347+ console.error("failed to apply presence", err);
348+ }
349+ break;
350+ default:
351+ console.warn("unknown frame tag", tag);
352+ }
353+}
354+
355+function connect() {
356+ const ws = new WebSocket(url);
357+ ws.binaryType = "arraybuffer";
358+ socket = ws;
359+
360+ ws.onopen = () => {
361+ retryDelay = BASE_DELAY;
362+ setConnected(true);
363+ // Handshake: ask the server for what we are missing.
364+ presenceReady = false;
365+ send(TAG_SYNC_REQ, (doc as unknown as LoroDoc).oplogVersion().encode());
366+ };
367+
368+ ws.onmessage = (ev: MessageEvent) => handleMessage(ev.data);
369+
370+ ws.onerror = () => {
371+ ws.close();
372+ };
373+
374+ ws.onclose = () => {
375+ if (socket === ws) socket = null;
376+ if (detached) return;
377+ setConnected(false);
378+ setTimeout(connect, retryDelay);
379+ retryDelay = Math.min(retryDelay * 2, MAX_DELAY);
380+ };
381+}
382+
383+// Live search swaps the page content without a reload; it fires `note:detach` first so
384+// this editor closes its socket instead of syncing a note that is no longer on screen.
385+let detached = false;
386+window.addEventListener("note:detach", () => {
387+ detached = true;
388+ socket?.close();
389+ view?.destroy();
390+ view = null;
391+});
392+
393+renderStatus();
394+connect();
web/src/floating.tsadded+453 -0
@@ -0,0 +1,453 @@
1+// Floating editor UI, all plain DOM on <body> and positioned from view.coordsAtPos:
2+// - selection bubble menu (formatting, shown for a non-empty text selection),
3+// - link popover (edit mode for Mod-K / buttons, view mode when a link is clicked),
4+// - slash menu (typing "/" at the start of a block or after a space).
5+// One ProseMirror plugin keeps them in sync with the editor state.
6+import type { MarkType, Schema } from "prosemirror-model";
7+import { Plugin, TextSelection, type Command, type EditorState } from "prosemirror-state";
8+import type { EditorView } from "prosemirror-view";
9+import { t } from "./i18n";
10+import { isBlockActive, isMarkActive, markRangeAt, normalizeHref, type Editing } from "./editing";
11+import { ALT, MOD, SHIFT, h, keycaps, placeFloating, rangeBox, tooltip } from "./dom";
12+import { isNoteHref } from "./noteLinks";
13+
14+interface BubbleItem {
15+ id: string;
16+ label: string;
17+ glyph: string;
18+ keys: string[];
19+ run: Command;
20+ active: (state: EditorState) => boolean;
21+}
22+
23+interface SlashItem {
24+ id: string;
25+ label: string;
26+ /** English words the filter also matches, so "h2" or "list" work in either language. */
27+ keywords: string;
28+ keys: string[];
29+ run: Command;
30+}
31+
32+export interface Floating {
33+ plugins: Plugin[];
34+ /** Opens the link popover for the selection, or for the link the cursor is in. */
35+ openLink(view: EditorView): void;
36+}
37+
38+interface LinkState {
39+ from: number;
40+ to: number;
41+ mode: "edit" | "view";
42+ /** Existing href at the range, if any. */
43+ href: string | null;
44+}
45+
46+/** Position of an open "/query" trigger and what has been typed after the slash. */
47+function slashContext(state: EditorState): { from: number; query: string } | null {
48+ const { selection } = state;
49+ if (!(selection instanceof TextSelection) || !selection.empty) return null;
50+ const $from = selection.$from;
51+ if (!$from.parent.isTextblock || $from.parent.type.spec.code) return null;
52+ const before = $from.parent.textBetween(0, $from.parentOffset, undefined, "\n");
53+ const match = /(?:^|\s)\/([^\s/]*)$/.exec(before);
54+ if (!match) return null;
55+ return { from: $from.pos - match[1].length - 1, query: match[1] };
56+}
57+
58+function hrefInRange(state: EditorState, from: number, to: number, type: MarkType): string | null {
59+ let href: string | null = null;
60+ state.doc.nodesBetween(from, to, (node) => {
61+ if (href !== null) return false;
62+ const mark = type.isInSet(node.marks);
63+ if (mark) href = String(mark.attrs.href);
64+ return href === null;
65+ });
66+ return href;
67+}
68+
69+export function createFloating(schema: Schema, editing: Editing): Floating {
70+ const { strong, em, code, link: linkMark } = schema.marks;
71+ const { heading } = schema.nodes;
72+
73+ let view: EditorView | null = null;
74+ let bubbleDismissed = false;
75+ let link: LinkState | null = null;
76+ let slashFrom: number | null = null;
77+ let slashQuery = "";
78+ let slashIndex = 0;
79+ let slashFiltered: SlashItem[] = [];
80+ let slashDismissed: number | null = null;
81+
82+ // ---- Bubble menu ----
83+ const bubbleItems: BubbleItem[] = [
84+ { id: "bold", label: t("bold"), glyph: "B", keys: [MOD, "B"], run: editing.bold, active: (s) => isMarkActive(s, strong) },
85+ { id: "italic", label: t("italic"), glyph: "I", keys: [MOD, "I"], run: editing.italic, active: (s) => isMarkActive(s, em) },
86+ { id: "code", label: t("inlineCode"), glyph: "</>", keys: [MOD, "E"], run: editing.inlineCode, active: (s) => isMarkActive(s, code) },
87+ { id: "link", label: t("link"), glyph: "Link", keys: [MOD, "K"], run: editing.link, active: (s) => isMarkActive(s, linkMark) },
88+ { id: "h1", label: t("heading1"), glyph: "H1", keys: [MOD, ALT, "1"], run: editing.heading(1), active: (s) => isBlockActive(s, heading, { level: 1 }) },
89+ { id: "h2", label: t("heading2"), glyph: "H2", keys: [MOD, ALT, "2"], run: editing.heading(2), active: (s) => isBlockActive(s, heading, { level: 2 }) },
90+ { id: "h3", label: t("heading3"), glyph: "H3", keys: [MOD, ALT, "3"], run: editing.heading(3), active: (s) => isBlockActive(s, heading, { level: 3 }) },
91+ ];
92+
93+ const bubble = h("div", { class: "bubble", role: "toolbar", "aria-label": t("bubbleLabel") });
94+ bubble.hidden = true;
95+ const bubbleButtons = bubbleItems.map((item) => {
96+ const btn = h(
97+ "button",
98+ { type: "button", class: "bubble-btn", "aria-label": item.label, "data-command": item.id },
99+ h("span", { class: "bubble-glyph", "aria-hidden": "true" }, item.glyph),
100+ tooltip(item.label, item.keys),
101+ );
102+ btn.addEventListener("click", () => {
103+ if (!view) return;
104+ item.run(view.state, view.dispatch, view);
105+ if (item.id !== "link") view.focus();
106+ });
107+ bubble.append(btn);
108+ return { btn, item };
109+ });
110+ // Keep the text selection while pressing bubble buttons.
111+ bubble.addEventListener("mousedown", (e) => e.preventDefault());
112+
113+ // ---- Link popover (edit and view panels share one element) ----
114+ const linkPop = h("div", { class: "popover link-popover", role: "dialog", "aria-label": t("linkDialog") });
115+ linkPop.hidden = true;
116+
117+ const editPanel = h("form", { class: "link-edit", novalidate: "" });
118+ const linkInput = h("input", {
119+ type: "text",
120+ class: "link-input",
121+ inputmode: "url",
122+ autocomplete: "off",
123+ autocapitalize: "off",
124+ spellcheck: "false",
125+ placeholder: "https://",
126+ "aria-label": t("linkUrl"),
127+ "aria-describedby": "link-error",
128+ });
129+ const linkError = h("p", { class: "link-error", id: "link-error", role: "alert" });
130+ linkError.hidden = true;
131+ const applyBtn = h("button", { type: "submit", class: "btn btn-primary" }, t("apply"), keycaps("↵"));
132+ const editRemove = h("button", { type: "button", class: "btn" }, t("remove"));
133+ const editOpen = h("button", { type: "button", class: "btn" }, t("open"));
134+ editPanel.append(
135+ h("div", { class: "link-row" }, linkInput, applyBtn),
136+ linkError,
137+ h("div", { class: "link-actions" }, editRemove, editOpen),
138+ );
139+
140+ // View mode is a small menu: href as its label, then Edit / Remove / Open as menu items.
141+ const viewPanel = h("div", { class: "link-view", role: "menu", "aria-label": t("linkMenu") });
142+ const linkHref = h("span", { class: "link-href" });
143+ const viewEdit = h("button", { type: "button", class: "btn", role: "menuitem" }, t("edit"));
144+ const viewRemove = h("button", { type: "button", class: "btn", role: "menuitem" }, t("remove"));
145+ const viewOpen = h("button", { type: "button", class: "btn", role: "menuitem" }, t("open"));
146+ viewPanel.append(linkHref, h("div", { class: "link-actions", role: "none" }, viewEdit, viewRemove, viewOpen));
147+
148+ linkPop.append(editPanel, viewPanel);
149+
150+ function closeLink(restoreFocus: boolean) {
151+ if (!link) return;
152+ link = null;
153+ linkPop.hidden = true;
154+ if (restoreFocus) view?.focus();
155+ }
156+
157+ function showLink(v: EditorView, from: number, to: number, mode: "edit" | "view") {
158+ closeSlash();
159+ const href = hrefInRange(v.state, from, to, linkMark);
160+ link = { from, to, mode, href };
161+ linkPop.hidden = false;
162+ editPanel.hidden = mode !== "edit";
163+ viewPanel.hidden = mode !== "view";
164+ linkError.hidden = true;
165+ linkInput.removeAttribute("aria-invalid");
166+ linkInput.value = href ?? "";
167+ linkHref.textContent = href ?? "";
168+ for (const btn of [editRemove, editOpen, viewRemove, viewOpen]) {
169+ btn.disabled = href === null;
170+ btn.title = href === null ? t("linkNeedsLink") : "";
171+ }
172+ renderFloating(v);
173+ if (mode === "edit") {
174+ linkInput.focus();
175+ linkInput.select();
176+ } else {
177+ viewEdit.focus();
178+ }
179+ }
180+
181+ function openLink(v: EditorView) {
182+ const sel = v.state.selection;
183+ const range = sel.empty ? markRangeAt(v.state.doc, sel.from, linkMark) : { from: sel.from, to: sel.to };
184+ if (!range) return;
185+ showLink(v, range.from, range.to, "edit");
186+ }
187+
188+ editPanel.addEventListener("submit", (e) => {
189+ e.preventDefault();
190+ if (!link || !view) return;
191+ const href = normalizeHref(linkInput.value);
192+ if (!href) {
193+ linkError.textContent = t("linkInvalid");
194+ linkError.hidden = false;
195+ linkInput.setAttribute("aria-invalid", "true");
196+ linkInput.focus();
197+ return;
198+ }
199+ const { from, to } = link;
200+ closeLink(false);
201+ view.dispatch(view.state.tr.removeMark(from, to, linkMark).addMark(from, to, linkMark.create({ href })));
202+ view.focus();
203+ });
204+
205+ function removeLink() {
206+ if (!link || !view) return;
207+ const { from, to } = link;
208+ closeLink(false);
209+ view.dispatch(view.state.tr.removeMark(from, to, linkMark));
210+ view.focus();
211+ }
212+
213+ function openHref() {
214+ if (!link?.href) return;
215+ // Note links open in this tab; external links keep opening in a new one.
216+ if (isNoteHref(link.href)) {
217+ location.assign(link.href);
218+ return;
219+ }
220+ window.open(link.href, "_blank", "noopener,noreferrer");
221+ }
222+
223+ editRemove.addEventListener("click", removeLink);
224+ viewRemove.addEventListener("click", removeLink);
225+ editOpen.addEventListener("click", openHref);
226+ viewOpen.addEventListener("click", openHref);
227+ viewEdit.addEventListener("click", () => {
228+ if (view && link) showLink(view, link.from, link.to, "edit");
229+ });
230+
231+ linkPop.addEventListener("keydown", (e) => {
232+ if (e.key === "Escape") {
233+ e.preventDefault();
234+ e.stopPropagation();
235+ closeLink(true);
236+ return;
237+ }
238+ // Arrow keys move between the menu items in view mode.
239+ if ((e.key === "ArrowDown" || e.key === "ArrowUp") && !viewPanel.hidden) {
240+ const items = [viewEdit, viewRemove, viewOpen].filter((b) => !b.disabled);
241+ const index = items.indexOf(document.activeElement as HTMLButtonElement);
242+ const step = e.key === "ArrowDown" ? 1 : -1;
243+ const next = items[(index + step + items.length) % items.length];
244+ if (next) {
245+ e.preventDefault();
246+ next.focus();
247+ }
248+ }
249+ });
250+
251+ // ---- Slash menu ----
252+ const slashItems: SlashItem[] = [
253+ { id: "text", label: t("paragraph"), keywords: "text paragraph p", keys: [MOD, ALT, "0"], run: editing.paragraph },
254+ { id: "h1", label: t("heading1"), keywords: "heading title h1", keys: [MOD, ALT, "1"], run: editing.heading(1) },
255+ { id: "h2", label: t("heading2"), keywords: "heading subtitle h2", keys: [MOD, ALT, "2"], run: editing.heading(2) },
256+ { id: "h3", label: t("heading3"), keywords: "heading h3", keys: [MOD, ALT, "3"], run: editing.heading(3) },
257+ { id: "bullets", label: t("bulletList"), keywords: "list ul bullet unordered", keys: [MOD, SHIFT, "8"], run: editing.bulletList },
258+ { id: "ordered", label: t("numberedList"), keywords: "list ol number ordered", keys: [MOD, SHIFT, "9"], run: editing.orderedList },
259+ { id: "quote", label: t("quote"), keywords: "blockquote quote", keys: [">"], run: editing.blockquote },
260+ { id: "codeblock", label: t("codeBlock"), keywords: "code pre fence", keys: ["```"], run: editing.codeBlock },
261+ { id: "divider", label: t("divider"), keywords: "hr rule line divider", keys: ["---"], run: editing.horizontalRule },
262+ ];
263+
264+ const slashMenu = h("div", { class: "popover slash-menu", role: "presentation" });
265+ slashMenu.hidden = true;
266+ const slashList = h("div", { class: "slash-list", role: "listbox", "aria-label": t("blockMenu") });
267+ const slashFooter = h(
268+ "div",
269+ { class: "slash-footer", "aria-hidden": "true" },
270+ keycaps("↑", "↓"),
271+ ` ${t("navigate")} `,
272+ keycaps("↵"),
273+ ` ${t("insert")} `,
274+ keycaps("Esc"),
275+ ` ${t("close")}`,
276+ );
277+ slashMenu.append(slashList, slashFooter);
278+ // Keep focus in the editor while clicking menu items.
279+ slashMenu.addEventListener("mousedown", (e) => e.preventDefault());
280+
281+ function closeSlash() {
282+ slashFrom = null;
283+ slashMenu.hidden = true;
284+ view?.dom.removeAttribute("aria-activedescendant");
285+ }
286+
287+ function renderSlash() {
288+ if (!view || slashFrom === null) return;
289+ const q = slashQuery.toLowerCase();
290+ slashFiltered = slashItems.filter(
291+ (item) => !q || item.label.toLowerCase().includes(q) || item.keywords.split(" ").some((w) => w.startsWith(q)),
292+ );
293+ if (slashIndex >= slashFiltered.length) slashIndex = 0;
294+ if (slashFiltered.length === 0) {
295+ slashList.replaceChildren(h("div", { class: "slash-empty", role: "presentation" }, t("noMatches")));
296+ view.dom.removeAttribute("aria-activedescendant");
297+ return;
298+ }
299+ slashList.replaceChildren(
300+ ...slashFiltered.map((item, i) => {
301+ const el = h(
302+ "div",
303+ { class: "slash-item", role: "option", id: `slash-opt-${item.id}`, "aria-selected": String(i === slashIndex) },
304+ h("span", { class: "slash-label" }, item.label),
305+ keycaps(...item.keys),
306+ );
307+ el.addEventListener("click", () => applySlash(item));
308+ return el;
309+ }),
310+ );
311+ const active = slashFiltered[slashIndex];
312+ view.dom.setAttribute("aria-activedescendant", `slash-opt-${active.id}`);
313+ slashList.querySelector<HTMLElement>(`#slash-opt-${active.id}`)?.scrollIntoView({ block: "nearest" });
314+ }
315+
316+ function applySlash(item: SlashItem) {
317+ const v = view;
318+ if (!v || slashFrom === null) return;
319+ const from = slashFrom;
320+ const to = v.state.selection.from;
321+ closeSlash();
322+ v.dispatch(v.state.tr.delete(from, to));
323+ item.run(v.state, v.dispatch, v);
324+ v.focus();
325+ }
326+
327+ /** Opens, filters or closes the slash menu from the current selection. */
328+ function syncSlash(v: EditorView) {
329+ const ctx = slashContext(v.state);
330+ if (!ctx) {
331+ slashDismissed = null;
332+ closeSlash();
333+ return;
334+ }
335+ if (ctx.from === slashDismissed || link) {
336+ closeSlash();
337+ return;
338+ }
339+ if (ctx.from !== slashFrom || ctx.query !== slashQuery) slashIndex = 0;
340+ slashFrom = ctx.from;
341+ slashQuery = ctx.query;
342+ slashMenu.hidden = false;
343+ renderSlash();
344+ }
345+
346+ // ---- Positioning and visibility ----
347+ function bubbleVisible(v: EditorView): boolean {
348+ const sel = v.state.selection;
349+ return sel instanceof TextSelection && !sel.empty && !v.composing && !bubbleDismissed && link === null;
350+ }
351+
352+ function renderFloating(v: EditorView) {
353+ view = v;
354+ const state = v.state;
355+ const show = bubbleVisible(v);
356+ bubble.hidden = !show;
357+ if (show) {
358+ for (const { btn, item } of bubbleButtons) {
359+ const on = item.active(state);
360+ btn.dataset.active = String(on);
361+ btn.setAttribute("aria-pressed", String(on));
362+ btn.disabled = !item.run(state);
363+ }
364+ placeFloating(bubble, rangeBox(v, state.selection.from, state.selection.to), "above");
365+ }
366+ if (link) {
367+ placeFloating(linkPop, rangeBox(v, link.from, link.to), "above");
368+ }
369+ if (slashFrom !== null && !slashMenu.hidden) {
370+ placeFloating(slashMenu, rangeBox(v, slashFrom, state.selection.from), "below");
371+ }
372+ }
373+
374+ // ---- Keyboard and mouse ----
375+ const plugin = new Plugin({
376+ props: {
377+ handleKeyDown(v, e) {
378+ if (slashFrom !== null) {
379+ const n = slashFiltered.length;
380+ if (e.key === "ArrowDown" && n) {
381+ slashIndex = (slashIndex + 1) % n;
382+ renderSlash();
383+ return true;
384+ }
385+ if (e.key === "ArrowUp" && n) {
386+ slashIndex = (slashIndex - 1 + n) % n;
387+ renderSlash();
388+ return true;
389+ }
390+ if (e.key === "Enter" && n) {
391+ applySlash(slashFiltered[slashIndex]);
392+ return true;
393+ }
394+ if (e.key === "Escape") {
395+ slashDismissed = slashFrom;
396+ closeSlash();
397+ return true;
398+ }
399+ }
400+ if (e.key === "Escape" && bubbleVisible(v)) {
401+ bubbleDismissed = true;
402+ renderFloating(v);
403+ return true;
404+ }
405+ return false;
406+ },
407+ handleClick(v, pos, event) {
408+ const target = event.target as Element | null;
409+ const anchor = target?.closest?.("a");
410+ if (!anchor) return false;
411+ // Ctrl/Cmd+click navigates to a note (noteLinks.ts), so no popover opens for it.
412+ if ((event.ctrlKey || event.metaKey) && isNoteHref(anchor.getAttribute("href"))) return false;
413+ const range = markRangeAt(v.state.doc, pos, linkMark);
414+ if (range) showLink(v, range.from, range.to, "view");
415+ return false;
416+ },
417+ },
418+ view(v) {
419+ view = v;
420+ document.body.append(bubble, linkPop, slashMenu);
421+ const onViewport = () => {
422+ if (view) renderFloating(view);
423+ };
424+ const onOutsideDown = (e: MouseEvent) => {
425+ if (link && !linkPop.contains(e.target as Node)) closeLink(false);
426+ };
427+ window.addEventListener("scroll", onViewport, { capture: true, passive: true });
428+ window.addEventListener("resize", onViewport);
429+ document.addEventListener("mousedown", onOutsideDown, true);
430+ renderFloating(v);
431+ return {
432+ update(u, prev) {
433+ if (!prev.selection.eq(u.state.selection)) bubbleDismissed = false;
434+ // A popover refers to a fixed range; remote or local edits invalidate it.
435+ if (link && u.state.doc !== prev.doc) closeLink(false);
436+ syncSlash(u);
437+ renderFloating(u);
438+ },
439+ destroy() {
440+ window.removeEventListener("scroll", onViewport, { capture: true });
441+ window.removeEventListener("resize", onViewport);
442+ document.removeEventListener("mousedown", onOutsideDown, true);
443+ bubble.remove();
444+ linkPop.remove();
445+ slashMenu.remove();
446+ view = null;
447+ },
448+ };
449+ },
450+ });
451+
452+ return { plugins: [plugin], openLink };
453+}
web/src/i18n.tsadded+109 -0
@@ -0,0 +1,109 @@
1+// Editor UI strings. The language comes from <html lang>; anything but Turkish uses English.
2+
3+const en = {
4+ placeholder: "Start writing…",
5+ toolbarLabel: "Formatting",
6+ bubbleLabel: "Text formatting",
7+ blockMenu: "Insert block",
8+ noMatches: "No matches",
9+ navigate: "navigate",
10+ insert: "insert",
11+ close: "close",
12+ unavailable: "Not available here",
13+ undo: "Undo",
14+ redo: "Redo",
15+ paragraph: "Paragraph",
16+ heading1: "Heading 1",
17+ heading2: "Heading 2",
18+ heading3: "Heading 3",
19+ bold: "Bold",
20+ italic: "Italic",
21+ inlineCode: "Inline code",
22+ link: "Link",
23+ bulletList: "Bullet list",
24+ numberedList: "Numbered list",
25+ quote: "Quote",
26+ codeBlock: "Code block",
27+ divider: "Divider",
28+ text: "Text",
29+ linkDialog: "Link",
30+ linkMenu: "Link options",
31+ linkUrl: "Link URL",
32+ linkInvalid: "Enter a valid link, such as example.com",
33+ linkNeedsLink: "Add a link first",
34+ apply: "Apply",
35+ remove: "Remove",
36+ open: "Open",
37+ edit: "Edit",
38+ statusSaved: "Saved",
39+ statusSaving: "Saving…",
40+ statusLocal: "Saved on this device",
41+ statusReconnecting: "Reconnecting…",
42+ statusConnecting: "Connecting…",
43+ announceOffline: "You are offline. Changes stay on this device.",
44+ announceOnline: "Back online.",
45+ pasteAsText: "Paste as plain text",
46+ noteMenu: "Link to a note",
47+ createNote: "Create note “{q}”",
48+ noNotesFound: "No notes found",
49+ untitled: "Untitled",
50+} as const;
51+
52+export type Key = keyof typeof en;
53+
54+const tr: Record<Key, string> = {
55+ placeholder: "Yazmaya başla…",
56+ toolbarLabel: "Biçimlendirme",
57+ bubbleLabel: "Metin biçimlendirme",
58+ blockMenu: "Blok ekle",
59+ noMatches: "Eşleşme yok",
60+ navigate: "gezin",
61+ insert: "ekle",
62+ close: "kapat",
63+ unavailable: "Bu alanda kullanılamaz",
64+ undo: "Geri al",
65+ redo: "Yinele",
66+ paragraph: "Metin",
67+ heading1: "Başlık 1",
68+ heading2: "Başlık 2",
69+ heading3: "Başlık 3",
70+ bold: "Kalın",
71+ italic: "İtalik",
72+ inlineCode: "Kod",
73+ link: "Bağlantı",
74+ bulletList: "Madde listesi",
75+ numberedList: "Numaralı liste",
76+ quote: "Alıntı",
77+ codeBlock: "Kod bloğu",
78+ divider: "Ayırıcı",
79+ text: "Metin",
80+ linkDialog: "Bağlantı",
81+ linkMenu: "Bağlantı seçenekleri",
82+ linkUrl: "Bağlantı adresi",
83+ linkInvalid: "Geçerli bir bağlantı girin, ör. example.com",
84+ linkNeedsLink: "Önce bir bağlantı ekleyin",
85+ apply: "Uygula",
86+ remove: "Kaldır",
87+ open: "Aç",
88+ edit: "Düzenle",
89+ statusSaved: "Kaydedildi",
90+ statusSaving: "Kaydediliyor…",
91+ statusLocal: "Bu cihazda kaydedildi",
92+ statusReconnecting: "Yeniden bağlanıyor…",
93+ statusConnecting: "Bağlanıyor…",
94+ announceOffline: "Çevrimdışısınız. Değişiklikler bu cihazda kalır.",
95+ announceOnline: "Yeniden çevrimiçisiniz.",
96+ pasteAsText: "Düz metin olarak yapıştır",
97+ noteMenu: "Nota bağlantısı",
98+ createNote: "“{q}” notunu oluştur",
99+ noNotesFound: "Not bulunamadı",
100+ untitled: "Adsız",
101+};
102+
103+const lang: "en" | "tr" = (document.documentElement.lang || "en").toLowerCase().startsWith("tr") ? "tr" : "en";
104+
105+/** Looks up a UI string; `{name}` placeholders are filled from `vars`. */
106+export function t(key: Key, vars?: Record<string, string>): string {
107+ const text: string = lang === "tr" ? tr[key] : en[key];
108+ return vars ? text.replace(/\{(\w+)\}/g, (match, name: string) => vars[name] ?? match) : text;
109+}
web/src/noteLinks.tsadded+334 -0
@@ -0,0 +1,334 @@
1+// Note-to-note links. Typing "[[" opens a suggestion menu of note titles. Picking one (or
2+// "Create note") replaces "[[query" with the title as a link mark whose href is /notes/<id>.
3+// The menu reuses the slash menu's classes and keyboard model so it looks and behaves the same.
4+import type { MarkType, Schema } from "prosemirror-model";
5+import { Plugin, TextSelection, type EditorState } from "prosemirror-state";
6+import type { EditorView } from "prosemirror-view";
7+import { t } from "./i18n";
8+import { h, keycaps, placeFloating, rangeBox } from "./dom";
9+
10+interface NoteHit {
11+ id: string;
12+ title: string;
13+}
14+
15+type Item = { kind: "note"; hit: NoteHit } | { kind: "create"; title: string };
16+
17+/** "[[" trigger: `from` is the position of the first bracket, `query` the text after it. */
18+interface Trigger {
19+ from: number;
20+ query: string;
21+}
22+
23+const SEARCH_DEBOUNCE_MS = 120;
24+
25+export interface NoteLinks {
26+ plugins: Plugin[];
27+}
28+
29+export function isNoteHref(href: string | null | undefined): boolean {
30+ return !!href && href.startsWith("/notes/");
31+}
32+
33+/** The "[[query" right before the cursor, when the cursor is in a textblock outside code. */
34+function triggerAt(state: EditorState, code: MarkType): Trigger | null {
35+ const { selection } = state;
36+ if (!(selection instanceof TextSelection) || !selection.empty) return null;
37+ const $from = selection.$from;
38+ if (!$from.parent.isTextblock || $from.parent.type.spec.code) return null;
39+ if (code.isInSet(state.storedMarks || $from.marks())) return null;
40+ const before = $from.parent.textBetween(0, $from.parentOffset, undefined, "\n");
41+ // A closing "]]" or a stray bracket ends the match, so the menu closes on its own.
42+ const match = /\[\[([^\[\]\n]*)$/.exec(before);
43+ if (!match) return null;
44+ return { from: $from.pos - match[0].length, query: match[1] };
45+}
46+
47+function parseHits(data: unknown): NoteHit[] {
48+ if (!Array.isArray(data)) return [];
49+ return data.filter(
50+ (x): x is NoteHit =>
51+ typeof x === "object" && x !== null && typeof x.id === "string" && typeof x.title === "string",
52+ );
53+}
54+
55+async function createNote(title: string): Promise<string> {
56+ const res = await fetch("/notes/quick", { method: "POST", body: new URLSearchParams({ title }) });
57+ if (!res.ok) throw new Error(`quick ${res.status}`);
58+ const id = (await res.text()).trim();
59+ if (!id) throw new Error("empty note id");
60+ return id;
61+}
62+
63+export function createNoteLinks(schema: Schema, opts: { currentNoteId: string }): NoteLinks {
64+ const linkMark = schema.marks.link;
65+ const codeMark = schema.marks.code;
66+ const currentId = opts.currentNoteId;
67+
68+ let view: EditorView | null = null;
69+ let active: Trigger | null = null;
70+ let dismissedFrom: number | null = null;
71+ let results: NoteHit[] = [];
72+ let loaded = false;
73+ let items: Item[] = [];
74+ let index = 0;
75+ let busy = false;
76+ let fetchTimer: ReturnType<typeof setTimeout> | undefined;
77+ let controller: AbortController | null = null;
78+
79+ const menu = h("div", { class: "popover slash-menu note-menu", role: "presentation" });
80+ menu.hidden = true;
81+ const list = h("div", { class: "slash-list", role: "listbox", "aria-label": t("noteMenu") });
82+ const footer = h(
83+ "div",
84+ { class: "slash-footer", "aria-hidden": "true" },
85+ keycaps("↑", "↓"),
86+ ` ${t("navigate")} `,
87+ keycaps("↵"),
88+ ` ${t("insert")} `,
89+ keycaps("Esc"),
90+ ` ${t("close")}`,
91+ );
92+ menu.append(list, footer);
93+ // Keep focus in the editor while clicking menu items.
94+ menu.addEventListener("mousedown", (e) => e.preventDefault());
95+
96+ function itemText(item: Item): string {
97+ if (item.kind === "create") return item.title;
98+ return item.hit.title.trim() || t("untitled");
99+ }
100+
101+ function itemLabel(item: Item): string {
102+ return item.kind === "create" ? t("createNote", { q: item.title }) : itemText(item);
103+ }
104+
105+ function buildItems(query: string): Item[] {
106+ const list: Item[] = results.map((hit): Item => ({ kind: "note", hit }));
107+ const q = query.trim();
108+ const exact = results.some((hit) => hit.title.trim().toLowerCase() === q.toLowerCase());
109+ if (q && !exact) list.push({ kind: "create", title: q });
110+ return list;
111+ }
112+
113+ function abortFetch() {
114+ clearTimeout(fetchTimer);
115+ controller?.abort();
116+ controller = null;
117+ }
118+
119+ function close() {
120+ abortFetch();
121+ active = null;
122+ items = [];
123+ results = [];
124+ loaded = false;
125+ index = 0;
126+ menu.hidden = true;
127+ view?.dom.removeAttribute("aria-activedescendant");
128+ }
129+
130+ async function search(query: string) {
131+ const ctrl = new AbortController();
132+ controller = ctrl;
133+ try {
134+ const res = await fetch(`/notes/titles.json?q=${encodeURIComponent(query)}`, {
135+ signal: ctrl.signal,
136+ headers: { accept: "application/json" },
137+ });
138+ if (!res.ok) throw new Error(`titles ${res.status}`);
139+ const data: unknown = await res.json();
140+ if (ctrl.signal.aborted) return;
141+ results = parseHits(data).filter((hit) => hit.id !== currentId);
142+ } catch (err) {
143+ if (ctrl.signal.aborted) return;
144+ console.error("note search failed", err);
145+ results = [];
146+ }
147+ if (controller === ctrl) controller = null;
148+ loaded = true;
149+ renderList();
150+ }
151+
152+ function scheduleSearch(query: string) {
153+ abortFetch();
154+ loaded = false;
155+ fetchTimer = setTimeout(() => void search(query), SEARCH_DEBOUNCE_MS);
156+ }
157+
158+ function markActive() {
159+ if (!view) return;
160+ const rows = list.querySelectorAll<HTMLElement>(".slash-item");
161+ rows.forEach((row, i) => row.setAttribute("aria-selected", String(i === index)));
162+ const row = rows[index];
163+ if (row) {
164+ view.dom.setAttribute("aria-activedescendant", row.id);
165+ row.scrollIntoView({ block: "nearest" });
166+ }
167+ }
168+
169+ function setIndex(i: number) {
170+ index = i;
171+ markActive();
172+ }
173+
174+ function renderList() {
175+ if (!view || !active) return;
176+ items = buildItems(active.query);
177+ if (index >= items.length) index = 0;
178+ if (items.length === 0) {
179+ // Only shown once the search for this query has answered; an empty query with no notes lands here.
180+ list.replaceChildren(
181+ ...(loaded ? [h("div", { class: "slash-empty", role: "presentation" }, t("noNotesFound"))] : []),
182+ );
183+ view.dom.removeAttribute("aria-activedescendant");
184+ return;
185+ }
186+ list.replaceChildren(
187+ ...items.map((item, i) => {
188+ const el = h(
189+ "div",
190+ { class: "slash-item", role: "option", id: `note-opt-${i}`, "aria-selected": String(i === index) },
191+ h("span", { class: "slash-label" }, itemLabel(item)),
192+ );
193+ el.addEventListener("mouseenter", () => setIndex(i));
194+ el.addEventListener("click", () => pick(item));
195+ return el;
196+ }),
197+ );
198+ markActive();
199+ }
200+
201+ function place(v: EditorView) {
202+ if (!active) return;
203+ placeFloating(menu, rangeBox(v, active.from, v.state.selection.from), "below");
204+ }
205+
206+ /** Replaces [from, to) with the link text, a plain space, and the cursor after it. One transaction. */
207+ function insertLink(v: EditorView, from: number, to: number, text: string, id: string) {
208+ const tr = v.state.tr.replaceWith(from, to, schema.text(text, [linkMark.create({ href: `/notes/${id}` })]));
209+ const end = from + text.length;
210+ tr.insert(end, schema.text(" "));
211+ tr.setSelection(TextSelection.create(tr.doc, end + 1));
212+ tr.setStoredMarks([]);
213+ v.dispatch(tr.scrollIntoView());
214+ v.focus();
215+ }
216+
217+ async function createAndInsert(v: EditorView, from: number, to: number, title: string) {
218+ // The range as it reads now; if the user edits it while the request runs, nothing is inserted.
219+ const before = v.state.doc.textBetween(from, to);
220+ busy = true;
221+ let id: string;
222+ try {
223+ id = await createNote(title);
224+ } catch (err) {
225+ console.error("note create failed", err);
226+ return;
227+ } finally {
228+ busy = false;
229+ }
230+ const cur = view;
231+ if (!cur) return;
232+ const sel = cur.state.selection;
233+ if (!sel.empty || sel.from !== to || cur.state.doc.textBetween(from, to) !== before) return;
234+ insertLink(cur, from, to, title, id);
235+ }
236+
237+ function pick(item: Item) {
238+ const v = view;
239+ if (!v || !active || busy) return;
240+ const { from } = active;
241+ const to = v.state.selection.from;
242+ if (item.kind === "note") {
243+ insertLink(v, from, to, itemText(item), item.hit.id);
244+ return;
245+ }
246+ void createAndInsert(v, from, to, item.title);
247+ }
248+
249+ /** Opens, refetches or closes the menu from the current selection. */
250+ function sync(v: EditorView) {
251+ view = v;
252+ const trig = triggerAt(v.state, codeMark);
253+ if (!trig) {
254+ dismissedFrom = null;
255+ close();
256+ return;
257+ }
258+ if (trig.from === dismissedFrom) {
259+ close();
260+ return;
261+ }
262+ const changed = !active || trig.from !== active.from || trig.query !== active.query;
263+ active = trig;
264+ if (changed) {
265+ index = 0;
266+ scheduleSearch(trig.query);
267+ }
268+ menu.hidden = false;
269+ if (changed) renderList();
270+ place(v);
271+ }
272+
273+ const plugin = new Plugin({
274+ props: {
275+ handleKeyDown(v, e) {
276+ if (!active) return false;
277+ const n = items.length;
278+ if (e.key === "Escape") {
279+ dismissedFrom = active.from;
280+ close();
281+ return true;
282+ }
283+ if (e.key === "ArrowDown" && n) {
284+ setIndex((index + 1) % n);
285+ return true;
286+ }
287+ if (e.key === "ArrowUp" && n) {
288+ setIndex((index - 1 + n) % n);
289+ return true;
290+ }
291+ if ((e.key === "Enter" || e.key === "Tab") && n) {
292+ if (!busy) pick(items[index]);
293+ return true;
294+ }
295+ return false;
296+ },
297+ // Ctrl/Cmd+click on a note link opens the note in this tab.
298+ handleDOMEvents: {
299+ click(_view, event) {
300+ if (!(event.ctrlKey || event.metaKey)) return false;
301+ const anchor = (event.target as Element | null)?.closest?.("a");
302+ const href = anchor?.getAttribute("href");
303+ if (!href || !isNoteHref(href)) return false;
304+ event.preventDefault();
305+ location.assign(href);
306+ return true;
307+ },
308+ },
309+ },
310+ view(v) {
311+ view = v;
312+ document.body.append(menu);
313+ const onViewport = () => {
314+ if (view) place(view);
315+ };
316+ window.addEventListener("scroll", onViewport, { capture: true, passive: true });
317+ window.addEventListener("resize", onViewport);
318+ return {
319+ update(u) {
320+ sync(u);
321+ },
322+ destroy() {
323+ window.removeEventListener("scroll", onViewport, { capture: true });
324+ window.removeEventListener("resize", onViewport);
325+ abortFetch();
326+ menu.remove();
327+ view = null;
328+ },
329+ };
330+ },
331+ });
332+
333+ return { plugins: [plugin] };
334+}
web/src/toolbar.tsadded+279 -0
@@ -0,0 +1,279 @@
1+// Formatting toolbar: plain DOM, rendered once. A ProseMirror plugin view keeps the
2+// active/disabled state of every button in sync with the editor. Icons only, with
3+// keycap tooltips; roving tabindex so the bar is one Tab stop.
4+import type { Schema } from "prosemirror-model";
5+import { Plugin, type Command, type EditorState } from "prosemirror-state";
6+import type { EditorView } from "prosemirror-view";
7+import { findAncestor, isBlockActive, isMarkActive, type Editing } from "./editing";
8+import { t } from "./i18n";
9+import { ALT, MOD, SHIFT, h, tooltip } from "./dom";
10+
11+
12+// Lucide-style glyphs (24x24, stroke based). Static strings, safe for innerHTML.
13+const ICONS = {
14+ undo: '<path d="M9 14 4 9l5-5"/><path d="M4 9h10.5a5.5 5.5 0 0 1 0 11H11"/>',
15+ redo: '<path d="m15 14 5-5-5-5"/><path d="M20 9H9.5a5.5 5.5 0 0 0 0 11H13"/>',
16+ paragraph: '<path d="M13 4v16"/><path d="M17 4v16"/><path d="M19 4H9.5a4.5 4.5 0 0 0 0 9H13"/>',
17+ h1: '<path d="M4 12h8"/><path d="M4 18V6"/><path d="M12 18V6"/><path d="m17 12 3-2v8"/>',
18+ 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"/>',
19+ 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"/>',
20+ 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"/>',
21+ 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"/>',
22+ code: '<polyline points="16 18 22 12 16 6"/><polyline points="8 6 2 12 8 18"/>',
23+ 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"/>',
24+ bullets:
25+ '<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"/>',
26+ ordered:
27+ '<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"/>',
28+ quote: '<path d="M17 6H3"/><path d="M21 12H8"/><path d="M21 18H8"/><path d="M3 12v6"/>',
29+ 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"/>',
30+ rule: '<line x1="5" x2="19" y1="12" y2="12"/>',
31+} as const;
32+
33+interface Item {
34+ id: string;
35+ label: string;
36+ keys: string[];
37+ icon: string;
38+ run: Command;
39+ /** Present for toggles: drives aria-pressed and the active look. */
40+ isActive?: (state: EditorState) => boolean;
41+}
42+
43+type Entry = Item | "|";
44+
45+function buildItems(schema: Schema, editing: Editing, history: { undo: Command; redo: Command }): Entry[] {
46+ const { paragraph, heading, code_block, blockquote, bullet_list, ordered_list } = schema.nodes;
47+ const { strong, em, code, link } = schema.marks;
48+ const headingItem = (level: 1 | 2 | 3): Item => ({
49+ id: `h${level}`,
50+ label: t(`heading${level}` as "heading1"),
51+ keys: [MOD, ALT, String(level)],
52+ icon: level === 1 ? ICONS.h1 : level === 2 ? ICONS.h2 : ICONS.h3,
53+ run: editing.heading(level),
54+ isActive: (s) => isBlockActive(s, heading, { level }),
55+ });
56+ const inList = (type: typeof bullet_list) => (s: EditorState) => findAncestor(s, (n) => n.type === type) !== null;
57+
58+ return [
59+ { id: "undo", label: t("undo"), keys: [MOD, "Z"], icon: ICONS.undo, run: history.undo },
60+ { id: "redo", label: t("redo"), keys: [MOD, SHIFT, "Z"], icon: ICONS.redo, run: history.redo },
61+ "|",
62+ {
63+ id: "paragraph",
64+ label: t("paragraph"),
65+ keys: [MOD, ALT, "0"],
66+ icon: ICONS.paragraph,
67+ run: editing.paragraph,
68+ isActive: (s) => isBlockActive(s, paragraph),
69+ },
70+ headingItem(1),
71+ headingItem(2),
72+ headingItem(3),
73+ "|",
74+ {
75+ id: "bold",
76+ label: t("bold"),
77+ keys: [MOD, "B"],
78+ icon: ICONS.bold,
79+ run: editing.bold,
80+ isActive: (s) => isMarkActive(s, strong),
81+ },
82+ {
83+ id: "italic",
84+ label: t("italic"),
85+ keys: [MOD, "I"],
86+ icon: ICONS.italic,
87+ run: editing.italic,
88+ isActive: (s) => isMarkActive(s, em),
89+ },
90+ {
91+ id: "code",
92+ label: t("inlineCode"),
93+ keys: [MOD, "E"],
94+ icon: ICONS.code,
95+ run: editing.inlineCode,
96+ isActive: (s) => isMarkActive(s, code),
97+ },
98+ {
99+ id: "link",
100+ label: t("link"),
101+ keys: [MOD, "K"],
102+ icon: ICONS.link,
103+ run: editing.link,
104+ isActive: (s) => isMarkActive(s, link),
105+ },
106+ "|",
107+ {
108+ id: "bullets",
109+ label: t("bulletList"),
110+ keys: [MOD, SHIFT, "8"],
111+ icon: ICONS.bullets,
112+ run: editing.bulletList,
113+ isActive: inList(bullet_list),
114+ },
115+ {
116+ id: "ordered",
117+ label: t("numberedList"),
118+ keys: [MOD, SHIFT, "9"],
119+ icon: ICONS.ordered,
120+ run: editing.orderedList,
121+ isActive: inList(ordered_list),
122+ },
123+ {
124+ id: "quote",
125+ label: t("quote"),
126+ keys: [">"],
127+ icon: ICONS.quote,
128+ run: editing.blockquote,
129+ isActive: (s) => findAncestor(s, (n) => n.type === blockquote) !== null,
130+ },
131+ {
132+ id: "codeblock",
133+ label: t("codeBlock"),
134+ keys: ["```"],
135+ icon: ICONS.codeBlock,
136+ run: editing.codeBlock,
137+ isActive: (s) => isBlockActive(s, code_block),
138+ },
139+ {
140+ id: "rule",
141+ label: t("divider"),
142+ keys: ["---"],
143+ icon: ICONS.rule,
144+ run: editing.horizontalRule,
145+ },
146+ ];
147+}
148+
149+// data-group names, in order: one per run of buttons between the separators of buildItems.
150+const GROUP_NAMES = ["history", "headings", "marks", "blocks"] as const;
151+
152+/**
153+ * Creates the toolbar DOM (into #editor-toolbar, or just before `mount`) and returns
154+ * the ProseMirror plugin that drives it. Buttons stay disabled until the view exists.
155+ */
156+export function createToolbar(
157+ mount: HTMLElement,
158+ schema: Schema,
159+ editing: Editing,
160+ history: { undo: Command; redo: Command },
161+): Plugin {
162+ let el = document.getElementById("editor-toolbar");
163+ if (!el) {
164+ el = document.createElement("div");
165+ el.id = "editor-toolbar";
166+ mount.before(el);
167+ }
168+ el.classList.add("editor-toolbar");
169+ el.setAttribute("role", "toolbar");
170+ el.setAttribute("aria-label", t("toolbarLabel"));
171+
172+ let current: EditorView | null = null;
173+ const buttons: { btn: HTMLButtonElement; item: Item; enabled: boolean }[] = [];
174+
175+ // Each run of buttons between separators is a group; CSS hides low-priority groups
176+ // and draws the dividers between them (see editor.css, container queries).
177+ let group = h("div", { class: "editor-toolbar-group", "data-group": GROUP_NAMES[0] });
178+ el.append(group);
179+ let groupIndex = 0;
180+
181+ for (const entry of buildItems(schema, editing, history)) {
182+ if (entry === "|") {
183+ groupIndex += 1;
184+ group = h("div", { class: "editor-toolbar-group", "data-group": GROUP_NAMES[groupIndex] });
185+ el.append(group);
186+ continue;
187+ }
188+ const btn = h(
189+ "button",
190+ {
191+ type: "button",
192+ class: "editor-toolbar-btn",
193+ "aria-label": entry.label,
194+ "aria-keyshortcuts": ariaKeys(entry.keys),
195+ "data-command": entry.id,
196+ tabindex: "-1",
197+ },
198+ h("span", { class: "editor-toolbar-icon", "aria-hidden": "true" }),
199+ tooltip(entry.label, entry.keys, t("unavailable")),
200+ );
201+ // Static icon paths only (see ICONS above).
202+ 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>`;
203+ btn.disabled = true;
204+ btn.addEventListener("click", () => {
205+ if (!current) return;
206+ entry.run(current.state, current.dispatch, current);
207+ current.focus();
208+ });
209+ group.append(btn);
210+ buttons.push({ btn, item: entry, enabled: false });
211+ }
212+
213+ // Keep the editor's selection and focus when pressing toolbar buttons.
214+ el.addEventListener("mousedown", (e) => e.preventDefault());
215+
216+ // Roving tabindex: arrows, Home and End move among enabled buttons.
217+ const enabledButtons = () => buttons.map((b) => b.btn).filter((b) => !b.disabled);
218+ const setStop = (target: HTMLButtonElement) => {
219+ for (const { btn } of buttons) btn.tabIndex = btn === target ? 0 : -1;
220+ };
221+ el.addEventListener("keydown", (e) => {
222+ const list = enabledButtons();
223+ if (!list.length) return;
224+ const index = list.indexOf(document.activeElement as HTMLButtonElement);
225+ let next: HTMLButtonElement | undefined;
226+ if (e.key === "ArrowRight") next = list[(index + 1 + list.length) % list.length];
227+ else if (e.key === "ArrowLeft") next = list[(index - 1 + list.length) % list.length];
228+ else if (e.key === "Home") next = list[0];
229+ else if (e.key === "End") next = list[list.length - 1];
230+ if (!next) return;
231+ e.preventDefault();
232+ setStop(next);
233+ next.focus();
234+ });
235+
236+ const sync = (state: EditorState) => {
237+ for (const entry of buttons) {
238+ // Commands without a dispatch only report whether they would apply.
239+ entry.enabled = !!entry.item.run(state);
240+ entry.btn.disabled = !entry.enabled;
241+ if (entry.item.isActive) {
242+ const active = entry.item.isActive(state);
243+ entry.btn.dataset.active = String(active);
244+ entry.btn.setAttribute("aria-pressed", String(active));
245+ }
246+ }
247+ // Keep one enabled button in the tab order, preferring the last one focused.
248+ const stop = buttons.find((b) => b.btn.tabIndex === 0 && !b.btn.disabled)?.btn ?? enabledButtons()[0];
249+ if (stop) setStop(stop);
250+ };
251+
252+ return new Plugin({
253+ view(view) {
254+ current = view;
255+ sync(view.state);
256+ return {
257+ update(v) {
258+ sync(v.state);
259+ },
260+ destroy() {
261+ current = null;
262+ },
263+ };
264+ },
265+ });
266+}
267+
268+/** Keyboard shortcut in aria-keyshortcuts form, e.g. "Control+B" or "Meta+Shift+8". */
269+function ariaKeys(keys: string[]): string {
270+ const names: Record<string, string> = {
271+ Ctrl: "Control",
272+ "⌘": "Meta",
273+ Shift: "Shift",
274+ "⇧": "Shift",
275+ Alt: "Alt",
276+ "⌥": "Alt",
277+ };
278+ return keys.map((k) => names[k] ?? k).join("+");
279+}