tauri_plugin_compmd/compmd.rs
1//! What the plugin keeps for the app: the bundle, its origin and the pack store.
2
3use std::sync::Arc;
4
5use compmd_host::{Bundle, Store, respond};
6use tauri::http::{Request, Response, StatusCode};
7
8/// The bundle the app serves, where, and the store of the packs it fetches, as the app's state (`app.compmd()`). The
9/// bundle and the store are shared, so the processor can keep them as its packs (`packs`).
10pub struct Compmd {
11 bundle: Option<Arc<Bundle>>,
12 origin: Option<String>,
13 store: Arc<dyn Store>,
14}
15
16/// Why the scheme serves nothing without a bundle.
17const NO_BUNDLE: &str = "this app has no bundle: build it with @compmd/vite before the app";
18
19impl Compmd {
20 /// The state of an app serving `bundle` at `origin`, with `store`.
21 pub(crate) fn new(
22 bundle: Option<Bundle>,
23 origin: Option<String>,
24 store: Arc<dyn Store>,
25 ) -> Self {
26 Self {
27 bundle: bundle.map(Arc::new),
28 origin,
29 store,
30 }
31 }
32
33 /// The bundle, when the app's build embedded one.
34 #[must_use]
35 pub fn bundle(&self) -> Option<&Bundle> {
36 self.bundle.as_deref()
37 }
38
39 /// Where the bundle is served, as the page has it in `__COMPMD__`: `compmd://localhost`, or
40 /// `http://compmd.localhost` on Windows and Android.
41 #[must_use]
42 pub fn origin(&self) -> Option<&str> {
43 self.origin.as_deref()
44 }
45
46 /// The store of the packs the app fetches, in its data folder.
47 #[must_use]
48 pub fn store(&self) -> &dyn Store {
49 self.store.as_ref()
50 }
51
52 /// The answer to a webview's `request` on the scheme: the serving contract (`compmd-host`'s `respond`), or a
53 /// `404` saying why when there is no bundle.
54 #[must_use]
55 pub fn respond<B>(&self, request: &Request<B>) -> Response<Vec<u8>> {
56 self.bundle.as_ref().map_or_else(
57 || {
58 let mut response = Response::new(NO_BUNDLE.as_bytes().to_vec());
59 *response.status_mut() = StatusCode::NOT_FOUND;
60 response
61 },
62 |bundle| respond(bundle, self.store(), request),
63 )
64 }
65
66 /// The processor's packs: the bundle's, then the store's, the same files the frames load; none without a bundle.
67 ///
68 /// ```ignore
69 /// let packs = app.compmd().packs().expect("a bundle");
70 /// let processor = Processor::new(path, text).parse(&ParseOptions::default()).resolve((), packs, &ambient);
71 /// ```
72 #[cfg(feature = "processor")]
73 #[must_use]
74 pub fn packs(&self) -> Option<compmd_host::HostPacks> {
75 let bundle = Arc::clone(self.bundle.as_ref()?);
76 Some(compmd_host::HostPacks::new(bundle, Arc::clone(&self.store)))
77 }
78}