1use gpui::{
4 AnyElement, App, Bounds, Div, Element, ElementId, Global, GlobalElementId, InspectorElementId,
5 IntoElement, LayoutId, ParentElement, Pixels, StyleRefinement, Styled, Window, div,
6};
7
8#[derive(Clone, Copy, Debug, Default, Eq, PartialEq)]
10pub enum Direction {
11 #[default]
12 Ltr,
13 Rtl,
14}
15
16impl Direction {
17 pub fn current(cx: &App) -> Self {
19 cx.try_global::<DirectionScope>()
20 .map_or(Self::Ltr, |scope| scope.0)
21 }
22
23 pub fn is_rtl(self) -> bool {
24 self == Self::Rtl
25 }
26
27 pub fn horizontal_forward(self, physical_right: bool) -> bool {
29 physical_right != self.is_rtl()
30 }
31
32 pub fn physical_fraction(self, logical: f32) -> f32 {
34 if self.is_rtl() { 1. - logical } else { logical }
35 }
36
37 pub fn row<E: Styled>(self, element: E) -> E {
40 if self.is_rtl() {
41 element.flex().flex_row_reverse()
42 } else {
43 element.flex().flex_row()
44 }
45 }
46
47 fn scope<T>(self, cx: &mut App, run: impl FnOnce(&mut App) -> T) -> T {
48 let previous = cx.default_global::<DirectionScope>().0;
49 cx.default_global::<DirectionScope>().0 = self;
50 let result = run(cx);
51 cx.default_global::<DirectionScope>().0 = previous;
52 result
53 }
54}
55
56#[derive(Default)]
57struct DirectionScope(Direction);
58impl Global for DirectionScope {}
59
60pub struct DirectionProvider {
70 direction: Direction,
71 base: Div,
72}
73
74impl DirectionProvider {
75 pub fn new(direction: Direction) -> Self {
76 let base = if direction.is_rtl() {
77 div().text_right()
78 } else {
79 div().text_left()
80 };
81 Self { direction, base }
82 }
83}
84
85impl Styled for DirectionProvider {
86 fn style(&mut self) -> &mut StyleRefinement {
87 self.base.style()
88 }
89}
90
91impl ParentElement for DirectionProvider {
92 fn extend(&mut self, elements: impl IntoIterator<Item = AnyElement>) {
93 self.base.extend(elements);
94 }
95}
96
97impl IntoElement for DirectionProvider {
98 type Element = Self;
99 fn into_element(self) -> Self {
100 self
101 }
102}
103
104impl Element for DirectionProvider {
105 type RequestLayoutState = <Div as Element>::RequestLayoutState;
106 type PrepaintState = <Div as Element>::PrepaintState;
107
108 fn id(&self) -> Option<ElementId> {
109 Element::id(&self.base)
110 }
111 fn source_location(&self) -> Option<&'static std::panic::Location<'static>> {
112 self.base.source_location()
113 }
114
115 fn request_layout(
116 &mut self,
117 id: Option<&GlobalElementId>,
118 inspector: Option<&InspectorElementId>,
119 window: &mut Window,
120 cx: &mut App,
121 ) -> (LayoutId, Self::RequestLayoutState) {
122 self.direction
123 .scope(cx, |cx| self.base.request_layout(id, inspector, window, cx))
124 }
125
126 fn prepaint(
127 &mut self,
128 id: Option<&GlobalElementId>,
129 inspector: Option<&InspectorElementId>,
130 bounds: Bounds<Pixels>,
131 layout: &mut Self::RequestLayoutState,
132 window: &mut Window,
133 cx: &mut App,
134 ) -> Self::PrepaintState {
135 self.direction.scope(cx, |cx| {
136 self.base
137 .prepaint(id, inspector, bounds, layout, window, cx)
138 })
139 }
140
141 fn paint(
142 &mut self,
143 id: Option<&GlobalElementId>,
144 inspector: Option<&InspectorElementId>,
145 bounds: Bounds<Pixels>,
146 layout: &mut Self::RequestLayoutState,
147 prepaint: &mut Self::PrepaintState,
148 window: &mut Window,
149 cx: &mut App,
150 ) {
151 self.direction.scope(cx, |cx| {
152 self.base
153 .paint(id, inspector, bounds, layout, prepaint, window, cx)
154 });
155 }
156}
157
158#[cfg(test)]
159mod tests {
160 use super::*;
161 use crate::{Root, Slider, SliderState, SliderThumb, Tab, TabItem, TabList, TabsState};
162 use gpui::{AppContext as _, Axis, Context, Entity, Render, TestAppContext, px, relative};
163 use std::{cell::RefCell, rc::Rc};
164
165 #[derive(IntoElement)]
166 struct Probe(Rc<RefCell<Vec<Direction>>>);
167 impl gpui::RenderOnce for Probe {
168 fn render(self, _: &mut Window, cx: &mut App) -> impl IntoElement {
169 self.0.borrow_mut().push(Direction::current(cx));
170 div()
171 }
172 }
173
174 struct Harness {
175 tabs: Entity<TabsState>,
176 slider: Entity<SliderState>,
177 vertical_slider: Entity<SliderState>,
178 directions: Rc<RefCell<Vec<Direction>>>,
179 }
180 impl Render for Harness {
181 fn render(&mut self, _: &mut Window, cx: &mut Context<Self>) -> impl IntoElement {
182 div()
183 .child(Probe(self.directions.clone()))
184 .child(
185 DirectionProvider::new(Direction::Rtl)
186 .w(px(400.))
187 .child(Probe(self.directions.clone()))
188 .child(
189 DirectionProvider::new(Direction::Ltr)
190 .child(Probe(self.directions.clone())),
191 )
192 .child(Probe(self.directions.clone()))
193 .child(
194 Direction::Rtl
195 .row(TabList::new("rtl-tabs", &self.tabs))
196 .child(Tab::new(&self.tabs, 0).child("First"))
197 .child(Tab::new(&self.tabs, 1).child("Second")),
198 )
199 .child(
200 Slider::new("rtl-slider", &self.slider)
201 .relative()
202 .w(px(200.))
203 .h(px(30.))
204 .child(
205 SliderThumb::new(&self.slider, 0)
206 .absolute()
207 .left(relative(
208 Direction::Rtl.physical_fraction(
209 self.slider.read(cx).percentage(0),
210 ),
211 ))
212 .ml(px(-10.))
213 .w(px(20.))
214 .h(px(30.)),
215 ),
216 )
217 .child(
218 Slider::new("rtl-vertical-slider", &self.vertical_slider)
219 .axis(Axis::Vertical)
220 .relative()
221 .w(px(30.))
222 .h(px(120.))
223 .child(
224 SliderThumb::new(&self.vertical_slider, 0)
225 .absolute()
226 .bottom(relative(
227 self.vertical_slider.read(cx).percentage(0),
228 ))
229 .mb(px(-10.))
230 .w(px(30.))
231 .h(px(20.)),
232 ),
233 ),
234 )
235 .child(Probe(self.directions.clone()))
236 }
237 }
238
239 #[gpui::test]
240 fn nested_scope_restores_siblings_and_mirrors_native_keys(cx: &mut TestAppContext) {
241 cx.update(crate::init);
242 let directions = Rc::new(RefCell::new(Vec::new()));
243 let observed = directions.clone();
244 let (root, cx) = cx.add_window_view(|window, cx| {
245 let view = cx.new(|cx| Harness {
246 tabs: cx.new(|cx| {
247 TabsState::new(
248 [TabItem::new("a", "First"), TabItem::new("b", "Second")],
249 cx,
250 )
251 }),
252 slider: cx.new(|cx| SliderState::new(0.0..=100.0, 10., [50.], cx)),
253 vertical_slider: cx.new(|cx| SliderState::new(0.0..=100.0, 10., [50.], cx)),
254 directions,
255 });
256 Root::new(view, window, cx)
257 });
258 let view = root
259 .read_with(cx, |root, _| root.view().clone())
260 .downcast::<Harness>()
261 .unwrap();
262 cx.update(|window, cx| {
263 window.activate_window();
264 let focus = view.read(cx).tabs.read(cx).tab_focus_handle(0).clone();
265 focus.focus(window, cx);
266 observed.borrow_mut().clear();
267 window.draw(cx).clear(cx);
268 });
269 assert_eq!(
270 &*observed.borrow(),
271 &[
272 Direction::Ltr,
273 Direction::Rtl,
274 Direction::Ltr,
275 Direction::Rtl,
276 Direction::Ltr
277 ]
278 );
279 cx.simulate_keystrokes("left");
280 cx.run_until_parked();
281 cx.update(|window, cx| {
282 assert_eq!(view.read(cx).tabs.read(cx).selected_index(), Some(1));
283 let focus = view.read(cx).slider.read(cx).thumb_focus_handle(0).clone();
284 focus.focus(window, cx);
285 window.draw(cx).clear(cx);
286 });
287 cx.simulate_keystrokes("left");
288 cx.update(|window, cx| {
289 assert_eq!(view.read(cx).slider.read(cx).values()[0], 60.);
290 assert_eq!(Direction::current(cx), Direction::Ltr);
291 view.read(cx)
292 .vertical_slider
293 .read(cx)
294 .thumb_focus_handle(0)
295 .clone()
296 .focus(window, cx);
297 window.draw(cx).clear(cx);
298 });
299 cx.simulate_keystrokes("left");
300 cx.update(|_, cx| assert_eq!(view.read(cx).vertical_slider.read(cx).values()[0], 40.));
301 cx.simulate_keystrokes("right up");
302 cx.update(|_, cx| assert_eq!(view.read(cx).vertical_slider.read(cx).values()[0], 60.));
303 #[cfg(feature = "test-support")]
304 {
305 let bounds = cx.update(|window, _| {
306 crate::test_support::find(window, &[], &"rtl-slider".into())
307 .unwrap()
308 .bounds()
309 });
310 cx.simulate_mouse_down(
311 gpui::point(bounds.left(), bounds.center().y),
312 gpui::MouseButton::Left,
313 gpui::Modifiers::default(),
314 );
315 cx.simulate_mouse_up(
316 gpui::point(bounds.left(), bounds.center().y),
317 gpui::MouseButton::Left,
318 gpui::Modifiers::default(),
319 );
320 cx.update(|_, cx| assert_eq!(view.read(cx).slider.read(cx).values()[0], 100.));
321 }
322 }
323}