Skip to main content

tauri_plugin_js/
lib.rs

1use tauri::{
2    plugin::{Builder, TauriPlugin},
3    Manager, RunEvent, Runtime,
4};
5
6pub use models::*;
7
8#[cfg(desktop)]
9mod desktop;
10#[cfg(mobile)]
11mod mobile;
12
13mod commands;
14mod error;
15mod models;
16
17pub use error::{Error, Result};
18
19#[cfg(desktop)]
20use desktop::Js;
21#[cfg(mobile)]
22use mobile::Js;
23
24/// Extensions to [`tauri::App`], [`tauri::AppHandle`] and [`tauri::Window`] to access the js APIs.
25pub trait JsExt<R: Runtime> {
26    fn js(&self) -> &Js<R>;
27}
28
29impl<R: Runtime, T: Manager<R>> crate::JsExt<R> for T {
30    fn js(&self) -> &Js<R> {
31        self.state::<Js<R>>().inner()
32    }
33}
34
35/// Initializes the plugin.
36pub fn init<R: Runtime>() -> TauriPlugin<R> {
37    Builder::new("js")
38        .invoke_handler(tauri::generate_handler![
39            commands::spawn,
40            commands::kill,
41            commands::kill_all,
42            commands::restart,
43            commands::list_processes,
44            commands::get_status,
45            commands::write_stdin,
46            commands::detect_runtimes,
47            commands::set_runtime_path,
48            commands::get_runtime_paths,
49        ])
50        .setup(|app, api| {
51            #[cfg(mobile)]
52            let js = mobile::init(app, api)?;
53            #[cfg(desktop)]
54            let js = desktop::init(app, api)?;
55            app.manage(js);
56            Ok(())
57        })
58        .on_event(|app, event| {
59            if let RunEvent::Exit = event {
60                let js = app.state::<Js<R>>();
61                tauri::async_runtime::block_on(async {
62                    let _ = js.kill_all().await;
63                });
64            }
65        })
66        .build()
67}