kkx/kkx/src/main.rs

110 lines
3.0 KiB
Rust

use std::time::Duration;
use kkdisp::{
component::{Plan, Widget},
theme::Color,
token::Token,
view::Event,
Action, View,
};
use tokio::sync::mpsc::{self, Receiver};
#[tokio::main]
async fn main() {
kkdisp::run(App::default()).await.unwrap();
std::process::exit(0);
}
pub struct App {
states: Vec<Plan>,
index: usize,
recv: Receiver<Token>,
}
impl Default for App {
fn default() -> Self {
let (snd, recv) = mpsc::channel(256);
tokio::spawn(async move {
std::thread::sleep(Duration::from_secs(10));
snd.send(Token::text("this is an event").centered())
.await
.unwrap();
});
Self {
recv,
index: 0,
states: vec![
Plan::start().fill(vec![]).fixed(
4,
vec![Widget::new(
100,
vec![
Token::End,
Token::text("click me")
.bg(Color::BLUE)
.link("click"),
],
)],
),
Plan::start()
.fixed(4, vec![])
.fill(vec![Widget::scrolling(
100,
(1..=100)
.into_iter()
.map(|num| {
Token::text(format!(
"this is {}",
num
))
.padded(30)
.bg("#330033".try_into().unwrap())
.link(format!("num{}", num))
.centered()
})
.collect(),
)])
.fixed(4, vec![]),
],
}
}
}
impl View for App {
type Message = Token;
fn init(
&mut self,
) -> std::result::Result<kkdisp::PlanLayers, anyhow::Error> {
tokio::spawn(async { loop {} });
Ok(vec![self.states[self.index].clone()])
}
fn update(
&mut self,
event: Event<Self::Message>,
) -> std::result::Result<Action, anyhow::Error> {
match event {
Event::Link(lnk) => {
eprintln!("recieved link: {}", lnk);
self.index ^= 1;
Ok(Action::ReplaceAll(vec![
self.states[self.index].clone()
]))
}
Event::Message(tok) => {
Ok(Action::ReplaceAll(vec![Plan::start()
.fixed(3, vec![Widget::new(100, vec![tok])])]))
}
_ => Ok(Action::Nothing),
}
}
fn query(&mut self) -> Option<Self::Message> {
match self.recv.try_recv() {
Ok(msg) => Some(msg),
Err(_) => None,
}
}
}