use std::ops::Range;
use rustc_hash::FxHashSet;
use crate::Attrs;
use crate::BlockId;
use crate::BlockTree;
use crate::BlockTypeId;
use crate::Document;
use crate::InlineText;
use crate::Mark;
use crate::MarkSet;
use crate::MarkTypeId;
use crate::Step;
use crate::StepError;
use crate::StepMap;
use crate::selection::Bias;
use crate::selection::Point;
use crate::selection::Selection;
use crate::step::Mapped;
#[derive(Debug)]
pub struct Transaction<'doc> {
doc: &'doc mut Document,
steps: Vec<Step>,
inverses: Vec<Step>,
maps: Vec<StepMap>,
touched: FxHashSet<BlockId>,
structural: bool,
}
impl<'doc> Transaction<'doc> {
pub fn new(doc: &'doc mut Document) -> Self {
Self {
doc,
steps: Vec::new(),
inverses: Vec::new(),
maps: Vec::new(),
touched: FxHashSet::default(),
structural: false,
}
}
#[must_use]
pub fn doc(&self) -> &Document {
self.doc
}
#[must_use]
pub fn is_empty(&self) -> bool {
self.steps.is_empty()
}
pub fn step(&mut self, step: Step) -> Result<(), StepError> {
let applied = step.clone().apply(self.doc)?;
self.steps.push(step);
self.inverses.push(applied.inverse);
self.maps.push(applied.map);
self.touched.extend(applied.touched);
self.structural |= applied.structural;
Ok(())
}
pub fn allocate_id(&mut self) -> Result<BlockId, StepError> {
self.doc.allocate_id()
}
#[must_use]
pub fn map(&self, point: Point, bias: Bias) -> Mapped {
map_through(&self.maps, point, bias)
}
pub fn insert_text(
&mut self,
at: Point,
text: &str,
marks: MarkSet,
) -> Result<Point, StepError> {
let content = InlineText::plain(text, marks);
let end = at.offset + content.len();
self.step(Step::InsertInline {
block: at.block,
offset: at.offset,
content,
})?;
Ok(Point::new(at.block, end))
}
pub fn delete_text(&mut self, block: BlockId, range: Range<u32>) -> Result<(), StepError> {
self.step(Step::RemoveInline { block, range })
}
pub fn add_mark(
&mut self,
block: BlockId,
range: Range<u32>,
mark: Mark,
) -> Result<(), StepError> {
self.step(Step::AddMark { block, range, mark })
}
pub fn remove_mark(
&mut self,
block: BlockId,
range: Range<u32>,
kind: MarkTypeId,
) -> Result<(), StepError> {
self.step(Step::RemoveMark { block, range, kind })
}
pub fn set_block(
&mut self,
block: BlockId,
kind: BlockTypeId,
attrs: Attrs,
) -> Result<(), StepError> {
self.step(Step::SetBlock { block, kind, attrs })
}
pub fn split(
&mut self,
at: Point,
kind: BlockTypeId,
attrs: Attrs,
) -> Result<Point, StepError> {
let new_block = self.doc.allocate_id()?;
self.step(Step::Split {
block: at.block,
offset: at.offset,
new_block,
kind,
attrs,
})?;
Ok(Point::new(new_block, 0))
}
pub fn join(&mut self, block: BlockId, next: BlockId) -> Result<Point, StepError> {
let offset = self.doc.inline(block).map_or(0, InlineText::len);
self.step(Step::Join { block, next })?;
Ok(Point::new(block, offset))
}
pub fn insert_blocks(
&mut self,
parent: Option<BlockId>,
index: usize,
blocks: Vec<BlockTree>,
) -> Result<(), StepError> {
self.step(Step::InsertBlocks {
parent,
index,
blocks,
})
}
pub fn remove_blocks(
&mut self,
parent: Option<BlockId>,
index: usize,
count: usize,
) -> Result<(), StepError> {
self.step(Step::RemoveBlocks {
parent,
index,
count,
})
}
pub fn move_blocks(
&mut self,
(parent, index, count): (Option<BlockId>, usize, usize),
(to_parent, to_index): (Option<BlockId>, usize),
) -> Result<(), StepError> {
self.step(Step::MoveBlocks {
parent,
index,
count,
to_parent,
to_index,
})
}
pub fn rollback(self) -> Result<(), StepError> {
for inverse in self.inverses.into_iter().rev() {
inverse.apply(self.doc)?;
}
Ok(())
}
#[must_use]
pub fn commit(self) -> Commit {
let mut touched: Vec<BlockId> = self.touched.into_iter().collect();
touched.retain(|&id| self.doc.contains(id));
touched.sort_unstable();
Commit {
steps: self.steps,
inverses: self.inverses,
maps: self.maps,
touched,
structural: self.structural,
version: self.doc.version(),
}
}
}
#[derive(Clone, Debug, PartialEq)]
pub struct Commit {
pub steps: Vec<Step>,
pub inverses: Vec<Step>,
pub maps: Vec<StepMap>,
pub touched: Vec<BlockId>,
pub structural: bool,
pub version: u64,
}
impl Commit {
#[must_use]
pub fn map(&self, point: Point, bias: Bias) -> Mapped {
map_through(&self.maps, point, bias)
}
#[must_use]
pub fn map_selection(&self, selection: Selection) -> Selection {
map_selection(&self.maps, selection)
}
#[must_use]
pub fn undo_steps(&self) -> Vec<Step> {
self.inverses.iter().rev().cloned().collect()
}
#[must_use]
pub fn is_empty(&self) -> bool {
self.steps.is_empty()
}
}
fn map_through(maps: &[StepMap], point: Point, bias: Bias) -> Mapped {
let mut deleted = false;
let mut point = point;
for map in maps {
let mapped = map.map(point, bias);
deleted |= mapped.deleted;
point = mapped.point;
}
Mapped { point, deleted }
}
fn map_selection(maps: &[StepMap], selection: Selection) -> Selection {
match selection {
Selection::Text { anchor, head } if anchor == head => {
Selection::caret(map_through(maps, head, Bias::After).point)
}
Selection::Text { anchor, head } => {
Selection::Text {
anchor: map_through(maps, anchor, Bias::Before).point,
head: map_through(maps, head, Bias::After).point,
}
}
Selection::Blocks { .. } => selection,
}
}
impl Document {
pub fn transaction(&mut self) -> Transaction<'_> {
Transaction::new(self)
}
pub fn apply_steps(
&mut self,
steps: impl IntoIterator<Item = Step>,
) -> Result<Commit, StepError> {
let mut transaction = self.transaction();
for step in steps {
if let Err(error) = transaction.step(step) {
transaction.rollback()?;
return Err(error);
}
}
Ok(transaction.commit())
}
}