BlueGit

ict rusty-teams

Files

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

format_toolbar.rs

format_toolbar.rs 12.5 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 .border_1()
198 .border_color(transparent_black())
199 .cursor_pointer()
200 .when(on, |button| {
201 button.bg(theme::accent().opacity(ACTIVE_ALPHA))
202 })
203 .hover(|button| button.border_color(theme::border_strong()))
204 .tooltip(move |window, cx| Tooltip::new(format.tooltip()).build(window, cx))
205 .child(format.content(color))
206 .when(state == FormatState::Mixed, |button| {
207 button.child(
208 div()
209 .absolute()
210 .bottom(px(2.))
211 .left(px(7.))
212 .w(px(BUTTON - 16.))
213 .h(px(2.))
214 .rounded(px(1.))
215 .bg(theme::accent()),
216 )
217 })
218 .on_mouse_down(MouseButton::Left, |_, window, cx| {
219 window.prevent_default();
220 cx.stop_propagation();
221 })
222 .on_click(move |_, window, cx| on_press(format, window, cx))
223}
224
225fn separator() -> Div {
226 div()
227 .w(px(1.))
228 .h(px(BUTTON - 8.))
229 .mx(px(SEPARATOR_MARGIN))
230 .bg(theme::border_strong())
231}
232
233fn bar(state: &dyn Fn(FormatButton) -> FormatState, on_press: PressHandler) -> Div {
234 let mut row = h_flex().gap(px(BUTTON_GAP)).items_center();
235 for (index, group) in GROUPS.iter().enumerate() {
236 if index > 0 {
237 row = row.child(separator());
238 }
239 for format in group.iter().copied() {
240 row = row.child(button(format, state(format), on_press.clone()));
241 }
242 }
243 row
244}
245
246fn link_editor(field: &Entity<InputState>, refused: bool, on_apply: ApplyHandler) -> Div {
247 let row = h_flex()
248 .gap(px(BUTTON_GAP * 2.))
249 .items_center()
250 .child(
251 div()
252 .w(px(LINK_FIELD_WIDTH))
253 .h(px(BUTTON))
254 .rounded(px(6.))
255 .border_1()
256 .border_color(if refused {
257 theme::red()
258 } else {
259 theme::accent()
260 })
261 .bg(theme::surface())
262 .child(Input::new(field).appearance(false).bordered(false)),
263 )
264 .child(
265 div()
266 .id("format-link-apply")
267 .w(px(APPLY_WIDTH))
268 .h(px(BUTTON))
269 .flex()
270 .items_center()
271 .justify_center()
272 .rounded(px(6.))
273 .bg(theme::accent())
274 .text_color(theme::on_accent())
275 .text_size(px(13.))
276 .font_weight(FontWeight::SEMIBOLD)
277 .cursor_pointer()
278 .hover(|button| button.opacity(0.9))
279 .child("Apply")
280 .on_mouse_down(MouseButton::Left, |_, window, cx| {
281 window.prevent_default();
282 cx.stop_propagation();
283 })
284 .on_click(move |_, window, cx| on_apply(window, cx)),
285 );
286 v_flex().child(row).when(refused, |editor| {
287 editor.child(
288 div()
289 .pt(px(4.))
290 .px(px(2.))
291 .text_size(px(11.5))
292 .text_color(theme::red_soft())
293 .child("Only http, https and mailto links"),
294 )
295 })
296}
297
298fn arrow(offset: Pixels) -> impl IntoElement {
299 canvas(
300 |_, _, _| {},
301 move |bounds, _, window, _| {
302 let tip = point(bounds.origin.x + offset, bounds.origin.y + px(ARROW_HEIGHT));
303 for (inset, color) in [(0., theme::border_strong()), (1.5, theme::surface_raised())] {
304 let mut builder = PathBuilder::fill();
305 builder.move_to(point(
306 tip.x - px(ARROW_WIDTH / 2. - inset),
307 bounds.origin.y - px(1.),
308 ));
309 builder.line_to(point(
310 tip.x + px(ARROW_WIDTH / 2. - inset),
311 bounds.origin.y - px(1.),
312 ));
313 builder.line_to(point(tip.x, tip.y - px(inset)));
314 builder.close();
315 if let Ok(path) = builder.build() {
316 window.paint_path(path, color);
317 }
318 }
319 },
320 )
321 .w_full()
322 .h(px(ARROW_HEIGHT))
323}
324
325pub fn render(placement: Placement, mode: Mode<'_>) -> AnyElement {
326 let content = match mode {
327 Mode::Bar { state, on_press } => bar(state, on_press),
328 Mode::Link {
329 field,
330 refused,
331 on_apply,
332 } => link_editor(field, refused, on_apply),
333 };
334 deferred(
335 anchored()
336 .position(point(placement.left, placement.bottom))
337 .anchor(Anchor::BottomLeft)
338 .child(
339 v_flex()
340 .id("format-toolbar")
341 .occlude()
342 .child(
343 div()
344 .p(px(PADDING))
345 .rounded(px(8.))
346 .border_1()
347 .border_color(theme::border_strong())
348 .bg(theme::surface_raised())
349 .shadow_lg()
350 .child(content),
351 )
352 .child(arrow(placement.arrow_x)),
353 ),
354 )
355 .with_priority(1)
356 .into_any_element()
357}
358
359#[cfg(test)]
360mod tests {
361 use gpui_kit::px;
362
363 use super::{ARROW_MARGIN, BUTTON, GROUPS, bar_width, place};
364
365 #[test]
366 fn the_bar_centers_over_the_selection() {
367 let placement = place(px(400.), px(300.), (px(100.), px(900.)), 200.);
368 assert_eq!(placement.left, px(300.));
369 assert_eq!(placement.bottom, px(292.));
370 assert_eq!(placement.arrow_x, px(100.));
371 }
372
373 #[test]
374 fn the_bar_stays_inside_the_composer_and_the_arrow_follows_the_selection() {
375 let near_left = place(px(120.), px(300.), (px(100.), px(900.)), 200.);
376 assert_eq!(near_left.left, px(100.));
377 assert_eq!(near_left.arrow_x, px(20.));
378 let near_right = place(px(899.), px(300.), (px(100.), px(900.)), 200.);
379 assert_eq!(near_right.left, px(700.));
380 assert_eq!(near_right.arrow_x, px(200. - ARROW_MARGIN));
381 }
382
383 #[test]
384 fn the_bar_holds_fourteen_buttons_in_five_groups() {
385 assert_eq!(GROUPS.iter().map(|group| group.len()).sum::<usize>(), 14);
386 assert!(bar_width() > 14. * BUTTON);
387 }
388}