| 1 | use serde_json::{json, Value}; |
| 2 | use yrs::branch::BranchPtr; |
| 3 | use yrs::{Any, Array, ArrayRef, BranchID, Out, ReadTxn, Text, Xml, XmlFragment, XmlFragmentRef, XmlOut, XmlTextRef, ID}; |
| 4 | |
| 5 | pub fn node_id(node: &XmlOut) -> String { |
| 6 | serde_json::to_string(&node.id()).expect("branch identity serializes") |
| 7 | } |
| 8 | /// A node identity as `node_id` writes it. Anything else (another spelling, |
| 9 | /// a root) names no node, as when nodes were found by comparing strings. |
| 10 | pub fn nested_id(id: &str) -> Option<ID> { |
| 11 | let parsed: BranchID = serde_json::from_str(id).ok()?; |
| 12 | if serde_json::to_string(&parsed).ok()? != id { return None; } |
| 13 | match parsed { BranchID::Nested(id) => Some(id), BranchID::Root(_) => None } |
| 14 | } |
| 15 | pub fn branch(node: &XmlOut) -> BranchPtr { node.as_ptr() } |
| 16 | fn xml(value: Out) -> Option<XmlOut> { |
| 17 | match value { |
| 18 | Out::YXmlElement(element) => Some(XmlOut::Element(element)), |
| 19 | Out::YXmlText(text) => Some(XmlOut::Text(text)), |
| 20 | Out::YXmlFragment(fragment) => Some(XmlOut::Fragment(fragment)), |
| 21 | _ => None, |
| 22 | } |
| 23 | } |
| 24 | /// The live XML children of a fragment in order, each with the index |
| 25 | /// `XmlFragment::get` gives it (values that are not XML count, and are |
| 26 | /// skipped). One pass over the item list, where `get(i)` per child walks the |
| 27 | /// list from its start every time. |
| 28 | pub fn indexed_children<'a, T: ReadTxn>(fragment: &XmlFragmentRef, txn: &'a T) -> impl Iterator<Item = (u32, XmlOut)> + 'a { |
| 29 | let array: &ArrayRef = fragment.as_ref(); |
| 30 | array.iter(txn).enumerate().filter_map(|(index, value)| xml(value).map(|node| (index as u32, node))) |
| 31 | } |
| 32 | pub fn fragment_of(node: &XmlOut) -> Option<XmlFragmentRef> { |
| 33 | match node { |
| 34 | XmlOut::Element(element) => Some(AsRef::<XmlFragmentRef>::as_ref(element).clone()), |
| 35 | XmlOut::Fragment(fragment) => Some(fragment.clone()), |
| 36 | XmlOut::Text(_) => None, |
| 37 | } |
| 38 | } |
| 39 | pub fn children<T: ReadTxn>(root: &XmlFragmentRef, txn: &T) -> Vec<Value> { |
| 40 | indexed_children(root, txn).map(|(_, node)| project(&node, txn)).collect() |
| 41 | } |
| 42 | /// A text's runs, each exactly as long in UTF-16 as the text positions it |
| 43 | /// covers: the display is then the text's `len` (yrs' UTF-16 content length) |
| 44 | /// and a display offset is a yrs offset. Strings are themselves; an embed is |
| 45 | /// one U+FFFC. Content Yjs editors never put in a text (an embedded string or |
| 46 | /// array, JSON, binary) is shown as U+FFFC padding, or trimmed, so the length |
| 47 | /// still holds. |
| 48 | pub fn runs<T: ReadTxn>(text: &XmlTextRef, txn: &T) -> Vec<(String, Option<Box<yrs::types::Attrs>>)> { |
| 49 | let length = text.len(txn) as usize; |
| 50 | let mut total = 0usize; |
| 51 | let mut runs: Vec<(String, Option<Box<yrs::types::Attrs>>)> = text.diff(txn, |_| ()).into_iter().map(|run| { |
| 52 | let insert = match run.insert { Out::Any(Any::String(value)) => value.to_string(), _ => "\u{FFFC}".to_owned() }; |
| 53 | total += insert.encode_utf16().count(); |
| 54 | (insert, run.attributes) |
| 55 | }).collect(); |
| 56 | if total < length { runs.push(("\u{FFFC}".repeat(length - total), None)); } |
| 57 | while total > length { |
| 58 | let Some((last, _)) = runs.last_mut() else { break }; |
| 59 | let Some(ch) = last.pop() else { runs.pop(); continue }; |
| 60 | total -= ch.len_utf16(); |
| 61 | if total < length { last.push_str(&"\u{FFFC}".repeat(length - total)); total = length; } |
| 62 | if last.is_empty() { runs.pop(); } |
| 63 | } |
| 64 | runs |
| 65 | } |
| 66 | pub fn raw_text<T: ReadTxn>(text: &XmlTextRef, txn: &T) -> String { |
| 67 | runs(text, txn).into_iter().map(|(insert, _)| insert).collect() |
| 68 | } |
| 69 | pub fn project<T: ReadTxn>(node: &XmlOut, txn: &T) -> Value { |
| 70 | match node { |
| 71 | XmlOut::Text(text) => { |
| 72 | let runs: Vec<_> = runs(text, txn).into_iter().map(|(insert, marks)| json!({"insert": insert, "marks": marks})).collect(); |
| 73 | json!({"id": node_id(node), "type": "text", "runs": runs}) |
| 74 | }, |
| 75 | XmlOut::Element(element) => { |
| 76 | let attrs: serde_json::Map<String, Value> = element.attributes(txn) |
| 77 | .map(|(key,value)| (key.to_string(), Value::String(value))).collect(); |
| 78 | json!({"id": node_id(node), "type": element.tag().as_ref(), "attrs": attrs, "children": children(element.as_ref(), txn)}) |
| 79 | }, |
| 80 | XmlOut::Fragment(fragment) => json!({"id": node_id(node), "type": "fragment", "children": children(fragment, txn)}), |
| 81 | } |
| 82 | } |
| 83 | /// A live node reachable from `root` through children, with its parent and |
| 84 | /// its index there: what a depth-first search comparing every node's |
| 85 | /// `node_id` used to find, looked up by identity and checked upwards. |
| 86 | pub fn locate<T: ReadTxn>(root: &XmlFragmentRef, txn: &T, id: &str) -> Option<(XmlOut, XmlFragmentRef, u32)> { |
| 87 | let branch = BranchID::get_nested(txn, &nested_id(id)?)?; |
| 88 | resolve(root, txn, branch) |
| 89 | } |
| 90 | pub fn locate_branch<T: ReadTxn>(root: &XmlFragmentRef, txn: &T, branch: BranchPtr) -> Option<(XmlOut, XmlFragmentRef, u32)> { |
| 91 | resolve(root, txn, branch) |
| 92 | } |
| 93 | fn resolve<T: ReadTxn>(root: &XmlFragmentRef, txn: &T, branch: BranchPtr) -> Option<(XmlOut, XmlFragmentRef, u32)> { |
| 94 | let node = XmlOut::try_from(branch).ok()?; |
| 95 | if branch.is_deleted() { return None; } |
| 96 | let parent = match &node { |
| 97 | XmlOut::Element(element) => element.parent(), |
| 98 | XmlOut::Text(text) => text.parent(), |
| 99 | XmlOut::Fragment(fragment) => fragment.parent(), |
| 100 | }?; |
| 101 | let container = fragment_of(&parent)?; |
| 102 | // Being some child's parent is not enough: the node must be one of its |
| 103 | // live children (not, say, an attribute value), and so must each ancestor. |
| 104 | let index = indexed_children(&container, txn).find(|(_, child)| branch_eq(child.as_ptr(), branch)).map(|(index, _)| index)?; |
| 105 | let container_branch = parent.as_ptr(); |
| 106 | if !branch_eq(container_branch, fragment_ptr(root)) { resolve(root, txn, container_branch)?; } |
| 107 | Some((node, container, index)) |
| 108 | } |
| 109 | pub fn branch_eq(a: BranchPtr, b: BranchPtr) -> bool { a == b } |
| 110 | pub fn find<T: ReadTxn>(root: &XmlFragmentRef, txn: &T, id: &str) -> Option<XmlOut> { |
| 111 | locate(root, txn, id).map(|(node, _, _)| node) |
| 112 | } |
| 113 | pub fn fragment_ptr(fragment: &XmlFragmentRef) -> BranchPtr { BranchPtr::from(AsRef::<yrs::branch::Branch>::as_ref(fragment)) } |
| 114 | |