ratatui_kit/hooks/
use_exit.rs

1use std::sync::Arc;
2
3use crate::{SystemContext, UseContext, UseState};
4
5mod private {
6    pub trait Sealed {}
7    impl Sealed for crate::hooks::Hooks<'_, '_> {}
8}
9
10pub trait UseExit: private::Sealed {
11    /// 注册退出回调,组件卸载时调用,适合清理资源、保存状态等场景。
12    fn use_exit(&mut self) -> impl FnMut() + Send + 'static;
13}
14
15impl UseExit for crate::hooks::Hooks<'_, '_> {
16    fn use_exit(&mut self) -> impl FnMut() + Send + 'static {
17        let mut state = self.use_state(|| false);
18        let mut system_ctx = self.use_context_mut::<SystemContext>();
19
20        if state.get() {
21            system_ctx.exit();
22        }
23
24        move || {
25            if !state.get() {
26                state.set(true);
27            }
28        }
29    }
30}