BlueGit

ict rusty-teams

Files

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

format_toolbar.rs

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