1use std::{ops::Index, time::Duration};
2
3use gpui::{Bounds, Context, ElementId, Pixels, point, px, size};
4use web_time::Instant;
5
6use super::{PaneExpansionAnchor, PaneOverlayAlignment};
7
8#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
10pub enum PaneRole {
11 #[default]
12 Primary,
13 Secondary,
14 Tertiary,
15}
16
17impl PaneRole {
18 pub(super) const ALL: [Self; 3] = [Self::Primary, Self::Secondary, Self::Tertiary];
19
20 pub(super) fn index(self) -> usize {
21 match self {
22 Self::Primary => 0,
23 Self::Secondary => 1,
24 Self::Tertiary => 2,
25 }
26 }
27}
28
29#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
31pub enum PaneAdaptStrategy {
32 #[default]
33 Hide,
34 Reflow(PaneRole),
35 Levitate(PaneOverlayAlignment),
36}
37
38#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
40pub enum PanePlacement {
41 #[default]
42 Hidden,
43 Expanded,
44 Reflow(PaneRole),
45 Levitate(PaneOverlayAlignment),
46}
47
48#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
50pub struct PaneLayoutValue([PanePlacement; 3]);
51
52impl PaneLayoutValue {
53 pub fn new(primary: PanePlacement, secondary: PanePlacement, tertiary: PanePlacement) -> Self {
54 Self([primary, secondary, tertiary])
55 }
56
57 pub fn placement(self, role: PaneRole) -> PanePlacement {
58 self[role]
59 }
60
61 fn set(&mut self, role: PaneRole, placement: PanePlacement) {
62 self.0[role.index()] = placement;
63 }
64}
65
66impl Index<PaneRole> for PaneLayoutValue {
67 type Output = PanePlacement;
68
69 fn index(&self, role: PaneRole) -> &Self::Output {
70 &self.0[role.index()]
71 }
72}
73
74#[derive(Clone, Debug, PartialEq, Eq)]
76pub struct PaneDestination {
77 pub role: PaneRole,
78 pub content_key: Option<ElementId>,
79}
80
81impl PaneDestination {
82 pub fn new(role: PaneRole) -> Self {
83 Self {
84 role,
85 content_key: None,
86 }
87 }
88
89 pub fn content_key(mut self, key: impl Into<ElementId>) -> Self {
90 self.content_key = Some(key.into());
91 self
92 }
93}
94
95#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
97pub enum PaneBackBehavior {
98 PopLatest,
99 #[default]
100 PopUntilScaffoldValueChange,
101 PopUntilCurrentDestinationChange,
102 PopUntilContentChange,
103}
104
105#[derive(Clone, Copy)]
106pub(super) struct Adaptation {
107 pub horizontal: usize,
108 pub vertical: usize,
109 pub strategies: [Option<PaneAdaptStrategy>; 3],
110}
111
112impl Default for Adaptation {
113 fn default() -> Self {
114 Self {
115 horizontal: 1,
116 vertical: 1,
117 strategies: [Some(PaneAdaptStrategy::Hide); 3],
118 }
119 }
120}
121
122impl Adaptation {
123 pub fn resolve(self, history: &[PaneDestination], aware: bool) -> PaneLayoutValue {
124 let mut value = PaneLayoutValue::default();
125 let horizontal = self.horizontal.clamp(1, 3);
126 let vertical = self.vertical.clamp(1, 3);
127 let active = history.last().map(|destination| destination.role);
128 let prior = history
129 .iter()
130 .rev()
131 .take(if aware { history.len() } else { 1 });
132 if let Some(role) = active
133 && let Some(PaneAdaptStrategy::Levitate(alignment)) = self.strategies[role.index()]
134 {
135 value.set(role, PanePlacement::Levitate(alignment));
136 }
137 let mut expanded = 0;
138 let mut reflowed = 0;
139 for role in prior
140 .map(|destination| destination.role)
141 .chain(PaneRole::ALL)
142 {
143 if value[role] != PanePlacement::Hidden {
144 continue;
145 }
146 match self.strategies[role.index()] {
147 Some(PaneAdaptStrategy::Reflow(anchor))
148 if horizontal == 1
149 && reflowed + 1 < vertical
150 && anchor != role
151 && self.strategies[anchor.index()].is_some_and(|strategy| {
152 !matches!(strategy, PaneAdaptStrategy::Levitate(_))
153 })
154 && (value[anchor] == PanePlacement::Expanded || expanded == 0) =>
155 {
156 value.set(anchor, PanePlacement::Expanded);
157 value.set(role, PanePlacement::Reflow(anchor));
158 expanded = 1;
159 reflowed += 1;
160 }
161 Some(PaneAdaptStrategy::Hide | PaneAdaptStrategy::Reflow(_))
162 if expanded < horizontal =>
163 {
164 value.set(role, PanePlacement::Expanded);
165 expanded += 1;
166 }
167 _ => {}
168 }
169 }
170 value
171 }
172
173 fn normalize(self, value: PaneLayoutValue) -> PaneLayoutValue {
174 let mut safe = value;
175 for role in PaneRole::ALL {
176 if self.strategies[role.index()].is_none()
177 || matches!(value[role], PanePlacement::Reflow(anchor)
178 if self.strategies[anchor.index()].is_none() || value[anchor] != PanePlacement::Expanded)
179 {
180 safe.set(role, PanePlacement::Hidden);
181 }
182 }
183 safe
184 }
185}
186
187#[derive(Clone, Copy, Debug, PartialEq)]
188enum Intent {
189 Navigate,
190 Animate(PaneLayoutValue),
191 Snap(PaneLayoutValue),
192 Seek(PaneLayoutValue, f32),
193 SeekBack(PaneBackBehavior, f32),
194}
195
196#[derive(Clone, Copy, PartialEq, Eq)]
197enum Timing {
198 Animate,
199 Snap,
200 Seek,
201}
202
203pub(super) type Frames = [Option<Bounds<Pixels>>; 3];
204
205#[derive(Clone, Copy)]
206struct Motion {
207 from: Frames,
208 started: Instant,
209 timing: Timing,
210}
211
212pub(super) struct DisplayedPanes {
213 pub frames: Frames,
214 pub animate_next_frame: bool,
215}
216
217pub struct AdaptivePaneState {
219 history: Vec<PaneDestination>,
220 history_aware: bool,
221 adaptation: Adaptation,
222 expansion: [Option<PaneExpansionAnchor>; 9],
223 current: PaneLayoutValue,
224 target: PaneLayoutValue,
225 progress: f32,
226 intent: Intent,
227 motion: Option<Motion>,
228 displayed: Frames,
229 measured: bool,
230}
231
232impl AdaptivePaneState {
233 pub fn new(initial: PaneDestination) -> Self {
234 let mut value = PaneLayoutValue::default();
235 value.set(initial.role, PanePlacement::Expanded);
236 Self {
237 history: vec![initial],
238 history_aware: true,
239 adaptation: Adaptation::default(),
240 expansion: [None; 9],
241 current: value,
242 target: value,
243 progress: 0.,
244 intent: Intent::Navigate,
245 motion: None,
246 displayed: [None; 3],
247 measured: false,
248 }
249 }
250
251 pub fn current_destination(&self) -> &PaneDestination {
252 self.history
253 .last()
254 .expect("initial destination is retained")
255 }
256
257 pub fn history(&self) -> &[PaneDestination] {
258 &self.history
259 }
260
261 pub fn set_history_aware(&mut self, aware: bool, cx: &mut Context<Self>) {
262 if self.history_aware != aware {
263 self.history_aware = aware;
264 cx.notify();
265 }
266 }
267
268 pub fn navigate_to(&mut self, destination: PaneDestination, cx: &mut Context<Self>) {
269 if self.current_destination() != &destination {
270 self.history.push(destination);
271 cx.notify();
272 }
273 self.follow_navigation(cx);
274 }
275
276 pub fn can_navigate_back(&self, behavior: PaneBackBehavior) -> bool {
277 self.back_index(behavior).is_some()
278 }
279
280 pub fn previous_value(&self, behavior: PaneBackBehavior) -> Option<PaneLayoutValue> {
281 self.back_index(behavior).map(|ix| self.history_value(ix))
282 }
283
284 pub fn navigate_back(&mut self, behavior: PaneBackBehavior, cx: &mut Context<Self>) -> bool {
285 let Some(ix) = self.back_index(behavior) else {
286 return false;
287 };
288 self.history.truncate(ix + 1);
289 self.intent = Intent::Navigate;
290 cx.notify();
291 true
292 }
293
294 pub fn seek_back(
296 &mut self,
297 behavior: PaneBackBehavior,
298 progress: f32,
299 cx: &mut Context<Self>,
300 ) -> bool {
301 if !self.can_navigate_back(behavior) {
302 return false;
303 }
304 self.request(Intent::SeekBack(behavior, fraction(progress)), cx);
305 true
306 }
307
308 pub fn current_value(&self) -> PaneLayoutValue {
309 self.current
310 }
311
312 pub fn target_value(&self) -> PaneLayoutValue {
313 self.target
314 }
315
316 pub fn progress(&self) -> f32 {
318 self.progress
319 }
320
321 pub fn snap_to(&mut self, value: PaneLayoutValue, cx: &mut Context<Self>) {
322 self.request(Intent::Snap(value), cx);
323 }
324
325 pub fn animate_to(&mut self, value: PaneLayoutValue, cx: &mut Context<Self>) {
326 self.request(Intent::Animate(value), cx);
327 }
328
329 pub fn seek_to(&mut self, value: PaneLayoutValue, progress: f32, cx: &mut Context<Self>) {
330 self.request(Intent::Seek(value, fraction(progress)), cx);
331 }
332
333 pub fn follow_navigation(&mut self, cx: &mut Context<Self>) {
334 self.request(Intent::Navigate, cx);
335 }
336
337 pub fn expansion(&self, start: PaneRole, end: PaneRole) -> Option<PaneExpansionAnchor> {
338 self.expansion[start.index() * 3 + end.index()]
339 }
340
341 pub fn set_expansion(
343 &mut self,
344 start: PaneRole,
345 end: PaneRole,
346 anchor: PaneExpansionAnchor,
347 cx: &mut Context<Self>,
348 ) {
349 if start != end && anchor.position(px(1.)).is_some() {
350 self.replace_expansion(start, end, Some(anchor), cx);
351 }
352 }
353
354 pub fn clear_expansion(&mut self, start: PaneRole, end: PaneRole, cx: &mut Context<Self>) {
355 self.replace_expansion(start, end, None, cx);
356 }
357
358 fn replace_expansion(
359 &mut self,
360 start: PaneRole,
361 end: PaneRole,
362 value: Option<PaneExpansionAnchor>,
363 cx: &mut Context<Self>,
364 ) {
365 let entry = &mut self.expansion[start.index() * 3 + end.index()];
366 if *entry != value {
367 *entry = value;
368 cx.notify();
369 }
370 }
371
372 fn request(&mut self, intent: Intent, cx: &mut Context<Self>) {
373 if self.intent != intent {
374 self.intent = intent;
375 cx.notify();
376 }
377 }
378
379 fn history_value(&self, end: usize) -> PaneLayoutValue {
380 self.adaptation
381 .resolve(&self.history[..=end], self.history_aware)
382 }
383
384 fn back_index(&self, behavior: PaneBackBehavior) -> Option<usize> {
385 let last = self.history.len() - 1;
386 let current = self.current_destination();
387 let value = self.history_value(last);
388 (0..last).rev().find(|&index| {
389 let prior = &self.history[index];
390 match behavior {
391 PaneBackBehavior::PopLatest => true,
392 PaneBackBehavior::PopUntilScaffoldValueChange => self.history_value(index) != value,
393 PaneBackBehavior::PopUntilCurrentDestinationChange => prior.role != current.role,
394 PaneBackBehavior::PopUntilContentChange => {
395 prior.content_key != current.content_key || self.history_value(index) != value
396 }
397 }
398 })
399 }
400
401 pub(super) fn project(&mut self, adaptation: Adaptation) -> PaneLayoutValue {
402 self.adaptation = adaptation;
403 match self.intent {
404 Intent::Navigate => self.history_value(self.history.len() - 1),
405 Intent::Animate(value) | Intent::Snap(value) | Intent::Seek(value, _) => {
406 adaptation.normalize(value)
407 }
408 Intent::SeekBack(behavior, _) => self
409 .previous_value(behavior)
410 .unwrap_or_else(|| self.history_value(self.history.len() - 1)),
411 }
412 }
413
414 pub(super) fn sample(
415 &mut self,
416 value: PaneLayoutValue,
417 target: Frames,
418 now: Instant,
419 duration: Duration,
420 cx: &mut Context<Self>,
421 ) -> DisplayedPanes {
422 let before = (self.current, self.target, self.progress);
423 let (timing, sought) = match self.intent {
424 Intent::Snap(_) => (Timing::Snap, 0.),
425 Intent::Seek(_, fraction) | Intent::SeekBack(_, fraction) => (Timing::Seek, fraction),
426 _ => (Timing::Animate, 0.),
427 };
428 let unsettled = timing == Timing::Seek || duration > Duration::ZERO;
429 let changed = self.target != value;
430 self.target = value;
431 if !self.measured || timing == Timing::Snap || !unsettled {
432 self.motion = None;
433 self.current = value;
434 self.progress = 0.;
435 self.displayed = target;
436 self.measured = true;
437 } else if changed || self.motion.is_some_and(|motion| motion.timing != timing) {
438 self.motion = Some(Motion {
439 from: self.displayed,
440 started: now,
441 timing,
442 });
443 }
444 let mut animate_next_frame = false;
445 if let Some(motion) = self.motion {
446 let raw = if timing == Timing::Seek {
447 sought
448 } else {
449 ((now - motion.started).as_secs_f32() / duration.as_secs_f32()).clamp(0., 1.)
450 };
451 if raw >= 1. && timing == Timing::Animate {
452 self.motion = None;
453 self.current = value;
454 self.progress = 0.;
455 self.displayed = target;
456 } else {
457 self.progress = raw;
458 let visual = if timing == Timing::Seek {
459 raw
460 } else {
461 raw * raw * (3. - 2. * raw)
462 };
463 self.displayed = std::array::from_fn(|ix| {
464 target[ix].map(|end| blend(motion.from[ix], end, visual))
465 });
466 animate_next_frame = timing == Timing::Animate;
467 }
468 } else {
469 self.displayed = target;
470 }
471 if before != (self.current, self.target, self.progress) {
472 cx.notify();
473 }
474 DisplayedPanes {
475 frames: self.displayed,
476 animate_next_frame,
477 }
478 }
479
480 pub(super) fn is_transitioning(&self) -> bool {
481 self.motion.is_some()
482 }
483}
484
485fn fraction(value: f32) -> f32 {
486 if value.is_finite() {
487 value.clamp(0., 1.)
488 } else {
489 0.
490 }
491}
492
493fn blend(from: Option<Bounds<Pixels>>, to: Bounds<Pixels>, fraction: f32) -> Bounds<Pixels> {
494 let from = from.unwrap_or_else(|| Bounds::new(to.center(), size(px(0.), px(0.))));
495 let interpolate = |a, b| a + (b - a) * fraction;
496 Bounds::new(
497 point(
498 interpolate(from.left(), to.left()),
499 interpolate(from.top(), to.top()),
500 ),
501 size(
502 interpolate(from.size.width, to.size.width),
503 interpolate(from.size.height, to.size.height),
504 ),
505 )
506}