BlueGit

ict rusty-teams

Files

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

format_toolbar.rs

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