use std::collections::HashSet;
use std::panic::Location;
use super::list::{row_inline, row_span};
use super::text_input::DOUBLE_CLICK_TIME;
use super::{Ui, WidgetKind, WidgetState, typed};
use crate::style::{Declaration, PseudoClasses, Sides};
use crate::tree::{
Behavior, DRAG_THRESHOLD, KeySource, Length, LengthAuto, NodeKey, Overflow, Response, Role,
hash_of,
};
pub const OUTLINER_INDENT: f32 = 12.0;
pub const OUTLINER_ROW_HEIGHT: f32 = 16.0;
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash, PartialOrd, Ord)]
pub struct OutlinerId(pub u64);
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
pub struct OutlinerRow {
pub id: OutlinerId,
pub parent: Option<OutlinerId>,
pub depth: u16,
pub branch: bool,
pub open: bool,
}
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash)]
pub enum SelectMode {
#[default]
Replace,
Toggle,
Range,
}
#[derive(Clone, Copy, Debug, PartialEq)]
pub struct OutlinerOptions {
pub row_height: f32,
pub indent: f32,
pub select: SelectMode,
}
impl Default for OutlinerOptions {
fn default() -> Self {
Self {
row_height: OUTLINER_ROW_HEIGHT,
indent: OUTLINER_INDENT,
select: SelectMode::Replace,
}
}
}
mod state;
pub use state::OutlinerState;
#[derive(Debug)]
pub struct OutlinerBuilder<'a> {
rows: &'a mut Vec<OutlinerRow>,
expanded: &'a HashSet<OutlinerId>,
depth: u16,
parent: Option<OutlinerId>,
}
impl OutlinerBuilder<'_> {
pub fn branch(&mut self, id: OutlinerId, children: impl FnOnce(&mut Self)) -> bool {
let open = self.expanded.contains(&id);
self.rows.push(OutlinerRow {
id,
parent: self.parent,
depth: self.depth,
branch: true,
open,
});
if open {
let (depth, parent) = (self.depth, self.parent);
self.depth = depth.saturating_add(1);
self.parent = Some(id);
children(self);
self.depth = depth;
self.parent = parent;
}
open
}
pub fn leaf(&mut self, id: OutlinerId) {
self.rows.push(OutlinerRow {
id,
parent: self.parent,
depth: self.depth,
branch: false,
open: false,
});
}
#[must_use]
pub const fn depth(&self) -> u16 {
self.depth
}
}
impl Ui {
#[track_caller]
pub fn outliner(
&mut self,
selector: &str,
state: &mut OutlinerState,
tree: impl FnOnce(&mut OutlinerBuilder<'_>),
row: impl FnMut(&mut Self, &OutlinerRow),
) -> Response {
self.outliner_with(selector, state, &OutlinerOptions::default(), tree, row)
}
#[track_caller]
pub fn outliner_with(
&mut self,
selector: &str,
state: &mut OutlinerState,
options: &OutlinerOptions,
tree: impl FnOnce(&mut OutlinerBuilder<'_>),
mut row: impl FnMut(&mut Self, &OutlinerRow),
) -> Response {
let selector = typed("outliner", selector);
let parsed = self.node_selector(&selector);
let key = self.widget_key(parsed, Location::caller());
let expansion = self.apply_expansion(key, state);
if state.is_stale() {
state.flatten(tree);
}
let mut changed = false;
for (id, was_open) in expansion.into_iter().rev() {
if state.rows().iter().any(|row| row.id == id && row.branch) {
changed = true;
} else {
state.set_expanded(id, was_open);
}
}
if options.select == SelectMode::Range
&& !self.building_disabled()
&& let Some((from, to)) = self.vertical_focus_move
&& self.inside(from, Some(key))
&& self.inside(to, Some(key))
&& let (
WidgetState::TreeItem {
item: Some(from), ..
},
WidgetState::TreeItem { item: Some(to), .. },
) = (self.widget_state(from), self.widget_state(to))
&& state.rows().iter().any(|row| row.id == from)
&& state.rows().iter().any(|row| row.id == to)
{
if state.anchor().is_none() {
changed |= state.select(from, SelectMode::Replace);
}
changed |= state.select(to, SelectMode::Range);
}
let height = row_span(options.row_height);
let mut focused = None;
let mut response = self.open_block(
key,
parsed,
&[Declaration::Overflow(Overflow::Scroll)],
Behavior::NONE,
PseudoClasses::NONE,
|ui| {
let (built, moved) = ui.outliner_rows(key, state, options, height, &mut row);
focused = built;
changed |= moved;
},
);
self.set_widget_state(key, WidgetState::Rows(focused));
self.mark(key, WidgetKind::Outliner);
response.changed = changed;
response
}
fn apply_expansion(
&mut self,
key: NodeKey,
state: &mut OutlinerState,
) -> Vec<(OutlinerId, bool)> {
if self.building_disabled() {
return Vec::new();
}
let mut changed = Vec::new();
if let Some(toggled) = self.tree_toggled
&& self.inside(toggled, Some(key))
&& let WidgetState::TreeItem {
open,
item: Some(id),
..
} = self.widget_state(toggled)
{
let was_open = state.is_expanded(id);
if state.set_expanded(id, open) {
changed.push((id, was_open));
}
}
if let Some(clicked) = self.clicked_key()
&& self.inside(clicked, Some(key))
&& let WidgetState::OutlinerToggle(id) = self.widget_state(clicked)
{
let was_open = state.is_expanded(id);
state.toggle_expanded(id);
changed.push((id, was_open));
}
changed
}
fn outliner_rows(
&mut self,
key: NodeKey,
state: &mut OutlinerState,
options: &OutlinerOptions,
height: f32,
row: &mut impl FnMut(&mut Self, &OutlinerRow),
) -> (Option<usize>, bool) {
let rows = state.rows().len();
let window = self.row_window(rows, height);
let content = [
Declaration::Height(LengthAuto::Px(rows as f32 * height)),
Declaration::FlexShrink(0.0),
];
let disabled = self.building_disabled();
let (mut focused, mut changed) = (None, false);
state.double_clicked = None;
self.block(".outliner-content", &content, |ui| {
let model: &[OutlinerRow] = state.rows();
let outside = ui
.kept_row(key, rows, |ui, index| {
ui.key(KeySource::Keyed(hash_of(model[index].id)))
})
.filter(|&index| index < window.first || index >= window.end);
let indices = outside
.filter(|&index| index < window.first)
.into_iter()
.chain(window.first..window.end)
.chain(outside.filter(|&index| index >= window.end));
for index in indices {
let item = state.rows()[index];
let (row_key, clicked) = ui.outliner_row(index, item, state, options, height, row);
if clicked && !disabled {
changed |= state.select(item.id, options.select);
ui.note_click(state, item.id);
}
if ui.focused() == Some(row_key) {
focused = Some(index);
}
}
});
(focused, changed)
}
fn note_click(&self, state: &mut OutlinerState, id: OutlinerId) {
let (now, at) = (self.text_clock, self.pointer.pos);
let second = state.last_click.is_some_and(|(row, when, from)| {
row == id
&& now.saturating_sub(when) <= DOUBLE_CLICK_TIME
&& (at - from).length_squared() <= DRAG_THRESHOLD * DRAG_THRESHOLD
});
if second {
state.double_clicked = Some(id);
state.last_click = None;
} else {
state.last_click = Some((id, now, at));
}
}
fn outliner_row(
&mut self,
index: usize,
item: OutlinerRow,
state: &OutlinerState,
options: &OutlinerOptions,
height: f32,
row: &mut impl FnMut(&mut Self, &OutlinerRow),
) -> (NodeKey, bool) {
let step = if options.indent.is_finite() {
options.indent.max(0.0)
} else {
0.0
};
let [position, top, left, right, height] = row_inline(index, height);
let inline = [
position,
top,
left,
right,
height,
Declaration::Padding(Sides::Left, Length::Px(f32::from(item.depth) * step)),
];
let open = if item.open {
PseudoClasses::OPEN
} else {
PseudoClasses::NONE
};
let selected = if state.is_selected(item.id) {
PseudoClasses::CHECKED
} else {
PseudoClasses::NONE
};
let keyed = |ui: &Self, id: OutlinerId| ui.key(KeySource::Keyed(hash_of(id)));
let parent = item.parent.map(|id| keyed(self, id));
let first_child = state
.rows()
.get(index + 1)
.filter(|next| next.parent == Some(item.id))
.map(|next| keyed(self, next.id));
let parsed = self.node_selector(".outliner-row");
let key = keyed(self, item.id);
let key = self.unique(key);
let response = self.open_block(
key,
parsed,
&inline,
Behavior::BUTTON,
open | selected,
|ui| {
ui.outliner_toggle(item);
row(ui, &item);
},
);
self.set_widget_state(
key,
WidgetState::TreeItem {
open: item.open,
branch: item.branch,
parent,
first_child,
item: Some(item.id),
},
);
self.mark(key, WidgetKind::OutlinerRow);
(key, response.clicked)
}
fn outliner_toggle(&mut self, item: OutlinerRow) {
let glyph = match (item.branch, item.open) {
(false, _) => " ",
(true, true) => "-",
(true, false) => "+",
};
let behavior = if item.branch {
Behavior {
role: Role::Button,
focusable: Some(false),
..Behavior::NONE
}
} else {
Behavior::NONE
};
let toggle = self.block_with(".outliner-toggle", &[], behavior, |ui| {
let glyph = ui.span(".outliner-toggle-glyph", glyph, &[]);
ui.mark(glyph.key, WidgetKind::Decoration);
});
if item.branch {
self.set_widget_state(toggle.key, WidgetState::OutlinerToggle(item.id));
self.mark(toggle.key, WidgetKind::OutlinerToggle);
} else {
self.mark(toggle.key, WidgetKind::Decoration);
}
}
}