返回 CodeWhale
surface.rs
1 //! Panels with depth, and the one horizon.
2 //!
3 //! Depth is elevation: raised things sit nearer the surface, the stage and
4 //! things put away sit deeper. Where the terminal paints grounds, depth is a
5 //! ground; where it cannot (16 colors, `NO_COLOR`, an unmeasured ground, or a
6 //! depth where two grounds quantize to one color), depth becomes an edge,
7 //! because a fill nobody can see separates nothing.
8 //!
9 //! Replaces the engine's three modal treatments (`render_modal_surface` with
10 //! its shadow, `render_underwater_surface` with its two rules, and hand-rolled
11 //! `Clear` blocks) and lifts `centered_modal_area` (`crates/tui/src/tui/
12 //! views/mod.rs`, `Hmbown/CodeWhale` `58b1dd3dd`).
13
14 use std::borrow::Cow;
15
16 use ratatui::{
17 buffer::Buffer,
18 layout::Rect,
19 style::{Modifier, Style},
20 symbols::border,
21 text::{Line, Span},
22 widgets::{Block, Borders, Clear, Paragraph, Widget},
23 };
24
25 use crate::{KeyHints, Paint, Role, Theme, color, detect::Appearance, glyphs, text};
26
27 /// How far from the surface a panel sits.
28 #[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
29 pub enum Depth {
30 /// Rails and things put away.
31 Deep,
32 /// The stage: full-screen sheets. No edge; a two-cell gutter.
33 Stage,
34 /// Tonal elevation: borderless `Role::Surface` fill where terminal grounds
35 /// differ, degrading to a quiet left rail (`▏` / `|`) in `Role::Border`
36 /// when grounds cannot be distinguished.
37 Tonal,
38 /// A card on the stage.
39 Raised,
40 /// A decision over everything else: always edged in `BorderStrong`.
41 Overlay,
42 }
43
44 impl Depth {
45 #[must_use]
46 pub const fn ground(self) -> Role {
47 match self {
48 Depth::Deep => Role::Sidebar,
49 Depth::Stage => Role::Background,
50 Depth::Tonal | Depth::Raised | Depth::Overlay => Role::Surface,
51 }
52 }
53 }
54
55 fn surface_grounds_collapse(theme: &Theme) -> bool {
56 !theme.grounds_differ(Role::Surface, Role::Background)
57 || (theme.depth() == color::ColorDepth::Ansi256
58 && theme
59 .bg(Role::Surface)
60 .bg
61 .zip(theme.bg(Role::Background).bg)
62 .and_then(|(surface, background)| color::contrast_ratio(surface, background))
63 .is_some_and(|contrast| contrast < 1.2))
64 }
65
66 /// A titled panel. [`Panel::draw`] paints it and returns the content area.
67 #[derive(Clone, Debug)]
68 pub struct Panel<'a> {
69 pub title: Option<Cow<'a, str>>,
70 /// Muted text at the right of the title row: a count, "changed 2 min ago".
71 pub aside: Option<Cow<'a, str>>,
72 pub depth: Depth,
73 /// Light the edge or gutter in `Primary`: this panel has the keyboard.
74 pub focused: bool,
75 pub hints: Option<&'a KeyHints>,
76 specular: bool,
77 shadow: bool,
78 }
79
80 impl<'a> Panel<'a> {
81 #[must_use]
82 pub fn new(depth: Depth) -> Self {
83 Self {
84 title: None,
85 aside: None,
86 depth,
87 focused: false,
88 hints: None,
89 specular: false,
90 shadow: false,
91 }
92 }
93
94 /// A tonal panel: borderless `Role::Surface` fill where terminal grounds
95 /// differ, degrading to a quiet left rail (`▏` / `|`) in `Role::Border`
96 /// where grounds collapse.
97 #[must_use]
98 pub fn tonal() -> Self {
99 Self::new(Depth::Tonal)
100 }
101
102 #[must_use]
103 pub fn title(mut self, title: impl Into<Cow<'a, str>>) -> Self {
104 self.title = Some(title.into());
105 self
106 }
107
108 #[must_use]
109 pub fn aside(mut self, aside: impl Into<Cow<'a, str>>) -> Self {
110 self.aside = Some(aside.into());
111 self
112 }
113
114 #[must_use]
115 pub fn focused(mut self, focused: bool) -> Self {
116 self.focused = focused;
117 self
118 }
119
120 #[must_use]
121 pub fn hints(mut self, hints: &'a KeyHints) -> Self {
122 self.hints = Some(hints);
123 self
124 }
125
126 /// Apply an OKLab overhead specular rim gradient to edged panel borders on
127 /// truecolor terminals with painted grounds.
128 #[must_use]
129 pub fn specular(mut self, enabled: bool) -> Self {
130 self.specular = enabled;
131 self
132 }
133
134 /// Cast a translucent buffer-blended OKLab drop shadow outside the panel
135 /// bounds on truecolor terminals with painted grounds.
136 #[must_use]
137 pub fn shadow(mut self, enabled: bool) -> Self {
138 self.shadow = enabled;
139 self
140 }
141
142 pub(crate) fn edged(&self, theme: &Theme) -> bool {
143 match self.depth {
144 Depth::Overlay => true,
145 Depth::Raised => surface_grounds_collapse(theme),
146 Depth::Deep | Depth::Stage | Depth::Tonal => false,
147 }
148 }
149
150 fn tonal_rail(&self, theme: &Theme) -> bool {
151 self.depth == Depth::Tonal && surface_grounds_collapse(theme)
152 }
153
154 /// Where everything goes in `area`, without painting. [`Panel::draw`]
155 /// paints from this, and [`Panel::body`] and [`Dialog`] size from it, so
156 /// the three cannot disagree.
157 fn layout(&self, area: Rect, theme: &Theme) -> PanelLayout {
158 let edged = self.edged(theme);
159 let mut inner = area;
160 if edged {
161 inner = Block::default().borders(Borders::ALL).inner(area);
162 }
163
164 let gutter = match self.depth {
165 Depth::Stage if inner.width >= 24 => 2,
166 _ if inner.width >= 8 => 1,
167 _ => 0,
168 };
169 let vpad = u16::from(edged && inner.height >= 6);
170 inner = Rect {
171 x: inner.x + gutter,
172 y: inner.y + vpad,
173 width: inner.width.saturating_sub(gutter * 2),
174 height: inner.height.saturating_sub(vpad * 2),
175 };
176 if gutter == 0 && self.tonal_rail(theme) && inner.width >= 2 {
177 inner.x += 1;
178 inner.width -= 1;
179 }
180
181 let mut title_row = None;
182 if self.title.is_some() && inner.height > 0 {
183 title_row = Some(Rect { height: 1, ..inner });
184 let used = 1 + u16::from(inner.height >= 6);
185 inner.y += used.min(inner.height);
186 inner.height = inner.height.saturating_sub(used);
187 }
188
189 let mut rail = None;
190 if let Some(hints) = self.hints {
191 let lines = hints.lines(inner.width, theme);
192 let h = u16::try_from(lines.len())
193 .unwrap_or(u16::MAX)
194 .min(inner.height);
195 if h > 0 {
196 let rect = Rect {
197 y: inner.bottom() - h,
198 height: h,
199 ..inner
200 };
201 rail = Some((rect, lines));
202 let gap = u16::from(inner.height >= h + 4);
203 inner.height = inner.height.saturating_sub(h + gap);
204 }
205 }
206 PanelLayout {
207 edged,
208 title_row,
209 rail,
210 body: inner,
211 }
212 }
213
214 /// The content area [`Panel::draw`] returns for `area`, without
215 /// painting: for sizing a popup to what goes in it.
216 #[must_use]
217 pub fn body(&self, area: Rect, theme: &Theme) -> Rect {
218 if area.is_empty() {
219 return area;
220 }
221 self.layout(area, theme).body
222 }
223
224 /// Paint the panel and return the area left for content.
225 pub fn draw(&self, area: Rect, buf: &mut Buffer, theme: &Theme) -> Rect {
226 let area = area.intersection(buf.area);
227 if area.is_empty() {
228 return area;
229 }
230 if self.shadow {
231 paint_drop_shadow(area, buf.area, buf, theme);
232 }
233 Clear.render(area, buf);
234 let ground = theme.bg(self.depth.ground());
235 buf.set_style(area, ground);
236
237 let layout = self.layout(area, theme);
238 if layout.edged {
239 let edge_role = if self.focused {
240 Role::Accent
241 } else if self.depth == Depth::Overlay
242 || (self.depth == Depth::Raised && theme.depth() == color::ColorDepth::Ansi256)
243 {
244 Role::BorderStrong
245 } else {
246 Role::Border
247 };
248 let set = if theme.ascii() {
249 border::Set {
250 top_left: "+",
251 top_right: "+",
252 bottom_left: "+",
253 bottom_right: "+",
254 vertical_left: "|",
255 vertical_right: "|",
256 horizontal_top: "-",
257 horizontal_bottom: "-",
258 }
259 } else {
260 border::ROUNDED
261 };
262 Block::default()
263 .borders(Borders::ALL)
264 .border_set(set)
265 .border_style(theme.fg(edge_role).patch(ground))
266 .render(area, buf);
267 if self.specular {
268 paint_specular_border(area, buf, theme, self.focused);
269 }
270 } else if self.focused && area.width >= 8 {
271 for y in area.y..area.bottom() {
272 buf[(area.x, y)]
273 .set_symbol(glyphs::pick("▏", theme.ascii()))
274 .set_style(theme.fg(Role::Accent).patch(ground));
275 }
276 } else if self.tonal_rail(theme) && area.width >= 2 {
277 for y in area.y..area.bottom() {
278 buf[(area.x, y)]
279 .set_symbol(glyphs::pick("▏", theme.ascii()))
280 .set_style(theme.fg(Role::Border).patch(ground));
281 }
282 }
283
284 if let (Some(title), Some(row)) = (&self.title, layout.title_row) {
285 let title = text::display_safe(title);
286 // The title keeps its room: an aside that cannot sit beside it
287 // is cut to a third of the row, or dropped.
288 let row_w = usize::from(row.width);
289 let aside = self.aside.as_deref().map(text::display_safe).and_then(|a| {
290 if text::width(&title) + 2 + text::width(&a) <= row_w {
291 Some(a.into_owned())
292 } else {
293 let cut = text::truncate(&a, row_w / 3, theme.ascii());
294 (row_w / 3 >= 4 && !cut.is_empty()).then(|| cut.into_owned())
295 }
296 });
297 let aside_w = aside.as_deref().map_or(0, |a| text::width(a) + 2);
298 let title_w = row_w.saturating_sub(aside_w);
299 let title = text::truncate(&title, title_w, theme.ascii());
300 Line::from(Span::styled(
301 title.into_owned(),
302 theme.fg(Role::Foreground).add_modifier(Modifier::BOLD),
303 ))
304 .render(row, buf);
305 if let Some(aside) = aside
306 && aside_w > 0
307 && aside_w <= usize::from(row.width)
308 {
309 Line::from(Span::styled(aside, theme.fg(Role::Muted)))
310 .right_aligned()
311 .render(row, buf);
312 }
313 }
314
315 if let Some((rect, lines)) = layout.rail {
316 Paragraph::new(lines).render(rect, buf);
317 }
318 layout.body
319 }
320 }
321
322 /// The geometry of a [`Panel`] in an area.
323 struct PanelLayout {
324 edged: bool,
325 title_row: Option<Rect>,
326 rail: Option<(Rect, Vec<Line<'static>>)>,
327 body: Rect,
328 }
329
330 impl Paint for Panel<'_> {
331 fn paint(&self, area: Rect, buf: &mut Buffer, theme: &Theme) {
332 self.draw(area, buf, theme);
333 }
334 }
335
336 /// A centered popup rect: starts from the preferred size, never exceeds the
337 /// frame (keeping a one-cell margin when it can), and never drops below the
338 /// minimum unless the frame is smaller. From the engine's
339 /// `centered_modal_area` (#3732).
340 #[must_use]
341 pub fn centered(
342 area: Rect,
343 preferred_width: u16,
344 preferred_height: u16,
345 min_width: u16,
346 min_height: u16,
347 ) -> Rect {
348 if area.is_empty() {
349 return area;
350 }
351 let avail_width = area.width.saturating_sub(2).max(1);
352 let avail_height = area.height.saturating_sub(2).max(1);
353 let width = preferred_width.clamp(min_width.min(avail_width), avail_width);
354 let height = preferred_height.clamp(min_height.min(avail_height), avail_height);
355 Rect {
356 x: area.x + area.width.saturating_sub(width) / 2,
357 y: area.y + area.height.saturating_sub(height) / 2,
358 width,
359 height,
360 }
361 }
362
363 /// How wide a [`Dialog`] wants to be before the terminal clamps it.
364 #[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash)]
365 pub enum DialogWidth {
366 /// A yes-or-no question: 48 cells.
367 Narrow,
368 /// Most decisions: 60 cells.
369 #[default]
370 Standard,
371 /// Detail worth reading before deciding: 72 cells.
372 Wide,
373 }
374
375 impl DialogWidth {
376 /// The preferred width in cells.
377 #[must_use]
378 pub const fn cells(self) -> u16 {
379 match self {
380 DialogWidth::Narrow => 48,
381 DialogWidth::Standard => 60,
382 DialogWidth::Wide => 72,
383 }
384 }
385 }
386
387 /// `preferred` cells of a `total`-cell axis, leaving `margin` cells of
388 /// backdrop when the axis can spare them, never below `floor` unless the
389 /// axis itself is smaller, and never more than the axis.
390 fn fit_axis(total: u16, preferred: u16, margin: u16, floor: u16) -> u16 {
391 preferred.min(total.saturating_sub(margin).max(floor.min(total)))
392 }
393
394 /// A decision, centered over everything else: confirmations, approvals,
395 /// destructive actions. Always edged in `BorderStrong`, so it stays legible
396 /// where grounds do not paint (16 colors, `NO_COLOR`), with rounded corners
397 /// and no shadow. Replaces the engine's modal surface with its shadow and
398 /// the hand-rolled `Clear` blocks.
399 ///
400 /// ```
401 /// # use codewhale_ratatui::{Dialog, DialogWidth, KeyHint, KeyHints, Theme};
402 /// # use ratatui::{buffer::Buffer, layout::Rect};
403 /// # let (theme, area) = (Theme::detect(), Rect::new(0, 0, 80, 24));
404 /// # let mut buf = Buffer::empty(area);
405 /// let hints = KeyHints::new(vec![KeyHint::new("y", "stop"), KeyHint::new("n", "keep running")]);
406 /// let body = Dialog::new()
407 /// .title("Stop the running workflow?")
408 /// .width(DialogWidth::Narrow)
409 /// .body_rows(2)
410 /// .hints(&hints)
411 /// .draw(area, &mut buf, &theme);
412 /// // paint the question into `body`
413 /// # let _ = body;
414 /// ```
415 #[derive(Clone, Debug, Default)]
416 pub struct Dialog<'a> {
417 pub title: Option<Cow<'a, str>>,
418 pub width: DialogWidth,
419 /// Rows of body the caller will fill. The dialog is as tall as that
420 /// needs, with padding and a blank row between its parts, then clamped
421 /// to the terminal. The body it returns has at least this many rows
422 /// unless the terminal is too short.
423 pub body_rows: u16,
424 pub hints: Option<&'a KeyHints>,
425 specular: bool,
426 shadow: bool,
427 }
428
429 impl<'a> Dialog<'a> {
430 /// The narrowest a dialog gets while the terminal can still spare it a
431 /// margin.
432 const MIN_WIDTH: u16 = 20;
433 const MIN_HEIGHT: u16 = 5;
434
435 #[must_use]
436 pub fn new() -> Self {
437 Self::default()
438 }
439
440 #[must_use]
441 pub fn title(mut self, title: impl Into<Cow<'a, str>>) -> Self {
442 self.title = Some(title.into());
443 self
444 }
445
446 #[must_use]
447 pub fn width(mut self, width: DialogWidth) -> Self {
448 self.width = width;
449 self
450 }
451
452 #[must_use]
453 pub fn body_rows(mut self, rows: u16) -> Self {
454 self.body_rows = rows;
455 self
456 }
457
458 #[must_use]
459 pub fn hints(mut self, hints: &'a KeyHints) -> Self {
460 self.hints = Some(hints);
461 self
462 }
463
464 /// Apply an OKLab overhead specular rim gradient to edged panel borders on
465 /// truecolor terminals with painted grounds.
466 #[must_use]
467 pub fn specular(mut self, enabled: bool) -> Self {
468 self.specular = enabled;
469 self
470 }
471
472 /// Cast a translucent buffer-blended OKLab drop shadow outside the panel
473 /// bounds on truecolor terminals with painted grounds.
474 #[must_use]
475 pub fn shadow(mut self, enabled: bool) -> Self {
476 self.shadow = enabled;
477 self
478 }
479
480 fn panel(&self) -> Panel<'a> {
481 Panel {
482 title: self.title.clone(),
483 aside: None,
484 depth: Depth::Overlay,
485 focused: false,
486 hints: self.hints,
487 specular: self.specular,
488 shadow: false,
489 }
490 }
491
492 fn width_in(&self, area_width: u16) -> u16 {
493 fit_axis(area_width, self.width.cells(), 4, Self::MIN_WIDTH)
494 }
495
496 /// Rows that leave `body_rows` of body at `width`, before clamping.
497 /// Starts from the roomy layout (padding, a blank row under the title and
498 /// above the hints) and grows until the panel really leaves that body.
499 fn rows_for(&self, width: u16, theme: &Theme) -> u16 {
500 let panel = self.panel();
501 let want = self.body_rows.max(1);
502 let hint_rows = self.hints.map_or(0, |h| h.height(width, theme));
503 let chrome = 4
504 + if self.title.is_some() { 2 } else { 0 }
505 + if hint_rows > 0 { hint_rows + 1 } else { 0 };
506 let start = want.saturating_add(chrome);
507 let limit = start.saturating_add(8);
508 (start..=limit)
509 .find(|&h| panel.body(Rect::new(0, 0, width, h), theme).height >= want)
510 .unwrap_or(limit)
511 }
512
513 /// Where the dialog goes in `area`: centered, at most the width asked
514 /// for, never wider or taller than `area`, with a two-cell margin at the
515 /// sides and one row above and below when `area` can spare them.
516 #[must_use]
517 pub fn rect(&self, area: Rect, theme: &Theme) -> Rect {
518 let width = self.width_in(area.width);
519 let rows = self.rows_for(width, theme);
520 let height = fit_axis(area.height, rows, 2, Self::MIN_HEIGHT);
521 Rect {
522 x: area.x + (area.width - width) / 2,
523 y: area.y + (area.height - height) / 2,
524 width,
525 height,
526 }
527 }
528
529 /// Paint the dialog over whatever is in `area` and return the body area
530 /// for the caller to fill.
531 pub fn draw(&self, area: Rect, buf: &mut Buffer, theme: &Theme) -> Rect {
532 let area = area.intersection(buf.area);
533 if area.is_empty() {
534 return area;
535 }
536 let rect = self.rect(area, theme);
537 if self.shadow {
538 paint_drop_shadow(rect, area, buf, theme);
539 }
540 self.panel().draw(rect, buf, theme)
541 }
542 }
543
544 impl Paint for Dialog<'_> {
545 fn paint(&self, area: Rect, buf: &mut Buffer, theme: &Theme) {
546 self.draw(area, buf, theme);
547 }
548
549 /// Rows the dialog wants at `width`, before the terminal clamps it.
550 fn height(&self, width: u16, theme: &Theme) -> u16 {
551 self.rows_for(self.width_in(width), theme)
552 }
553 }
554
555 /// The edge a [`Sheet`] is anchored to.
556 #[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash)]
557 pub enum SheetEdge {
558 #[default]
559 Bottom,
560 Top,
561 Left,
562 Right,
563 }
564
565 impl SheetEdge {
566 /// Whether the sheet's size is a height (it spans the width).
567 #[must_use]
568 pub const fn spans_width(self) -> bool {
569 matches!(self, SheetEdge::Top | SheetEdge::Bottom)
570 }
571 }
572
573 /// A raised surface anchored to one edge of the screen: settings, managers
574 /// and pickers that slide in over the work. The ground separates it where
575 /// grounds paint; where they do not (16 colors, `NO_COLOR`, a 256-color
576 /// ground that collapses) [`Panel`] draws an edge, so a sheet is never an
577 /// unmarked patch of text. Replaces the engine's underwater surface, whose
578 /// two rules broke the one-horizon rule.
579 #[derive(Clone, Debug, Default)]
580 pub struct Sheet<'a> {
581 pub title: Option<Cow<'a, str>>,
582 /// Muted text at the right of the title row.
583 pub aside: Option<Cow<'a, str>>,
584 pub edge: SheetEdge,
585 /// Rows (top and bottom) or columns (left and right) wanted; half the
586 /// screen when unset.
587 pub size: Option<u16>,
588 /// The most rows or columns the sheet takes, however much is wanted.
589 pub max_size: Option<u16>,
590 pub focused: bool,
591 pub hints: Option<&'a KeyHints>,
592 }
593
594 impl<'a> Sheet<'a> {
595 /// A sheet anchored to the bottom edge.
596 #[must_use]
597 pub fn new() -> Self {
598 Self::default()
599 }
600
601 #[must_use]
602 pub fn edge(mut self, edge: SheetEdge) -> Self {
603 self.edge = edge;
604 self
605 }
606
607 #[must_use]
608 pub fn title(mut self, title: impl Into<Cow<'a, str>>) -> Self {
609 self.title = Some(title.into());
610 self
611 }
612
613 #[must_use]
614 pub fn aside(mut self, aside: impl Into<Cow<'a, str>>) -> Self {
615 self.aside = Some(aside.into());
616 self
617 }
618
619 #[must_use]
620 pub fn size(mut self, size: u16) -> Self {
621 self.size = Some(size);
622 self
623 }
624
625 #[must_use]
626 pub fn max_size(mut self, max: u16) -> Self {
627 self.max_size = Some(max);
628 self
629 }
630
631 #[must_use]
632 pub fn focused(mut self, focused: bool) -> Self {
633 self.focused = focused;
634 self
635 }
636
637 #[must_use]
638 pub fn hints(mut self, hints: &'a KeyHints) -> Self {
639 self.hints = Some(hints);
640 self
641 }
642
643 /// Where the sheet goes in `area`: against its edge, across the whole
644 /// other axis, and as large as asked for, no larger than `max_size` or
645 /// `area`.
646 #[must_use]
647 pub fn rect(&self, area: Rect) -> Rect {
648 let total = if self.edge.spans_width() {
649 area.height
650 } else {
651 area.width
652 };
653 let size = self
654 .size
655 .unwrap_or_else(|| total.div_ceil(2))
656 .min(self.max_size.unwrap_or(u16::MAX))
657 .min(total);
658 match self.edge {
659 SheetEdge::Bottom => Rect {
660 y: area.bottom() - size,
661 height: size,
662 ..area
663 },
664 SheetEdge::Top => Rect {
665 height: size,
666 ..area
667 },
668 SheetEdge::Left => Rect {
669 width: size,
670 ..area
671 },
672 SheetEdge::Right => Rect {
673 x: area.right() - size,
674 width: size,
675 ..area
676 },
677 }
678 }
679
680 fn panel(&self) -> Panel<'a> {
681 Panel {
682 title: self.title.clone(),
683 aside: self.aside.clone(),
684 depth: Depth::Raised,
685 focused: self.focused,
686 hints: self.hints,
687 specular: false,
688 shadow: false,
689 }
690 }
691
692 /// Paint the sheet over whatever is in `area` and return the body area
693 /// for the caller to fill.
694 pub fn draw(&self, area: Rect, buf: &mut Buffer, theme: &Theme) -> Rect {
695 let area = area.intersection(buf.area);
696 if area.is_empty() {
697 return area;
698 }
699 self.panel().draw(self.rect(area), buf, theme)
700 }
701 }
702
703 impl Paint for Sheet<'_> {
704 fn paint(&self, area: Rect, buf: &mut Buffer, theme: &Theme) {
705 self.draw(area, buf, theme);
706 }
707 }
708
709 /// The horizon: one full-width rule, drawn once per frame, above the place
710 /// where the person types. Sugimoto's seascapes, not a table border.
711 ///
712 /// On a truecolor ground we painted, its ends fade into it, so it reads as a
713 /// horizon rather than a box edge. Everywhere else it is a plain `Border`
714 /// line; ASCII-safe terminals draw `-`.
715 #[derive(Clone, Debug, Default)]
716 pub struct HorizonRule<'a> {
717 /// Muted words at the left: what the space below is for.
718 pub label: Option<Cow<'a, str>>,
719 /// Muted words at the right.
720 pub aside: Option<Cow<'a, str>>,
721 }
722
723 impl<'a> HorizonRule<'a> {
724 #[must_use]
725 pub fn new() -> Self {
726 Self::default()
727 }
728
729 #[must_use]
730 pub fn label(mut self, label: impl Into<Cow<'a, str>>) -> Self {
731 self.label = Some(label.into());
732 self
733 }
734
735 #[must_use]
736 pub fn aside(mut self, aside: impl Into<Cow<'a, str>>) -> Self {
737 self.aside = Some(aside.into());
738 self
739 }
740 }
741
742 impl Paint for HorizonRule<'_> {
743 fn paint(&self, area: Rect, buf: &mut Buffer, theme: &Theme) {
744 let area = area.intersection(buf.area);
745 if area.is_empty() {
746 return;
747 }
748 let row = Rect { height: 1, ..area };
749 let rule = glyphs::pick("─", theme.ascii());
750 let line_style = theme.fg(Role::Border);
751 // Fade only into a ground we painted: after `without_base_ground` the
752 // ground is the terminal's own, whose color we do not know.
753 let fade = theme.depth() == color::ColorDepth::TrueColor && theme.paints_base_ground();
754 let width = row.width;
755 let ramp = (width / 8).min(6);
756 for i in 0..width {
757 let mut style = line_style;
758 if fade && ramp > 0 {
759 let from_edge = i.min(width - 1 - i);
760 if from_edge < ramp {
761 let alpha = f32::from(from_edge + 1) / f32::from(ramp + 1);
762 style = Style::default().fg(color::blend(
763 theme.token(Role::Border),
764 theme.token(Role::Background),
765 alpha,
766 ));
767 }
768 }
769 buf[(row.x + i, row.y)].set_symbol(rule).set_style(style);
770 }
771 let muted = theme.fg(Role::Muted);
772 if let Some(label) = &self.label {
773 let label = text::display_safe(label);
774 let budget = usize::from(width.saturating_sub(ramp.max(2) * 2 + 4)) / 2;
775 let label = format!(" {} ", text::truncate(&label, budget, theme.ascii()));
776 let x = row.x + ramp.max(2).min(width);
777 buf.set_stringn(x, row.y, &label, usize::from(row.right() - x), muted);
778 }
779 if let Some(aside) = &self.aside {
780 let aside = text::display_safe(aside);
781 let budget = usize::from(width.saturating_sub(ramp.max(2) * 2 + 4)) / 2;
782 let aside = format!(" {} ", text::truncate(&aside, budget, theme.ascii()));
783 let w = u16::try_from(text::width(&aside)).unwrap_or(u16::MAX);
784 let x = row.right().saturating_sub(w + ramp.max(2));
785 if x > row.x {
786 buf.set_stringn(x, row.y, &aside, usize::from(w), muted);
787 }
788 }
789 }
790 }
791
792 /// Apply an overhead OKLab specular rim gradient to an already-painted box
793 /// border on truecolor terminals with painted grounds.
794 ///
795 /// Leaves titles, metadata spans and interior cells intact, and cleanly no-ops
796 /// on lower color depths or terminal-owned grounds.
797 pub fn paint_specular_border(area: Rect, buf: &mut Buffer, theme: &Theme, focused: bool) {
798 if theme.depth() != color::ColorDepth::TrueColor || !theme.paints_grounds() {
799 return;
800 }
801 let border_role = if focused {
802 Role::Accent
803 } else {
804 Role::BorderStrong
805 };
806 let highlight_role = if focused {
807 Role::Foreground
808 } else {
809 Role::Accent
810 };
811 let Some(border) = theme.color(border_role) else {
812 return;
813 };
814 let Some(highlight) = theme.color(highlight_role) else {
815 return;
816 };
817 let bg = theme.token(Role::Surface);
818 color::paint_sculpted_border_colors(area, buf, border, highlight, bg, theme.ascii());
819 }
820
821 /// Cast a soft, translucent buffer-blended drop shadow around `popup_area`
822 /// within `bounds` on truecolor terminals with painted grounds.
823 ///
824 /// Uses half-block vertical offsets (`▄`/`▀`) and OKLab shading of the actual
825 /// underlying cell backgrounds already painted into `buf`, so ocean water and
826 /// transcript text remain subtly visible beneath the shadow. Cleanly no-ops on
827 /// non-truecolor profiles, narrow terminals, or unpainted grounds.
828 pub fn paint_drop_shadow(popup_area: Rect, bounds: Rect, buf: &mut Buffer, theme: &Theme) {
829 if !theme.paints_grounds() {
830 return;
831 }
832 color::paint_translucent_shadow(popup_area, bounds, buf, theme.depth(), theme.ascii());
833 }
834
835 /// A micro-beveled tonal pill that looks machined in any monospace font
836 /// without Nerd Fonts.
837 ///
838 /// On truecolor terminals with painted grounds, wraps the label in half-cell
839 /// bevel caps (`▐`/`▌`) over an OKLab contrast-guarded chip ground. Degrades
840 /// cleanly to `[label]` on 256-color, 16-color, `NO_COLOR`, and ASCII profiles.
841 #[derive(Clone, Debug, PartialEq, Eq)]
842 pub struct MicroBadge<'a> {
843 pub label: Cow<'a, str>,
844 pub role: Role,
845 pub dot: bool,
846 pub outer_ground: Role,
847 }
848
849 impl<'a> MicroBadge<'a> {
850 /// Create a micro-beveled badge with the given label and default `Accent`
851 /// role.
852 #[must_use]
853 pub fn new(label: impl Into<Cow<'a, str>>) -> Self {
854 Self {
855 label: label.into(),
856 role: Role::Accent,
857 dot: false,
858 outer_ground: Role::Surface,
859 }
860 }
861
862 /// Semantic role coloring the badge.
863 #[must_use]
864 pub const fn role(mut self, role: Role) -> Self {
865 self.role = role;
866 self
867 }
868
869 /// Prepend a compact status dot (`●`, or `*` in ASCII).
870 #[must_use]
871 pub const fn dot(mut self, dot: bool) -> Self {
872 self.dot = dot;
873 self
874 }
875
876 /// The surrounding ground role the half-edge bevel caps blend against.
877 #[must_use]
878 pub const fn on_ground(mut self, ground: Role) -> Self {
879 self.outer_ground = ground;
880 self
881 }
882
883 /// Build styled spans for inline composition inside a [`Line`].
884 #[must_use]
885 pub fn spans(&self, theme: &Theme) -> Vec<Span<'static>> {
886 let safe = text::display_safe(&self.label).into_owned();
887 let dot_prefix = if self.dot {
888 format!("{} ", glyphs::pick(glyphs::CURRENT, theme.ascii()))
889 } else {
890 String::new()
891 };
892 let body = format!("{dot_prefix}{safe}");
893 let bevel = theme.depth() == color::ColorDepth::TrueColor
894 && theme.paints_grounds()
895 && !theme.ascii();
896 if bevel
897 && let (Some(accent), Some(surface), Some(fg_fallback)) = (
898 theme.color(self.role),
899 theme.color(self.outer_ground),
900 theme.color(Role::Foreground),
901 )
902 && let Some((chip_bg, chip_fg)) = color::bevel_chip_colors(
903 accent,
904 surface,
905 fg_fallback,
906 theme.caps().appearance == Appearance::Light,
907 )
908 {
909 let cap_style = Style::default()
910 .fg(chip_bg)
911 .patch(theme.bg(self.outer_ground));
912 let body_style = Style::default()
913 .fg(chip_fg)
914 .bg(chip_bg)
915 .add_modifier(Modifier::BOLD);
916 return vec![
917 Span::styled("▐", cap_style),
918 Span::styled(body, body_style),
919 Span::styled("▌", cap_style),
920 ];
921 }
922 let style = theme.fg(self.role).add_modifier(Modifier::BOLD);
923 vec![Span::styled(format!("[{body}]"), style)]
924 }
925
926 /// Rendered width in terminal cells.
927 #[must_use]
928 pub fn width(&self, theme: &Theme) -> u16 {
929 let total: usize = self
930 .spans(theme)
931 .iter()
932 .map(|span| text::width(&span.content))
933 .sum();
934 u16::try_from(total).unwrap_or(u16::MAX)
935 }
936 }
937
938 impl Paint for MicroBadge<'_> {
939 fn paint(&self, area: Rect, buf: &mut Buffer, theme: &Theme) {
940 let area = area.intersection(buf.area);
941 if area.is_empty() {
942 return;
943 }
944 Line::from(self.spans(theme)).render(Rect::new(area.x, area.y, area.width, 1), buf);
945 }
946
947 fn height(&self, _width: u16, _theme: &Theme) -> u16 {
948 1
949 }
950 }
951
952 #[cfg(test)]
953 mod tests {
954 use super::*;
955
956 #[test]
957 fn centered_clamps_to_the_frame() {
958 let area = Rect::new(0, 0, 80, 24);
959 assert_eq!(centered(area, 68, 10, 44, 8), Rect::new(6, 7, 68, 10));
960 let small = Rect::new(0, 0, 30, 6);
961 let r = centered(small, 68, 10, 44, 8);
962 assert!(r.width <= 28 && r.height <= 4);
963 }
964
965 /// A raised card must be told from the stage in every profile: by its
966 /// ground where the two grounds differ, by an edge everywhere else.
967 #[test]
968 fn a_raised_panel_is_always_distinguishable() {
969 use crate::testing::{Profile, render, text};
970 for profile in Profile::ALL {
971 for theme in [profile.theme(), profile.theme().without_base_ground()] {
972 let buf = render(12, 4, |area, buf| {
973 Panel::new(Depth::Raised).draw(area, buf, &theme);
974 });
975 let edged = text(&buf).starts_with(['╭', '+']);
976 let grounded = theme.grounds_differ(Role::Surface, Role::Background);
977 assert!(
978 edged || grounded,
979 "{}: raised panel has neither an edge nor its own ground",
980 profile.name()
981 );
982 }
983 }
984 let dark256 = Profile::Dark256.theme();
985 assert!(!dark256.grounds_differ(Role::Surface, Role::Background));
986 assert!(Panel::new(Depth::Raised).edged(&Profile::Light256.theme()));
987 }
988
989 #[test]
990 fn the_horizon_does_not_fade_into_a_ground_it_did_not_paint() {
991 use crate::testing::{Profile, render};
992 let theme = Profile::DarkTrue.theme().without_base_ground();
993 let buf = render(40, 1, |area, buf| {
994 HorizonRule::new().paint(area, buf, &theme)
995 });
996 for x in 0..40 {
997 assert_eq!(
998 buf[(x, 0)].fg,
999 theme.color(Role::Border).unwrap(),
1000 "col {x}"
1001 );
1002 }
1003 let painted = Profile::DarkTrue.theme();
1004 let buf = render(40, 1, |area, buf| {
1005 HorizonRule::new().paint(area, buf, &painted);
1006 });
1007 assert_ne!(buf[(0, 0)].fg, painted.color(Role::Border).unwrap());
1008 }
1009 }
1010
1010 lines RUST