oficina / docs Public

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

Plain git — no account needed to clone.

Download

Download this file

1use crate::projection;
2use serde_json::Value;
3use yrs::{Any, Doc, In, ReadTxn, Text, Transact, XmlElementPrelim, XmlFragment, XmlFragmentRef, XmlOut, XmlTextPrelim};
4use yrs::types::{AsPrelim, Delta};
5use yrs::types::xml::{XmlDeltaPrelim, XmlIn};
6
7pub(crate) fn parent<T: ReadTxn>(root: &XmlFragmentRef, txn: &T, id: &str) -> Option<(XmlFragmentRef, u32)> {
8 projection::locate(root, txn, id).map(|(_, parent, index)| (parent, index))
9}
10fn number(value: &Value) -> Result<u32, &'static str> { value.as_u64().and_then(|v| v.try_into().ok()).ok_or("invalid_range") }
11fn slice(text: &str, from: u32) -> Result<String, &'static str> {
12 let units: Vec<_> = text.encode_utf16().collect();
13 if from as usize > units.len() { return Err("invalid_range"); }
14 String::from_utf16(&units[from as usize..]).map_err(|_| "invalid_range")
15}
16fn clean_empty_containers(root: &XmlFragmentRef, txn: &mut yrs::TransactionMut) {
17 for index in (0..root.len(txn)).rev() {
18 if let Some(XmlOut::Element(element)) = root.get(txn,index) {
19 clean_empty_containers(element.as_ref(),txn);
20 if ["bullet_list","ordered_list","list_item","blockquote"].contains(&element.tag().as_ref()) && element.len(txn) == 0 { root.remove(txn,index); }
21 }
22 }
23}
24// Keep every prefix node in place. Only the lifted block and following tails
25// need new identities, so a range can safely lift its blocks from last to first.
26fn unwrap_quote(root: &XmlFragmentRef, txn: &mut yrs::TransactionMut, node: &yrs::XmlElementRef) -> Result<bool, &'static str> {
27 let mut current = projection::node_id(&XmlOut::Element(node.clone()));
28 let mut path = Vec::new();
29 loop {
30 let Some((container, index)) = parent(root, txn, &current) else { return Ok(false); };
31 current = projection::node_id(&XmlOut::Fragment(container));
32 let Some(XmlOut::Element(element)) = projection::find(root, txn, &current) else { return Ok(false); };
33 let is_quote = element.tag().as_ref() == "blockquote";
34 path.push((element, index));
35 if is_quote { break; }
36 }
37 let selected = node.as_prelim(txn);
38 let (quote_parent, quote_index) = parent(root, txn, &current).ok_or("missing_parent")?;
39 let quote = path.last().ok_or("missing_parent")?.0.clone();
40 let mut tail: Option<XmlElementPrelim> = None;
41 for (depth, (container, index)) in path.into_iter().enumerate() {
42 let mut following = container.as_prelim(txn);
43 following.children.clear();
44 if let Some(tail) = tail.take() { following.children.push(tail.into()); }
45 for offset in index + 1..container.len(txn) {
46 if let Some(XmlOut::Element(element)) = container.get(txn, offset) { following.children.push(element.as_prelim(txn).into()); }
47 }
48 let remove_child = depth == 0 || container.get(txn, index).and_then(XmlOut::into_xml_element).is_some_and(|child| child.len(txn) == 0);
49 let remove_from = index + u32::from(!remove_child);
50 let remove_count = container.len(txn) - remove_from;
51 if remove_count > 0 { container.remove_range(txn, remove_from, remove_count); }
52 if !following.children.is_empty() { tail = Some(following); }
53 }
54 quote_parent.insert(txn, quote_index + 1, selected);
55 if let Some(tail) = tail { quote_parent.insert(txn, quote_index + 2, tail); }
56 if quote.len(txn) == 0 { quote_parent.remove(txn, quote_index); }
57 Ok(true)
58}
59pub fn execute(doc: &Doc, request: &Value) -> Result<(), &'static str> {
60 let root = doc.get_or_insert_xml_fragment("prosemirror");
61 let id = request["node"].as_str().ok_or("missing_node")?;
62 let mut txn = doc.transact_mut_with("native-edit");
63 let node = projection::find(&root, &txn, id).ok_or("missing_node")?;
64 match request["op"].as_str() {
65 Some("join_range") => {
66 let start_text = match node {
67 XmlOut::Text(text) => text,
68 XmlOut::Element(element) if element.len(&txn) == 0 => element.insert(&mut txn,0,XmlTextPrelim::new("")),
69 _ => return Err("not_text"),
70 };
71 let end_id = request["end_node"].as_str().ok_or("missing_node")?;
72 let end_text = match projection::find(&root, &txn, end_id) {
73 Some(XmlOut::Text(text)) => text,
74 Some(XmlOut::Element(element)) if element.len(&txn) == 0 => element.insert(&mut txn,0,XmlTextPrelim::new("")),
75 _ => return Err("not_text"),
76 };
77 let start_at = number(&request["at"])?;
78 let end_at = number(&request["end_at"])?;
79 let (start_parent, start_index) = parent(&root, &txn, &projection::node_id(&XmlOut::Text(start_text.clone()))).ok_or("missing_parent")?;
80 let (end_parent, end_index) = parent(&root, &txn, &projection::node_id(&XmlOut::Text(end_text.clone()))).ok_or("missing_parent")?;
81 let start_block = projection::fragment_ptr(&start_parent);
82 let end_block = projection::fragment_ptr(&end_parent);
83 let mut blocks = Vec::new();
84 crate::display::leaf_blocks(&root, &txn, &mut blocks);
85 let first = blocks.iter().position(|v| *v == start_block).ok_or("missing_node")?;
86 let last = blocks.iter().position(|v| *v == end_block).ok_or("missing_node")?;
87 if first > last { return Err("invalid_range"); }
88 let raw: String = start_text.diff(&txn, |_| ()).iter().map(|r| r.insert.clone().to_string(&txn)).collect();
89 slice(&raw, start_at)?;
90 let mut remaining = end_at;
91 let mut delta = Vec::new();
92 for diff in end_text.diff(&txn, |_| ()) {
93 let raw = diff.insert.to_string(&txn);
94 let length = raw.encode_utf16().count() as u32;
95 if remaining > length { remaining -= length; continue; }
96 let suffix = slice(&raw, remaining)?; remaining = 0;
97 if !suffix.is_empty() { delta.push(Delta::Inserted(In::Any(Any::from(suffix)), diff.attributes)); }
98 }
99 if remaining > 0 || start_at > start_text.len(&txn) || end_at > end_text.len(&txn) { return Err("invalid_range"); }
100 let mut trailing = vec![XmlIn::Text(XmlDeltaPrelim { attributes: Default::default(), delta })];
101 for index in end_index + 1..end_parent.len(&txn) {
102 trailing.push(match end_parent.get(&txn,index).ok_or("missing_node")? { XmlOut::Element(e) => e.as_prelim(&txn).into(), XmlOut::Text(t) => t.as_prelim(&txn).into(), XmlOut::Fragment(f) => XmlIn::Fragment(f.as_prelim(&txn)) });
103 }
104 let tail = start_text.len(&txn) - start_at;
105 start_text.remove_range(&mut txn, start_at, tail);
106 let count = start_parent.len(&txn) - start_index - 1;
107 if count > 0 { start_parent.remove_range(&mut txn, start_index + 1, count); }
108 for (offset, child) in trailing.into_iter().enumerate() { start_parent.insert(&mut txn, start_index + 1 + offset as u32, child); }
109 for block in &blocks[first + 1..=last] {
110 let (_, parent, index) = projection::locate_branch(&root, &txn, *block).ok_or("missing_parent")?;
111 parent.remove(&mut txn, index);
112 }
113 clean_empty_containers(&root,&mut txn);
114 },
115 Some("block") => {
116 let XmlOut::Element(element) = node else { return Err("not_element"); };
117 let (parent, index) = parent(&root, &txn, id).ok_or("missing_parent")?;
118 let tag = request["type"].as_str().ok_or("invalid_type")?;
119 if tag == "blockquote" && unwrap_quote(&root, &mut txn, &element)? { return Ok(()); }
120 let mut copy = element.as_prelim(&txn);
121 if ["paragraph", "heading", "code_block"].contains(&tag) {
122 copy.tag = tag.into();
123 if tag == "heading" { copy.attributes.insert("level".into(), number(&request["level"])?.clamp(1,6).to_string()); }
124 else { copy.attributes.remove("level"); }
125 } else if ["bullet_list", "ordered_list"].contains(&tag) {
126 copy = XmlElementPrelim::new(tag, [XmlElementPrelim::new("list_item", [XmlIn::Element(copy)]).into()]);
127 } else if tag == "blockquote" { copy = XmlElementPrelim::new(tag, [XmlIn::Element(copy)]); }
128 else { return Err("invalid_type"); }
129 parent.remove(&mut txn, index);
130 parent.insert(&mut txn, index, copy);
131 },
132 Some("split") | Some("hard_break") => {
133 let text = match node {
134 XmlOut::Text(text) => text,
135 XmlOut::Element(element) if element.len(&txn) == 0 => element.insert(&mut txn, 0, XmlTextPrelim::new("")),
136 XmlOut::Element(element) => match element.get(&txn, 0) { Some(XmlOut::Text(text)) => text, _ => return Err("not_text") },
137 _ => return Err("not_text"),
138 };
139 let text_id = projection::node_id(&XmlOut::Text(text.clone()));
140 let at = number(&request["at"])?;
141 let (block_fragment, text_index) = parent(&root, &txn, &text_id).ok_or("missing_parent")?;
142 let block_id = projection::node_id(&XmlOut::Fragment(block_fragment.clone()));
143 let (container, block_index) = parent(&root, &txn, &block_id).ok_or("missing_parent")?;
144 let Some(XmlOut::Element(block)) = container.get(&txn, block_index) else { return Err("not_block"); };
145 let mut remaining = at;
146 let mut delta = Vec::new();
147 for diff in text.diff(&txn, |_| ()) {
148 let raw = diff.insert.to_string(&txn);
149 let length = raw.encode_utf16().count() as u32;
150 if remaining > length { remaining -= length; continue; }
151 let suffix = slice(&raw, remaining)?; remaining = 0;
152 if !suffix.is_empty() { delta.push(Delta::Inserted(In::Any(Any::from(suffix)), diff.attributes)); }
153 }
154 if remaining > 0 || at > text.len(&txn) { return Err("invalid_range"); }
155 let suffix = XmlDeltaPrelim { attributes: Default::default(), delta };
156 let mut copy = block.as_prelim(&txn);
157 copy.children = vec![XmlIn::Text(suffix)];
158 for index in text_index + 1..block.len(&txn) {
159 copy.children.push(match block.get(&txn,index).ok_or("missing_node")? { XmlOut::Element(e) => e.as_prelim(&txn).into(), XmlOut::Text(t) => t.as_prelim(&txn).into(), XmlOut::Fragment(f) => XmlIn::Fragment(f.as_prelim(&txn)) });
160 }
161 let tail = text.len(&txn) - at;
162 if tail == 0 && block.tag().as_ref() == "heading" { copy.tag = "paragraph".into(); copy.attributes.remove("level"); }
163 text.remove_range(&mut txn, at, tail);
164 let extra = block.len(&txn) - text_index - 1;
165 if extra > 0 { block.remove_range(&mut txn, text_index + 1, extra); }
166 if request["op"] == "hard_break" {
167 block.insert(&mut txn,text_index+1,XmlElementPrelim::empty("hard_break"));
168 for (offset, child) in copy.children.into_iter().enumerate() { block.insert(&mut txn,text_index+2+offset as u32,child); }
169 return Ok(());
170 }
171 let container_id = projection::node_id(&XmlOut::Fragment(container.clone()));
172 let list_item = projection::find(&root, &txn, &container_id)
173 .and_then(|node| node.into_xml_element()).filter(|e| e.tag().as_ref() == "list_item");
174 if let Some(item) = list_item.filter(|_| request["inside"] != true) {
175 let (list, item_index) = parent(&root, &txn, &container_id).ok_or("missing_parent")?;
176 let mut item_copy = XmlElementPrelim::new("list_item", [XmlIn::Element(copy)]);
177 for index in block_index + 1..item.len(&txn) {
178 item_copy.children.push(match item.get(&txn,index).ok_or("missing_node")? { XmlOut::Element(e) => e.as_prelim(&txn).into(), XmlOut::Text(t) => t.as_prelim(&txn).into(), XmlOut::Fragment(f) => XmlIn::Fragment(f.as_prelim(&txn)) });
179 }
180 let count = item.len(&txn) - block_index - 1;
181 if count > 0 { item.remove_range(&mut txn, block_index + 1, count); }
182 list.insert(&mut txn, item_index + 1, item_copy);
183 } else { container.insert(&mut txn, block_index + 1, copy); }
184 },
185 _ => return Err("unknown_command"),
186 }
187 Ok(())
188}
189