wip: don't style at all but collect link targets

But do collect the link targets and have hotkeys for them.
This commit is contained in:
Jeremy Wall 2025-03-11 21:49:23 -04:00
parent 3b2c65a9fa
commit 27d30302f5
5 changed files with 94 additions and 198 deletions

View File

@ -1,12 +1,11 @@
use ratatui::text::Text; use crate::ui::render::markdown::Markdown;
use tui_markdown;
pub fn render_topic(topic: &str) -> Text<'static> { pub fn to_widget(topic: &str) -> Markdown {
match topic { match topic {
"navigate" => tui_markdown::from_str(include_str!("../../../docs/navigation.md")), "navigate" => Markdown::from_str(include_str!("../../../docs/navigation.md")),
"edit" => tui_markdown::from_str(include_str!("../../../docs/edit.md")), "edit" => Markdown::from_str(include_str!("../../../docs/edit.md")),
"command" => tui_markdown::from_str(include_str!("../../../docs/command.md")), "command" => Markdown::from_str(include_str!("../../../docs/command.md")),
"visual" => tui_markdown::from_str(include_str!("../../../docs/visual.md")), "visual" => Markdown::from_str(include_str!("../../../docs/visual.md")),
_ => tui_markdown::from_str(include_str!("../../../docs/intro.md")), _ => Markdown::from_str(include_str!("../../../docs/intro.md")),
} }
} }

View File

@ -7,7 +7,7 @@ use anyhow::{anyhow, Result};
use crossterm::event::{self, Event, KeyCode, KeyEventKind, KeyModifiers}; use crossterm::event::{self, Event, KeyCode, KeyEventKind, KeyModifiers};
use ironcalc::base::{expressions::types::Area, Model}; use ironcalc::base::{expressions::types::Area, Model};
use ratatui::{ use ratatui::{
buffer::Buffer, layout::{Constraint, Flex, Layout}, style::{Modifier, Style}, text::{Line, Text}, widgets::Block buffer::Buffer, layout::{Constraint, Flex, Layout}, style::{Modifier, Style}, widgets::Block
}; };
use tui_prompts::{State, Status, TextPrompt, TextState}; use tui_prompts::{State, Status, TextPrompt, TextState};
use tui_textarea::{CursorMove, TextArea}; use tui_textarea::{CursorMove, TextArea};
@ -19,7 +19,7 @@ pub mod render;
mod test; mod test;
use cmd::Cmd; use cmd::Cmd;
use render::viewport::ViewportState; use render::{markdown::Markdown, viewport::ViewportState};
#[derive(Default, Debug, PartialEq, Clone)] #[derive(Default, Debug, PartialEq, Clone)]
pub enum Modality { pub enum Modality {
@ -80,7 +80,7 @@ pub struct AppState<'ws> {
pub range_select: RangeSelection, pub range_select: RangeSelection,
pub dialog_scroll: u16, pub dialog_scroll: u16,
dirty: bool, dirty: bool,
popup: Text<'ws>, popup: Option<Markdown>,
clipboard: Option<ClipboardContents>, clipboard: Option<ClipboardContents>,
} }
@ -299,16 +299,16 @@ impl<'ws> Workspace<'ws> {
Ok(None) Ok(None)
} }
fn render_help_text(&self) -> Text<'static> { fn render_help_text(&self) -> Markdown {
// TODO(zaphar): We should be sourcing these from our actual help documentation. // TODO(zaphar): We should be sourcing these from our actual help documentation.
// Ideally we would also render the markdown content properly. // Ideally we would also render the markdown content properly.
// https://github.com/zaphar/sheetsui/issues/22 // https://github.com/zaphar/sheetsui/issues/22
match self.state.modality() { match self.state.modality() {
Modality::Navigate => help::render_topic("navigate"), Modality::Navigate => help::to_widget("navigate"),
Modality::CellEdit => help::render_topic("edit"), Modality::CellEdit => help::to_widget("edit"),
Modality::Command => help::render_topic("command"), Modality::Command => help::to_widget("command"),
Modality::RangeSelect => help::render_topic("visual"), Modality::RangeSelect => help::to_widget("visual"),
_ => help::render_topic(""), _ => help::to_widget(""),
} }
} }
@ -361,8 +361,10 @@ impl<'ws> Workspace<'ws> {
KeyCode::Char('k') | KeyCode::Up => { KeyCode::Char('k') | KeyCode::Up => {
self.state.dialog_scroll = self.state.dialog_scroll.saturating_sub(1); self.state.dialog_scroll = self.state.dialog_scroll.saturating_sub(1);
} }
_ => { code => {
// NOOP if let Some(widget) = &self.state.popup {
widget.handle_input(code);
}
} }
} }
} }
@ -414,7 +416,7 @@ impl<'ws> Workspace<'ws> {
Ok(None) Ok(None)
} }
Ok(Some(Cmd::Help(maybe_topic))) => { Ok(Some(Cmd::Help(maybe_topic))) => {
self.enter_dialog_mode(help::render_topic(maybe_topic.unwrap_or(""))); self.enter_dialog_mode(help::to_widget(maybe_topic.unwrap_or("")));
Ok(None) Ok(None)
} }
Ok(Some(Cmd::Write(maybe_path))) => { Ok(Some(Cmd::Write(maybe_path))) => {
@ -508,11 +510,11 @@ impl<'ws> Workspace<'ws> {
Ok(None) Ok(None)
} }
Ok(None) => { Ok(None) => {
self.enter_dialog_mode(vec![Line::from(format!("Unrecognized commmand {}", cmd_text))]); self.enter_dialog_mode(Markdown::from_str(&format!("Unrecognized commmand {}", cmd_text)));
Ok(None) Ok(None)
} }
Err(msg) => { Err(msg) => {
self.enter_dialog_mode(vec![Line::from(msg.to_owned())]); self.enter_dialog_mode(Markdown::from_str(msg));
Ok(None) Ok(None)
} }
} }
@ -951,8 +953,8 @@ impl<'ws> Workspace<'ws> {
self.state.command_state.focus(); self.state.command_state.focus();
} }
fn enter_dialog_mode<T: Into<Text<'ws>>>(&mut self, msg: T) { fn enter_dialog_mode(&mut self, msg: Markdown) {
self.state.popup = msg.into(); self.state.popup = Some(msg);
self.state.modality_stack.push(Modality::Dialog); self.state.modality_stack.push(Modality::Dialog);
} }

View File

@ -1,124 +1,55 @@
use core::panic;
use std::collections::BTreeSet; use std::collections::BTreeSet;
use ratatui::{ use crossterm::event::KeyCode;
text::{Line, Span, Text}, use ratatui::{text::Text, widgets::Widget};
widgets::Widget,
};
use pulldown_cmark::{Event, HeadingLevel, LinkType, Parser, Tag, TagEnd, TextMergeStream}; use pulldown_cmark::{Event,LinkType, Parser, Tag, TextMergeStream};
enum State { //enum State {
Para, // Para,
NumberList, // NumberList,
BulletList, // BulletList,
Heading, // Heading,
BlockQuote, // BlockQuote,
} //}
struct WidgetWriter<'i> { #[derive(Debug, Clone, PartialEq)]
input: &'i str, pub struct Markdown {
state_stack: Vec<State>, input: String,
heading_stack: Vec<&'static str>,
list_stack: Vec<u64>,
accumulator: String,
lines: Vec<String>,
links: BTreeSet<String>, links: BTreeSet<String>,
} }
impl<'i> WidgetWriter<'i> impl Markdown {
{ pub fn from_str(input: &str) -> Self {
pub fn from_str(input: &'i str) -> Self { let mut me = Self {
Self { input: input.to_owned(),
input,
state_stack: Default::default(),
heading_stack: Default::default(),
list_stack: Default::default(),
accumulator: Default::default(),
lines: Default::default(),
links: Default::default(), links: Default::default(),
} };
me.parse();
me
} }
pub fn parse(&mut self) { fn parse(&mut self) {
let iter = TextMergeStream::new(Parser::new(self.input)); let input = self.input.clone();
let iter = TextMergeStream::new(Parser::new(&input));
for event in iter { for event in iter {
match event { match event {
Event::Start(tag) => { Event::Start(tag) => {
self.start_tag(&tag); self.start_tag(&tag);
}, }
Event::End(tag) => { _ => { /* noop */ }
self.end_tag(tag);
},
Event::Text(txt)
| Event::Code(txt)
| Event::InlineHtml(txt)
| Event::Html(txt) => {
let prefix = if let Some(State::BlockQuote) = self.state_stack.first() {
"| "
} else {
""
};
for ln in txt.lines() {
self.accumulator.push_str(prefix);
self.accumulator.push_str(ln);
}
},
Event::Rule => { /* noop */ },
Event::SoftBreak => { /* noop */ },
Event::HardBreak => { /* noop */ },
// We don't support these
Event::InlineMath(_) => todo!(),
Event::DisplayMath(_) => todo!(),
Event::FootnoteReference(_) => todo!(),
Event::TaskListMarker(_) => todo!(),
} }
} }
} }
fn start_tag(&mut self, tag: &Tag<'i>) { fn start_tag(&mut self, tag: &Tag<'_>) {
match tag { match tag {
Tag::Paragraph => { Tag::Link {
self.state_stack.push(State::Para); link_type,
}, dest_url,
Tag::Heading { level, id: _id, classes: _classes, attrs: _attrs } => { title,
self.heading_stack.push(match level { id,
HeadingLevel::H1 => "1", } => {
HeadingLevel::H2 => "2",
HeadingLevel::H3 => "3",
HeadingLevel::H4 => "4",
HeadingLevel::H5 => "5",
HeadingLevel::H6 => "6",
});
self.state_stack.push(State::Heading);
let prefix = self.heading_stack.join(".");
self.accumulator.push_str(&prefix);
self.accumulator.push_str(" ");
},
Tag::List(Some(first)) => {
self.list_stack.push(*first);
self.state_stack.push(State::NumberList);
},
Tag::List(None) => {
self.state_stack.push(State::BulletList);
},
Tag::Item => {
if let Some(State::BulletList) = self.state_stack.first() {
self.accumulator.push_str("- ");
} else if let Some(State::NumberList) = self.state_stack.first() {
let num = self.list_stack.pop().unwrap_or(1);
self.accumulator.push_str(&format!("{}. ", num));
self.list_stack.push(num + 1);
}
panic!("No list type in our state stack");
},
Tag::Emphasis => {
self.accumulator.push_str("*");
},
Tag::Strong => {
self.accumulator.push_str("**");
},
Tag::Link { link_type, dest_url, title, id } => {
let dest = match link_type { let dest = match link_type {
// [foo](bar) // [foo](bar)
LinkType::Inline => format!("({})", dest_url), LinkType::Inline => format!("({})", dest_url),
@ -135,77 +66,41 @@ impl<'i> WidgetWriter<'i>
LinkType::Email => todo!(), LinkType::Email => todo!(),
LinkType::WikiLink { has_pothole: _ } => todo!(), LinkType::WikiLink { has_pothole: _ } => todo!(),
}; };
self.accumulator.push_str(&format!("[{}]{}", title, dest));
self.links.insert(dest); self.links.insert(dest);
}, }
Tag::BlockQuote(_) => { _ => { /* noop */ }
self.state_stack.push(State::BlockQuote);
},
// these are all noops
Tag::CodeBlock(_) => {},
Tag::HtmlBlock => {},
Tag::FootnoteDefinition(_) => {},
Tag::DefinitionList => {},
Tag::DefinitionListTitle => {},
Tag::DefinitionListDefinition => {},
Tag::Table(_) => {},
Tag::TableHead => {},
Tag::TableRow => {},
Tag::TableCell => {},
Tag::Strikethrough => {},
Tag::Superscript => {},
Tag::Subscript => {}
Tag::Image { link_type: _link_type, dest_url: _dest_url, title: _title, id: _id } => {},
Tag::MetadataBlock(_) => {},
} }
} }
fn end_tag(&mut self, tag: TagEnd) { pub fn handle_input(&self, code: KeyCode) -> Option<String> {
match tag { let num = match code {
TagEnd::Paragraph => { KeyCode::Char('0') => 0,
self.state_stack.pop(); KeyCode::Char('1') => 1,
self.lines.push("\n".to_owned()); KeyCode::Char('2') => 2,
}, KeyCode::Char('3') => 3,
TagEnd::Heading(_level) => { KeyCode::Char('4') => 4,
self.heading_stack.pop(); KeyCode::Char('5') => 5,
self.state_stack.pop(); KeyCode::Char('6') => 6,
self.lines.extend(self.accumulator.lines().map(|s| s.to_owned())); KeyCode::Char('7') => 7,
self.accumulator.clear(); KeyCode::Char('8') => 8,
}, KeyCode::Char('9') => 9,
TagEnd::List(_ordered) => { _ => return None,
self.state_stack.pop(); };
}, self.links.iter().nth(num).cloned()
TagEnd::BlockQuote(_kind) => { }
self.state_stack.pop();
}, pub fn get_text<'w>(&'w self) -> Text<'_> {
TagEnd::CodeBlock => { Text::raw(&self.input)
todo!() }
}, }
TagEnd::HtmlBlock => {
todo!() // TODO(jwall): We need this to be lines instead of just a render.
}, impl Widget for Markdown {
TagEnd::Item => { /* noop */ }, fn render(self, area: ratatui::prelude::Rect, buf: &mut ratatui::prelude::Buffer)
TagEnd::Link => { /* noop */ }, where
// We don't support these Self: Sized,
TagEnd::FootnoteDefinition => todo!(), {
TagEnd::DefinitionList => todo!(), let text = Text::raw(self.input);
TagEnd::DefinitionListTitle => todo!(), text.render(area, buf);
TagEnd::DefinitionListDefinition => todo!(),
TagEnd::Table => todo!(),
TagEnd::TableHead => todo!(),
TagEnd::TableRow => todo!(),
TagEnd::TableCell => todo!(),
TagEnd::Emphasis => {
self.accumulator.push_str("*");
},
TagEnd::Strong => {
self.accumulator.push_str("**");
},
TagEnd::Strikethrough => todo!(),
TagEnd::Superscript => todo!(),
TagEnd::Subscript => todo!(),
TagEnd::Image => todo!(),
TagEnd::MetadataBlock(_) => todo!(),
}
} }
} }

View File

@ -100,7 +100,7 @@ impl<'widget, 'ws: 'widget> Widget for &'widget mut Workspace<'ws> {
Self: Sized, Self: Sized,
{ {
if self.state.modality() == &Modality::Dialog { if self.state.modality() == &Modality::Dialog {
let lines = Text::from_iter(self.state.popup.iter().cloned()); let lines = self.state.popup.as_ref().map(|md| md.get_text()).unwrap_or_else(|| Text::raw("Popup message here"));
let popup = dialog::Dialog::new(lines, "Help").scroll(self.state.dialog_scroll); let popup = dialog::Dialog::new(lines, "Help").scroll(self.state.dialog_scroll);
popup.render(area, buf); popup.render(area, buf);
} else if self.state.modality() == &Modality::Quit { } else if self.state.modality() == &Modality::Quit {

View File

@ -395,7 +395,7 @@ macro_rules! assert_help_dialog {
.run(&mut ws) .run(&mut ws)
.expect("Failed to handle 'alt-h' key event"); .expect("Failed to handle 'alt-h' key event");
assert_eq!(Some(&Modality::Dialog), ws.state.modality_stack.last()); assert_eq!(Some(&Modality::Dialog), ws.state.modality_stack.last());
assert_eq!(edit_help, ws.state.popup); assert_eq!(Some(edit_help), ws.state.popup);
$exit.run(&mut ws).expect("Failed to handle key event"); $exit.run(&mut ws).expect("Failed to handle key event");
assert_eq!(Some(&Modality::CellEdit), ws.state.modality_stack.last()); assert_eq!(Some(&Modality::CellEdit), ws.state.modality_stack.last());
}}; }};
@ -431,7 +431,7 @@ fn test_navigation_mode_help_keycode() {
.run(&mut ws) .run(&mut ws)
.expect("Failed to handle 'alt-h' key event"); .expect("Failed to handle 'alt-h' key event");
assert_eq!(Some(&Modality::Dialog), ws.state.modality_stack.last()); assert_eq!(Some(&Modality::Dialog), ws.state.modality_stack.last());
assert_eq!(help_text, ws.state.popup); assert_eq!(Some(help_text), ws.state.popup);
} }
#[test] #[test]
@ -449,7 +449,7 @@ fn test_command_mode_help_keycode() {
.run(&mut ws) .run(&mut ws)
.expect("Failed to handle 'alt-h' key event"); .expect("Failed to handle 'alt-h' key event");
assert_eq!(Some(&Modality::Dialog), ws.state.modality_stack.last()); assert_eq!(Some(&Modality::Dialog), ws.state.modality_stack.last());
assert_eq!(edit_help, ws.state.popup); assert_eq!(Some(edit_help), ws.state.popup);
} }
#[test] #[test]