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,
125 pl,
126 pr,
127 DefiniteLength
128 );
129 logical_edge!(
130 pe,
132 pr,
133 pl,
134 DefiniteLength
135 );
136 logical_edge!(
137 ms,
139 ml,
140 mr,
141 Length
142 );
143 logical_edge!(
144 me,
146 mr,
147 ml,
148 Length
149 );
150 logical_edge!(
151 inset_s,
153 left,
154 right,
155 Length
156 );
157 logical_edge!(
158 inset_e,
160 right,
161 left,
162 Length
163 );
164
165 fn border_s(mut self, width: impl Into<AbsoluteLength>, cx: &App) -> Self {
167 let width = Some(width.into());
168 let widths = &mut self.style().border_widths;
169 if LayoutDirection::global(cx).start_is_left() {
170 widths.left = width;
171 } else {
172 widths.right = width;
173 }
174 self
175 }
176
177 fn border_e(mut self, width: impl Into<AbsoluteLength>, cx: &App) -> Self {
179 let width = Some(width.into());
180 let widths = &mut self.style().border_widths;
181 if LayoutDirection::global(cx).start_is_left() {
182 widths.right = width;
183 } else {
184 widths.left = width;
185 }
186 self
187 }
188
189 fn rounded_s(self, radius: impl Into<AbsoluteLength> + Clone, cx: &App) -> Self {
191 if LayoutDirection::global(cx).start_is_left() {
192 self.rounded_l(radius)
193 } else {
194 self.rounded_r(radius)
195 }
196 }
197
198 fn rounded_e(self, radius: impl Into<AbsoluteLength> + Clone, cx: &App) -> Self {
200 if LayoutDirection::global(cx).start_is_left() {
201 self.rounded_r(radius)
202 } else {
203 self.rounded_l(radius)
204 }
205 }
206
207 fn flex_row_dir(self, cx: &App) -> Self {
210 if LayoutDirection::global(cx).is_rtl() {
211 self.flex().flex_row_reverse()
212 } else {
213 self.flex().flex_row()
214 }
215 }
216
217 fn justify_flex_start(mut self) -> Self {
223 self.style().justify_content = Some(JustifyContent::FlexStart);
224 self
225 }
226
227 fn justify_flex_end(mut self) -> Self {
231 self.style().justify_content = Some(JustifyContent::FlexEnd);
232 self
233 }
234
235 fn text_start(self, cx: &App) -> Self {
237 if LayoutDirection::global(cx).start_is_left() {
238 self.text_left()
239 } else {
240 self.text_right()
241 }
242 }
243
244 fn text_end(self, cx: &App) -> Self {
246 if LayoutDirection::global(cx).start_is_left() {
247 self.text_right()
248 } else {
249 self.text_left()
250 }
251 }
252}
253
254impl<T: Styled> LogicalStyledExt for T {}
255
256#[cfg(test)]
257mod tests {
258 use super::*;
259 use gpui::{TestAppContext, div, px};
260
261 #[test]
262 fn locale_direction() {
263 for rtl in ["ar", "ar-EG", "he_IL", "fa", "ur-PK", "HE", "yi.UTF-8"] {
264 assert_eq!(
265 LayoutDirection::from_locale(rtl),
266 LayoutDirection::Rtl,
267 "{rtl}"
268 );
269 }
270 for ltr in ["en", "en-US", "zh-CN", "", "C", "arn"] {
271 assert_eq!(
272 LayoutDirection::from_locale(ltr),
273 LayoutDirection::Ltr,
274 "{ltr}"
275 );
276 }
277 }
278
279 #[gpui::test]
280 fn logical_edges_follow_global_direction(cx: &mut TestAppContext) {
281 cx.update(|cx| {
282 crate::init(cx);
283 assert_eq!(LayoutDirection::global(cx), LayoutDirection::Ltr);
284
285 let mut ltr = div().ps(px(4.), cx).me(px(8.), cx).border_s(px(1.), cx);
286 let style = ltr.style();
287 assert_eq!(style.padding.left, Some(px(4.).into()));
288 assert_eq!(style.margin.right, Some(px(8.).into()));
289 assert_eq!(style.border_widths.left, Some(px(1.).into()));
290
291 LayoutDirection::Rtl.set_global(cx);
292 let mut rtl = div().ps(px(4.), cx).me(px(8.), cx).border_s(px(1.), cx);
293 let style = rtl.style();
294 assert_eq!(style.padding.right, Some(px(4.).into()));
295 assert_eq!(style.padding.left, None);
296 assert_eq!(style.margin.left, Some(px(8.).into()));
297 assert_eq!(style.border_widths.right, Some(px(1.).into()));
298 });
299 }
300
301 #[gpui::test]
302 fn flex_justification_follows_row_direction(cx: &mut TestAppContext) {
303 use gpui::{
304 Context, InteractiveElement as _, IntoElement, ParentElement as _, Render, Window,
305 };
306
307 struct Row;
308 impl Render for Row {
309 fn render(&mut self, _: &mut Window, cx: &mut Context<Self>) -> impl IntoElement {
310 div()
311 .flex_row_dir(cx)
312 .w(px(100.))
313 .justify_flex_end()
314 .child(div().size(px(10.)).debug_selector(|| "item".into()))
315 }
316 }
317
318 cx.update(crate::init);
319 for (direction, expected_left) in [
320 (LayoutDirection::Ltr, px(90.)),
321 (LayoutDirection::Rtl, px(0.)),
322 ] {
323 cx.update(|cx| direction.set_global(cx));
324 let (_, window) = cx.add_window_view(|_, _| Row);
325 window.update(|window, cx| window.draw(cx).clear(cx));
326 let item = window.debug_bounds("item").expect("item not rendered");
327 assert_eq!(item.left(), expected_left, "{direction:?}");
328 }
329 }
330
331 #[gpui::test]
332 fn text_alignment_follows_global_direction(cx: &mut TestAppContext) {
333 use gpui::TextAlign;
334 cx.update(|cx| {
335 crate::init(cx);
336 assert_eq!(
337 div().text_start(cx).style().text.text_align,
338 Some(TextAlign::Left)
339 );
340 assert_eq!(
341 div().text_end(cx).style().text.text_align,
342 Some(TextAlign::Right)
343 );
344
345 LayoutDirection::Rtl.set_global(cx);
346 assert_eq!(
347 div().text_start(cx).style().text.text_align,
348 Some(TextAlign::Right)
349 );
350 assert_eq!(
351 div().text_end(cx).style().text.text_align,
352 Some(TextAlign::Left)
353 );
354 });
355 }
356}