use crate::accessibility::Role;
use crate::cells::CellEditor;
use crate::color::Color;
use crate::el::El;
use crate::event::{Cursor, Key, Mods};
use crate::geom::Rect;
use crate::id::Id;
use crate::layout::{Align, Content, Flow, Length, NONE, Spec};
use crate::ui::{Icon, Measure, Response, Ui};
use std::hash::Hash;
use std::ops::Range;
const UP: Icon = Icon::line("M4 9.5 8 5.5 12 9.5");
const DOWN: Icon = Icon::line("M4 6.5 8 10.5 12 6.5");
const BODY: &str = "rows";
const KEYS: &str = "keys";
pub(crate) const EDGE: f32 = 8.0;
pub(crate) const BETWEEN: f32 = 13.0;
pub(crate) const FAR: f32 = 1_048_576.0;
const NARROWEST: f32 = 24.0;
const STEP: f32 = 16.0;
const MOVES: Mods = Mods { ctrl: true, shift: true, alt: false };
const WIDENS: Mods = Mods { ctrl: false, shift: false, alt: true };
const LIST: Id = 0x7ab1_e5c0_1c0d_e5ed;
#[derive(Clone, Copy, Debug, PartialEq)]
pub struct Column<'a> {
pub name: &'a str,
pub width: Length,
pub align: Align,
pub sortable: bool,
pub editor: CellEditor<'a>,
}
impl<'a> Column<'a> {
pub const fn new(name: &'a str) -> Self {
Column { name, width: Length::Grow(1.0), align: Align::Start, sortable: true, editor: CellEditor::None }
}
pub const fn editable(self, entry: CellEditor<'a>) -> Self {
Column { editor: entry, ..self }
}
pub const fn px(self, width: f32) -> Self {
Column { width: Length::Px(width), ..self }
}
pub const fn grow(self, weight: f32) -> Self {
Column { width: Length::Grow(weight), ..self }
}
pub const fn align(self, align: Align) -> Self {
Column { align, ..self }
}
pub const fn unsorted(self) -> Self {
Column { sortable: false, ..self }
}
}
#[derive(Clone, Debug, Default, PartialEq)]
pub struct Table {
pub widths: Vec<f32>,
pub sort: Vec<(usize, bool)>,
pub order: Vec<usize>,
pub hidden: Vec<usize>,
pub frozen: usize,
pub focused_cell: Option<[usize; 2]>,
}
impl Table {
pub fn sort_by(&mut self, by: usize, more: bool) {
let down = self.sort.iter().any(|(column, down)| *column == by && !*down);
self.sort.retain(|(column, _)| more && *column != by);
self.sort.push((by, down));
}
fn dragged(&self, column: usize) -> Option<f32> {
self.widths.get(column).copied().filter(|width| *width > 0.0)
}
pub(crate) fn column_at(&self, place: usize, count: usize) -> usize {
let named = self.order.iter().fold(0u64, |named, column| named | 1 << (column & 63));
let named = if count > 64 { once_each(&self.order, count) } else { named == u64::MAX >> (64 - count.clamp(1, 64)) };
let whole = self.order.len() == count && self.order.iter().all(|column| *column < count) && named;
if whole { self.order[place] } else { place }
}
fn shows(&self, column: usize) -> bool {
!self.hidden.contains(&column)
}
fn show(&mut self, column: usize, shown: bool, count: usize) {
let others = (0..count).filter(|other| *other != column && self.shows(*other)).count();
self.hidden.retain(|hidden| *hidden != column);
if !shown && others > 0 {
self.hidden.push(column);
}
}
fn move_column(&mut self, column: usize, to: usize, count: usize) {
let places: Vec<usize> = (0..count).map(|place| self.column_at(place, count)).collect();
let (from, to) = (places.iter().position(|at| *at == column), places.iter().position(|at| *at == to));
self.order = places;
if let (Some(from), Some(to)) = (from, to) {
let moved = self.order.remove(from);
self.order.insert(to, moved);
}
}
}
fn once_each(order: &[usize], count: usize) -> bool {
let mut named = vec![false; count];
order.iter().all(|column| *column < count && !std::mem::replace(&mut named[*column], true))
}
#[derive(Clone, Copy)]
pub(crate) struct Track {
x: f32,
pub width: f32,
under: f32,
eager: f32,
side: Align,
pub shows: bool,
pub place: u32,
}
impl Track {
fn part(&self, from: f32, wide: f32) -> [f32; 3] {
let cut = (self.under - from).max(0.0);
[self.x + from + cut.min(wide), (wide - cut).max(0.0), cut]
}
pub fn start(&self) -> f32 {
self.x
}
pub fn holds(&self, along: f32) -> bool {
along >= self.x + self.under.min(self.width) && along < self.x + self.width + BETWEEN
}
pub fn seat(&self, spec: &mut Spec) {
let own = match (spec.content, spec.frame.size[0]) {
(Content::Icon { .. } | Content::Picture { .. }, Length::Px(own)) => own,
_ => self.width,
};
let from = ((self.width - own).max(0.0) * [0.0, 0.5, 1.0, 0.0][self.side as usize]).round();
let [x, width, cut] = self.part(from, own.min(self.width));
(spec.frame.size[0], spec.frame.nudge[0], spec.frame.clip) = (Length::Px(width), x, true);
(spec.frame.pad.left, spec.frame.pad.right) = (spec.frame.pad.left - cut, spec.frame.pad.right - (own - self.width).max(0.0));
match (&mut spec.content, spec.frame.flow) {
_ if self.side == Align::Start => {}
(Content::Text { side, .. }, _) => *side = self.side,
(_, Flow::Column) => spec.frame.across = self.side,
_ => spec.frame.along = self.side,
}
}
}
impl Ui {
#[cfg_attr(debug_assertions, track_caller)]
pub fn table(&mut self, state: &mut Table, columns: &[Column]) -> Response {
self.table_of(state, columns, true)
}
pub(crate) fn table_of_rows(&mut self, state: &mut Table, columns: &[Column]) -> Response {
self.table_of(state, columns, false)
}
#[cfg_attr(debug_assertions, track_caller)]
fn table_of(&mut self, state: &mut Table, columns: &[Column], cells: bool) -> Response {
let mut all = self.column().grow().open();
let (body, keys) = (self.id(BODY), self.id(KEYS));
let read = self.rooms.get(&body).copied().unwrap_or([self.size().w, 0.0, 0.0]);
let first = self.tracks.len() as u32;
let across = self.scrolls.get(&body).map_or(0.0, |offset| offset[0]);
self.lay_columns(state, columns, read[0], across);
let moved = if cells { self.work_cells(state, columns, [all.id, body, keys], first, [read[0], read[1]]) } else { self.leave_cells(first) };
if let Some(across) = moved {
self.tracks.truncate(first as usize);
self.lay_columns(state, columns, read[0], across);
}
let across = self.scrolls.get(&body).map_or(0.0, |offset| offset[0]);
if self.listening {
self.tell_table(&all, self.tracks[first as usize..].iter().filter(|track| track.shows).count());
}
all.changed |= self.column_headers(state, columns, first, body, across);
self.separator();
if cells {
self.el().key(KEYS).size(0.0, 0.0).focusable().show();
}
let (at, end) = (self.tree.specs.len() as u32, self.tracks.len() as u32);
self.note_body(all.id, at);
self.join_next = true;
self.column().key(BODY).grow().scroll().scroll_x().open();
self.measures.push(Measure { at, within: at, id: body, read });
if let Some(open) = self.open.last_mut() {
open.columns = [first, end];
}
all.focused = cells && self.focus == keys;
all
}
fn lay_columns(&mut self, state: &Table, columns: &[Column], room: f32, across: f32) {
let (first, font, count) = (self.tracks.len(), self.theme.small_font.bold(), columns.len());
let (mut taken, mut eager) = (2.0 * EDGE, f32::MIN_POSITIVE);
for (number, column) in columns.iter().enumerate() {
let asks = match (state.dragged(number), column.width) {
_ if !state.shows(number) => [-BETWEEN, 0.0],
(Some(width), _) | (None, Length::Px(width)) => [width, 0.0],
(None, Length::Grow(weight)) => [0.0, weight],
(None, Length::Fit) => [self.text.measure(column.name, font, self.scale, None).ceil() + 2.0, 0.0],
};
(taken, eager) = (taken + asks[0] + BETWEEN, eager + asks[1]);
self.tracks.push(Track { x: 0.0, width: asks[0], under: 0.0, eager: asks[1], side: column.align, shows: state.shows(number), place: 0 });
}
let (spare, mut x, mut keep, mut clear, mut shown) = ((room - taken).max(0.0), 0.0, state.frozen, 0.0, 0);
for place in 0..count {
let track = &mut self.tracks[first + state.column_at(place, count)];
let width = if track.shows { (track.width + spare * track.eager / eager).floor().max(NARROWEST) } else { 0.0 };
let (kept, after) = (track.shows && keep > 0, x + if track.shows { width + BETWEEN } else { 0.0 });
(track.x, track.width, track.under, track.place) = (x + if kept { across } else { 0.0 }, width, if kept { 0.0 } else { (clear - x).max(0.0) }, shown);
(x, keep, clear, shown) = (after, keep - kept as usize, if kept { across + after } else { clear }, shown + track.shows as u32);
}
}
fn column_headers(&mut self, state: &mut Table, columns: &[Column], first: u32, body: Id, across: f32) -> bool {
let t = self.theme;
let headers = self.el().flow(Flow::Stack).h(Length::Px(t.control_height)).pad((EDGE, 0.0)).fill(t.panel).clip().shifted(across, 0.0).open();
self.follows.push((headers.id, body));
let mut sorted = false;
for place in 0..columns.len() {
let number = state.column_at(place, columns.len());
if state.shows(number) {
sorted |= self.column_header(state, columns, number, first);
self.column_resizer(state, number, first);
}
}
self.close();
sorted
}
fn column_header(&mut self, state: &mut Table, columns: &[Column], number: usize, first: u32) -> bool {
let (t, column, track) = (self.theme, &columns[number], self.tracks[first as usize + number]);
let [x, width, cut] = track.part(0.0, track.width);
let press = self.press(self.id(number));
let taken = self.drag_delta(&press, [0.0; 4]).is_some_and(|(gone, _)| gone.x.abs() > 4.0);
if taken {
self.move_column_header(state, columns.len(), number, &press);
}
let more = press.focused && column.sortable && self.key(Key::Enter, Mods::SHIFT);
let clicked = (press.clicked || more) && column.sortable && self.gone().x.abs() <= 4.0;
if clicked {
state.sort_by(number, more || self.input.mods.shift && self.input.released[0]);
}
if press.focused {
self.column_header_keys(state, columns.len(), number, track.width);
}
let sorted = state.sort.iter().find(|(by, _)| *by == number).map(|(_, down)| *down);
let lit = sorted.is_some() || press.hovered || press.pressed;
let cell = self.row().key(number).offset(x, 0.0).w(Length::Px(width)).h(Length::Grow(1.0)).pad((-cut, 0.0, 0.0, 0.0)).gap(4.0).align(column.align, Align::Center).clip().sense();
if column.sortable {
cell.focusable().open()
} else {
cell.open()
};
self.tell(&press, Role::ColumnHeader, None, "");
if self.listening {
self.tell_position(track.place as usize + 1, self.tracks[first as usize..].iter().filter(|track| track.shows).count());
self.tell_sorted(sorted);
}
self.text(column.name, t.small_font.bold(), if lit { t.text } else { t.text_dim });
if let Some(down) = sorted {
self.el().icon(if down { DOWN } else { UP }, 12.0, t.text_dim).show();
}
self.close();
self.column_menu(state, columns, &press);
clicked
}
fn move_column_header(&mut self, state: &mut Table, count: usize, number: usize, held: &Response) {
let Some(at) = self.pointer() else { return };
let place = (0..count).position(|place| state.column_at(place, count) == number).unwrap_or(0);
let before = (0..place).rev().map(|place| state.column_at(place, count)).find(|column| state.shows(*column));
let after = (place + 1..count).map(|place| state.column_at(place, count)).find(|column| state.shows(*column));
let (beside, left) = if at.x < held.rect.x { (before, true) } else { (after, false) };
let there = beside.map_or(Rect::EMPTY, |column| self.seen(self.id(column)));
let past = if left { at.x < there.x + there.w / 2.0 } else { at.x >= there.x + there.w / 2.0 };
if let (Some(beside), true, false) = (beside, past, there.is_empty()) {
state.move_column(number, beside, count);
self.again = true;
}
}
fn column_menu(&mut self, state: &mut Table, columns: &[Column], of: &Response) {
let keyed = of.focused && self.key(Key::F(10), Mods::SHIFT);
let at = if keyed { Some(of.rect) } else { self.pointer().filter(|_| of.right_clicked).map(|at| Rect { x: at.x, y: at.y, w: 0.0, h: 0.0 }) };
if let Some(at) = at {
self.open_popup(of.id ^ LIST, at);
}
if !self.menu(of.id ^ LIST) {
return;
}
for (number, column) in columns.iter().enumerate() {
let mut shown = state.shows(number);
if self.menu_checkbox(&mut shown, column.name).changed {
state.show(number, shown, columns.len());
}
}
self.close();
}
fn column_header_keys(&mut self, state: &mut Table, count: usize, number: usize, width: f32) {
let [back, on, narrower, wider] = [(Key::Left, MOVES), (Key::Right, MOVES), (Key::Left, WIDENS), (Key::Right, WIDENS)].map(|(key, mods)| self.key(key, mods));
let place = (0..count).position(|place| state.column_at(place, count) == number).unwrap_or(0);
let beside = match (back, on) {
(true, _) => (0..place).rev().map(|place| state.column_at(place, count)).find(|column| state.shows(*column)),
(_, true) => (place + 1..count).map(|place| state.column_at(place, count)).find(|column| state.shows(*column)),
_ => None,
};
if let Some(beside) = beside {
state.move_column(number, beside, count);
self.again = true;
}
if narrower || wider {
state.widths.resize(state.widths.len().max(number + 1), 0.0);
(state.widths[number], self.again) = ((width + if wider { STEP } else { -STEP }).max(NARROWEST), true);
}
}
fn column_resizer(&mut self, state: &mut Table, number: usize, first: u32) {
let (t, track) = (self.theme, self.tracks[first as usize + number]);
let (width, [x, wide, cut]) = (track.width, track.part(track.width, BETWEEN));
let hold = self.interact(self.id((number, "edge")));
if hold.hovered || hold.pressed {
self.set_cursor(Cursor::ResizeX);
}
let dragged = self.drag_delta(&hold, [width, 0.0, 0.0, 0.0]).map(|(gone, was)| (was[0] + gone.x).round().max(NARROWEST));
let to = if hold.double_clicked { Some(0.0) } else { dragged.filter(|to| *to != width) };
if let Some(to) = to {
state.widths.resize(state.widths.len().max(number + 1), 0.0);
(state.widths[number], self.again) = (to, true);
}
let line = if hold.hovered || hold.pressed { t.accent } else { t.line };
self.row().key((number, "edge")).offset(x, 0.0).w(Length::Px(wide)).h(Length::Grow(1.0)).pad((-cut, 0.0, 0.0, 0.0)).align(Align::Center, Align::Spread).clip().sense().open();
self.el().w(Length::Px(1.0)).fill(line).show();
self.close();
}
#[cfg_attr(debug_assertions, track_caller)]
pub fn table_row(&mut self) -> El<'_> {
let [first, end] = self.open.last().map_or([NONE; 2], |open| open.columns);
let columns = self.tracks.get(first as usize..end as usize).unwrap_or(&[]);
let wide = 2.0 * EDGE + columns.iter().filter(|track| track.shows).map(|track| track.width + BETWEEN).sum::<f32>();
self.cells_next = true;
if self.listening {
self.count_row([first, end]);
}
let row = self.el().flow(Flow::Stack).align(Align::Start, Align::Center).pad((EDGE, 0.0)).min(wide, 0.0);
if first == NONE { row } else { row.sense() }
}
fn table_told(&self) -> Option<usize> {
let columns = self.open.last().filter(|_| self.listening)?.columns;
let body = self.open.iter().find(|open| open.columns == columns && columns != [NONE; 2])?.at;
self.table_note(self.tree.specs[body as usize].frame.parent, columns)
}
fn count_row(&mut self, columns: [u32; 2]) {
let Some(around) = self.open.last() else { return };
let (among, place) = (if around.row > 0.0 { around.count } else { 0 }, around.children);
let Some((table, rows)) = self.table_told().and_then(|table| Some((table, self.table_row_count(table)?))) else { return };
let row = if among > 0 { (*rows + place).saturating_sub(among + 1) } else { (*rows += 1, *rows - 1).1 };
self.tell_row(row, columns, table);
}
pub fn selectable_row(&mut self, key: impl Hash, picked: bool) -> Response {
let (t, id, columns) = (self.theme, self.id(&key), self.open.last().map_or([NONE; 2], |open| open.columns));
let mut state = self.press_to_select(id);
let keyed = self.table_now(columns).is_some();
state.clicked |= keyed && self.keys_picked(columns, id);
let fill = match (picked, state.hovered) {
(true, _) => t.selected,
(false, true) => t.hover,
(false, false) => Color::NONE,
};
let told = self.notes.len();
let row = self.table_row().key(&key).fill(fill).sense();
if keyed {
row.open()
} else {
row.focusable().open()
};
if self.notes.len() > told {
self.tell_selected(picked);
return state;
}
self.tell(&state, Role::Row, Some(picked), "");
let place = self.open.iter().rev().nth(1).filter(|around| around.row > 0.0).map(|around| (around.children as usize - 1, around.count as usize));
place.into_iter().for_each(|(nth, count)| self.tell_position(nth, count));
state
}
#[cfg_attr(debug_assertions, track_caller)]
pub fn rows(&mut self, count: usize, row: f32) -> Range<usize> {
let row = if row > 0.0 { row.max(self.text.metrics(self.theme.font, self.scale).height().ceil()) } else { row };
if let Some(rows) = self.table_told().and_then(|table| self.table_row_count(table)) {
*rows += count as u32;
}
let (id, page) = (self.next_id(), self.open.first().map_or(0, |open| open.at));
let within = self.open.iter().rev().map(|open| open.at).find(|at| self.tree.specs[*at as usize].frame.scroll[1]).unwrap_or(page);
let read = self.rooms.get(&id).copied().unwrap_or([0.0, self.size().h, 0.0]);
let (left_out, mut above) = self.rows_left_out(within, id, count, row, read);
let high = row as f64;
if let Some(asked) = self.row_asked().filter(|asked| *asked < count && row > 0.0) {
above = self.list_into_view(within, above, read[1], asked as f64 * high, high);
}
let rows = if row > 0.0 { ((above / high) as usize).min(count)..(((above + read[1] as f64) / high).ceil() as usize).min(count) } else { 0..0 };
if let Some(hooks) = self.grids.hooks {
(hooks.rows)(self, count, row, read[2]);
}
self.measures.push(Measure { at: self.tree.specs.len() as u32, within, id, read });
self.column().h(Length::Px(((count - left_out) as f64 * high) as f32)).open();
self.el().h(Length::Px((rows.start.saturating_sub(left_out) as f64 * high) as f32)).show();
if let Some(open) = self.open.last_mut() {
(open.row, open.count, open.children) = (row, count as u32, open.children + rows.start as u32);
}
rows
}
fn rows_left_out(&mut self, within: u32, list: Id, count: usize, row: f32, read: [f32; 3]) -> (usize, f64) {
let (holder, stored, high) = (self.tree.specs[within as usize].id, self.tree.specs[within as usize].offset[1], row as f64);
let kept = self.grids.lists.iter().position(|(scrolls, ..)| *scrolls == holder);
let was = match kept.map(|at| self.grids.lists[at]) {
Some((_, by, rows)) if by == list || by == 0 => rows,
Some(_) => return (0, stored as f64 - read[2] as f64),
None => 0,
};
let above = stored as f64 + was as f64 * high - read[2] as f64;
let far = (stored - read[2]).abs() > FAR || stored < read[2] && was > 0;
let now = match () {
_ if count as f64 * high <= 4.0 * FAR as f64 => 0,
_ if far => ((above / high) as usize).saturating_sub(2 * (read[1] / row).ceil() as usize + 2).min(count),
_ => was,
};
if now != was {
let past = if stored > 0.0 && stored >= self.tree.scroll_end(within, 1) - 0.5 { 4.0 * row as f64 + 1024.0 } else { 0.0 };
let stored = (stored as f64 + (was as f64 - now as f64) * high + past) as f32;
self.tree.specs[within as usize].offset[1] = stored;
self.scrolls.insert(holder, [self.tree.specs[within as usize].offset[0], stored]);
self.again = true;
}
match (kept, now) {
(Some(at), 0) => _ = self.grids.lists.remove(at),
(Some(at), _) => self.grids.lists[at] = (holder, list, now),
(None, 0) => {}
(None, _) => self.grids.lists.push((holder, list, now)),
}
if now > 0 {
self.tree.shifted.push((within, (now as f64 * high) as f32));
}
(now, above)
}
#[cfg_attr(debug_assertions, track_caller)]
#[doc(alias("listbox"))]
pub fn list(&mut self, count: usize, row: f32) -> Range<usize> {
self.column().grow().scroll().open();
self.join_next = true;
self.rows(count, row)
}
}