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: crates-tui based async tutorial #440

Draft
wants to merge 5 commits into
base: main
Choose a base branch
from
Draft
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
973 changes: 799 additions & 174 deletions Cargo.lock

Large diffs are not rendered by default.

44 changes: 35 additions & 9 deletions astro.config.mjs
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,14 @@ import remarkIncludeCode from "/src/plugins/remark-code-import";

// https://astro.build/config
export default defineConfig({
image: {
service: {
entrypoint: "astro/assets/services/sharp",
config: {
limitInputPixels: false,
},
},
},
kdheepak marked this conversation as resolved.
Show resolved Hide resolved
site: "https://ratatui.rs",
image: {
service: {
Expand Down Expand Up @@ -135,21 +143,39 @@ export default defineConfig({
],
},
{
label: "Async Counter App",
label: "Crates TUI App",
collapsed: true,
items: [
{ label: "Async Counter App", link: "/tutorials/counter-async-app/" },
{ label: "Crates TUI", link: "/tutorials/crates-tui/" },
{ label: "Main", link: "/tutorials/crates-tui/main" },
{
label: "Async KeyEvents",
link: "/tutorials/counter-async-app/async-event-stream/",
label: "Helper",
link: "/tutorials/crates-tui/crates-io-api-helper",
},
{ label: "Async Render", link: "/tutorials/counter-async-app/full-async-events/" },
{ label: "Introducing Actions", link: "/tutorials/counter-async-app/actions/" },
{ label: "Tui", link: "/tutorials/crates-tui/tui" },
{ label: "Errors", link: "/tutorials/crates-tui/errors" },
{ label: "Events", link: "/tutorials/crates-tui/events" },
{
label: "Async Actions",
link: "/tutorials/counter-async-app/full-async-actions/",
label: "App",
collapsed: true,
items: [
{ label: "App Basics", link: "/tutorials/crates-tui/app-basics" },
{ label: "App Mode", link: "/tutorials/crates-tui/app-mode" },
{ label: "App Async", link: "/tutorials/crates-tui/app-async" },
{ label: "App Prototype", link: "/tutorials/crates-tui/app-prototype" },
],
},
{
label: "Widgets",
collapsed: true,
items: [
{ label: "Widgets", link: "/tutorials/crates-tui/widgets" },
{ label: "Prompt", link: "/tutorials/crates-tui/prompt" },
{ label: "Results", link: "/tutorials/crates-tui/results" },
{ label: "App", link: "/tutorials/crates-tui/app" },
],
},
{ label: "Conclusion", link: "/tutorials/counter-async-app/conclusion/" },
{ label: "Conclusion", link: "/tutorials/crates-tui/conclusion" },
],
},
],
Expand Down
1 change: 1 addition & 0 deletions code/crates-tui-tutorial-app/.gitignore
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
.data/*.log
17 changes: 17 additions & 0 deletions code/crates-tui-tutorial-app/Cargo.toml
Original file line number Diff line number Diff line change
@@ -0,0 +1,17 @@
[package]
name = "crates-tui"
version = "0.1.0"
edition = "2021"

# See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html

[dependencies]
color-eyre = "0.6.2"
crates_io_api = "0.9.0"
crossterm = { version = "0.27.0", features = ["serde", "event-stream"] }
futures = "0.3.28"
itertools = "0.12.0"
ratatui = { version = "0.26.1", features = ["serde", "macros"] }
tokio = { version = "1.36.0", features = ["full"] }
tokio-stream = "0.1.14"
tui-input = "0.8.0"
21 changes: 21 additions & 0 deletions code/crates-tui-tutorial-app/LICENSE
Original file line number Diff line number Diff line change
@@ -0,0 +1,21 @@
MIT License

Copyright (c) 2023 The Ratatui Developers

Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
23 changes: 23 additions & 0 deletions code/crates-tui-tutorial-app/demo.tape
Original file line number Diff line number Diff line change
@@ -0,0 +1,23 @@
# A VHS tape. See https://github.com/charmbracelet/vhs
Output crates-tui-demo.gif
Set Theme "Aardvark Blue"
Set Width 1600
Set Height 800
Type "cargo run --bin crates-tui"
Enter
Sleep 3s
Type @0.1s "ratatui"
Sleep 1s
Enter
Sleep 5s
Down @0.1s 5
Sleep 5s
Up @0.1s 5
Sleep 5s
Screenshot crates-tui-demo-2.png
Sleep 2s
Type "/"
Sleep 1s
Screenshot crates-tui-demo-1.png
Sleep 2s

247 changes: 247 additions & 0 deletions code/crates-tui-tutorial-app/src/app.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,247 @@
use std::sync::{atomic::AtomicBool, Arc, Mutex};

// ANCHOR: imports_all
// ANCHOR: imports_external
use color_eyre::eyre::Result;
use crossterm::event::KeyEvent;
use ratatui::prelude::*;
// ANCHOR: imports_external

// ANCHOR: imports_core
use crate::{
events::{Event, Events},
tui::Tui,
widgets::{
search_prompt::{SearchPrompt, SearchPromptWidget},
search_results::{SearchResults, SearchResultsWidget},
status_bar::{StatusBar, StatusBarWidget},
},
};
// ANCHOR_END: imports_core
// ANCHOR_END: imports_all

// ANCHOR: full_app
// ANCHOR: mode
#[derive(Default, Debug, Clone, Copy, PartialEq, Eq, Hash)]
pub enum Mode {
#[default]
Prompt,
Results,
}
// ANCHOR_END: mode

// ANCHOR: mode_handle_key
impl Mode {
fn handle_key(&self, key: KeyEvent) -> Option<Action> {
use crossterm::event::KeyCode::*;
let action = match self {
Mode::Prompt => match key.code {
Enter => Action::SubmitSearchQuery,
Esc => Action::SwitchMode(Mode::Results),
_ => return None,
},
Mode::Results => match key.code {
Up => Action::ScrollUp,
Down => Action::ScrollDown,
Char('/') => Action::SwitchMode(Mode::Prompt),
Esc => Action::Quit,
_ => return None,
},
};
Some(action)
}
}
// ANCHOR_END: mode_handle_key

// ANCHOR: action
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum Action {
Quit,
SwitchMode(Mode),
ScrollDown,
ScrollUp,
SubmitSearchQuery,
UpdateSearchResults,
}
// ANCHOR_END: action

// ANCHOR: app
#[derive(Debug)]
pub struct App {
quit: bool,
mode: Mode,
rx: tokio::sync::mpsc::UnboundedReceiver<Action>,
tx: tokio::sync::mpsc::UnboundedSender<Action>,

status_bar: StatusBar,
results: SearchResults,
prompt: SearchPrompt,
}
// ANCHOR_END: app

impl App {
// ANCHOR: app_new
pub fn new() -> Self {
let loading_status = Arc::new(AtomicBool::default());
let (tx, rx) = tokio::sync::mpsc::unbounded_channel();
let crates: Arc<Mutex<Vec<crates_io_api::Crate>>> = Default::default();
let results = SearchResults::new(crates.clone());
let prompt = SearchPrompt::new(
tx.clone(),
loading_status.clone(),
crates.clone(),
);
let status_bar = StatusBar::new(loading_status);
let mode = Mode::default();
let quit = false;
Self {
quit,
mode,
rx,
tx,
status_bar,
results,
prompt,
}
}
// ANCHOR_END: app_new

// ANCHOR: app_run
pub async fn run(
&mut self,
mut tui: Tui,
mut events: Events,
) -> Result<()> {
loop {
if let Some(e) = events.next().await {
if matches!(e, Event::Render) {
self.draw(&mut tui)?
} else {
self.handle_event(e)?
}
}
while let Ok(action) = self.rx.try_recv() {
self.handle_action(action)?;
}
if self.should_quit() {
break;
}
}
Ok(())
}
// ANCHOR_END: app_run

// ANCHOR: app_handle_event
fn handle_event(&mut self, e: Event) -> Result<()> {
use crossterm::event::Event as CrosstermEvent;
if let Event::Crossterm(CrosstermEvent::Key(key)) = e {
self.status_bar.last_key_event = Some(key);
self.handle_key(key)
};
Ok(())
}
// ANCHOR_END: app_handle_event

// ANCHOR: app_handle_key_event
fn handle_key(&mut self, key: KeyEvent) {
let maybe_action = self.mode.handle_key(key);
if maybe_action.is_none() && matches!(self.mode, Mode::Prompt) {
self.prompt.handle_key(key);
}
maybe_action.map(|action| self.tx.send(action));
}
// ANCHOR_END: app_handle_key_event

// ANCHOR: app_handle_action
fn handle_action(&mut self, action: Action) -> Result<()> {
match action {
Action::Quit => self.quit(),
Action::SwitchMode(mode) => self.switch_mode(mode),
Action::ScrollUp => self.results.scroll_previous(),
Action::ScrollDown => self.results.scroll_next(),
Action::SubmitSearchQuery => {
self.results.clear_selection();
self.prompt.submit_query();
}
Action::UpdateSearchResults => self.results.update_search_results(),
}
Ok(())
}
// ANCHOR_END: app_handle_action
}

impl Default for App {
fn default() -> Self {
Self::new()
}
}

impl App {
// ANCHOR: app_draw
fn draw(&mut self, tui: &mut Tui) -> Result<()> {
tui.draw(|frame| {
frame.render_stateful_widget(AppWidget, frame.size(), self);
self.set_cursor(frame);
})?;
Ok(())
}
// ANCHOR_END: app_draw

fn quit(&mut self) {
self.quit = true
}

fn switch_mode(&mut self, mode: Mode) {
self.mode = mode;
}

fn should_quit(&self) -> bool {
self.quit
}

// ANCHOR: loading
fn set_cursor(&mut self, frame: &mut Frame<'_>) {
if matches!(self.mode, Mode::Prompt) {
if let Some(cursor_position) = self.prompt.cursor_position {
frame.set_cursor(cursor_position.x, cursor_position.y)
}
}
}
}

const PROMPT_HEIGHT: u16 = 5;

// ANCHOR: app_widget
struct AppWidget;
// ANCHOR_END: app_widget

// ANCHOR: app_statefulwidget
impl StatefulWidget for AppWidget {
type State = App;

fn render(self, area: Rect, buf: &mut Buffer, state: &mut Self::State) {
let [status_bar, main, prompt] = Layout::vertical([
Constraint::Length(1),
Constraint::Min(0),
Constraint::Length(PROMPT_HEIGHT),
])
.areas(area);

StatusBarWidget.render(status_bar, buf, &mut state.status_bar);

SearchResultsWidget::new(matches!(state.mode, Mode::Results)).render(
main,
buf,
&mut state.results,
);

SearchPromptWidget::new(matches!(state.mode, Mode::Prompt)).render(
prompt,
buf,
&mut state.prompt,
);
}
}
// ANCHOR_END: app_statefulwidget

// ANCHOR_END: full_app
18 changes: 18 additions & 0 deletions code/crates-tui-tutorial-app/src/bin/crates-tui.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,18 @@
use crates_tui::app;
use crates_tui::errors;
use crates_tui::events;
use crates_tui::tui;

// ANCHOR: main
#[tokio::main]
async fn main() -> color_eyre::Result<()> {
errors::install_hooks()?;

let tui = tui::init()?;
let events = events::Events::new();
app::App::new().run(tui, events).await?;
tui::restore()?;

Ok(())
}
// ANCHOR_END: main
Loading
Loading