builder.rs 1.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445
  1. use crate::{
  2. core::{Attributes, Operation, PlainTextAttributes},
  3. rich_text::RichTextAttributes,
  4. };
  5. pub type RichTextOpBuilder = OpBuilder<RichTextAttributes>;
  6. pub type PlainTextOpBuilder = OpBuilder<PlainTextAttributes>;
  7. pub struct OpBuilder<T: Attributes> {
  8. ty: Operation<T>,
  9. attrs: T,
  10. }
  11. impl<T> OpBuilder<T>
  12. where
  13. T: Attributes,
  14. {
  15. pub fn new(ty: Operation<T>) -> OpBuilder<T> {
  16. OpBuilder {
  17. ty,
  18. attrs: T::default(),
  19. }
  20. }
  21. pub fn retain(n: usize) -> OpBuilder<T> { OpBuilder::new(Operation::Retain(n.into())) }
  22. pub fn delete(n: usize) -> OpBuilder<T> { OpBuilder::new(Operation::Delete(n)) }
  23. pub fn insert(s: &str) -> OpBuilder<T> { OpBuilder::new(Operation::Insert(s.into())) }
  24. pub fn attributes(mut self, attrs: T) -> OpBuilder<T> {
  25. self.attrs = attrs;
  26. self
  27. }
  28. pub fn build(self) -> Operation<T> {
  29. let mut operation = self.ty;
  30. match &mut operation {
  31. Operation::Delete(_) => {},
  32. Operation::Retain(retain) => retain.attributes = self.attrs,
  33. Operation::Insert(insert) => insert.attributes = self.attrs,
  34. }
  35. operation
  36. }
  37. }