Compare commits
75
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
5d1361621d | ||
|
|
5ca7221afa | ||
|
|
71660418a1 | ||
|
|
26eb1679f6 | ||
|
|
db66803347 | ||
|
|
de9039dbaf | ||
|
|
e2d7c1ef91 | ||
|
|
3a7d69cb04 | ||
|
|
a75c02fa90 | ||
|
|
250dde8f9e | ||
|
|
e3bbda6b59 | ||
|
|
b0b1835cc1 | ||
|
|
a59a8eeb73 | ||
|
|
a8e832892b | ||
|
|
26c112bdb2 | ||
|
|
a79617e219 | ||
|
|
10fae90ecc | ||
|
|
5c2c5ba46b | ||
|
|
211b5aa95c | ||
|
|
02bdca151b | ||
|
|
00f7493741 | ||
|
|
d9c23f1f09 | ||
|
|
cba301db74 | ||
|
|
327f14d9ed | ||
|
|
0878cad01c | ||
|
|
3d995671cd | ||
|
|
5fabd1a8ab | ||
|
|
4dfbee5984 | ||
|
|
2f328f6762 | ||
|
|
8ae6fb49db | ||
|
|
6255b9c4f4 | ||
|
|
ec963707a1 | ||
|
|
cec25c02d5 | ||
|
|
661756eccd | ||
|
|
921bfa27c1 | ||
|
|
bbaa9d09e1 | ||
|
|
85bfa0f45f | ||
|
|
af719d83db | ||
|
|
cff2e315ca | ||
|
|
eb64a77aac | ||
|
|
bb0ef3adc4 | ||
|
|
fd73514a7b | ||
|
|
f43be496c1 | ||
|
|
f401d4a995 | ||
|
|
551a062021 | ||
|
|
627ab80338 | ||
|
|
3adfff41fb | ||
|
|
6c8ff5f3da | ||
|
|
9715630d9f | ||
|
|
3cacd42421 | ||
|
|
15b61d57c8 | ||
|
|
dfb17ab48e | ||
|
|
82b847314e | ||
|
|
f363bbdae1 | ||
|
|
8274afff04 | ||
|
|
7693711aa9 | ||
|
|
08f1d3364b | ||
|
|
6c0dde8e85 | ||
|
|
f72959bcee | ||
|
|
52f4dcfb2f | ||
|
|
09d1ee21bf | ||
|
|
aa55cc059a | ||
|
|
fda5387ccc | ||
|
|
5a21f9f740 | ||
|
|
49ce197f78 | ||
|
|
fb82c611df | ||
|
|
ab5554abce | ||
|
|
9ecf8de501 | ||
|
|
bde4438663 | ||
|
|
a2ec2f9d41 | ||
|
|
e2e1a466f4 | ||
|
|
85dd5a6f66 | ||
|
|
a6472f8e2e | ||
|
|
eeefd1f002 | ||
|
|
6878777140 |
+5
-3
@@ -1,6 +1,6 @@
|
||||
[package]
|
||||
name = "osui"
|
||||
version = "0.0.8-alpha.2"
|
||||
version = "0.0.9-alpha.2"
|
||||
edition = "2021"
|
||||
license = "Apache-2.0"
|
||||
description = "A TUI library for advanced uis"
|
||||
@@ -8,6 +8,10 @@ repository = "https://github.com/osui-rs/osui"
|
||||
homepage = "https://osui.netlify.app"
|
||||
documentation = "https://osui.netlify.app/docs/"
|
||||
|
||||
[features]
|
||||
no_rsx = []
|
||||
no_elem = []
|
||||
|
||||
[lib]
|
||||
name = "osui"
|
||||
path = "src/lib.rs"
|
||||
@@ -21,8 +25,6 @@ cc = "1.0"
|
||||
|
||||
[dependencies]
|
||||
crossterm = "0.28.1"
|
||||
dyn-clone = "1.0.17"
|
||||
osui-element = "0.1.23"
|
||||
|
||||
[profile.dev]
|
||||
opt-level = 1
|
||||
|
||||
@@ -20,6 +20,20 @@
|
||||
<b>OSUI is a customizable terminal user interface (TUI) library written in Rust. It provides a set of components and rsx to build interactive command-line interfaces with ease.</b>
|
||||
</p>
|
||||
|
||||
```rust
|
||||
use osui::{style::Transform, Screen};
|
||||
|
||||
fn main() -> std::io::Result<()> {
|
||||
let screen = Screen::new();
|
||||
|
||||
screen
|
||||
.draw(format!("Hello, World"))
|
||||
.component(Transform::center());
|
||||
|
||||
screen.run()
|
||||
}
|
||||
```
|
||||
|
||||
## [Documentation](https://osui.netlify.app/docs)
|
||||
|
||||
## Features
|
||||
|
||||
-206
@@ -1,206 +0,0 @@
|
||||
#[macro_export]
|
||||
macro_rules! __css {
|
||||
($_style:expr,)=>{};
|
||||
// percentage (n%)
|
||||
(
|
||||
$_style:expr, $name:ident: $value:literal% $(, $($rest:tt)*)?
|
||||
) => {{
|
||||
$_style.$name = (true, Number::Pe($value));
|
||||
$crate::__css!($_style, $($($rest)*)?);
|
||||
}};
|
||||
|
||||
// Number
|
||||
(
|
||||
$_style:expr, $name:ident: $value:literal px $(, $($rest:tt)*)?
|
||||
) => {{
|
||||
$_style.$name = (true, Number::Px($value));
|
||||
$crate::__css!($_style, $($($rest)*)?);
|
||||
}};
|
||||
|
||||
// Vector
|
||||
(
|
||||
$_style:expr, $name:ident: [$($inner:tt),*] $(, $($rest:tt)*)?
|
||||
) => {{
|
||||
$_style.$name = (true, vec![$($inner),*]);
|
||||
$crate::__css!($_style, $($($rest)*)?);
|
||||
}};
|
||||
|
||||
// Normal
|
||||
(
|
||||
$_style:expr, $name:ident: $value:expr $(, $($rest:tt)*)?
|
||||
) => {{
|
||||
$_style.$name = (true, $value);
|
||||
$crate::__css!($_style, $($($rest)*)?);
|
||||
}};
|
||||
}
|
||||
|
||||
#[macro_export]
|
||||
macro_rules! _css {
|
||||
($_style:expr,) => {};
|
||||
(
|
||||
$hm:expr, $($($name:ident)-+),* { $($inner:tt)* } $($rest:tt)*
|
||||
) => {{
|
||||
let mut _style = $crate::ui::StyleElement::default();
|
||||
$crate::__css!(_style, $($inner)*);
|
||||
$(
|
||||
$hm.insert(
|
||||
$crate::ui::StyleName::Class(String::from(stringify!($($name)-+).replace(' ', ""))),
|
||||
_style.clone(),
|
||||
);
|
||||
)*
|
||||
$crate::_css!($hm, $($rest)*);
|
||||
}};
|
||||
(
|
||||
$hm:expr, $($($name:ident)-+),*: $state:literal { $($inner:tt)* } $($rest:tt)*
|
||||
) => {{
|
||||
let mut _style = $crate::ui::StyleElement::default();
|
||||
$crate::__css!(_style, $($inner)*);
|
||||
$(
|
||||
$hm.insert(
|
||||
$crate::ui::StyleName::ClassState(String::from(stringify!($($name)-+).replace(' ', "")), String::from($state)),
|
||||
_style.clone(),
|
||||
);
|
||||
)*
|
||||
$crate::_css!($hm, $($rest)*);
|
||||
}};
|
||||
(
|
||||
$hm:expr, $($name:literal),+ { $($inner:tt)* } $($rest:tt)*
|
||||
) => {{
|
||||
let mut _style = $crate::ui::StyleElement::default();
|
||||
$crate::__css!(_style, $($inner)*);
|
||||
$(
|
||||
$hm.insert(
|
||||
$crate::ui::StyleName::Class(String::from($name)),
|
||||
_style,
|
||||
);
|
||||
)+
|
||||
$crate::_css!($hm, $($rest)*);
|
||||
}};
|
||||
(
|
||||
$hm:expr, $($name:literal),+: $state:literal { $($inner:tt)* } $($rest:tt)*
|
||||
) => {{
|
||||
let mut _style = $crate::ui::StyleElement::default();
|
||||
$crate::__css!(_style, $($inner)*);
|
||||
$(
|
||||
$hm.insert(
|
||||
$crate::ui::StyleName::ClassState(String::from($name), String::from($state)),
|
||||
_style,
|
||||
);
|
||||
)+
|
||||
$crate::_css!($hm, $($rest)*);
|
||||
}};
|
||||
}
|
||||
|
||||
/// Creates a styling map `Css`
|
||||
///
|
||||
/// # Example
|
||||
/// ```
|
||||
/// css! {
|
||||
/// "btn" {
|
||||
/// color: Red,
|
||||
/// }
|
||||
/// "btn": "clicked" {
|
||||
/// color: Blue,
|
||||
/// }
|
||||
/// }
|
||||
/// ```
|
||||
///
|
||||
/// # Returns
|
||||
/// `Css`
|
||||
#[macro_export]
|
||||
macro_rules! css {
|
||||
(
|
||||
$($inner:tt)*
|
||||
) => {{
|
||||
#[allow(unused_mut)]
|
||||
let mut hm: $crate::ui::Css = std::collections::HashMap::new();
|
||||
$crate::_css!(hm, $($inner)*);
|
||||
hm
|
||||
}};
|
||||
}
|
||||
|
||||
#[macro_export]
|
||||
macro_rules! style {
|
||||
(
|
||||
$key:ident: $value:literal% $(, $($rest:tt)*)?
|
||||
) => {{
|
||||
let mut _style = $crate::ui::Style::default();
|
||||
$crate::__css!(_style.0, $key: $crate::ui::Number::Pe($value));
|
||||
$crate::style!{ _style; $($($rest)*)? }
|
||||
}};
|
||||
(
|
||||
$key:ident: $value:literal px $(, $($rest:tt)*)?
|
||||
) => {{
|
||||
let mut _style = $crate::ui::Style::default();
|
||||
$crate::__css!(_style.0, $key: $crate::ui::Number::Px($value));
|
||||
$crate::style!{ _style; $($($rest)*)? }
|
||||
}};
|
||||
(
|
||||
$style:expr; $key:ident: $value:literal% $(, $($rest:tt)*)?
|
||||
) => {{
|
||||
$crate::__css!($style.0, $key: $crate::ui::Number::Pe($value));
|
||||
$crate::style!{ $style; $($($rest)*)? }
|
||||
}};
|
||||
(
|
||||
$style:expr; $key:ident: $value:literal px $(, $($rest:tt)*)?
|
||||
) => {{
|
||||
$crate::__css!($style.0, $key: $crate::ui::Number::Px($value));
|
||||
$crate::style!{ $style; $($($rest)*)? }
|
||||
}};
|
||||
(
|
||||
$key:ident: $value:expr $(, $($rest:tt)*)?
|
||||
) => {{
|
||||
let mut _style = $crate::ui::Style::default();
|
||||
$crate::__css!(_style.0, $key: $value);
|
||||
$crate::style!{ _style; $($($rest)*)? }
|
||||
}};
|
||||
(
|
||||
$style:expr; $key:ident: $value:expr $(, $($rest:tt)*)?
|
||||
) => {{
|
||||
let mut style_elem = $crate::ui::StyleElement::default();
|
||||
$crate::__css!($style.0, $key: $value);
|
||||
$crate::style!{ $style; $($($rest)*)? }
|
||||
}};
|
||||
(
|
||||
($key:ident): $value:expr $(, $($rest:tt)*)?
|
||||
) => {{
|
||||
let mut _style = $crate::ui::Style::default();
|
||||
$crate::__css!(_style.0, ($key): $value);
|
||||
$crate::style!{ _style; $($($rest)*)? }
|
||||
}};
|
||||
(
|
||||
$style:expr; $key:literal: $value:expr $(, $($rest:tt)*)?
|
||||
) => {{
|
||||
let mut style_elem = $crate::ui::StyleElement::default();
|
||||
$crate::__css!($style.0, $key: $value);
|
||||
$crate::style!{ $style; $($($rest)*)? }
|
||||
}};
|
||||
|
||||
(
|
||||
$kind:ident {$($inner:tt)*} $(, $($rest:tt)*)?
|
||||
) => {{
|
||||
let mut _style = $crate::ui::Style::default();
|
||||
let mut style_elem = $crate::ui::StyleElement::default();
|
||||
$crate::__css!(style_elem, $($inner)*);
|
||||
_style.1.insert(stringify!($kind).to_string(), style_elem);
|
||||
$crate::style!{ _style; $($($rest)*)? }
|
||||
}};
|
||||
(
|
||||
$style:expr; $kind:ident {$($inner:tt)*} $(, $($rest:tt)*)?
|
||||
) => {{
|
||||
let mut style_elem = $crate::ui::StyleElement::default();
|
||||
$crate::__css!(style_elem, $($inner)*);
|
||||
$style.1.insert(stringify!($kind).to_string(), style_elem);
|
||||
$crate::style!{ $style; $($($rest)*)? }
|
||||
}};
|
||||
|
||||
(
|
||||
$style:expr;
|
||||
) => {{
|
||||
$style
|
||||
}};
|
||||
|
||||
() => {{
|
||||
$crate::ui::Style::default()
|
||||
}};
|
||||
}
|
||||
@@ -0,0 +1,70 @@
|
||||
use std::sync::{Arc, Mutex};
|
||||
|
||||
use crate::{
|
||||
widget::{Element, Widget},
|
||||
NoRender,
|
||||
};
|
||||
|
||||
pub struct Div {
|
||||
color: u32,
|
||||
children: Mutex<Vec<Arc<Widget>>>,
|
||||
size: (u16, u16),
|
||||
}
|
||||
|
||||
impl Element for Div {
|
||||
fn render(&mut self, scope: &mut crate::render_scope::RenderScope) {
|
||||
let (width, height) = scope.get_size_or(self.size.0, self.size.1);
|
||||
scope.draw_rect(width, height, self.color);
|
||||
}
|
||||
|
||||
fn after_render(&mut self, scope: &mut crate::render_scope::RenderScope) {
|
||||
let mut transform = scope.get_transform().clone();
|
||||
let (w, h) = scope.get_parent_size();
|
||||
scope.set_parent_size(transform.width, transform.height);
|
||||
|
||||
for elem in self.children.lock().unwrap().iter() {
|
||||
scope.clear();
|
||||
if let Some(t) = elem.get() {
|
||||
scope.set_transform(&t);
|
||||
}
|
||||
elem.0.lock().unwrap().render(scope);
|
||||
if let Some(t) = elem.get() {
|
||||
scope.set_transform(&t);
|
||||
}
|
||||
let t = scope.get_transform_mut();
|
||||
transform.width = transform.width.max(t.x + t.width);
|
||||
transform.height = transform.height.max(t.y + t.height);
|
||||
t.x += transform.x;
|
||||
t.y += transform.y;
|
||||
|
||||
scope.draw();
|
||||
elem.0.lock().unwrap().after_render(scope);
|
||||
scope.clear();
|
||||
}
|
||||
scope.set_parent_size(w, h);
|
||||
self.size = (transform.width, transform.height);
|
||||
}
|
||||
|
||||
fn draw_child(&self, element: &Arc<Widget>) {
|
||||
self.children.lock().unwrap().push(element.clone());
|
||||
element.inject(|w| w.component(NoRender));
|
||||
}
|
||||
|
||||
fn as_any(&self) -> &dyn std::any::Any {
|
||||
self
|
||||
}
|
||||
|
||||
fn as_any_mut(&mut self) -> &mut dyn std::any::Any {
|
||||
self
|
||||
}
|
||||
}
|
||||
|
||||
impl Div {
|
||||
pub fn new(color: u32) -> Self {
|
||||
Div {
|
||||
color,
|
||||
children: Mutex::new(Vec::new()),
|
||||
size: (0, 0),
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,141 @@
|
||||
use std::sync::{Arc, Mutex};
|
||||
|
||||
use crate::{widget::{Element, Widget}, NoRender};
|
||||
|
||||
pub struct FlexRow {
|
||||
color: u32,
|
||||
gap: u16,
|
||||
children: Mutex<Vec<Arc<Widget>>>,
|
||||
size: (u16, u16),
|
||||
}
|
||||
|
||||
pub struct FlexCol {
|
||||
color: u32,
|
||||
gap: u16,
|
||||
children: Mutex<Vec<Arc<Widget>>>,
|
||||
size: (u16, u16),
|
||||
}
|
||||
|
||||
impl Element for FlexRow {
|
||||
fn render(&mut self, scope: &mut crate::render_scope::RenderScope) {
|
||||
let (width, height) = scope.get_size_or(self.size.0, self.size.1);
|
||||
scope.draw_rect(width, height, self.color);
|
||||
}
|
||||
|
||||
fn after_render(&mut self, scope: &mut crate::render_scope::RenderScope) {
|
||||
let mut transform = scope.get_transform().clone();
|
||||
let (w, h) = scope.get_parent_size();
|
||||
scope.set_parent_size(transform.width, transform.height);
|
||||
|
||||
let mut v = 0;
|
||||
|
||||
for elem in self.children.lock().unwrap().iter() {
|
||||
scope.clear();
|
||||
if let Some(t) = elem.get() {
|
||||
scope.set_transform(&t);
|
||||
}
|
||||
elem.0.lock().unwrap().render(scope);
|
||||
if let Some(t) = elem.get() {
|
||||
scope.set_transform(&t);
|
||||
}
|
||||
let t = scope.get_transform_mut();
|
||||
transform.width = transform.width.max(t.width);
|
||||
transform.height = transform.height.max(v + t.height);
|
||||
t.x += transform.x;
|
||||
t.y += transform.y + v;
|
||||
v += t.height + self.gap;
|
||||
|
||||
scope.draw();
|
||||
|
||||
elem.0.lock().unwrap().after_render(scope);
|
||||
}
|
||||
scope.set_parent_size(w, h);
|
||||
self.size = (transform.width, transform.height);
|
||||
}
|
||||
|
||||
fn draw_child(&self, element: &Arc<Widget>) {
|
||||
self.children.lock().unwrap().push(element.clone());
|
||||
element.inject(|w| w.component(NoRender));
|
||||
}
|
||||
|
||||
fn as_any(&self) -> &dyn std::any::Any {
|
||||
self
|
||||
}
|
||||
|
||||
fn as_any_mut(&mut self) -> &mut dyn std::any::Any {
|
||||
self
|
||||
}
|
||||
}
|
||||
|
||||
impl FlexRow {
|
||||
pub fn new(color: u32, gap: u16) -> Self {
|
||||
Self {
|
||||
children: Mutex::new(Vec::new()),
|
||||
size: (0, 0),
|
||||
color,
|
||||
gap,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl Element for FlexCol {
|
||||
fn render(&mut self, scope: &mut crate::render_scope::RenderScope) {
|
||||
let (width, height) = scope.get_size_or(self.size.0, self.size.1);
|
||||
scope.draw_rect(width, height, self.color);
|
||||
}
|
||||
|
||||
fn after_render(&mut self, scope: &mut crate::render_scope::RenderScope) {
|
||||
let mut transform = scope.get_transform().clone();
|
||||
let (w, h) = scope.get_parent_size();
|
||||
scope.set_parent_size(transform.width, transform.height);
|
||||
|
||||
let mut v = 0;
|
||||
|
||||
for elem in self.children.lock().unwrap().iter() {
|
||||
scope.clear();
|
||||
if let Some(t) = elem.get() {
|
||||
scope.set_transform(&t);
|
||||
}
|
||||
elem.0.lock().unwrap().render(scope);
|
||||
if let Some(t) = elem.get() {
|
||||
scope.set_transform(&t);
|
||||
}
|
||||
let t = scope.get_transform_mut();
|
||||
transform.width = transform.width.max(v + t.width);
|
||||
transform.height = transform.height.max(t.height);
|
||||
t.x += transform.x + v;
|
||||
t.y += transform.y;
|
||||
v += t.width + self.gap;
|
||||
|
||||
scope.draw();
|
||||
|
||||
elem.0.lock().unwrap().after_render(scope);
|
||||
}
|
||||
scope.set_parent_size(w, h);
|
||||
self.size = (transform.width, transform.height);
|
||||
}
|
||||
|
||||
fn draw_child(&self, element: &Arc<Widget>) {
|
||||
self.children.lock().unwrap().push(element.clone());
|
||||
element.inject(|w| w.component(NoRender));
|
||||
}
|
||||
|
||||
fn as_any(&self) -> &dyn std::any::Any {
|
||||
self
|
||||
}
|
||||
|
||||
fn as_any_mut(&mut self) -> &mut dyn std::any::Any {
|
||||
self
|
||||
}
|
||||
}
|
||||
|
||||
impl FlexCol {
|
||||
pub fn new(color: u32, gap: u16) -> Self {
|
||||
Self {
|
||||
children: Mutex::new(Vec::new()),
|
||||
size: (0, 0),
|
||||
color,
|
||||
gap,
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,37 @@
|
||||
pub mod div;
|
||||
pub mod flex;
|
||||
pub mod shape;
|
||||
|
||||
pub use div::*;
|
||||
pub use flex::*;
|
||||
pub use shape::*;
|
||||
|
||||
use crate::Element;
|
||||
|
||||
impl Element for String {
|
||||
fn render(&mut self, scope: &mut crate::render_scope::RenderScope) {
|
||||
scope.draw_text(self);
|
||||
}
|
||||
|
||||
fn as_any(&self) -> &dyn std::any::Any {
|
||||
self
|
||||
}
|
||||
|
||||
fn as_any_mut(&mut self) -> &mut dyn std::any::Any {
|
||||
self
|
||||
}
|
||||
}
|
||||
|
||||
impl Element for (String, u32) {
|
||||
fn render(&mut self, scope: &mut crate::render_scope::RenderScope) {
|
||||
scope.draw_text_colored(&self.0, self.1);
|
||||
}
|
||||
|
||||
fn as_any(&self) -> &dyn std::any::Any {
|
||||
self
|
||||
}
|
||||
|
||||
fn as_any_mut(&mut self) -> &mut dyn std::any::Any {
|
||||
self
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,59 @@
|
||||
use crate::widget::Element;
|
||||
|
||||
pub struct RoundedOutline;
|
||||
|
||||
impl Element for RoundedOutline {
|
||||
fn render(&mut self, scope: &mut crate::prelude::RenderScope) {
|
||||
let (w, h) = scope.get_size_or_parent();
|
||||
if w > 2 && h > 2 {
|
||||
let d = "─".repeat(w as usize - 2);
|
||||
scope.draw_text(&format!(
|
||||
"╭{d}╮{}\n╰{d}╯",
|
||||
format!("\n│{}│", " ".repeat(w as usize - 2)).repeat(h as usize - 2),
|
||||
));
|
||||
}
|
||||
}
|
||||
|
||||
fn as_any(&self) -> &dyn std::any::Any {
|
||||
self
|
||||
}
|
||||
|
||||
fn as_any_mut(&mut self) -> &mut dyn std::any::Any {
|
||||
self
|
||||
}
|
||||
}
|
||||
|
||||
impl RoundedOutline {
|
||||
pub fn new() -> Self {
|
||||
Self
|
||||
}
|
||||
}
|
||||
|
||||
pub struct Outline;
|
||||
|
||||
impl Element for Outline {
|
||||
fn render(&mut self, scope: &mut crate::prelude::RenderScope) {
|
||||
let (w, h) = scope.get_size_or_parent();
|
||||
if w > 2 && h > 2 {
|
||||
let d = "─".repeat(w as usize - 2);
|
||||
scope.draw_text(&format!(
|
||||
"┌{d}┐{}\n└{d}┘",
|
||||
format!("\n│{}│", " ".repeat(w as usize - 2)).repeat(h as usize - 2),
|
||||
));
|
||||
}
|
||||
}
|
||||
|
||||
fn as_any(&self) -> &dyn std::any::Any {
|
||||
self
|
||||
}
|
||||
|
||||
fn as_any_mut(&mut self) -> &mut dyn std::any::Any {
|
||||
self
|
||||
}
|
||||
}
|
||||
|
||||
impl Outline {
|
||||
pub fn new() -> Self {
|
||||
Self
|
||||
}
|
||||
}
|
||||
-132
@@ -1,132 +0,0 @@
|
||||
pub mod counter_example {
|
||||
use crate::prelude::*;
|
||||
|
||||
#[component]
|
||||
pub fn App() -> Element {
|
||||
let count = use_state(0);
|
||||
|
||||
rsx! {
|
||||
@SetStyle(styling())
|
||||
|
||||
button {
|
||||
class: "btn",
|
||||
|
||||
on_click: fn(_, _, _) @count {
|
||||
count += 1;
|
||||
},
|
||||
|
||||
"The current count is: {count}"
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
pub fn styling() -> Css {
|
||||
css! {
|
||||
btn {
|
||||
outline: true,
|
||||
outline_color: Red
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
pub mod todo_example {
|
||||
use crate::prelude::*;
|
||||
|
||||
#[component]
|
||||
pub fn App() -> Element {
|
||||
let todo = vec!["Todo", "Hovering", "Completed", "Foo", "Bar"];
|
||||
|
||||
rsx! {
|
||||
@SetStyle(styling())
|
||||
@SetChild(2)
|
||||
|
||||
text { class: "title", static "Todo list app made with OSUI" }
|
||||
text { class: "title", "{}", "-".repeat(crossterm::terminal::size().unwrap().0 as usize) }
|
||||
for (t in todo) {
|
||||
ersx!(button { class: "todo", on_click: fn(btn: &mut Button, _, _) {
|
||||
btn.class = if btn.class == "todo" {
|
||||
"complete"
|
||||
} else {
|
||||
"todo"
|
||||
};
|
||||
}, "{t}" } )
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
pub fn styling() -> Css {
|
||||
css! {
|
||||
todo {
|
||||
x: 0 px,
|
||||
y: Auto,
|
||||
color: Red,
|
||||
}
|
||||
todo: "hover" {
|
||||
color: Blue,
|
||||
}
|
||||
complete {
|
||||
x: 0 px,
|
||||
y: Auto,
|
||||
color: Green,
|
||||
}
|
||||
complete: "hover" {
|
||||
color: Cyan
|
||||
}
|
||||
title {
|
||||
x: 0 px,
|
||||
y: Auto,
|
||||
}
|
||||
title: "hover" {
|
||||
color: Blue
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
pub mod login_example {
|
||||
use crate::prelude::*;
|
||||
|
||||
#[component]
|
||||
pub fn App() -> Element {
|
||||
rsx! {
|
||||
@SetStyle(styling())
|
||||
|
||||
input { class: "input", id: "usr", on_click: fn(_, _, document) {
|
||||
let root = document.get_root::<Div>();
|
||||
root.children.set_index(1);
|
||||
}, "username: " }
|
||||
|
||||
input { class: "input", id: "psw", on_click: fn(_, _, document) {
|
||||
let root = document.get_root::<Div>();
|
||||
root.children.set_index(2);
|
||||
}, "password: " }
|
||||
|
||||
button { class: "input", on_click: fn(_, _, document) {
|
||||
if let Some(usr) = document.get_element_by_id::<Input>("usr") {
|
||||
if let Some(psw) = document.get_element_by_id::<Input>("psw") {
|
||||
document.draw(rsx! {
|
||||
text { static "Username: {}\nPassword: {}", usr.text, psw.text }
|
||||
});
|
||||
}
|
||||
}
|
||||
}, "Submit" }
|
||||
}
|
||||
}
|
||||
|
||||
pub fn styling() -> Css {
|
||||
css! {
|
||||
input {
|
||||
width: 50 px,
|
||||
outline: true,
|
||||
y: Auto,
|
||||
x: 0 px,
|
||||
caret: String::new(),
|
||||
}
|
||||
input: "hover" {
|
||||
outline_color: Red,
|
||||
caret: String::from("█"),
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,27 @@
|
||||
use std::sync::Arc;
|
||||
|
||||
use crate::{component, extensions::Extension, widget::Widget, Screen};
|
||||
|
||||
pub struct IdExtension(pub Arc<Screen>);
|
||||
|
||||
impl Extension for Arc<IdExtension> {}
|
||||
|
||||
impl IdExtension {
|
||||
pub fn new(screen: Arc<Screen>) -> Arc<Self> {
|
||||
Arc::new(IdExtension(screen))
|
||||
}
|
||||
|
||||
pub fn get_element(self: &Arc<IdExtension>, id: usize) -> Option<Arc<Widget>> {
|
||||
for elem in self.0.widgets.lock().unwrap().iter() {
|
||||
if let Some(current_id) = elem.get::<Id>() {
|
||||
if current_id.0 == id {
|
||||
return Some(elem.clone());
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
None
|
||||
}
|
||||
}
|
||||
|
||||
component!(Id(pub usize));
|
||||
@@ -0,0 +1,59 @@
|
||||
pub mod id;
|
||||
pub mod resources;
|
||||
pub mod tick;
|
||||
pub mod velocity;
|
||||
|
||||
pub use id::*;
|
||||
pub use resources::*;
|
||||
pub use tick::*;
|
||||
pub use velocity::*;
|
||||
|
||||
use std::{
|
||||
any::{type_name, Any},
|
||||
fmt::Debug,
|
||||
sync::{Arc, Mutex},
|
||||
};
|
||||
|
||||
use crate::{
|
||||
render_scope::RenderScope,
|
||||
widget::{Component, Widget},
|
||||
Screen,
|
||||
};
|
||||
|
||||
pub trait Extension {
|
||||
fn init(&mut self, _screen: Arc<Screen>) {}
|
||||
fn render_widget(&mut self, _scope: &mut RenderScope, _widget: &Arc<Widget>) {}
|
||||
}
|
||||
|
||||
pub trait Event: Send + Sync {
|
||||
fn as_any(&self) -> &dyn Any;
|
||||
}
|
||||
|
||||
#[derive(Clone)]
|
||||
pub struct Handler<E: Event>(Arc<Mutex<dyn FnMut(&Arc<Widget>, &E) + Send + Sync>>);
|
||||
|
||||
impl<E: Event + 'static> Component for Handler<E> {
|
||||
fn as_any(&self) -> &dyn Any {
|
||||
self
|
||||
}
|
||||
|
||||
fn as_any_mut(&mut self) -> &mut dyn Any {
|
||||
self
|
||||
}
|
||||
}
|
||||
|
||||
impl<E: Event + 'static> Handler<E> {
|
||||
pub fn new<F: FnMut(&Arc<Widget>, &E) + Send + Sync + 'static>(f: F) -> Handler<E> {
|
||||
Handler(Arc::new(Mutex::new(f)))
|
||||
}
|
||||
|
||||
pub fn call(&self, w: &Arc<Widget>, e: &E) {
|
||||
(self.0.lock().unwrap())(w, e)
|
||||
}
|
||||
}
|
||||
|
||||
impl<E: Event> Debug for Handler<E> {
|
||||
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
|
||||
write!(f, "Handler({})", type_name::<E>())
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,22 @@
|
||||
use std::sync::{Arc, Mutex};
|
||||
|
||||
#[derive(Clone)]
|
||||
pub struct VecResource<T>(Arc<Mutex<Box<dyn FnMut(&T) + Send + Sync>>>);
|
||||
|
||||
impl<T: Send + Sync + 'static> VecResource<T> {
|
||||
pub fn new() -> Self {
|
||||
Self(Arc::new(Mutex::new(Box::new(|_| {}))))
|
||||
}
|
||||
|
||||
pub fn iterate<F: FnMut(&T) + Send + Sync + 'static>(&self, f: F) {
|
||||
*self.0.lock().unwrap() = Box::new(f);
|
||||
}
|
||||
|
||||
pub fn push(&self, e: T) {
|
||||
let i = self.0.clone();
|
||||
|
||||
std::thread::spawn(move || {
|
||||
(i.lock().unwrap())(&e);
|
||||
});
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,29 @@
|
||||
use std::{fmt::Debug, sync::Arc};
|
||||
|
||||
use crate::extensions::Extension;
|
||||
use crate::extensions::Handler;
|
||||
use crate::{event, Screen};
|
||||
|
||||
pub struct TickExtension(pub u16);
|
||||
|
||||
impl Extension for TickExtension {
|
||||
fn init(&mut self, screen: Arc<Screen>) {
|
||||
let rate_dur = 1000 / self.0 as u64;
|
||||
std::thread::spawn({
|
||||
move || {
|
||||
let mut tick = 0;
|
||||
loop {
|
||||
for w in screen.widgets.lock().unwrap().iter() {
|
||||
if let Some(on_tick) = w.get::<Handler<TickEvent>>() {
|
||||
on_tick.call(&w, &TickEvent(tick))
|
||||
}
|
||||
}
|
||||
tick += 1;
|
||||
std::thread::sleep(std::time::Duration::from_millis(rate_dur));
|
||||
}
|
||||
}
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
event!(TickEvent(pub u32));
|
||||
@@ -0,0 +1,66 @@
|
||||
use std::sync::Arc;
|
||||
|
||||
use crate::{
|
||||
component,
|
||||
extensions::Extension,
|
||||
style::{Position, Transform},
|
||||
widget::Widget,
|
||||
Screen,
|
||||
};
|
||||
|
||||
pub struct VelocityExtension;
|
||||
|
||||
impl VelocityExtension {
|
||||
fn apply_velocity(ticks: u16, velocity: i32, x: &mut u16) {
|
||||
if velocity.abs() != 0 && ticks as i32 % (1000 / velocity.abs()) == 0 {
|
||||
if velocity > 0 {
|
||||
*x += 1;
|
||||
} else if velocity < 0 {
|
||||
*x -= 1;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl VelocityExtension {
|
||||
fn apply_velocity_xy(ticks: u16, widget: &Arc<Widget>) {
|
||||
if let Some(velocity) = widget.get::<Velocity>() {
|
||||
if let Some(mut t) = widget.get::<Transform>() {
|
||||
match &mut t.x {
|
||||
Position::Const(x) => Self::apply_velocity(ticks, velocity.0, x),
|
||||
_ => {}
|
||||
}
|
||||
|
||||
match &mut t.y {
|
||||
Position::Const(y) => Self::apply_velocity(ticks, velocity.1, y),
|
||||
_ => {}
|
||||
}
|
||||
|
||||
widget.set_component(t);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl Extension for VelocityExtension {
|
||||
fn init(&mut self, screen: Arc<Screen>) {
|
||||
std::thread::spawn({
|
||||
move || {
|
||||
let mut tick = 0;
|
||||
loop {
|
||||
for widget in screen.widgets.lock().unwrap().iter() {
|
||||
Self::apply_velocity_xy(tick, widget);
|
||||
}
|
||||
if tick > 1000 {
|
||||
tick = 0;
|
||||
} else {
|
||||
tick += 1;
|
||||
}
|
||||
std::thread::sleep(std::time::Duration::from_millis(1));
|
||||
}
|
||||
}
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
component!(Velocity(pub i32, pub i32));
|
||||
@@ -0,0 +1,58 @@
|
||||
use std::sync::Arc;
|
||||
|
||||
use crate::{
|
||||
state::DependencyHandler,
|
||||
widget::{Widget, WidgetLoad},
|
||||
Screen,
|
||||
};
|
||||
|
||||
pub enum RsxElement {
|
||||
Element(
|
||||
Box<dyn FnMut() -> WidgetLoad + Send + Sync>,
|
||||
Vec<Box<dyn DependencyHandler>>,
|
||||
Rsx,
|
||||
),
|
||||
}
|
||||
|
||||
pub struct Rsx(pub Vec<RsxElement>);
|
||||
|
||||
impl Rsx {
|
||||
pub fn draw(self, screen: &Arc<Screen>) {
|
||||
self.draw_parent(screen, None);
|
||||
}
|
||||
|
||||
pub fn draw_parent(self, screen: &Arc<Screen>, parent: Option<Arc<Widget>>) {
|
||||
for rsx_elem in self.0 {
|
||||
match rsx_elem {
|
||||
RsxElement::Element(f, dep, child) => {
|
||||
let w = if let Some(parent) = &parent {
|
||||
let w = screen.draw_box(f);
|
||||
parent.0.lock().unwrap().draw_child(&w);
|
||||
w
|
||||
} else {
|
||||
screen.draw_box(f)
|
||||
};
|
||||
|
||||
for d in dep {
|
||||
w.dependency_box(d);
|
||||
}
|
||||
child.draw_parent(screen, Some(w.clone()));
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
pub fn create_element<F: FnMut() -> WidgetLoad + Send + Sync + 'static>(
|
||||
&mut self,
|
||||
load: F,
|
||||
dependencies: Vec<Box<dyn DependencyHandler>>,
|
||||
children: Rsx,
|
||||
) {
|
||||
self.0
|
||||
.push(RsxElement::Element(Box::new(load), dependencies, children));
|
||||
}
|
||||
|
||||
pub fn expand(&mut self, other: &mut Rsx) {
|
||||
self.0.append(&mut other.0);
|
||||
}
|
||||
}
|
||||
+97
-508
@@ -1,543 +1,132 @@
|
||||
//! # OSUI
|
||||
//!
|
||||
//! A terminal user interface (TUI) library providing customizable components
|
||||
//! to build command-line interfaces in Rust. OSUI enables users to create
|
||||
//! interactive CLI applications with various UI elements and handle keyboard
|
||||
//! input for real-time events.
|
||||
//!
|
||||
//! ## Example Usage
|
||||
//!
|
||||
//! ```rust
|
||||
//! use osui::prelude::*;
|
||||
//!
|
||||
//! #[component]
|
||||
//! pub fn App() -> Element {
|
||||
//! let count = State::new(0);
|
||||
//!
|
||||
//! rsx! {
|
||||
//! button {
|
||||
//! class: "btn",
|
||||
//!
|
||||
//! on_click: fn(_, _, _) @count {
|
||||
//! count += 1;
|
||||
//! },
|
||||
//!
|
||||
//! "The current count is: {count}"
|
||||
//! }
|
||||
//! }
|
||||
//! }
|
||||
//! fn main() {
|
||||
//! launch!(App);
|
||||
//! }
|
||||
//! ```
|
||||
//!
|
||||
//! ## Modules
|
||||
//! - `ui` - Contains all user interface components, enabling rich CLI experiences.
|
||||
//! - `utils` - Utility functions for common TUI tasks such as clearing the screen.
|
||||
use std::sync::{Arc, Mutex};
|
||||
|
||||
use std::{
|
||||
collections::HashMap,
|
||||
fmt::Debug,
|
||||
ops::{AddAssign, SubAssign},
|
||||
sync::{Arc, Mutex},
|
||||
use crate::{
|
||||
extensions::{Extension, Handler},
|
||||
render_scope::RenderScope,
|
||||
widget::{Element, Widget, WidgetLoad},
|
||||
};
|
||||
|
||||
use crossterm::event::Event;
|
||||
use ui::{Style, StyleCore};
|
||||
use utils::VisibleLength;
|
||||
|
||||
pub mod css;
|
||||
pub mod examples;
|
||||
pub mod elements;
|
||||
pub mod extensions;
|
||||
pub mod frontend;
|
||||
pub mod macros;
|
||||
pub mod rsx;
|
||||
pub mod ui;
|
||||
pub mod render_scope;
|
||||
pub mod state;
|
||||
pub mod style;
|
||||
pub mod utils;
|
||||
pub mod widget;
|
||||
|
||||
pub mod prelude {
|
||||
pub use crate::ui::Color::*;
|
||||
pub use crate::ui::Font::*;
|
||||
pub use crate::ui::Number::{Auto, Center};
|
||||
pub use crate::Instruction::*;
|
||||
pub use crate::{self as osui, css, ersx, launch, rsx, ui::*, Handler};
|
||||
pub use crate::{style, Component, Document};
|
||||
pub use crate::{Children, Element, ElementCore, ElementWidget};
|
||||
pub use crossterm::event::{Event, KeyCode, KeyEvent, KeyEventKind};
|
||||
pub use osui_element::component;
|
||||
pub fn sleep(ms: u64) {
|
||||
std::thread::sleep(std::time::Duration::from_millis(ms));
|
||||
}
|
||||
pub fn use_state<'a, T>(v: T) -> crate::State<T> {
|
||||
crate::State::new(v)
|
||||
}
|
||||
}
|
||||
|
||||
//////////////////////////////////////////////////////////////////////////////////////////////////
|
||||
// Type aliases
|
||||
//////////////////////////////////////////////////////////////////////////////////////////////////
|
||||
|
||||
pub type Element = Box<dyn ElementWidget>;
|
||||
|
||||
//////////////////////////////////////////////////////////////////////////////////////////////////
|
||||
/// Traits
|
||||
//////////////////////////////////////////////////////////////////////////////////////////////////
|
||||
|
||||
pub trait ElementCore {
|
||||
fn get_element_by_id(&mut self, id: &str) -> Option<&mut Element>;
|
||||
fn get_id(&self) -> String;
|
||||
fn get_class(&self) -> String;
|
||||
fn get_style(&self) -> &Style;
|
||||
}
|
||||
|
||||
pub trait ElementWidget: ElementCore + std::fmt::Debug {
|
||||
fn render(&self, writer: &mut Writer);
|
||||
fn event(&mut self, event: crossterm::event::Event, document: &mut Document) {
|
||||
_ = (event, document)
|
||||
}
|
||||
fn initialize(&mut self, document: &mut Document) {
|
||||
_ = document
|
||||
}
|
||||
}
|
||||
|
||||
pub trait Component: std::fmt::Debug {
|
||||
type Element;
|
||||
fn create_element(self) -> Self::Element;
|
||||
}
|
||||
|
||||
//////////////////////////////////////////////////////////////////////////////////////////////////
|
||||
/// Structs
|
||||
//////////////////////////////////////////////////////////////////////////////////////////////////
|
||||
|
||||
pub struct Handler<T>(pub Arc<Mutex<dyn FnMut(&mut T, crossterm::event::Event, &mut Document)>>);
|
||||
|
||||
pub struct Document {
|
||||
element: *mut Element,
|
||||
running: Option<bool>,
|
||||
pub css: ui::Css,
|
||||
}
|
||||
|
||||
#[derive(Debug)]
|
||||
pub struct Writer {
|
||||
css: *const ui::Css,
|
||||
style: ui::StyleElement,
|
||||
focused: bool,
|
||||
size: (u16, u16),
|
||||
pos: (u16, u16),
|
||||
written: (u16, u16),
|
||||
parent: Option<*mut Writer>,
|
||||
}
|
||||
|
||||
pub struct State<T>(Arc<Mutex<T>>);
|
||||
|
||||
//////////////////////////////////////////////////////////////////////////////////////////////////
|
||||
/// Enums
|
||||
//////////////////////////////////////////////////////////////////////////////////////////////////
|
||||
|
||||
pub enum Children {
|
||||
None,
|
||||
Text(Arc<dyn Fn() -> String>),
|
||||
StaticText(String),
|
||||
Children(Vec<Element>, usize),
|
||||
}
|
||||
|
||||
//////////////////////////////////////////////////////////////////////////////////////////////////
|
||||
/// Implementations
|
||||
//////////////////////////////////////////////////////////////////////////////////////////////////
|
||||
|
||||
impl Document {
|
||||
pub fn with_elem(element: &mut Element) -> Document {
|
||||
Document {
|
||||
element,
|
||||
running: None,
|
||||
css: HashMap::new(),
|
||||
}
|
||||
}
|
||||
pub fn exit(&mut self) {
|
||||
self.running = Some(false);
|
||||
}
|
||||
pub fn restart(&mut self) {
|
||||
self.running = Some(true);
|
||||
}
|
||||
pub fn get_root<T>(&self) -> &mut Box<T> {
|
||||
unsafe { &mut *(self.element as *mut Element as *mut Box<T>) }
|
||||
}
|
||||
pub fn get_element_by_id<T>(&self, id: &str) -> Option<&mut Box<T>> {
|
||||
if let Some(e) = self.get_element_by_id_raw(id) {
|
||||
Some(unsafe { &mut *(e as *mut Element as *mut Box<T>) })
|
||||
} else {
|
||||
None
|
||||
}
|
||||
}
|
||||
pub fn get_element_by_id_raw(&self, id: &str) -> Option<&mut Element> {
|
||||
if !self.element.is_null() {
|
||||
unsafe {
|
||||
if (*self.element).get_id() == id {
|
||||
Some(&mut *self.element)
|
||||
} else {
|
||||
(*self.element).get_element_by_id(id)
|
||||
}
|
||||
}
|
||||
} else {
|
||||
None
|
||||
}
|
||||
}
|
||||
pub fn render(&self) {
|
||||
if !self.element.is_null() {
|
||||
let (width, height) = crossterm::terminal::size().unwrap();
|
||||
let mut writer = Writer {
|
||||
css: &self.css,
|
||||
focused: true,
|
||||
style: ui::StyleElement {
|
||||
// outline: (true, true),
|
||||
..Default::default()
|
||||
},
|
||||
size: (width, height),
|
||||
pos: (1, 1),
|
||||
written: (0, 0),
|
||||
parent: None,
|
||||
pub use crate::{
|
||||
elements::*, extensions::*, frontend::*, render_scope::*, state::*, style::*, utils::*,
|
||||
widget::*, *,
|
||||
};
|
||||
let mut frame = writer.new_frame();
|
||||
utils::clear();
|
||||
frame.render(true, unsafe { &*self.element });
|
||||
writer.after_render(width, height);
|
||||
utils::flush();
|
||||
}
|
||||
}
|
||||
pub fn set_css(&mut self, css: ui::Css) {
|
||||
self.css = css;
|
||||
}
|
||||
pub fn clear_css(&mut self) {
|
||||
self.css.clear();
|
||||
}
|
||||
pub fn draw(&mut self, element: Element) {
|
||||
unsafe {
|
||||
*self.element = element;
|
||||
(*self.element).initialize(self);
|
||||
}
|
||||
}
|
||||
pub fn run(&mut self) -> bool {
|
||||
// Set up the screen
|
||||
utils::hide_cursor();
|
||||
crossterm::terminal::enable_raw_mode().unwrap();
|
||||
utils::clear();
|
||||
|
||||
self.running = None;
|
||||
let element = unsafe { &mut *self.element };
|
||||
self.render();
|
||||
element.initialize(self);
|
||||
|
||||
// Send initial event
|
||||
element.event(crossterm::event::Event::FocusGained, self);
|
||||
|
||||
while self.running == None {
|
||||
self.render();
|
||||
element.event(crossterm::event::read().unwrap(), self);
|
||||
pub use crate::style::{Dimension::{Full, Content}, Position::{Center, End}};
|
||||
}
|
||||
|
||||
utils::show_cursor();
|
||||
crossterm::terminal::disable_raw_mode().unwrap();
|
||||
utils::clear();
|
||||
pub struct Screen {
|
||||
pub widgets: Mutex<Vec<Arc<Widget>>>,
|
||||
extensions: Mutex<Vec<Arc<Mutex<Box<dyn Extension + Send + Sync>>>>>,
|
||||
}
|
||||
|
||||
self.running.unwrap()
|
||||
event!(RenderWrapperEvent(*mut RenderScope));
|
||||
component!(NoRender);
|
||||
|
||||
impl RenderWrapperEvent {
|
||||
pub fn get_scope(&self) -> &mut RenderScope {
|
||||
unsafe { &mut *self.0 }
|
||||
}
|
||||
}
|
||||
|
||||
impl Default for Children {
|
||||
fn default() -> Self {
|
||||
Self::None
|
||||
}
|
||||
}
|
||||
unsafe impl Send for RenderWrapperEvent {}
|
||||
unsafe impl Sync for RenderWrapperEvent {}
|
||||
|
||||
impl std::fmt::Debug for Children {
|
||||
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
|
||||
f.write_str(&match self {
|
||||
Self::None => String::new(),
|
||||
Self::Children(a, b) => format!("({b}, {a:?})"),
|
||||
Self::Text(a) => format!("{:?}", a()),
|
||||
Self::StaticText(a) => format!("static({a:?})"),
|
||||
impl Screen {
|
||||
pub fn new() -> Arc<Self> {
|
||||
Arc::new(Self {
|
||||
widgets: Mutex::new(Vec::new()),
|
||||
extensions: Mutex::new(Vec::new()),
|
||||
})
|
||||
}
|
||||
|
||||
pub fn draw<F: FnMut() -> WidgetLoad + 'static + Send + Sync>(
|
||||
self: &Arc<Self>,
|
||||
element: F,
|
||||
) -> Arc<Widget> {
|
||||
let w = Arc::new(Widget::new(Box::new(element)));
|
||||
self.widgets.lock().unwrap().push(w.clone());
|
||||
w
|
||||
}
|
||||
|
||||
impl Children {
|
||||
pub fn is_none(&self) -> bool {
|
||||
match self {
|
||||
Children::None => true,
|
||||
_ => false,
|
||||
pub fn draw_box(
|
||||
self: &Arc<Self>,
|
||||
element: Box<dyn FnMut() -> WidgetLoad + Send + Sync>,
|
||||
) -> Arc<Widget> {
|
||||
let w = Arc::new(Widget::new(Box::new(element)));
|
||||
self.widgets.lock().unwrap().push(w.clone());
|
||||
w
|
||||
}
|
||||
|
||||
pub fn extension<E: Extension + Send + Sync + 'static>(self: &Arc<Self>, ext: E) {
|
||||
self.extensions
|
||||
.lock()
|
||||
.unwrap()
|
||||
.push(Arc::new(Mutex::new(Box::new(ext))));
|
||||
}
|
||||
|
||||
pub fn run(self: &Arc<Self>) -> std::io::Result<()> {
|
||||
for ext in self.extensions.lock().unwrap().iter() {
|
||||
ext.lock().unwrap().init(self.clone());
|
||||
}
|
||||
|
||||
utils::hide_cursor()?;
|
||||
|
||||
loop {
|
||||
self.render()?;
|
||||
std::thread::sleep(std::time::Duration::from_millis(28));
|
||||
}
|
||||
}
|
||||
|
||||
pub fn get_text(&self) -> String {
|
||||
match self {
|
||||
Children::Text(text) => text(),
|
||||
Children::StaticText(text) => text.clone(),
|
||||
_ => String::new(),
|
||||
pub fn render(self: &Arc<Self>) -> std::io::Result<()> {
|
||||
let mut scope = RenderScope::new();
|
||||
let (w, h) = crossterm::terminal::size().unwrap();
|
||||
scope.set_parent_size(w, h);
|
||||
|
||||
utils::clear()?;
|
||||
for elem in self.widgets.lock().unwrap().iter() {
|
||||
if let Some(NoRender) = elem.get() {
|
||||
for ext in self.extensions.lock().unwrap().iter() {
|
||||
ext.lock().unwrap().render_widget(&mut scope, elem);
|
||||
}
|
||||
elem.auto_refresh();
|
||||
continue;
|
||||
}
|
||||
|
||||
pub fn set_text(&mut self, text: Arc<dyn Fn() -> String>) {
|
||||
match self {
|
||||
Children::Text(t) => {
|
||||
*t = text;
|
||||
}
|
||||
_ => {}
|
||||
}
|
||||
}
|
||||
|
||||
pub fn set_static(&mut self, text: String) {
|
||||
*self = Children::StaticText(text);
|
||||
}
|
||||
|
||||
pub fn add_child(&mut self, element: Element) {
|
||||
if let Children::Children(children, _) = self {
|
||||
children.push(element);
|
||||
}
|
||||
}
|
||||
pub fn get_child(&mut self) -> (Option<&mut Element>, usize) {
|
||||
if let Children::Children(children, child) = self {
|
||||
let l = children.len();
|
||||
(children.get_mut(*child), l)
|
||||
if let Some(wrapper) = elem.get::<Handler<RenderWrapperEvent>>() {
|
||||
wrapper.call(elem, &RenderWrapperEvent(&mut scope));
|
||||
} else {
|
||||
(None, 0)
|
||||
}
|
||||
}
|
||||
pub fn get_child_idx(&mut self) -> (Option<(&mut Element, &mut usize)>, usize) {
|
||||
if let Children::Children(children, child) = self {
|
||||
let l = children.len();
|
||||
if let Some(d) = children.get_mut(*child) {
|
||||
(Some((d, child)), l)
|
||||
} else {
|
||||
(None, 0)
|
||||
}
|
||||
} else {
|
||||
(None, 0)
|
||||
}
|
||||
}
|
||||
pub fn set_index(&mut self, index: usize) {
|
||||
if let Children::Children(_, child) = self {
|
||||
*child = index;
|
||||
}
|
||||
}
|
||||
pub fn len(&self) -> usize {
|
||||
if let Children::Children(children, _) = self {
|
||||
children.len()
|
||||
} else {
|
||||
0
|
||||
}
|
||||
}
|
||||
pub fn index(&self) -> usize {
|
||||
if let Children::Children(_, c) = self {
|
||||
*c
|
||||
} else {
|
||||
0
|
||||
}
|
||||
}
|
||||
pub fn index_mut(&mut self) -> Option<&mut usize> {
|
||||
if let Children::Children(_, c) = self {
|
||||
Some(c)
|
||||
} else {
|
||||
None
|
||||
}
|
||||
}
|
||||
pub fn insert(&mut self, index: usize, element: Element) {
|
||||
if let Children::Children(children, _) = self {
|
||||
children.insert(index, element);
|
||||
}
|
||||
}
|
||||
scope.clear();
|
||||
if let Some(t) = elem.get() {
|
||||
scope.set_transform(&t);
|
||||
}
|
||||
|
||||
impl<T> Handler<T> {
|
||||
pub fn new<F>(handler_fn: F) -> Handler<T>
|
||||
where
|
||||
F: FnMut(&mut T, crossterm::event::Event, &mut Document) + 'static,
|
||||
{
|
||||
Handler(Arc::new(Mutex::new(handler_fn)))
|
||||
for ext in self.extensions.lock().unwrap().iter() {
|
||||
ext.lock().unwrap().render_widget(&mut scope, elem);
|
||||
}
|
||||
|
||||
pub fn call(&self, s: &mut T, event: Event, document: &mut Document) {
|
||||
let mut o = self.0.lock().unwrap();
|
||||
o(s, event, document);
|
||||
elem.0.lock().unwrap().render(&mut scope);
|
||||
|
||||
if let Some(t) = elem.get() {
|
||||
scope.set_transform(&t);
|
||||
}
|
||||
scope.draw();
|
||||
|
||||
elem.0.lock().unwrap().after_render(&mut scope);
|
||||
}
|
||||
|
||||
pub fn clone(&self) -> Handler<T> {
|
||||
Handler(Arc::clone(&self.0))
|
||||
elem.auto_refresh();
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
|
||||
impl Writer {
|
||||
pub fn after_render(&self, width: u16, height: u16) {
|
||||
if self.style.outline.1 {
|
||||
let ol = self.style.write_outline("│");
|
||||
let hl = "─".repeat(width as usize);
|
||||
self.write_abs_outline(&self.style.write_outline(&format!("╭{}╮", hl)), (0, 0));
|
||||
for i in 1..height+1 {
|
||||
self.write_abs_outline(&ol, (0, i));
|
||||
self.write_abs_outline(&ol, (width + 1, i));
|
||||
}
|
||||
self.write_abs_outline(&self.style.write_outline(&format!("╰{}╯", hl)), (0, height + 1));
|
||||
}
|
||||
}
|
||||
|
||||
pub fn write(&mut self, s: &str) {
|
||||
self.write_abs(&self.style.write(&s), (0, 0));
|
||||
}
|
||||
|
||||
pub fn write_abs_outline(&self, s: &str, pos: (u16, u16)) {
|
||||
if let Some(parent) = self.parent {
|
||||
let parent = unsafe { &mut *parent };
|
||||
parent.write_abs_outline(s, (self.pos.0 + pos.0, self.pos.1 + pos.1));
|
||||
} else {
|
||||
print!(
|
||||
"\x1b[{};{}H{}",
|
||||
self.pos.1 + pos.1 - 1,
|
||||
self.pos.0 + pos.0 - 1,
|
||||
self.style.write_outline(s)
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
pub fn write_abs(&mut self, s: &str, pos: (u16, u16)) {
|
||||
let width = self.get_size().0 as usize;
|
||||
let mut max_written = self.written.0;
|
||||
let mut lines_written = 0;
|
||||
|
||||
let truncated_lines: Vec<_> = s
|
||||
.lines()
|
||||
.map(|l| {
|
||||
let truncated = if l.len() > width {
|
||||
l.chars().take(width).collect::<String>()
|
||||
} else {
|
||||
l.to_string()
|
||||
};
|
||||
max_written = max_written.max(truncated.visible_len() as u16);
|
||||
lines_written += 1;
|
||||
truncated
|
||||
})
|
||||
.collect();
|
||||
|
||||
self.written.0 = max_written;
|
||||
self.written.1 += lines_written;
|
||||
|
||||
if let Some(parent) = self.parent {
|
||||
let parent = unsafe { &mut *parent };
|
||||
let combined_pos = (self.pos.0 + pos.0, self.pos.1 + pos.1);
|
||||
let s_combined = truncated_lines.join("\n");
|
||||
parent.write_abs(&s_combined, combined_pos);
|
||||
} else {
|
||||
for (i, line) in truncated_lines.iter().enumerate() {
|
||||
print!(
|
||||
"\x1b[{};{}H{}",
|
||||
self.pos.1 + pos.1 + i as u16,
|
||||
self.pos.0 + pos.0,
|
||||
line
|
||||
);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
pub fn get_focused(&self) -> bool {
|
||||
self.focused
|
||||
}
|
||||
|
||||
pub fn get_size(&self) -> (u16, u16) {
|
||||
(
|
||||
self.style
|
||||
.width
|
||||
.1
|
||||
.as_size(self.size.0, self.size.0, self.style.outline.1),
|
||||
self.style
|
||||
.height
|
||||
.1
|
||||
.as_size(self.size.1, self.size.1, self.style.outline.1),
|
||||
)
|
||||
}
|
||||
|
||||
pub fn get_size_root(&self) -> (u16, u16) {
|
||||
(
|
||||
self.style
|
||||
.width
|
||||
.1
|
||||
.as_size(self.written.0, self.size.0, self.style.outline.1),
|
||||
self.style
|
||||
.height
|
||||
.1
|
||||
.as_size(self.written.1, self.size.1, self.style.outline.1),
|
||||
)
|
||||
}
|
||||
|
||||
pub fn new_frame(&mut self) -> crate::utils::Frame {
|
||||
crate::utils::Frame::new(self)
|
||||
}
|
||||
|
||||
pub fn caret(&self) -> String {
|
||||
format!(
|
||||
"{}{}\x1b[0m",
|
||||
self.style.cursor.1.ansi(),
|
||||
self.style.caret.1
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
impl<T> Default for Handler<T> {
|
||||
fn default() -> Self {
|
||||
Handler(Arc::new(Mutex::new(
|
||||
|_: &mut T, _: crossterm::event::Event, _: &mut Document| {},
|
||||
)))
|
||||
}
|
||||
}
|
||||
|
||||
impl<T> std::fmt::Debug for Handler<T> {
|
||||
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
|
||||
f.write_str("Handler()")
|
||||
}
|
||||
}
|
||||
|
||||
impl<T> State<T> {
|
||||
pub fn new<'a>(v: T) -> State<T> {
|
||||
State(Arc::new(Mutex::new(v)))
|
||||
}
|
||||
pub fn use_state<'a>(&'a self) -> std::sync::MutexGuard<'a, T> {
|
||||
self.0.lock().unwrap()
|
||||
}
|
||||
pub fn clone<'a>(&'a self) -> State<T> {
|
||||
State(Arc::clone(&self.0))
|
||||
}
|
||||
}
|
||||
|
||||
impl<T: std::fmt::Display> std::fmt::Display for State<T> {
|
||||
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
|
||||
// Acquire the lock, handle potential poisoning
|
||||
match self.0.lock() {
|
||||
Ok(guard) => write!(f, "{}", *guard),
|
||||
Err(poisoned) => write!(f, "<Poisoned: {}>", *poisoned.into_inner()),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl<T: AddAssign> AddAssign<T> for State<T> {
|
||||
fn add_assign(&mut self, rhs: T) {
|
||||
*self.0.lock().unwrap() += rhs;
|
||||
}
|
||||
}
|
||||
|
||||
impl<T: SubAssign> SubAssign<T> for State<T> {
|
||||
fn sub_assign(&mut self, rhs: T) {
|
||||
*self.0.lock().unwrap() -= rhs;
|
||||
}
|
||||
}
|
||||
|
||||
impl<T: PartialEq> PartialEq<T> for State<T> {
|
||||
fn eq(&self, other: &T) -> bool {
|
||||
self.use_state().eq(other)
|
||||
}
|
||||
fn ne(&self, other: &T) -> bool {
|
||||
self.use_state().ne(other)
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Debug)]
|
||||
pub enum Instruction<'a> {
|
||||
SetStyle(ui::Css),
|
||||
SetChild(usize),
|
||||
Ghost(usize),
|
||||
Load(Handler<ui::Div<'a>>),
|
||||
}
|
||||
|
||||
+169
-12
@@ -1,18 +1,175 @@
|
||||
#[macro_export]
|
||||
macro_rules! launch {
|
||||
($elem:path) => {
|
||||
let mut element = <$elem>::default().create_element();
|
||||
let mut document = $crate::Document::with_elem(&mut element);
|
||||
while document.run() {
|
||||
element = <$elem>::default().create_element();
|
||||
macro_rules! event {
|
||||
($name:ident) => {
|
||||
#[derive(Debug, Clone)]
|
||||
pub struct $name;
|
||||
|
||||
impl $crate::extensions::Event for $name {
|
||||
fn as_any(&self) -> &dyn std::any::Any {
|
||||
self
|
||||
}
|
||||
}
|
||||
};
|
||||
($elem:path, $css:expr) => {
|
||||
let mut element = <$elem>::default().create_element();
|
||||
let mut document = $crate::Document::with_elem(&mut element);
|
||||
document.set_css($css);
|
||||
while document.run() {
|
||||
element = <$elem>::default().create_element();
|
||||
|
||||
($name:ident {$($inner:tt)*}) => {
|
||||
#[derive(Debug, Clone)]
|
||||
pub struct $name {
|
||||
$($inner)*
|
||||
}
|
||||
|
||||
impl $crate::extensions::Event for $name {
|
||||
fn as_any(&self) -> &dyn std::any::Any {
|
||||
self
|
||||
}
|
||||
}
|
||||
};
|
||||
|
||||
($name:ident ($($inner:tt)*)) => {
|
||||
#[derive(Debug, Clone)]
|
||||
pub struct $name ($($inner)*);
|
||||
|
||||
impl $crate::extensions::Event for $name {
|
||||
fn as_any(&self) -> &dyn std::any::Any {
|
||||
self
|
||||
}
|
||||
}
|
||||
};
|
||||
}
|
||||
|
||||
#[macro_export]
|
||||
macro_rules! component {
|
||||
($name:ident) => {
|
||||
#[derive(Debug, Clone)]
|
||||
pub struct $name;
|
||||
|
||||
impl $crate::widget::Component for $name {
|
||||
fn as_any(&self) -> &dyn std::any::Any {
|
||||
self
|
||||
}
|
||||
|
||||
fn as_any_mut(&mut self) -> &mut dyn std::any::Any {
|
||||
self
|
||||
}
|
||||
}
|
||||
};
|
||||
|
||||
($name:ident {$($inner:tt)*}) => {
|
||||
#[derive(Debug, Clone)]
|
||||
pub struct $name {
|
||||
$($inner)*
|
||||
}
|
||||
|
||||
impl $crate::widget::Component for $name {
|
||||
fn as_any(&self) -> &dyn std::any::Any {
|
||||
self
|
||||
}
|
||||
|
||||
fn as_any_mut(&mut self) -> &mut dyn std::any::Any {
|
||||
self
|
||||
}
|
||||
}
|
||||
};
|
||||
|
||||
($name:ident ($($inner:tt)*)) => {
|
||||
#[derive(Debug, Clone)]
|
||||
pub struct $name ($($inner)*);
|
||||
|
||||
impl $crate::widget::Component for $name {
|
||||
fn as_any(&self) -> &dyn std::any::Any {
|
||||
self
|
||||
}
|
||||
|
||||
fn as_any_mut(&mut self) -> &mut dyn std::any::Any {
|
||||
self
|
||||
}
|
||||
}
|
||||
};
|
||||
}
|
||||
|
||||
/// Macro to create an event handler closure that calls a method on `self`
|
||||
///
|
||||
/// This macro automates the pattern of capturing `self` as a raw pointer,
|
||||
/// then passing an event to a method on `self` inside an unsafe closure.
|
||||
///
|
||||
/// # Parameters
|
||||
/// - `$self_ty`: The self type.
|
||||
/// - `$self`: The instance variable (usually `self`) to call the method on.
|
||||
/// - `$events`: The event source which has an `.on` method to register the handler.
|
||||
/// - `$method`: The method name on `self` to call when an event occurs.
|
||||
///
|
||||
/// # Usage
|
||||
/// ```rust
|
||||
/// event_handler!(self, events, on_keypress);
|
||||
/// ```
|
||||
///
|
||||
/// This expands roughly to:
|
||||
/// ```rust
|
||||
/// let self_ref = self as *mut Self;
|
||||
/// events.on(move |event| unsafe { (*self_ref).on_keypress(event) });
|
||||
/// ```
|
||||
///
|
||||
/// # Safety
|
||||
/// This macro uses `unsafe` code because it dereferences a raw pointer inside the closure.
|
||||
/// Ensure that the `self` reference lives at least as long as the closure to avoid undefined behavior.
|
||||
///
|
||||
/// # Why use raw pointers here?
|
||||
/// Often, event handlers require `'static` closures, but `self` is a stack reference.
|
||||
/// Capturing `self` directly is not possible, so this workaround uses a raw pointer.
|
||||
#[macro_export]
|
||||
macro_rules! event_handler {
|
||||
($self_ty:ty, $self:ident, $events:ident, $method:ident) => {{
|
||||
let self_ref = $self as *mut $self_ty;
|
||||
$events.on(move |es, e| unsafe { (*self_ref).$method(es, e) });
|
||||
}};
|
||||
}
|
||||
|
||||
#[macro_export]
|
||||
macro_rules! transform {
|
||||
($($f:ident: $v:expr),* $(,)?) => {{
|
||||
let mut t = Transform::new();
|
||||
$(t.$f = $v.into();)*
|
||||
t
|
||||
}};
|
||||
}
|
||||
|
||||
#[macro_export]
|
||||
macro_rules! rsx {
|
||||
($($inner:tt)*) => {{
|
||||
let mut r = $crate::frontend::Rsx(Vec::new());
|
||||
|
||||
$crate::rsx_inner! { r, $($inner)* };
|
||||
|
||||
r
|
||||
}};
|
||||
}
|
||||
|
||||
#[macro_export]
|
||||
macro_rules! rsx_inner {
|
||||
($r:expr, $(%$dep:ident)* $(@$comp:expr;)* $s:literal $($rest:tt)*) => {
|
||||
$r.create_element({ $(let $dep = $dep.clone();)* move || {
|
||||
$crate::widget::WidgetLoad::new(format!($s)) $(.component($comp))*
|
||||
} }, vec![$(Box::new($dep.clone())),*], $crate::frontend::Rsx(Vec::new()));
|
||||
$crate::rsx_inner! { $r, $($rest)* };
|
||||
};
|
||||
|
||||
($r:expr, $(%$dep:ident)* $(@$comp:expr;)* $name:path { $($inner:tt)* } ($($e:expr),*) $($rest:tt)*) => {
|
||||
$r.create_element({ $(let $dep = $dep.clone();)* move || {
|
||||
$crate::widget::WidgetLoad::new(<$name>::new($($e),*)) $(.component($comp))*
|
||||
} }, vec![$(Box::new($dep.clone())),*], $crate::rsx!{ $($inner)* });
|
||||
$crate::rsx_inner! { $r, $($rest)* };
|
||||
};
|
||||
|
||||
($r:expr, $(%$dep:ident)* $(@$comp:expr;)* $name:path { $($inner:tt)* } $($rest:tt)*) => {
|
||||
$r.create_element({ $(let $dep = $dep.clone();)* move || {
|
||||
$crate::widget::WidgetLoad::new(<$name>::new()) $(.component($comp))*
|
||||
} }, vec![$(Box::new($dep.clone())),*], $crate::rsx!{ $($inner)* });
|
||||
$crate::rsx_inner! { $r, $($rest)* };
|
||||
};
|
||||
|
||||
($r:expr, $expand:ident => ($($inner:tt)*) $($rest:tt)*) => {
|
||||
$r.expand(&mut $expand($($inner)*));
|
||||
$crate::rsx_inner! { $r, $($rest)* };
|
||||
};
|
||||
|
||||
($r:expr,) => {};
|
||||
}
|
||||
|
||||
+21
-20
@@ -1,27 +1,28 @@
|
||||
use osui::{examples, prelude::*};
|
||||
use osui::prelude::*;
|
||||
|
||||
fn main() {
|
||||
launch!(App);
|
||||
fn main() -> std::io::Result<()> {
|
||||
let screen = Screen::new();
|
||||
|
||||
app().draw(&screen);
|
||||
|
||||
screen.run()
|
||||
}
|
||||
|
||||
#[component]
|
||||
fn App() {
|
||||
fn app() -> Rsx {
|
||||
rsx! {
|
||||
@SetStyle(css! {
|
||||
example: "hover" {
|
||||
color: Blue,
|
||||
}
|
||||
})
|
||||
@transform! {
|
||||
width: Full,
|
||||
height: Full,
|
||||
};
|
||||
Div {
|
||||
@transform! {
|
||||
width: Full,
|
||||
height: Full,
|
||||
};
|
||||
RoundedOutline {}
|
||||
|
||||
%text { "Choose an example to run" }
|
||||
button { class: "example", on_click: |_, _, doc| {
|
||||
doc.draw(examples::counter_example::App::default().create_element());
|
||||
}, "Counter" }
|
||||
button { class: "example", on_click: |_, _, doc| {
|
||||
doc.draw(examples::login_example::App::default().create_element());
|
||||
}, "Login" }
|
||||
button { class: "example", on_click: |_, _, doc| {
|
||||
doc.draw(examples::todo_example::App::default().create_element());
|
||||
}, "Todo" }
|
||||
@Transform::center();
|
||||
"Welcome To OSUI!"
|
||||
} (0x000000)
|
||||
}
|
||||
}
|
||||
|
||||
@@ -0,0 +1,154 @@
|
||||
use std::fmt::Debug;
|
||||
|
||||
use crate::{
|
||||
style::{RawTransform, Transform},
|
||||
utils::{self, hex_ansi_bg},
|
||||
};
|
||||
|
||||
#[derive(Clone)]
|
||||
enum RenderMethod {
|
||||
Text(String),
|
||||
TextColored(String, u32),
|
||||
Rectangle(u16, u16, u32),
|
||||
}
|
||||
|
||||
#[derive(Clone)]
|
||||
pub struct RenderScope {
|
||||
transform: RawTransform,
|
||||
render_stack: Vec<RenderMethod>,
|
||||
parent_width: u16,
|
||||
parent_height: u16,
|
||||
}
|
||||
|
||||
impl RenderScope {
|
||||
pub fn new() -> RenderScope {
|
||||
RenderScope {
|
||||
transform: RawTransform::new(),
|
||||
render_stack: Vec::new(),
|
||||
parent_width: 0,
|
||||
parent_height: 0,
|
||||
}
|
||||
}
|
||||
|
||||
pub fn set_transform_raw(&mut self, transform: RawTransform) {
|
||||
self.transform = transform;
|
||||
}
|
||||
|
||||
pub fn set_transform(&mut self, transform: &Transform) {
|
||||
transform.use_dimensions(self.parent_width, self.parent_height, &mut self.transform);
|
||||
transform.use_position(self.parent_width, self.parent_height, &mut self.transform);
|
||||
}
|
||||
|
||||
pub fn draw_text(&mut self, text: &str) {
|
||||
self.render_stack.push(RenderMethod::Text(text.to_string()));
|
||||
let (w, h) = utils::str_size(text);
|
||||
self.transform.width = self.transform.width.max(w);
|
||||
self.transform.height = self.transform.height.max(h);
|
||||
}
|
||||
|
||||
pub fn draw_text_colored(&mut self, text: &str, color: u32) {
|
||||
self.render_stack
|
||||
.push(RenderMethod::TextColored(text.to_string(), color));
|
||||
let (w, h) = utils::str_size(text);
|
||||
self.transform.width = self.transform.width.max(w);
|
||||
self.transform.height = self.transform.height.max(h);
|
||||
}
|
||||
|
||||
pub fn draw_rect(&mut self, width: u16, height: u16, color: u32) {
|
||||
self.render_stack
|
||||
.push(RenderMethod::Rectangle(width, height, color));
|
||||
self.transform.width = self.transform.width.max(width);
|
||||
self.transform.height = self.transform.height.max(height);
|
||||
}
|
||||
|
||||
pub fn draw(&self) {
|
||||
for m in &self.render_stack {
|
||||
match m {
|
||||
RenderMethod::Text(t) => {
|
||||
utils::print(self.transform.x, self.transform.y, t);
|
||||
}
|
||||
RenderMethod::TextColored(t, c) => utils::print(
|
||||
self.transform.x,
|
||||
self.transform.y,
|
||||
&(utils::hex_ansi(*c) + t),
|
||||
),
|
||||
RenderMethod::Rectangle(width, height, color) => {
|
||||
utils::print_liner(
|
||||
self.transform.x,
|
||||
self.transform.y,
|
||||
&hex_ansi_bg(*color),
|
||||
&std::iter::repeat(" ".repeat(*width as usize))
|
||||
.take(*height as usize)
|
||||
.collect::<Vec<_>>()
|
||||
.join("\n"),
|
||||
);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
pub fn clear(&mut self) {
|
||||
self.render_stack.clear();
|
||||
self.transform.width = 0;
|
||||
self.transform.height = 0;
|
||||
self.transform.x = 0;
|
||||
self.transform.y = 0;
|
||||
}
|
||||
|
||||
pub fn get_size(&self) -> (u16, u16) {
|
||||
(self.transform.width, self.transform.height)
|
||||
}
|
||||
|
||||
pub fn get_size_or(&self, width: u16, height: u16) -> (u16, u16) {
|
||||
(
|
||||
if self.transform.width == 0 {
|
||||
width
|
||||
} else {
|
||||
self.transform.width
|
||||
},
|
||||
if self.transform.height == 0 {
|
||||
height
|
||||
} else {
|
||||
self.transform.height
|
||||
},
|
||||
)
|
||||
}
|
||||
|
||||
pub fn get_size_or_parent(&self) -> (u16, u16) {
|
||||
(
|
||||
if self.transform.width == 0 {
|
||||
self.parent_width
|
||||
} else {
|
||||
self.transform.width
|
||||
},
|
||||
if self.transform.height == 0 {
|
||||
self.parent_height
|
||||
} else {
|
||||
self.transform.height
|
||||
},
|
||||
)
|
||||
}
|
||||
|
||||
pub fn get_parent_size(&self) -> (u16, u16) {
|
||||
(self.parent_width, self.parent_height)
|
||||
}
|
||||
|
||||
pub fn set_parent_size(&mut self, width: u16, height: u16) {
|
||||
self.parent_width = width;
|
||||
self.parent_height = height;
|
||||
}
|
||||
|
||||
pub fn get_transform_mut(&mut self) -> &mut RawTransform {
|
||||
&mut self.transform
|
||||
}
|
||||
|
||||
pub fn get_transform(&self) -> &RawTransform {
|
||||
&self.transform
|
||||
}
|
||||
}
|
||||
|
||||
impl Debug for RenderScope {
|
||||
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
|
||||
write!(f, "RenderScope")
|
||||
}
|
||||
}
|
||||
-153
@@ -1,153 +0,0 @@
|
||||
#[macro_export]
|
||||
macro_rules! check_expr {
|
||||
(|| $code:block) => {
|
||||
$crate::Handler::new(move |_, _, _| $code)
|
||||
};
|
||||
(|$($inner:tt)*| $code:block) => {
|
||||
$crate::Handler::new(move |$($inner)*| $code)
|
||||
};
|
||||
($expr:expr) => {
|
||||
$expr
|
||||
};
|
||||
}
|
||||
#[macro_export]
|
||||
macro_rules! parse_rsx_param {
|
||||
//// FUNCTIONS
|
||||
|
||||
($elem:expr, $($k:ident).+: fn($($params:tt)*) $(@$($v:ident),+)? $body:expr $(, $($rest:tt)*)?) => {
|
||||
$elem.$($k).+ = $crate::Handler::new({
|
||||
$($(
|
||||
#[allow(unused_mut)]
|
||||
let mut $v = $v.clone();
|
||||
)+)?
|
||||
move |$($params)*| {
|
||||
$body
|
||||
}
|
||||
});
|
||||
osui::parse_rsx_param!($elem, $($($rest)*)?);
|
||||
};
|
||||
|
||||
($elem:expr, $($k:ident).+: |$($args:tt $(: $aty:ty)?),*| $(@$($v:ident),+)? $body:expr $(, $($rest:tt)*)?) => {
|
||||
$elem.$($k).+ = $crate::Handler::new({
|
||||
$($(
|
||||
#[allow(unused_mut)]
|
||||
let mut $v = $v.clone();
|
||||
)+)?
|
||||
move |$($args $(: $aty)?),*| $body
|
||||
});
|
||||
osui::parse_rsx_param!($elem, $($($rest)*)?);
|
||||
};
|
||||
|
||||
//// FUNCTIONS END
|
||||
|
||||
|
||||
($elem:expr, async $code:block $($rest:tt)*) => {
|
||||
let elem_len = $elem.children.len();
|
||||
$elem.instructions.push($crate::Instruction::Load(Handler::new(
|
||||
move |d: &mut Div, _, _| {
|
||||
d.children.insert(elem_len, $code);
|
||||
}
|
||||
)));
|
||||
osui::parse_rsx_param!($elem, $($rest)*);
|
||||
};
|
||||
|
||||
($elem:expr, %$elem_path:path { $($inner:tt)* } $($rest:tt)*) => {
|
||||
$elem.ghosts.push($elem.ghosts.len());
|
||||
if let $crate::Children::Children(children, _) = &mut $elem.children {
|
||||
children.push($crate::ersx!($elem_path { $($inner)* }));
|
||||
} else {
|
||||
$elem.children = $crate::Children::Children(vec![$crate::ersx!($elem_path { $($inner)* })], 0)
|
||||
}
|
||||
osui::parse_rsx_param!($elem, $($rest)*)
|
||||
};
|
||||
|
||||
($elem:expr, @ $($i:ident)::+($($inner:tt)*) $($rest:tt)*) => {
|
||||
$elem.instructions.push($($i)::+($($inner)*));
|
||||
osui::parse_rsx_param!($elem, $($rest)*);
|
||||
};
|
||||
($elem:expr, @ $($i:ident)::+ $($rest:tt)*) => {
|
||||
$elem.instructions.push($($i)::+);
|
||||
osui::parse_rsx_param!($elem, $($rest)*);
|
||||
};
|
||||
|
||||
($elem:expr, static $text:literal $($other:tt)*) => {
|
||||
$elem.children = $crate::Children::StaticText(format!($text $($other)*));
|
||||
};
|
||||
|
||||
($elem:expr, for ($($for:tt)*) $code:block $($rest:tt)*) => {
|
||||
if $elem.children.is_none() {$elem.children = $crate::Children::Children(Vec::new(), 0)}
|
||||
if let $crate::Children::Children(children, _) = &mut $elem.children {
|
||||
for $($for)* {
|
||||
children.push($code)
|
||||
}
|
||||
}
|
||||
osui::parse_rsx_param!($elem, $($rest)*);
|
||||
};
|
||||
|
||||
($elem:expr, $($k:ident).+: $v:expr $(, $($rest:tt)*)?) => {
|
||||
$elem.$($k).+ = $crate::check_expr!($v);
|
||||
osui::parse_rsx_param!($elem, $($($rest)*)?);
|
||||
};
|
||||
|
||||
($elem:expr, $p:path) => {
|
||||
$p;
|
||||
};
|
||||
|
||||
($elem:expr, $($k:ident).+, $($rest:tt)*) => {
|
||||
$elem.$($k).+ = !$elem.$($k).+;
|
||||
osui::parse_rsx_param!($elem, $($rest)*);
|
||||
};
|
||||
|
||||
($elem:expr, $code:block $($rest:tt)*) => {
|
||||
if $elem.children.is_none() {$elem.children = $crate::Children::Children(Vec::new(), 0)}
|
||||
if let $crate::Children::Children(children, _) = &mut $elem.children {
|
||||
children.push($code);
|
||||
}
|
||||
osui::parse_rsx_param!($elem, $($rest)*);
|
||||
};
|
||||
|
||||
($elem:expr, $elem_path:path { $($inner:tt)* } $($rest:tt)*) => {
|
||||
if let $crate::Children::Children(children, _) = &mut $elem.children {
|
||||
children.push($crate::ersx!($elem_path { $($inner)* }));
|
||||
} else {
|
||||
$elem.children = $crate::Children::Children(vec![$crate::ersx!($elem_path { $($inner)* })], 0)
|
||||
}
|
||||
osui::parse_rsx_param!($elem, $($rest)*)
|
||||
};
|
||||
|
||||
($elem:expr, $text:literal $($other:tt)*) => {
|
||||
$elem.children = $crate::Children::Text(
|
||||
std::sync::Arc::new(move || format!($text $($other)*))
|
||||
);
|
||||
};
|
||||
|
||||
($elem:expr,) => {};
|
||||
}
|
||||
|
||||
#[macro_export]
|
||||
macro_rules! ersx {
|
||||
($elem:path { $($inner:tt)* }) => {{
|
||||
let mut elem = <$elem>::default();
|
||||
$crate::parse_rsx_param!(elem, $($inner)*);
|
||||
elem.create_element()
|
||||
}};
|
||||
}
|
||||
|
||||
/// Makes a div and puts elements into it
|
||||
///
|
||||
/// # Example
|
||||
/// ```
|
||||
/// rsx! {
|
||||
/// button { class: "btn", "Click me!" }
|
||||
/// }
|
||||
/// ```
|
||||
///
|
||||
/// # Returns
|
||||
/// A `osui::Element` - Which is a `Box<dyn osui::ElementWidget>`
|
||||
#[macro_export]
|
||||
macro_rules! rsx {
|
||||
($($inner:tt)*) => {
|
||||
$crate::ersx!{ $crate::ui::div { $($inner)* } }
|
||||
};
|
||||
|
||||
}
|
||||
@@ -0,0 +1,97 @@
|
||||
use std::{
|
||||
fmt::{Debug, Display, Formatter, Result as FmtResult},
|
||||
ops::{Deref, DerefMut},
|
||||
sync::{Arc, Mutex, MutexGuard},
|
||||
};
|
||||
|
||||
#[derive(Debug, Clone)]
|
||||
pub struct State<T> {
|
||||
inner: Arc<Mutex<Inner<T>>>,
|
||||
}
|
||||
|
||||
#[derive(Debug)]
|
||||
pub struct Inner<T> {
|
||||
value: T,
|
||||
dependencies: usize,
|
||||
changed: usize,
|
||||
}
|
||||
|
||||
pub fn use_state<T>(v: T) -> State<T> {
|
||||
State {
|
||||
inner: Arc::new(Mutex::new(Inner {
|
||||
value: v,
|
||||
dependencies: 0,
|
||||
changed: 0,
|
||||
})),
|
||||
}
|
||||
}
|
||||
|
||||
impl<T: Clone> State<T> {
|
||||
/// Gets the cloned value, recommended for preventing deadlocks
|
||||
pub fn get_dl(&self) -> T {
|
||||
self.inner.lock().unwrap().value.clone()
|
||||
}
|
||||
}
|
||||
|
||||
impl<T> State<T> {
|
||||
/// Gets a lock on the state for read/write access.
|
||||
pub fn get(&self) -> MutexGuard<'_, Inner<T>> {
|
||||
self.inner.lock().unwrap()
|
||||
}
|
||||
|
||||
/// Sets the value and marks it as changed.
|
||||
pub fn set(&self, v: T) {
|
||||
let mut inner = self.inner.lock().unwrap();
|
||||
inner.value = v;
|
||||
inner.changed = inner.dependencies;
|
||||
}
|
||||
|
||||
/// Marks the state as updated.
|
||||
pub fn update(&self) {
|
||||
let mut inner = self.inner.lock().unwrap();
|
||||
inner.changed = inner.dependencies;
|
||||
}
|
||||
}
|
||||
|
||||
impl<T: Debug + Send + Sync> DependencyHandler for State<T> {
|
||||
fn check(&self) -> bool {
|
||||
let mut inner = self.inner.lock().unwrap();
|
||||
let i = inner.changed > 0;
|
||||
if i {
|
||||
inner.changed -= 1;
|
||||
}
|
||||
i
|
||||
}
|
||||
|
||||
fn add(&self) {
|
||||
let mut inner = self.inner.lock().unwrap();
|
||||
inner.dependencies += 1;
|
||||
}
|
||||
}
|
||||
|
||||
impl<T: Display> Display for State<T> {
|
||||
fn fmt(&self, f: &mut Formatter<'_>) -> FmtResult {
|
||||
let inner = self.inner.lock().unwrap();
|
||||
write!(f, "{}", inner.value)
|
||||
}
|
||||
}
|
||||
|
||||
impl<T> Deref for Inner<T> {
|
||||
type Target = T;
|
||||
|
||||
fn deref(&self) -> &Self::Target {
|
||||
&self.value
|
||||
}
|
||||
}
|
||||
|
||||
impl<T> DerefMut for Inner<T> {
|
||||
fn deref_mut(&mut self) -> &mut Self::Target {
|
||||
self.changed = self.dependencies;
|
||||
&mut self.value
|
||||
}
|
||||
}
|
||||
|
||||
pub trait DependencyHandler: std::fmt::Debug + Send + Sync {
|
||||
fn add(&self);
|
||||
fn check(&self) -> bool;
|
||||
}
|
||||
+153
@@ -0,0 +1,153 @@
|
||||
use crate::component;
|
||||
|
||||
#[derive(Debug, Clone)]
|
||||
pub struct RawTransform {
|
||||
pub x: u16,
|
||||
pub y: u16,
|
||||
pub width: u16,
|
||||
pub height: u16,
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone)]
|
||||
pub enum Position {
|
||||
Const(u16),
|
||||
Center,
|
||||
End,
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone)]
|
||||
pub enum Dimension {
|
||||
Full,
|
||||
Content,
|
||||
Const(u16),
|
||||
}
|
||||
|
||||
component!(Transform {
|
||||
pub x: Position,
|
||||
pub y: Position,
|
||||
pub mx: i32,
|
||||
pub my: i32,
|
||||
pub width: Dimension,
|
||||
pub height: Dimension,
|
||||
});
|
||||
|
||||
impl Transform {
|
||||
pub fn new() -> Transform {
|
||||
Transform {
|
||||
x: Position::Const(0),
|
||||
y: Position::Const(0),
|
||||
mx: 0,
|
||||
my: 0,
|
||||
width: Dimension::Content,
|
||||
height: Dimension::Content,
|
||||
}
|
||||
}
|
||||
|
||||
pub fn center() -> Transform {
|
||||
Transform {
|
||||
x: Position::Center,
|
||||
y: Position::Center,
|
||||
mx: 0,
|
||||
my: 0,
|
||||
width: Dimension::Content,
|
||||
height: Dimension::Content,
|
||||
}
|
||||
}
|
||||
|
||||
pub fn bottom(mut self) -> Self {
|
||||
self.y = Position::End;
|
||||
self
|
||||
}
|
||||
|
||||
pub fn right(mut self) -> Self {
|
||||
self.x = Position::End;
|
||||
self
|
||||
}
|
||||
|
||||
pub fn margin(mut self, x: i32, y: i32) -> Self {
|
||||
self.mx = x;
|
||||
self.my = y;
|
||||
self
|
||||
}
|
||||
|
||||
pub fn dimensions(mut self, width: u16, height: u16) -> Self {
|
||||
self.width = Dimension::Const(width);
|
||||
self.height = Dimension::Const(height);
|
||||
self
|
||||
}
|
||||
|
||||
pub fn use_dimensions(&self, parent_width: u16, parent_height: u16, raw: &mut RawTransform) {
|
||||
self.width.use_dimension(parent_width, &mut raw.width);
|
||||
self.height.use_dimension(parent_height, &mut raw.height);
|
||||
}
|
||||
|
||||
pub fn use_position(&self, parent_width: u16, parent_height: u16, raw: &mut RawTransform) {
|
||||
self.x
|
||||
.use_position(raw.width, parent_width, self.mx, &mut raw.x);
|
||||
self.y
|
||||
.use_position(raw.height, parent_height, self.my, &mut raw.y);
|
||||
}
|
||||
}
|
||||
|
||||
impl RawTransform {
|
||||
pub fn new() -> RawTransform {
|
||||
RawTransform {
|
||||
x: 0,
|
||||
y: 0,
|
||||
width: 0,
|
||||
height: 0,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl Dimension {
|
||||
pub fn use_dimension(&self, parent: u16, r: &mut u16) {
|
||||
match self {
|
||||
Self::Full => *r = parent,
|
||||
Self::Content => {}
|
||||
Self::Const(n) => *r = *n,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl Position {
|
||||
pub fn use_position(&self, size: u16, parent: u16, m: i32, r: &mut u16) {
|
||||
let base = match self {
|
||||
Self::Center => {
|
||||
if parent < size {
|
||||
return;
|
||||
}
|
||||
(parent - size) / 2
|
||||
}
|
||||
Self::Const(n) => *n,
|
||||
Self::End => {
|
||||
if parent < size {
|
||||
return;
|
||||
}
|
||||
parent - size
|
||||
}
|
||||
};
|
||||
|
||||
let adjusted = if m >= 0 {
|
||||
base.checked_add(m as u16)
|
||||
} else {
|
||||
base.checked_sub((-m) as u16)
|
||||
};
|
||||
|
||||
if let Some(val) = adjusted {
|
||||
*r = val;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl From<u16> for Position {
|
||||
fn from(value: u16) -> Self {
|
||||
Self::Const(value)
|
||||
}
|
||||
}
|
||||
|
||||
impl From<u16> for Dimension {
|
||||
fn from(value: u16) -> Self {
|
||||
Self::Const(value)
|
||||
}
|
||||
}
|
||||
-267
@@ -1,267 +0,0 @@
|
||||
/// The `ui` module defines the basic building blocks for creating a terminal-based UI framework.
|
||||
///
|
||||
/// # Modules
|
||||
/// - `styles`: A module for defining UI styles.
|
||||
pub mod styles;
|
||||
|
||||
pub use styles::*;
|
||||
|
||||
use crate::prelude::*;
|
||||
use osui_element::element;
|
||||
|
||||
#[element]
|
||||
#[derive(Default, Debug)]
|
||||
pub struct Text {}
|
||||
|
||||
impl ElementWidget for Text<'_> {
|
||||
fn render(&self, writer: &mut crate::Writer) {
|
||||
writer.write(&self.children.get_text());
|
||||
}
|
||||
}
|
||||
|
||||
#[component]
|
||||
pub fn text<'a>(class: &'a str, id: &'a str, children: Children, style: Style) -> Box<Text<'a>> {
|
||||
Box::new(Text {
|
||||
class: self.class,
|
||||
id: self.id,
|
||||
children: self.children,
|
||||
style: self.style,
|
||||
})
|
||||
}
|
||||
|
||||
#[element]
|
||||
#[derive(Default, Debug)]
|
||||
pub struct Div {
|
||||
pub instructions: Vec<crate::Instruction<'a>>,
|
||||
pub ghosts: Vec<usize>,
|
||||
}
|
||||
|
||||
impl ElementWidget for Div<'_> {
|
||||
fn render(&self, writer: &mut crate::Writer) {
|
||||
let focused = writer.get_focused();
|
||||
let mut frame = writer.new_frame();
|
||||
|
||||
if let Children::Children(children, child) = &self.children {
|
||||
for (i, elem) in children.iter().enumerate() {
|
||||
frame.render(focused && i == *child, elem);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn event(&mut self, event: Event, document: &mut Document) {
|
||||
if let (Some((child, i)), l) = self.children.get_child_idx() {
|
||||
match event {
|
||||
Event::Key(k) => match k.code {
|
||||
KeyCode::Tab => {
|
||||
child.event(Event::FocusLost, document);
|
||||
if *i < l - 1 {
|
||||
*i += 1;
|
||||
} else {
|
||||
*i = 0;
|
||||
}
|
||||
while self.ghosts.get(*i).is_some() {
|
||||
if *i < l - 1 {
|
||||
*i += 1;
|
||||
} else {
|
||||
*i = 0;
|
||||
}
|
||||
}
|
||||
child.event(Event::FocusGained, document);
|
||||
}
|
||||
KeyCode::BackTab => {
|
||||
child.event(Event::FocusLost, document);
|
||||
if *i > 0 {
|
||||
*i -= 1;
|
||||
} else {
|
||||
*i = l - 1;
|
||||
}
|
||||
while self.ghosts.get(*i).is_some() {
|
||||
if *i > 0 {
|
||||
*i -= 1;
|
||||
} else {
|
||||
*i = l - 1;
|
||||
}
|
||||
}
|
||||
child.event(Event::FocusGained, document);
|
||||
}
|
||||
_ => child.event(event, document),
|
||||
},
|
||||
_ => child.event(event, document),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn initialize(&mut self, document: &mut Document) {
|
||||
let l = self.children.len();
|
||||
if let Some(i) = self.children.index_mut() {
|
||||
while self.ghosts.get(*i).is_some() {
|
||||
if *i < l - 1 {
|
||||
*i += 1;
|
||||
} else {
|
||||
*i = 0;
|
||||
break;
|
||||
}
|
||||
}
|
||||
}
|
||||
let mut load_funcs = Vec::new();
|
||||
for inst in &self.instructions {
|
||||
match inst {
|
||||
crate::Instruction::SetStyle(s) => {
|
||||
document.css.extend(s.clone().into_iter());
|
||||
}
|
||||
crate::Instruction::SetChild(c) => {
|
||||
self.children.set_index(*c);
|
||||
}
|
||||
crate::Instruction::Ghost(idx) => {
|
||||
self.ghosts.push(*idx);
|
||||
}
|
||||
crate::Instruction::Load(f) => {
|
||||
load_funcs.push(f.clone());
|
||||
}
|
||||
}
|
||||
}
|
||||
self.instructions.clear();
|
||||
for i in load_funcs {
|
||||
i.call(self, Event::FocusGained, document)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[component]
|
||||
pub fn div<'a>(
|
||||
class: &'a str,
|
||||
id: &'a str,
|
||||
children: Children,
|
||||
style: Style,
|
||||
instructions: Vec<crate::Instruction<'a>>,
|
||||
ghosts: Vec<usize>,
|
||||
) -> Box<Div<'a>> {
|
||||
Box::new(Div {
|
||||
children: self.children,
|
||||
class: self.class,
|
||||
id: self.id,
|
||||
style: self.style,
|
||||
instructions: self.instructions,
|
||||
ghosts: self.ghosts,
|
||||
})
|
||||
}
|
||||
|
||||
#[element]
|
||||
#[derive(Default, Debug)]
|
||||
pub struct Button {
|
||||
pub on_click: Handler<Button<'a>>,
|
||||
pub on_hover: Handler<Button<'a>>,
|
||||
}
|
||||
|
||||
impl ElementWidget for Button<'_> {
|
||||
fn render(&self, writer: &mut crate::Writer) {
|
||||
writer.write(&self.children.get_text());
|
||||
}
|
||||
|
||||
fn event(&mut self, event: Event, document: &mut Document) {
|
||||
match event {
|
||||
Event::Key(key) => {
|
||||
if key.code == KeyCode::Enter {
|
||||
document.render();
|
||||
self.style.set_state("clicked");
|
||||
self.on_click.clone().call(self, event, document);
|
||||
document.render();
|
||||
sleep(65);
|
||||
self.style.set_state("");
|
||||
}
|
||||
}
|
||||
Event::FocusGained => {
|
||||
self.on_hover.clone().call(self, event, document);
|
||||
}
|
||||
_ => {}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[component]
|
||||
pub fn button<'a>(
|
||||
class: &'a str,
|
||||
id: &'a str,
|
||||
children: Children,
|
||||
style: Style,
|
||||
on_click: Handler<Button<'a>>,
|
||||
on_hover: Handler<Button<'a>>,
|
||||
) -> Box<Button<'a>> {
|
||||
Box::new(Button {
|
||||
class: self.class,
|
||||
id: self.id,
|
||||
children: self.children,
|
||||
on_click: self.on_click.clone(),
|
||||
on_hover: self.on_hover.clone(),
|
||||
style: self.style,
|
||||
})
|
||||
}
|
||||
|
||||
#[element]
|
||||
#[derive(Default, Debug)]
|
||||
pub struct Input {
|
||||
pub on_click: Handler<Input<'a>>,
|
||||
pub text: String,
|
||||
pub placeholder: &'a str,
|
||||
}
|
||||
|
||||
impl ElementWidget for Input<'_> {
|
||||
fn render(&self, writer: &mut crate::Writer) {
|
||||
if self.text.is_empty() {
|
||||
writer.write(&format!(
|
||||
"{}{}{}",
|
||||
self.children.get_text(),
|
||||
self.placeholder,
|
||||
writer.caret()
|
||||
));
|
||||
} else {
|
||||
writer.write(&format!(
|
||||
"{}{}{}",
|
||||
self.children.get_text(),
|
||||
self.text,
|
||||
writer.caret()
|
||||
));
|
||||
}
|
||||
}
|
||||
|
||||
fn event(&mut self, event: crossterm::event::Event, document: &mut Document) {
|
||||
match event {
|
||||
Event::Key(k) => match k.code {
|
||||
KeyCode::Backspace => {
|
||||
if self.text.len() > 0 {
|
||||
self.text.pop();
|
||||
}
|
||||
}
|
||||
KeyCode::Enter => {
|
||||
self.on_click.clone().call(self, event, document);
|
||||
}
|
||||
KeyCode::Char(c) => {
|
||||
self.text.push(c);
|
||||
}
|
||||
_ => {}
|
||||
},
|
||||
_ => {}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[component]
|
||||
pub fn input<'a>(
|
||||
class: &'a str,
|
||||
id: &'a str,
|
||||
placeholder: &'a str,
|
||||
text: String,
|
||||
children: Children,
|
||||
style: Style,
|
||||
on_click: Handler<Input<'a>>,
|
||||
) -> Box<Input<'a>> {
|
||||
Box::new(Input {
|
||||
class: self.class,
|
||||
id: self.id,
|
||||
children: self.children,
|
||||
style: self.style,
|
||||
on_click: self.on_click,
|
||||
placeholder: self.placeholder,
|
||||
text: self.text,
|
||||
})
|
||||
}
|
||||
@@ -1,347 +0,0 @@
|
||||
//! The `styles` module defines various styling options for UI elements. This includes colors,
|
||||
//! fonts, padding, margins, and other visual properties that can be applied to UI components
|
||||
//! to change their appearance.
|
||||
|
||||
use std::{collections::HashMap, fmt::Debug};
|
||||
|
||||
use dyn_clone::{clone_trait_object, DynClone};
|
||||
|
||||
//////////////////////////////////////////////////////////////////////////////////////////////////
|
||||
// Type aliases
|
||||
//////////////////////////////////////////////////////////////////////////////////////////////////
|
||||
|
||||
pub type Css = HashMap<StyleName, StyleElement>;
|
||||
|
||||
//////////////////////////////////////////////////////////////////////////////////////////////////
|
||||
// Traits
|
||||
//////////////////////////////////////////////////////////////////////////////////////////////////
|
||||
|
||||
pub trait StyleCore: Debug + Send + Sync + DynClone {
|
||||
fn ansi(&self) -> String;
|
||||
fn ansi_bg(&self) -> String;
|
||||
}
|
||||
clone_trait_object!(StyleCore);
|
||||
|
||||
//////////////////////////////////////////////////////////////////////////////////////////////////
|
||||
// Enums
|
||||
//////////////////////////////////////////////////////////////////////////////////////////////////
|
||||
|
||||
#[derive(Debug, Clone, PartialEq, Eq, Hash)]
|
||||
pub enum Font {
|
||||
Bold,
|
||||
Underline,
|
||||
Italic,
|
||||
Reverse,
|
||||
Strike,
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, PartialEq, Eq, Hash)]
|
||||
pub enum Color {
|
||||
NoColor,
|
||||
Rgb(u8, u8, u8),
|
||||
Hex(String),
|
||||
Black,
|
||||
Red,
|
||||
Green,
|
||||
Yellow,
|
||||
Blue,
|
||||
Magenta,
|
||||
Cyan,
|
||||
White,
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, PartialEq, Eq, Hash)]
|
||||
pub enum Number {
|
||||
Px(u16),
|
||||
Pe(u16),
|
||||
Center,
|
||||
Auto,
|
||||
}
|
||||
|
||||
#[derive(PartialEq, Eq, Hash, Debug, Clone)]
|
||||
pub enum StyleName {
|
||||
Class(String),
|
||||
ClassState(String, String),
|
||||
}
|
||||
|
||||
//////////////////////////////////////////////////////////////////////////////////////////////////
|
||||
// Structs
|
||||
//////////////////////////////////////////////////////////////////////////////////////////////////
|
||||
|
||||
#[derive(Debug, Clone)]
|
||||
pub struct StyleElement {
|
||||
pub color: (bool, Color),
|
||||
pub background: (bool, Color),
|
||||
pub outline_color: (bool, Color),
|
||||
pub font: (bool, Vec<Font>),
|
||||
pub x: (bool, Number),
|
||||
pub y: (bool, Number),
|
||||
pub width: (bool, Number),
|
||||
pub height: (bool, Number),
|
||||
pub visible: (bool, bool),
|
||||
pub outline: (bool, bool),
|
||||
pub cursor: (bool, Color),
|
||||
pub caret: (bool, String),
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone)]
|
||||
pub struct Style(
|
||||
pub StyleElement,
|
||||
pub HashMap<String, StyleElement>,
|
||||
pub String,
|
||||
);
|
||||
|
||||
//////////////////////////////////////////////////////////////////////////////////////////////////
|
||||
// Implementations
|
||||
//////////////////////////////////////////////////////////////////////////////////////////////////
|
||||
|
||||
impl Default for Style {
|
||||
fn default() -> Self {
|
||||
Style(StyleElement::default(), HashMap::new(), String::new())
|
||||
}
|
||||
}
|
||||
|
||||
impl Style {
|
||||
pub fn get(mut self, hover: bool) -> StyleElement {
|
||||
if let Some(style_element) = self.1.get(&self.2) {
|
||||
self.0.merge(style_element);
|
||||
self.0
|
||||
} else if hover {
|
||||
if let Some(style_element) = self.1.get("hover") {
|
||||
self.0.merge(style_element);
|
||||
self.0
|
||||
} else {
|
||||
self.0
|
||||
}
|
||||
} else {
|
||||
self.0
|
||||
}
|
||||
}
|
||||
|
||||
pub fn set_state(&mut self, state: &str) {
|
||||
self.2 = state.to_string();
|
||||
}
|
||||
}
|
||||
|
||||
impl StyleElement {
|
||||
pub fn write(&self, s: &str) -> String {
|
||||
s.split('\n')
|
||||
.into_iter()
|
||||
.map(|p| {
|
||||
format!(
|
||||
"{}{}{}{p}\x1b[0m",
|
||||
self.color.1.ansi(),
|
||||
self.background.1.ansi_bg(),
|
||||
self.font.1.ansi()
|
||||
)
|
||||
})
|
||||
.collect::<Vec<String>>()
|
||||
.join("\n")
|
||||
}
|
||||
pub fn write_outline(&self, outline: &str) -> String {
|
||||
format!("{}{outline}\x1b[0m", self.outline_color.1.ansi(),)
|
||||
}
|
||||
}
|
||||
|
||||
impl Default for StyleElement {
|
||||
fn default() -> Self {
|
||||
StyleElement {
|
||||
color: (false, Color::NoColor),
|
||||
background: (false, Color::NoColor),
|
||||
cursor: (false, Color::NoColor),
|
||||
font: (false, Vec::new()),
|
||||
outline_color: (false, Color::NoColor),
|
||||
x: (false, Number::Px(0)),
|
||||
y: (false, Number::Auto),
|
||||
width: (false, Number::Auto),
|
||||
height: (false, Number::Auto),
|
||||
visible: (false, true),
|
||||
outline: (false, false),
|
||||
caret: (false, String::from("█")),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl StyleElement {
|
||||
pub fn merge(&mut self, upper: &Self) {
|
||||
if upper.color.0 {
|
||||
self.color = upper.color.clone();
|
||||
}
|
||||
if upper.background.0 {
|
||||
self.background = upper.background.clone();
|
||||
}
|
||||
if upper.font.0 {
|
||||
self.font = upper.font.clone();
|
||||
}
|
||||
if upper.outline_color.0 {
|
||||
self.outline_color = upper.outline_color.clone();
|
||||
}
|
||||
if upper.x.0 {
|
||||
self.x = upper.x.clone();
|
||||
}
|
||||
if upper.y.0 {
|
||||
self.y = upper.y.clone();
|
||||
}
|
||||
if upper.width.0 {
|
||||
self.width = upper.width.clone();
|
||||
}
|
||||
if upper.height.0 {
|
||||
self.height = upper.height.clone();
|
||||
}
|
||||
if upper.visible.0 {
|
||||
self.visible = upper.visible.clone();
|
||||
}
|
||||
if upper.outline.0 {
|
||||
self.outline = upper.outline.clone();
|
||||
}
|
||||
if upper.cursor.0 {
|
||||
self.cursor = upper.cursor.clone();
|
||||
}
|
||||
if upper.caret.0 {
|
||||
self.caret = upper.caret.clone();
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl StyleCore for Color {
|
||||
fn ansi(&self) -> String {
|
||||
String::from(match self {
|
||||
Color::NoColor => "",
|
||||
Color::Rgb(r, g, b) => {
|
||||
return format!("\x1b[38;2;{r};{g};{b}m");
|
||||
}
|
||||
Color::Hex(hex) => {
|
||||
let (r, g, b) = hex_to_rgb(hex);
|
||||
return format!("\x1b[38;2;{r};{g};{b}m");
|
||||
}
|
||||
Color::Black => "\x1b[30m",
|
||||
Color::Red => "\x1b[31m",
|
||||
Color::Green => "\x1b[32m",
|
||||
Color::Yellow => "\x1b[33m",
|
||||
Color::Blue => "\x1b[34m",
|
||||
Color::Magenta => "\x1b[35m",
|
||||
Color::Cyan => "\x1b[36m",
|
||||
Color::White => "\x1b[37m",
|
||||
})
|
||||
}
|
||||
|
||||
fn ansi_bg(&self) -> String {
|
||||
String::from(match self {
|
||||
Color::NoColor => "",
|
||||
Color::Rgb(r, g, b) => {
|
||||
return format!("\x1b[48;2;{r};{g};{b}m");
|
||||
}
|
||||
Color::Hex(hex) => {
|
||||
let (r, g, b) = hex_to_rgb(hex);
|
||||
return format!("\x1b[48;2;{r};{g};{b}m");
|
||||
}
|
||||
Color::Black => "\x1b[40m",
|
||||
Color::Red => "\x1b[41m",
|
||||
Color::Green => "\x1b[42m",
|
||||
Color::Yellow => "\x1b[43m",
|
||||
Color::Blue => "\x1b[44m",
|
||||
Color::Magenta => "\x1b[45m",
|
||||
Color::Cyan => "\x1b[46m",
|
||||
Color::White => "\x1b[47m",
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
impl Default for Color {
|
||||
fn default() -> Self {
|
||||
Color::NoColor
|
||||
}
|
||||
}
|
||||
|
||||
fn hex_to_rgb(hex: &str) -> (u8, u8, u8) {
|
||||
let hex = hex.trim_start_matches('#');
|
||||
|
||||
let hex = if hex.len() == 3 {
|
||||
format!(
|
||||
"{}{}{}{}{}{}",
|
||||
&hex[0..1],
|
||||
&hex[0..1],
|
||||
&hex[1..2],
|
||||
&hex[1..2],
|
||||
&hex[2..3],
|
||||
&hex[2..3]
|
||||
)
|
||||
} else if hex.len() == 6 {
|
||||
hex.to_string()
|
||||
} else {
|
||||
return (255, 255, 255);
|
||||
};
|
||||
|
||||
let r = u8::from_str_radix(&hex[0..2], 16).unwrap_or(255);
|
||||
let g = u8::from_str_radix(&hex[2..4], 16).unwrap_or(255);
|
||||
let b = u8::from_str_radix(&hex[4..6], 16).unwrap_or(255);
|
||||
|
||||
(r, g, b)
|
||||
}
|
||||
|
||||
impl StyleCore for Font {
|
||||
fn ansi(&self) -> String {
|
||||
String::from(match self {
|
||||
Font::Bold => "\x1b[1m",
|
||||
Font::Underline => "\x1b[4m",
|
||||
Font::Italic => "\x1b[3m",
|
||||
Font::Reverse => "\x1b[7m",
|
||||
Font::Strike => "\x1b[9m",
|
||||
})
|
||||
}
|
||||
fn ansi_bg(&self) -> String {
|
||||
self.ansi()
|
||||
}
|
||||
}
|
||||
|
||||
impl StyleCore for Vec<Font> {
|
||||
fn ansi(&self) -> String {
|
||||
let mut a = String::new();
|
||||
for i in self {
|
||||
a += i.ansi().as_str();
|
||||
}
|
||||
a
|
||||
}
|
||||
|
||||
fn ansi_bg(&self) -> String {
|
||||
let mut a = String::new();
|
||||
for i in self {
|
||||
a += i.ansi_bg().as_str();
|
||||
}
|
||||
a
|
||||
}
|
||||
}
|
||||
|
||||
impl Number {
|
||||
pub fn as_size_raw(&self, frame_size: u16) -> u16 {
|
||||
match self {
|
||||
Number::Px(s) => *s,
|
||||
Number::Pe(pe) => (frame_size * pe) / 100,
|
||||
_ => frame_size,
|
||||
}
|
||||
}
|
||||
pub fn as_size(&self, written: u16, frame_size: u16, outline: bool) -> u16 {
|
||||
if *self == Number::Auto {
|
||||
written
|
||||
} else if outline {
|
||||
self.as_size_raw(frame_size) - 2
|
||||
} else {
|
||||
self.as_size_raw(frame_size)
|
||||
}
|
||||
}
|
||||
pub fn as_position_raw(&self, used: &u16, frame_size: u16) -> u16 {
|
||||
match self {
|
||||
crate::ui::Number::Px(px) => *px,
|
||||
crate::ui::Number::Pe(pe) => (frame_size * pe) / 100,
|
||||
crate::ui::Number::Center => (frame_size) / 2,
|
||||
crate::ui::Number::Auto => *used,
|
||||
}
|
||||
}
|
||||
pub fn as_position(&self, outline: bool, used: &u16, frame_size: u16) -> u16 {
|
||||
if outline {
|
||||
self.as_position_raw(used, frame_size) + 1
|
||||
} else {
|
||||
self.as_position_raw(used, frame_size)
|
||||
}
|
||||
}
|
||||
}
|
||||
+102
-113
@@ -1,133 +1,122 @@
|
||||
use std::io::{stdout, Write};
|
||||
//! The `utils` module provides utility functions for terminal manipulation
|
||||
//! and string operations, designed to enhance terminal-based applications.
|
||||
|
||||
pub struct Frame<'a> {
|
||||
used: Vec<u16>,
|
||||
writer: &'a mut crate::Writer,
|
||||
}
|
||||
use std::io::{self, Write};
|
||||
|
||||
impl<'a> Frame<'a> {
|
||||
pub fn new(writer: &'a mut crate::Writer) -> Self {
|
||||
Frame {
|
||||
used: vec![0; writer.size.1 as usize],
|
||||
writer,
|
||||
}
|
||||
}
|
||||
pub fn render(&mut self, focused: bool, element: &crate::Element) {
|
||||
let style = element.get_style();
|
||||
let mut style_element = style.clone().get(focused);
|
||||
let css = unsafe { &*self.writer.css };
|
||||
|
||||
for class in element.get_class().split(" ") {
|
||||
if let Some(upper) = css.get(&crate::ui::StyleName::Class(class.to_string())) {
|
||||
style_element.merge(upper);
|
||||
}
|
||||
|
||||
if let Some(upper) = css.get(&crate::ui::StyleName::ClassState(
|
||||
class.to_string(),
|
||||
if style.2 == "" && focused {
|
||||
"hover".to_string()
|
||||
} else {
|
||||
style.2.clone()
|
||||
},
|
||||
)) {
|
||||
style_element.merge(upper);
|
||||
}
|
||||
}
|
||||
|
||||
if !style_element.visible.1 {
|
||||
return;
|
||||
}
|
||||
|
||||
let y = style_element.y.1.as_position(
|
||||
style_element.outline.1,
|
||||
&{
|
||||
let mut y = 0;
|
||||
while y < self.used.len() && self.used[y] != 0 {
|
||||
y += 1;
|
||||
}
|
||||
y as u16
|
||||
},
|
||||
self.writer.size.1,
|
||||
);
|
||||
|
||||
if let Some(y_) = self.used.get(y as usize) {
|
||||
let x = style_element
|
||||
.x
|
||||
.1
|
||||
.as_position(style_element.outline.1, y_, self.writer.size.0);
|
||||
|
||||
let mut writer = crate::Writer {
|
||||
focused,
|
||||
style: style_element.clone(),
|
||||
pos: (x, y),
|
||||
size: self.writer.size,
|
||||
css,
|
||||
parent: Some(self.writer),
|
||||
written: (0, 0),
|
||||
};
|
||||
element.render(&mut writer);
|
||||
let (width, height) = writer.get_size_root();
|
||||
{
|
||||
let (x, y, width, height) = if style_element.outline.1 {
|
||||
(x - 1, y - 1, width + 2, height + 2)
|
||||
} else {
|
||||
(x, y, width, height)
|
||||
};
|
||||
|
||||
for i in y..y + height {
|
||||
if let Some(o) = self.used.get_mut(i as usize) {
|
||||
if style_element.x.1 != crate::ui::Number::Auto {
|
||||
*o += x;
|
||||
}
|
||||
*o += width;
|
||||
}
|
||||
}
|
||||
}
|
||||
writer.after_render(width, height);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
pub fn clear() {
|
||||
/// Clears the terminal screen and moves the cursor to the top-left corner.
|
||||
///
|
||||
/// # Returns
|
||||
/// A `io::Result<()>` indicating whether the operation succeeded.
|
||||
///
|
||||
/// # Example
|
||||
/// ```
|
||||
/// utils::clear().unwrap();
|
||||
/// ```
|
||||
pub fn clear() -> io::Result<()> {
|
||||
print!("\x1B[2J\x1B[H");
|
||||
stdout().flush().unwrap();
|
||||
std::io::stdout().flush()
|
||||
}
|
||||
|
||||
pub fn hide_cursor() {
|
||||
/// Hides the terminal cursor.
|
||||
///
|
||||
/// # Returns
|
||||
/// A `io::Result<()>` indicating whether the operation succeeded.
|
||||
///
|
||||
/// # Example
|
||||
/// ```
|
||||
/// utils::hide_cursor().unwrap();
|
||||
/// ```
|
||||
pub fn hide_cursor() -> io::Result<()> {
|
||||
print!("\x1b[?25l");
|
||||
stdout().flush().unwrap();
|
||||
std::io::stdout().flush()
|
||||
}
|
||||
|
||||
pub fn show_cursor() {
|
||||
/// Shows the terminal cursor.
|
||||
///
|
||||
/// # Returns
|
||||
/// A `io::Result<()>` indicating whether the operation succeeded.
|
||||
///
|
||||
/// # Example
|
||||
/// ```
|
||||
/// utils::show_cursor().unwrap();
|
||||
/// ```
|
||||
pub fn show_cursor() -> io::Result<()> {
|
||||
print!("\x1B[?25h");
|
||||
stdout().flush().unwrap();
|
||||
std::io::stdout().flush()
|
||||
}
|
||||
|
||||
pub fn flush() {
|
||||
stdout().flush().unwrap();
|
||||
/// Flushes the terminal's stdout buffer.
|
||||
///
|
||||
/// # Returns
|
||||
/// A `io::Result<()>` indicating whether the operation succeeded.
|
||||
///
|
||||
/// # Example
|
||||
/// ```
|
||||
/// utils::flush().unwrap();
|
||||
/// ```
|
||||
pub fn flush() -> io::Result<()> {
|
||||
std::io::stdout().flush()
|
||||
}
|
||||
|
||||
pub trait VisibleLength {
|
||||
fn visible_len(&self) -> usize;
|
||||
}
|
||||
/// Calculates the width and height of a string when rendered in a terminal.
|
||||
///
|
||||
/// # Arguments
|
||||
/// - `s`: The input string.
|
||||
///
|
||||
/// # Returns
|
||||
/// A tuple `(u16, u16)` where:
|
||||
/// - The first value is the maximum width of the string in characters.
|
||||
/// - The second value is the height of the string in lines.
|
||||
///
|
||||
/// # Example
|
||||
/// ```
|
||||
/// let (width, height) = utils::str_size("Hello\nWorld!");
|
||||
/// assert_eq!((5, 2), (width, height));
|
||||
/// ```
|
||||
pub fn str_size(s: &str) -> (u16, u16) {
|
||||
let mut height = 1;
|
||||
let mut max_width = 0;
|
||||
let mut current_width = 0;
|
||||
|
||||
impl VisibleLength for String {
|
||||
fn visible_len(&self) -> usize {
|
||||
let mut length = 0;
|
||||
let mut in_escape = false;
|
||||
|
||||
for c in self.chars() {
|
||||
if c == '\x1b' {
|
||||
in_escape = true;
|
||||
} else if in_escape {
|
||||
if c.is_ascii_alphabetic() {
|
||||
in_escape = false;
|
||||
}
|
||||
for b in s.bytes() {
|
||||
if b == b'\n' {
|
||||
height += 1;
|
||||
max_width = max_width.max(current_width);
|
||||
current_width = 0;
|
||||
} else {
|
||||
length += 1;
|
||||
current_width += 1;
|
||||
}
|
||||
}
|
||||
|
||||
length
|
||||
max_width = max_width.max(current_width);
|
||||
|
||||
(max_width, height)
|
||||
}
|
||||
|
||||
pub fn hex_ansi(hex: u32) -> String {
|
||||
let r = ((hex >> 16) & 0xFF) as u8;
|
||||
let g = ((hex >> 8) & 0xFF) as u8;
|
||||
let b = (hex & 0xFF) as u8;
|
||||
format!("\x1b[38;2;{r};{g};{b}m")
|
||||
}
|
||||
|
||||
pub fn hex_ansi_bg(hex: u32) -> String {
|
||||
let r = ((hex >> 16) & 0xFF) as u8;
|
||||
let g = ((hex >> 8) & 0xFF) as u8;
|
||||
let b = (hex & 0xFF) as u8;
|
||||
format!("\x1b[48;2;{r};{g};{b}m")
|
||||
}
|
||||
|
||||
pub(crate) fn print(x: u16, y: u16, text: &str) {
|
||||
for (i, line) in text.lines().enumerate() {
|
||||
print!("\x1b[{};{}H{line}\x1b[0m", y + i as u16 + 1, x + 1);
|
||||
flush().unwrap();
|
||||
}
|
||||
}
|
||||
|
||||
pub(crate) fn print_liner(x: u16, y: u16, liner: &str, text: &str) {
|
||||
for (i, line) in text.lines().enumerate() {
|
||||
print!("\x1b[{};{}H{liner}{line}\x1b[0m", y + i as u16 + 1, x + 1);
|
||||
flush().unwrap();
|
||||
}
|
||||
}
|
||||
|
||||
+140
@@ -0,0 +1,140 @@
|
||||
use std::{
|
||||
any::{Any, TypeId},
|
||||
collections::HashMap,
|
||||
sync::{Arc, Mutex},
|
||||
};
|
||||
|
||||
use crate::{render_scope::RenderScope, state::DependencyHandler};
|
||||
|
||||
pub type BoxedElement = Box<dyn Element + Send + Sync>;
|
||||
pub type BoxedComponent = Box<dyn Component + Send + Sync>;
|
||||
|
||||
pub trait Element: Send + Sync {
|
||||
#[allow(unused)]
|
||||
fn render(&mut self, scope: &mut RenderScope) {}
|
||||
#[allow(unused)]
|
||||
fn after_render(&mut self, scope: &mut RenderScope) {}
|
||||
#[allow(unused)]
|
||||
fn draw_child(&self, element: &Arc<Widget>) {}
|
||||
fn as_any(&self) -> &dyn Any;
|
||||
fn as_any_mut(&mut self) -> &mut dyn Any;
|
||||
}
|
||||
|
||||
pub trait Component: Send + Sync {
|
||||
fn as_any(&self) -> &dyn Any;
|
||||
fn as_any_mut(&mut self) -> &mut dyn Any;
|
||||
}
|
||||
|
||||
pub struct Widget(
|
||||
pub Mutex<BoxedElement>,
|
||||
Mutex<HashMap<TypeId, BoxedComponent>>,
|
||||
Mutex<Box<dyn FnMut() -> WidgetLoad + Send + Sync>>,
|
||||
Mutex<Vec<Box<dyn DependencyHandler>>>,
|
||||
Mutex<Option<Box<dyn FnMut(WidgetLoad) -> WidgetLoad + Send + Sync>>>,
|
||||
);
|
||||
|
||||
impl Widget {
|
||||
pub fn new<F: FnMut() -> WidgetLoad + 'static + Send + Sync>(mut e: F) -> Self {
|
||||
let wl = e();
|
||||
Self(
|
||||
Mutex::new(wl.0),
|
||||
Mutex::new(wl.1),
|
||||
Mutex::new(Box::new(e)),
|
||||
Mutex::new(Vec::new()),
|
||||
Mutex::new(None),
|
||||
)
|
||||
}
|
||||
|
||||
pub fn inject<F: FnMut(WidgetLoad) -> WidgetLoad + 'static + Send + Sync>(
|
||||
self: &Arc<Self>,
|
||||
f: F,
|
||||
) {
|
||||
{
|
||||
*self.4.lock().unwrap() = Some(Box::new(f));
|
||||
}
|
||||
self.refresh();
|
||||
}
|
||||
|
||||
pub fn refresh(self: &Arc<Self>) {
|
||||
let w = (self.2.lock().unwrap())();
|
||||
match &mut *self.4.lock().unwrap() {
|
||||
Some(inject) => {
|
||||
let w = inject(w);
|
||||
*self.0.lock().unwrap() = w.0;
|
||||
*self.1.lock().unwrap() = w.1;
|
||||
}
|
||||
None => {
|
||||
*self.0.lock().unwrap() = w.0;
|
||||
*self.1.lock().unwrap() = w.1;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
pub fn auto_refresh(self: &Arc<Self>) {
|
||||
for d in self.3.lock().unwrap().iter() {
|
||||
if d.check() {
|
||||
self.refresh();
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
pub fn dependency<D: DependencyHandler + 'static>(self: &Arc<Self>, d: D) -> &Arc<Self> {
|
||||
d.add();
|
||||
self.3.lock().unwrap().push(Box::new(d));
|
||||
self
|
||||
}
|
||||
|
||||
pub fn dependency_box(self: &Arc<Self>, d: Box<dyn DependencyHandler>) -> &Arc<Self> {
|
||||
d.add();
|
||||
self.3.lock().unwrap().push(d);
|
||||
self
|
||||
}
|
||||
|
||||
pub fn component<C: Component + 'static>(self: &Arc<Self>, c: C) -> &Arc<Self> {
|
||||
self.1
|
||||
.lock()
|
||||
.unwrap()
|
||||
.entry(c.type_id())
|
||||
.or_insert_with(|| Box::new(c));
|
||||
self
|
||||
}
|
||||
|
||||
pub fn set_component<C: Component + 'static>(self: &Arc<Self>, c: C) -> &Arc<Self> {
|
||||
self.1.lock().unwrap().insert(c.type_id(), Box::new(c));
|
||||
self
|
||||
}
|
||||
|
||||
pub fn get<C: Component + 'static + Clone>(&self) -> Option<C> {
|
||||
self.1
|
||||
.lock()
|
||||
.unwrap()
|
||||
.get(&TypeId::of::<C>())
|
||||
.and_then(|c| c.as_any().downcast_ref::<C>())
|
||||
.map(|c| c.clone())
|
||||
}
|
||||
}
|
||||
|
||||
pub struct WidgetLoad(BoxedElement, HashMap<TypeId, BoxedComponent>);
|
||||
|
||||
impl WidgetLoad {
|
||||
pub fn new<E: Element + 'static>(e: E) -> Self {
|
||||
Self(Box::new(e), HashMap::new())
|
||||
}
|
||||
|
||||
pub fn component<C: Component + 'static>(mut self, c: C) -> Self {
|
||||
self.1.entry(c.type_id()).or_insert_with(|| Box::new(c));
|
||||
self
|
||||
}
|
||||
|
||||
pub fn set_component<C: Component + 'static>(mut self, c: C) -> Self {
|
||||
self.1.insert(c.type_id(), Box::new(c));
|
||||
self
|
||||
}
|
||||
|
||||
pub fn get<C: Component + 'static + Clone>(&self) -> Option<C> {
|
||||
self.1
|
||||
.get(&TypeId::of::<C>())
|
||||
.and_then(|c| c.as_any().downcast_ref::<C>())
|
||||
.map(|c| c.clone())
|
||||
}
|
||||
}
|
||||
@@ -1,9 +0,0 @@
|
||||
`color`, `background`: `$color{}\x1b[0m`;
|
||||
|
||||
`font`: `$font{}\x1b[0m`;
|
||||
|
||||
`width`, `height`: `n`, `n%`, `auto`;
|
||||
|
||||
`x`, `y`: `n`, `n%`, `center`, `auto`;
|
||||
|
||||
<!-- `display`: `row`, `column`, `overlap`; -->
|
||||
Reference in New Issue
Block a user