BlueGit

ict rusty-teams

Files

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

format_toolbar.rs

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