BlueGit

ict rusty-teams

Files

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

format_toolbar.rs

format_toolbar.rs 29.7 KiB Download Raw
1use std::rc::Rc;
2
3use gpui_kit::component::input::{Input, InputState};
4use gpui_kit::component::tooltip::PopupTriggerTooltip as _;
5use gpui_kit::component::{h_flex, v_flex};
6use gpui_kit::prelude::FluentBuilder as _;
7use gpui_kit::assets::IconName;
8use gpui_kit::*;
9use teams_core::FormatState;
10
11use super::widgets::{icon, symbol};
12use crate::theme::{self, ElevatedSurface as _};
13
14const PADDING: f32 = 4.;
15const BUTTON: f32 = 28.;
16const BUTTON_GAP: f32 = 2.;
17const SEPARATOR_MARGIN: f32 = 4.;
18const GAP: f32 = 8.;
19const ARROW_WIDTH: f32 = 14.;
20const ARROW_HEIGHT: f32 = 7.;
21const ARROW_MARGIN: f32 = 12.;
22const LINK_FIELD_WIDTH: f32 = 240.;
23const APPLY_WIDTH: f32 = 64.;
24const ACTIVE_ALPHA: f32 = 0.22;
25const DISABLED_OPACITY: f32 = 0.4;
26const SMALL_LETTER: f32 = 11.;
27const NORMAL_LETTER: f32 = 15.;
28const LARGE_LETTER: f32 = 19.;
29const SCRIPT_LETTER: f32 = 10.;
30const SCRIPT_SHIFT: f32 = 4.;
31
32#[derive(Debug, Clone, Copy, PartialEq, Eq)]
33pub enum FormatButton {
34 Bold,
35 Italic,
36 Underline,
37 Strike,
38 Superscript,
39 Subscript,
40 SizeSmall,
41 SizeNormal,
42 SizeLarge,
43 Code,
44 Link,
45 Bulleted,
46 Numbered,
47 Quote,
48 Table,
49 TableInsertLine,
50 TableRemoveLine,
51 Highlight,
52 FontColor,
53 ParagraphStyle,
54 ClearFormatting,
55 Outdent,
56 Indent,
57 CodeBlock,
58 Rule,
59 FontSize,
60 More,
61}
62
63const STYLE_GROUP: &[FormatButton] = &[
64 FormatButton::Bold,
65 FormatButton::Italic,
66 FormatButton::Underline,
67 FormatButton::Strike,
68];
69const SCRIPT_GROUP: &[FormatButton] = &[FormatButton::Superscript, FormatButton::Subscript];
70const SIZE_GROUP: &[FormatButton] = &[FormatButton::FontSize];
71const INLINE_GROUP: &[FormatButton] = &[FormatButton::Code, FormatButton::Link];
72const LINE_GROUP: &[FormatButton] = &[
73 FormatButton::Bulleted,
74 FormatButton::Numbered,
75 FormatButton::Quote,
76];
77const TABLE_GROUP: &[FormatButton] = &[
78 FormatButton::Table,
79 FormatButton::TableInsertLine,
80 FormatButton::TableRemoveLine,
81];
82
83const FONT_GROUP: &[FormatButton] = &[
84 FormatButton::Highlight,
85 FormatButton::FontColor,
86 FormatButton::FontSize,
87 FormatButton::ParagraphStyle,
88 FormatButton::ClearFormatting,
89];
90const PARAGRAPH_GROUP: &[FormatButton] = &[
91 FormatButton::Outdent,
92 FormatButton::Indent,
93 FormatButton::Bulleted,
94 FormatButton::Numbered,
95];
96const INSERT_GROUP: &[FormatButton] = &[
97 FormatButton::Quote,
98 FormatButton::Link,
99 FormatButton::Code,
100 FormatButton::CodeBlock,
101 FormatButton::Rule,
102];
103
104/// The floating bar over a selection: text formats only, tables live in the format bar.
105pub const SELECTION_GROUPS: [&[FormatButton]; 5] = [
106 STYLE_GROUP,
107 SCRIPT_GROUP,
108 SIZE_GROUP,
109 INLINE_GROUP,
110 LINE_GROUP,
111];
112
113/// The format bar the Format button opens, in Teams' group order; Teams' last group (undo,
114/// redo) is left out, so the table group ends the bar.
115pub const BAR_GROUPS: [&[FormatButton]; 6] = [
116 STYLE_GROUP,
117 SCRIPT_GROUP,
118 FONT_GROUP,
119 PARAGRAPH_GROUP,
120 INSERT_GROUP,
121 TABLE_GROUP,
122];
123
124pub const PARAGRAPH_STYLE_WIDTH: f32 = 104.;
125const SEPARATOR_WIDTH: f32 = 1. + 2. * SEPARATOR_MARGIN;
126const MENU_ROW_HEIGHT: f32 = 32.;
127const MENU_ROW_PADDING_X: f32 = 10.;
128const MENU_PADDING: f32 = 4.;
129const MENU_WIDTH: f32 = 220.;
130
131/// The format bar split like Teams' overflow: buttons leave from the end into More options,
132/// each side keeps the group boundaries of its own buttons.
133#[derive(Debug, Clone, PartialEq, Eq)]
134pub struct BarFit {
135 pub visible: Vec<Vec<FormatButton>>,
136 pub overflow: Vec<Vec<FormatButton>>,
137}
138
139fn groups_width<G: AsRef<[FormatButton]>>(groups: &[G]) -> f32 {
140 let buttons = groups.iter().flat_map(|group| group.as_ref().iter());
141 let widths: f32 = buttons.clone().map(|button| button.width()).sum();
142 let gaps = buttons.count().saturating_sub(1) as f32 * BUTTON_GAP;
143 let separators = groups.len().saturating_sub(1) as f32 * (SEPARATOR_WIDTH + BUTTON_GAP);
144 widths + gaps + separators
145}
146
147fn split_groups(groups: &[&[FormatButton]], count: usize) -> BarFit {
148 let mut visible = Vec::new();
149 let mut overflow = Vec::new();
150 let mut taken = 0;
151 for group in groups {
152 let shown = group.len().min(count - taken.min(count));
153 taken += group.len();
154 if shown > 0 {
155 visible.push(group[..shown].to_vec());
156 }
157 if shown < group.len() {
158 overflow.push(group[shown..].to_vec());
159 }
160 }
161 BarFit { visible, overflow }
162}
163
164pub fn fit_groups(available: f32, groups: &[&[FormatButton]]) -> BarFit {
165 let total: usize = groups.iter().map(|group| group.len()).sum();
166 if groups_width(groups) <= available {
167 return split_groups(groups, total);
168 }
169 let more = BUTTON_GAP + FormatButton::More.width();
170 let count = (0..total)
171 .rev()
172 .find(|count| groups_width(&split_groups(groups, *count).visible) + more <= available)
173 .unwrap_or(0);
174 split_groups(groups, count)
175}
176
177pub const TOGGLE_SHORTCUT: &str = "Ctrl+Shift+X";
178
179pub fn toggle_tooltip(open: bool) -> String {
180 let label = if open {
181 "Hide Formatting options"
182 } else {
183 "Show Formatting options"
184 };
185 format!("{label} ({TOGGLE_SHORTCUT})")
186}
187
188pub fn toggle_symbol(open: bool) -> &'static str {
189 if open {
190 "text_format_fill"
191 } else {
192 "text_format"
193 }
194}
195
196#[derive(Debug, Clone, Copy, PartialEq, Eq)]
197pub struct ButtonState {
198 pub format: FormatState,
199 pub enabled: bool,
200 pub label: Option<&'static str>,
201}
202
203impl ButtonState {
204 pub fn enabled(format: FormatState) -> Self {
205 ButtonState {
206 format,
207 enabled: true,
208 label: None,
209 }
210 }
211
212 pub fn disabled() -> Self {
213 ButtonState {
214 format: FormatState::Off,
215 enabled: false,
216 label: None,
217 }
218 }
219
220 pub fn with_label(self, label: &'static str) -> Self {
221 ButtonState {
222 label: Some(label),
223 ..self
224 }
225 }
226}
227
228impl FormatButton {
229 fn tooltip(self) -> &'static str {
230 match self {
231 FormatButton::Bold => "Bold (Ctrl+B)",
232 FormatButton::Italic => "Italic (Ctrl+I)",
233 FormatButton::Underline => "Underline (Ctrl+U)",
234 FormatButton::Strike => "Strikethrough (Ctrl+Alt+X)",
235 FormatButton::Superscript => "Superscript (Ctrl+Shift+=)",
236 FormatButton::Subscript => "Subscript (Ctrl+=)",
237 FormatButton::SizeSmall => "Small text",
238 FormatButton::SizeNormal => "Normal text",
239 FormatButton::SizeLarge => "Large text",
240 FormatButton::Code => "Code (Ctrl+Shift+C)",
241 FormatButton::Link => "Link (Ctrl+K)",
242 FormatButton::Bulleted => "Bulleted list",
243 FormatButton::Numbered => "Numbered list",
244 FormatButton::Quote => "Quote (Ctrl+Alt+4)",
245 FormatButton::Table => "Insert table",
246 FormatButton::TableInsertLine => "Insert column or row (Ctrl+Alt+=)",
247 FormatButton::TableRemoveLine => "Delete column, row, or table (Ctrl+Alt+-)",
248 FormatButton::Highlight => "Text highlight colour",
249 FormatButton::FontColor => "Font colour",
250 FormatButton::ParagraphStyle => "Rich style",
251 FormatButton::ClearFormatting => "Clear all formatting",
252 FormatButton::Outdent => "Decrease indent",
253 FormatButton::Indent => "Increase indent",
254 FormatButton::CodeBlock => "Code block (Ctrl+Shift+B)",
255 FormatButton::Rule => "Insert horizontal rule",
256 FormatButton::FontSize => "Font size",
257 FormatButton::More => "More options",
258 }
259 }
260
261 pub fn menu_label(self) -> &'static str {
262 let tooltip = self.tooltip();
263 tooltip.split(" (").next().unwrap_or(tooltip)
264 }
265
266 fn edits_table(self) -> bool {
267 matches!(
268 self,
269 FormatButton::TableInsertLine | FormatButton::TableRemoveLine
270 )
271 }
272
273 /// Opens a picker or menu below itself instead of acting at once.
274 pub fn opens_popup(self) -> bool {
275 matches!(
276 self,
277 FormatButton::Highlight
278 | FormatButton::FontColor
279 | FormatButton::FontSize
280 | FormatButton::ParagraphStyle
281 | FormatButton::Table
282 | FormatButton::TableInsertLine
283 | FormatButton::TableRemoveLine
284 | FormatButton::More
285 )
286 }
287
288 fn content(self, color: Hsla, label: Option<&'static str>) -> AnyElement {
289 let letter = |text: &'static str| div().text_size(px(15.)).text_color(color).child(text);
290 match self {
291 FormatButton::Bold => letter("B").font_weight(FontWeight::BOLD).into_any_element(),
292 FormatButton::Italic => letter("I").italic().into_any_element(),
293 FormatButton::Underline => letter("U").underline().into_any_element(),
294 FormatButton::Strike => letter("S").line_through().into_any_element(),
295 FormatButton::Superscript => script("x", "2", true, color),
296 FormatButton::Subscript => script("x", "2", false, color),
297 FormatButton::SizeSmall => sized_letter(SMALL_LETTER, color),
298 FormatButton::SizeNormal => sized_letter(NORMAL_LETTER, color),
299 FormatButton::SizeLarge => sized_letter(LARGE_LETTER, color),
300 FormatButton::Code => symbol("code", 18., color).into_any_element(),
301 FormatButton::Link => symbol("link", 18., color).into_any_element(),
302 FormatButton::Bulleted => symbol("format_list_bulleted", 18., color).into_any_element(),
303 FormatButton::Numbered => symbol("format_list_numbered", 18., color).into_any_element(),
304 FormatButton::Quote => symbol("format_quote", 18., color).into_any_element(),
305 FormatButton::Table => symbol("table", 18., color).into_any_element(),
306 FormatButton::TableInsertLine => {
307 symbol("table_chart", 20., color).into_any_element()
308 }
309 FormatButton::TableRemoveLine => {
310 symbol("grid_off", 20., color).into_any_element()
311 }
312 FormatButton::Highlight => symbol("format_ink_highlighter", 20., color).into_any_element(),
313 FormatButton::FontColor => symbol("format_color_text", 20., color).into_any_element(),
314 FormatButton::ParagraphStyle => h_flex()
315 .w_full()
316 .px(px(6.))
317 .gap(px(4.))
318 .items_center()
319 .justify_between()
320 .text_size(px(13.))
321 .text_color(color)
322 .child(label.unwrap_or_default())
323 .child(icon(IconName::ChevronDown, 12., color))
324 .into_any_element(),
325 FormatButton::ClearFormatting => {
326 symbol("format_clear", 20., color).into_any_element()
327 }
328 FormatButton::Outdent => {
329 symbol("format_indent_decrease", 20., color).into_any_element()
330 }
331 FormatButton::Indent => {
332 symbol("format_indent_increase", 20., color).into_any_element()
333 }
334 FormatButton::CodeBlock => symbol("code_blocks", 20., color).into_any_element(),
335 FormatButton::Rule => symbol("horizontal_rule", 20., color).into_any_element(),
336 FormatButton::FontSize => {
337 symbol("format_size", 20., color).into_any_element()
338 }
339 FormatButton::More => icon(IconName::Ellipsis, 18., color).into_any_element(),
340 }
341 }
342
343 fn width(self) -> f32 {
344 match self {
345 FormatButton::ParagraphStyle => PARAGRAPH_STYLE_WIDTH,
346 _ => BUTTON,
347 }
348 }
349}
350
351fn script(base: &'static str, mark: &'static str, raised: bool, color: Hsla) -> AnyElement {
352 h_flex()
353 .items_baseline()
354 .text_color(color)
355 .child(div().text_size(px(15.)).child(base))
356 .child(
357 div()
358 .text_size(px(SCRIPT_LETTER))
359 .when(raised, |mark| mark.mb(px(SCRIPT_SHIFT)))
360 .when(!raised, |mark| mark.mt(px(SCRIPT_SHIFT)))
361 .child(mark),
362 )
363 .into_any_element()
364}
365
366fn sized_letter(size: f32, color: Hsla) -> AnyElement {
367 div()
368 .text_size(px(size))
369 .text_color(color)
370 .child("A")
371 .into_any_element()
372}
373
374pub fn bar_width() -> f32 {
375 2. * PADDING + groups_width(&SELECTION_GROUPS)
376}
377
378pub fn link_width() -> f32 {
379 2. * PADDING + LINK_FIELD_WIDTH + BUTTON_GAP * 2. + APPLY_WIDTH
380}
381
382#[derive(Debug, Clone, Copy, PartialEq)]
383pub struct Placement {
384 pub left: Pixels,
385 pub bottom: Pixels,
386 pub arrow_x: Pixels,
387}
388
389/// Centered over `center_x`, `GAP` above `top`, kept between the composer edges.
390pub fn place(center_x: Pixels, top: Pixels, edges: (Pixels, Pixels), width: f32) -> Placement {
391 let width = px(width);
392 let (left_edge, right_edge) = edges;
393 let left = (center_x - width / 2.)
394 .max(left_edge)
395 .min(right_edge - width);
396 Placement {
397 left,
398 bottom: top - px(GAP),
399 arrow_x: (center_x - left)
400 .max(px(ARROW_MARGIN))
401 .min(width - px(ARROW_MARGIN)),
402 }
403}
404
405pub type PressHandler = Rc<dyn Fn(FormatButton, &mut Window, &mut App)>;
406pub type ApplyHandler = Rc<dyn Fn(&mut Window, &mut App)>;
407
408pub enum Mode<'a> {
409 Bar {
410 state: &'a dyn Fn(FormatButton) -> ButtonState,
411 on_press: PressHandler,
412 overlay: &'a mut dyn FnMut(FormatButton) -> Option<AnyElement>,
413 },
414 Link {
415 field: &'a Entity<InputState>,
416 refused: bool,
417 on_apply: ApplyHandler,
418 },
419}
420
421fn button(
422 format: FormatButton,
423 state: ButtonState,
424 on_press: PressHandler,
425 overlay: Option<AnyElement>,
426) -> impl IntoElement {
427 let on = state.enabled && state.format == FormatState::On;
428 let color = if on {
429 theme::accent_soft()
430 } else {
431 theme::text_soft()
432 };
433 div()
434 .id(ElementId::Name(format!("format-{format:?}").into()))
435 .relative()
436 .w(px(format.width()))
437 .h(px(BUTTON))
438 .flex()
439 .flex_none()
440 .items_center()
441 .justify_center()
442 .rounded(px(6.))
443 .popup_trigger_tooltip_text(format.opens_popup() && on, format.tooltip())
444 .child(format.content(color, state.label))
445 .on_mouse_down(MouseButton::Left, |_, window, cx| {
446 window.prevent_default();
447 cx.stop_propagation();
448 })
449 .when(!state.enabled, |button| button.opacity(DISABLED_OPACITY))
450 .when(state.enabled, |button| {
451 button
452 .cursor_pointer()
453 .when(on, |button| {
454 button.bg(theme::accent().opacity(ACTIVE_ALPHA))
455 })
456 .hover(|button| button.bg(theme::popup_hover()))
457 .when(state.format == FormatState::Mixed, |button| {
458 button.child(
459 div()
460 .absolute()
461 .bottom(px(2.))
462 .left(px(7.))
463 .w(px(BUTTON - 16.))
464 .h(px(2.))
465 .rounded(px(1.))
466 .bg(theme::accent()),
467 )
468 })
469 .on_click(move |_, window, cx| on_press(format, window, cx))
470 })
471 .children(overlay.map(|overlay| overlay_below(overlay, BUTTON + GAP / 2.)))
472}
473
474fn overlay_below(overlay: AnyElement, offset: f32) -> Div {
475 div().absolute().top(px(offset)).left_0().child(
476 deferred(
477 anchored()
478 .snap_to_window_with_margin(px(GAP))
479 .child(overlay),
480 )
481 .with_priority(2),
482 )
483}
484
485fn separator() -> Div {
486 div()
487 .w(px(1.))
488 .h(px(BUTTON - 8.))
489 .mx(px(SEPARATOR_MARGIN))
490 .bg(theme::popup_hover())
491}
492
493fn groups_row<G: AsRef<[FormatButton]>>(
494 groups: &[G],
495 state: &dyn Fn(FormatButton) -> ButtonState,
496 on_press: PressHandler,
497 overlay: &mut dyn FnMut(FormatButton) -> Option<AnyElement>,
498) -> Div {
499 let mut row = h_flex().gap(px(BUTTON_GAP)).items_center();
500 for (index, group) in groups.iter().enumerate() {
501 if index > 0 {
502 row = row.child(separator());
503 }
504 for format in group.as_ref().iter().copied() {
505 row = row.child(button(
506 format,
507 state(format),
508 on_press.clone(),
509 overlay(format),
510 ));
511 }
512 }
513 row
514}
515
516fn bar(
517 state: &dyn Fn(FormatButton) -> ButtonState,
518 on_press: PressHandler,
519 overlay: &mut dyn FnMut(FormatButton) -> Option<AnyElement>,
520) -> Div {
521 groups_row(&SELECTION_GROUPS, state, on_press, overlay)
522}
523
524/// The format bar inside the composer box. `overlay` hangs a popup under a button; the
525/// More button's popup is the overflow menu, built with `render_overflow_menu`.
526pub fn render_format_bar(
527 fit: &BarFit,
528 state: &dyn Fn(FormatButton) -> ButtonState,
529 on_press: PressHandler,
530 overlay: &mut dyn FnMut(FormatButton) -> Option<AnyElement>,
531) -> Div {
532 let row = groups_row(&fit.visible, state, on_press.clone(), overlay);
533 if menu_groups(&fit.overflow, state).is_empty() {
534 return row;
535 }
536 row.child(button(
537 FormatButton::More,
538 state(FormatButton::More),
539 on_press,
540 overlay(FormatButton::More),
541 ))
542}
543
544/// The groups that do not fit, as menu rows with a divider between groups.
545pub fn render_overflow_menu(
546 groups: &[Vec<FormatButton>],
547 state: &dyn Fn(FormatButton) -> ButtonState,
548 on_press: PressHandler,
549 overlay: &mut dyn FnMut(FormatButton) -> Option<AnyElement>,
550) -> Div {
551 let mut menu = v_flex().w(px(MENU_WIDTH)).py(px(MENU_PADDING));
552 for (index, group) in menu_groups(groups, state).iter().enumerate() {
553 if index > 0 {
554 menu = menu.child(
555 div()
556 .w_full()
557 .h(px(1.))
558 .my(px(MENU_PADDING))
559 .bg(theme::popup_hover()),
560 );
561 }
562 for format in group.iter().copied() {
563 menu = menu.child(menu_row(
564 format,
565 state(format),
566 on_press.clone(),
567 overlay(format),
568 ));
569 }
570 }
571 menu
572}
573
574fn menu_groups(
575 groups: &[Vec<FormatButton>],
576 state: &dyn Fn(FormatButton) -> ButtonState,
577) -> Vec<Vec<FormatButton>> {
578 groups
579 .iter()
580 .map(|group| {
581 group
582 .iter()
583 .copied()
584 .filter(|format| !format.edits_table() || state(*format).enabled)
585 .collect::<Vec<_>>()
586 })
587 .filter(|group| !group.is_empty())
588 .collect()
589}
590
591fn menu_row(
592 format: FormatButton,
593 state: ButtonState,
594 on_press: PressHandler,
595 overlay: Option<AnyElement>,
596) -> impl IntoElement {
597 let on = state.enabled && state.format == FormatState::On;
598 let color = if on {
599 theme::accent_soft()
600 } else {
601 theme::text_soft()
602 };
603 let content = match format {
604 FormatButton::ParagraphStyle => symbol("format_h1", 20., color).into_any_element(),
605 _ => format.content(color, None),
606 };
607 div()
608 .id(ElementId::Name(format!("format-overflow-{format:?}").into()))
609 .relative()
610 .mx(px(MENU_PADDING))
611 .h(px(MENU_ROW_HEIGHT))
612 .flex_none()
613 .px(px(MENU_ROW_PADDING_X))
614 .flex()
615 .items_center()
616 .gap(px(GAP))
617 .rounded(px(6.))
618 .child(div().w(px(BUTTON)).flex().justify_center().child(content))
619 .child(
620 div()
621 .flex_1()
622 .text_size(px(13.))
623 .text_color(theme::text())
624 .child(format.menu_label()),
625 )
626 .on_mouse_down(MouseButton::Left, |_, window, cx| {
627 window.prevent_default();
628 cx.stop_propagation();
629 })
630 .when(!state.enabled, |row| row.opacity(DISABLED_OPACITY))
631 .when(state.enabled, |row| {
632 row.cursor_pointer()
633 .when(on, |row| row.bg(theme::accent().opacity(ACTIVE_ALPHA)))
634 .hover(|row| row.bg(theme::popup_hover()))
635 .on_click(move |_, window, cx| on_press(format, window, cx))
636 })
637 .children(overlay.map(|overlay| overlay_below(overlay, MENU_ROW_HEIGHT)))
638}
639
640fn link_editor(field: &Entity<InputState>, refused: bool, on_apply: ApplyHandler) -> Div {
641 let row = h_flex()
642 .gap(px(BUTTON_GAP * 2.))
643 .items_center()
644 .child(
645 div()
646 .w(px(LINK_FIELD_WIDTH))
647 .h(px(BUTTON))
648 .rounded(px(6.))
649 .border_1()
650 .border_color(if refused {
651 theme::red()
652 } else {
653 theme::accent()
654 })
655 .bg(theme::popup_hover())
656 .child(Input::new(field).appearance(false).bordered(false)),
657 )
658 .child(
659 div()
660 .id("format-link-apply")
661 .w(px(APPLY_WIDTH))
662 .h(px(BUTTON))
663 .flex()
664 .items_center()
665 .justify_center()
666 .rounded(px(6.))
667 .bg(theme::accent())
668 .text_color(theme::on_accent())
669 .text_size(px(13.))
670 .font_weight(FontWeight::SEMIBOLD)
671 .cursor_pointer()
672 .hover(|button| button.opacity(0.9))
673 .child("Apply")
674 .on_mouse_down(MouseButton::Left, |_, window, cx| {
675 window.prevent_default();
676 cx.stop_propagation();
677 })
678 .on_click(move |_, window, cx| on_apply(window, cx)),
679 );
680 v_flex().child(row).when(refused, |editor| {
681 editor.child(
682 div()
683 .pt(px(4.))
684 .px(px(2.))
685 .text_size(px(11.5))
686 .text_color(theme::red_soft())
687 .child("Only http, https and mailto links"),
688 )
689 })
690}
691
692fn arrow(offset: Pixels) -> impl IntoElement {
693 canvas(
694 |_, _, _| {},
695 move |bounds, _, window, _| {
696 let tip = point(bounds.origin.x + offset, bounds.origin.y + px(ARROW_HEIGHT));
697 let mut builder = PathBuilder::fill();
698 builder.move_to(point(
699 tip.x - px(ARROW_WIDTH / 2.),
700 bounds.origin.y - px(1.),
701 ));
702 builder.line_to(point(
703 tip.x + px(ARROW_WIDTH / 2.),
704 bounds.origin.y - px(1.),
705 ));
706 builder.line_to(point(tip.x, tip.y));
707 builder.close();
708 if let Ok(path) = builder.build() {
709 window.paint_path(path, theme::popup());
710 }
711 },
712 )
713 .w_full()
714 .h(px(ARROW_HEIGHT))
715}
716
717pub fn render(placement: Placement, mode: Mode<'_>) -> AnyElement {
718 let content = match mode {
719 Mode::Bar {
720 state,
721 on_press,
722 overlay,
723 } => bar(state, on_press, overlay),
724 Mode::Link {
725 field,
726 refused,
727 on_apply,
728 } => link_editor(field, refused, on_apply),
729 };
730 deferred(
731 anchored()
732 .position(point(placement.left, placement.bottom))
733 .anchor(Anchor::BottomLeft)
734 .child(
735 v_flex()
736 .id("format-toolbar")
737 .occlude()
738 .child(
739 div()
740 .p(px(PADDING))
741 .rounded(px(10.))
742 .flyout_surface()
743 .child(content),
744 )
745 .child(arrow(placement.arrow_x)),
746 ),
747 )
748 .with_priority(1)
749 .into_any_element()
750}
751
752#[cfg(test)]
753mod tests {
754 use gpui_kit::px;
755
756 use super::{
757 ARROW_MARGIN, BAR_GROUPS, BUTTON, ButtonState, FormatButton, FormatState,
758 SELECTION_GROUPS, bar_width, fit_groups, groups_width, menu_groups, place, toggle_symbol,
759 toggle_tooltip,
760 };
761
762
763 #[test]
764 fn the_bar_centers_over_the_selection() {
765 let placement = place(px(400.), px(300.), (px(100.), px(900.)), 200.);
766 assert_eq!(placement.left, px(300.));
767 assert_eq!(placement.bottom, px(292.));
768 assert_eq!(placement.arrow_x, px(100.));
769 }
770
771 #[test]
772 fn the_bar_stays_inside_the_composer_and_the_arrow_follows_the_selection() {
773 let near_left = place(px(120.), px(300.), (px(100.), px(900.)), 200.);
774 assert_eq!(near_left.left, px(100.));
775 assert_eq!(near_left.arrow_x, px(20.));
776 let near_right = place(px(899.), px(300.), (px(100.), px(900.)), 200.);
777 assert_eq!(near_right.left, px(700.));
778 assert_eq!(near_right.arrow_x, px(200. - ARROW_MARGIN));
779 }
780
781 #[test]
782 fn a_bar_wider_than_the_composer_ends_at_its_right_edge() {
783 let placement = place(px(560.), px(300.), (px(500.), px(800.)), 400.);
784 assert_eq!(placement.left, px(400.));
785 assert_eq!(placement.arrow_x, px(160.));
786 }
787
788 #[test]
789 fn the_selection_bar_holds_the_text_formats_without_the_table() {
790 assert_eq!(
791 SELECTION_GROUPS
792 .iter()
793 .map(|group| group.len())
794 .sum::<usize>(),
795 12
796 );
797 assert!(
798 SELECTION_GROUPS
799 .iter()
800 .all(|group| !group.contains(&FormatButton::Table))
801 );
802 assert!(SELECTION_GROUPS.iter().any(|group| group == &[FormatButton::FontSize]));
803 assert!(bar_width() > 12. * BUTTON);
804 }
805
806 #[test]
807 fn the_format_bar_follows_the_teams_groups_and_keeps_every_selection_format() {
808 assert_eq!(
809 BAR_GROUPS[BAR_GROUPS.len() - 1],
810 &[
811 FormatButton::Table,
812 FormatButton::TableInsertLine,
813 FormatButton::TableRemoveLine
814 ][..]
815 );
816 assert_eq!(
817 BAR_GROUPS[2][..3],
818 [
819 FormatButton::Highlight,
820 FormatButton::FontColor,
821 FormatButton::FontSize
822 ]
823 );
824 assert_eq!(
825 BAR_GROUPS[3],
826 &[
827 FormatButton::Outdent,
828 FormatButton::Indent,
829 FormatButton::Bulleted,
830 FormatButton::Numbered
831 ][..]
832 );
833 assert_eq!(BAR_GROUPS[4].last(), Some(&FormatButton::Rule));
834 for button in SELECTION_GROUPS.iter().flat_map(|group| group.iter()) {
835 assert!(BAR_GROUPS.iter().any(|group| group.contains(button)));
836 }
837 }
838
839 fn flat(groups: &[Vec<FormatButton>]) -> Vec<FormatButton> {
840 groups.iter().flatten().copied().collect()
841 }
842
843 #[test]
844 fn a_wide_bar_shows_every_button_without_more_options() {
845 let fit = fit_groups(groups_width(&BAR_GROUPS), &BAR_GROUPS);
846 assert_eq!(fit.visible.len(), BAR_GROUPS.len());
847 assert!(fit.overflow.is_empty());
848 }
849
850 #[test]
851 fn single_buttons_leave_from_the_end_and_keep_their_groups() {
852 let all: Vec<FormatButton> = BAR_GROUPS.iter().flat_map(|group| group.iter()).copied().collect();
853 let fit = fit_groups(groups_width(&BAR_GROUPS) - 1., &BAR_GROUPS);
854 assert_eq!(flat(&fit.overflow), all[all.len() - 2..]);
855 assert_eq!(fit.overflow, vec![vec![FormatButton::TableInsertLine, FormatButton::TableRemoveLine]]);
856 assert_eq!(fit.visible.last(), Some(&vec![FormatButton::Table]));
857 let mut both = flat(&fit.visible);
858 both.extend(flat(&fit.overflow));
859 assert_eq!(both, all);
860 }
861
862 #[test]
863 fn a_cut_between_groups_leaves_no_empty_group_on_either_side() {
864 let two = groups_width(&BAR_GROUPS[..2]);
865 let fit = fit_groups(two + 2. + BUTTON, &BAR_GROUPS);
866 assert_eq!(fit.visible, vec![BAR_GROUPS[0].to_vec(), BAR_GROUPS[1].to_vec()]);
867 assert_eq!(fit.overflow.len(), BAR_GROUPS.len() - 2);
868 assert!(fit.overflow.iter().chain(&fit.visible).all(|group| !group.is_empty()));
869 let fit = fit_groups(two + 2. + BUTTON - 1., &BAR_GROUPS);
870 assert_eq!(fit.visible.len(), 2);
871 assert_eq!(fit.visible[1], vec![FormatButton::Superscript]);
872 assert_eq!(fit.overflow[0], vec![FormatButton::Subscript]);
873 }
874
875 #[test]
876 fn outside_a_table_the_menu_drops_the_table_edits_and_their_group() {
877 let fit = fit_groups(groups_width(&BAR_GROUPS) - 1., &BAR_GROUPS);
878 let outside = |format: FormatButton| match format {
879 FormatButton::TableInsertLine | FormatButton::TableRemoveLine => ButtonState::disabled(),
880 _ => ButtonState::enabled(FormatState::Off),
881 };
882 assert!(menu_groups(&fit.overflow, &outside).is_empty());
883 let inside = |_| ButtonState::enabled(FormatState::Off);
884 assert_eq!(menu_groups(&fit.overflow, &inside), fit.overflow);
885 }
886
887 #[test]
888 fn a_tiny_bar_keeps_only_more_options() {
889 let fit = fit_groups(BUTTON, &BAR_GROUPS);
890 assert!(fit.visible.is_empty());
891 assert_eq!(fit.overflow.len(), BAR_GROUPS.len());
892 }
893
894 #[test]
895 fn overflow_rows_read_without_the_shortcut() {
896 assert_eq!(FormatButton::CodeBlock.menu_label(), "Code block");
897 assert_eq!(FormatButton::Rule.menu_label(), "Insert horizontal rule");
898 assert_eq!(FormatButton::More.tooltip(), "More options");
899 assert_eq!(FormatButton::FontSize.tooltip(), "Font size");
900 }
901
902 #[test]
903 fn the_format_toggle_reads_like_teams() {
904 assert_eq!(
905 toggle_tooltip(false),
906 "Show Formatting options (Ctrl+Shift+X)"
907 );
908 assert_eq!(
909 toggle_tooltip(true),
910 "Hide Formatting options (Ctrl+Shift+X)"
911 );
912 assert_ne!(toggle_symbol(false), toggle_symbol(true));
913 assert_eq!(FormatButton::Strike.tooltip(), "Strikethrough (Ctrl+Alt+X)");
914 }
915}