moduforge_runtime/
traits.rs

1use std::sync::Arc;
2use crate::{
3    event::EventBus, extension_manager::ExtensionManager,
4    history_manager::HistoryManager, types::EditorOptions,
5};
6use async_trait::async_trait;
7
8use moduforge_state::{
9    state::State,
10    transaction::{Command, Transaction},
11};
12use moduforge_model::{node_pool::NodePool, schema::Schema};
13/// 定义编辑器核心功能的基础特征
14#[async_trait]
15pub trait EditorCore {
16    type Error;
17
18    /// 获取当前文档内容
19    fn doc(&self) -> Arc<NodePool>;
20
21    /// 获取编辑器配置选项
22    fn get_options(&self) -> &EditorOptions;
23
24    /// 获取当前状态
25    fn get_state(&self) -> &Arc<State>;
26
27    /// 获取文档模式定义
28    fn get_schema(&self) -> Arc<Schema>;
29
30    /// 获取事件总线实例
31    fn get_event_bus(&self) -> &EventBus;
32
33    /// 创建新的事务实例
34    fn get_tr(&self) -> Transaction;
35
36    /// 执行自定义命令
37    async fn command(
38        &mut self,
39        command: Arc<dyn Command>,
40    ) -> Result<(), Self::Error>;
41
42    /// 处理事务并更新状态
43    async fn dispatch(
44        &mut self,
45        transaction: Transaction,
46    ) -> Result<(), Self::Error>;
47
48    /// 注册新插件
49    async fn register_plugin(&mut self) -> Result<(), Self::Error>;
50
51    /// 注销插件
52    async fn unregister_plugin(
53        &mut self,
54        plugin_key: String,
55    ) -> Result<(), Self::Error>;
56
57    /// 执行撤销操作
58    fn undo(&mut self);
59
60    /// 执行重做操作
61    fn redo(&mut self);
62}
63
64/// 编辑器的基础结构,包含共享字段
65pub struct EditorBase {
66    pub event_bus: EventBus,
67    pub state: Arc<State>,
68    pub extension_manager: ExtensionManager,
69    pub history_manager: HistoryManager<Arc<State>>,
70    pub options: EditorOptions,
71}
72
73impl EditorBase {
74    /// 共享的基础实现方法
75    pub fn doc(&self) -> Arc<NodePool> {
76        self.state.doc()
77    }
78
79    pub fn get_options(&self) -> &EditorOptions {
80        &self.options
81    }
82
83    pub fn get_state(&self) -> &Arc<State> {
84        &self.state
85    }
86
87    pub fn get_schema(&self) -> Arc<Schema> {
88        self.extension_manager.get_schema()
89    }
90
91    pub fn get_event_bus(&self) -> &EventBus {
92        &self.event_bus
93    }
94
95    pub fn get_tr(&self) -> Transaction {
96        let tr = self.get_state().tr();
97        tr
98    }
99
100    pub fn undo(&mut self) {
101        self.history_manager.jump(-1);
102        self.state = self.history_manager.get_present();
103    }
104
105    pub fn redo(&mut self) {
106        self.history_manager.jump(1);
107        self.state = self.history_manager.get_present();
108    }
109}