Skip to content

Commit

Permalink
cleanup
Browse files Browse the repository at this point in the history
  • Loading branch information
Brendonovich committed Sep 2, 2023
1 parent f293417 commit aeda797
Show file tree
Hide file tree
Showing 5 changed files with 108 additions and 86 deletions.
30 changes: 18 additions & 12 deletions example/src-tauri/src/main.rs
Original file line number Diff line number Diff line change
Expand Up @@ -51,19 +51,25 @@ pub struct DemoEvent(String);
pub struct EmptyEvent;

fn main() {
let specta_builder = {
let specta_builder = ts::builder()
.commands(tauri_specta::collect_commands![
hello_world,
goodbye_world,
has_error,
nested::some_struct
])
.events(tauri_specta::collect_events![DemoEvent, EmptyEvent])
.config(specta::ts::ExportConfig::default().formatter(specta::ts::prettier));

#[cfg(debug_assertions)]
let specta_builder = specta_builder.path("../src/bindings.ts");

specta_builder.into_plugin()
};

tauri::Builder::default()
.plugin(
ts::Exporter::new("../src/bindings.ts")
.commands(tauri_specta::collect_commands![
hello_world,
goodbye_world,
has_error,
nested::some_struct
])
.events(tauri_specta::collect_events![DemoEvent, EmptyEvent])
.cfg(specta::ts::ExportConfig::default().formatter(specta::ts::prettier))
.to_plugin(),
)
.plugin(specta_builder)
.setup(|app| {
let handle = app.handle();

Expand Down
14 changes: 6 additions & 8 deletions src/event.rs
Original file line number Diff line number Diff line change
Expand Up @@ -43,14 +43,12 @@ impl EventRegistry {
pub fn register_collection(&self, collection: EventCollection, plugin_name: PluginName) {
let mut registry = self.0.write().expect("Failed to write EventRegistry");

registry.extend(collection.0.into_iter().map(|sid| {
(
sid,
EventRegistryMeta {
plugin_name: PluginName::from(plugin_name),
},
)
}));
registry.extend(
collection
.0
.into_iter()
.map(|sid| (sid, EventRegistryMeta { plugin_name })),
);
}

pub fn get_or_manage<'a, R: Runtime>(handle: &'a impl Manager<R>) -> tauri::State<'a, Self> {

Check warning on line 54 in src/event.rs

View workflow job for this annotation

GitHub Actions / clippy

the following explicit lifetimes could be elided: 'a

warning: the following explicit lifetimes could be elided: 'a --> src/event.rs:54:26 | 54 | pub fn get_or_manage<'a, R: Runtime>(handle: &'a impl Manager<R>) -> tauri::State<'a, Self> { | ^^ ^^ ^^ | = help: for further information visit https://rust-lang.github.io/rust-clippy/master/index.html#needless_lifetimes = note: `#[warn(clippy::needless_lifetimes)]` implied by `#[warn(clippy::all)]` help: elide the lifetimes | 54 - pub fn get_or_manage<'a, R: Runtime>(handle: &'a impl Manager<R>) -> tauri::State<'a, Self> { 54 + pub fn get_or_manage<R: Runtime>(handle: &impl Manager<R>) -> tauri::State<'_, Self> { |
Expand Down
7 changes: 6 additions & 1 deletion src/js.rs
Original file line number Diff line number Diff line change
Expand Up @@ -8,12 +8,17 @@ use specta::{
ts::{self, js_doc, TsExportError},
DataType, TypeMap,
};
use tauri::Runtime;

/// Implements [`ExportLanguage`] for JS exporting
pub struct Language;

/// [`Exporter`](crate::Exporter) for JavaScript
pub type Exporter<TRuntime> = crate::Exporter<Language, NoCommands<TRuntime>, NoEvents>;
pub type PluginBuilder<TCommands, TEvents> = crate::PluginBuilder<Language, TCommands, TEvents>;

pub fn builder<TRuntime: Runtime>() -> PluginBuilder<NoCommands<TRuntime>, NoEvents> {
PluginBuilder::default()
}

impl ExportLanguage for Language {
fn globals() -> String {
Expand Down
105 changes: 54 additions & 51 deletions src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -98,7 +98,7 @@ use std::{
fs::{self, File},
io::Write,
marker::PhantomData,
path::{Path, PathBuf},
path::Path,
};

use crate::ts::ExportConfig;
Expand All @@ -121,10 +121,9 @@ mod event;

pub use event::*;

pub type CollectCommandsTuple<TInvokeHandler> = (
Result<(Vec<FunctionDataType>, TypeMap), ExportError>,
TInvokeHandler,
);
pub type CollectFunctionsResult = Result<(Vec<FunctionDataType>, TypeMap), ExportError>;

pub type CollectCommandsTuple<TInvokeHandler> = (CollectFunctionsResult, TInvokeHandler);

#[macro_export]
macro_rules! collect_commands {
Expand Down Expand Up @@ -181,11 +180,13 @@ pub trait CommandsTypeState: 'static {
type InvokeHandler: Fn(tauri::Invoke<Self::Runtime>) + Send + Sync + 'static;

fn split(self) -> CollectCommandsTuple<Self::InvokeHandler>;

fn macro_data(&self) -> &CollectFunctionsResult;
}

fn dummy_invoke_handler(_: Invoke<impl Runtime>) {}

pub struct NoCommands<TRuntime>(PhantomData<TRuntime>);
pub struct NoCommands<TRuntime>(CollectFunctionsResult, PhantomData<TRuntime>);

impl<TRuntime> CommandsTypeState for NoCommands<TRuntime>
where
Expand All @@ -197,6 +198,10 @@ where
fn split(self) -> CollectCommandsTuple<Self::InvokeHandler> {
(Ok(Default::default()), dummy_invoke_handler)
}

fn macro_data(&self) -> &CollectFunctionsResult {
&self.0
}
}

pub struct Commands<TRuntime, TInvokeHandler>(
Expand All @@ -215,6 +220,10 @@ where
fn split(self) -> CollectCommandsTuple<TInvokeHandler> {
self.0
}

fn macro_data(&self) -> &CollectFunctionsResult {
&self.0 .0
}
}

pub trait EventsTypeState: 'static {
Expand All @@ -238,70 +247,67 @@ impl EventsTypeState for Events {
}

/// General exporter, takes a generic for the specific language that is being exported to.
pub struct Exporter<TLang, TCommands, TEvents> {
export_path: PathBuf,
pub struct PluginBuilder<TLang, TCommands, TEvents> {
lang: PhantomData<TLang>,
commands: TCommands,
events: TEvents,
cfg: ExportConfig,
header: Cow<'static, str>,
config: ExportConfig,
}

impl<TLang, TRuntime> Exporter<TLang, NoCommands<TRuntime>, NoEvents> {
pub fn new(export_path: impl AsRef<Path>) -> Self {
impl<TLang, TRuntime> Default for PluginBuilder<TLang, NoCommands<TRuntime>, NoEvents> {
fn default() -> Self {
Self {
export_path: export_path.as_ref().into(),
lang: PhantomData,
commands: NoCommands(Default::default()),
commands: NoCommands(Ok((vec![], Default::default())), Default::default()),
events: NoEvents,
cfg: ExportConfig::default(),
header: CRINGE_ESLINT_DISABLE.into(),
config: ExportConfig::default(),
}
}
}

impl<TLang, TEvents, TRuntime> Exporter<TLang, NoCommands<TRuntime>, TEvents>
impl<TLang, TEvents, TRuntime> PluginBuilder<TLang, NoCommands<TRuntime>, TEvents>
where
TRuntime: tauri::Runtime,
{
pub fn commands<TInvokeHandler: Fn(tauri::Invoke<TRuntime>) + Send + Sync + 'static>(
self,
commands: CollectCommandsTuple<TInvokeHandler>,
) -> Exporter<TLang, Commands<TRuntime, TInvokeHandler>, TEvents> {
Exporter {
export_path: self.export_path,
) -> PluginBuilder<TLang, Commands<TRuntime, TInvokeHandler>, TEvents> {
PluginBuilder {
lang: self.lang,
commands: Commands(commands, Default::default()),
events: self.events,
cfg: self.cfg,
header: self.header,
config: self.config,
}
}
}

impl<TLang, TCommands> Exporter<TLang, TCommands, NoEvents> {
pub fn events(self, events: CollectEventsTuple) -> Exporter<TLang, TCommands, Events> {
Exporter {
export_path: self.export_path,
impl<TLang, TCommands> PluginBuilder<TLang, TCommands, NoEvents> {
pub fn events(self, events: CollectEventsTuple) -> PluginBuilder<TLang, TCommands, Events> {
PluginBuilder {
lang: self.lang,
events: Events(events),
commands: self.commands,
cfg: self.cfg,
header: self.header,
config: self.config,
}
}
}

impl<TLang, TCommands, TEvents> Exporter<TLang, TCommands, TEvents> {
impl<TLang, TCommands, TEvents> PluginBuilder<TLang, TCommands, TEvents> {
/// Allows for specifying a custom [`ExportConfiguration`](specta::ts::ExportConfiguration).
pub fn cfg(mut self, cfg: specta::ts::ExportConfig) -> Self {
self.cfg = ExportConfig::new(cfg);
pub fn config(mut self, config: specta::ts::ExportConfig) -> Self {
self.config.inner = config;
self
}

/// Allows for specifying a custom header to
pub fn with_header(mut self, header: &'static str) -> Self {
self.header = header.into();
pub fn header(mut self, header: &'static str) -> Self {
self.config.header = header.into();
self
}

pub fn path(mut self, path: impl AsRef<Path>) -> Self {
self.config.path = Some(path.as_ref().to_path_buf());
self
}
}
Expand All @@ -319,17 +325,17 @@ where

const PLUGIN_NAME: &str = "tauri-specta";

impl<TLang, TCommands, TEvents> Exporter<TLang, TCommands, TEvents>
impl<TLang, TCommands, TEvents> PluginBuilder<TLang, TCommands, TEvents>
where
TLang: ExportLanguage,
TCommands: CommandsTypeState,
TEvents: EventsTypeState,
{
#[must_use]
pub fn to_plugin(self) -> tauri::plugin::TauriPlugin<TCommands::Runtime> {
pub fn into_plugin(self) -> tauri::plugin::TauriPlugin<TCommands::Runtime> {
let builder = tauri::plugin::Builder::new(PLUGIN_NAME);

let plugin_utils = self.to_utils_for_plugin(PLUGIN_NAME);
let plugin_utils = self.into_plugin_utils(PLUGIN_NAME);

builder
.invoke_handler(plugin_utils.invoke_handler)
Expand All @@ -342,7 +348,7 @@ where
}

#[must_use]
pub fn to_utils_for_plugin<TManager>(
pub fn into_plugin_utils<TManager>(
mut self,
plugin_name: &'static str,
) -> PluginUtils<TCommands, TManager, impl FnOnce(&TManager)>
Expand All @@ -351,7 +357,7 @@ where
{
let plugin_name = PluginName::new(plugin_name);

self.cfg.plugin_name = plugin_name;
self.config.plugin_name = plugin_name;

let (invoke_handler, event_collection) = self.export_inner().unwrap();

Check warning on line 362 in src/lib.rs

View workflow job for this annotation

GitHub Actions / clippy

used `unwrap()` on a `Result` value

warning: used `unwrap()` on a `Result` value --> src/lib.rs:362:50 | 362 | let (invoke_handler, event_collection) = self.export_inner().unwrap(); | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^ | = help: if you don't want to handle the `Err` case gracefully, consider using `expect()` to provide a better panic message = help: for further information visit https://rust-lang.github.io/rust-clippy/master/index.html#unwrap_used note: the lint level is defined here --> src/lib.rs:91:22 | 91 | #![warn(clippy::all, clippy::unwrap_used, clippy::panic | ^^^^^^^^^^^^^^^^^^^

Expand All @@ -366,17 +372,15 @@ where
}

fn export_inner(self) -> Result<(TCommands::InvokeHandler, EventCollection), TsExportError> {
let path = self.export_path.clone();
let cfg = self.cfg.clone();
let cfg = self.config.clone();

let (rendered, ret) = self.render()?;

if let Some(export_dir) = path.parent() {
fs::create_dir_all(export_dir)?;
}
if let Some(path) = cfg.path {
if let Some(export_dir) = path.parent() {
fs::create_dir_all(export_dir)?;
}

#[cfg(debug_assertions)]
{
let mut file = File::create(&path)?;

write!(file, "{}", rendered)?;
Expand All @@ -392,8 +396,7 @@ where
) -> Result<(String, (TCommands::InvokeHandler, EventCollection)), TsExportError> {
let Self {
commands,
cfg,
header,
config,
events,
..
} = self;
Expand All @@ -410,19 +413,19 @@ where
.into_iter()
.chain(events_type_map)
.collect(),
&cfg,
&config,
)?;

Ok((
format!("{header}{rendered}"),
format!("{}{rendered}", &config.header),
(invoke_handler, events_registry),
))
}
}

type HardcodedRuntime = tauri::Wry;

impl<TLang, TCommands, TEvents> Exporter<TLang, TCommands, TEvents>
impl<TLang, TCommands, TEvents> PluginBuilder<TLang, TCommands, TEvents>
where
TLang: ExportLanguage,
TCommands: CommandsTypeState<Runtime = HardcodedRuntime>,
Expand All @@ -434,7 +437,7 @@ where
}

pub fn export_for_plugin(mut self, plugin_name: &'static str) -> Result<(), TsExportError> {
self.cfg.plugin_name = PluginName::new(plugin_name);
self.config.plugin_name = PluginName::new(plugin_name);

self.export_inner().map(|_| ())
}
Expand Down
Loading

0 comments on commit aeda797

Please sign in to comment.