1use std::time::Duration;
2
3use gpui::{
4 AnyElement, App, Bounds, ElementId, Entity, FocusHandle, InteractiveElement, IntoElement,
5 ParentElement, Pixels, RenderOnce, Role, SharedString, Size, StatefulInteractiveElement,
6 Styled, WeakFocusHandle, Window, div, prelude::FluentBuilder, px, size,
7};
8use gpui_base::{FocusTrapElement, TestSupportExt};
9use gpui_material_foundation::window_material_theme;
10
11use crate::VerticalDragHandle;
12
13mod geometry;
14mod state;
15
16use geometry::{Boundary, GeometryInput, Measures, length};
17use state::{Adaptation, Frames};
18
19pub use geometry::{PaneExpansionAnchor, PaneLayoutDirective, PaneMargins, PaneOverlayAlignment};
20pub use state::{
21 AdaptivePaneState, PaneAdaptStrategy, PaneBackBehavior, PaneDestination, PaneLayoutValue,
22 PanePlacement, PaneRole,
23};
24
25type AdaptationRule = Box<dyn Fn(Size<Pixels>, &PaneLayoutDirective) -> PaneAdaptStrategy>;
26type HandleBuilder = Box<dyn FnOnce(VerticalDragHandle) -> VerticalDragHandle>;
27
28pub struct AdaptivePane {
30 id: ElementId,
31 content: AnyElement,
32 measures: Measures,
33 adapt: Option<PaneAdaptStrategy>,
34 rule: Option<AdaptationRule>,
35 scrim: Option<AnyElement>,
36 entry_focus: Option<FocusHandle>,
37}
38
39impl AdaptivePane {
40 pub fn new(id: impl Into<ElementId>, content: impl IntoElement) -> Self {
41 Self {
42 id: id.into(),
43 content: content.into_any_element(),
44 measures: Measures::default(),
45 adapt: None,
46 rule: None,
47 scrim: None,
48 entry_focus: None,
49 }
50 }
51
52 pub fn preferred_width(mut self, width: Pixels) -> Self {
53 self.measures.preferred_width = Some(width);
54 self
55 }
56
57 pub fn preferred_height(mut self, height: Pixels) -> Self {
58 self.measures.preferred_height = Some(height);
59 self
60 }
61
62 pub fn minimum_width(mut self, width: Pixels) -> Self {
63 self.measures.minimum_width = width;
64 self
65 }
66
67 pub fn margins(mut self, margins: PaneMargins) -> Self {
68 self.measures.margins = margins;
69 self
70 }
71
72 pub fn adapt(mut self, strategy: PaneAdaptStrategy) -> Self {
73 self.adapt = Some(strategy);
74 self.rule = None;
75 self
76 }
77
78 pub fn adapt_with(
80 mut self,
81 rule: impl Fn(Size<Pixels>, &PaneLayoutDirective) -> PaneAdaptStrategy + 'static,
82 ) -> Self {
83 self.rule = Some(Box::new(rule));
84 self
85 }
86
87 pub fn levitate_scrim(mut self, scrim: impl IntoElement) -> Self {
89 self.scrim = Some(scrim.into_any_element());
90 self
91 }
92
93 pub fn entry_focus(mut self, focus: &FocusHandle) -> Self {
94 self.entry_focus = Some(focus.clone());
95 self
96 }
97
98 pub(super) fn has_adaptation(&self) -> bool {
99 self.rule.is_some() || self.adapt.is_some()
100 }
101
102 fn strategy(&self, size: Size<Pixels>, directive: &PaneLayoutDirective) -> PaneAdaptStrategy {
103 self.rule
104 .as_ref()
105 .map_or(self.adapt.unwrap_or_default(), |rule| rule(size, directive))
106 }
107}
108
109pub struct PaneSeparator {
111 label: SharedString,
112 anchors: Vec<PaneExpansionAnchor>,
113 keyboard_step: Pixels,
114 build: Option<HandleBuilder>,
115}
116
117impl PaneSeparator {
118 pub fn new(label: impl Into<SharedString>) -> Self {
119 Self {
120 label: label.into(),
121 anchors: Vec::new(),
122 keyboard_step: px(8.),
123 build: None,
124 }
125 }
126
127 pub fn anchors(mut self, anchors: impl IntoIterator<Item = PaneExpansionAnchor>) -> Self {
128 self.anchors = anchors.into_iter().collect();
129 self
130 }
131
132 pub fn keyboard_step(mut self, step: Pixels) -> Self {
133 self.keyboard_step = step;
134 self
135 }
136
137 pub fn handle(
139 mut self,
140 build: impl FnOnce(VerticalDragHandle) -> VerticalDragHandle + 'static,
141 ) -> Self {
142 self.build = Some(Box::new(build));
143 self
144 }
145}
146
147fn pair_index(start: PaneRole, end: PaneRole) -> usize {
148 start.index() * 3 + end.index()
149}
150
151#[derive(IntoElement)]
154pub struct AdaptivePaneLayout {
155 id: ElementId,
156 viewport: Size<Pixels>,
157 state: Entity<AdaptivePaneState>,
158 directive: Option<PaneLayoutDirective>,
159 panes: [Option<AdaptivePane>; 3],
160 order: [PaneRole; 3],
161 separators: [Option<PaneSeparator>; 9],
162 duration: Duration,
163}
164
165impl AdaptivePaneLayout {
166 pub fn new(
167 id: impl Into<ElementId>,
168 viewport: Size<Pixels>,
169 state: &Entity<AdaptivePaneState>,
170 ) -> Self {
171 Self {
172 id: id.into(),
173 viewport,
174 state: state.clone(),
175 directive: None,
176 panes: Default::default(),
177 order: PaneRole::ALL,
178 separators: Default::default(),
179 duration: Duration::from_millis(240),
180 }
181 }
182
183 pub fn pane(mut self, role: PaneRole, pane: AdaptivePane) -> Self {
184 self.panes[role.index()] = Some(pane);
185 self
186 }
187
188 pub fn directive(mut self, directive: PaneLayoutDirective) -> Self {
189 self.directive = Some(directive);
190 self
191 }
192
193 pub fn order(mut self, order: [PaneRole; 3]) -> Self {
195 if PaneRole::ALL.into_iter().all(|role| order.contains(&role)) {
196 self.order = order;
197 }
198 self
199 }
200
201 pub fn separator(mut self, start: PaneRole, end: PaneRole, separator: PaneSeparator) -> Self {
202 self.separators[pair_index(start, end)] = Some(separator);
203 self
204 }
205
206 pub fn transition_duration(mut self, duration: Duration) -> Self {
207 self.duration = duration;
208 self
209 }
210}
211
212struct LayoutFocus {
213 panes: [FocusHandle; 3],
214 separators: [FocusHandle; 9],
215 remembered: [Option<FocusHandle>; 3],
216 overlay: Option<PaneRole>,
217 trap: Option<WeakFocusHandle>,
218}
219
220struct FocusPlan<'a> {
221 active: Option<PaneRole>,
222 overlay: Option<PaneRole>,
223 modal: Option<&'a FocusHandle>,
224 panes: &'a [Option<AdaptivePane>; 3],
225 frames: Frames,
226 separators: &'a [bool; 9],
227}
228
229impl LayoutFocus {
230 fn new(cx: &mut App) -> Self {
231 Self {
232 panes: std::array::from_fn(|_| cx.focus_handle().tab_stop(false)),
233 separators: std::array::from_fn(|_| cx.focus_handle().tab_stop(false)),
234 remembered: Default::default(),
235 overlay: None,
236 trap: None,
237 }
238 }
239
240 fn restore(&mut self, plan: FocusPlan<'_>, window: &mut Window, cx: &mut App) {
241 let opened = self.overlay != plan.overlay;
242 self.overlay = plan.overlay;
243 let prior_trap = self.trap.take();
247 self.trap = plan.modal.map(FocusHandle::downgrade);
248 let Some(focused) = window.focused(cx) else {
249 return;
250 };
251 let old = self
252 .panes
253 .iter()
254 .position(|pane| pane.contains(&focused, window));
255 let boundary = self
256 .separators
257 .iter()
258 .position(|scope| scope.contains(&focused, window));
259 if let Some(ix) = old
260 && focused != self.panes[ix]
261 {
262 self.remembered[ix] = Some(focused.clone());
263 }
264 let released_trap = prior_trap
265 .and_then(|scope| scope.upgrade())
266 .is_some_and(|scope| focused == scope && plan.modal != Some(&scope));
267 let transfer_to_overlay = plan.overlay.filter(|_| opened || plan.modal.is_some());
268 let needs_restore = released_trap
269 || old.is_some_and(|ix| {
270 plan.frames[ix].is_none()
271 || transfer_to_overlay.is_some_and(|active| ix != active.index())
272 })
273 || boundary.is_some_and(|ix| !plan.separators[ix] || transfer_to_overlay.is_some());
274 if !needs_restore {
275 return;
276 }
277 if let Some(next) = transfer_to_overlay.or(plan.active) {
278 let ix = next.index();
279 let scope = self.panes[ix].clone();
280 let remembered = self.remembered[ix].clone();
281 let entry = plan.panes[ix]
282 .as_ref()
283 .and_then(|pane| pane.entry_focus.clone());
284 window.defer(cx, move |window, cx| {
285 if window.focused(cx).is_none_or(|current| current == focused) {
286 remembered
287 .filter(|handle| scope.contains(handle, window))
288 .or_else(|| entry.filter(|handle| scope.contains(handle, window)))
289 .unwrap_or(scope)
290 .focus(window, cx);
291 }
292 });
293 } else {
294 window.blur(cx);
295 }
296 }
297}
298
299impl RenderOnce for AdaptivePaneLayout {
300 fn render(mut self, window: &mut Window, cx: &mut App) -> impl IntoElement {
301 let viewport = size(length(self.viewport.width), length(self.viewport.height));
302 let directive = self
303 .directive
304 .take()
305 .unwrap_or_else(|| PaneLayoutDirective::for_size(viewport));
306 let adaptation = Adaptation {
307 horizontal: directive.horizontal_partitions,
308 vertical: directive.vertical_partitions,
309 strategies: std::array::from_fn(|ix| {
310 self.panes[ix]
311 .as_ref()
312 .map(|pane| pane.strategy(viewport, &directive))
313 }),
314 };
315 let input = GeometryInput {
316 viewport,
317 direction: window_material_theme(window, cx).layout.direction,
318 directive: &directive,
319 order: self.order,
320 measures: std::array::from_fn(|ix| {
321 self.panes[ix]
322 .as_ref()
323 .map_or_else(Measures::default, |pane| pane.measures)
324 }),
325 };
326 let duration = if cx.reduce_motion() {
327 Duration::ZERO
328 } else {
329 self.duration
330 };
331 let (active, placement, geometry, sample, transitioning) =
332 self.state.update(cx, |state, cx| {
333 let active = state.current_destination().role;
334 let placement = state.project(adaptation);
335 let geometry = input.layout(placement, |start, end| state.expansion(start, end));
336 let sample = state.sample(
337 placement,
338 geometry.panes,
339 cx.background_executor().now(),
340 duration,
341 cx,
342 );
343 (
344 active,
345 placement,
346 geometry,
347 sample,
348 state.is_transitioning(),
349 )
350 });
351 if sample.animate_next_frame {
352 window.request_animation_frame();
353 }
354
355 let can_show = |role: PaneRole| sample.frames[role.index()].is_some();
356 let overlay =
357 self.order.into_iter().rev().find(|role| {
358 can_show(*role) && matches!(placement[*role], PanePlacement::Levitate(_))
359 });
360 let modal = overlay.is_some_and(|role| {
361 self.panes[role.index()]
362 .as_ref()
363 .is_some_and(|pane| pane.scrim.is_some())
364 });
365 let active = if can_show(active) {
366 Some(active)
367 } else {
368 self.order.into_iter().find(|role| can_show(*role))
369 };
370 let trap = overlay.filter(|_| modal).map(|role| {
371 window
372 .use_keyed_state(
373 (
374 self.id.clone(),
375 ["primary-modal", "secondary-modal", "extra-modal"][role.index()],
376 ),
377 cx,
378 |_, cx| cx.focus_handle().tab_stop(false),
379 )
380 .read(cx)
381 .clone()
382 });
383 let mut active_separators = [false; 9];
384 for boundary in &geometry.boundaries {
385 let ix = pair_index(boundary.start, boundary.end);
386 active_separators[ix] = !transitioning
388 && !modal
389 && self.separators[ix].is_some()
390 && boundary.min < boundary.max;
391 }
392
393 let focus_state = window.use_keyed_state((self.id.clone(), "pane-focus"), cx, |_, cx| {
394 LayoutFocus::new(cx)
395 });
396 let (pane_focus, separator_focus) = focus_state.update(cx, |focus, cx| {
397 focus.restore(
398 FocusPlan {
399 active,
400 overlay,
401 modal: trap.as_ref(),
402 panes: &self.panes,
403 frames: sample.frames,
404 separators: &active_separators,
405 },
406 window,
407 cx,
408 );
409 (focus.panes.clone(), focus.separators.clone())
410 });
411
412 let mut root = div()
413 .id(self.id)
414 .test_support()
415 .relative()
416 .w(viewport.width)
417 .h(viewport.height)
418 .overflow_hidden();
419 for role in self.order {
422 if let Some(pane) = self.panes[role.index()].take_if(|_| {
423 can_show(role) && !matches!(placement[role], PanePlacement::Levitate(_))
424 }) {
425 root = root.child(render_pane(
426 pane,
427 sample.frames[role.index()].unwrap(),
428 &pane_focus[role.index()],
429 false,
430 None,
431 modal,
432 ));
433 }
434 }
435 for boundary in geometry.boundaries {
436 let ix = pair_index(boundary.start, boundary.end);
437 if active_separators[ix] {
438 let separator = self.separators[ix].take().unwrap();
439 root = root.child(render_separator(
440 separator,
441 boundary,
442 viewport,
443 &self.state,
444 &separator_focus[ix],
445 ));
446 }
447 }
448 for role in self.order {
449 if let Some(mut pane) = self.panes[role.index()].take_if(|_| can_show(role)) {
450 let backdrop = pane.scrim.take();
451 let is_modal = Some(role) == overlay && backdrop.is_some();
452 if let Some(backdrop) = backdrop {
453 root = root.child(
454 div()
455 .id((pane.id.clone(), "backdrop"))
456 .absolute()
457 .inset_0()
458 .occlude()
459 .child(backdrop),
460 );
461 }
462 root = root.child(render_pane(
463 pane,
464 sample.frames[role.index()].unwrap(),
465 &pane_focus[role.index()],
466 true,
467 trap.as_ref().filter(|_| is_modal),
468 modal && Some(role) != overlay,
469 ));
470 }
471 }
472 root
473 }
474}
475
476fn render_pane(
477 pane: AdaptivePane,
478 bounds: Bounds<Pixels>,
479 focus: &FocusHandle,
480 elevated: bool,
481 modal: Option<&FocusHandle>,
482 hidden_from_a11y: bool,
483) -> AnyElement {
484 let body = div()
485 .id("pane-content")
486 .size_full()
487 .flex()
488 .flex_col()
489 .child(pane.content);
490 let body = if let Some(trap) = modal {
491 body.focus_trap("pane-content", trap).into_any_element()
492 } else {
493 body.into_any_element()
494 };
495 div()
496 .id(pane.id)
497 .role(Role::Group)
498 .test_support()
499 .track_focus(focus)
500 .absolute()
501 .left(bounds.left())
502 .top(bounds.top())
503 .w(bounds.size.width)
504 .h(bounds.size.height)
505 .min_w_0()
506 .min_h_0()
507 .flex()
508 .flex_col()
509 .overflow_hidden()
510 .when(elevated, |node| node.occlude())
511 .when(hidden_from_a11y, |node| {
512 node.a11y_synthetic_children(|tree| tree.parent_node().set_hidden())
513 })
514 .child(body)
515 .into_any_element()
516}
517
518fn render_separator(
519 separator: PaneSeparator,
520 boundary: Boundary,
521 viewport: Size<Pixels>,
522 owner: &Entity<AdaptivePaneState>,
523 focus: &FocusHandle,
524) -> impl IntoElement {
525 let pair = pair_index(boundary.start, boundary.end);
526 let handle = VerticalDragHandle::new(("pane-separator", pair));
527 let handle = match separator.build {
528 Some(build) => build(handle),
529 None => handle,
530 };
531 let resize = owner.clone();
532 let snap = owner.clone();
533 let keyboard_state = owner.clone();
534 let keyboard_anchors = separator.anchors.clone();
535 div()
536 .id(("pane-boundary", pair))
537 .track_focus(focus)
538 .absolute()
539 .left(boundary.center - px(24.))
540 .top_0()
541 .w(px(48.))
542 .h(viewport.height)
543 .flex()
544 .items_center()
545 .justify_center()
546 .when(!keyboard_anchors.is_empty(), |container| {
547 container.on_key_down(move |event, _, cx| {
548 let sign = match event.keystroke.key.as_str() {
549 "pageup" => 1.,
550 "pagedown" => -1.,
551 _ => return,
552 };
553 let anchor = boundary
554 .anchors(&keyboard_anchors)
555 .map(|(anchor, at)| (anchor, f32::from(at - boundary.position) * sign))
556 .filter(|(_, distance)| *distance > 0.01)
557 .min_by(|(_, a), (_, b)| a.total_cmp(b));
558 if let Some((anchor, _)) = anchor {
559 keyboard_state.update(cx, |state, cx| {
560 state.set_expansion(boundary.start, boundary.end, anchor, cx)
561 });
562 }
563 cx.stop_propagation();
564 })
565 })
566 .child(
567 handle
568 .resize_context(viewport)
569 .keyboard_step(separator.keyboard_step)
570 .on_resize(
571 separator.label,
572 boundary.position,
573 boundary.min..=boundary.max,
574 move |position, _, cx| {
575 resize.update(cx, |state, cx| {
576 state.set_expansion(
577 boundary.start,
578 boundary.end,
579 PaneExpansionAnchor::FromStart(position),
580 cx,
581 )
582 });
583 },
584 )
585 .on_resize_end(move |position, _, cx| {
586 let anchor = boundary
587 .anchors(&separator.anchors)
588 .map(|(anchor, at)| (anchor, f32::from((at - position).abs())))
589 .min_by(|(_, a), (_, b)| a.total_cmp(b));
590 if let Some((anchor, _)) = anchor {
591 snap.update(cx, |state, cx| {
592 state.set_expansion(boundary.start, boundary.end, anchor, cx)
593 });
594 }
595 }),
596 )
597}