Skip to content

Commit

Permalink
feat: introduce logging
Browse files Browse the repository at this point in the history
  • Loading branch information
friendlymatthew committed Feb 29, 2024
1 parent 1e33a9a commit 6be255c
Show file tree
Hide file tree
Showing 8 changed files with 103 additions and 28 deletions.
3 changes: 2 additions & 1 deletion .gitignore
Original file line number Diff line number Diff line change
@@ -1,2 +1,3 @@
/target
/Cargo.lock
/Cargo.lock
/node_modules
2 changes: 1 addition & 1 deletion Cargo.lock

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

3 changes: 2 additions & 1 deletion Cargo.toml
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
[package]
name = "leptos_hotkeys"
version = "0.1.5"
version = "0.1.6"
edition = "2021"
description = "A library that declaratively pairs keybindings with callbacks for Leptos applications."
license = "MIT"
Expand All @@ -27,4 +27,5 @@ path = "src/lib.rs"
[features]
hydrate = ["dep:web-sys", "dep:wasm-bindgen"]
csr = ["dep:web-sys", "dep:wasm-bindgen"]
debug = []
ssr = []
22 changes: 16 additions & 6 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,7 @@

Declaratively create and pair keybindings with callbacks for Leptos applications.

[![crates](https://img.shields.io/badge/📦_crates-0.1.5-%20green)](https://crates.io/crates/leptos_hotkeys)
[![crates](https://img.shields.io/badge/📦_crates-0.1.6-%20green)](https://crates.io/crates/leptos_hotkeys)
[![discord](https://img.shields.io/badge/Join-Discord-%235865F2.svg)](https://discord.gg/XhVbKk38ux)
<!-- [![version](https://img.shields.io/badge/version-0.1.3-purple)](https://materialize.com/s/chat) -->

Expand All @@ -18,7 +18,7 @@ Declaratively create and pair keybindings with callbacks for Leptos applications
> [!NOTE]
>
> This library is ready for use.
> If you're curious read the [CHANGELOG](#changelog).
> If you're curious about updates, please read the [CHANGELOG](#changelog).

## Live example
Expand Down Expand Up @@ -111,7 +111,7 @@ pub fn SomeComponent() -> impl IntoView {


### Focus trapped Hotkeys
> Embed a hotkey with an `HtmlElement` and the hotkey will only fire if the element is focused and the scope is enabled.
> Embed a hotkey with an html element and the hotkey will only fire if the element is focused and the scope is enabled.
```rust
use leptos_hotkeys::prelude::*;
Expand Down Expand Up @@ -142,18 +142,19 @@ cargo add leptos_hotkeys
```

> [!NOTE]
> `leptos-hotkeys` supports both client-side rendered and server-side rendered > applications. Depending on your application, make sure to include the `csr` or `hydrate` feature flag.
> `leptos-hotkeys` supports both client-side rendered and server-side rendered applications. Depending on your application, make sure to include the `csr` or `hydrate` feature flag.
> For client side rendered:
> ```toml
> leptos_hotkeys = { path = "0.1.4", features = ["csr"] }
> leptos_hotkeys = { path = "0.1.6", features = ["csr"] }
> ```
>
> For server side rendered:
> ```toml
> leptos_hotkeys = { version = "0.1.4", features = ["hydrate"] }
> leptos_hotkeys = { version = "0.1.6", features = ["hydrate"] }
> ```
We also other feature flags that enhance developer experience, to learn more read [feature-flags](#feature-flags)
### Hotkey Provider
Wrap your project with `<HotkeysProvider />`:
Expand Down Expand Up @@ -259,6 +260,15 @@ view! {
}
```

## Feature Flags
In addition to the `CSR` and `Hydrate` feature flags, we want to improve developer experience by introducing the `debug` flag which adds logging to your console. It logs the current pressed key values, hotkeys fires, and scopes toggling.

Just simply:
```toml
> ```toml
> leptos_hotkeys = { path = "0.1.6", features = ["hydrate", "debug"] }
> ```
```

## API
### `<HotkeysProvider />`
Expand Down
27 changes: 21 additions & 6 deletions src/hotkeys_provider.rs
Original file line number Diff line number Diff line change
Expand Up @@ -72,22 +72,34 @@ pub fn HotkeysProvider(
let enable_scope = Callback::new(move |scope: String| {
active_scopes.update(|scopes| {
if !scopes.contains(&scope) {
if cfg!(feature = "debug") {
logging::log!("inserting scope {}", &scope);
}
scopes.insert(scope);
}
})
});

let disable_scope = Callback::new(move |scope: String| {
active_scopes.update(|scopes| {
if cfg!(feature = "debug") {
logging::log!("removing scope {}", &scope);
}
scopes.remove(&scope);
})
});

let toggle_scope = Callback::new(move |scope: String| {
active_scopes.update(|scopes| {
if scopes.contains(&scope) {
if cfg!(feature = "debug") {
logging::log!("removing scope {}", &scope);
}
scopes.remove(&scope);
} else {
if cfg!(feature = "debug") {
logging::log!("inserting scope {}", &scope);
}
scopes.insert(scope);
}
})
Expand All @@ -107,21 +119,24 @@ pub fn HotkeysProvider(
div()
.on_mount(move |_| {
let blur_listener = Closure::wrap(Box::new(move || {
// todo! add tracing
// logging::log!("Window lost focus");
if cfg!(feature = "debug") {
logging::log!("Window lost focus");
}
pressed_keys.set(HashMap::new());
}) as Box<dyn Fn()>);

let keydown_listener = Closure::wrap(Box::new(move |event: KeyboardEvent| {
// todo! add tracing
// logging::log!("key pressed: {}", event.key().to_lowercase());
if cfg!(feature="debug") {
logging::log!("key pressed: {}", event.key().to_lowercase());
}
pressed_keys.update(|keys| {
keys.insert(event.key().to_lowercase(), event);
});
}) as Box<dyn Fn(_)>);
let keyup_listener = Closure::wrap(Box::new(move |event: KeyboardEvent| {
// todo! add tracing
// logging::log!("key up: {}", event.key().to_lowercase())
if cfg!(feature="debug") {
logging::log!("key up: {}", event.key().to_lowercase())
}
pressed_keys.update(|keys| {
keys.remove(&event.key().to_lowercase());
});
Expand Down
42 changes: 42 additions & 0 deletions src/types.rs
Original file line number Diff line number Diff line change
@@ -1,3 +1,5 @@
use std::fmt::{Display, Formatter, Result};

pub type Keys = Vec<String>;

#[derive(PartialEq, Hash, Eq)]
Expand All @@ -8,6 +10,30 @@ pub struct KeyboardModifiers {
pub(crate) shift: bool,
}

impl Display for KeyboardModifiers {
fn fmt(&self, f: &mut Formatter<'_>) -> Result {
let mut modifiers = Vec::new();

if self.alt {
modifiers.push("Alt");
}
if self.ctrl {
modifiers.push("Ctrl");
}
if self.meta {
modifiers.push("Meta");
}
if self.shift {
modifiers.push("Shift");
}

match modifiers.is_empty() {
true => write!(f, ""),
false => write!(f, ", modifiers: {}", modifiers.join(", ")),
}
}
}

impl Default for KeyboardModifiers {
fn default() -> Self {
KeyboardModifiers {
Expand All @@ -25,6 +51,22 @@ pub struct Hotkey {
pub(crate) keys: Keys,
}

impl Display for Hotkey {
fn fmt(&self, f: &mut Formatter<'_>) -> Result {
let keys = self
.keys
.iter()
.map(|k| k.as_str())
.collect::<Vec<&str>>()
.join(", ");

match keys.is_empty() {
true => write!(f, "{}", self.modifiers),
false => write!(f, "keys: {} {}", keys, self.modifiers),
}
}
}

pub type RefType<T> = Option<T>;

pub type HotkeyEvent = Hotkey;
23 changes: 12 additions & 11 deletions src/use_hotkeys.rs
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,6 @@ cfg_if! {
use web_sys::KeyboardEvent;
use crate::hotkeys_provider::use_hotkeys_context;
use crate::types::{Hotkey, KeyboardModifiers};

use std::collections::{HashMap, HashSet};

fn parse_key(key_combination: &str) -> Hotkey {
Expand Down Expand Up @@ -78,16 +77,16 @@ cfg_if! {

create_effect(move |_| {
let active_scopes = hotkeys_context.active_scopes.get();

//intersection should be O(min(scopes, active_scopes))
let within_scope = &scopes.iter().any(|scope| active_scopes.contains(scope));

if *within_scope {
let mut pressed_keyset = pressed_keys.get();
if parsed_keys
.iter()
.any(|hotkey| is_hotkey_match(hotkey, &mut pressed_keyset))
{
if let Some(matching_hotkey) = parsed_keys.iter().find(|hotkey| {
is_hotkey_match(hotkey, &mut pressed_keyset)
}) {
if cfg!(feature = "debug") {
logging::log!("\tfiring hotkey: {}", &matching_hotkey);
}
Callable::call(&on_triggered, ());
}
}
Expand Down Expand Up @@ -118,10 +117,12 @@ cfg_if! {
let within_scope = scopes.iter().any(|scope| active_scopes.contains(scope));

if within_scope {
if parsed_keys
.iter()
.any(|hotkey| is_hotkey_match(hotkey, &mut pressed_keys))
{
if let Some(matching_hotkey) = parsed_keys.iter().find(|hotkey| {
is_hotkey_match(hotkey, &mut pressed_keys)
}) {
if cfg!(feature = "debug") {
logging::log!("\tfiring hotkey: {}", &matching_hotkey);
}
Callable::call(&on_triggered, ());
}
}
Expand Down
9 changes: 7 additions & 2 deletions workspace/ssr-demo/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -20,10 +20,15 @@ wasm-bindgen = "=0.2.89"
thiserror = "1"
tracing = { version = "0.1", optional = true }
http = "1"
leptos_hotkeys = { path = "../..", features = ["hydrate"] }
leptos_hotkeys = { path = "../..", features = ["hydrate", "debug"] }

[features]
hydrate = ["leptos/hydrate", "leptos_meta/hydrate", "leptos_router/hydrate", "leptos_hotkeys/hydrate"]
hydrate = [
"leptos/hydrate",
"leptos_meta/hydrate",
"leptos_router/hydrate",
"leptos_hotkeys/hydrate",
]
ssr = [
"dep:axum",
"dep:tokio",
Expand Down

0 comments on commit 6be255c

Please sign in to comment.