yggdrasil/codemirror_bridge.rs
1//! CodeMirror 编辑器的 wasm-bindgen 绑定层。
2//!
3//! 封装与 `window.CodeMirrorEditor`(IIFE 暴露的全局对象字面量)的全部交互,
4//! 严格镜像 [`crate::tiptap_bridge`] 的结构:共享纯数据类型双目标编译,
5//! wasm-bindgen extern + `EditorHandle` 仅在 WASM 前端编译(server 构建无 window)。
6//!
7//! 与 tiptap 一样,`CodeMirrorEditor` 是 IIFE 挂在 window 上的**对象字面量**
8//! (`{ create }`),不是函数——因此用 `js_sys::Reflect::get` 做属性访问拿到,
9//! 不能用 wasm-bindgen 的 extern fn(那会被编成函数调用,"not a function")。
10
11use serde::{Deserialize, Serialize};
12
13/// SQL 补全用 schema 数据,由 `get_db_schema` server function 填充。
14#[derive(Serialize, Deserialize, Clone, Default, Debug)]
15pub struct SqlSchema {
16 pub tables: Vec<SqlTable>,
17}
18
19/// 单张表的补全数据:表名 + 列名列表。
20#[derive(Serialize, Deserialize, Clone, Debug)]
21pub struct SqlTable {
22 pub name: String,
23 pub columns: Vec<String>,
24}
25
26// ============================================================================
27// 以下全部仅在 WASM 前端编译:wasm-bindgen extern + EditorHandle + 闭包。
28// 放在 #[cfg] 子模块内,避免 server 构建尝试编译引用 JS 对象的 extern。
29// ============================================================================
30#[cfg(target_arch = "wasm32")]
31pub mod wasm {
32 use wasm_bindgen::prelude::*;
33 use wasm_bindgen::JsCast;
34
35 // —— window.CodeMirrorEditor 模块对象 ——
36 //
37 // CodeMirrorEditor 是 IIFE 产物挂在 window 上的对象字面量(含 create 方法),
38 // 不是函数。wasm-bindgen 对 `fn get_module() -> T` 形式的 extern 会生成
39 // `window.CodeMirrorEditor()`(函数调用),会因 "not a function" 失败。
40 // 因此用 js_sys::Reflect::get 做属性访问拿到模块对象,再 unchecked_into。
41 #[wasm_bindgen]
42 extern "C" {
43 /// `window.CodeMirrorEditor` 模块对象的 Rust 映射(IIFE 产物挂在 window 上的对象字面量)。
44 /// 不是函数——通过 [`get_module`] 用 Reflect::get 取属性而非 extern fn 调用拿到。
45 pub type CodeMirrorEditorModule;
46
47 /// 调用 `CodeMirrorEditor.create(containerId, opts)`。
48 /// 找不到容器返回 null(被 Option 捕获);构造失败抛异常(被 catch 捕获)。
49 #[wasm_bindgen(method, catch)]
50 pub fn create(
51 this: &CodeMirrorEditorModule,
52 container_id: &str,
53 opts: &EditorOptions,
54 ) -> Result<Option<EditorInstance>, JsValue>;
55 }
56
57 /// 读取 `window.CodeMirrorEditor`(IIFE 默认导出,顶层 var 即 window 属性)。
58 /// 用 Reflect::get 做属性访问——extern fn 形式会被 wasm-bindgen 编成函数调用。
59 ///
60 /// 用 unchecked_into 而非 dyn_into:CodeMirrorEditor 是 JS 对象字面量,
61 /// 不是 wasm-bindgen 注册的构造函数实例,dyn_into 的 instanceof 检查必然失败。
62 /// unchecked_into 只做编译期类型标注,不做运行时校验
63 /// (Reflect.get 已保证拿到的是目标对象)。
64 pub fn get_module() -> CodeMirrorEditorModule {
65 let window = web_sys::window().expect("no window");
66 let val = js_sys::Reflect::get(&window, &"CodeMirrorEditor".into())
67 .expect("window.CodeMirrorEditor missing");
68 val.unchecked_into::<CodeMirrorEditorModule>()
69 }
70
71 // —— 编辑器实例(CodeMirrorInstance)——
72 #[wasm_bindgen]
73 extern "C" {
74 /// `CodeMirrorEditor.create` 返回的编辑器实例对象,承载 CodeMirror EditorView。
75 pub type EditorInstance;
76
77 /// 返回当前文档全文。
78 #[wasm_bindgen(method, js_name = getValue)]
79 pub fn get_value(this: &EditorInstance) -> String;
80
81 /// 替换整个文档内容(dispatch changes,触发 onChange)。
82 #[wasm_bindgen(method, js_name = setValue)]
83 pub fn set_value(this: &EditorInstance, s: &str);
84
85 /// 热切换主题(Compartment.reconfigure,不重建实例)。
86 #[wasm_bindgen(method, js_name = setTheme)]
87 pub fn set_theme(this: &EditorInstance, theme: &str);
88
89 /// 热切换 Vim 模式(Compartment.reconfigure,不重建实例)。
90 #[wasm_bindgen(method, js_name = setVim)]
91 pub fn set_vim(this: &EditorInstance, v: bool);
92
93 /// 热切换语言(python/node/javascript/sql,Compartment.reconfigure)。
94 /// 由 CodeRunner 组件在挂载时按 data-lang 调用。
95 #[wasm_bindgen(method, js_name = setLanguage)]
96 pub fn set_language(this: &EditorInstance, lang: &str);
97
98 /// 更新 SQL 补全 schema(Compartment.reconfigure)。
99 /// 参数为 serde_wasm_bindgen::to_value 序列化后的 JsValue
100 ///(SqlSchema 是 serde 类型,非 wasm-bindgen 类型,故不能直接传 &SqlSchema)。
101 #[wasm_bindgen(method, js_name = setSchema)]
102 pub fn set_schema(this: &EditorInstance, schema: &wasm_bindgen::JsValue);
103
104 /// 让编辑器获取焦点。
105 #[wasm_bindgen(method)]
106 pub fn focus(this: &EditorInstance);
107
108 /// 销毁编辑器,释放 JS 侧资源。
109 #[wasm_bindgen(method)]
110 pub fn destroy(this: &EditorInstance);
111 }
112
113 // —— EditorOptions:用 builder 模式(setter)构造 JS 对象 ——
114 #[wasm_bindgen]
115 extern "C" {
116 /// 传给 `CodeMirrorEditor.create` 的配置对象,对应 JS 侧的 EditorOptions。
117 /// 用 `new()` 创建空对象后通过 setter 链式设置字段。
118 pub type EditorOptions;
119
120 /// 构造一个空的 EditorOptions,随后用各 setter 填充。
121 #[wasm_bindgen(constructor)]
122 pub fn new() -> EditorOptions;
123
124 /// 语言(默认 'sql')。
125 #[wasm_bindgen(method, setter, js_name = language)]
126 pub fn set_language(this: &EditorOptions, v: &str);
127
128 /// 主题:'light'(Catppuccin Latte)或 'dark'(Catppuccin Mocha)。
129 #[wasm_bindgen(method, setter, js_name = theme)]
130 pub fn set_theme(this: &EditorOptions, v: &str);
131
132 /// 是否启用 Vim keymap。
133 #[wasm_bindgen(method, setter, js_name = vim)]
134 pub fn set_vim(this: &EditorOptions, v: bool);
135
136 /// SQL 补全 schema(表/列数据)。v 为 serde_wasm_bindgen::to_value 序列化结果。
137 #[wasm_bindgen(method, setter, js_name = schema)]
138 pub fn set_schema(this: &EditorOptions, v: &wasm_bindgen::JsValue);
139
140 /// 初始文档内容。
141 #[wasm_bindgen(method, setter, js_name = value)]
142 pub fn set_value(this: &EditorOptions, v: &str);
143
144 /// 文档变更回调(参数为最新全文)。
145 #[wasm_bindgen(method, setter, js_name = onChange)]
146 pub fn set_on_change(this: &EditorOptions, cb: &Closure<dyn FnMut(String)>);
147
148 /// 编辑器就绪回调(构造末尾同步触发一次)。
149 #[wasm_bindgen(method, setter, js_name = onReady)]
150 pub fn set_on_ready(this: &EditorOptions, cb: &Closure<dyn FnMut()>);
151
152 /// Ctrl/Cmd + Enter 快捷键回调(SQL 控制台触发执行)。
153 #[wasm_bindgen(method, setter, js_name = onRunShortcut)]
154 pub fn set_on_run_shortcut(this: &EditorOptions, cb: &Closure<dyn FnMut()>);
155 }
156
157 /// 编辑器实例句柄:持有 instance + 所有 Closure,Drop 时销毁实例并释放闭包。
158 ///
159 /// 闭包字段 `_` 前缀表示仅用于保持生命周期——它们被注入 JS 后,JS 侧持有
160 /// 函数引用;只要 [`EditorHandle`] 存活,闭包就不会被回收。Drop 时随结构释放。
161 pub struct EditorHandle {
162 instance: EditorInstance,
163 _on_change: Closure<dyn FnMut(String)>,
164 _on_ready: Closure<dyn FnMut()>,
165 _on_run_shortcut: Closure<dyn FnMut()>,
166 }
167
168 impl EditorHandle {
169 /// 调用方须先把各 closure set 进 EditorOptions,再 create,
170 /// 然后把返回的 instance + 同名 closure 一起传入 new。
171 /// `on_run_shortcut` 对应 Ctrl/Cmd+Enter 回调;不用该功能时传 no-op 闭包。
172 pub fn new(
173 instance: EditorInstance,
174 on_change: Closure<dyn FnMut(String)>,
175 on_ready: Closure<dyn FnMut()>,
176 on_run_shortcut: Closure<dyn FnMut()>,
177 ) -> Self {
178 Self {
179 instance,
180 _on_change: on_change,
181 _on_ready: on_ready,
182 _on_run_shortcut: on_run_shortcut,
183 }
184 }
185
186 /// 借用底层实例,供宿主调 getValue/setTheme/setSchema 等。
187 pub fn instance(&self) -> &EditorInstance {
188 &self.instance
189 }
190 }
191
192 impl Drop for EditorHandle {
193 fn drop(&mut self) {
194 // 销毁 JS 侧编辑器;随后 _on_change/_on_ready 字段按声明顺序释放,
195 // 释放 wasm-bindgen 函数表槽位。
196 self.instance.destroy();
197 }
198 }
199}
200
201#[cfg(target_arch = "wasm32")]
202pub use wasm::*;