tauri_plugin_compmd/lib.rs
1//! `tauri-plugin-compmd`: CompMD's sandbox frames for a Tauri app, served from a scheme of the app's own
2//! (docs/tauri-plugin.md).
3//!
4//! The sandbox (`@compmd/sandbox`) runs a document's components in frames, which need an origin apart from the app's
5//! page. The plugin brings the frames, serves them on a scheme of their own, and tells the page where they are. An app
6//! adds it in one call:
7//!
8//! ```
9//! let app = tauri::Builder::<tauri::Wry>::default().plugin(tauri_plugin_compmd::init());
10//! // then, as every Tauri app: app.run(tauri::generate_context!())
11//! # drop(app);
12//! ```
13//!
14//! and its page opens a sandbox with no `base`, which the plugin gave it:
15//!
16//! ```js
17//! const view = createSandbox({ page: "host" }).open(container, { components: processed.hostComponents });
18//! ```
19//!
20//! [`Builder`] customizes it: another scheme's name, or the app's own build of the frames.
21
22mod command;
23mod content_type;
24mod embedded;
25mod files;
26mod frames;
27mod respond;
28mod scheme;
29mod served;
30
31use std::path::{Path, PathBuf};
32
33pub use files::Files;
34pub use frames::{Build, FRAMES_JSON, Frames};
35pub use served::Served;
36use tauri::plugin::{Builder as PluginBuilder, TauriPlugin};
37use tauri::{Manager, Runtime};
38
39/// The scheme's name when the app gives none, the one the embedded frames are built for.
40pub const SCHEME: &str = "compmd";
41
42/// The plugin as it comes: the embedded frames on the scheme `compmd`, their `base` given to the app's pages.
43///
44/// # Example
45///
46/// ```
47/// let app = tauri::Builder::<tauri::Wry>::default().plugin(tauri_plugin_compmd::init());
48/// # drop(app);
49/// ```
50#[must_use]
51pub fn init<R: Runtime>() -> TauriPlugin<R> {
52 Builder::new().build()
53}
54
55/// The plugin, set up by further calls.
56///
57/// # Example
58///
59/// ```
60/// // Frames the app built itself, with libraries it offers, on a scheme of its own name.
61/// let plugin = tauri_plugin_compmd::Builder::new()
62/// .scheme("myframes")
63/// .frames_dir("sandbox")
64/// .build::<tauri::Wry>();
65/// # drop(plugin);
66/// ```
67#[derive(Clone, Debug)]
68pub struct Builder {
69 scheme: String,
70 frames_dir: Option<PathBuf>,
71}
72
73impl Default for Builder {
74 fn default() -> Self {
75 Self::new()
76 }
77}
78
79impl Builder {
80 /// The plugin with the embedded frames on the scheme `compmd`, as [`init`] gives it.
81 #[must_use]
82 pub fn new() -> Self {
83 Self {
84 scheme: SCHEME.to_owned(),
85 frames_dir: None,
86 }
87 }
88
89 /// The scheme the frames are served on: a name of the app's choosing, lowercase letters, digits, `+`, `-` and
90 /// `.`, starting with a letter. A scheme other than `compmd` needs the app's own build (`frames_dir`), built with
91 /// its `source`, since the embedded frames name `compmd://`.
92 #[must_use]
93 pub fn scheme(mut self, scheme: impl Into<String>) -> Self {
94 self.scheme = scheme.into();
95 self
96 }
97
98 /// The app's own build of the frames (`buildHashedFrames`) in place of the embedded one: the folder holding its
99 /// `frames.json`, relative to the app's resources, or absolute. Its page then asks for `base` with the command
100 /// `plugin:compmd|base`, which `compmd:default` grants, since its hash is known only when the app starts.
101 #[must_use]
102 pub fn frames_dir(mut self, folder: impl Into<PathBuf>) -> Self {
103 self.frames_dir = Some(folder.into());
104 self
105 }
106
107 /// The plugin, named `compmd`: its scheme, the `base` command, the frames, and, for the embedded frames, the
108 /// script that gives the app's pages their `base`.
109 ///
110 /// # Panics
111 ///
112 /// When the scheme's name isn't one, or isn't `compmd` with the embedded frames: mistakes in the app's code.
113 #[must_use]
114 pub fn build<R: Runtime>(self) -> TauriPlugin<R> {
115 let Self { scheme, frames_dir } = self;
116 assert!(is_scheme(&scheme), "`{scheme}` isn't a scheme's name");
117 assert!(
118 frames_dir.is_some() || scheme == SCHEME,
119 "the embedded frames are built for the scheme `{SCHEME}`: the scheme `{scheme}` needs the app's own build (`frames_dir`)"
120 );
121 let embedded = frames_dir.is_none().then(Frames::embedded);
122 let mut plugin =
123 PluginBuilder::new("compmd").invoke_handler(tauri::generate_handler![command::base]);
124 if let Some(base) = embedded.as_ref().and_then(|frames| frames.base(&scheme)) {
125 plugin = plugin.js_init_script(init_script(&base));
126 }
127 let served_scheme = scheme.clone();
128 plugin
129 .register_uri_scheme_protocol(served_scheme, scheme::serve)
130 .setup(move |app, _api| {
131 let frames = embedded.clone().unwrap_or_else(|| {
132 let folder = frames_dir
133 .as_deref()
134 .and_then(|dir| folder_of(dir, app.path().resource_dir().ok()));
135 folder.map_or_else(Frames::none, |folder| Frames::read(&folder))
136 });
137 app.manage(Served {
138 frames,
139 scheme: scheme.clone(),
140 });
141 Ok(())
142 })
143 .build()
144 }
145}
146
147/// The script that gives the app's pages the frames' `base`, as `createSandbox` reads it.
148fn init_script(base: &str) -> String {
149 let base = serde_json::to_string(base).expect("a string serializes");
150 format!("globalThis.__COMPMD__ = Object.freeze({{ base: {base} }});")
151}
152
153/// Where the app's own frames are: `frames` itself when it is absolute, else under the app's `resources`; none when
154/// those can't be found, so the app starts with no frames, and gives no `base`.
155fn folder_of(frames: &Path, resources: Option<PathBuf>) -> Option<PathBuf> {
156 if frames.is_absolute() {
157 Some(frames.to_path_buf())
158 } else {
159 resources.map(|resources| resources.join(frames))
160 }
161}
162
163/// Whether `name` is a scheme's name (RFC 3986): a letter, then letters, digits, `+`, `-` or `.`; lowercase, as
164/// webviews compare them.
165fn is_scheme(name: &str) -> bool {
166 let mut bytes = name.bytes();
167 bytes.next().is_some_and(|first| first.is_ascii_lowercase())
168 && bytes.all(|byte| {
169 byte.is_ascii_lowercase() || byte.is_ascii_digit() || matches!(byte, b'+' | b'-' | b'.')
170 })
171}
172
173/// What the plugin gives Rust code of the app.
174pub trait CompmdExt<R: Runtime> {
175 /// The frames the app serves, and their scheme.
176 fn compmd(&self) -> &Served;
177}
178
179impl<R: Runtime, T: Manager<R>> CompmdExt<R> for T {
180 fn compmd(&self) -> &Served {
181 self.state::<Served>().inner()
182 }
183}
184
185#[cfg(test)]
186mod tests;