ДЗ smart-house-web завершено

This commit is contained in:
28 changed files with 1671 additions and 0 deletions
+1
View File
@@ -0,0 +1 @@
/dist/
+13
View File
@@ -0,0 +1,13 @@
[package]
name = "frontend"
version = "0.1.0"
edition = "2024"
[dependencies]
smart_house = { path = "../smart_house" }
console_error_panic_hook = "0.1"
leptos = { version = "0.8", features = ["csr"] }
leptos_router = "0.8"
reqwest = { version = "0.13", features = ["json"] }
serde_json = "1.0"
+10
View File
@@ -0,0 +1,10 @@
# Фронтэнд умного дома
Запуск сервера разработки (sh):
RUSTFLAGS="--cfg erase_components" trunk serve
Запуск сервера разработки (powershell):
$env:RUSTFLAGS = '--cfg erase_components'
trunk serve
+3
View File
@@ -0,0 +1,3 @@
[[proxy]]
backend = "http://localhost:8081"
rewrite = "/api"
@@ -0,0 +1,92 @@
#![allow(non_snake_case, unused)]
use leptos::prelude::*;
// Often, you want to pass some kind of child view to another
// component. There are two basic patterns for doing this:
// - "render props": creating a component prop that takes a function
// that creates a view
// - the `children` prop: a special property that contains content
// passed as the children of a component in your view, not as a
// property
#[component]
pub fn App() -> impl IntoView {
let (items, set_items) = signal(vec![0, 1, 2]);
let render_prop = move || {
let len = move || items.read().len();
view! {
<p>"Length: " {len}</p>
}
};
view! {
// This component just displays the two kinds of children,
// embedding them in some other markup
<TakesChildren
// for component props, you can shorthand
// `render_prop=render_prop` => `render_prop`
// (this doesn't work for HTML element attributes)
render_prop
>
// these look just like the children of an HTML element
<p>"Here's a child."</p>
<p>"Here's another child."</p>
</TakesChildren>
<hr/>
// This component actually iterates over and wraps the children
<WrapsChildren>
<p>"Here's a child."</p>
<p>"Here's another child."</p>
</WrapsChildren>
}
}
/// Displays a `render_prop` and some children within markup.
#[component]
pub fn TakesChildren<F, IV>(
/// Takes a function (type F) that returns anything that can be
/// converted into a View (type IV)
render_prop: F,
/// `children` takes the `Children` type
/// this is an alias for `Box<dyn FnOnce() -> Fragment>`
/// ... aren't you glad we named it `Children` instead?
children: Children,
) -> impl IntoView
where
F: Fn() -> IV,
IV: IntoView,
{
view! {
<h1><code>"<TakesChildren/>"</code></h1>
<h2>"Render Prop"</h2>
{render_prop()}
<hr/>
<h2>"Children"</h2>
{children()}
}
}
/// Wraps each child in an `<li>` and embeds them in a `<ul>`.
#[component]
pub fn WrapsChildren(children: ChildrenFragment) -> impl IntoView {
// children() returns a `Fragment`, which has a
// `nodes` field that contains a Vec<View>
// this means we can iterate over the children
// to create something new!
let children = children()
.nodes
.into_iter()
.map(|child| view! { <li>{child}</li> })
.collect::<Vec<_>>();
view! {
<h1><code>"<WrapsChildren/>"</code></h1>
// wrap our wrapped children in a UL
<ul>{children}</ul>
}
}
fn main() {
leptos::mount::mount_to_body(App)
}
@@ -0,0 +1,158 @@
use leptos::prelude::*;
// Iteration is a very common task in most applications.
// So how do you take a list of data and render it in the DOM?
// This example will show you the two ways:
// 1) for mostly-static lists, using Rust iterators
// 2) for lists that grow, shrink, or move items, using <For/>
#[component]
fn App() -> impl IntoView {
view! {
<h1>"Iteration"</h1>
<h2>"Static List"</h2>
<p>"Use this pattern if the list itself is static."</p>
<StaticList length=5/>
<h2>"Dynamic List"</h2>
<p>"Use this pattern if the rows in your list will change."</p>
<DynamicList initial_length=5/>
}
}
/// A list of counters, without the ability
/// to add or remove any.
#[component]
fn StaticList(
/// How many counters to include in this list.
length: usize,
) -> impl IntoView {
// create counter signals that start at incrementing numbers
let counters = (1..=length).map(|idx| RwSignal::new(idx));
// when you have a list that doesn't change, you can
// manipulate it using ordinary Rust iterators
// and collect it into a Vec<_> to insert it into the DOM
let counter_buttons = counters
.map(|count| {
view! {
<li>
<button
on:click=move |_| *count.write() += 1
>
{count}
</button>
</li>
}
})
.collect::<Vec<_>>();
// Note that if `counter_buttons` were a reactive list
// and its value changed, this would be very inefficient:
// it would rerender every row every time the list changed.
view! {
<ul>{counter_buttons}</ul>
}
}
/// A list of counters that allows you to add or
/// remove counters.
#[component]
fn DynamicList(
/// The number of counters to begin with.
initial_length: usize,
) -> impl IntoView {
// This dynamic list will use the <For/> component.
// <For/> is a keyed list. This means that each row
// has a defined key. If the key does not change, the row
// will not be re-rendered. When the list changes, only
// the minimum number of changes will be made to the DOM.
// `next_counter_id` will let us generate unique IDs
// we do this by simply incrementing the ID by one
// each time we create a counter
let mut next_counter_id = initial_length;
// we generate an initial list as in <StaticList/>
// but this time we include the ID along with the signal
// see NOTE in add_counter below re: ArcRwSignal
let initial_counters = (0..initial_length)
.map(|id| (id, ArcRwSignal::new(id + 1)))
.collect::<Vec<_>>();
// now we store that initial list in a signal
// this way, we'll be able to modify the list over time,
// adding and removing counters, and it will change reactively
let (counters, set_counters) = signal(initial_counters);
let add_counter = move |_| {
// create a signal for the new counter
// we use ArcRwSignal here, instead of RwSignal
// ArcRwSignal is a reference-counted type, rather than the arena-allocated
// signal types we've been using so far.
// When we're creating a collection of signals like this, using ArcRwSignal
// allows each signal to be deallocated when its row is removed.
let sig = ArcRwSignal::new(next_counter_id + 1);
// add this counter to the list of counters
set_counters.update(move |counters| {
// since `.update()` gives us `&mut T`
// we can just use normal Vec methods like `push`
counters.push((next_counter_id, sig))
});
// increment the ID so it's always unique
next_counter_id += 1;
};
view! {
<div>
<button on:click=add_counter>
"Add Counter"
</button>
<ul>
// The <For/> component is central here
// This allows for efficient, key list rendering
<For
// `each` takes any function that returns an iterator
// this should usually be a signal or derived signal
// if it's not reactive, just render a Vec<_> instead of <For/>
each=move || counters.get()
// the key should be unique and stable for each row
// using an index is usually a bad idea, unless your list
// can only grow, because moving items around inside the list
// means their indices will change and they will all rerender
key=|counter| counter.0
// `children` receives each item from your `each` iterator
// and returns a view
children=move |(id, count)| {
// we can convert our ArcRwSignal to a Copy-able RwSignal
// for nicer DX when moving it into the view
let count = RwSignal::from(count);
view! {
<li>
<button
on:click=move |_| *count.write() += 1
>
{count}
</button>
<button
on:click=move |_| {
set_counters
.write()
.retain(|(counter_id, _)| {
counter_id != &id
});
}
>
"Remove"
</button>
</li>
}
}
/>
</ul>
</div>
}
}
fn main() {
leptos::mount::mount_to_body(App)
}
@@ -0,0 +1,99 @@
use leptos::ev::SubmitEvent;
use leptos::prelude::*;
#[component]
fn App() -> impl IntoView {
view! {
<h2>"Controlled Component"</h2>
<ControlledComponent/>
<h2>"Uncontrolled Component"</h2>
<UncontrolledComponent/>
}
}
#[component]
fn ControlledComponent() -> impl IntoView {
// create a signal to hold the value
let (name, set_name) = signal("Controlled".to_string());
view! {
<input type="text"
// fire an event whenever the input changes
// adding :target after the event gives us access to
// a correctly-typed element at ev.target()
on:input:target=move |ev| {
set_name.set(ev.target().value());
}
// the `prop:` syntax lets you update a DOM property,
// rather than an attribute.
//
// IMPORTANT: the `value` *attribute* only sets the
// initial value, until you have made a change.
// The `value` *property* sets the current value.
// This is a quirk of the DOM; I didn't invent it.
// Other frameworks gloss this over; I think it's
// more important to give you access to the browser
// as it really works.
//
// tl;dr: use prop:value for form inputs
prop:value=name
/>
<p>"Name is: " {name}</p>
}
}
#[component]
fn UncontrolledComponent() -> impl IntoView {
// import the type for <input>
use leptos::html::Input;
let (name, set_name) = signal("Uncontrolled".to_string());
// we'll use a NodeRef to store a reference to the input element
// this will be filled when the element is created
let input_element: NodeRef<Input> = NodeRef::new();
// fires when the form `submit` event happens
// this will store the value of the <input> in our signal
let on_submit = move |ev: SubmitEvent| {
// stop the page from reloading!
ev.prevent_default();
// here, we'll extract the value from the input
let value = input_element
.get()
// event handlers can only fire after the view
// is mounted to the DOM, so the `NodeRef` will be `Some`
.expect("<input> to exist")
// `NodeRef` implements `Deref` for the DOM element type
// this means we can call`HtmlInputElement::value()`
// to get the current value of the input
.value();
set_name.set(value);
};
view! {
<form on:submit=on_submit>
<input type="text"
// here, we use the `value` *attribute* to set only
// the initial value, letting the browser maintain
// the state after that
value=name
// store a reference to this input in `input_element`
node_ref=input_element
/>
<input type="submit" value="Submit"/>
</form>
<p>"Name is: " {name}</p>
}
}
// This `main` function is the entry point into the app
// It just mounts our component to the <body>
// Because we defined it as `fn App`, we can now use it in a
// template as <App/>
fn main() {
leptos::mount::mount_to_body(App)
}
+5
View File
@@ -0,0 +1,5 @@
<!doctype html>
<html>
<head></head>
<body></body>
</html>
+60
View File
@@ -0,0 +1,60 @@
use leptos::logging::*;
use leptos::prelude::*;
use leptos::task::spawn_local;
use leptos_router::hooks::use_params_map;
use reqwest::StatusCode;
use serde_json::Value;
async fn load_device(room: &str, dev: &str, write_signal: WriteSignal<String>) {
let resp = reqwest::Client::new()
.get(format!("http://localhost:8081/room/{room}/device/{dev}"))
.send()
.await;
let Ok(resp) = resp else {
debug_log!("Cannot fetch device");
return;
};
if resp.status() != StatusCode::OK {
debug_log!("Device fetching error");
return;
};
let value = match resp.json::<Value>().await {
Ok(value) => value,
Err(e) => {
debug_log!("error parsing device: {:?}", e);
return;
}
};
let Ok(json) = serde_json::to_string_pretty(&value) else {
debug_log!("can not print json value");
return;
};
write_signal.set(json);
}
#[component]
pub fn Device() -> impl IntoView {
let params_map = use_params_map();
let room = params_map.read().get("room").unwrap_or_default();
let dev = params_map.read().get("dev").unwrap_or_default();
let (dev_read, dev_write) = signal(String::default());
Effect::new(move |_| {
let room = params_map.read().get("room").unwrap_or_default();
let dev = params_map.read().get("dev").unwrap_or_default();
spawn_local(async move {
load_device(&room, &dev, dev_write).await;
});
});
view! {
<h1>{move || dev.clone()}</h1>
<p>
<a href=format!("/room/{}", room)>{"<= BACK"}</a>
</p>
<pre>
{dev_read}
</pre>
}
}
+168
View File
@@ -0,0 +1,168 @@
use leptos::logging::*;
use leptos::prelude::*;
use leptos::task::spawn_local;
use reqwest::StatusCode;
use serde_json::Value;
async fn load_rooms(rooms_write_signal: WriteSignal<Vec<String>>) {
let resp = reqwest::Client::new()
.get("http://localhost:8081/rooms")
.send()
.await;
let Ok(resp) = resp else {
debug_log!("Cannot fetch rooms");
return;
};
if resp.status() != StatusCode::OK {
debug_log!("Rooms fetching error");
return;
};
let value = match resp.json::<Value>().await {
Ok(value) => value,
Err(e) => {
debug_log!("error parsing rooms: {:?}", e);
return;
}
};
let value = match value {
Value::Object(value) => value,
_ => {
return;
}
};
let mut rooms = Vec::with_capacity(value.len());
for (name, _) in value.into_iter() {
rooms.push(name);
}
rooms_write_signal.set(rooms);
}
async fn add_room(name: &str) {
let resp = reqwest::Client::new()
.put(format!("http://localhost:8081/room/{}", name))
.header("Content-Type", "application/json")
.body("{\"devices\":{}}")
.send()
.await;
let Ok(resp) = resp else {
debug_log!("Cannot call room creation");
return;
};
if resp.status() != StatusCode::CREATED {
debug_log!("Room creation is not succeeded");
};
}
async fn remove_room(name: &str) {
let resp = reqwest::Client::new()
.delete(format!("http://localhost:8081/room/{}", name))
.send()
.await;
let Ok(resp) = resp else {
debug_log!("Cannot call room removing");
return;
};
if resp.status() != StatusCode::ACCEPTED {
debug_log!("Room removing is not succeeded");
};
}
async fn get_report(write_signal: WriteSignal<String>) {
let resp = reqwest::Client::new()
.get("http://localhost:8081/rooms")
.send()
.await;
let Ok(resp) = resp else {
debug_log!("Cannot fetch rooms");
return;
};
if resp.status() != StatusCode::OK {
debug_log!("Rooms fetching error");
return;
};
let value = match resp.json::<Value>().await {
Ok(value) => value,
Err(e) => {
debug_log!("error parsing rooms: {:?}", e);
return;
}
};
let Ok(json) = serde_json::to_string_pretty(&value) else {
debug_log!("can not print json value");
return;
};
write_signal.set(json);
}
#[component]
pub fn House() -> impl IntoView {
use leptos::html::Input;
let (rooms, set_rooms) = signal(Vec::<String>::new());
let (report_read, report_write) = signal(String::default());
let input_element: NodeRef<Input> = NodeRef::new();
let remove_room = move |name: String| {
spawn_local(async move {
remove_room(&name).await;
load_rooms(set_rooms).await;
});
};
let add_room = move |_| {
let name = input_element.get().expect("<input> to exist").value();
spawn_local(async move {
add_room(&name).await;
load_rooms(set_rooms).await;
});
};
let refresh_report = move |_| {
spawn_local(async move {
get_report(report_write).await;
});
};
Effect::new(move |_| {
spawn_local(async move {
load_rooms(set_rooms).await;
});
});
view! {
<h1>ROOMS</h1>
<ul>
<For
each=move || rooms.get()
key=|room| room.clone()
children=move |room| {
view! {
<li>
<a href={format!("room/{}", room.clone())}>{room.clone()}</a>
<button
on:click=move |_| {
remove_room(room.clone());
}
>X</button>
</li>
}
}
/>
</ul>
<div>
<input
node_ref=input_element
/>
<button
on:click=add_room
>ADD</button>
</div>
<br />
<div>
<button
on:click=refresh_report
>GET REPORT</button>
</div>
<pre>{report_read}</pre>
}
}
+26
View File
@@ -0,0 +1,26 @@
use leptos::prelude::*;
use leptos_router::components::{Route, Router, Routes};
use leptos_router::path;
#[component]
pub fn App() -> impl IntoView {
view! {
<Router>
<main>
<Routes fallback=|| "Not found">
<Route path=path!("/") view=house::House />
<Route path=path!("/room/:name") view=room::Room />
<Route path=path!("/room/:room/device/:dev") view=device::Device />
</Routes>
</main>
</Router>
}
}
fn main() {
leptos::mount::mount_to_body(App)
}
mod device;
mod house;
mod room;
+207
View File
@@ -0,0 +1,207 @@
use std::collections::HashMap;
use leptos::html::Input;
use leptos::logging::*;
use leptos::prelude::*;
use leptos::task::spawn_local;
use leptos_router::hooks::use_params_map;
use reqwest::StatusCode;
use serde_json::Value;
use serde_json::json;
use smart_house::*;
async fn load_devices(room: &str, rooms_write_signal: WriteSignal<Vec<(String, String)>>) {
let resp = reqwest::Client::new()
.get(format!("http://localhost:8081/room/{room}/devices"))
.send()
.await;
let Ok(resp) = resp else {
debug_log!("Cannot fetch devices");
return;
};
if resp.status() != StatusCode::OK {
debug_log!("Devices fetching error");
return;
};
let value = match resp.json::<HashMap<String, Device>>().await {
Ok(value) => value,
Err(e) => {
debug_log!("error parsing devices: {:?}", e);
return;
}
};
let mut devices = Vec::with_capacity(value.len());
for (name, dev) in value.into_iter() {
devices.push((name, dev.report()));
}
rooms_write_signal.set(devices);
}
async fn add_device(room: &str, name: &str, device: Value) {
let resp = reqwest::Client::new()
.put(format!("http://localhost:8081/room/{room}/device/{name}"))
.json(&device)
.send()
.await;
let Ok(resp) = resp else {
debug_log!("Cannot call device creation");
return;
};
if resp.status() != StatusCode::CREATED {
debug_log!("Device creation is not succeeded");
};
}
async fn remove_device(room: &str, name: &str) {
let resp = reqwest::Client::new()
.delete(format!("http://localhost:8081/room/{room}/device/{name}"))
.send()
.await;
let Ok(resp) = resp else {
debug_log!("Cannot call device removing");
return;
};
if resp.status() != StatusCode::ACCEPTED {
debug_log!("Device removing is not succeeded");
};
}
#[component]
pub fn Room() -> impl IntoView {
let params_map = use_params_map();
let (devs_read, devs_write) = signal(Vec::<(String, String)>::new());
let ps_name_input = NodeRef::<Input>::new();
let ps_power_input = NodeRef::<Input>::new();
let ps_on_input = NodeRef::<Input>::new();
let trm_name_input = NodeRef::<Input>::new();
let trm_temp_input = NodeRef::<Input>::new();
Effect::new(move |_| {
let room_name = params_map.read().get("name").unwrap_or_default();
spawn_local(async move {
load_devices(&room_name, devs_write).await;
});
});
let add_ps = move |_| {
let ps_name = ps_name_input
.get()
.map(|e| e.value())
.unwrap_or("".to_string());
let ps_power = ps_power_input
.get()
.map(|e| e.value_as_number())
.unwrap_or(0.0);
let ps_on = ps_on_input.get().map(|e| e.checked()).unwrap_or(false);
let dev = json!({
"type": "PowerSocket",
"power_rate": ps_power,
"on": ps_on
});
let room_name = params_map.read().get("name").unwrap_or_default();
spawn_local(async move {
add_device(&room_name, &ps_name, dev).await;
load_devices(&room_name, devs_write).await;
});
};
let add_trm = move |_| {
let trm_name = trm_name_input
.get()
.map(|e| e.value())
.unwrap_or("".to_string());
let trm_temp = trm_temp_input
.get()
.map(|e| e.value_as_number())
.unwrap_or(0.0);
let dev = json!({
"type": "Thermometer",
"temperature": trm_temp
});
let room_name = params_map.read().get("name").unwrap_or_default();
spawn_local(async move {
add_device(&room_name, &trm_name, dev).await;
load_devices(&room_name, devs_write).await;
});
};
let rm_dev = move |name: String| {
let room_name = params_map.read().get("name").unwrap_or_default();
spawn_local(async move {
remove_device(&room_name, &name).await;
load_devices(&room_name, devs_write).await;
});
};
let room_name = params_map.read().get("name").unwrap_or_default();
view! {
<h1>{move || params_map.read().get("name").unwrap_or_default()}</h1>
<p>
<a href="/">{"<= BACK"}</a>
</p>
<table>
<thead>
<tr>
<th>device name</th>
<th>device state</th>
<th>remove</th>
</tr>
</thead>
<tbody>
<For
each=move || devs_read.get()
key=|dev| dev.clone()
children=move |dev| { view! {
<tr>
<td>
<a href={format!("/room/{}/device/{}", room_name, dev.0.clone())}>{dev.0.clone()}</a>
</td>
<td>{dev.1}</td>
<td>
<button
on:click=move |_| {
rm_dev(dev.0.clone());
}
>-</button>
</td>
</tr>
} }
/>
</tbody>
</table>
<div>
<label>{"Power Socket: "}</label>
<input
node_ref=ps_name_input
type="text"
/>
<input
node_ref=ps_power_input
type="number"
/>
<input
node_ref=ps_on_input
type="checkbox"
/>
<button
on:click=add_ps
>+</button>
</div>
<div>
<label>{"Thermometer: "}</label>
<input
node_ref=trm_name_input
type="text"
/>
<input
node_ref=trm_temp_input
type="number"
/>
<button
on:click=add_trm
>+</button>
</div>
}
}