moduforge_runtime/
async_runtime.rs

1use std::sync::Arc;
2
3use crate::{
4    event::{Event, EventBus},
5    extension_manager::ExtensionManager,
6    flow::{FlowEngine, ProcessorResult},
7    helpers::create_doc,
8    history_manager::HistoryManager,
9    traits::{EditorBase, EditorCore},
10    types::EditorOptions,
11};
12use async_trait::async_trait;
13use moduforge_core::{
14    debug,
15    model::{node_pool::NodePool, schema::Schema},
16    state::{
17        state::{State, StateConfig},
18        transaction::{Command, Transaction},
19    },
20    transform::transform::Transform,
21};
22
23/// Editor 结构体代表编辑器的核心功能实现
24/// 负责管理文档状态、事件处理、插件系统和存储等核心功能
25pub struct Editor {
26    base: EditorBase,
27    flow_engine: FlowEngine,
28}
29
30impl Editor {
31    /// 创建新的编辑器实例
32    /// options: 编辑器配置选项
33    pub async fn create(
34        options: EditorOptions
35    ) -> Result<Self, Box<dyn std::error::Error>> {
36        debug!("正在创建新的编辑器实例");
37        let extension_manager =
38            ExtensionManager::new(&options.get_extensions());
39        debug!("已初始化扩展管理器");
40        let doc = create_doc::create_doc(
41            &extension_manager.get_schema(),
42            &options.get_content(),
43        )
44        .await;
45        let event_bus = EventBus::new();
46        debug!("已创建文档和事件总线");
47        let state: State = State::create(StateConfig {
48            schema: Some(extension_manager.get_schema()),
49            doc,
50            stored_marks: None,
51            plugins: Some(extension_manager.get_plugins().clone()),
52        })
53        .await?;
54        let state: Arc<State> = Arc::new(state);
55
56        let base = EditorBase {
57            event_bus,
58            state: state.clone(),
59            extension_manager,
60            history_manager: HistoryManager::new(
61                state,
62                options.get_history_limit(),
63            ),
64            options,
65        };
66
67        let mut runtime = Editor { base, flow_engine: FlowEngine::new()? };
68        runtime.init().await?;
69        debug!("编辑器实例创建成功");
70        Ok(runtime)
71    }
72
73    /// 初始化编辑器,设置事件处理器并启动事件循环
74    async fn init(&mut self) -> Result<(), Box<dyn std::error::Error>> {
75        self.base
76            .event_bus
77            .add_event_handlers(self.base.options.get_event_handlers())
78            .await?;
79        self.base.event_bus.start_event_loop();
80        self.base
81            .event_bus
82            .broadcast_blocking(Event::Create(self.base.state.clone()))?;
83        Ok(())
84    }
85}
86#[async_trait]
87impl EditorCore for Editor {
88    type Error = Box<dyn std::error::Error>;
89
90    fn doc(&self) -> Arc<NodePool> {
91        self.base.doc()
92    }
93
94    fn get_options(&self) -> &EditorOptions {
95        self.base.get_options()
96    }
97
98    fn get_state(&self) -> &Arc<State> {
99        self.base.get_state()
100    }
101
102    fn get_schema(&self) -> Arc<Schema> {
103        self.base.get_schema()
104    }
105
106    fn get_event_bus(&self) -> &EventBus {
107        self.base.get_event_bus()
108    }
109
110    fn get_tr(&self) -> Transaction {
111        self.base.get_tr()
112    }
113
114    async fn command(
115        &mut self,
116        command: Arc<dyn Command>,
117    ) -> Result<(), Self::Error> {
118        let mut tr = self.get_tr();
119        tr.transaction(command).await;
120        self.dispatch(tr).await
121    }
122
123    async fn dispatch(
124        &mut self,
125        transaction: Transaction,
126    ) -> Result<(), Self::Error> {
127        let (_id, mut rx) = self
128            .flow_engine
129            .submit_transaction((self.base.state.clone(), transaction))
130            .await?;
131
132        let Some(task_result) = rx.recv().await else {
133            return Ok(());
134        };
135        let Some(ProcessorResult { result: Some(mut result), .. }) =
136            task_result.output
137        else {
138            return Ok(());
139        };
140
141        self.base.state = Arc::new(result.state);
142
143        if let Some(tr) = result.transactions.last() {
144            if tr.doc_changed() {
145                self.base.history_manager.insert(self.base.state.clone());
146                self.base
147                    .event_bus
148                    .broadcast(Event::TrApply(
149                        Arc::new(result.transactions),
150                        self.base.state.clone(),
151                    ))
152                    .await?;
153            }
154        }
155        Ok(())
156    }
157
158    async fn register_plugin(&mut self) -> Result<(), Self::Error> {
159        let state = self
160            .get_state()
161            .reconfigure(StateConfig {
162                schema: Some(self.get_schema()),
163                doc: Some(self.get_state().doc()),
164                stored_marks: None,
165                plugins: Some(self.get_state().plugins().clone()),
166            })
167            .await?;
168        self.base.state = Arc::new(state);
169        Ok(())
170    }
171
172    async fn unregister_plugin(
173        &mut self,
174        plugin_key: String,
175    ) -> Result<(), Self::Error> {
176        let ps = self
177            .get_state()
178            .plugins()
179            .iter()
180            .filter(|p| p.key != plugin_key)
181            .cloned()
182            .collect();
183        let state = self
184            .get_state()
185            .reconfigure(StateConfig {
186                schema: Some(self.get_schema().clone()),
187                doc: Some(self.get_state().doc()),
188                stored_marks: None,
189                plugins: Some(ps),
190            })
191            .await?;
192        self.base.state = Arc::new(state);
193        Ok(())
194    }
195
196    fn undo(&mut self) {
197        self.base.undo()
198    }
199
200    fn redo(&mut self) {
201        self.base.redo()
202    }
203}