Skip to content

Commit

Permalink
Merge pull request #30 from photovoltex/usage-inconveniences
Browse files Browse the repository at this point in the history
Usage inconveniences
  • Loading branch information
photovoltex authored Mar 17, 2024
2 parents 88f43c1 + 7cdc33f commit 05d7cb9
Show file tree
Hide file tree
Showing 19 changed files with 104 additions and 72 deletions.
20 changes: 3 additions & 17 deletions Cargo.lock

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

8 changes: 4 additions & 4 deletions Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -24,8 +24,8 @@ description = "Easily connect your rust frontend and backend without writing dup
readme = "README.md"

[dependencies]
#tauri-interop-macro = { path = "./tauri-interop-macro" }
tauri-interop-macro = "2.1.1"
tauri-interop-macro = { path = "./tauri-interop-macro" }
#tauri-interop-macro = "2.1.1"

js-sys = "0.3"
serde = { version = "1.0", features = ["derive"] }
Expand All @@ -43,8 +43,8 @@ leptos = { version = "0.6", optional = true }
tauri = { version = "1.6", default-features = false, features = ["wry"] }

[target.'cfg(target_family = "wasm")'.dependencies]
#tauri-interop-macro = { path = "./tauri-interop-macro", features = ["_wasm"] }
tauri-interop-macro = { version = "2.1.1", features = [ "_wasm" ] }
tauri-interop-macro = { path = "./tauri-interop-macro", features = ["_wasm"] }
#tauri-interop-macro = { version = "2.1.1", features = [ "_wasm" ] }

[target.'cfg(not(target_family = "wasm"))'.dev-dependencies]
tauri = "1.6"
Expand Down
8 changes: 8 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -20,3 +20,11 @@ The crates therefore provides the following features:
- collect and register all defined tauri-commands
- QOL-macros to exclude multiple imports in wasm or the host architecture
- easier usage of [tauri's event feature](https://tauri.app/v1/guides/features/events/)

### Note

The library uses a resolver 2 features to allow easy inclusion without configuration. When working with virtual
workspaces the resolver defaults to 1. In that case it is required to set the resolver manually to version 2,
otherwise the [target specific compilation](https://doc.rust-lang.org/cargo/reference/specifying-dependencies.html#platform-specific-dependencies)
will not resolve correctly. When the wrong resolver is used, an error should state that the `Listen` trait is missing.

29 changes: 29 additions & 0 deletions src/event.rs
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,8 @@ pub use emit::*;
#[cfg(any(target_family = "wasm", doc))]
#[doc(cfg(target_family = "wasm"))]
pub use listen::*;
#[cfg(doc)]
use tauri_interop_macro::{Emit, EmitField, Event, Listen, ListenField};

/// traits for event emitting in the host code
#[cfg(not(target_family = "wasm"))]
Expand All @@ -19,7 +21,34 @@ mod emit;
#[doc(cfg(target_family = "wasm"))]
mod listen;

#[allow(clippy::needless_doctest_main)]
/// Trait defining a [Field] to a related struct implementing [Parent] with the related [Field::Type]
///
/// When using [Event], [Emit] or [Listen], for each field of the struct, a struct named after the
/// field is generated. The field naming is snake_case to PascalCase, but because of the possibility
/// that the type and the field name are the same, the generated field has a "F" appended at the
/// beginning to separate each other and avoid type collision.
///
/// ```
/// use serde::{Deserialize, Serialize};
/// use tauri_interop::{Event, event::ManagedEmit};
///
/// #[derive(Default, Clone, Serialize, Deserialize)]
/// struct Bar {
/// foo: u16
/// }
///
/// #[derive(Event)]
/// struct Test {
/// bar: Bar
/// }
///
/// impl ManagedEmit for Test {}
///
/// fn main() {
/// let _ = test::FBar;
/// }
/// ```
pub trait Field<P>
where
P: Parent,
Expand Down
12 changes: 6 additions & 6 deletions src/event/emit.rs
Original file line number Diff line number Diff line change
Expand Up @@ -36,7 +36,7 @@ where
get_field_value: impl Fn(&Self) -> F::Type,
) -> Option<F::Type>
where
Self: Sized + Send + Sync,
Self: Send + Sync,
{
use tauri::Manager;

Expand All @@ -47,7 +47,7 @@ where
}

/// Trait that defines the available event emitting methods
pub trait Emit {
pub trait Emit: Sized {
/// Emit all field events
///
/// ### Example
Expand Down Expand Up @@ -89,14 +89,14 @@ pub trait Emit {
///
/// #[tauri_interop::command]
/// fn emit_bar(handle: TauriAppHandle) {
/// Test::default().emit::<test::Foo>(&handle).expect("emitting failed");
/// Test::default().emit::<test::FFoo>(&handle).expect("emitting failed");
/// }
///
/// fn main() {}
/// ```
fn emit<F: Field<Self>>(&self, handle: &AppHandle<Wry>) -> Result<(), Error>
where
Self: Sized + Parent;
Self: Parent;

/// Update a single field and emit it afterward
///
Expand All @@ -116,7 +116,7 @@ pub trait Emit {
///
/// #[tauri_interop::command]
/// fn emit_bar(handle: TauriAppHandle) {
/// Test::default().update::<test::Bar>(&handle, true).expect("emitting failed");
/// Test::default().update::<test::FBar>(&handle, true).expect("emitting failed");
/// }
///
/// fn main() {}
Expand All @@ -127,5 +127,5 @@ pub trait Emit {
field: F::Type,
) -> Result<(), Error>
where
Self: Sized + Parent;
Self: Parent;
}
19 changes: 10 additions & 9 deletions src/event/listen.rs
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,7 @@ use wasm_bindgen::{closure::Closure, JsCast, JsValue};
use crate::command::bindings::listen;

#[cfg(doc)]
use super::Emit;
use super::{Emit, Parent};
use super::Field;

/// The trait which needs to be implemented for a [Field]
Expand Down Expand Up @@ -95,15 +95,16 @@ impl ListenHandle {

/// Registers a given event and binds a returned signal to these event changes
///
/// Providing [None] will unwrap into the default value. When feature `initial_value`
/// Providing [None] will unwrap into the default value. When feature `initial_value`
/// is enabled [None] will try to get the value from tauri.
///
///
/// Internally it stores a created [ListenHandle] for `event` in a [leptos::RwSignal] to hold it in
/// scope, while it is used in a leptos [component](https://docs.rs/leptos_macro/0.5.2/leptos_macro/attr.component.html)
#[cfg(feature = "leptos")]
#[doc(cfg(feature = "leptos"))]
pub fn use_register<P, F: Field<P>>(initial_value: Option<F::Type>) -> ReadSignal<F::Type>
where P: Sized + super::Parent
where
P: Parent,
{
use leptos::SignalSet;

Expand All @@ -116,10 +117,10 @@ impl ListenHandle {
if cfg!(feature = "initial_value") && acquire_initial_value {
match F::get_value().await {
Ok(value) => set_signal.set(value),
Err(why) => log::error!("{why}")
Err(why) => log::error!("{why}"),
}
}

let listen_handle = ListenHandle::register(F::EVENT_NAME, move |value: F::Type| {
log::trace!("update for {}", F::EVENT_NAME);
set_signal.set(value)
Expand All @@ -136,7 +137,7 @@ impl ListenHandle {
}

/// Trait that defines the available listen methods
pub trait Listen {
pub trait Listen: Sized {
/// Registers a callback to a [Field]
///
/// Default Implementation: see [ListenHandle::register]
Expand Down Expand Up @@ -164,7 +165,7 @@ pub trait Listen {
callback: impl Fn(F::Type) + 'static,
) -> impl std::future::Future<Output = ListenResult>
where
Self: Sized + super::Parent,
Self: Parent,
{
ListenHandle::register(F::EVENT_NAME, callback)
}
Expand Down Expand Up @@ -194,7 +195,7 @@ pub trait Listen {
#[doc(cfg(feature = "leptos"))]
fn use_field<F: Field<Self>>(initial: Option<F::Type>) -> ReadSignal<F::Type>
where
Self: Sized + super::Parent,
Self: Parent,
{
ListenHandle::use_register::<Self, F>(initial)
}
Expand Down
8 changes: 8 additions & 0 deletions src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -13,6 +13,14 @@
//!
//! Detail explanations and example can be found on the respected traits or macros. Some
//! examples are ignored because they are only valid when compiling to wasm.
//!
//! ### Note
//!
//! The library uses resolver 2 features to allow easy inclusion without configuration. When working
//! with virtual workspaces the resolver defaults to 1 in which case it is required to set the
//! resolver manually to version 2, otherwise the [target specific compilation](https://doc.rust-lang.org/cargo/reference/specifying-dependencies.html#platform-specific-dependencies)
//! will not resolve correctly. When the wrong resolver is used, an error should state that the
//! [event::Listen] trait is missing.
#![feature(trait_alias)]
#![feature(doc_cfg)]
Expand Down
2 changes: 1 addition & 1 deletion tauri-interop-macro/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -27,7 +27,7 @@ proc-macro-error = "1.0.4"
[dev-dependencies]
tauri = { version = "^1.6", default-features = false, features = ["wry"] }
log = "^0.4"
serde = "^1.0"
serde = { version = "^1.0", features = [ "derive" ] }
# required because the intented usage is to use the main crate,
# for testing we need the reexported macros from tauri-interop
tauri-interop = { path = "..", features = ["event", "initial_value"] }
Expand Down
2 changes: 1 addition & 1 deletion tauri-interop-macro/src/event.rs
Original file line number Diff line number Diff line change
Expand Up @@ -57,7 +57,7 @@ fn prepare_event(derive_input: DeriveInput) -> EventStruct {
.iter()
.map(|field| {
let field_ident = field.ident.as_ref().unwrap();
let field_name = format_ident!("{}", field_ident.to_string().to_case(Case::Pascal));
let field_name = format_ident!("F{}", field_ident.to_string().to_case(Case::Pascal));

EventField {
field_name,
Expand Down
2 changes: 1 addition & 1 deletion tauri-interop-macro/src/event/emit.rs
Original file line number Diff line number Diff line change
Expand Up @@ -41,7 +41,7 @@ pub fn derive(stream: TokenStream) -> TokenStream {
let stream = quote! {
#commands_attr
pub mod #mod_name {
use super::#name;
use super::*;

#( #emit_fields )*

Expand Down
5 changes: 2 additions & 3 deletions tauri-interop-macro/src/event/listen.rs
Original file line number Diff line number Diff line change
Expand Up @@ -31,8 +31,7 @@ pub fn derive(stream: TokenStream) -> TokenStream {

let stream = quote! {
pub mod #mod_name {
use super::#name;
use ::tauri_interop::event::Field;
use super::*;

#( #listen_fields )*
}
Expand Down Expand Up @@ -74,7 +73,7 @@ pub fn derive_field(stream: TokenStream) -> TokenStream {
let stream = quote! {
#get_cmd_fn

impl Field<#parent> for #name {
impl ::tauri_interop::event::Field<#parent> for #name {
type Type = #parent_field_ty;
const EVENT_NAME: &'static str = #event_name;

Expand Down
8 changes: 7 additions & 1 deletion tauri-interop-macro/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -42,11 +42,17 @@ mod event;
///
/// ```
/// use tauri_interop_macro::Event;
/// use serde::{Serialize, Deserialize};
///
/// #[derive(Default, Clone, Serialize, Deserialize)]
/// pub struct Bar {
/// value: bool
/// }
///
/// #[derive(Event)]
/// struct EventModel {
/// foo: String,
/// pub bar: bool
/// pub bar: Bar
/// }
///
/// impl tauri_interop::event::ManagedEmit for EventModel {}
Expand Down
6 changes: 2 additions & 4 deletions test-project/Cargo.lock

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

2 changes: 1 addition & 1 deletion test-project/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -10,7 +10,7 @@ default-target = "wasm32-unknown-unknown"
members = ["src-tauri", "api"]

[dependencies]
api = { path = "./api", default-features = false, features = [ "wasm" ]}
api = { path = "./api" }

console_error_panic_hook = "^0.1"
console_log = "^1.0"
Expand Down
21 changes: 9 additions & 12 deletions test-project/api/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -4,24 +4,21 @@ version = "0.1.0"
edition = "2021"

[dependencies]
tauri-interop = { path = "../..", default-features = false, features = ["event", "initial_value"] }
tauri-interop = { path = "../..", features = ["event", "initial_value"] }

# common
log = "0.4"
serde = { version = "1", features = ["derive"] }

# host target
tauri = { version = "1.6", optional = true }
[target.'cfg(not(target_family = "wasm"))'.dependencies]
tauri = { version = "1.6" }

# wasm target
js-sys = { version = "0.3", optional = true }
serde-wasm-bindgen = { version = "0.6", optional = true }
wasm-bindgen = { version = "0.2", features = ["serde-serialize"], optional = true }
wasm-bindgen-futures = {version = "0.4", optional = true}
[target.'cfg(target_family = "wasm")'.dependencies]
js-sys = { version = "0.3" }
serde-wasm-bindgen = { version = "0.6" }
wasm-bindgen = { version = "0.2", features = ["serde-serialize"] }
wasm-bindgen-futures = { version = "0.4" }
leptos = { version = "0.6", features = ["csr"], optional = true }

[features]
default = [ "host" ]
host = [ "dep:tauri" ]
wasm = [ "dep:js-sys", "dep:serde-wasm-bindgen", "dep:wasm-bindgen", "dep:wasm-bindgen-futures"]
leptos = [ "dep:leptos", "tauri-interop/leptos" ]
leptos = ["dep:leptos", "tauri-interop/leptos"]
4 changes: 2 additions & 2 deletions test-project/api/src/cmd.rs
Original file line number Diff line number Diff line change
Expand Up @@ -61,8 +61,8 @@ pub fn emit(state: TauriState<RwLock<TestState>>, handle: TauriAppHandle) {
"foo"
};

state.update::<test_mod::Foo>(&handle, foo_value.into()).unwrap();
state.update::<test_mod::Bar>(&handle, bar_value).unwrap();
state.update::<test_mod::FFoo>(&handle, foo_value.into()).unwrap();
state.update::<test_mod::FBar>(&handle, bar_value).unwrap();
}

tauri_interop::collect_commands!();
Loading

0 comments on commit 05d7cb9

Please sign in to comment.