Debian Codegraph @

helix-term/src/ui/overlay.rs

raw symbols SCIP
1 use helix_core::Position;
2 use helix_view::{
3 graphics::{CursorKind, Rect},
4 Editor,
5 };
6 use tui::buffer::Buffer;
7
8 use crate::compositor::{Component, Context, Event, EventResult};
9
10 pub const FULL_OVERLAID_MAX_WIDTH: u16 = 200;
11
12 /// Contains a component placed in the center of the parent component
13 pub struct Overlay<T> {
14 /// Child component
15 pub content: T,
16 /// Function to compute the size and position of the child component
17 pub calc_child_size: Box<dyn Fn(Rect) -> Rect>,
18 }
19
20 /// Surrounds the component with a margin of 5% on each side, and an additional 2 rows at the bottom
21 pub fn overlaid<T>(content: T) -> Overlay<T> {
22 Overlay {
23 content,
24 calc_child_size: Box::new(|rect: Rect| {
25 let percentage = if rect.width < FULL_OVERLAID_MAX_WIDTH {
26 100
27 } else {
28 90
29 };
30 clip_rect_relative(rect.clip_bottom(2), percentage, percentage)
31 }),
32 }
33 }
34
35 fn clip_rect_relative(rect: Rect, percent_horizontal: u8, percent_vertical: u8) -> Rect {
36 fn mul_and_cast(size: u16, factor: u8) -> u16 {
37 ((size as u32) * (factor as u32) / 100).try_into().unwrap()
38 }
39
40 let inner_w = mul_and_cast(rect.width, percent_horizontal);
41 let inner_h = mul_and_cast(rect.height, percent_vertical);
42
43 let offset_x = rect.width.saturating_sub(inner_w) / 2;
44 let offset_y = rect.height.saturating_sub(inner_h) / 2;
45
46 Rect {
47 x: rect.x + offset_x,
48 y: rect.y + offset_y,
49 width: inner_w,
50 height: inner_h,
51 }
52 }
53
54 impl<T: Component + 'static> Component for Overlay<T> {
55 fn render(&mut self, area: Rect, frame: &mut Buffer, ctx: &mut Context) {
56 let dimensions = (self.calc_child_size)(area);
57 self.content.render(dimensions, frame, ctx)
58 }
59
60 fn required_size(&mut self, (width, height): (u16, u16)) -> Option<(u16, u16)> {
61 let area = Rect {
62 x: 0,
63 y: 0,
64 width,
65 height,
66 };
67 let dimensions = (self.calc_child_size)(area);
68 let viewport = (dimensions.width, dimensions.height);
69 let _ = self.content.required_size(viewport)?;
70 Some((width, height))
71 }
72
73 fn handle_event(&mut self, event: &Event, ctx: &mut Context) -> EventResult {
74 self.content.handle_event(event, ctx)
75 }
76
77 fn cursor(&self, area: Rect, ctx: &Editor) -> (Option<Position>, CursorKind) {
78 let dimensions = (self.calc_child_size)(area);
79 self.content.cursor(dimensions, ctx)
80 }
81
82 fn id(&self) -> Option<&'static str> {
83 self.content.id()
84 }
85 }