use petitcarnets as tea;
use std::time::Duration;
use tea::bubbles::help;
use tea::bubbles::key::Binding;
use tea::bubbles::{progress, textarea, viewport};
use tea::style::{Color, Style, height};
pub(crate) const EDITOR_HEIGHT: usize = 5;
pub(crate) const STEP: Duration = Duration::from_millis(200);
const CHROME: usize = EDITOR_HEIGHT + 8;
const TITLE: Style = Style::new().bold(true).foreground(Color::Palette(212));
const DIM: Style = Style::new().faint(true);
const HEADING: Style = Style::new().bold(true).foreground(Color::Palette(99));
const QUOTE: Style = Style::new().italic(true).foreground(Color::Palette(244));
pub(crate) const GUIDE: &str = "# Keeping a notebook
A notebook is a small thing to carry and a large thing to keep. Write in the note above; ctrl+s copies it to the end of this guide.
## Before you start
- Write the date at the top of each page, every time, even when the page is only a list.
- Number the pages, so that an index at the back can find them again later.
- Leave the last pages blank for that index.
## While you write
Write in full sentences when you can. A note that made sense on the train makes less sense a month later, and none at all a year later.
Draw a line under each entry. The line says the thought is finished, and the next one starts fresh.
- Short entries are fine.
- Wrong entries are fine; cross them out, do not tear them out.
- Copy what you will look up again: a measurement, a recipe, a phone number.
## Reading it back
Once a week, read the last week's pages. Mark what still matters with a star in the margin, and copy the stars to the index.
## Moving around this guide
The guide is a viewport with Bubbles' keys: up and down or k and j move a line, f, space and pgdown a page down, b and pgup a page up, d and u half a page.
Left and right, or h and l, move sideways, for the lines too long for the window, like this one, which goes on past the edge to show it.
## A last word
Fill one, and start the next. A shelf of full notebooks is the best record of a life there is, and the cheapest.";
pub(crate) fn render(guide: &str, notes: &[String]) -> String {
let mut out: Vec<String> = guide.lines().map(render_line).collect();
if !notes.is_empty() {
out.extend([String::new(), HEADING.paint("Your notes"), String::new()]);
out.extend(
notes
.iter()
.map(|n| format!(" {}", QUOTE.paint(&format!("│ {n}")))),
);
}
out.join("\n")
}
fn render_line(line: &str) -> String {
if let Some(title) = line.strip_prefix("# ") {
HEADING.underline(true).paint(title)
} else if let Some(title) = line.strip_prefix("## ") {
HEADING.paint(title)
} else if let Some(item) = line.strip_prefix("- ") {
format!(" • {item}")
} else {
line.to_owned()
}
}
pub(crate) enum Msg {
Note(textarea::Msg),
Bar(progress::Msg),
Progress(Progress),
}
pub(crate) struct Progress {
pub(crate) line: String,
pub(crate) written: u32,
pub(crate) total: u32,
}
pub(crate) struct Export {
pub(crate) lines: Vec<String>,
pub(crate) written: Vec<String>,
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub(crate) enum Focus {
Note,
Guide,
}
pub(crate) struct Keys {
pub(crate) switch: Binding,
pub(crate) export: Binding,
pub(crate) help: Binding,
pub(crate) quit: Binding,
}
impl Default for Keys {
fn default() -> Self {
Self {
switch: Binding::new(&["tab"]).with_help("tab", "switch"),
export: Binding::new(&["ctrl+s"]).with_help("ctrl+s", "export"),
help: Binding::new(&["?"]).with_help("?", "more"),
quit: Binding::new(&["esc", "ctrl+c"]).with_help("esc", "quit"),
}
}
}
pub(crate) struct Model {
pub(crate) note: textarea::Model,
pub(crate) guide: viewport::Model,
pub(crate) bar: progress::Model,
pub(crate) help: help::Model,
pub(crate) keys: Keys,
pub(crate) focus: Focus,
pub(crate) export: Option<Export>,
pub(crate) notes: Vec<String>,
pub(crate) status: String,
pub(crate) size: (usize, usize),
}
pub(crate) fn new_model() -> Model {
let mut note = textarea::Model::new();
note.placeholder = "Write a note...".into();
note.set_virtual_cursor(false);
let _ = note.focus();
let mut guide = viewport::Model::new(0, 0);
guide.fill_height = true;
guide.set_content(&render(GUIDE, &[]));
let mut m = Model {
note,
guide,
bar: progress::Model::new().with_default_blend(),
help: help::Model::new(),
keys: Keys::default(),
focus: Focus::Note,
export: None,
notes: Vec::new(),
status: "Not exported yet.".into(),
size: (0, 0),
};
m.sync_keys();
m
}
const fn note_msg(m: &Msg) -> Option<textarea::Msg> {
match m {
Msg::Note(n) => Some(*n),
_ => None,
}
}
const fn bar_msg(m: &Msg) -> Option<progress::Msg> {
match m {
Msg::Bar(f) => Some(*f),
_ => None,
}
}
fn fraction(n: u32, total: u32) -> f64 {
f64::from(n) / f64::from(total.max(1))
}
impl Model {
fn sync_keys(&mut self) {
self.keys.help.set_enabled(self.focus == Focus::Guide);
self.keys.export.set_enabled(self.export.is_none());
}
fn layout(&mut self) {
let (w, h) = self.size;
self.note.set_width(w);
self.note.set_height(EDITOR_HEIGHT);
self.bar.set_width(w);
self.guide.set_width(w);
self.help.set_width(w);
let help = height(&self.help.view(&HelpKeys(self)));
self.guide
.set_height(h.saturating_sub(CHROME + help).max(1));
}
fn key(&mut self, k: &tea::Key) -> Option<tea::Cmd<Msg>> {
let cmd = if self.keys.quit.matches(k) {
tea::quit()
} else if self.keys.switch.matches(k) {
self.switch_focus()
} else if self.keys.export.matches(k) {
self.start_export()
} else if self.keys.help.matches(k) {
self.help.show_all = !self.help.show_all;
tea::Cmd::none()
} else {
return None;
};
self.sync_keys();
self.layout();
Some(cmd)
}
fn switch_focus(&mut self) -> tea::Cmd<Msg> {
if self.focus == Focus::Note {
self.focus = Focus::Guide;
self.note.blur();
tea::Cmd::none()
} else {
self.focus = Focus::Note;
self.note.focus().map(Msg::Note)
}
}
fn start_export(&mut self) -> tea::Cmd<Msg> {
let lines: Vec<String> = self.note.value().lines().map(str::to_owned).collect();
if lines.iter().all(|l| l.trim().is_empty()) {
"Nothing to export yet.".clone_into(&mut self.status);
return tea::Cmd::none();
}
self.export = Some(Export {
lines,
written: Vec::new(),
});
"Exporting...".clone_into(&mut self.status);
tea::batch([self.bar.set_percent(0.0).map(Msg::Bar), self.write_next()])
}
fn write_next(&self) -> tea::Cmd<Msg> {
let Some(export) = &self.export else {
return tea::Cmd::none();
};
let n = export.written.len();
let line = export.lines[n].clone();
let total = u32::try_from(export.lines.len()).unwrap_or(u32::MAX);
let written = u32::try_from(n + 1).unwrap_or(u32::MAX);
tea::tick(STEP, move |_| {
Msg::Progress(Progress {
line,
written,
total,
})
})
}
fn progress(&mut self, p: Progress) -> tea::Cmd<Msg> {
let Some(export) = &mut self.export else {
return tea::Cmd::none();
};
export.written.push(p.line);
let bar = self
.bar
.set_percent(fraction(p.written, p.total))
.map(Msg::Bar);
if p.written < p.total {
self.status = format!("Exporting: {} of {} lines", p.written, p.total);
return tea::batch([bar, self.write_next()]);
}
if let Some(done) = self.export.take() {
self.notes.extend(done.written);
}
self.status = format!("Exported {} lines into the guide.", p.total);
self.guide.set_content(&render(GUIDE, &self.notes));
self.guide.goto_bottom();
self.sync_keys();
bar
}
fn children(&mut self, msg: &tea::Msg<Msg>) -> tea::Cmd<Msg> {
let mut cmds = Vec::new();
if let Some(m) = msg.route(note_msg) {
cmds.push(self.note.update(&m).map(Msg::Note));
}
if let Some(m) = msg.route(bar_msg) {
cmds.push(self.bar.update(&m).map(Msg::Bar));
}
let key = matches!(msg, tea::Msg::KeyPress(_));
if !key || self.focus == Focus::Guide {
cmds.push(self.guide.update(msg));
}
tea::batch(cmds)
}
fn title(&self, name: &str, focus: Focus, info: &str) -> String {
let style = if self.focus == focus { TITLE } else { DIM };
format!("{} {}", style.paint(name), DIM.paint(info))
}
}
impl tea::Model for Model {
type Msg = Msg;
fn update(&mut self, msg: tea::Msg<Msg>) -> tea::Cmd<Msg> {
if let tea::Msg::KeyPress(k) = &msg {
if let Some(cmd) = self.key(k) {
return cmd;
}
}
match msg {
tea::Msg::WindowSize(size) => {
self.size = (usize::from(size.width), usize::from(size.height));
self.layout();
tea::Cmd::none()
}
tea::Msg::App(Msg::Progress(p)) => self.progress(p),
msg => self.children(&msg),
}
}
fn view(&self) -> tea::View {
let lines = format!(
"line {} of {}",
self.note.line() + 1,
self.note.line_count()
);
let read = format!("{:.0}%", self.guide.scroll_percent() * 100.0);
let content = [
self.title("Note", Focus::Note, &lines),
self.note.view(),
String::new(),
self.title("Guide", Focus::Guide, &read),
self.guide.view(),
String::new(),
self.bar.view(),
DIM.paint(&self.status),
String::new(),
self.help.view(&HelpKeys(self)),
]
.join("\n");
let mut v = tea::View::new(content)
.with_alt_screen(true)
.with_mouse_mode(tea::MouseMode::CellMotion);
if let Some(mut c) = self.note.cursor() {
c.y += 1;
v = v.with_cursor(c);
}
v
}
}
pub(crate) struct HelpKeys<'a>(pub(crate) &'a Model);
impl help::KeyMap for HelpKeys<'_> {
fn short_help(&self) -> Vec<Binding> {
let (m, app) = (self.0, &self.0.keys);
let mut keys = match m.focus {
Focus::Note => {
let k = &m.note.key_map;
vec![k.insert_newline.clone(), k.word_forward.clone()]
}
Focus::Guide => {
let k = &m.guide.key_map;
vec![k.down.clone(), k.page_down.clone()]
}
};
keys.extend([&app.switch, &app.export, &app.help, &app.quit].map(Binding::clone));
keys
}
fn full_help(&self) -> Vec<Vec<Binding>> {
let (m, app) = (self.0, &self.0.keys);
let mut groups = match m.focus {
Focus::Note => {
let k = &m.note.key_map;
vec![
vec![
&k.line_previous,
&k.line_next,
&k.character_backward,
&k.character_forward,
],
vec![
&k.word_backward,
&k.word_forward,
&k.line_start,
&k.line_end,
],
vec![
&k.insert_newline,
&k.delete_word_backward,
&k.input_begin,
&k.input_end,
],
]
}
Focus::Guide => {
let k = &m.guide.key_map;
vec![
vec![&k.up, &k.down, &k.left, &k.right],
vec![&k.page_down, &k.page_up, &k.half_page_down, &k.half_page_up],
]
}
};
groups.push(vec![&app.switch, &app.export, &app.help, &app.quit]);
groups
.into_iter()
.map(|g| g.into_iter().cloned().collect())
.collect()
}
}
pub(crate) fn main() -> Result<(), tea::Error> {
let _ = tea::Program::new(new_model()).run()?;
Ok(())
}