BlueGit

ict rusty-teams

Files

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

format_toolbar.rs

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