moduforge_runtime/
traits.rs

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