返回 CodeWhale
workbench.rs
1 //! Composable workspace geometry, quiet module headers, composer context,
2 //! and the optional Codewhale workbar. Everything shown is a caller fact;
3 //! these components own neither a session nor a timer.
4
5 use std::borrow::Cow;
6
7 use ratatui::{
8 buffer::Buffer,
9 layout::Rect,
10 style::Modifier,
11 text::{Line, Span},
12 };
13
14 use crate::{Paint, Role, Theme, text};
15
16 /// Paint one clipped row without asking a terminal widget to walk beyond
17 /// an offset buffer or the last representable terminal coordinate.
18 pub(crate) fn row(area: Rect, buf: &mut Buffer, line: &Line<'_>) {
19 let area = area.intersection(buf.area);
20 if !area.is_empty() {
21 buf.set_line(area.x, area.y, line, area.width);
22 }
23 }
24
25 fn safe(value: &str) -> String {
26 text::display_safe(value).into_owned()
27 }
28
29 fn rule(area: Rect, buf: &mut Buffer, theme: &Theme) {
30 let mark = if theme.ascii() { "-" } else { "─" };
31 row(
32 area,
33 buf,
34 &Line::styled(mark.repeat(usize::from(area.width)), theme.fg(Role::Border)),
35 );
36 }
37
38 /// Regions inside a [`WorkspaceFrame`]. A hidden side pane receives no
39 /// rectangle: the host can expose it through its own Details action.
40 #[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
41 pub struct WorkspaceAreas {
42 pub main: Rect,
43 pub side: Option<Rect>,
44 pub footer: Rect,
45 }
46
47 /// A project and branch header, reading canvas, optional inset dock, and a
48 /// quiet footer. The host paints its conversation and modules in `areas()`.
49 #[derive(Clone, Debug)]
50 pub struct WorkspaceFrame<'a> {
51 pub project: Cow<'a, str>,
52 pub branch: Cow<'a, str>,
53 pub mode: Cow<'a, str>,
54 pub footer: Cow<'a, str>,
55 pub side_width: u16,
56 pub minimum_main_width: u16,
57 }
58
59 impl<'a> WorkspaceFrame<'a> {
60 #[must_use]
61 pub fn new(project: impl Into<Cow<'a, str>>) -> Self {
62 Self {
63 project: project.into(),
64 branch: Cow::Borrowed(""),
65 mode: Cow::Borrowed("Workspace"),
66 footer: Cow::Borrowed(""),
67 side_width: 36,
68 minimum_main_width: 56,
69 }
70 }
71 #[must_use]
72 pub fn branch(mut self, branch: impl Into<Cow<'a, str>>) -> Self {
73 self.branch = branch.into();
74 self
75 }
76 #[must_use]
77 pub fn mode(mut self, mode: impl Into<Cow<'a, str>>) -> Self {
78 self.mode = mode.into();
79 self
80 }
81 #[must_use]
82 pub fn footer(mut self, footer: impl Into<Cow<'a, str>>) -> Self {
83 self.footer = footer.into();
84 self
85 }
86 #[must_use]
87 pub fn side_width(mut self, width: u16) -> Self {
88 self.side_width = width;
89 self
90 }
91 #[must_use]
92 pub fn minimum_main_width(mut self, width: u16) -> Self {
93 self.minimum_main_width = width;
94 self
95 }
96
97 /// Layout is pure and deterministic. Pass the intersection of the
98 /// requested area and the buffer when painting into an offset buffer.
99 #[must_use]
100 pub fn areas(&self, area: Rect) -> WorkspaceAreas {
101 if area.is_empty() {
102 return WorkspaceAreas::default();
103 }
104 let header = if area.height >= 4 { 3 } else { 1 };
105 let footer_height = u16::from(area.height > header + 1);
106 let footer = Rect::new(
107 area.x,
108 area.bottom().saturating_sub(footer_height),
109 area.width,
110 footer_height,
111 );
112 let body = Rect::new(
113 area.x,
114 area.y.saturating_add(header),
115 area.width,
116 area.height.saturating_sub(header + footer_height),
117 );
118 let gutter = u16::from(area.width >= 8) * 2;
119 let required = usize::from(self.minimum_main_width)
120 + usize::from(self.side_width)
121 + usize::from(2 * gutter)
122 + 1;
123 let side_visible = self.side_width >= 8 && usize::from(body.width) >= required;
124 if side_visible {
125 let split = body.right().saturating_sub(self.side_width + 1);
126 WorkspaceAreas {
127 main: Rect::new(
128 body.x.saturating_add(gutter),
129 body.y,
130 split.saturating_sub(body.x).saturating_sub(2 * gutter),
131 body.height,
132 ),
133 side: Some(Rect::new(
134 split.saturating_add(3),
135 body.y,
136 self.side_width.saturating_sub(4),
137 body.height,
138 )),
139 footer,
140 }
141 } else {
142 WorkspaceAreas {
143 main: Rect::new(
144 body.x.saturating_add(gutter),
145 body.y,
146 body.width.saturating_sub(2 * gutter),
147 body.height,
148 ),
149 side: None,
150 footer,
151 }
152 }
153 }
154 }
155
156 impl Paint for WorkspaceFrame<'_> {
157 fn paint(&self, area: Rect, buf: &mut Buffer, theme: &Theme) {
158 let area = area.intersection(buf.area);
159 if area.is_empty() {
160 return;
161 }
162 buf.set_style(
163 area,
164 theme.bg(Role::Background).patch(theme.fg(Role::Foreground)),
165 );
166 let gutter = u16::from(area.width >= 8) * 2;
167 let header = Rect::new(
168 area.x.saturating_add(gutter),
169 area.y,
170 area.width.saturating_sub(2 * gutter),
171 1,
172 );
173 let identity = if self.branch.is_empty() {
174 safe(&self.project)
175 } else {
176 format!("{} / {}", safe(&self.project), safe(&self.branch))
177 };
178 let brand = "Codewhale";
179 let mode = safe(&self.mode);
180 let mode_width = text::width(&mode);
181 let reserve = if usize::from(header.width) > 48 + mode_width {
182 mode_width + 2
183 } else {
184 0
185 };
186 let left = usize::from(header.width).saturating_sub(reserve);
187 let mut spans = vec![Span::styled(
188 text::truncate(brand, left, theme.ascii()).into_owned(),
189 theme.fg(Role::Accent).add_modifier(Modifier::BOLD),
190 )];
191 if left > brand.len() + 3 {
192 spans.push(Span::styled(" / ", theme.fg(Role::BorderStrong)));
193 spans.push(Span::styled(
194 text::truncate_words(
195 &identity,
196 left.saturating_sub(brand.len() + 5),
197 theme.ascii(),
198 )
199 .into_owned(),
200 theme.fg(Role::Muted),
201 ));
202 }
203 row(header, buf, &Line::from(spans));
204 if reserve > 0 {
205 row(
206 Rect::new(
207 header.right().saturating_sub(mode_width as u16),
208 header.y,
209 mode_width as u16,
210 1,
211 ),
212 buf,
213 &Line::styled(
214 mode,
215 theme.fg(Role::Foreground).add_modifier(Modifier::BOLD),
216 ),
217 );
218 }
219 if area.height >= 4 {
220 rule(
221 Rect::new(area.x, area.y.saturating_add(1), area.width, 1),
222 buf,
223 theme,
224 );
225 }
226 let regions = self.areas(area);
227 if let Some(side) = regions.side {
228 let panel = Rect::new(
229 side.x.saturating_sub(2),
230 area.y.saturating_add(2),
231 side.width.saturating_add(4),
232 regions.footer.y.saturating_sub(area.y.saturating_add(2)),
233 );
234 buf.set_style(panel, theme.bg(Role::Sidebar));
235 let x = panel.x.saturating_sub(1);
236 for y in panel.y..panel.bottom() {
237 row(
238 Rect::new(x, y, 1, 1),
239 buf,
240 &Line::styled(
241 if theme.ascii() { "|" } else { "│" },
242 theme.fg(Role::Border),
243 ),
244 );
245 }
246 }
247 if !regions.footer.is_empty() {
248 buf.set_style(regions.footer, theme.bg(Role::Sidebar));
249 row(
250 Rect::new(
251 regions.footer.x.saturating_add(gutter),
252 regions.footer.y,
253 regions.footer.width.saturating_sub(2 * gutter),
254 1,
255 ),
256 buf,
257 &Line::styled(
258 text::truncate_words(
259 &safe(&self.footer),
260 usize::from(regions.footer.width.saturating_sub(2 * gutter)),
261 theme.ascii(),
262 )
263 .into_owned(),
264 theme.fg(Role::Muted),
265 ),
266 );
267 }
268 }
269 }
270
271 /// One thin module title and optional right-aligned fact, with a hairline.
272 #[derive(Clone, Debug)]
273 pub struct PaneHeader<'a> {
274 pub title: Cow<'a, str>,
275 pub meta: Cow<'a, str>,
276 pub focused: bool,
277 pub divider: bool,
278 /// Optional right-aligned item count pill shown beside `meta`.
279 pub count: Option<usize>,
280 }
281 impl<'a> PaneHeader<'a> {
282 #[must_use]
283 pub fn new(title: impl Into<Cow<'a, str>>) -> Self {
284 Self {
285 title: title.into(),
286 meta: Cow::Borrowed(""),
287 focused: false,
288 divider: true,
289 count: None,
290 }
291 }
292 #[must_use]
293 pub fn meta(mut self, meta: impl Into<Cow<'a, str>>) -> Self {
294 self.meta = meta.into();
295 self
296 }
297 #[must_use]
298 pub fn focused(mut self, focused: bool) -> Self {
299 self.focused = focused;
300 self
301 }
302 #[must_use]
303 pub fn divider(mut self, divider: bool) -> Self {
304 self.divider = divider;
305 self
306 }
307 /// Show a right-aligned count pill in the header.
308 #[must_use]
309 pub const fn count(mut self, count: usize) -> Self {
310 self.count = Some(count);
311 self
312 }
313 }
314 impl Paint for PaneHeader<'_> {
315 fn paint(&self, area: Rect, buf: &mut Buffer, theme: &Theme) {
316 let area = area.intersection(buf.area);
317 if area.is_empty() {
318 return;
319 }
320 let title = safe(&self.title);
321 let meta = safe(&self.meta);
322 let count_pill = self.count.map(|n| format!(" {n} "));
323 let pill_width = count_pill.as_deref().map_or(0, text::width);
324 let meta_width = text::width(&meta);
325 let right_width = match (meta_width > 0, pill_width > 0) {
326 (true, true) => meta_width + 1 + pill_width,
327 (true, false) => meta_width,
328 (false, true) => pill_width,
329 (false, false) => 0,
330 };
331 let show_right =
332 right_width > 0 && right_width + text::width(&title) + 2 <= usize::from(area.width);
333 let show_pill_only =
334 !show_right && pill_width > 0 && pill_width + 2 < usize::from(area.width);
335 let reserved = if show_right {
336 right_width + 2
337 } else if show_pill_only {
338 pill_width + 2
339 } else {
340 0
341 };
342 let width = usize::from(area.width).saturating_sub(reserved);
343 row(
344 area,
345 buf,
346 &Line::styled(
347 text::truncate_words(&title, width, theme.ascii()).into_owned(),
348 theme.fg(Role::Foreground).add_modifier(Modifier::BOLD),
349 ),
350 );
351 if show_right {
352 let mut spans = Vec::new();
353 if meta_width > 0 {
354 spans.push(Span::styled(meta, theme.fg(Role::Muted)));
355 }
356 if let Some(pill) = count_pill {
357 if meta_width > 0 {
358 spans.push(Span::raw(" "));
359 }
360 spans.push(Span::styled(
361 pill,
362 theme.fg(Role::Muted).patch(theme.bg(Role::Surface)),
363 ));
364 }
365 row(
366 Rect::new(
367 area.right().saturating_sub(right_width as u16),
368 area.y,
369 right_width as u16,
370 1,
371 ),
372 buf,
373 &Line::from(spans),
374 );
375 } else if show_pill_only && let Some(pill) = count_pill {
376 row(
377 Rect::new(
378 area.right().saturating_sub(pill_width as u16),
379 area.y,
380 pill_width as u16,
381 1,
382 ),
383 buf,
384 &Line::styled(pill, theme.fg(Role::Muted).patch(theme.bg(Role::Surface))),
385 );
386 }
387 if self.divider && area.height > 1 {
388 rule(
389 Rect::new(area.x, area.y.saturating_add(1), area.width, 1),
390 buf,
391 theme,
392 );
393 }
394 if self.focused {
395 row(
396 Rect::new(
397 area.x,
398 area.y
399 .saturating_add(u16::from(self.divider && area.height > 1)),
400 1,
401 1,
402 ),
403 buf,
404 &Line::styled(
405 if theme.ascii() { ">" } else { "╸" },
406 theme.fg(Role::Accent),
407 ),
408 );
409 }
410 }
411 fn height(&self, _width: u16, _theme: &Theme) -> u16 {
412 1 + u16::from(self.divider)
413 }
414 }
415
416 /// A composer-adjacent fact. Larger priorities survive a narrow ribbon.
417 #[derive(Clone, Debug)]
418 pub struct ContextItem<'a> {
419 pub label: Cow<'a, str>,
420 pub value: Cow<'a, str>,
421 pub priority: u8,
422 pub role: Role,
423 }
424 impl<'a> ContextItem<'a> {
425 #[must_use]
426 pub fn new(label: impl Into<Cow<'a, str>>, value: impl Into<Cow<'a, str>>) -> Self {
427 Self {
428 label: label.into(),
429 value: value.into(),
430 priority: 0,
431 role: Role::Foreground,
432 }
433 }
434 #[must_use]
435 pub fn priority(mut self, priority: u8) -> Self {
436 self.priority = priority;
437 self
438 }
439 #[must_use]
440 pub fn role(mut self, role: Role) -> Self {
441 self.role = role;
442 self
443 }
444 fn content(&self) -> String {
445 if self.label.is_empty() {
446 safe(&self.value)
447 } else {
448 format!("{} {}", safe(&self.label), safe(&self.value))
449 }
450 }
451 }
452
453 /// Facts in declaration order, folded by priority with an explicit count.
454 #[derive(Clone, Debug)]
455 pub struct ContextRibbon<'a> {
456 pub items: Vec<ContextItem<'a>>,
457 pub details_label: Cow<'a, str>,
458 }
459 impl<'a> ContextRibbon<'a> {
460 #[must_use]
461 pub fn new(items: Vec<ContextItem<'a>>) -> Self {
462 Self {
463 items,
464 details_label: Cow::Borrowed("details"),
465 }
466 }
467 #[must_use]
468 pub fn details_label(mut self, label: impl Into<Cow<'a, str>>) -> Self {
469 self.details_label = label.into();
470 self
471 }
472 }
473 impl Paint for ContextRibbon<'_> {
474 fn paint(&self, area: Rect, buf: &mut Buffer, theme: &Theme) {
475 let area = area.intersection(buf.area);
476 if area.is_empty() || self.items.is_empty() {
477 return;
478 }
479 let separator = if theme.ascii() { " / " } else { " · " };
480 let mut kept: Vec<usize> = (0..self.items.len()).collect();
481 loop {
482 let omitted = self.items.len() - kept.len();
483 let more = if omitted == 0 {
484 String::new()
485 } else {
486 format!("+{omitted} {}", safe(&self.details_label))
487 };
488 if kept.len() == 1 && omitted > 0 && usize::from(area.width) <= text::width(&more) + 3 {
489 kept.clear();
490 continue;
491 }
492 let total = kept
493 .iter()
494 .map(|&i| text::width(&self.items[i].content()))
495 .sum::<usize>()
496 + 3 * kept.len().saturating_sub(1)
497 + if omitted > 0 {
498 usize::from(!kept.is_empty()) * 3 + text::width(&more)
499 } else {
500 0
501 };
502 if total <= usize::from(area.width) || kept.len() <= 1 {
503 let remaining = if kept.is_empty() {
504 0
505 } else {
506 usize::from(area.width).saturating_sub(if omitted > 0 {
507 text::width(&more) + 3
508 } else {
509 0
510 })
511 };
512 let mut spans = Vec::new();
513 for (position, &index) in kept.iter().enumerate() {
514 if position > 0 {
515 spans.push(Span::styled(separator, theme.fg(Role::BorderStrong)));
516 }
517 let value = self.items[index].content();
518 let fitted = if kept.len() == 1 {
519 text::truncate_words(&value, remaining, theme.ascii()).into_owned()
520 } else {
521 value
522 };
523 spans.push(Span::styled(fitted, theme.fg(self.items[index].role)));
524 }
525 if omitted > 0 {
526 if remaining > 0 {
527 spans.push(Span::styled(separator, theme.fg(Role::BorderStrong)));
528 }
529 spans.push(Span::styled(
530 text::truncate_words(
531 &more,
532 usize::from(area.width)
533 .saturating_sub(remaining + usize::from(remaining > 0) * 3),
534 theme.ascii(),
535 )
536 .into_owned(),
537 theme.fg(Role::Muted),
538 ));
539 }
540 row(area, buf, &Line::from(spans));
541 break;
542 }
543 let drop = kept
544 .iter()
545 .enumerate()
546 .min_by_key(|&(position, &index)| {
547 (self.items[index].priority, std::cmp::Reverse(position))
548 })
549 .map(|(position, _)| position)
550 .unwrap_or(0);
551 kept.remove(drop);
552 }
553 }
554 }
555
555 lines RUST