BlueGit

ict rusty-teams

Files

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

format_toolbar.rs

format_toolbar.rs 17.2 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 DISABLED_OPACITY: f32 = 0.4;
24const SMALL_LETTER: f32 = 11.;
25const NORMAL_LETTER: f32 = 15.;
26const LARGE_LETTER: f32 = 19.;
27const SCRIPT_LETTER: f32 = 10.;
28const SCRIPT_SHIFT: f32 = 4.;
29
30#[derive(Debug, Clone, Copy, PartialEq, Eq)]
31pub enum FormatButton {
32 Bold,
33 Italic,
34 Underline,
35 Strike,
36 Superscript,
37 Subscript,
38 SizeSmall,
39 SizeNormal,
40 SizeLarge,
41 Code,
42 Link,
43 Bulleted,
44 Numbered,
45 Quote,
46 Table,
47 TableInsertLine,
48 TableRemoveLine,
49}
50
51const STYLE_GROUP: &[FormatButton] = &[
52 FormatButton::Bold,
53 FormatButton::Italic,
54 FormatButton::Underline,
55 FormatButton::Strike,
56];
57const SCRIPT_GROUP: &[FormatButton] = &[FormatButton::Superscript, FormatButton::Subscript];
58const SIZE_GROUP: &[FormatButton] = &[
59 FormatButton::SizeSmall,
60 FormatButton::SizeNormal,
61 FormatButton::SizeLarge,
62];
63const INLINE_GROUP: &[FormatButton] = &[FormatButton::Code, FormatButton::Link];
64const LINE_GROUP: &[FormatButton] = &[
65 FormatButton::Bulleted,
66 FormatButton::Numbered,
67 FormatButton::Quote,
68];
69const TABLE_GROUP: &[FormatButton] = &[
70 FormatButton::Table,
71 FormatButton::TableInsertLine,
72 FormatButton::TableRemoveLine,
73];
74
75/// The floating bar over a selection: text formats only, tables live in the format bar.
76pub const SELECTION_GROUPS: [&[FormatButton]; 5] = [
77 STYLE_GROUP,
78 SCRIPT_GROUP,
79 SIZE_GROUP,
80 INLINE_GROUP,
81 LINE_GROUP,
82];
83
84/// The format bar the Format button opens, table group second to last like Teams.
85pub const BAR_GROUPS: [&[FormatButton]; 6] = [
86 STYLE_GROUP,
87 SCRIPT_GROUP,
88 SIZE_GROUP,
89 INLINE_GROUP,
90 TABLE_GROUP,
91 LINE_GROUP,
92];
93
94pub const TOGGLE_SHORTCUT: &str = "Ctrl+Shift+X";
95
96pub fn toggle_tooltip(open: bool) -> String {
97 let label = if open {
98 "Hide Formatting options"
99 } else {
100 "Show Formatting options"
101 };
102 format!("{label} ({TOGGLE_SHORTCUT})")
103}
104
105pub fn toggle_symbol(open: bool) -> &'static str {
106 if open {
107 "fluent_text_edit_style_filled"
108 } else {
109 "fluent_text_edit_style"
110 }
111}
112
113#[derive(Debug, Clone, Copy, PartialEq, Eq)]
114pub struct ButtonState {
115 pub format: FormatState,
116 pub enabled: bool,
117}
118
119impl ButtonState {
120 pub fn enabled(format: FormatState) -> Self {
121 ButtonState {
122 format,
123 enabled: true,
124 }
125 }
126
127 pub fn disabled() -> Self {
128 ButtonState {
129 format: FormatState::Off,
130 enabled: false,
131 }
132 }
133}
134
135impl FormatButton {
136 fn tooltip(self) -> &'static str {
137 match self {
138 FormatButton::Bold => "Bold (Ctrl+B)",
139 FormatButton::Italic => "Italic (Ctrl+I)",
140 FormatButton::Underline => "Underline (Ctrl+U)",
141 FormatButton::Strike => "Strikethrough (Ctrl+Alt+X)",
142 FormatButton::Superscript => "Superscript (Ctrl+Shift+=)",
143 FormatButton::Subscript => "Subscript (Ctrl+=)",
144 FormatButton::SizeSmall => "Small text",
145 FormatButton::SizeNormal => "Normal text",
146 FormatButton::SizeLarge => "Large text",
147 FormatButton::Code => "Code (Ctrl+Shift+C)",
148 FormatButton::Link => "Link (Ctrl+K)",
149 FormatButton::Bulleted => "Bulleted list",
150 FormatButton::Numbered => "Numbered list",
151 FormatButton::Quote => "Quote",
152 FormatButton::Table => "Insert table",
153 FormatButton::TableInsertLine => "Insert column or row (Ctrl+Alt+=)",
154 FormatButton::TableRemoveLine => "Delete column, row, or table (Ctrl+Alt+-)",
155 }
156 }
157
158 fn content(self, color: Hsla) -> AnyElement {
159 let letter = |text: &'static str| div().text_size(px(15.)).text_color(color).child(text);
160 match self {
161 FormatButton::Bold => letter("B").font_weight(FontWeight::BOLD).into_any_element(),
162 FormatButton::Italic => letter("I").italic().into_any_element(),
163 FormatButton::Underline => letter("U").underline().into_any_element(),
164 FormatButton::Strike => letter("S").line_through().into_any_element(),
165 FormatButton::Superscript => script("x", "2", true, color),
166 FormatButton::Subscript => script("x", "2", false, color),
167 FormatButton::SizeSmall => sized_letter(SMALL_LETTER, color),
168 FormatButton::SizeNormal => sized_letter(NORMAL_LETTER, color),
169 FormatButton::SizeLarge => sized_letter(LARGE_LETTER, color),
170 FormatButton::Code => symbol("code", 18., color).into_any_element(),
171 FormatButton::Link => symbol("link", 18., color).into_any_element(),
172 FormatButton::Bulleted => symbol("format_list_bulleted", 18., color).into_any_element(),
173 FormatButton::Numbered => symbol("format_list_numbered", 18., color).into_any_element(),
174 FormatButton::Quote => symbol("format_quote", 18., color).into_any_element(),
175 FormatButton::Table => symbol("table", 18., color).into_any_element(),
176 FormatButton::TableInsertLine => {
177 symbol("fluent_table_add", 20., color).into_any_element()
178 }
179 FormatButton::TableRemoveLine => {
180 symbol("fluent_table_dismiss", 20., color).into_any_element()
181 }
182 }
183 }
184}
185
186fn script(base: &'static str, mark: &'static str, raised: bool, color: Hsla) -> AnyElement {
187 h_flex()
188 .items_baseline()
189 .text_color(color)
190 .child(div().text_size(px(15.)).child(base))
191 .child(
192 div()
193 .text_size(px(SCRIPT_LETTER))
194 .when(raised, |mark| mark.mb(px(SCRIPT_SHIFT)))
195 .when(!raised, |mark| mark.mt(px(SCRIPT_SHIFT)))
196 .child(mark),
197 )
198 .into_any_element()
199}
200
201fn sized_letter(size: f32, color: Hsla) -> AnyElement {
202 div()
203 .text_size(px(size))
204 .text_color(color)
205 .child("A")
206 .into_any_element()
207}
208
209pub fn bar_width() -> f32 {
210 let groups = SELECTION_GROUPS;
211 let buttons: usize = groups.iter().map(|group| group.len()).sum();
212 let gaps: usize = groups.iter().map(|group| group.len() - 1).sum();
213 let separators = (groups.len() - 1) as f32 * (1. + 2. * SEPARATOR_MARGIN);
214 2. * PADDING + buttons as f32 * BUTTON + gaps as f32 * BUTTON_GAP + separators
215}
216
217pub fn link_width() -> f32 {
218 2. * PADDING + LINK_FIELD_WIDTH + BUTTON_GAP * 2. + APPLY_WIDTH
219}
220
221#[derive(Debug, Clone, Copy, PartialEq)]
222pub struct Placement {
223 pub left: Pixels,
224 pub bottom: Pixels,
225 pub arrow_x: Pixels,
226}
227
228/// Centered over `center_x`, `GAP` above `top`, kept between the composer edges.
229pub fn place(center_x: Pixels, top: Pixels, edges: (Pixels, Pixels), width: f32) -> Placement {
230 let width = px(width);
231 let (left_edge, right_edge) = edges;
232 let left = (center_x - width / 2.)
233 .max(left_edge)
234 .min(right_edge - width);
235 Placement {
236 left,
237 bottom: top - px(GAP),
238 arrow_x: (center_x - left)
239 .max(px(ARROW_MARGIN))
240 .min(width - px(ARROW_MARGIN)),
241 }
242}
243
244pub type PressHandler = Rc<dyn Fn(FormatButton, &mut Window, &mut App)>;
245pub type ApplyHandler = Rc<dyn Fn(&mut Window, &mut App)>;
246
247pub enum Mode<'a> {
248 Bar {
249 state: &'a dyn Fn(FormatButton) -> ButtonState,
250 on_press: PressHandler,
251 },
252 Link {
253 field: &'a Entity<InputState>,
254 refused: bool,
255 on_apply: ApplyHandler,
256 },
257}
258
259fn button(
260 format: FormatButton,
261 state: ButtonState,
262 on_press: PressHandler,
263 overlay: Option<AnyElement>,
264) -> impl IntoElement {
265 let on = state.enabled && state.format == FormatState::On;
266 let color = if on {
267 theme::accent_soft()
268 } else {
269 theme::text_soft()
270 };
271 div()
272 .id(ElementId::Name(format!("format-{format:?}").into()))
273 .relative()
274 .size(px(BUTTON))
275 .flex()
276 .flex_none()
277 .items_center()
278 .justify_center()
279 .rounded(px(6.))
280 .tooltip(move |window, cx| Tooltip::new(format.tooltip()).build(window, cx))
281 .child(format.content(color))
282 .on_mouse_down(MouseButton::Left, |_, window, cx| {
283 window.prevent_default();
284 cx.stop_propagation();
285 })
286 .when(!state.enabled, |button| button.opacity(DISABLED_OPACITY))
287 .when(state.enabled, |button| {
288 button
289 .cursor_pointer()
290 .when(on, |button| {
291 button.bg(theme::accent().opacity(ACTIVE_ALPHA))
292 })
293 .hover(|button| button.bg(theme::popup_hover()))
294 .when(state.format == FormatState::Mixed, |button| {
295 button.child(
296 div()
297 .absolute()
298 .bottom(px(2.))
299 .left(px(7.))
300 .w(px(BUTTON - 16.))
301 .h(px(2.))
302 .rounded(px(1.))
303 .bg(theme::accent()),
304 )
305 })
306 .on_click(move |_, window, cx| on_press(format, window, cx))
307 })
308 .children(overlay.map(|overlay| {
309 div().absolute().top(px(BUTTON + GAP / 2.)).left_0().child(
310 deferred(
311 anchored()
312 .snap_to_window_with_margin(px(GAP))
313 .child(overlay),
314 )
315 .with_priority(2),
316 )
317 }))
318}
319
320fn separator() -> Div {
321 div()
322 .w(px(1.))
323 .h(px(BUTTON - 8.))
324 .mx(px(SEPARATOR_MARGIN))
325 .bg(theme::popup_hover())
326}
327
328fn groups_row(
329 groups: &[&[FormatButton]],
330 state: &dyn Fn(FormatButton) -> ButtonState,
331 on_press: PressHandler,
332 overlay: &mut dyn FnMut(FormatButton) -> Option<AnyElement>,
333) -> Div {
334 let mut row = h_flex().flex_wrap().gap(px(BUTTON_GAP)).items_center();
335 for (index, group) in groups.iter().enumerate() {
336 if index > 0 {
337 row = row.child(separator());
338 }
339 for format in group.iter().copied() {
340 row = row.child(button(
341 format,
342 state(format),
343 on_press.clone(),
344 overlay(format),
345 ));
346 }
347 }
348 row
349}
350
351fn bar(state: &dyn Fn(FormatButton) -> ButtonState, on_press: PressHandler) -> Div {
352 groups_row(&SELECTION_GROUPS, state, on_press, &mut |_| None)
353}
354
355/// The format bar inside the composer box. `overlay` hangs a popup under a button.
356pub fn render_format_bar(
357 state: &dyn Fn(FormatButton) -> ButtonState,
358 on_press: PressHandler,
359 overlay: &mut dyn FnMut(FormatButton) -> Option<AnyElement>,
360) -> Div {
361 groups_row(&BAR_GROUPS, state, on_press, overlay)
362}
363
364fn link_editor(field: &Entity<InputState>, refused: bool, on_apply: ApplyHandler) -> Div {
365 let row = h_flex()
366 .gap(px(BUTTON_GAP * 2.))
367 .items_center()
368 .child(
369 div()
370 .w(px(LINK_FIELD_WIDTH))
371 .h(px(BUTTON))
372 .rounded(px(6.))
373 .border_1()
374 .border_color(if refused {
375 theme::red()
376 } else {
377 theme::accent()
378 })
379 .bg(theme::popup_hover())
380 .child(Input::new(field).appearance(false).bordered(false)),
381 )
382 .child(
383 div()
384 .id("format-link-apply")
385 .w(px(APPLY_WIDTH))
386 .h(px(BUTTON))
387 .flex()
388 .items_center()
389 .justify_center()
390 .rounded(px(6.))
391 .bg(theme::accent())
392 .text_color(theme::on_accent())
393 .text_size(px(13.))
394 .font_weight(FontWeight::SEMIBOLD)
395 .cursor_pointer()
396 .hover(|button| button.opacity(0.9))
397 .child("Apply")
398 .on_mouse_down(MouseButton::Left, |_, window, cx| {
399 window.prevent_default();
400 cx.stop_propagation();
401 })
402 .on_click(move |_, window, cx| on_apply(window, cx)),
403 );
404 v_flex().child(row).when(refused, |editor| {
405 editor.child(
406 div()
407 .pt(px(4.))
408 .px(px(2.))
409 .text_size(px(11.5))
410 .text_color(theme::red_soft())
411 .child("Only http, https and mailto links"),
412 )
413 })
414}
415
416fn arrow(offset: Pixels) -> impl IntoElement {
417 canvas(
418 |_, _, _| {},
419 move |bounds, _, window, _| {
420 let tip = point(bounds.origin.x + offset, bounds.origin.y + px(ARROW_HEIGHT));
421 let mut builder = PathBuilder::fill();
422 builder.move_to(point(
423 tip.x - px(ARROW_WIDTH / 2.),
424 bounds.origin.y - px(1.),
425 ));
426 builder.line_to(point(
427 tip.x + px(ARROW_WIDTH / 2.),
428 bounds.origin.y - px(1.),
429 ));
430 builder.line_to(point(tip.x, tip.y));
431 builder.close();
432 if let Ok(path) = builder.build() {
433 window.paint_path(path, theme::popup());
434 }
435 },
436 )
437 .w_full()
438 .h(px(ARROW_HEIGHT))
439}
440
441pub fn render(placement: Placement, mode: Mode<'_>) -> AnyElement {
442 let content = match mode {
443 Mode::Bar { state, on_press } => bar(state, on_press),
444 Mode::Link {
445 field,
446 refused,
447 on_apply,
448 } => link_editor(field, refused, on_apply),
449 };
450 deferred(
451 anchored()
452 .position(point(placement.left, placement.bottom))
453 .anchor(Anchor::BottomLeft)
454 .child(
455 v_flex()
456 .id("format-toolbar")
457 .occlude()
458 .child(
459 div()
460 .p(px(PADDING))
461 .rounded(px(10.))
462 .flyout_surface()
463 .child(content),
464 )
465 .child(arrow(placement.arrow_x)),
466 ),
467 )
468 .with_priority(1)
469 .into_any_element()
470}
471
472#[cfg(test)]
473mod tests {
474 use gpui_kit::px;
475
476 use super::{
477 ARROW_MARGIN, BAR_GROUPS, BUTTON, FormatButton, SELECTION_GROUPS, bar_width, place,
478 toggle_symbol, toggle_tooltip,
479 };
480
481 #[test]
482 fn the_bar_centers_over_the_selection() {
483 let placement = place(px(400.), px(300.), (px(100.), px(900.)), 200.);
484 assert_eq!(placement.left, px(300.));
485 assert_eq!(placement.bottom, px(292.));
486 assert_eq!(placement.arrow_x, px(100.));
487 }
488
489 #[test]
490 fn the_bar_stays_inside_the_composer_and_the_arrow_follows_the_selection() {
491 let near_left = place(px(120.), px(300.), (px(100.), px(900.)), 200.);
492 assert_eq!(near_left.left, px(100.));
493 assert_eq!(near_left.arrow_x, px(20.));
494 let near_right = place(px(899.), px(300.), (px(100.), px(900.)), 200.);
495 assert_eq!(near_right.left, px(700.));
496 assert_eq!(near_right.arrow_x, px(200. - ARROW_MARGIN));
497 }
498
499 #[test]
500 fn a_bar_wider_than_the_composer_ends_at_its_right_edge() {
501 let placement = place(px(560.), px(300.), (px(500.), px(800.)), 400.);
502 assert_eq!(placement.left, px(400.));
503 assert_eq!(placement.arrow_x, px(160.));
504 }
505
506 #[test]
507 fn the_selection_bar_holds_the_text_formats_without_the_table() {
508 assert_eq!(
509 SELECTION_GROUPS
510 .iter()
511 .map(|group| group.len())
512 .sum::<usize>(),
513 14
514 );
515 assert!(
516 SELECTION_GROUPS
517 .iter()
518 .all(|group| !group.contains(&FormatButton::Table))
519 );
520 assert!(bar_width() > 14. * BUTTON);
521 }
522
523 #[test]
524 fn the_format_bar_has_the_teams_table_group_second_to_last() {
525 let table_group = BAR_GROUPS[BAR_GROUPS.len() - 2];
526 assert_eq!(
527 table_group,
528 &[
529 FormatButton::Table,
530 FormatButton::TableInsertLine,
531 FormatButton::TableRemoveLine
532 ][..]
533 );
534 for group in SELECTION_GROUPS {
535 assert!(BAR_GROUPS.contains(&group));
536 }
537 }
538
539 #[test]
540 fn the_format_toggle_reads_like_teams() {
541 assert_eq!(
542 toggle_tooltip(false),
543 "Show Formatting options (Ctrl+Shift+X)"
544 );
545 assert_eq!(
546 toggle_tooltip(true),
547 "Hide Formatting options (Ctrl+Shift+X)"
548 );
549 assert_ne!(toggle_symbol(false), toggle_symbol(true));
550 assert_eq!(FormatButton::Strike.tooltip(), "Strikethrough (Ctrl+Alt+X)");
551 }
552}