gaucho-labs / leptos-hotkeys

a declarative way of using keyboard shortcuts + callbacks in leptos applications
https://leptos-hotkeys.vercel.app
MIT License
43 stars 8 forks source link

How to use scopes? #128

Closed rkimoakbioinformatics closed 3 weeks ago

rkimoakbioinformatics commented 3 weeks ago

Hi, can you help me with using scopes? I made a similar code to the example, but can't make scopes to work. My code is below.

use leptos::leptos_dom::ev::SubmitEvent;
use leptos::*;
use serde::{Deserialize, Serialize};
use serde_wasm_bindgen::to_value;
use wasm_bindgen::prelude::*;
use leptos::logging::log;
use leptos_hotkeys::use_hotkeys;
use leptos_hotkeys::use_hotkeys_ref;

#[wasm_bindgen]
extern "C" {
    #[wasm_bindgen(js_namespace = ["window", "__TAURI__", "core"])]
    async fn invoke(cmd: &str, args: JsValue) -> JsValue;
}

#[derive(Serialize, Deserialize)]
struct GreetArgs<'a> {
    name: &'a str,
}

#[component]
pub fn App() -> impl IntoView {
    let main_ref = leptos::create_node_ref::<leptos::html::Div>();
    leptos_hotkeys::provide_hotkeys_context(main_ref, false, leptos_hotkeys::scopes!());
    use_hotkeys!(("space") => move |_| {
        log!("Space pressed!");
    });
    use_hotkeys!(("enter", "scope_a") => move |_| {
        log!("Enter pressed in scope A!");
    });
    view! {
        <div _ref=main_ref class="container">
            <div id="scope_a" class="row">
                <a href="https://tauri.app" target="_blank">
                    <img src="public/tauri.svg" class="logo tauri" alt="Tauri logo"/>
                </a>
                <a href="https://docs.rs/leptos/" target="_blank">
                    <img src="public/leptos.svg" class="logo leptos" alt="Leptos logo"/>
                </a>
                <div>Scope A</div>
            </div>
        </div>
    }
}

I created it by cargo create-tauri-app --rc (Tauri v2), cargo add leptos_hotkeys, and editing app.rs. Detecting the space key works, but Enter key is not detected when I click "Scope A" text and press Enter, or any other way.

Also, how should I use use_hotkeys_ref? In the example code, I see something like use_hotkeys_ref(ref, "space", scope) => fn). What are the roles of ref and scope? Does it mean "detect the space key in the referenced element, which is under the scope"?

friendlymatthew commented 3 weeks ago

Hi, there is a section on how to use scopes in the README

rkimoakbioinformatics commented 3 weeks ago

Thanks. It helped. One things is that I had to use enable_scope.call("scope_b".to_string()); instead of enable_scope("scope_b");, for disable_scope as well.

friendlymatthew commented 2 weeks ago

@rkimoakbioinformatics

Thanks. It helped. One things is that I had to use enable_scope.call("scope_b".to_string()); instead of enable_scope("scope_b");, for disable_scope as well.

Thanks! Do you mind updating the README to reflect the correct calling convention for enable_scope?