BlueGit

ict rusty-teams

Files

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

format_toolbar.rs

format_toolbar.rs 28.5 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 "fluent_text_edit_style_filled"
191 } else {
192 "fluent_text_edit_style"
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 /// Opens a picker or menu below itself instead of acting at once.
267 pub fn opens_popup(self) -> bool {
268 matches!(
269 self,
270 FormatButton::Highlight
271 | FormatButton::FontColor
272 | FormatButton::FontSize
273 | FormatButton::ParagraphStyle
274 | FormatButton::Table
275 | FormatButton::TableInsertLine
276 | FormatButton::TableRemoveLine
277 | FormatButton::More
278 )
279 }
280
281 fn content(self, color: Hsla, label: Option<&'static str>) -> AnyElement {
282 let letter = |text: &'static str| div().text_size(px(15.)).text_color(color).child(text);
283 match self {
284 FormatButton::Bold => letter("B").font_weight(FontWeight::BOLD).into_any_element(),
285 FormatButton::Italic => letter("I").italic().into_any_element(),
286 FormatButton::Underline => letter("U").underline().into_any_element(),
287 FormatButton::Strike => letter("S").line_through().into_any_element(),
288 FormatButton::Superscript => script("x", "2", true, color),
289 FormatButton::Subscript => script("x", "2", false, color),
290 FormatButton::SizeSmall => sized_letter(SMALL_LETTER, color),
291 FormatButton::SizeNormal => sized_letter(NORMAL_LETTER, color),
292 FormatButton::SizeLarge => sized_letter(LARGE_LETTER, color),
293 FormatButton::Code => symbol("code", 18., color).into_any_element(),
294 FormatButton::Link => symbol("link", 18., color).into_any_element(),
295 FormatButton::Bulleted => symbol("format_list_bulleted", 18., color).into_any_element(),
296 FormatButton::Numbered => symbol("format_list_numbered", 18., color).into_any_element(),
297 FormatButton::Quote => symbol("format_quote", 18., color).into_any_element(),
298 FormatButton::Table => symbol("table", 18., color).into_any_element(),
299 FormatButton::TableInsertLine => {
300 symbol("fluent_table_add", 20., color).into_any_element()
301 }
302 FormatButton::TableRemoveLine => {
303 symbol("fluent_table_dismiss", 20., color).into_any_element()
304 }
305 FormatButton::Highlight => symbol("fluent_highlight", 20., color).into_any_element(),
306 FormatButton::FontColor => symbol("fluent_text_color", 20., color).into_any_element(),
307 FormatButton::ParagraphStyle => h_flex()
308 .w_full()
309 .px(px(6.))
310 .gap(px(4.))
311 .items_center()
312 .justify_between()
313 .text_size(px(13.))
314 .text_color(color)
315 .child(label.unwrap_or_default())
316 .child(icon(IconName::ChevronDown, 12., color))
317 .into_any_element(),
318 FormatButton::ClearFormatting => {
319 symbol("fluent_text_clear_formatting", 20., color).into_any_element()
320 }
321 FormatButton::Outdent => {
322 symbol("fluent_text_indent_decrease", 20., color).into_any_element()
323 }
324 FormatButton::Indent => {
325 symbol("fluent_text_indent_increase", 20., color).into_any_element()
326 }
327 FormatButton::CodeBlock => symbol("fluent_code_block", 20., color).into_any_element(),
328 FormatButton::Rule => symbol("fluent_line_horizontal_1", 20., color).into_any_element(),
329 FormatButton::FontSize => {
330 symbol("fluent_text_font_size", 20., color).into_any_element()
331 }
332 FormatButton::More => icon(IconName::Ellipsis, 18., color).into_any_element(),
333 }
334 }
335
336 fn width(self) -> f32 {
337 match self {
338 FormatButton::ParagraphStyle => PARAGRAPH_STYLE_WIDTH,
339 _ => BUTTON,
340 }
341 }
342}
343
344fn script(base: &'static str, mark: &'static str, raised: bool, color: Hsla) -> AnyElement {
345 h_flex()
346 .items_baseline()
347 .text_color(color)
348 .child(div().text_size(px(15.)).child(base))
349 .child(
350 div()
351 .text_size(px(SCRIPT_LETTER))
352 .when(raised, |mark| mark.mb(px(SCRIPT_SHIFT)))
353 .when(!raised, |mark| mark.mt(px(SCRIPT_SHIFT)))
354 .child(mark),
355 )
356 .into_any_element()
357}
358
359fn sized_letter(size: f32, color: Hsla) -> AnyElement {
360 div()
361 .text_size(px(size))
362 .text_color(color)
363 .child("A")
364 .into_any_element()
365}
366
367pub fn bar_width() -> f32 {
368 2. * PADDING + groups_width(&SELECTION_GROUPS)
369}
370
371pub fn link_width() -> f32 {
372 2. * PADDING + LINK_FIELD_WIDTH + BUTTON_GAP * 2. + APPLY_WIDTH
373}
374
375#[derive(Debug, Clone, Copy, PartialEq)]
376pub struct Placement {
377 pub left: Pixels,
378 pub bottom: Pixels,
379 pub arrow_x: Pixels,
380}
381
382/// Centered over `center_x`, `GAP` above `top`, kept between the composer edges.
383pub fn place(center_x: Pixels, top: Pixels, edges: (Pixels, Pixels), width: f32) -> Placement {
384 let width = px(width);
385 let (left_edge, right_edge) = edges;
386 let left = (center_x - width / 2.)
387 .max(left_edge)
388 .min(right_edge - width);
389 Placement {
390 left,
391 bottom: top - px(GAP),
392 arrow_x: (center_x - left)
393 .max(px(ARROW_MARGIN))
394 .min(width - px(ARROW_MARGIN)),
395 }
396}
397
398pub type PressHandler = Rc<dyn Fn(FormatButton, &mut Window, &mut App)>;
399pub type ApplyHandler = Rc<dyn Fn(&mut Window, &mut App)>;
400
401pub enum Mode<'a> {
402 Bar {
403 state: &'a dyn Fn(FormatButton) -> ButtonState,
404 on_press: PressHandler,
405 overlay: &'a mut dyn FnMut(FormatButton) -> Option<AnyElement>,
406 },
407 Link {
408 field: &'a Entity<InputState>,
409 refused: bool,
410 on_apply: ApplyHandler,
411 },
412}
413
414fn button(
415 format: FormatButton,
416 state: ButtonState,
417 on_press: PressHandler,
418 overlay: Option<AnyElement>,
419) -> impl IntoElement {
420 let on = state.enabled && state.format == FormatState::On;
421 let color = if on {
422 theme::accent_soft()
423 } else {
424 theme::text_soft()
425 };
426 div()
427 .id(ElementId::Name(format!("format-{format:?}").into()))
428 .relative()
429 .w(px(format.width()))
430 .h(px(BUTTON))
431 .flex()
432 .flex_none()
433 .items_center()
434 .justify_center()
435 .rounded(px(6.))
436 .popup_trigger_tooltip_text(format.opens_popup() && on, format.tooltip())
437 .child(format.content(color, state.label))
438 .on_mouse_down(MouseButton::Left, |_, window, cx| {
439 window.prevent_default();
440 cx.stop_propagation();
441 })
442 .when(!state.enabled, |button| button.opacity(DISABLED_OPACITY))
443 .when(state.enabled, |button| {
444 button
445 .cursor_pointer()
446 .when(on, |button| {
447 button.bg(theme::accent().opacity(ACTIVE_ALPHA))
448 })
449 .hover(|button| button.bg(theme::popup_hover()))
450 .when(state.format == FormatState::Mixed, |button| {
451 button.child(
452 div()
453 .absolute()
454 .bottom(px(2.))
455 .left(px(7.))
456 .w(px(BUTTON - 16.))
457 .h(px(2.))
458 .rounded(px(1.))
459 .bg(theme::accent()),
460 )
461 })
462 .on_click(move |_, window, cx| on_press(format, window, cx))
463 })
464 .children(overlay.map(|overlay| overlay_below(overlay, BUTTON + GAP / 2.)))
465}
466
467fn overlay_below(overlay: AnyElement, offset: f32) -> Div {
468 div().absolute().top(px(offset)).left_0().child(
469 deferred(
470 anchored()
471 .snap_to_window_with_margin(px(GAP))
472 .child(overlay),
473 )
474 .with_priority(2),
475 )
476}
477
478fn separator() -> Div {
479 div()
480 .w(px(1.))
481 .h(px(BUTTON - 8.))
482 .mx(px(SEPARATOR_MARGIN))
483 .bg(theme::popup_hover())
484}
485
486fn groups_row<G: AsRef<[FormatButton]>>(
487 groups: &[G],
488 state: &dyn Fn(FormatButton) -> ButtonState,
489 on_press: PressHandler,
490 overlay: &mut dyn FnMut(FormatButton) -> Option<AnyElement>,
491) -> Div {
492 let mut row = h_flex().gap(px(BUTTON_GAP)).items_center();
493 for (index, group) in groups.iter().enumerate() {
494 if index > 0 {
495 row = row.child(separator());
496 }
497 for format in group.as_ref().iter().copied() {
498 row = row.child(button(
499 format,
500 state(format),
501 on_press.clone(),
502 overlay(format),
503 ));
504 }
505 }
506 row
507}
508
509fn bar(
510 state: &dyn Fn(FormatButton) -> ButtonState,
511 on_press: PressHandler,
512 overlay: &mut dyn FnMut(FormatButton) -> Option<AnyElement>,
513) -> Div {
514 groups_row(&SELECTION_GROUPS, state, on_press, overlay)
515}
516
517/// The format bar inside the composer box. `overlay` hangs a popup under a button; the
518/// More button's popup is the overflow menu, built with `render_overflow_menu`.
519pub fn render_format_bar(
520 fit: &BarFit,
521 state: &dyn Fn(FormatButton) -> ButtonState,
522 on_press: PressHandler,
523 overlay: &mut dyn FnMut(FormatButton) -> Option<AnyElement>,
524) -> Div {
525 let row = groups_row(&fit.visible, state, on_press.clone(), overlay);
526 if fit.overflow.is_empty() {
527 return row;
528 }
529 row.child(button(
530 FormatButton::More,
531 state(FormatButton::More),
532 on_press,
533 overlay(FormatButton::More),
534 ))
535}
536
537/// The groups that do not fit, as menu rows with a divider between groups.
538pub fn render_overflow_menu(
539 groups: &[Vec<FormatButton>],
540 state: &dyn Fn(FormatButton) -> ButtonState,
541 on_press: PressHandler,
542 overlay: &mut dyn FnMut(FormatButton) -> Option<AnyElement>,
543) -> Div {
544 let mut menu = v_flex().w(px(MENU_WIDTH)).py(px(MENU_PADDING));
545 for (index, group) in groups.iter().enumerate() {
546 if index > 0 {
547 menu = menu.child(
548 div()
549 .w_full()
550 .h(px(1.))
551 .my(px(MENU_PADDING))
552 .bg(theme::popup_hover()),
553 );
554 }
555 for format in group.iter().copied() {
556 menu = menu.child(menu_row(
557 format,
558 state(format),
559 on_press.clone(),
560 overlay(format),
561 ));
562 }
563 }
564 menu
565}
566
567fn menu_row(
568 format: FormatButton,
569 state: ButtonState,
570 on_press: PressHandler,
571 overlay: Option<AnyElement>,
572) -> impl IntoElement {
573 let on = state.enabled && state.format == FormatState::On;
574 let color = if on {
575 theme::accent_soft()
576 } else {
577 theme::text_soft()
578 };
579 let content = match format {
580 FormatButton::ParagraphStyle => symbol("fluent_text_header_1", 20., color).into_any_element(),
581 _ => format.content(color, None),
582 };
583 div()
584 .id(ElementId::Name(format!("format-overflow-{format:?}").into()))
585 .relative()
586 .mx(px(MENU_PADDING))
587 .h(px(MENU_ROW_HEIGHT))
588 .flex_none()
589 .px(px(MENU_ROW_PADDING_X))
590 .flex()
591 .items_center()
592 .gap(px(GAP))
593 .rounded(px(6.))
594 .child(div().w(px(BUTTON)).flex().justify_center().child(content))
595 .child(
596 div()
597 .flex_1()
598 .text_size(px(13.))
599 .text_color(theme::text())
600 .child(format.menu_label()),
601 )
602 .on_mouse_down(MouseButton::Left, |_, window, cx| {
603 window.prevent_default();
604 cx.stop_propagation();
605 })
606 .when(!state.enabled, |row| row.opacity(DISABLED_OPACITY))
607 .when(state.enabled, |row| {
608 row.cursor_pointer()
609 .when(on, |row| row.bg(theme::accent().opacity(ACTIVE_ALPHA)))
610 .hover(|row| row.bg(theme::popup_hover()))
611 .on_click(move |_, window, cx| on_press(format, window, cx))
612 })
613 .children(overlay.map(|overlay| overlay_below(overlay, MENU_ROW_HEIGHT)))
614}
615
616fn link_editor(field: &Entity<InputState>, refused: bool, on_apply: ApplyHandler) -> Div {
617 let row = h_flex()
618 .gap(px(BUTTON_GAP * 2.))
619 .items_center()
620 .child(
621 div()
622 .w(px(LINK_FIELD_WIDTH))
623 .h(px(BUTTON))
624 .rounded(px(6.))
625 .border_1()
626 .border_color(if refused {
627 theme::red()
628 } else {
629 theme::accent()
630 })
631 .bg(theme::popup_hover())
632 .child(Input::new(field).appearance(false).bordered(false)),
633 )
634 .child(
635 div()
636 .id("format-link-apply")
637 .w(px(APPLY_WIDTH))
638 .h(px(BUTTON))
639 .flex()
640 .items_center()
641 .justify_center()
642 .rounded(px(6.))
643 .bg(theme::accent())
644 .text_color(theme::on_accent())
645 .text_size(px(13.))
646 .font_weight(FontWeight::SEMIBOLD)
647 .cursor_pointer()
648 .hover(|button| button.opacity(0.9))
649 .child("Apply")
650 .on_mouse_down(MouseButton::Left, |_, window, cx| {
651 window.prevent_default();
652 cx.stop_propagation();
653 })
654 .on_click(move |_, window, cx| on_apply(window, cx)),
655 );
656 v_flex().child(row).when(refused, |editor| {
657 editor.child(
658 div()
659 .pt(px(4.))
660 .px(px(2.))
661 .text_size(px(11.5))
662 .text_color(theme::red_soft())
663 .child("Only http, https and mailto links"),
664 )
665 })
666}
667
668fn arrow(offset: Pixels) -> impl IntoElement {
669 canvas(
670 |_, _, _| {},
671 move |bounds, _, window, _| {
672 let tip = point(bounds.origin.x + offset, bounds.origin.y + px(ARROW_HEIGHT));
673 let mut builder = PathBuilder::fill();
674 builder.move_to(point(
675 tip.x - px(ARROW_WIDTH / 2.),
676 bounds.origin.y - px(1.),
677 ));
678 builder.line_to(point(
679 tip.x + px(ARROW_WIDTH / 2.),
680 bounds.origin.y - px(1.),
681 ));
682 builder.line_to(point(tip.x, tip.y));
683 builder.close();
684 if let Ok(path) = builder.build() {
685 window.paint_path(path, theme::popup());
686 }
687 },
688 )
689 .w_full()
690 .h(px(ARROW_HEIGHT))
691}
692
693pub fn render(placement: Placement, mode: Mode<'_>) -> AnyElement {
694 let content = match mode {
695 Mode::Bar {
696 state,
697 on_press,
698 overlay,
699 } => bar(state, on_press, overlay),
700 Mode::Link {
701 field,
702 refused,
703 on_apply,
704 } => link_editor(field, refused, on_apply),
705 };
706 deferred(
707 anchored()
708 .position(point(placement.left, placement.bottom))
709 .anchor(Anchor::BottomLeft)
710 .child(
711 v_flex()
712 .id("format-toolbar")
713 .occlude()
714 .child(
715 div()
716 .p(px(PADDING))
717 .rounded(px(10.))
718 .flyout_surface()
719 .child(content),
720 )
721 .child(arrow(placement.arrow_x)),
722 ),
723 )
724 .with_priority(1)
725 .into_any_element()
726}
727
728#[cfg(test)]
729mod tests {
730 use gpui_kit::px;
731
732 use super::{
733 ARROW_MARGIN, BAR_GROUPS, BUTTON, FormatButton, SELECTION_GROUPS, bar_width, fit_groups,
734 groups_width, place, toggle_symbol, toggle_tooltip,
735 };
736
737
738 #[test]
739 fn the_bar_centers_over_the_selection() {
740 let placement = place(px(400.), px(300.), (px(100.), px(900.)), 200.);
741 assert_eq!(placement.left, px(300.));
742 assert_eq!(placement.bottom, px(292.));
743 assert_eq!(placement.arrow_x, px(100.));
744 }
745
746 #[test]
747 fn the_bar_stays_inside_the_composer_and_the_arrow_follows_the_selection() {
748 let near_left = place(px(120.), px(300.), (px(100.), px(900.)), 200.);
749 assert_eq!(near_left.left, px(100.));
750 assert_eq!(near_left.arrow_x, px(20.));
751 let near_right = place(px(899.), px(300.), (px(100.), px(900.)), 200.);
752 assert_eq!(near_right.left, px(700.));
753 assert_eq!(near_right.arrow_x, px(200. - ARROW_MARGIN));
754 }
755
756 #[test]
757 fn a_bar_wider_than_the_composer_ends_at_its_right_edge() {
758 let placement = place(px(560.), px(300.), (px(500.), px(800.)), 400.);
759 assert_eq!(placement.left, px(400.));
760 assert_eq!(placement.arrow_x, px(160.));
761 }
762
763 #[test]
764 fn the_selection_bar_holds_the_text_formats_without_the_table() {
765 assert_eq!(
766 SELECTION_GROUPS
767 .iter()
768 .map(|group| group.len())
769 .sum::<usize>(),
770 12
771 );
772 assert!(
773 SELECTION_GROUPS
774 .iter()
775 .all(|group| !group.contains(&FormatButton::Table))
776 );
777 assert!(SELECTION_GROUPS.iter().any(|group| group == &[FormatButton::FontSize]));
778 assert!(bar_width() > 12. * BUTTON);
779 }
780
781 #[test]
782 fn the_format_bar_follows_the_teams_groups_and_keeps_every_selection_format() {
783 assert_eq!(
784 BAR_GROUPS[BAR_GROUPS.len() - 1],
785 &[
786 FormatButton::Table,
787 FormatButton::TableInsertLine,
788 FormatButton::TableRemoveLine
789 ][..]
790 );
791 assert_eq!(
792 BAR_GROUPS[2][..3],
793 [
794 FormatButton::Highlight,
795 FormatButton::FontColor,
796 FormatButton::FontSize
797 ]
798 );
799 assert_eq!(
800 BAR_GROUPS[3],
801 &[
802 FormatButton::Outdent,
803 FormatButton::Indent,
804 FormatButton::Bulleted,
805 FormatButton::Numbered
806 ][..]
807 );
808 assert_eq!(BAR_GROUPS[4].last(), Some(&FormatButton::Rule));
809 for button in SELECTION_GROUPS.iter().flat_map(|group| group.iter()) {
810 assert!(BAR_GROUPS.iter().any(|group| group.contains(button)));
811 }
812 }
813
814 fn flat(groups: &[Vec<FormatButton>]) -> Vec<FormatButton> {
815 groups.iter().flatten().copied().collect()
816 }
817
818 #[test]
819 fn a_wide_bar_shows_every_button_without_more_options() {
820 let fit = fit_groups(groups_width(&BAR_GROUPS), &BAR_GROUPS);
821 assert_eq!(fit.visible.len(), BAR_GROUPS.len());
822 assert!(fit.overflow.is_empty());
823 }
824
825 #[test]
826 fn single_buttons_leave_from_the_end_and_keep_their_groups() {
827 let all: Vec<FormatButton> = BAR_GROUPS.iter().flat_map(|group| group.iter()).copied().collect();
828 let fit = fit_groups(groups_width(&BAR_GROUPS) - 1., &BAR_GROUPS);
829 assert_eq!(flat(&fit.overflow), all[all.len() - 2..]);
830 assert_eq!(fit.overflow, vec![vec![FormatButton::TableInsertLine, FormatButton::TableRemoveLine]]);
831 assert_eq!(fit.visible.last(), Some(&vec![FormatButton::Table]));
832 let mut both = flat(&fit.visible);
833 both.extend(flat(&fit.overflow));
834 assert_eq!(both, all);
835 }
836
837 #[test]
838 fn a_cut_between_groups_leaves_no_empty_group_on_either_side() {
839 let two = groups_width(&BAR_GROUPS[..2]);
840 let fit = fit_groups(two + 2. + BUTTON, &BAR_GROUPS);
841 assert_eq!(fit.visible, vec![BAR_GROUPS[0].to_vec(), BAR_GROUPS[1].to_vec()]);
842 assert_eq!(fit.overflow.len(), BAR_GROUPS.len() - 2);
843 assert!(fit.overflow.iter().chain(&fit.visible).all(|group| !group.is_empty()));
844 let fit = fit_groups(two + 2. + BUTTON - 1., &BAR_GROUPS);
845 assert_eq!(fit.visible.len(), 2);
846 assert_eq!(fit.visible[1], vec![FormatButton::Superscript]);
847 assert_eq!(fit.overflow[0], vec![FormatButton::Subscript]);
848 }
849
850 #[test]
851 fn a_tiny_bar_keeps_only_more_options() {
852 let fit = fit_groups(BUTTON, &BAR_GROUPS);
853 assert!(fit.visible.is_empty());
854 assert_eq!(fit.overflow.len(), BAR_GROUPS.len());
855 }
856
857 #[test]
858 fn overflow_rows_read_without_the_shortcut() {
859 assert_eq!(FormatButton::CodeBlock.menu_label(), "Code block");
860 assert_eq!(FormatButton::Rule.menu_label(), "Insert horizontal rule");
861 assert_eq!(FormatButton::More.tooltip(), "More options");
862 assert_eq!(FormatButton::FontSize.tooltip(), "Font size");
863 }
864
865 #[test]
866 fn the_format_toggle_reads_like_teams() {
867 assert_eq!(
868 toggle_tooltip(false),
869 "Show Formatting options (Ctrl+Shift+X)"
870 );
871 assert_eq!(
872 toggle_tooltip(true),
873 "Hide Formatting options (Ctrl+Shift+X)"
874 );
875 assert_ne!(toggle_symbol(false), toggle_symbol(true));
876 assert_eq!(FormatButton::Strike.tooltip(), "Strikethrough (Ctrl+Alt+X)");
877 }
878}