egui_pop_model/sections.rs
1//! The arithmetic of a stack of collapsible sections: how heights share
2//! a panel, and what a drag on a boundary between two sections does.
3//!
4//! <div class="warning">Experimental: may change in any release
5//! (docs/stability.md).</div>
6//!
7//! **Deprecated:** it moved to egui_stack (`egui_stack::sections::plan`,
8//! re-exported as `egui_pop_core::sections::plan`), with the section
9//! widget; this copy is kept, unchanged and unused, for one release. It is
10//! not a re-export, as this crate stays free of egui (ADR 0001) and
11//! egui_stack depends on it. Its tests are egui_stack's. Its types are not egui_stack's: a
12//! [`DragMode`] read from `egui_pop_core::sections::laid_out` is
13//! `egui_pop_core::sections::DragMode`.
14//! Heights are in points, a section's body alone (its title band is the
15//! caller's); folded sections take no height and are skipped.
16//!
17//! - [`fit`]: the heights a stack shows in the room it has. A height set
18//! by hand is kept while it fits; the sections never set by hand share
19//! the rest equally, and the last open section takes what is left, less
20//! any empty room kept under it.
21//! - [`plan_drag`]: what moving a boundary does, from the heights shown.
22//! Nothing gives way in proportion: sections give in turn, the nearest
23//! first, each down to its least height, as a code editor's split view
24//! does. [`DragMode::Pull`] moves the sections below as a block instead,
25//! opening empty room under the last.
26//! - [`resized_above`]: the section a boundary resizes: under a folded
27//! section, the first open one above it.
28//! - [`pin_plan`]: the heights to keep by hand so that [`fit`] shows a
29//! plan, the sections it did not touch staying sized by the list.
30//! - [`keep_title`]: what folding or opening a section keeps so that its
31//! title stays where it is ([`held_above`]: the sections that must not
32//! move).
33//! - [`rows_least`]: the least height of a section of rows.
34//!
35//! ```
36//! # #![allow(deprecated, reason = "the example uses a deprecated item")]
37//! use egui_pop_model::sections::{DragMode, Placed, plan_drag};
38//!
39//! let section = |height| Placed { open: true, least: 50.0, height };
40//! let stack = [section(100.0), section(100.0), section(100.0)];
41//! // Down, the section just below gives first, down to its least height;
42//! // the last gives only then.
43//! let plan = plan_drag(&stack, 0, 70.0, 0.0, DragMode::Push);
44//! assert_eq!(plan.heights, [170.0, 50.0, 80.0]);
45//! assert_eq!(plan.moved, 70.0);
46//! ```
47
48use serde::Serialize;
49
50/// A difference between two heights too small to see.
51const SAME: f32 = 0.01;
52
53/// A section as laid out: what a drag starts from.
54#[derive(Clone, Copy, Debug, PartialEq)]
55pub struct Placed {
56 /// Whether it is open; a folded section is skipped.
57 pub open: bool,
58 /// The height it never goes under.
59 pub least: f32,
60 /// The height it has.
61 pub height: f32,
62}
63
64/// How a drag moves the sections around a boundary.
65#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Serialize)]
66#[serde(rename_all = "kebab-case")]
67#[non_exhaustive]
68pub enum DragMode {
69 /// Down, the sections below give way, the nearest first, then the
70 /// last is pushed into the empty room under it, then it gives way.
71 /// Up, the section above gives way, then those above it, the nearest
72 /// first, and the first open section below takes all the room.
73 #[default]
74 Push,
75 /// The sections below follow as a block, keeping their heights: only
76 /// the section above changes. Up, it gives way, then those above it,
77 /// the nearest first, and empty room opens under the last. Down, the
78 /// block goes into the empty room, then the last section alone gives
79 /// way, and the drag stops.
80 Pull,
81}
82
83/// What a drag does ([`plan_drag`]).
84#[derive(Clone, Debug, PartialEq)]
85pub struct DragPlan {
86 /// Every section's height after it, in the order given.
87 pub heights: Vec<f32>,
88 /// How far the boundary moved: down if positive. Less than asked
89 /// when the stack stopped it; 0 when nothing could move.
90 pub moved: f32,
91 /// The empty room left under the last section.
92 pub empty: f32,
93}
94
95/// The section a boundary resizes, the one on the line under the section
96/// `line`: `line` itself when open, else the first open one above it, past
97/// any folded ones (they have no height to change); `None` when nothing
98/// above is open, and the boundary cannot move. `open`: whether each
99/// section is, top first.
100///
101/// Folded bands between do not change the distance: they follow the
102/// section, so the line stays under the pointer in both directions.
103pub fn resized_above(open: &[bool], line: usize) -> Option<usize> {
104 (0..=line).rev().find(|&i| open.get(i) == Some(&true))
105}
106
107/// What moving the boundary under the section `above` by `delta` does
108/// (down if positive), from the heights in `placed`; `empty` is the room
109/// under the last section.
110///
111/// A drag plans each move from the heights shown, by the distance between
112/// the boundary and the pointer, so that it stays under the pointer: what a
113/// drag shrank stays shrunk, and a move back gives the room where a fresh
114/// drag would. Plans compose: a move of `a` then of `b` the same way is a
115/// move of `a + b`. When `above` is not an open section or no section
116/// lies below it, no boundary is there: nothing moves and the
117/// plan says so (`moved` is 0). With only folded sections below it, nothing
118/// else can give or take: down, it takes the empty room, and up, it opens
119/// some, the folded bands following.
120pub fn plan_drag(
121 placed: &[Placed],
122 above: usize,
123 delta: f32,
124 empty: f32,
125 mode: DragMode,
126) -> DragPlan {
127 let mut plan = DragPlan {
128 heights: placed.iter().map(|p| p.height).collect(),
129 moved: 0.0,
130 empty: empty.max(0.0),
131 };
132 let above_open = placed.get(above).is_some_and(|p| p.open);
133 if !above_open || above + 1 >= placed.len() || !delta.is_finite() {
134 return plan;
135 }
136 let below: Vec<usize> = (above + 1..placed.len())
137 .filter(|&i| placed[i].open)
138 .collect();
139 match mode {
140 DragMode::Push if delta > 0.0 => push_down(placed, above, &below, delta, &mut plan),
141 DragMode::Push if delta < 0.0 => push_up(placed, above, &below, -delta, &mut plan),
142 DragMode::Pull if delta > 0.0 => pull_down(placed, above, &below, delta, &mut plan),
143 DragMode::Pull if delta < 0.0 => pull_up(placed, above, -delta, &mut plan),
144 DragMode::Push | DragMode::Pull => {}
145 }
146 plan
147}
148
149/// Takes up to `owed` from a section, down to its least height; says how
150/// much it gave.
151fn give(height: &mut f32, least: f32, owed: f32) -> f32 {
152 let given = (*height - least).max(0.0).min(owed);
153 *height -= given;
154 given
155}
156
157fn push_down(placed: &[Placed], above: usize, below: &[usize], asked: f32, plan: &mut DragPlan) {
158 let mut owed = asked;
159 let (last, between) = match below.split_last() {
160 Some((&last, between)) => (Some(last), between),
161 None => (None, below),
162 };
163 for &i in between {
164 owed -= give(&mut plan.heights[i], placed[i].least, owed);
165 }
166 let into_empty = owed.min(plan.empty);
167 plan.empty -= into_empty;
168 owed -= into_empty;
169 if let Some(last) = last {
170 owed -= give(&mut plan.heights[last], placed[last].least, owed);
171 }
172 plan.moved = asked - owed;
173 plan.heights[above] += plan.moved;
174}
175
176fn push_up(placed: &[Placed], above: usize, below: &[usize], asked: f32, plan: &mut DragPlan) {
177 let given = give_above(placed, above, asked, plan);
178 plan.moved = -given;
179 match below.first() {
180 Some(&next) => plan.heights[next] += given,
181 None => plan.empty += given,
182 }
183}
184
185fn pull_down(placed: &[Placed], above: usize, below: &[usize], asked: f32, plan: &mut DragPlan) {
186 let into_empty = asked.min(plan.empty);
187 plan.empty -= into_empty;
188 let mut owed = asked - into_empty;
189 if let Some(&last) = below.last() {
190 owed -= give(&mut plan.heights[last], placed[last].least, owed);
191 }
192 plan.moved = asked - owed;
193 plan.heights[above] += plan.moved;
194}
195
196fn pull_up(placed: &[Placed], above: usize, asked: f32, plan: &mut DragPlan) {
197 let given = give_above(placed, above, asked, plan);
198 plan.moved = -given;
199 plan.empty += given;
200}
201
202/// Takes up to `asked` from the section `above`, then those above it, the
203/// nearest first; says how much they gave.
204fn give_above(placed: &[Placed], above: usize, asked: f32, plan: &mut DragPlan) -> f32 {
205 let mut owed = asked;
206 for i in (0..=above).rev().filter(|&i| placed[i].open) {
207 owed -= give(&mut plan.heights[i], placed[i].least, owed);
208 }
209 asked - owed
210}
211
212/// The open sections above `section`, with their shown heights: what must
213/// not move for its title to stay where it is.
214pub fn held_above(placed: &[Placed], section: usize) -> Vec<(usize, f32)> {
215 if section >= placed.len() {
216 return Vec::new();
217 }
218 placed[..section]
219 .iter()
220 .enumerate()
221 .filter(|(_, p)| p.open)
222 .map(|(i, p)| (i, p.height))
223 .collect()
224}
225
226/// What to keep so that folding or opening a section leaves its title where
227/// it is ([`keep_title`]).
228#[derive(Clone, Debug, PartialEq)]
229pub struct Kept {
230 /// Every section's height to keep by hand, in the order given.
231 pub hands: Vec<Option<f32>>,
232 /// The empty room to keep under the last section.
233 pub empty: f32,
234}
235
236/// What folding or opening the section `section` keeps, from the `heights`
237/// shown and the `empty` room under them, so that its title does not move.
238///
239/// The open sections above keep their shown height, as if set by hand. Those
240/// below move: folding, they take the room it frees; opening, they give it
241/// its room, and the empty room gives only when they are at their least
242/// ([`fit`]). With no open section below, the room stays empty when folding;
243/// opening takes it back, up to the section's own height when it has one.
244pub fn keep_title(asked: &[Asked], heights: &[f32], empty: f32, section: usize) -> Kept {
245 let placed: Vec<Placed> = asked
246 .iter()
247 .zip(heights)
248 .map(|(a, &height)| Placed {
249 open: a.open,
250 least: a.least,
251 height,
252 })
253 .collect();
254 let mut hands: Vec<Option<f32>> = asked.iter().map(|a| a.hand).collect();
255 for (i, height) in held_above(&placed, section) {
256 hands[i] = Some(height);
257 }
258 let empty = match placed.get(section) {
259 Some(_) if asked[section + 1..].iter().any(|a| a.open) => empty,
260 Some(this) if this.open => empty + this.height,
261 Some(this) => match asked[section].hand {
262 Some(own) => (empty - own.max(this.least)).max(0.0),
263 None => 0.0,
264 },
265 None => empty,
266 };
267 Kept { hands, empty }
268}
269
270/// The least height of a section of `count` rows, each `row` tall: two
271/// rows, or all of them when it has fewer.
272pub fn rows_least(row: f32, count: usize) -> f32 {
273 count.min(2) as f32 * row
274}
275
276/// A section as a stack asks for it: what [`fit`] lays out.
277#[derive(Clone, Copy, Debug, PartialEq)]
278pub struct Asked {
279 /// Whether it is open; a folded section takes no height.
280 pub open: bool,
281 /// The height it never goes under.
282 pub least: f32,
283 /// The height set by hand, if any. The last open section ignores
284 /// its own: it takes what the others leave.
285 pub hand: Option<f32>,
286}
287
288/// The heights a stack shows ([`fit`]).
289#[derive(Clone, Debug, PartialEq)]
290pub struct Fit {
291 /// Every section's height, in the order given (0 when folded).
292 pub heights: Vec<f32>,
293 /// Whether each section's height is its own, set by hand.
294 pub by_hand: Vec<bool>,
295 /// What the least heights lack to fit in the room: the stack scrolls
296 /// by this much. 0 when they fit.
297 pub overflow: f32,
298 /// The empty room shown under the last section: the room left when no
299 /// section is open.
300 pub empty: f32,
301}
302
303/// Lays sections out in `room` points, keeping `empty` points of it under
304/// the last section.
305///
306/// Heights set by hand are kept and the others (the last open section
307/// among them) share the rest equally, each at least its least height.
308/// In a panel too short for that, the sections sized by the list are
309/// already at their least, so those set by hand give way, from the
310/// bottom up. When even the least heights do not fit, each has its least
311/// and [`Fit::overflow`] says by how much the stack is too tall. The empty
312/// room gives way after the sections sized by the list and before those set
313/// by hand; it comes back with the room, as they do.
314pub fn fit(asked: &[Asked], room: f32, empty: f32) -> Fit {
315 let room = if room.is_finite() { room.max(0.0) } else { 0.0 };
316 let empty = if empty.is_finite() {
317 empty.max(0.0)
318 } else {
319 0.0
320 };
321 let open: Vec<usize> = (0..asked.len()).filter(|&i| asked[i].open).collect();
322 let last = open.last().copied();
323 let mut heights = vec![0.0; asked.len()];
324 let mut by_hand = vec![false; asked.len()];
325 let (mut own, mut listed) = (Vec::new(), Vec::new());
326 for &i in &open {
327 match asked[i].hand {
328 Some(height) if Some(i) != last => {
329 heights[i] = height.max(asked[i].least);
330 by_hand[i] = true;
331 own.push(i);
332 }
333 _ => listed.push(i),
334 }
335 }
336
337 if open.is_empty() {
338 return Fit {
339 heights,
340 by_hand,
341 overflow: 0.0,
342 empty: room,
343 };
344 }
345
346 // What the sections need comes before the empty room.
347 let needed: f32 = own.iter().map(|&i| heights[i]).sum::<f32>()
348 + listed.iter().map(|&i| asked[i].least).sum::<f32>();
349 let empty = empty.min((room - needed).max(0.0));
350 let room = room - empty;
351
352 let least: f32 = open.iter().map(|&i| asked[i].least).sum();
353 if least >= room {
354 for &i in &open {
355 heights[i] = asked[i].least;
356 }
357 return Fit {
358 heights,
359 by_hand,
360 overflow: least - room,
361 empty,
362 };
363 }
364
365 // What the list needs at least comes first: those set by hand give
366 // way to it, from the bottom up.
367 let listed_least: f32 = listed.iter().map(|&i| asked[i].least).sum();
368 let kept: f32 = own.iter().map(|&i| heights[i]).sum();
369 let mut owed = kept + listed_least - room;
370 for &i in own.iter().rev() {
371 if owed <= 0.0 {
372 break;
373 }
374 owed -= give(&mut heights[i], asked[i].least, owed);
375 }
376 let kept: f32 = own.iter().map(|&i| heights[i]).sum();
377 share_out(asked, &listed, room - kept, &mut heights);
378 Fit {
379 heights,
380 by_hand,
381 overflow: 0.0,
382 empty,
383 }
384}
385
386/// Divides `room` equally between sections, each at least its least
387/// height (`room` holds them all).
388fn share_out(asked: &[Asked], sections: &[usize], room: f32, heights: &mut [f32]) {
389 let mut left = sections.to_vec();
390 let mut room = room;
391 loop {
392 let each = room / left.len().max(1) as f32;
393 let (pinned, free): (Vec<usize>, Vec<usize>) =
394 left.iter().partition(|&&i| asked[i].least > each);
395 if pinned.is_empty() {
396 for i in free {
397 heights[i] = each;
398 }
399 return;
400 }
401 for i in pinned {
402 heights[i] = asked[i].least;
403 room -= asked[i].least;
404 }
405 left = free;
406 }
407}
408
409/// The heights to keep by hand, section by section, so that [`fit`]
410/// shows `plan` in `room`, with `empty` kept under the last section.
411///
412/// A section set by hand takes its height from the plan, which aligns it
413/// on what is shown. One sized by the list stays so as long as [`fit`]
414/// gives it the plan's height: a section the drag did not touch gets a
415/// height of its own only if the list would otherwise move it. The last
416/// open section and folded ones keep what they had.
417pub fn pin_plan(asked: &[Asked], room: f32, empty: f32, plan: &[f32]) -> Vec<Option<f32>> {
418 let mut asked = asked.to_vec();
419 let last = (0..asked.len()).rev().find(|&i| asked[i].open);
420 let pinnable: Vec<usize> = (0..asked.len().min(plan.len()))
421 .filter(|&i| asked[i].open && Some(i) != last)
422 .collect();
423 for &i in &pinnable {
424 if asked[i].hand.is_some() {
425 asked[i].hand = Some(plan[i]);
426 }
427 }
428 loop {
429 let shown = fit(&asked, room, empty).heights;
430 let mut changed = false;
431 for &i in &pinnable {
432 if asked[i].hand.is_none() && (shown[i] - plan[i]).abs() > SAME {
433 asked[i].hand = Some(plan[i]);
434 changed = true;
435 }
436 }
437 if !changed {
438 return asked.iter().map(|a| a.hand).collect();
439 }
440 }
441}