返回 CodeWhale
display.rs
1 //! Gallery entries for package Display: the receipt, diff, tree and
2 //! progress. The toast's entries live in `toast.rs`.
3
4 use std::ops::Range;
5
6 use ratatui::{buffer::Buffer, layout::Rect};
7
8 use super::Entry;
9 use crate::{
10 CountBar, Diff, DiffGutter, DiffWrap, Paint, Receipt, ReceiptColumn, ReceiptDensity,
11 ReceiptTable, ReceiptValue, Role, State, Theme, TreeNode, TreeState, TurnSummary, WorkflowTree,
12 parse_unified,
13 };
14 use std::time::Duration;
15
16 use crate::Cost;
17
18 // ---------------------------------------------------------------------------
19 // Receipts
20 // ---------------------------------------------------------------------------
21
22 fn columns() -> Vec<ReceiptColumn> {
23 vec![
24 ReceiptColumn::new("Time").essential(),
25 ReceiptColumn::new("Tokens"),
26 ReceiptColumn::new("Cost").essential(),
27 ]
28 }
29
30 fn secs(s: u64) -> ReceiptValue {
31 ReceiptValue::Duration(Some(Duration::from_secs(s)))
32 }
33
34 /// Language text is outside the ASCII charter, but an ASCII-safe frame must
35 /// stay ASCII, so the fixtures swap in a Latin line there.
36 fn words(ascii: bool, text: &'static str, latin: &'static str) -> &'static str {
37 if ascii { latin } else { text }
38 }
39
40 fn rows(ascii: bool) -> Vec<Receipt> {
41 vec![
42 Receipt::new(State::Done, "Edited summary.md").values([
43 secs(4),
44 ReceiptValue::Tokens(Some(1_240)),
45 ReceiptValue::Cost(Some(Cost::usd_cents(1))),
46 ]),
47 Receipt::new(State::Failed, "Ran cargo test")
48 .values([
49 secs(72),
50 ReceiptValue::Tokens(Some(12_400)),
51 ReceiptValue::Cost(None),
52 ])
53 .opens(),
54 Receipt::new(State::Done, "Read 14 files").values([
55 ReceiptValue::Duration(Some(Duration::from_millis(850))),
56 ReceiptValue::Tokens(None),
57 ReceiptValue::Cost(Some(Cost::usd_cents(0))),
58 ]),
59 Receipt::new(State::Working, "Writing CHANGELOG.md").values([
60 secs(38),
61 ReceiptValue::Tokens(Some(96_300)),
62 ReceiptValue::Cost(Some(Cost::new(382_000, "$").estimate())),
63 ]),
64 Receipt::new(
65 State::Stopped,
66 words(
67 ascii,
68 "整理发布说明,翻译成中文",
69 "Translate the release notes",
70 ),
71 )
72 .values([
73 secs(3_720),
74 ReceiptValue::Tokens(Some(1_950_000)),
75 ReceiptValue::Cost(Some(Cost::usd_cents(1_240))),
76 ]),
77 ]
78 }
79
80 fn receipt_row(area: Rect, buf: &mut Buffer, theme: &Theme) {
81 Receipt::new(State::Done, "Edited summary.md")
82 .values([
83 secs(4),
84 ReceiptValue::Tokens(Some(1_240)),
85 ReceiptValue::Cost(Some(Cost::usd_cents(1))),
86 ])
87 .opens()
88 .paint(area, buf, theme);
89 }
90
91 fn table(density: Option<ReceiptDensity>, ascii: bool) -> ReceiptTable {
92 let table = ReceiptTable::new(columns(), rows(ascii))
93 .label_header("Action")
94 .totals();
95 match density {
96 Some(d) => table.density(d),
97 None => table,
98 }
99 }
100
101 fn receipt_table(area: Rect, buf: &mut Buffer, theme: &Theme) {
102 table(None, theme.ascii()).paint(area, buf, theme);
103 }
104
105 fn receipt_table_compact(area: Rect, buf: &mut Buffer, theme: &Theme) {
106 table(Some(ReceiptDensity::Compact), theme.ascii()).paint(area, buf, theme);
107 }
108
109 fn receipt_table_minimal(area: Rect, buf: &mut Buffer, theme: &Theme) {
110 table(Some(ReceiptDensity::Minimal), theme.ascii()).paint(area, buf, theme);
111 }
112
113 fn receipt_table_clipped(area: Rect, buf: &mut Buffer, theme: &Theme) {
114 table(None, theme.ascii()).paint(area, buf, theme);
115 }
116
117 fn turn_summary(area: Rect, buf: &mut Buffer, theme: &Theme) {
118 TurnSummary::new(Duration::from_secs(134), 6)
119 .tokens(12_400)
120 .cost(Cost::usd_cents(14))
121 .paint(area, buf, theme);
122 }
123
124 // ---------------------------------------------------------------------------
125 // Diff
126 // ---------------------------------------------------------------------------
127
128 const PATCH: &str = concat!(
129 "diff --git a/src/lib.rs b/src/lib.rs\n",
130 "index 3f2a1c9..8b7d4e0 100644\n",
131 "--- a/src/lib.rs\n",
132 "+++ b/src/lib.rs\n",
133 "@@ -10,5 +10,6 @@ fn main() {\n",
134 " fn main() {\n",
135 " let name = \"whale\";\n",
136 "- let depth = 1;\n",
137 "+ let depth = 2;\n",
138 "+ let pods = 3;\n",
139 " println!(\"{name}\");\n",
140 " }\n",
141 "@@ -40,3 +41,3 @@ impl Pod {\n",
142 " \tfn describe(&self) -> String {\n",
143 "-\t\tformat!(\"a pod of {} whales swimming together in the deep blue ocean at night\", self.count)\n",
144 "+\t\tformat!(\"a pod of {} whales swimming together in the deep blue ocean at dawn\", self.count)\n",
145 " \t}\n",
146 );
147
148 /// A hunk of language text, for terminals that can show it.
149 const CJK_HUNK: &str = concat!(
150 "@@ -70,2 +71,2 @@ impl Pod {\n",
151 "- let note = \"鲸鱼在深海里游动\";\n",
152 "+ let note = \"鲸鱼在深蓝的海里游动\";\n",
153 " }\n",
154 );
155
156 fn diff_lines<'a>(
157 patch: &'a str,
158 old: &'a [Range<usize>],
159 new: &'a [Range<usize>],
160 ) -> Vec<crate::DiffLine<'a>> {
161 let mut lines = parse_unified(patch);
162 for line in &mut lines {
163 if line.text.contains("at night") {
164 line.emphasis = old;
165 } else if line.text.contains("at dawn") {
166 line.emphasis = new;
167 }
168 }
169 lines
170 }
171
172 /// Where `word` sits in the text of the patch line containing `marker`
173 /// (the text starts after the sign).
174 fn word_range(marker: &str, word: &str) -> Vec<Range<usize>> {
175 let text = PATCH
176 .lines()
177 .find(|l| l.contains(marker))
178 .map_or("", |l| &l[1..]);
179 let at = text.find(word).unwrap_or(0);
180 std::iter::once(at..at + word.len()).collect()
181 }
182
183 fn paint_diff(area: Rect, buf: &mut Buffer, theme: &Theme, build: impl Fn(Diff) -> Diff) {
184 let old = word_range("at night", "night");
185 let new = word_range("at dawn", "dawn");
186 let patch = if theme.ascii() {
187 PATCH.to_string()
188 } else {
189 format!("{PATCH}{CJK_HUNK}")
190 };
191 build(Diff::new(diff_lines(&patch, &old, &new))).paint(area, buf, theme);
192 }
193
194 fn diff_truncated(area: Rect, buf: &mut Buffer, theme: &Theme) {
195 paint_diff(area, buf, theme, |d| d);
196 }
197
198 fn diff_wrapped(area: Rect, buf: &mut Buffer, theme: &Theme) {
199 paint_diff(area, buf, theme, |d| d.wrap(DiffWrap::Wrap));
200 }
201
202 fn diff_no_numbers(area: Rect, buf: &mut Buffer, theme: &Theme) {
203 paint_diff(area, buf, theme, |d| d.gutter(DiffGutter::Off).scroll(4));
204 }
205
206 /// A stand-in for a caller's highlighter: keywords in `Primary`, string
207 /// literals in `Muted`.
208 fn keywords(line: &str) -> Vec<(Range<usize>, Role)> {
209 let mut out = Vec::new();
210 for word in ["fn", "let", "impl", "format!", "println!"] {
211 let mut from = 0;
212 while let Some(at) = line[from..].find(word) {
213 let start = from + at;
214 out.push((start..start + word.len(), Role::Accent));
215 from = start + word.len();
216 }
217 }
218 if let (Some(open), Some(close)) = (line.find('"'), line.rfind('"'))
219 && close > open
220 {
221 out.push((open..close + 1, Role::Muted));
222 }
223 out
224 }
225
226 fn diff_highlighted(area: Rect, buf: &mut Buffer, theme: &Theme) {
227 paint_diff(area, buf, theme, |d| d.highlight(keywords).scroll(4));
228 }
229
230 // ---------------------------------------------------------------------------
231 // Tree
232 // ---------------------------------------------------------------------------
233
234 fn run() -> Vec<TreeNode> {
235 vec![
236 TreeNode::new(State::Working, "Release notes")
237 .detail("4m 06s")
238 .receipt("$0.38")
239 .children([
240 TreeNode::new(State::Done, "Gather")
241 .detail("3 agents")
242 .receipt("1m 12s")
243 .collapsed(true)
244 .children([
245 TreeNode::new(State::Done, "reader-1").receipt("40 s"),
246 TreeNode::new(State::Done, "reader-2").receipt("52 s"),
247 TreeNode::new(State::Done, "reader-3").receipt("1m 12s"),
248 ]),
249 TreeNode::new(State::Working, "Draft")
250 .detail("2 of 4 agents")
251 .children([
252 TreeNode::new(State::Working, "writer-1")
253 .detail("Editing CHANGELOG.md")
254 .receipt("38 s"),
255 TreeNode::new(State::Failed, "writer-2")
256 .detail("tests did not pass")
257 .opens(),
258 TreeNode::new(State::Ready, "writer-3"),
259 ]),
260 TreeNode::new(State::Ready, "Review"),
261 ]),
262 ]
263 }
264
265 fn workflow_tree(area: Rect, buf: &mut Buffer, theme: &Theme) {
266 let nodes = run();
267 WorkflowTree::new(&nodes).summary().paint(area, buf, theme);
268 }
269
270 fn workflow_tree_selected(area: Rect, buf: &mut Buffer, theme: &Theme) {
271 let nodes = run();
272 let mut state = TreeState::new();
273 state.selected = 4;
274 WorkflowTree::new(&nodes)
275 .state(&state)
276 .summary()
277 .paint(area, buf, theme);
278 }
279
280 fn workflow_tree_clipped(area: Rect, buf: &mut Buffer, theme: &Theme) {
281 let nodes = run();
282 let mut state = TreeState::new();
283 state.selected = 1;
284 WorkflowTree::new(&nodes)
285 .state(&state)
286 .summary()
287 .paint(area, buf, theme);
288 }
289
290 fn workflow_tree_long(area: Rect, buf: &mut Buffer, theme: &Theme) {
291 let ascii = theme.ascii();
292 let nodes = vec![
293 TreeNode::new(
294 State::NeedsYou,
295 words(
296 ascii,
297 "整理发布说明并翻译成中文,然后提交审阅",
298 "Tidy the release notes, translate them, then send for review",
299 ),
300 )
301 .detail(words(
302 ascii,
303 "等待你批准运行 cargo publish,这一步不能撤销",
304 "Waiting for you to approve cargo publish, which cannot be undone",
305 ))
306 .child(TreeNode::new(
307 State::Unknown,
308 "review-with-a-very-long-agent-name",
309 )),
310 ];
311 WorkflowTree::new(&nodes).paint(area, buf, theme);
312 }
313
314 // ---------------------------------------------------------------------------
315 // Progress
316 // ---------------------------------------------------------------------------
317
318 fn count_bars(area: Rect, buf: &mut Buffer, theme: &Theme) {
319 let bars = [
320 CountBar::new(3, 5).label("phases"),
321 CountBar::new(0, 5).label("files"),
322 CountBar::new(5, 5).label("phases").state(State::Done),
323 CountBar::new(7, 5).label("checks").state(State::NeedsYou),
324 CountBar::unknown(12).label("files"),
325 CountBar::new(0, 0).label("tasks").state(State::Ready),
326 ];
327 for (row, bar) in bars.iter().enumerate() {
328 let Some(y) = area
329 .y
330 .checked_add(row as u16)
331 .filter(|y| *y < area.bottom())
332 else {
333 break;
334 };
335 bar.paint(Rect::new(area.x, y, area.width, 1), buf, theme);
336 }
337 }
338
339 pub(crate) fn entries() -> Vec<Entry> {
340 vec![
341 Entry {
342 name: "receipt-row",
343 width: 60,
344 height: 1,
345 draw: receipt_row,
346 },
347 Entry {
348 name: "receipt-table",
349 width: 80,
350 height: 8,
351 draw: receipt_table,
352 },
353 Entry {
354 name: "receipt-table-compact",
355 width: 56,
356 height: 7,
357 draw: receipt_table_compact,
358 },
359 Entry {
360 name: "receipt-table-minimal",
361 width: 40,
362 height: 7,
363 draw: receipt_table_minimal,
364 },
365 Entry {
366 name: "receipt-table-clipped",
367 width: 80,
368 height: 5,
369 draw: receipt_table_clipped,
370 },
371 Entry {
372 name: "turn-summary",
373 width: 60,
374 height: 1,
375 draw: turn_summary,
376 },
377 Entry {
378 name: "diff",
379 width: 80,
380 height: 22,
381 draw: diff_truncated,
382 },
383 Entry {
384 name: "diff-wrapped",
385 width: 48,
386 height: 26,
387 draw: diff_wrapped,
388 },
389 Entry {
390 name: "diff-no-numbers",
391 width: 60,
392 height: 10,
393 draw: diff_no_numbers,
394 },
395 Entry {
396 name: "diff-highlighted",
397 width: 80,
398 height: 12,
399 draw: diff_highlighted,
400 },
401 Entry {
402 name: "workflow-tree",
403 width: 64,
404 height: 9,
405 draw: workflow_tree,
406 },
407 Entry {
408 name: "workflow-tree-selected",
409 width: 64,
410 height: 9,
411 draw: workflow_tree_selected,
412 },
413 Entry {
414 name: "workflow-tree-clipped",
415 width: 64,
416 height: 6,
417 draw: workflow_tree_clipped,
418 },
419 Entry {
420 name: "workflow-tree-long",
421 width: 48,
422 height: 3,
423 draw: workflow_tree_long,
424 },
425 Entry {
426 name: "count-bars",
427 width: 60,
428 height: 6,
429 draw: count_bars,
430 },
431 ]
432 }
433
433 lines RUST