返回 CodeWhale
rounded.rs
根目录 / crates / tui / src / tui / views / rounded.rs
1 use ratatui::{
2 buffer::Buffer,
3 layout::Rect,
4 style::{Color, Modifier, Style},
5 symbols,
6 text::{Line, Span},
7 widgets::{Block, BorderType, Borders, Clear, Padding, Paragraph, Widget},
8 };
9 use unicode_width::UnicodeWidthStr;
10
11 use crate::tui::views::{ActionHint, action_footer_lines};
12 use codewhale_palette as palette;
13
14 pub(crate) const ASCII_BORDER_SET: symbols::border::Set = symbols::border::Set {
15 top_left: "+",
16 top_right: "+",
17 bottom_left: "+",
18 bottom_right: "+",
19 vertical_left: "|",
20 vertical_right: "|",
21 horizontal_top: "-",
22 horizontal_bottom: "-",
23 };
24
25 pub(crate) fn resolved_surface_bg(theme: &palette::UiTheme) -> Color {
26 if theme.composer_bg != Color::Reset {
27 theme.composer_bg
28 } else {
29 palette::COMPOSER_BG
30 }
31 }
32
33 pub(crate) fn rounded_block_with_colors(
34 border_color: Color,
35 text_color: Color,
36 bg: Color,
37 ) -> Block<'static> {
38 let block = Block::default()
39 .borders(Borders::ALL)
40 .border_style(Style::default().fg(border_color).bg(bg))
41 .style(Style::default().fg(text_color).bg(bg));
42 if crate::tui::color_compat::ascii_safe_enabled() {
43 block.border_set(ASCII_BORDER_SET)
44 } else {
45 block.border_type(BorderType::Rounded)
46 }
47 }
48
49 pub(crate) fn rounded_titled_block(
50 title: &str,
51 right_meta: Option<&str>,
52 active: bool,
53 bg: Color,
54 max_width: u16,
55 ) -> Block<'static> {
56 let border_color = if active {
57 palette::WHALE_ACTION
58 } else {
59 palette::BORDER_COLOR
60 };
61 rounded_titled_block_with_colors(
62 title,
63 right_meta,
64 border_color,
65 palette::WHALE_ACTION,
66 palette::TEXT_PRIMARY,
67 palette::TEXT_MUTED,
68 bg,
69 max_width,
70 )
71 }
72
73 #[allow(clippy::too_many_arguments)]
74 pub(crate) fn rounded_titled_block_with_colors(
75 title: &str,
76 right_meta: Option<&str>,
77 border_color: Color,
78 title_color: Color,
79 text_color: Color,
80 meta_color: Color,
81 bg: Color,
82 max_width: u16,
83 ) -> Block<'static> {
84 let ascii = crate::tui::color_compat::ascii_safe_enabled();
85 let rule = if ascii { "-" } else { "─" };
86 let border_style = Style::default().fg(border_color).bg(bg);
87 let title_style = Style::default()
88 .fg(title_color)
89 .bg(bg)
90 .add_modifier(Modifier::BOLD);
91 let meta_style = Style::default().fg(meta_color).bg(bg);
92 let title_budget = usize::from(max_width.saturating_sub(6));
93 let clipped_title = codewhale_tui_kit::ui_text::semantic_truncate(title, title_budget);
94 let mut block =
95 rounded_block_with_colors(border_color, text_color, bg).title_top(Line::from(vec![
96 Span::styled(rule, border_style),
97 Span::styled(format!(" {clipped_title} "), title_style),
98 ]));
99 if let Some(meta) = right_meta
100 && !meta.is_empty()
101 && clipped_title.width() + meta.width() + 9 <= usize::from(max_width)
102 {
103 block = block.title_top(
104 Line::from(vec![
105 Span::styled(format!(" {meta} "), meta_style),
106 Span::styled(rule, border_style),
107 ])
108 .right_aligned(),
109 );
110 }
111 block
112 }
113
114 fn room_border(quiet: Color, accent: Color, ground: Color, active: bool) -> Color {
115 if active
116 && (crate::tui::color_compat::ascii_safe_enabled()
117 || !matches!(
118 (quiet, accent, ground),
119 (Color::Rgb(..), Color::Rgb(..), Color::Rgb(..))
120 ))
121 {
122 accent
123 } else {
124 quiet
125 }
126 }
127
128 pub(super) fn light_title_edge(
129 area: Rect,
130 buf: &mut Buffer,
131 title_end: usize,
132 border: Color,
133 accent: Color,
134 ground: Color,
135 ) {
136 if area.width < 12
137 || area.height < 3
138 || !matches!(
139 (border, accent, ground),
140 (Color::Rgb(..), Color::Rgb(..), Color::Rgb(..))
141 )
142 || !buf
143 .cell((area.x, area.y))
144 .is_some_and(|cell| cell.symbol() == "╭")
145 {
146 return;
147 }
148 let shades = [0.92, 0.77, 0.57, 0.37, 0.20, 0.08].map(|strength| {
149 codewhale_ratatui::color::contrast_safe_oklab_mix(border, accent, ground, strength, 3.0)
150 });
151 let x = area.left();
152 let y = area.top();
153 for (dy, weight) in [(0, 1), (1, 3), (2, 5)] {
154 let Some(cell) = buf.cell_mut((x, y.saturating_add(dy))) else {
155 continue;
156 };
157 if matches!(cell.symbol(), "╭" | "│") && cell.fg == border {
158 cell.set_fg(shades[weight]);
159 }
160 }
161 let first = x.saturating_add(u16::try_from(title_end).unwrap_or(u16::MAX));
162 let reach = area.width.div_ceil(5).clamp(12, 24);
163 let last = first
164 .saturating_add(reach)
165 .min(area.right().saturating_sub(1));
166 for column in first..last {
167 let Some(cell) = buf.cell_mut((column, y)) else {
168 continue;
169 };
170 if cell.symbol() != "─" || cell.fg != border || !cell.modifier.is_empty() {
171 break;
172 }
173 let band = usize::from(column - first) * shades.len() / usize::from(reach);
174 cell.set_fg(shades[band]);
175 }
176 }
177
178 pub(crate) fn render_rounded_surface(
179 area: Rect,
180 buf: &mut Buffer,
181 title: impl Into<String>,
182 right_meta: Option<String>,
183 active: bool,
184 ) -> Rect {
185 let theme = super::active_modal_theme();
186 render_rounded_surface_themed(area, buf, title, right_meta, active, theme.as_ref())
187 }
188
189 pub(crate) fn render_rounded_surface_themed(
190 area: Rect,
191 buf: &mut Buffer,
192 title: impl Into<String>,
193 right_meta: Option<String>,
194 active: bool,
195 theme: Option<&palette::UiTheme>,
196 ) -> Rect {
197 let backdrop_bg = theme
198 .map(|t| t.surface_bg)
199 .filter(|c| *c != Color::Reset)
200 .unwrap_or(palette::WHALE_BG);
201 let bg = theme
202 .map(resolved_surface_bg)
203 .unwrap_or(palette::COMPOSER_BG);
204 let text_fg = theme
205 .map(|t| t.text_body)
206 .filter(|c| *c != Color::Reset)
207 .unwrap_or(palette::TEXT_PRIMARY);
208 let accent = theme
209 .map(|t| t.accent_primary)
210 .filter(|c| *c != Color::Reset)
211 .unwrap_or(palette::WHALE_ACTION);
212 let quiet_border = theme
213 .map(|t| t.border)
214 .filter(|c| *c != Color::Reset)
215 .unwrap_or(palette::BORDER_COLOR);
216 let muted = theme
217 .map(|t| t.text_muted)
218 .filter(|c| *c != Color::Reset)
219 .unwrap_or(palette::TEXT_MUTED);
220 let border_color = room_border(quiet_border, accent, bg, active);
221
222 let margin_x = u16::from(area.width >= 96);
223 let margin_y = u16::from(area.height >= 28);
224 let surface = super::room_bounds(area, margin_x, margin_y);
225 super::prepare_room(area, surface, buf, text_fg, backdrop_bg);
226
227 let title = title.into();
228 let pad_x = u16::from(surface.width >= 24);
229 let block = rounded_titled_block_with_colors(
230 &title,
231 right_meta.as_deref(),
232 border_color,
233 accent,
234 text_fg,
235 muted,
236 bg,
237 surface.width,
238 )
239 .padding(Padding::new(pad_x, pad_x, 0, 0));
240 let inner = block.inner(surface);
241 block.render(surface, buf);
242 let light = if active { accent } else { muted };
243 light_title_edge(surface, buf, 4 + title.width(), border_color, light, bg);
244 inner
245 }
246
247 pub(super) fn paint_room_shadow(area: Rect, popup_area: Rect, buf: &mut Buffer) {
248 if let Some(caps) = super::ACTIVE_MODAL_THEME.with(std::cell::Cell::get).caps {
249 codewhale_ratatui::color::paint_translucent_shadow(
250 popup_area, area, buf, caps.depth, caps.ascii,
251 );
252 }
253 }
254
255 pub(crate) fn render_rounded_modal(
256 area: Rect,
257 popup_area: Rect,
258 buf: &mut Buffer,
259 title: impl Into<String>,
260 right_meta: Option<String>,
261 active: bool,
262 ) -> Rect {
263 paint_room_shadow(area, popup_area, buf);
264
265 Clear.render(popup_area, buf);
266 let title = title.into();
267 let pad_x = u16::from(popup_area.width >= 20);
268 let theme = super::active_modal_theme().unwrap_or(palette::UI_THEME);
269 let bg = resolved_surface_bg(&theme);
270 let border = room_border(theme.border, theme.accent_primary, bg, active);
271 let block = rounded_titled_block_with_colors(
272 &title,
273 right_meta.as_deref(),
274 border,
275 theme.accent_primary,
276 theme.text_body,
277 theme.text_muted,
278 bg,
279 popup_area.width,
280 )
281 .padding(Padding::new(pad_x, pad_x, 0, 0));
282 let inner = block.inner(popup_area);
283 block.render(popup_area, buf);
284 let light = if active {
285 theme.accent_primary
286 } else {
287 theme.text_muted
288 };
289 light_title_edge(popup_area, buf, 4 + title.width(), border, light, bg);
290 inner
291 }
292
293 pub(crate) fn render_hairline(area: Rect, buf: &mut Buffer, border_color: Color, bg: Color) {
294 if area.width == 0 || area.height == 0 {
295 return;
296 }
297 let ch = if crate::tui::color_compat::ascii_safe_enabled() {
298 "-"
299 } else {
300 "─"
301 };
302 Paragraph::new(Line::from(Span::styled(
303 ch.repeat(usize::from(area.width)),
304 Style::default().fg(border_color).bg(bg),
305 )))
306 .render(Rect::new(area.x, area.y, area.width, 1), buf);
307 }
308
309 pub(crate) fn render_rounded_footer(inner: Rect, buf: &mut Buffer, hints: &[ActionHint]) -> Rect {
310 render_rounded_footer_themed(
311 inner,
312 buf,
313 hints,
314 palette::COMPOSER_BG,
315 palette::BORDER_COLOR,
316 )
317 }
318
319 pub(crate) fn render_rounded_footer_themed(
320 inner: Rect,
321 buf: &mut Buffer,
322 hints: &[ActionHint],
323 bg: Color,
324 border_color: Color,
325 ) -> Rect {
326 let lines = action_footer_lines(hints, inner.width);
327 if lines.is_empty() || inner.height == 0 {
328 return inner;
329 }
330 let footer_height = u16::try_from(lines.len())
331 .unwrap_or(u16::MAX)
332 .min(inner.height);
333 let show_divider = inner.height >= footer_height.saturating_add(5);
334 let divider_height = u16::from(show_divider);
335 let footer_area = Rect {
336 x: inner.x,
337 y: inner.y + inner.height - footer_height,
338 width: inner.width,
339 height: footer_height,
340 };
341 Paragraph::new(lines)
342 .style(Style::default().bg(bg))
343 .render(footer_area, buf);
344 if show_divider {
345 render_hairline(
346 Rect::new(inner.x, footer_area.y.saturating_sub(1), inner.width, 1),
347 buf,
348 border_color,
349 bg,
350 );
351 }
352 Rect {
353 x: inner.x,
354 y: inner.y,
355 width: inner.width,
356 height: inner
357 .height
358 .saturating_sub(footer_height.saturating_add(divider_height)),
359 }
360 }
361
362 pub(crate) fn pad_selected_line(
363 mut line: Line<'static>,
364 width: usize,
365 style: Style,
366 ) -> Line<'static> {
367 let used: usize = line.spans.iter().map(|s| s.content.width()).sum();
368 if used < width {
369 line.spans
370 .push(Span::styled(" ".repeat(width - used), style));
371 }
372 line
373 }
374
375 #[cfg(test)]
376 mod tests {
377 use super::*;
378
379 #[test]
380 fn rounded_modal_casts_translucent_shadow_and_sculpted_specular_rim() {
381 let area = Rect::new(0, 0, 60, 18);
382 let popup = Rect::new(10, 4, 36, 9);
383 let mut buf = Buffer::empty(area);
384 let ocean = Color::Rgb(0x10, 0x2a, 0x45);
385 buf.set_style(area, Style::default().bg(ocean));
386
387 let caps = codewhale_ratatui::Caps {
388 depth: codewhale_ratatui::color::ColorDepth::TrueColor,
389 ascii: false,
390 appearance: codewhale_ratatui::detect::Appearance::Dark,
391 };
392 let _scope =
393 super::super::ModalThemeScope::with_ocean(Some(palette::UI_THEME), None, Some(caps));
394 let inner = render_rounded_modal(area, popup, &mut buf, "Preview", None, true);
395 assert!(inner.width > 0 && inner.height > 0);
396 assert_ne!(
397 buf[(popup.x + popup.width / 2, popup.y)].fg,
398 buf[(popup.x + popup.width / 2, popup.bottom() - 1)].fg
399 );
400 assert_eq!(buf[(popup.right(), popup.y)].symbol(), "▄");
401 assert_eq!(buf[(popup.x + 2, popup.bottom())].symbol(), "▀");
402 assert_ne!(buf[(popup.right(), popup.y + 2)].bg, ocean);
403 assert_ne!(
404 buf[(popup.right(), popup.y + 2)].bg,
405 palette::SURFACE_ELEVATED
406 );
407 }
408
409 #[test]
410 fn rooms_keep_the_launch_water_at_screen_coordinates_and_opaque_controls() {
411 let area = Rect::new(3, 2, 106, 39);
412 let theme = palette::UNDERWATER_UI_THEME;
413 let caps = crate::tui::color_compat::ColorCompatBackend::new(
414 std::io::sink(),
415 palette::ColorDepth::TrueColor,
416 palette::PaletteMode::Dark,
417 )
418 .native_ocean_caps();
419 let ocean = crate::tui::ocean::OceanColumn::still_room(area, &theme, Some(caps)).unwrap();
420 let scope = super::super::ModalThemeScope::with_ocean(Some(theme), Some(ocean), Some(caps));
421 let mut home = Buffer::empty(area);
422 home.set_style(area, Style::default().bg(theme.surface_bg));
423 ocean.paint_matching_native(area, &mut home, theme.surface_bg, &theme, &[]);
424 let mut room = Buffer::empty(area);
425 room[(area.x + 8, area.y)]
426 .set_symbol("x")
427 .set_style(Style::default().add_modifier(Modifier::REVERSED));
428 let body = render_rounded_surface(area, &mut room, "Settings", None, true);
429 assert_eq!(room[(area.x + 8, area.y)].symbol(), " ");
430 assert!(room[(area.x + 8, area.y)].modifier.is_empty());
431 let sample = |offset| room[(area.x + offset, area.y)].bg;
432 assert_ne!(sample(4), sample(85));
433 for x in area.left()..area.right() {
434 assert_eq!(room[(x, area.y)].bg, home[(x, area.y)].bg);
435 }
436 assert_eq!(room[(body.x, body.y)].bg, resolved_surface_bg(&theme));
437 assert!(body.x >= area.x + 4 && body.y >= area.y + 2);
438 let narrow = Rect::new(0, 0, 80, 24);
439 assert_eq!(
440 super::super::room_bounds(narrow, 1, 1),
441 Rect::new(1, 1, 78, 22)
442 );
443 drop(scope);
444 let custom = theme.with_background_color(Color::Rgb(30, 16, 25));
445 let custom_water =
446 crate::tui::ocean::OceanColumn::still_room(area, &custom, Some(caps)).unwrap();
447 let _custom =
448 super::super::ModalThemeScope::with_ocean(Some(custom), Some(custom_water), Some(caps));
449 let custom_body = render_rounded_surface(area, &mut room, "Settings", None, true);
450 assert_eq!(
451 room[(area.x + 4, area.y)].bg,
452 room[(area.x + 85, area.y)].bg
453 );
454 assert_ne!(
455 room[(area.x + 85, area.y)].bg,
456 home[(area.x + 85, area.y)].bg
457 );
458 assert_eq!(
459 room[(custom_body.x, custom_body.y)].bg,
460 resolved_surface_bg(&custom)
461 );
462 let light = palette::LIGHT_UI_THEME;
463 assert!(crate::tui::ocean::OceanColumn::still_room(area, &light, Some(caps)).is_none());
464 }
465
466 #[test]
467 fn room_light_follows_the_title_and_leaves_actions_and_reading_surface_alone() {
468 let area = Rect::new(3, 2, 76, 16);
469 for theme in [
470 palette::UI_THEME,
471 palette::LIGHT_UI_THEME,
472 palette::TERMINAL_UI_THEME,
473 ] {
474 let mut buf = Buffer::empty(area);
475 let inner = render_rounded_surface_themed(
476 area,
477 &mut buf,
478 "Models",
479 Some("Provider".to_string()),
480 true,
481 Some(&theme),
482 );
483 assert_eq!(inner, Rect::new(5, 3, 72, 14));
484 let title = &buf[(area.x + 3, area.y)];
485 assert_eq!(title.symbol(), "M");
486 assert!(title.modifier.contains(Modifier::BOLD));
487 let rim = &buf[(area.x + 10, area.y)];
488 let far = &buf[(area.x + 42, area.y)];
489 assert_eq!(rim.symbol(), far.symbol());
490 if matches!(theme.border, Color::Rgb(..)) {
491 assert_ne!(rim.fg, far.fg);
492 assert_eq!(far.fg, theme.border);
493 } else {
494 assert_eq!(rim.fg, far.fg);
495 }
496 assert_eq!(buf[(inner.x, inner.y)].symbol(), " ");
497 assert_eq!(buf[(inner.x, inner.y)].bg, resolved_surface_bg(&theme));
498 let meta = if theme.text_muted == Color::Reset {
499 palette::TEXT_MUTED
500 } else {
501 theme.text_muted
502 };
503 assert_eq!(buf[(area.right() - 6, area.y)].fg, meta);
504 }
505 }
506
507 #[test]
508 fn rounded_modal_shadow_noops_on_reset_ground() {
509 let area = Rect::new(0, 0, 60, 18);
510 let popup = Rect::new(10, 4, 36, 9);
511 let mut buf = Buffer::empty(area);
512 let caps = codewhale_ratatui::Caps {
513 depth: codewhale_ratatui::color::ColorDepth::TrueColor,
514 ascii: false,
515 appearance: codewhale_ratatui::detect::Appearance::Dark,
516 };
517 let _scope =
518 super::super::ModalThemeScope::with_ocean(Some(palette::UI_THEME), None, Some(caps));
519 render_rounded_modal(area, popup, &mut buf, "Preview", None, false);
520 assert_eq!(buf[(popup.right(), popup.y + 2)].bg, Color::Reset);
521 assert_eq!(buf[(popup.x + 2, popup.bottom())].symbol(), " ");
522 }
523 }
524
524 lines RUST