Skip to main content

tauri_plugin_compmd/
lib.rs

1//! `tauri-plugin-compmd`: the Tauri adapter of CompMD's hosting (docs/tauri-plugin.md, docs/hosting.md).
2//!
3//! What every host does is shared: the configuration, the bundle `@compmd/vite` builds from the page's own
4//! `@compmd/sandbox`, the pack store and the serving contract (`compmd-host`). The plugin does the four things only
5//! Tauri can: it embeds the bundle in the app, serves it on the scheme the bundle was built for, gives the page the
6//! origin, and gives the store a folder.
7//!
8//! The bundle is written by `@compmd/vite` (`compmd({ out: "src-tauri/compmd", source: "compmd://localhost/" })`);
9//! the app's `build.rs` embeds it, with the `build` feature:
10//!
11//! ```no_run
12//! # #[cfg(feature = "build")]
13//! tauri_plugin_compmd::build::bundle("compmd");
14//! ```
15//!
16//! and its `main` passes it to the plugin:
17//!
18//! ```ignore
19//! tauri::Builder::default().plugin(tauri_plugin_compmd::init(tauri_plugin_compmd::include_bundle!()))
20//! ```
21//!
22//! The page then takes everything from its own bundle and the origin from the plugin, and passes nothing:
23//!
24//! ```js
25//! import { sandbox } from "virtual:compmd";
26//! const view = createSandbox({ ...sandbox, page: "host" }).open(container, { components });
27//! ```
28
29#[cfg(feature = "build")]
30pub mod build;
31#[cfg(feature = "build")]
32mod build_error;
33mod compmd;
34mod origin;
35mod scheme;
36
37use std::path::PathBuf;
38use std::sync::Arc;
39
40pub use compmd::Compmd;
41/// The shared layers of hosting: the bundle, the store and the serving contract.
42pub use compmd_host;
43use compmd_host::{Bundle, FolderStore, NoStore, Store};
44use tauri::plugin::{Builder, TauriPlugin};
45use tauri::{Manager, Runtime};
46
47#[cfg(feature = "build")]
48pub use build_error::BuildError;
49
50/// The bundle `build::bundle` embedded in the app, or `None` when the build found none (with a warning then): the
51/// plugin then serves nothing, and the page reports that its frames didn't load.
52///
53/// ```ignore
54/// tauri::Builder::default().plugin(tauri_plugin_compmd::init(tauri_plugin_compmd::include_bundle!()))
55/// ```
56#[macro_export]
57macro_rules! include_bundle {
58    () => {
59        $crate::embedded(include!(concat!(env!("OUT_DIR"), "/compmd_bundle.rs")))
60    };
61}
62
63/// The bundle of the files `build::bundle` embedded, for [`include_bundle!`]; none when there are none.
64#[doc(hidden)]
65#[must_use]
66pub fn embedded(files: Option<&'static [(&'static str, &'static [u8])]>) -> Option<Bundle> {
67    files.and_then(|files| Bundle::embedded(files).ok())
68}
69
70/// The plugin, serving `bundle` on the scheme its manifest names (`compmd`), with the origin given to the app's pages
71/// and the pack store in the app's data folder.
72///
73/// # Panics
74///
75/// When the bundle's scheme isn't a scheme's name, or it was built without one (`source`): mistakes in the app's
76/// build, which `build::bundle` refuses already.
77///
78/// # Example
79///
80/// ```
81/// # use compmd_host::Bundle;
82/// let bundle = Bundle::from_files([(
83///     "manifest.json",
84///     br#"{"format": 1, "frames": {"hash": "1df336e75685de8c"}, "source": "compmd://localhost/"}"#.to_vec(),
85/// )])?;
86/// let app = tauri::Builder::<tauri::Wry>::default().plugin(tauri_plugin_compmd::init(bundle));
87/// # drop(app);
88/// # Ok::<(), compmd_host::BundleError>(())
89/// ```
90#[must_use]
91pub fn init<R: Runtime>(bundle: impl Into<Option<Bundle>>) -> TauriPlugin<R> {
92    let bundle = bundle.into();
93    let scheme = bundle.as_ref().map(|bundle| {
94        let scheme = bundle.manifest().scheme();
95        let scheme = scheme.unwrap_or_else(|| panic!("{}", BUILT_WITHOUT_SOURCE));
96        assert!(
97            origin::is_scheme(scheme),
98            "`{scheme}` isn't a scheme's name"
99        );
100        scheme.to_owned()
101    });
102    let origin = scheme.as_deref().map(origin::origin_of);
103    let mut plugin = Builder::new("compmd");
104    if let (Some(scheme), Some(origin)) = (&scheme, &origin) {
105        plugin = plugin
106            .js_init_script(origin::init_script(origin))
107            .register_uri_scheme_protocol(scheme.clone(), scheme::serve);
108    }
109    plugin
110        .setup(move |app, _api| {
111            let store = store_in(app.path().app_data_dir().ok());
112            app.manage(Compmd::new(bundle, origin, store));
113            Ok(())
114        })
115        .build()
116}
117
118/// The pack store in the app's data folder, `compmd/packs/` there (docs/tauri-plugin.md, decision 11); none when the
119/// platform gives the app no data folder.
120fn store_in(data: Option<PathBuf>) -> Arc<dyn Store> {
121    data.map_or_else(
122        || Arc::new(NoStore) as Arc<dyn Store>,
123        |data| Arc::new(FolderStore::new(data.join("compmd").join("packs"))),
124    )
125}
126
127/// Why a bundle built for an http origin can't be served on a scheme.
128pub(crate) const BUILT_WITHOUT_SOURCE: &str = "the bundle was built without a `source`, so it names no scheme: build it with the scheme it is served on, `compmd({ out, source: \"compmd://localhost/\" })`";
129
130/// What the plugin gives Rust code of the app.
131pub trait CompmdExt<R: Runtime> {
132    /// The bundle the app serves, its origin and the pack store.
133    fn compmd(&self) -> &Compmd;
134}
135
136impl<R: Runtime, T: Manager<R>> CompmdExt<R> for T {
137    fn compmd(&self) -> &Compmd {
138        self.state::<Compmd>().inner()
139    }
140}
141
142#[cfg(test)]
143mod tests;