| 1 | //! Large, realistically edited documents for the engine tests, built with |
| 2 | //! yrs directly (the same shape as fixtures/generate-large-doc.mjs): a page is |
| 3 | //! five ~560-character paragraphs with bold and italic runs, a level-2 |
| 4 | //! heading every second page and a five-item bullet list every fifth. `edits` |
| 5 | //! then applies that many small concurrent edits from twenty clients, synced |
| 6 | //! in rounds, so the document carries real tombstones and fragmentation. |
| 7 | #![allow(dead_code)] |
| 8 | use serde_json::Value; |
| 9 | use yrs::types::xml::{XmlDeltaPrelim, XmlIn}; |
| 10 | use yrs::types::Delta; |
| 11 | use yrs::{Any, Doc, In, OffsetKind, Options, ReadTxn, StateVector, Text, Transact, Update, XmlElementPrelim, XmlFragment, XmlOut, XmlTextRef}; |
| 12 | use yrs::updates::decoder::Decode; |
| 13 | |
| 14 | pub struct Random(u64); |
| 15 | impl Random { |
| 16 | pub fn new(seed: u64) -> Self { Random(seed.wrapping_mul(6364136223846793005).wrapping_add(1442695040888963407)) } |
| 17 | pub fn next(&mut self) -> u64 { |
| 18 | self.0 = self.0.wrapping_mul(6364136223846793005).wrapping_add(1442695040888963407); |
| 19 | let mut x = self.0; x ^= x >> 33; x = x.wrapping_mul(0xff51afd7ed558ccd); x ^= x >> 33; x |
| 20 | } |
| 21 | pub fn below(&mut self, n: u64) -> u64 { if n == 0 { 0 } else { self.next() % n } } |
| 22 | } |
| 23 | const WORDS: &[&str] = &["the","of","and","to","in","is","that","for","it","as","was","with","be","by","on","not","this","are","or","from","at","which","but","have","an","they","you","were","there","would","their","we","been","has","when","who","will","more","if","out","so","up","what","about","than","into","them","can","only","other","time","new","some","could","these","two","may","first","then","any","like","now","over","such","our","even","most","made","after","also","many","before","must","well","back","through","years","much","where","your","way","down","should","because","each","just","those","people","how","too","little","state","good","very","make","world","still","own","work","long","here","both","between","life","being","under","never","day","same","another","know","while","last","might","great","old","year","come","since","against","right","used","take","three","naïve","café","😀"]; |
| 24 | fn sentence(random: &mut Random) -> String { |
| 25 | let n = 8 + random.below(14) as usize; |
| 26 | let mut words: Vec<String> = (0..n).map(|_| WORDS[random.below(WORDS.len() as u64) as usize].to_owned()).collect(); |
| 27 | let first: String = words[0].chars().take(1).flat_map(char::to_uppercase).chain(words[0].chars().skip(1)).collect(); |
| 28 | words[0] = first; |
| 29 | words.join(" ") + "." |
| 30 | } |
| 31 | fn paragraph_text(random: &mut Random) -> String { |
| 32 | let mut text = String::new(); |
| 33 | while text.chars().count() < 560 { if !text.is_empty() { text.push(' '); } text += &sentence(random); } |
| 34 | text |
| 35 | } |
| 36 | fn run(text: &str, mark: Option<&str>) -> Delta<In> { |
| 37 | let attrs = mark.map(|m| Box::new([(m.into(), Any::Map(Default::default()))].into_iter().collect())); |
| 38 | Delta::Inserted(In::Any(Any::from(text)), attrs) |
| 39 | } |
| 40 | fn text(delta: Vec<Delta<In>>) -> XmlIn { XmlIn::Text(XmlDeltaPrelim { attributes: Default::default(), delta }) } |
| 41 | fn rich_paragraph(random: &mut Random) -> XmlElementPrelim { |
| 42 | let words = paragraph_text(random); |
| 43 | let chars: Vec<char> = words.chars().collect(); |
| 44 | if random.below(10) < 3 { return XmlElementPrelim::new("paragraph", [text(vec![run(&words, None)])]); } |
| 45 | let len = chars.len(); |
| 46 | let a = random.below((len - 80) as u64) as usize; let b = a + 10 + random.below(30) as usize; |
| 47 | let c = (b + 20 + random.below(40) as usize).min(len - 1); let d = (c + 5 + random.below(20) as usize).min(len); |
| 48 | let slice = |from: usize, to: usize| chars[from..to].iter().collect::<String>(); |
| 49 | let mut delta = Vec::new(); |
| 50 | for (from, to, mark) in [(0, a, None), (a, b, Some("strong")), (b, c, None), (c, d, Some("em")), (d, len, None)] { |
| 51 | if to > from { delta.push(run(&slice(from, to), mark)); } |
| 52 | } |
| 53 | XmlElementPrelim::new("paragraph", [text(delta)]) |
| 54 | } |
| 55 | fn options(client: u64) -> Options { |
| 56 | let mut options = Options::with_guid_and_client_id("large-document".into(), client); |
| 57 | options.offset_kind = OffsetKind::Utf16; |
| 58 | options |
| 59 | } |
| 60 | fn texts<T: ReadTxn>(fragment: &impl XmlFragment, txn: &T, out: &mut Vec<XmlTextRef>) { |
| 61 | for child in fragment.children(txn) { |
| 62 | match child { |
| 63 | XmlOut::Text(t) => out.push(t), |
| 64 | XmlOut::Element(e) => texts(&e, txn, out), |
| 65 | XmlOut::Fragment(f) => texts(&f, txn, out), |
| 66 | } |
| 67 | } |
| 68 | } |
| 69 | /// A Yjs v1 update holding the whole document. |
| 70 | pub fn generate(pages: usize, edits: usize, seed: u64) -> Vec<u8> { |
| 71 | let mut random = Random::new(seed); |
| 72 | let author = Doc::with_options(options(7_000)); |
| 73 | let root = author.get_or_insert_xml_fragment("prosemirror"); |
| 74 | { |
| 75 | let mut txn = author.transact_mut(); |
| 76 | let mut index = 0; |
| 77 | for page in 0..pages { |
| 78 | if page % 2 == 0 { |
| 79 | let mut heading = XmlElementPrelim::new("heading", [text(vec![run(&format!("Section {}: {}", page / 2 + 1, sentence(&mut random).chars().take(40).collect::<String>()), None)])]); |
| 80 | heading.attributes.insert("level".into(), "2".into()); |
| 81 | root.insert(&mut txn, index, heading); index += 1; |
| 82 | } |
| 83 | for _ in 0..5 { root.insert(&mut txn, index, rich_paragraph(&mut random)); index += 1; } |
| 84 | if page % 5 == 4 { |
| 85 | let items: Vec<XmlIn> = (0..5).map(|_| XmlIn::Element(XmlElementPrelim::new("list_item", [XmlIn::Element(XmlElementPrelim::new("paragraph", [text(vec![run(&sentence(&mut random), None)])]))]))).collect(); |
| 86 | root.insert(&mut txn, index, XmlElementPrelim::new("bullet_list", items)); index += 1; |
| 87 | } |
| 88 | } |
| 89 | } |
| 90 | let base = author.transact().encode_state_as_update_v1(&StateVector::default()); |
| 91 | if edits == 0 { return base; } |
| 92 | let clients: Vec<Doc> = (0..20).map(|i| { |
| 93 | let doc = Doc::with_options(options(7_001 + i)); |
| 94 | doc.transact_mut().apply_update(Update::decode_v1(&base).unwrap()).unwrap(); |
| 95 | doc |
| 96 | }).collect(); |
| 97 | let mut done = 0; |
| 98 | while done < edits { |
| 99 | let mut round = Vec::new(); |
| 100 | for doc in &clients { |
| 101 | if done == edits { break; } |
| 102 | let before = doc.transact().state_vector(); |
| 103 | { |
| 104 | let fragment = doc.get_or_insert_xml_fragment("prosemirror"); |
| 105 | let mut all = Vec::new(); |
| 106 | texts(&fragment, &doc.transact(), &mut all); |
| 107 | let mut txn = doc.transact_mut(); |
| 108 | let target = &all[random.below(all.len() as u64) as usize]; |
| 109 | let content: String = target.diff(&txn, |_| ()).iter().map(|d| d.insert.clone().to_string(&txn)).collect(); |
| 110 | let units: Vec<u16> = content.encode_utf16().collect(); |
| 111 | let at = random.below(units.len() as u64 + 1) as u32; |
| 112 | let boundary = |at: u32| at as usize >= units.len() || !(0xDC00..0xE000).contains(&units[at as usize]); |
| 113 | if !boundary(at) { continue; } |
| 114 | if random.below(3) == 0 && units.len() > 4 { |
| 115 | let mut length = 1 + random.below(4) as u32; |
| 116 | while at + length > units.len() as u32 || !boundary(at + length) { if length == 0 { break; } length -= 1; } |
| 117 | if length > 0 { target.remove_range(&mut txn, at, length); } |
| 118 | } else { |
| 119 | let insert: String = (0..1 + random.below(8)).map(|_| (b'a' + random.below(26) as u8) as char).collect(); |
| 120 | target.insert(&mut txn, at, &insert); |
| 121 | } |
| 122 | } |
| 123 | round.push(doc.transact().encode_state_as_update_v1(&before)); |
| 124 | done += 1; |
| 125 | } |
| 126 | for doc in &clients { |
| 127 | let mut txn = doc.transact_mut(); |
| 128 | for update in &round { txn.apply_update(Update::decode_v1(update).unwrap()).unwrap(); } |
| 129 | } |
| 130 | } |
| 131 | let merged = Doc::with_options(options(6_999)); |
| 132 | merged.transact_mut().apply_update(Update::decode_v1(&base).unwrap()).unwrap(); |
| 133 | merged.transact_mut().apply_update(Update::decode_v1(&clients[0].transact().encode_state_as_update_v1(&StateVector::default())).unwrap()).unwrap(); |
| 134 | let bytes = merged.transact().encode_state_as_update_v1(&StateVector::default()); |
| 135 | bytes |
| 136 | } |
| 137 | |
| 138 | pub fn plain(value: &Value) -> String { |
| 139 | if let Some(runs) = value["runs"].as_array() { return runs.iter().filter_map(|run| run["insert"].as_str()).collect(); } |
| 140 | value["children"].as_array().map(|children| children.iter().map(plain).collect()).unwrap_or_default() |
| 141 | } |
| 142 | |
| 143 | /// The display mapping as it was defined before the engine stopped building a |
| 144 | /// projection for it (display.rs at 8e54d3a): the oracle the fast walk must match. |
| 145 | pub struct Span { pub node: String, pub start: u32, pub length: u32, pub atomic: bool } |
| 146 | pub fn spans(value: &Value, offset: &mut u32, output: &mut Vec<Span>) { |
| 147 | let tag = value["type"].as_str().unwrap_or(""); |
| 148 | if tag == "text" { |
| 149 | let length = value["runs"].as_array().map(|runs| runs.iter().map(|r| r["insert"].as_str().unwrap_or("").encode_utf16().count() as u32).sum()).unwrap_or(0); |
| 150 | output.push(Span { node: value["id"].as_str().unwrap_or("").to_owned(), start: *offset, length, atomic: false }); |
| 151 | *offset += length; return; |
| 152 | } |
| 153 | if ["hard_break", "image", "horizontal_rule"].contains(&tag) { |
| 154 | output.push(Span { node: value["id"].as_str().unwrap_or("").to_owned(), start: *offset, length: 1, atomic: true }); |
| 155 | *offset += if tag == "horizontal_rule" { 2 } else { 1 }; return; |
| 156 | } |
| 157 | let start = *offset; |
| 158 | if let Some(children) = value["children"].as_array() { for child in children { spans(child, offset, output); } } |
| 159 | if ["paragraph", "heading", "code_block"].contains(&tag) { |
| 160 | if *offset == start { output.push(Span { node: value["id"].as_str().unwrap_or("").to_owned(), start, length: 0, atomic: false }); } |
| 161 | *offset += 1; |
| 162 | } |
| 163 | } |
| 164 | pub fn oracle(projection: &Value) -> (Vec<Span>, u32) { |
| 165 | let mut offset = 0; let mut ranges = Vec::new(); |
| 166 | for child in projection["children"].as_array().unwrap() { spans(child, &mut offset, &mut ranges); } |
| 167 | (ranges, offset) |
| 168 | } |
| 169 | pub fn oracle_locate(ranges: &[Span], at: u32, length: u32) -> Option<(String, u32)> { |
| 170 | let end = at.checked_add(length)?; |
| 171 | ranges.iter().find(|r| !r.atomic && at >= r.start && end <= r.start + r.length) |
| 172 | .or_else(|| ranges.iter().find(|r| r.atomic && at >= r.start && end <= r.start + r.length)) |
| 173 | .map(|r| (r.node.clone(), at - r.start)) |
| 174 | } |
| 175 | |
| 176 | /// The projection exactly as projection.rs built it at 8e54d3a (children by |
| 177 | /// index, runs by `to_string`): the oracle for documents without embeds. |
| 178 | pub fn legacy_projection(bytes: &[u8]) -> Value { |
| 179 | use serde_json::json; |
| 180 | use yrs::{Xml, XmlFragmentRef}; |
| 181 | fn node_id(node: &XmlOut) -> String { serde_json::to_string(&node.id()).unwrap() } |
| 182 | fn children<T: ReadTxn>(root: &XmlFragmentRef, txn: &T) -> Vec<Value> { |
| 183 | (0..root.len(txn)).filter_map(|i| root.get(txn, i)).map(|node| project(&node, txn)).collect() |
| 184 | } |
| 185 | fn project<T: ReadTxn>(node: &XmlOut, txn: &T) -> Value { |
| 186 | match node { |
| 187 | XmlOut::Text(text) => { |
| 188 | let runs: Vec<_> = text.diff(txn, |_| ()).iter().map(|run| json!({"insert": run.insert.clone().to_string(txn), "marks": run.attributes})).collect(); |
| 189 | json!({"id": node_id(node), "type": "text", "runs": runs}) |
| 190 | }, |
| 191 | XmlOut::Element(element) => { |
| 192 | let attrs: serde_json::Map<String, Value> = element.attributes(txn).map(|(key,value)| (key.to_string(), Value::String(value))).collect(); |
| 193 | json!({"id": node_id(node), "type": element.tag().as_ref(), "attrs": attrs, "children": children(element.as_ref(), txn)}) |
| 194 | }, |
| 195 | XmlOut::Fragment(fragment) => json!({"id": node_id(node), "type": "fragment", "children": children(fragment, txn)}), |
| 196 | } |
| 197 | } |
| 198 | let doc = Doc::with_options(options(1)); |
| 199 | doc.transact_mut().apply_update(Update::decode_v1(bytes).unwrap()).unwrap(); |
| 200 | let root = doc.get_or_insert_xml_fragment("prosemirror"); |
| 201 | let txn = doc.transact(); |
| 202 | json!({"children": children(&root, &txn)}) |
| 203 | } |
| 204 | |