use std::sync::Arc;
use parking_lot::Mutex;
use super::{
icons, names,
part_style::Length,
recipe::{Case, Interaction, Name, Recipe, ResolvedPart, ResolvedRecipe, Selector},
shared::{Orientation, glyph},
text_box::edge,
theme::{Themed, current_theme},
};
use crate::{
app::{
component::Component,
ctx::Ctx,
events::{DragEvent, KeyboardEvent, MouseButtonMask, MouseEvent},
theme::{PaletteColor, RadiusSize, Theme},
},
components::{Column, Row, Stack},
core::{ElementRect, ElementRefMut, Signal},
layout::{Alignment, stack_alignment::StackAlignment},
node::{
BackgroundColor, CursorIcon, Element, HitTestBehavior, color::Color, dimension::Dimension, transform::Transform2D,
},
};
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
pub enum SplitterPart {
Root,
Pane,
Handle,
Line,
Bar,
Grip,
GripIcon,
}
names!(SplitterPart {
Root => "root",
Pane => "pane",
Handle => "handle",
Line => "line",
Bar => "bar",
Grip => "grip",
GripIcon => "grip-icon",
});
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
pub enum SplitterState {
Horizontal,
Vertical,
Framed,
Disabled,
}
names!(SplitterState {
Horizontal => "horizontal",
Vertical => "vertical",
Framed => "framed",
Disabled => "disabled",
});
pub type SplitterOrientation = Orientation;
fn divider_orientation(orientation: Orientation) -> &'static str {
match orientation {
Orientation::Horizontal => "vertical",
Orientation::Vertical => "horizontal",
}
}
pub type SplitterRenderer = Arc<dyn Fn(SplitterView) -> Element + Send + Sync>;
type SizesHandler = Arc<dyn Fn(&[f32]) + Send + Sync>;
#[derive(Clone, Copy, Debug, PartialEq)]
enum PaneSize {
Px(f32),
Share(f32),
}
#[derive(Clone)]
pub struct SplitterPane {
content: Element,
size: Option<PaneSize>,
min: f32,
max: f32,
collapsible: bool,
disabled: bool,
label: Option<Arc<str>>,
id: Option<Arc<str>>,
key: Option<Arc<str>>,
}
impl SplitterPane {
pub fn new(content: impl Into<Element>) -> Self {
Self {
content: content.into(),
size: None,
min: 0.0,
max: f32::INFINITY,
collapsible: false,
disabled: false,
label: None,
id: None,
key: None,
}
}
pub fn length(mut self, px: f32) -> Self {
self.size = Some(PaneSize::Px(px.max(0.0)));
self
}
pub fn share(mut self, share: f32) -> Self {
self.size = Some(PaneSize::Share(share.clamp(0.0, 1.0)));
self
}
pub fn min(mut self, px: f32) -> Self {
self.min = px.max(0.0);
self
}
pub fn max(mut self, px: f32) -> Self {
self.max = px.max(0.0);
self
}
pub fn collapsible(mut self, collapsible: bool) -> Self {
self.collapsible = collapsible;
self
}
pub fn label(mut self, label: &str) -> Self {
self.label = Some(Arc::from(label));
self
}
pub fn disabled(mut self, disabled: bool) -> Self {
self.disabled = disabled;
self
}
pub fn id(mut self, id: impl Into<Arc<str>>) -> Self {
self.id = Some(id.into());
self
}
pub fn key(mut self, key: impl Into<Arc<str>>) -> Self {
self.key = Some(key.into());
self
}
}
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
enum Kind {
Px,
Share,
Rest,
}
#[derive(Clone, Debug, PartialEq)]
struct Spec {
kind: Kind,
begin: f32,
min: f32,
max: f32,
collapsible: bool,
disabled: bool,
label: Option<Arc<str>>,
}
fn specs(panes: &[SplitterPane]) -> Vec<Spec> {
let rest = panes
.iter()
.rposition(|pane| pane.size.is_none())
.unwrap_or(panes.len().saturating_sub(1));
let given: f32 = panes
.iter()
.filter_map(|pane| match pane.size {
Some(PaneSize::Share(share)) => Some(share),
_ => None,
})
.sum();
let unsized_panes = panes.iter().filter(|pane| pane.size.is_none()).count().max(1);
let even = (1.0 - given).max(0.0) / unsized_panes as f32;
panes
.iter()
.enumerate()
.map(|(index, pane)| {
let (kind, begin) = if index == rest {
(Kind::Rest, 0.0)
} else {
match pane.size {
Some(PaneSize::Px(px)) => (Kind::Px, px),
Some(PaneSize::Share(share)) => (Kind::Share, share),
None => (Kind::Share, even),
}
};
Spec {
kind,
begin,
min: pane.min,
max: pane.max.max(pane.min),
collapsible: pane.collapsible && kind != Kind::Rest && !pane.disabled,
disabled: pane.disabled,
label: pane.label.clone(),
}
})
.collect()
}
#[derive(Clone)]
pub struct Splitter {
orientation: SplitterOrientation,
panes: Vec<SplitterPane>,
sizes: Option<Signal<Vec<f32>>>,
on_resize: Vec<SizesHandler>,
on_resize_end: Vec<SizesHandler>,
step: f32,
large_step: f32,
grip: bool,
framed: bool,
disabled: bool,
label: Option<Arc<str>>,
states: Vec<Name>,
rules: Recipe,
forced: Option<Interaction>,
id: Option<Arc<str>>,
key: Option<Arc<str>>,
host: Option<Arc<HostLink>>,
}
impl Splitter {
pub fn new() -> Self {
Self {
orientation: Orientation::Horizontal,
panes: Vec::new(),
sizes: None,
on_resize: Vec::new(),
on_resize_end: Vec::new(),
step: 10.0,
large_step: 50.0,
grip: false,
framed: false,
disabled: false,
label: None,
states: Vec::new(),
rules: Recipe::new(),
forced: None,
id: None,
key: None,
host: None,
}
}
pub fn orientation(mut self, orientation: Orientation) -> Self {
self.orientation = orientation;
self
}
pub fn pane(mut self, pane: SplitterPane) -> Self {
self.panes.push(pane);
self
}
pub fn panes(mut self, panes: impl IntoIterator<Item = SplitterPane>) -> Self {
self.panes.extend(panes);
self
}
pub fn sizes(mut self, sizes: Signal<Vec<f32>>) -> Self {
self.sizes = Some(sizes);
self
}
pub fn on_resize(mut self, handler: impl Fn(&[f32]) + Send + Sync + 'static) -> Self {
self.on_resize.push(Arc::new(handler));
self
}
pub fn on_resize_end(mut self, handler: impl Fn(&[f32]) + Send + Sync + 'static) -> Self {
self.on_resize_end.push(Arc::new(handler));
self
}
pub fn step(mut self, px: f32) -> Self {
self.step = px.max(1.0);
self
}
pub fn large_step(mut self, px: f32) -> Self {
self.large_step = px.max(1.0);
self
}
pub fn grip(mut self, grip: bool) -> Self {
self.grip = grip;
self
}
pub fn framed(mut self, framed: bool) -> Self {
self.framed = framed;
self
}
pub fn disabled(mut self, disabled: bool) -> Self {
self.disabled = disabled;
self
}
pub fn label(mut self, label: &str) -> Self {
self.label = Some(Arc::from(label));
self
}
pub fn state(mut self, state: impl Into<Name>, on: bool) -> Self {
let state = state.into();
self.states.retain(|held| *held != state);
if on {
self.states.push(state);
}
self
}
pub fn style(mut self, part: impl Into<Name>, style: impl FnOnce(super::PartStyle) -> super::PartStyle) -> Self {
self.rules = self.rules.base(part, style);
self
}
pub fn rules(mut self, rules: &Recipe) -> Self {
self.rules = self.rules.extend(rules);
self
}
pub fn force(mut self, interaction: Option<Interaction>) -> Self {
self.forced = interaction;
self
}
pub fn id(mut self, id: impl Into<Arc<str>>) -> Self {
self.id = Some(id.into());
self
}
pub fn key(mut self, key: impl Into<Arc<str>>) -> Self {
self.key = Some(key.into());
self
}
fn view(self, theme: &Theme) -> SplitterView {
let case = Case {
variant: None,
size: None,
density: None,
breakpoint: super::current_breakpoint(),
states: self.states.clone(),
}
.state(SplitterState::Horizontal, self.orientation == Orientation::Horizontal)
.state(SplitterState::Vertical, self.orientation == Orientation::Vertical)
.state(SplitterState::Framed, self.framed)
.state(SplitterState::Disabled, self.disabled);
let specs = specs(&self.panes);
let mut ids = Vec::with_capacity(self.panes.len());
let (contents, keys) = self
.panes
.into_iter()
.map(|pane| {
ids.push(pane.id);
(pane.content, pane.key)
})
.unzip();
SplitterView {
orientation: self.orientation,
grip: self.grip,
disabled: self.disabled,
label: self.label,
recipe: theme
.resolve::<Splitter>(&case, Some(&self.rules))
.owned_by(self.id.as_ref()),
specs,
contents,
keys,
ids,
sizes: self.sizes.unwrap_or_else(|| Signal::new(Vec::new())),
on_resize: self.on_resize,
on_resize_end: self.on_resize_end,
step: self.step,
large_step: self.large_step,
forced: self.forced,
id: self.id,
key: self.key,
host: self.host,
}
}
pub fn build(self, theme: &Theme) -> Element {
let view = self.view(theme);
match theme.renderer::<Splitter>() {
Some(renderer) => renderer(view),
None => view.render(),
}
}
pub fn mount(self, ctx: &mut Ctx) -> Element {
let key = self.key.clone();
let props = SplitterProps {
splitter: Arc::new(Mutex::new(self)),
};
match key {
Some(key) => ctx.mount_keyed::<SplitterHost>(&key, props),
None => ctx.mount::<SplitterHost>(props),
}
}
}
impl Default for Splitter {
fn default() -> Self {
Self::new()
}
}
impl From<Splitter> for Element {
fn from(splitter: Splitter) -> Self {
splitter.build(¤t_theme())
}
}
struct DragStart {
sizes: Vec<f32>,
moved: bool,
}
struct Panes {
orientation: SplitterOrientation,
specs: Vec<Spec>,
thickness: f32,
sizes: Signal<Vec<f32>>,
panes: Vec<ElementRefMut>,
shadows: Vec<ElementRefMut>,
handles: Vec<ElementRefMut>,
room: ElementRefMut,
on_resize: Vec<SizesHandler>,
on_resize_end: Vec<SizesHandler>,
drag: Mutex<Option<DragStart>>,
host: Option<Arc<HostLink>>,
steps: (f32, f32),
}
impl Panes {
fn along(&self, rect: ElementRect) -> f32 {
match self.orientation {
SplitterOrientation::Horizontal => rect.width,
SplitterOrientation::Vertical => rect.height,
}
}
fn room(&self) -> f32 {
self.along(self.room.bounds())
}
fn gaps(&self) -> f32 {
self.thickness * self.specs.len().saturating_sub(1) as f32
}
fn measured(&self) -> Vec<f32> {
self.panes.iter().map(|pane| self.along(pane.bounds())).collect()
}
fn current(&self) -> Vec<f32> {
let model = self.sizes.get_untracked();
if model.len() == self.specs.len() {
self.expected(&model, self.room())
} else {
self.measured()
}
}
fn initial(&self, room: f32) -> Vec<f32> {
let mut sizes: Vec<f32> = self
.specs
.iter()
.map(|spec| match spec.kind {
Kind::Px => spec.begin,
Kind::Share => spec.begin * room,
Kind::Rest => 0.0,
})
.collect();
self.fill_rest(&mut sizes, room);
sizes
}
fn expected(&self, model: &[f32], room: f32) -> Vec<f32> {
if model.len() != self.specs.len() {
return self.initial(room);
}
let saved = model.iter().sum::<f32>() + self.gaps();
let mut sizes: Vec<f32> = self
.specs
.iter()
.zip(model)
.map(|(spec, size)| match spec.kind {
Kind::Px => *size,
Kind::Share if saved > 0.0 => size / saved * room,
_ => *size,
})
.collect();
self.fill_rest(&mut sizes, room);
sizes
}
fn fill_rest(&self, sizes: &mut [f32], room: f32) {
let Some(rest) = self.specs.iter().position(|spec| spec.kind == Kind::Rest) else {
return;
};
let others: f32 = sizes
.iter()
.enumerate()
.filter(|(index, _)| *index != rest)
.map(|(_, size)| size)
.sum();
sizes[rest] = (room - self.gaps() - others).max(0.0);
}
fn fit(&self, sizes: &mut [f32], room: f32) -> bool {
let before = sizes.to_vec();
let open = |sizes: &[f32], index: usize| !(self.specs[index].collapsible && sizes[index] <= 0.0);
for (index, spec) in self.specs.iter().enumerate() {
if spec.kind != Kind::Rest && open(sizes, index) {
sizes[index] = sizes[index].clamp(spec.min, spec.max);
}
}
self.fill_rest(sizes, room);
if let Some(rest) = self.specs.iter().position(|spec| spec.kind == Kind::Rest) {
let mut lacks = self.specs[rest].min - sizes[rest];
let mut order: Vec<usize> = (0..self.specs.len()).filter(|index| *index != rest).collect();
order.sort_by_key(|index| index.abs_diff(rest));
for index in order {
if lacks <= 0.0 {
break;
}
if !open(sizes, index) {
continue;
}
let gives = (sizes[index] - self.specs[index].min).max(0.0).min(lacks);
sizes[index] -= gives;
lacks -= gives;
}
self.fill_rest(sizes, room);
}
sizes.iter().zip(&before).any(|(now, was)| (now - was).abs() > 0.5)
}
fn dimension(&self, index: usize, size: f32, room: f32) -> Option<Dimension> {
let spec = &self.specs[index];
if spec.collapsible && size <= 0.0 {
return Some(Dimension::Px(0.0));
}
match spec.kind {
Kind::Px => Some(Dimension::Px(size)),
Kind::Share if room > 0.0 => Some(Dimension::Pct(size / room * 100.0)),
Kind::Share => Some(Dimension::Px(size)),
Kind::Rest => None,
}
}
fn put(&self, sizes: &[f32]) {
let room = self.room();
for (index, size) in sizes.iter().enumerate() {
let dimension = self.dimension(index, *size, room);
let (width, height) = match self.orientation {
SplitterOrientation::Horizontal => (dimension, None),
SplitterOrientation::Vertical => (None, dimension),
};
self.panes[index].set_size(width, height);
self.panes[index].set_inert(self.specs[index].collapsible && *size <= 0.0);
self.shadows[index].set_size(width, height);
}
self.keep(sizes.to_vec());
}
fn keep(&self, sizes: Vec<f32>) {
for (handle, size) in self.handles.iter().zip(&sizes) {
handle.describe("a11y_valuenow", format!("{}", size.round()));
}
if let Some(host) = &self.host {
*host.written.lock() = Some(sizes.clone());
}
self.sizes.set(sizes);
}
fn resize(&self, sizes: &[f32]) {
self.put(sizes);
for handler in &self.on_resize {
handler(sizes);
}
}
fn resized(&self) {
let sizes = self.sizes.get_untracked();
for handler in &self.on_resize_end {
handler(&sizes);
}
}
fn step_to(&self, sizes: Option<Vec<f32>>) {
if let Some(sizes) = sizes {
self.resize(&sizes);
self.resized();
}
}
fn moved(&self, start: &[f32], index: usize, by: f32, closes: bool) -> Option<Vec<f32>> {
let (first, second) = (&self.specs[index], &self.specs[index + 1]);
if first.disabled || second.disabled {
return None;
}
let total = start[index] + start[index + 1];
let shut = |spec: &Spec, size: f32| closes && spec.collapsible && size < spec.min / 2.0;
let mut a = start[index] + by;
a = if shut(first, a) {
0.0
} else {
a.clamp(first.min, first.max)
};
a = a.clamp(0.0, total);
let mut b = total - a;
if shut(second, b) && total <= first.max {
b = 0.0;
} else if b < second.min {
b = second.min;
} else if b > second.max {
b = second.max;
}
a = total - b;
let a_fits = (a >= first.min - 0.01 && a <= first.max + 0.01) || (first.collapsible && a <= 0.0);
let b_fits = (b >= second.min - 0.01 && b <= second.max + 0.01) || (second.collapsible && b <= 0.0);
if !a_fits || !b_fits || a < 0.0 {
return None;
}
let mut sizes = start.to_vec();
sizes[index] = a;
sizes[index + 1] = b;
Some(sizes)
}
fn toggled(&self, index: usize) -> Option<Vec<f32>> {
let start = self.current();
let pane = [index, index + 1]
.into_iter()
.find(|pane| self.specs[*pane].collapsible)?;
let other = if pane == index { index + 1 } else { index };
if self.specs[other].disabled {
return None;
}
let total = start[index] + start[index + 1];
let mut sizes = start.clone();
if start[pane] > 0.0 {
sizes[pane] = 0.0;
sizes[other] = total;
return Some(sizes);
}
let spec = &self.specs[pane];
let room = total - self.specs[other].min;
if room < spec.min {
return None;
}
let size = self.initial(self.room())[pane].clamp(spec.min, spec.max).min(room);
sizes[pane] = size;
sizes[other] = total - size;
Some(sizes)
}
fn restored(&self, index: usize) -> Option<Vec<f32>> {
let start = self.current();
let closed = |pane: usize| self.specs[pane].collapsible && start[pane] <= 0.0;
if closed(index) || closed(index + 1) {
return self.toggled(index);
}
let began = self.initial(self.room())[index];
self.moved(&start, index, began - start[index], false)
}
fn settle(&self, room: f32) {
if room <= 0.0 || self.drag.lock().is_some() {
return;
}
let model = self.sizes.get_untracked();
let before = self.host.as_ref().and_then(|host| {
host
.fitted
.lock()
.as_ref()
.filter(|fitted| same(&fitted.to, &model))
.map(|fitted| fitted.from.clone())
});
let from = before.unwrap_or_else(|| model.clone());
let mut sizes = self.expected(&from, room);
let changed = self.fit(&mut sizes, room);
if let Some(host) = &self.host {
*host.fitted.lock() = changed.then(|| Fitted {
from: from.clone(),
to: sizes.clone(),
});
}
let first = model.len() != self.specs.len();
let shown = self.expected(&model, room);
if first && same(&sizes, &shown) {
self.keep(sizes);
} else if first || !same(&sizes, &shown) {
self.put(&sizes);
}
}
fn drag_start(&self) {
*self.drag.lock() = Some(DragStart {
sizes: self.current(),
moved: false,
});
}
fn drag_move(&self, index: usize, event: &DragEvent) {
let by = match self.orientation {
SplitterOrientation::Horizontal => event.total_delta_x,
SplitterOrientation::Vertical => event.total_delta_y,
};
let sizes = {
let mut drag = self.drag.lock();
let Some(start) = drag.as_mut() else {
return;
};
if by != 0.0 {
start.moved = true;
}
self.moved(&start.sizes, index, by, true)
};
if let Some(sizes) = sizes
&& sizes != self.sizes.get_untracked()
{
self.resize(&sizes);
}
}
fn drag_end(&self) {
let moved = self.drag.lock().take().is_some_and(|start| start.moved);
if moved {
self.resized();
}
}
fn key(&self, index: usize, event: &KeyboardEvent) {
if !event.focus_within || event.ctrl || event.alt || event.meta || event.composing {
return;
}
let step = if event.shift {
self.large_step()
} else {
self.small_step()
};
let (back, forth) = match self.orientation {
SplitterOrientation::Horizontal => ("ArrowLeft", "ArrowRight"),
SplitterOrientation::Vertical => ("ArrowUp", "ArrowDown"),
};
let start = self.current();
let sizes = match event.key.as_str() {
key if key == back => self.moved(&start, index, -step, false),
key if key == forth => self.moved(&start, index, step, false),
"Home" => self.moved(&start, index, self.specs[index].min - start[index], false),
"End" => {
let most = self.specs[index].max.min(start[index] + start[index + 1]);
self.moved(&start, index, most - start[index], false)
}
"Enter" => self.toggled(index),
_ => return,
};
event.prevent_default();
self.step_to(sizes);
}
fn small_step(&self) -> f32 {
self.steps.0
}
fn large_step(&self) -> f32 {
self.steps.1
}
}
pub struct SplitterView {
pub orientation: SplitterOrientation,
pub grip: bool,
pub disabled: bool,
pub label: Option<Arc<str>>,
pub recipe: ResolvedRecipe,
specs: Vec<Spec>,
contents: Vec<Element>,
keys: Vec<Option<Arc<str>>>,
ids: Vec<Option<Arc<str>>>,
sizes: Signal<Vec<f32>>,
on_resize: Vec<SizesHandler>,
on_resize_end: Vec<SizesHandler>,
step: f32,
large_step: f32,
forced: Option<Interaction>,
id: Option<Arc<str>>,
key: Option<Arc<str>>,
host: Option<Arc<HostLink>>,
}
impl SplitterView {
pub fn part(&self, part: impl Into<Name>) -> ResolvedPart {
self.recipe.part(part).forced(self.forced)
}
pub fn theme(&self) -> &Theme {
self.recipe.theme()
}
pub fn len(&self) -> usize {
self.specs.len()
}
pub fn is_empty(&self) -> bool {
self.specs.is_empty()
}
pub fn sizes(&self) -> Vec<f32> {
self.sizes.get_untracked()
}
fn px(&self, part: SplitterPart, across: bool) -> Option<f32> {
let style = self.part(part).rest();
let length = match (self.orientation, across) {
(SplitterOrientation::Horizontal, true) | (SplitterOrientation::Vertical, false) => style.width,
_ => style.height,
};
match length?.resolve(self.theme())? {
Dimension::Px(px) => Some(px),
_ => None,
}
}
pub fn thickness(&self) -> f32 {
self.px(SplitterPart::Line, true).unwrap_or(1.0)
}
fn pane_box(&self, dimension: Option<Dimension>, element_ref: &ElementRefMut) -> Column {
let mut pane = Column::new()
.part(&self.part(SplitterPart::Pane))
.align_items(Alignment::Stretch)
.ref_element(element_ref.clone());
pane = match (dimension, self.orientation) {
(Some(dimension), SplitterOrientation::Horizontal) => pane.width(dimension),
(Some(dimension), SplitterOrientation::Vertical) => pane.height(dimension),
(None, _) => pane.flex(1.0),
};
pane
}
fn grip_part(&self) -> Element {
let icon = glyph(
&self.part(SplitterPart::GripIcon),
Name::new(icons::GRIP_VERTICAL),
false,
);
let icon: Element = match self.orientation {
SplitterOrientation::Horizontal => icon,
SplitterOrientation::Vertical => Row::new().transform(Transform2D::rotate_deg(90.0)).child(icon).into(),
};
Row::new()
.part(&self.part(SplitterPart::Grip))
.align_items(Alignment::Center)
.justify(crate::layout::layout_kind::Justify::Center)
.child(icon)
.into()
}
pub fn render(self) -> Element {
let count = self.specs.len();
let thickness = self.thickness();
let handle_across = self.px(SplitterPart::Handle, true).unwrap_or(thickness);
let model = self.sizes.get_untracked();
let panes: Vec<ElementRefMut> = (0..count).map(|_| ElementRefMut::new()).collect();
let shadows: Vec<ElementRefMut> = (0..count).map(|_| ElementRefMut::new()).collect();
let room = ElementRefMut::new();
let shared = Arc::new(Panes {
orientation: self.orientation,
specs: self.specs.clone(),
thickness,
sizes: self.sizes.clone(),
panes: panes.clone(),
shadows: shadows.clone(),
handles: (0..count.saturating_sub(1)).map(|_| ElementRefMut::new()).collect(),
room: room.clone(),
on_resize: self.on_resize.clone(),
on_resize_end: self.on_resize_end.clone(),
drag: Mutex::new(None),
host: self.host.clone(),
steps: (self.step, self.large_step),
});
{
let shared = shared.clone();
room.observe_rect_before_paint(move |rect| {
let along = shared.along(rect);
shared.settle(along);
});
}
let saved = model.iter().sum::<f32>() + thickness * count.saturating_sub(1) as f32;
let dimensions: Vec<Option<Dimension>> = self
.specs
.iter()
.enumerate()
.map(|(index, spec)| {
if model.len() == count {
shared.dimension(index, model[index], saved)
} else {
match spec.kind {
Kind::Px => Some(Dimension::Px(spec.begin)),
Kind::Share => Some(Dimension::Pct(spec.begin * 100.0)),
Kind::Rest => None,
}
}
})
.collect();
let horizontal = self.orientation == SplitterOrientation::Horizontal;
let fill = Dimension::Pct(100.0);
let mut below: Vec<Element> = Vec::with_capacity(count);
let mut above: Vec<Element> = Vec::with_capacity(count * 2);
for (index, content) in self.contents.iter().enumerate() {
panes[index].set_inert(self.specs[index].collapsible && model.len() == count && model[index] <= 0.0);
let mut pane = self
.pane_box(dimensions[index], &panes[index])
.key(format!("pane-{index}"))
.child(content.clone());
if let Some(key) = &self.keys[index] {
pane = pane.key(key.clone());
}
if let Some(id) = &self.ids[index] {
pane = pane.id(id.clone());
}
below.push(pane.into());
above.push(
self
.pane_box(dimensions[index], &shadows[index])
.key(format!("shadow-{index}"))
.pointer_events_none()
.into(),
);
if index + 1 < count {
above.push(self.divider(index, &shared, thickness, handle_across, &model));
}
}
let (below, above): (Element, Element) = if horizontal {
(
Row::new()
.size(fill, fill)
.spacing(thickness)
.align_items(Alignment::Stretch)
.ref_element(room)
.key("panes")
.with_children(below)
.into(),
Row::new()
.size(fill, fill)
.align_items(Alignment::Stretch)
.hit_test(HitTestBehavior::ContentOnly)
.key("dividers")
.with_children(above)
.into(),
)
} else {
(
Column::new()
.size(fill, fill)
.spacing(thickness)
.align_items(Alignment::Stretch)
.ref_element(room)
.key("panes")
.with_children(below)
.into(),
Column::new()
.size(fill, fill)
.align_items(Alignment::Stretch)
.hit_test(HitTestBehavior::ContentOnly)
.key("dividers")
.with_children(above)
.into(),
)
};
let mut root = Stack::new()
.part(&self.part(SplitterPart::Root))
.child(below)
.child(above);
if let Some(id) = &self.id {
root = root.id(id.clone());
}
if let Some(key) = &self.key {
root = root.key(key.clone());
}
root.into()
}
fn divider(&self, index: usize, shared: &Arc<Panes>, thickness: f32, handle_across: f32, model: &[f32]) -> Element {
let horizontal = self.orientation == SplitterOrientation::Horizontal;
let back = -(handle_across - thickness) / 2.0;
let mut handle = Stack::new()
.stack_align(StackAlignment::Center)
.part(&self.part(SplitterPart::Handle))
.key(format!("divider-{index}"))
.ref_element(shared.handles[index].clone())
.child(Row::new().part(&self.part(SplitterPart::Line)))
.child(Row::new().part(&self.part(SplitterPart::Bar)))
.describe("a11y_role", "separator")
.describe("a11y_orientation", divider_orientation(self.orientation));
if horizontal {
handle = handle.offset(back, 0.0);
} else {
handle = handle.offset(0.0, back);
}
if self.grip {
handle = handle.child(self.grip_part());
}
let spec = &self.specs[index];
if let Some(label) = spec.label.clone().or_else(|| self.label.clone()) {
handle = handle.describe("a11y_name", label);
}
if let Some(size) = model.get(index) {
handle = handle.describe("a11y_valuenow", format!("{}", size.round()));
}
handle = handle.describe("a11y_valuemin", format!("{}", spec.min.round()));
if spec.max.is_finite() {
handle = handle.describe("a11y_valuemax", format!("{}", spec.max.round()));
}
if let Some(id) = &self.id {
handle = handle.id(format!("{id}-divider-{index}"));
}
if self.disabled {
handle = handle.disabled(true);
} else {
handle = handle
.tab_index(0)
.start_drag_buttons(MouseButtonMask::LEFT)
.on_drag_start({
let shared = shared.clone();
move |_: DragEvent| shared.drag_start()
})
.on_drag_move({
let shared = shared.clone();
move |event: DragEvent| shared.drag_move(index, &event)
})
.on_drag_end({
let shared = shared.clone();
move |_: DragEvent| shared.drag_end()
})
.on_dblclick({
let shared = shared.clone();
move |_: MouseEvent| shared.step_to(shared.restored(index))
})
.on_double_tap({
let shared = shared.clone();
move |event: crate::app::events::TapEvent| {
if event.fingers == 1 {
shared.step_to(shared.restored(index));
}
}
})
.on_key_down({
let shared = shared.clone();
move |event: KeyboardEvent| shared.key(index, &event)
});
}
if horizontal {
Row::new()
.width(thickness)
.hit_test(HitTestBehavior::ContentOnly)
.overflow_visible()
.child(handle)
.into()
} else {
Column::new()
.height(thickness)
.hit_test(HitTestBehavior::ContentOnly)
.overflow_visible()
.child(handle)
.into()
}
}
}
impl crate::ui::Styled for Splitter {
type Component = Self;
fn rules(self, rules: &crate::ui::Recipe) -> Self {
Self::rules(self, rules)
}
fn state(self, state: impl Into<crate::ui::Name>, on: bool) -> Self {
Self::state(self, state, on)
}
}
impl Themed for Splitter {
const NAME: &'static str = "splitter";
type Renderer = SplitterRenderer;
fn parts() -> crate::ui::Declared {
SplitterPart::declared()
}
fn states() -> crate::ui::Declared {
SplitterState::declared()
}
fn recipe() -> Recipe {
use PaletteColor::*;
use SplitterPart::{Bar, Grip, GripIcon, Handle, Line, Root};
let clear = Color::new(0, 0, 0, 0);
let disabled = || Selector::new().state(SplitterState::Disabled);
Recipe::new()
.base(Root, |s| s.width(Length::Fill).height(Length::Fill))
.base(Handle, |s| {
s.width(12.0)
.height(Length::Fill)
.foreground(clear)
.cursor(CursorIcon::ColResize)
})
.base(Line, |s| {
s.width(1.0).height(Length::Fill).background(PaletteColor::Border)
})
.base(Bar, |s| {
s.width(3.0)
.height(Length::Fill)
.background(BackgroundColor::CurrentForeground)
})
.base(Grip, |s| {
s.width(12.0)
.height(20.0)
.radius(RadiusSize::Sm)
.background(PaletteColor::Border)
})
.base(GripIcon, |s| s.width(10.0).foreground(Foreground))
.hovered(Handle, |s| s.foreground(Ring))
.pressed(Handle, |s| s.foreground(Primary))
.focus_visible(Handle, |s| s.foreground(Ring))
.state(SplitterState::Vertical, Handle, |s| {
s.width(Length::Fill).height(12.0).cursor(CursorIcon::RowResize)
})
.state(SplitterState::Vertical, Line, |s| s.width(Length::Fill).height(1.0))
.state(SplitterState::Vertical, Bar, |s| s.width(Length::Fill).height(3.0))
.state(SplitterState::Vertical, Grip, |s| s.width(20.0).height(12.0))
.state(SplitterState::Framed, Root, |s| {
s.background(Background)
.border(edge(PaletteColor::Border))
.radius(RadiusSize::Lg)
})
.state(SplitterState::Disabled, Handle, |s| s.cursor(CursorIcon::Default))
.when(disabled().hovered(), Handle, |s| s.foreground(clear))
.when(disabled().pressed(), Handle, |s| s.foreground(clear))
}
}
fn same(a: &[f32], b: &[f32]) -> bool {
a.len() == b.len() && a.iter().zip(b).all(|(a, b)| (a - b).abs() <= 0.5)
}
struct Fitted {
from: Vec<f32>,
to: Vec<f32>,
}
struct HostLink {
written: Mutex<Option<Vec<f32>>>,
fitted: Mutex<Option<Fitted>>,
revision: Signal<u64>,
}
impl HostLink {
fn settled(&self) {
self.revision.update(|revision| *revision += 1);
}
}
#[derive(Clone)]
struct SplitterProps {
splitter: Arc<Mutex<Splitter>>,
}
impl PartialEq for SplitterProps {
fn eq(&self, _: &Self) -> bool {
false
}
}
impl crate::app::component::DevtoolsInspectable for SplitterProps {}
struct SplitterHost {
own: Signal<Vec<f32>>,
link: Arc<HostLink>,
watched: Mutex<Option<usize>>,
}
impl SplitterHost {
fn watch(&self, ctx: &mut Ctx, sizes: &Signal<Vec<f32>>) {
let mut watched = self.watched.lock();
if *watched == Some(sizes.id()) {
return;
}
*watched = Some(sizes.id());
let link = self.link.clone();
ctx.watch(sizes, move |value: &Vec<f32>| {
let ours = link.written.lock().as_ref() == Some(value);
if !ours {
link.settled();
}
});
}
}
impl Component for SplitterHost {
type Props = SplitterProps;
fn create(ctx: &mut Ctx) -> Self {
Self {
own: Signal::new(Vec::new()),
link: Arc::new(HostLink {
written: Mutex::new(None),
fitted: Mutex::new(None),
revision: ctx.signal(0_u64),
}),
watched: Mutex::new(None),
}
}
fn render(&self, ctx: &mut Ctx) -> impl Into<Element> {
let mut splitter = ctx.props::<SplitterProps>().splitter.lock().clone();
let sizes = splitter.sizes.clone().unwrap_or_else(|| self.own.clone());
self.watch(ctx, &sizes);
splitter.sizes = Some(sizes);
splitter.host = Some(self.link.clone());
splitter.build(¤t_theme())
}
}