preserve_inline_style.rs 1.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051
  1. use crate::{
  2. client::{
  3. extensions::InsertExt,
  4. util::{contain_newline, OpNewline},
  5. },
  6. core::{AttributeKey, Attributes, Delta, DeltaBuilder, DeltaIter},
  7. };
  8. pub struct PreserveInlineStylesExt {}
  9. impl InsertExt for PreserveInlineStylesExt {
  10. fn ext_name(&self) -> &str { "PreserveInlineStylesExt" }
  11. fn apply(&self, delta: &Delta, replace_len: usize, text: &str, index: usize) -> Option<Delta> {
  12. if contain_newline(text) {
  13. return None;
  14. }
  15. let mut iter = DeltaIter::new(delta);
  16. let prev = iter.next_op_before(index)?;
  17. if OpNewline::parse(&prev).is_contain() {
  18. return None;
  19. }
  20. let mut attributes = prev.get_attributes();
  21. if attributes.is_empty() || !attributes.contains_key(&AttributeKey::Link) {
  22. return Some(
  23. DeltaBuilder::new()
  24. .retain(index + replace_len)
  25. .insert_with_attributes(text, attributes)
  26. .build(),
  27. );
  28. }
  29. let next = iter.next_op();
  30. match &next {
  31. None => attributes = Attributes::empty(),
  32. Some(next) => {
  33. if OpNewline::parse(&next).is_equal() {
  34. attributes = Attributes::empty();
  35. }
  36. },
  37. }
  38. let new_delta = DeltaBuilder::new()
  39. .retain(index + replace_len)
  40. .insert_with_attributes(text, attributes)
  41. .build();
  42. return Some(new_delta);
  43. }
  44. }