1use retroglyph_core::{Backend, Grid, Rect, Style, Terminal, Tile};
15use unicode_width::{UnicodeWidthChar, UnicodeWidthStr};
16
17use crate::draw::{BL, BR, H, TL, TR, V};
18use crate::text::truncate;
19use crate::widget::Widget;
20
21#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
23pub struct Sides {
24 pub top: u16,
26 pub right: u16,
28 pub bottom: u16,
30 pub left: u16,
32}
33
34impl Sides {
35 pub const ZERO: Self = Self {
37 top: 0,
38 right: 0,
39 bottom: 0,
40 left: 0,
41 };
42
43 #[must_use]
45 pub const fn all(n: u16) -> Self {
46 Self {
47 top: n,
48 right: n,
49 bottom: n,
50 left: n,
51 }
52 }
53
54 #[must_use]
57 pub const fn symmetric(vertical: u16, horizontal: u16) -> Self {
58 Self {
59 top: vertical,
60 right: horizontal,
61 bottom: vertical,
62 left: horizontal,
63 }
64 }
65
66 #[must_use]
68 pub const fn top(mut self, top: u16) -> Self {
69 self.top = top;
70 self
71 }
72
73 #[must_use]
75 pub const fn right(mut self, right: u16) -> Self {
76 self.right = right;
77 self
78 }
79
80 #[must_use]
82 pub const fn bottom(mut self, bottom: u16) -> Self {
83 self.bottom = bottom;
84 self
85 }
86
87 #[must_use]
89 pub const fn left(mut self, left: u16) -> Self {
90 self.left = left;
91 self
92 }
93
94 const fn horizontal(self) -> u16 {
95 self.left.saturating_add(self.right)
96 }
97
98 const fn vertical(self) -> u16 {
99 self.top.saturating_add(self.bottom)
100 }
101}
102
103#[derive(Clone, Copy, Debug)]
123pub struct BoxStyle {
124 style: Style,
125 padding: Sides,
126 margin: Sides,
127 border: bool,
128 width: Option<u16>,
129 height: Option<u16>,
130}
131
132impl BoxStyle {
133 #[must_use]
136 pub const fn new(style: Style) -> Self {
137 Self {
138 style,
139 padding: Sides::ZERO,
140 margin: Sides::ZERO,
141 border: false,
142 width: None,
143 height: None,
144 }
145 }
146
147 #[must_use]
149 pub const fn padding(mut self, padding: Sides) -> Self {
150 self.padding = padding;
151 self
152 }
153
154 #[must_use]
156 pub const fn margin(mut self, margin: Sides) -> Self {
157 self.margin = margin;
158 self
159 }
160
161 #[must_use]
163 pub const fn border(mut self, border: bool) -> Self {
164 self.border = border;
165 self
166 }
167
168 #[must_use]
173 pub const fn width(mut self, width: u16) -> Self {
174 self.width = Some(width);
175 self
176 }
177
178 #[must_use]
183 pub const fn height(mut self, height: u16) -> Self {
184 self.height = Some(height);
185 self
186 }
187
188 #[must_use]
204 pub fn render(&self, text: &str) -> Grid {
205 let lines: Vec<&str> = text.split('\n').collect();
206 let content_w = self.width.unwrap_or_else(|| {
207 u16::try_from(lines.iter().map(|l| l.width()).max().unwrap_or(0)).unwrap_or(u16::MAX)
208 });
209 let content_h = self
210 .height
211 .unwrap_or_else(|| u16::try_from(lines.len()).unwrap_or(u16::MAX));
212
213 let (mut grid, content_x, content_y) = self.scaffold(content_w, content_h);
214 for (row, line) in lines.iter().take(usize::from(content_h)).enumerate() {
215 let Ok(row) = u16::try_from(row) else { break };
216 let clipped = truncate(line, usize::from(content_w));
217 let mut col = 0u16;
218 for ch in clipped.chars() {
219 let w = u16::try_from(ch.width().unwrap_or(0)).unwrap_or(u16::MAX);
220 if col.saturating_add(w) > content_w {
221 break;
222 }
223 grid.put(content_x + col, content_y + row, Tile::new(ch, self.style));
224 col = col.saturating_add(w);
225 }
226 }
227 grid
228 }
229
230 #[cfg(feature = "egc")]
241 #[must_use]
242 pub fn render_wrapped(&self, text: &str) -> Grid {
243 use retroglyph_core::Headless;
244 use retroglyph_core::layout::TextLayout;
245 use retroglyph_core::text::{Line, Span};
246
247 let content_w = self.width.unwrap_or_else(|| {
248 u16::try_from(
249 text.split('\n')
250 .map(UnicodeWidthStr::width)
251 .max()
252 .unwrap_or(0),
253 )
254 .unwrap_or(u16::MAX)
255 });
256 let line = Line::from(Span::styled(text, self.style));
257 let content_h = self.height.unwrap_or_else(|| {
258 TextLayout::new(&line)
259 .rect(Rect::new(0, 0, content_w, u16::MAX))
260 .measure()
261 .height
262 });
263
264 let (mut grid, content_x, content_y) = self.scaffold(content_w, content_h);
265
266 let mut scratch = Terminal::new(Headless::new(content_w.max(1), content_h.max(1)));
272 TextLayout::new(&line)
273 .rect(Rect::new(0, 0, content_w, content_h))
274 .render(&mut scratch);
275 let content_rect = Rect::new(0, 0, content_w, content_h);
276 grid.blit(0, scratch.grid(), content_rect, content_x, content_y);
277
278 grid
279 }
280
281 fn scaffold(&self, content_w: u16, content_h: u16) -> (Grid, u16, u16) {
286 let border_wh = u16::from(self.border) * 2;
287 let inner_w = content_w
288 .saturating_add(self.padding.horizontal())
289 .saturating_add(border_wh);
290 let inner_h = content_h
291 .saturating_add(self.padding.vertical())
292 .saturating_add(border_wh);
293 let outer_w = inner_w.saturating_add(self.margin.horizontal()).max(1);
294 let outer_h = inner_h.saturating_add(self.margin.vertical()).max(1);
295
296 let mut grid = Grid::new(outer_w, outer_h);
297 let box_x = self.margin.left;
298 let box_y = self.margin.top;
299
300 fill_rect(&mut grid, box_x, box_y, inner_w, inner_h, self.style);
301 if self.border {
302 draw_border(&mut grid, box_x, box_y, inner_w, inner_h, self.style);
305 }
306
307 let content_x = box_x
308 .saturating_add(u16::from(self.border))
309 .saturating_add(self.padding.left);
310 let content_y = box_y
311 .saturating_add(u16::from(self.border))
312 .saturating_add(self.padding.top);
313 (grid, content_x, content_y)
314 }
315}
316
317#[derive(Clone, Copy, Debug)]
328pub struct Boxed<'a> {
329 style: BoxStyle,
330 text: &'a str,
331}
332
333impl BoxStyle {
334 #[must_use]
336 pub const fn text(self, text: &str) -> Boxed<'_> {
337 Boxed { style: self, text }
338 }
339}
340
341impl<B: Backend> Widget<B> for Boxed<'_> {
342 fn render(self, area: Rect, term: &mut Terminal<B>) {
343 let grid = self.style.render(self.text);
344 crate::block::blit_into(term, &grid, area.left(), area.top());
345 }
346}
347
348fn fill_rect(grid: &mut Grid, x: u16, y: u16, w: u16, h: u16, style: Style) {
350 for dy in 0..h {
351 for dx in 0..w {
352 grid.put(x + dx, y + dy, Tile::new(' ', style));
353 }
354 }
355}
356
357fn draw_border(grid: &mut Grid, x: u16, y: u16, w: u16, h: u16, style: Style) {
360 let right = x + w - 1;
361 let bottom = y + h - 1;
362
363 grid.put(x, y, Tile::new(TL, style));
364 grid.put(right, y, Tile::new(TR, style));
365 grid.put(x, bottom, Tile::new(BL, style));
366 grid.put(right, bottom, Tile::new(BR, style));
367 for cx in (x + 1)..right {
368 grid.put(cx, y, Tile::new(H, style));
369 grid.put(cx, bottom, Tile::new(H, style));
370 }
371 for cy in (y + 1)..bottom {
372 grid.put(x, cy, Tile::new(V, style));
373 grid.put(right, cy, Tile::new(V, style));
374 }
375}
376
377#[cfg(test)]
378mod tests {
379 use super::*;
380
381 fn glyphs(grid: &Grid) -> Vec<String> {
382 (0..grid.height())
383 .map(|y| (0..grid.width()).map(|x| grid.get(x, y).glyph()).collect())
384 .collect()
385 }
386
387 #[test]
388 fn sides_helpers() {
389 assert_eq!(
390 Sides::all(2),
391 Sides {
392 top: 2,
393 right: 2,
394 bottom: 2,
395 left: 2
396 }
397 );
398 assert_eq!(
399 Sides::symmetric(1, 3),
400 Sides {
401 top: 1,
402 right: 3,
403 bottom: 1,
404 left: 3
405 }
406 );
407 }
408
409 #[test]
410 fn sizes_to_content_with_no_padding_or_border() {
411 let grid = BoxStyle::new(Style::default()).render("hi");
412 assert_eq!((grid.width(), grid.height()), (2, 1));
413 assert_eq!(grid.get(0, 0).glyph(), 'h');
414 assert_eq!(grid.get(1, 0).glyph(), 'i');
415 }
416
417 #[test]
418 fn sizes_to_the_widest_of_multiple_lines() {
419 let grid = BoxStyle::new(Style::default()).render("a\nbcd\nef");
420 assert_eq!((grid.width(), grid.height()), (3, 3));
421 assert_eq!(grid.get(0, 0).glyph(), 'a');
422 assert_eq!(grid.get(1, 0).glyph(), ' '); assert_eq!(grid.get(0, 1).glyph(), 'b');
424 assert_eq!(grid.get(2, 1).glyph(), 'd');
425 }
426
427 #[test]
428 fn explicit_width_clips_longer_lines_and_pads_shorter_ones() {
429 let grid = BoxStyle::new(Style::default()).width(3).render("hello");
430 assert_eq!(grid.width(), 3);
431 let row: String = (0..3).map(|x| grid.get(x, 0).glyph()).collect();
432 assert_eq!(row, "hel");
433 }
434
435 #[test]
436 fn explicit_height_drops_extra_lines() {
437 let grid = BoxStyle::new(Style::default()).height(1).render("a\nb\nc");
438 assert_eq!(grid.height(), 1);
439 assert_eq!(grid.get(0, 0).glyph(), 'a');
440 }
441
442 #[test]
443 fn padding_surrounds_content_with_the_box_style() {
444 let grid = BoxStyle::new(Style::default())
445 .padding(Sides::all(1))
446 .render("x");
447 assert_eq!((grid.width(), grid.height()), (3, 3));
449 assert_eq!(grid.get(1, 1).glyph(), 'x');
450 assert_eq!(grid.get(0, 0).glyph(), ' ');
451 }
452
453 #[test]
454 fn border_draws_a_box_around_padding_and_content() {
455 let grid = BoxStyle::new(Style::default()).border(true).render("x");
456 assert_eq!((grid.width(), grid.height()), (3, 3));
458 let rows = glyphs(&grid);
459 assert_eq!(rows[0], "┌─┐");
460 assert_eq!(rows[1], "│x│");
461 assert_eq!(rows[2], "└─┘");
462 }
463
464 #[test]
465 fn margin_is_left_transparent_outside_the_border() {
466 let grid = BoxStyle::new(Style::default())
467 .margin(Sides::all(1))
468 .render("x");
469 assert_eq!((grid.width(), grid.height()), (3, 3));
473 assert!(grid.get(0, 0).is_empty());
474 assert_eq!(grid.get(1, 1).glyph(), 'x');
475 }
476
477 #[test]
478 fn wide_characters_push_later_columns_over_by_their_width() {
479 let grid = BoxStyle::new(Style::default()).render("aあb");
488 assert_eq!(grid.width(), 4);
489 assert_eq!(grid.get(0, 0).glyph(), 'a');
490 assert_eq!(grid.get(1, 0).glyph(), 'あ');
491 assert_eq!(grid.get(3, 0).glyph(), 'b');
492 }
493
494 #[test]
495 fn border_with_empty_content_is_still_at_least_a_2x2_box() {
496 let grid = BoxStyle::new(Style::default()).border(true).render("");
499 assert_eq!((grid.width(), grid.height()), (2, 3));
500 let rows = glyphs(&grid);
501 assert_eq!(rows[0], "┌┐");
502 assert_eq!(rows[2], "└┘");
503 }
504
505 #[test]
506 #[cfg(feature = "egc")]
507 fn render_wrapped_word_wraps_to_the_explicit_width() {
508 let grid = BoxStyle::new(Style::default())
511 .width(10)
512 .render_wrapped("the quick brown fox jumps");
513 assert_eq!(grid.width(), 10);
514 let rows = glyphs(&grid);
515 assert_eq!(rows[0].trim_end(), "the quick");
516 assert_eq!(rows[1].trim_end(), "brown fox");
517 assert_eq!(rows[2].trim_end(), "jumps");
518 }
519
520 #[test]
521 #[cfg(feature = "egc")]
522 fn render_wrapped_without_an_explicit_width_measures_but_does_not_wrap() {
523 let grid = BoxStyle::new(Style::default()).render_wrapped("hi");
526 assert_eq!((grid.width(), grid.height()), (2, 1));
527 assert_eq!(grid.get(0, 0).glyph(), 'h');
528 assert_eq!(grid.get(1, 0).glyph(), 'i');
529 }
530
531 #[test]
532 #[cfg(feature = "egc")]
533 fn render_wrapped_respects_padding_and_border_like_render() {
534 let grid = BoxStyle::new(Style::default())
535 .border(true)
536 .padding(Sides::all(1))
537 .width(3)
538 .render_wrapped("hi");
539 assert_eq!((grid.width(), grid.height()), (7, 5));
542 assert_eq!(grid.get(2, 2).glyph(), 'h');
543 assert_eq!(grid.get(3, 2).glyph(), 'i');
544 }
545
546 #[test]
547 fn boxed_widget_places_the_box_at_the_areas_top_left() {
548 use retroglyph_core::Headless;
549
550 let styled = BoxStyle::new(Style::default()).border(true).text("hi");
551 let mut term = Terminal::new(Headless::new(10, 6));
552 styled.render(Rect::new(2, 1, 10, 6), &mut term);
553
554 assert_eq!(term.grid().get(2, 1).glyph(), '┌');
557 assert_eq!(term.grid().get(3, 2).glyph(), 'h');
558 assert_eq!(term.grid().get(4, 2).glyph(), 'i');
559 assert_eq!(term.grid().get(5, 3).glyph(), '┘');
560 }
561}