oficina / docs Public

Clone
git clone https://amadan.net/oficina/docs

Plain git — no account needed to clone.

Download

Download this file

1//! Resolve optimistic native UTF-16 display positions against their own source
2//! generation, never against an authority which may already include peer edits.
3//!
4//! The display is the projection rendered as text: a text node is its
5//! content, an inline atom (hard break, image) is one position and a rule two,
6//! and a paragraph, heading or code block ends with one. Positions are mapped
7//! by walking the document tree with each text's stored length, not by
8//! building the projection: no JSON and no string copies.
9use crate::{operations, projection, structure};
10use serde_json::{json, Value};
11use yrs::branch::BranchPtr;
12use yrs::{Doc, ReadTxn, Text, Transact, XmlFragmentRef, XmlOut};
13
14/// Visit the display spans in document order: `visit(node, start, length,
15/// atomic)`, returning true to stop. A text is one span; an inline atom is a
16/// one-position atomic span; an empty paragraph, heading or code block is a
17/// zero-length span of its own.
18fn walk<T: ReadTxn>(fragment: &XmlFragmentRef, txn: &T, offset: &mut u32, visit: &mut dyn FnMut(&XmlOut, u32, u32, bool) -> bool) -> bool {
19 for (_, child) in projection::indexed_children(fragment, txn) {
20 if walk_node(&child, txn, offset, visit) { return true; }
21 }
22 false
23}
24fn walk_node<T: ReadTxn>(node: &XmlOut, txn: &T, offset: &mut u32, visit: &mut dyn FnMut(&XmlOut, u32, u32, bool) -> bool) -> bool {
25 match node {
26 XmlOut::Text(text) => {
27 let length = text.len(txn);
28 if visit(node, *offset, length, false) { return true; }
29 *offset += length;
30 false
31 },
32 XmlOut::Element(element) => {
33 let tag = element.tag();
34 match tag.as_ref() {
35 // An element named "text" projects as a text with no runs.
36 "text" => visit(node, *offset, 0, false),
37 "hard_break" | "image" | "horizontal_rule" => {
38 if visit(node, *offset, 1, true) { return true; }
39 *offset += if tag.as_ref() == "horizontal_rule" { 2 } else { 1 };
40 false
41 },
42 tag => {
43 let start = *offset;
44 if walk(element.as_ref(), txn, offset, visit) { return true; }
45 if ["paragraph", "heading", "code_block"].contains(&tag) {
46 if *offset == start && visit(node, start, 0, false) { return true; }
47 *offset += 1;
48 }
49 false
50 },
51 }
52 },
53 XmlOut::Fragment(fragment) => walk(fragment, txn, offset, visit),
54 }
55}
56fn root(doc: &Doc) -> XmlFragmentRef { doc.get_or_insert_xml_fragment("prosemirror") }
57/// The whole display's length, including the final block's terminator.
58pub(crate) fn display_length<T: ReadTxn>(root: &XmlFragmentRef, txn: &T) -> u32 {
59 let mut offset = 0;
60 walk(root, txn, &mut offset, &mut |_, _, _, _| false);
61 offset
62}
63/// The span containing [at, at + length]: the first text (or empty block)
64/// that does, else the first inline atom that does.
65fn span<T: ReadTxn>(root: &XmlFragmentRef, txn: &T, at: u32, end: u32) -> Option<(XmlOut, u32)> {
66 let mut text = None;
67 let mut atom = None;
68 walk(root, txn, &mut 0, &mut |node, start, length, atomic| {
69 // Spans start in order, so none after this one can contain `at`.
70 if start > at { return true; }
71 if end <= start + length {
72 if !atomic { text = Some((node.clone(), start)); return true; }
73 if atom.is_none() { atom = Some((node.clone(), start)); }
74 }
75 false
76 });
77 text.or(atom)
78}
79pub(crate) fn locate(doc: &Doc, at: u32, length: u32) -> Result<(String,u32), &'static str> {
80 let end = at.checked_add(length).ok_or("invalid_range")?;
81 let root = root(doc);
82 let txn = doc.transact();
83 span(&root, &txn, at, end).map(|(node, start)| (projection::node_id(&node), at - start)).ok_or("unsupported_range")
84}
85fn endpoint(doc: &Doc, at: u32) -> Result<(String,u32), &'static str> {
86 use yrs::{XmlFragment, XmlTextPrelim};
87 let (id, local) = locate(doc,at,0)?;
88 let root = doc.get_or_insert_xml_fragment("prosemirror");
89 let mut txn = doc.transact_mut_with("native-edit");
90 let inline_atom = projection::find(&root,&txn,&id).and_then(yrs::XmlOut::into_xml_element)
91 .is_some_and(|e| ["image","hard_break"].contains(&e.tag().as_ref()));
92 if inline_atom {
93 let (parent,index) = structure::parent(&root,&txn,&id).ok_or("missing_parent")?;
94 let text = parent.insert(&mut txn,index + if local == 1 { 1 } else { 0 },XmlTextPrelim::new(""));
95 return Ok((projection::node_id(&yrs::XmlOut::Text(text)),0));
96 }
97 Ok((id,local))
98}
99pub fn execute(doc: &Doc, request: &Value) -> Result<(), &'static str> {
100 let at = request["at"].as_u64().and_then(|v| u32::try_from(v).ok()).ok_or("invalid_range")?;
101 let mut length = request["length"].as_u64().and_then(|v| u32::try_from(v).ok()).ok_or("invalid_range")?;
102 let root = root(doc);
103 let display_length = display_length(&root, &doc.transact());
104 let end = at.checked_add(length).ok_or("invalid_range")?;
105 if end > display_length { return Err("invalid_range"); }
106 // The final native paragraph terminator is presentation, not user content.
107 if length > 0 && end == display_length { length -= 1; }
108 let text = request["text"].as_str().ok_or("invalid_command")?;
109 let (node, local) = match locate(doc, at, length) {
110 Ok(value) => value,
111 Err(_) if length > 0 => {
112 let (start, local) = endpoint(doc, at)?;
113 let (end, end_at) = endpoint(doc, at.checked_add(length).ok_or("invalid_range")?)?;
114 structure::execute(doc, &json!({"op":"join_range","node":start,"at":local,"end_node":end,"end_at":end_at}))?;
115 return execute(doc, &json!({"op":"display_edit","at":at,"length":0,"text":text,"marks":request["marks"]}));
116 },
117 Err(error) => return Err(error),
118 };
119 let atom = projection::find(&root,&doc.transact(),&node).and_then(yrs::XmlOut::into_xml_element)
120 .filter(|element| ["image","hard_break","horizontal_rule"].contains(&element.tag().as_ref()));
121 if let Some(atom) = atom {
122 use yrs::{XmlFragment, XmlElementPrelim, XmlTextPrelim};
123 if local > 1 || length > 1 || (length == 1 && local != 0) { return Err("invalid_range"); }
124 let mut txn = doc.transact_mut_with("native-edit");
125 let (parent,index) = structure::parent(&root,&txn,&node).ok_or("missing_parent")?;
126 if atom.tag().as_ref() == "horizontal_rule" {
127 if length != 1 { return Err("unsupported_range"); }
128 parent.remove(&mut txn,index);
129 parent.insert(&mut txn,index,XmlElementPrelim::new("paragraph",[XmlTextPrelim::new("").into()]));
130 } else {
131 if length == 1 { parent.remove(&mut txn,index); }
132 parent.insert(&mut txn,index + if local == 1 { 1 } else { 0 },XmlTextPrelim::new(""));
133 }
134 drop(txn);
135 return execute(doc,&json!({"op":"display_edit","at":at,"length":0,"text":text,"marks":request["marks"]}));
136 }
137 let is_code = {
138 let txn = doc.transact();
139 let block = match projection::find(&root,&txn,&node) {
140 Some(yrs::XmlOut::Element(element)) => Some(element),
141 Some(yrs::XmlOut::Text(_)) => structure::parent(&root,&txn,&node).and_then(|(parent,_)| projection::find(&root,&txn,&projection::node_id(&yrs::XmlOut::Fragment(parent))).and_then(yrs::XmlOut::into_xml_element)),
142 _ => None,
143 };
144 block.is_some_and(|block| block.tag().as_ref() == "code_block")
145 };
146 if is_code { return operations::execute(doc, &json!({"op":"replace_text","node":node,"at":local,"length":length,"text":text.replace('\u{2028}',"\n"),"marks":request["marks"]})); }
147 let mut parts = text.split(['\n', '\u{2028}']);
148 let first = parts.next().unwrap_or("");
149 operations::execute(doc, &json!({"op":"replace_text","node":node,"at":local,"length":length,"text":first,"marks":request["marks"]}))?;
150 let mut cursor = at + first.encode_utf16().count() as u32;
151 for (separator, part) in text.chars().filter(|c| *c == '\n' || *c == '\u{2028}').zip(parts) {
152 let (node, local) = locate(doc, cursor, 0)?;
153 let op = if separator == '\n' { "split" } else { "hard_break" };
154 structure::execute(doc, &json!({"op":op,"node":node,"at":local}))?;
155 cursor += 1;
156 let (node, local) = locate(doc, cursor, 0)?;
157 operations::execute(doc, &json!({"op":"replace_text","node":node,"at":local,"length":0,"text":part,"marks":request["marks"]}))?;
158 cursor += part.encode_utf16().count() as u32;
159 }
160 Ok(())
161}
162
163pub fn anchor(doc: &Doc, at: u32) -> Result<Value, &'static str> {
164 use yrs::{Assoc, IndexedSequence, Text, XmlOut};
165 let Ok((id, local)) = locate(doc, at, 0) else { return Ok(json!({"fallback":at})); };
166 let root = doc.get_or_insert_xml_fragment("prosemirror");
167 let mut txn = doc.transact_mut_with("selection");
168 match projection::find(&root, &txn, &id).ok_or("missing_node")? {
169 XmlOut::Text(text) => {
170 let assoc = if local == text.len(&txn) { Assoc::Before } else { Assoc::After };
171 let sticky = text.sticky_index(&mut txn, local, assoc).unwrap_or_else(|| yrs::StickyIndex::from_type(&txn,&text,Assoc::After));
172 Ok(json!({"node":id,"sticky":sticky,"fallback":at}))
173 },
174 _ => Ok(json!({"node":id,"offset":local,"fallback":at})),
175 }
176}
177pub fn resolve(doc: &Doc, anchor: &Value) -> Result<u32, &'static str> {
178 let root = root(doc);
179 let txn = doc.transact();
180 let local = if anchor["sticky"].is_null() { anchor["offset"].as_u64().unwrap_or(0) as u32 } else {
181 let sticky: yrs::StickyIndex = serde_json::from_value(anchor["sticky"].clone()).map_err(|_| "invalid_anchor")?;
182 sticky.get_offset(&txn).map(|value| value.index).unwrap_or(0)
183 };
184 let target: Option<BranchPtr> = anchor["node"].as_str().and_then(projection::nested_id).and_then(|id| yrs::BranchID::get_nested(&txn, &id));
185 if let Some(target) = target {
186 let mut found = None;
187 walk(&root, &txn, &mut 0, &mut |node, start, length, _| {
188 if projection::branch_eq(node.as_ptr(), target) { found = Some(start + local.min(length)); true } else { false }
189 });
190 if let Some(found) = found { return Ok(found); }
191 }
192 Ok((anchor["fallback"].as_u64().unwrap_or(0) as u32).min(display_length(&root, &txn).saturating_sub(1)))
193}
194/// The identities of the leaf blocks (paragraph, heading, code block, rule)
195/// in document order.
196pub(crate) fn leaf_blocks<T: ReadTxn>(fragment: &XmlFragmentRef, txn: &T, ids: &mut Vec<BranchPtr>) {
197 for (_, child) in projection::indexed_children(fragment, txn) {
198 match &child {
199 XmlOut::Element(element) if ["paragraph", "heading", "code_block", "horizontal_rule"].contains(&element.tag().as_ref()) => ids.push(child.as_ptr()),
200 XmlOut::Element(element) => leaf_blocks(element.as_ref(), txn, ids),
201 XmlOut::Fragment(fragment) => leaf_blocks(fragment, txn, ids),
202 XmlOut::Text(_) => {},
203 }
204 }
205}
206