Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Feat/UI components #79

Merged
merged 7 commits into from
Oct 31, 2023
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
10 changes: 8 additions & 2 deletions src/main.rs
Original file line number Diff line number Diff line change
Expand Up @@ -33,7 +33,10 @@ enum Commands {
#[clap(index = 1, default_value = "test")]
type_: String,
},
Ui {},
Ui {
#[clap(index = 1, default_value = "example")]
app: String,
},
}

fn main() -> Result<()> {
Expand Down Expand Up @@ -81,7 +84,10 @@ fn main() -> Result<()> {
.arg(type_)
.status()?
),
Some(Commands::Ui {}) => interface::run()?,
Some(Commands::Ui { app }) => match app.as_str() {
"example" => interface::example()?,
_ => interface::run()?,
},
None => Args::command().print_long_help()?,
}
Ok(())
Expand Down
9 changes: 8 additions & 1 deletion ui/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -17,7 +17,14 @@ serde = { workspace = true }
serde_json = { workspace = true }
bytesize = { workspace = true }
dotenv = { workspace = true }
thiserror = { workspace = true}

# deps for ui
eyre = "0.6.8"
iced = { version = "0.10.0", features = ["system", "tokio", "lazy"] }
iced = { version = "0.10.0", features = [
"system",
"tokio",
"lazy",
"image",
"palette",
] }
54 changes: 54 additions & 0 deletions ui/README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,54 @@
# Excalibur Ui
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I really like how you give us some good resources here


Excalibur uses [iced](https://github.com/iced-rs/iced) to deliver a rust GUI over the core excalibur software.

Get familiar with [Elm Architecture](https://guide.elm-lang.org/architecture/) and start buildings [components](./src/components/).

## Running a UI

```bash
cargo run ui
cargo run ui example
cargo run ui <application name>
```

## Structure
Files and directories:
- lib.rs - Exposes the `run` function to start running an application.
- app/ - All iced `Application`s. Yes, we can have multiple applications. Check the [example app](./src/app/example.rs).
- components/ - All the iced `Element`s/`Component`s that are responsible for individual state and behaviors.
- sdk/ - Abstractions over arbiter + contracts that are used by iced, does not use iced.

## How to make a screen

A screen is a dedicated view into some part of the application. It can encapsulate an entire screen/page/view or just be a section of the overall layout.

It's architected to communicate directly with the root `Application`. The `Application` trait in iced is capable of processing async functions via `Command::perform()`. This forces our hand with how to execute api calls with arbiter.

Individual screens can be made that forward messages to the `Application`, which is processed in `Application::update()`, which calls `Screen::update()`. Logic is handled in the Application update, with the Screen update simply reacting to the Application's updates.

## How to make a Component

A component is specifically implemented as an iced Element. An iced Element can be easily rendered in the application's view function.

Check out the [example component](./src/components/example.rs) for reference.

A component needs to:
- Implement the possible Messages that can be sent, this should be a generic type.
- Implement the iced Renderer.
- Implement the `from` function for an iced Element, so the component can be casted to the Element type.

Components can pass messages to their parent, making it easier for their parent to react to component changes. This is why components should have a generic message type that is implemented.

## How to add the component to the application UI

Components can be rendered by adding the converted iced Element into the container that is rendered in the main application's `view` function.


## Notes and todo

Components are like mini applications, they are designed just like the main application that is running just with a smaller amount of overhead.

Next tasks are to spec out the rough "model" of the application and its children components, then implement them.

Another idea is to host an api in the background that can be `curl` into from the application, i.e. a backend. This might be more work than just integrating direct calls into arbiter with iced components.
Binary file added ui/images/banner.JPG
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
175 changes: 175 additions & 0 deletions ui/src/app/example.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,175 @@
use std::sync::Arc;

use arbiter_core::{
environment::{builder::EnvironmentBuilder, Environment},
middleware::RevmMiddleware,
};
use iced::{
alignment, executor,
widget::{button, column, container, text},
Application, Command, Element, Length, Theme,
};

use crate::screen;

#[allow(clippy::large_enum_variant)]
/// Application state of an example app that runs arbiter's environment in the
/// background.
pub enum ExampleApp {
Loading,
Running {
environment: Environment,
client: Arc<RevmMiddleware>,
screen: Screen,
},
}

/// Screens implement their own `view` and `update` functions and forward
/// messages to this application's `update` function to process them with
/// [`Command`].
#[derive(Clone, Debug)]
pub enum Screen {
/// The start screen is the first screen of the application.
Start,
/// Main screen of the application.
Home,
/// An example screen that deploys the Counter.sol smart contract.
Example(screen::example::ExampleScreen),
}

#[derive(Debug, Clone)]
#[allow(clippy::large_enum_variant)]
/// Messages that can be sent to the application to process logic.
/// Each screen has a message variant that enables to application to mutate the
/// screen.
pub enum Message {
/// Changes the current screen.
ChangePage(Screen),
/// Receiving a message from the Example screen.
ExampleScreen(screen::example::ExampleScreenMessage),
}

impl Application for ExampleApp {
type Message = Message;
type Theme = Theme;
type Executor = executor::Default;
type Flags = ();

fn new(_flags: ()) -> (Self, Command<Message>) {
(
{
let env = EnvironmentBuilder::new().build();
let client = RevmMiddleware::new(&env, Some("client")).unwrap();
Self::Running {
environment: env,
client,
screen: Screen::Start,
}
},
Command::none(),
)
}

fn title(&self) -> String {
String::from("Excalibur")
}

fn update(&mut self, message: Message) -> Command<Message> {
match message {
// Mutates this application's `screen` state to the new screen.
Message::ChangePage(page) => {
if let Self::Running { screen, .. } = self {
*screen = page;
}
}
// Mutates the example screen's state or performs forwarded commands.
Message::ExampleScreen(message) => {
if let Self::Running { screen, .. } = self {
let Screen::Example(example) = screen else {
return Command::none();
};

if let Some(event) = example.update(message) {
match event {
screen::example::Event::Clicked => {
return Command::perform(
crate::sdk::vault::Vault::deploy::<
screen::example::ExampleScreenError,
>(example.client.clone()),
|res| {
Message::ExampleScreen(
screen::example::ExampleScreenMessage::DeploySuccess(
res,
),
)
},
);
}
screen::example::Event::Deployed(res) => match res {
Ok(vault) => {
example.state =
screen::example::ExampleScreenState::Deployed(vault);
}
Err(err) => {
example.state =
screen::example::ExampleScreenState::DeploymentFailed(err);
}
},
}
}
}
}
}

Command::none()
}

fn view(&self) -> Element<Message> {
let content: Element<_> = match self {
ExampleApp::Loading => text("Loading...").into(),
ExampleApp::Running { client, screen, .. } => {
// Base container for the Running state
let mut content = column![];
// Button for routing back to start screen.
content = content
.push(button("Restart").on_press(Message::ChangePage(Screen::Start)))
.spacing(10)
.align_items(alignment::Alignment::Center);

// Renders the current screen.
match screen {
Screen::Start => {
let start_screen =
screen::start::StartScreen::new(|| Message::ChangePage(Screen::Home));
content = content.push(start_screen);
}
Screen::Home => {
// Button to go to the example screen.
let example_screen = screen::example::ExampleScreen::new(client.clone());
content =
content
.push(button("Go to Example").on_press(Message::ChangePage(
Screen::Example(example_screen),
)));
}
Screen::Example(example) => {
content = content.push(example.view().map(Message::ExampleScreen));
}
}

content.into()
}
};

container(content)
.center_x()
.center_y()
.width(Length::Fill)
.height(Length::Fill)
.into()
}

fn theme(&self) -> Theme {
Theme::Dark
}
}
1 change: 1 addition & 0 deletions ui/src/app/mod.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
pub mod example;
23 changes: 23 additions & 0 deletions ui/src/components/banner.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,23 @@
//! A simple banner image that can be rendered on startup, closing, or loading
//! screens.

use iced::{
widget::{container, image, Container},
Length,
};

/// Returns a banner image with the given width.
pub fn banner<'a, Message>(width: u16) -> Container<'a, Message> {
container(
// This should go away once we unify resource loading on native
// platforms
if cfg!(target_arch = "wasm32") {
image("../images/banner.jpg")
} else {
image(format!("{}/images/banner.jpg", env!("CARGO_MANIFEST_DIR")))
}
.width(width),
)
.width(Length::Fill)
.center_x()
}
55 changes: 39 additions & 16 deletions ui/src/counter_component.rs → ui/src/components/example.rs
Original file line number Diff line number Diff line change
@@ -1,41 +1,62 @@
//! # Example component
//! This is a "component" that interacts with the Counter.sol smart contract.
//! A component is just a siloed piece of the UI that has its own state.
//!
//! Adding this component to the UI is as simple as pushing it to the container
//! that is rendered in the app's view function.

use std::sync::Arc;

use iced::{
alignment::{self, Alignment},
widget::{button, component, row, text, Component},
Element, Length, Renderer,
};
pub struct Counter<Message> {
value: Option<u32>,
on_change: Box<dyn Fn(Option<u32>) -> Message>,
}

pub fn counter_state<Message>(
/// Type alias for the on_change function that can be passed to the counter
/// component. This enables the application to react to changes in the counter's
/// state.
type HandlerFn<Msg> = Arc<Box<dyn Fn(Option<u32>) -> Msg + Send + Sync + 'static>>;

/// This is the "model" for the counter component.
/// It holds the state of the component and a function handler for updating the
/// model.
#[derive(Clone)]
pub struct Counter<Msg> {
value: Option<u32>,
on_change: impl Fn(Option<u32>) -> Message + 'static,
) -> Counter<Message> {
Counter::new(value, on_change)
on_change: HandlerFn<Msg>,
}

impl<Message> Counter<Message> {
pub fn new(value: Option<u32>, on_change: impl Fn(Option<u32>) -> Message + 'static) -> Self {
/// - Msg is a generic type for the application Message that is transmitted from
/// the on_change function.
impl<Msg> Counter<Msg> {
pub fn new(
value: Option<u32>,
on_change: impl Fn(Option<u32>) -> Msg + Send + Sync + 'static,
) -> Self {
Self {
value,
on_change: Box::new(on_change),
on_change: Arc::new(Box::new(on_change)),
}
}
}

/// Events that occur in the component.
#[derive(Debug, Clone)]
pub enum Event {
Increment,
Decrement,
InputChanged(String),
}

impl<Message> Component<Message, Renderer> for Counter<Message> {
/// Implementation of the actual component for the application.
/// update - Handles the model updates.
/// view - Handles the model view.
impl<Msg> Component<Msg, Renderer> for Counter<Msg> {
type State = ();
type Event = Event;

fn update(&mut self, _state: &mut Self::State, event: Event) -> Option<Message> {
fn update(&mut self, _state: &mut Self::State, event: Event) -> Option<Msg> {
match event {
Event::Increment => Some((self.on_change)(Some(
self.value.unwrap_or_default().saturating_add(1),
Expand Down Expand Up @@ -78,11 +99,13 @@ impl<Message> Component<Message, Renderer> for Counter<Message> {
}
}

impl<'a, Message> From<Counter<Message>> for Element<'a, Message, Renderer>
/// Converts the component into an iced Element, which can be pushed to a
/// content container in the UI.
impl<'a, Msg> From<Counter<Msg>> for Element<'a, Msg, Renderer>
where
Message: 'a,
Msg: 'a,
{
fn from(counter: Counter<Message>) -> Self {
fn from(counter: Counter<Msg>) -> Self {
component(counter).into()
}
}
2 changes: 2 additions & 0 deletions ui/src/components/mod.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,2 @@
pub mod banner;
pub mod example;
Loading