Compare commits

..

152 Commits

Author SHA1 Message Date
Kevin Jahns
34b9343b2e
Merge pull request #702 from kapv89/patch-1
Update README.md to add https://github.com/kapv89/k_yrs_go to persistence providers
2025-03-26 12:57:27 +01:00
kapil verma
d5b5e7a9a1
Update README.md to add https://github.com/kapv89/k_yrs_go to persistence providers
Ref: https://x.com/kevin_jahns/status/1904252641124753641
2025-03-26 01:55:02 +05:30
Kevin Jahns
ad0d915794
Merge pull request #701 from hacklschorsch/patch-2
README: Remove duplicate btw mention
2025-03-18 20:18:35 +01:00
Florian Sesser
2ef9ccd170
README: Remove duplicate btw mention
'btw' was mentioned twice; remove one mention.
2025-03-18 19:23:51 +01:00
Kevin Jahns
3ecfb4e898 add rowsncolumns 2025-03-09 20:57:52 +01:00
Kevin Jahns
35c030d834 improve reject update example 2025-03-06 10:36:18 +01:00
Kevin Jahns
e3739bce8e test example for rejecting updates 2025-03-05 14:15:26 +01:00
Kevin Jahns
afa4c35866 update titanic funding information - closes #696 2025-03-05 14:15:12 +01:00
Kevin Jahns
09fbb62ba9 improve documentation on global UndoManager 2025-03-04 14:52:19 +01:00
Kevin Jahns
78e0527b46 13.6.24 2025-03-04 14:44:19 +01:00
Kevin Jahns
69d4a5c821 [UndoManager] support global undo 2025-03-04 14:42:19 +01:00
Kevin Jahns
cc9a857441 slightly optimize TreeWalker and integration process 2025-02-24 20:30:48 +01:00
Kevin Jahns
4b865764b8
Merge pull request #691 from reknih/add-typst
Add Typst to Yjs users in README
2025-01-17 12:00:53 +01:00
Martin Haug
40725e373b Add Typst to Yjs users in README 2025-01-17 11:58:36 +01:00
Kevin Jahns
c05b815b4c 13.6.23 2025-01-15 21:46:23 +01:00
Kevin Jahns
e53c44e3a6 expose getItemCleanStart/End 2025-01-15 21:44:18 +01:00
Kevin Jahns
1bec008862 13.6.22 2025-01-12 19:45:03 +01:00
Kevin Jahns
bb5410b6dd marginally better typings for applyDelta - #689 2025-01-12 19:41:19 +01:00
Kevin Jahns
2d2e662d4d
Merge pull request #690 from yjs/revert-689-patch-1
Revert "fix(yText): applyDelta should support both Delta and Ops[]"
2025-01-12 19:33:12 +01:00
Kevin Jahns
80e83a84c6
Revert "fix(yText): applyDelta should support both Delta and Ops[]" 2025-01-12 19:32:51 +01:00
Kevin Jahns
3c9c0f17d1
Merge pull request #689 from ykou-clickup/patch-1
fix(yText): applyDelta should support both Delta and Ops[]
2025-01-12 19:26:30 +01:00
Yuxiang Kou
e67b1296a7
fix(yText): applyDelta should support both Delta and Ops[]
Fixed an issue that the yText.applyDelta() accepted only Ops[], but not Delta.
2025-01-09 14:58:47 -08:00
Kevin Jahns
1a0d4aa797
Merge pull request #685 from szepeviktor/typos
Fix typos
2025-01-07 12:36:44 +01:00
Viktor Szépe
f18eab2dfe Fix typos 2025-01-03 18:11:43 +00:00
Kevin Jahns
89dddc2a95 13.6.21 2024-12-21 00:55:05 +01:00
Kevin Jahns
f583d2a211 fix #657 - relative positions issue when using followUndoneDeletions=false 2024-12-21 00:52:48 +01:00
Kevin Jahns
1b0f2e5463 lint 2024-12-18 14:35:13 +01:00
Kevin Jahns
4404d090e4 add nodejs specific tests 2024-12-18 14:34:33 +01:00
Kevin Jahns
d4d4ae5f53
Merge pull request #679 from hoangqwe159/main
Add PSPDFKit binding to README.md
2024-12-14 21:24:57 +01:00
Viet Hoang Do
4ffd3709f8 Add PSPDFKit binding to README.md 2024-12-06 09:58:19 +10:00
Kevin Jahns
0419b74315
Merge pull request #676 from himself65/patch-1
docs: remove `@toeverything/y-indexeddb`
2024-12-04 22:37:32 +01:00
Kevin Jahns
c951f2b7ea add Open Collaboration Tools as a user 2024-11-28 01:08:37 +01:00
Alex Yang
4e2d3c8ac6
docs: remove @toeverything/y-indexeddb 2024-11-27 15:42:50 -08:00
Kevin Jahns
8dc1296a0b update readme 2024-10-24 18:07:52 +02:00
Kevin Jahns
4329997350 add stars to providers that sponsor yjs 2024-10-24 18:05:42 +02:00
Kevin Jahns
2b7ea8a2af
Merge pull request #671 from carlossantos74/main
Added SuperViz Provider to the list of providers
2024-10-24 17:38:00 +02:00
Carlos
4f47355893 add SuperViz Provider in yjs README 2024-10-22 16:26:33 -03:00
Kevin Jahns
6074f80257 [funding.json] fix some validation issues 2024-10-19 17:43:48 +02:00
Kevin Jahns
42bbb44bfc fix errors in funding.json 2024-10-19 04:50:46 +02:00
Kevin Jahns
cc2d7320aa add funding.json 2024-10-19 04:40:13 +02:00
Kevin Jahns
e804dd7573 add y-crdt elexir bindings 2024-10-19 04:40:11 +02:00
Kevin Jahns
a304024a76 13.6.20 2024-10-14 01:41:22 +02:00
Kevin Jahns
487465d701 lint 2024-10-14 01:39:15 +02:00
Kevin Jahns
345fd31b10 add yjs-inspector 2024-10-07 09:45:27 +02:00
Kevin Jahns
4ff65b5dc3 add devtools 2024-10-07 09:43:13 +02:00
Kevin Jahns
8152cf81cb [#667] sanity checks for Yjs caveats. In dev_mode, objects inserted into Yjs can't be manipulated. 2024-10-04 21:23:59 +02:00
Kevin Jahns
3bf44b9850 #667 - add sanity messages when data is read before type is added to a document. 2024-10-04 21:07:19 +02:00
Kevin Jahns
8cd1a482bb Y.Array.length should be 0 before it is integrated - #666 2024-09-26 19:30:34 +02:00
Kevin Jahns
9e9f294009
Merge pull request #665 from batchor/main
add ScienHub as a user.
2024-09-19 23:02:50 +02:00
Kevin Jahns
9a993f81d4 13.6.19 2024-09-10 15:37:58 +02:00
Kevin Jahns
f604250fc3 add ydoc.isDestroyed property 2024-09-10 15:35:46 +02:00
Batchor
4fb7789cdd add ScienHub as a user. 2024-09-05 15:23:58 -07:00
Batchor
c1ef9a12b9 add ScienHub as a user. 2024-09-05 15:22:40 -07:00
Kevin Jahns
7422b18e87 add eclipse theia as a user 2024-09-04 00:02:19 +02:00
Kevin Jahns
95e2bc4429 add secsync 2024-09-02 18:54:19 +02:00
Kevin Jahns
f2ff8b9536 add kanbert as a user 2024-08-30 19:09:59 +02:00
Kevin Jahns
3f9bfe42f7
Merge pull request #664 from jul13579/add-qdacity-to-readme
Add QDAcity to `README.md`
2024-08-29 17:51:35 +02:00
Julian Lehrhuber
5b4d2a6bcf Add QDAcity to README.md 2024-08-29 14:24:29 +02:00
Kevin Jahns
44e51080af fix new lint issues 2024-08-06 16:48:14 +02:00
Kevin Jahns
dd17228a8f update markdownlint 2024-08-06 16:37:52 +02:00
Kevin Jahns
eeb4c9969d lint readme 2024-08-05 16:14:47 +02:00
Kevin Jahns
56d5e3287b
Merge pull request #660 from mtreinik/main
Add missing functions and remove erroneus function from API docs
2024-07-30 17:20:14 +02:00
Mikko Reinikainen
294c6a15c5 Remove erroneous ymap.get(index:number) from API docs 2024-07-30 12:55:45 +03:00
Mikko Reinikainen
c944a4553c Add Y.Array.from() and yarray.clone() to API docs 2024-07-30 12:55:11 +03:00
Kevin Jahns
f29cd2baf4 update users 2024-07-10 17:52:29 +02:00
Kevin Jahns
384ec4db78
Merge pull request #651 from nikgraf/patch-2
add react-yjs to bindings
2024-06-30 12:04:10 +02:00
Nik Graf
5e19c35405
add react-yjs to bindings 2024-06-24 13:35:55 +02:00
Kevin Jahns
1bfa6dfb74 13.6.18 2024-06-18 16:59:36 +02:00
Kevin Jahns
2e5abad773 fix #645 yjs/y-utility#8 2024-06-18 16:51:57 +02:00
Kevin Jahns
3f1746f3a9 add lexical editor 2024-06-17 20:29:14 +02:00
Kevin Jahns
34b06b6cf9 13.6.17 2024-06-17 15:15:04 +02:00
Kevin Jahns
d4dac558c0 fix creating relative position from json when type name is the empty string 2024-06-17 15:13:07 +02:00
Kevin Jahns
a47a48b891
Merge pull request #649 from szv/readme-fixes
Readme fixes
2024-06-15 20:12:15 +02:00
Sebastian Szvetecz
2e79d0369e
Fixed markdown link for ellipsus.org in README.md 2024-06-12 01:12:48 +02:00
Sebastian Szvetecz
88506f6d78
Fixed star icon in README.md 2024-06-12 01:12:13 +02:00
Kevin Jahns
fbd088ee78 13.6.16 2024-06-10 12:21:06 +02:00
Kevin Jahns
0678ed1eb5 fix event.path in observeDeep - closes #457 2024-06-10 12:18:16 +02:00
Kevin Jahns
0973e0acd4
Merge pull request #648 from ellipsus-writes/export-merge-ds
Export mergeDeleteSets
2024-06-07 17:20:20 +02:00
Fuad Saud
6932696795
Export mergeDeleteSets
Useful for comparing snapshots.
2024-06-06 13:38:08 +02:00
Kevin Jahns
a4303f914d
Merge pull request #646 from MaxNoetzold/patch-1
Add y-postgresql to provider list in README
2024-06-04 13:47:02 +02:00
Max Nötzold
03593aeeb1
fix linting errors 2024-05-21 16:03:31 +02:00
Max Nötzold
d67a951104
add y-postgresql info to readme 2024-05-21 15:30:24 +02:00
Kevin Jahns
72205a688f
Merge pull request #644 from i12345/patch-1
Update INTERNALS.md
2024-05-15 21:00:32 +02:00
i12345
edad668dbd
Update INTERNALS.md
explained 53 bit JS numbers
2024-05-15 13:43:59 -05:00
Kevin Jahns
c264b1c291
Merge pull request #640 from malte-j/patch-1
Add y-op-sqlite to Readme
2024-05-11 12:27:35 +02:00
Kevin Jahns
cdd8e4f5fc
Merge pull request #643 from jasonbw/patch-1
Fix y-websocket `server.cjs` path
2024-05-09 13:43:05 +02:00
Jason Wang
06e71f651d
Fix y-websocket server path
The commmit c3d14cf07d renamed `server.js` to `server.cjs`; mirror that change here.
2024-05-09 05:55:26 -05:00
Malte Janßen
54594a2d75
Add y-op-sqlite to readme 2024-04-30 16:29:06 +02:00
Kevin Jahns
13772bf891
Merge pull request #603 from kevboh/patch-1
add screen.garden as user
2024-04-28 21:39:28 +02:00
Kevin Jahns
0896ed42b2
Merge branch 'main' into patch-1 2024-04-28 21:38:49 +02:00
Kevin Jahns
656b7e7f6a add more users 2024-04-28 21:16:58 +02:00
Kevin Jahns
0511b66346
Merge pull request #635 from synix/fix/unused-transaction
remove unused _transaction in YArrayEvent
2024-04-28 21:08:58 +02:00
Kevin Jahns
91b718cde0 13.6.15 2024-04-27 00:50:32 +02:00
Kevin Jahns
d56221b66a
Merge pull request #637 from synix/fix/readme-lint
fix: markdownlint readme error
2024-04-27 00:46:42 +02:00
Kevin Jahns
ce43124ad0 [relative-positions] add option to configure whether to follow redon insertions - #638 2024-04-27 00:24:49 +02:00
synix
0af69cf6d6 fix: markdownlint readme error 2024-04-26 13:15:06 +08:00
synix
3df335cb4c update slice() function's doc 2024-04-26 12:03:28 +08:00
synix
387be70ae9 make slice() function's doc more accurate 2024-04-26 11:49:52 +08:00
Kevin Jahns
927c2369aa
Merge pull request #636 from fxsalazar/patch-1
Add Hocuspocus as a backend provider
2024-04-26 00:42:32 +02:00
Felix Salazar
8270373c9f
Add Hocuspocus as a backend provider 2024-04-25 19:34:05 +02:00
synix
43815d8292 fix lint error 2024-04-25 11:33:36 +08:00
synix
f0dc53f53f fix minor typos 2024-04-25 11:17:49 +08:00
synix
25ae9f3236 remove unused _transaction in YArray 2024-04-25 11:03:17 +08:00
Kevin Jahns
5e712e39b1 add ourboard as user 2024-04-24 16:03:21 +02:00
Kevin Jahns
4ffd23fd0b typo 2024-04-17 20:41:42 +02:00
Kevin Jahns
05d974cee1
Merge pull request #630 from sakihet/fix-typo
fix typo
2024-04-15 18:54:02 +02:00
saki
f1532771b7 fix typo 2024-04-16 01:15:02 +09:00
Kevin Jahns
aee9e14d09
Merge pull request #629 from synix/fix/outdated-y-instance
remove outdated Y instance in comments
2024-04-13 19:54:23 +02:00
synix
f5aa852054 remove outdated Y instance in comments 2024-04-13 21:26:44 +08:00
Kevin Jahns
b990ad9f86
Merge pull request #627 from synix/fix/INTERNALS
update search marker count in INTERNALS.md
2024-04-12 13:22:02 +02:00
synix
43e17802a6 fix: update search marker count in INTERNALS.md 2024-04-11 11:21:14 +08:00
Kevin Jahns
01c3668a0b
Merge pull request #626 from satyajeetjadhav/main
Update Readme who-is-using (thinkdeli.com)
2024-04-09 18:06:25 +02:00
Satyajeet Jadhav
52b906898f
Update Readme who-is-using (thinkdeli.com) 2024-04-09 16:39:18 +05:30
Kevin Jahns
d119459fad add huly as a user 2024-04-03 15:22:58 +02:00
Kevin Jahns
d730abe594 add synthesia as a user 2024-03-24 21:00:23 +01:00
Kevin Jahns
ca24f1ee76 added more sponsors 2024-03-23 14:29:23 +01:00
Kevin Jahns
dc45a8d3cf [readme] Added AppMaster to "Who is Using" 2024-03-23 12:44:01 +01:00
Kevin Jahns
2062f52a90 add reference to y-redis 2024-03-15 01:42:16 +01:00
Kevin Jahns
6e674ff5f7 add y-webxdc - related to yjs/docs#55 2024-03-14 21:09:34 +01:00
Kevin Jahns
2fba694cd4 Add documentation & clarification to clone method #622 2024-03-14 20:33:34 +01:00
Kevin Jahns
b235c57d76 add tinybase 2024-03-12 16:22:12 +01:00
Kevin Jahns
6beab79eb4 add tests for falsy formatting attributes - #619 2024-03-01 11:39:31 +01:00
Kevin Jahns
1e69d650b8 13.6.14 2024-03-01 11:31:21 +01:00
Kevin Jahns
133cfc9cdc allow falsy values in formatting attributes 2024-03-01 11:29:14 +01:00
Kevin Jahns
83db6c814c
Merge pull request #619 from jul13579/allow-falsy-attribute-values
Allow falsy attribute values
2024-03-01 11:23:04 +01:00
Julian Lehrhuber
cdbb55818d Allow falsy attribute values 2024-03-01 10:37:51 +01:00
Kevin Jahns
90675be3ab 13.6.13 2024-02-29 17:37:25 +01:00
Kevin Jahns
541306b254 migrate to ObservableV2 2024-02-29 17:08:57 +01:00
Kevin Jahns
53173a9ea7 Merge branch 'mylesj-feat/undomanager-doingstackitem' 2024-02-29 14:47:00 +01:00
Kevin Jahns
29fa60ccf9 [Undo] add UndoManager.currStackItem 2024-02-29 14:46:43 +01:00
Myles J
917261a1ce
Facilitate referencing UndoManager StackItem inside Type observers 2024-02-29 00:50:36 +00:00
Kevin Jahns
a9dc72fcc0
Merge pull request #612 from MentalGear/patch-1
docs: fix typo
2024-02-25 10:31:20 +01:00
Kevin Jahns
90a90ab010 add y-fire to provider list #189 2024-02-20 19:52:58 +01:00
MentalGear
009f6ab551
docs: fix typo 2024-02-17 20:38:53 +01:00
Kevin Jahns
a8582442e3 13.6.12 2024-02-09 23:38:50 +01:00
Kevin Jahns
f54ea625e2 Merge branch 'raineorshine-getXmlElement' 2024-02-09 23:31:29 +01:00
Kevin Jahns
ce06b2abec update deps 2024-02-09 23:31:07 +01:00
Kevin Jahns
e1bce03ed8 better typings for ydoc.get 2024-02-09 23:27:24 +01:00
Raine Revere
16d9638bc8 Add ydoc.getXmlElement 2024-02-05 13:35:32 +00:00
Kevin Jahns
415a645874 13.6.11 2024-01-21 11:30:14 +01:00
Kevin Jahns
1cb52dc863 fix Y.Text formatting issue - closes #606 2024-01-21 11:27:12 +01:00
Kevin Jahns
7a8ca6eaa5 add linear as a user of Yjs 2024-01-15 14:11:28 +01:00
Kevin Jahns
e348255bb1
Merge pull request #604 from lukasz-jazwa/proffesional-support-section
Updated readme.md with Professional Support section
2024-01-10 17:27:03 +01:00
Kevin Jahns
79c095d4dc
Merge pull request #605 from xaviergonz/patch-1
Update README.md with mobx-keystone binding
2023-12-28 15:31:00 +01:00
Javier Gonzalez
0241fd3c40
Update README.md with mobx-keystone binding 2023-12-23 11:16:57 +01:00
lukasz jazwa
cf78ce12b2 Updated readme.md with Professional Support section 2023-12-14 21:55:53 +01:00
Kevin Jahns
77bd74127d Update who-is-using (Cargo.site) 2023-12-11 16:37:23 +01:00
Kevin Barrett
221cb81dbf
add screen.garden as user 2023-11-30 16:51:23 -05:00
Kevin Jahns
fe36ffd122 add AWS Sagemaker, JupyterLab, JupyterCAD as users 2023-11-28 16:22:37 +01:00
Kevin Jahns
28ccd5e0dd add providers (also mention some y-crdt based providers) 2023-11-21 19:55:29 +01:00
Kevin Jahns
1d4f2e5435 13.6.10 2023-11-21 12:29:49 +01:00
Kevin Jahns
2c0daeb071 implement snapshot API for yxml.getAttributes. implements #543 2023-11-21 12:24:21 +01:00
54 changed files with 2199 additions and 796 deletions

View File

@ -26,7 +26,7 @@ article](https://blog.kevinjahns.de/are-crdts-suitable-for-shared-editing/).
Each client is assigned a unique *clientID* property on first insert. This is a
random 53-bit integer (53 bits because that fits in the javascript safe integer
range).
range \[JavaScript uses IEEE 754 floats\]).
## List items
@ -60,7 +60,7 @@ characters have either been deleted or all characters are not deleted. The item
will be split if the run is interrupted for any reason (eg a character in the
middle of the run is deleted).
When an item is created, it stores a reference to the IDs of the preceeding and
When an item is created, it stores a reference to the IDs of the preceding and
succeeding item. These are stored in the item's `origin` and `originRight`
fields, respectively. These are used when peers concurrently insert at the same
location in a document. Though quite rare in practice, Yjs needs to make sure
@ -88,7 +88,7 @@ When a local insert happens, Yjs needs to map the insert position in the
document (eg position 1000) to an ID. With just the linked list, this would
require a slow O(n) linear scan of the list. But when editing a document, most
inserts are either at the same position as the last insert, or nearby. To
improve performance, Yjs stores a cache of the 10 most recently looked up
improve performance, Yjs stores a cache of the 80 most recently looked up
insert positions in the document. This is consulted and updated when a position
is looked up to improve performance in the average case. The cache is updated
using a heuristic that is still changing (currently, it is updated when a new

252
README.md
View File

@ -3,7 +3,7 @@
> A CRDT framework with a powerful abstraction of shared data
Yjs is a [CRDT implementation](#Yjs-CRDT-Algorithm) that exposes its internal
Yjs is a [CRDT implementation](#yjs-crdt-algorithm) that exposes its internal
data structure as *shared types*. Shared types are common data types like `Map`
or `Array` with superpowers: changes are automatically distributed to other
peers and merged without merge conflicts.
@ -32,13 +32,34 @@ Otherwise you can find help on our community [discussion board](https://discuss.
Please contribute to the project financially - especially if your company relies
on Yjs. [![Become a Sponsor](https://img.shields.io/static/v1?label=Become%20a%20Sponsor&message=%E2%9D%A4&logo=GitHub&style=flat&color=d42f2d)](https://github.com/sponsors/dmonad)
## Professional Support
* [Support Contract with the Maintainer](https://github.com/sponsors/dmonad) -
By contributing financially to the open-source Yjs project, you can receive
professional support directly from the author. This includes the opportunity for
weekly video calls to discuss your specific challenges.
* [Synergy Codes](https://synergycodes.com/yjs-services/) - Specializing in
consulting and developing real-time collaborative editing solutions for visual
apps, Synergy Codes focuses on interactive diagrams, complex graphs, charts, and
various data visualization types. Their expertise empowers developers to build
engaging and interactive visual experiences leveraging the power of Yjs. See
their work in action at [Visual Collaboration
Showcase](https://yjs-diagram.synergy.codes/).
## Who is using Yjs
* [AFFiNE](https://affine.pro/) A local-first, privacy-first, open source
knowledge base. 🏅
* [Dynaboard](https://dynaboard.com/) Build web apps collaboratively. :star2:
* [Sana](https://sanalabs.com/) A learning platform with collaborative text
editing powered by Yjs.
knowledge base. :star2:
* [Huly](https://huly.io/) - Open Source All-in-One Project Management Platform :star2:
* [Cargo](https://cargo.site/) Site builder for designers and artists :star2:
* [Gitbook](https://gitbook.com) Knowledge management for technical teams :star2:
* [Evernote](https://evernote.com) Note-taking app :star2:
* [Lessonspace](https://thelessonspace.com) Enterprise platform for virtual
classrooms and online training :star2:
* [Ellipsus](ellipsus.com) - Collaborative writing app for storytelling etc.
Supports versioning, change attribution, and "blame". A solution for the whole
publishing process (also selling) :star:
* [Dynaboard](https://dynaboard.com/) Build web apps collaboratively. :star:
* [Relm](https://www.relm.us/) A collaborative gameworld for teamwork and
community. :star:
* [Room.sh](https://room.sh/) A meeting application with integrated
@ -47,15 +68,24 @@ on Yjs. [![Become a Sponsor](https://img.shields.io/static/v1?label=Become%20a%2
Nimbus Web. :star:
* [Pluxbox RadioManager](https://getradiomanager.com/) A web-based app to
collaboratively organize radio broadcasts. :star:
* [modyfi](https://www.modyfi.com) - Modyfi is the design platform built for
multidisciplinary designers. Design, generate, animate, and more — without
switching between apps. :star:
* [Sana](https://sanalabs.com/) A learning platform with collaborative text
editing powered by Yjs.
* [Serenity Notes](https://www.serenity.re/en/notes) End-to-end encrypted
collaborative notes app.
* [PRSM](https://prsm.uk/) Collaborative mind-mapping and system visualisation. *[(source)](https://github.com/micrology/prsm)*
* [PRSM](https://prsm.uk/) Collaborative mind-mapping and system visualisation.
*[(source)](https://github.com/micrology/prsm)*
* [Alldone](https://alldone.app/) A next-gen project management and
collaboration platform.
* [Living Spec](https://livingspec.com/) A modern way for product teams to collaborate.
* [Slidebeamer](https://slidebeamer.com/) Presentation app.
* [BlockSurvey](https://blocksurvey.io) End-to-end encryption for your forms/surveys.
* [Skiff](https://skiff.org/) Private, decentralized workspace.
* [JupyterLab](https://jupyter.org/) Collaborative computational Notebooks
* [JupyterCad](https://jupytercad.readthedocs.io/en/latest/) Extension to
JupyterLab that enables collaborative editing of 3d FreeCAD Models.
* [Hyperquery](https://hyperquery.ai/) A collaborative data workspace for
sharing analyses, documentation, spreadsheets, and dashboards.
* [Nosgestesclimat](https://nosgestesclimat.fr/groupe) The french carbon
@ -66,22 +96,50 @@ on Yjs. [![Become a Sponsor](https://img.shields.io/static/v1?label=Become%20a%2
worldbuilding app for tabletop RPGs.
* [IllumiDesk](https://illumidesk.com/) Build courses and content with A.I.
* [btw](https://www.btw.so) Open-source Medium alternative
* [AWS SageMaker](https://aws.amazon.com/sagemaker/) Tools for building Machine
Learning Models
* [linear](https://linear.app) Streamline issues, projects, and product roadmaps.
* [AWS SageMaker](https://aws.amazon.com/sagemaker/) - Machine Learning Service
* [Arkiter](https://www.arkiter.com/) - Live interview software
* [Appflowy](https://www.appflowy.io/) - They use Yrs
* [Multi.app](https://multi.app) - Multiplayer app sharing: Point, draw and edit
in shared apps as if they're on your computer. They are using Yrs.
* [AppMaster](https://appmaster.io) A No-Code platform for creating
production-ready applications with source code generation.
* [Synthesia](https://www.synthesia.io) - Collaborative Video Editor
* [thinkdeli](https://thinkdeli.com) - A fast and simple notes app powered by AI
* [ourboard](https://github.com/raimohanska/ourboard) - A collaborative whiteboard
application
* [Ellie.ai](https://ellie.ai) - Data Product Design and Collaboration
* [GoPeer](https://gopeer.org/) - Collaborative tutoring
* [screen.garden](https://screen.garden) - Collaborative backend for PKM apps.
* [NextCloud](https://nextcloud.com/) - Content Collaboration Platform
* [keystatic](https://github.com/Thinkmill/keystatic) - git-based CMS
* [QDAcity](https://qdacity.com) - Collaborative qualitative data analysis platform
* [Kanbert](https://kanbert.com) - Project management software
* [Eclipse Theia](https://github.com/eclipse-theia/theia) - A cloud & desktop
IDE that runs in the browser.
* [ScienHub](https://scienhub.com) - Collaborative LaTeX editor in the browser.
* [Open Collaboration Tools](https://www.open-collab.tools/) - Collaborative
editing for your IDE or custom editor
* [Typst](https://typst.app/) - Compose, edit, and automate technical documents
## Table of Contents
* [Overview](#Overview)
* [Bindings](#Bindings)
* [Providers](#Providers)
* [Ports](#Ports)
* [Getting Started](#Getting-Started)
* [API](#API)
* [Shared Types](#Shared-Types)
* [Y.Doc](#YDoc)
* [Document Updates](#Document-Updates)
* [Relative Positions](#Relative-Positions)
* [Y.UndoManager](#YUndoManager)
* [Yjs CRDT Algorithm](#Yjs-CRDT-Algorithm)
* [License and Author](#License-and-Author)
* [Overview](#overview)
* [Bindings](#bindings)
* [Providers](#providers)
* [Tooling](#tooling)
* [Ports](#ports)
* [Getting Started](#getting-started)
* [API](#api)
* [Shared Types](#shared-types)
* [Y.Doc](#ydoc)
* [Document Updates](#document-updates)
* [Relative Positions](#relative-positions)
* [Y.UndoManager](#yundomanager)
* [Yjs CRDT Algorithm](#yjs-crdt-algorithm)
* [License and Author](#license-and-author)
## Overview
@ -99,9 +157,14 @@ are implemented in separate modules.
| [Monaco](https://microsoft.github.io/monaco-editor/) | ✔ | [y-monaco](https://github.com/yjs/y-monaco) | [demo](https://demos.yjs.dev/monaco/monaco.html) |
| [Slate](https://github.com/ianstormtaylor/slate) | ✔ | [slate-yjs](https://github.com/bitphinix/slate-yjs) | [demo](https://bitphinix.github.io/slate-yjs-example) |
| [BlockSuite](https://github.com/toeverything/blocksuite) | ✔ | (native) | [demo](https://blocksuite-toeverything.vercel.app/?init) |
| [Lexical](https://lexical.dev/) | ✔ | (native) | [demo](https://lexical.dev/docs/collaboration/react#see-it-in-action) |
| [valtio](https://github.com/pmndrs/valtio) | | [valtio-yjs](https://github.com/dai-shi/valtio-yjs) | [demo](https://codesandbox.io/s/valtio-yjs-demo-ox3iy) |
| [immer](https://github.com/immerjs/immer) | | [immer-yjs](https://github.com/sep2/immer-yjs) | [demo](https://codesandbox.io/s/immer-yjs-demo-6e0znb) |
| React | | [react-yjs](https://github.com/nikgraf/react-yjs) | [demo](https://react-yjs-example.vercel.app/) |
| React / Vue / Svelte / MobX | | [SyncedStore](https://syncedstore.org) | [demo](https://syncedstore.org/docs/react) |
| [mobx-keystone](https://mobx-keystone.js.org/) | | [mobx-keystone-yjs](https://github.com/xaviergonz/mobx-keystone/tree/master/packages/mobx-keystone-yjs) | [demo](https://mobx-keystone.js.org/examples/yjs-binding) |
| [PSPDFKit](https://www.nutrient.io/) | | [yjs-pspdfkit](https://github.com/hoangqwe159/yjs-pspdfkit) | [demo](https://github.com/hoangqwe159/yjs-pspdfkit) |
| [Rows n'Columns](https://www.rowsncolumns.app/) | ✔ | [@rowsncolumns/y-spreadsheet](https://docs.rowsncolumns.app/collaboration/yjs-collaboration) | |
### Providers
@ -110,26 +173,56 @@ and storing shared data for offline usage is quite a hassle. **Providers**
manage all that for you and are the perfect starting point for your
collaborative app.
> This list of providers is incomplete. Please open PRs to add your providers to
> this list!
#### Connection Providers
<dl>
<dt><a href="https://github.com/yjs/y-websocket">y-websocket</a></dt>
<dd>
A module that contains a simple websocket backend and a websocket client that
connects to that backend. <a href="https://github.com/yjs/y-redis/"><b>y-redis</b></a>,
<b>y-sweet</b>, <b>ypy-websocket</b> and <a href="https://tiptap.dev/docs/hocuspocus/introduction">
<b>Hocuspocus</b></a> (see below) are alternative
backends to y-websocket.
</dd>
<dt><a href="https://github.com/yjs/y-webrtc">y-webrtc</a></dt>
<dd>
Propagates document updates peer-to-peer using WebRTC. The peers exchange
signaling data over signaling servers. Publically available signaling servers
signaling data over signaling servers. Publicly available signaling servers
are available. Communication over the signaling servers can be encrypted by
providing a shared secret, keeping the connection information and the shared
document private.
</dd>
<dt><a href="https://github.com/yjs/y-websocket">y-websocket</a></dt>
<dt><a href="https://github.com/liveblocks/liveblocks">@liveblocks/yjs </a> 🌟</dt>
<dd>
A module that contains a simple websocket backend and a websocket client that
connects to that backend. The backend can be extended to persist updates in a
leveldb database.
<a href="https://liveblocks.io/document/yjs">Liveblocks Yjs</a> provides a fully
hosted WebSocket infrastructure and persisted data store for Yjs
documents. No configuration or maintenance is required. It also features
Yjs webhook events, REST API to read and update Yjs documents, and a
browser DevTools extension.
</dd>
<dt><a href="https://github.com/yjs/y-indexeddb">y-indexeddb</a></dt>
<dt><a href="https://github.com/drifting-in-space/y-sweet">y-sweet</a></dt>
<dd>
Efficiently persists document updates to the browsers indexeddb database.
The document is immediately available and only diffs need to be synced through the
network provider.
A standalone yjs server with persistence to S3 or filesystem. They offer a
<a href="https://y-sweet.cloud">cloud service</a> as well.
</dd>
<dt><a href="https://github.com/ueberdosis/hocuspocus">Hocuspocus</a></dt>
<dd>
A standalone extensible yjs server with sqlite persistence, webhooks, auth and more.
</dd>
<dt><a href="https://docs.superviz.com/collaboration/integrations/YJS/overview">@superviz/yjs</a></dt>
<dd>
SuperViz Yjs Provider comes with a secure, scalable real-time infrastructure
for Yjs documents, fully compatible with a set of real-time
collaboration components offered by SuperViz. This solution ensures
synchronization, offline editing, and real-time updates, enabling
multiple users to collaborate effectively within shared workspaces.
</dd>
<dt><a href="https://docs.partykit.io/reference/y-partykit-api/">PartyKit</a></dt>
<dd>
Cloud service for building multiplayer apps.
</dd>
<dt><a href="https://github.com/marcopolo/y-libp2p">y-libp2p</a></dt>
<dd>
@ -144,14 +237,6 @@ Also includes a peer-sync mechanism to catch up on missed updates.
an append-only log of CRDT local updates (hypercore). Multifeed manages and sync
hypercores and y-dat listens to changes and applies them to the Yjs document.
</dd>
<dt><a href="https://github.com/liveblocks/liveblocks">@liveblocks/yjs</a></dt>
<dd>
<a href="https://liveblocks.io/document/yjs">Liveblocks Yjs</a> provides a fully
hosted WebSocket infrastructure and persisted data store for Yjs
documents. No configuration or maintenance is required. It also features
Yjs webhook events, REST API to read and update Yjs documents, and a
browser DevTools extension.
</dd>
<dt><a href="https://github.com/yousefED/matrix-crdt">Matrix-CRDT</a></dt>
<dd>
Use <a href="https://www.matrix.org">Matrix</a> as an off-the-shelf backend for
@ -160,20 +245,74 @@ Use Matrix as transport and storage of Yjs updates, so you can focus building
your client app and Matrix can provide powerful features like Authentication,
Authorization, Federation, hosting (self-hosting or SaaS) and even End-to-End
Encryption (E2EE).
</dd>
</dd>
<dt><a href="https://github.com/y-crdt/yrb-actioncable">yrb-actioncable</a></dt>
<dd>
An ActionCable companion for Yjs clients. There is a fitting
<a href="https://github.com/y-crdt/yrb-redis">redis extension</a> as well.
</dd>
<dt><a href="https://github.com/y-crdt/ypy-websocket">ypy-websocket</a></dt>
<dd>
Websocket backend, written in Python.
</dd>
<dt><a href="https://tinybase.org/">Tinybase</a></dt>
<dd>
The reactive data store for local-first apps. They support multiple CRDTs and
different network technologies.
</dd>
<dt><a href="https://codeberg.org/webxdc/y-webxdc">y-webxdc</a></dt>
<dd>
Provider for sharing data in <a href="https://webxdc.org">webxdc chat apps</a>.
</dd>
<dt><a href="https://www.secsync.com/">secsync</a></dt>
<dd>
An architecture to relay end-to-end encrypted CRDTs over a central service.
</dd>
</dl>
#### Persistence Providers
<dl>
<dt><a href="https://github.com/yjs/y-indexeddb">y-indexeddb</a></dt>
<dd>
Efficiently persists document updates to the browsers indexeddb database.
The document is immediately available and only diffs need to be synced through the
network provider.
</dd>
<dt><a href="https://github.com/MaxNoetzold/y-mongodb-provider">y-mongodb-provider</a></dt>
<dd>
Adds persistent storage to a server with MongoDB. Can be used with the
y-websocket provider.
</dd>
<dt><a href="https://github.com/toeverything/AFFiNE/tree/master/packages/y-indexeddb">
@toeverything/y-indexeddb</a></dt>
</dd>
<dt><a href="https://github.com/podraven/y-fire">y-fire</a></dt>
<dd>
Like y-indexeddb, but with sub-documents support and fully TypeScript.
</dd>
A database and connection provider for Yjs based on Firestore.
</dd>
<dt><a href="https://github.com/malte-j/y-op-sqlite">y-op-sqlite</a></dt>
<dd>
Persist YJS updates in your React Native app using
<a href="https://github.com/OP-Engineering/op-sqlite">op-sqlite</a>
, the fastest SQLite library for React Native.
</dd>
<dt><a href="https://github.com/MaxNoetzold/y-postgresql">y-postgresql</a></dt>
<dd>
Provides persistent storage for a web server using PostgreSQL and
is easily compatible with y-websocket.
</dd>
<dt><a href="https://github.com/kapv89/k_yrs_go">k_yrs_go</a></dt>
<dd>
Golang database server for YJS CRDT using Postgres + Redis
</dd>
</dl>
# Ports
### Tooling
* [y-sweet debugger](https://docs.jamsocket.com/y-sweet/advanced/debugger)
* [liveblocks devtools](https://liveblocks.io/devtools)
* [Yjs inspector](https://inspector.yjs.dev)
### Ports
There are several Yjs-compatible ports to other programming languages.
@ -187,6 +326,7 @@ language bindings to other languages
* [yswift](https://github.com/y-crdt/yswift) - Swift binding
* [yffi](https://github.com/y-crdt/y-crdt/tree/main/yffi) - C-FFI
* [ywasm](https://github.com/y-crdt/y-crdt/tree/main/ywasm) - WASM binding
* [y_ex](https://github.com/satoren/y_ex) - Elixir bindings
* [ycs](https://github.com/yjs/ycs) - .Net compatible C# implementation.
## Getting Started
@ -200,7 +340,7 @@ npm i yjs y-websocket
Start the y-websocket server:
```sh
PORT=1234 node ./node_modules/y-websocket/bin/server.js
PORT=1234 node ./node_modules/y-websocket/bin/server.cjs
```
### Example: Observe types
@ -301,6 +441,11 @@ necessary.
</p>
<pre>const yarray = new Y.Array()</pre>
<dl>
<b><code>
Y.Array.from(Array&lt;object|boolean|Array|string|number|null|Uint8Array|Y.Type&gt;):
Y.Array
</code></b>
<dd>An alternative factory function to create a Y.Array based on existing content.</dd>
<b><code>parent:Y.AbstractType|null</code></b>
<dd></dd>
<b><code>insert(index:number, content:Array&lt;object|boolean|Array|string|number|null|Uint8Array|Y.Type&gt;)</code></b>
@ -330,6 +475,11 @@ forEach(function(value:object|boolean|Array|string|number|null|Uint8Array|Y.Type
<dd></dd>
<b><code>map(function(T, number, YArray):M):Array&lt;M&gt;</code></b>
<dd></dd>
<b><code>clone(): Y.Array</code></b>
<dd>
Clone all values into a fresh Y.Array instance. The returned type can be
included into the Yjs document.
</dd>
<b><code>toArray():Array&lt;object|boolean|Array|string|number|null|Uint8Array|Y.Type&gt;</code></b>
<dd>Copies the content of this YArray to a new Array.</dd>
<b><code>toJSON():Array&lt;Object|boolean|Array|string|number|null&gt;</code></b>
@ -386,8 +536,6 @@ or any of its children.
<dd></dd>
<b><code>has(key:string):boolean</code></b>
<dd></dd>
<b><code>get(index:number)</code></b>
<dd></dd>
<b><code>clear()</code></b>
<dd>Removes all elements from this YMap.</dd>
<b><code>clone():Y.Map</code></b>
@ -684,6 +832,8 @@ type. Doesn't log types that have not been defined (using
<dd>Define a shared Y.Map type. Is equivalent to <code>y.get(string, Y.Map)</code>.</dd>
<b><code>getText(string):Y.Text</code></b>
<dd>Define a shared Y.Text type. Is equivalent to <code>y.get(string, Y.Text)</code>.</dd>
<b><code>getXmlElement(string, string):Y.XmlElement</code></b>
<dd>Define a shared Y.XmlElement type. Is equivalent to <code>y.get(string, Y.XmlElement)</code>.</dd>
<b><code>getXmlFragment(string):Y.XmlFragment</code></b>
<dd>Define a shared Y.XmlFragment type. Is equivalent to <code>y.get(string, Y.XmlFragment)</code>.</dd>
<b><code>on(string, function)</code></b>
@ -739,7 +889,7 @@ doc1.getArray('myarray').insert(0, ['Hello doc2, you got this?'])
doc2.getArray('myarray').get(0) // => 'Hello doc2, you got this?'
```
Yjs internally maintains a [state vector](#State-Vector) that denotes the next
Yjs internally maintains a [state vector](#state-vector) that denotes the next
expected clock from each client. In a different interpretation it holds the
number of structs created by each client. When two clients sync, you can either
exchange the complete document structure or only the differences by sending the
@ -821,7 +971,7 @@ ydoc2.getText().toString() // => "00000000000"
#### Using V2 update format
Yjs implements two update formats. By default you are using the V1 update format.
You can opt-in into the V2 update format wich provides much better compression.
You can opt-in into the V2 update format which provides much better compression.
It is not yet used by all providers. However, you can already use it if
you are building your own provider. All below functions are available with the
suffix "V2". E.g. `Y.applyUpdate``Y.applyUpdateV2`. Also when listening to updates
@ -952,7 +1102,7 @@ encoding format for document updates. If you prefer JSON encoding, you can
simply JSON.stringify / JSON.parse the relative position instead.
</dd>
<b><code>Y.decodeRelativePosition(Uint8Array):RelativePosition</code></b>
<dd>Decode a binary-encoded relative position to a RelativePositon object.</dd>
<dd>Decode a binary-encoded relative position to a RelativePosition object.</dd>
</dl>
### Y.UndoManager
@ -1132,11 +1282,11 @@ More information about the specific implementation is available in
CRDTs that are suitable for shared text editing suffer from the fact that they
only grow in size. There are CRDTs that do not grow in size, but they do not
have the characteristics that are benificial for shared text editing (like
have the characteristics that are beneficial for shared text editing (like
intention preservation). Yjs implements many improvements to the original
algorithm that diminish the trade-off that the document only grows in size. We
can't garbage collect deleted structs (tombstones) while ensuring a unique
order of the structs. But we can 1. merge preceeding structs into a single
order of the structs. But we can 1. merge preceding structs into a single
struct to reduce the amount of meta information, 2. we can delete content from
the struct if it is deleted, and 3. we can garbage collect tombstones if we
don't care about the order of the structs anymore (e.g. if the parent was

142
funding.json Normal file
View File

@ -0,0 +1,142 @@
{
"version": "v1.0.0",
"entity": {
"type": "group",
"role": "steward",
"name": "Kevin Jahns",
"email": "kevin.jahns@protonmail.com",
"phone": "",
"description": "OSS Developer",
"webpageUrl": {
"url": "https://github.com/yjs"
}
},
"projects": [
{
"guid": "yjs",
"name": "Yjs",
"description": "A library for building collaborative applications. #p2p #local-first #CRDT Funding this project will also enable me to maintain the other Yjs-related technologies.",
"webpageUrl": {
"url": "https://github.com/yjs/yjs"
},
"repositoryUrl": {
"url": "https://github.com/yjs/yjs"
},
"licenses": [
"spdx:MIT"
],
"tags": [
"collaboration",
"p2p",
"CRDT",
"rich-text",
"real-time"
]
},
{
"guid": "Titanic",
"name": "Y/Titanic",
"description": "A provider for syncing millions of docs efficiently with other peers. This will become the foundation for building real local-first apps with Yjs.",
"webpageUrl": {
"url": "https://github.com/yjs/titanic",
"wellKnown": "https://github.com/yjs/titanic/blob/main/.well-known/funding-manifest-urls"
},
"repositoryUrl": {
"url": "https://github.com/yjs/titanic",
"wellKnown": "https://github.com/yjs/titanic/blob/main/.well-known/funding-manifest-urls"
},
"licenses": [
"spdx:MIT"
],
"tags": [
"privacy",
"collaboration",
"p2p",
"CRDT",
"rich-text",
"real-time",
"web-development"
]
}
],
"funding": {
"channels": [
{
"guid": "github-sponsors",
"type": "payment-provider",
"address": "",
"description": "For funding of the Yjs project"
},
{
"guid": "y-collective",
"type": "payment-provider",
"address": "https://opencollective.com/y-collective",
"description": "For funding the Y-CRDT - the Rust implementation of Yjs and other listed projects."
}
],
"plans": [
{
"guid": "supporter",
"status": "active",
"name": "Supporter",
"description": "",
"amount": 0,
"currency": "USD",
"frequency": "monthly",
"channels": [
"github-sponsors",
"y-collective"
]
},
{
"guid": "titanic-funding",
"status": "active",
"name": "Titanic Funding",
"description": "Fund the next generation of local-first providers.",
"amount": 30000,
"currency": "USD",
"frequency": "one-time",
"channels": [
"github-sponsors"
]
},
{
"guid": "bronze-sponsor",
"status": "active",
"name": "Bronze Sponsor",
"description": "This is the recommended plan for companies that use Yjs.",
"amount": 500,
"currency": "USD",
"frequency": "monthly",
"channels": [
"github-sponsors"
]
},
{
"guid": "silver-sponsor",
"status": "active",
"name": "Silver Sponsor",
"description": "This is the recommended plan for large/successfull companies that use Yjs.",
"amount": 1000,
"currency": "USD",
"frequency": "monthly",
"channels": [
"github-sponsors"
]
},
{
"guid": "gold-sponsor",
"status": "active",
"name": "Gold Sponsor",
"description": "This is the recommended plan for successful companies that build their entire product around Yjs-related technologies.",
"amount": 3000,
"currency": "USD",
"frequency": "monthly",
"channels": [
"github-sponsors"
]
}
],
"history": null
}
}

1750
package-lock.json generated

File diff suppressed because it is too large Load Diff

View File

@ -1,6 +1,6 @@
{
"name": "yjs",
"version": "13.6.9",
"version": "13.6.24",
"description": "Shared Editing Library",
"main": "./dist/yjs.cjs",
"module": "./dist/yjs.mjs",
@ -12,9 +12,10 @@
"url": "https://github.com/sponsors/dmonad"
},
"scripts": {
"test": "npm run dist && node ./dist/tests.cjs --repetition-time 50",
"clean": "rm -rf dist docs",
"test": "npm run dist && NODE_ENV=development node ./dist/tests.cjs --repetition-time 50",
"test-extensive": "npm run lint && npm run dist && node ./dist/tests.cjs --production --repetition-time 10000",
"dist": "rm -rf dist && rollup -c && tsc",
"dist": "npm run clean && rollup -c && tsc",
"watch": "rollup -wc",
"lint": "markdownlint README.md && standard && tsc",
"docs": "rm -rf docs; jsdoc --configure ./.jsdoc.json --verbose --readme ./README.md --package ./package.json || true",
@ -75,7 +76,7 @@
},
"homepage": "https://docs.yjs.dev",
"dependencies": {
"lib0": "^0.2.86"
"lib0": "^0.2.99"
},
"devDependencies": {
"@rollup/plugin-commonjs": "^24.0.1",
@ -84,7 +85,7 @@
"concurrently": "^3.6.1",
"http-server": "^0.12.3",
"jsdoc": "^3.6.7",
"markdownlint-cli": "^0.23.2",
"markdownlint-cli": "^0.41.0",
"rollup": "^3.20.0",
"standard": "^16.0.4",
"tui-jsdoc-template": "^1.2.2",

View File

@ -50,8 +50,11 @@ export {
findRootTypeKey,
findIndexSS,
getItem,
getItemCleanStart,
getItemCleanEnd,
typeListToArraySnapshot,
typeMapGetSnapshot,
typeMapGetAllSnapshot,
createDocFromSnapshot,
iterateDeletedStructs,
applyUpdate,
@ -99,6 +102,7 @@ export {
UpdateDecoderV1,
UpdateDecoderV2,
equalDeleteSets,
mergeDeleteSets,
snapshotContainsUpdate
} from './internals.js'

View File

@ -1,4 +1,3 @@
export * from './utils/AbstractConnector.js'
export * from './utils/DeleteSet.js'
export * from './utils/Doc.js'

View File

@ -1,4 +1,3 @@
import {
UpdateEncoderV1, UpdateEncoderV2, ID, Transaction // eslint-disable-line
} from '../internals.js'
@ -27,7 +26,7 @@ export class AbstractStruct {
* This method is already assuming that `this.id.clock + this.length === this.id.clock`.
* Also this method does *not* remove right from StructStore!
* @param {AbstractStruct} right
* @return {boolean} wether this merged with right
* @return {boolean} whether this merged with right
*/
mergeWith (right) {
return false

View File

@ -2,6 +2,11 @@ import {
UpdateEncoderV1, UpdateEncoderV2, UpdateDecoderV1, UpdateDecoderV2, Transaction, Item, StructStore // eslint-disable-line
} from '../internals.js'
import * as env from 'lib0/environment'
import * as object from 'lib0/object'
const isDevMode = env.getVariable('node_env') === 'development'
export class ContentAny {
/**
* @param {Array<any>} arr
@ -11,6 +16,7 @@ export class ContentAny {
* @type {Array<any>}
*/
this.arr = arr
isDevMode && object.deepFreeze(arr)
}
/**

View File

@ -1,4 +1,3 @@
import {
addToDeleteSet,
UpdateDecoderV1, UpdateDecoderV2, UpdateEncoderV1, UpdateEncoderV2, StructStore, Item, Transaction // eslint-disable-line

View File

@ -1,4 +1,3 @@
import {
Doc, UpdateDecoderV1, UpdateDecoderV2, UpdateEncoderV1, UpdateEncoderV2, StructStore, Transaction, Item // eslint-disable-line
} from '../internals.js'

View File

@ -1,4 +1,3 @@
import {
UpdateDecoderV1, UpdateDecoderV2, UpdateEncoderV1, UpdateEncoderV2, StructStore, Item, Transaction // eslint-disable-line
} from '../internals.js'

View File

@ -1,4 +1,3 @@
import {
YText, UpdateDecoderV1, UpdateDecoderV2, UpdateEncoderV1, UpdateEncoderV2, Item, StructStore, Transaction // eslint-disable-line
} from '../internals.js'

View File

@ -1,4 +1,3 @@
import {
readYArray,
readYMap,

View File

@ -1,4 +1,3 @@
import {
AbstractStruct,
addStruct,

View File

@ -1,4 +1,3 @@
import {
GC,
getState,
@ -394,8 +393,7 @@ export class Item extends AbstractStruct {
if (this.left && this.left.constructor === Item) {
this.parent = this.left.parent
this.parentSub = this.left.parentSub
}
if (this.right && this.right.constructor === Item) {
} else if (this.right && this.right.constructor === Item) {
this.parent = this.right.parent
this.parentSub = this.right.parentSub
}

View File

@ -1,4 +1,3 @@
import {
AbstractStruct,
UpdateEncoderV1, UpdateEncoderV2, StructStore, Transaction, ID // eslint-disable-line

View File

@ -1,4 +1,3 @@
import {
removeEventHandlerListener,
callEventHandlerListeners,
@ -18,6 +17,12 @@ import * as map from 'lib0/map'
import * as iterator from 'lib0/iterator'
import * as error from 'lib0/error'
import * as math from 'lib0/math'
import * as log from 'lib0/logging'
/**
* https://docs.yjs.dev/getting-started/working-with-shared-types#caveats
*/
export const warnPrematureAccess = () => { log.warn('Invalid access: Add Yjs type to a document before reading data.') }
const maxSearchMarker = 80
@ -150,11 +155,11 @@ export const findMarker = (yarray, index) => {
// }
// }
// if (marker) {
// if (window.lengthes == null) {
// window.lengthes = []
// window.getLengthes = () => window.lengthes.sort((a, b) => a - b)
// if (window.lengths == null) {
// window.lengths = []
// window.getLengths = () => window.lengths.sort((a, b) => a - b)
// }
// window.lengthes.push(marker.index - pindex)
// window.lengths.push(marker.index - pindex)
// console.log('distance', marker.index - pindex, 'len', p && p.parent.length)
// }
if (marker !== null && math.abs(marker.index - pindex) < /** @type {YText|YArray<any>} */ (p.parent).length / maxSearchMarker) {
@ -216,6 +221,7 @@ export const updateMarkerChanges = (searchMarker, index, len) => {
* @return {Array<Item>}
*/
export const getTypeChildren = t => {
t.doc ?? warnPrematureAccess()
let s = t._start
const arr = []
while (s) {
@ -317,6 +323,10 @@ export class AbstractType {
}
/**
* Makes a copy of this data type that can be included somewhere else.
*
* Note that the content is only readable _after_ it has been included somewhere in the Ydoc.
*
* @return {AbstractType<EventType>}
*/
clone () {
@ -405,6 +415,7 @@ export class AbstractType {
* @function
*/
export const typeListSlice = (type, start, end) => {
type.doc ?? warnPrematureAccess()
if (start < 0) {
start = type._length + start
}
@ -440,6 +451,7 @@ export const typeListSlice = (type, start, end) => {
* @function
*/
export const typeListToArray = type => {
type.doc ?? warnPrematureAccess()
const cs = []
let n = type._start
while (n !== null) {
@ -478,7 +490,7 @@ export const typeListToArraySnapshot = (type, snapshot) => {
}
/**
* Executes a provided function on once on overy element of this YArray.
* Executes a provided function on once on every element of this YArray.
*
* @param {AbstractType<any>} type
* @param {function(any,number,any):void} f A function to execute on every element of this YArray.
@ -489,6 +501,7 @@ export const typeListToArraySnapshot = (type, snapshot) => {
export const typeListForEach = (type, f) => {
let index = 0
let n = type._start
type.doc ?? warnPrematureAccess()
while (n !== null) {
if (n.countable && !n.deleted) {
const c = n.content.getContent()
@ -570,7 +583,7 @@ export const typeListCreateIterator = type => {
}
/**
* Executes a provided function on once on overy element of this YArray.
* Executes a provided function on once on every element of this YArray.
* Operates on a snapshotted state of the document.
*
* @param {AbstractType<any>} type
@ -603,6 +616,7 @@ export const typeListForEachSnapshot = (type, f, snapshot) => {
* @function
*/
export const typeListGet = (type, index) => {
type.doc ?? warnPrematureAccess()
const marker = findMarker(type, index)
let n = type._start
if (marker !== null) {
@ -737,7 +751,7 @@ export const typeListInsertGenerics = (transaction, parent, index, content) => {
/**
* Pushing content is special as we generally want to push after the last item. So we don't have to update
* the serach marker.
* the search marker.
*
* @param {Transaction} transaction
* @param {AbstractType<any>} parent
@ -871,6 +885,7 @@ export const typeMapSet = (transaction, parent, key, value) => {
* @function
*/
export const typeMapGet = (parent, key) => {
parent.doc ?? warnPrematureAccess()
const val = parent._map.get(key)
return val !== undefined && !val.deleted ? val.content.getContent()[val.length - 1] : undefined
}
@ -887,6 +902,7 @@ export const typeMapGetAll = (parent) => {
* @type {Object<string,any>}
*/
const res = {}
parent.doc ?? warnPrematureAccess()
parent._map.forEach((value, key) => {
if (!value.deleted) {
res[key] = value.content.getContent()[value.length - 1]
@ -904,6 +920,7 @@ export const typeMapGetAll = (parent) => {
* @function
*/
export const typeMapHas = (parent, key) => {
parent.doc ?? warnPrematureAccess()
const val = parent._map.get(key)
return val !== undefined && !val.deleted
}
@ -926,10 +943,41 @@ export const typeMapGetSnapshot = (parent, key, snapshot) => {
}
/**
* @param {Map<string,Item>} map
* @param {AbstractType<any>} parent
* @param {Snapshot} snapshot
* @return {Object<string,Object<string,any>|number|null|Array<any>|string|Uint8Array|AbstractType<any>|undefined>}
*
* @private
* @function
*/
export const typeMapGetAllSnapshot = (parent, snapshot) => {
/**
* @type {Object<string,any>}
*/
const res = {}
parent._map.forEach((value, key) => {
/**
* @type {Item|null}
*/
let v = value
while (v !== null && (!snapshot.sv.has(v.id.client) || v.id.clock >= (snapshot.sv.get(v.id.client) || 0))) {
v = v.left
}
if (v !== null && isVisible(v, snapshot)) {
res[key] = v.content.getContent()[v.length - 1]
}
})
return res
}
/**
* @param {AbstractType<any> & { _map: Map<string, Item> }} type
* @return {IterableIterator<Array<any>>}
*
* @private
* @function
*/
export const createMapIterator = map => iterator.iteratorFilter(map.entries(), /** @param {any} entry */ entry => !entry[1].deleted)
export const createMapIterator = type => {
type.doc ?? warnPrematureAccess()
return iterator.iteratorFilter(type._map.entries(), /** @param {any} entry */ entry => !entry[1].deleted)
}

View File

@ -16,6 +16,7 @@ import {
YArrayRefID,
callTypeObservers,
transact,
warnPrematureAccess,
ArraySearchMarker, UpdateDecoderV1, UpdateDecoderV2, UpdateEncoderV1, UpdateEncoderV2, Doc, Transaction, Item // eslint-disable-line
} from '../internals.js'
import { typeListSlice } from './AbstractType.js'
@ -25,16 +26,7 @@ import { typeListSlice } from './AbstractType.js'
* @template T
* @extends YEvent<YArray<T>>
*/
export class YArrayEvent extends YEvent {
/**
* @param {YArray<T>} yarray The changed type
* @param {Transaction} transaction The transaction object
*/
constructor (yarray, transaction) {
super(yarray, transaction)
this._transaction = transaction
}
}
export class YArrayEvent extends YEvent {}
/**
* A shared Array implementation.
@ -95,6 +87,10 @@ export class YArray extends AbstractType {
}
/**
* Makes a copy of this data type that can be included somewhere else.
*
* Note that the content is only readable _after_ it has been included somewhere in the Ydoc.
*
* @return {YArray<T>}
*/
clone () {
@ -109,7 +105,8 @@ export class YArray extends AbstractType {
}
get length () {
return this._prelimContent === null ? this._length : this._prelimContent.length
this.doc ?? warnPrematureAccess()
return this._length
}
/**
@ -167,9 +164,9 @@ export class YArray extends AbstractType {
}
/**
* Preppends content to this YArray.
* Prepends content to this YArray.
*
* @param {Array<T>} content Array of content to preppend.
* @param {Array<T>} content Array of content to prepend.
*/
unshift (content) {
this.insert(0, content)
@ -211,7 +208,8 @@ export class YArray extends AbstractType {
}
/**
* Transforms this YArray to a JavaScript Array.
* Returns a portion of this YArray into a JavaScript Array selected
* from start to end (end not included).
*
* @param {number} [start]
* @param {number} [end]
@ -244,7 +242,7 @@ export class YArray extends AbstractType {
}
/**
* Executes a provided function once on overy element of this YArray.
* Executes a provided function once on every element of this YArray.
*
* @param {function(T,number,YArray<T>):void} f A function to execute on every element of this YArray.
*/

View File

@ -1,4 +1,3 @@
/**
* @module YMap
*/
@ -14,6 +13,7 @@ import {
YMapRefID,
callTypeObservers,
transact,
warnPrematureAccess,
UpdateDecoderV1, UpdateDecoderV2, UpdateEncoderV1, UpdateEncoderV2, Doc, Transaction, Item // eslint-disable-line
} from '../internals.js'
@ -89,6 +89,10 @@ export class YMap extends AbstractType {
}
/**
* Makes a copy of this data type that can be included somewhere else.
*
* Note that the content is only readable _after_ it has been included somewhere in the Ydoc.
*
* @return {YMap<MapType>}
*/
clone () {
@ -118,6 +122,7 @@ export class YMap extends AbstractType {
* @return {Object<string,any>}
*/
toJSON () {
this.doc ?? warnPrematureAccess()
/**
* @type {Object<string,MapType>}
*/
@ -137,7 +142,7 @@ export class YMap extends AbstractType {
* @return {number}
*/
get size () {
return [...createMapIterator(this._map)].length
return [...createMapIterator(this)].length
}
/**
@ -146,7 +151,7 @@ export class YMap extends AbstractType {
* @return {IterableIterator<string>}
*/
keys () {
return iterator.iteratorMap(createMapIterator(this._map), /** @param {any} v */ v => v[0])
return iterator.iteratorMap(createMapIterator(this), /** @param {any} v */ v => v[0])
}
/**
@ -155,7 +160,7 @@ export class YMap extends AbstractType {
* @return {IterableIterator<MapType>}
*/
values () {
return iterator.iteratorMap(createMapIterator(this._map), /** @param {any} v */ v => v[1].content.getContent()[v[1].length - 1])
return iterator.iteratorMap(createMapIterator(this), /** @param {any} v */ v => v[1].content.getContent()[v[1].length - 1])
}
/**
@ -164,7 +169,7 @@ export class YMap extends AbstractType {
* @return {IterableIterator<[string, MapType]>}
*/
entries () {
return iterator.iteratorMap(createMapIterator(this._map), /** @param {any} v */ v => /** @type {any} */ ([v[0], v[1].content.getContent()[v[1].length - 1]]))
return iterator.iteratorMap(createMapIterator(this), /** @param {any} v */ v => /** @type {any} */ ([v[0], v[1].content.getContent()[v[1].length - 1]]))
}
/**
@ -173,6 +178,7 @@ export class YMap extends AbstractType {
* @param {function(MapType,string,YMap<MapType>):void} f A function to execute on every element of this YArray.
*/
forEach (f) {
this.doc ?? warnPrematureAccess()
this._map.forEach((item, key) => {
if (!item.deleted) {
f(item.content.getContent()[item.length - 1], key, this)

View File

@ -1,4 +1,3 @@
/**
* @module YText
*/
@ -27,6 +26,7 @@ import {
typeMapGetAll,
updateMarkerChanges,
ContentType,
warnPrematureAccess,
ArraySearchMarker, UpdateDecoderV1, UpdateDecoderV2, UpdateEncoderV1, UpdateEncoderV2, ID, Doc, Item, Snapshot, Transaction // eslint-disable-line
} from '../internals.js'
@ -118,14 +118,15 @@ const findNextPosition = (transaction, pos, count) => {
* @param {Transaction} transaction
* @param {AbstractType<any>} parent
* @param {number} index
* @param {boolean} useSearchMarker
* @return {ItemTextListPosition}
*
* @private
* @function
*/
const findPosition = (transaction, parent, index) => {
const findPosition = (transaction, parent, index, useSearchMarker) => {
const currentAttributes = new Map()
const marker = findMarker(parent, index)
const marker = useSearchMarker ? findMarker(parent, index) : null
if (marker) {
const pos = new ItemTextListPosition(marker.p.left, marker.p, marker.index, currentAttributes)
return findNextPosition(transaction, pos, index - marker.index)
@ -201,7 +202,7 @@ const minimizeAttributeChanges = (currPos, attributes) => {
while (true) {
if (currPos.right === null) {
break
} else if (currPos.right.deleted || (currPos.right.content.constructor === ContentFormat && equalAttrs(attributes[(/** @type {ContentFormat} */ (currPos.right.content)).key] || null, /** @type {ContentFormat} */ (currPos.right.content).value))) {
} else if (currPos.right.deleted || (currPos.right.content.constructor === ContentFormat && equalAttrs(attributes[(/** @type {ContentFormat} */ (currPos.right.content)).key] ?? null, /** @type {ContentFormat} */ (currPos.right.content).value))) {
//
} else {
break
@ -227,7 +228,7 @@ const insertAttributes = (transaction, parent, currPos, attributes) => {
// insert format-start items
for (const key in attributes) {
const val = attributes[key]
const currentVal = currPos.currentAttributes.get(key) || null
const currentVal = currPos.currentAttributes.get(key) ?? null
if (!equalAttrs(currentVal, val)) {
// save negated attribute (set null if currentVal undefined)
negatedAttributes.set(key, currentVal)
@ -389,12 +390,12 @@ const cleanupFormattingGap = (transaction, start, curr, startAttributes, currAtt
switch (content.constructor) {
case ContentFormat: {
const { key, value } = /** @type {ContentFormat} */ (content)
const startAttrValue = startAttributes.get(key) || null
const startAttrValue = startAttributes.get(key) ?? null
if (endFormats.get(key) !== content || startAttrValue === value) {
// Either this format is overwritten or it is not necessary because the attribute already existed.
start.delete(transaction)
cleanups++
if (!reachedCurr && (currAttributes.get(key) || null) === value && startAttrValue !== value) {
if (!reachedCurr && (currAttributes.get(key) ?? null) === value && startAttrValue !== value) {
if (startAttrValue === null) {
currAttributes.delete(key)
} else {
@ -477,7 +478,7 @@ export const cleanupYTextFormatting = type => {
}
/**
* This will be called by the transction once the event handlers are called to potentially cleanup
* This will be called by the transaction once the event handlers are called to potentially cleanup
* formatting attributes.
*
* @param {Transaction} transaction
@ -567,7 +568,7 @@ const deleteText = (transaction, currPos, length) => {
/**
* The Quill Delta format represents changes on a text document with
* formatting information. For mor information visit {@link https://quilljs.com/docs/delta/|Quill Delta}
* formatting information. For more information visit {@link https://quilljs.com/docs/delta/|Quill Delta}
*
* @example
* {
@ -769,12 +770,12 @@ export class YTextEvent extends YEvent {
const { key, value } = /** @type {ContentFormat} */ (item.content)
if (this.adds(item)) {
if (!this.deletes(item)) {
const curVal = currentAttributes.get(key) || null
const curVal = currentAttributes.get(key) ?? null
if (!equalAttrs(curVal, value)) {
if (action === 'retain') {
addOp()
}
if (equalAttrs(value, (oldAttributes.get(key) || null))) {
if (equalAttrs(value, (oldAttributes.get(key) ?? null))) {
delete attributes[key]
} else {
attributes[key] = value
@ -785,7 +786,7 @@ export class YTextEvent extends YEvent {
}
} else if (this.deletes(item)) {
oldAttributes.set(key, value)
const curVal = currentAttributes.get(key) || null
const curVal = currentAttributes.get(key) ?? null
if (!equalAttrs(curVal, value)) {
if (action === 'retain') {
addOp()
@ -875,6 +876,7 @@ export class YText extends AbstractType {
* @type {number}
*/
get length () {
this.doc ?? warnPrematureAccess()
return this._length
}
@ -897,6 +899,10 @@ export class YText extends AbstractType {
}
/**
* Makes a copy of this data type that can be included somewhere else.
*
* Note that the content is only readable _after_ it has been included somewhere in the Ydoc.
*
* @return {YText}
*/
clone () {
@ -927,6 +933,7 @@ export class YText extends AbstractType {
* @public
*/
toString () {
this.doc ?? warnPrematureAccess()
let str = ''
/**
* @type {Item|null}
@ -954,7 +961,7 @@ export class YText extends AbstractType {
/**
* Apply a {@link Delta} on this shared YText type.
*
* @param {any} delta The changes to apply on this element.
* @param {Array<any>} delta The changes to apply on this element.
* @param {object} opts
* @param {boolean} [opts.sanitize] Sanitize input delta. Removes ending newlines if set to true.
*
@ -1000,6 +1007,7 @@ export class YText extends AbstractType {
* @public
*/
toDelta (snapshot, prevSnapshot, computeYChange) {
this.doc ?? warnPrematureAccess()
/**
* @type{Array<any>}
*/
@ -1120,7 +1128,7 @@ export class YText extends AbstractType {
const y = this.doc
if (y !== null) {
transact(y, transaction => {
const pos = findPosition(transaction, this, index)
const pos = findPosition(transaction, this, index, !attributes)
if (!attributes) {
attributes = {}
// @ts-ignore
@ -1138,20 +1146,20 @@ export class YText extends AbstractType {
*
* @param {number} index The index to insert the embed at.
* @param {Object | AbstractType<any>} embed The Object that represents the embed.
* @param {TextAttributes} attributes Attribute information to apply on the
* @param {TextAttributes} [attributes] Attribute information to apply on the
* embed
*
* @public
*/
insertEmbed (index, embed, attributes = {}) {
insertEmbed (index, embed, attributes) {
const y = this.doc
if (y !== null) {
transact(y, transaction => {
const pos = findPosition(transaction, this, index)
insertText(transaction, this, pos, embed, attributes)
const pos = findPosition(transaction, this, index, !attributes)
insertText(transaction, this, pos, embed, attributes || {})
})
} else {
/** @type {Array<function>} */ (this._pending).push(() => this.insertEmbed(index, embed, attributes))
/** @type {Array<function>} */ (this._pending).push(() => this.insertEmbed(index, embed, attributes || {}))
}
}
@ -1170,7 +1178,7 @@ export class YText extends AbstractType {
const y = this.doc
if (y !== null) {
transact(y, transaction => {
deleteText(transaction, findPosition(transaction, this, index), length)
deleteText(transaction, findPosition(transaction, this, index, true), length)
})
} else {
/** @type {Array<function>} */ (this._pending).push(() => this.delete(index, length))
@ -1194,7 +1202,7 @@ export class YText extends AbstractType {
const y = this.doc
if (y !== null) {
transact(y, transaction => {
const pos = findPosition(transaction, this, index)
const pos = findPosition(transaction, this, index, false)
if (pos.right === null) {
return
}

View File

@ -8,9 +8,10 @@ import {
typeMapSet,
typeMapGet,
typeMapGetAll,
typeMapGetAllSnapshot,
typeListForEach,
YXmlElementRefID,
YXmlText, ContentType, AbstractType, UpdateDecoderV1, UpdateDecoderV2, UpdateEncoderV1, UpdateEncoderV2, Doc, Item // eslint-disable-line
Snapshot, YXmlText, ContentType, AbstractType, UpdateDecoderV1, UpdateDecoderV2, UpdateEncoderV1, UpdateEncoderV2, Doc, Item // eslint-disable-line
} from '../internals.js'
/**
@ -19,7 +20,7 @@ import {
/**
* An YXmlElement imitates the behavior of a
* {@link https://developer.mozilla.org/en-US/docs/Web/API/Element|Dom Element}.
* https://developer.mozilla.org/en-US/docs/Web/API/Element|Dom Element
*
* * An YXmlElement has attributes (key value pairs)
* * An YXmlElement has childElements that must inherit from YXmlElement
@ -80,6 +81,10 @@ export class YXmlElement extends YXmlFragment {
}
/**
* Makes a copy of this data type that can be included somewhere else.
*
* Note that the content is only readable _after_ it has been included somewhere in the Ydoc.
*
* @return {YXmlElement<KV>}
*/
clone () {
@ -192,12 +197,13 @@ export class YXmlElement extends YXmlFragment {
/**
* Returns all attribute name/value pairs in a JSON Object.
*
* @param {Snapshot} [snapshot]
* @return {{ [Key in Extract<keyof KV,string>]?: KV[Key]}} A JSON Object that describes the attributes.
*
* @public
*/
getAttributes () {
return /** @type {any} */ (typeMapGetAll(this))
getAttributes (snapshot) {
return /** @type {any} */ (snapshot ? typeMapGetAllSnapshot(this, snapshot) : typeMapGetAll(this))
}
/**

View File

@ -1,4 +1,3 @@
import {
YEvent,
YXmlText, YXmlElement, YXmlFragment, Transaction // eslint-disable-line
@ -13,7 +12,7 @@ export class YXmlEvent extends YEvent {
* @param {YXmlElement|YXmlText|YXmlFragment} target The target on which the event is created.
* @param {Set<string|null>} subs The set of changed attributes. `null` is included if the
* child list changed.
* @param {Transaction} transaction The transaction instance with wich the
* @param {Transaction} transaction The transaction instance with which the
* change was created.
*/
constructor (target, subs, transaction) {

View File

@ -17,6 +17,7 @@ import {
transact,
typeListGet,
typeListSlice,
warnPrematureAccess,
UpdateDecoderV1, UpdateDecoderV2, UpdateEncoderV1, UpdateEncoderV2, Doc, ContentType, Transaction, Item, YXmlText, YXmlHook // eslint-disable-line
} from '../internals.js'
@ -66,6 +67,7 @@ export class YXmlTreeWalker {
*/
this._currentNode = /** @type {Item} */ (root._start)
this._firstCall = true
root.doc ?? warnPrematureAccess()
}
[Symbol.iterator] () {
@ -94,8 +96,12 @@ export class YXmlTreeWalker {
} else {
// walk right or up in the tree
while (n !== null) {
if (n.right !== null) {
n = n.right
/**
* @type {Item | null}
*/
const nxt = n.next
if (nxt !== null) {
n = nxt
break
} else if (n.parent === this._root) {
n = null
@ -163,6 +169,10 @@ export class YXmlFragment extends AbstractType {
}
/**
* Makes a copy of this data type that can be included somewhere else.
*
* Note that the content is only readable _after_ it has been included somewhere in the Ydoc.
*
* @return {YXmlFragment}
*/
clone () {
@ -173,6 +183,7 @@ export class YXmlFragment extends AbstractType {
}
get length () {
this.doc ?? warnPrematureAccess()
return this._prelimContent === null ? this._length : this._prelimContent.length
}
@ -376,9 +387,9 @@ export class YXmlFragment extends AbstractType {
}
/**
* Preppends content to this YArray.
* Prepends content to this YArray.
*
* @param {Array<YXmlElement|YXmlText>} content Array of content to preppend.
* @param {Array<YXmlElement|YXmlText>} content Array of content to prepend.
*/
unshift (content) {
this.insert(0, content)
@ -395,7 +406,8 @@ export class YXmlFragment extends AbstractType {
}
/**
* Transforms this YArray to a JavaScript Array.
* Returns a portion of this YXmlFragment into a JavaScript Array selected
* from start to end (end not included).
*
* @param {number} [start]
* @param {number} [end]
@ -406,7 +418,7 @@ export class YXmlFragment extends AbstractType {
}
/**
* Executes a provided function on once on overy child element.
* Executes a provided function on once on every child element.
*
* @param {function(YXmlElement|YXmlText,number, typeof self):void} f A function to execute on every element of this YArray.
*/

View File

@ -1,4 +1,3 @@
import {
YMap,
YXmlHookRefID,
@ -30,6 +29,10 @@ export class YXmlHook extends YMap {
}
/**
* Makes a copy of this data type that can be included somewhere else.
*
* Note that the content is only readable _after_ it has been included somewhere in the Ydoc.
*
* @return {YXmlHook}
*/
clone () {

View File

@ -1,4 +1,3 @@
import {
YText,
YXmlTextRefID,
@ -31,6 +30,10 @@ export class YXmlText extends YText {
}
/**
* Makes a copy of this data type that can be included somewhere else.
*
* Note that the content is only readable _after_ it has been included somewhere in the Ydoc.
*
* @return {YXmlText}
*/
clone () {

View File

@ -1,5 +1,4 @@
import { Observable } from 'lib0/observable'
import { ObservableV2 } from 'lib0/observable'
import {
Doc // eslint-disable-line
@ -11,9 +10,9 @@ import {
* @note This interface is experimental and it is not advised to actually inherit this class.
* It just serves as typing information.
*
* @extends {Observable<any>}
* @extends {ObservableV2<any>}
*/
export class AbstractConnector extends Observable {
export class AbstractConnector extends ObservableV2 {
/**
* @param {Doc} ydoc
* @param {any} awareness

View File

@ -1,4 +1,3 @@
import {
findIndexSS,
getState,

View File

@ -8,12 +8,13 @@ import {
YArray,
YText,
YMap,
YXmlElement,
YXmlFragment,
transact,
ContentDoc, Item, Transaction, YEvent // eslint-disable-line
} from '../internals.js'
import { Observable } from 'lib0/observable'
import { ObservableV2 } from 'lib0/observable'
import * as random from 'lib0/random'
import * as map from 'lib0/map'
import * as array from 'lib0/array'
@ -33,10 +34,26 @@ export const generateNewClientId = random.uint32
*/
/**
* A Yjs instance handles the state of shared data.
* @extends Observable<string>
* @typedef {Object} DocEvents
* @property {function(Doc):void} DocEvents.destroy
* @property {function(Doc):void} DocEvents.load
* @property {function(boolean, Doc):void} DocEvents.sync
* @property {function(Uint8Array, any, Doc, Transaction):void} DocEvents.update
* @property {function(Uint8Array, any, Doc, Transaction):void} DocEvents.updateV2
* @property {function(Doc):void} DocEvents.beforeAllTransactions
* @property {function(Transaction, Doc):void} DocEvents.beforeTransaction
* @property {function(Transaction, Doc):void} DocEvents.beforeObserverCalls
* @property {function(Transaction, Doc):void} DocEvents.afterTransaction
* @property {function(Transaction, Doc):void} DocEvents.afterTransactionCleanup
* @property {function(Doc, Array<Transaction>):void} DocEvents.afterAllTransactions
* @property {function({ loaded: Set<Doc>, added: Set<Doc>, removed: Set<Doc> }, Doc, Transaction):void} DocEvents.subdocs
*/
export class Doc extends Observable {
/**
* A Yjs instance handles the state of shared data.
* @extends ObservableV2<DocEvents>
*/
export class Doc extends ObservableV2 {
/**
* @param {DocOpts} opts configuration
*/
@ -87,8 +104,9 @@ export class Doc extends Observable {
* lost (with false as a parameter).
*/
this.isSynced = false
this.isDestroyed = false
/**
* Promise that resolves once the document has been loaded from a presistence provider.
* Promise that resolves once the document has been loaded from a persistence provider.
*/
this.whenLoaded = promise.create(resolve => {
this.on('load', () => {
@ -114,7 +132,7 @@ export class Doc extends Observable {
}
this.isSynced = isSynced === undefined || isSynced === true
if (this.isSynced && !this.isLoaded) {
this.emit('load', [])
this.emit('load', [this])
}
})
/**
@ -170,30 +188,31 @@ export class Doc extends Observable {
/**
* Define a shared data type.
*
* Multiple calls of `y.get(name, TypeConstructor)` yield the same result
* Multiple calls of `ydoc.get(name, TypeConstructor)` yield the same result
* and do not overwrite each other. I.e.
* `y.define(name, Y.Array) === y.define(name, Y.Array)`
* `ydoc.get(name, Y.Array) === ydoc.get(name, Y.Array)`
*
* After this method is called, the type is also available on `y.share.get(name)`.
* After this method is called, the type is also available on `ydoc.share.get(name)`.
*
* *Best Practices:*
* Define all types right after the Yjs instance is created and store them in a separate object.
* Define all types right after the Y.Doc instance is created and store them in a separate object.
* Also use the typed methods `getText(name)`, `getArray(name)`, ..
*
* @template {typeof AbstractType<any>} Type
* @example
* const y = new Y(..)
* const ydoc = new Y.Doc(..)
* const appState = {
* document: y.getText('document')
* comments: y.getArray('comments')
* document: ydoc.getText('document')
* comments: ydoc.getArray('comments')
* }
*
* @param {string} name
* @param {Function} TypeConstructor The constructor of the type definition. E.g. Y.Text, Y.Array, Y.Map, ...
* @return {AbstractType<any>} The created type. Constructed with TypeConstructor
* @param {Type} TypeConstructor The constructor of the type definition. E.g. Y.Text, Y.Array, Y.Map, ...
* @return {InstanceType<Type>} The created type. Constructed with TypeConstructor
*
* @public
*/
get (name, TypeConstructor = AbstractType) {
get (name, TypeConstructor = /** @type {any} */ (AbstractType)) {
const type = map.setIfUndefined(this.share, name, () => {
// @ts-ignore
const t = new TypeConstructor()
@ -219,12 +238,12 @@ export class Doc extends Observable {
t._length = type._length
this.share.set(name, t)
t._integrate(this, null)
return t
return /** @type {InstanceType<Type>} */ (t)
} else {
throw new Error(`Type with the name ${name} has already been defined with a different constructor`)
}
}
return type
return /** @type {InstanceType<Type>} */ (type)
}
/**
@ -235,8 +254,7 @@ export class Doc extends Observable {
* @public
*/
getArray (name = '') {
// @ts-ignore
return this.get(name, YArray)
return /** @type {YArray<T>} */ (this.get(name, YArray))
}
/**
@ -246,7 +264,6 @@ export class Doc extends Observable {
* @public
*/
getText (name = '') {
// @ts-ignore
return this.get(name, YText)
}
@ -258,8 +275,17 @@ export class Doc extends Observable {
* @public
*/
getMap (name = '') {
// @ts-ignore
return this.get(name, YMap)
return /** @type {YMap<T>} */ (this.get(name, YMap))
}
/**
* @param {string} [name]
* @return {YXmlElement}
*
* @public
*/
getXmlElement (name = '') {
return /** @type {YXmlElement<{[key:string]:string}>} */ (this.get(name, YXmlElement))
}
/**
@ -269,7 +295,6 @@ export class Doc extends Observable {
* @public
*/
getXmlFragment (name = '') {
// @ts-ignore
return this.get(name, YXmlFragment)
}
@ -298,6 +323,7 @@ export class Doc extends Observable {
* Emit `destroy` event and unregister all event handlers.
*/
destroy () {
this.isDestroyed = true
array.from(this.subdocs).forEach(subdoc => subdoc.destroy())
const item = this._item
if (item !== null) {
@ -313,24 +339,9 @@ export class Doc extends Observable {
transaction.subdocsRemoved.add(this)
}, null, true)
}
this.emit('destroyed', [true])
// @ts-ignore
this.emit('destroyed', [true]) // DEPRECATED!
this.emit('destroy', [this])
super.destroy()
}
/**
* @param {string} eventName
* @param {function(...any):any} f
*/
on (eventName, f) {
super.on(eventName, f)
}
/**
* @param {string} eventName
* @param {function} f
*/
off (eventName, f) {
super.off(eventName, f)
}
}

View File

@ -1,4 +1,3 @@
import { AbstractType } from '../internals.js' // eslint-disable-line
import * as decoding from 'lib0/decoding'

View File

@ -1,4 +1,3 @@
import {
YArray,
YMap,
@ -63,7 +62,7 @@ export class PermanentUserData {
initUser(storeType.get(userDescription), userDescription)
)
})
// add intial data
// add initial data
storeType.forEach(initUser)
}

View File

@ -1,4 +1,3 @@
import {
writeID,
readID,
@ -9,7 +8,8 @@ import {
createID,
ContentType,
followRedone,
ID, Doc, AbstractType // eslint-disable-line
getItem,
StructStore, ID, Doc, AbstractType, // eslint-disable-line
} from '../internals.js'
import * as encoding from 'lib0/encoding'
@ -66,7 +66,7 @@ export class RelativePosition {
* after the meant position.
* I.e. position 1 in 'ab' is associated to character 'b'.
*
* If assoc < 0, then the relative position is associated to the caharacter
* If assoc < 0, then the relative position is associated to the character
* before the meant position.
*
* @type {number}
@ -102,7 +102,7 @@ export const relativePositionToJSON = rpos => {
*
* @function
*/
export const createRelativePositionFromJSON = json => new RelativePosition(json.type == null ? null : createID(json.type.client, json.type.clock), json.tname || null, json.item == null ? null : createID(json.item.client, json.item.clock), json.assoc == null ? 0 : json.assoc)
export const createRelativePositionFromJSON = json => new RelativePosition(json.type == null ? null : createID(json.type.client, json.type.clock), json.tname ?? null, json.item == null ? null : createID(json.item.client, json.item.clock), json.assoc == null ? 0 : json.assoc)
export class AbsolutePosition {
/**
@ -257,13 +257,36 @@ export const readRelativePosition = decoder => {
export const decodeRelativePosition = uint8Array => readRelativePosition(decoding.createDecoder(uint8Array))
/**
* @param {StructStore} store
* @param {ID} id
*/
const getItemWithOffset = (store, id) => {
const item = getItem(store, id)
const diff = id.clock - item.id.clock
return {
item, diff
}
}
/**
* Transform a relative position to an absolute position.
*
* If you want to share the relative position with other users, you should set
* `followUndoneDeletions` to false to get consistent results across all clients.
*
* When calculating the absolute position, we try to follow the "undone deletions". This yields
* better results for the user who performed undo. However, only the user who performed the undo
* will get the better results, the other users don't know which operations recreated a deleted
* range of content. There is more information in this ticket: https://github.com/yjs/yjs/issues/638
*
* @param {RelativePosition} rpos
* @param {Doc} doc
* @param {boolean} followUndoneDeletions - whether to follow undone deletions - see https://github.com/yjs/yjs/issues/638
* @return {AbsolutePosition|null}
*
* @function
*/
export const createAbsolutePositionFromRelativePosition = (rpos, doc) => {
export const createAbsolutePositionFromRelativePosition = (rpos, doc, followUndoneDeletions = true) => {
const store = doc.store
const rightID = rpos.item
const typeID = rpos.type
@ -275,7 +298,7 @@ export const createAbsolutePositionFromRelativePosition = (rpos, doc) => {
if (getState(store, rightID.client) <= rightID.clock) {
return null
}
const res = followRedone(store, rightID)
const res = followUndoneDeletions ? followRedone(store, rightID) : getItemWithOffset(store, rightID)
const right = res.item
if (!(right instanceof Item)) {
return null
@ -299,7 +322,7 @@ export const createAbsolutePositionFromRelativePosition = (rpos, doc) => {
// type does not exist yet
return null
}
const { item } = followRedone(store, typeID)
const { item } = followUndoneDeletions ? followRedone(store, typeID) : { item: getItem(store, typeID) }
if (item instanceof Item && item.content instanceof ContentType) {
type = item.content.type
} else {

View File

@ -1,4 +1,3 @@
import {
isDeleted,
createDeleteSetFromStructStore,

View File

@ -1,4 +1,3 @@
import {
GC,
splitItem,
@ -67,13 +66,13 @@ export const getState = (store, client) => {
* @private
* @function
*/
export const integretyCheck = store => {
export const integrityCheck = store => {
store.clients.forEach(structs => {
for (let i = 1; i < structs.length; i++) {
const l = structs[i - 1]
const r = structs[i]
if (l.id.clock + l.length !== r.id.clock) {
throw new Error('StructStore failed integrety check')
throw new Error('StructStore failed integrity check')
}
}
})

View File

@ -1,4 +1,3 @@
import {
getState,
writeStructsFromTransaction,
@ -29,7 +28,8 @@ import { callAll } from 'lib0/function'
* possible. Here is an example to illustrate the advantages of bundling:
*
* @example
* const map = y.define('map', YMap)
* const ydoc = new Y.Doc()
* const map = ydoc.getMap('map')
* // Log content when change is triggered
* map.observe(() => {
* console.log('change triggered')
@ -38,7 +38,7 @@ import { callAll } from 'lib0/function'
* map.set('a', 0) // => "change triggered"
* map.set('b', 0) // => "change triggered"
* // When put in a transaction, it will trigger the log after the transaction:
* y.transact(() => {
* ydoc.transact(() => {
* map.set('a', 1)
* map.set('b', 1)
* }) // => "change triggered"
@ -225,7 +225,7 @@ const tryGcDeleteSet = (ds, store, gcFilter) => {
*/
const tryMergeDeleteSet = (ds, store) => {
// try to merge deleted / gc'd items
// merge from right to left for better efficiecy and so we don't miss any merge targets
// merge from right to left for better efficiency and so we don't miss any merge targets
ds.clients.forEach((deleteItems, client) => {
const structs = /** @type {Array<GC|Item>} */ (store.clients.get(client))
for (let di = deleteItems.length - 1; di >= 0; di--) {

View File

@ -10,13 +10,13 @@ import {
getItemCleanStart,
isDeleted,
addToDeleteSet,
Transaction, Doc, Item, GC, DeleteSet, AbstractType // eslint-disable-line
YEvent, Transaction, Doc, Item, GC, DeleteSet, AbstractType // eslint-disable-line
} from '../internals.js'
import * as time from 'lib0/time'
import * as array from 'lib0/array'
import * as logging from 'lib0/logging'
import { Observable } from 'lib0/observable'
import { ObservableV2 } from 'lib0/observable'
export class StackItem {
/**
@ -39,7 +39,7 @@ export class StackItem {
*/
const clearUndoManagerStackItem = (tr, um, stackItem) => {
iterateDeletedStructs(tr, stackItem.deletions, item => {
if (item instanceof Item && um.scope.some(type => isParentOf(type, item))) {
if (item instanceof Item && um.scope.some(type => type === tr.doc || isParentOf(/** @type {AbstractType<any>} */ (type), item))) {
keepItem(item, false)
}
})
@ -48,15 +48,10 @@ const clearUndoManagerStackItem = (tr, um, stackItem) => {
/**
* @param {UndoManager} undoManager
* @param {Array<StackItem>} stack
* @param {string} eventType
* @param {'undo'|'redo'} eventType
* @return {StackItem?}
*/
const popStackItem = (undoManager, stack, eventType) => {
/**
* Whether a change happened
* @type {StackItem?}
*/
let result = null
/**
* Keep a reference to the transaction so we can fire the event with the changedParentTypes
* @type {any}
@ -65,7 +60,7 @@ const popStackItem = (undoManager, stack, eventType) => {
const doc = undoManager.doc
const scope = undoManager.scope
transact(doc, transaction => {
while (stack.length > 0 && result === null) {
while (stack.length > 0 && undoManager.currStackItem === null) {
const store = doc.store
const stackItem = /** @type {StackItem} */ (stack.pop())
/**
@ -86,7 +81,7 @@ const popStackItem = (undoManager, stack, eventType) => {
}
struct = item
}
if (!struct.deleted && scope.some(type => isParentOf(type, /** @type {Item} */ (struct)))) {
if (!struct.deleted && scope.some(type => type === transaction.doc || isParentOf(/** @type {AbstractType<any>} */ (type), /** @type {Item} */ (struct)))) {
itemsToDelete.push(struct)
}
}
@ -94,7 +89,7 @@ const popStackItem = (undoManager, stack, eventType) => {
iterateDeletedStructs(transaction, stackItem.deletions, struct => {
if (
struct instanceof Item &&
scope.some(type => isParentOf(type, struct)) &&
scope.some(type => type === transaction.doc || isParentOf(/** @type {AbstractType<any>} */ (type), struct)) &&
// Never redo structs in stackItem.insertions because they were created and deleted in the same capture interval.
!isDeleted(stackItem.insertions, struct.id)
) {
@ -113,7 +108,7 @@ const popStackItem = (undoManager, stack, eventType) => {
performedChange = true
}
}
result = performedChange ? stackItem : null
undoManager.currStackItem = performedChange ? stackItem : null
}
transaction.changed.forEach((subProps, type) => {
// destroy search marker if necessary
@ -123,11 +118,13 @@ const popStackItem = (undoManager, stack, eventType) => {
})
_tr = transaction
}, undoManager)
if (result != null) {
const res = undoManager.currStackItem
if (res != null) {
const changedParentTypes = _tr.changedParentTypes
undoManager.emit('stack-item-popped', [{ stackItem: result, type: eventType, changedParentTypes }, undoManager])
undoManager.emit('stack-item-popped', [{ stackItem: res, type: eventType, changedParentTypes, origin: undoManager }, undoManager])
undoManager.currStackItem = null
}
return result
return res
}
/**
@ -143,6 +140,14 @@ const popStackItem = (undoManager, stack, eventType) => {
* @property {Doc} [doc] The document that this UndoManager operates on. Only needed if typeScope is empty.
*/
/**
* @typedef {Object} StackItemEvent
* @property {StackItem} StackItemEvent.stackItem
* @property {any} StackItemEvent.origin
* @property {'undo'|'redo'} StackItemEvent.type
* @property {Map<AbstractType<YEvent<any>>,Array<YEvent<any>>>} StackItemEvent.changedParentTypes
*/
/**
* Fires 'stack-item-added' event when a stack item was added to either the undo- or
* the redo-stack. You may store additional stack information via the
@ -150,11 +155,11 @@ const popStackItem = (undoManager, stack, eventType) => {
* Fires 'stack-item-popped' event when a stack item was popped from either the
* undo- or the redo-stack. You may restore the saved stack information from `event.stackItem.meta`.
*
* @extends {Observable<'stack-item-added'|'stack-item-popped'|'stack-cleared'|'stack-item-updated'>}
* @extends {ObservableV2<{'stack-item-added':function(StackItemEvent, UndoManager):void, 'stack-item-popped': function(StackItemEvent, UndoManager):void, 'stack-cleared': function({ undoStackCleared: boolean, redoStackCleared: boolean }):void, 'stack-item-updated': function(StackItemEvent, UndoManager):void }>}
*/
export class UndoManager extends Observable {
export class UndoManager extends ObservableV2 {
/**
* @param {AbstractType<any>|Array<AbstractType<any>>} typeScope Accepts either a single type, or an array of types
* @param {Doc|AbstractType<any>|Array<AbstractType<any>>} typeScope Limits the scope of the UndoManager. If this is set to a ydoc instance, all changes on that ydoc will be undone. If set to a specific type, only changes on that type or its children will be undone. Also accepts an array of types.
* @param {UndoManagerOptions} options
*/
constructor (typeScope, {
@ -163,11 +168,11 @@ export class UndoManager extends Observable {
deleteFilter = () => true,
trackedOrigins = new Set([null]),
ignoreRemoteMapChanges = false,
doc = /** @type {Doc} */ (array.isArray(typeScope) ? typeScope[0].doc : typeScope.doc)
doc = /** @type {Doc} */ (array.isArray(typeScope) ? typeScope[0].doc : typeScope instanceof Doc ? typeScope : typeScope.doc)
} = {}) {
super()
/**
* @type {Array<AbstractType<any>>}
* @type {Array<AbstractType<any> | Doc>}
*/
this.scope = []
this.doc = doc
@ -191,6 +196,12 @@ export class UndoManager extends Observable {
*/
this.undoing = false
this.redoing = false
/**
* The currently popped stack item if UndoManager.undoing or UndoManager.redoing
*
* @type {StackItem|null}
*/
this.currStackItem = null
this.lastChange = 0
this.ignoreRemoteMapChanges = ignoreRemoteMapChanges
this.captureTimeout = captureTimeout
@ -201,7 +212,7 @@ export class UndoManager extends Observable {
// Only track certain transactions
if (
!this.captureTransaction(transaction) ||
!this.scope.some(type => transaction.changedParentTypes.has(type)) ||
!this.scope.some(type => transaction.changedParentTypes.has(/** @type {AbstractType<any>} */ (type)) || type === this.doc) ||
(!this.trackedOrigins.has(transaction.origin) && (!transaction.origin || !this.trackedOrigins.has(transaction.origin.constructor)))
) {
return
@ -240,10 +251,13 @@ export class UndoManager extends Observable {
}
// make sure that deleted structs are not gc'd
iterateDeletedStructs(transaction, transaction.deleteSet, /** @param {Item|GC} item */ item => {
if (item instanceof Item && this.scope.some(type => isParentOf(type, item))) {
if (item instanceof Item && this.scope.some(type => type === transaction.doc || isParentOf(/** @type {AbstractType<any>} */ (type), item))) {
keepItem(item, true)
}
})
/**
* @type {[StackItemEvent, UndoManager]}
*/
const changeEvent = [{ stackItem: stack[stack.length - 1], origin: transaction.origin, type: undoing ? 'redo' : 'undo', changedParentTypes: transaction.changedParentTypes }, this]
if (didAdd) {
this.emit('stack-item-added', changeEvent)
@ -258,13 +272,17 @@ export class UndoManager extends Observable {
}
/**
* @param {Array<AbstractType<any>> | AbstractType<any>} ytypes
* Extend the scope.
*
* @param {Array<AbstractType<any> | Doc> | AbstractType<any> | Doc} ytypes
*/
addToScope (ytypes) {
const tmpSet = new Set(this.scope)
ytypes = array.isArray(ytypes) ? ytypes : [ytypes]
ytypes.forEach(ytype => {
if (this.scope.every(yt => yt !== ytype)) {
if (ytype.doc !== this.doc) logging.warn('[yjs#509] Not same Y.Doc') // use MultiDocUndoManager instead. also see https://github.com/yjs/yjs/issues/509
if (!tmpSet.has(ytype)) {
tmpSet.add(ytype)
if (ytype instanceof AbstractType ? ytype.doc !== this.doc : ytype !== this.doc) logging.warn('[yjs#509] Not same Y.Doc') // use MultiDocUndoManager instead. also see https://github.com/yjs/yjs/issues/509
this.scope.push(ytype)
}
})

View File

@ -1,4 +1,3 @@
import * as error from 'lib0/error'
import * as encoding from 'lib0/encoding'
@ -168,7 +167,7 @@ export class UpdateEncoderV2 extends DSEncoderV2 {
*/
this.keyMap = new Map()
/**
* Refers to the next uniqe key-identifier to me used.
* Refers to the next unique key-identifier to me used.
* See writeKey method for more information.
*
* @type {number}

View File

@ -1,4 +1,3 @@
import {
isDeleted,
Item, AbstractType, Transaction, AbstractStruct // eslint-disable-line
@ -265,8 +264,8 @@ const getPathTo = (parent, child) => {
let i = 0
let c = /** @type {AbstractType<any>} */ (child._item.parent)._start
while (c !== child._item && c !== null) {
if (!c.deleted) {
i++
if (!c.deleted && c.countable) {
i += c.length
}
c = c.right
}

View File

@ -1,4 +1,3 @@
/**
* @module encoding
*/
@ -155,7 +154,7 @@ export const readClientsStructRefs = (decoder, doc) => {
// @type {string|null}
const struct = new Item(
createID(client, clock),
null, // leftd
null, // left
(info & binary.BIT8) === binary.BIT8 ? decoder.readLeftID() : null, // origin
null, // right
(info & binary.BIT7) === binary.BIT7 ? decoder.readRightID() : null, // right origin
@ -179,7 +178,7 @@ export const readClientsStructRefs = (decoder, doc) => {
const struct = new Item(
createID(client, clock),
null, // leftd
null, // left
origin, // origin
null, // right
rightOrigin, // right origin
@ -212,7 +211,7 @@ export const readClientsStructRefs = (decoder, doc) => {
* then we start emptying the stack.
*
* It is not possible to have circles: i.e. struct1 (from client1) depends on struct2 (from client2)
* depends on struct3 (from client1). Therefore the max stack size is eqaul to `structReaders.length`.
* depends on struct3 (from client1). Therefore the max stack size is equal to `structReaders.length`.
*
* This method is implemented in a way so that we can resume computation if this update
* causally depends on another update.
@ -280,14 +279,14 @@ const integrateStructs = (transaction, store, clientsStructRefs) => {
const addStackToRestSS = () => {
for (const item of stack) {
const client = item.id.client
const unapplicableItems = clientsStructRefs.get(client)
if (unapplicableItems) {
const inapplicableItems = clientsStructRefs.get(client)
if (inapplicableItems) {
// decrement because we weren't able to apply previous operation
unapplicableItems.i--
restStructs.clients.set(client, unapplicableItems.refs.slice(unapplicableItems.i))
inapplicableItems.i--
restStructs.clients.set(client, inapplicableItems.refs.slice(inapplicableItems.i))
clientsStructRefs.delete(client)
unapplicableItems.i = 0
unapplicableItems.refs = []
inapplicableItems.i = 0
inapplicableItems.refs = []
} else {
// item was the last item on clientsStructRefs and the field was already cleared. Add item to restStructs and continue
restStructs.clients.set(client, [item])
@ -371,7 +370,7 @@ export const writeStructsFromTransaction = (encoder, transaction) => writeClient
/**
* Read and apply a document update.
*
* This function has the same effect as `applyUpdate` but accepts an decoder.
* This function has the same effect as `applyUpdate` but accepts a decoder.
*
* @param {decoding.Decoder} decoder
* @param {Doc} ydoc
@ -452,7 +451,7 @@ export const readUpdateV2 = (decoder, ydoc, transactionOrigin, structDecoder = n
/**
* Read and apply a document update.
*
* This function has the same effect as `applyUpdate` but accepts an decoder.
* This function has the same effect as `applyUpdate` but accepts a decoder.
*
* @param {decoding.Decoder} decoder
* @param {Doc} ydoc

View File

@ -1,4 +1,3 @@
import { AbstractType, Item } from '../internals.js' // eslint-disable-line
/**

View File

@ -1,4 +1,3 @@
import {
AbstractType // eslint-disable-line
} from '../internals.js'

View File

@ -1,4 +1,3 @@
import * as binary from 'lib0/binary'
import * as decoding from 'lib0/decoding'
import * as encoding from 'lib0/encoding'

View File

@ -1,6 +1,5 @@
/**
* Testing if encoding/decoding compatibility and integration compatiblity is given.
* Testing if encoding/decoding compatibility and integration compatibility is given.
* We expect that the document always looks the same, even if we upgrade the integration algorithm, or add additional encoding approaches.
*
* The v1 documents were generated with Yjs v13.2.0 based on the randomisized tests.

View File

@ -1,4 +1,3 @@
import * as Y from '../src/index.js'
import * as t from 'lib0/testing'

View File

@ -15,15 +15,28 @@ import * as relativePositions from './relativePositions.tests.js'
import { runTests } from 'lib0/testing'
import { isBrowser, isNode } from 'lib0/environment'
import * as log from 'lib0/logging'
import { environment } from 'lib0'
if (isBrowser) {
log.createVConsole(document.body)
}
runTests({
/**
* @type {any}
*/
const tests = {
doc, map, array, text, xml, encoding, undoredo, compatibility, snapshot, updates, relativePositions
}).then(success => {
}
const run = async () => {
if (environment.isNode) {
// tests.nodejs = await import('./node.tests.js')
}
const success = await runTests(tests)
/* istanbul ignore next */
if (isNode) {
process.exit(success ? 0 : 1)
}
})
}
run()

View File

@ -1,4 +1,3 @@
import * as Y from '../src/index.js'
import * as t from 'lib0/testing'
@ -86,6 +85,26 @@ export const testRelativePositionCase6 = tc => {
checkRelativePositions(ytext)
}
/**
* Testing https://github.com/yjs/yjs/issues/657
*
* @param {t.TestCase} tc
*/
export const testRelativePositionCase7 = tc => {
const docA = new Y.Doc()
const textA = docA.getText('text')
textA.insert(0, 'abcde')
// Create a relative position at index 2 in 'textA'
const relativePosition = Y.createRelativePositionFromTypeIndex(textA, 2)
// Verify that the absolutes positions on 'docA' are the same
const absolutePositionWithFollow =
Y.createAbsolutePositionFromRelativePosition(relativePosition, docA, true)
const absolutePositionWithoutFollow =
Y.createAbsolutePositionFromRelativePosition(relativePosition, docA, false)
t.assert(absolutePositionWithFollow?.index === 2)
t.assert(absolutePositionWithoutFollow?.index === 2)
}
/**
* @param {t.TestCase} tc
*/
@ -102,3 +121,25 @@ export const testRelativePositionAssociationDifference = tc => {
t.assert(posRight != null && posRight.index === 2)
t.assert(posLeft != null && posLeft.index === 1)
}
/**
* @param {t.TestCase} tc
*/
export const testRelativePositionWithUndo = tc => {
const ydoc = new Y.Doc()
const ytext = ydoc.getText()
ytext.insert(0, 'hello world')
const rpos = Y.createRelativePositionFromTypeIndex(ytext, 1)
const um = new Y.UndoManager(ytext)
ytext.delete(0, 6)
t.assert(Y.createAbsolutePositionFromRelativePosition(rpos, ydoc)?.index === 0)
um.undo()
t.assert(Y.createAbsolutePositionFromRelativePosition(rpos, ydoc)?.index === 1)
const posWithoutFollow = Y.createAbsolutePositionFromRelativePosition(rpos, ydoc, false)
console.log({ posWithoutFollow })
t.assert(Y.createAbsolutePositionFromRelativePosition(rpos, ydoc, false)?.index === 6)
const ydocClone = new Y.Doc()
Y.applyUpdate(ydocClone, Y.encodeStateAsUpdate(ydoc))
t.assert(Y.createAbsolutePositionFromRelativePosition(rpos, ydocClone)?.index === 6)
t.assert(Y.createAbsolutePositionFromRelativePosition(rpos, ydocClone, false)?.index === 6)
}

View File

@ -14,6 +14,21 @@ export const testBasic = _tc => {
t.assert(restored.getText().toString() === 'world!')
}
/**
* @param {t.TestCase} _tc
*/
export const testBasicXmlAttributes = _tc => {
const ydoc = new Y.Doc({ gc: false })
const yxml = ydoc.getMap().set('el', new Y.XmlElement('div'))
const snapshot1 = Y.snapshot(ydoc)
yxml.setAttribute('a', '1')
const snapshot2 = Y.snapshot(ydoc)
yxml.setAttribute('a', '2')
t.compare(yxml.getAttributes(), { a: '2' })
t.compare(yxml.getAttributes(snapshot2), { a: '1' })
t.compare(yxml.getAttributes(snapshot1), {})
}
/**
* @param {t.TestCase} _tc
*/
@ -43,7 +58,7 @@ export const testEmptyRestoreSnapshot = _tc => {
t.compare(docRestored.getArray().toArray(), [])
t.compare(doc.getArray().toArray(), ['world'])
// now this snapshot reflects the latest state. It shoult still work.
// now this snapshot reflects the latest state. It should still work.
const snap2 = Y.snapshot(doc)
const docRestored2 = Y.createDocFromSnapshot(doc, snap2)
t.compare(docRestored2.getArray().toArray(), ['world'])

View File

@ -1,4 +1,3 @@
import * as t from 'lib0/testing'
import * as prng from 'lib0/prng'
import * as encoding from 'lib0/encoding'
@ -35,7 +34,7 @@ export const encV1 = {
mergeUpdates: Y.mergeUpdates,
applyUpdate: Y.applyUpdate,
logUpdate: Y.logUpdate,
updateEventName: 'update',
updateEventName: /** @type {'update'} */ ('update'),
diffUpdate: Y.diffUpdate
}
@ -44,7 +43,7 @@ export const encV2 = {
mergeUpdates: Y.mergeUpdatesV2,
applyUpdate: Y.applyUpdateV2,
logUpdate: Y.logUpdateV2,
updateEventName: 'updateV2',
updateEventName: /** @type {'updateV2'} */ ('updateV2'),
diffUpdate: Y.diffUpdateV2
}

View File

@ -3,6 +3,46 @@ import { init } from './testHelper.js' // eslint-disable-line
import * as Y from '../src/index.js'
import * as t from 'lib0/testing'
export const testInconsistentFormat = () => {
/**
* @param {Y.Doc} ydoc
*/
const testYjsMerge = ydoc => {
const content = /** @type {Y.XmlText} */ (ydoc.get('text', Y.XmlText))
content.format(0, 6, { bold: null })
content.format(6, 4, { type: 'text' })
t.compare(content.toDelta(), [
{
attributes: { type: 'text' },
insert: 'Merge Test'
},
{
attributes: { type: 'text', italic: true },
insert: ' After'
}
])
}
const initializeYDoc = () => {
const yDoc = new Y.Doc({ gc: false })
const content = /** @type {Y.XmlText} */ (yDoc.get('text', Y.XmlText))
content.insert(0, ' After', { type: 'text', italic: true })
content.insert(0, 'Test', { type: 'text' })
content.insert(0, 'Merge ', { type: 'text', bold: true })
return yDoc
}
{
const yDoc = initializeYDoc()
testYjsMerge(yDoc)
}
{
const initialYDoc = initializeYDoc()
const yDoc = new Y.Doc({ gc: false })
Y.applyUpdate(yDoc, Y.encodeStateAsUpdate(initialYDoc))
testYjsMerge(yDoc)
}
}
/**
* @param {t.TestCase} tc
*/
@ -76,6 +116,72 @@ export const testEmptyTypeScope = _tc => {
t.assert(yarray.length === 0)
}
/**
* @param {t.TestCase} _tc
*/
export const testRejectUpdateExample = _tc => {
const tmpydoc1 = new Y.Doc()
tmpydoc1.getArray('restricted').insert(0, [1])
tmpydoc1.getArray('public').insert(0, [1])
const update1 = Y.encodeStateAsUpdate(tmpydoc1)
const tmpydoc2 = new Y.Doc()
tmpydoc2.getArray('public').insert(0, [2])
const update2 = Y.encodeStateAsUpdate(tmpydoc2)
const ydoc = new Y.Doc()
const restrictedType = ydoc.getArray('restricted')
/**
* Assume this function handles incoming updates via a communication channel like websockets.
* Changes to the `ydoc.getMap('restricted')` type should be rejected.
*
* - set up undo manager on the restricted types
* - cache pending* updates from the Ydoc to avoid certain attacks
* - apply received update and check whether the restricted type (or any of its children) has been changed.
* - catch errors that might try to circumvent the restrictions
* - undo changes on restricted types
* - reapply pending* updates
*
* @param {Uint8Array} update
*/
const updateHandler = (update) => {
// don't handle changes of the local undo manager, which is used to undo invalid changes
const um = new Y.UndoManager(restrictedType, { trackedOrigins: new Set(['remote change']) })
const beforePendingDs = ydoc.store.pendingDs
const beforePendingStructs = ydoc.store.pendingStructs?.update
try {
Y.applyUpdate(ydoc, update, 'remote change')
} finally {
while (um.undoStack.length) {
um.undo()
}
um.destroy()
ydoc.store.pendingDs = beforePendingDs
ydoc.store.pendingStructs = null
if (beforePendingStructs) {
Y.applyUpdateV2(ydoc, beforePendingStructs)
}
}
}
updateHandler(update1)
updateHandler(update2)
t.assert(restrictedType.length === 0)
t.assert(ydoc.getArray('public').length === 2)
}
/**
* Test case to fix #241
* @param {t.TestCase} _tc
*/
export const testGlobalScope = _tc => {
const ydoc = new Y.Doc()
const um = new Y.UndoManager(ydoc)
const yarray = ydoc.getArray()
yarray.insert(0, [1])
um.undo()
t.assert(yarray.length === 0)
}
/**
* Test case to fix #241
* @param {t.TestCase} _tc
@ -675,3 +781,33 @@ export const testUndoDeleteInMap = (tc) => {
undoManager.undo()
t.compare(map0.toJSON(), { a: 'a' })
}
/**
* It should expose the StackItem being processed if undoing
*
* @param {t.TestCase} _tc
*/
export const testUndoDoingStackItem = async (_tc) => {
const doc = new Y.Doc()
const text = doc.getText('text')
const undoManager = new Y.UndoManager([text])
undoManager.on('stack-item-added', /** @param {any} event */ event => {
event.stackItem.meta.set('str', '42')
})
let metaUndo = /** @type {any} */ (null)
let metaRedo = /** @type {any} */ (null)
text.observe((event) => {
const /** @type {Y.UndoManager} */ origin = event.transaction.origin
if (origin === undoManager && origin.undoing) {
metaUndo = origin.currStackItem?.meta.get('str')
} else if (origin === undoManager && origin.redoing) {
metaRedo = origin.currStackItem?.meta.get('str')
}
})
text.insert(0, 'abc')
undoManager.undo()
undoManager.redo()
t.compare(metaUndo, '42', 'currStackItem is accessible while undoing')
t.compare(metaRedo, '42', 'currStackItem is accessible while redoing')
t.compare(undoManager.currStackItem, null, 'currStackItem is null after observe/transaction')
}

View File

@ -15,7 +15,7 @@ import * as object from 'lib0/object'
* @property {function(Uint8Array):{from:Map<number,number>,to:Map<number,number>}} Enc.parseUpdateMeta
* @property {function(Y.Doc):Uint8Array} Enc.encodeStateVector
* @property {function(Uint8Array):Uint8Array} Enc.encodeStateVectorFromUpdate
* @property {string} Enc.updateEventName
* @property {'update'|'updateV2'} Enc.updateEventName
* @property {string} Enc.description
* @property {function(Uint8Array, Uint8Array):Uint8Array} Enc.diffUpdate
*/
@ -169,7 +169,7 @@ const checkUpdateCases = (ydoc, updates, enc, hasDeletes) => {
// t.info('Target State: ')
// enc.logUpdate(targetState)
cases.forEach((mergedUpdates, i) => {
cases.forEach((mergedUpdates) => {
// t.info('State Case $' + i + ':')
// enc.logUpdate(updates)
const merged = new Y.Doc({ gc: false })
@ -218,10 +218,10 @@ const checkUpdateCases = (ydoc, updates, enc, hasDeletes) => {
}
/**
* @param {t.TestCase} tc
* @param {t.TestCase} _tc
*/
export const testMergeUpdates1 = tc => {
encoders.forEach((enc, i) => {
export const testMergeUpdates1 = _tc => {
encoders.forEach((enc) => {
t.info(`Using encoder: ${enc.description}`)
const ydoc = new Y.Doc({ gc: false })
const updates = /** @type {Array<Uint8Array>} */ ([])
@ -299,16 +299,16 @@ export const testMergePendingUpdates = tc => {
Y.applyUpdate(yDoc5, update4)
Y.applyUpdate(yDoc5, serverUpdates[4])
// @ts-ignore
const update5 = Y.encodeStateAsUpdate(yDoc5) // eslint-disable-line
const _update5 = Y.encodeStateAsUpdate(yDoc5) // eslint-disable-line
const yText5 = yDoc5.getText('textBlock')
t.compareStrings(yText5.toString(), 'nenor')
}
/**
* @param {t.TestCase} tc
* @param {t.TestCase} _tc
*/
export const testObfuscateUpdates = tc => {
export const testObfuscateUpdates = _tc => {
const ydoc = new Y.Doc()
const ytext = ydoc.getText('text')
const ymap = ydoc.getMap('map')

View File

@ -4,6 +4,9 @@ import * as Y from '../src/index.js'
import * as t from 'lib0/testing'
import * as prng from 'lib0/prng'
import * as math from 'lib0/math'
import * as env from 'lib0/environment'
const isDevMode = env.getVariable('node_env') === 'development'
/**
* @param {t.TestCase} tc
@ -17,6 +20,28 @@ export const testBasicUpdate = tc => {
t.compare(doc2.getArray('array').toArray(), ['hi'])
}
/**
* @param {t.TestCase} tc
*/
export const testFailsObjectManipulationInDevMode = tc => {
if (isDevMode) {
t.info('running in dev mode')
const doc = new Y.Doc()
const a = [1, 2, 3]
const b = { o: 1 }
doc.getArray('test').insert(0, [a])
doc.getMap('map').set('k', b)
t.fails(() => {
a[0] = 42
})
t.fails(() => {
b.o = 42
})
} else {
t.info('not in dev mode')
}
}
/**
* @param {t.TestCase} tc
*/
@ -330,6 +355,29 @@ export const testObserveDeepEventOrder = tc => {
}
}
/**
* Correct index when computing event.path in observeDeep - https://github.com/yjs/yjs/issues/457
*
* @param {t.TestCase} _tc
*/
export const testObservedeepIndexes = _tc => {
const doc = new Y.Doc()
const map = doc.getMap()
// Create a field with the array as value
map.set('my-array', new Y.Array())
// Fill the array with some strings and our Map
map.get('my-array').push(['a', 'b', 'c', new Y.Map()])
/**
* @type {Array<any>}
*/
let eventPath = []
map.observeDeep((events) => { eventPath = events[0].path })
// set a value on the map inside of our array
map.get('my-array').get(3).set('hello', 'world')
console.log(eventPath)
t.compare(eventPath, ['my-array', 3])
}
/**
* @param {t.TestCase} tc
*/

View File

@ -369,11 +369,11 @@ export const testObserversUsingObservedeep = tc => {
/**
* @type {Array<Array<string|number>>}
*/
const pathes = []
const paths = []
let calls = 0
map0.observeDeep(events => {
events.forEach(event => {
pathes.push(event.path)
paths.push(event.path)
})
calls++
})
@ -381,7 +381,7 @@ export const testObserversUsingObservedeep = tc => {
map0.get('map').set('array', new Y.Array())
map0.get('map').get('array').insert(0, ['content'])
t.assert(calls === 3)
t.compare(pathes, [[], ['map'], ['map', 'array']])
t.compare(paths, [[], ['map'], ['map', 'array']])
compare(users)
}
@ -393,14 +393,14 @@ export const testPathsOfSiblingEvents = tc => {
/**
* @type {Array<Array<string|number>>}
*/
const pathes = []
const paths = []
let calls = 0
const doc = users[0]
map0.set('map', new Y.Map())
map0.get('map').set('text1', new Y.Text('initial'))
map0.observeDeep(events => {
events.forEach(event => {
pathes.push(event.path)
paths.push(event.path)
})
calls++
})
@ -409,7 +409,7 @@ export const testPathsOfSiblingEvents = tc => {
map0.get('map').set('text2', new Y.Text('new'))
})
t.assert(calls === 1)
t.compare(pathes, [['map'], ['map', 'text1']])
t.compare(paths, [['map'], ['map', 'text1']])
compare(users)
}

View File

@ -376,7 +376,7 @@ export const testDeltaBug = _tc => {
},
{
insert: '\n',
// This attibutes has only list and no table-cell-line
// This attributes has only list and no table-cell-line
attributes: {
list: {
rowspan: '1',
@ -1746,6 +1746,27 @@ export const testBasicFormat = tc => {
compare(users)
}
/**
* @param {t.TestCase} tc
*/
export const testFalsyFormats = tc => {
const { users, text0 } = init(tc, { users: 2 })
let delta
text0.observe(event => {
delta = event.delta
})
text0.insert(0, 'abcde', { falsy: false })
t.compare(text0.toDelta(), [{ insert: 'abcde', attributes: { falsy: false } }])
t.compare(delta, [{ insert: 'abcde', attributes: { falsy: false } }])
text0.format(1, 3, { falsy: true })
t.compare(text0.toDelta(), [{ insert: 'a', attributes: { falsy: false } }, { insert: 'bcd', attributes: { falsy: true } }, { insert: 'e', attributes: { falsy: false } }])
t.compare(delta, [{ retain: 1 }, { retain: 3, attributes: { falsy: true } }])
text0.format(2, 1, { falsy: false })
t.compare(text0.toDelta(), [{ insert: 'a', attributes: { falsy: false } }, { insert: 'b', attributes: { falsy: true } }, { insert: 'c', attributes: { falsy: false } }, { insert: 'd', attributes: { falsy: true } }, { insert: 'e', attributes: { falsy: false } }])
t.compare(delta, [{ retain: 2 }, { retain: 1, attributes: { falsy: false } }])
compare(users)
}
/**
* @param {t.TestCase} _tc
*/

View File

@ -189,7 +189,6 @@ export const testClone = _tc => {
const third = new Y.XmlElement('p')
yxml.push([first, second, third])
t.compareArrays(yxml.toArray(), [first, second, third])
const cloneYxml = yxml.clone()
ydoc.getArray('copyarr').insert(0, [cloneYxml])
t.assert(cloneYxml.length === 3)
@ -210,3 +209,15 @@ export const testFormattingBug = _tc => {
yxml.applyDelta(delta)
t.compare(yxml.toDelta(), delta)
}
/**
* @param {t.TestCase} _tc
*/
export const testElement = _tc => {
const ydoc = new Y.Doc()
const yxmlel = ydoc.getXmlElement()
const text1 = new Y.XmlText('text1')
const text2 = new Y.XmlText('text2')
yxmlel.insert(0, [text1, text2])
t.compareArrays(yxmlel.toArray(), [text1, text2])
}