crisol-core 1.0.0

Crisol core: an egui-free data model, themes, metrics, localization, commands, state, and storage.
Documentation
//! Pure unsaved-changes close state; the window adapter lives in the UI.
//!
//! The state only decides whether the next close request must be cancelled. The UI
//! turns `true` into `ViewportCommand::CancelClose` and `allow()` into `Close`.
//!
//! ```
//! use crisol_core::state::close_guard;
//! ```

/// Delays window close requests until unsaved documents are resolved.
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
/// # Example
///
/// ```
/// use crisol_core::state::CloseGuard;
/// ```
pub struct CloseGuard {
    allow: bool,
}

impl CloseGuard {
    /// A guard that prompts while documents are dirty.
    pub fn new() -> Self {
        Self::default()
    }

    /// Whether the next close request bypasses the prompt.
    pub fn is_allowed(&self) -> bool {
        self.allow
    }

    /// Whether this close request should be cancelled and the prompt shown.
    ///
    /// Returns `false` when closing is already allowed or nothing is unsaved.
    pub fn should_prompt(&mut self, has_unsaved: bool) -> bool {
        !self.allow && has_unsaved
    }

    /// Let the next close request through.
    pub fn allow(&mut self) {
        self.allow = true;
    }

    /// Return to prompting on the next close request.
    pub fn reset(&mut self) {
        self.allow = false;
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn prompts_only_while_dirty_and_not_allowed() {
        let mut guard = CloseGuard::new();
        assert!(!guard.should_prompt(false));
        assert!(guard.should_prompt(true));
        guard.allow();
        assert!(!guard.should_prompt(true));
        guard.reset();
        assert!(guard.should_prompt(true));
    }
}