Skip to main content

gpui_material_components/navigation/multi_pane/
render.rs

1use std::time::Duration;
2
3use gpui::{
4    AnyElement, App, Bounds, ElementId, Entity, FocusHandle, InteractiveElement, IntoElement,
5    ParentElement, Pixels, RenderOnce, Role, Size, StatefulInteractiveElement, Styled,
6    WeakFocusHandle, Window, div, prelude::FluentBuilder, px, size,
7};
8use gpui_base::{FocusTrapElement, TestSupportExt};
9use gpui_material_foundation::current_material_theme;
10
11use crate::VerticalDragHandle;
12
13use super::{
14    AdaptivePane, AdaptivePaneLayout, AdaptivePaneState, PaneExpansionAnchor, PaneLayoutDirective,
15    PanePlacement, PaneRole, PaneSeparator,
16    geometry::{Boundary, GeometryInput, Measures, length},
17    state::{Adaptation, Frames},
18    types::pair_index,
19};
20
21struct LayoutFocus {
22    panes: [FocusHandle; 3],
23    separators: [FocusHandle; 9],
24    remembered: [Option<FocusHandle>; 3],
25    overlay: Option<PaneRole>,
26    trap: Option<WeakFocusHandle>,
27}
28
29struct FocusPlan<'a> {
30    active: Option<PaneRole>,
31    overlay: Option<PaneRole>,
32    modal: Option<&'a FocusHandle>,
33    panes: &'a [Option<AdaptivePane>; 3],
34    frames: Frames,
35    separators: &'a [bool; 9],
36}
37
38impl LayoutFocus {
39    fn new(cx: &mut App) -> Self {
40        Self {
41            panes: std::array::from_fn(|_| cx.focus_handle().tab_stop(false)),
42            separators: std::array::from_fn(|_| cx.focus_handle().tab_stop(false)),
43            remembered: Default::default(),
44            overlay: None,
45            trap: None,
46        }
47    }
48
49    fn restore(&mut self, plan: FocusPlan<'_>, window: &mut Window, cx: &mut App) {
50        let opened = self.overlay != plan.overlay;
51        self.overlay = plan.overlay;
52        // The pane's stable scope survives the projection. The separate modal
53        // scope only exists while levitated, so Base cannot keep trapping Tab
54        // when the same pane has reflowed or become a normal column.
55        let prior_trap = self.trap.take();
56        self.trap = plan.modal.map(FocusHandle::downgrade);
57        let Some(focused) = window.focused(cx) else {
58            return;
59        };
60        let old = self
61            .panes
62            .iter()
63            .position(|pane| pane.contains(&focused, window));
64        let boundary = self
65            .separators
66            .iter()
67            .position(|scope| scope.contains(&focused, window));
68        if let Some(ix) = old
69            && focused != self.panes[ix]
70        {
71            self.remembered[ix] = Some(focused.clone());
72        }
73        let released_trap = prior_trap
74            .and_then(|scope| scope.upgrade())
75            .is_some_and(|scope| focused == scope && plan.modal != Some(&scope));
76        let transfer_to_overlay = plan.overlay.filter(|_| opened || plan.modal.is_some());
77        let needs_restore = released_trap
78            || old.is_some_and(|ix| {
79                plan.frames[ix].is_none()
80                    || transfer_to_overlay.is_some_and(|active| ix != active.index())
81            })
82            || boundary.is_some_and(|ix| !plan.separators[ix] || transfer_to_overlay.is_some());
83        if !needs_restore {
84            return;
85        }
86        if let Some(next) = transfer_to_overlay.or(plan.active) {
87            let ix = next.index();
88            let scope = self.panes[ix].clone();
89            let remembered = self.remembered[ix].clone();
90            let entry = plan.panes[ix]
91                .as_ref()
92                .and_then(|pane| pane.entry_focus.clone());
93            window.defer(cx, move |window, cx| {
94                if window.focused(cx).is_none_or(|current| current == focused) {
95                    remembered
96                        .filter(|handle| scope.contains(handle, window))
97                        .or_else(|| entry.filter(|handle| scope.contains(handle, window)))
98                        .unwrap_or(scope)
99                        .focus(window, cx);
100                }
101            });
102        } else {
103            window.blur(cx);
104        }
105    }
106}
107
108impl RenderOnce for AdaptivePaneLayout {
109    fn render(mut self, window: &mut Window, cx: &mut App) -> impl IntoElement {
110        let viewport = size(length(self.viewport.width), length(self.viewport.height));
111        let directive = self
112            .directive
113            .take()
114            .unwrap_or_else(|| PaneLayoutDirective::for_size(viewport));
115        let adaptation = Adaptation {
116            horizontal: directive.horizontal_partitions,
117            vertical: directive.vertical_partitions,
118            strategies: std::array::from_fn(|ix| {
119                self.panes[ix]
120                    .as_ref()
121                    .map(|pane| pane.strategy(viewport, &directive))
122            }),
123        };
124        let input = GeometryInput {
125            viewport,
126            direction: current_material_theme(window, cx).layout.direction,
127            directive: &directive,
128            order: self.order,
129            measures: std::array::from_fn(|ix| {
130                self.panes[ix]
131                    .as_ref()
132                    .map_or_else(Measures::default, |pane| pane.measures)
133            }),
134        };
135        let duration = if cx.reduce_motion() {
136            Duration::ZERO
137        } else {
138            self.duration
139        };
140        let (active, placement, geometry, sample, transitioning) =
141            self.state.update(cx, |state, cx| {
142                let active = state.current_destination().role;
143                let placement = state.project(adaptation);
144                let geometry = input.layout(placement, |start, end| state.expansion(start, end));
145                let sample = state.sample(
146                    placement,
147                    geometry.panes,
148                    cx.background_executor().now(),
149                    duration,
150                    cx,
151                );
152                (
153                    active,
154                    placement,
155                    geometry,
156                    sample,
157                    state.is_transitioning(),
158                )
159            });
160        if sample.animate_next_frame {
161            window.request_animation_frame();
162        }
163
164        let can_show = |role: PaneRole| sample.frames[role.index()].is_some();
165        let overlay =
166            self.order.into_iter().rev().find(|role| {
167                can_show(*role) && matches!(placement[*role], PanePlacement::Levitate(_))
168            });
169        let modal = overlay.is_some_and(|role| {
170            self.panes[role.index()]
171                .as_ref()
172                .is_some_and(|pane| pane.scrim.is_some())
173        });
174        let active = if can_show(active) {
175            Some(active)
176        } else {
177            self.order.into_iter().find(|role| can_show(*role))
178        };
179        let trap = overlay.filter(|_| modal).map(|role| {
180            window
181                .use_keyed_state(
182                    (
183                        self.id.clone(),
184                        ["primary-modal", "secondary-modal", "extra-modal"][role.index()],
185                    ),
186                    cx,
187                    |_, cx| cx.focus_handle().tab_stop(false),
188                )
189                .read(cx)
190                .clone()
191        });
192        let mut active_separators = [false; 9];
193        for boundary in &geometry.boundaries {
194            let ix = pair_index(boundary.start, boundary.end);
195            // Do not create a movable target during a changing pane arrangement.
196            active_separators[ix] = !transitioning
197                && !modal
198                && self.separators[ix].is_some()
199                && boundary.min < boundary.max;
200        }
201
202        let focus_state = window.use_keyed_state((self.id.clone(), "pane-focus"), cx, |_, cx| {
203            LayoutFocus::new(cx)
204        });
205        let (pane_focus, separator_focus) = focus_state.update(cx, |focus, cx| {
206            focus.restore(
207                FocusPlan {
208                    active,
209                    overlay,
210                    modal: trap.as_ref(),
211                    panes: &self.panes,
212                    frames: sample.frames,
213                    separators: &active_separators,
214                },
215                window,
216                cx,
217            );
218            (focus.panes.clone(), focus.separators.clone())
219        });
220
221        let layout_id = self.id.clone();
222        let mut root = div()
223            .id(self.id)
224            .test_support()
225            .relative()
226            .w(viewport.width)
227            .h(viewport.height)
228            .overflow_hidden();
229        // Panes keep sibling scopes while changing between normal, reflowed and
230        // levitated placements. Their child IDs never inherit a neighbor's path.
231        for role in self.order {
232            if let Some(pane) = self.panes[role.index()].take_if(|_| {
233                can_show(role) && !matches!(placement[role], PanePlacement::Levitate(_))
234            }) {
235                root = root.child(render_pane(
236                    pane,
237                    sample.frames[role.index()].unwrap(),
238                    &pane_focus[role.index()],
239                    false,
240                    None,
241                    modal,
242                ));
243            }
244        }
245        for boundary in geometry.boundaries {
246            let ix = pair_index(boundary.start, boundary.end);
247            if active_separators[ix] {
248                let separator = self.separators[ix].take().unwrap();
249                root = root.child(render_separator(
250                    &layout_id,
251                    separator,
252                    boundary,
253                    viewport,
254                    &self.state,
255                    &separator_focus[ix],
256                ));
257            }
258        }
259        for role in self.order {
260            if let Some(mut pane) = self.panes[role.index()].take_if(|_| can_show(role)) {
261                let backdrop = pane.scrim.take();
262                let is_modal = Some(role) == overlay && backdrop.is_some();
263                if let Some(backdrop) = backdrop {
264                    root = root.child(
265                        div()
266                            .id((pane.id.clone(), "backdrop"))
267                            .absolute()
268                            .inset_0()
269                            .occlude()
270                            .child(backdrop),
271                    );
272                }
273                root = root.child(render_pane(
274                    pane,
275                    sample.frames[role.index()].unwrap(),
276                    &pane_focus[role.index()],
277                    true,
278                    trap.as_ref().filter(|_| is_modal),
279                    modal && Some(role) != overlay,
280                ));
281            }
282        }
283        root
284    }
285}
286
287fn render_pane(
288    pane: AdaptivePane,
289    bounds: Bounds<Pixels>,
290    focus: &FocusHandle,
291    elevated: bool,
292    modal: Option<&FocusHandle>,
293    hidden_from_a11y: bool,
294) -> AnyElement {
295    let content_id: ElementId = (pane.id.clone(), "pane-content").into();
296    let body = div()
297        .id(content_id.clone())
298        .size_full()
299        .flex()
300        .flex_col()
301        .child(pane.content);
302    let body = if let Some(trap) = modal {
303        body.focus_trap(content_id, trap).into_any_element()
304    } else {
305        body.into_any_element()
306    };
307    div()
308        .id(pane.id)
309        .role(Role::Group)
310        .test_support()
311        .track_focus(focus)
312        .absolute()
313        .left(bounds.left())
314        .top(bounds.top())
315        .w(bounds.size.width)
316        .h(bounds.size.height)
317        .min_w_0()
318        .min_h_0()
319        .flex()
320        .flex_col()
321        .overflow_hidden()
322        .when(elevated, |node| node.occlude())
323        .when(hidden_from_a11y, |node| {
324            node.a11y_synthetic_children(|tree| tree.parent_node().set_hidden())
325        })
326        .child(body)
327        .into_any_element()
328}
329
330fn render_separator(
331    layout_id: &ElementId,
332    separator: PaneSeparator,
333    boundary: Boundary,
334    viewport: Size<Pixels>,
335    owner: &Entity<AdaptivePaneState>,
336    focus: &FocusHandle,
337) -> impl IntoElement {
338    let pair = pair_index(boundary.start, boundary.end);
339    let handle = VerticalDragHandle::new((layout_id.clone(), format!("pane-separator-{pair}")));
340    let handle = match separator.build {
341        Some(build) => build(handle),
342        None => handle,
343    };
344    let resize = owner.clone();
345    let snap = owner.clone();
346    let keyboard_state = owner.clone();
347    let keyboard_anchors = separator.anchors.clone();
348    div()
349        .id((layout_id.clone(), format!("pane-boundary-{pair}")))
350        .track_focus(focus)
351        .absolute()
352        .left(boundary.center - px(24.))
353        .top_0()
354        .w(px(48.))
355        .h(viewport.height)
356        .flex()
357        .items_center()
358        .justify_center()
359        .when(!keyboard_anchors.is_empty(), |container| {
360            container.on_key_down(move |event, _, cx| {
361                if event.keystroke.modifiers.modified() {
362                    return;
363                }
364                let sign = match event.keystroke.key.as_str() {
365                    "pageup" => 1.,
366                    "pagedown" => -1.,
367                    _ => return,
368                };
369                let anchor = boundary
370                    .anchors(&keyboard_anchors)
371                    .map(|(anchor, at)| (anchor, f32::from(at - boundary.position) * sign))
372                    .filter(|(_, distance)| *distance > 0.01)
373                    .min_by(|(_, a), (_, b)| a.total_cmp(b));
374                if let Some((anchor, _)) = anchor {
375                    keyboard_state.update(cx, |state, cx| {
376                        state.set_expansion(boundary.start, boundary.end, anchor, cx)
377                    });
378                }
379                cx.stop_propagation();
380            })
381        })
382        .child(
383            handle
384                .resize_context(viewport)
385                .keyboard_step(separator.keyboard_step)
386                .on_resize(
387                    separator.label,
388                    boundary.position,
389                    boundary.min..=boundary.max,
390                    move |position, _, cx| {
391                        resize.update(cx, |state, cx| {
392                            state.set_expansion(
393                                boundary.start,
394                                boundary.end,
395                                PaneExpansionAnchor::FromStart(position),
396                                cx,
397                            )
398                        });
399                    },
400                )
401                .on_resize_end(move |position, _, cx| {
402                    let anchor = boundary
403                        .anchors(&separator.anchors)
404                        .map(|(anchor, at)| (anchor, f32::from((at - position).abs())))
405                        .min_by(|(_, a), (_, b)| a.total_cmp(b));
406                    if let Some((anchor, _)) = anchor {
407                        snap.update(cx, |state, cx| {
408                            state.set_expansion(boundary.start, boundary.end, anchor, cx)
409                        });
410                    }
411                }),
412        )
413}