rofd-editor 0.1.7

Annotation command/transaction layer for the rofd OFD editor.
Documentation
use rofd_dom::{AnnotationId, OfdDocument};

use crate::cursor::TextCursor;
use crate::selection::AnnotationSelection;
use crate::steps::history::History;
use crate::steps::transaction::Transaction;

/// Annotation editor. Owns the document; mutates only `.annotations` via commands.
/// No callbacks - the host/component layer queries state after commands.
pub struct Editor {
    pub(crate) document: OfdDocument,
    pub(crate) selection: AnnotationSelection,
    pub(crate) text_cursor: Option<TextCursor>,
    pub(crate) history: History,
    pub(crate) author: String,
    pub(crate) current_ts: i64,
}

impl Editor {
    pub fn new() -> Self {
        Self {
            document: OfdDocument::default(),
            selection: AnnotationSelection::None,
            text_cursor: None,
            history: History::new(100),
            author: String::new(),
            current_ts: 0,
        }
    }

    pub fn load_document(&mut self, doc: OfdDocument) {
        self.document = doc;
        self.selection = AnnotationSelection::None;
        self.text_cursor = None;
        self.history = History::new(100);
    }

    /// A change to the document that is neither an annotation command nor
    /// another document (spec 2026-11-23 ยง17.11): a signature appended to the
    /// package it carries. `revise` gets the document, and what it returns is
    /// returned. The selection, the text cursor and the history are not
    /// touched, and no page is invalidated - call [`Self::invalidate_pages`]
    /// when the content of the pages changed (a seal is page content).
    pub fn revise_document<T>(&mut self, revise: impl FnOnce(&mut OfdDocument) -> T) -> T {
        revise(&mut self.document)
    }

    /// The content of the pages changed: every cached page is stale. The
    /// page scenes and the CPU fallback's page bitmaps key on the body
    /// revision.
    pub fn invalidate_pages(&mut self) {
        self.document.body_revision += 1;
    }

    /// Caller-supplied author + timestamp. The library never reads a system clock.
    pub fn set_clock(&mut self, author: String, ts: i64) {
        self.author = author;
        self.current_ts = ts;
    }

    pub fn document(&self) -> &OfdDocument {
        &self.document
    }
    pub fn selection(&self) -> &AnnotationSelection {
        &self.selection
    }
    pub fn text_cursor(&self) -> Option<&TextCursor> {
        self.text_cursor.as_ref()
    }
    pub fn can_undo(&self) -> bool {
        self.history.can_undo()
    }
    pub fn can_redo(&self) -> bool {
        self.history.can_redo()
    }
    /// Number of undoable transactions on the history stack. Mainly for
    /// testing (e.g. asserting a drag pushes exactly one Transaction).
    pub fn history_len(&self) -> usize {
        self.history.done_len()
    }

    /// Select a single annotation by id.
    pub fn select(&mut self, id: AnnotationId) {
        self.selection = AnnotationSelection::Single(id);
    }
    /// Replace the current selection wholesale.
    pub fn set_selection(&mut self, sel: AnnotationSelection) {
        self.selection = sel;
    }
    /// Clear the selection.
    pub fn clear_selection(&mut self) {
        self.selection = AnnotationSelection::None;
    }
    /// Position the text cursor at `offset` within `annotation`.
    pub fn set_cursor(&mut self, annotation: AnnotationId, offset: usize) {
        self.set_cursor_with_preferred_x(annotation, offset, None);
    }

    /// Position the text cursor and keep a preferred column x (vertical
    /// caret movement across visual lines). `None` clears the preference.
    pub fn set_cursor_with_preferred_x(
        &mut self,
        annotation: AnnotationId,
        offset: usize,
        preferred_x: Option<f32>,
    ) {
        self.text_cursor = Some(TextCursor {
            annotation,
            offset,
            preferred_x,
        });
    }
    /// Clear the text cursor.
    pub fn clear_cursor(&mut self) {
        self.text_cursor = None;
    }

    /// Apply a Transaction: run its steps forward, set selection/cursor to the
    /// "after" state, and push it onto the history. Used by the command methods
    /// (create/delete/move/...) starting in Task 5; the unit tests here exercise
    /// it directly.
    pub(crate) fn execute_transaction(&mut self, txn: Transaction) {
        for step in &txn.steps {
            step.apply(&mut self.document.annotations);
        }
        self.selection = txn.selection_after.clone();
        self.text_cursor = txn.text_cursor_after.clone();
        self.history.push(txn);
    }

    pub fn undo(&mut self) -> bool {
        let txn = self.history.undo();
        if let Some(txn) = txn {
            for step in txn.steps.iter().rev() {
                step.revert(&mut self.document.annotations);
            }
            self.selection = txn.selection_before.clone();
            self.text_cursor = txn.text_cursor_before.clone();
            true
        } else {
            false
        }
    }

    pub fn redo(&mut self) -> bool {
        let txn = self.history.redo();
        if let Some(txn) = txn {
            for step in &txn.steps {
                step.apply(&mut self.document.annotations);
            }
            self.selection = txn.selection_after.clone();
            self.text_cursor = txn.text_cursor_after.clone();
            true
        } else {
            false
        }
    }
}

impl Default for Editor {
    fn default() -> Self {
        Self::new()
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::steps::annotation_steps::InsertAnnotationStep;
    use rofd_dom::{
        Annotation, AnnotationId, AnnotationKind, AnnotationPayload, Color, NoteIcon, PageId, Rect,
    };

    fn note_ann(id: &str) -> Annotation {
        Annotation {
            id: AnnotationId::new(id),
            kind: AnnotationKind::Note,
            page: PageId::new("P0"),
            creator: "t".into(),
            created: 0,
            modified: 0,
            reply_to: None,
            payload: AnnotationPayload::Note {
                rect: Rect {
                    x: 0.0,
                    y: 0.0,
                    w: 1.0,
                    h: 1.0,
                },
                color: Color::Rgb(0, 0, 0),
                content: "x".into(),
                icon: NoteIcon::Note,
            },
        }
    }

    #[test]
    fn execute_undo_redo_via_transaction() {
        let mut e = Editor::new();
        let ann = note_ann("21");
        let txn = Transaction {
            steps: vec![Box::new(InsertAnnotationStep {
                annotation: ann.clone(),
            })],
            selection_before: AnnotationSelection::None,
            selection_after: AnnotationSelection::Single(ann.id.clone()),
            text_cursor_before: None,
            text_cursor_after: None,
        };
        e.execute_transaction(txn);
        assert!(e.document().annotations.find(&ann.id).is_some());
        assert!(e.undo());
        assert!(e.document().annotations.find(&ann.id).is_none());
        assert!(e.redo());
        assert!(e.document().annotations.find(&ann.id).is_some());
    }

    #[test]
    fn history_capacity_evicts_oldest() {
        let mut e = Editor::new();
        for i in 0..105u32 {
            let ann = note_ann(&format!("{}", i));
            let txn = Transaction {
                steps: vec![Box::new(InsertAnnotationStep { annotation: ann })],
                selection_before: AnnotationSelection::None,
                selection_after: AnnotationSelection::None,
                text_cursor_before: None,
                text_cursor_after: None,
            };
            e.execute_transaction(txn);
        }
        assert!(e.can_undo());
        for _ in 0..100 {
            assert!(e.undo());
        }
        assert!(!e.can_undo());
    }

    #[test]
    fn set_cursor_with_preferred_x_round_trips() {
        let mut e = Editor::new();
        e.set_cursor_with_preferred_x(AnnotationId::from_int(1), 3, Some(4.5));
        let c = e.text_cursor().unwrap();
        assert_eq!((c.offset, c.preferred_x), (3, Some(4.5)));
        e.set_cursor(AnnotationId::from_int(1), 3);
        assert_eq!(e.text_cursor().unwrap().preferred_x, None);
    }
}

#[cfg(test)]
mod revising_tests {
    use super::*;
    use crate::steps::annotation_steps::InsertAnnotationStep;
    use rofd_dom::{Annotation, AnnotationKind, AnnotationPayload, Color, NoteIcon, PageId, Rect};

    fn note_ann(id: &str) -> Annotation {
        Annotation {
            id: AnnotationId::new(id),
            kind: AnnotationKind::Note,
            page: PageId::new("P0"),
            creator: "t".into(),
            created: 0,
            modified: 0,
            reply_to: None,
            payload: AnnotationPayload::Note {
                rect: Rect {
                    x: 0.0,
                    y: 0.0,
                    w: 1.0,
                    h: 1.0,
                },
                color: Color::Rgb(0, 0, 0),
                content: "x".into(),
                icon: NoteIcon::Note,
            },
        }
    }

    #[test]
    fn revising_keeps_the_selection_the_cursor_and_the_history() {
        let mut e = Editor::new();
        let ann = note_ann("21");
        e.execute_transaction(Transaction {
            steps: vec![Box::new(InsertAnnotationStep {
                annotation: ann.clone(),
            })],
            selection_before: AnnotationSelection::None,
            selection_after: AnnotationSelection::Single(ann.id.clone()),
            text_cursor_before: None,
            text_cursor_after: None,
        });
        e.set_cursor(ann.id.clone(), 2);

        let highest = e.revise_document(|document| document.highest_known_object_id());

        assert_eq!(highest, 21);
        assert!(e.can_undo());
        assert_eq!(
            e.selection().clone(),
            AnnotationSelection::Single(ann.id.clone())
        );
        assert_eq!(e.text_cursor().map(|cursor| cursor.offset), Some(2));
        assert_eq!(
            e.document().body_revision,
            0,
            "revising alone moves no page"
        );
    }

    #[test]
    fn invalidating_pages_moves_the_body_revision() {
        let mut e = Editor::new();
        e.invalidate_pages();
        assert_eq!(e.document().body_revision, 1);
    }
}