insert_ext.rs 1.9 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273
  1. use crate::{
  2. client::view::InsertExt,
  3. core::{
  4. attributes_at_index,
  5. AttributeKey,
  6. Attributes,
  7. Delta,
  8. DeltaBuilder,
  9. DeltaIter,
  10. Operation,
  11. },
  12. };
  13. pub const NEW_LINE: &'static str = "\n";
  14. pub struct PreserveInlineStyleExt {}
  15. impl PreserveInlineStyleExt {
  16. pub fn new() -> Self { Self {} }
  17. }
  18. impl InsertExt for PreserveInlineStyleExt {
  19. fn apply(&self, delta: &Delta, _replace_len: usize, text: &str, index: usize) -> Option<Delta> {
  20. if text.ends_with(NEW_LINE) {
  21. return None;
  22. }
  23. let attributes = attributes_at_index(delta, index);
  24. let delta = DeltaBuilder::new().insert(text, attributes).build();
  25. Some(delta)
  26. }
  27. }
  28. pub struct ResetLineFormatOnNewLineExt {}
  29. impl ResetLineFormatOnNewLineExt {
  30. pub fn new() -> Self { Self {} }
  31. }
  32. impl InsertExt for ResetLineFormatOnNewLineExt {
  33. fn apply(&self, delta: &Delta, replace_len: usize, text: &str, index: usize) -> Option<Delta> {
  34. if text != NEW_LINE {
  35. return None;
  36. }
  37. let mut iter = DeltaIter::new(delta);
  38. iter.seek(index);
  39. let maybe_next_op = iter.next();
  40. if maybe_next_op.is_none() {
  41. return None;
  42. }
  43. let op = maybe_next_op.unwrap();
  44. if !op.get_data().starts_with(NEW_LINE) {
  45. return None;
  46. }
  47. let mut reset_attribute = Attributes::new();
  48. if op.get_attributes().contains_key(&AttributeKey::Header) {
  49. reset_attribute.add(AttributeKey::Header.with_value(""));
  50. }
  51. let len = index + replace_len;
  52. Some(
  53. DeltaBuilder::new()
  54. .retain(len, Attributes::default())
  55. .insert(NEW_LINE, op.get_attributes())
  56. .retain(1, reset_attribute)
  57. .trim()
  58. .build(),
  59. )
  60. }
  61. }