Skip to main content

taba_tauri/
lib.rs

1//! Taba's Tauri transport
2#![cfg_attr(docsrs, feature(doc_cfg))]
3
4use std::{borrow::Cow, fmt, sync::Arc};
5
6use serde_core::Deserialize as _;
7use taba::rpc::{Router, Sessions};
8use tauri::{
9    App, Builder, Context, Runtime, WindowEvent, async_runtime,
10    ipc::{Invoke, InvokeBody, InvokeError},
11    plugin::{self, TauriPlugin},
12};
13
14/// A [`tauri::Builder`] answering Taba, wrapped to protect the invoke handler.
15///
16/// This overwrites any previous `invoke_handler`, so all previous commands reject as not found.
17/// If you want those commands handled, pass them to [`WithTaba::with_fallback`] instead.
18///
19/// Making one takes Tauri's async runtime, so an app that sets its own with
20/// [`tauri::async_runtime::set`] has to do so first.
21pub struct WithTaba<R: Runtime>(Builder<R>);
22
23impl<R: Runtime> WithTaba<R> {
24    /// Answers only Taba commands, with `router`.
25    pub fn new(builder: Builder<R>, router: Router) -> Self {
26        Self::with_fallback(builder, router, |_| false)
27    }
28
29    /// Answers Taba commands with `router`, otherwise passing through to `fallback`.
30    pub fn with_fallback<F>(builder: Builder<R>, router: Router, fallback: F) -> Self
31    where
32        F: Fn(Invoke<R>) -> bool + Send + Sync + 'static,
33    {
34        let runtime = async_runtime::handle().inner().clone();
35        let sessions = Arc::new(Sessions::new(router, runtime));
36        let destroyed = Arc::clone(&sessions);
37        let builder = builder
38            .plugin(injected())
39            .on_window_event(move |window, event| {
40                if let WindowEvent::Destroyed = event {
41                    destroyed.end(window.label());
42                }
43            })
44            .invoke_handler(handler(sessions, fallback));
45        Self(builder)
46    }
47
48    /// [`tauri::Builder::run`].
49    ///
50    /// # Errors
51    ///
52    /// The app failed to build or run.
53    pub fn run(self, context: Context<R>) -> tauri::Result<()> {
54        self.0.run(context)
55    }
56
57    /// [`tauri::Builder::build`].
58    ///
59    /// # Errors
60    ///
61    /// The app failed to build.
62    pub fn build(self, context: Context<R>) -> tauri::Result<App<R>> {
63        self.0.build(context)
64    }
65}
66
67impl<R: Runtime> fmt::Debug for WithTaba<R> {
68    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
69        f.debug_struct("WithTaba").finish_non_exhaustive()
70    }
71}
72
73/// Helpers for [`WithTaba`].
74pub trait BuilderExt<R: Runtime> {
75    /// [`WithTaba::new`].
76    fn taba(self, router: Router) -> WithTaba<R>;
77
78    /// [`WithTaba::with_fallback`].
79    fn taba_with_fallback<F>(self, router: Router, fallback: F) -> WithTaba<R>
80    where
81        F: Fn(Invoke<R>) -> bool + Send + Sync + 'static;
82}
83
84impl<R: Runtime> BuilderExt<R> for Builder<R> {
85    fn taba(self, router: Router) -> WithTaba<R> {
86        WithTaba::new(self, router)
87    }
88
89    fn taba_with_fallback<F>(self, router: Router, fallback: F) -> WithTaba<R>
90    where
91        F: Fn(Invoke<R>) -> bool + Send + Sync + 'static,
92    {
93        WithTaba::with_fallback(self, router, fallback)
94    }
95}
96
97/// A minimal plugin for the init script.
98fn injected<R: Runtime>() -> TauriPlugin<R> {
99    plugin::Builder::new("taba").js_init_script(include_str!("injected.js")).build()
100}
101
102/// Answers Taba commands from `sessions`, using webview labels for the session address.
103fn handler<R: Runtime, F>(sessions: Arc<Sessions>, fallback: F) -> impl Fn(Invoke<R>) -> bool
104where
105    F: Fn(Invoke<R>) -> bool,
106{
107    move |invoke| {
108        let label = invoke.message.webview_ref().label();
109        match invoke.message.command() {
110            "taba::connect" => {
111                // a reload keeps the label
112                sessions.end(label);
113                invoke.resolver.resolve(sessions.connect(label));
114            }
115            "taba::send" => {
116                let sent = bytes(invoke.message.payload())
117                    .and_then(|body| sessions.send(label, &body).map_err(InvokeError::from_error));
118                invoke.resolver.respond(sent);
119            }
120            "taba::poll" => {
121                let poll = bytes(invoke.message.payload()).map(|body| sessions.poll(label, &body));
122                let frame = async move { poll?.await.map_err(InvokeError::from_error) };
123                invoke.resolver.respond_async(frame);
124            }
125            _ => return fallback(invoke),
126        }
127        true
128    }
129}
130
131/// A `Uint8Array` body's bytes.
132///
133/// It arrives raw, or as a JSON array of numbers when Tauri falls back to `postMessage`.
134fn bytes(body: &InvokeBody) -> Result<Cow<'_, [u8]>, InvokeError> {
135    match body {
136        InvokeBody::Raw(bytes) => Ok(Cow::Borrowed(bytes)),
137        InvokeBody::Json(numbers) => {
138            Vec::<u8>::deserialize(numbers).map(Cow::Owned).map_err(InvokeError::from_error)
139        }
140    }
141}
142
143#[cfg(test)]
144mod tests {
145    use serde_json::{Value, json};
146    use taba::rpc::{Router, SessionId};
147    use tauri::{
148        App, WebviewUrl, WebviewWindow, WebviewWindowBuilder,
149        http::HeaderMap,
150        ipc::{CallbackFn, Invoke, InvokeBody, InvokeResponseBody},
151        test::{
152            INVOKE_KEY, MockRuntime, get_ipc_response, mock_builder, mock_context, noop_assets,
153        },
154        webview::InvokeRequest,
155    };
156
157    use super::{BuilderExt, WithTaba};
158
159    /// A Tauri app on Tauri's mock runtime.
160    struct Mock(App<MockRuntime>);
161
162    impl Mock {
163        fn new(with_taba: WithTaba<MockRuntime>) -> Self {
164            Self(with_taba.build(mock_context(noop_assets())).unwrap())
165        }
166
167        fn webview(&self, label: &str) -> Webview {
168            let builder = WebviewWindowBuilder::new(&self.0, label, WebviewUrl::default());
169            Webview(builder.build().unwrap())
170        }
171    }
172
173    /// One webview of a [`Mock`].
174    struct Webview(WebviewWindow<MockRuntime>);
175
176    impl Webview {
177        /// Invokes `command` from the webview's URL, which Tauri treats as local.
178        fn invoke(&self, command: &str, body: InvokeBody) -> String {
179            let request = InvokeRequest {
180                cmd: command.to_owned(),
181                callback: CallbackFn(0),
182                error: CallbackFn(1),
183                url: self.0.url().unwrap(),
184                body,
185                headers: HeaderMap::new(),
186                invoke_key: INVOKE_KEY.to_owned(),
187            };
188            match get_ipc_response(&self.0, request) {
189                Ok(InvokeResponseBody::Json(json)) => json,
190                Ok(InvokeResponseBody::Raw(raw)) => String::from_utf8(raw).unwrap(),
191                Err(error) => format!("rejected: {error}"),
192            }
193        }
194
195        fn connect(&self) -> SessionId {
196            serde_json::from_str(&self.invoke("taba::connect", InvokeBody::default())).unwrap()
197        }
198
199        /// Sends `batch` as `id`'s session, as raw bytes.
200        fn send(&self, id: SessionId, batch: Value) -> String {
201            let body = serde_json::to_vec(&json!([id, batch])).unwrap();
202            self.invoke("taba::send", InvokeBody::Raw(body))
203        }
204    }
205
206    fn router() -> Router {
207        Router::builder([]).build().unwrap()
208    }
209
210    #[test]
211    fn a_second_connect_ends_the_first() {
212        let mock = Mock::new(mock_builder().taba(router()));
213        let main = mock.webview("main");
214        let first = main.connect();
215        let second = main.connect();
216        let sends = [first, second].map(|id| main.send(id, json!([])));
217        insta::assert_snapshot!(sends.join("\n"), @r#"
218        rejected: "this session has ended"
219        null
220        "#);
221    }
222
223    #[test]
224    fn each_webview_has_its_own_sessions() {
225        let mock = Mock::new(mock_builder().taba(router()));
226        let main = mock.webview("main");
227        let second = mock.webview("second");
228        let id = main.connect();
229        second.connect();
230        let sends = [main.send(id, json!([])), second.send(id, json!([]))];
231        insta::assert_snapshot!(sends.join("\n"), @r#"
232        null
233        rejected: "this session has ended"
234        "#);
235    }
236
237    #[test]
238    fn a_json_body_reads_as_bytes() {
239        let mock = Mock::new(mock_builder().taba(router()));
240        let main = mock.webview("main");
241        let id = main.connect();
242        let numbers = Value::from(serde_json::to_vec(&json!([id, []])).unwrap());
243        insta::assert_snapshot!(main.invoke("taba::send", InvokeBody::Json(numbers)), @"null");
244    }
245
246    #[test]
247    fn other_commands_reach_the_fallback() {
248        let greet = |invoke: Invoke<MockRuntime>| match invoke.message.command() {
249            "greet" => {
250                invoke.resolver.resolve("hello");
251                true
252            }
253            _ => false,
254        };
255        let mock = Mock::new(mock_builder().taba_with_fallback(router(), greet));
256        let main = mock.webview("main");
257        let answers = [
258            main.invoke("greet", InvokeBody::default()),
259            main.invoke("taba::connect", InvokeBody::default()),
260        ];
261        insta::assert_snapshot!(answers.join("\n"), @r#"
262        "hello"
263        0
264        "#);
265    }
266}