default_insert.rs 1.3 KB

12345678910111213141516171819202122232425262728293031323334353637383940
  1. use crate::client_document::InsertExt;
  2. use lib_ot::{
  3. core::{Attributes, DeltaBuilder, DeltaIterator, NEW_LINE},
  4. rich_text::{RichTextDelta, TextAttributeKey, TextAttributes},
  5. };
  6. pub struct DefaultInsertAttribute {}
  7. impl InsertExt for DefaultInsertAttribute {
  8. fn ext_name(&self) -> &str {
  9. "DefaultInsertAttribute"
  10. }
  11. fn apply(&self, delta: &RichTextDelta, replace_len: usize, text: &str, index: usize) -> Option<RichTextDelta> {
  12. let iter = DeltaIterator::new(delta);
  13. let mut attributes = TextAttributes::new();
  14. // Enable each line split by "\n" remains the block attributes. for example:
  15. // insert "\n" to "123456" at index 3
  16. //
  17. // [{"insert":"123"},{"insert":"\n","attributes":{"header":1}},
  18. // {"insert":"456"},{"insert":"\n","attributes":{"header":1}}]
  19. if text.ends_with(NEW_LINE) {
  20. match iter.last() {
  21. None => {}
  22. Some(op) => {
  23. if op.get_attributes().contains_key(&TextAttributeKey::Header) {
  24. attributes.extend_other(op.get_attributes());
  25. }
  26. }
  27. }
  28. }
  29. Some(
  30. DeltaBuilder::new()
  31. .retain(index + replace_len)
  32. .insert_with_attributes(text, attributes)
  33. .build(),
  34. )
  35. }
  36. }