1use gpui::{AbsoluteLength, App, DefiniteLength, Global, JustifyContent, Length, Styled};
21
22#[derive(Clone, Copy, Debug, Default, Eq, PartialEq, Hash)]
24pub enum LayoutDirection {
25 #[default]
27 Ltr,
28 Rtl,
30}
31
32#[derive(Clone, Copy)]
33struct GlobalLayoutDirection(LayoutDirection);
34
35impl Global for GlobalLayoutDirection {}
36
37impl LayoutDirection {
38 pub fn is_rtl(self) -> bool {
40 self == Self::Rtl
41 }
42
43 pub fn global(cx: &App) -> Self {
45 cx.try_global::<GlobalLayoutDirection>()
46 .map(|direction| direction.0)
47 .unwrap_or_default()
48 }
49
50 pub fn set_global(self, cx: &mut App) {
52 if cx.try_global::<GlobalLayoutDirection>().map(|d| d.0) == Some(self) {
53 return;
54 }
55 cx.set_global(GlobalLayoutDirection(self));
56 cx.refresh_windows();
57 }
58
59 pub fn from_locale(locale: &str) -> Self {
61 const RTL: [&str; 12] = [
62 "ar", "ckb", "dv", "fa", "he", "iw", "ks", "ps", "sd", "ug", "ur", "yi",
63 ];
64 let language = locale.split(['-', '_', '.']).next().unwrap_or_default();
65 if RTL.iter().any(|rtl| language.eq_ignore_ascii_case(rtl)) {
66 Self::Rtl
67 } else {
68 Self::Ltr
69 }
70 }
71
72 pub fn system() -> Self {
74 sys_locale::get_locale()
75 .map(|locale| Self::from_locale(&locale))
76 .unwrap_or_default()
77 }
78
79 pub(crate) fn start_is_left(self) -> bool {
82 self == Self::Ltr
83 }
84}
85
86pub(crate) fn init(cx: &mut App) {
89 if cx.has_global::<GlobalLayoutDirection>() {
90 return;
91 }
92 let is_test = cx
93 .background_executor()
94 .scheduler_executor()
95 .scheduler()
96 .as_test()
97 .is_some();
98 let direction = if is_test {
99 LayoutDirection::Ltr
100 } else {
101 LayoutDirection::system()
102 };
103 cx.set_global(GlobalLayoutDirection(direction));
104}
105
106macro_rules! logical_edge {
107 ($(#[$doc:meta])* $name:ident, $start:ident, $end:ident, $len:ty) => {
108 $(#[$doc])*
109 fn $name(self, length: impl Into<$len> + Clone, cx: &App) -> Self {
110 if LayoutDirection::global(cx).start_is_left() {
111 self.$start(length)
112 } else {
113 self.$end(length)
114 }
115 }
116 };
117}
118
119pub trait LogicalStyledExt: Styled + Sized {
122 logical_edge!(
123 ps, pl, pr, DefiniteLength
125 );
126 logical_edge!(
127 pe, pr, pl, DefiniteLength
129 );
130 logical_edge!(
131 ms, ml, mr, Length
133 );
134 logical_edge!(
135 me, mr, ml, Length
137 );
138 logical_edge!(
139 inset_s, left, right, Length
141 );
142 logical_edge!(
143 inset_e, right, left, Length
145 );
146
147 fn border_s(mut self, width: impl Into<AbsoluteLength>, cx: &App) -> Self {
149 let width = Some(width.into());
150 let widths = &mut self.style().border_widths;
151 if LayoutDirection::global(cx).start_is_left() {
152 widths.left = width;
153 } else {
154 widths.right = width;
155 }
156 self
157 }
158
159 fn border_e(mut self, width: impl Into<AbsoluteLength>, cx: &App) -> Self {
161 let width = Some(width.into());
162 let widths = &mut self.style().border_widths;
163 if LayoutDirection::global(cx).start_is_left() {
164 widths.right = width;
165 } else {
166 widths.left = width;
167 }
168 self
169 }
170
171 fn rounded_s(self, radius: impl Into<AbsoluteLength> + Clone, cx: &App) -> Self {
173 if LayoutDirection::global(cx).start_is_left() {
174 self.rounded_l(radius)
175 } else {
176 self.rounded_r(radius)
177 }
178 }
179
180 fn rounded_e(self, radius: impl Into<AbsoluteLength> + Clone, cx: &App) -> Self {
182 if LayoutDirection::global(cx).start_is_left() {
183 self.rounded_r(radius)
184 } else {
185 self.rounded_l(radius)
186 }
187 }
188
189 fn flex_row_dir(self, cx: &App) -> Self {
192 if LayoutDirection::global(cx).is_rtl() {
193 self.flex().flex_row_reverse()
194 } else {
195 self.flex().flex_row()
196 }
197 }
198
199 fn justify_flex_start(mut self) -> Self {
205 self.style().justify_content = Some(JustifyContent::FlexStart);
206 self
207 }
208
209 fn justify_flex_end(mut self) -> Self {
213 self.style().justify_content = Some(JustifyContent::FlexEnd);
214 self
215 }
216
217 fn text_start(self, cx: &App) -> Self {
219 if LayoutDirection::global(cx).start_is_left() {
220 self.text_left()
221 } else {
222 self.text_right()
223 }
224 }
225
226 fn text_end(self, cx: &App) -> Self {
228 if LayoutDirection::global(cx).start_is_left() {
229 self.text_right()
230 } else {
231 self.text_left()
232 }
233 }
234}
235
236impl<T: Styled> LogicalStyledExt for T {}
237
238#[cfg(test)]
239mod tests {
240 use super::*;
241 use gpui::{TestAppContext, div, px};
242
243 #[test]
244 fn locale_direction() {
245 for rtl in ["ar", "ar-EG", "he_IL", "fa", "ur-PK", "HE", "yi.UTF-8"] {
246 assert_eq!(
247 LayoutDirection::from_locale(rtl),
248 LayoutDirection::Rtl,
249 "{rtl}"
250 );
251 }
252 for ltr in ["en", "en-US", "zh-CN", "", "C", "arn"] {
253 assert_eq!(
254 LayoutDirection::from_locale(ltr),
255 LayoutDirection::Ltr,
256 "{ltr}"
257 );
258 }
259 }
260
261 #[gpui::test]
262 fn logical_edges_follow_global_direction(cx: &mut TestAppContext) {
263 cx.update(|cx| {
264 crate::init(cx);
265 assert_eq!(LayoutDirection::global(cx), LayoutDirection::Ltr);
266
267 let mut ltr = div().ps(px(4.), cx).me(px(8.), cx).border_s(px(1.), cx);
268 let style = ltr.style();
269 assert_eq!(style.padding.left, Some(px(4.).into()));
270 assert_eq!(style.margin.right, Some(px(8.).into()));
271 assert_eq!(style.border_widths.left, Some(px(1.).into()));
272
273 LayoutDirection::Rtl.set_global(cx);
274 let mut rtl = div().ps(px(4.), cx).me(px(8.), cx).border_s(px(1.), cx);
275 let style = rtl.style();
276 assert_eq!(style.padding.right, Some(px(4.).into()));
277 assert_eq!(style.padding.left, None);
278 assert_eq!(style.margin.left, Some(px(8.).into()));
279 assert_eq!(style.border_widths.right, Some(px(1.).into()));
280 });
281 }
282
283 #[gpui::test]
284 fn flex_justification_follows_row_direction(cx: &mut TestAppContext) {
285 use gpui::{
286 Context, InteractiveElement as _, IntoElement, ParentElement as _, Render, Window,
287 };
288
289 struct Row;
290 impl Render for Row {
291 fn render(&mut self, _: &mut Window, cx: &mut Context<Self>) -> impl IntoElement {
292 div()
293 .flex_row_dir(cx)
294 .w(px(100.))
295 .justify_flex_end()
296 .child(div().size(px(10.)).debug_selector(|| "item".into()))
297 }
298 }
299
300 cx.update(crate::init);
301 for (direction, expected_left) in [
302 (LayoutDirection::Ltr, px(90.)),
303 (LayoutDirection::Rtl, px(0.)),
304 ] {
305 cx.update(|cx| direction.set_global(cx));
306 let (_, window) = cx.add_window_view(|_, _| Row);
307 window.update(|window, cx| window.draw(cx).clear(cx));
308 let item = window.debug_bounds("item").expect("item not rendered");
309 assert_eq!(item.left(), expected_left, "{direction:?}");
310 }
311 }
312
313 #[gpui::test]
314 fn text_alignment_follows_global_direction(cx: &mut TestAppContext) {
315 use gpui::TextAlign;
316 cx.update(|cx| {
317 crate::init(cx);
318 assert_eq!(
319 div().text_start(cx).style().text.text_align,
320 Some(TextAlign::Left)
321 );
322 assert_eq!(
323 div().text_end(cx).style().text.text_align,
324 Some(TextAlign::Right)
325 );
326
327 LayoutDirection::Rtl.set_global(cx);
328 assert_eq!(
329 div().text_start(cx).style().text.text_align,
330 Some(TextAlign::Right)
331 );
332 assert_eq!(
333 div().text_end(cx).style().text.text_align,
334 Some(TextAlign::Left)
335 );
336 });
337 }
338}