#![cfg_attr(feature = "ssr", allow(unused_variables, unused_imports, dead_code))]
use cfg_if::cfg_if;
use core::fmt;
use leptos::{leptos_dom::helpers::TimeoutHandle, *};
use std::rc::Rc;
use std::time::Duration;
use default_struct_builder::DefaultBuilder;
use js_sys::Array;
use wasm_bindgen::{prelude::*, JsCast, JsValue};
use web_sys::{BinaryType, CloseEvent, Event, MessageEvent, WebSocket};
use crate::utils::CloneableFnWithArg;
/// Creating and managing a [Websocket](https://developer.mozilla.org/en-US/docs/Web/API/WebSocket) connection.
///
/// ## Demo
///
/// [Link to Demo](https://github.com/Synphonyte/leptos-use/tree/main/examples/use_websocket)
///
/// ## Usage
///
/// ```
/// # use leptos::*;
/// # use leptos_use::{use_websocket, UseWebSocketReadyState, UseWebsocketReturn};
/// #
/// # #[component]
/// # fn Demo(cx: Scope) -> impl IntoView {
/// let UseWebsocketReturn {
/// ready_state,
/// message,
/// message_bytes,
/// send,
/// send_bytes,
/// open,
/// close,
/// ..
/// } = use_websocket(cx, "wss://echo.websocket.events/".to_string());
///
/// let send_message = move |_| {
/// let m = "Hello, world!".to_string();
/// send(m.clone());
/// };
///
/// let send_byte_message = move |_| {
/// let m = b"Hello, world!\r\n".to_vec();
/// send_bytes(m.clone());
/// };
///
/// let status = move || ready_state.get().to_string();
///
/// let connected = move || ready_state.get() == UseWebSocketReadyState::Open;
///
/// let open_connection = move |_| {
/// open();
/// };
///
/// let close_connection = move |_| {
/// close();
/// };
///
/// view! { cx,
///
///
"status: " {status}
///
///
///
///
///
///
///
"Receive message: " {format! {"{:?}", message}}
///
"Receive byte message: " {format! {"{:?}", message_bytes}}
///
/// }
/// # }
/// ```
///
/// ## Server-Side Rendering
///
/// On the server the returned functions amount to noops.
pub fn use_websocket(
cx: Scope,
url: String,
) -> UseWebsocketReturn<
impl Fn() + Clone + 'static,
impl Fn() + Clone + 'static,
impl Fn(String) + Clone + 'static,
impl Fn(Vec) + Clone + 'static,
> {
use_websocket_with_options(cx, url, UseWebSocketOptions::default())
}
/// Version of [`use_websocket`] that takes `UseWebSocketOptions`. See [`use_websocket`] for how to use.
pub fn use_websocket_with_options(
cx: Scope,
url: String,
options: UseWebSocketOptions,
) -> UseWebsocketReturn<
impl Fn() + Clone + 'static,
impl Fn() + Clone + 'static,
impl Fn(String) + Clone + 'static,
impl Fn(Vec) + Clone,
> {
let (ready_state, set_ready_state) = create_signal(cx, UseWebSocketReadyState::Closed);
let (message, set_message) = create_signal(cx, None);
let (message_bytes, set_message_bytes) = create_signal(cx, None);
let ws_ref: StoredValue