Skip to content

Commit

Permalink
feat: Add crates-tui tutorial
Browse files Browse the repository at this point in the history
  • Loading branch information
kdheepak committed Feb 21, 2024
1 parent b214193 commit 5e3f562
Show file tree
Hide file tree
Showing 70 changed files with 5,027 additions and 1,457 deletions.
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,
},
},
},
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", 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: "Search", link: "/tutorials/crates-tui/search" },
{ label: "Prompt", link: "/tutorials/crates-tui/prompt" },
{ label: "Results", link: "/tutorials/crates-tui/results" },
],
},
{ 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

230 changes: 230 additions & 0 deletions code/crates-tui-tutorial-app/src/app.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,230 @@
use color_eyre::eyre::Result;
use crossterm::event::KeyEvent;
use ratatui::{prelude::*, widgets::Paragraph};

use crate::{
events::{Event, Events},
tui::Tui,
widgets::{search_page::SearchPage, search_page::SearchPageWidget},
};

// 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_widget
struct AppWidget;
// ANCHOR_END: app_widget

// ANCHOR: app
#[derive(Debug)]
pub struct App {
quit: bool,
last_key_event: Option<crossterm::event::KeyEvent>,
mode: Mode,

rx: tokio::sync::mpsc::UnboundedReceiver<Action>,
tx: tokio::sync::mpsc::UnboundedSender<Action>,
search_page: SearchPage,
}
// ANCHOR_END: app

impl App {
// ANCHOR: app_new
pub fn new() -> Self {
let (tx, rx) = tokio::sync::mpsc::unbounded_channel();
let search_page = SearchPage::new(tx.clone());
let mode = Mode::default();
let quit = false;
let last_key_event = None;
Self {
quit,
last_key_event,
mode,
rx,
tx,
search_page,
}
}
// 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.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.search_page.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.scroll_up(),
Action::ScrollDown => self.scroll_down(),
Action::SubmitSearchQuery => self.submit_search_query(),
Action::UpdateSearchResults => self.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.update_cursor(frame);
})?;
Ok(())
}
// ANCHOR_END: app_draw

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

fn scroll_up(&mut self) {
self.search_page.scroll_up()
}

fn scroll_down(&mut self) {
self.search_page.scroll_down()
}

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

fn submit_search_query(&mut self) {
self.switch_mode(Mode::Results);
self.search_page.submit_query()
}

fn update_search_results(&mut self) {
self.search_page.update_search_results();
let _ = self.tx.send(Action::ScrollDown);
}

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

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

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

fn render(self, area: Rect, buf: &mut Buffer, state: &mut Self::State) {
let [last_key_event, search_page] =
Layout::vertical([Constraint::Length(1), Constraint::Fill(0)])
.areas(area);

if let Some(key) = state.last_key_event {
Paragraph::new(format!("last key event: {:?}", key.code))
.right_aligned()
.render(last_key_event, buf);
}

SearchPageWidget { mode: state.mode }.render(
search_page,
buf,
&mut state.search_page,
);
}
}
// ANCHOR_END: app_statefulwidget
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

0 comments on commit 5e3f562

Please sign in to comment.