use yew::prelude::*; use web_sys::HtmlTextAreaElement; use crate::pages::room::ChatMessage; #[derive(Properties, PartialEq)] pub struct ChatSidebarProps { pub messages: Vec, pub on_send_message: Callback, } #[function_component(ChatSidebar)] pub fn chat_sidebar(props: &ChatSidebarProps) -> Html { let input_ref = use_node_ref(); let message_input = use_state(|| String::new()); let on_input_change = { let message_input = message_input.clone(); Callback::from(move |e: InputEvent| { let input: HtmlTextAreaElement = e.target_unchecked_into(); message_input.set(input.value()); }) }; let on_send = { let message_input = message_input.clone(); let on_send_message = props.on_send_message.clone(); let input_ref = input_ref.clone(); Callback::from(move |e: KeyboardEvent| { if e.key() == "Enter" && !e.shift_key() { e.prevent_default(); let content = (*message_input).trim().to_string(); if !content.is_empty() { on_send_message.emit(content); message_input.set(String::new()); if let Some(input) = input_ref.cast::() { input.set_value(""); } } } }) }; let on_send_button = { let message_input = message_input.clone(); let on_send_message = props.on_send_message.clone(); let input_ref = input_ref.clone(); Callback::from(move |_: MouseEvent| { let content = (*message_input).trim().to_string(); if !content.is_empty() { on_send_message.emit(content); message_input.set(String::new()); if let Some(input) = input_ref.cast::() { input.set_value(""); } } }) }; html! {
{"Chat"}
{for props.messages.iter().map(|message| { html! {
{&message.author} {message.timestamp.format("%H:%M").to_string()}
{&message.content}
} })} {if props.messages.is_empty() { html! {
{"No messages yet. Start the conversation!"}
} } else { html! {} }}