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