yrby 0.9.0 → 0.10.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- checksums.yaml +4 -4
- data/CHANGELOG.md +46 -0
- data/Cargo.lock +12 -20
- data/README.md +57 -6
- data/ext/yrby/Cargo.toml +1 -1
- data/ext/yrby/src/array.rs +37 -25
- data/ext/yrby/src/lib.rs +161 -99
- data/ext/yrby/src/map.rs +26 -15
- data/ext/yrby/src/read.rs +76 -1
- data/ext/yrby/src/shared.rs +29 -10
- data/ext/yrby/src/text.rs +14 -17
- data/ext/yrby/src/xml_text.rs +46 -55
- data/lib/generators/yrby/install/install_generator.rb +39 -3
- data/lib/y/array.rb +17 -0
- data/lib/y/collaborative/attribute.rb +10 -9
- data/lib/y/collaborative/helper.rb +4 -4
- data/lib/y/collaborative.rb +6 -5
- data/lib/y/doc.rb +52 -9
- data/lib/y/map.rb +12 -0
- data/lib/y/trix.rb +393 -0
- data/lib/y/version.rb +1 -1
- data/lib/y.rb +3 -0
- metadata +4 -1
data/ext/yrby/src/lib.rs
CHANGED
|
@@ -33,7 +33,49 @@ pub(crate) use yjs_html_core as render_rules;
|
|
|
33
33
|
/// interior-mutability wrapper (RefCell and friends): every method opens and
|
|
34
34
|
/// closes its transaction within a single call.
|
|
35
35
|
#[magnus::wrap(class = "Y::Doc", free_immediately, size)]
|
|
36
|
-
struct RbDoc(Doc);
|
|
36
|
+
struct RbDoc(Doc, Unsent);
|
|
37
|
+
|
|
38
|
+
/// The updates of this document's own transactions that no `Doc#edit` has
|
|
39
|
+
/// returned yet. Every transaction but a peer's lands here when it commits,
|
|
40
|
+
/// after yrs is done changing the document, whichever thread or fiber made
|
|
41
|
+
/// it and whether or not an edit was running. So no local write is left out.
|
|
42
|
+
/// They're merged only when an edit takes them, so until then the document
|
|
43
|
+
/// holds the bytes of every local write.
|
|
44
|
+
type Unsent = std::sync::Arc<std::sync::Mutex<Vec<Vec<u8>>>>;
|
|
45
|
+
|
|
46
|
+
/// `Unsent`'s list. A push or a take holds it only briefly, so taking it
|
|
47
|
+
/// with the GVL held never waits long.
|
|
48
|
+
fn lock(unsent: &Unsent) -> std::sync::MutexGuard<'_, Vec<Vec<u8>>> {
|
|
49
|
+
unsent
|
|
50
|
+
.lock()
|
|
51
|
+
.unwrap_or_else(|poisoned| poisoned.into_inner())
|
|
52
|
+
}
|
|
53
|
+
|
|
54
|
+
/// How many updates `merge_unsent` merges at once.
|
|
55
|
+
const MERGE_FAN_IN: usize = 16;
|
|
56
|
+
|
|
57
|
+
/// The updates merged into one, a few at a time and then the results again.
|
|
58
|
+
/// One merge of them all costs time quadratic in how many there are.
|
|
59
|
+
fn merge_unsent(updates: &[Vec<u8>]) -> Result<Vec<u8>, String> {
|
|
60
|
+
let mut level: Vec<Vec<u8>> = match updates {
|
|
61
|
+
[update] => return Ok(update.clone()),
|
|
62
|
+
_ => merge_chunks(updates)?,
|
|
63
|
+
};
|
|
64
|
+
while level.len() > 1 {
|
|
65
|
+
level = merge_chunks(&level)?;
|
|
66
|
+
}
|
|
67
|
+
Ok(level.pop().unwrap_or_default())
|
|
68
|
+
}
|
|
69
|
+
|
|
70
|
+
fn merge_chunks(updates: &[Vec<u8>]) -> Result<Vec<Vec<u8>>, String> {
|
|
71
|
+
updates
|
|
72
|
+
.chunks(MERGE_FAN_IN)
|
|
73
|
+
.map(|chunk| match chunk {
|
|
74
|
+
[update] => Ok(update.clone()),
|
|
75
|
+
_ => yrs::merge_updates_v1(chunk).map_err(|e| e.to_string()),
|
|
76
|
+
})
|
|
77
|
+
.collect()
|
|
78
|
+
}
|
|
37
79
|
|
|
38
80
|
/// Compile-time proof that the wrapped Doc is thread-safe. If a future yrs
|
|
39
81
|
/// upgrade makes Doc lose Send/Sync, this fails the build instead of silently
|
|
@@ -171,7 +213,17 @@ impl RbDoc {
|
|
|
171
213
|
yrs::Options::with_client_id(yrs::block::ClientID::new(client_id))
|
|
172
214
|
};
|
|
173
215
|
options.offset_kind = yrs::OffsetKind::Utf16;
|
|
174
|
-
|
|
216
|
+
let doc = Doc::with_options(options);
|
|
217
|
+
let unsent = Unsent::default();
|
|
218
|
+
let sink = unsent.clone();
|
|
219
|
+
doc.observe_update_v1("yrby-unsent", move |txn, event| {
|
|
220
|
+
if shared::is_remote(txn.origin()) {
|
|
221
|
+
return;
|
|
222
|
+
}
|
|
223
|
+
lock(&sink).push(event.update.clone());
|
|
224
|
+
})
|
|
225
|
+
.map_err(|e| yrb_error(e.to_string()))?;
|
|
226
|
+
Ok(RbDoc(doc, unsent))
|
|
175
227
|
}
|
|
176
228
|
|
|
177
229
|
/// The id this document writes its own edits under. Presence for the same
|
|
@@ -212,6 +264,20 @@ impl RbDoc {
|
|
|
212
264
|
})
|
|
213
265
|
}
|
|
214
266
|
|
|
267
|
+
/// A `Y.Text` root as a Yjs delta in a JSON array string: the runs of
|
|
268
|
+
/// text with their formatting attributes, and the embeds. What
|
|
269
|
+
/// `ytext.toDelta()` gives in JavaScript. `read_text` gives the
|
|
270
|
+
/// characters alone. Callers parse the JSON. The serialization lives in
|
|
271
|
+
/// `read::text_delta_json` (pure, Rust-tested).
|
|
272
|
+
fn read_text_delta(&self, name: String) -> Result<Option<String>, Error> {
|
|
273
|
+
let doc = &self.0;
|
|
274
|
+
nogvl(move || {
|
|
275
|
+
let txn = doc.transact();
|
|
276
|
+
let text = txn.get_text(name.as_str())?;
|
|
277
|
+
Some(read::text_delta_json(&txn, &text))
|
|
278
|
+
})
|
|
279
|
+
}
|
|
280
|
+
|
|
215
281
|
/// Text of an XML-shaped root, one top-level block per line. The walk +
|
|
216
282
|
/// block-join logic lives in `read::xml_blocks_text` (pure, Rust-tested);
|
|
217
283
|
/// this just opens the transaction and resolves the root.
|
|
@@ -312,7 +378,7 @@ impl RbDoc {
|
|
|
312
378
|
// One transaction from the snapshot of the blocks to the commit,
|
|
313
379
|
// under an origin of its own: another write can't change the
|
|
314
380
|
// blocks in between, and its events don't count.
|
|
315
|
-
let key = shared::
|
|
381
|
+
let key = shared::remote_key();
|
|
316
382
|
let mut txn = doc.transact_mut_with(key.clone());
|
|
317
383
|
let fragment = yrs::WriteTxn::get_or_insert_xml_fragment(&mut txn, root.as_str());
|
|
318
384
|
let branch: &yrs::branch::Branch = fragment.as_ref();
|
|
@@ -398,30 +464,31 @@ impl RbDoc {
|
|
|
398
464
|
Ok(id.map(|id| xml_text::handle(&self.0, id, root)))
|
|
399
465
|
}
|
|
400
466
|
|
|
401
|
-
///
|
|
402
|
-
///
|
|
403
|
-
|
|
404
|
-
|
|
405
|
-
|
|
406
|
-
|
|
467
|
+
/// Every update in `Unsent`, merged into one, or nil for none. Taking them
|
|
468
|
+
/// empties it, and writes made meanwhile wait for the next take. The
|
|
469
|
+
/// merge runs without the GVL. If it fails, or an interrupt comes back
|
|
470
|
+
/// with it (a signal trap can raise even where `Thread.handle_interrupt`
|
|
471
|
+
/// masks), the updates go back ahead of those writes.
|
|
472
|
+
fn take_unsent(&self) -> Result<Option<RString>, Error> {
|
|
473
|
+
let taken = std::mem::take(&mut *lock(&self.1));
|
|
474
|
+
if taken.is_empty() {
|
|
475
|
+
return Ok(None);
|
|
476
|
+
}
|
|
477
|
+
match nogvl(|| merge_unsent(&taken)).and_then(|merged| merged.map_err(yrb_error)) {
|
|
478
|
+
Ok(merged) => Ok(Some(binary_string(&merged))),
|
|
479
|
+
Err(error) => {
|
|
480
|
+
let mut unsent = lock(&self.1);
|
|
481
|
+
let since = std::mem::replace(&mut *unsent, taken);
|
|
482
|
+
unsent.extend(since);
|
|
483
|
+
Err(error)
|
|
484
|
+
}
|
|
485
|
+
}
|
|
407
486
|
}
|
|
408
487
|
|
|
409
|
-
///
|
|
410
|
-
///
|
|
411
|
-
fn
|
|
412
|
-
|
|
413
|
-
let doc = &self.0;
|
|
414
|
-
let update = nogvl(move || -> Result<Option<Vec<u8>>, String> {
|
|
415
|
-
let before = yrs::Snapshot::decode_v1(&bytes).map_err(|e| e.to_string())?;
|
|
416
|
-
let txn = doc.transact();
|
|
417
|
-
let now = txn.snapshot();
|
|
418
|
-
if now == before {
|
|
419
|
-
return Ok(None);
|
|
420
|
-
}
|
|
421
|
-
Ok(Some(changes_since(&txn, &before, &now)))
|
|
422
|
-
})?
|
|
423
|
-
.map_err(yrb_error)?;
|
|
424
|
-
Ok(update.map(|update| binary_string(&update)))
|
|
488
|
+
/// Put a taken update back ahead of anything written since, for the next
|
|
489
|
+
/// take to return again.
|
|
490
|
+
fn keep_unsent(&self, update: RString) {
|
|
491
|
+
lock(&self.1).insert(0, copy_bytes(update));
|
|
425
492
|
}
|
|
426
493
|
|
|
427
494
|
/// Encode state as update (optionally diffed against a state vector)
|
|
@@ -450,7 +517,7 @@ impl RbDoc {
|
|
|
450
517
|
let doc = &self.0;
|
|
451
518
|
nogvl(move || -> Result<(), String> {
|
|
452
519
|
let update = yrs::Update::decode_v1(&update_bytes).map_err(|e| e.to_string())?;
|
|
453
|
-
let mut txn = doc.
|
|
520
|
+
let mut txn = doc.transact_mut_with(shared::REMOTE);
|
|
454
521
|
txn.apply_update(update).map_err(|e| e.to_string())
|
|
455
522
|
})?
|
|
456
523
|
.map_err(yrb_error)
|
|
@@ -513,7 +580,7 @@ impl RbDoc {
|
|
|
513
580
|
// Apply the update
|
|
514
581
|
let update =
|
|
515
582
|
yrs::Update::decode_v1(&update_bytes).map_err(|e| e.to_string())?;
|
|
516
|
-
let mut txn = doc.
|
|
583
|
+
let mut txn = doc.transact_mut_with(shared::REMOTE);
|
|
517
584
|
txn.apply_update(update).map_err(|e| e.to_string())?;
|
|
518
585
|
Ok((0, 1, Vec::new()))
|
|
519
586
|
}
|
|
@@ -521,7 +588,7 @@ impl RbDoc {
|
|
|
521
588
|
// Apply the update
|
|
522
589
|
let update =
|
|
523
590
|
yrs::Update::decode_v1(&update_bytes).map_err(|e| e.to_string())?;
|
|
524
|
-
let mut txn = doc.
|
|
591
|
+
let mut txn = doc.transact_mut_with(shared::REMOTE);
|
|
525
592
|
txn.apply_update(update).map_err(|e| e.to_string())?;
|
|
526
593
|
Ok((0, 2, Vec::new()))
|
|
527
594
|
}
|
|
@@ -805,27 +872,6 @@ fn update_from_message(data: RString) -> Result<Option<RString>, Error> {
|
|
|
805
872
|
// Module Initialization
|
|
806
873
|
// ============================================================================
|
|
807
874
|
|
|
808
|
-
/// The blocks added since `before`, and the deletions made since it.
|
|
809
|
-
///
|
|
810
|
-
/// An update since a state vector carries the whole delete set, every
|
|
811
|
-
/// deletion the document has ever had, so a chunk streamed into a long-lived
|
|
812
|
-
/// document would grow with its history. A v1 update is its blocks followed
|
|
813
|
-
/// by its delete set, so this swaps that delete set for only the new
|
|
814
|
-
/// deletions. If the bytes ever don't end with the delete set as expected, it
|
|
815
|
-
/// keeps the whole update, which is bigger but still right.
|
|
816
|
-
fn changes_since<T: ReadTxn>(txn: &T, before: &yrs::Snapshot, now: &yrs::Snapshot) -> Vec<u8> {
|
|
817
|
-
let full = txn.encode_state_as_update_v1(&before.state_map);
|
|
818
|
-
let all = now.delete_set.encode_v1();
|
|
819
|
-
match full.strip_suffix(all.as_slice()) {
|
|
820
|
-
Some(blocks) => {
|
|
821
|
-
let mut update = blocks.to_vec();
|
|
822
|
-
update.extend(now.delete_set.diff(&before.delete_set).encode_v1());
|
|
823
|
-
update
|
|
824
|
-
}
|
|
825
|
-
None => full,
|
|
826
|
-
}
|
|
827
|
-
}
|
|
828
|
-
|
|
829
875
|
/// A root's children in order: the document index each starts at and
|
|
830
876
|
/// whether it is an `XmlText` block. Ordinals count only those, as
|
|
831
877
|
/// `xml_text(n)` does; a divider or an image is a child but not a block.
|
|
@@ -1182,10 +1228,11 @@ fn init(ruby: &Ruby) -> Result<(), Error> {
|
|
|
1182
1228
|
)?;
|
|
1183
1229
|
doc_class.define_private_method("native_block_at", method!(RbDoc::block_at, 2))?;
|
|
1184
1230
|
doc_class.define_private_method("native_find", method!(RbDoc::find, 2))?;
|
|
1185
|
-
doc_class.define_private_method("
|
|
1186
|
-
doc_class.define_private_method("
|
|
1231
|
+
doc_class.define_private_method("native_take_unsent", method!(RbDoc::take_unsent, 0))?;
|
|
1232
|
+
doc_class.define_private_method("native_keep_unsent", method!(RbDoc::keep_unsent, 1))?;
|
|
1187
1233
|
doc_class.define_method("root_names", method!(RbDoc::root_names, 0))?;
|
|
1188
1234
|
doc_class.define_method("read_text", method!(RbDoc::read_text, 1))?;
|
|
1235
|
+
doc_class.define_method("read_text_delta", method!(RbDoc::read_text_delta, 1))?;
|
|
1189
1236
|
doc_class.define_method("read_xml", method!(RbDoc::read_xml, 1))?;
|
|
1190
1237
|
doc_class.define_method("read_map", method!(RbDoc::read_map, 1))?;
|
|
1191
1238
|
doc_class.define_method("read_array", method!(RbDoc::read_array, 1))?;
|
|
@@ -1360,6 +1407,69 @@ mod tests {
|
|
|
1360
1407
|
);
|
|
1361
1408
|
}
|
|
1362
1409
|
|
|
1410
|
+
fn take(doc: &RbDoc) -> Option<RString> {
|
|
1411
|
+
doc.take_unsent().unwrap()
|
|
1412
|
+
}
|
|
1413
|
+
|
|
1414
|
+
#[ruby_test]
|
|
1415
|
+
fn local_writes_wait_to_be_taken_and_a_peers_never_do() {
|
|
1416
|
+
let doc = new_doc();
|
|
1417
|
+
push(&doc, "t", "mine");
|
|
1418
|
+
let mine = take(&doc).expect("a local write waits");
|
|
1419
|
+
assert!(take(&doc).is_none(), "taking empties it");
|
|
1420
|
+
|
|
1421
|
+
let peer = new_doc();
|
|
1422
|
+
peer.apply_update(mine).unwrap();
|
|
1423
|
+
peer.handle_sync_message(wrap_update(mine)).unwrap();
|
|
1424
|
+
peer.apply_update_changes(mine, "root".into()).unwrap();
|
|
1425
|
+
assert!(take(&peer).is_none(), "applied updates are a peer's");
|
|
1426
|
+
assert_eq!(peer.read_text("t".into()).unwrap().as_deref(), Some("mine"));
|
|
1427
|
+
}
|
|
1428
|
+
|
|
1429
|
+
#[ruby_test]
|
|
1430
|
+
fn unsent_updates_merge_into_one_that_carries_them_all() {
|
|
1431
|
+
let doc = new_doc();
|
|
1432
|
+
for n in 0..300 {
|
|
1433
|
+
push(&doc, "t", &n.to_string());
|
|
1434
|
+
}
|
|
1435
|
+
let fresh = new_doc();
|
|
1436
|
+
fresh.apply_update(take(&doc).unwrap()).unwrap();
|
|
1437
|
+
assert_eq!(
|
|
1438
|
+
fresh.read_text("t".into()).unwrap(),
|
|
1439
|
+
doc.read_text("t".into()).unwrap()
|
|
1440
|
+
);
|
|
1441
|
+
assert!(!fresh.pending().unwrap());
|
|
1442
|
+
}
|
|
1443
|
+
|
|
1444
|
+
#[ruby_test]
|
|
1445
|
+
fn a_kept_update_is_taken_again_with_what_came_after() {
|
|
1446
|
+
let doc = new_doc();
|
|
1447
|
+
push(&doc, "t", "inner");
|
|
1448
|
+
doc.keep_unsent(take(&doc).unwrap());
|
|
1449
|
+
push(&doc, "t", " outer");
|
|
1450
|
+
let fresh = new_doc();
|
|
1451
|
+
fresh.apply_update(take(&doc).unwrap()).unwrap();
|
|
1452
|
+
assert_eq!(
|
|
1453
|
+
fresh.read_text("t".into()).unwrap().as_deref(),
|
|
1454
|
+
Some("inner outer")
|
|
1455
|
+
);
|
|
1456
|
+
}
|
|
1457
|
+
|
|
1458
|
+
#[ruby_test]
|
|
1459
|
+
fn unsent_updates_stay_when_the_merge_fails() {
|
|
1460
|
+
let doc = new_doc();
|
|
1461
|
+
push(&doc, "t", "kept");
|
|
1462
|
+
doc.1.lock().unwrap().push(vec![255]);
|
|
1463
|
+
assert!(doc.take_unsent().is_err());
|
|
1464
|
+
doc.1.lock().unwrap().pop();
|
|
1465
|
+
let fresh = new_doc();
|
|
1466
|
+
fresh.apply_update(take(&doc).unwrap()).unwrap();
|
|
1467
|
+
assert_eq!(
|
|
1468
|
+
fresh.read_text("t".into()).unwrap().as_deref(),
|
|
1469
|
+
Some("kept")
|
|
1470
|
+
);
|
|
1471
|
+
}
|
|
1472
|
+
|
|
1363
1473
|
#[ruby_test]
|
|
1364
1474
|
fn a_malformed_update_raises() {
|
|
1365
1475
|
assert!(new_doc()
|
|
@@ -1439,54 +1549,6 @@ mod tests {
|
|
|
1439
1549
|
assert!(peer.handle_sync_message(binary_string(&[9, 9])).is_err());
|
|
1440
1550
|
}
|
|
1441
1551
|
|
|
1442
|
-
#[ruby_test]
|
|
1443
|
-
fn an_update_since_a_snapshot_holds_what_changed_after_it() {
|
|
1444
|
-
let doc = new_doc();
|
|
1445
|
-
push(&doc, "t", "before");
|
|
1446
|
-
let snapshot = doc.snapshot().unwrap();
|
|
1447
|
-
assert!(doc.update_since(snapshot).unwrap().is_none());
|
|
1448
|
-
push(&doc, "t", " after");
|
|
1449
|
-
let peer = new_doc();
|
|
1450
|
-
peer.apply_update(doc.update_since(snapshot).unwrap().unwrap())
|
|
1451
|
-
.unwrap();
|
|
1452
|
-
assert!(
|
|
1453
|
-
peer.pending().unwrap(),
|
|
1454
|
-
"the update leaves out what came before"
|
|
1455
|
-
);
|
|
1456
|
-
peer.apply_update(update(&doc)).unwrap();
|
|
1457
|
-
assert_eq!(
|
|
1458
|
-
peer.read_text("t".into()).unwrap().as_deref(),
|
|
1459
|
-
Some("before after")
|
|
1460
|
-
);
|
|
1461
|
-
}
|
|
1462
|
-
|
|
1463
|
-
#[ruby_test]
|
|
1464
|
-
fn an_update_since_a_snapshot_carries_only_new_deletions() {
|
|
1465
|
-
let doc = new_doc();
|
|
1466
|
-
let text = doc.0.get_or_insert_text("t");
|
|
1467
|
-
for _ in 0..200 {
|
|
1468
|
-
push(&doc, "t", "xy");
|
|
1469
|
-
let mut txn = doc.0.transact_mut();
|
|
1470
|
-
let at = text.len(&txn) - 1;
|
|
1471
|
-
text.remove_range(&mut txn, at, 1);
|
|
1472
|
-
}
|
|
1473
|
-
let snapshot = doc.snapshot().unwrap();
|
|
1474
|
-
let peer = new_doc();
|
|
1475
|
-
peer.apply_update(update(&doc)).unwrap();
|
|
1476
|
-
text.remove_range(&mut doc.0.transact_mut(), 0, 1);
|
|
1477
|
-
let chunk = doc.update_since(snapshot).unwrap().unwrap();
|
|
1478
|
-
assert!(
|
|
1479
|
-
copy_bytes(chunk).len() < 40,
|
|
1480
|
-
"{} bytes",
|
|
1481
|
-
copy_bytes(chunk).len()
|
|
1482
|
-
);
|
|
1483
|
-
peer.apply_update(chunk).unwrap();
|
|
1484
|
-
assert_eq!(
|
|
1485
|
-
peer.read_text("t".into()).unwrap(),
|
|
1486
|
-
doc.read_text("t".into()).unwrap()
|
|
1487
|
-
);
|
|
1488
|
-
}
|
|
1489
|
-
|
|
1490
1552
|
#[ruby_test]
|
|
1491
1553
|
fn apply_update_changes_reports_the_blocks_an_update_touched() {
|
|
1492
1554
|
let doc = lexical_doc(&["one", "two", "three"]);
|
data/ext/yrby/src/map.rs
CHANGED
|
@@ -11,13 +11,13 @@
|
|
|
11
11
|
|
|
12
12
|
use magnus::{prelude::*, typed_data::Obj, Error, Ruby, Value};
|
|
13
13
|
use yrs::branch::BranchID;
|
|
14
|
-
use yrs::{Any, Doc, Map, MapRef, Transact};
|
|
14
|
+
use yrs::{Any, Doc, Map, MapRef, TextPrelim, Transact};
|
|
15
15
|
|
|
16
16
|
use crate::array::RbArray;
|
|
17
17
|
use crate::nogvl;
|
|
18
18
|
use crate::read::out_to_any;
|
|
19
19
|
use crate::shared::{
|
|
20
|
-
any_to_ruby,
|
|
20
|
+
any_to_ruby, identity, key_to_string, resolve, ruby_to_invalue, to_in, write, Child,
|
|
21
21
|
};
|
|
22
22
|
use crate::text::RbText;
|
|
23
23
|
|
|
@@ -168,27 +168,38 @@ impl RbMap {
|
|
|
168
168
|
let key = key_to_string(key)?;
|
|
169
169
|
let iv = ruby_to_invalue(&ruby, value)?;
|
|
170
170
|
let (doc, id) = (&self.doc, &self.id);
|
|
171
|
-
|
|
172
|
-
let
|
|
173
|
-
|
|
174
|
-
m.insert(&mut txn, key, to_in(iv));
|
|
171
|
+
write(doc, move |txn| {
|
|
172
|
+
let m = resolve::<MapRef, _>(txn, id).ok_or("map no longer exists")?;
|
|
173
|
+
m.insert(txn, key, to_in(iv));
|
|
175
174
|
Ok(())
|
|
176
175
|
})?;
|
|
177
176
|
Ok(value)
|
|
178
177
|
}
|
|
179
178
|
|
|
179
|
+
/// Store a new `Y.Text` holding `content` at `key`, replacing what was
|
|
180
|
+
/// there, and return a live handle to it. A text in a map is what lets
|
|
181
|
+
/// two people type in the same field and both keep their edit.
|
|
182
|
+
fn set_text(&self, key: Value, content: String) -> Result<RbText, Error> {
|
|
183
|
+
let key = key_to_string(key)?;
|
|
184
|
+
let (doc, id) = (&self.doc, &self.id);
|
|
185
|
+
let text = write(doc, move |txn| {
|
|
186
|
+
let m = resolve::<MapRef, _>(txn, id).ok_or("map no longer exists")?;
|
|
187
|
+
Ok(identity(&m.insert(txn, key, TextPrelim::new(content))))
|
|
188
|
+
})?;
|
|
189
|
+
Ok(RbText::new(self.doc.clone(), text))
|
|
190
|
+
}
|
|
191
|
+
|
|
180
192
|
/// Remove `key`, returning its previous snapshot value (or `nil`).
|
|
181
193
|
fn delete(&self, key: Value) -> Result<Value, Error> {
|
|
182
194
|
let key = key_to_string(key)?;
|
|
183
195
|
let (doc, id) = (&self.doc, &self.id);
|
|
184
|
-
let prev: Option<Any> =
|
|
185
|
-
let
|
|
186
|
-
let Some(m) = resolve::<MapRef, _>(&txn, id) else {
|
|
196
|
+
let prev: Option<Any> = write(doc, move |txn| {
|
|
197
|
+
let Some(m) = resolve::<MapRef, _>(txn, id) else {
|
|
187
198
|
return Ok(None);
|
|
188
199
|
};
|
|
189
200
|
// Convert before removing (a removed shared ref would dangle).
|
|
190
|
-
let prev = m.get(
|
|
191
|
-
m.remove(
|
|
201
|
+
let prev = m.get(txn, &key).map(|v| out_to_any(txn, &v));
|
|
202
|
+
m.remove(txn, &key);
|
|
192
203
|
Ok(prev)
|
|
193
204
|
})?;
|
|
194
205
|
let ruby = Ruby::get().unwrap();
|
|
@@ -200,10 +211,9 @@ impl RbMap {
|
|
|
200
211
|
|
|
201
212
|
fn clear(&self) -> Result<(), Error> {
|
|
202
213
|
let (doc, id) = (&self.doc, &self.id);
|
|
203
|
-
|
|
204
|
-
let
|
|
205
|
-
|
|
206
|
-
m.clear(&mut txn);
|
|
214
|
+
write(doc, move |txn| {
|
|
215
|
+
if let Some(m) = resolve::<MapRef, _>(txn, id) {
|
|
216
|
+
m.clear(txn);
|
|
207
217
|
}
|
|
208
218
|
Ok(())
|
|
209
219
|
})
|
|
@@ -227,6 +237,7 @@ pub fn define(ruby: &Ruby, module: magnus::RModule) -> Result<(), Error> {
|
|
|
227
237
|
class.define_method("get_text", magnus::method!(RbMap::get_text, 1))?;
|
|
228
238
|
class.define_method("[]=", magnus::method!(RbMap::set, 2))?;
|
|
229
239
|
class.define_method("set", magnus::method!(RbMap::set, 2))?;
|
|
240
|
+
class.define_method("native_set_text", magnus::method!(RbMap::set_text, 2))?;
|
|
230
241
|
class.define_method("delete", magnus::method!(RbMap::delete, 1))?;
|
|
231
242
|
class.define_method("clear", magnus::method!(RbMap::clear, 0))?;
|
|
232
243
|
class.define_method("key?", magnus::method!(RbMap::has_key, 1))?;
|
data/ext/yrby/src/read.rs
CHANGED
|
@@ -6,7 +6,7 @@ use std::collections::HashMap;
|
|
|
6
6
|
use std::sync::Arc;
|
|
7
7
|
use yrs::types::text::YChange;
|
|
8
8
|
use yrs::{
|
|
9
|
-
Any, Array, ArrayRef, GetString, Map, MapRef, Out, ReadTxn, Text, Xml, XmlFragment,
|
|
9
|
+
Any, Array, ArrayRef, GetString, Map, MapRef, Out, ReadTxn, Text, TextRef, Xml, XmlFragment,
|
|
10
10
|
XmlFragmentRef, XmlOut, XmlTextRef,
|
|
11
11
|
};
|
|
12
12
|
|
|
@@ -183,6 +183,34 @@ pub fn array_json<T: ReadTxn>(txn: &T, array: &ArrayRef) -> String {
|
|
|
183
183
|
any_to_json(&Any::Array(items.into()))
|
|
184
184
|
}
|
|
185
185
|
|
|
186
|
+
/// A `Y.Text` as a Yjs delta, in a JSON array string: what `ytext.toDelta()`
|
|
187
|
+
/// returns in JavaScript. Each element is `{"insert": ...}` with the run's
|
|
188
|
+
/// formatting under `"attributes"` when it has any. A string run inserts a
|
|
189
|
+
/// string; an embed inserts its value (an object, usually).
|
|
190
|
+
///
|
|
191
|
+
/// `read_text` gives the characters alone. An editor that keeps rich text in a
|
|
192
|
+
/// plain `Y.Text` (Quill, Trix through y-trix) puts everything else in the
|
|
193
|
+
/// attributes: bold, links, and what kind of block a line break ends. This is
|
|
194
|
+
/// how a server reads those. Object keys are sorted, as in `map_json`.
|
|
195
|
+
pub fn text_delta_json<T: ReadTxn>(txn: &T, text: &TextRef) -> String {
|
|
196
|
+
let mut ops: Vec<Any> = Vec::new();
|
|
197
|
+
for d in text.diff(txn, YChange::identity) {
|
|
198
|
+
let mut op: HashMap<String, Any> = HashMap::new();
|
|
199
|
+
op.insert("insert".to_string(), out_to_any(txn, &d.insert));
|
|
200
|
+
if let Some(attrs) = d.attributes {
|
|
201
|
+
if !attrs.is_empty() {
|
|
202
|
+
let hm: HashMap<String, Any> = attrs
|
|
203
|
+
.iter()
|
|
204
|
+
.map(|(k, v)| (k.to_string(), v.clone()))
|
|
205
|
+
.collect();
|
|
206
|
+
op.insert("attributes".to_string(), Any::Map(Arc::new(hm)));
|
|
207
|
+
}
|
|
208
|
+
}
|
|
209
|
+
ops.push(Any::Map(Arc::new(op)));
|
|
210
|
+
}
|
|
211
|
+
any_to_json(&Any::Array(ops.into()))
|
|
212
|
+
}
|
|
213
|
+
|
|
186
214
|
/// JSON-serialize an `Any` with object keys sorted at every depth. yrs's own
|
|
187
215
|
/// `Any::to_json` iterates `Any::Map` (a `HashMap`) in arbitrary order, so a
|
|
188
216
|
/// nested map would serialize unpredictably and differ run to run; sorting here
|
|
@@ -312,6 +340,53 @@ mod tests {
|
|
|
312
340
|
assert_eq!(xml_blocks_text(&txn, &frag), "");
|
|
313
341
|
}
|
|
314
342
|
|
|
343
|
+
#[test]
|
|
344
|
+
fn text_delta_json_gives_runs_with_their_attributes_and_embeds() {
|
|
345
|
+
use yrs::types::Attrs;
|
|
346
|
+
let doc = Doc::new();
|
|
347
|
+
let text = doc.get_or_insert_text("t");
|
|
348
|
+
{
|
|
349
|
+
let mut txn = doc.transact_mut();
|
|
350
|
+
let embed: HashMap<String, Any> =
|
|
351
|
+
HashMap::from([("src".to_string(), Any::from("a.png"))]);
|
|
352
|
+
text.insert_embed(&mut txn, 0, Any::Map(Arc::new(embed)));
|
|
353
|
+
text.insert(&mut txn, 1, "plain ");
|
|
354
|
+
let bold: Attrs = HashMap::from([(Arc::from("bold"), Any::Bool(true))]);
|
|
355
|
+
text.insert_with_attributes(&mut txn, 7, "bold", bold);
|
|
356
|
+
let link: Attrs = HashMap::from([
|
|
357
|
+
(Arc::from("href"), Any::from("https://example.com/")),
|
|
358
|
+
(Arc::from("bold"), Any::Bool(true)),
|
|
359
|
+
]);
|
|
360
|
+
text.insert_with_attributes(&mut txn, 11, "link", link);
|
|
361
|
+
let block: Attrs = HashMap::from([
|
|
362
|
+
(Arc::from("blockBreak"), Any::Bool(true)),
|
|
363
|
+
(
|
|
364
|
+
Arc::from("block"),
|
|
365
|
+
Any::Array(Arc::from(vec![Any::from("quote")])),
|
|
366
|
+
),
|
|
367
|
+
]);
|
|
368
|
+
text.insert_with_attributes(&mut txn, 15, "\n", block);
|
|
369
|
+
}
|
|
370
|
+
let txn = doc.transact();
|
|
371
|
+
assert_eq!(
|
|
372
|
+
text_delta_json(&txn, &text),
|
|
373
|
+
concat!(
|
|
374
|
+
r#"[{"insert":{"src":"a.png"}},"#,
|
|
375
|
+
r#"{"insert":"plain "},"#,
|
|
376
|
+
r#"{"attributes":{"bold":true},"insert":"bold"},"#,
|
|
377
|
+
r#"{"attributes":{"bold":true,"href":"https://example.com/"},"insert":"link"},"#,
|
|
378
|
+
r#"{"attributes":{"block":["quote"],"blockBreak":true},"insert":"\n"}]"#
|
|
379
|
+
)
|
|
380
|
+
);
|
|
381
|
+
}
|
|
382
|
+
|
|
383
|
+
#[test]
|
|
384
|
+
fn text_delta_json_of_an_empty_text_is_an_empty_array() {
|
|
385
|
+
let doc = Doc::new();
|
|
386
|
+
let text = doc.get_or_insert_text("t");
|
|
387
|
+
assert_eq!(text_delta_json(&doc.transact(), &text), "[]");
|
|
388
|
+
}
|
|
389
|
+
|
|
315
390
|
#[test]
|
|
316
391
|
fn map_json_serializes_primitives_with_sorted_keys() {
|
|
317
392
|
let doc = Doc::new();
|
data/ext/yrby/src/shared.rs
CHANGED
|
@@ -24,26 +24,34 @@ use magnus::{
|
|
|
24
24
|
use yrs::branch::{Branch, BranchID, BranchPtr};
|
|
25
25
|
use yrs::types::text::YChange;
|
|
26
26
|
use yrs::{
|
|
27
|
-
Any, Hook, In, IndexScope, MapPrelim, Number, Out, ReadTxn, SharedRef, StickyIndex, Text,
|
|
28
|
-
XmlOut, XmlTextRef,
|
|
27
|
+
Any, Doc, Hook, In, IndexScope, MapPrelim, Number, Out, ReadTxn, SharedRef, StickyIndex, Text,
|
|
28
|
+
Transact, TransactionMut, Xml, XmlOut, XmlTextRef,
|
|
29
29
|
};
|
|
30
30
|
|
|
31
31
|
use crate::{nogvl, yrb_error};
|
|
32
32
|
|
|
33
|
-
/// The origin of every transaction a handle opens
|
|
34
|
-
/// these, so an update applied from elsewhere while it runs stays out.
|
|
33
|
+
/// The origin of every transaction a handle opens, all through `write`.
|
|
35
34
|
pub const ORIGIN: &str = "yrby";
|
|
36
35
|
|
|
36
|
+
/// What the origin of every transaction that applies a peer's update starts
|
|
37
|
+
/// with. The document keeps every other transaction's update for `Doc#edit`.
|
|
38
|
+
pub const REMOTE: &str = "yrby-remote";
|
|
39
|
+
|
|
40
|
+
/// True when `origin` marks a transaction that applied a peer's update.
|
|
41
|
+
pub fn is_remote(origin: Option<&yrs::Origin>) -> bool {
|
|
42
|
+
origin.is_some_and(|origin| origin.as_ref().starts_with(REMOTE.as_bytes()))
|
|
43
|
+
}
|
|
44
|
+
|
|
37
45
|
/// The largest integer a double represents exactly (2^53).
|
|
38
46
|
const MAX_SAFE_INTEGER: u64 = 1 << 53;
|
|
39
47
|
|
|
40
|
-
///
|
|
41
|
-
///
|
|
42
|
-
/// ones.
|
|
43
|
-
pub fn
|
|
48
|
+
/// An origin for a transaction that applies a peer's update, and a key no
|
|
49
|
+
/// other observer uses: yrs registers an observer under a key and removes it
|
|
50
|
+
/// by that key, so two observers on one document need different ones.
|
|
51
|
+
pub fn remote_key() -> yrs::Origin {
|
|
44
52
|
static NEXT: std::sync::atomic::AtomicU64 = std::sync::atomic::AtomicU64::new(0);
|
|
45
|
-
NEXT.fetch_add(1, std::sync::atomic::Ordering::Relaxed)
|
|
46
|
-
|
|
53
|
+
let n = NEXT.fetch_add(1, std::sync::atomic::Ordering::Relaxed);
|
|
54
|
+
format!("{REMOTE}:{n}").as_str().into()
|
|
47
55
|
}
|
|
48
56
|
|
|
49
57
|
/// The branch `id` names, if it exists and has not been deleted.
|
|
@@ -97,6 +105,17 @@ where
|
|
|
97
105
|
.map_err(yrb_error)
|
|
98
106
|
}
|
|
99
107
|
|
|
108
|
+
/// Run `f` in a write transaction under `ORIGIN`, as `guarded` runs its
|
|
109
|
+
/// closure. The document keeps the transaction's update for `Doc#edit` when
|
|
110
|
+
/// it commits (see `RbDoc::new`).
|
|
111
|
+
pub fn write<F, R>(doc: &Doc, f: F) -> Result<R, Error>
|
|
112
|
+
where
|
|
113
|
+
F: FnOnce(&mut TransactionMut) -> Result<R, String> + Send,
|
|
114
|
+
R: Send,
|
|
115
|
+
{
|
|
116
|
+
guarded(move || f(&mut doc.transact_mut_with(ORIGIN)))
|
|
117
|
+
}
|
|
118
|
+
|
|
100
119
|
// --- indexes ---
|
|
101
120
|
|
|
102
121
|
/// What `insert(index, ...)` means in a sequence of `len`, as in Ruby: a
|
data/ext/yrby/src/text.rs
CHANGED
|
@@ -17,7 +17,7 @@ use yrs::{Assoc, Doc, GetString, IndexedSequence, StickyIndex, Text, TextRef, Tr
|
|
|
17
17
|
use crate::nogvl;
|
|
18
18
|
use crate::shared::{
|
|
19
19
|
char_len, delete_span, end_or_units, guarded, identity, insert_index, resolve, to_chars,
|
|
20
|
-
to_units,
|
|
20
|
+
to_units, write, Position,
|
|
21
21
|
};
|
|
22
22
|
use crate::yrb_error;
|
|
23
23
|
|
|
@@ -84,11 +84,10 @@ impl RbText {
|
|
|
84
84
|
/// appends). Clamped into range.
|
|
85
85
|
fn insert_at(&self, index: i64, text: String) -> Result<(), Error> {
|
|
86
86
|
let (doc, id) = (&self.doc, &self.id);
|
|
87
|
-
|
|
88
|
-
let
|
|
89
|
-
let
|
|
90
|
-
|
|
91
|
-
t.insert(&mut txn, at, &text);
|
|
87
|
+
write(doc, move |txn| {
|
|
88
|
+
let t = resolve::<TextRef, _>(txn, id).ok_or("text no longer exists")?;
|
|
89
|
+
let at = end_or_units(txn, &t, index);
|
|
90
|
+
t.insert(txn, at, &text);
|
|
92
91
|
Ok(())
|
|
93
92
|
})
|
|
94
93
|
}
|
|
@@ -137,13 +136,12 @@ impl RbText {
|
|
|
137
136
|
/// negative index counts from the end, and the length stops at the end.
|
|
138
137
|
fn delete(&self, index: i64, length: i64) -> Result<(), Error> {
|
|
139
138
|
let (doc, id) = (&self.doc, &self.id);
|
|
140
|
-
|
|
141
|
-
let
|
|
142
|
-
let
|
|
143
|
-
|
|
144
|
-
let (from, to) = (to_units(&txn, &t, from), to_units(&txn, &t, to));
|
|
139
|
+
write(doc, move |txn| {
|
|
140
|
+
let t = resolve::<TextRef, _>(txn, id).ok_or("text no longer exists")?;
|
|
141
|
+
if let Some((from, to)) = delete_span(index, length, char_len(txn, &t)) {
|
|
142
|
+
let (from, to) = (to_units(txn, &t, from), to_units(txn, &t, to));
|
|
145
143
|
if to > from {
|
|
146
|
-
t.remove_range(
|
|
144
|
+
t.remove_range(txn, from, to - from);
|
|
147
145
|
}
|
|
148
146
|
}
|
|
149
147
|
Ok(())
|
|
@@ -152,12 +150,11 @@ impl RbText {
|
|
|
152
150
|
|
|
153
151
|
fn clear(&self) -> Result<(), Error> {
|
|
154
152
|
let (doc, id) = (&self.doc, &self.id);
|
|
155
|
-
|
|
156
|
-
let
|
|
157
|
-
|
|
158
|
-
let len = t.len(&txn);
|
|
153
|
+
write(doc, move |txn| {
|
|
154
|
+
if let Some(t) = resolve::<TextRef, _>(txn, id) {
|
|
155
|
+
let len = t.len(txn);
|
|
159
156
|
if len > 0 {
|
|
160
|
-
t.remove_range(
|
|
157
|
+
t.remove_range(txn, 0, len);
|
|
161
158
|
}
|
|
162
159
|
}
|
|
163
160
|
Ok(())
|