rustonpasteweb-sysleptos

How can I get on:paste to work with `web_sys`?


For the project I want the verification code part of the sign up stepper to have each number separated into small boxes and when pasted the code will be pasted into each individual box. The problem is I'm not sure how to get the paste data from the user. The function that I'm trying to get to work is the following:

on:paste=move |ev| {
    match on_paste {
        Some(on_paste) => {
            ev.prevent_default();

            // // let mut data_transfer_res = event_target_value(&ev);
            // let data_transfer_res = ClipboardEvent::from(ev).clipboard_data();

            // match data_transfer_res {
            //     Some(data_transfer) => {
            //         match data_transfer.get_data() {
            //             Ok(paste) => {
            //                 on_paste.dispatch((paste));
            //             },
            //             Err(err) => {
            //                 log::error!("{:?}", err);
            //             }
            //         }

            //     },
            //     None => {
            //         // Do nothing
            //     }
            // }



            let document = use_document();
            on_paste.dispatch((document.as_ref().unwrap().onpaste().unwrap().to_string().into()));

            // match document {
            //     Some(document) => {
            //         let paste = document.onpaste();
            //         let target =

            //         on_paste.dispatch((paste));
            //     },
            //     None => todo!(),
            // }
        },
        None => {
            // Do nothing
        },
    }
}

Before, I have used web_sys since there isn't an implementation for this in the implementation the paste returned a function? I don't know how to access the paste information that is inside that returned function.


Solution

  • leptos doesn't include ClipboardEvent, but web-sys does, and you can convert between them via JsCast. This requires the ClipboardEvent and DataTransfer features of web-sys to be activated:

    let on_paste = |ev: leptos::ev::Event| {
        ev.prevent_default();
    
        let ev = ev.dyn_into::<web_sys::ClipboardEvent>().unwrap_throw();
        let data = ev.clipboard_data().unwrap_throw();
        if data.types().includes(&JsValue::from_str("text/plain"), 0) {
            let pasted = data.get_data("text/plain").unwrap_throw();
            log::debug!("pasted: {pasted}");
        } else {
            log::debug!("pasted non-text");
        }
    };