default_insert.rs 1.3 KB

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