Compare commits

...

751 Commits

Author SHA1 Message Date
Kevin Jahns
67bbc0a3fe implemented websocket provider 2018-10-30 00:51:09 +01:00
Kevin Jahns
e1ece6dc66 refactoring: removed default connector and persistence, new code style, proper jsdocs, enabled typechecking 2018-10-29 21:58:21 +01:00
Kevin Jahns
fe038822a3 Merge branch 'ydb-integration' of https://github.com/y-js/yjs into ydb-integration 2018-10-22 12:23:47 +02:00
Kevin Jahns
dece14486c start refactoring 2018-10-22 12:23:35 +02:00
Kevin Jahns
2daffbc2ca implement syncstate 2018-10-17 15:14:47 +02:00
Kevin Jahns
4c01a34d09 integrate ydb client and adapt some demos 2018-10-13 14:38:29 +02:00
Kevin Jahns
3b08267daa merge experimental-connectors 2018-10-08 17:11:18 +02:00
Kevin
b98ebddb69 ydb client 2018-10-08 16:09:50 +02:00
Kevin Jahns
9d5bf50676 13.0.0-66 2018-07-17 18:50:03 +02:00
Kevin Jahns
c0972f8158 reset selection also for local transactions 2018-07-17 18:49:28 +02:00
Kevin Jahns
548125a944 13.0.0-65 2018-07-16 18:38:09 +02:00
Kevin Jahns
a7b124ca6e 13.0.0-64 2018-07-16 18:19:36 +02:00
Kevin Jahns
4022374620 dombinding: always set browser range after change 2018-07-16 18:15:24 +02:00
Kevin Jahns
860e4d7af6 13.0.0-63 2018-06-23 00:30:45 +02:00
Kevin Jahns
6376d69b58 fix undo of map update 2018-06-23 00:29:44 +02:00
Kevin Jahns
5cf6f45f19 13.0.0-62 2018-06-13 00:08:01 +02:00
Kevin Jahns
967903673b fixed undo/redo issues and implemented ability to manually flush the UndoManager 2018-06-13 00:06:38 +02:00
Kevin Jahns
2d897f1844 add function to create lots of rooms 2018-06-07 16:36:42 +02:00
Kevin Jahns
fb2f9bc493 add client-server updateCounter support to sync all persisted rooms 2018-06-04 17:35:39 +02:00
Kevin Jahns
6f9ae0c4fc save current state at the beginning in YIndexedDB 2018-06-03 22:39:22 +02:00
Kevin Jahns
9df20fac8a added YIndexedDB 2018-06-03 21:58:51 +02:00
Kevin Jahns
a1fb1a6258 add persistence decoder 2018-06-02 22:16:12 +02:00
Kevin Jahns
417d0ef3b5 save state in FilePersistence 2018-06-02 13:33:04 +02:00
Kevin Jahns
9be256231b enable gc in demo 2018-05-23 16:15:11 +02:00
Kevin Jahns
c122bdc750 BinaryEncoder writes directly to ArrayBuffer, improves memory consumption 2018-05-23 16:06:38 +02:00
Kevin Jahns
4ef36ab81c fix tests 2018-05-23 14:16:54 +02:00
Kevin Jahns
cccc0e1015 implemented experimental websockets-connector 2018-05-23 14:01:00 +02:00
Kevin Jahns
db5312443e 13.0.0-61 2018-05-18 02:02:44 +02:00
Kevin Jahns
dbda07424b fix DomBinding destroy 2018-05-18 02:01:53 +02:00
Kevin Jahns
684d38d6c8 make compatible with webpack and less sophisticated module bundlers 2018-05-13 13:07:24 +02:00
Kevin Jahns
44fa064eb2 Merge branch 'master' of github.com:y-js/yjs 2018-05-12 16:43:28 +02:00
Kevin Jahns
9b6fffd880 Add rollup dependency - closes #110 2018-05-12 16:43:05 +02:00
Kevin Jahns
e9993b2643 Merge pull request #111 from larskarbo/patch-1
(DOCS) Remove y-array duplicates
2018-05-12 16:41:14 +02:00
Kevin Jahns
762e9e8a3a do not log _start in logItemHelper. Fixes #114 2018-05-12 15:42:31 +02:00
Kevin Jahns
6ddeb788c7 Merge branch 'master' of github.com:y-js/yjs 2018-05-09 16:28:07 +02:00
Kevin Jahns
b9245f323c prefer !== undefined check instead of hasOwnProperty 2018-05-09 16:27:55 +02:00
Kevin Jahns
c0e630b635 prefer parentElement instead of parentNode 2018-05-09 14:42:24 +02:00
Kevin Jahns
e56457a0ef 13.0.0-60 2018-05-08 13:46:27 +02:00
Kevin Jahns
ca13849828 fix domBinding infinite loop 2018-05-08 13:45:51 +02:00
Kevin Jahns
92c2fbd6d3 remove debug dependency 2018-05-07 11:52:37 +02:00
Kevin Jahns
65b8921f05 13.0.0-59 2018-05-07 11:45:39 +02:00
Kevin Jahns
1ace7f4b73 fix parentNode binding in case parent doesn't fire MO 2018-05-07 11:44:22 +02:00
Kevin Jahns
6336064516 13.0.0-58 2018-05-05 15:33:53 +02:00
Kevin Jahns
49d2e42b41 fix missing dom-binding - still investigating 2018-05-05 15:33:16 +02:00
Kevin Jahns
c098e8e745 implement scroll-fixer 2018-05-05 14:47:59 +02:00
Kevin Jahns
38558a7fad 13.0.0-57 2018-05-02 18:42:56 +02:00
Kevin Jahns
bdb3782f8f add option to disable gc (compatible with older versions) 2018-05-02 18:42:18 +02:00
Kevin Jahns
bc32f7348e 13.0.0-56 2018-04-27 18:43:24 +02:00
Kevin Jahns
09a94f053e merge with master 2018-04-27 18:39:34 +02:00
Kevin Jahns
0df0079fa3 Merge branch 'master' of github.com:y-js/yjs 2018-04-27 18:33:51 +02:00
Kevin Jahns
a54d826d6d bugfixes 2018-04-27 18:33:28 +02:00
Kevin Jahns
99f92cb9a0 fix filtering 2018-04-26 16:01:17 +02:00
Kevin Jahns
e788ad1333 fix hook binding 2018-04-26 14:07:12 +02:00
Kevin Jahns
1fe37c565e hooks port to domBinding 2018-04-26 13:26:21 +02:00
Lars Karbo
ed2273e2ed Remove y-array duplicates 2018-04-24 12:59:51 -07:00
Kevin Jahns
94933a704d correctly handle gc with UndoManager and un-merge when syncing 2018-04-23 13:25:40 +02:00
Kevin Jahns
ef6eb08335 fix most gc bugs - test suite running again 2018-04-19 18:28:25 +02:00
Kevin Jahns
d915c8dd13 prelim gc 2018-04-03 13:28:24 +02:00
Kevin Jahns
32207cbca0 implement new mark deleted / gc approach 2018-03-29 16:36:34 +02:00
Kevin Jahns
135c6d31be documentation and fix tests 2018-03-29 11:58:02 +02:00
Kevin Jahns
61149b458a less duplicate code 2018-03-23 05:22:45 +01:00
Kevin Jahns
ba97bfdd9e remove fundraiser campaign 2018-03-23 04:44:26 +01:00
Kevin Jahns
689bca8602 Merge remote-tracking branch 'origin' into v13-doc 2018-03-23 04:40:08 +01:00
Kevin Jahns
6dd43cde17 cleanup docs 2018-03-23 04:39:32 +01:00
Kevin Jahns
026675b438 separate dom binding 2018-03-23 01:55:47 +01:00
Kevin Jahns
941a22b257 13.0.0-55 2018-03-14 18:52:49 -07:00
Kevin Jahns
4aa41b98a9 fix dom filtering bug 2018-03-14 18:51:48 -07:00
Kevin Jahns
acf443aacb reworking bindings 2018-03-12 03:36:37 +01:00
Kevin Jahns
aa8c934833 Add fundraiser campaign 2018-03-06 05:27:03 +01:00
Kevin Jahns
814af5a3d7 fix import locations 2018-03-06 05:22:18 +01:00
Kevin Jahns
bbc207aaa6 restructer and move to esdoc 2018-03-06 03:17:50 +01:00
Kevin Jahns
a9b610479d big documentation update - all public functions and classes are documented now 2018-03-05 03:12:04 +01:00
Kevin Jahns
079de07eff 13.0.0-54 2018-03-01 16:45:25 +01:00
Kevin Jahns
54453e87fa fix consecutive undo,redo,undo,redo.. (abc test) 2018-03-01 16:44:26 +01:00
Kevin Jahns
1b0e3659c3 undo fixes for consecutive undo-redo 2018-03-01 13:50:01 +01:00
Kevin Jahns
dc22a79ac4 properly unregister event when binding is destroyed 2018-02-27 03:52:40 +01:00
Kevin Jahns
384a4b72b0 add quill-cursors example 2018-02-26 17:24:28 +01:00
Kevin Jahns
f35c056bde fix some tests 2018-02-26 03:23:22 +01:00
Kevin Jahns
250050e83b Merge remote-tracking branch 'origin' into y-richtext-rewrite 2018-02-26 02:19:08 +01:00
Kevin Jahns
248d08be30 implement quill binding for y-text 2018-02-26 02:18:39 +01:00
Kevin Jahns
641f426339 13.0.0-53 2018-02-25 02:31:59 +01:00
Kevin Jahns
fcbca65d8f fromBinary is a transaction 2018-02-25 02:31:20 +01:00
Kevin Jahns
5f8ae0dd43 13.0.0-52 2018-02-18 19:20:00 +01:00
Kevin Jahns
de14fe0f3e fix getAttribute vs attributes.value fixes y-js/y-xml#8 2018-02-18 18:58:49 +01:00
Kevin Jahns
5e4b071693 actually use clock in undo-manager 2018-02-15 18:58:43 +01:00
Kevin Jahns
937de2c59f fix fast undo-redo bug 2018-02-15 18:28:53 +01:00
Kevin Jahns
f1f1bff901 preliminary undo-redo fixes 2018-02-15 17:58:14 +01:00
Kevin Jahns
da748a78f4 start rewriting y-richtext 2018-02-15 01:25:08 +01:00
Kevin Jahns
4855b2d590 13.0.0-51 2018-02-07 14:08:43 +01:00
Kevin Jahns
908ce31e2f Merge branch 'master' of github.com:y-js/yjs 2018-02-07 14:08:07 +01:00
Kevin Jahns
e4d4c23f0b bugfix - persist deletes when syncing 2018-02-07 14:07:57 +01:00
Kevin Jahns
fc500a8247 Merge pull request #94 from LukasDrgon/patch-3
Add CDN usage
2018-01-31 20:36:26 -08:00
Kevin Jahns
4b84541d76 13.0.0-50 2018-01-30 20:12:58 -08:00
Kevin Jahns
a3ab42c157 implemnt mutual exclude pattern directly in Persistence.js 2018-01-30 20:11:59 -08:00
Kevin Jahns
bbd3317d62 13.0.0-49 2018-01-30 15:53:33 -08:00
Kevin Jahns
5d3922cb64 fix undo-redo 2018-01-30 15:52:36 -08:00
Kevin Jahns
a81a2cd553 13.0.0-48 2018-01-29 16:41:52 -08:00
Kevin Jahns
c0d24bdba4 lint 2018-01-29 16:41:27 -08:00
Kevin Jahns
40e913e9c5 add toBinary and fromBinary to Y.utils 2018-01-29 16:39:09 -08:00
Kevin Jahns
94f6a0fd9c implement Y.*Binding approach 2018-01-29 11:55:28 -08:00
Kevin Jahns
41a88dbc43 fix examples for Yjs@13 2018-01-25 17:28:33 -07:00
Kevin Jahns
1d4f283955 13.0.0-47 2018-01-18 18:44:56 +01:00
Kevin Jahns
fc3a4c376c implement when-handler 2018-01-18 18:44:20 +01:00
Lukas Drgon
acb0affa33 Add CDN usage 2018-01-17 22:03:49 +01:00
Kevin Jahns
0b510b64a3 persistence updates + make Persistence.init async 2018-01-16 16:13:47 +01:00
Kevin Jahns
c8f0cf5556 13.0.0-46 2018-01-10 00:20:03 +01:00
Kevin Jahns
11a4271fd1 13.0.0-45 2018-01-10 00:18:50 +01:00
Kevin Jahns
c7670915c7 Merge branch 'master' of github.com:y-js/yjs 2018-01-10 00:17:34 +01:00
Kevin Jahns
eb2d596538 implement mutualExclude factory 2018-01-10 00:17:26 +01:00
Kevin Jahns
48e17ea1a7 13.0.0-44 2018-01-10 00:16:33 +01:00
Kevin Jahns
1a22fdd45e persistence improvements 2018-01-10 00:11:25 +01:00
Kevin Jahns
07cf0b3436 export AbstractPersistence 2018-01-08 17:30:30 +01:00
Kevin Jahns
5a68b9f4ad loaded event when loaded from persistence adapter 2018-01-08 02:28:46 +01:00
Kevin Jahns
445dd3e0da fix several y-xml bugs 2018-01-03 03:50:27 +01:00
Kevin Jahns
0ba97d78f8 better relative cursor positions for text editing - decrease number of generated messages for cursor 2017-12-31 16:14:02 +01:00
Kevin Jahns
fc5be5c7cc fix empty string insertion bug 2017-12-31 14:49:20 +01:00
Kevin Jahns
f2debc150c reimplement persistence approach 2017-12-24 03:18:00 +01:00
Kevin Jahns
08f37a86e3 13.0.0-43 2017-12-21 16:06:29 +01:00
Kevin Jahns
f5d17e6236 filter y-xml when domFilter is set 2017-12-21 16:05:50 +01:00
Kevin Jahns
8f3bd7170a 13.0.0-42 2017-12-19 17:39:01 +01:00
Kevin Jahns
5586334549 fix initial content in y-array 2017-12-19 17:37:04 +01:00
Kevin Jahns
24c1e4dcc8 13.0.0-41 2017-12-14 14:30:02 +01:00
Kevin Jahns
d61bbecf4e fix tree walker on YXmlFragment 2017-12-14 14:29:16 +01:00
Kevin Jahns
85492ad2e0 fix drawing example. Add drawing hook for y-xml 2017-12-13 12:49:34 +01:00
Kevin Jahns
02253f9a8d fix log outputs 2017-12-13 10:28:19 +01:00
Kevin Jahns
8105bef1af work on drawing demo 2017-12-06 19:20:52 -08:00
Kevin Jahns
4efa16e2dd 13.0.0-40 2017-12-05 21:50:34 -08:00
Kevin Jahns
ad44f59def implement new dom update algorithm 2017-12-05 21:50:00 -08:00
Kevin Jahns
9c471ea24d 13.0.0-39 2017-12-05 17:06:01 -08:00
Kevin Jahns
d9e76014f5 fix remaining cursor relocation issues 2017-12-05 17:05:12 -08:00
Kevin Jahns
4091b7d004 13.0.0-38 2017-12-05 00:53:25 -08:00
Kevin Jahns
dfc183643d support data-yjs-hook attribute for yjs hooks 2017-12-05 00:52:52 -08:00
Kevin Jahns
cf8698f2b6 13.0.0-37 2017-12-02 01:45:55 -08:00
Kevin Jahns
3595f14da7 fix insert in y-text 2017-12-02 01:45:22 -08:00
Kevin Jahns
c6e671b1d5 13.0.0-36 2017-11-30 18:39:17 -08:00
Kevin Jahns
e4c10fd6b3 handle xmlhook in mutation observer 2017-11-30 18:38:12 -08:00
Kevin Jahns
e70aa09f88 Implement YXml element hooks (based on _yjsHook property) 2017-11-29 17:16:06 -08:00
Kevin Jahns
7808b143da 13.0.0-35 2017-11-28 17:38:31 -08:00
Kevin Jahns
b35092928e fix user selection issues 2017-11-28 17:37:15 -08:00
Kevin Jahns
b7dbcf69d3 13.0.0-34 2017-11-26 23:24:41 -08:00
Kevin Jahns
377df18788 prevent updating cursor position if not necessary 2017-11-26 23:23:29 -08:00
Kevin Jahns
26a323733d 13.0.0-33 2017-11-26 14:42:59 -08:00
Kevin Jahns
d0d1015074 filter remote changes in YXml* 2017-11-26 14:42:06 -08:00
Kevin Jahns
2e3240b379 13.0.0-32 2017-11-14 21:31:11 -08:00
Kevin Jahns
2558652356 fix attribute filter (it used to filter everything) 2017-11-14 21:19:39 -08:00
Kevin Jahns
783cbd63fc 13.0.0-31 2017-11-14 20:44:12 -08:00
Kevin Jahns
41be80e751 fix y-xml server environment 2017-11-14 20:43:30 -08:00
Kevin Jahns
3d6050d8a2 13.0.0-30 2017-11-12 13:37:37 -08:00
Kevin Jahns
3d5ba7b4cc fix the case that a new transaction starts in an event listener (afterTransaction, observe, observeDeep) 2017-11-12 13:37:06 -08:00
Kevin Jahns
415b66607c fixed filtering 2017-11-10 19:04:00 -08:00
Kevin Jahns
05cd1d0575 13.0.0-29 2017-11-10 18:46:10 -08:00
Kevin Jahns
4edc22bedb remove prematurely commited dom-filter update 2017-11-10 18:45:41 -08:00
Kevin Jahns
16f84c67d5 13.0.0-28 2017-11-10 18:41:39 -08:00
Kevin Jahns
290d3c8ffe support undefined as an attribute value 2017-11-10 18:41:10 -08:00
Kevin Jahns
c51e8b46c2 13.0.0-27 2017-11-10 12:55:05 -08:00
Kevin Jahns
0cda1630d2 fix path bugs 2017-11-10 12:54:33 -08:00
Kevin Jahns
d232b883e9 13.0.0-26 2017-11-09 17:32:45 -08:00
Kevin Jahns
3a0e65403f fix undo scope 2017-11-09 17:31:58 -08:00
Kevin Jahns
224fff93ba 13.0.0-25 2017-11-08 17:31:50 -08:00
Kevin Jahns
4f55e8c655 fix event.path by using event.currentTarget 2017-11-08 17:31:12 -08:00
Kevin Jahns
a08624c04e implemented tree-walker 2017-11-08 13:40:36 -08:00
Kevin Jahns
9b00929172 13.0.0-24 2017-11-08 00:02:24 -08:00
Kevin Jahns
b94267e14a prevent mangling of Types and other useful data 2017-11-08 00:01:18 -08:00
Kevin Jahns
e696304845 13.0.0-23 2017-11-07 22:52:33 -08:00
Kevin Jahns
d503c9d640 lint 2017-11-07 22:51:46 -08:00
Kevin Jahns
e5f289506f observeDeep receives array of events 2017-11-07 22:44:43 -08:00
Kevin Jahns
c453593ee7 y-xml: hand over fake document if necessary 2017-11-07 21:06:29 -08:00
Kevin Jahns
5ed1818de5 fix selection RootID name 2017-11-07 20:47:00 -08:00
Kevin Jahns
0310500c4e add YEvent 2017-11-07 20:34:44 -08:00
Kevin Jahns
b7defc32e8 fix selecting multiple paragraphs 2017-11-07 20:28:31 -08:00
Kevin Jahns
dbdd49af23 fix relativePosition if startof is a root type 2017-11-07 20:10:01 -08:00
Kevin Jahns
b7c05ba133 fix YMap.keys() 2017-11-07 19:56:03 -08:00
Kevin Jahns
9298903bdb filter out attribute events for YXmlFragment 2017-11-07 19:31:57 -08:00
Kevin Jahns
d59e30b239 implement generic YEvent with path property 2017-11-07 19:18:41 -08:00
Kevin Jahns
d29b83a457 improve backwards-compatibility 2017-11-07 18:31:04 -08:00
Kevin Jahns
0208d83f91 implemented undo 🙌 2017-10-30 11:47:56 +01:00
Kevin Jahns
c545118637 fixed selection handler befor/after transactions 2017-10-28 23:02:48 +02:00
Kevin Jahns
c619aa33d9 fixed inserting large xml portions 2017-10-27 22:28:42 +02:00
Kevin Jahns
1dea8f394f unbind yxml immediately when deleted 2017-10-26 21:02:25 +02:00
Kevin Jahns
5cf8d20cf6 delete child if parent is deleted 2017-10-26 20:53:27 +02:00
Kevin Jahns
74f9ceab01 fixed dom filtering tests 2017-10-26 20:24:09 +02:00
Kevin Jahns
ca81cdf3be fixed xml tests 2017-10-26 19:50:43 +02:00
Kevin Jahns
96c6aa2751 fixed ds syncing bug 2017-10-26 19:12:33 +02:00
Kevin Jahns
e6b5e258fb several DS fixes (logging works now) 2017-10-26 16:22:35 +02:00
Kevin Jahns
e8170a09a7 fixed all insert tests 2017-10-26 14:40:21 +02:00
Kevin Jahns
9d1ad8cb28 fix item-splitting 2017-10-24 16:41:19 +02:00
Kevin Jahns
d859fd68fe fixed several random tests 2017-10-23 22:43:41 +02:00
Kevin Jahns
2b7d2ed1e6 implemented logTable method on data stores 2017-10-22 23:50:49 +02:00
Kevin Jahns
142a5ada60 fix some tests, implement event classes for types, and re-implement logging 2017-10-22 19:13:12 +02:00
Kevin Jahns
c92f987496 fix some tests, implement event classes for types, and re-implement logging 2017-10-22 19:12:50 +02:00
Kevin Jahns
755c9eb16e implemented xml type for new event system 2017-10-19 17:36:28 +02:00
Kevin Jahns
1311c7a0d8 fix first y-array test 2017-10-16 04:53:12 +02:00
Kevin Jahns
4eec8ecdd3 fix encoding and rb tree tests 2017-10-15 12:21:14 +02:00
Kevin Jahns
0e426f8928 fix compiling issues 2017-10-14 23:03:24 +02:00
Kevin Jahns
82015d5a37 refactor the whole damn thing 2017-10-11 03:41:54 +02:00
Kevin Jahns
d9ee67d2f3 13.0.0-22 2017-10-07 00:42:06 +02:00
Kevin Jahns
791f6c12f0 add indexeddb example 2017-10-07 00:40:34 +02:00
Kevin Jahns
23d019c244 add writeObjectToYMap and writeArrayToYArray helper utilities 2017-10-07 00:39:26 +02:00
Kevin Jahns
c8ca80d15f 13.0.0-21 2017-10-02 15:52:11 +02:00
Kevin Jahns
be282c8338 fix lint 2017-10-02 15:50:56 +02:00
Kevin Jahns
829a094c6d check for responsiveness when maxBufferSize is set 2017-10-02 15:45:23 +02:00
Kevin Jahns
725273167e 13.0.0-20 2017-09-29 22:34:18 +02:00
Kevin Jahns
581264c5e3 implement relative position helper 2017-09-29 22:33:28 +02:00
Kevin Jahns
be537c9f8c 13.0.0-19 2017-09-26 21:53:01 +02:00
Kevin Jahns
4028eee39d implemented chunked broadcast of updates 2017-09-26 21:52:07 +02:00
Kevin Jahns
0e3e561ec7 13.0.0-18 2017-09-20 11:34:03 +02:00
Kevin Jahns
7df46cb731 Merge branch 'master' of github.com:y-js/yjs 2017-09-20 11:30:24 +02:00
Kevin Jahns
40fb16ef32 catch y-* related errors 2017-09-20 11:29:13 +02:00
Kevin Jahns
ada5d36cd5 add more y-xml tests 2017-09-19 03:16:48 +02:00
Kevin Jahns
f537a43e29 implement tests for dom filter 2017-09-18 22:14:45 +02:00
Kevin Jahns
3a305fb228 13.0.0-17 2017-09-11 17:38:21 +02:00
Kevin Jahns
1afdab376d fix linting 2017-09-11 17:37:39 +02:00
Kevin Jahns
526c862071 added test case for moving nodes 2017-09-11 17:35:20 +02:00
Kevin Jahns
fdbb558ce2 persistence db fixes 2017-09-11 16:02:19 +02:00
Kevin Jahns
76ad58bb59 fix example dist script 2017-09-07 23:02:19 +02:00
Kevin Jahns
c88a813bb0 fix tests by removing y-memory include 2017-09-06 20:52:52 +02:00
Kevin Jahns
ccf6d86c98 removed generators 2017-09-06 20:10:38 +02:00
Kevin Jahns
6b5c02f1ce 13.0.0-16 2017-08-26 01:11:31 +02:00
Kevin Jahns
2be6e935a4 fix lint in xml tests 2017-08-26 01:10:50 +02:00
Kevin Jahns
0ddf3bf742 Y.Xml renamed to Y.XmlElement 2017-08-25 20:35:17 +02:00
Kevin Jahns
5f29724578 merge textarea example 2017-08-24 14:46:16 +02:00
Kevin Jahns
ab6cde07e6 Implemented Xml Struct 2017-08-24 14:44:40 +02:00
Kevin Jahns
0455eaa8ad 13.0.0-15 2017-08-14 15:53:54 +02:00
Kevin Jahns
9ed7e15d0f 13.0.0-14 2017-08-14 15:49:15 +02:00
Kevin Jahns
6e633d0bd9 lint 2017-08-14 15:41:37 +02:00
Kevin Jahns
e16195cb54 implement timeout for creating Yjs instance 2017-08-14 15:39:17 +02:00
Kevin Jahns
86c46cf0ec 13.0.0-13 2017-08-13 01:04:37 +02:00
Kevin Jahns
8770c8e934 Implement persistence layer 2017-08-13 01:03:54 +02:00
Kevin Jahns
7e12ea2db5 move array tests and map tests to yjs 2017-08-09 02:21:17 +02:00
Kevin Jahns
3ca260e0da 13.0.0-12 2017-08-04 18:07:44 +02:00
Kevin Jahns
edb5e4f719 send sync step 1 after sync step 2 is processed (for slaves) 2017-08-04 18:06:36 +02:00
Kevin Jahns
be3b8b65ce 13.0.0-11 2017-08-04 16:30:58 +02:00
Kevin Jahns
d093ef56c8 userJoined accepts auth parameter. Sync with all users at once, instead of one at a time 2017-08-04 16:27:07 +02:00
Kevin Jahns
90b2a895b8 13.0.0-10 2017-08-03 00:25:13 +02:00
Kevin Jahns
4f57c91b82 fix syncing protocol - compute messages after auth 2017-08-03 00:24:01 +02:00
Kevin Jahns
3e1d89253f fix unhandled message bug in connector 2017-08-01 17:49:37 +02:00
Kevin Jahns
03e1a3fc12 13.0.0-9 2017-08-01 16:21:38 +02:00
Kevin Jahns
5c33f41c30 fix linting 2017-08-01 16:19:25 +02:00
Kevin Jahns
65e8c29b33 remove all async-functions - making it compatible with node 6 2017-08-01 16:15:36 +02:00
Kevin Jahns
fed77d532f 13.0.0-8 2017-07-31 16:05:30 +02:00
Kevin Jahns
d129184f7b fix linting 2017-07-31 15:43:04 +02:00
Kevin Jahns
a05bb1d4f9 merge bugfix-unable-to-deliver-message branch 2017-07-31 15:40:25 +02:00
Kevin Jahns
65af4963e6 merge bugfix-multiple-clients-sync branch 2017-07-31 15:35:27 +02:00
Kevin Jahns
4dce0816a6 fix preferUntransformed sync 2017-07-31 14:41:40 +02:00
Kevin Jahns
5384bf4faf remove unneccesarry whenTransactionsFinished command 2017-07-31 14:01:34 +02:00
Kevin Jahns
454ac9ba16 remove ds.length == 0 condition for preferUntransformed 2017-07-31 03:19:47 +02:00
Kevin Jahns
e2ec53be65 implemented three-way sync for master-slave apps 2017-07-31 02:06:07 +02:00
Kevin Jahns
aa6edcfd9b add warning for message type when ArrayBuffer is expected 2017-07-31 01:13:52 +02:00
Kevin Jahns
f31ec9a8b8 fixed varUint encoding issue 2017-07-30 22:16:59 +02:00
Kevin Jahns
003fa735a0 enable y-map tests 2017-07-27 15:15:20 +02:00
Kevin Jahns
574f0c3269 fix logging message type 2017-07-27 14:49:36 +02:00
Kevin Jahns
eb4fb3a225 binary encoding bugfixes & export BinaryEncoder + BinaryDecoder 2017-07-24 15:37:04 +02:00
Kevin Jahns
c97130abc4 implement generateUserId for node & clients that dont support crypto 2017-07-22 18:37:48 +02:00
Kevin Jahns
a19cfa1465 redesigned connector protocol - enabled binary compression 2017-07-22 18:07:56 +02:00
Kevin Jahns
bb45abbb70 13.0.0-7 2017-07-22 01:16:50 +02:00
Kevin Jahns
67b47fd868 bugfix - sync step 2 also authenticates) 2017-07-22 01:15:13 +02:00
Kevin Jahns
2c18b9ffad 13.0.0-6 2017-07-21 23:56:13 +02:00
Kevin Jahns
a6b7d76544 bugfix: unable to deliver message. fixes receiving message before authentication 2017-07-21 23:55:11 +02:00
Kevin Jahns
442ea7ec70 13.0.0-5 2017-07-19 21:22:37 +02:00
Kevin Jahns
747da52c0b fix two clients syncing at the time 2017-07-19 21:19:41 +02:00
Kevin Jahns
6c37bd4463 Merge remote-tracking branch 'origin/master' into v13 2017-07-13 20:03:29 +02:00
Kevin Jahns
dd6c196135 link to the IPFS connector 2017-07-13 19:51:29 +02:00
Kevin Jahns
252bec0ad2 implemented binary encoding for all basic structs 2017-07-13 17:42:21 +02:00
Kevin Jahns
6c8876d282 remove option forwardToSyncing clients as it is no longer necessary - it was previously only used by y-webrtc 2017-07-13 00:48:14 +02:00
Kevin Jahns
3c317828d1 Use integer as userId instead of String 2017-07-13 00:37:35 +02:00
Kevin Jahns
cd3f4a72d6 13.0.0-4 2017-07-06 15:17:23 +02:00
Kevin Jahns
2c852c85c6 add node build 2017-07-06 15:16:13 +02:00
Kevin Jahns
434ec84837 13.0.0-3 2017-07-06 03:29:09 +02:00
Kevin Jahns
2b618cd83c change to correct main file 2017-07-06 03:28:06 +02:00
Kevin Jahns
f4327529b9 13.0.0-2 2017-07-05 18:41:26 +02:00
Kevin Jahns
67189f4d44 dont lint in postversion 2017-07-05 18:40:41 +02:00
Kevin Jahns
6225fb4dfd fix linting of examples 2017-07-05 18:33:16 +02:00
Kevin Jahns
a7550fe5d3 13.0.0-1 2017-07-05 18:12:35 +02:00
Kevin Jahns
9d9c84f40e fit y-memory in helper.js 2017-07-05 18:10:24 +02:00
Kevin Jahns
ae91902de3 Yjs throws "error" event in unexpected cases. fixes #72 2017-07-05 17:58:19 +02:00
Kevin Jahns
033d24eee7 use y-memory@v8 directory structure 2017-07-05 17:44:17 +02:00
Kevin Jahns
8abef69aa7 implemented named event handler 2017-07-05 17:01:21 +02:00
Kevin Jahns
7e4dedab38 always use generateUniqueUserId. fixes #74 2017-07-05 11:40:19 +02:00
Kevin Jahns
85e488bbe6 Throw proper error stack when observer function thrown an error - implements #75 2017-07-05 11:37:22 +02:00
Kevin Jahns
a6a321da10 fix textarea example to fit new directory structure 2017-07-05 11:34:28 +02:00
Kevin Jahns
008764ccdc remove dist submodule 2017-07-05 11:26:20 +02:00
Kevin Jahns
de5f4abe32 filter deleted ops only if gc is disabled 2017-07-04 04:59:07 -07:00
Kevin Jahns
382d06f6d4 reworked getOperations (decrease size of sent operations, fixe some gc issues). garbageCollectOperation now sets origin to the direct left operation, if possible 2017-07-03 23:19:11 -07:00
Kevin Jahns
66de422749 fix issues with new master-slave tests 2017-06-30 15:18:07 -07:00
Kevin Jahns
bbf5e39408 implemented client-server model (untested) 2017-06-30 14:07:14 -07:00
Kevin Jahns
c8bca15d72 13.0.0-0 2017-06-30 09:16:58 -07:00
Kevin Jahns
a64730e651 fix several sync issues. improve performance a bit by removing ds from first sync step 2017-06-29 15:04:36 -07:00
Kevin Jahns
409a9414f1 fix the "gc state" warning 2017-06-27 02:07:03 +02:00
Kevin Jahns
24facaab09 fix os comparison in compareUsers 2017-06-21 16:29:51 +02:00
Kevin Jahns
060549f2cb enable gc in random tests 2017-06-19 21:16:42 +02:00
Kevin Jahns
dfe3b0b1d1 Merge branch 'master' into v13 2017-06-19 10:48:16 +02:00
Kevin Jahns
a5506a5ded Release 12.3.1 2017-06-17 14:32:28 +02:00
Kevin Jahns
361d4a48e1 implement getPath for any type. types now initialize _parent. fix some cases where observeDeep is not fired 2017-06-17 14:31:00 +02:00
Kevin Jahns
e23154bec2 update dependencies 2017-06-16 01:04:58 +02:00
Kevin Jahns
1682d43c26 added chancejs to dependencies 2017-06-07 21:43:52 +02:00
Kevin Jahns
68c417fe6f fix gc timeout 2017-05-24 16:34:57 +02:00
Kevin Jahns
2ea163a5cf outsourced helper and test-connector 2017-05-22 13:57:16 +02:00
Kevin Jahns
020dacdad4 removed some unnecessary setTimeouts 2017-05-21 00:31:16 +02:00
Kevin Jahns
42abcc897c added examples 2017-05-19 02:22:00 +02:00
Kevin Jahns
0a321610aa use rollup for yjs 2017-05-16 18:35:30 +02:00
Kevin Jahns
edf47d3491 add disconnect / reconnect return values 2017-05-12 04:19:14 +02:00
Kevin Jahns
14ee42cad5 Release 12.3.0 2017-05-08 12:40:31 +02:00
Kevin Jahns
f990927d3e implemented Y.utils.bubbleEvent 2017-05-08 12:01:51 +02:00
Kevin Jahns
a1cef4662f Release 12.2.1 2017-05-03 18:00:59 +02:00
Kevin Jahns
2c343970c4 fixed sync issue with "preferUntransformed" 2017-05-03 18:00:20 +02:00
Kevin Jahns
74b41e03e3 Release 12.2.0 2017-05-03 16:17:13 +02:00
Kevin Jahns
b242aab955 implemented "preferUntransformed" 2017-05-03 16:13:52 +02:00
Kevin Jahns
8e4efd9bba fixed "waiting for auth" issue in the test suite 2017-04-28 11:21:26 +02:00
Kevin Jahns
47d5899058 fixed test suite. It stopped working because of previous adoptions on the gc behavior. I failed to notice it.. 2017-04-27 14:58:08 +02:00
Kevin Jahns
a126a29876 Added Monaco editor example 2017-04-18 18:24:03 +02:00
Kevin Jahns
4aa720116f add serviceworker example 2017-04-11 16:21:00 +02:00
Kevin Jahns
e29162c3fc Release 12.1.7 2017-04-10 11:22:34 +02:00
Kevin Jahns
aa40855953 Add debug package as dependency. Fixes #66 2017-04-10 10:30:28 +02:00
Kevin Jahns
b6545d62fc update CodeMirror example 2017-03-29 13:43:26 +02:00
Kevin Jahns
3425d95507 update CodeMirror example 2017-03-29 13:23:28 +02:00
Kevin Jahns
53682c17fb added CodeMirror example 2017-03-29 13:21:30 +02:00
Kevin Jahns
a492a83f0c Release 12.1.6 2017-03-20 19:16:06 +01:00
Kevin Jahns
d340e557c1 removed the Changelog from README.md. Instead use the github releases to describe the changes 2017-03-20 19:13:08 +01:00
Kevin Jahns
d5cd9d94d5 implemented logging with the debug logging utility (read the updated docs) 2017-03-20 19:11:59 +01:00
Kevin Jahns
e1a160b894 Release 12.1.5 2017-03-06 13:27:32 +01:00
Kevin Jahns
f996ac83d2 added option *generateUserId* in abstract connector 2017-03-06 13:27:04 +01:00
Kevin Jahns
922637930f Release 12.1.4 2016-12-19 10:42:05 +01:00
Kevin Jahns
ff7e9cdef2 var/let declaration - fixes #61 2016-12-19 10:41:15 +01:00
Kevin Jahns
f02641deb7 Added Yjs Polymer element to module section 2016-12-01 11:15:39 +01:00
Kevin Jahns
f97144356c Release 12.1.3 2016-11-22 13:12:36 +01:00
Kevin Jahns
a9fdd5df66 updated webworker example 2016-11-21 16:29:03 +01:00
Kevin Jahns
e90f241ae0 implemented resetAuth 2016-11-21 01:22:15 +01:00
Kevin Jahns
102bef4f92 added sw example 2016-11-14 16:29:58 +01:00
Kevin Jahns
96e9c3c166 enable empty share property 2016-11-14 16:27:08 +01:00
Kevin Jahns
1080f83990 implemented moduleName, made window statements failsafe 2016-11-14 13:01:41 +01:00
Kevin Jahns
66b6b2a568 added banner to distribution files. Fixes #56 2016-11-14 10:30:10 +01:00
Kevin Jahns
7415f27fbc Release 12.1.2 2016-11-10 17:01:58 +01:00
Kevin Jahns
c9d1f34864 reconnect only when disconnected (and reverse) 2016-11-10 12:54:01 +01:00
Kevin Jahns
34997f940b Release 12.1.1 2016-11-09 14:26:37 +01:00
Kevin Jahns
4e9e21e75e lint 2016-11-09 14:19:13 +01:00
Kevin Jahns
6c375a37c8 update dist dir 2016-11-09 14:18:06 +01:00
Kevin Jahns
cd0cddaf35 fixed several sync issues 2016-11-04 11:42:50 +01:00
Kevin Jahns
93c23ddc09 fixed some gc issues (unfinished) 2016-11-03 16:28:48 +01:00
Kevin Jahns
480dfdfb77 dont modify gc buffer if gcTimeout > 0 or disconnected 2016-11-02 20:55:24 +01:00
Kevin Jahns
dda2a1ef82 another take on sourcedir: null specifies not to load anything automatically 2016-10-31 02:58:21 +01:00
Kevin Jahns
f32ff1b613 fixed several consistency issues with y-indexeddb. Implemented support for .close() - a soft replacement for .destroy() 2016-10-31 01:17:24 +01:00
Kevin Jahns
8ab16f4ada Release 12.1.0 2016-10-29 21:45:38 +02:00
Kevin Jahns
3fdcf82bcc fixed error description for observers that throw errors 2016-10-29 16:55:16 +02:00
Kevin Jahns
6dd33f4f90 copy db, connector, and type properties before handing them over to the connector, etc. This prevents some weird errors using y-elements 2016-10-24 23:10:44 +02:00
Kevin Jahns
0521fac8d8 implemented auth utilities for yjs 2016-10-24 11:57:59 +02:00
Kevin Jahns
666ab8285c update examples 2016-10-13 17:29:24 +02:00
Kevin Jahns
675c7f6638 rephrase intro 2016-10-13 15:53:41 +02:00
Kevin Jahns
463608cb5c Release 12.0.4 2016-10-12 15:52:04 +02:00
Kevin Jahns
d1059b5d04 local sourceDir causes troubles if modules are required by a yjs instance 2016-10-12 15:51:42 +02:00
Kevin Jahns
8b24284e25 Release 12.0.3 2016-10-07 21:00:46 +02:00
Kevin Jahns
08bcdfb008 implemented es6 import utility function (Y.extend(module) === module(Y)) 2016-10-07 21:00:17 +02:00
Kevin Jahns
f93d7b1e70 Release 12.0.2 2016-10-05 01:00:00 +02:00
Kevin Jahns
4d024883bc Fixed "[0] of undefined" server issue 2016-10-04 16:12:24 +02:00
Kevin Jahns
ecd412c6f6 sourcedir is no longer a global variable 2016-10-04 14:54:52 +02:00
Kevin Jahns
b939cdd086 Release 12.0.1 2016-09-27 16:17:33 +02:00
Kevin Jahns
17803266d4 repairChecker: Yjs is now able to detect incorrect states that happen when messages get lost. When Yjs is in an incorrect state it repairs itself and syncs again 2016-09-27 16:12:35 +02:00
Kevin Jahns
f0e88d192c Release 12.0.0 2016-09-20 19:19:18 +02:00
Kevin Jahns
e66c0f8a4e update doc 2016-09-20 19:13:09 +02:00
Kevin Jahns
eba3d590cc update doc 2016-09-20 19:12:41 +02:00
Kevin Jahns
0b31e63b82 update dist 2016-09-20 18:30:52 +02:00
Kevin Jahns
d22fbca6cc ready to publish (lint) 2016-09-01 02:40:35 +02:00
Kevin Jahns
330434ee24 update npm example 2016-08-31 02:58:28 +02:00
Kevin Jahns
2f0216bf89 update help 2016-08-30 21:03:08 +02:00
Kevin Jahns
f9d0625bd2 simplify example 2016-08-30 20:58:17 +02:00
Kevin Jahns
7a9d60770a simplify documentation 2016-08-30 20:43:05 +02:00
Kevin Jahns
059f72ffe1 fix init problems with v12, update examples to be synchronous 2016-08-30 18:10:19 +02:00
Kevin Jahns
d2d74a64ab update dist & added note to changelog 2016-08-29 17:56:39 +02:00
Kevin Jahns
a1f0140069 updated documentation (changelog for v12, added leveldb, consistency) 2016-08-29 17:21:30 +02:00
Kevin Jahns
7bd8e81342 fix test verifier 2016-08-28 22:13:07 +02:00
Kevin Jahns
34f365cd8f implemented support for synchronous type creation 2016-08-26 13:53:31 +02:00
Kevin Jahns
b3ba8e7546 Merge branch 'master' of github.com:y-js/yjs into v12 2016-08-25 04:43:43 +02:00
Kevin Jahns
e1e94bcf5d made createType synchronous 2016-08-25 04:42:23 +02:00
Kevin Jahns
4a83ff8514 updated quill example 2016-08-23 11:13:09 +02:00
Kevin Jahns
4078020afd Release 11.2.5 2016-08-22 12:15:32 +02:00
Kevin Jahns
e31d5e0e1d fixed late-join sync issue & use leveldb only in node environment 2016-08-22 12:05:39 +02:00
Kevin Jahns
acbc884eb5 Release 11.2.4 2016-08-04 19:25:36 +02:00
Kevin Jahns
f9315288d0 found another bug that only happens in persistent databases (operationAdded changes an operation, so it needs to be retrieved again after calling it) 2016-08-01 20:48:55 +02:00
Kevin Jahns
3b0d0343f4 Release 11.2.2 2016-08-01 17:04:06 +02:00
Kevin Jahns
74c881bb5b Fixed bug that only occurs in persistent databases (setOperation was not called). 2016-08-01 16:52:02 +02:00
Kevin Jahns
63f8a891be update dist 2016-07-05 16:21:19 +02:00
Kevin Jahns
2083cdb6b0 several bug-fixes (for y-richtext beta) 2016-07-01 17:45:53 +02:00
Kevin Jahns
2091392031 implemented random seed generator, in order to reproduce tests 2016-06-29 17:48:56 +02:00
Kevin Jahns
3dc67e075b debugged some of the special cases of Utils.receivedOp & found some bugs 2016-06-28 16:23:02 +02:00
Kevin Jahns
81e72126ce implemented new extention for awaitOps. It fixes several consistency issues (they were previously hard to detect), and it is also pretty efficient. It still has some debugger statements, so enjoy with care 2016-06-14 21:27:42 +02:00
Kevin Jahns
e77a753708 fixed bug in array & richtext 2016-06-03 19:04:47 +02:00
Kevin Jahns
bc856a09f5 Release 11.2.1 2016-05-24 15:25:14 +02:00
Kevin Jahns
f7ae62a906 Release 11.2.0 2016-05-10 18:13:01 +02:00
Kevin Jahns
6669be104e Release 11.1.0 2016-05-07 13:20:43 +01:00
Kevin Jahns
14d59de2bd improved awaitOps 2016-05-07 13:16:48 +01:00
Kevin Jahns
483d2c78aa Use uglify-js v2.5.0 to fix #52 2016-05-06 12:57:07 +01:00
Kevin Jahns
5b835563c8 implement new method awaitedOps in favor of awaitedDeletes/awaitedInserts. This will fix some bugs when the type gets out of sync with the state of yjs 2016-05-06 12:53:10 +01:00
Kevin Jahns
996566419c some flush updates 2016-05-04 17:14:39 +02:00
Kevin Jahns
5d6a9872e2 Michael found a weird character in my code 2016-05-02 11:04:24 +02:00
Kevin Jahns
8930865a21 Release 11.0.4 2016-05-02 11:00:07 +02:00
Kevin Jahns
2897695680 update dist, more args for SmallLookupBuffer 2016-04-30 23:01:36 +01:00
Kevin Jahns
5118f02b49 Release 11.0.3 2016-04-27 12:04:39 +01:00
Kevin Jahns
a10933beef fixed awaitedInserts (critical for y-richtext) 2016-04-27 12:02:39 +01:00
Kevin Jahns
c2ffe0b697 Release 11.0.2 2016-04-26 21:28:21 +02:00
Kevin Jahns
2d1a7b067b fixed some minor problems related to compareId 2016-04-26 21:27:08 +02:00
Kevin Jahns
2675f0277c Release 11.0.1 2016-04-26 15:34:19 +02:00
Kevin Jahns
918bc334b2 Release 11.0.0 2016-04-26 15:02:44 +02:00
Kevin Jahns
accf0dbafb fixed bump script 2016-04-26 15:01:22 +02:00
Kevin Jahns
6b8ce0ab4f changed the observe functionality 2016-04-25 16:32:45 +02:00
Kevin Jahns
71bf6438e1 found some gc bugs that occur when using deletion lengths 2016-04-25 13:09:52 +02:00
Kevin Jahns
90b7b01e9a fixes #49 2016-04-22 22:09:49 +01:00
Kevin Jahns
895ec86ff6 all tests working. Fixed an older bug: When gc an op I forgot to update the state. This only affected offline editing, and was very hard to catch in the past 2016-04-22 21:27:43 +01:00
Kevin Jahns
bffd130b92 fixed first two random cases, (gc seems still to be an issue ..) 2016-04-21 18:04:46 +02:00
Kevin Jahns
feae0d51bd fixed content.length in tryExecute 2016-04-20 12:37:56 +02:00
Kevin Jahns
f46c8df605 fixed some cases that lead to inconsistencies 2016-04-20 12:03:06 +02:00
Kevin Jahns
82025c5de9 better debugging, pretty print (no undefined) in logtable 2016-04-19 16:34:14 +02:00
Kevin Jahns
153ec811e2 fixed some gc bugs, improved applyDeleteSet 2016-04-18 16:13:29 +02:00
Kevin Jahns
01031d27c3 some gc fixes 2016-04-18 10:48:48 +01:00
Kevin Jahns
c72f62ecb6 implemented support for range of deletions (unfinished) 2016-04-14 18:09:27 +02:00
Kevin Jahns
e1df1a7a12 fixed one more problem with ds & fixed ace example & insertions are combined even when created in different execution tasks 2016-04-13 16:59:54 +02:00
Kevin Jahns
a7f845f553 fixed some old todos, fixed some cases related to "content is an array" 2016-04-12 16:18:05 +02:00
Kevin Jahns
20321c8a7d fixed test connector buffer to really be parallel! 2016-04-11 16:20:27 +02:00
Kevin Jahns
f3fadd3895 test suite works again with "contentS" feature! 2016-04-11 15:07:08 +02:00
Kevin Jahns
08a79d0e7b several bug fixes regarding "content is an array" 2016-04-07 15:54:47 +02:00
Kevin Jahns
5b21104da3 del is applied after ins (type is always called when ins already deleted) 2016-04-06 15:45:30 +02:00
Kevin Jahns
ecc2aef0f8 update 2016-04-05 15:38:22 +02:00
Kevin Jahns
1c32067908 implementing new insertion struct (unfinished) 2016-04-05 10:43:57 +01:00
Kevin Jahns
fe75ed6208 typos in README.md 2016-03-24 12:00:19 +01:00
Kevin Jahns
c2404b1e98 Release 10.0.3 2016-03-23 19:55:56 +01:00
Kevin Jahns
f363e1e9fc Merge branch 'master' of https://github.com/y-js/yjs 2016-03-23 19:54:40 +01:00
Kevin Jahns
749514c074 update dist 2016-03-23 19:54:28 +01:00
Kevin Jahns
24f8616386 Release 10.0.2 2016-03-23 14:42:26 +01:00
Kevin Jahns
d4ee8af772 Release 10.0.1 2016-03-23 14:41:08 +01:00
Kevin Jahns
83a42271ad fix remaining memory leaks 2016-03-23 14:33:51 +01:00
Kevin Jahns
88971b4e69 fixed several issues of the gc. I.e. the gc sometimes did not collect the whole subtree when deleting an operation 2016-03-21 21:00:28 +01:00
Kevin Jahns
f844dcbc1e bugfixes creating structs without loading type (e.g. for y-websockets-server) 2016-03-14 19:46:57 +01:00
Kevin Jahns
c9c00b5a08 found bug: types are not called anymore 2016-03-11 01:08:26 +01:00
Kevin Jahns
d79e3102fc new approach for type definitions 2016-03-10 17:49:36 +01:00
Kevin Jahns
ba4f444f32 Implemented support for composite type, fixed insert type issues for y-array 2016-02-29 13:46:08 +01:00
Kevin Jahns
effc2fe576 Release 9.0.4 2016-02-24 12:00:50 +01:00
Kevin Jahns
f9a54626b1 update dist 2016-02-24 12:00:27 +01:00
Kevin Jahns
808a07d218 added some error messages 2016-02-24 11:40:19 +01:00
Kevin Jahns
afbe81a602 update .gitignore 2016-02-24 10:09:56 +01:00
Kevin Jahns
2883947641 remove jsconfig 2016-02-24 10:08:11 +01:00
Kevin Jahns
1c15edd332 remove another .vscode 2016-02-24 10:07:07 +01:00
Kevin Jahns
214380c3ca updated changelog 2016-02-23 16:24:07 +01:00
Kevin Jahns
ecbf03ab10 Release 9.0.3 2016-02-23 15:50:19 +01:00
Kevin Jahns
5aedddeea3 update dist 2016-02-23 15:48:15 +01:00
Kevin Jahns
babdb765c5 Release 9.0.2 2016-02-23 15:42:13 +01:00
Kevin Jahns
43b4d59f9b updated package.json, major version upgrade, added peerDependencies 2016-02-23 15:41:28 +01:00
Kevin Jahns
64a5fae838 Release 9.0.1 2016-02-23 11:58:14 +01:00
Kevin Jahns
5036053d9c added peer dependencies, upgraded version to major (new versioning scheme) 2016-02-23 11:57:44 +01:00
Kevin Jahns
0ec249d388 Release 0.8.28 2016-02-23 11:27:30 +01:00
Kevin Jahns
be68a25904 Implement vesion header. Different version headers must not sync. implements #48 2016-02-23 11:21:37 +01:00
Kevin Jahns
fc92b12e85 Release 0.8.27 2016-02-22 13:08:05 +01:00
Kevin Jahns
e35f4d19f3 Release 0.8.26 2016-02-22 13:06:15 +01:00
Kevin Jahns
6d3c4b21fb Release 0.8.25 2016-02-22 13:04:36 +01:00
Kevin Jahns
339590f49e Release 0.8.22 2016-02-22 12:38:26 +01:00
Kevin Jahns
429c1f83c1 Merge pull request #45 from istvank/master
Making documentation consistent
2016-02-18 17:33:04 +01:00
Kevin Jahns
03bab63358 Release 0.8.21 2016-02-18 16:57:32 +01:00
Kevin Jahns
06ef22b8ca sorry sorry sorry -.- fixes #47 2016-02-18 16:52:13 +01:00
Kevin Jahns
f579a436c7 Release 0.8.20 2016-02-16 16:08:54 +01:00
Kevin Jahns
da7e67d97d implemented destroy & updated disconnect 2016-02-16 15:51:12 +01:00
Kevin Jahns
bd54a43a33 Release 0.8.18 2016-02-15 15:22:55 +01:00
Kevin Jahns
68c21131d3 Remove that single \for.. in\ loop that appearantly causes troubles for istvan (why am I fixing this again?) fixes #46 2016-02-15 15:21:11 +01:00
István Koren
3826d9b592 Make it consistent with npm doc few lines below 2016-02-14 13:24:12 +01:00
István Koren
fa9ff669e4 Merge pull request #1 from y-js/master
Updating to latest yjs version
2016-02-13 13:14:43 +01:00
Kevin Jahns
bca7477ca5 Release 0.8.17 2016-02-04 23:13:51 +01:00
Kevin Jahns
b40b7e10ab Release 0.8.16 2016-02-04 23:12:53 +01:00
Kevin Jahns
d20141fec1 Release 0.8.15 2016-02-04 23:11:11 +01:00
Kevin Jahns
5f2a81d064 updated api documentation 2016-02-04 23:08:29 +01:00
Kevin Jahns
56ba55cbab Release 0.8.14 2016-02-04 15:26:32 +01:00
Kevin Jahns
7be262e9f3 fixing @Joeao bug 2016-02-04 15:26:09 +01:00
Kevin Jahns
1da76dbc20 update dist 2016-02-04 12:53:39 +01:00
Kevin Jahns
8924c3e163 Release 0.8.13 2016-02-04 12:47:09 +01:00
Kevin Jahns
608b5e3319 Release 0.8.12 2016-02-04 12:12:57 +01:00
Kevin Jahns
d532fc530f update dist 2016-02-04 12:06:06 +01:00
Kevin Jahns
a5760a45bb Release 0.8.11 2016-02-04 10:53:04 +01:00
Kevin Jahns
437955ba84 update 2016-02-03 11:47:07 +01:00
Kevin Jahns
dab72be87f update 2016-02-03 11:37:36 +01:00
Kevin Jahns
89a6ec374e update 2016-01-27 17:05:28 +01:00
Kevin Jahns
4b6352b11a typo 2016-01-27 11:34:11 +01:00
Kevin Jahns
31d2a231e3 Further reduced number of db requests 2016-01-26 15:30:19 +01:00
Kevin Jahns
6b1cf18822 Improvements on DS lookups 2016-01-26 11:29:58 +01:00
Kevin Jahns
39dc2317b7 Implemented more efficient garbage collectior
from worst case of O(n) -> O(1) - where n is the number of insertions in
a list

So this is a huge improvement, I guess :)
2016-01-23 20:09:30 +01:00
Kevin Jahns
38bf398709 Improvements that are required for offline editing 2016-01-23 01:02:01 +01:00
Kevin Jahns
364ed325b0 fixed spec 2016-01-22 14:16:16 +01:00
Kevin Jahns
1b3f5443b3 implemented small lookup buffer. This heavily improves lookups for slow databases 2016-01-22 14:09:51 +01:00
Kevin Jahns
37ac7787d0 Update garbage collect algorithm. Fixed some tests appearantly :) 2016-01-21 21:08:20 +01:00
Kevin Jahns
8e4cf83330 typos 2016-01-18 17:21:47 +01:00
Kevin Jahns
5524ab9c20 Release 0.8.9 2016-01-18 16:45:46 +01:00
Kevin Jahns
65dc716936 Release 0.8.8 2016-01-18 15:40:38 +01:00
Kevin Jahns
5b7a4482cf Release 0.8.7 2016-01-16 01:45:58 +01:00
Kevin Jahns
cfa089f7cf Release 0.8.6 2016-01-16 01:42:00 +01:00
Kevin Jahns
190442a58d update documentation 2016-01-16 01:40:26 +01:00
Kevin Jahns
0398b5260a Release 0.8.5 2016-01-15 18:09:46 +01:00
Kevin Jahns
8544c16771 Release 0.8.4 2016-01-15 17:58:08 +01:00
Kevin Jahns
a5f55359c3 improve data exchange performance 2016-01-15 17:57:06 +01:00
Kevin Jahns
102555a3b0 Release 0.8.3 2016-01-15 03:46:55 +01:00
Kevin Jahns
ece8268e44 Release 0.8.2 2016-01-15 03:10:58 +01:00
Kevin Jahns
dd279bccf7 Release 0.8.1 2016-01-15 00:03:43 +01:00
Kevin Jahns
7e046e0753 Release 0.8.0 2016-01-15 00:02:12 +01:00
Kevin Jahns
51a834d6c9 Implemente a new sync procedure that is optimal with respect to big O notation (there is probably a way to reduce it by a factor of 1/2) 2016-01-15 00:00:41 +01:00
Kevin Jahns
a33d0bf7bc Release 0.7.6 2016-01-11 15:48:10 +01:00
Kevin Jahns
fd6a28eb25 Release 0.7.5 2016-01-11 15:47:24 +01:00
Kevin Jahns
579fd52455 publish v0.7.3 2016-01-09 21:08:02 +01:00
Kevin Jahns
8cfc9d41c3 Made compatible with windows 2016-01-09 04:17:23 +01:00
Kevin Jahns
bdf290adb2 added safety to setUserId (when called twice) 2015-12-30 16:37:35 +01:00
Kevin Jahns
98d87cb26d update 2015-12-18 16:34:21 +01:00
Kevin Jahns
fbbfa9fd47 added example 2015-12-09 18:40:10 +01:00
Kevin Jahns
72bd0d9c3a update map type 2015-12-08 16:26:55 +01:00
Kevin Jahns
3dbeb2c415 Merge pull request #34 from istvank/master
Changed to semver ;)
2015-12-08 14:17:29 +01:00
István Koren
2a9fd96958 Changed to semver ;)
Two lines below it states you switch to semver, still there was 1.0... ;)
2015-12-08 12:08:12 +01:00
Kevin Jahns
9d34ccfdbc update 2015-12-03 18:05:12 +01:00
Kevin Jahns
7753994e36 fixed bugs resolving from new init style 2015-12-03 17:27:13 +01:00
Kevin Jahns
709779425c make module import safer 2015-12-02 20:04:59 +01:00
Kevin Jahns
334db3234b outsourced Y.Map type 2015-12-02 16:57:55 +01:00
Kevin Jahns
0db7fe5d46 added support for static content, added jigsaw puzzle 2015-12-02 15:58:22 +01:00
Kevin Jahns
3a55ca4f21 update 2015-12-01 19:27:14 +01:00
Kevin Jahns
8d14a9cbba starting to implement new sharedObjects idea 2015-11-30 15:56:45 +01:00
Kevin Jahns
f6c5051472 added es6 distribution & gulp task for es6 distribution 2015-11-30 15:25:55 +01:00
Kevin Jahns
eff6fb1cc5 added flow support for everything except tests 2015-11-30 15:02:34 +01:00
Kevin Jahns
0ebfae6997 added flow support for Transaction.js 2015-11-30 14:26:22 +01:00
Kevin Jahns
e9c40f9a83 added flow support for Struct.js 2015-11-30 12:47:33 +01:00
Kevin Jahns
da2762edf5 added flow support for Connector.js 2015-11-30 12:26:02 +01:00
Kevin Jahns
bd9c3813fd * starting flow integration
* found a bug in EventHelper
* reduce wait() calls
2015-11-26 00:46:02 +01:00
Kevin Jahns
940a44bb7c fix transaction wait bug 2015-11-25 16:04:01 +01:00
Kevin Jahns
aa2e7fd917 Added jsconfig.json, fixed tests for large numbers 2015-11-20 21:18:34 +01:00
Kevin Jahns
9fc55f5386 update readme 2015-11-19 18:10:31 +01:00
Kevin Jahns
8ee563f873 finally fixed the timeout hack for tests 2015-11-18 16:17:59 +01:00
Kevin Jahns
5fcfbbfe94 updated build process 2015-11-17 15:28:45 +01:00
Kevin Jahns
8870fdc495 lint 2015-11-15 02:14:06 +01:00
Kevin Jahns
58a612eaa1 added option for servers that want to propagate applied operations (aka the websockets connector) 2015-11-15 02:04:06 +01:00
Kevin Jahns
ae12b087e7 fixed module loading issue 2015-11-14 20:53:38 +01:00
Kevin Jahns
528dbc6e5a announcing new version in readme 2015-11-14 20:44:54 +01:00
Kevin Jahns
1deb453cc5 fixed the dist build process 2015-11-14 20:41:34 +01:00
Kevin Jahns
099297ebdf working on build process 2015-11-13 16:09:40 +01:00
Kevin Jahns
3faeb628fd updated dist build process 2015-11-12 20:42:58 +01:00
Kevin Jahns
d1e30c5040 updated examples and dist build 2015-11-11 17:19:22 +01:00
Kevin Jahns
fa45ce04ef prettyfied README for website 2015-11-11 00:00:15 +01:00
Kevin Jahns
2d20fd59d0 outsourced Textbind, improved automatic module loader 2015-11-09 03:03:37 +01:00
Kevin Jahns
08d07796ee added spec helper 2015-11-07 22:20:47 +01:00
Kevin Jahns
010d0d684e fixed linting 2015-11-07 22:18:28 +01:00
Kevin Jahns
6dc347642b implemented module loader for yjs 2015-11-07 22:12:48 +01:00
Kevin Jahns
138afe39dc improving.. breaking.. the gulpfile 2015-11-06 16:16:38 +01:00
Kevin Jahns
0832be2380 improved error messaging.. thats it for today 2015-11-05 17:20:27 +01:00
Kevin Jahns
8a2a184f30 Release 0.6.32 2015-11-05 17:09:01 +01:00
Kevin Jahns
4882e77fdd improved gulpfile.helper 2015-11-05 16:55:03 +01:00
Kevin Jahns
78f4f6f5b9 implemented gulpfile.helper 2015-11-05 15:53:26 +01:00
Kevin Jahns
317f7f19bb updated gulpfile to wiki 2015-11-05 00:35:11 +01:00
Kevin Jahns
00f58ba68f fixed travis 2015-11-04 17:12:59 +01:00
Kevin Jahns
029a169114 fixed serve:examples 2015-11-04 17:06:20 +01:00
Kevin Jahns
f58889a05d outsourced examples 2015-11-04 16:53:02 +01:00
Kevin Jahns
e9ac59dcf8 fixed tests, finalizing the scripts (sorry for all the commits -.-) 2015-11-04 15:01:12 +01:00
Kevin Jahns
57cf20555f Deploy 0.6.21 2015-11-04 14:39:54 +01:00
Kevin Jahns
805ed3b577 Deploy 0.6.20 2015-11-04 14:37:06 +01:00
Kevin Jahns
2a0d5c0cd7 Deploy 0.6.19 2015-11-04 14:36:01 +01:00
Kevin Jahns
13ed66c326 Deploy 0.6.18 2015-11-04 14:35:08 +01:00
Kevin Jahns
1c35198839 Deploy 0.6.17 2015-11-04 14:33:44 +01:00
Kevin Jahns
a7021b9212 Deploy 0.6.16 2015-11-04 14:32:04 +01:00
Kevin Jahns
1fa1f1a668 bumps package version 2015-11-04 14:10:01 +01:00
DadaMonad
243e62e320 bumps package version 2015-11-02 13:14:52 +00:00
DadaMonad
15e933ee5b bumps package version 2015-11-02 13:04:55 +00:00
DadaMonad
605e1052ac bumps package version 2015-11-02 13:04:08 +00:00
DadaMonad
16c00525d1 bumps package version 2015-11-02 12:57:00 +00:00
Kevin Jahns
e9da461625 update 2015-10-30 16:00:08 +01:00
Kevin Jahns
a071c07ee2 added dist submodule 2015-10-30 15:30:02 +01:00
DadaMonad
8dad4f6ed4 updated documentaiton 2015-10-25 16:15:03 +00:00
Kevin Jahns
0980609cc9 fixed bug in delete operations 2015-10-19 11:27:49 +02:00
Kevin Jahns
29f3f3f722 added offline editing demo 🌟 2015-10-18 03:07:34 +02:00
Kevin Jahns
04139d3b7e implemented indexedDB database :shipit: 2015-10-17 23:02:51 +02:00
Kevin Jahns
45814c4e00 fixed bug (o.right is already gc'd), implemented some test helpers 2015-10-17 17:16:36 +02:00
Kevin Jahns
cf365b8902 started to remove everything RBTree related from the Transaction.js 2015-10-16 12:31:03 +02:00
Kevin Jahns
aff10fa4db started refactoring the Memory db 2015-10-15 18:54:29 +02:00
Kevin Jahns
181595293f refactored database 2015-10-14 19:28:19 +02:00
Kevin Jahns
ee133ef334 refactored test suites 2015-10-14 18:10:04 +02:00
Kevin Jahns
661232f23c fixed the test suite 2015-10-14 10:27:46 +02:00
Kevin Jahns
541a93d152 refactoring the tarnsition functions 2015-10-13 21:40:36 +02:00
Kevin Jahns
d6e1cd42a2 implemented disconnect/reconnect in webrtc connector. adapted the example gc also collects child elements (needs improvements) 2015-10-13 14:50:54 +02:00
Kevin Jahns
51e20fb9c7 fixed some example issues 2015-10-12 15:59:22 +02:00
Kevin Jahns
e32aef4c9f late join works (also when activating garbage collector), added some tests to verify (havent tested for large >500 operations) 2015-10-12 15:17:12 +02:00
Kevin Jahns
9c4074e3e3 fixed late join issues when gc is turned off 2015-10-11 03:06:26 +02:00
Kevin Jahns
aadef59934 fixed DS bugs (i guess..) now handling more complicated scenarios 2015-10-09 16:09:00 +02:00
Kevin Jahns
6a13419c62 fixed several bugs in multi join/rejoin 2015-10-08 02:12:20 +02:00
Kevin Jahns
1ace3e3120 implemented observePath, fixed some inconsistencies 2015-10-06 19:45:29 +02:00
Kevin Jahns
c95dae3c33 fixed inconsistency bugs for tests<1000 2015-10-06 14:22:52 +02:00
Kevin Jahns
82e2254302 fixed some inconsistency bugs with DS 2015-10-05 14:24:11 +02:00
DadaMonad
6e9f990d5c small fixes that i made on the train 2015-10-05 09:48:32 +00:00
DadaMonad
7d4adf314d fixed some bugs from the last commit 2015-10-02 08:01:58 +00:00
Kevin Jahns
8745fd64ca code refactoring, and documentation 2015-09-29 13:59:38 +02:00
Kevin Jahns
638c575dfc fixed some consistency bugs. new method seems to work well, it still has problems though 2015-09-29 01:01:04 +02:00
Kevin Jahns
acf8d37616 added deploy gulp method 2015-09-28 23:54:56 +02:00
Kevin Jahns
ae8be1ec6b improved new sync idea (save gcs in DS) 2015-09-28 13:06:17 +02:00
Kevin Jahns
a5f76cee84 starting to extend the DS with gc functionality 2015-09-27 20:02:00 +02:00
Kevin Jahns
2013266d56 merged changes on home pc. some improvements on rejoin&sync 2015-09-27 00:58:23 +02:00
Kevin Jahns
b08aeee4fc updating some changes i forgot to commit 2015-09-26 14:42:50 +02:00
Kevin Jahns
183f30878e checking out new gc approach 2015-09-25 16:00:20 +02:00
Kevin Jahns
5e4c56af29 fixed bugs, tests are running, source is documented 2015-09-17 20:30:40 +02:00
Kevin Jahns
13bef69be4 updated gitignore 2015-09-17 02:34:43 +02:00
Kevin Jahns
b1d70ef25e added comments to most of the classes. 2015-09-17 00:21:01 +02:00
Kevin Jahns
6f3a291ef5 fixed some tests, lint, better run-scripts 2015-09-16 16:25:30 +02:00
Kevin Jahns
2a601ac6f6 fixed some bugs & linted & prettyfied gulpfile 2015-09-13 18:22:45 +02:00
Kevin Jahns
82b3e50d49 new build system 2015-09-11 18:35:32 +02:00
Kevin Jahns
4bfe484fc2 node-inspector 2015-09-10 19:41:07 +02:00
Kevin Jahns
b9e21665e2 update 2015-09-09 20:29:39 +02:00
Kevin Jahns
06e7caab2d gc implementation 2015-07-26 16:03:13 +00:00
Kevin Jahns
c8ded24842 started implementing the garbage collector 2015-07-26 03:13:13 +00:00
Kevin Jahns
dae0f71cbc fixed another test 2015-07-26 00:01:53 +00:00
Kevin Jahns
81c601c65f fixed late sync with deletions 2015-07-25 23:58:57 +00:00
Kevin Jahns
56165a3c10 late sync with insertions only work now 2015-07-25 23:26:52 +00:00
Kevin Jahns
5e0d602e12 finished & tested DeleteStore 2015-07-25 16:28:05 +00:00
Kevin Jahns
420821be31 continuing DeleteStore 2015-07-24 22:24:49 +02:00
Kevin Jahns
d1fda080d9 added some fixes and started DeleteStore implementation 2015-07-22 19:30:00 +02:00
Kevin Jahns
dd5e2adc87 update 2015-07-21 17:25:07 +02:00
Kevin Jahns
ee983ceff6 switched to *standard* coding style 2015-07-21 17:15:38 +02:00
Kevin Jahns
ee116b8ca4 fixed all the tests 2015-07-19 23:31:35 +00:00
Kevin Jahns
d4ef54358b re-implementing tests with async await. tests also check asynchronous behaviour now. 2015-07-18 23:15:20 +02:00
Kevin Jahns
ebc628adfc fixed really nasty bug, requestTransaction was called synchronously 2015-07-17 15:04:00 +02:00
Kevin Jahns
4563ccc98e fixed trailing space bug in contenteditable elements 2015-07-17 10:43:39 +02:00
Kevin Jahns
a4f7f5c987 fixed bugs that came wih the last commit 2015-07-17 10:34:43 +02:00
Kevin Jahns
4a7f09c32d last bug fixes for TextBind type (for now) 2015-07-16 06:53:47 +02:00
Kevin Jahns
f78dc52d7b added textbind example, improved & fixed syncing, RBTree handles ids correctly now, webrtc connector is quite reliable now 2015-07-16 06:15:23 +02:00
Kevin Jahns
f9f8228db6 outsourcing some code. custom types definition change 2015-07-15 22:32:36 +02:00
Kevin Jahns
60b75d1862 array & type are observeable 2015-07-15 21:24:05 +02:00
Kevin Jahns
9b3fe2f197 webrtc connector working 2015-07-14 22:39:01 +02:00
Kevin Jahns
6b153896dd delete support for Array & Map 2015-07-14 20:51:07 +02:00
Kevin Jahns
66a7d2720d split the big text suite into smaller ones 2015-07-14 11:58:43 +02:00
Kevin Jahns
d50d34dc12 created Array type that has a good time complexity for both insert and retrieval of objects 2015-07-12 03:45:12 +02:00
Kevin Jahns
8cc374cabb added eventhandler 2015-07-10 15:00:54 +02:00
Kevin Jahns
8e9e62b3d0 discontinuing todays session 2015-07-09 22:19:10 +02:00
Kevin Jahns
9b45a78e58 fixing types. 2015-07-09 15:50:59 +02:00
Kevin Jahns
f862fae473 fixed a bug 2015-07-09 01:33:46 +02:00
Kevin Jahns
0493d99d57 list and map types work now and they support delete. added random tests 2015-07-09 01:30:57 +02:00
Kevin Jahns
a1026bc365 use RBTree for in-memory storage 2015-07-08 21:25:36 +02:00
Kevin Jahns
fe4564542b implemented deletion of elements & and iteration method & lots of tests 2015-07-08 20:05:18 +02:00
Kevin Jahns
7b52111c31 fixed insertion bug in RBTree. adding does now work correctly 2015-07-07 21:17:28 +02:00
Kevin Jahns
c184cb961b implemented RBTree as a in-memory database for operations (in progress) 2015-07-07 18:11:27 +02:00
Kevin Jahns
02f2f6b0fe wrap up todays session 2015-07-06 23:39:28 +02:00
Kevin Jahns
e47dee53a3 random tests succeed on Map :) 2015-07-06 23:04:01 +02:00
Kevin Jahns
9b6183ea70 custom types work. Now I need to re-implement the test case from 0.5 2015-07-06 18:37:54 +02:00
Kevin Jahns
79ec71d559 added test case 2015-07-06 16:57:30 +02:00
Kevin Jahns
bf4d5f24a8 simple conflicts are now handled correctly 2015-07-06 16:47:49 +02:00
Kevin Jahns
9d0373b85b added not working tests 2015-07-03 14:43:08 +02:00
Kevin Jahns
f8ad9abcc0 late join should work now. Need to test more. root is passed to transaction generator 2015-06-30 17:57:19 +02:00
Kevin Jahns
b25977be06 Map type works with simple update & sync. now going to implement support for syncing existing operation buffers 2015-06-30 15:44:14 +02:00
Kevin Jahns
bffbb6ca27 basic get&set of Map properties works 2015-06-29 13:20:19 +02:00
Kevin Jahns
8f63147dbc added Map struct 2015-06-28 12:42:54 +02:00
Kevin Jahns
7a274565e5 added memory data store (actually adding it..) 2015-06-28 11:14:40 +02:00
Kevin Jahns
75793d0ced added memory data store 2015-06-28 01:42:17 +02:00
Kevin Jahns
7ec409e09f linted all files 2015-06-27 19:01:15 +02:00
Kevin Jahns
fec03dc6e1 added test connector, webrtc connector, ideas to apply operations with very low overhead 2015-06-25 18:41:00 +02:00
Kevin Jahns
3142b0f161 added some Operations, a connector, more structure. In particular I put a lot of time into the event handling 2015-06-21 14:56:41 +02:00
Kevin Jahns
042bcee482 now using one master generator, that rulez them all 2015-06-21 09:45:57 +02:00
Kevin Jahns
b3e09d001f updated whenOperationExists 2015-06-21 03:50:58 +02:00
Kevin Jahns
dcec0fe967 Implemented some operations. OperationStore executes now ops, not the Engine 2015-06-21 02:24:41 +02:00
Kevin Jahns
ae790b6947 updated OperationBuffer 2015-06-19 14:54:35 +02:00
Kevin Jahns
4b08cbe875 no more promises in requestTransaction :) 2015-06-18 15:11:22 +02:00
Kevin Jahns
01173879a0 Merge pull request #25 from y-js/origin/0.6
merging the infamous `origin/origin/0.6` branch
2015-06-18 11:47:47 +02:00
Kevin Jahns
6f99ee5c34 requestTransaction accepts Promises&Generators 2015-06-18 02:35:52 +02:00
Kevin Jahns
8d1bccbea0 added new generator approach 2015-06-17 19:16:52 +02:00
Kevin Jahns
b6c278f8e4 added indexeddb 2015-06-16 20:13:14 +02:00
Kevin Jahns
5a9f59913e changed to pre-commit 2015-06-16 19:51:14 +02:00
Kevin Jahns
bf493216a2 updated gitignore, flow working 2015-06-16 17:45:05 +02:00
Kevin Jahns
d37d0ef9af update 2015-06-16 17:18:40 +02:00
Kevin Jahns
c7a6e74dd9 updated precommit 2015-06-16 16:20:38 +02:00
Kevin Jahns
24570b791a defined specs 2015-06-16 14:41:35 +02:00
Kevin Jahns
f99853529e improved gulpfile 2015-06-16 14:36:00 +02:00
Kevin Jahns
159f37474d checking out new stuff 2015-06-15 14:53:02 +02:00
Kevin Jahns
1b63f5efde added lots of magic 2015-06-09 22:30:42 +02:00
Kevin Jahns
c3ba8173d7 added v0.6 info note 2015-06-09 18:10:11 +02:00
Kevin Jahns
7a89c1cc6d added first prototype of the new HB with indexedDB 2015-06-09 18:08:23 +02:00
Kevin Jahns
c5b47e88ac bump version numbers 2015-05-28 15:47:43 +02:00
Kevin Jahns
dc3c6a5d42 added support to use existing user ids! Fixes #23 2015-05-28 15:44:13 +02:00
Kevin Jahns
a9c2ec6ba0 Merge pull request #22 from cphyc/bugfix-21
Bugfix 21
2015-05-21 14:51:48 +02:00
Corentin STG_CADIOU
f166b9efc5 Compiled files 2015-05-21 14:39:13 +02:00
Corentin STG_CADIOU
0441b83f74 Fix error with compute_when_synced 2015-05-21 14:28:47 +02:00
Kevin Jahns
90c82a6a02 Merge pull request #20 from cphyc/Fix-error-in-package.json
Use correct path for gulp
2015-05-19 13:31:56 +02:00
cphyc
da25905b73 Use correct path for gulp 2015-05-19 10:47:36 +02:00
Kevin Jahns
3c07a938cd prepublish yjs 2015-05-07 13:34:42 +02:00
Kevin Jahns
55ccacc442 added doc 2015-05-05 16:09:34 +02:00
Kevin Jahns
946a11f03d fixing possible source of a bug in y-rt 2015-05-05 12:55:21 +02:00
Kevin Jahns
93f3a49396 fixed problem in large sendHB 2015-05-04 13:25:12 +02:00
Kevin Jahns
3eed100b8d updated compiled files 2015-05-03 19:59:41 +02:00
Kevin Jahns
eb136ae1bf update README 2015-05-03 19:57:51 +02:00
Kevin Jahns
006d0a2643 update README 2015-05-03 19:56:44 +02:00
Kevin Jahns
7959bdf5ac Merge pull request #19 from y-js/0.5
0.5
2015-05-03 19:51:50 +02:00
Kevin Jahns
6f9ee0d9ba added tutorial in README 2015-05-03 19:50:59 +02:00
Kevin Jahns
d901d5f5e4 small fixes 2015-04-30 16:29:48 +02:00
Kevin Jahns
b2c7706a2e fixed y-object polymer 2015-04-30 15:09:10 +02:00
Kevin Jahns
4d926cf841 updated examples 2015-04-30 14:15:48 +02:00
Kevin Jahns
0314a1b709 Merge pull request #18 from y-js/0.5
Added support for custom connectors. Not compatible with 0.4!!
2015-04-30 12:42:38 +02:00
Kevin Jahns
8a5b69e86c better fix for #17 2015-04-30 09:48:39 +02:00
Kevin Jahns
ce5250b9d8 updated readme 2015-04-29 01:07:12 +02:00
Kevin Jahns
f51c791490 updated readme 2015-04-29 00:57:36 +02:00
Kevin Jahns
b75305a082 updated readme 2015-04-29 00:55:11 +02:00
Kevin Jahns
8d80fd5614 updated readme 2015-04-29 00:54:27 +02:00
Kevin Jahns
bad6c913fc upd 2015-04-28 16:07:45 +02:00
Kevin Jahns
85d85540e7 updated Composition (error when doing undo) 2015-04-28 14:57:37 +02:00
Kevin Jahns
80f1cfd21b added user events 2015-04-28 11:31:43 +02:00
Kevin Jahns
729d7ed3aa fixed getNext & getPrev 2015-04-24 13:52:17 +02:00
Kevin Jahns
0a89150fab insertions must not be deleted anymore! 2015-04-23 17:40:40 +02:00
Kevin Jahns
6fc33e40bb observer will get the reference too now (ListManager) 2015-04-23 15:27:20 +02:00
Kevin Jahns
7f6592a6b7 removed phantom 2015-04-20 11:51:52 +02:00
Kevin Jahns
b9cdbcc6fa deleted debug log 2015-04-19 19:21:05 +02:00
Kevin Jahns
2a78cdba48 Operation can now save static content/Operations 2015-04-19 18:54:03 +02:00
Kevin Jahns
b02662c36e refs, complex saveOperation' and validateSavedOperations` 2015-04-17 20:11:05 +02:00
Kevin Jahns
f44f463e9d references & composition value
fixing bugs with references
composition type parses now composition value
2015-04-17 00:36:52 +02:00
Kevin Jahns
757bb118ce Insert bug detected (because of references) 2015-04-16 02:31:22 +02:00
DadaMonad
5417ffb999 non-important update 2015-04-14 17:14:43 +00:00
DadaMonad
4de979bc33 Merge branch '0.5' of https://github.com/rwth-acis/yjs into 0.5 2015-04-14 17:13:27 +00:00
DadaMonad
875f56586e added parameter to getNext 2015-04-14 17:13:16 +00:00
Kevin Jahns
249b712648 MapManager returns null, when reference does not exist 2015-04-14 01:30:35 +02:00
DadaMonad
58cefae839 updated composition 2015-04-12 13:09:10 +00:00
DadaMonad
d9c5ab5fa8 added support for getNext/getPrev on insertions 2015-04-07 10:37:50 +00:00
DadaMonad
6d99ed07f0 update 2015-04-07 03:17:03 +00:00
DadaMonad
e55ed9f2b4 composition type & support for list references 2015-04-07 00:16:12 +00:00
DadaMonad
bb0bfcc5c8 cleaned up, removed Replaceable operation, changed Operation specific events method (put it into the Manager types), created Composition type 2015-04-06 21:35:04 +00:00
DadaMonad
b24de43fe2 removed webcomponents from dependencies 2015-03-09 19:39:18 +00:00
DadaMonad
446560d9e8 added support for namespaces on types 2015-03-09 17:38:26 +00:00
DadaMonad
148e46f043 updated README 2015-03-01 15:44:31 +00:00
DadaMonad
e8f20dabd3 updated readme with new types 2015-02-27 18:32:05 +00:00
DadaMonad
96ed8b0f98 outsourced all types (except for object type) 2015-02-27 18:01:21 +00:00
DadaMonad
c663230c1b add xml examples 2015-02-26 21:39:12 +00:00
DadaMonad
0a8118367d yay - every test on xml and dom succeeds 2015-02-26 21:28:06 +00:00
DadaMonad
f932f560bd completed the xml tests - and lots of them run successfully 2015-02-26 18:28:35 +00:00
DadaMonad
f9542b90db made xml tests more expressive 2015-02-26 10:09:41 +00:00
DadaMonad
014495febd added random tests for xml test suite 2015-02-26 09:20:26 +00:00
DadaMonad
82f11c421f fixed parent issue (only one parent per Y.Xml type) 2015-02-25 23:41:57 +00:00
DadaMonad
9059618d1f Y-Xml tests pass 2015-02-25 22:50:26 +00:00
DadaMonad
9a8f8fba05 added tests for new xml type. 2015-02-24 20:34:27 +00:00
DadaMonad
3ba89edf7d support for circular structures (e.g. with JSON) 2015-02-24 16:09:42 +00:00
DadaMonad
fea6de3bf9 starting to refine the Replaceable type. Most types should be a replaceable. 2015-02-23 16:36:55 +00:00
DadaMonad
2a644f2f0c travis: build master branch only 2015-02-23 13:30:58 +00:00
DadaMonad
f189ae11b0 tests are no longer failing :) 2015-02-23 13:20:52 +00:00
DadaMonad
2e9f8f6d03 added text as a custom type, more tests are working 2015-02-23 11:41:04 +00:00
DadaMonad
860934de06 broke the dammn thing 2015-02-19 15:55:05 +00:00
DadaMonad
792440a71d devided ops/types 2015-02-19 10:41:34 +00:00
DadaMonad
1aacc0e967 remove travis 0.8 0.6 version 2015-02-18 00:44:16 +00:00
DadaMonad
d4b0c8cbbd travis build 2015-02-18 00:28:43 +00:00
DadaMonad
d6526f12fb fixed mocha stop 2015-02-18 00:01:43 +00:00
DadaMonad
d3af98cd17 travis - install coffee and bower first 2015-02-17 23:19:41 +00:00
DadaMonad
e33eb6a928 travis build bug 2015-02-17 23:14:00 +00:00
DadaMonad
d1be152983 travis button 2015-02-17 23:06:29 +00:00
DadaMonad
548a77833a added travis stuff 2015-02-17 23:00:25 +00:00
DadaMonad
5ba0a7492a refactoring text types 2015-02-17 21:10:46 +00:00
DadaMonad
c65f11b308 updated mocha 2015-02-17 19:37:15 +00:00
DadaMonad
77b83cae2a fixing double late join test fail 2015-02-17 19:23:27 +00:00
DadaMonad
f609c22be8 fixed text binding (enter, utf8 chars..) 2015-02-17 10:26:32 +00:00
DadaMonad
670854e9d8 added gitter button 2015-02-15 17:48:30 +00:00
DadaMonad
2bb7ba03cd added contrib (finally - heh?) 2015-02-15 17:17:34 +00:00
DadaMonad
686be484fc bumped version numbers 2015-02-15 15:35:09 +00:00
DadaMonad
60de3ce5b0 getting ready for 0.4 realeasy 2015-02-15 15:33:35 +00:00
DadaMonad
b6fe47efe1 changed to syncMethod 2015-02-05 16:19:55 +00:00
DadaMonad
e5f16812b3 added new y-test connector 2015-02-05 14:15:20 +00:00
DadaMonad
3eb933400a fixed doSync bug, fixed connection problems, improved p2p sync method - still
there are some cases that may lead to inconsistencies. Currently, only the master-slave method is a reliable sync method
2015-02-05 10:46:40 +00:00
DadaMonad
58a479be9b included connector type 2015-02-03 18:55:02 +00:00
DadaMonad
f835a72151 v0.3.2 2015-01-30 17:03:18 +00:00
182 changed files with 20562 additions and 43327 deletions

View File

@@ -1,3 +0,0 @@
{
"directory": "../"
}

10
.esdoc.json Normal file
View File

@@ -0,0 +1,10 @@
{
"source": "./src",
"destination": "./docs",
"plugins": [{
"name": "esdoc-standard-plugin",
"option": {
"accessor": {"access": ["public"], "autoPrivate": true}
}
}]
}

12
.gitignore vendored
View File

@@ -1,6 +1,8 @@
/node_modules/
node_modules
bower_components
.directory
.c9
.codio
.settings
docs
/y.*
/examples/yjs-dist.js*
.vscode
.yjsPersisted
build

View File

@@ -1,6 +1,8 @@
The MIT License (MIT)
Copyright (c) 2014 Kevin Jahns <kevin.jahns@rwth-aachen.de>.
Copyright (c) 2014
- Kevin Jahns <kevin.jahns@rwth-aachen.de>.
- Chair of Computer Science 5 (Databases & Information Systems), RWTH Aachen University, Germany
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal

321
README.md
View File

@@ -1,78 +1,305 @@
# ![Yatta!](https://dadamonad.github.io/files/layout/yjs.svg)
# ![Yjs](http://y-js.org/images/yjs.png)
[![Build Status](http://layers.dbis.rwth-aachen.de/jenkins/job/Yatta/badge/icon)](http://layers.dbis.rwth-aachen.de/jenkins/job/Yatta/)
Yjs is a framework for offline-first p2p shared editing on structured data like
text, richtext, json, or XML. It is fairly easy to get started, as Yjs hides
most of the complexity of concurrent editing. For additional information, demos,
and tutorials visit [y-js.org](http://y-js.org/).
Yjs is a framework for optimistic concurrency control and automatic conflict resolution on arbitrary data types. The framework implements a new OT-like concurrency algorithm and provides similar functionality as [ShareJs] and [OpenCoweb]. Yjs was designed to take away the pain from concurrently editing complex data types like Text, Json, and XML. You can find some applications for this framework [here](https://dadamonad.github.io/yjs/examples/).
### Extensions
Yjs only knows how to resolve conflicts on shared data. You have to choose a ..
* *Connector* - a communication protocol that propagates changes to the clients
* *Database* - a database to store your changes
* one or more *Types* - that represent the shared data
In the future, we want to enable users to implement their own collaborative types. Currently we provide data types for
* Text
* Json
* XML
Connectors, Databases, and Types are available as modules that extend Yjs. Here
is a list of the modules we know of:
Unlike other frameworks, Yjs supports P2P message propagation and is not bound to a specific communication protocol. Therefore, Yjs is extremely scalable and can be used in a wide range of application scenarios.
##### Connectors
We support several communication protocols as so called *Connectors*. You find a bunch of Connectors in the [y-connectors](https://github.com/rwth-acis/y-connectors) repository. Currently supported communication protocols:
* [XMPP-Connector](http://xmpp.org) - Propagates updates in a XMPP multi-user-chat room
* [WebRTC-Connector](http://peerjs.com/) - Propagate updates directly with WebRTC
* [IWC-Connector](http://dbis.rwth-aachen.de/cms/projects/the-xmpp-experience#interwidget-communication) - Inter-widget Communication
|Name | Description |
|----------------|-----------------------------------|
|[webrtc](https://github.com/y-js/y-webrtc) | Propagate updates Browser2Browser via WebRTC|
|[websockets](https://github.com/y-js/y-websockets-client) | Set up [a central server](https://github.com/y-js/y-websockets-client), and connect to it via websockets |
|[xmpp](https://github.com/y-js/y-xmpp) | Propagate updates in a XMPP multi-user-chat room ([XEP-0045](http://xmpp.org/extensions/xep-0045.html))|
|[ipfs](https://github.com/ipfs-labs/y-ipfs-connector) | Connector for the [Interplanetary File System](https://ipfs.io/)!|
|[test](https://github.com/y-js/y-test) | A Connector for testing purposes. It is designed to simulate delays that happen in worst case scenarios|
You can use Yjs client-, and server- side. You can get it as via npm, and bower. We even provide a polymer element for Yjs!
##### Database adapters
The theoretical advantages over similar frameworks are support for
* .. P2P message propagation and arbitrary communication protocols
* .. arbitrary complex data types
* .. offline editing: Only relevant changes are propagated on rejoin (unimplemented)
* .. AnyUndo: Undo *any* action that was executed in constant time (unimplemented)
* .. Intention Preservation: When working on Text, the intention of your changes are preserved. This is particularily important when working offline.
|Name | Description |
|----------------|-----------------------------------|
|[memory](https://github.com/y-js/y-memory) | In-memory storage. |
|[indexeddb](https://github.com/y-js/y-indexeddb) | Offline storage for the browser |
|[leveldb](https://github.com/y-js/y-leveldb) | Persistent storage for node apps |
##### Types
| Name | Description |
|----------|-------------------|
|[map](https://github.com/y-js/y-map) | A shared Map implementation. Maps from text to any stringify-able object |
|[array](https://github.com/y-js/y-array) | A shared Array implementation |
|[xml](https://github.com/y-js/y-xml) | An implementation of the DOM. You can create a two way binding to Browser DOM objects |
|[text](https://github.com/y-js/y-text) | Collaborate on text. Supports two way binding to the [Ace Editor](https://ace.c9.io), [CodeMirror](https://codemirror.net/), [Monaco](https://github.com/Microsoft/monaco-editor), textareas, input elements, and HTML elements (e.g. <*h1*>, or <*p*>) |
|[richtext](https://github.com/y-js/y-richtext) | Collaborate on rich text. Supports two way binding to the [Quill Rich Text Editor](http://quilljs.com/)|
##### Other
| Name | Description |
|-----------|-------------------|
|[y-element](http://y-js.org/y-element/) | Yjs Polymer Element |
## Use it!
You find a tutorial, examples, and documentation on the [website](https://dadamonad.github.io/yjs/).
Either clone this git repository, install it with [bower](http://bower.io/), or install it with [npm](https://www.npmjs.org/package/yjs).
Install Yjs, and its modules with [bower](http://bower.io/), or
[npm](https://www.npmjs.org/package/yjs).
### Bower
```
bower install rwth-acis/yjs
bower install --save yjs y-array % add all y-* modules you want to use
```
Then you include the libraries directly from the installation folder.
You only need to include the `y.js` file. Yjs is able to automatically require
missing modules.
```
<script src="./bower_components/yjs/y.js"></script>
```
### CDN
```
<script src="https://cdn.jsdelivr.net/npm/yjs@12/src/y.js"></script>
<script src="https://cdn.jsdelivr.net/npm/y-array@10/dist/y-array.js"></script>
<script src="https://cdn.jsdelivr.net/npm/y-websockets-client@8/dist/y-websockets-client.js"></script>
<script src="https://cdn.jsdelivr.net/npm/y-memory@8/dist/y-memory.js"></script>
<script src="https://cdn.jsdelivr.net/npm/y-map@10/dist/y-map.js"></script>
<script src="https://cdn.jsdelivr.net/npm/y-text@9/dist/y-text.js"></script>
// ..
// do the same for all modules you want to use
```
### Npm
```
npm install yjs --save
npm install --save yjs % add all y-* modules you want to use
```
And use it like this with *npm*:
If you don't include via script tag, you have to explicitly include all modules!
(Same goes for other module systems)
```
Y = require("yjs");
var Y = require('yjs')
require('y-array')(Y) // add the y-array type to Yjs
require('y-websockets-client')(Y)
require('y-memory')(Y)
require('y-map')(Y)
require('y-text')(Y)
// ..
// do the same for all modules you want to use
```
## Status
Yjs is still in an early development phase. Don't expect that everything is working fine.
But I would become really motivated if you gave me some feedback :) ([github](https://github.com/rwth-acis/yjs/issues)).
### ES6 Syntax
```
import Y from 'yjs'
import yArray from 'y-array'
import yWebsocketsClient from 'y-webrtc'
import yMemory from 'y-memory'
import yMap from 'y-map'
import yText from 'y-text'
// ..
Y.extend(yArray, yWebsocketsClient, yMemory, yArray, yMap, yText /*, .. */)
```
### Current Issues
* The History Buffer should be able to store operations in a database
* Documentation
* Reimplement support for XML as a data type
* Custom data types
# Text editing example
Install dependencies
```
bower i yjs y-memory y-webrtc y-array y-text
```
## Support
Please report _any_ issues to the [Github issue page](https://github.com/rwth-acis/yjs/issues)!
I would appreciate if developers give me feedback on how _convenient_ the framework is, and if it is easy to use. Particularly the XML-support may not support every DOM-methods - if you encounter a method that does not cause any change on other peers, please state function name, and sample parameters. However, there are browser-specific features, that Y won't support.
Here is a simple example of a shared textarea
```HTML
<!DOCTYPE html>
<html>
<body>
<script src="./bower_components/yjs/y.js"></script>
<!-- Yjs automatically includes all missing dependencies (browser only) -->
<script>
Y({
db: {
name: 'memory' // use memory database adapter.
// name: 'indexeddb' // use indexeddb database adapter instead for offline apps
},
connector: {
name: 'webrtc', // use webrtc connector
// name: 'websockets-client'
// name: 'xmpp'
room: 'my-room' // clients connecting to the same room share data
},
sourceDir: '/bower_components', // location of the y-* modules (browser only)
share: {
textarea: 'Text' // y.share.textarea is of type y-text
}
}).then(function (y) {
// The Yjs instance `y` is available
// y.share.* contains the shared types
// Bind `y.share.textarea` to `<textarea/>`
y.share.textarea.bind(document.querySelector('textarea'))
})
</script>
<textarea></textarea>
</body>
</html>
```
## Get Help & Give Help
There are some friendly people on [![Gitter](https://badges.gitter.im/Join%20Chat.svg)](https://gitter.im/y-js/yjs?utm_source=badge&utm_medium=badge&utm_campaign=pr-badge) who are eager to help, and answer questions. Please join!
Report _any_ issues to the
[Github issue page](https://github.com/y-js/yjs/issues)! I try to fix them very
soon, if possible.
# API
### Y(options)
* Y.extend(module1, module2, ..)
* Add extensions to Y
* `Y.extend(require('y-webrtc'))` has the same semantics as
`require('y-webrtc')(Y)`
* options.db
* Will be forwarded to the database adapter. Specify the database adaper on
`options.db.name`.
* Have a look at the used database adapter repository to see all available
options.
* options.connector
* Will be forwarded to the connector adapter. Specify the connector adaper on
`options.connector.name`.
* All our connectors implement a `room` property. Clients that specify the
same room share the same data.
* All of our connectors specify an `url` property that defines the connection
endpoint of the used connector.
* All of our connectors also have a default connection endpoint that you can
use for development.
* Set `options.connector.generateUserId = true` in order to genenerate a
userid, instead of receiving one from the server. This way the `Y(..)` is
immediately going to be resolved, without waiting for any confirmation from
the server. Use with caution.
* Have a look at the used connector repository to see all available options.
* *Only if you know what you are doing:* Set
`options.connector.preferUntransformed = true` in order receive the shared
data untransformed. This is very efficient as the database content is simply
copied to this client. This does only work if this client receives content
from only one client.
* options.sourceDir (browser only)
* Path where all y-* modules are stored
* Defaults to `/bower_components`
* Not required when running on `nodejs` / `iojs`
* When using nodejs you need to manually extend Yjs:
```
var Y = require('yjs')
// you have to require a db, connector, and *all* types you use!
require('y-memory')(Y)
require('y-webrtc')(Y)
require('y-map')(Y)
// ..
```
* options.share
* Specify on `options.share[arbitraryName]` types that are shared among all
users.
* E.g. Specify `options.share[arbitraryName] = 'Array'` to require y-array and
create an y-array type on `y.share[arbitraryName]`.
* If userA doesn't specify `options.share[arbitraryName]`, it won't be
available for userA.
* If userB specifies `options.share[arbitraryName]`, it still won't be
available for userA. But all the updates are send from userB to userA.
* In contrast to y-map, types on `y.share.*` cannot be overwritten or deleted.
Instead, they are merged among all users. This feature is only available on
`y.share.*`
* Weird behavior: It is supported that two users specify different types with
the same property name.
E.g. userA specifies `options.share.x = 'Array'`, and userB specifies
`options.share.x = 'Text'`. But they only share data if they specified the
same type with the same property name
* options.type (browser only)
* Array of modules that Yjs needs to require, before instantiating a shared
type.
* By default Yjs requires the specified database adapter, the specified
connector, and all modules that are used in `options.share.*`
* Put all types here that you intend to use, but are not used in y.share.*
### Instantiated Y object (y)
`Y(options)` returns a promise that is fulfilled when..
* All modules are loaded
* The specified database adapter is loaded
* The specified connector is loaded
* All types are included
* The connector is initialized, and a unique user id is set (received from the
server)
* Note: When using y-indexeddb, a retrieved user id is stored on `localStorage`
The promise returns an instance of Y. We denote it with a lower case `y`.
* y.share.*
* Instances of the types you specified on options.share.*
* y.share.* can only be defined once when you instantiate Y!
* y.connector is an instance of Y.AbstractConnector
* y.connector.onUserEvent(function (event) {..})
* Observe user events (event.action is either 'userLeft' or 'userJoined')
* y.connector.whenSynced(listener)
* `listener` is executed when y synced with at least one user.
* `listener` is not called when no other user is in the same room.
* y-websockets-client aways waits to sync with the server
* y.connector.disconnect()
* Force to disconnect this instance from the other instances
* y.connector.connect()
* Try to reconnect to the other instances (needs to be supported by the
connector)
* Not supported by y-xmpp
* y.close()
* Destroy this object.
* Destroys all types (they will throw weird errors if you still use them)
* Disconnects from the other instances (via connector)
* Returns a promise
* y.destroy()
* calls y.close()
* Removes all data from the database
* Returns a promise
* y.db.stopGarbageCollector()
* Stop the garbage collector. Call y.db.garbageCollect() to continue garbage
collection
* y.db.gc :: Boolean
* Whether gc is turned on
* y.db.gcTimeout :: Number (defaults to 50000 ms)
* Time interval between two garbage collect cycles
* It is required that all instances exchanged all messages after two garbage
collect cycles (after 100000 ms per default)
* y.db.userId :: String
* The used user id for this client. **Never overwrite this**
### Logging
Yjs uses [debug](https://github.com/visionmedia/debug) for logging. The flag
`y*` enables logging for all y-* components. You can selectively remove
components you are not interested in: E.g. The flag `y*,-y:connector-message`
will not log the long `y:connector-message` messages.
##### Enable logging in Node.js
```sh
DEBUG=y* node app.js
```
Remove the colors in order to log to a file:
```sh
DEBUG_COLORS=0 DEBUG=y* node app.js > log
```
##### Enable logging in the browser
```js
localStorage.debug = 'y*'
```
## Contribution
I created this framework during my bachelor thesis at the chair of computer
science 5 [(i5)](http://dbis.rwth-aachen.de/cms), RWTH University. Since
December 2014 I'm working on Yjs as a part of my student worker job at the i5.
## License
Yjs is licensed under the [MIT License](./LICENSE.txt).
[ShareJs]: https://github.com/share/ShareJS
[OpenCoweb]: https://github.com/opencoweb/coweb
<kevin.jahns@rwth-aachen.de>
Yjs is licensed under the [MIT License](./LICENSE).
<yjs@dbis.rwth-aachen.de>

View File

@@ -1,33 +0,0 @@
{
"name": "yjs",
"version": "0.3.1",
"homepage": "https://github.com/DadaMonad/yjs",
"authors": [
"Kevin Jahns <kevin.jahns@rwth-aachen.de>"
],
"description": "A Framework that enables Real-Time collaboration on arbitrary data structures.",
"main": [
"./y.js",
"./y-object.html",
"./build/node/y.js"
],
"keywords": [
"OT",
"collaboration",
"synchronization",
"ShareJS",
"Coweb",
"concurrency"
],
"license": "MIT",
"ignore": [
"node_modules",
"bower_components",
"test",
"extras",
"test"
],
"dependencies": {
"polymer": "Polymer/polymer#~0.5.3"
}
}

File diff suppressed because one or more lines are too long

File diff suppressed because one or more lines are too long

View File

@@ -1,66 +0,0 @@
var adaptConnector;
adaptConnector = function(connector, engine, HB, execution_listener) {
var applyHB, encode_state_vector, getHB, getStateVector, parse_state_vector, send_;
send_ = function(o) {
if (o.uid.creator === HB.getUserId() && (typeof o.uid.op_number !== "string")) {
return connector.broadcast(o);
}
};
if (connector.invokeSync != null) {
HB.setInvokeSyncHandler(connector.invokeSync);
}
execution_listener.push(send_);
encode_state_vector = function(v) {
var name, value, _results;
_results = [];
for (name in v) {
value = v[name];
_results.push({
user: name,
state: value
});
}
return _results;
};
parse_state_vector = function(v) {
var s, state_vector, _i, _len;
state_vector = {};
for (_i = 0, _len = v.length; _i < _len; _i++) {
s = v[_i];
state_vector[s.user] = s.state;
}
return state_vector;
};
getStateVector = function() {
return encode_state_vector(HB.getOperationCounter());
};
getHB = function(v) {
var hb, json, o, state_vector, _i, _len;
state_vector = parse_state_vector(v);
hb = HB._encode(state_vector);
for (_i = 0, _len = hb.length; _i < _len; _i++) {
o = hb[_i];
o.fromHB = "true";
}
json = {
hb: hb,
state_vector: encode_state_vector(HB.getOperationCounter())
};
return json;
};
applyHB = function(hb) {
return engine.applyOp(hb);
};
connector.getStateVector = getStateVector;
connector.getHB = getHB;
connector.applyHB = applyHB;
connector.receive_handlers.push(function(sender, op) {
if (op.uid.creator !== HB.getUserId()) {
return engine.applyOp(op);
}
});
return connector.setIsBoundToY();
};
module.exports = adaptConnector;

View File

@@ -1,113 +0,0 @@
var Engine;
if (typeof window !== "undefined" && window !== null) {
window.unprocessed_counter = 0;
}
if (typeof window !== "undefined" && window !== null) {
window.unprocessed_exec_counter = 0;
}
if (typeof window !== "undefined" && window !== null) {
window.unprocessed_types = [];
}
Engine = (function() {
function Engine(HB, types) {
this.HB = HB;
this.types = types;
this.unprocessed_ops = [];
}
Engine.prototype.parseOperation = function(json) {
var type;
type = this.types[json.type];
if ((type != null ? type.parse : void 0) != null) {
return type.parse(json);
} else {
throw new Error("You forgot to specify a parser for type " + json.type + ". The message is " + (JSON.stringify(json)) + ".");
}
};
/*
applyOpsBundle: (ops_json)->
ops = []
for o in ops_json
ops.push @parseOperation o
for o in ops
if not o.execute()
@unprocessed_ops.push o
@tryUnprocessed()
*/
Engine.prototype.applyOpsCheckDouble = function(ops_json) {
var o, _i, _len, _results;
_results = [];
for (_i = 0, _len = ops_json.length; _i < _len; _i++) {
o = ops_json[_i];
if (this.HB.getOperation(o.uid) == null) {
_results.push(this.applyOp(o));
} else {
_results.push(void 0);
}
}
return _results;
};
Engine.prototype.applyOps = function(ops_json) {
return this.applyOp(ops_json);
};
Engine.prototype.applyOp = function(op_json_array) {
var o, op_json, _i, _len;
if (op_json_array.constructor !== Array) {
op_json_array = [op_json_array];
}
for (_i = 0, _len = op_json_array.length; _i < _len; _i++) {
op_json = op_json_array[_i];
o = this.parseOperation(op_json);
if (op_json.fromHB != null) {
o.fromHB = op_json.fromHB;
}
if (this.HB.getOperation(o) != null) {
} else if (((!this.HB.isExpectedOperation(o)) && (o.fromHB == null)) || (!o.execute())) {
this.unprocessed_ops.push(o);
if (typeof window !== "undefined" && window !== null) {
window.unprocessed_types.push(o.type);
}
}
}
return this.tryUnprocessed();
};
Engine.prototype.tryUnprocessed = function() {
var old_length, op, unprocessed, _i, _len, _ref;
while (true) {
old_length = this.unprocessed_ops.length;
unprocessed = [];
_ref = this.unprocessed_ops;
for (_i = 0, _len = _ref.length; _i < _len; _i++) {
op = _ref[_i];
if (this.HB.getOperation(op) != null) {
} else if ((!this.HB.isExpectedOperation(op) && (op.fromHB == null)) || (!op.execute())) {
unprocessed.push(op);
}
}
this.unprocessed_ops = unprocessed;
if (this.unprocessed_ops.length === old_length) {
break;
}
}
if (this.unprocessed_ops.length !== 0) {
return this.HB.invokeSync();
}
};
return Engine;
})();
module.exports = Engine;

View File

@@ -1,250 +0,0 @@
var HistoryBuffer,
__bind = function(fn, me){ return function(){ return fn.apply(me, arguments); }; };
HistoryBuffer = (function() {
function HistoryBuffer(user_id) {
this.user_id = user_id;
this.emptyGarbage = __bind(this.emptyGarbage, this);
this.operation_counter = {};
this.buffer = {};
this.change_listeners = [];
this.garbage = [];
this.trash = [];
this.performGarbageCollection = true;
this.garbageCollectTimeout = 30000;
this.reserved_identifier_counter = 0;
setTimeout(this.emptyGarbage, this.garbageCollectTimeout);
}
HistoryBuffer.prototype.resetUserId = function(id) {
var o, o_name, own;
own = this.buffer[this.user_id];
if (own != null) {
for (o_name in own) {
o = own[o_name];
o.uid.creator = id;
}
if (this.buffer[id] != null) {
throw new Error("You are re-assigning an old user id - this is not (yet) possible!");
}
this.buffer[id] = own;
delete this.buffer[this.user_id];
}
this.operation_counter[id] = this.operation_counter[this.user_id];
delete this.operation_counter[this.user_id];
return this.user_id = id;
};
HistoryBuffer.prototype.emptyGarbage = function() {
var o, _i, _len, _ref;
_ref = this.garbage;
for (_i = 0, _len = _ref.length; _i < _len; _i++) {
o = _ref[_i];
if (typeof o.cleanup === "function") {
o.cleanup();
}
}
this.garbage = this.trash;
this.trash = [];
if (this.garbageCollectTimeout !== -1) {
this.garbageCollectTimeoutId = setTimeout(this.emptyGarbage, this.garbageCollectTimeout);
}
return void 0;
};
HistoryBuffer.prototype.getUserId = function() {
return this.user_id;
};
HistoryBuffer.prototype.addToGarbageCollector = function() {
var o, _i, _len, _results;
if (this.performGarbageCollection) {
_results = [];
for (_i = 0, _len = arguments.length; _i < _len; _i++) {
o = arguments[_i];
if (o != null) {
_results.push(this.garbage.push(o));
} else {
_results.push(void 0);
}
}
return _results;
}
};
HistoryBuffer.prototype.stopGarbageCollection = function() {
this.performGarbageCollection = false;
this.setManualGarbageCollect();
this.garbage = [];
return this.trash = [];
};
HistoryBuffer.prototype.setManualGarbageCollect = function() {
this.garbageCollectTimeout = -1;
clearTimeout(this.garbageCollectTimeoutId);
return this.garbageCollectTimeoutId = void 0;
};
HistoryBuffer.prototype.setGarbageCollectTimeout = function(garbageCollectTimeout) {
this.garbageCollectTimeout = garbageCollectTimeout;
};
HistoryBuffer.prototype.getReservedUniqueIdentifier = function() {
return {
creator: '_',
op_number: "_" + (this.reserved_identifier_counter++),
doSync: false
};
};
HistoryBuffer.prototype.getOperationCounter = function(user_id) {
var ctn, res, user, _ref;
if (user_id == null) {
res = {};
_ref = this.operation_counter;
for (user in _ref) {
ctn = _ref[user];
res[user] = ctn;
}
return res;
} else {
return this.operation_counter[user_id];
}
};
HistoryBuffer.prototype.isExpectedOperation = function(o) {
var _base, _name;
if ((_base = this.operation_counter)[_name = o.uid.creator] == null) {
_base[_name] = 0;
}
o.uid.op_number <= this.operation_counter[o.uid.creator];
return true;
};
HistoryBuffer.prototype._encode = function(state_vector) {
var json, o, o_json, o_next, o_number, o_prev, u_name, unknown, user, _ref;
if (state_vector == null) {
state_vector = {};
}
json = [];
unknown = function(user, o_number) {
if ((user == null) || (o_number == null)) {
throw new Error("dah!");
}
return (state_vector[user] == null) || state_vector[user] <= o_number;
};
_ref = this.buffer;
for (u_name in _ref) {
user = _ref[u_name];
for (o_number in user) {
o = user[o_number];
if (o.uid.doSync && unknown(u_name, o_number)) {
o_json = o._encode();
if (o.next_cl != null) {
o_next = o.next_cl;
while ((o_next.next_cl != null) && unknown(o_next.uid.creator, o_next.uid.op_number)) {
o_next = o_next.next_cl;
}
o_json.next = o_next.getUid();
} else if (o.prev_cl != null) {
o_prev = o.prev_cl;
while ((o_prev.prev_cl != null) && unknown(o_prev.uid.creator, o_prev.uid.op_number)) {
o_prev = o_prev.prev_cl;
}
o_json.prev = o_prev.getUid();
}
json.push(o_json);
}
}
}
return json;
};
HistoryBuffer.prototype.getNextOperationIdentifier = function(user_id) {
var uid;
if (user_id == null) {
user_id = this.user_id;
}
if (this.operation_counter[user_id] == null) {
this.operation_counter[user_id] = 0;
}
uid = {
'creator': user_id,
'op_number': this.operation_counter[user_id],
'doSync': true
};
this.operation_counter[user_id]++;
return uid;
};
HistoryBuffer.prototype.getOperation = function(uid) {
var o, _ref;
if (uid.uid != null) {
uid = uid.uid;
}
o = (_ref = this.buffer[uid.creator]) != null ? _ref[uid.op_number] : void 0;
if ((uid.sub != null) && (o != null)) {
return o.retrieveSub(uid.sub);
} else {
return o;
}
};
HistoryBuffer.prototype.addOperation = function(o) {
if (this.buffer[o.uid.creator] == null) {
this.buffer[o.uid.creator] = {};
}
if (this.buffer[o.uid.creator][o.uid.op_number] != null) {
throw new Error("You must not overwrite operations!");
}
if ((o.uid.op_number.constructor !== String) && (!this.isExpectedOperation(o)) && (o.fromHB == null)) {
throw new Error("this operation was not expected!");
}
this.addToCounter(o);
this.buffer[o.uid.creator][o.uid.op_number] = o;
return o;
};
HistoryBuffer.prototype.removeOperation = function(o) {
var _ref;
return (_ref = this.buffer[o.uid.creator]) != null ? delete _ref[o.uid.op_number] : void 0;
};
HistoryBuffer.prototype.setInvokeSyncHandler = function(f) {
return this.invokeSync = f;
};
HistoryBuffer.prototype.invokeSync = function() {};
HistoryBuffer.prototype.renewStateVector = function(state_vector) {
var state, user, _results;
_results = [];
for (user in state_vector) {
state = state_vector[user];
if ((this.operation_counter[user] == null) || (this.operation_counter[user] < state_vector[user])) {
_results.push(this.operation_counter[user] = state_vector[user]);
} else {
_results.push(void 0);
}
}
return _results;
};
HistoryBuffer.prototype.addToCounter = function(o) {
if (this.operation_counter[o.uid.creator] == null) {
this.operation_counter[o.uid.creator] = 0;
}
if (typeof o.uid.op_number === 'number' && o.uid.creator !== this.getUserId()) {
if (o.uid.op_number === this.operation_counter[o.uid.creator]) {
return this.operation_counter[o.uid.creator]++;
} else {
return this.invokeSync(o.uid.creator);
}
}
};
return HistoryBuffer;
})();
module.exports = HistoryBuffer;

View File

@@ -1,487 +0,0 @@
var __slice = [].slice,
__hasProp = {}.hasOwnProperty,
__extends = function(child, parent) { for (var key in parent) { if (__hasProp.call(parent, key)) child[key] = parent[key]; } function ctor() { this.constructor = child; } ctor.prototype = parent.prototype; child.prototype = new ctor(); child.__super__ = parent.prototype; return child; };
module.exports = function(HB) {
var execution_listener, types;
types = {};
execution_listener = [];
types.Operation = (function() {
function Operation(uid) {
this.is_deleted = false;
this.garbage_collected = false;
this.event_listeners = [];
if (uid != null) {
this.uid = uid;
}
}
Operation.prototype.type = "Operation";
Operation.prototype.retrieveSub = function() {
throw new Error("sub properties are not enable on this operation type!");
};
Operation.prototype.observe = function(f) {
return this.event_listeners.push(f);
};
Operation.prototype.unobserve = function(f) {
return this.event_listeners = this.event_listeners.filter(function(g) {
return f !== g;
});
};
Operation.prototype.deleteAllObservers = function() {
return this.event_listeners = [];
};
Operation.prototype["delete"] = function() {
(new types.Delete(void 0, this)).execute();
return null;
};
Operation.prototype.callEvent = function() {
return this.forwardEvent.apply(this, [this].concat(__slice.call(arguments)));
};
Operation.prototype.forwardEvent = function() {
var args, f, op, _i, _len, _ref, _results;
op = arguments[0], args = 2 <= arguments.length ? __slice.call(arguments, 1) : [];
_ref = this.event_listeners;
_results = [];
for (_i = 0, _len = _ref.length; _i < _len; _i++) {
f = _ref[_i];
_results.push(f.call.apply(f, [op].concat(__slice.call(args))));
}
return _results;
};
Operation.prototype.isDeleted = function() {
return this.is_deleted;
};
Operation.prototype.applyDelete = function(garbagecollect) {
if (garbagecollect == null) {
garbagecollect = true;
}
if (!this.garbage_collected) {
this.is_deleted = true;
if (garbagecollect) {
this.garbage_collected = true;
return HB.addToGarbageCollector(this);
}
}
};
Operation.prototype.cleanup = function() {
HB.removeOperation(this);
return this.deleteAllObservers();
};
Operation.prototype.setParent = function(parent) {
this.parent = parent;
};
Operation.prototype.getParent = function() {
return this.parent;
};
Operation.prototype.getUid = function() {
if (this.uid.noOperation == null) {
return this.uid;
} else {
return this.uid.alt;
}
};
Operation.prototype.cloneUid = function() {
var n, uid, v, _ref;
uid = {};
_ref = this.getUid();
for (n in _ref) {
v = _ref[n];
uid[n] = v;
}
return uid;
};
Operation.prototype.dontSync = function() {
return this.uid.doSync = false;
};
Operation.prototype.execute = function() {
var l, _i, _len;
this.is_executed = true;
if (this.uid == null) {
this.uid = HB.getNextOperationIdentifier();
}
if (this.uid.noOperation == null) {
HB.addOperation(this);
for (_i = 0, _len = execution_listener.length; _i < _len; _i++) {
l = execution_listener[_i];
l(this._encode());
}
}
return this;
};
Operation.prototype.saveOperation = function(name, op) {
if ((op != null ? op.execute : void 0) != null) {
return this[name] = op;
} else if (op != null) {
if (this.unchecked == null) {
this.unchecked = {};
}
return this.unchecked[name] = op;
}
};
Operation.prototype.validateSavedOperations = function() {
var name, op, op_uid, success, uninstantiated, _ref;
uninstantiated = {};
success = this;
_ref = this.unchecked;
for (name in _ref) {
op_uid = _ref[name];
op = HB.getOperation(op_uid);
if (op) {
this[name] = op;
} else {
uninstantiated[name] = op_uid;
success = false;
}
}
delete this.unchecked;
if (!success) {
this.unchecked = uninstantiated;
}
return success;
};
return Operation;
})();
types.Delete = (function(_super) {
__extends(Delete, _super);
function Delete(uid, deletes) {
this.saveOperation('deletes', deletes);
Delete.__super__.constructor.call(this, uid);
}
Delete.prototype.type = "Delete";
Delete.prototype._encode = function() {
return {
'type': "Delete",
'uid': this.getUid(),
'deletes': this.deletes.getUid()
};
};
Delete.prototype.execute = function() {
var res;
if (this.validateSavedOperations()) {
res = Delete.__super__.execute.apply(this, arguments);
if (res) {
this.deletes.applyDelete(this);
}
return res;
} else {
return false;
}
};
return Delete;
})(types.Operation);
types.Delete.parse = function(o) {
var deletes_uid, uid;
uid = o['uid'], deletes_uid = o['deletes'];
return new this(uid, deletes_uid);
};
types.Insert = (function(_super) {
__extends(Insert, _super);
function Insert(uid, prev_cl, next_cl, origin, parent) {
this.saveOperation('parent', parent);
this.saveOperation('prev_cl', prev_cl);
this.saveOperation('next_cl', next_cl);
if (origin != null) {
this.saveOperation('origin', origin);
} else {
this.saveOperation('origin', prev_cl);
}
Insert.__super__.constructor.call(this, uid);
}
Insert.prototype.type = "Insert";
Insert.prototype.applyDelete = function(o) {
var callLater, garbagecollect, _ref;
if (this.deleted_by == null) {
this.deleted_by = [];
}
callLater = false;
if ((this.parent != null) && !this.isDeleted() && (o != null)) {
callLater = true;
}
if (o != null) {
this.deleted_by.push(o);
}
garbagecollect = false;
if (this.next_cl.isDeleted()) {
garbagecollect = true;
}
Insert.__super__.applyDelete.call(this, garbagecollect);
if (callLater) {
this.callOperationSpecificDeleteEvents(o);
}
if ((_ref = this.prev_cl) != null ? _ref.isDeleted() : void 0) {
return this.prev_cl.applyDelete();
}
};
Insert.prototype.cleanup = function() {
var d, o, _i, _len, _ref;
if (this.next_cl.isDeleted()) {
_ref = this.deleted_by;
for (_i = 0, _len = _ref.length; _i < _len; _i++) {
d = _ref[_i];
d.cleanup();
}
o = this.next_cl;
while (o.type !== "Delimiter") {
if (o.origin === this) {
o.origin = this.prev_cl;
}
o = o.next_cl;
}
this.prev_cl.next_cl = this.next_cl;
this.next_cl.prev_cl = this.prev_cl;
return Insert.__super__.cleanup.apply(this, arguments);
}
};
Insert.prototype.getDistanceToOrigin = function() {
var d, o;
d = 0;
o = this.prev_cl;
while (true) {
if (this.origin === o) {
break;
}
d++;
o = o.prev_cl;
}
return d;
};
Insert.prototype.execute = function() {
var distance_to_origin, i, o;
if (!this.validateSavedOperations()) {
return false;
} else {
if (this.parent != null) {
if (this.prev_cl == null) {
this.prev_cl = this.parent.beginning;
}
if (this.origin == null) {
this.origin = this.parent.beginning;
}
if (this.next_cl == null) {
this.next_cl = this.parent.end;
}
}
if (this.prev_cl != null) {
distance_to_origin = this.getDistanceToOrigin();
o = this.prev_cl.next_cl;
i = distance_to_origin;
while (true) {
if (o !== this.next_cl) {
if (o.getDistanceToOrigin() === i) {
if (o.uid.creator < this.uid.creator) {
this.prev_cl = o;
distance_to_origin = i + 1;
} else {
}
} else if (o.getDistanceToOrigin() < i) {
if (i - distance_to_origin <= o.getDistanceToOrigin()) {
this.prev_cl = o;
distance_to_origin = i + 1;
} else {
}
} else {
break;
}
i++;
o = o.next_cl;
} else {
break;
}
}
this.next_cl = this.prev_cl.next_cl;
this.prev_cl.next_cl = this;
this.next_cl.prev_cl = this;
}
this.setParent(this.prev_cl.getParent());
Insert.__super__.execute.apply(this, arguments);
this.callOperationSpecificInsertEvents();
return this;
}
};
Insert.prototype.callOperationSpecificInsertEvents = function() {
var _ref;
return (_ref = this.parent) != null ? _ref.callEvent([
{
type: "insert",
position: this.getPosition(),
object: this.parent,
changedBy: this.uid.creator,
value: this.content
}
]) : void 0;
};
Insert.prototype.callOperationSpecificDeleteEvents = function(o) {
return this.parent.callEvent([
{
type: "delete",
position: this.getPosition(),
object: this.parent,
length: 1,
changedBy: o.uid.creator
}
]);
};
Insert.prototype.getPosition = function() {
var position, prev;
position = 0;
prev = this.prev_cl;
while (true) {
if (prev instanceof types.Delimiter) {
break;
}
if (!prev.isDeleted()) {
position++;
}
prev = prev.prev_cl;
}
return position;
};
return Insert;
})(types.Operation);
types.ImmutableObject = (function(_super) {
__extends(ImmutableObject, _super);
function ImmutableObject(uid, content) {
this.content = content;
ImmutableObject.__super__.constructor.call(this, uid);
}
ImmutableObject.prototype.type = "ImmutableObject";
ImmutableObject.prototype.val = function() {
return this.content;
};
ImmutableObject.prototype._encode = function() {
var json;
json = {
'type': this.type,
'uid': this.getUid(),
'content': this.content
};
return json;
};
return ImmutableObject;
})(types.Operation);
types.ImmutableObject.parse = function(json) {
var content, uid;
uid = json['uid'], content = json['content'];
return new this(uid, content);
};
types.Delimiter = (function(_super) {
__extends(Delimiter, _super);
function Delimiter(prev_cl, next_cl, origin) {
this.saveOperation('prev_cl', prev_cl);
this.saveOperation('next_cl', next_cl);
this.saveOperation('origin', prev_cl);
Delimiter.__super__.constructor.call(this, {
noOperation: true
});
}
Delimiter.prototype.type = "Delimiter";
Delimiter.prototype.applyDelete = function() {
var o;
Delimiter.__super__.applyDelete.call(this);
o = this.prev_cl;
while (o != null) {
o.applyDelete();
o = o.prev_cl;
}
return void 0;
};
Delimiter.prototype.cleanup = function() {
return Delimiter.__super__.cleanup.call(this);
};
Delimiter.prototype.execute = function() {
var _ref, _ref1;
if (((_ref = this.unchecked) != null ? _ref['next_cl'] : void 0) != null) {
return Delimiter.__super__.execute.apply(this, arguments);
} else if ((_ref1 = this.unchecked) != null ? _ref1['prev_cl'] : void 0) {
if (this.validateSavedOperations()) {
if (this.prev_cl.next_cl != null) {
throw new Error("Probably duplicated operations");
}
this.prev_cl.next_cl = this;
return Delimiter.__super__.execute.apply(this, arguments);
} else {
return false;
}
} else if ((this.prev_cl != null) && (this.prev_cl.next_cl == null)) {
delete this.prev_cl.unchecked.next_cl;
this.prev_cl.next_cl = this;
return Delimiter.__super__.execute.apply(this, arguments);
} else if ((this.prev_cl != null) || (this.next_cl != null) || true) {
return Delimiter.__super__.execute.apply(this, arguments);
}
};
Delimiter.prototype._encode = function() {
var _ref, _ref1;
return {
'type': this.type,
'uid': this.getUid(),
'prev': (_ref = this.prev_cl) != null ? _ref.getUid() : void 0,
'next': (_ref1 = this.next_cl) != null ? _ref1.getUid() : void 0
};
};
return Delimiter;
})(types.Operation);
types.Delimiter.parse = function(json) {
var next, prev, uid;
uid = json['uid'], prev = json['prev'], next = json['next'];
return new this(uid, prev, next);
};
return {
'types': types,
'execution_listener': execution_listener
};
};

View File

@@ -1,158 +0,0 @@
var text_types_uninitialized,
__hasProp = {}.hasOwnProperty,
__extends = function(child, parent) { for (var key in parent) { if (__hasProp.call(parent, key)) child[key] = parent[key]; } function ctor() { this.constructor = child; } ctor.prototype = parent.prototype; child.prototype = new ctor(); child.__super__ = parent.prototype; return child; };
text_types_uninitialized = require("./TextTypes");
module.exports = function(HB) {
var text_types, types;
text_types = text_types_uninitialized(HB);
types = text_types.types;
types.Object = (function(_super) {
__extends(Object, _super);
function Object() {
return Object.__super__.constructor.apply(this, arguments);
}
Object.prototype.type = "Object";
Object.prototype.applyDelete = function() {
return Object.__super__.applyDelete.call(this);
};
Object.prototype.cleanup = function() {
return Object.__super__.cleanup.call(this);
};
Object.prototype.toJson = function(transform_to_value) {
var json, name, o, that, val;
if (transform_to_value == null) {
transform_to_value = false;
}
if ((this.bound_json == null) || (Object.observe == null) || true) {
val = this.val();
json = {};
for (name in val) {
o = val[name];
if (o instanceof types.Object) {
json[name] = o.toJson(transform_to_value);
} else if (o instanceof types.Array) {
json[name] = o.toJson(transform_to_value);
} else if (transform_to_value && o instanceof types.Operation) {
json[name] = o.val();
} else {
json[name] = o;
}
}
this.bound_json = json;
if (Object.observe != null) {
that = this;
Object.observe(this.bound_json, function(events) {
var event, _i, _len, _results;
_results = [];
for (_i = 0, _len = events.length; _i < _len; _i++) {
event = events[_i];
if ((event.changedBy == null) && (event.type === "add" || (event.type = "update"))) {
_results.push(that.val(event.name, event.object[event.name]));
} else {
_results.push(void 0);
}
}
return _results;
});
this.observe(function(events) {
var event, notifier, oldVal, _i, _len, _results;
_results = [];
for (_i = 0, _len = events.length; _i < _len; _i++) {
event = events[_i];
if (event.created_ !== HB.getUserId()) {
notifier = Object.getNotifier(that.bound_json);
oldVal = that.bound_json[event.name];
if (oldVal != null) {
notifier.performChange('update', function() {
return that.bound_json[event.name] = that.val(event.name);
}, that.bound_json);
_results.push(notifier.notify({
object: that.bound_json,
type: 'update',
name: event.name,
oldValue: oldVal,
changedBy: event.changedBy
}));
} else {
notifier.performChange('add', function() {
return that.bound_json[event.name] = that.val(event.name);
}, that.bound_json);
_results.push(notifier.notify({
object: that.bound_json,
type: 'add',
name: event.name,
oldValue: oldVal,
changedBy: event.changedBy
}));
}
} else {
_results.push(void 0);
}
}
return _results;
});
}
}
return this.bound_json;
};
Object.prototype.val = function(name, content) {
var args, i, o, type, _i, _ref;
if ((name != null) && arguments.length > 1) {
if ((content != null) && (content.constructor != null)) {
type = types[content.constructor.name];
if ((type != null) && (type.create != null)) {
args = [];
for (i = _i = 1, _ref = arguments.length; 1 <= _ref ? _i < _ref : _i > _ref; i = 1 <= _ref ? ++_i : --_i) {
args.push(arguments[i]);
}
o = type.create.apply(null, args);
return Object.__super__.val.call(this, name, o);
} else {
throw new Error("The " + content.constructor.name + "-type is not (yet) supported in Y.");
}
} else {
return Object.__super__.val.call(this, name, content);
}
} else {
return Object.__super__.val.call(this, name);
}
};
Object.prototype._encode = function() {
return {
'type': this.type,
'uid': this.getUid()
};
};
return Object;
})(types.MapManager);
types.Object.parse = function(json) {
var uid;
uid = json['uid'];
return new this(uid);
};
types.Object.create = function(content, mutable) {
var json, n, o;
json = new types.Object().execute();
for (n in content) {
o = content[n];
json.val(n, o, mutable);
}
return json;
};
types.Number = {};
types.Number.create = function(content) {
return content;
};
return text_types;
};

View File

@@ -1,354 +0,0 @@
var basic_types_uninitialized,
__hasProp = {}.hasOwnProperty,
__extends = function(child, parent) { for (var key in parent) { if (__hasProp.call(parent, key)) child[key] = parent[key]; } function ctor() { this.constructor = child; } ctor.prototype = parent.prototype; child.prototype = new ctor(); child.__super__ = parent.prototype; return child; };
basic_types_uninitialized = require("./BasicTypes");
module.exports = function(HB) {
var basic_types, types;
basic_types = basic_types_uninitialized(HB);
types = basic_types.types;
types.MapManager = (function(_super) {
__extends(MapManager, _super);
function MapManager(uid) {
this.map = {};
MapManager.__super__.constructor.call(this, uid);
}
MapManager.prototype.type = "MapManager";
MapManager.prototype.applyDelete = function() {
var name, p, _ref;
_ref = this.map;
for (name in _ref) {
p = _ref[name];
p.applyDelete();
}
return MapManager.__super__.applyDelete.call(this);
};
MapManager.prototype.cleanup = function() {
return MapManager.__super__.cleanup.call(this);
};
MapManager.prototype.val = function(name, content) {
var o, prop, result, _ref;
if (arguments.length > 1) {
this.retrieveSub(name).replace(content);
return this;
} else if (name != null) {
prop = this.map[name];
if ((prop != null) && !prop.isContentDeleted()) {
return prop.val();
} else {
return void 0;
}
} else {
result = {};
_ref = this.map;
for (name in _ref) {
o = _ref[name];
if (!o.isContentDeleted()) {
result[name] = o.val();
}
}
return result;
}
};
MapManager.prototype["delete"] = function(name) {
var _ref;
if ((_ref = this.map[name]) != null) {
_ref.deleteContent();
}
return this;
};
MapManager.prototype.retrieveSub = function(property_name) {
var event_properties, event_this, map_uid, rm, rm_uid;
if (this.map[property_name] == null) {
event_properties = {
name: property_name
};
event_this = this;
map_uid = this.cloneUid();
map_uid.sub = property_name;
rm_uid = {
noOperation: true,
alt: map_uid
};
rm = new types.ReplaceManager(event_properties, event_this, rm_uid);
this.map[property_name] = rm;
rm.setParent(this, property_name);
rm.execute();
}
return this.map[property_name];
};
return MapManager;
})(types.Operation);
types.ListManager = (function(_super) {
__extends(ListManager, _super);
function ListManager(uid) {
this.beginning = new types.Delimiter(void 0, void 0);
this.end = new types.Delimiter(this.beginning, void 0);
this.beginning.next_cl = this.end;
this.beginning.execute();
this.end.execute();
ListManager.__super__.constructor.call(this, uid);
}
ListManager.prototype.type = "ListManager";
ListManager.prototype.execute = function() {
if (this.validateSavedOperations()) {
this.beginning.setParent(this);
this.end.setParent(this);
return ListManager.__super__.execute.apply(this, arguments);
} else {
return false;
}
};
ListManager.prototype.getLastOperation = function() {
return this.end.prev_cl;
};
ListManager.prototype.getFirstOperation = function() {
return this.beginning.next_cl;
};
ListManager.prototype.toArray = function() {
var o, result;
o = this.beginning.next_cl;
result = [];
while (o !== this.end) {
result.push(o);
o = o.next_cl;
}
return result;
};
ListManager.prototype.getOperationByPosition = function(position) {
var o;
o = this.beginning;
while (true) {
if (o instanceof types.Delimiter && (o.prev_cl != null)) {
o = o.prev_cl;
while (o.isDeleted() || !(o instanceof types.Delimiter)) {
o = o.prev_cl;
}
break;
}
if (position <= 0 && !o.isDeleted()) {
break;
}
o = o.next_cl;
if (!o.isDeleted()) {
position -= 1;
}
}
return o;
};
return ListManager;
})(types.Operation);
types.ReplaceManager = (function(_super) {
__extends(ReplaceManager, _super);
function ReplaceManager(event_properties, event_this, uid, beginning, end) {
this.event_properties = event_properties;
this.event_this = event_this;
if (this.event_properties['object'] == null) {
this.event_properties['object'] = this.event_this;
}
ReplaceManager.__super__.constructor.call(this, uid, beginning, end);
}
ReplaceManager.prototype.type = "ReplaceManager";
ReplaceManager.prototype.applyDelete = function() {
var o;
o = this.beginning;
while (o != null) {
o.applyDelete();
o = o.next_cl;
}
return ReplaceManager.__super__.applyDelete.call(this);
};
ReplaceManager.prototype.cleanup = function() {
return ReplaceManager.__super__.cleanup.call(this);
};
ReplaceManager.prototype.callEventDecorator = function(events) {
var event, name, prop, _i, _len, _ref;
if (!this.isDeleted()) {
for (_i = 0, _len = events.length; _i < _len; _i++) {
event = events[_i];
_ref = this.event_properties;
for (name in _ref) {
prop = _ref[name];
event[name] = prop;
}
}
this.event_this.callEvent(events);
}
return void 0;
};
ReplaceManager.prototype.replace = function(content, replaceable_uid) {
var o, relp;
o = this.getLastOperation();
relp = (new types.Replaceable(content, this, replaceable_uid, o, o.next_cl)).execute();
return void 0;
};
ReplaceManager.prototype.isContentDeleted = function() {
return this.getLastOperation().isDeleted();
};
ReplaceManager.prototype.deleteContent = function() {
(new types.Delete(void 0, this.getLastOperation().uid)).execute();
return void 0;
};
ReplaceManager.prototype.val = function() {
var o;
o = this.getLastOperation();
return typeof o.val === "function" ? o.val() : void 0;
};
ReplaceManager.prototype._encode = function() {
var json;
json = {
'type': this.type,
'uid': this.getUid(),
'beginning': this.beginning.getUid(),
'end': this.end.getUid()
};
return json;
};
return ReplaceManager;
})(types.ListManager);
types.Replaceable = (function(_super) {
__extends(Replaceable, _super);
function Replaceable(content, parent, uid, prev, next, origin, is_deleted) {
if ((content != null) && (content.creator != null)) {
this.saveOperation('content', content);
} else {
this.content = content;
}
this.saveOperation('parent', parent);
Replaceable.__super__.constructor.call(this, uid, prev, next, origin);
this.is_deleted = is_deleted;
}
Replaceable.prototype.type = "Replaceable";
Replaceable.prototype.val = function() {
return this.content;
};
Replaceable.prototype.applyDelete = function() {
var res, _base, _base1, _base2;
res = Replaceable.__super__.applyDelete.apply(this, arguments);
if (this.content != null) {
if (this.next_cl.type !== "Delimiter") {
if (typeof (_base = this.content).deleteAllObservers === "function") {
_base.deleteAllObservers();
}
}
if (typeof (_base1 = this.content).applyDelete === "function") {
_base1.applyDelete();
}
if (typeof (_base2 = this.content).dontSync === "function") {
_base2.dontSync();
}
}
this.content = null;
return res;
};
Replaceable.prototype.cleanup = function() {
return Replaceable.__super__.cleanup.apply(this, arguments);
};
Replaceable.prototype.callOperationSpecificInsertEvents = function() {
var old_value;
if (this.next_cl.type === "Delimiter" && this.prev_cl.type !== "Delimiter") {
if (!this.is_deleted) {
old_value = this.prev_cl.content;
this.parent.callEventDecorator([
{
type: "update",
changedBy: this.uid.creator,
oldValue: old_value
}
]);
}
this.prev_cl.applyDelete();
} else if (this.next_cl.type !== "Delimiter") {
this.applyDelete();
} else {
this.parent.callEventDecorator([
{
type: "add",
changedBy: this.uid.creator
}
]);
}
return void 0;
};
Replaceable.prototype.callOperationSpecificDeleteEvents = function(o) {
if (this.next_cl.type === "Delimiter") {
return this.parent.callEventDecorator([
{
type: "delete",
changedBy: o.uid.creator,
oldValue: this.content
}
]);
}
};
Replaceable.prototype._encode = function() {
var json;
json = {
'type': this.type,
'parent': this.parent.getUid(),
'prev': this.prev_cl.getUid(),
'next': this.next_cl.getUid(),
'origin': this.origin.getUid(),
'uid': this.getUid(),
'is_deleted': this.is_deleted
};
if (this.content instanceof types.Operation) {
json['content'] = this.content.getUid();
} else {
if ((this.content != null) && (this.content.creator != null)) {
throw new Error("You must not set creator here!");
}
json['content'] = this.content;
}
return json;
};
return Replaceable;
})(types.Insert);
types.Replaceable.parse = function(json) {
var content, is_deleted, next, origin, parent, prev, uid;
content = json['content'], parent = json['parent'], uid = json['uid'], prev = json['prev'], next = json['next'], origin = json['origin'], is_deleted = json['is_deleted'];
return new this(content, parent, uid, prev, next, origin, is_deleted);
};
return basic_types;
};

View File

@@ -1,561 +0,0 @@
var structured_types_uninitialized,
__hasProp = {}.hasOwnProperty,
__extends = function(child, parent) { for (var key in parent) { if (__hasProp.call(parent, key)) child[key] = parent[key]; } function ctor() { this.constructor = child; } ctor.prototype = parent.prototype; child.prototype = new ctor(); child.__super__ = parent.prototype; return child; };
structured_types_uninitialized = require("./StructuredTypes");
module.exports = function(HB) {
var parser, structured_types, types;
structured_types = structured_types_uninitialized(HB);
types = structured_types.types;
parser = structured_types.parser;
types.TextInsert = (function(_super) {
__extends(TextInsert, _super);
function TextInsert(content, uid, prev, next, origin, parent) {
if (content != null ? content.creator : void 0) {
this.saveOperation('content', content);
} else {
this.content = content;
}
TextInsert.__super__.constructor.call(this, uid, prev, next, origin, parent);
}
TextInsert.prototype.type = "TextInsert";
TextInsert.prototype.getLength = function() {
if (this.isDeleted()) {
return 0;
} else {
return this.content.length;
}
};
TextInsert.prototype.applyDelete = function() {
TextInsert.__super__.applyDelete.apply(this, arguments);
if (this.content instanceof types.Operation) {
this.content.applyDelete();
}
return this.content = null;
};
TextInsert.prototype.execute = function() {
if (!this.validateSavedOperations()) {
return false;
} else {
if (this.content instanceof types.Operation) {
this.content.insert_parent = this;
}
return TextInsert.__super__.execute.call(this);
}
};
TextInsert.prototype.val = function(current_position) {
if (this.isDeleted() || (this.content == null)) {
return "";
} else {
return this.content;
}
};
TextInsert.prototype._encode = function() {
var json, _ref;
json = {
'type': this.type,
'uid': this.getUid(),
'prev': this.prev_cl.getUid(),
'next': this.next_cl.getUid(),
'origin': this.origin.getUid(),
'parent': this.parent.getUid()
};
if (((_ref = this.content) != null ? _ref.getUid : void 0) != null) {
json['content'] = this.content.getUid();
} else {
json['content'] = this.content;
}
return json;
};
return TextInsert;
})(types.Insert);
types.TextInsert.parse = function(json) {
var content, next, origin, parent, prev, uid;
content = json['content'], uid = json['uid'], prev = json['prev'], next = json['next'], origin = json['origin'], parent = json['parent'];
return new types.TextInsert(content, uid, prev, next, origin, parent);
};
types.Array = (function(_super) {
__extends(Array, _super);
function Array() {
return Array.__super__.constructor.apply(this, arguments);
}
Array.prototype.type = "Array";
Array.prototype.applyDelete = function() {
var o;
o = this.end;
while (o != null) {
o.applyDelete();
o = o.prev_cl;
}
return Array.__super__.applyDelete.call(this);
};
Array.prototype.cleanup = function() {
return Array.__super__.cleanup.call(this);
};
Array.prototype.toJson = function(transform_to_value) {
var i, o, val, _i, _len, _results;
if (transform_to_value == null) {
transform_to_value = false;
}
val = this.val();
_results = [];
for (o = _i = 0, _len = val.length; _i < _len; o = ++_i) {
i = val[o];
if (o instanceof types.Object) {
_results.push(o.toJson(transform_to_value));
} else if (o instanceof types.Array) {
_results.push(o.toJson(transform_to_value));
} else if (transform_to_value && o instanceof types.Operation) {
_results.push(o.val());
} else {
_results.push(o);
}
}
return _results;
};
Array.prototype.val = function(pos) {
var o, result;
if (pos != null) {
o = this.getOperationByPosition(pos + 1);
if (!(o instanceof types.Delimiter)) {
return o.val();
} else {
throw new Error("this position does not exist");
}
} else {
o = this.beginning.next_cl;
result = [];
while (o !== this.end) {
if (!o.isDeleted()) {
result.push(o.val());
}
o = o.next_cl;
}
return result;
}
};
Array.prototype.push = function(content) {
return this.insertAfter(this.end.prev_cl, content);
};
Array.prototype.insertAfter = function(left, content, options) {
var c, createContent, right, tmp, _i, _len;
createContent = function(content, options) {
var type;
if ((content != null) && (content.constructor != null)) {
type = types[content.constructor.name];
if ((type != null) && (type.create != null)) {
return type.create(content, options);
} else {
throw new Error("The " + content.constructor.name + "-type is not (yet) supported in Y.");
}
} else {
return content;
}
};
right = left.next_cl;
while (right.isDeleted()) {
right = right.next_cl;
}
left = right.prev_cl;
if (content instanceof types.Operation) {
(new types.TextInsert(content, void 0, left, right)).execute();
} else {
for (_i = 0, _len = content.length; _i < _len; _i++) {
c = content[_i];
tmp = (new types.TextInsert(createContent(c, options), void 0, left, right)).execute();
left = tmp;
}
}
return this;
};
Array.prototype.insert = function(position, content, options) {
var ith;
ith = this.getOperationByPosition(position);
return this.insertAfter(ith, [content], options);
};
Array.prototype["delete"] = function(position, length) {
var d, delete_ops, i, o, _i;
o = this.getOperationByPosition(position + 1);
delete_ops = [];
for (i = _i = 0; 0 <= length ? _i < length : _i > length; i = 0 <= length ? ++_i : --_i) {
if (o instanceof types.Delimiter) {
break;
}
d = (new types.Delete(void 0, o)).execute();
o = o.next_cl;
while ((!(o instanceof types.Delimiter)) && o.isDeleted()) {
o = o.next_cl;
}
delete_ops.push(d._encode());
}
return this;
};
Array.prototype._encode = function() {
var json;
json = {
'type': this.type,
'uid': this.getUid()
};
return json;
};
return Array;
})(types.ListManager);
types.Array.parse = function(json) {
var uid;
uid = json['uid'];
return new this(uid);
};
types.Array.create = function(content, mutable) {
var ith, list;
if (mutable === "mutable") {
list = new types.Array().execute();
ith = list.getOperationByPosition(0);
list.insertAfter(ith, content);
return list;
} else if ((mutable == null) || (mutable === "immutable")) {
return content;
} else {
throw new Error("Specify either \"mutable\" or \"immutable\"!!");
}
};
types.String = (function(_super) {
__extends(String, _super);
function String(uid) {
this.textfields = [];
String.__super__.constructor.call(this, uid);
}
String.prototype.type = "String";
String.prototype.val = function() {
var c, o;
c = (function() {
var _i, _len, _ref, _results;
_ref = this.toArray();
_results = [];
for (_i = 0, _len = _ref.length; _i < _len; _i++) {
o = _ref[_i];
if (o.val != null) {
_results.push(o.val());
} else {
_results.push("");
}
}
return _results;
}).call(this);
return c.join('');
};
String.prototype.toString = function() {
return this.val();
};
String.prototype.insert = function(position, content, options) {
var ith;
ith = this.getOperationByPosition(position);
return this.insertAfter(ith, content, options);
};
String.prototype.bind = function(textfield, dom_root) {
var createRange, creator_token, t, word, writeContent, writeRange, _i, _len, _ref;
if (dom_root == null) {
dom_root = window;
}
if (dom_root.getSelection == null) {
dom_root = window;
}
_ref = this.textfields;
for (_i = 0, _len = _ref.length; _i < _len; _i++) {
t = _ref[_i];
if (t === textfield) {
return;
}
}
creator_token = false;
word = this;
textfield.value = this.val();
this.textfields.push(textfield);
if ((textfield.selectionStart != null) && (textfield.setSelectionRange != null)) {
createRange = function(fix) {
var left, right;
left = textfield.selectionStart;
right = textfield.selectionEnd;
if (fix != null) {
left = fix(left);
right = fix(right);
}
return {
left: left,
right: right
};
};
writeRange = function(range) {
writeContent(word.val());
return textfield.setSelectionRange(range.left, range.right);
};
writeContent = function(content) {
return textfield.value = content;
};
} else {
createRange = function(fix) {
var clength, edited_element, range, s;
range = {};
s = dom_root.getSelection();
clength = textfield.textContent.length;
range.left = Math.min(s.anchorOffset, clength);
range.right = Math.min(s.focusOffset, clength);
if (fix != null) {
range.left = fix(range.left);
range.right = fix(range.right);
}
edited_element = s.focusNode;
if (edited_element === textfield || edited_element === textfield.childNodes[0]) {
range.isReal = true;
} else {
range.isReal = false;
}
return range;
};
writeRange = function(range) {
var r, s, textnode;
writeContent(word.val());
textnode = textfield.childNodes[0];
if (range.isReal && (textnode != null)) {
if (range.left < 0) {
range.left = 0;
}
range.right = Math.max(range.left, range.right);
if (range.right > textnode.length) {
range.right = textnode.length;
}
range.left = Math.min(range.left, range.right);
r = document.createRange();
r.setStart(textnode, range.left);
r.setEnd(textnode, range.right);
s = window.getSelection();
s.removeAllRanges();
return s.addRange(r);
}
};
writeContent = function(content) {
var append;
append = "";
if (content[content.length - 1] === " ") {
content = content.slice(0, content.length - 1);
append = '&nbsp;';
}
textfield.textContent = content;
return textfield.innerHTML += append;
};
}
writeContent(this.val());
this.observe(function(events) {
var event, fix, o_pos, r, _j, _len1, _results;
_results = [];
for (_j = 0, _len1 = events.length; _j < _len1; _j++) {
event = events[_j];
if (!creator_token) {
if (event.type === "insert") {
o_pos = event.position;
fix = function(cursor) {
if (cursor <= o_pos) {
return cursor;
} else {
cursor += 1;
return cursor;
}
};
r = createRange(fix);
_results.push(writeRange(r));
} else if (event.type === "delete") {
o_pos = event.position;
fix = function(cursor) {
if (cursor < o_pos) {
return cursor;
} else {
cursor -= 1;
return cursor;
}
};
r = createRange(fix);
_results.push(writeRange(r));
} else {
_results.push(void 0);
}
} else {
_results.push(void 0);
}
}
return _results;
});
textfield.onkeypress = function(event) {
var char, diff, pos, r;
if (word.is_deleted) {
textfield.onkeypress = null;
return true;
}
creator_token = true;
char = null;
if (event.key != null) {
if (event.charCode === 32) {
char = " ";
} else if (event.keyCode === 13) {
char = '\n';
} else {
char = event.key;
}
} else {
char = window.String.fromCharCode(event.keyCode);
}
if (char.length > 1) {
return true;
} else if (char.length > 0) {
r = createRange();
pos = Math.min(r.left, r.right);
diff = Math.abs(r.right - r.left);
word["delete"](pos, diff);
word.insert(pos, char);
r.left = pos + char.length;
r.right = r.left;
writeRange(r);
}
event.preventDefault();
creator_token = false;
return false;
};
textfield.onpaste = function(event) {
if (word.is_deleted) {
textfield.onpaste = null;
return true;
}
return event.preventDefault();
};
textfield.oncut = function(event) {
if (word.is_deleted) {
textfield.oncut = null;
return true;
}
return event.preventDefault();
};
return textfield.onkeydown = function(event) {
var del_length, diff, new_pos, pos, r, val;
creator_token = true;
if (word.is_deleted) {
textfield.onkeydown = null;
return true;
}
r = createRange();
pos = Math.min(r.left, r.right, word.val().length);
diff = Math.abs(r.left - r.right);
if ((event.keyCode != null) && event.keyCode === 8) {
if (diff > 0) {
word["delete"](pos, diff);
r.left = pos;
r.right = pos;
writeRange(r);
} else {
if ((event.ctrlKey != null) && event.ctrlKey) {
val = word.val();
new_pos = pos;
del_length = 0;
if (pos > 0) {
new_pos--;
del_length++;
}
while (new_pos > 0 && val[new_pos] !== " " && val[new_pos] !== '\n') {
new_pos--;
del_length++;
}
word["delete"](new_pos, pos - new_pos);
r.left = new_pos;
r.right = new_pos;
writeRange(r);
} else {
if (pos > 0) {
word["delete"](pos - 1, 1);
r.left = pos - 1;
r.right = pos - 1;
writeRange(r);
}
}
}
event.preventDefault();
creator_token = false;
return false;
} else if ((event.keyCode != null) && event.keyCode === 46) {
if (diff > 0) {
word["delete"](pos, diff);
r.left = pos;
r.right = pos;
writeRange(r);
} else {
word["delete"](pos, 1);
r.left = pos;
r.right = pos;
writeRange(r);
}
event.preventDefault();
creator_token = false;
return false;
} else {
creator_token = false;
return true;
}
};
};
String.prototype._encode = function() {
var json;
json = {
'type': this.type,
'uid': this.getUid()
};
return json;
};
return String;
})(types.Array);
types.String.parse = function(json) {
var uid;
uid = json['uid'];
return new this(uid);
};
types.String.create = function(content, mutable) {
var word;
if (mutable === "mutable") {
word = new types.String().execute();
word.insert(0, content);
return word;
} else if ((mutable == null) || (mutable === "immutable")) {
return content;
} else {
throw new Error("Specify either \"mutable\" or \"immutable\"!!");
}
};
return structured_types;
};

View File

@@ -1,92 +0,0 @@
var Y, bindToChildren;
Y = require('./y');
bindToChildren = function(that) {
var attr, i, _i, _ref;
for (i = _i = 0, _ref = that.children.length; 0 <= _ref ? _i < _ref : _i > _ref; i = 0 <= _ref ? ++_i : --_i) {
attr = that.children.item(i);
if (attr.name != null) {
attr.val = that.val.val(attr.name);
}
}
return that.val.observe(function(events) {
var event, newVal, _j, _len, _results;
_results = [];
for (_j = 0, _len = events.length; _j < _len; _j++) {
event = events[_j];
if (event.name != null) {
_results.push((function() {
var _k, _ref1, _results1;
_results1 = [];
for (i = _k = 0, _ref1 = that.children.length; 0 <= _ref1 ? _k < _ref1 : _k > _ref1; i = 0 <= _ref1 ? ++_k : --_k) {
attr = that.children.item(i);
if ((attr.name != null) && attr.name === event.name) {
newVal = that.val.val(attr.name);
if (attr.val !== newVal) {
_results1.push(attr.val = newVal);
} else {
_results1.push(void 0);
}
} else {
_results1.push(void 0);
}
}
return _results1;
})());
} else {
_results.push(void 0);
}
}
return _results;
});
};
Polymer("y-object", {
ready: function() {
if (this.connector != null) {
this.val = new Y(this.connector);
return bindToChildren(this);
} else if (this.val != null) {
return bindToChildren(this);
}
},
valChanged: function() {
if ((this.val != null) && this.val.type === "Object") {
return bindToChildren(this);
}
},
connectorChanged: function() {
if (this.val == null) {
this.val = new Y(this.connector);
return bindToChildren(this);
}
}
});
Polymer("y-property", {
ready: function() {
if ((this.val != null) && (this.name != null)) {
if (this.val.constructor === Object) {
this.val = this.parentElement.val(this.name, this.val).val(this.name);
} else if (typeof this.val === "string") {
this.parentElement.val(this.name, this.val);
}
if (this.val.type === "Object") {
return bindToChildren(this);
}
}
},
valChanged: function() {
var _ref;
if ((this.val != null) && (this.name != null)) {
if (this.val.constructor === Object) {
return this.val = this.parentElement.val.val(this.name, this.val).val(this.name);
} else if (this.val.type === "Object") {
return bindToChildren(this);
} else if ((((_ref = this.parentElement.val) != null ? _ref.val : void 0) != null) && this.val !== this.parentElement.val.val(this.name)) {
return this.parentElement.val.val(this.name, this.val);
}
}
}
});

View File

@@ -1,54 +0,0 @@
var Engine, HistoryBuffer, adaptConnector, createY, json_types_uninitialized,
__hasProp = {}.hasOwnProperty,
__extends = function(child, parent) { for (var key in parent) { if (__hasProp.call(parent, key)) child[key] = parent[key]; } function ctor() { this.constructor = child; } ctor.prototype = parent.prototype; child.prototype = new ctor(); child.__super__ = parent.prototype; return child; };
json_types_uninitialized = require("./Types/JsonTypes");
HistoryBuffer = require("./HistoryBuffer");
Engine = require("./Engine");
adaptConnector = require("./ConnectorAdapter");
createY = function(connector) {
var HB, Y, type_manager, types, user_id;
user_id = null;
if (connector.id != null) {
user_id = connector.id;
} else {
user_id = "_temp";
connector.onUserIdSet(function(id) {
user_id = id;
return HB.resetUserId(id);
});
}
HB = new HistoryBuffer(user_id);
type_manager = json_types_uninitialized(HB);
types = type_manager.types;
Y = (function(_super) {
__extends(Y, _super);
function Y() {
this.connector = connector;
this.HB = HB;
this.types = types;
this.engine = new Engine(this.HB, type_manager.types);
adaptConnector(this.connector, this.engine, this.HB, type_manager.execution_listener);
Y.__super__.constructor.apply(this, arguments);
}
Y.prototype.getConnector = function() {
return this.connector;
};
return Y;
})(types.Object);
return new Y(HB.getReservedUniqueIdentifier()).execute();
};
module.exports = createY;
if ((typeof window !== "undefined" && window !== null) && (window.Y == null)) {
window.Y = createY;
}

File diff suppressed because one or more lines are too long

File diff suppressed because one or more lines are too long

View File

@@ -1,27 +0,0 @@
<html>
<head>
<meta charset="utf-8">
<title>Test Yatta!</title>
<link rel="stylesheet" href="../../node_modules/mocha/mocha.css" />
</head>
<body>
<div id="mocha"></div>
<div id="test_dom" test_attribute="the test" class="stuffy" style="color: blue"><p id="replaceme">replace me</p><p id="removeme">remove me</p><p>This is a test object for <b>XmlFramework</b></p><span class="span_element"><p>span</p></span></div>
<script src="../../node_modules/mocha/mocha.js" class="awesome"></script>
<script>
mocha.setup('bdd');
mocha.ui('bdd');
mocha.reporter('html');
</script>
<script src="TextYatta_test.js"></script>
<script src="JsonYatta_test.js"></script>
<!--script src="XmlYatta_test_browser.js"></script-->
<script>
//mocha.checkLeaks();
//mocha.run();
window.onerror = null;
if (window.mochaPhantomJS) { mochaPhantomJS.run(); }
else { mocha.run(); }
</script>
</body>
</html>

View File

@@ -1,5 +0,0 @@
# Examples
Here you find some (hopefully) usefull examples on how to use Yatta!
Please note, that the XMPP Connector is the best supported Connector at the moment.

View File

@@ -1,15 +0,0 @@
<!DOCTYPE HTML>
<html>
<head>
<meta charset=utf-8 />
<title>Y Example</title>
<script src="../../../webcomponentsjs/webcomponents.min.js"></script>
<link rel="import" href="../../../polymer/polymer.html">
<link rel="import" href="y-test.html">
</head>
<body>
<y-test></y-test>
<script src="./index.js"></script>
</body>
</html>

View File

@@ -1,19 +0,0 @@
setTimeout(function(){
window.y_test = document.querySelector("y-test");
window.y_test.y.val("stuff",{otherstuff:{nostuff:"this is no stuff"}})
setTimeout(function(){
var res = y_test.y.val("stuff");
if(!(y_test.nostuff === "this is no stuff")){
console.log("Deep inherit doesn't work!")
}
window.y_stuff_property.val = {nostuff: "this is also no stuff"};
setTimeout(function(){
if(!(y_test.nostuff === "this is also no stuff")){
console.log("Element val overwrite doesn't work")
}
console.log("Everything is fine :)");
},500)
},500);
},3000)

View File

@@ -1,38 +0,0 @@
<link rel="import" href="../../y-object.html">
<link rel="import" href="../../../y-connectors/y-xmpp/y-xmpp.html">
<link rel="import" href="../../../paper-slider/paper-slider.html">
<polymer-element name="y-test" attributes="y connector stuff">
<template>
<h1 id="text" contentEditable> Check this out !</h1>
<y-xmpp id="connector" connector={{connector}} room="testy-xmpp-polymer"></y-xmpp>
<y-object connector={{connector}} val={{y}}>
<y-property name="slider" val={{slider}}>
</y-property>
<y-property name="stuff" val={{stuff}}>
<y-property id="otherstuff" name="otherstuff" val={{otherstuff}}>
</y-property>
</y-property>
</y-object>
<y-object val={{otherstuff}}>
<y-property name="nostuff" val={{nostuff}}>
</y-property>
</y-object>
<paper-slider min="0" max="200" immediateValue={{slider}}></paper-slider>
</template>
<script>
Polymer({
ready: function(){
window.y_stuff_property = this.$.otherstuff;
this.y.val("slider",50)
var that = this;
this.connector.whenSynced(function(){
if(that.y.val("text") == null){
that.y.val("text","stuff","mutable");
}
that.y.val("text").bind(that.$.text,that.shadowRoot)
})
}
})
</script>
</polymer-element>

View File

@@ -1,20 +0,0 @@
<!DOCTYPE html>
<html>
<head>
<meta charset=utf-8 />
<title>Y Example</title>
<script src="../../build/browser/y.js"></script>
<script src="../../../y-connectors/y-xmpp/y-xmpp.js"></script>
<script src="./index.js"></script>
</head>
<body>
<h1 contentEditable> yjs Tutorial</h1>
<p> Collaborative Json editing with <a href="https://github.com/rwth-acis/yjs/">yjs</a>
and XMPP Connector. </p>
<textarea style="width:80%;" rows=40 id="textfield"></textarea>
<p> <a href="https://github.com/rwth-acis/yjs/">yjs</a> is a Framework for Real-Time collaboration on arbitrary data types.
</p>
</body>
</html>

View File

@@ -1,26 +0,0 @@
connector = new Y.XMPP("testy-xmpp-json2");
connector.debug = true
y = new Y(connector);
window.onload = function(){
var textbox = document.getElementById("textfield");
y.observe(function(events){
for(var i=0; i<events.length; i++){
var event = events[i];
if(event.name === "textfield" && event.type !== "delete"){
y.val("textfield").bind(textbox);
y.val("headline").bind(document.querySelector("h1"))
}
}
});
connector.whenSynced(function(){
if(y.val("textfield") == null){
y.val("headline","headline", "mutable");
y.val("textfield","stuff", "mutable")
}
})
};

33
examples/ace/index.html Normal file
View File

@@ -0,0 +1,33 @@
<!DOCTYPE html>
<html>
<head>
<style type="text/css" media="screen">
#aceContainer {
position: absolute;
top: 0;
right: 0;
bottom: 0;
left: 0;
}
.inserted {
position:absolute;
z-index:20;
background-color: #FFC107;
}
.deleted {
position:absolute;
z-index:20;
background-color: #FFC107;
}
</style>
</head>
<body>
<div id="aceContainer"></div>
<script src="../../y.js"></script>
<script src='../../../y-websockets-client/y-websockets-client.js'></script>
<script src="../bower_components/ace-builds/src/ace.js"></script>
<script src="./index.js"></script>
</body>
</html>

17
examples/ace/index.js Normal file
View File

@@ -0,0 +1,17 @@
/* global Y, ace */
let y = new Y('ace-example', {
connector: {
name: 'websockets-client',
url: 'http://127.0.0.1:1234'
}
})
window.yAce = y
// bind the textarea to a shared text element
var editor = ace.edit('aceContainer')
editor.setTheme('ace/theme/chrome')
editor.getSession().setMode('ace/mode/javascript')
y.define('ace', Y.Text).bindAce(editor)

19
examples/bower.json Normal file
View File

@@ -0,0 +1,19 @@
{
"name": "yjs-examples",
"version": "0.0.0",
"homepage": "y-js.org",
"authors": [
"Kevin Jahns <kevin.jahns@rwth-aachen.de>"
],
"description": "Examples for Yjs",
"license": "MIT",
"ignore": [],
"dependencies": {
"quill": "^1.0.0-rc.2",
"ace": "~1.2.3",
"ace-builds": "~1.2.3",
"jquery": "~2.2.2",
"d3": "^3.5.16",
"codemirror": "^5.25.0"
}
}

19
examples/chat/index.html Normal file
View File

@@ -0,0 +1,19 @@
<!DOCTYPE html>
<html>
<body>
<style>
#chat p span {
color: blue;
}
</style>
<div id="chat"></div>
<form id="chatform">
<input name="username" type="text" style="width:15%;">
<input name="message" type="text" style="width:60%;">
<input type="submit" value="Send">
</form>
<script src="../../y.js"></script>
<script src='../../../y-websockets-client/y-websockets-client.js'></script>
<script src="./index.js"></script>
</body>
</html>

65
examples/chat/index.js Normal file
View File

@@ -0,0 +1,65 @@
/* global Y */
let y = new Y('chat-example', {
connector: {
name: 'websockets-client',
url: 'http://127.0.0.1:1234'
}
})
window.yChat = y
let chatprotocol = y.define('chatprotocol', Y.Array)
let chatcontainer = document.querySelector('#chat')
// This functions inserts a message at the specified position in the DOM
function appendMessage (message, position) {
var p = document.createElement('p')
var uname = document.createElement('span')
uname.appendChild(document.createTextNode(message.username + ': '))
p.appendChild(uname)
p.appendChild(document.createTextNode(message.message))
chatcontainer.insertBefore(p, chatcontainer.children[position] || null)
}
// This function makes sure that only 7 messages exist in the chat history.
// The rest is deleted
function cleanupChat () {
if (chatprotocol.length > 7) {
chatprotocol.delete(0, chatprotocol.length - 7)
}
}
cleanupChat()
// Insert the initial content
chatprotocol.toArray().forEach(appendMessage)
// whenever content changes, make sure to reflect the changes in the DOM
chatprotocol.observe(function (event) {
// concurrent insertions may result in a history > 7, so cleanup here
cleanupChat()
chatcontainer.innerHTML = ''
chatprotocol.toArray().forEach(appendMessage)
})
document.querySelector('#chatform').onsubmit = function (event) {
// the form is submitted
var message = {
username: this.querySelector('[name=username]').value,
message: this.querySelector('[name=message]').value
}
if (message.username.length > 0 && message.message.length > 0) {
if (chatprotocol.length > 6) {
// If we are goint to insert the 8th element, make sure to delete first.
chatprotocol.delete(0)
}
// Here we insert a message in the shared chat type.
// This will call the observe function (see line 40)
// and reflect the change in the DOM
chatprotocol.push([message])
this.querySelector('[name=message]').value = ''
}
// Do not send this form!
event.preventDefault()
return false
}

View File

@@ -0,0 +1,24 @@
<!DOCTYPE html>
<html>
<head>
</head>
<body>
<div id="codeMirrorContainer"></div>
<script src="../../y.js"></script>
<script src='../../../y-websockets-client/y-websockets-client.js'></script>
<script src="../bower_components/codemirror/lib/codemirror.js"></script>
<script src="../bower_components/codemirror/mode/javascript/javascript.js"></script>
<link rel="stylesheet" href="../bower_components/codemirror/lib/codemirror.css">
<style>
.CodeMirror {
position: fixed;
top: 0;
left: 0;
height: 100%;
width: 100%;
}
</style>
<script src="./index.js"></script>
</body>
</html>

View File

@@ -0,0 +1,16 @@
/* global Y, CodeMirror */
let y = new Y('codemirror-example', {
connector: {
name: 'websockets-client',
url: 'http://127.0.0.1:1234'
}
})
window.yCodeMirror = y
var editor = CodeMirror(document.querySelector('#codeMirrorContainer'), {
mode: 'javascript',
lineNumbers: true
})
y.define('codemirror', Y.Text).bindCodeMirror(editor)

View File

@@ -0,0 +1,20 @@
<!DOCTYPE html>
<html>
<body>
<style>
path {
fill: none;
stroke: blue;
stroke-width: 1px;
stroke-linejoin: round;
stroke-linecap: round;
}
</style>
<button type="button" id="clearDrawingCanvas">Clear Drawing</button>
<svg id="drawingCanvas" viewbox="0 0 100 100" width="100%"></svg>
<script src="../../y.js"></script>
<script src='../../../y-websockets-client/y-websockets-client.js'></script>
<script src="../bower_components/d3/d3.min.js"></script>
<script src="./index.js"></script>
</body>
</html>

74
examples/drawing/index.js Normal file
View File

@@ -0,0 +1,74 @@
/* globals Y, d3 */
let y = new Y('drawing-example', {
connector: {
name: 'websockets-client',
url: 'http://127.0.0.1:1234'
}
})
window.yDrawing = y
var drawing = y.define('drawing', Y.Array)
var renderPath = d3.svg.line()
.x(function (d) { return d[0] })
.y(function (d) { return d[1] })
.interpolate('basic')
var svg = d3.select('#drawingCanvas')
.call(d3.behavior.drag()
.on('dragstart', dragstart)
.on('drag', drag)
.on('dragend', dragend))
// create line from a shared array object and update the line when the array changes
function drawLine (yarray) {
var line = svg.append('path').datum(yarray.toArray())
line.attr('d', renderPath)
yarray.observe(function (event) {
line.remove()
line = svg.append('path').datum(yarray.toArray())
line.attr('d', renderPath)
})
}
// call drawLine every time an array is appended
drawing.observe(function (event) {
event.removedElements.forEach(function () {
// if one is deleted, all will be deleted!!
svg.selectAll('path').remove()
})
event.addedElements.forEach(function (path) {
drawLine(path)
})
})
// draw all existing content
for (var i = 0; i < drawing.length; i++) {
drawLine(drawing.get(i))
}
// clear canvas on request
document.querySelector('#clearDrawingCanvas').onclick = function () {
drawing.delete(0, drawing.length)
}
var sharedLine = null
function dragstart () {
drawing.insert(drawing.length, [Y.Array])
sharedLine = drawing.get(drawing.length - 1)
}
// After one dragged event is recognized, we ignore them for 33ms.
var ignoreDrag = null
function drag () {
if (sharedLine != null && ignoreDrag == null) {
ignoreDrag = window.setTimeout(function () {
ignoreDrag = null
}, 10)
sharedLine.push([d3.mouse(this)])
}
}
function dragend () {
sharedLine = null
window.clearTimeout(ignoreDrag)
ignoreDrag = null
}

View File

@@ -0,0 +1,36 @@
<!DOCTYPE html>
<html>
</head>
<script src="../../y.js"></script>
<script src='../../../y-websockets-client/y-websockets-client.js'></script>
<script src="../bower_components/d3/d3.min.js"></script>
<script src="./index.js"></script>
<style>
magic-drawing .drawingCanvas path {
fill: none;
stroke: blue;
stroke-width: 2px;
stroke-linejoin: round;
stroke-linecap: round;
}
magic-drawing .drawingCanvas {
width: 500px;
height: 500px;
cursor: default;
padding:1px;
border:1px solid #021a40;
}
magic-drawing .clearDrawingButton {
position: absolute;
top: 0;
left: 0;
}
magic-drawing {
position: relative;
display: block;
}
</style>
</head>
<body contenteditable="true">
</body>
</html>

View File

@@ -0,0 +1,134 @@
/* global Y, d3 */
const hooks = {
'magic-drawing': {
fillType: function (dom, type) {
initDrawingBindings(type, dom)
},
createDom: function (type) {
const dom = document.createElement('magic-drawing')
initDrawingBindings(type, dom)
return dom
}
}
}
window.onload = function () {
window.domBinding = new Y.DomBinding(window.yXmlType, document.body, { hooks })
}
window.addMagicDrawing = function addMagicDrawing () {
let mt = document.createElement('magic-drawing')
mt.setAttribute('data-yjs-hook', 'magic-drawing')
document.body.append(mt)
}
var renderPath = d3.svg.line()
.x(function (d) { return d[0] })
.y(function (d) { return d[1] })
.interpolate('basic')
function initDrawingBindings (type, dom) {
dom.contentEditable = 'false'
dom.setAttribute('data-yjs-hook', 'magic-drawing')
var drawing = type.get('drawing')
if (drawing === undefined) {
drawing = type.set('drawing', new Y.Array())
}
var canvas = dom.querySelector('.drawingCanvas')
if (canvas == null) {
canvas = document.createElementNS('http://www.w3.org/2000/svg', 'svg')
canvas.setAttribute('class', 'drawingCanvas')
canvas.setAttribute('viewbox', '0 0 100 100')
dom.insertBefore(canvas, null)
}
var clearDrawingButton = dom.querySelector('.clearDrawingButton')
if (clearDrawingButton == null) {
clearDrawingButton = document.createElement('button')
clearDrawingButton.setAttribute('type', 'button')
clearDrawingButton.setAttribute('class', 'clearDrawingButton')
clearDrawingButton.innerText = 'Clear Drawing'
dom.insertBefore(clearDrawingButton, null)
}
var svg = d3.select(canvas)
.call(d3.behavior.drag()
.on('dragstart', dragstart)
.on('drag', drag)
.on('dragend', dragend))
// create line from a shared array object and update the line when the array changes
function drawLine (yarray, svg) {
var line = svg.append('path').datum(yarray.toArray())
line.attr('d', renderPath)
yarray.observe(function (event) {
line.remove()
line = svg.append('path').datum(yarray.toArray())
line.attr('d', renderPath)
})
}
// call drawLine every time an array is appended
drawing.observe(function (event) {
event.removedElements.forEach(function () {
// if one is deleted, all will be deleted!!
svg.selectAll('path').remove()
})
event.addedElements.forEach(function (path) {
drawLine(path, svg)
})
})
// draw all existing content
for (var i = 0; i < drawing.length; i++) {
drawLine(drawing.get(i), svg)
}
// clear canvas on request
clearDrawingButton.onclick = function () {
drawing.delete(0, drawing.length)
}
var sharedLine = null
function dragstart () {
drawing.insert(drawing.length, [Y.Array])
sharedLine = drawing.get(drawing.length - 1)
}
// After one dragged event is recognized, we ignore them for 33ms.
var ignoreDrag = null
function drag () {
if (sharedLine != null && ignoreDrag == null) {
ignoreDrag = window.setTimeout(function () {
ignoreDrag = null
}, 10)
sharedLine.push([d3.mouse(this)])
}
}
function dragend () {
sharedLine = null
window.clearTimeout(ignoreDrag)
ignoreDrag = null
}
}
let y = new Y('html-editor-drawing-hook-example', {
connector: {
name: 'websockets-client',
url: 'http://127.0.0.1:1234'
}
})
window.yXml = y
window.yXmlType = y.define('xml', Y.XmlFragment)
window.undoManager = new Y.utils.UndoManager(window.yXmlType, {
captureTimeout: 500
})
document.onkeydown = function interceptUndoRedo (e) {
if (e.keyCode === 90 && e.metaKey) {
if (!e.shiftKey) {
window.undoManager.undo()
} else {
window.undoManager.redo()
}
e.preventDefault()
}
}

View File

@@ -0,0 +1,11 @@
<!DOCTYPE html>
<html>
</head>
<script src="./index.js" type="module"></script>
</head>
<body>
<label for="room">Room: </label>
<input type="text" id="room" name="room">
<div id="content" contenteditable style="position:absolute;top:35px;left:0;right:0;bottom:0;outline: 0px solid transparent;"></div>
</body>
</html>

View File

@@ -0,0 +1,77 @@
import YWebsocketsConnector from '../../src/Connectors/WebsocketsConnector/WebsocketsConnector.js'
import Y from '../../src/Y.js'
import DomBinding from '../../src/Bindings/DomBinding/DomBinding.js'
import UndoManager from '../../src/Util/UndoManager.js'
import YXmlFragment from '../../src/Types/YXml/YXmlFragment.js'
import YXmlText from '../../src/Types/YXml/YXmlText.js'
import YXmlElement from '../../src/Types/YXml/YXmlElement.js'
import YIndexdDBPersistence from '../../src/Persistences/IndexedDBPersistence.js'
const connector = new YWebsocketsConnector()
const persistence = new YIndexdDBPersistence()
const roomInput = document.querySelector('#room')
let currentRoomName = null
let y = null
let domBinding = null
function setRoomName (roomName) {
if (currentRoomName !== roomName) {
console.log(`change room: "${roomName}"`)
roomInput.value = roomName
currentRoomName = roomName
location.hash = '#' + roomName
if (y !== null) {
domBinding.destroy()
}
const room = connector._rooms.get(roomName)
if (room !== undefined) {
y = room.y
} else {
y = new Y(roomName, null, null, { gc: true })
persistence.connectY(roomName, y).then(() => {
// connect after persisted content was applied to y
// If we don't wait for persistence, the other peer will send all data, waisting
// network bandwidth..
connector.connectY(roomName, y)
})
window.y = y
}
window.y = y
window.yXmlType = y.define('xml', YXmlFragment)
domBinding = new DomBinding(window.yXmlType, document.querySelector('#content'), { scrollingElement: document.scrollingElement })
}
}
window.setRoomName = setRoomName
window.createRooms = function (i = 0) {
setInterval(function () {
setRoomName(i + '')
i++
const nodes = []
for (let j = 0; j < 100; j++) {
const node = new YXmlElement('p')
node.insert(0, [new YXmlText(`This is the ${i}th paragraph of room ${i}`)])
nodes.push(node)
}
y.share.xml.insert(0, nodes)
}, 100)
}
connector.syncPersistence(persistence)
window.connector = connector
window.persistence = persistence
window.onload = function () {
setRoomName((location.hash || '#default').slice(1))
roomInput.addEventListener('input', e => {
const roomName = e.target.value
setRoomName(roomName)
})
}

View File

@@ -0,0 +1,24 @@
<!DOCTYPE html>
<html>
<head>
</head>
<body>
<div id="codeMirrorContainer"></div>
<script src="../bower_components/codemirror/lib/codemirror.js"></script>
<script src="../bower_components/codemirror/mode/javascript/javascript.js"></script>
<link rel="stylesheet" href="../bower_components/codemirror/lib/codemirror.css">
<style>
.CodeMirror {
position: fixed;
top: 0;
left: 0;
height: 100%;
width: 100%;
}
</style>
<script src="../../y.js"></script>
<script src='../../../y-websockets-client/y-websockets-client.js'></script>
<script src='../../../y-indexeddb/y-indexeddb.js'></script>
<script src="./index.js"></script>
</body>
</html>

View File

@@ -0,0 +1,19 @@
/* global Y, CodeMirror */
const persistence = new Y.IndexedDB()
const connector = {
connector: {
name: 'websockets-client',
room: 'codemirror-example'
}
}
const y = new Y('codemirror-example', connector, persistence)
window.yCodeMirror = y
var editor = CodeMirror(document.querySelector('#codeMirrorContainer'), {
mode: 'javascript',
lineNumbers: true
})
y.define('codemirror', Y.Text).bindCodeMirror(editor)

View File

@@ -0,0 +1,55 @@
<!DOCTYPE html>
<html>
<body>
<style>
.wrapper {
display: grid;
grid-template-columns: repeat(3, 1fr);
grid-gap: 7px;
}
.one {
grid-column: 1 ;
}
.two {
grid-column: 2;
}
.three {
grid-column: 3;
}
textarea {
width: calc(100% - 10px)
}
.editor-container {
background-color: #4caf50;
padding: 4px 5px 10px 5px;
border-radius: 11px;
}
.editor-container[disconnected] {
background-color: red;
}
.disconnected-info {
display: none;
}
.editor-container[disconnected] .disconnected-info {
display: inline;
}
</style>
<div class="wrapper">
<div id="container1" class="one editor-container">
<h1>Server 1 <span class="disconnected-info">(disconnected)</span></h1>
<textarea id="textarea1" rows=40 autocomplete="off" autocorrect="off" autocapitalize="off" spellcheck="false"></textarea>
</div>
<div id="container2" class="two editor-container">
<h1>Server 2 <span class="disconnected-info">(disconnected)</span></h1>
<textarea id="textarea2" rows=40 autocomplete="off" autocorrect="off" autocapitalize="off" spellcheck="false"></textarea>
</div>
<div id="container3" class="three editor-container">
<h1>Server 3 <span class="disconnected-info">(disconnected)</span></h1>
<textarea id="textarea3" rows=40 autocomplete="off" autocorrect="off" autocapitalize="off" spellcheck="false"></textarea>
</div>
</div>
<script src="../../y.js"></script>
<script src='../../../y-websockets-client/y-websockets-client.js'></script>
<script src="./index.js"></script>
</body>
</html>

View File

@@ -0,0 +1,38 @@
/* global Y */
function bindYjsInstance (y, suffix) {
y.define('textarea', Y.Text).bind(document.getElementById('textarea' + suffix))
y.connector.socket.on('connection', function () {
document.getElementById('container' + suffix).removeAttribute('disconnected')
})
y.connector.socket.on('disconnect', function () {
document.getElementById('container' + suffix).setAttribute('disconnected', true)
})
}
let y1 = new Y('infinite-example', {
connector: {
name: 'websockets-client',
url: 'http://127.0.0.1:1234'
}
})
window.y1 = y1
bindYjsInstance(y1, '1')
let y2 = new Y('infinite-example', {
connector: {
name: 'websockets-client',
url: 'http://127.0.0.1:1234'
}
})
window.y2 = y2
bindYjsInstance(y2, '2')
let y3 = new Y('infinite-example', {
connector: {
name: 'websockets-client',
url: 'http://127.0.0.1:1234'
}
})
window.y3 = y3
bindYjsInstance(y1, '3')

View File

@@ -0,0 +1,24 @@
<!DOCTYPE html>
<html>
<head>
<style type="text/css">
.draggable {
cursor: move;
}
</style>
</head>
<body>
<svg id="puzzle-example" width="100%" viewBox="0 0 800 800">
<g>
<path d="M 311.76636,154.23389 C 312.14136,171.85693 318.14087,184.97998 336.13843,184.23047 C 354.13647,183.48047 351.88647,180.48096 354.88599,178.98096 C 357.8855,177.48096 368.38452,170.35693 380.00806,169.98193 C 424.61841,168.54297 419.78296,223.6001 382.25757,223.6001 C 377.75806,223.6001 363.51001,219.10107 356.38599,211.97656 C 349.26196,204.85254 310.64185,207.10254 314.76636,236.34863 C 316.34888,247.5708 324.08374,267.90723 324.84595,286.23486 C 325.29321,296.99414 323.17603,307.00635 321.58911,315.6377 C 360.11353,305.4585 367.73462,304.30518 404.00513,312.83936 C 410.37915,314.33887 436.62573,310.21436 421.25269,290.3418 C 405.87964,270.46924 406.25464,248.34717 417.12817,240.84814 C 428.00171,233.34912 446.74976,228.84961 457.99829,234.09912 C 469.24683,239.34814 484.61987,255.84619 475.24585,271.59424 C 465.87231,287.34229 452.74878,290.7168 456.49829,303.84033 C 460.2478,316.96387 479.74536,320.33838 500.74292,321.83789 C 509.70142,322.47803 527.97192,323.28467 542.10864,320.12939 C 549.91821,318.38672 556.92212,315.89502 562.46753,313.56396 C 561.40796,277.80664 560.84888,245.71729 560.3606,241.97314 C 558.85278,230.41455 542.49536,217.28564 525.86499,223.2251 C 520.61548,225.1001 519.86548,231.84912 505.24243,232.59912 C 444.92798,235.69238 462.06958,143.26709 525.86499,180.48096 C 539.52759,188.45068 575.19409,190.7583 570.10913,156.85889 C 567.85962,141.86035 553.98608,102.86523 553.98608,102.86523 C 553.98608,102.86523 477.23755,111.82227 451.99878,91.991699 C 441.50024,83.74292 444.87476,69.494629 449.37427,61.245605 C 453.87378,52.996582 465.12231,46.622559 464.74731,36.123779 C 463.02563,-12.086426 392.96704,-10.902832 396.5061,36.873535 C 397.25562,46.997314 406.62964,52.621582 410.75415,60.495605 C 420.00757,78.161377 405.50024,96.073486 384.50757,99.490723 C 377.36206,100.65381 349.17505,102.65332 320.39429,102.23486 C 319.677,102.22461 318.95923,102.21143 318.24194,102.19775 C 315.08423,120.9751 311.55688,144.39697 311.76636,154.23389 z " style="fill:#f2c569;stroke:#000000" id="path2502"/>
<path d="M 500.74292,321.83789 C 479.74536,320.33838 460.2478,316.96387 456.49829,303.84033 C 452.74878,290.7168 465.87231,287.34229 475.24585,271.59424 C 484.61987,255.84619 469.24683,239.34814 457.99829,234.09912 C 446.74976,228.84961 428.00171,233.34912 417.12817,240.84814 C 406.25464,248.34717 405.87964,270.46924 421.25269,290.3418 C 436.62573,310.21436 410.37915,314.33887 404.00513,312.83936 C 367.73462,304.30518 360.11353,305.4585 321.58911,315.6377 C 320.56372,321.21484 319.75854,326.2207 320.01538,330.46191 C 320.76538,342.83545 329.3894,385.95508 327.8894,392.7041 C 326.3894,399.45312 313.64136,418.20117 297.89331,407.32715 C 282.14526,396.45361 276.52075,393.4541 265.27222,394.5791 C 254.02368,395.70361 239.77563,402.07812 239.77563,419.32568 C 239.77563,436.57373 250.27417,449.69727 268.64673,447.82227 C 287.36353,445.9126 317.92163,423.11035 325.63989,452.69678 C 330.1394,469.94434 330.51392,487.19238 330.1394,498.44092 C 329.95825,503.87646 326.09985,518.06592 322.16089,531.28125 C 353.2854,532.73682 386.47095,531.26611 394.2561,529.93701 C 430.30933,523.78174 429.31909,496.09766 412.62866,477.44385 C 406.25464,470.31934 401.75513,455.32129 405.87964,444.82275 C 414.07056,423.97314 458.8064,422.17773 473.37134,438.82324 C 483.86987,450.82178 475.99585,477.44385 468.49683,482.69287 C 453.52222,493.17529 457.22485,516.83008 473.37134,528.06201 C 504.79126,549.91943 572.35913,535.56152 572.35913,535.56152 C 572.35913,535.56152 567.85962,498.06592 567.48462,471.81934 C 567.10962,445.57275 589.60669,450.07227 593.3562,450.07227 C 597.10571,450.07227 604.22974,455.32129 609.47925,459.4458 C 614.72876,463.57031 618.85327,469.94434 630.85181,470.69434 C 677.43726,473.60596 674.58813,420.7373 631.97632,413.32666 C 623.35229,411.82666 614.72876,416.32617 603.10522,424.57519 C 591.48169,432.82422 577.23315,425.32519 570.10913,417.45117 C 566.07788,412.99561 563.8479,360.16406 562.46753,313.56396 C 556.92212,315.89502 549.91821,318.38672 542.10864,320.12939 C 527.97192,323.28467 509.70142,322.47803 500.74292,321.83789 z " style="fill:#f3f3d6;stroke:#000000" id="path2504"/>
<path d="M 240.52563,141.86035 C 257.60327,159.6499 243.94507,188.68799 214.65356,190.22949 C 185.09448,191.78516 164.66675,157.17822 190.28589,136.61621 C 200.49585,128.42139 198.05786,114.12158 179.78296,106.98975 C 154.4187,97.091553 90.54419,107.73975 90.54419,107.73975 C 90.54419,107.73975 100.88794,135.11328 101.41772,168.48242 C 101.79272,192.104 68.796875,189.47949 63.172607,186.85498 C 57.54834,184.23047 45.924805,173.73145 37.675781,173.73145 C -14.411865,173.73145 -10.013184,245.84375 39.925537,232.22412 C 48.174316,229.97461 56.42334,220.97559 68.796875,222.47559 C 81.17041,223.9751 87.544434,232.59912 87.544434,246.09766 C 87.544434,252.51709 87.0354,281.24268 86.340576,312.87012 C 119.15894,313.67676 160.60962,314.46582 170.03442,313.58887 C 186.15698,312.08936 195.90601,301.59033 188.40698,293.3418 C 180.90796,285.09277 156.16089,256.59619 179.03296,239.34814 C 201.90503,222.10059 235.65112,231.84912 239.77563,247.22217 C 243.90015,262.59521 240.52563,273.46924 234.90112,279.09326 C 229.27661,284.71777 210.52905,298.96582 221.40259,308.71484 C 232.27661,318.46338 263.77222,330.83691 302.39282,320.71338 C 309.58862,318.82715 315.92114,317.13525 321.58911,315.6377 C 323.17603,307.00635 325.29321,296.99414 324.84595,286.23486 C 324.08374,267.90723 316.34888,247.5708 314.76636,236.34863 C 310.64185,207.10254 349.26196,204.85254 356.38599,211.97656 C 363.51001,219.10107 377.75806,223.6001 382.25757,223.6001 C 419.78296,223.6001 424.61841,168.54297 380.00806,169.98193 C 368.38452,170.35693 357.8855,177.48096 354.88599,178.98096 C 351.88647,180.48096 354.13647,183.48047 336.13843,184.23047 C 318.14087,184.97998 312.14136,171.85693 311.76636,154.23389 C 311.55688,144.39697 315.08423,120.9751 318.24194,102.19775 C 290.37524,101.67725 262.46069,98.968262 254.39868,97.991211 C 233.38013,95.443359 217.17456,117.53662 240.52563,141.86035 z " style="fill:#bebcdb;stroke:#000000" id="path2506"/>
<path d="M 325.63989,452.69678 C 317.92163,423.11035 287.36353,445.9126 268.64673,447.82227 C 250.27417,449.69727 239.77563,436.57373 239.77563,419.32568 C 239.77563,402.07812 254.02368,395.70361 265.27222,394.5791 C 276.52075,393.4541 282.14526,396.45361 297.89331,407.32715 C 313.64136,418.20117 326.3894,399.45313 327.8894,392.7041 C 329.3894,385.95508 320.76538,342.83545 320.01538,330.46191 C 319.75855,326.2207 320.56372,321.21484 321.58911,315.6377 C 315.92114,317.13525 309.58862,318.82715 302.39282,320.71338 C 263.77222,330.83691 232.27661,318.46338 221.40259,308.71484 C 210.52905,298.96582 229.27661,284.71777 234.90112,279.09326 C 240.52563,273.46924 243.90015,262.59521 239.77563,247.22217 C 235.65112,231.84912 201.90503,222.10059 179.03296,239.34814 C 156.16089,256.59619 180.90796,285.09277 188.40698,293.3418 C 195.90601,301.59033 186.15698,312.08936 170.03442,313.58887 C 160.60962,314.46582 119.15894,313.67676 86.340576,312.87012 C 85.573975,347.74561 84.581299,386.15088 83.794922,402.07812 C 82.295166,432.44922 109.29175,422.32568 115.66577,420.82568 C 122.04028,419.32568 126.16479,409.57715 143.03735,408.45215 C 185.9231,405.59326 186.09985,466.69629 144.16235,467.69482 C 128.41431,468.06982 113.79126,451.19678 108.16675,447.44727 C 102.54272,443.69775 87.919433,442.94775 83.794922,457.9458 C 82.01709,464.41113 78.118652,481.65137 78.098144,496.18994 C 78.071045,515.38037 82.295166,531.81201 82.295166,531.81201 C 82.295166,531.81201 105.54224,526.5625 149.41187,526.5625 C 193.28149,526.5625 199.65552,547.93506 194.78101,558.80859 C 189.90649,569.68213 181.28296,568.93213 179.40796,583.18066 C 172.7063,634.11133 253.34106,631.08203 249.14917,584.68018 C 247.96948,571.62354 237.16528,571.66699 232.27661,557.68359 C 222.17944,528.80273 244.64966,523.56299 257.39819,524.68799 C 263.59351,525.23437 290.95679,529.73389 320.75757,531.21582 C 321.22437,531.23877 321.69312,531.25928 322.16089,531.28125 C 326.09985,518.06592 329.95825,503.87646 330.1394,498.44092 C 330.51392,487.19238 330.1394,469.94434 325.63989,452.69678 z " style="fill:#d3ea9d;stroke:#000000" id="path2508"/>
</g>
</svg>
<script src="../../y.js"></script>
<script src='../../../y-websockets-client/y-websockets-client.js'></script>
<script src="../bower_components/d3/d3.js"></script>
<script src="./index.js"></script>
</body>
</html>

67
examples/jigsaw/index.js Normal file
View File

@@ -0,0 +1,67 @@
/* global Y, d3 */
let y = new Y('jigsaw-example', {
connector: {
name: 'websockets-client',
url: 'http://127.0.0.1:1234'
}
})
let jigsaw = y.define('jigsaw', Y.Map)
window.yJigsaw = y
var origin // mouse start position - translation of piece
var drag = d3.behavior.drag()
.on('dragstart', function (params) {
// get the translation of the element
var translation = d3
.select(this)
.attr('transform')
.slice(10, -1)
.split(',')
.map(Number)
// mouse coordinates
var mouse = d3.mouse(this.parentNode)
origin = {
x: mouse[0] - translation[0],
y: mouse[1] - translation[1]
}
})
.on('drag', function () {
var mouse = d3.mouse(this.parentNode)
var x = mouse[0] - origin.x // =^= mouse - mouse at dragstart + translation at dragstart
var y = mouse[1] - origin.y
d3.select(this).attr('transform', 'translate(' + x + ',' + y + ')')
})
.on('dragend', function (piece, i) {
// save the current translation of the puzzle piece
var mouse = d3.mouse(this.parentNode)
var x = mouse[0] - origin.x
var y = mouse[1] - origin.y
jigsaw.set(piece, {x: x, y: y})
})
var data = ['piece1', 'piece2', 'piece3', 'piece4']
var pieces = d3.select(document.querySelector('#puzzle-example')).selectAll('path').data(data)
pieces
.classed('draggable', true)
.attr('transform', function (piece) {
var translation = piece.get('translation') || {x: 0, y: 0}
return 'translate(' + translation.x + ',' + translation.y + ')'
}).call(drag)
data.forEach(function (piece) {
jigsaw.observe(function () {
// whenever a property of a piece changes, update the translation of the pieces
pieces
.transition()
.attr('transform', function (piece) {
var translation = piece.get(piece)
if (translation == null || typeof translation.x !== 'number' || typeof translation.y !== 'number') {
translation = { x: 0, y: 0 }
}
return 'translate(' + translation.x + ',' + translation.y + ')'
})
})
})

View File

@@ -0,0 +1,21 @@
<!DOCTYPE html>
<html>
<head>
</head>
<body>
<div id="monacoContainer"></div>
<style>
#monacoContainer {
position: fixed;
top: 0;
left: 0;
height: 100%;
width: 100%;
}
</style>
<script src="../../y.js"></script>
<script src='../../../y-websockets-client/y-websockets-client.js'></script>
<script src="../node_modules/monaco-editor/min/vs/loader.js"></script>
<script src="./index.js"></script>
</body>
</html>

22
examples/monaco/index.js Normal file
View File

@@ -0,0 +1,22 @@
/* global Y, monaco */
require.config({ paths: { 'vs': '../node_modules/monaco-editor/min/vs' } })
let y = new Y('monaco-example', {
connector: {
name: 'websockets-client',
url: 'http://127.0.0.1:1234'
}
})
require(['vs/editor/editor.main'], function () {
window.yMonaco = y
// Create Monaco editor
var editor = monaco.editor.create(document.getElementById('monacoContainer'), {
language: 'javascript'
})
// Bind to y.share.monaco
y.define('monaco', Y.Text).bindMonaco(editor)
})

17
examples/notes/index.html Normal file
View File

@@ -0,0 +1,17 @@
<!DOCTYPE html>
<html>
</head>
<script src="./index.js" type="module"></script>
<link rel="stylesheet" type="text/css" href="style.css">
</head>
<body>
<div class="sidebar">
<h3 id="createNoteButton">+ Create Note</h3>
<div class="notelist"></div>
</div>
<div class="main">
<h1 id="headline"></h1>
<div id="editor" contenteditable="true"></div>
</div>
</body>
</html>

132
examples/notes/index.js Normal file
View File

@@ -0,0 +1,132 @@
/* eslint-env browser */
import { createYdbClient } from '../../YdbClient/index.js'
import Y from '../../src/Y.dist.js'
import * as ydb from '../../YdbClient/YdbClient.js'
import DomBinding from '../../src/Bindings/DomBinding/DomBinding.js'
const uuidv4 = () => 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, c => {
const r = Math.random() * 16 | 0
return (c === 'x' ? r : (r & 0x3 | 0x8)).toString(16)
})
createYdbClient('ws://localhost:8899/ws').then(ydbclient => {
const y = ydbclient.getY('notelist')
let ynotelist = y.define('notelist', Y.Array)
window.ynotelist = ynotelist
const domNoteList = document.querySelector('.notelist')
// utils
const addEventListener = (element, eventname, f) => element.addEventListener(eventname, f)
// create note button
const createNoteButton = event => {
ynotelist.insert(0, [{
guid: uuidv4(),
title: 'Note #' + ynotelist.length
}])
}
addEventListener(document.querySelector('#createNoteButton'), 'click', createNoteButton)
window.createNote = createNoteButton
window.createNotes = n => {
y.transact(() => {
for (let i = 0; i < n; i++) {
createNoteButton()
}
})
}
// clear note list function
window.clearNotes = () => ynotelist.delete(0, ynotelist.length)
// update editor and editor title
let domBinding = null
const updateEditor = () => {
domNoteList.querySelectorAll('a').forEach(a => a.classList.remove('selected'))
const domNote = document.querySelector('.notelist').querySelector(`[href="${location.hash}"]`)
if (domNote !== null) {
domNote.classList.add('selected')
const note = ynotelist.toArray().find(note => note.guid === location.hash.slice(1))
if (note !== undefined) {
const ydoc = ydbclient.getY(note.guid)
const ycontent = ydoc.define('content', Y.XmlFragment)
if (domBinding !== null) {
domBinding.destroy()
}
domBinding = new DomBinding(ycontent, document.querySelector('#editor'))
document.querySelector('#headline').innerText = note.title
document.querySelector('#editor').focus()
}
}
}
// listen to url-hash changes
addEventListener(window, 'hashchange', updateEditor)
updateEditor()
const styleSyncedState = (div, noteSyncedState) => {
let classes = []
if (noteSyncedState.persisted) {
classes.push('persisted')
} else {
if (noteSyncedState.upsynced) {
classes.push('upsynced')
} else {
classes.push('noupsynced')
}
if (noteSyncedState.downsynced) {
classes.push('downsynced')
} else {
classes.push('nodownsynced')
}
}
div.setAttribute('class', classes.join(' '))
}
ydbclient.on('syncstate', event => event.updated.forEach((state, room) => {
const a = document.querySelector(`[href="#${room}"]`)
if (a !== null) {
styleSyncedState(a.firstChild, state)
}
}))
// render note list
const renderNoteList = (elementList, insertRef = domNoteList.firstChild) => {
const fragment = document.createDocumentFragment()
const addNow = elementList.splice(0, 100)
addNow.forEach(note => {
const a = document.createElement('a')
const div = document.createElement('div')
a.insertBefore(div, null)
a.setAttribute('href', '#' + note.guid)
div.innerText = note.title
styleSyncedState(div, ydbclient.getRoomState(note.guid))
fragment.insertBefore(a, null)
})
if (domBinding == null) {
updateEditor()
}
domNoteList.insertBefore(fragment, insertRef)
if (elementList.length > 0) {
setTimeout(() => renderNoteList(elementList, insertRef), 100)
}
}
{
const notelist = ynotelist.toArray()
if (notelist.length > 0) {
renderNoteList(notelist)
ydb.subscribeRooms(ydbclient, notelist.map(note => note.guid))
}
}
ynotelist.observe(event => {
const addedNotes = []
event.addedElements.forEach(itemJson => itemJson._content.forEach(json => addedNotes.push(json)))
renderNoteList(addedNotes.slice().reverse()) // renderNoteList modifies addedNotes, so first make a copy of it
setTimeout(() => {
ydb.subscribeRooms(ydbclient, addedNotes.map(note => note.guid))
}, 200)
if (domBinding === null) {
updateEditor()
}
})
})

100
examples/notes/style.css Normal file
View File

@@ -0,0 +1,100 @@
.sidebar {
height: 100%; /* Full-height: remove this if you want "auto" height */
width: 180px; /* Set the width of the sidebar */
position: fixed; /* Fixed Sidebar (stay in place on scroll) */
z-index: 1; /* Stay on top */
top: 0; /* Stay at the top */
left: 0;
background-color: #111; /* Black */
overflow-x: hidden; /* Disable horizontal scroll */
padding-top: 20px;
color: #50abff;
}
#createNoteButton {
padding-left: .5em;
padding-top: .5em;
padding-bottom: .7em;
margin: 0;
cursor: pointer;
}
.notelist > a {
padding: 6px 8px 6px 16px;
text-decoration: none;
font-size: 13px;
color: #818181;
display: block;
}
.notelist > a.selected {
border-style: outset;
}
.notelist > a > div {
position: relative;
display: inline;
}
/* When you mouse over the navigation links, change their color */
.sidebar a:hover {
color: #f1f1f1;
}
/* Style page content */
.main {
margin-left: 180px; /* Same as the width of the sidebar */
padding: 0px 10px;
}
/* On smaller screens, where height is less than 450px, change the style of the sidebar (less padding and a smaller font size) */
@media screen and (max-height: 450px) {
.sidebar {padding-top: 15px;}
.sidebar a {font-size: 18px;}
}
#editor {
min-height: 400px;
}
[contenteditable]:focus {
outline: 0px solid transparent;
}
.persisted::before {
content: "✔";
color: green;
position: absolute;
right: -14px;
top: 0px;
}
.upsynced::before {
content: "↑";
color: green;
position: absolute;
right: -14px;
top: 0px;
}
.noupsynced::before {
content: "↑";
color: red;
position: absolute;
right: -14px;
top: 0px;
}
.downsynced::after {
content: "↓";
color: green;
position: absolute;
right: -22px;
top: 0px;
}
.nodownsynced::after {
content: "↓";
color: red;
position: absolute;
right: -22px;
top: 0px;
}

23
examples/package.json Normal file
View File

@@ -0,0 +1,23 @@
{
"name": "examples",
"version": "0.0.0",
"description": "",
"scripts": {
"dist": "rollup -c",
"watch": "rollup -cw"
},
"author": "Kevin Jahns",
"license": "MIT",
"dependencies": {
"monaco-editor": "^0.8.3",
"rollup": "^0.52.3"
},
"devDependencies": {
"standard": "^10.0.2"
},
"standard": {
"ignore": [
"bower_components"
]
}
}

View File

@@ -0,0 +1,21 @@
<!DOCTYPE html>
<html>
<head>
<!-- Main quill library -->
<script src="../../node_modules/quill/dist/quill.min.js"></script>
<link href="../../node_modules/quill/dist/quill.snow.css" rel="stylesheet">
<!-- Quill cursors module -->
<script src="../../node_modules/quill-cursors/dist/quill-cursors.min.js"></script>
<link href="../../node_modules/quill-cursors/dist/quill-cursors.css" rel="stylesheet">
<!-- Yjs Library and connector -->
<script src="../../y.js"></script>
<script src='../../../y-websockets-client/y-websockets-client.js'></script>
</head>
<body>
<div id="quill-container">
<div id="quill">
</div>
</div>
<script src="./index.js"></script>
</body>
</html>

View File

@@ -0,0 +1,78 @@
/* global Y, Quill, QuillCursors */
Quill.register('modules/cursors', QuillCursors)
let y = new Y('quill-0', {
connector: {
name: 'websockets-client',
url: 'http://127.0.0.1:1234'
}
})
let users = y.define('users', Y.Array)
let myUserInfo = new Y.Map()
myUserInfo.set('name', 'dada')
myUserInfo.set('color', 'red')
users.push([myUserInfo])
let quill = new Quill('#quill-container', {
modules: {
toolbar: [
[{ header: [1, 2, false] }],
['bold', 'italic', 'underline'],
['image', 'code-block'],
[{ color: [] }, { background: [] }], // Snow theme fills in values
[{ script: 'sub' }, { script: 'super' }],
['link', 'image'],
['link', 'code-block'],
[{ list: 'ordered' }, { list: 'bullet' }]
],
cursors: {
hideDelay: 500
}
},
placeholder: 'Compose an epic...',
theme: 'snow' // or 'bubble'
})
let cursors = quill.getModule('cursors')
function drawCursors () {
cursors.clearCursors()
users.map((user, userId) => {
if (user !== myUserInfo) {
let relativeRange = user.get('range')
let lastUpdated = new Date(user.get('last updated'))
if (lastUpdated != null && new Date() - lastUpdated < 20000 && relativeRange != null) {
let start = Y.utils.fromRelativePosition(y, relativeRange.start).offset
let end = Y.utils.fromRelativePosition(y, relativeRange.end).offset
let range = { index: start, length: end - start }
cursors.setCursor(userId + '', range, user.get('name'), user.get('color'))
}
}
})
}
users.observeDeep(drawCursors)
drawCursors()
quill.on('selection-change', function (range) {
if (range != null) {
myUserInfo.set('range', {
start: Y.utils.getRelativePosition(yText, range.index),
end: Y.utils.getRelativePosition(yText, range.index + range.length)
})
} else {
myUserInfo.delete('range')
}
myUserInfo.set('last updated', new Date().toString())
})
let yText = y.define('quill', Y.Text)
let quillBinding = new Y.QuillBinding(yText, quill)
window.quillBinding = quillBinding
window.yText = yText
window.y = y
window.quill = quill
window.users = users
window.cursors = cursors

18
examples/quill/index.html Normal file
View File

@@ -0,0 +1,18 @@
<!DOCTYPE html>
<html>
<head>
<!-- Main Quill library -->
<script src="../../node_modules/quill/dist/quill.min.js"></script>
<link href="../../node_modules/quill/dist/quill.snow.css" rel="stylesheet">
<!-- Yjs Library and connector -->
<script src="../../y.js"></script>
<script src='../../../y-websockets-client/y-websockets-client.js'></script>
</head>
<body>
<div id="quill-container">
<div id="quill">
</div>
</div>
<script src="./index.js"></script>
</body>
</html>

33
examples/quill/index.js Normal file
View File

@@ -0,0 +1,33 @@
/* global Y, Quill */
let y = new Y('quill-cursors-0', {
connector: {
name: 'websockets-client',
url: 'http://127.0.0.1:1234'
}
})
let quill = new Quill('#quill-container', {
modules: {
toolbar: [
[{ header: [1, 2, false] }],
['bold', 'italic', 'underline'],
['image', 'code-block'],
[{ color: [] }, { background: [] }], // Snow theme fills in values
[{ script: 'sub' }, { script: 'super' }],
['link', 'image'],
['link', 'code-block'],
[{ list: 'ordered' }, { list: 'bullet' }]
]
},
placeholder: 'Compose an epic...',
theme: 'snow' // or 'bubble'
})
let yText = y.define('quill', Y.Text)
let quillBinding = new Y.QuillBinding(yText, quill)
window.quillBinding = quillBinding
window.yText = yText
window.y = y
window.quill = quill

29
examples/rollup.config.js Normal file
View File

@@ -0,0 +1,29 @@
import nodeResolve from 'rollup-plugin-node-resolve'
import commonjs from 'rollup-plugin-commonjs'
var pkg = require('./package.json')
export default {
input: 'yjs-dist.js',
name: 'Y',
output: {
file: 'yjs-dist.js',
format: 'umd'
},
plugins: [
nodeResolve({
main: true,
module: true,
browser: true
}),
commonjs()
],
sourcemap: true,
banner: `
/**
* ${pkg.name} - ${pkg.description}
* @version v${pkg.version}
* @license ${pkg.license}
*/
`
}

View File

@@ -0,0 +1,31 @@
<!DOCTYPE html>
<html>
<head>
<!-- quill does not include dist files! We are using the hosted version instead -->
<!--link rel="stylesheet" href="../bower_components/quill/dist/quill.snow.css" /-->
<link href="https://cdn.quilljs.com/1.0.4/quill.snow.css" rel="stylesheet">
<link href="//cdnjs.cloudflare.com/ajax/libs/KaTeX/0.5.1/katex.min.css" rel="stylesheet">
<link href="//cdnjs.cloudflare.com/ajax/libs/highlight.js/9.2.0/styles/monokai-sublime.min.css" rel="stylesheet">
<style>
#quill-container {
border: 1px solid gray;
box-shadow: 0px 0px 10px gray;
}
</style>
</head>
<body>
<div id="quill-container">
<div id="quill">
</div>
</div>
<script src="//cdnjs.cloudflare.com/ajax/libs/KaTeX/0.5.1/katex.min.js" type="text/javascript"></script>
<script src="//cdnjs.cloudflare.com/ajax/libs/highlight.js/9.2.0/highlight.min.js" type="text/javascript"></script>
<script src="https://cdn.quilljs.com/1.0.4/quill.js"></script>
<!-- quill does not include dist files! We are using the hosted version instead (see above)
<script src="../bower_components/quill/dist/quill.js"></script>
-->
<script src="../bower_components/yjs/y.js"></script>
<script src="./index.js"></script>
</body>
</html>

View File

@@ -0,0 +1,49 @@
/* global Y, Quill */
// register yjs service worker
if ('serviceWorker' in navigator) {
// Register service worker
// it is important to copy yjs-sw-template to the root directory!
navigator.serviceWorker.register('./yjs-sw-template.js').then(function (reg) {
console.log('Yjs service worker registration succeeded. Scope is ' + reg.scope)
}).catch(function (err) {
console.error('Yjs service worker registration failed with error ' + err)
})
}
// initialize a shared object. This function call returns a promise!
Y({
db: {
name: 'memory'
},
connector: {
name: 'serviceworker',
room: 'ServiceWorkerExample2'
},
sourceDir: '/bower_components',
share: {
richtext: 'Richtext' // y.share.richtext is of type Y.Richtext
}
}).then(function (y) {
window.yServiceWorker = y
// create quill element
window.quill = new Quill('#quill', {
modules: {
formula: true,
syntax: true,
toolbar: [
[{ size: ['small', false, 'large', 'huge'] }],
['bold', 'italic', 'underline'],
[{ color: [] }, { background: [] }], // Snow theme fills in values
[{ script: 'sub' }, { script: 'super' }],
['link', 'image'],
['link', 'code-block'],
[{ list: 'ordered' }]
]
},
theme: 'snow'
})
// bind quill to richtext type
y.share.richtext.bind(window.quill)
})

View File

@@ -0,0 +1,22 @@
/* eslint-env worker */
// copy and modify this file
self.DBConfig = {
name: 'indexeddb'
}
self.ConnectorConfig = {
name: 'websockets-client',
// url: '..',
options: {
jsonp: false
}
}
importScripts(
'/bower_components/yjs/y.js',
'/bower_components/y-memory/y-memory.js',
'/bower_components/y-indexeddb/y-indexeddb.js',
'/bower_components/y-websockets-client/y-websockets-client.js',
'/bower_components/y-serviceworker/yjs-sw-include.js'
)

View File

@@ -0,0 +1,7 @@
<!DOCTYPE html>
<html>
<body>
<textarea style="width:80%;" rows=40 autocomplete="off" autocorrect="off" autocapitalize="off" spellcheck="false"></textarea>
<script type="module" src="./index.js"></script>
</body>
</html>

View File

@@ -0,0 +1,13 @@
/* eslint-env browser */
import * as Y from '../../src/index.js'
import WebsocketProvider from '../../provider/websocket/WebSocketProvider.js'
const provider = new WebsocketProvider('ws://localhost:1234/')
const ydocument = provider.get('textarea')
const type = ydocument.define('textarea', Y.Text)
const textarea = document.querySelector('textarea')
const binding = new Y.TextareaBinding(type, textarea)
window.textareaExample = {
provider, ydocument, type, textarea, binding
}

43
examples/xml/index.html Normal file
View File

@@ -0,0 +1,43 @@
<!DOCTYPE html>
<html>
</head>
<!-- jquery is not required for YXml. It is just here for convenience, and to test batch operations. -->
<script src="https://code.jquery.com/jquery-3.2.1.min.js"></script>
<script src="../../y.js"></script>
<script src='../../../y-websockets-client/y-websockets-client.js'></script>
<script src="./index.js"></script>
</head>
<body>
<h1> Shared DOM Example </h1>
<p> Use native DOM function or jQuery to manipulate the shared DOM (window.sharedDom). </p>
<div class="command">
<button type="button">Execute</button>
<input type="text" value='$(sharedDom).append("<h3>Appended headline</h3>")' size="40"/>
</div>
<div class="command">
<button type="button">Execute</button>
<input type="text" value='$(sharedDom).attr("align","right")' size="40"/>
</div>
<div class="command">
<button type="button">Execute</button>
<input type="text" value='$(sharedDom).attr("style","color:blue;")' size="40"/>
</div>
<script>
/* global $ */
var commands = document.querySelectorAll('.command')
Array.prototype.forEach.call(commands, function (command) {
var execute = function () {
// eslint-disable-next-line no-eval
eval(command.querySelector('input').value)
}
command.querySelector('button').onclick = execute
$(command.querySelector('input')).keyup(function (e) {
if (e.keyCode === 13) {
execute()
}
})
})
</script>
</body>
</html>

13
examples/xml/index.js Normal file
View File

@@ -0,0 +1,13 @@
/* global Y */
let y = new Y('xml-example', {
connector: {
name: 'websockets-client',
url: 'http://127.0.0.1:1234'
}
})
window.yXml = y
// bind xml type to a dom, and put it in body
window.sharedDom = y.define('xml', Y.XmlElement).toDom()
document.body.appendChild(window.sharedDom)

View File

@@ -1,122 +0,0 @@
gulp = require('gulp')
coffee = require('gulp-coffee')
concat = require('gulp-concat')
uglify = require 'gulp-uglify'
sourcemaps = require('gulp-sourcemaps')
browserify = require('gulp-browserify')
rename = require 'gulp-rename'
rimraf = require 'gulp-rimraf'
gulpif = require 'gulp-if'
ignore = require 'gulp-ignore'
git = require 'gulp-git'
debug = require 'gulp-debug'
coffeelint = require 'gulp-coffeelint'
mocha = require 'gulp-mocha'
run = require 'gulp-run'
ljs = require 'gulp-ljs'
plumber = require 'gulp-plumber'
mochaPhantomJS = require 'gulp-mocha-phantomjs'
cache = require 'gulp-cached'
coffeeify = require 'gulp-coffeeify'
gulp.task 'default', ['build_browser']
files =
lib : ['./lib/**/*.coffee']
browser : ['./lib/y.coffee','./lib/y-object.coffee']
#test : ['./test/**/*_test.coffee']
test : ['./test/Json_test.coffee', './test/Text_test.coffee']
gulp : ['./gulpfile.coffee']
examples : ['./examples/**/*.js']
other: ['./lib/**/*']
files.all = []
for name,file_list of files
if name isnt 'build'
files.all = files.all.concat file_list
gulp.task 'deploy_nodejs', ->
gulp.src files.lib
.pipe sourcemaps.init()
.pipe coffee()
.pipe sourcemaps.write './'
.pipe gulp.dest 'build/node/'
.pipe gulpif '!**/', git.add({args : "-A"})
gulp.task 'deploy', ['mocha', 'build_browser', 'deploy_nodejs', 'lint', 'phantom_test', 'codo']
gulp.task 'build_browser', ->
gulp.src files.browser, { read: false }
.pipe plumber()
.pipe browserify
transform: ['coffeeify']
extensions: ['.coffee']
debug : true
.pipe rename
extname: ".js"
.pipe gulp.dest './build/browser/'
.pipe uglify()
.pipe gulp.dest '.'
gulp.src files.test, {read: false}
.pipe plumber()
.pipe browserify
transform: ['coffeeify']
extensions: ['.coffee']
debug: true
.pipe rename
extname: ".js"
.pipe gulp.dest './build/test/'
gulp.task 'build_node', ->
gulp.src files.lib
.pipe plumber()
.pipe coffee({bare:true})
.pipe gulp.dest './build/node'
gulp.task 'build', ['build_node', 'build_browser'], ->
gulp.task 'watch', ['build_browser'], ->
gulp.watch files.all, ['build_browser']
gulp.task 'mocha', ->
gulp.src files.test, { read: false }
.pipe plumber()
.pipe mocha {reporter : 'list'}
gulp.task 'lint', ->
gulp.src files.all
.pipe ignore.include '**/*.coffee'
.pipe coffeelint {
"max_line_length":
"level": "ignore"
}
.pipe coffeelint.reporter()
gulp.task 'phantom_watch', ['phantom_test'], ->
gulp.watch files.all, ['phantom_test']
gulp.task 'literate', ->
gulp.src files.examples
.pipe ljs { code : true }
.pipe rename
basename : "README"
extname : ".md"
.pipe gulp.dest 'examples/'
.pipe gulpif '!**/', git.add({args : "-A"})
gulp.task 'codo', [], ()->
command = './node_modules/codo/bin/codo -o "./doc" --name "yjs" --readme "README.md" --undocumented false --private true --title "yjs API" ./lib - LICENSE.txt '
run(command).exec()
gulp.task 'phantom_test', ['build_browser'], ()->
gulp.src 'build/test/index.html'
.pipe mochaPhantomJS()
gulp.task 'clean', ->
gulp.src ['./build/{browser,test,node}/**/*.{js,map}','./doc/'], { read: false }
.pipe rimraf()
gulp.task 'default', ['clean','build'], ->

View File

@@ -1,55 +0,0 @@
#
# @param {Engine} engine The transformation engine
# @param {HistoryBuffer} HB
# @param {Array<Function>} execution_listener You must ensure that whenever an operation is executed, every function in this Array is called.
#
adaptConnector = (connector, engine, HB, execution_listener)->
send_ = (o)->
if o.uid.creator is HB.getUserId() and (typeof o.uid.op_number isnt "string")
connector.broadcast o
if connector.invokeSync?
HB.setInvokeSyncHandler connector.invokeSync
execution_listener.push send_
# For the XMPPConnector: lets send it as an array
# therefore, we have to restructure it later
encode_state_vector = (v)->
for name,value of v
user: name
state: value
parse_state_vector = (v)->
state_vector = {}
for s in v
state_vector[s.user] = s.state
state_vector
getStateVector = ()->
encode_state_vector HB.getOperationCounter()
getHB = (v)->
state_vector = parse_state_vector v
hb = HB._encode state_vector
for o in hb
o.fromHB = "true" # execute immediately
json =
hb: hb
state_vector: encode_state_vector HB.getOperationCounter()
json
applyHB = (hb)->
engine.applyOp hb
connector.getStateVector = getStateVector
connector.getHB = getHB
connector.applyHB = applyHB
connector.receive_handlers.push (sender, op)->
if op.uid.creator isnt HB.getUserId()
engine.applyOp op
connector.setIsBoundToY()
module.exports = adaptConnector

View File

@@ -1,112 +0,0 @@
window?.unprocessed_counter = 0 # del this
window?.unprocessed_exec_counter = 0 # TODO
window?.unprocessed_types = []
#
# @nodoc
# The Engine handles how and in which order to execute operations and add operations to the HistoryBuffer.
#
class Engine
#
# @param {HistoryBuffer} HB
# @param {Object} types list of available types
#
constructor: (@HB, @types)->
@unprocessed_ops = []
#
# Parses an operatio from the json format. It uses the specified parser in your OperationType module.
#
parseOperation: (json)->
type = @types[json.type]
if type?.parse?
type.parse json
else
throw new Error "You forgot to specify a parser for type #{json.type}. The message is #{JSON.stringify json}."
#
# Apply a set of operations. E.g. the operations you received from another users HB._encode().
# @note You must not use this method when you already have ops in your HB!
###
applyOpsBundle: (ops_json)->
ops = []
for o in ops_json
ops.push @parseOperation o
for o in ops
if not o.execute()
@unprocessed_ops.push o
@tryUnprocessed()
###
#
# Same as applyOps but operations that are already in the HB are not applied.
# @see Engine.applyOps
#
applyOpsCheckDouble: (ops_json)->
for o in ops_json
if not @HB.getOperation(o.uid)?
@applyOp o
#
# Apply a set of operations. (Helper for using applyOp on Arrays)
# @see Engine.applyOp
applyOps: (ops_json)->
@applyOp ops_json
#
# Apply an operation that you received from another peer.
# TODO: make this more efficient!!
# - operations may only executed in order by creator, order them in object of arrays (key by creator)
# - you can probably make something like dependencies (creator1 waits for creator2)
applyOp: (op_json_array)->
if op_json_array.constructor isnt Array
op_json_array = [op_json_array]
for op_json in op_json_array
# $parse_and_execute will return false if $o_json was parsed and executed, otherwise the parsed operadion
o = @parseOperation op_json
if op_json.fromHB?
o.fromHB = op_json.fromHB
# @HB.addOperation o
if @HB.getOperation(o)?
# nop
else if ((not @HB.isExpectedOperation(o)) and (not o.fromHB?)) or (not o.execute())
@unprocessed_ops.push o
window?.unprocessed_types.push o.type # TODO: delete this
@tryUnprocessed()
#
# Call this method when you applied a new operation.
# It checks if operations that were previously not executable are now executable.
#
tryUnprocessed: ()->
while true
old_length = @unprocessed_ops.length
unprocessed = []
for op in @unprocessed_ops
if @HB.getOperation(op)?
# nop
else if (not @HB.isExpectedOperation(op) and (not op.fromHB?)) or (not op.execute())
unprocessed.push op
@unprocessed_ops = unprocessed
if @unprocessed_ops.length is old_length
break
if @unprocessed_ops.length isnt 0
@HB.invokeSync()
module.exports = Engine

View File

@@ -1,220 +0,0 @@
#
# @nodoc
# An object that holds all applied operations.
#
# @note The HistoryBuffer is commonly abbreviated to HB.
#
class HistoryBuffer
#
# Creates an empty HB.
# @param {Object} user_id Creator of the HB.
#
constructor: (@user_id)->
@operation_counter = {}
@buffer = {}
@change_listeners = []
@garbage = [] # Will be cleaned on next call of garbageCollector
@trash = [] # Is deleted. Wait until it is not used anymore.
@performGarbageCollection = true
@garbageCollectTimeout = 30000
@reserved_identifier_counter = 0
setTimeout @emptyGarbage, @garbageCollectTimeout
resetUserId: (id)->
own = @buffer[@user_id]
if own?
for o_name,o of own
o.uid.creator = id
if @buffer[id]?
throw new Error "You are re-assigning an old user id - this is not (yet) possible!"
@buffer[id] = own
delete @buffer[@user_id]
@operation_counter[id] = @operation_counter[@user_id]
delete @operation_counter[@user_id]
@user_id = id
emptyGarbage: ()=>
for o in @garbage
#if @getOperationCounter(o.uid.creator) > o.uid.op_number
o.cleanup?()
@garbage = @trash
@trash = []
if @garbageCollectTimeout isnt -1
@garbageCollectTimeoutId = setTimeout @emptyGarbage, @garbageCollectTimeout
undefined
#
# Get the user id with wich the History Buffer was initialized.
#
getUserId: ()->
@user_id
addToGarbageCollector: ()->
if @performGarbageCollection
for o in arguments
if o?
@garbage.push o
stopGarbageCollection: ()->
@performGarbageCollection = false
@setManualGarbageCollect()
@garbage = []
@trash = []
setManualGarbageCollect: ()->
@garbageCollectTimeout = -1
clearTimeout @garbageCollectTimeoutId
@garbageCollectTimeoutId = undefined
setGarbageCollectTimeout: (@garbageCollectTimeout)->
#
# I propose to use it in your Framework, to create something like a root element.
# An operation with this identifier is not propagated to other clients.
# This is why everybode must create the same operation with this uid.
#
getReservedUniqueIdentifier: ()->
{
creator : '_'
op_number : "_#{@reserved_identifier_counter++}"
doSync: false
}
#
# Get the operation counter that describes the current state of the document.
#
getOperationCounter: (user_id)->
if not user_id?
res = {}
for user,ctn of @operation_counter
res[user] = ctn
res
else
@operation_counter[user_id]
isExpectedOperation: (o)->
@operation_counter[o.uid.creator] ?= 0
o.uid.op_number <= @operation_counter[o.uid.creator]
true #TODO: !! this could break stuff. But I dunno why
#
# Encode this operation in such a way that it can be parsed by remote peers.
# TODO: Make this more efficient!
_encode: (state_vector={})->
json = []
unknown = (user, o_number)->
if (not user?) or (not o_number?)
throw new Error "dah!"
not state_vector[user]? or state_vector[user] <= o_number
for u_name,user of @buffer
# TODO next, if @state_vector[user] <= state_vector[user]
for o_number,o of user
if o.uid.doSync and unknown(u_name, o_number)
# its necessary to send it, and not known in state_vector
o_json = o._encode()
if o.next_cl? # applies for all ops but the most right delimiter!
# search for the next _known_ operation. (When state_vector is {} then this is the Delimiter)
o_next = o.next_cl
while o_next.next_cl? and unknown(o_next.uid.creator, o_next.uid.op_number)
o_next = o_next.next_cl
o_json.next = o_next.getUid()
else if o.prev_cl? # most right delimiter only!
# same as the above with prev.
o_prev = o.prev_cl
while o_prev.prev_cl? and unknown(o_prev.uid.creator, o_prev.uid.op_number)
o_prev = o_prev.prev_cl
o_json.prev = o_prev.getUid()
json.push o_json
json
#
# Get the number of operations that were created by a user.
# Accordingly you will get the next operation number that is expected from that user.
# This will increment the operation counter.
#
getNextOperationIdentifier: (user_id)->
if not user_id?
user_id = @user_id
if not @operation_counter[user_id]?
@operation_counter[user_id] = 0
uid =
'creator' : user_id
'op_number' : @operation_counter[user_id]
'doSync' : true
@operation_counter[user_id]++
uid
#
# Retrieve an operation from a unique id.
#
# when uid has a "sub" property, the value of it will be applied
# on the operations retrieveSub method (which must! be defined)
#
getOperation: (uid)->
if uid.uid?
uid = uid.uid
o = @buffer[uid.creator]?[uid.op_number]
if uid.sub? and o?
o.retrieveSub uid.sub
else
o
#
# Add an operation to the HB. Note that this will not link it against
# other operations (it wont executed)
#
addOperation: (o)->
if not @buffer[o.uid.creator]?
@buffer[o.uid.creator] = {}
if @buffer[o.uid.creator][o.uid.op_number]?
throw new Error "You must not overwrite operations!"
if (o.uid.op_number.constructor isnt String) and (not @isExpectedOperation(o)) and (not o.fromHB?) # you already do this in the engine, so delete it here!
throw new Error "this operation was not expected!"
@addToCounter(o)
@buffer[o.uid.creator][o.uid.op_number] = o
o
removeOperation: (o)->
delete @buffer[o.uid.creator]?[o.uid.op_number]
# When the HB determines inconsistencies, then the invokeSync
# handler wil be called, which should somehow invoke the sync with another collaborator.
# The parameter of the sync handler is the user_id with wich an inconsistency was determined
setInvokeSyncHandler: (f)->
@invokeSync = f
# empty per default # TODO: do i need this?
invokeSync: ()->
# after you received the HB of another user (in the sync process),
# you renew your own state_vector to the state_vector of the other user
renewStateVector: (state_vector)->
for user,state of state_vector
if (not @operation_counter[user]?) or (@operation_counter[user] < state_vector[user])
@operation_counter[user] = state_vector[user]
#
# Increment the operation_counter that defines the current state of the Engine.
#
addToCounter: (o)->
if not @operation_counter[o.uid.creator]?
@operation_counter[o.uid.creator] = 0
if typeof o.uid.op_number is 'number' and o.uid.creator isnt @getUserId()
# TODO: check if operations are send in order
if o.uid.op_number is @operation_counter[o.uid.creator]
@operation_counter[o.uid.creator]++
else
@invokeSync o.uid.creator
#if @operation_counter[o.uid.creator] isnt (o.uid.op_number + 1)
#console.log (@operation_counter[o.uid.creator] - (o.uid.op_number + 1))
#console.log o
#throw new Error "You don't receive operations in the proper order. Try counting like this 0,1,2,3,4,.. ;)"
module.exports = HistoryBuffer

113
lib/NamedEventHandler.js Normal file
View File

@@ -0,0 +1,113 @@
/**
* Handles named events.
*/
export default class NamedEventHandler {
constructor () {
this._eventListener = new Map()
this._stateListener = new Map()
}
/**
* @private
* Returns all listeners that listen to a specified name.
*
* @param {String} name The query event name.
*/
_getListener (name) {
let listeners = this._eventListener.get(name)
if (listeners === undefined) {
listeners = {
once: new Set(),
on: new Set()
}
this._eventListener.set(name, listeners)
}
return listeners
}
/**
* Adds a named event listener. The listener is removed after it has been
* called once.
*
* @param {String} name The event name to listen to.
* @param {Function} f The function that is executed when the event is fired.
*/
once (name, f) {
let listeners = this._getListener(name)
listeners.once.add(f)
}
/**
* Adds a named event listener.
*
* @param {String} name The event name to listen to.
* @param {Function} f The function that is executed when the event is fired.
*/
on (name, f) {
let listeners = this._getListener(name)
listeners.on.add(f)
}
/**
* @private
* Init the saved state for an event name.
*/
_initStateListener (name) {
let state = this._stateListener.get(name)
if (state === undefined) {
state = {}
state.promise = new Promise(function (resolve) {
state.resolve = resolve
})
this._stateListener.set(name, state)
}
return state
}
/**
* Returns a Promise that is resolved when the event name is called.
* The Promise is immediately resolved when the event name was called in the
* past.
*/
when (name) {
return this._initStateListener(name).promise
}
/**
* Remove an event listener that was registered with either
* {@link EventHandler#on} or {@link EventHandler#once}.
*/
off (name, f) {
if (name == null || f == null) {
throw new Error('You must specify event name and function!')
}
const listener = this._eventListener.get(name)
if (listener !== undefined) {
listener.on.delete(f)
listener.once.delete(f)
}
}
/**
* Emit a named event. All registered event listeners that listen to the
* specified name will receive the event.
*
* @param {String} name The event name.
* @param {Array} args The arguments that are applied to the event listener.
*/
emit (name, ...args) {
this._initStateListener(name).resolve()
const listener = this._eventListener.get(name)
if (listener !== undefined) {
listener.on.forEach(f => f.apply(null, args))
listener.once.forEach(f => f.apply(null, args))
listener.once = new Set()
} else if (name === 'error') {
console.error(args[0])
}
}
destroy () {
this._eventListener = null
}
}

465
lib/Tree.js Normal file
View File

@@ -0,0 +1,465 @@
function rotate (tree, parent, newParent, n) {
if (parent === null) {
tree.root = newParent
newParent._parent = null
} else if (parent.left === n) {
parent.left = newParent
} else if (parent.right === n) {
parent.right = newParent
} else {
throw new Error('The elements are wrongly connected!')
}
}
class N {
// A created node is always red!
constructor (val) {
this.val = val
this.color = true
this._left = null
this._right = null
this._parent = null
}
isRed () { return this.color }
isBlack () { return !this.color }
redden () { this.color = true; return this }
blacken () { this.color = false; return this }
get grandparent () {
return this.parent.parent
}
get parent () {
return this._parent
}
get sibling () {
return (this === this.parent.left)
? this.parent.right : this.parent.left
}
get left () {
return this._left
}
get right () {
return this._right
}
set left (n) {
if (n !== null) {
n._parent = this
}
this._left = n
}
set right (n) {
if (n !== null) {
n._parent = this
}
this._right = n
}
rotateLeft (tree) {
const parent = this.parent
const newParent = this.right
const newRight = this.right.left
newParent.left = this
this.right = newRight
rotate(tree, parent, newParent, this)
}
next () {
if (this.right !== null) {
// search the most left node in the right tree
var o = this.right
while (o.left !== null) {
o = o.left
}
return o
} else {
var p = this
while (p.parent !== null && p !== p.parent.left) {
p = p.parent
}
return p.parent
}
}
prev () {
if (this.left !== null) {
// search the most right node in the left tree
var o = this.left
while (o.right !== null) {
o = o.right
}
return o
} else {
var p = this
while (p.parent !== null && p !== p.parent.right) {
p = p.parent
}
return p.parent
}
}
rotateRight (tree) {
const parent = this.parent
const newParent = this.left
const newLeft = this.left.right
newParent.right = this
this.left = newLeft
rotate(tree, parent, newParent, this)
}
getUncle () {
// we can assume that grandparent exists when this is called!
if (this.parent === this.parent.parent.left) {
return this.parent.parent.right
} else {
return this.parent.parent.left
}
}
}
/*
* This is a Red Black Tree implementation
*/
export default class Tree {
constructor () {
this.root = null
this.length = 0
}
findNext (id) {
var nextID = id.clone()
nextID.clock += 1
return this.findWithLowerBound(nextID)
}
findPrev (id) {
let prevID = id.clone()
prevID.clock -= 1
return this.findWithUpperBound(prevID)
}
findNodeWithLowerBound (from) {
var o = this.root
if (o === null) {
return null
} else {
while (true) {
if (from === null || (from.lessThan(o.val._id) && o.left !== null)) {
// o is included in the bound
// try to find an element that is closer to the bound
o = o.left
} else if (from !== null && o.val._id.lessThan(from)) {
// o is not within the bound, maybe one of the right elements is..
if (o.right !== null) {
o = o.right
} else {
// there is no right element. Search for the next bigger element,
// this should be within the bounds
return o.next()
}
} else {
return o
}
}
}
}
findNodeWithUpperBound (to) {
if (to === void 0) {
throw new Error('You must define from!')
}
var o = this.root
if (o === null) {
return null
} else {
while (true) {
if ((to === null || o.val._id.lessThan(to)) && o.right !== null) {
// o is included in the bound
// try to find an element that is closer to the bound
o = o.right
} else if (to !== null && to.lessThan(o.val._id)) {
// o is not within the bound, maybe one of the left elements is..
if (o.left !== null) {
o = o.left
} else {
// there is no left element. Search for the prev smaller element,
// this should be within the bounds
return o.prev()
}
} else {
return o
}
}
}
}
findSmallestNode () {
var o = this.root
while (o != null && o.left != null) {
o = o.left
}
return o
}
findWithLowerBound (from) {
var n = this.findNodeWithLowerBound(from)
return n == null ? null : n.val
}
findWithUpperBound (to) {
var n = this.findNodeWithUpperBound(to)
return n == null ? null : n.val
}
iterate (from, to, f) {
var o
if (from === null) {
o = this.findSmallestNode()
} else {
o = this.findNodeWithLowerBound(from)
}
while (
o !== null &&
(
to === null || // eslint-disable-line no-unmodified-loop-condition
o.val._id.lessThan(to) ||
o.val._id.equals(to)
)
) {
f(o.val)
o = o.next()
}
}
find (id) {
let n = this.findNode(id)
if (n !== null) {
return n.val
} else {
return null
}
}
findNode (id) {
var o = this.root
if (o === null) {
return null
} else {
while (true) {
if (o === null) {
return null
}
if (id.lessThan(o.val._id)) {
o = o.left
} else if (o.val._id.lessThan(id)) {
o = o.right
} else {
return o
}
}
}
}
delete (id) {
var d = this.findNode(id)
if (d == null) {
// throw new Error('Element does not exist!')
return
}
this.length--
if (d.left !== null && d.right !== null) {
// switch d with the greates element in the left subtree.
// o should have at most one child.
var o = d.left
// find
while (o.right !== null) {
o = o.right
}
// switch
d.val = o.val
d = o
}
// d has at most one child
// let n be the node that replaces d
var isFakeChild
var child = d.left || d.right
if (child === null) {
isFakeChild = true
child = new N(null)
child.blacken()
d.right = child
} else {
isFakeChild = false
}
if (d.parent === null) {
if (!isFakeChild) {
this.root = child
child.blacken()
child._parent = null
} else {
this.root = null
}
return
} else if (d.parent.left === d) {
d.parent.left = child
} else if (d.parent.right === d) {
d.parent.right = child
} else {
throw new Error('Impossible!')
}
if (d.isBlack()) {
if (child.isRed()) {
child.blacken()
} else {
this._fixDelete(child)
}
}
this.root.blacken()
if (isFakeChild) {
if (child.parent.left === child) {
child.parent.left = null
} else if (child.parent.right === child) {
child.parent.right = null
} else {
throw new Error('Impossible #3')
}
}
}
_fixDelete (n) {
function isBlack (node) {
return node !== null ? node.isBlack() : true
}
function isRed (node) {
return node !== null ? node.isRed() : false
}
if (n.parent === null) {
// this can only be called after the first iteration of fixDelete.
return
}
// d was already replaced by the child
// d is not the root
// d and child are black
var sibling = n.sibling
if (isRed(sibling)) {
// make sibling the grandfather
n.parent.redden()
sibling.blacken()
if (n === n.parent.left) {
n.parent.rotateLeft(this)
} else if (n === n.parent.right) {
n.parent.rotateRight(this)
} else {
throw new Error('Impossible #2')
}
sibling = n.sibling
}
// parent, sibling, and children of n are black
if (n.parent.isBlack() &&
sibling.isBlack() &&
isBlack(sibling.left) &&
isBlack(sibling.right)
) {
sibling.redden()
this._fixDelete(n.parent)
} else if (n.parent.isRed() &&
sibling.isBlack() &&
isBlack(sibling.left) &&
isBlack(sibling.right)
) {
sibling.redden()
n.parent.blacken()
} else {
if (n === n.parent.left &&
sibling.isBlack() &&
isRed(sibling.left) &&
isBlack(sibling.right)
) {
sibling.redden()
sibling.left.blacken()
sibling.rotateRight(this)
sibling = n.sibling
} else if (n === n.parent.right &&
sibling.isBlack() &&
isRed(sibling.right) &&
isBlack(sibling.left)
) {
sibling.redden()
sibling.right.blacken()
sibling.rotateLeft(this)
sibling = n.sibling
}
sibling.color = n.parent.color
n.parent.blacken()
if (n === n.parent.left) {
sibling.right.blacken()
n.parent.rotateLeft(this)
} else {
sibling.left.blacken()
n.parent.rotateRight(this)
}
}
}
put (v) {
var node = new N(v)
if (this.root !== null) {
var p = this.root // p abbrev. parent
while (true) {
if (node.val._id.lessThan(p.val._id)) {
if (p.left === null) {
p.left = node
break
} else {
p = p.left
}
} else if (p.val._id.lessThan(node.val._id)) {
if (p.right === null) {
p.right = node
break
} else {
p = p.right
}
} else {
p.val = node.val
return p
}
}
this._fixInsert(node)
} else {
this.root = node
}
this.length++
this.root.blacken()
return node
}
_fixInsert (n) {
if (n.parent === null) {
n.blacken()
return
} else if (n.parent.isBlack()) {
return
}
var uncle = n.getUncle()
if (uncle !== null && uncle.isRed()) {
// Note: parent: red, uncle: red
n.parent.blacken()
uncle.blacken()
n.grandparent.redden()
this._fixInsert(n.grandparent)
} else {
// Note: parent: red, uncle: black or null
// Now we transform the tree in such a way that
// either of these holds:
// 1) grandparent.left.isRed
// and grandparent.left.left.isRed
// 2) grandparent.right.isRed
// and grandparent.right.right.isRed
if (n === n.parent.right && n.parent === n.grandparent.left) {
n.parent.rotateLeft(this)
// Since we rotated and want to use the previous
// cases, we need to set n in such a way that
// n.parent.isRed again
n = n.left
} else if (n === n.parent.left && n.parent === n.grandparent.right) {
n.parent.rotateRight(this)
// see above
n = n.right
}
// Case 1) or 2) hold from here on.
// Now traverse grandparent, make parent a black node
// on the highest level which holds two red nodes.
n.parent.blacken()
n.grandparent.redden()
if (n === n.parent.left) {
// Case 1
n.grandparent.rotateRight(this)
} else {
// Case 2
n.grandparent.rotateLeft(this)
}
}
}
}

View File

@@ -1,555 +0,0 @@
module.exports = (HB)->
# @see Engine.parse
types = {}
execution_listener = []
#
# @private
# @abstract
# @nodoc
# A generic interface to operations.
#
# An operation has the following methods:
# * _encode: encodes an operation (needed only if instance of this operation is sent).
# * execute: execute the effects of this operations. Good examples are Insert-type and AddName-type
# * val: in the case that the operation holds a value
#
# Furthermore an encodable operation has a parser. We extend the parser object in order to parse encoded operations.
#
class types.Operation
#
# @param {Object} uid A unique identifier.
# If uid is undefined, a new uid will be created before at the end of the execution sequence
#
constructor: (uid)->
@is_deleted = false
@garbage_collected = false
@event_listeners = [] # TODO: rename to observers or sth like that
if uid?
@uid = uid
type: "Operation"
retrieveSub: ()->
throw new Error "sub properties are not enable on this operation type!"
#
# Add an event listener. It depends on the operation which events are supported.
# @param {Function} f f is executed in case the event fires.
#
observe: (f)->
@event_listeners.push f
#
# Deletes function from the observer list
# @see Operation.observe
#
# @overload unobserve(event, f)
# @param f {Function} The function that you want to delete
unobserve: (f)->
@event_listeners = @event_listeners.filter (g)->
f isnt g
#
# Deletes all subscribed event listeners.
# This should be called, e.g. after this has been replaced.
# (Then only one replace event should fire. )
# This is also called in the cleanup method.
deleteAllObservers: ()->
@event_listeners = []
delete: ()->
(new types.Delete undefined, @).execute()
null
#
# Fire an event.
# TODO: Do something with timeouts. You don't want this to fire for every operation (e.g. insert).
# TODO: do you need callEvent+forwardEvent? Only one suffices probably
callEvent: ()->
@forwardEvent @, arguments...
#
# Fire an event and specify in which context the listener is called (set 'this').
# TODO: do you need this ?
forwardEvent: (op, args...)->
for f in @event_listeners
f.call op, args...
isDeleted: ()->
@is_deleted
applyDelete: (garbagecollect = true)->
if not @garbage_collected
#console.log "applyDelete: #{@type}"
@is_deleted = true
if garbagecollect
@garbage_collected = true
HB.addToGarbageCollector @
cleanup: ()->
#console.log "cleanup: #{@type}"
HB.removeOperation @
@deleteAllObservers()
#
# Set the parent of this operation.
#
setParent: (@parent)->
#
# Get the parent of this operation.
#
getParent: ()->
@parent
#
# Computes a unique identifier (uid) that identifies this operation.
#
getUid: ()->
if not @uid.noOperation?
@uid
else
@uid.alt # could be (safely) undefined
cloneUid: ()->
uid = {}
for n,v of @getUid()
uid[n] = v
uid
dontSync: ()->
@uid.doSync = false
#
# @private
# If not already done, set the uid
# Add this to the HB
# Notify the all the listeners.
#
execute: ()->
@is_executed = true
if not @uid?
# When this operation was created without a uid, then set it here.
# There is only one other place, where this can be done - before an Insertion
# is executed (because we need the creator_id)
@uid = HB.getNextOperationIdentifier()
if not @uid.noOperation?
HB.addOperation @
for l in execution_listener
l @_encode()
@
#
# @private
# Operations may depend on other operations (linked lists, etc.).
# The saveOperation and validateSavedOperations methods provide
# an easy way to refer to these operations via an uid or object reference.
#
# For example: We can create a new Delete operation that deletes the operation $o like this
# - var d = new Delete(uid, $o); or
# - var d = new Delete(uid, $o.getUid());
# Either way we want to access $o via d.deletes. In the second case validateSavedOperations must be called first.
#
# @overload saveOperation(name, op_uid)
# @param {String} name The name of the operation. After validating (with validateSavedOperations) the instantiated operation will be accessible via this[name].
# @param {Object} op_uid A uid that refers to an operation
# @overload saveOperation(name, op)
# @param {String} name The name of the operation. After calling this function op is accessible via this[name].
# @param {Operation} op An Operation object
#
saveOperation: (name, op)->
#
# Every instance of $Operation must have an $execute function.
# We use duck-typing to check if op is instantiated since there
# could exist multiple classes of $Operation
#
if op?.execute?
# is instantiated
@[name] = op
else if op?
# not initialized. Do it when calling $validateSavedOperations()
@unchecked ?= {}
@unchecked[name] = op
#
# @private
# After calling this function all not instantiated operations will be accessible.
# @see Operation.saveOperation
#
# @return [Boolean] Whether it was possible to instantiate all operations.
#
validateSavedOperations: ()->
uninstantiated = {}
success = @
for name, op_uid of @unchecked
op = HB.getOperation op_uid
if op
@[name] = op
else
uninstantiated[name] = op_uid
success = false
delete @unchecked
if not success
@unchecked = uninstantiated
success
#
# @nodoc
# A simple Delete-type operation that deletes an operation.
#
class types.Delete extends types.Operation
#
# @param {Object} uid A unique identifier. If uid is undefined, a new uid will be created.
# @param {Object} deletes UID or reference of the operation that this to be deleted.
#
constructor: (uid, deletes)->
@saveOperation 'deletes', deletes
super uid
type: "Delete"
#
# @private
# Convert all relevant information of this operation to the json-format.
# This result can be sent to other clients.
#
_encode: ()->
{
'type': "Delete"
'uid': @getUid()
'deletes': @deletes.getUid()
}
#
# @private
# Apply the deletion.
#
execute: ()->
if @validateSavedOperations()
res = super
if res
@deletes.applyDelete @
res
else
false
#
# Define how to parse Delete operations.
#
types.Delete.parse = (o)->
{
'uid' : uid
'deletes': deletes_uid
} = o
new this(uid, deletes_uid)
#
# @nodoc
# A simple insert-type operation.
#
# An insert operation is always positioned between two other insert operations.
# Internally this is realized as associative lists, whereby each insert operation has a predecessor and a successor.
# For the sake of efficiency we maintain two lists:
# - The short-list (abbrev. sl) maintains only the operations that are not deleted
# - The complete-list (abbrev. cl) maintains all operations
#
class types.Insert extends types.Operation
#
# @param {Object} uid A unique identifier. If uid is undefined, a new uid will be created.
# @param {Operation} prev_cl The predecessor of this operation in the complete-list (cl)
# @param {Operation} next_cl The successor of this operation in the complete-list (cl)
#
constructor: (uid, prev_cl, next_cl, origin, parent)->
@saveOperation 'parent', parent
@saveOperation 'prev_cl', prev_cl
@saveOperation 'next_cl', next_cl
if origin?
@saveOperation 'origin', origin
else
@saveOperation 'origin', prev_cl
super uid
type: "Insert"
#
# set content to null and other stuff
# @private
#
applyDelete: (o)->
@deleted_by ?= []
callLater = false
if @parent? and not @isDeleted() and o? # o? : if not o?, then the delimiter deleted this Insertion. Furthermore, it would be wrong to call it. TODO: make this more expressive and save
# call iff wasn't deleted earlyer
callLater = true
if o?
@deleted_by.push o
garbagecollect = false
if @next_cl.isDeleted()
garbagecollect = true
super garbagecollect
if callLater
@callOperationSpecificDeleteEvents(o)
if @prev_cl?.isDeleted()
# garbage collect prev_cl
@prev_cl.applyDelete()
cleanup: ()->
if @next_cl.isDeleted()
# delete all ops that delete this insertion
for d in @deleted_by
d.cleanup()
# throw new Error "right is not deleted. inconsistency!, wrararar"
# change origin references to the right
o = @next_cl
while o.type isnt "Delimiter"
if o.origin is @
o.origin = @prev_cl
o = o.next_cl
# reconnect left/right
@prev_cl.next_cl = @next_cl
@next_cl.prev_cl = @prev_cl
super
# else
# Someone inserted something in the meantime.
# Remember: this can only be garbage collected when next_cl is deleted
#
# @private
# The amount of positions that $this operation was moved to the right.
#
getDistanceToOrigin: ()->
d = 0
o = @prev_cl
while true
if @origin is o
break
d++
o = o.prev_cl
d
#
# @private
# Include this operation in the associative lists.
execute: ()->
if not @validateSavedOperations()
return false
else
if @parent?
if not @prev_cl?
@prev_cl = @parent.beginning
if not @origin?
@origin = @parent.beginning
if not @next_cl?
@next_cl = @parent.end
if @prev_cl?
distance_to_origin = @getDistanceToOrigin() # most cases: 0
o = @prev_cl.next_cl
i = distance_to_origin # loop counter
# $this has to find a unique position between origin and the next known character
# case 1: $origin equals $o.origin: the $creator parameter decides if left or right
# let $OL= [o1,o2,o3,o4], whereby $this is to be inserted between o1 and o4
# o2,o3 and o4 origin is 1 (the position of o2)
# there is the case that $this.creator < o2.creator, but o3.creator < $this.creator
# then o2 knows o3. Since on another client $OL could be [o1,o3,o4] the problem is complex
# therefore $this would be always to the right of o3
# case 2: $origin < $o.origin
# if current $this insert_position > $o origin: $this ins
# else $insert_position will not change
# (maybe we encounter case 1 later, then this will be to the right of $o)
# case 3: $origin > $o.origin
# $this insert_position is to the left of $o (forever!)
while true
if o isnt @next_cl
# $o happened concurrently
if o.getDistanceToOrigin() is i
# case 1
if o.uid.creator < @uid.creator
@prev_cl = o
distance_to_origin = i + 1
else
# nop
else if o.getDistanceToOrigin() < i
# case 2
if i - distance_to_origin <= o.getDistanceToOrigin()
@prev_cl = o
distance_to_origin = i + 1
else
#nop
else
# case 3
break
i++
o = o.next_cl
else
# $this knows that $o exists,
break
# now reconnect everything
@next_cl = @prev_cl.next_cl
@prev_cl.next_cl = @
@next_cl.prev_cl = @
@setParent @prev_cl.getParent() # do Insertions always have a parent?
super # notify the execution_listeners
@callOperationSpecificInsertEvents()
@
callOperationSpecificInsertEvents: ()->
@parent?.callEvent [
type: "insert"
position: @getPosition()
object: @parent
changedBy: @uid.creator
value: @content
]
callOperationSpecificDeleteEvents: (o)->
@parent.callEvent [
type: "delete"
position: @getPosition()
object: @parent # TODO: You can combine getPosition + getParent in a more efficient manner! (only left Delimiter will hold @parent)
length: 1
changedBy: o.uid.creator
]
#
# Compute the position of this operation.
#
getPosition: ()->
position = 0
prev = @prev_cl
while true
if prev instanceof types.Delimiter
break
if not prev.isDeleted()
position++
prev = prev.prev_cl
position
#
# @nodoc
# Defines an object that is cannot be changed. You can use this to set an immutable string, or a number.
#
class types.ImmutableObject extends types.Operation
#
# @param {Object} uid A unique identifier. If uid is undefined, a new uid will be created.
# @param {Object} content
#
constructor: (uid, @content)->
super uid
type: "ImmutableObject"
#
# @return [String] The content of this operation.
#
val : ()->
@content
#
# Encode this operation in such a way that it can be parsed by remote peers.
#
_encode: ()->
json = {
'type': @type
'uid' : @getUid()
'content' : @content
}
json
types.ImmutableObject.parse = (json)->
{
'uid' : uid
'content' : content
} = json
new this(uid, content)
#
# @nodoc
# A delimiter is placed at the end and at the beginning of the associative lists.
# This is necessary in order to have a beginning and an end even if the content
# of the Engine is empty.
#
class types.Delimiter extends types.Operation
#
# @param {Object} uid A unique identifier. If uid is undefined, a new uid will be created.
# @param {Operation} prev_cl The predecessor of this operation in the complete-list (cl)
# @param {Operation} next_cl The successor of this operation in the complete-list (cl)
#
constructor: (prev_cl, next_cl, origin)->
@saveOperation 'prev_cl', prev_cl
@saveOperation 'next_cl', next_cl
@saveOperation 'origin', prev_cl
super {noOperation: true}
type: "Delimiter"
applyDelete: ()->
super()
o = @prev_cl
while o?
o.applyDelete()
o = o.prev_cl
undefined
cleanup: ()->
super()
#
# @private
#
execute: ()->
if @unchecked?['next_cl']?
super
else if @unchecked?['prev_cl']
if @validateSavedOperations()
if @prev_cl.next_cl?
throw new Error "Probably duplicated operations"
@prev_cl.next_cl = @
super
else
false
else if @prev_cl? and not @prev_cl.next_cl?
delete @prev_cl.unchecked.next_cl
@prev_cl.next_cl = @
super
else if @prev_cl? or @next_cl? or true # TODO: are you sure? This can happen right?
super
#else
# throw new Error "Delimiter is unsufficient defined!"
#
# @private
#
_encode: ()->
{
'type' : @type
'uid' : @getUid()
'prev' : @prev_cl?.getUid()
'next' : @next_cl?.getUid()
}
types.Delimiter.parse = (json)->
{
'uid' : uid
'prev' : prev
'next' : next
} = json
new this(uid, prev, next)
# This is what this module exports after initializing it with the HistoryBuffer
{
'types' : types
'execution_listener' : execution_listener
}

View File

@@ -1,148 +0,0 @@
text_types_uninitialized = require "./TextTypes"
module.exports = (HB)->
text_types = text_types_uninitialized HB
types = text_types.types
#
# Manages Object-like values.
#
class types.Object extends types.MapManager
#
# Identifies this class.
# Use it to check whether this is a json-type or something else.
#
# @example
# var x = y.val('unknown')
# if (x.type === "Object") {
# console.log JSON.stringify(x.toJson())
# }
#
type: "Object"
applyDelete: ()->
super()
cleanup: ()->
super()
#
# Transform this to a Json. If your browser supports Object.observe it will be transformed automatically when a change arrives.
# Otherwise you will loose all the sharing-abilities (the new object will be a deep clone)!
# @return {Json}
#
# TODO: at the moment you don't consider changing of properties.
# E.g.: let x = {a:[]}. Then x.a.push 1 wouldn't change anything
#
toJson: (transform_to_value = false)->
if not @bound_json? or not Object.observe? or true # TODO: currently, you are not watching mutable strings for changes, and, therefore, the @bound_json is not updated. TODO TODO wuawuawua easy
val = @val()
json = {}
for name, o of val
if o instanceof types.Object
json[name] = o.toJson(transform_to_value)
else if o instanceof types.Array
json[name] = o.toJson(transform_to_value)
else if transform_to_value and o instanceof types.Operation
json[name] = o.val()
else
json[name] = o
@bound_json = json
if Object.observe?
that = @
Object.observe @bound_json, (events)->
for event in events
if not event.changedBy? and (event.type is "add" or event.type = "update")
# this event is not created by Y.
that.val(event.name, event.object[event.name])
@observe (events)->
for event in events
if event.created_ isnt HB.getUserId()
notifier = Object.getNotifier(that.bound_json)
oldVal = that.bound_json[event.name]
if oldVal?
notifier.performChange 'update', ()->
that.bound_json[event.name] = that.val(event.name)
, that.bound_json
notifier.notify
object: that.bound_json
type: 'update'
name: event.name
oldValue: oldVal
changedBy: event.changedBy
else
notifier.performChange 'add', ()->
that.bound_json[event.name] = that.val(event.name)
, that.bound_json
notifier.notify
object: that.bound_json
type: 'add'
name: event.name
oldValue: oldVal
changedBy:event.changedBy
@bound_json
#
# @overload val()
# Get this as a Json object.
# @return [Json]
#
# @overload val(name)
# Get value of a property.
# @param {String} name Name of the object property.
# @return [Object Type||String|Object] Depending on the value of the property. If mutable it will return a Operation-type object, if immutable it will return String/Object.
#
# @overload val(name, content)
# Set a new property.
# @param {String} name Name of the object property.
# @param {Object|String} content Content of the object property.
# @return [Object Type] This object. (supports chaining)
#
val: (name, content)->
if name? and arguments.length > 1
if content? and content.constructor?
type = types[content.constructor.name]
if type? and type.create?
args = []
for i in [1...arguments.length]
args.push arguments[i]
o = type.create.apply null, args
super name, o
else
throw new Error "The #{content.constructor.name}-type is not (yet) supported in Y."
else
super name, content
else # is this even necessary ? I have to define every type anyway.. (see Number type below)
super name
#
# @private
#
_encode: ()->
{
'type' : @type
'uid' : @getUid()
}
types.Object.parse = (json)->
{
'uid' : uid
} = json
new this(uid)
types.Object.create = (content, mutable)->
json = new types.Object().execute()
for n,o of content
json.val n, o, mutable
json
types.Number = {}
types.Number.create = (content)->
content
text_types

View File

@@ -1,357 +0,0 @@
basic_types_uninitialized = require "./BasicTypes"
module.exports = (HB)->
basic_types = basic_types_uninitialized HB
types = basic_types.types
#
# @nodoc
# Manages map like objects. E.g. Json-Type and XML attributes.
#
class types.MapManager extends types.Operation
#
# @param {Object} uid A unique identifier. If uid is undefined, a new uid will be created.
#
constructor: (uid)->
@map = {}
super uid
type: "MapManager"
applyDelete: ()->
for name,p of @map
p.applyDelete()
super()
cleanup: ()->
super()
#
# @see JsonTypes.val
#
val: (name, content)->
if arguments.length > 1
@retrieveSub(name).replace content
@
else if name?
prop = @map[name]
if prop? and not prop.isContentDeleted()
prop.val()
else
undefined
else
result = {}
for name,o of @map
if not o.isContentDeleted()
result[name] = o.val()
result
delete: (name)->
@map[name]?.deleteContent()
@
retrieveSub: (property_name)->
if not @map[property_name]?
event_properties =
name: property_name
event_this = @
map_uid = @cloneUid()
map_uid.sub = property_name
rm_uid =
noOperation: true
alt: map_uid
rm = new types.ReplaceManager event_properties, event_this, rm_uid # this operation shall not be saved in the HB
@map[property_name] = rm
rm.setParent @, property_name
rm.execute()
@map[property_name]
#
# @nodoc
# Manages a list of Insert-type operations.
#
class types.ListManager extends types.Operation
#
# A ListManager maintains a non-empty list that has a beginning and an end (both Delimiters!)
# @param {Object} uid A unique identifier. If uid is undefined, a new uid will be created.
# @param {Delimiter} beginning Reference or Object.
# @param {Delimiter} end Reference or Object.
constructor: (uid)->
@beginning = new types.Delimiter undefined, undefined
@end = new types.Delimiter @beginning, undefined
@beginning.next_cl = @end
@beginning.execute()
@end.execute()
super uid
type: "ListManager"
#
# @private
# @see Operation.execute
#
execute: ()->
if @validateSavedOperations()
@beginning.setParent @
@end.setParent @
super
else
false
# Get the element previous to the delemiter at the end
getLastOperation: ()->
@end.prev_cl
# similar to the above
getFirstOperation: ()->
@beginning.next_cl
# Transforms the the list to an array
# Doesn't return left-right delimiter.
toArray: ()->
o = @beginning.next_cl
result = []
while o isnt @end
result.push o
o = o.next_cl
result
#
# Retrieves the x-th not deleted element.
# e.g. "abc" : the 1th character is "a"
# the 0th character is the left Delimiter
#
getOperationByPosition: (position)->
o = @beginning
while true
# find the i-th op
if o instanceof types.Delimiter and o.prev_cl?
# the user or you gave a position parameter that is to big
# for the current array. Therefore we reach a Delimiter.
# Then, we'll just return the last character.
o = o.prev_cl
while o.isDeleted() or not (o instanceof types.Delimiter)
o = o.prev_cl
break
if position <= 0 and not o.isDeleted()
break
o = o.next_cl
if not o.isDeleted()
position -= 1
o
#
# @nodoc
# Adds support for replace. The ReplaceManager manages Replaceable operations.
# Each Replaceable holds a value that is now replaceable.
#
# The TextType-type has implemented support for replace
# @see TextType
#
class types.ReplaceManager extends types.ListManager
#
# @param {Object} event_properties Decorates the event that is thrown by the RM
# @param {Object} event_this The object on which the event shall be executed
# @param {Operation} initial_content Initialize this with a Replaceable that holds the initial_content.
# @param {Object} uid A unique identifier. If uid is undefined, a new uid will be created.
# @param {Delimiter} beginning Reference or Object.
# @param {Delimiter} end Reference or Object.
constructor: (@event_properties, @event_this, uid, beginning, end)->
if not @event_properties['object']?
@event_properties['object'] = @event_this
super uid, beginning, end
type: "ReplaceManager"
applyDelete: ()->
o = @beginning
while o?
o.applyDelete()
o = o.next_cl
super()
cleanup: ()->
super()
#
# This doesn't throw the same events as the ListManager. Therefore, the
# Replaceables also not throw the same events.
# So, ReplaceManager and ListManager both implement
# these functions that are called when an Insertion is executed (at the end).
#
#
callEventDecorator: (events)->
if not @isDeleted()
for event in events
for name,prop of @event_properties
event[name] = prop
@event_this.callEvent events
undefined
#
# Replace the existing word with a new word.
#
# @param content {Operation} The new value of this ReplaceManager.
# @param replaceable_uid {UID} Optional: Unique id of the Replaceable that is created
#
replace: (content, replaceable_uid)->
o = @getLastOperation()
relp = (new types.Replaceable content, @, replaceable_uid, o, o.next_cl).execute()
# TODO: delete repl (for debugging)
undefined
isContentDeleted: ()->
@getLastOperation().isDeleted()
deleteContent: ()->
(new types.Delete undefined, @getLastOperation().uid).execute()
undefined
#
# Get the value of this
# @return {String}
#
val: ()->
o = @getLastOperation()
#if o instanceof types.Delimiter
# throw new Error "Replace Manager doesn't contain anything."
o.val?() # ? - for the case that (currently) the RM does not contain anything (then o is a Delimiter)
#
# Encode this operation in such a way that it can be parsed by remote peers.
#
_encode: ()->
json =
{
'type': @type
'uid' : @getUid()
'beginning' : @beginning.getUid()
'end' : @end.getUid()
}
json
#
# @nodoc
# The ReplaceManager manages Replaceables.
# @see ReplaceManager
#
class types.Replaceable extends types.Insert
#
# @param {Operation} content The value that this Replaceable holds.
# @param {ReplaceManager} parent Used to replace this Replaceable with another one.
# @param {Object} uid A unique identifier. If uid is undefined, a new uid will be created.
#
constructor: (content, parent, uid, prev, next, origin, is_deleted)->
# see encode to see, why we are doing it this way
if content? and content.creator?
@saveOperation 'content', content
else
@content = content
@saveOperation 'parent', parent
super uid, prev, next, origin # Parent is already saved by Replaceable
@is_deleted = is_deleted
type: "Replaceable"
#
# Return the content that this operation holds.
#
val: ()->
@content
applyDelete: ()->
res = super
if @content?
if @next_cl.type isnt "Delimiter"
@content.deleteAllObservers?()
@content.applyDelete?()
@content.dontSync?()
@content = null
res
cleanup: ()->
super
#
# This is called, when the Insert-type was successfully executed.
# TODO: consider doing this in a more consistent manner. This could also be
# done with execute. But currently, there are no specital Insert-types for ListManager.
#
callOperationSpecificInsertEvents: ()->
if @next_cl.type is "Delimiter" and @prev_cl.type isnt "Delimiter"
# this replaces another Replaceable
if not @is_deleted # When this is received from the HB, this could already be deleted!
old_value = @prev_cl.content
@parent.callEventDecorator [
type: "update"
changedBy: @uid.creator
oldValue: old_value
]
@prev_cl.applyDelete()
else if @next_cl.type isnt "Delimiter"
# This won't be recognized by the user, because another
# concurrent operation is set as the current value of the RM
@applyDelete()
else # prev _and_ next are Delimiters. This is the first created Replaceable in the RM
@parent.callEventDecorator [
type: "add"
changedBy: @uid.creator
]
undefined
callOperationSpecificDeleteEvents: (o)->
if @next_cl.type is "Delimiter"
@parent.callEventDecorator [
type: "delete"
changedBy: o.uid.creator
oldValue: @content
]
#
# Encode this operation in such a way that it can be parsed by remote peers.
#
_encode: ()->
json =
{
'type': @type
'parent' : @parent.getUid()
'prev': @prev_cl.getUid()
'next': @next_cl.getUid()
'origin' : @origin.getUid()
'uid' : @getUid()
'is_deleted': @is_deleted
}
if @content instanceof types.Operation
json['content'] = @content.getUid()
else
# This could be a security concern.
# Throw error if the users wants to trick us
if @content? and @content.creator?
throw new Error "You must not set creator here!"
json['content'] = @content
json
types.Replaceable.parse = (json)->
{
'content' : content
'parent' : parent
'uid' : uid
'prev': prev
'next': next
'origin' : origin
'is_deleted': is_deleted
} = json
new this(content, parent, uid, prev, next, origin, is_deleted)
basic_types

View File

@@ -1,525 +0,0 @@
structured_types_uninitialized = require "./StructuredTypes"
module.exports = (HB)->
structured_types = structured_types_uninitialized HB
types = structured_types.types
parser = structured_types.parser
#
# @nodoc
# Extends the basic Insert type to an operation that holds a text value
#
class types.TextInsert extends types.Insert
#
# @param {String} content The content of this Insert-type Operation. Usually you restrict the length of content to size 1
# @param {Object} uid A unique identifier. If uid is undefined, a new uid will be created.
#
constructor: (content, uid, prev, next, origin, parent)->
if content?.creator
@saveOperation 'content', content
else
@content = content
super uid, prev, next, origin, parent
type: "TextInsert"
#
# Retrieve the effective length of the $content of this operation.
#
getLength: ()->
if @isDeleted()
0
else
@content.length
applyDelete: ()->
super # no braces indeed!
if @content instanceof types.Operation
@content.applyDelete()
@content = null
execute: ()->
if not @validateSavedOperations()
return false
else
if @content instanceof types.Operation
@content.insert_parent = @
super()
#
# The result will be concatenated with the results from the other insert operations
# in order to retrieve the content of the engine.
# @see HistoryBuffer.toExecutedArray
#
val: (current_position)->
if @isDeleted() or not @content?
""
else
@content
#
# Convert all relevant information of this operation to the json-format.
# This result can be send to other clients.
#
_encode: ()->
json =
{
'type': @type
'uid' : @getUid()
'prev': @prev_cl.getUid()
'next': @next_cl.getUid()
'origin': @origin.getUid()
'parent': @parent.getUid()
}
if @content?.getUid?
json['content'] = @content.getUid()
else
json['content'] = @content
json
types.TextInsert.parse = (json)->
{
'content' : content
'uid' : uid
'prev': prev
'next': next
'origin' : origin
'parent' : parent
} = json
new types.TextInsert content, uid, prev, next, origin, parent
class types.Array extends types.ListManager
type: "Array"
applyDelete: ()->
o = @end
while o?
o.applyDelete()
o = o.prev_cl
super()
cleanup: ()->
super()
toJson: (transform_to_value = false)->
val = @val()
for i, o in val
if o instanceof types.Object
o.toJson(transform_to_value)
else if o instanceof types.Array
o.toJson(transform_to_value)
else if transform_to_value and o instanceof types.Operation
o.val()
else
o
val: (pos)->
if pos?
o = @getOperationByPosition(pos+1)
if not (o instanceof types.Delimiter)
o.val()
else
throw new Error "this position does not exist"
else
o = @beginning.next_cl
result = []
while o isnt @end
if not o.isDeleted()
result.push o.val()
o = o.next_cl
result
push: (content)->
@insertAfter @end.prev_cl, content
insertAfter: (left, content, options)->
createContent = (content, options)->
if content? and content.constructor?
type = types[content.constructor.name]
if type? and type.create?
type.create content, options
else
throw new Error "The #{content.constructor.name}-type is not (yet) supported in Y."
else
content
right = left.next_cl
while right.isDeleted()
right = right.next_cl # find the first character to the right, that is not deleted. In the case that position is 0, its the Delimiter.
left = right.prev_cl
if content instanceof types.Operation
(new types.TextInsert content, undefined, left, right).execute()
else
for c in content
tmp = (new types.TextInsert createContent(c, options), undefined, left, right).execute()
left = tmp
@
#
# Inserts a string into the word.
#
# @return {Array Type} This String object.
#
insert: (position, content, options)->
ith = @getOperationByPosition position
# the (i-1)th character. e.g. "abc" the 1th character is "a"
# the 0th character is the left Delimiter
@insertAfter ith, [content], options
#
# Deletes a part of the word.
#
# @return {Array Type} This String object
#
delete: (position, length)->
o = @getOperationByPosition(position+1) # position 0 in this case is the deletion of the first character
delete_ops = []
for i in [0...length]
if o instanceof types.Delimiter
break
d = (new types.Delete undefined, o).execute()
o = o.next_cl
while (not (o instanceof types.Delimiter)) and o.isDeleted()
o = o.next_cl
delete_ops.push d._encode()
@
#
# @private
# Encode this operation in such a way that it can be parsed by remote peers.
#
_encode: ()->
json = {
'type': @type
'uid' : @getUid()
}
json
types.Array.parse = (json)->
{
'uid' : uid
} = json
new this(uid)
types.Array.create = (content, mutable)->
if (mutable is "mutable")
list = new types.Array().execute()
ith = list.getOperationByPosition 0
list.insertAfter ith, content
list
else if (not mutable?) or (mutable is "immutable")
content
else
throw new Error "Specify either \"mutable\" or \"immutable\"!!"
#
# Handles a String-like data structures with support for insert/delete at a word-position.
# @note Currently, only Text is supported!
#
class types.String extends types.Array
#
# @private
# @param {Object} uid A unique identifier. If uid is undefined, a new uid will be created.
#
constructor: (uid)->
@textfields = []
super uid
#
# Identifies this class.
# Use it to check whether this is a word-type or something else.
#
# @example
# var x = y.val('unknown')
# if (x.type === "String") {
# console.log JSON.stringify(x.toJson())
# }
#
type: "String"
#
# Get the String-representation of this word.
# @return {String} The String-representation of this object.
#
val: ()->
c = for o in @toArray()
if o.val?
o.val()
else
""
c.join('')
#
# Same as String.val
# @see String.val
#
toString: ()->
@val()
#
# Inserts a string into the word.
#
# @return {Array Type} This String object.
#
insert: (position, content, options)->
ith = @getOperationByPosition position
# the (i-1)th character. e.g. "abc" the 1th character is "a"
# the 0th character is the left Delimiter
@insertAfter ith, content, options
#
# Bind this String to a textfield or input field.
#
# @example
# var textbox = document.getElementById("textfield");
# y.bind(textbox);
#
bind: (textfield, dom_root)->
dom_root ?= window
if (not dom_root.getSelection?)
dom_root = window
# don't duplicate!
for t in @textfields
if t is textfield
return
creator_token = false;
word = @
textfield.value = @val()
@textfields.push textfield
if textfield.selectionStart? and textfield.setSelectionRange?
createRange = (fix)->
left = textfield.selectionStart
right = textfield.selectionEnd
if fix?
left = fix left
right = fix right
{
left: left
right: right
}
writeRange = (range)->
writeContent word.val()
textfield.setSelectionRange range.left, range.right
writeContent = (content)->
textfield.value = content
else
createRange = (fix)->
range = {}
s = dom_root.getSelection()
clength = textfield.textContent.length
range.left = Math.min s.anchorOffset, clength
range.right = Math.min s.focusOffset, clength
if fix?
range.left = fix range.left
range.right = fix range.right
edited_element = s.focusNode
if edited_element is textfield or edited_element is textfield.childNodes[0]
range.isReal = true
else
range.isReal = false
range
writeRange = (range)->
writeContent word.val()
textnode = textfield.childNodes[0]
if range.isReal and textnode?
if range.left < 0
range.left = 0
range.right = Math.max range.left, range.right
if range.right > textnode.length
range.right = textnode.length
range.left = Math.min range.left, range.right
r = document.createRange()
r.setStart(textnode, range.left)
r.setEnd(textnode, range.right)
s = window.getSelection()
s.removeAllRanges()
s.addRange(r)
writeContent = (content)->
append = ""
if content[content.length - 1] is " "
content = content.slice(0,content.length-1)
append = '&nbsp;'
textfield.textContent = content
textfield.innerHTML += append
writeContent this.val()
@observe (events)->
for event in events
if not creator_token
if event.type is "insert"
o_pos = event.position
fix = (cursor)->
if cursor <= o_pos
cursor
else
cursor += 1
cursor
r = createRange fix
writeRange r
else if event.type is "delete"
o_pos = event.position
fix = (cursor)->
if cursor < o_pos
cursor
else
cursor -= 1
cursor
r = createRange fix
writeRange r
# consume all text-insert changes.
textfield.onkeypress = (event)->
if word.is_deleted
# if word is deleted, do not do anything ever again
textfield.onkeypress = null
return true
creator_token = true
char = null
if event.key?
if event.charCode is 32
char = " "
else if event.keyCode is 13
char = '\n'
else
char = event.key
else
char = window.String.fromCharCode event.keyCode
if char.length > 1
return true
else if char.length > 0
r = createRange()
pos = Math.min r.left, r.right
diff = Math.abs(r.right - r.left)
word.delete pos, diff
word.insert pos, char
r.left = pos + char.length
r.right = r.left
writeRange r
event.preventDefault()
creator_token = false
false
textfield.onpaste = (event)->
if word.is_deleted
# if word is deleted, do not do anything ever again
textfield.onpaste = null
return true
event.preventDefault()
textfield.oncut = (event)->
if word.is_deleted
# if word is deleted, do not do anything ever again
textfield.oncut = null
return true
event.preventDefault()
#
# consume deletes. Note that
# chrome: won't consume deletions on keypress event.
# keyCode is deprecated. BUT: I don't see another way.
# since event.key is not implemented in the current version of chrome.
# Every browser supports keyCode. Let's stick with it for now..
#
textfield.onkeydown = (event)->
creator_token = true
if word.is_deleted
# if word is deleted, do not do anything ever again
textfield.onkeydown = null
return true
r = createRange()
pos = Math.min(r.left, r.right, word.val().length)
diff = Math.abs(r.left - r.right)
if event.keyCode? and event.keyCode is 8 # Backspace
if diff > 0
word.delete pos, diff
r.left = pos
r.right = pos
writeRange r
else
if event.ctrlKey? and event.ctrlKey
val = word.val()
new_pos = pos
del_length = 0
if pos > 0
new_pos--
del_length++
while new_pos > 0 and val[new_pos] isnt " " and val[new_pos] isnt '\n'
new_pos--
del_length++
word.delete new_pos, (pos-new_pos)
r.left = new_pos
r.right = new_pos
writeRange r
else
if pos > 0
word.delete (pos-1), 1
r.left = pos-1
r.right = pos-1
writeRange r
event.preventDefault()
creator_token = false
return false
else if event.keyCode? and event.keyCode is 46 # Delete
if diff > 0
word.delete pos, diff
r.left = pos
r.right = pos
writeRange r
else
word.delete pos, 1
r.left = pos
r.right = pos
writeRange r
event.preventDefault()
creator_token = false
return false
else
creator_token = false
true
#
# @private
# Encode this operation in such a way that it can be parsed by remote peers.
#
_encode: ()->
json = {
'type': @type
'uid' : @getUid()
}
json
types.String.parse = (json)->
{
'uid' : uid
} = json
new this(uid)
types.String.create = (content, mutable)->
if (mutable is "mutable")
word = new types.String().execute()
word.insert 0, content
word
else if (not mutable?) or (mutable is "immutable")
content
else
throw new Error "Specify either \"mutable\" or \"immutable\"!!"
structured_types

View File

@@ -1,367 +0,0 @@
###
json_types_uninitialized = require "./JsonTypes"
# some dom implementations may call another dom.method that simulates the behavior of another.
# For example xml.insertChild(dom) , wich inserts an element at the end, and xml.insertAfter(dom,null) wich does the same
# But Y's proxy may be called only once!
proxy_token = false
dont_proxy = (f)->
proxy_token = true
try
f()
catch e
proxy_token = false
throw new Error e
proxy_token = false
_proxy = (f_name, f)->
old_f = @[f_name]
if old_f?
@[f_name] = ()->
if not proxy_token and not @_y?.isDeleted()
that = this
args = arguments
dont_proxy ()->
f.apply that, args
old_f.apply that, args
else
old_f.apply this, arguments
#else
# @[f_name] = f
Element?.prototype._proxy = _proxy
module.exports = (HB)->
json_types = json_types_uninitialized HB
types = json_types.types
parser = json_types.parser
#
# Manages XML types
# Not supported:
# * Attribute nodes
# * Real replace of child elements (to much overhead). Currently, the new element is inserted after the 'replaced' element, and then it is deleted.
# * Namespaces (*NS)
# * Browser specific methods (webkit-* operations)
class XmlType extends types.Insert
constructor: (uid, @tagname, attributes, elements, @xml)->
### In case you make this instanceof Insert again
if prev? and (not next?) and prev.type?
# adjust what you actually mean. you want to insert after prev, then
# next is not defined. but we only insert after non-deleted elements.
# This is also handled in TextInsert.
while prev.isDeleted()
prev = prev.prev_cl
next = prev.next_cl
###
super(uid)
if @xml?._y?
d = new types.Delete undefined, @xml._y
HB.addOperation(d).execute()
@xml._y = null
if attributes? and elements?
@saveOperation 'attributes', attributes
@saveOperation 'elements', elements
else if (not attributes?) and (not elements?)
@attributes = new types.JsonType()
@attributes.setMutableDefault 'immutable'
HB.addOperation(@attributes).execute()
@elements = new types.WordType()
@elements.parent = @
HB.addOperation(@elements).execute()
else
throw new Error "Either define attribute and elements both, or none of them"
if @xml?
@tagname = @xml.tagName
for i in [0...@xml.attributes.length]
attr = xml.attributes[i]
@attributes.val(attr.name, attr.value)
for n in @xml.childNodes
if n.nodeType is n.TEXT_NODE
word = new TextNodeType(undefined, n)
HB.addOperation(word).execute()
@elements.push word
else if n.nodeType is n.ELEMENT_NODE
element = new XmlType undefined, undefined, undefined, undefined, n
HB.addOperation(element).execute()
@elements.push element
else
throw new Error "I don't know Node-type #{n.nodeType}!!"
@setXmlProxy()
undefined
#
# Identifies this class.
# Use it in order to check whether this is an xml-type or something else.
#
type: "XmlType"
applyDelete: (op)->
if @insert_parent? and not @insert_parent.isDeleted()
@insert_parent.applyDelete op
else
@attributes.applyDelete()
@elements.applyDelete()
super
cleanup: ()->
super()
setXmlProxy: ()->
@xml._y = @
that = @
@elements.on 'insert', (event, op)->
if op.creator isnt HB.getUserId() and this is that.elements
newNode = op.content.val()
right = op.next_cl
while right? and right.isDeleted()
right = right.next_cl
rightNode = null
if right.type isnt 'Delimiter'
rightNode = right.val().val()
dont_proxy ()->
that.xml.insertBefore newNode, rightNode
@elements.on 'delete', (event, op)->
del_op = op.deleted_by[0]
if del_op? and del_op.creator isnt HB.getUserId() and this is that.elements
deleted = op.content.val()
dont_proxy ()->
that.xml.removeChild deleted
@attributes.on ['add', 'update'], (event, property_name, op)->
if op.creator isnt HB.getUserId() and this is that.attributes
dont_proxy ()->
newval = op.val().val()
if newval?
that.xml.setAttribute(property_name, op.val().val())
else
that.xml.removeAttribute(property_name)
## Here are all methods that proxy the behavior of the xml
# you want to find a specific child element. Since they are carried by an Insert-Type, you want to find that Insert-Operation.
# @param child {DomElement} Dom element.
# @return {InsertType} This carries the XmlType that represents the DomElement (child). false if i couldn't find it.
#
findNode = (child)->
if not child?
throw new Error "you must specify a parameter!"
child = child._y
elem = that.elements.beginning.next_cl
while elem.type isnt 'Delimiter' and elem.content isnt child
elem = elem.next_cl
if elem.type is 'Delimiter'
false
else
elem
insertBefore = (insertedNode_s, adjacentNode)->
next = null
if adjacentNode?
next = findNode adjacentNode
prev = null
if next
prev = next.prev_cl
else
prev = @_y.elements.end.prev_cl
while prev.isDeleted()
prev = prev.prev_cl
inserted_nodes = null
if insertedNode_s.nodeType is insertedNode_s.DOCUMENT_FRAGMENT_NODE
child = insertedNode_s.lastChild
while child?
element = new XmlType undefined, undefined, undefined, undefined, child
HB.addOperation(element).execute()
that.elements.insertAfter prev, element
child = child.previousSibling
else
element = new XmlType undefined, undefined, undefined, undefined, insertedNode_s
HB.addOperation(element).execute()
that.elements.insertAfter prev, element
@xml._proxy 'insertBefore', insertBefore
@xml._proxy 'appendChild', insertBefore
@xml._proxy 'removeAttribute', (name)->
that.attributes.val(name, undefined)
@xml._proxy 'setAttribute', (name, value)->
that.attributes.val name, value
renewClassList = (newclass)->
dont_do_it = false
if newclass?
for elem in this
if newclass is elem
dont_do_it = true
value = Array.prototype.join.call this, " "
if newclass? and not dont_do_it
value += " "+newclass
that.attributes.val('class', value )
_proxy.call @xml.classList, 'add', renewClassList
_proxy.call @xml.classList, 'remove', renewClassList
@xml.__defineSetter__ 'className', (val)->
@setAttribute('class', val)
@xml.__defineGetter__ 'className', ()->
that.attributes.val('class')
@xml.__defineSetter__ 'textContent', (val)->
# remove all nodes
elem = that.xml.firstChild
while elem?
remove = elem
elem = elem.nextSibling
that.xml.removeChild remove
# insert word content
if val isnt ""
text_node = document.createTextNode val
that.xml.appendChild text_node
removeChild = (node)->
elem = findNode node
if not elem
throw new Error "You are only allowed to delete existing (direct) child elements!"
d = new types.Delete undefined, elem
HB.addOperation(d).execute()
node._y = null
@xml._proxy 'removeChild', removeChild
@xml._proxy 'replaceChild', (insertedNode, replacedNode)->
insertBefore.call this, insertedNode, replacedNode
removeChild.call this, replacedNode
val: (enforce = false)->
if document?
if (not @xml?) or enforce
@xml = document.createElement @tagname
attr = @attributes.val()
for attr_name, value of attr
if value?
a = document.createAttribute attr_name
a.value = value
@xml.setAttributeNode a
e = @elements.beginning.next_cl
while e.type isnt "Delimiter"
n = e.content
if not e.isDeleted() and e.content? # TODO: how can this happen? Probably because listeners
if n.type is "XmlType"
@xml.appendChild n.val(enforce)
else if n.type is "TextNodeType"
text_node = n.val()
@xml.appendChild text_node
else
throw new Error "Internal structure cannot be transformed to dom"
e = e.next_cl
@setXmlProxy()
@xml
execute: ()->
super()
###
if not @validateSavedOperations()
return false
else
return true
###
#
# Get the parent of this JsonType.
# @return {XmlType}
#
getParent: ()->
@parent
#
# @private
#
# Convert all relevant information of this operation to the json-format.
# This result can be send to other clients.
#
_encode: ()->
json =
{
'type' : @type
'attributes' : @attributes.getUid()
'elements' : @elements.getUid()
'tagname' : @tagname
'uid' : @getUid()
}
json
parser['XmlType'] = (json)->
{
'uid' : uid
'attributes' : attributes
'elements' : elements
'tagname' : tagname
} = json
new XmlType uid, tagname, attributes, elements, undefined
#
# @nodoc
# Defines an object that is cannot be changed. You can use this to set an immutable string, or a number.
#
class TextNodeType extends types.ImmutableObject
#
# @param {Object} uid A unique identifier. If uid is undefined, a new uid will be created.
# @param {Object} content
#
constructor: (uid, content)->
if content._y?
d = new types.Delete undefined, content._y
HB.addOperation(d).execute()
content._y = null
content._y = @
super uid, content
applyDelete: (op)->
if @insert_parent? and not @insert_parent.isDeleted()
@insert_parent.applyDelete op
else
super
type: "TextNodeType"
#
# Encode this operation in such a way that it can be parsed by remote peers.
#
_encode: ()->
json = {
'type': @type
'uid' : @getUid()
'content' : @content.textContent
}
json
parser['TextNodeType'] = (json)->
{
'uid' : uid
'content' : content
} = json
textnode = document.createTextNode content
new TextNodeType uid, textnode
types['XmlType'] = XmlType
json_types
###

7
lib/binary.js Normal file
View File

@@ -0,0 +1,7 @@
export const BITS32 = 0xFFFFFFFF
export const BITS21 = (1 << 21) - 1
export const BITS16 = (1 << 16) - 1
export const BIT26 = 1 << 26
export const BIT32 = 1 << 32

168
lib/decoding.js Normal file
View File

@@ -0,0 +1,168 @@
/* global Buffer */
import * as globals from './globals.js'
/**
* A Decoder handles the decoding of an ArrayBuffer.
*/
export class Decoder {
/**
* @param {ArrayBuffer} buffer Binary data to decode
*/
constructor (buffer) {
this.arr = new Uint8Array(buffer)
this.pos = 0
}
}
/**
* @param {ArrayBuffer} buffer
* @return {Decoder}
*/
export const createDecoder = buffer => new Decoder(buffer)
export const hasContent = decoder => decoder.pos !== decoder.arr.length
/**
* Clone a decoder instance.
* Optionally set a new position parameter.
* @param {Decoder} decoder The decoder instance
* @return {Decoder} A clone of `decoder`
*/
export const clone = (decoder, newPos = decoder.pos) => {
let _decoder = createDecoder(decoder.arr.buffer)
_decoder.pos = newPos
return _decoder
}
/**
* Read `len` bytes as an ArrayBuffer.
* @param {Decoder} decoder The decoder instance
* @param {number} len The length of bytes to read
* @return {ArrayBuffer}
*/
export const readArrayBuffer = (decoder, len) => {
const arrayBuffer = globals.createUint8ArrayFromLen(len)
const view = globals.createUint8ArrayFromBuffer(decoder.arr.buffer, decoder.pos, len)
arrayBuffer.set(view)
decoder.pos += len
return arrayBuffer.buffer
}
/**
* Read variable length payload as ArrayBuffer
* @param {Decoder} decoder
* @return {ArrayBuffer}
*/
export const readPayload = decoder => readArrayBuffer(decoder, readVarUint(decoder))
/**
* Read the rest of the content as an ArrayBuffer
* @param {Decoder} decoder
* @return {ArrayBuffer}
*/
export const readTail = decoder => readArrayBuffer(decoder, decoder.arr.length - decoder.pos)
/**
* Skip one byte, jump to the next position.
* @param {Decoder} decoder The decoder instance
* @return {number} The next position
*/
export const skip8 = decoder => decoder.pos++
/**
* Read one byte as unsigned integer.
* @param {Decoder} decoder The decoder instance
* @return {number} Unsigned 8-bit integer
*/
export const readUint8 = decoder => decoder.arr[decoder.pos++]
/**
* Read 4 bytes as unsigned integer.
*
* @param {Decoder} decoder
* @return {number} An unsigned integer.
*/
export const readUint32 = decoder => {
let uint =
decoder.arr[decoder.pos] +
(decoder.arr[decoder.pos + 1] << 8) +
(decoder.arr[decoder.pos + 2] << 16) +
(decoder.arr[decoder.pos + 3] << 24)
decoder.pos += 4
return uint
}
/**
* Look ahead without incrementing position.
* to the next byte and read it as unsigned integer.
*
* @param {Decoder} decoder
* @return {number} An unsigned integer.
*/
export const peekUint8 = decoder => decoder.arr[decoder.pos]
/**
* Read unsigned integer (32bit) with variable length.
* 1/8th of the storage is used as encoding overhead.
* * numbers < 2^7 is stored in one bytlength
* * numbers < 2^14 is stored in two bylength
*
* @param {Decoder} decoder
* @return {number} An unsigned integer.length
*/
export const readVarUint = decoder => {
let num = 0
let len = 0
while (true) {
let r = decoder.arr[decoder.pos++]
num = num | ((r & 0b1111111) << len)
len += 7
if (r < 1 << 7) {
return num >>> 0 // return unsigned number!
}
if (len > 35) {
throw new Error('Integer out of range!')
}
}
}
/**
* Read string of variable length
* * varUint is used to store the length of the string
*
* Transforming utf8 to a string is pretty expensive. The code performs 10x better
* when String.fromCodePoint is fed with all characters as arguments.
* But most environments have a maximum number of arguments per functions.
* For effiency reasons we apply a maximum of 10000 characters at once.
*
* @param {Decoder} decoder
* @return {String} The read String.
*/
export const readVarString = decoder => {
let remainingLen = readVarUint(decoder)
let encodedString = ''
while (remainingLen > 0) {
const nextLen = remainingLen < 10000 ? remainingLen : 10000
const bytes = new Array(nextLen)
for (let i = 0; i < nextLen; i++) {
bytes[i] = decoder.arr[decoder.pos++]
}
encodedString += String.fromCodePoint.apply(null, bytes)
remainingLen -= nextLen
}
return decodeURIComponent(escape(encodedString))
}
/**
* Look ahead and read varString without incrementing position
* @param {Decoder} decoder
* @return {string}
*/
export const peekVarString = decoder => {
let pos = decoder.pos
let s = readVarString(decoder)
decoder.pos = pos
return s
}

218
lib/encoding.js Normal file
View File

@@ -0,0 +1,218 @@
import * as globals from './globals.js'
const bits7 = 0b1111111
const bits8 = 0b11111111
/**
* A BinaryEncoder handles the encoding to an ArrayBuffer.
*/
export class Encoder {
constructor () {
this.cpos = 0
this.cbuf = globals.createUint8ArrayFromLen(1000)
this.bufs = []
}
}
export const createEncoder = () => new Encoder()
/**
* The current length of the encoded data.
*/
export const length = encoder => {
let len = encoder.cpos
for (let i = 0; i < encoder.bufs.length; i++) {
len += encoder.bufs[i].length
}
return len
}
/**
* Transform to ArrayBuffer. TODO: rename to .toArrayBuffer
* @param {Encoder} encoder
* @return {ArrayBuffer} The created ArrayBuffer.
*/
export const toBuffer = encoder => {
const uint8arr = globals.createUint8ArrayFromLen(length(encoder))
let curPos = 0
for (let i = 0; i < encoder.bufs.length; i++) {
let d = encoder.bufs[i]
uint8arr.set(d, curPos)
curPos += d.length
}
uint8arr.set(globals.createUint8ArrayFromBuffer(encoder.cbuf.buffer, 0, encoder.cpos), curPos)
return uint8arr.buffer
}
/**
* Write one byte to the encoder.
*
* @param {Encoder} encoder
* @param {number} num The byte that is to be encoded.
*/
export const write = (encoder, num) => {
if (encoder.cpos === encoder.cbuf.length) {
encoder.bufs.push(encoder.cbuf)
encoder.cbuf = globals.createUint8ArrayFromLen(encoder.cbuf.length * 2)
encoder.cpos = 0
}
encoder.cbuf[encoder.cpos++] = num
}
/**
* Write one byte at a specific position.
* Position must already be written (i.e. encoder.length > pos)
*
* @param {Encoder} encoder
* @param {number} pos Position to which to write data
* @param {number} num Unsigned 8-bit integer
*/
export const set = (encoder, pos, num) => {
let buffer = null
// iterate all buffers and adjust position
for (let i = 0; i < encoder.bufs.length && buffer === null; i++) {
const b = encoder.bufs[i]
if (pos < b.length) {
buffer = b // found buffer
} else {
pos -= b.length
}
}
if (buffer === null) {
// use current buffer
buffer = encoder.cbuf
}
buffer[pos] = num
}
/**
* Write one byte as an unsigned integer.
*
* @param {Encoder} encoder
* @param {number} num The number that is to be encoded.
*/
export const writeUint8 = (encoder, num) => write(encoder, num & bits8)
/**
* Write one byte as an unsigned Integer at a specific location.
*
* @param {Encoder} encoder
* @param {number} pos The location where the data will be written.
* @param {number} num The number that is to be encoded.
*/
export const setUint8 = (encoder, pos, num) => set(encoder, pos, num & bits8)
/**
* Write two bytes as an unsigned integer.
*
* @param {Encoder} encoder
* @param {number} num The number that is to be encoded.
*/
export const writeUint16 = (encoder, num) => {
write(encoder, num & bits8)
write(encoder, (num >>> 8) & bits8)
}
/**
* Write two bytes as an unsigned integer at a specific location.
*
* @param {Encoder} encoder
* @param {number} pos The location where the data will be written.
* @param {number} num The number that is to be encoded.
*/
export const setUint16 = (encoder, pos, num) => {
set(encoder, pos, num & bits8)
set(encoder, pos + 1, (num >>> 8) & bits8)
}
/**
* Write two bytes as an unsigned integer
*
* @param {Encoder} encoder
* @param {number} num The number that is to be encoded.
*/
export const writeUint32 = (encoder, num) => {
for (let i = 0; i < 4; i++) {
write(encoder, num & bits8)
num >>>= 8
}
}
/**
* Write two bytes as an unsigned integer at a specific location.
*
* @param {Encoder} encoder
* @param {number} pos The location where the data will be written.
* @param {number} num The number that is to be encoded.
*/
export const setUint32 = (encoder, pos, num) => {
for (let i = 0; i < 4; i++) {
set(encoder, pos + i, num & bits8)
num >>>= 8
}
}
/**
* Write a variable length unsigned integer.
*
* Encodes integers in the range from [0, 4294967295] / [0, 0xffffffff]. (max 32 bit unsigned integer)
*
* @param {Encoder} encoder
* @param {number} num The number that is to be encoded.
*/
export const writeVarUint = (encoder, num) => {
while (num >= 0b10000000) {
write(encoder, 0b10000000 | (bits7 & num))
num >>>= 7
}
write(encoder, bits7 & num)
}
/**
* Write a variable length string.
*
* @param {Encoder} encoder
* @param {String} str The string that is to be encoded.
*/
export const writeVarString = (encoder, str) => {
const encodedString = unescape(encodeURIComponent(str))
const len = encodedString.length
writeVarUint(encoder, len)
for (let i = 0; i < len; i++) {
write(encoder, encodedString.codePointAt(i))
}
}
/**
* Write the content of another Encoder.
*
* TODO: can be improved!
*
* @param {Encoder} encoder The enUint8Arr
* @param {Encoder} append The BinaryEncoder to be written.
*/
export const writeBinaryEncoder = (encoder, append) => writeArrayBuffer(encoder, toBuffer(append))
/**
* Append an arrayBuffer to the encoder.
*
* @param {Encoder} encoder
* @param {ArrayBuffer} arrayBuffer
*/
export const writeArrayBuffer = (encoder, arrayBuffer) => {
const prevBufferLen = encoder.cbuf.length
// TODO: Append to cbuf if possible
encoder.bufs.push(globals.createUint8ArrayFromBuffer(encoder.cbuf.buffer, 0, encoder.cpos))
encoder.bufs.push(globals.createUint8ArrayFromArrayBuffer(arrayBuffer))
encoder.cbuf = globals.createUint8ArrayFromLen(prevBufferLen)
encoder.cpos = 0
}
/**
* @param {Encoder} encoder
* @param {ArrayBuffer} arrayBuffer
*/
export const writePayload = (encoder, arrayBuffer) => {
writeVarUint(encoder, arrayBuffer.byteLength)
writeArrayBuffer(encoder, arrayBuffer)
}

49
lib/encoding.test.js Normal file
View File

@@ -0,0 +1,49 @@
import * as encoding from './encoding.js'
/**
* Check if binary encoding is compatible with golang binary encoding - binary.PutVarUint.
*
* Result: is compatible up to 32 bit: [0, 4294967295] / [0, 0xffffffff]. (max 32 bit unsigned integer)
*/
let err = null
try {
const tests = [
{ in: 0, out: [0] },
{ in: 1, out: [1] },
{ in: 128, out: [128, 1] },
{ in: 200, out: [200, 1] },
{ in: 32, out: [32] },
{ in: 500, out: [244, 3] },
{ in: 256, out: [128, 2] },
{ in: 700, out: [188, 5] },
{ in: 1024, out: [128, 8] },
{ in: 1025, out: [129, 8] },
{ in: 4048, out: [208, 31] },
{ in: 5050, out: [186, 39] },
{ in: 1000000, out: [192, 132, 61] },
{ in: 34951959, out: [151, 166, 213, 16] },
{ in: 2147483646, out: [254, 255, 255, 255, 7] },
{ in: 2147483647, out: [255, 255, 255, 255, 7] },
{ in: 2147483648, out: [128, 128, 128, 128, 8] },
{ in: 2147483700, out: [180, 128, 128, 128, 8] },
{ in: 4294967294, out: [254, 255, 255, 255, 15] },
{ in: 4294967295, out: [255, 255, 255, 255, 15] }
]
tests.forEach(test => {
const encoder = encoding.createEncoder()
encoding.writeVarUint(encoder, test.in)
const buffer = new Uint8Array(encoding.toBuffer(encoder))
if (buffer.byteLength !== test.out.length) {
throw new Error('Length don\'t match!')
}
for (let j = 0; j < buffer.length; j++) {
if (buffer[j] !== test[1][j]) {
throw new Error('values don\'t match!')
}
}
})
} catch (error) {
err = error
} finally {
console.log('YDB Client: Encoding varUint compatiblity test: ', err || 'success!')
}

63
lib/globals.js Normal file
View File

@@ -0,0 +1,63 @@
/* eslint-env browser */
export const Uint8Array_ = Uint8Array
/**
* @param {Array<number>} arr
* @return {ArrayBuffer}
*/
export const createArrayBufferFromArray = arr => new Uint8Array_(arr).buffer
export const createUint8ArrayFromLen = len => new Uint8Array_(len)
/**
* Create Uint8Array with initial content from buffer
*/
export const createUint8ArrayFromBuffer = (buffer, byteOffset, length) => new Uint8Array_(buffer, byteOffset, length)
/**
* Create Uint8Array with initial content from buffer
*/
export const createUint8ArrayFromArrayBuffer = arraybuffer => new Uint8Array_(arraybuffer)
export const createArrayFromArrayBuffer = arraybuffer => Array.from(createUint8ArrayFromArrayBuffer(arraybuffer))
export const createPromise = f => new Promise(f)
export const createMap = () => new Map()
export const createSet = () => new Set()
/**
* `Promise.all` wait for all promises in the array to resolve and return the result
* @param {Array<Promise<any>>} arrp
* @return {any}
*/
export const pall = arrp => Promise.all(arrp)
export const preject = reason => Promise.reject(reason)
export const presolve = res => Promise.resolve(res)
export const until = (timeout, check) => createPromise((resolve, reject) => {
const hasTimeout = timeout > 0
const untilInterval = () => {
if (check()) {
clearInterval(intervalHandle)
resolve()
} else if (hasTimeout) {
timeout -= 10
if (timeout < 0) {
clearInterval(intervalHandle)
reject(error('Timeout'))
}
}
}
const intervalHandle = setInterval(untilInterval, 10)
})
export const error = description => new Error(description)
export const max = (a, b) => a > b ? a : b
/**
* @param {number} t Time to wait
* @return {Promise} Promise that is resolved after t ms
*/
export const wait = t => createPromise(r => setTimeout(r, t))

159
lib/idb.js Normal file
View File

@@ -0,0 +1,159 @@
/* eslint-env browser */
import * as globals from './globals.js'
/*
* IDB Request to Promise transformer
*/
export const rtop = request => globals.createPromise((resolve, reject) => {
request.onerror = event => reject(new Error(event.target.error))
request.onblocked = () => location.reload()
request.onsuccess = event => resolve(event.target.result)
})
/**
* @return {Promise<IDBDatabase>}
*/
export const openDB = (name, initDB) => globals.createPromise((resolve, reject) => {
let request = indexedDB.open(name)
/**
* @param {any} event
*/
request.onupgradeneeded = event => initDB(event.target.result)
/**
* @param {any} event
*/
request.onerror = event => reject(new Error(event.target.error))
request.onblocked = () => location.reload()
/**
* @param {any} event
*/
request.onsuccess = event => {
const db = event.target.result
db.onversionchange = () => { db.close() }
addEventListener('unload', () => db.close())
resolve(db)
}
})
export const deleteDB = name => rtop(indexedDB.deleteDatabase(name))
export const createStores = (db, definitions) => definitions.forEach(d =>
db.createObjectStore.apply(db, d)
)
/**
* @param {IDBObjectStore} store
* @param {String | number | ArrayBuffer | Date | Array } key
* @return {Promise<ArrayBuffer>}
*/
export const get = (store, key) =>
rtop(store.get(key))
/**
* @param {IDBObjectStore} store
* @param {String | number | ArrayBuffer | Date | IDBKeyRange | Array } key
*/
export const del = (store, key) =>
rtop(store.delete(key))
/**
* @param {IDBObjectStore} store
* @param {String | number | ArrayBuffer | Date | boolean} item
* @param {String | number | ArrayBuffer | Date | Array} [key]
*/
export const put = (store, item, key) =>
rtop(store.put(item, key))
/**
* @param {IDBObjectStore} store
* @param {String | number | ArrayBuffer | Date | boolean} item
* @param {String | number | ArrayBuffer | Date | Array} [key]
* @return {Promise<ArrayBuffer>}
*/
export const add = (store, item, key) =>
rtop(store.add(item, key))
/**
* @param {IDBObjectStore} store
* @param {String | number | ArrayBuffer | Date} item
* @return {Promise<number>}
*/
export const addAutoKey = (store, item) =>
rtop(store.add(item))
/**
* @param {IDBObjectStore} store
* @param {IDBKeyRange} [range]
*/
export const getAll = (store, range) =>
rtop(store.getAll(range))
/**
* @param {IDBObjectStore} store
* @param {IDBKeyRange} [range]
*/
export const getAllKeys = (store, range) =>
rtop(store.getAllKeys(range))
/**
* @typedef KeyValuePair
* @type {Object}
* @property {any} k key
* @property {any} v Value
*/
/**
* @param {IDBObjectStore} store
* @param {IDBKeyRange} [range]
* @return {Promise<Array<KeyValuePair>>}
*/
export const getAllKeysValues = (store, range) =>
globals.pall([getAllKeys(store, range), getAll(store, range)]).then(([ks, vs]) => ks.map((k, i) => ({ k, v: vs[i] })))
/**
* Iterate on keys and values
* @param {IDBObjectStore} store
* @param {IDBKeyRange?} keyrange
* @param {function(any, any)} f Return true in order to continue the cursor
*/
export const iterate = (store, keyrange, f) => globals.createPromise((resolve, reject) => {
const request = store.openCursor(keyrange)
request.onerror = reject
/**
* @param {any} event
*/
request.onsuccess = event => {
const cursor = event.target.result
if (cursor === null) {
return resolve()
}
f(cursor.value, cursor.key)
cursor.continue()
}
})
/**
* Iterate on the keys (no values)
* @param {IDBObjectStore} store
* @param {IDBKeyRange} keyrange
* @param {function(IDBCursor)} f Call `idbcursor.continue()` to iterate further
*/
export const iterateKeys = (store, keyrange, f) => {
/**
* @param {any} event
*/
store.openKeyCursor(keyrange).onsuccess = event => f(event.target.result)
}
/**
* Open store from transaction
* @param {IDBTransaction} t
* @param {String} store
* @returns {IDBObjectStore}
*/
export const getStore = (t, store) => t.objectStore(store)
export const createIDBKeyRangeBound = (lower, upper, lowerOpen, upperOpen) => IDBKeyRange.bound(lower, upper, lowerOpen, upperOpen)
export const createIDBKeyRangeUpperBound = (upper, upperOpen) => IDBKeyRange.upperBound(upper, upperOpen)
export const createIDBKeyRangeLowerBound = (lower, lowerOpen) => IDBKeyRange.lowerBound(lower, lowerOpen)

34
lib/idb.test.js Normal file
View File

@@ -0,0 +1,34 @@
import * as test from './test.js'
import * as idb from './idb.js'
import * as logging from './logging.js'
const initTestDB = db => idb.createStores(db, [['test']])
const testDBName = 'idb-test'
const createTransaction = db => db.transaction(['test'], 'readwrite')
/**
* @param {IDBTransaction} t
* @return {IDBObjectStore}
*/
const getStore = t => idb.getStore(t, 'test')
idb.deleteDB(testDBName).then(() => idb.openDB(testDBName, initTestDB)).then(db => {
test.run('idb iteration', async testname => {
const t = createTransaction(db)
await idb.put(getStore(t), 0, ['t', 0])
await idb.put(getStore(t), 1, ['t', 1])
const valsGetAll = await idb.getAll(getStore(t))
if (valsGetAll.length !== 2) {
logging.fail('getAll does not return two values')
}
const valsIterate = []
const keyrange = idb.createIDBKeyRangeBound(['t', 0], ['t', 1], false, false)
await idb.put(getStore(t), 2, ['t', 2])
await idb.iterate(getStore(t), keyrange, (val, key) => {
valsIterate.push(val)
})
if (valsIterate.length !== 2) {
logging.fail('iterate does not return two values')
}
})
})

23
lib/logging.js Normal file
View File

@@ -0,0 +1,23 @@
import * as globals from './globals.js'
let date = new Date().getTime()
const writeDate = () => {
const oldDate = date
date = new Date().getTime()
return date - oldDate
}
export const print = (...args) => console.log(...args)
export const log = m => print(`%cydb-client: %c${m} %c+${writeDate()}ms`, 'color: blue;', '', 'color: blue')
export const fail = m => {
throw new Error(m)
}
/**
* @param {ArrayBuffer} buffer
* @return {string}
*/
export const arrayBufferToString = buffer => JSON.stringify(Array.from(globals.createUint8ArrayFromBuffer(buffer)))

2
lib/math.js Normal file
View File

@@ -0,0 +1,2 @@
export const floor = Math.floor

32
lib/mutex.js Normal file
View File

@@ -0,0 +1,32 @@
/**
* Creates a mutual exclude function with the following property:
*
* @example
* const mutex = createMutex()
* mutex(function () {
* // This function is immediately executed
* mutex(function () {
* // This function is never executed, as it is called with the same
* // mutex function
* })
* })
*
* @return {Function} A mutual exclude function
* @public
*/
export const createMutex = () => {
let token = true
return (f, g) => {
if (token) {
token = false
try {
f()
} finally {
token = true
}
} else if (g !== undefined) {
g()
}
}
}

2
lib/number.js Normal file
View File

@@ -0,0 +1,2 @@
export const MAX_SAFE_INTEGER = Number.MAX_SAFE_INTEGER
export const MIN_SAFE_INTEGER = Number.MIN_SAFE_INTEGER

View File

@@ -0,0 +1,66 @@
const N = 624
const M = 397
function twist (u, v) {
return ((((u & 0x80000000) | (v & 0x7fffffff)) >>> 1) ^ ((v & 1) ? 0x9908b0df : 0))
}
function nextState (state) {
let p = 0
let j
for (j = N - M + 1; --j; p++) {
state[p] = state[p + M] ^ twist(state[p], state[p + 1])
}
for (j = M; --j; p++) {
state[p] = state[p + M - N] ^ twist(state[p], state[p + 1])
}
state[p] = state[p + M - N] ^ twist(state[p], state[0])
}
/**
* This is a port of Shawn Cokus's implementation of the original Mersenne Twister algorithm (http://www.math.sci.hiroshima-u.ac.jp/~m-mat/MT/MT2002/CODES/MTARCOK/mt19937ar-cok.c).
* MT has a very high period of 2^19937. Though the authors of xorshift describe that a high period is not
* very relevant (http://vigna.di.unimi.it/xorshift/). It is four times slower than xoroshiro128plus and
* needs to recompute its state after generating 624 numbers.
*
* @example
* const gen = new Mt19937(new Date().getTime())
* console.log(gen.next())
*
* @public
*/
export default class Mt19937 {
/**
* @param {Number} seed The starting point for the random number generation. If you use the same seed, the generator will return the same sequence of random numbers.
*/
constructor (seed) {
this.seed = seed
const state = new Uint32Array(N)
state[0] = seed
for (let i = 1; i < N; i++) {
state[i] = (Math.imul(1812433253, (state[i - 1] ^ (state[i - 1] >>> 30))) + i) & 0xFFFFFFFF
}
this._state = state
this._i = 0
nextState(this._state)
}
/**
* Generate a random signed integer.
*
* @return {Number} A 32 bit signed integer.
*/
next () {
if (this._i === N) {
// need to compute a new state
nextState(this._state)
this._i = 0
}
let y = this._state[this._i++]
y ^= (y >>> 11)
y ^= (y << 7) & 0x9d2c5680
y ^= (y << 15) & 0xefc60000
y ^= (y >>> 18)
return y
}
}

View File

@@ -0,0 +1,48 @@
import Mt19937 from './Mt19937.js'
import Xoroshiro128plus from './Xoroshiro128plus.js'
import Xorshift32 from './Xorshift32.js'
import * as time from '../../time.js'
const DIAMETER = 300
const NUMBERS = 10000
function runPRNG (name, Gen) {
console.log('== ' + name + ' ==')
const gen = new Gen(1234)
let head = 0
let tails = 0
const date = time.getUnixTime()
const canvas = document.createElement('canvas')
canvas.height = DIAMETER
canvas.width = DIAMETER
const ctx = canvas.getContext('2d')
const vals = new Set()
ctx.fillStyle = 'blue'
for (let i = 0; i < NUMBERS; i++) {
const n = gen.next() & 0xFFFFFF
const x = (gen.next() >>> 0) % DIAMETER
const y = (gen.next() >>> 0) % DIAMETER
ctx.fillRect(x, y, 1, 2)
if ((n & 1) === 1) {
head++
} else {
tails++
}
if (vals.has(n)) {
console.warn(`The generator generated a duplicate`)
}
vals.add(n)
}
console.log('time: ', time.getUnixTime() - date)
console.log('head:', head, 'tails:', tails)
console.log('%c ', `font-size: 200px; background: url(${canvas.toDataURL()}) no-repeat;`)
const h1 = document.createElement('h1')
h1.insertBefore(document.createTextNode(name), null)
document.body.insertBefore(h1, null)
document.body.appendChild(canvas)
}
runPRNG('mt19937', Mt19937)
runPRNG('xoroshiro128plus', Xoroshiro128plus)
runPRNG('xorshift32', Xorshift32)

View File

@@ -0,0 +1,5 @@
# Pseudo Random Number Generators (PRNG)
Given a seed a PRNG generates a sequence of numbers that cannot be reasonably predicted. Two PRNGs must generate the same random sequence of numbers if given the same seed.
TODO: explain what POINT is

View File

@@ -0,0 +1,98 @@
import Xorshift32 from './Xorshift32.js'
/**
* This is a variant of xoroshiro128plus - the fastest full-period generator passing BigCrush without systematic failures.
*
* This implementation follows the idea of the original xoroshiro128plus implementation,
* but is optimized for the JavaScript runtime. I.e.
* * The operations are performed on 32bit integers (the original implementation works with 64bit values).
* * The initial 128bit state is computed based on a 32bit seed and Xorshift32.
* * This implementation returns two 32bit values based on the 64bit value that is computed by xoroshiro128plus.
* Caution: The last addition step works slightly different than in the original implementation - the add carry of the
* first 32bit addition is not carried over to the last 32bit.
*
* [Reference implementation](http://vigna.di.unimi.it/xorshift/xoroshiro128plus.c)
*/
export default class Xoroshiro128plus {
constructor (seed) {
this.seed = seed
// This is a variant of Xoroshiro128plus to fill the initial state
const xorshift32 = new Xorshift32(seed)
this.state = new Uint32Array(4)
for (let i = 0; i < 4; i++) {
this.state[i] = xorshift32.next()
}
this._fresh = true
}
next () {
const state = this.state
if (this._fresh) {
this._fresh = false
return (state[0] + state[2]) & 0xFFFFFFFF
} else {
this._fresh = true
const s0 = state[0]
const s1 = state[1]
const s2 = state[2] ^ s0
const s3 = state[3] ^ s1
// function js_rotl (x, k) {
// k = k - 32
// const x1 = x[0]
// const x2 = x[1]
// x[0] = x2 << k | x1 >>> (32 - k)
// x[1] = x1 << k | x2 >>> (32 - k)
// }
// rotl(s0, 55) // k = 23 = 55 - 32; j = 9 = 32 - 23
state[0] = (s1 << 23 | s0 >>> 9) ^ s2 ^ (s2 << 14 | s3 >>> 18)
state[1] = (s0 << 23 | s1 >>> 9) ^ s3 ^ (s3 << 14)
// rol(s1, 36) // k = 4 = 36 - 32; j = 23 = 32 - 9
state[2] = s3 << 4 | s2 >>> 28
state[3] = s2 << 4 | s3 >>> 28
return (state[1] + state[3]) & 0xFFFFFFFF
}
}
}
/*
// reference implementation
#include <stdint.h>
#include <stdio.h>
uint64_t s[2];
static inline uint64_t rotl(const uint64_t x, int k) {
return (x << k) | (x >> (64 - k));
}
uint64_t next(void) {
const uint64_t s0 = s[0];
uint64_t s1 = s[1];
s1 ^= s0;
s[0] = rotl(s0, 55) ^ s1 ^ (s1 << 14); // a, b
s[1] = rotl(s1, 36); // c
return (s[0] + s[1]) & 0xFFFFFFFF;
}
int main(void)
{
int i;
s[0] = 1111 | (1337ul << 32);
s[1] = 1234 | (9999ul << 32);
printf("1000 outputs of genrand_int31()\n");
for (i=0; i<100; i++) {
printf("%10lu ", i);
printf("%10lu ", next());
printf("- %10lu ", s[0] >> 32);
printf("%10lu ", (s[0] << 32) >> 32);
printf("%10lu ", s[1] >> 32);
printf("%10lu ", (s[1] << 32) >> 32);
printf("\n");
// if (i%5==4) printf("\n");
}
return 0;
}
*/

View File

@@ -0,0 +1,26 @@
/**
* Xorshift32 is a very simple but elegang PRNG with a period of `2^32-1`.
*/
export default class Xorshift32 {
/**
* @param {number} seed The starting point for the random number generation. If you use the same seed, the generator will return the same sequence of random numbers.
*/
constructor (seed) {
this.seed = seed
this._state = seed
}
/**
* Generate a random signed integer.
*
* @return {Number} A 32 bit signed integer.
*/
next () {
let x = this._state
x ^= x << 13
x ^= x >> 17
x ^= x << 5
this._state = x
return x
}
}

131
lib/random/random.js Normal file
View File

@@ -0,0 +1,131 @@
import * as binary from '../binary.js'
import { fromCharCode, fromCodePoint } from '../string.js'
import { MAX_SAFE_INTEGER, MIN_SAFE_INTEGER } from '../number.js'
import * as math from '../math.js'
import DefaultPRNG from './PRNG/Xoroshiro128plus.js'
/**
* Description of the function
* @callback generatorNext
* @return {number} A 32bit integer
*/
/**
* A random type generator.
*
* @typedef {Object} PRNG
* @property {generatorNext} next Generate new number
*/
/**
* Create a Xoroshiro128plus Pseudo-Random-Number-Generator.
* This is the fastest full-period generator passing BigCrush without systematic failures.
* But there are more PRNGs available in ./PRNG/.
*
* @param {number} seed A positive 32bit integer. Do not use negative numbers.
* @return {PRNG}
*/
export const createPRNG = seed => new DefaultPRNG(Math.floor(seed < 1 ? seed * binary.BITS32 : seed))
/**
* Generates a single random bool.
*
* @param {PRNG} gen A random number generator.
* @return {Boolean} A random boolean
*/
export const bool = gen => (gen.next() & 2) === 2 // brackets are non-optional!
/**
* Generates a random integer with 53 bit resolution.
*
* @param {PRNG} gen A random number generator.
* @param {Number} [min = MIN_SAFE_INTEGER] The lower bound of the allowed return values (inclusive).
* @param {Number} [max = MAX_SAFE_INTEGER] The upper bound of the allowed return values (inclusive).
* @return {Number} A random integer on [min, max]
*/
export const int53 = (gen, min = MIN_SAFE_INTEGER, max = MAX_SAFE_INTEGER) => math.floor(real53(gen) * (max + 1 - min) + min)
/**
* Generates a random integer with 32 bit resolution.
*
* @param {PRNG} gen A random number generator.
* @param {Number} [min = MIN_SAFE_INTEGER] The lower bound of the allowed return values (inclusive).
* @param {Number} [max = MAX_SAFE_INTEGER] The upper bound of the allowed return values (inclusive).
* @return {Number} A random integer on [min, max]
*/
export const int32 = (gen, min = MIN_SAFE_INTEGER, max = MAX_SAFE_INTEGER) => min + ((gen.next() >>> 0) % (max + 1 - min))
/**
* Generates a random real on [0, 1) with 32 bit resolution.
*
* @param {PRNG} gen A random number generator.
* @return {Number} A random real number on [0, 1).
*/
export const real32 = gen => (gen.next() >>> 0) / binary.BITS32
/**
* Generates a random real on [0, 1) with 53 bit resolution.
*
* @param {PRNG} gen A random number generator.
* @return {Number} A random real number on [0, 1).
*/
export const real53 = gen => (((gen.next() >>> 5) * binary.BIT26) + (gen.next() >>> 6)) / MAX_SAFE_INTEGER
/**
* Generates a random character from char code 32 - 126. I.e. Characters, Numbers, special characters, and Space:
*
* (Space)!"#$%&'()*+,-./0123456789:;<=>?@ABCDEFGHIJKLMNOPQRSTUVWXYZ[/]^_`abcdefghijklmnopqrstuvwxyz{|}~
*/
export const char = gen => fromCharCode(int32(gen, 32, 126))
/**
* @param {PRNG} gen
* @return {string} A single letter (a-z)
*/
export const letter = gen => fromCharCode(int32(gen, 97, 122))
/**
* @param {PRNG} gen
* @return {string} A random word without spaces consisting of letters (a-z)
*/
export const word = gen => {
const len = int32(gen, 0, 20)
let str = ''
for (let i = 0; i < len; i++) {
str += letter(gen)
}
return str
}
/**
* TODO: this function produces invalid runes. Does not cover all of utf16!!
*/
export const utf16Rune = gen => {
const codepoint = int32(gen, 0, 256)
return fromCodePoint(codepoint)
}
/**
* @param {PRNG} gen
* @param {number} [maxlen = 20]
*/
export const utf16String = (gen, maxlen = 20) => {
const len = int32(gen, 0, maxlen)
let str = ''
for (let i = 0; i < len; i++) {
str += utf16Rune(gen)
}
return str
}
/**
* Returns one element of a given array.
*
* @param {PRNG} gen A random number generator.
* @param {Array<T>} array Non empty Array of possible values.
* @return {T} One of the values of the supplied Array.
* @template T
*/
export const oneOf = (gen, array) => array[int32(gen, 0, array.length - 1)]

110
lib/random/random.test.js Normal file
View File

@@ -0,0 +1,110 @@
/**
*TODO: enable tests
import * as rt from '../rich-text/formatters.mjs'
import { test } from '../test/test.mjs'
import Xoroshiro128plus from './PRNG/Xoroshiro128plus.mjs'
import Xorshift32 from './PRNG/Xorshift32.mjs'
import MT19937 from './PRNG/Mt19937.mjs'
import { generateBool, generateInt, generateInt32, generateReal, generateChar } from './random.mjs'
import { MAX_SAFE_INTEGER } from '../number/constants.mjs'
import { BIT32 } from '../binary/constants.mjs'
function init (Gen) {
return {
gen: new Gen(1234)
}
}
const PRNGs = [
{ name: 'Xoroshiro128plus', Gen: Xoroshiro128plus },
{ name: 'Xorshift32', Gen: Xorshift32 },
{ name: 'MT19937', Gen: MT19937 }
]
const ITERATONS = 1000000
for (const PRNG of PRNGs) {
const prefix = rt.orange`${PRNG.name}:`
test(rt.plain`${prefix} generateBool`, function generateBoolTest (t) {
const { gen } = init(PRNG.Gen)
let head = 0
let tail = 0
let b
let i
for (i = 0; i < ITERATONS; i++) {
b = generateBool(gen)
if (b) {
head++
} else {
tail++
}
}
t.log(`Generated ${head} heads and ${tail} tails.`)
t.assert(tail >= Math.floor(ITERATONS * 0.49), 'Generated enough tails.')
t.assert(head >= Math.floor(ITERATONS * 0.49), 'Generated enough heads.')
})
test(rt.plain`${prefix} generateInt integers average correctly`, function averageIntTest (t) {
const { gen } = init(PRNG.Gen)
let count = 0
let i
for (i = 0; i < ITERATONS; i++) {
count += generateInt(gen, 0, 100)
}
const average = count / ITERATONS
const expectedAverage = 100 / 2
t.log(`Average is: ${average}. Expected average is ${expectedAverage}.`)
t.assert(Math.abs(average - expectedAverage) <= 1, 'Expected average is at most 1 off.')
})
test(rt.plain`${prefix} generateInt32 generates integer with 32 bits`, function generateLargeIntegers (t) {
const { gen } = init(PRNG.Gen)
let num = 0
let i
let newNum
for (i = 0; i < ITERATONS; i++) {
newNum = generateInt32(gen, 0, MAX_SAFE_INTEGER)
if (newNum > num) {
num = newNum
}
}
t.log(`Largest number generated is ${num} (0b${num.toString(2)})`)
t.assert(num > (BIT32 >>> 0), 'Largest number is 32 bits long.')
})
test(rt.plain`${prefix} generateReal has 53 bit resolution`, function real53bitResolution (t) {
const { gen } = init(PRNG.Gen)
let num = 0
let i
let newNum
for (i = 0; i < ITERATONS; i++) {
newNum = generateReal(gen) * MAX_SAFE_INTEGER
if (newNum > num) {
num = newNum
}
}
t.log(`Largest number generated is ${num}.`)
t.assert((MAX_SAFE_INTEGER - num) / MAX_SAFE_INTEGER < 0.01, 'Largest number is close to MAX_SAFE_INTEGER (at most 1% off).')
})
test(rt.plain`${prefix} generateChar generates all described characters`, function real53bitResolution (t) {
const { gen } = init(PRNG.Gen)
const charSet = new Set()
const chars = ' !"#$%&\'()*+,-./0123456789:;<=>?@ABCDEFGHIJKLMNOPQRSTUVWXYZ[/]^_`abcdefghijklmnopqrstuvwxyz{|}~"'
let i
let char
for (i = chars.length - 1; i >= 0; i--) {
charSet.add(chars[i])
}
for (i = 0; i < ITERATONS; i++) {
char = generateChar(gen)
charSet.delete(char)
}
t.log(`Charactes missing: ${charSet.size} - generating all of "${chars}"`)
t.assert(charSet.size === 0, 'Generated all documented characters.')
})
}
*/

47
lib/simpleDiff.js Normal file
View File

@@ -0,0 +1,47 @@
/**
* A SimpleDiff describes a change on a String.
*
* @example
* console.log(a) // the old value
* console.log(b) // the updated value
* // Apply changes of diff (pseudocode)
* a.remove(diff.pos, diff.remove) // Remove `diff.remove` characters
* a.insert(diff.pos, diff.insert) // Insert `diff.insert`
* a === b // values match
*
* @typedef {Object} SimpleDiff
* @property {Number} pos The index where changes were applied
* @property {Number} remove The number of characters to delete starting
* at `index`.
* @property {String} insert The new text to insert at `index` after applying
* `delete`
*/
/**
* Create a diff between two strings. This diff implementation is highly
* efficient, but not very sophisticated.
*
* @public
* @param {String} a The old version of the string
* @param {String} b The updated version of the string
* @return {SimpleDiff} The diff description.
*/
export default function simpleDiff (a, b) {
let left = 0 // number of same characters counting from left
let right = 0 // number of same characters counting from right
while (left < a.length && left < b.length && a[left] === b[left]) {
left++
}
if (left !== a.length || left !== b.length) {
// Only check right if a !== b
while (right + left < a.length && right + left < b.length && a[a.length - right - 1] === b[b.length - right - 1]) {
right++
}
}
return {
pos: left, // TODO: rename to index (also in type above)
remove: a.length - left - right,
insert: b.slice(left, b.length - right)
}
}

2
lib/string.js Normal file
View File

@@ -0,0 +1,2 @@
export const fromCharCode = String.fromCharCode
export const fromCodePoint = String.fromCodePoint

33
lib/test.js Normal file
View File

@@ -0,0 +1,33 @@
import * as logging from './logging.js'
import simpleDiff from './simpleDiff.js'
export const run = async (name, f) => {
console.log(`%cStart:%c ${name}`, 'color:blue;', '')
const start = new Date()
try {
await f(name)
} catch (e) {
logging.print(`%cFailure:%c ${name} in %c${new Date().getTime() - start.getTime()}ms`, 'color:red;font-weight:bold', '', 'color:grey')
throw e
}
logging.print(`%cSuccess:%c ${name} in %c${new Date().getTime() - start.getTime()}ms`, 'color:green;font-weight:bold', '', 'color:grey')
}
export const compareArrays = (as, bs) => {
if (as.length !== bs.length) {
return false
}
for (let i = 0; i < as.length; i++) {
if (as[i] !== bs[i]) {
return false
}
}
return true
}
export const compareStrings = (a, b) => {
if (a !== b) {
const diff = simpleDiff(a, b)
logging.print(`%c${a.slice(0, diff.pos)}%c${a.slice(diff.pos, diff.remove)}%c${diff.insert}%c${a.slice(diff.pos + diff.remove)}`, 'color:grey', 'color:red', 'color:green', 'color:grey')
}
}

3
lib/time.js Normal file
View File

@@ -0,0 +1,3 @@
export const getDate = () => new Date()
export const getUnixTime = () => getDate().getTime()

View File

@@ -1,59 +0,0 @@
Y = require './y'
bindToChildren = (that)->
for i in [0...that.children.length]
attr = that.children.item(i)
if attr.name?
attr.val = that.val.val(attr.name)
that.val.observe (events)->
for event in events
if event.name?
for i in [0...that.children.length]
attr = that.children.item(i)
if attr.name? and attr.name is event.name
newVal = that.val.val(attr.name)
if attr.val isnt newVal
attr.val = newVal
Polymer "y-object",
ready: ()->
if @connector?
@val = new Y @connector
bindToChildren @
else if @val?
bindToChildren @
valChanged: ()->
if @val? and @val.type is "Object"
bindToChildren @
connectorChanged: ()->
if (not @val?)
@val = new Y @connector
bindToChildren @
Polymer "y-property",
ready: ()->
if @val? and @name?
if @val.constructor is Object
@val = @parentElement.val(@name,@val).val(@name)
# TODO: please use instanceof instead of .type,
# since it is more safe (consider someone putting a custom Object type here)
else if typeof @val is "string"
@parentElement.val(@name,@val)
if @val.type is "Object"
bindToChildren @
valChanged: ()->
if @val? and @name?
if @val.constructor is Object
@val = @parentElement.val.val(@name,@val).val(@name)
# TODO: please use instanceof instead of .type,
# since it is more safe (consider someone putting a custom Object type here)
else if @val.type is "Object"
bindToChildren @
else if @parentElement.val?.val? and @val isnt @parentElement.val.val(@name)
@parentElement.val.val @name, @val

View File

@@ -1,48 +0,0 @@
json_types_uninitialized = require "./Types/JsonTypes"
HistoryBuffer = require "./HistoryBuffer"
Engine = require "./Engine"
adaptConnector = require "./ConnectorAdapter"
createY = (connector)->
user_id = null
if connector.id?
user_id = connector.id # TODO: change to getUniqueId()
else
user_id = "_temp"
connector.onUserIdSet (id)->
user_id = id
HB.resetUserId id
HB = new HistoryBuffer user_id
type_manager = json_types_uninitialized HB
types = type_manager.types
#
# Framework for Json data-structures.
# Known values that are supported:
# * String
# * Integer
# * Array
#
class Y extends types.Object
#
# @param {String} user_id Unique id of the peer.
# @param {Connector} Connector the connector class.
#
constructor: ()->
@connector = connector
@HB = HB
@types = types
@engine = new Engine @HB, type_manager.types
adaptConnector @connector, @engine, @HB, type_manager.execution_listener
super
getConnector: ()->
@connector
return new Y(HB.getReservedUniqueIdentifier()).execute()
module.exports = createY
if window? and not window.Y?
window.Y = createY

7067
package-lock.json generated Normal file

File diff suppressed because it is too large Load Diff

View File

@@ -1,66 +1,76 @@
{
"name": "yjs",
"version": "0.3.1",
"description": "A Framework that enables Real-Time Collaboration on arbitrary data structures.",
"main": "./build/node/y.js",
"version": "13.0.0-66",
"description": "A framework for real-time p2p shared editing on any data",
"main": "./y.node.js",
"browser": "./y.js",
"module": "./src/index.js",
"scripts": {
"test": "./node_modules/.bin/gulp test"
"test": "npm run lint",
"debug": "concurrently 'rollup -wc rollup.test.js' 'cutest-serve y.test.js -o'",
"lint": "standard src/**/*.js test/**/*.js tests-lib/**/*.js",
"docs": "esdoc",
"serve-docs": "npm run docs && serve ./docs/",
"dist": "rollup -c rollup.browser.js; rollup -c rollup.node.js",
"watch": "concurrently 'rollup -wc rollup.browser.js' 'rollup -wc rollup.node.js'",
"postversion": "npm run dist"
},
"files": [
"y.*",
"src/*",
".esdoc.json",
"docs/*"
],
"standard": {
"ignore": [
"/y.js",
"/y.js.map"
]
},
"repository": {
"type": "git",
"url": "https://github.com/rwth-acis/yjs"
"url": "https://github.com/y-js/yjs.git"
},
"keywords": [
"Yjs",
"OT",
"collaboration",
"Yata",
"synchronization",
"Collaboration",
"Synchronization",
"ShareJS",
"Coweb",
"concurrency"
"Concurrency"
],
"author": "Kevin Jahns",
"email": "kevin.jahns@rwth-aachen.de",
"license": "MIT",
"bugs": {
"url": "https://github.com/rwth-acis/yjs/issues"
},
"homepage": "https://dadamonad.github.io/yjs/",
"dependencies": {
"url": "https://github.com/y-js/yjs/issues"
},
"homepage": "http://y-js.org",
"devDependencies": {
"codo": "^2.0.9",
"underscore": "^1.6.0",
"chai": "^1.9.1",
"codo": "^2.0.9",
"coffee-errors": "~0.8.6",
"coffee-script": "^1.7.1",
"coffeeify": "^0.6.0",
"gulp": "^3.8.7",
"gulp-browserify": "^0.5.0",
"gulp-cached": "^1.0.1",
"gulp-coffee": "^2.1.1",
"gulp-coffeeify": "^0.1.2",
"gulp-coffeelint": "^0.3.3",
"gulp-concat": "^2.3.4",
"gulp-copy": "0.0.2",
"gulp-debug": "^1.0.0",
"gulp-git": "^0.5.0",
"gulp-if": "^1.2.4",
"gulp-ignore": "^1.2.0",
"gulp-ljs": "^0.1.1",
"gulp-mocha": "^0.5.2",
"gulp-mocha-phantomjs": "^0.5.0",
"gulp-plumber": "^0.6.6",
"gulp-rename": "^1.2.0",
"gulp-rimraf": "^0.1.0",
"gulp-run": "^1.6.3",
"gulp-sourcemaps": "^1.1.1",
"gulp-uglify": "^0.3.1",
"gulp-watch": "^3.0.0",
"jquery": "^2.1.1",
"mocha": "^1.21.4",
"sinon": "^1.10.2",
"sinon-chai": "^2.5.0"
"babel-cli": "^6.26.0",
"babel-plugin-external-helpers": "^6.22.0",
"babel-plugin-transform-regenerator": "^6.26.0",
"babel-plugin-transform-runtime": "^6.23.0",
"babel-preset-latest": "^6.24.1",
"concurrently": "^3.6.1",
"cutest": "^0.1.9",
"esdoc": "^1.1.0",
"esdoc-standard-plugin": "^1.0.0",
"quill": "^1.3.6",
"quill-cursors": "^1.0.3",
"rollup": "^0.58.2",
"rollup-plugin-babel": "^2.7.1",
"rollup-plugin-commonjs": "^8.4.1",
"rollup-plugin-inject": "^2.2.0",
"rollup-plugin-multi-entry": "^2.0.2",
"rollup-plugin-node-resolve": "^3.4.0",
"rollup-plugin-uglify": "^1.0.2",
"rollup-regenerator-runtime": "^6.23.1",
"rollup-watch": "^3.2.2",
"standard": "^11.0.1"
},
"dependencies": {
"ws": "^6.1.0"
}
}

Some files were not shown because too many files have changed in this diff Show More