1use ratatui::{
2 layout::{Constraint, Direction, Layout, Rect},
3 style::{Color, Modifier, Style},
4 text::{Line, Span},
5 widgets::{Block, BorderType, Borders, Paragraph, Wrap},
6 Frame,
7};
8
9use crate::app::{App, Pane, ViewMode};
10use crate::checklist::ChecklistItem;
11use crate::format::{format_date_short, word_and_line_count};
12use crate::ui::theme;
13
14pub fn render(f: &mut Frame, app: &App, area: Rect) {
15 let is_focused = app.focused_pane == Pane::Detail;
16 let border_color = if is_focused {
17 theme::ACCENT_BLUE
18 } else {
19 theme::FG_MUTED
20 };
21 let border_type = if is_focused {
22 BorderType::Thick
23 } else {
24 BorderType::Plain
25 };
26
27 let title_style = if is_focused {
28 Style::default()
29 .fg(theme::ACCENT_BLUE)
30 .add_modifier(Modifier::BOLD)
31 } else {
32 Style::default().fg(theme::FG_MUTED)
33 };
34
35 let block_title = format!(" [3] Prompt Detail [{}] ", app.view_mode.label());
36
37 let block = Block::default()
38 .borders(Borders::ALL)
39 .border_type(border_type)
40 .border_style(Style::default().fg(border_color))
41 .style(Style::default().bg(theme::BG_MAIN))
42 .title(Span::styled(block_title, title_style));
43
44 let inner = block.inner(area);
45 f.render_widget(block, area);
46
47 let detail = match &app.current_prompt {
48 Some(d) => d,
49 None => {
50 let empty = Paragraph::new(Line::from(Span::styled(
51 "No prompt selected",
52 Style::default().fg(Color::DarkGray),
53 )));
54 f.render_widget(empty, inner);
55 return;
56 }
57 };
58
59 let chunks = Layout::default()
61 .direction(Direction::Vertical)
62 .constraints([
63 Constraint::Length(3),
64 Constraint::Length(1),
65 Constraint::Min(0),
66 ])
67 .split(inner);
68
69 let mut meta_lines = Vec::new();
71 let star = if detail.pinned { " โ
Pinned" } else { "" };
72 let proj_name = detail
73 .project_name
74 .as_deref()
75 .unwrap_or("Standalone (scratchpad)");
76
77 meta_lines.push(Line::from(vec![
78 Span::styled(
79 &detail.title,
80 Style::default()
81 .fg(Color::LightCyan)
82 .add_modifier(Modifier::BOLD),
83 ),
84 Span::styled(
85 star,
86 Style::default()
87 .fg(Color::Cyan)
88 .add_modifier(Modifier::BOLD),
89 ),
90 ]));
91
92 let body_text = detail.body.as_deref().unwrap_or("");
93 let (chars, words, lines_count) = word_and_line_count(body_text);
94
95 let updated = detail
96 .updated_at
97 .as_deref()
98 .map(format_date_short)
99 .unwrap_or_else(|| "unknown".into());
100
101 let att_text = if detail.attachments_count > 0 {
102 format!(" ยท ๐ {} files ('A' to view)", detail.attachments_count)
103 } else {
104 " ยท ๐ 0 files ('A' to attach)".to_string()
105 };
106
107 meta_lines.push(Line::from(vec![
108 Span::styled(
109 format!("Project: {}", proj_name),
110 Style::default().fg(Color::Blue),
111 ),
112 Span::styled(
113 format!(" ยท {}c / {}w / {}L", chars, words, lines_count),
114 Style::default().fg(Color::Cyan),
115 ),
116 Span::styled(
117 format!(" ยท Updated: {}", updated),
118 Style::default().fg(Color::DarkGray),
119 ),
120 Span::styled(att_text, Style::default().fg(Color::LightBlue)),
121 ]));
122
123 f.render_widget(
124 Paragraph::new(meta_lines).wrap(Wrap { trim: false }),
125 chunks[0],
126 );
127
128 let divider = Paragraph::new(Line::from(Span::styled(
130 "โ".repeat(chunks[1].width as usize),
131 Style::default().fg(Color::DarkGray),
132 )));
133 f.render_widget(divider, chunks[1]);
134
135 let rendered_lines = match app.view_mode {
137 ViewMode::Preview => render_markdown_preview(
138 body_text,
139 &app.checklist_items,
140 app.detail_selected_checklist,
141 is_focused,
142 chunks[2].width as usize,
143 ),
144 ViewMode::Raw => render_markdown_raw(body_text),
145 };
146
147 let scroll_y = app.detail_scroll as u16;
148 let body_paragraph = Paragraph::new(rendered_lines)
149 .wrap(Wrap { trim: false })
150 .scroll((scroll_y, 0));
151 f.render_widget(body_paragraph, chunks[2]);
152}
153
154fn render_markdown_raw(text: &str) -> Vec<Line<'_>> {
155 if text.trim().is_empty() {
156 return vec![Line::from(Span::styled(
157 "(empty prompt body โ press 'a' to append content, 'E' to edit in $EDITOR)",
158 Style::default().fg(Color::DarkGray),
159 ))];
160 }
161
162 text.lines()
163 .enumerate()
164 .map(|(idx, line)| {
165 let line_num_str = format!("{:>3} โ ", idx + 1);
166 Line::from(vec![
167 Span::styled(line_num_str, Style::default().fg(Color::DarkGray)),
168 Span::styled(line, Style::default().fg(Color::White)),
169 ])
170 })
171 .collect()
172}
173
174pub fn format_inline_with_variables(text: &str, base_style: Style) -> Vec<Span<'static>> {
175 let mut spans = Vec::new();
176 let mut cursor = 0;
177
178 while let Some(start_offset) = text[cursor..].find("{{") {
179 let abs_start = cursor + start_offset;
180 if abs_start > cursor {
181 spans.push(Span::styled(text[cursor..abs_start].to_string(), base_style));
182 }
183
184 if let Some(end_offset) = text[abs_start..].find("}}") {
185 let abs_end = abs_start + end_offset + 2;
186 let var_token = text[abs_start..abs_end].to_string();
187 spans.push(Span::styled(
188 var_token,
189 Style::default()
190 .fg(Color::LightCyan)
191 .bg(Color::DarkGray)
192 .add_modifier(Modifier::BOLD | Modifier::UNDERLINED),
193 ));
194 cursor = abs_end;
195 } else {
196 spans.push(Span::styled(text[abs_start..].to_string(), base_style));
197 cursor = text.len();
198 break;
199 }
200 }
201
202 if cursor < text.len() {
203 spans.push(Span::styled(text[cursor..].to_string(), base_style));
204 }
205
206 spans
207}
208
209fn render_markdown_preview<'a>(
210 text: &'a str,
211 checklist_items: &[ChecklistItem],
212 selected_checklist: Option<usize>,
213 pane_focused: bool,
214 width: usize,
215) -> Vec<Line<'a>> {
216 if text.trim().is_empty() {
217 return vec![Line::from(Span::styled(
218 "(empty prompt body โ press 'a' to append content, 'E' to edit in $EDITOR)",
219 Style::default().fg(Color::DarkGray),
220 ))];
221 }
222
223 let mut out = Vec::new();
224 let mut in_code_block = false;
225
226 for (line_idx, raw_line) in text.lines().enumerate() {
227 let line_num = line_idx + 1;
228 let trimmed = raw_line.trim();
229
230 if trimmed.starts_with("```") || trimmed.starts_with("~~~") {
232 in_code_block = !in_code_block;
233 out.push(Line::from(Span::styled(
234 raw_line,
235 Style::default().fg(Color::DarkGray),
236 )));
237 continue;
238 }
239
240 if in_code_block {
241 out.push(Line::from(Span::styled(
242 format!(" {}", raw_line),
243 Style::default().fg(Color::Green),
244 )));
245 continue;
246 }
247
248 if let Some(item) = checklist_items.iter().find(|i| i.line_number == line_num) {
250 let is_selected_item = selected_checklist == Some(item.index);
251 let bullet_cursor = if is_selected_item && pane_focused {
252 "โถ "
253 } else {
254 " "
255 };
256
257 let mark_span = if item.completed {
258 Span::styled(
259 "[x] ",
260 Style::default()
261 .fg(Color::Green)
262 .add_modifier(Modifier::BOLD),
263 )
264 } else {
265 Span::styled(
266 "[ ] ",
267 Style::default()
268 .fg(Color::Cyan)
269 .add_modifier(Modifier::BOLD),
270 )
271 };
272
273 let text_style = if is_selected_item && pane_focused {
274 Style::default()
275 .fg(Color::White)
276 .bg(Color::DarkGray)
277 .add_modifier(Modifier::BOLD)
278 } else if item.completed {
279 Style::default()
280 .fg(Color::DarkGray)
281 .add_modifier(Modifier::CROSSED_OUT)
282 } else {
283 Style::default().fg(Color::White)
284 };
285
286 let cursor_style = if is_selected_item && pane_focused {
287 Style::default()
288 .fg(Color::LightCyan)
289 .add_modifier(Modifier::BOLD)
290 } else {
291 Style::default().fg(Color::DarkGray)
292 };
293
294 let mut line_spans = vec![
295 Span::styled(bullet_cursor, cursor_style),
296 Span::styled(item.indent.clone(), Style::default()),
297 mark_span,
298 ];
299 line_spans.extend(format_inline_with_variables(&item.text, text_style));
300
301 out.push(Line::from(line_spans));
302 continue;
303 }
304
305 if trimmed == "---" || trimmed == "***" || trimmed == "___" {
307 out.push(Line::from(Span::styled(
308 "โ".repeat(width.saturating_sub(2).max(10)),
309 Style::default().fg(Color::DarkGray),
310 )));
311 continue;
312 }
313
314 if trimmed.starts_with("# ") {
316 out.push(Line::from(Span::styled(
317 raw_line,
318 Style::default()
319 .fg(Color::Cyan)
320 .add_modifier(Modifier::BOLD | Modifier::UNDERLINED),
321 )));
322 } else if trimmed.starts_with("## ") {
323 out.push(Line::from(Span::styled(
324 raw_line,
325 Style::default()
326 .fg(Color::LightCyan)
327 .add_modifier(Modifier::BOLD),
328 )));
329 } else if trimmed.starts_with("### ") || trimmed.starts_with("#### ") {
330 out.push(Line::from(Span::styled(
331 raw_line,
332 Style::default()
333 .fg(Color::LightBlue)
334 .add_modifier(Modifier::BOLD),
335 )));
336 } else if trimmed.starts_with('>') {
337 out.push(Line::from(Span::styled(
338 raw_line,
339 Style::default()
340 .fg(Color::Blue)
341 .add_modifier(Modifier::ITALIC),
342 )));
343 } else if trimmed.starts_with('|') && trimmed.ends_with('|') {
344 out.push(Line::from(Span::styled(
346 raw_line,
347 Style::default().fg(Color::LightCyan),
348 )));
349 } else if let Some(rest) = trimmed.strip_prefix("- ").or_else(|| trimmed.strip_prefix("* "))
350 {
351 let indent = &raw_line[..(raw_line.len() - trimmed.len())];
352 let mut line_spans = vec![
353 Span::raw(indent.to_string()),
354 Span::styled("โข ", Style::default().fg(Color::Cyan)),
355 ];
356 line_spans.extend(format_inline_with_variables(rest, Style::default().fg(Color::White)));
357 out.push(Line::from(line_spans));
358 } else {
359 let spans = format_inline_with_variables(raw_line, Style::default().fg(Color::White));
360 out.push(Line::from(spans));
361 }
362 }
363
364 out
365}