BlueGit

ict rusty-teams

Files

rusty-teams / crates / app / src / views / format_toolbar.rs

format_toolbar.rs

format_toolbar.rs 10.8 KiB Download Raw
1use std::rc::Rc;
2
3use gpui_kit::component::input::{Input, InputState};
4use gpui_kit::component::{h_flex, tooltip::Tooltip, v_flex};
5use gpui_kit::prelude::FluentBuilder as _;
6use gpui_kit::*;
7use teams_core::FormatState;
8
9use super::widgets::symbol;
10use crate::theme;
11
12const PADDING: f32 = 4.;
13const BUTTON: f32 = 28.;
14const BUTTON_GAP: f32 = 2.;
15const SEPARATOR_MARGIN: f32 = 4.;
16const GAP: f32 = 8.;
17const ARROW_WIDTH: f32 = 14.;
18const ARROW_HEIGHT: f32 = 7.;
19const ARROW_MARGIN: f32 = 12.;
20const LINK_FIELD_WIDTH: f32 = 240.;
21const APPLY_WIDTH: f32 = 64.;
22const ACTIVE_ALPHA: f32 = 0.22;
23
24#[derive(Debug, Clone, Copy, PartialEq, Eq)]
25pub enum FormatButton {
26 Bold,
27 Italic,
28 Underline,
29 Strike,
30 Code,
31 Link,
32 Bulleted,
33 Numbered,
34 Quote,
35}
36
37pub const GROUPS: [&[FormatButton]; 3] = [
38 &[
39 FormatButton::Bold,
40 FormatButton::Italic,
41 FormatButton::Underline,
42 FormatButton::Strike,
43 ],
44 &[FormatButton::Code, FormatButton::Link],
45 &[
46 FormatButton::Bulleted,
47 FormatButton::Numbered,
48 FormatButton::Quote,
49 ],
50];
51
52impl FormatButton {
53 fn tooltip(self) -> &'static str {
54 match self {
55 FormatButton::Bold => "Bold (Ctrl+B)",
56 FormatButton::Italic => "Italic (Ctrl+I)",
57 FormatButton::Underline => "Underline (Ctrl+U)",
58 FormatButton::Strike => "Strikethrough (Ctrl+Shift+X)",
59 FormatButton::Code => "Code (Ctrl+Shift+C)",
60 FormatButton::Link => "Link (Ctrl+K)",
61 FormatButton::Bulleted => "Bulleted list",
62 FormatButton::Numbered => "Numbered list",
63 FormatButton::Quote => "Quote",
64 }
65 }
66
67 fn content(self, color: Hsla) -> AnyElement {
68 let letter = |text: &'static str| div().text_size(px(15.)).text_color(color).child(text);
69 match self {
70 FormatButton::Bold => letter("B").font_weight(FontWeight::BOLD).into_any_element(),
71 FormatButton::Italic => letter("I").italic().into_any_element(),
72 FormatButton::Underline => letter("U").underline().into_any_element(),
73 FormatButton::Strike => letter("S").line_through().into_any_element(),
74 FormatButton::Code => symbol("code", 18., color).into_any_element(),
75 FormatButton::Link => symbol("link", 18., color).into_any_element(),
76 FormatButton::Bulleted => symbol("format_list_bulleted", 18., color).into_any_element(),
77 FormatButton::Numbered => symbol("format_list_numbered", 18., color).into_any_element(),
78 FormatButton::Quote => symbol("format_quote", 18., color).into_any_element(),
79 }
80 }
81}
82
83pub fn bar_width() -> f32 {
84 let buttons: usize = GROUPS.iter().map(|group| group.len()).sum();
85 let gaps: usize = GROUPS.iter().map(|group| group.len() - 1).sum();
86 let separators = (GROUPS.len() - 1) as f32 * (1. + 2. * SEPARATOR_MARGIN);
87 2. * PADDING + buttons as f32 * BUTTON + gaps as f32 * BUTTON_GAP + separators
88}
89
90pub fn link_width() -> f32 {
91 2. * PADDING + LINK_FIELD_WIDTH + BUTTON_GAP * 2. + APPLY_WIDTH
92}
93
94#[derive(Debug, Clone, Copy, PartialEq)]
95pub struct Placement {
96 pub left: Pixels,
97 pub bottom: Pixels,
98 pub arrow_x: Pixels,
99}
100
101/// Centered over `center_x`, `GAP` above `top`, kept between the composer edges.
102pub fn place(center_x: Pixels, top: Pixels, edges: (Pixels, Pixels), width: f32) -> Placement {
103 let width = px(width);
104 let (left_edge, right_edge) = edges;
105 let left = (center_x - width / 2.)
106 .min(right_edge - width)
107 .max(left_edge);
108 Placement {
109 left,
110 bottom: top - px(GAP),
111 arrow_x: (center_x - left)
112 .max(px(ARROW_MARGIN))
113 .min(width - px(ARROW_MARGIN)),
114 }
115}
116
117pub type PressHandler = Rc<dyn Fn(FormatButton, &mut Window, &mut App)>;
118pub type ApplyHandler = Rc<dyn Fn(&mut Window, &mut App)>;
119
120pub enum Mode<'a> {
121 Bar {
122 state: &'a dyn Fn(FormatButton) -> FormatState,
123 on_press: PressHandler,
124 },
125 Link {
126 field: &'a Entity<InputState>,
127 refused: bool,
128 on_apply: ApplyHandler,
129 },
130}
131
132fn button(format: FormatButton, state: FormatState, on_press: PressHandler) -> impl IntoElement {
133 let on = state == FormatState::On;
134 let color = if on {
135 theme::accent_soft()
136 } else {
137 theme::text_soft()
138 };
139 div()
140 .id(ElementId::Name(format!("format-{format:?}").into()))
141 .relative()
142 .size(px(BUTTON))
143 .flex()
144 .flex_none()
145 .items_center()
146 .justify_center()
147 .rounded(px(6.))
148 .border_1()
149 .border_color(transparent_black())
150 .cursor_pointer()
151 .when(on, |button| {
152 button.bg(theme::accent().opacity(ACTIVE_ALPHA))
153 })
154 .hover(|button| button.border_color(theme::border_strong()))
155 .tooltip(move |window, cx| Tooltip::new(format.tooltip()).build(window, cx))
156 .child(format.content(color))
157 .when(state == FormatState::Mixed, |button| {
158 button.child(
159 div()
160 .absolute()
161 .bottom(px(2.))
162 .left(px(7.))
163 .w(px(BUTTON - 16.))
164 .h(px(2.))
165 .rounded(px(1.))
166 .bg(theme::accent()),
167 )
168 })
169 .on_mouse_down(MouseButton::Left, |_, window, cx| {
170 window.prevent_default();
171 cx.stop_propagation();
172 })
173 .on_click(move |_, window, cx| on_press(format, window, cx))
174}
175
176fn separator() -> Div {
177 div()
178 .w(px(1.))
179 .h(px(BUTTON - 8.))
180 .mx(px(SEPARATOR_MARGIN))
181 .bg(theme::border_strong())
182}
183
184fn bar(state: &dyn Fn(FormatButton) -> FormatState, on_press: PressHandler) -> Div {
185 let mut row = h_flex().gap(px(BUTTON_GAP)).items_center();
186 for (index, group) in GROUPS.iter().enumerate() {
187 if index > 0 {
188 row = row.child(separator());
189 }
190 for format in group.iter().copied() {
191 row = row.child(button(format, state(format), on_press.clone()));
192 }
193 }
194 row
195}
196
197fn link_editor(field: &Entity<InputState>, refused: bool, on_apply: ApplyHandler) -> Div {
198 let row = h_flex()
199 .gap(px(BUTTON_GAP * 2.))
200 .items_center()
201 .child(
202 div()
203 .w(px(LINK_FIELD_WIDTH))
204 .h(px(BUTTON))
205 .rounded(px(6.))
206 .border_1()
207 .border_color(if refused {
208 theme::red()
209 } else {
210 theme::accent()
211 })
212 .bg(theme::surface())
213 .child(Input::new(field).appearance(false).bordered(false)),
214 )
215 .child(
216 div()
217 .id("format-link-apply")
218 .w(px(APPLY_WIDTH))
219 .h(px(BUTTON))
220 .flex()
221 .items_center()
222 .justify_center()
223 .rounded(px(6.))
224 .bg(theme::accent())
225 .text_color(theme::on_accent())
226 .text_size(px(13.))
227 .font_weight(FontWeight::SEMIBOLD)
228 .cursor_pointer()
229 .hover(|button| button.opacity(0.9))
230 .child("Apply")
231 .on_mouse_down(MouseButton::Left, |_, window, cx| {
232 window.prevent_default();
233 cx.stop_propagation();
234 })
235 .on_click(move |_, window, cx| on_apply(window, cx)),
236 );
237 v_flex().child(row).when(refused, |editor| {
238 editor.child(
239 div()
240 .pt(px(4.))
241 .px(px(2.))
242 .text_size(px(11.5))
243 .text_color(theme::red_soft())
244 .child("Only http, https and mailto links"),
245 )
246 })
247}
248
249fn arrow(offset: Pixels) -> impl IntoElement {
250 canvas(
251 |_, _, _| {},
252 move |bounds, _, window, _| {
253 let tip = point(bounds.origin.x + offset, bounds.origin.y + px(ARROW_HEIGHT));
254 for (inset, color) in [(0., theme::border_strong()), (1.5, theme::surface_raised())] {
255 let mut builder = PathBuilder::fill();
256 builder.move_to(point(
257 tip.x - px(ARROW_WIDTH / 2. - inset),
258 bounds.origin.y - px(1.),
259 ));
260 builder.line_to(point(
261 tip.x + px(ARROW_WIDTH / 2. - inset),
262 bounds.origin.y - px(1.),
263 ));
264 builder.line_to(point(tip.x, tip.y - px(inset)));
265 builder.close();
266 if let Ok(path) = builder.build() {
267 window.paint_path(path, color);
268 }
269 }
270 },
271 )
272 .w_full()
273 .h(px(ARROW_HEIGHT))
274}
275
276pub fn render(placement: Placement, mode: Mode<'_>) -> AnyElement {
277 let content = match mode {
278 Mode::Bar { state, on_press } => bar(state, on_press),
279 Mode::Link {
280 field,
281 refused,
282 on_apply,
283 } => link_editor(field, refused, on_apply),
284 };
285 deferred(
286 anchored()
287 .position(point(placement.left, placement.bottom))
288 .anchor(Anchor::BottomLeft)
289 .child(
290 v_flex()
291 .id("format-toolbar")
292 .occlude()
293 .child(
294 div()
295 .p(px(PADDING))
296 .rounded(px(8.))
297 .border_1()
298 .border_color(theme::border_strong())
299 .bg(theme::surface_raised())
300 .shadow_lg()
301 .child(content),
302 )
303 .child(arrow(placement.arrow_x)),
304 ),
305 )
306 .with_priority(1)
307 .into_any_element()
308}
309
310#[cfg(test)]
311mod tests {
312 use gpui_kit::px;
313
314 use super::{ARROW_MARGIN, BUTTON, GROUPS, bar_width, place};
315
316 #[test]
317 fn the_bar_centers_over_the_selection() {
318 let placement = place(px(400.), px(300.), (px(100.), px(900.)), 200.);
319 assert_eq!(placement.left, px(300.));
320 assert_eq!(placement.bottom, px(292.));
321 assert_eq!(placement.arrow_x, px(100.));
322 }
323
324 #[test]
325 fn the_bar_stays_inside_the_composer_and_the_arrow_follows_the_selection() {
326 let near_left = place(px(120.), px(300.), (px(100.), px(900.)), 200.);
327 assert_eq!(near_left.left, px(100.));
328 assert_eq!(near_left.arrow_x, px(20.));
329 let near_right = place(px(899.), px(300.), (px(100.), px(900.)), 200.);
330 assert_eq!(near_right.left, px(700.));
331 assert_eq!(near_right.arrow_x, px(200. - ARROW_MARGIN));
332 }
333
334 #[test]
335 fn the_bar_holds_nine_buttons_in_three_groups() {
336 assert_eq!(GROUPS.iter().map(|group| group.len()).sum::<usize>(), 9);
337 assert!(bar_width() > 9. * BUTTON);
338 }
339}