| 1 | |
| 2 | |
| 3 | |
| 4 | |
| 5 | |
| 6 | |
| 7 | |
| 8 | |
| 9 | |
| 10 | use super::{Handler, ValueOrHandler}; |
| 11 | use crate::{ |
| 12 | delta::{ResolvedMapDelta, ResolvedMapValue, TreeDiff, TreeDiffItem, TreeExternalDiff}, |
| 13 | event::{Diff, ListDeltaMeta, ListDiff, TextDiff, TextMeta}, |
| 14 | state::TreeParentId, |
| 15 | utils::{ |
| 16 | string_slice::StringSlice, |
| 17 | utf16::{count_unicode_chars, count_utf16_len}, |
| 18 | }, |
| 19 | }; |
| 20 | use fractional_index::FractionalIndex; |
| 21 | use loro_common::{ContainerID, InternalString, LoroValue, TreeID}; |
| 22 | use loro_delta::{array_vec::ArrayVec, DeltaItem, DeltaRope}; |
| 23 | use rustc_hash::{FxHashMap, FxHashSet}; |
| 24 | |
| 25 | |
| 26 | |
| 27 | |
| 28 | |
| 29 | |
| 30 | |
| 31 | |
| 32 | pub(crate) fn align_full_state( |
| 33 | handler: &Handler, |
| 34 | target: &Diff, |
| 35 | current: Diff, |
| 36 | full_state_targets: &mut FxHashSet<ContainerID>, |
| 37 | ) -> Option<Diff> { |
| 38 | match (target, current) { |
| 39 | (Diff::Map(target), Diff::Map(current)) => { |
| 40 | align_map(target, current, full_state_targets).map(Diff::Map) |
| 41 | } |
| 42 | #[cfg(feature = "counter")] |
| 43 | (Diff::Counter(target), Diff::Counter(current)) => { |
| 44 | let delta = target - current; |
| 45 | (matches!(handler, Handler::Counter(_)) && delta != 0.0).then_some(Diff::Counter(delta)) |
| 46 | } |
| 47 | (Diff::Text(target), Diff::Text(current)) => match align_text(target, ¤t) { |
| 48 | Some(edit) => (!edit.is_empty()).then_some(Diff::Text(edit)), |
| 49 | None => Some(Diff::Text(target.clone())), |
| 50 | }, |
| 51 | (Diff::List(target), Diff::List(current)) => { |
| 52 | let movable = matches!(handler, Handler::MovableList(_)); |
| 53 | match align_list(target, ¤t, movable, full_state_targets) { |
| 54 | Some(edit) => (!edit.is_empty()).then_some(Diff::List(edit)), |
| 55 | None => Some(Diff::List(target.clone())), |
| 56 | } |
| 57 | } |
| 58 | (Diff::Tree(target), Diff::Tree(current)) => { |
| 59 | match align_tree(target, ¤t, full_state_targets) { |
| 60 | Some(edit) => (!edit.diff.is_empty()).then_some(Diff::Tree(edit)), |
| 61 | None => Some(Diff::Tree(target.clone())), |
| 62 | } |
| 63 | } |
| 64 | (Diff::Unknown, _) => None, |
| 65 | (target, _) => Some(target.clone()), |
| 66 | } |
| 67 | } |
| 68 | |
| 69 | fn map_value(v: &ResolvedMapValue) -> Option<LoroValue> { |
| 70 | v.value.as_ref().map(ValueOrHandler::to_value) |
| 71 | } |
| 72 | |
| 73 | |
| 74 | fn align_map( |
| 75 | target: &ResolvedMapDelta, |
| 76 | current: ResolvedMapDelta, |
| 77 | full_state_targets: &mut FxHashSet<ContainerID>, |
| 78 | ) -> Option<ResolvedMapDelta> { |
| 79 | let current: FxHashMap<InternalString, LoroValue> = current |
| 80 | .updated |
| 81 | .iter() |
| 82 | .filter_map(|(k, v)| Some((k.clone(), map_value(v)?))) |
| 83 | .collect(); |
| 84 | let mut updated = FxHashMap::default(); |
| 85 | let mut target_keys = FxHashSet::default(); |
| 86 | for (key, value) in target.updated.iter() { |
| 87 | let Some(target_value) = map_value(value) else { |
| 88 | continue; |
| 89 | }; |
| 90 | target_keys.insert(key.clone()); |
| 91 | if current.get(key) == Some(&target_value) { |
| 92 | if let LoroValue::Container(id) = target_value { |
| 93 | full_state_targets.insert(id); |
| 94 | } |
| 95 | } else { |
| 96 | updated.insert(key.clone(), value.clone()); |
| 97 | } |
| 98 | } |
| 99 | for key in current.keys() { |
| 100 | if !target_keys.contains(key) { |
| 101 | updated.insert(key.clone(), ResolvedMapValue::new_unset()); |
| 102 | } |
| 103 | } |
| 104 | (!updated.is_empty()).then_some(ResolvedMapDelta { updated }) |
| 105 | } |
| 106 | |
| 107 | |
| 108 | fn text_len(s: &str) -> usize { |
| 109 | if cfg!(feature = "wasm") { |
| 110 | count_utf16_len(s.as_bytes()) |
| 111 | } else { |
| 112 | count_unicode_chars(s.as_bytes()) |
| 113 | } |
| 114 | } |
| 115 | |
| 116 | |
| 117 | fn text_runs(diff: &TextDiff) -> Option<Vec<(&str, &TextMeta)>> { |
| 118 | let mut ans = Vec::new(); |
| 119 | for item in diff.iter() { |
| 120 | let DeltaItem::Replace { |
| 121 | value, |
| 122 | attr, |
| 123 | delete: 0, |
| 124 | } = item |
| 125 | else { |
| 126 | return None; |
| 127 | }; |
| 128 | ans.push((value.as_str(), attr)); |
| 129 | } |
| 130 | Some(ans) |
| 131 | } |
| 132 | |
| 133 | |
| 134 | fn slice_runs<'a>( |
| 135 | runs: &[(&'a str, &'a TextMeta)], |
| 136 | range: std::ops::Range<usize>, |
| 137 | ) -> Vec<(&'a str, &'a TextMeta)> { |
| 138 | let mut ans = Vec::new(); |
| 139 | let mut offset = 0; |
| 140 | for &(text, attr) in runs { |
| 141 | let (start, end) = (offset, offset + text.len()); |
| 142 | offset = end; |
| 143 | let (from, to) = (range.start.max(start), range.end.min(end)); |
| 144 | if from < to { |
| 145 | ans.push((&text[from - start..to - start], attr)); |
| 146 | } |
| 147 | } |
| 148 | ans |
| 149 | } |
| 150 | |
| 151 | |
| 152 | fn common_ends<T: PartialEq>(a: &[T], b: &[T]) -> (usize, usize) { |
| 153 | common_ends_by(a, b, |x, y| x == y) |
| 154 | } |
| 155 | |
| 156 | fn common_ends_by<T>(a: &[T], b: &[T], eq: impl Fn(&T, &T) -> bool) -> (usize, usize) { |
| 157 | let prefix = a.iter().zip(b).take_while(|(x, y)| eq(x, y)).count(); |
| 158 | let suffix = a[prefix..] |
| 159 | .iter() |
| 160 | .rev() |
| 161 | .zip(b[prefix..].iter().rev()) |
| 162 | .take_while(|(x, y)| eq(x, y)) |
| 163 | .count(); |
| 164 | (prefix, suffix) |
| 165 | } |
| 166 | |
| 167 | |
| 168 | fn style_change(current: &TextMeta, target: &TextMeta) -> TextMeta { |
| 169 | let mut change = TextMeta::default(); |
| 170 | for (key, value) in target.0.iter() { |
| 171 | if current.0.get(key) != Some(value) { |
| 172 | change.0.insert(key.clone(), value.clone()); |
| 173 | } |
| 174 | } |
| 175 | for key in current.0.keys() { |
| 176 | if !target.0.contains_key(key) { |
| 177 | change.0.insert(key.clone(), LoroValue::Null); |
| 178 | } |
| 179 | } |
| 180 | change |
| 181 | } |
| 182 | |
| 183 | |
| 184 | |
| 185 | fn push_restyled_retain( |
| 186 | edit: &mut TextDiff, |
| 187 | current: &[(&str, &TextMeta)], |
| 188 | target: &[(&str, &TextMeta)], |
| 189 | ) { |
| 190 | let (mut ci, mut ti) = (0, 0); |
| 191 | let (mut c_off, mut t_off) = (0, 0); |
| 192 | while ci < current.len() && ti < target.len() { |
| 193 | let (c_text, c_attr) = current[ci]; |
| 194 | let (t_text, t_attr) = target[ti]; |
| 195 | let take = (c_text.len() - c_off).min(t_text.len() - t_off); |
| 196 | let piece = &c_text[c_off..c_off + take]; |
| 197 | let change = if c_attr == t_attr { |
| 198 | TextMeta::default() |
| 199 | } else { |
| 200 | style_change(c_attr, t_attr) |
| 201 | }; |
| 202 | edit.push_retain(text_len(piece), change); |
| 203 | c_off += take; |
| 204 | t_off += take; |
| 205 | if c_off == c_text.len() { |
| 206 | ci += 1; |
| 207 | c_off = 0; |
| 208 | } |
| 209 | if t_off == t_text.len() { |
| 210 | ti += 1; |
| 211 | t_off = 0; |
| 212 | } |
| 213 | } |
| 214 | } |
| 215 | |
| 216 | |
| 217 | |
| 218 | |
| 219 | fn align_text(target: &TextDiff, current: &TextDiff) -> Option<TextDiff> { |
| 220 | let target = text_runs(target)?; |
| 221 | let current = text_runs(current)?; |
| 222 | let target_text: String = target.iter().map(|(s, _)| *s).collect(); |
| 223 | let current_text: String = current.iter().map(|(s, _)| *s).collect(); |
| 224 | let (t, c) = (target_text.as_bytes(), current_text.as_bytes()); |
| 225 | let mut prefix = t.iter().zip(c).take_while(|(x, y)| x == y).count(); |
| 226 | while !target_text.is_char_boundary(prefix) { |
| 227 | prefix -= 1; |
| 228 | } |
| 229 | let mut suffix = t[prefix..] |
| 230 | .iter() |
| 231 | .rev() |
| 232 | .zip(c[prefix..].iter().rev()) |
| 233 | .take_while(|(x, y)| x == y) |
| 234 | .count(); |
| 235 | while !target_text.is_char_boundary(t.len() - suffix) { |
| 236 | suffix -= 1; |
| 237 | } |
| 238 | let mut edit = TextDiff::new(); |
| 239 | push_restyled_retain( |
| 240 | &mut edit, |
| 241 | &slice_runs(¤t, 0..prefix), |
| 242 | &slice_runs(&target, 0..prefix), |
| 243 | ); |
| 244 | edit.push_delete(text_len(¤t_text[prefix..c.len() - suffix])); |
| 245 | for (text, attr) in slice_runs(&target, prefix..t.len() - suffix) { |
| 246 | edit.push_insert(StringSlice::from(text), attr.clone()); |
| 247 | } |
| 248 | push_restyled_retain( |
| 249 | &mut edit, |
| 250 | &slice_runs(¤t, c.len() - suffix..c.len()), |
| 251 | &slice_runs(&target, t.len() - suffix..t.len()), |
| 252 | ); |
| 253 | Some(edit) |
| 254 | } |
| 255 | |
| 256 | |
| 257 | fn list_items(diff: &ListDiff) -> Option<Vec<&ValueOrHandler>> { |
| 258 | let mut ans = Vec::new(); |
| 259 | for item in diff.iter() { |
| 260 | let DeltaItem::Replace { |
| 261 | value, delete: 0, .. |
| 262 | } = item |
| 263 | else { |
| 264 | return None; |
| 265 | }; |
| 266 | ans.extend(value.iter()); |
| 267 | } |
| 268 | Some(ans) |
| 269 | } |
| 270 | |
| 271 | |
| 272 | |
| 273 | |
| 274 | |
| 275 | |
| 276 | fn align_list( |
| 277 | target: &ListDiff, |
| 278 | current: &ListDiff, |
| 279 | movable: bool, |
| 280 | full_state_targets: &mut FxHashSet<ContainerID>, |
| 281 | ) -> Option<ListDiff> { |
| 282 | let target = list_items(target)?; |
| 283 | let current = list_items(current)?; |
| 284 | let target_values: Vec<LoroValue> = target.iter().map(|v| v.to_value()).collect(); |
| 285 | let current_values: Vec<LoroValue> = current.iter().map(|v| v.to_value()).collect(); |
| 286 | let (prefix, suffix) = common_ends(&target_values, ¤t_values); |
| 287 | let mut kept: Vec<&LoroValue> = target_values[..prefix] |
| 288 | .iter() |
| 289 | .chain(&target_values[target_values.len() - suffix..]) |
| 290 | .collect(); |
| 291 | if movable { |
| 292 | let current_middle: FxHashSet<&ContainerID> = current_values |
| 293 | [prefix..current_values.len() - suffix] |
| 294 | .iter() |
| 295 | .filter_map(|v| v.as_container()) |
| 296 | .collect(); |
| 297 | kept.extend( |
| 298 | target_values[prefix..target_values.len() - suffix] |
| 299 | .iter() |
| 300 | .filter(|v| { |
| 301 | v.as_container() |
| 302 | .is_some_and(|id| current_middle.contains(id)) |
| 303 | }), |
| 304 | ); |
| 305 | } |
| 306 | for v in kept { |
| 307 | if let LoroValue::Container(id) = v { |
| 308 | full_state_targets.insert(id.clone()); |
| 309 | } |
| 310 | } |
| 311 | let mut edit: ListDiff = DeltaRope::new(); |
| 312 | if prefix == target.len() && prefix == current.len() { |
| 313 | return Some(edit); |
| 314 | } |
| 315 | edit.push_retain(prefix, ListDeltaMeta::default()); |
| 316 | edit.push_delete(current.len() - prefix - suffix); |
| 317 | for v in &target[prefix..target.len() - suffix] { |
| 318 | edit.push_insert(ArrayVec::from([(*v).clone()]), ListDeltaMeta::default()); |
| 319 | } |
| 320 | Some(edit) |
| 321 | } |
| 322 | |
| 323 | |
| 324 | |
| 325 | fn align_tree( |
| 326 | target: &TreeDiff, |
| 327 | current: &TreeDiff, |
| 328 | full_state_targets: &mut FxHashSet<ContainerID>, |
| 329 | ) -> Option<TreeDiff> { |
| 330 | let mut current_nodes: FxHashMap<TreeID, (TreeParentId, &FractionalIndex, usize)> = |
| 331 | FxHashMap::default(); |
| 332 | for item in current.diff.iter() { |
| 333 | let TreeExternalDiff::Create { |
| 334 | parent, |
| 335 | index, |
| 336 | position, |
| 337 | } = &item.action |
| 338 | else { |
| 339 | return None; |
| 340 | }; |
| 341 | current_nodes.insert(item.target, (*parent, position, *index)); |
| 342 | } |
| 343 | let mut edit = TreeDiff::default(); |
| 344 | let mut target_nodes = FxHashSet::default(); |
| 345 | for item in target.diff.iter() { |
| 346 | let TreeExternalDiff::Create { |
| 347 | parent, position, .. |
| 348 | } = &item.action |
| 349 | else { |
| 350 | return None; |
| 351 | }; |
| 352 | target_nodes.insert(item.target); |
| 353 | match current_nodes.get(&item.target) { |
| 354 | Some((p, pos, _)) if p == parent && *pos == position => { |
| 355 | full_state_targets.insert(item.target.associated_meta_container()); |
| 356 | } |
| 357 | Some(_) => { |
| 358 | |
| 359 | full_state_targets.insert(item.target.associated_meta_container()); |
| 360 | edit.diff.push(item.clone()); |
| 361 | } |
| 362 | None => edit.diff.push(item.clone()), |
| 363 | } |
| 364 | } |
| 365 | for (id, (parent, _, index)) in current_nodes { |
| 366 | if !target_nodes.contains(&id) { |
| 367 | edit.diff.push(TreeDiffItem { |
| 368 | target: id, |
| 369 | action: TreeExternalDiff::Delete { |
| 370 | old_parent: parent, |
| 371 | old_index: index, |
| 372 | }, |
| 373 | }); |
| 374 | } |
| 375 | } |
| 376 | Some(edit) |
| 377 | } |