BlueGit

ict rusty-teams

Files

rusty-teams / crates / app / src / views / composer / code_language.rs

code_language.rs

code_language.rs 7.7 KiB Download Raw
1use gpui_kit::component::input::InlineToken;
2use gpui_kit::component::{h_flex, v_flex};
3use gpui_kit::prelude::FluentBuilder as _;
4use gpui_kit::*;
5use teams_core::{CODE_HEADER_MARK, CODE_LANGUAGES, LineKind, PLAIN_LANGUAGE};
6
7use super::Composer;
8use crate::theme::{self, ElevatedSurface as _};
9use crate::views::draft_style::CODE_INDENT;
10use crate::views::widgets::symbol;
11
12const TOKEN_PREFIX: &str = "code-header-";
13pub(super) const CODE_LANGUAGE_TAG: &str = "composer/code-language";
14pub(super) const CODE_LANGUAGE_ROW_TAG: &str = "composer/code-language-row-";
15const HEADER_HEIGHT: f32 = 36.;
16/// Room between the rule and the first code line.
17const CODE_TOP_GAP: f32 = 6.;
18const MENU_WIDTH: f32 = 180.;
19const MENU_HEIGHT: f32 = 280.;
20
21pub(super) fn is_code_header_token(token: &InlineToken) -> bool {
22 token.id().starts_with(TOKEN_PREFIX)
23}
24
25impl Composer {
26 /// Every code block's first line gets its header token in place of the header mark.
27 pub(super) fn sync_code_headers(&mut self, window: &mut Window, cx: &mut Context<Self>) {
28 if self.input.read(cx).value().as_ref() != self.draft.text() {
29 return;
30 }
31 let tokens: Vec<_> = self
32 .input
33 .read(cx)
34 .tokens()
35 .iter()
36 .filter(|span| is_code_header_token(span.token()))
37 .map(|span| span.range())
38 .collect();
39 let marks: Vec<_> = self
40 .draft
41 .text()
42 .match_indices(CODE_HEADER_MARK)
43 .map(|(at, mark)| at..at + mark.len())
44 .filter(|mark| !tokens.contains(mark))
45 .collect();
46 for mark in marks {
47 self.table_counter += 1;
48 let token = InlineToken::new(
49 format!("{TOKEN_PREFIX}{}", self.table_counter),
50 CODE_HEADER_MARK.to_string(),
51 )
52 .header();
53 self.input.update(cx, |state, cx| {
54 let selection = state.selected_range();
55 if state
56 .replace_range_with_token(mark, token, window, cx)
57 .is_ok()
58 {
59 state.set_selected_range(selection, cx);
60 }
61 });
62 }
63 }
64
65 /// Teams' code block header: the language, which opens its picker, over a rule.
66 pub(super) fn render_code_header(
67 &self,
68 composer: WeakEntity<Composer>,
69 at: usize,
70 width: Pixels,
71 ) -> AnyElement {
72 let line = self.draft.line_at(at);
73 let language = match self.draft.lines().get(line) {
74 Some(LineKind::Code(language)) => language.clone(),
75 _ => None,
76 };
77 let chosen = language.unwrap_or_else(|| PLAIN_LANGUAGE.to_owned());
78 let name = teams_core::code_language(&chosen)
79 .map_or(chosen.clone(), |language| language.name.to_owned());
80 let open = self.code_language_menu == Some(line);
81 let toggle = composer.clone();
82 let button = h_flex()
83 .id(ElementId::Name(format!("code-language-{at}").into()))
84 .debug_selector(|| CODE_LANGUAGE_TAG.into())
85 .h(px(24.))
86 .px(px(6.))
87 .gap(px(4.))
88 .items_center()
89 .rounded(px(4.))
90 .text_size(px(13.))
91 .text_color(theme::text())
92 .cursor_pointer()
93 .hover(|button| button.bg(theme::popup_hover()))
94 .on_mouse_down(MouseButton::Left, |_, window, cx| {
95 window.prevent_default();
96 cx.stop_propagation();
97 })
98 .on_click(move |_, _, cx| {
99 toggle
100 .update(cx, |this, cx| {
101 this.code_language_menu = (!open).then_some(line);
102 cx.notify();
103 })
104 .ok();
105 })
106 .child(symbol("code", 14., theme::text_muted()))
107 .child(name)
108 .child(symbol("keyboard_arrow_down", 14., theme::text_muted()));
109 v_flex()
110 .w(width)
111 .pb(px(CODE_TOP_GAP))
112 .child(
113 h_flex()
114 .h(px(HEADER_HEIGHT))
115 .px(px(6.))
116 .items_center()
117 .border_b_1()
118 .border_color(theme::code_frame())
119 .child(button),
120 )
121 .into_any_element()
122 }
123
124 /// The open picker, drawn over the composer: inside the input it could not be clicked
125 /// where it reaches past the input's bounds.
126 pub(super) fn render_code_language_menu(&self, cx: &mut Context<Self>) -> Option<AnyElement> {
127 let line = self.code_language_menu?;
128 let at = self.draft.line_ranges().get(line)?.start;
129 let LineKind::Code(language) = self.draft.lines().get(line)? else {
130 return None;
131 };
132 let chosen = language
133 .as_deref()
134 .and_then(teams_core::code_language)
135 .map_or(PLAIN_LANGUAGE, |language| language.id);
136 let header = self.input.read(cx).range_to_bounds(&(at..at))?;
137 let rows = CODE_LANGUAGES.iter().map(|language| {
138 let (id, name) = (language.id, language.name);
139 div()
140 .id(ElementId::Name(format!("code-language-{id}").into()))
141 .debug_selector(move || format!("{CODE_LANGUAGE_ROW_TAG}{id}"))
142 .px(px(10.))
143 .py(px(5.))
144 .rounded(px(6.))
145 .text_size(px(13.))
146 .text_color(theme::text())
147 .cursor_pointer()
148 .when(id == chosen, |row| row.bg(theme::popup_hover()))
149 .hover(|row| row.bg(theme::popup_hover()))
150 .on_mouse_down(MouseButton::Left, |_, window, cx| {
151 window.prevent_default();
152 cx.stop_propagation();
153 })
154 .on_click(cx.listener(move |this, _, window, cx| {
155 this.choose_code_language(at, id, window, cx)
156 }))
157 .child(name)
158 });
159 // Lined up with the block's edge, left of the line indent where `at` sits.
160 let left = header.left() - px(CODE_INDENT);
161 Some(
162 deferred(
163 // Above the header, as in Teams: the composer sits at the window's bottom.
164 anchored()
165 .position(point(left, header.top()))
166 .anchor(Anchor::BottomLeft)
167 .snap_to_window_with_margin(px(8.))
168 .child(
169 v_flex()
170 .id("code-language-menu")
171 .mb(px(4.))
172 .w(px(MENU_WIDTH))
173 .max_h(px(MENU_HEIGHT))
174 .overflow_y_scroll()
175 .p(px(4.))
176 .rounded(px(10.))
177 .flyout_surface()
178 .occlude()
179 .on_mouse_down_out(cx.listener(|this, _, _, cx| {
180 this.code_language_menu = None;
181 cx.notify();
182 }))
183 .children(rows),
184 ),
185 )
186 .with_priority(1)
187 .into_any_element(),
188 )
189 }
190
191 pub(super) fn choose_code_language(
192 &mut self,
193 at: usize,
194 id: &str,
195 window: &mut Window,
196 cx: &mut Context<Self>,
197 ) {
198 let language = (id != PLAIN_LANGUAGE).then(|| id.to_owned());
199 self.draft.set_code_language(at, language);
200 self.code_language_menu = None;
201 self.commit(None, window, cx);
202 cx.notify();
203 }
204}