teksilo_widgets/table_view/table_header.rs
1// SPDX-License-Identifier: MPL-2.0
2// SPDX-FileCopyrightText: 2026 FernTech
3
4//! [`TableHeader`] — the column header strip of [`TableView`](crate::TableView)
5//! and [`TreeTableView`](crate::TreeTableView), and a widget of its own for an
6//! application that lays out its own rows under columns: a section list with
7//! full-width group rows, an album card beside its tracks.
8//!
9//! Both views compose this widget, so there is one header implementation: the
10//! `HeaderCell`s (label, sort indicator, filter popover, the resize grip on
11//! each divider, the column-reorder drag, `Role::ColumnHeader` with its sort
12//! direction and AccessKit `Increment` / `Decrement`), the strip that lays them
13//! out in pinned and scrolling bands and paints their separators, and the drop
14//! target that turns a reorder drag into a new column order.
15//!
16//! ## State
17//!
18//! The header's state is six signals — the width overrides, the sort, the
19//! column order, the pinning overrides, the filters and the horizontal scroll
20//! offset. Each builder ([`widths`](TableHeader::widths),
21//! [`sort`](TableHeader::sort), [`order`](TableHeader::order),
22//! [`pinning`](TableHeader::pinning), [`filters`](TableHeader::filters),
23//! [`scroll_x`](TableHeader::scroll_x)) adopts an application's signal; one
24//! that is not given is the header's own, read back through its getter. The
25//! rules are the views' ("Column state an application owns" in the
26//! [`table_view`](crate::table_view) module docs): the header writes nothing
27//! into these signals until the user acts on it, ignores ids it does not
28//! declare, and keeps them when it writes. Hand the same signals to a
29//! `TableView` and the two stay in step.
30//!
31//! The width map holds **overrides**, not the layout: a column with no entry
32//! takes its declared [`ColumnWidth`]. What the header actually laid each
33//! column out at is [`resolved_widths_signal`](TableHeader::resolved_widths_signal),
34//! which is what rows of an application's own read to line their cells up.
35//!
36//! ## Hosted
37//!
38//! Inside a view the header is *hosted* (`TableHeader::hosted`): the view
39//! resolves the widths and the display order (its body needs both before the
40//! header is placed), paints the `OnRelease` resize guide across the whole
41//! table, rebuilds the header whenever its state changes, and holds the
42//! resize-drag state, which a relayout keeps. A rebuild abandons an
43//! in-flight resize, hosted or not: it destroys the cells and the pointer
44//! capture with them (see `TableHeader::build`). A standalone header does
45//! all of that itself, within its own bounds, which it clips to.
46
47use std::cell::{Cell, RefCell};
48use std::collections::HashMap;
49use std::rc::Rc;
50
51use teksilo_canvas::{Canvas, Point, Rect, Size, SizeProposal};
52use teksilo_core::accessibility::AccessNodeBuilder;
53use teksilo_core::binding::BindingLevel;
54use teksilo_core::build_context::BuildContext;
55use teksilo_core::signal::Signal;
56use teksilo_core::widget::{LayoutContext, LayoutResponse, PaintContext, Widget, WidgetPlacement};
57use teksilo_core::widget_builder::HandlerSet;
58use teksilo_core::widget_id::WidgetId;
59use teksilo_data::SortDirection;
60use teksilo_tokens::{BorderRole, SurfaceRole};
61
62use super::body::{RowBand, SharedColumnWidths, has_pinning};
63use super::column::{ColumnResizePolicy, ColumnSpec, ColumnWidth, PinnedSide};
64use super::header::{
65 ColumnResizeInfo, ColumnResizeTable, HeaderCell, HeaderCellSpec, ResizeStateHandle,
66 SharedFrozenWidths, width_overrides,
67};
68use super::imperative;
69use super::layout::{self, ColumnSolver, band_rects, insertion_slot_at_x};
70use super::{ColumnReorderDragData, PaneBoundaries};
71use crate::styles::recipe_table_style as cp;
72
73/// A process-unique id for one header's column-reorder drags. Every header
74/// draws from this one counter — a `TableView`'s, a `TreeTableView`'s and a
75/// standalone one — so a drop never takes another header's drag for one of
76/// its own.
77pub(crate) fn next_header_id() -> usize {
78 use std::sync::atomic::{AtomicUsize, Ordering};
79 static NEXT: AtomicUsize = AtomicUsize::new(1);
80 NEXT.fetch_add(1, Ordering::Relaxed)
81}
82
83/// The handles a header shares with whatever lays it out — all of them outlive
84/// one build of the header.
85///
86/// A standalone header owns a set ([`HeaderLink::new`]) and fills it itself; a
87/// view composing the header hands over its own (see [`TableHeader::hosted`]).
88#[derive(Clone)]
89pub(crate) struct HeaderLink {
90 /// Disambiguates this header's reorder drags; see [`next_header_id`].
91 pub table_id: usize,
92 /// Resolved widths in display order — shared with a view's body rows.
93 pub widths: SharedColumnWidths,
94 /// Display order, as indices into the columns.
95 pub display_indices: Rc<RefCell<Vec<usize>>>,
96 pub pane_boundaries: Rc<RefCell<PaneBoundaries>>,
97 /// The strip's width: the reorder drop mirrors its x against it under RTL,
98 /// where the columns are anchored to the strip's right edge.
99 pub strip_width: Rc<Cell<f32>>,
100 pub resize_state: ResizeStateHandle,
101 pub resize_target: Signal<Option<usize>>,
102 pub resize_preview_x: Signal<Option<f32>>,
103 /// `Some` when the width map is adopted: the widths a resize freezes stay
104 /// here rather than in the map, which other views may share. See
105 /// `commit_resize` in the header cell module.
106 pub frozen_widths: Option<SharedFrozenWidths>,
107}
108
109impl HeaderLink {
110 pub(crate) fn new() -> Self {
111 Self {
112 table_id: next_header_id(),
113 widths: Rc::new(RefCell::new(Vec::new())),
114 display_indices: Rc::new(RefCell::new(Vec::new())),
115 pane_boundaries: Rc::new(RefCell::new(PaneBoundaries::default())),
116 strip_width: Rc::new(Cell::new(0.0)),
117 resize_state: Rc::new(RefCell::new(None)),
118 resize_target: Signal::new(None),
119 resize_preview_x: Signal::new(None),
120 frozen_widths: None,
121 }
122 }
123}
124
125/// A table's column header strip: one `Role::ColumnHeader` cell per column,
126/// with click-to-sort, drag-to-resize on every divider, drag-to-reorder,
127/// pinned columns, the filter popover and a horizontal scroll offset to follow
128/// a scrolled body.
129///
130/// ```ignore
131/// let widths = Signal::new(HashMap::new());
132/// let sort = Signal::new(None);
133/// let header = TableHeader::new(vec![
134/// ColumnSpec::new("title", lit!("Title")).sortable(true),
135/// ColumnSpec::new("length", lit!("Length"))
136/// .width(ColumnWidth::Fixed(80.0))
137/// .sortable(true),
138/// ])
139/// .widths(widths.clone())
140/// .sort(sort.clone());
141/// let layout = header.resolved_widths_signal().clone(); // line rows up with this
142/// ```
143///
144/// A header announces itself as the `Role::Row` with row index 1, its cells as
145/// `Role::ColumnHeader`s, so place it inside the container that announces the
146/// rows under it as a table or a grid.
147///
148/// See the [module docs](crate::table_view::table_header) for how its state is
149/// shared and for how a view hosts it.
150pub struct TableHeader {
151 columns: Vec<ColumnSpec>,
152 widths: Signal<HashMap<String, f32>>,
153 sort: Signal<Option<(String, SortDirection)>>,
154 order: Signal<Vec<String>>,
155 pinning: Signal<HashMap<String, PinnedSide>>,
156 filters: Signal<HashMap<String, String>>,
157 scroll_x: Signal<f32>,
158 resize_policy: ColumnResizePolicy,
159 stretch_last_column: bool,
160 /// `(id, width)` per displayed column, published by a standalone header
161 /// after each layout.
162 resolved: Signal<Vec<(String, f32)>>,
163 link: HeaderLink,
164 /// `true` when a view composes this header; see the module docs.
165 hosted: bool,
166
167 // Build state.
168 cells: Vec<WidgetId>,
169 /// Pane bands, built only while a column is pinned (see `BodyRow`'s
170 /// module docs for why the split exists).
171 bands: Option<[Option<WidgetId>; 3]>,
172 boundaries: PaneBoundaries,
173 /// The active `TableStyle`'s header height, read at build: the height a
174 /// standalone header takes when its parent leaves the height free.
175 style_height: f32,
176}
177
178impl TableHeader {
179 /// A header over `columns`, in declaration order. Every piece of state it
180 /// is not handed is its own.
181 pub fn new(columns: Vec<ColumnSpec>) -> Self {
182 Self {
183 columns,
184 widths: Signal::new(HashMap::new()),
185 sort: Signal::new(None),
186 order: Signal::new(Vec::new()),
187 pinning: Signal::new(HashMap::new()),
188 filters: Signal::new(HashMap::new()),
189 scroll_x: Signal::new(0.0),
190 resize_policy: ColumnResizePolicy::default(),
191 stretch_last_column: false,
192 resolved: Signal::new(Vec::new()),
193 link: HeaderLink::new(),
194 hosted: false,
195 cells: Vec::new(),
196 bands: None,
197 boundaries: PaneBoundaries::default(),
198 style_height: cp::HEADER_HEIGHT,
199 }
200 }
201
202 /// Adopt `widths` as the map of column id → width override; a column
203 /// with no entry takes its declared [`ColumnWidth`]. A resize drag writes
204 /// the resized column only. Each `Flex` column before it keeps its
205 /// current width in this header, but not in the map, which other views
206 /// may share at other widths.
207 pub fn widths(mut self, widths: Signal<HashMap<String, f32>>) -> Self {
208 self.widths = widths;
209 // A hosting view hands over its own, adopted or not.
210 if !self.hosted {
211 self.link.frozen_widths = Some(Rc::default());
212 }
213 self
214 }
215
216 /// Adopt `sort` as the active sort. A click on a sortable column cycles it
217 /// None → ascending → descending → None.
218 pub fn sort(mut self, sort: Signal<Option<(String, SortDirection)>>) -> Self {
219 self.sort = sort;
220 self
221 }
222
223 /// Adopt `order` as the column order, a list of column ids; columns it
224 /// does not name follow in declaration order. A reorder drop writes it.
225 pub fn order(mut self, order: Signal<Vec<String>>) -> Self {
226 self.order = order;
227 self
228 }
229
230 /// Adopt `pinning` as the per-column pinning overrides, which win over
231 /// each [`ColumnSpec::pinned`]; [`PinnedSide::None`] unpins a column
232 /// declared pinned. A reorder drop writes it: an entry when the drop puts
233 /// the column in a pane other than the one it declares, none when it
234 /// puts it back.
235 pub fn pinning(mut self, pinning: Signal<HashMap<String, PinnedSide>>) -> Self {
236 self.pinning = pinning;
237 self
238 }
239
240 /// Adopt `filters` as the per-column filter text the filter popover of a
241 /// [`filterable`](ColumnSpec::filterable) column edits.
242 pub fn filters(mut self, filters: Signal<HashMap<String, String>>) -> Self {
243 self.filters = filters;
244 self
245 }
246
247 /// Follow `scroll_x`, the horizontal offset of the body under the header:
248 /// the unpinned columns shift left by it, the pinned ones stay put.
249 pub fn scroll_x(mut self, scroll_x: Signal<f32>) -> Self {
250 self.scroll_x = scroll_x;
251 self
252 }
253
254 /// Whether a resize writes its width on every pointer move (`Live`, the
255 /// default) or on release (`OnRelease`, with a guide line meanwhile).
256 pub fn resize_policy(mut self, policy: ColumnResizePolicy) -> Self {
257 self.resize_policy = policy;
258 self
259 }
260
261 /// Let the last column in display order take the width the others leave
262 /// — see [`TableView::stretch_last_column`](crate::TableView::stretch_last_column).
263 /// Default off.
264 pub fn stretch_last_column(mut self, on: bool) -> Self {
265 self.stretch_last_column = on;
266 self
267 }
268
269 /// Compose this header inside a view, which owns the layout and the drag
270 /// state `link` carries; see the module docs.
271 pub(crate) fn hosted(mut self, link: HeaderLink) -> Self {
272 self.link = link;
273 self.hosted = true;
274 self
275 }
276
277 /// The width overrides — the signal [`widths`](Self::widths) adopted, or
278 /// the header's own.
279 pub fn widths_signal(&self) -> &Signal<HashMap<String, f32>> {
280 &self.widths
281 }
282
283 /// The active sort — the signal [`sort`](Self::sort) adopted, or the
284 /// header's own.
285 pub fn sort_signal(&self) -> &Signal<Option<(String, SortDirection)>> {
286 &self.sort
287 }
288
289 /// The column order — the signal [`order`](Self::order) adopted, or the
290 /// header's own.
291 pub fn order_signal(&self) -> &Signal<Vec<String>> {
292 &self.order
293 }
294
295 /// The pinning overrides — the signal [`pinning`](Self::pinning)
296 /// adopted, or the header's own.
297 pub fn pinning_signal(&self) -> &Signal<HashMap<String, PinnedSide>> {
298 &self.pinning
299 }
300
301 /// The filters — the signal [`filters`](Self::filters) adopted, or the
302 /// header's own.
303 pub fn filters_signal(&self) -> &Signal<HashMap<String, String>> {
304 &self.filters
305 }
306
307 /// The horizontal offset the header follows — the signal
308 /// [`scroll_x`](Self::scroll_x) adopted, or the header's own (which
309 /// stays at 0).
310 pub fn scroll_x_signal(&self) -> &Signal<f32> {
311 &self.scroll_x
312 }
313
314 /// `(column id, width)` for each displayed column, in display order: the
315 /// widths the header laid its cells out at, after the overrides, the
316 /// declared widths, the `Flex` share and the min / max clamps. Written
317 /// when the header is placed in a layout pass, and only when it changed;
318 /// bind a row's layout to it to line the row's cells up with the columns.
319 /// Leading-pinned columns come first and do not move with `scroll_x`, nor
320 /// do the trailing-pinned ones at the end.
321 ///
322 /// **Rows follow it one layout pass late**, unless they read it in their
323 /// own `place_children` and are laid out after the header (below it in
324 /// the same stack): only the header's bounds settle the widths, and a row
325 /// that sizes itself from them in `layout_response` (a `FixedSize` bound
326 /// to a width derived from this, say) has been measured by then, so it is
327 /// relaid out on the next pass. During a live resize drag such a row
328 /// trails the header by a frame, and a headless test needs a second
329 /// `layout()` before it lines up.
330 ///
331 /// Published by a standalone header only; a view hosting the header lays
332 /// its rows out from the same widths directly.
333 pub fn resolved_widths_signal(&self) -> &Signal<Vec<(String, f32)>> {
334 &self.resolved
335 }
336
337 fn has_pinning(&self) -> bool {
338 has_pinning(self.boundaries, self.cells.len())
339 }
340
341 /// The display order, from the order and pinning signals — a standalone
342 /// header's own; a hosted one reads the view's.
343 fn compute_display_order(&self) {
344 let (display, boundaries) =
345 layout::display_order(&self.columns, &self.order.get(), &self.pinning.get());
346 *self.link.display_indices.borrow_mut() = display;
347 *self.link.pane_boundaries.borrow_mut() = boundaries;
348 }
349
350 fn resolve_widths(&self, available: f32) -> Vec<f32> {
351 let overrides = width_overrides(
352 self.widths.get(),
353 self.link.frozen_widths.as_ref(),
354 self.columns.iter().map(|c| c.id.as_str()),
355 );
356 ColumnSolver::resolve_in_order(
357 &self.columns,
358 &self.link.display_indices.borrow(),
359 available,
360 cp::MIN_COLUMN_WIDTH_DEFAULT,
361 &overrides,
362 self.stretch_last_column,
363 )
364 }
365
366 /// Wire the strip as the drop target of its own cells' reorder drags:
367 /// classify the drop into a pane and an insertion slot, and write the
368 /// pinning and the order.
369 fn reorder_drop_handlers(&self) -> HandlerSet {
370 let link = self.link.clone();
371 let order = self.order.clone();
372 let pinning = self.pinning.clone();
373 let scroll_x = self.scroll_x.clone();
374 let ids: Vec<String> = self.columns.iter().map(|c| c.id.clone()).collect();
375 let declared_pinning: Vec<PinnedSide> = self.columns.iter().map(|c| c.pinned).collect();
376 let table_id = self.link.table_id;
377
378 HandlerSet::new()
379 .on_drag_hover(|payload, _position, _ctx| {
380 if payload.has_typed::<ColumnReorderDragData>() {
381 teksilo_core::DropFeedback::HighlightRect {
382 rect: Rect::ZERO,
383 color: teksilo_tokens::Color::TRANSPARENT,
384 }
385 } else {
386 teksilo_core::DropFeedback::NoFeedback
387 }
388 })
389 .on_drop(move |mut payload, position, ctx| {
390 let drag = match payload.take_typed::<ColumnReorderDragData>() {
391 Some(d) => d,
392 None => return false,
393 };
394 if drag.source_table_id != table_id {
395 return false;
396 }
397 let widths = link.widths.borrow().clone();
398 let display = link.display_indices.borrow().clone();
399 let panes = *link.pane_boundaries.borrow();
400 let total = display.len();
401 if total == 0 {
402 return false;
403 }
404
405 // `position` is local to the strip (origin at its physical-left
406 // edge). Under RTL the columns are placed in display order from
407 // the strip's right edge leftward, so mirror the drop x against
408 // the strip width before running the left-to-right scan. (A drop
409 // in any non-content dead space then maps past the last column →
410 // append, matching LTR's trailing-end behaviour.)
411 let drop_x = if ctx.is_rtl() {
412 link.strip_width.get() - position.x
413 } else {
414 position.x
415 };
416
417 // Insertion index in display order: the first column whose
418 // midpoint exceeds the (mirrored) x — pane- and scroll-aware, so
419 // a drop under a nonzero `scroll_x` resolves against the columns
420 // actually under the pointer, not their unscrolled positions.
421 let insertion_display_idx = insertion_slot_at_x(
422 &widths,
423 panes,
424 scroll_x.get(),
425 link.strip_width.get(),
426 drop_x,
427 );
428
429 // Classify the drop position into a pane. A pane only exists
430 // while a column is pinned to it: with nothing pinned the leading
431 // pane is empty and the middle pane ends at the strip's end, so a
432 // drop at either end of the strip is a plain move to the first /
433 // last slot, not a pin — without the guards it would pin the
434 // column to a pane the user never saw.
435 let new_pinning = if panes.leading_count > 0
436 && insertion_display_idx <= panes.leading_count
437 {
438 PinnedSide::Leading
439 } else if panes.middle_end < total && insertion_display_idx >= panes.middle_end {
440 PinnedSide::Trailing
441 } else {
442 PinnedSide::None
443 };
444
445 // The pinning override: an entry when the drop puts the column
446 // on a side other than the one it declares — `None` included,
447 // or a column declared pinned could never be dragged out of its
448 // pane — and none when it puts it back on its own.
449 let Some(col_idx) = ids.iter().position(|id| id == &drag.col_id) else {
450 return false;
451 };
452 let mut pin_map = pinning.get();
453 if new_pinning == declared_pinning[col_idx] {
454 pin_map.remove(&drag.col_id);
455 } else {
456 pin_map.insert(drag.col_id.clone(), new_pinning);
457 }
458 pinning.set(pin_map);
459
460 // This header's columns in their new display order, each with
461 // the pane it now sits in.
462 let pane_at = |slot: usize| {
463 if slot < panes.leading_count {
464 PinnedSide::Leading
465 } else if slot < panes.middle_end {
466 PinnedSide::None
467 } else {
468 PinnedSide::Trailing
469 }
470 };
471 let mut new_display: Vec<(String, PinnedSide)> = display
472 .iter()
473 .enumerate()
474 .map(|(slot, &i)| (ids[i].clone(), pane_at(slot)))
475 .collect();
476 let from_pos = new_display.iter().position(|(id, _)| id == &drag.col_id);
477 if let Some(from) = from_pos {
478 let (item, _) = new_display.remove(from);
479 let to = if from < insertion_display_idx {
480 insertion_display_idx.saturating_sub(1)
481 } else {
482 insertion_display_idx
483 };
484 let to = to.min(new_display.len());
485 new_display.insert(to, (item, new_pinning));
486 order.set(move_dropped_column(
487 &order.get(),
488 &new_display,
489 &drag.col_id,
490 ));
491 }
492 true
493 })
494 }
495}
496
497impl std::fmt::Debug for TableHeader {
498 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
499 f.debug_struct("TableHeader")
500 .field("columns", &self.columns.len())
501 .field("hosted", &self.hosted)
502 .field("sort", &self.sort.get())
503 .finish()
504 }
505}
506
507impl Widget for TableHeader {
508 fn build(&mut self, ctx: &mut BuildContext) -> Vec<WidgetId> {
509 let self_id = ctx.self_id();
510 self.style_height = crate::styles::recipe_table_style::resolve_table_style(ctx)
511 .header_height(&ctx.theme().input);
512 // `paint` draws the column separators from the widths and `scroll_x`,
513 // but neither a column resize nor a horizontal scroll changes the
514 // strip's own bounds — and the render walker replays a clean node's
515 // cached paint. The cells move with their new bounds; only the
516 // separators would stay behind. Repaint-only: geometry is a relayout's
517 // business, below for a standalone header and the view's for a hosted
518 // one.
519 self.widths
520 .bind_to(self_id, ctx.binding_registry(), BindingLevel::RepaintOnly);
521 self.scroll_x
522 .bind_to(self_id, ctx.binding_registry(), BindingLevel::RepaintOnly);
523 // The column titles and the "Filter <column>" trigger names are
524 // resolved here, at build: a locale switch, which rebuilds nothing on
525 // its own, rebuilds the header so both follow it. Like every header
526 // rebuild (a sort, each filter keystroke) it ends a column resize in
527 // progress where the last move left it.
528 ctx.locale_signal()
529 .bind_to(self_id, ctx.binding_registry(), BindingLevel::Rebuild);
530 if !self.hosted {
531 // A view relays out and rebuilds a hosted header on all of these
532 // itself, and owns the display order it reads.
533 self.widths
534 .bind_to(self_id, ctx.binding_registry(), BindingLevel::Relayout);
535 self.scroll_x
536 .bind_to(self_id, ctx.binding_registry(), BindingLevel::Relayout);
537 // Each cell captures its sort direction, its filter state and its
538 // display position at build, and the bands follow the pinning.
539 self.sort
540 .bind_to(self_id, ctx.binding_registry(), BindingLevel::Rebuild);
541 self.order
542 .bind_to(self_id, ctx.binding_registry(), BindingLevel::Rebuild);
543 self.pinning
544 .bind_to(self_id, ctx.binding_registry(), BindingLevel::Rebuild);
545 self.filters
546 .bind_to(self_id, ctx.binding_registry(), BindingLevel::Rebuild);
547 self.link.resize_preview_x.bind_to(
548 self_id,
549 ctx.binding_registry(),
550 BindingLevel::RepaintOnly,
551 );
552 self.compute_display_order();
553 }
554
555 // A resize drag that loses the window never gets its PointerUp: the
556 // user Alt-Tabs (or a native dialog steals focus) with the button
557 // down, releases it over another window, and the OS delivers the Up
558 // nowhere. Abandon the gesture on deactivation, or the state outlives
559 // it and the next bare PointerMove drags the column with no button
560 // held. Nothing is committed — an interrupted drag leaves the column
561 // wherever the last delivered move put it, which is what the user last
562 // saw.
563 {
564 let resize_state = self.link.resize_state.clone();
565 let resize_target = self.link.resize_target.clone();
566 let resize_preview_x = self.link.resize_preview_x.clone();
567 ctx.effect(&ctx.window_active_signal(), move |active| {
568 if !*active && resize_state.borrow().is_some() {
569 *resize_state.borrow_mut() = None;
570 resize_target.set(None);
571 resize_preview_x.set(None);
572 }
573 });
574 }
575
576 // A build destroys (and re-creates) every header cell, which drops the
577 // pointer capture an in-flight resize depends on. Clear the shared drag
578 // state with it: a `ResizeState` that outlived its anchor would
579 // otherwise let the next bare PointerMove over the same column resize
580 // it with no button held.
581 *self.link.resize_state.borrow_mut() = None;
582 self.link.resize_target.set(None);
583 self.link.resize_preview_x.set(None);
584
585 let display = self.link.display_indices.borrow().clone();
586 self.boundaries = *self.link.pane_boundaries.borrow();
587
588 // A stretched last column has no size of its own to drag: its trailing
589 // grip (and the AT step actions behind the same flag) is off. The grip
590 // on its *leading* edge still resizes its predecessor.
591 let stretched_slot = self
592 .stretch_last_column
593 .then(|| display.len().saturating_sub(1));
594 let resize_columns: ColumnResizeTable = Rc::new(
595 display
596 .iter()
597 .enumerate()
598 .map(|(slot, &i)| {
599 let c = &self.columns[i];
600 ColumnResizeInfo {
601 id: c.id.clone(),
602 min_width: c.min_width.unwrap_or(cp::MIN_COLUMN_WIDTH_DEFAULT),
603 max_width: c.max_width,
604 resizable: c.resizable && stretched_slot != Some(slot),
605 flex: matches!(c.width, ColumnWidth::Flex(_)),
606 }
607 })
608 .collect(),
609 );
610
611 let active_sort = self.sort.get();
612 let cell_padding_horizontal = crate::styles::recipe_table_style::resolve_table_style(ctx)
613 .cell_padding_horizontal(&ctx.theme().input);
614 // Filter zone width: indicator glyph + a small horizontal padding for
615 // tap tolerance. Mirrors the layout of the HStack inside
616 // `HeaderCell::build` — including its gutter, which comes from the
617 // active `TableStyle` rather than from `cp::CELL_PADDING_HORIZONTAL`, so
618 // the padding the cell applies and the zone the press handler measures
619 // cannot name different cells.
620 //
621 // At every shipped gutter this is currently inert:
622 // `header_cell_zones` hands the figure to `partition_targets` with a
623 // floor of `target_size`, and 12 + 8 (IntUI) and 12 + 12 (Fluent) are
624 // both under the 24 dp Compact floor, so the solved zone is 24 either
625 // way. It stops being inert the moment a preset's gutter takes the sum
626 // past the floor, which is exactly when the two numbers disagreeing
627 // would show.
628 let filter_zone_width = cp::FILTER_INDICATOR_SIZE + cell_padding_horizontal;
629 self.cells = display
630 .iter()
631 .enumerate()
632 .map(|(display_pos, &col_idx)| {
633 let col = &self.columns[col_idx];
634 let current_sort = active_sort
635 .as_ref()
636 .and_then(|(id, dir)| (id == &col.id).then_some(*dir));
637 ctx.add(HeaderCell::new(HeaderCellSpec {
638 col_id: col.id.clone(),
639 label: col.header_label.resolve_now(),
640 col_index_1based: display_pos + 1,
641 sortable: col.sortable,
642 reorderable: col.reorderable,
643 filterable: col.filterable,
644 resize_grip: cp::RESIZE_HANDLE_WIDTH,
645 filter_zone_width,
646 current_sort,
647 width_index: display_pos,
648 pane_boundaries: self.boundaries,
649 resize_columns: resize_columns.clone(),
650 resize_policy: self.resize_policy,
651 resize_state: self.link.resize_state.clone(),
652 resize_target: self.link.resize_target.clone(),
653 resize_preview_x: self.link.resize_preview_x.clone(),
654 table_id: self.link.table_id,
655 sort_signal: self.sort.clone(),
656 column_widths_signal: self.widths.clone(),
657 frozen_widths: self.link.frozen_widths.clone(),
658 column_widths: self.link.widths.clone(),
659 filters_signal: self.filters.clone(),
660 }))
661 })
662 .collect();
663
664 ctx.apply_self_handlers(self.reorder_drop_handlers());
665
666 if !self.has_pinning() {
667 self.bands = None;
668 return self.cells.clone();
669 }
670 let b = self.boundaries;
671 let leading_end = b.leading_count.min(self.cells.len());
672 let middle_end = b.middle_end.min(self.cells.len()).max(leading_end);
673 let leading: Vec<WidgetId> = self.cells[..leading_end].to_vec();
674 let middle: Vec<WidgetId> = self.cells[leading_end..middle_end].to_vec();
675 let trailing: Vec<WidgetId> = self.cells[middle_end..].to_vec();
676
677 let mut bands: [Option<WidgetId>; 3] = [None, None, None];
678 if !leading.is_empty() {
679 bands[0] = Some(ctx.add(RowBand::new(leading, self.link.widths.clone(), 0)));
680 }
681 if !middle.is_empty() {
682 bands[1] = Some(
683 ctx.add(
684 RowBand::new(middle, self.link.widths.clone(), leading_end)
685 .scrollable(self.scroll_x.clone()),
686 ),
687 );
688 }
689 if !trailing.is_empty() {
690 bands[2] = Some(ctx.add(RowBand::new(trailing, self.link.widths.clone(), middle_end)));
691 }
692 self.bands = Some(bands);
693 bands.iter().copied().flatten().collect()
694 }
695
696 fn layout_response(&self, proposal: SizeProposal, _ctx: &LayoutContext) -> LayoutResponse {
697 let width = proposal.width.unwrap_or_else(|| {
698 if self.hosted {
699 self.link.widths.borrow().iter().sum()
700 } else {
701 // With no width to fill, every `Flex` column sits at its floor.
702 self.resolve_widths(0.0).iter().sum()
703 }
704 });
705 let height = proposal.height.unwrap_or(self.style_height);
706 Size::new(width, height).into()
707 }
708
709 fn place_children(
710 &self,
711 bounds: Rect,
712 _proposal: SizeProposal,
713 children: &mut [WidgetPlacement],
714 ctx: &LayoutContext,
715 ) {
716 if !self.hosted {
717 let widths = self.resolve_widths(bounds.width);
718 let resolved: Vec<(String, f32)> = self
719 .link
720 .display_indices
721 .borrow()
722 .iter()
723 .zip(&widths)
724 .map(|(&i, &w)| (self.columns[i].id.clone(), w))
725 .collect();
726 *self.link.widths.borrow_mut() = widths;
727 self.link.strip_width.set(bounds.width);
728 // Equality-guarded: a layout that changed nothing must not wake a
729 // row bound to this.
730 imperative::set_if_changed(&self.resolved, resolved);
731 }
732
733 if let Some(bands) = self.bands {
734 let widths = self.link.widths.borrow();
735 let rtl = ctx.is_rtl();
736 let (leading_rect, middle_rect, trailing_rect) =
737 band_rects(bounds, &widths, self.boundaries, rtl);
738 let rects = [leading_rect, middle_rect, trailing_rect];
739 let mut next = 0;
740 for (band, rect) in bands.iter().zip(rects.iter()) {
741 if band.is_some() {
742 if let Some(child) = children.get_mut(next) {
743 child.origin = rect.origin();
744 child.size = rect.size();
745 }
746 next += 1;
747 }
748 }
749 return;
750 }
751
752 let widths = self.link.widths.borrow();
753 let total_children = children.len();
754 let fallback_w = if total_children == 0 {
755 0.0
756 } else {
757 bounds.width / total_children as f32
758 };
759 let scroll = self.scroll_x.get();
760 // Mirror the body: preserve display order, reverse physical x in RTL.
761 if ctx.is_rtl() {
762 let mut x = bounds.right() + scroll;
763 for (i, child) in children.iter_mut().enumerate() {
764 let w = widths.get(i).copied().unwrap_or(fallback_w);
765 x -= w;
766 child.origin = Point::new(x, bounds.y);
767 child.size = Size::new(w, bounds.height);
768 }
769 } else {
770 let mut x = bounds.x - scroll;
771 for (i, child) in children.iter_mut().enumerate() {
772 let w = widths.get(i).copied().unwrap_or(fallback_w);
773 child.origin = Point::new(x, bounds.y);
774 child.size = Size::new(w, bounds.height);
775 x += w;
776 }
777 }
778 }
779
780 fn paint(&self, bounds: Rect, canvas: &mut Canvas, ctx: &PaintContext) {
781 let bg = SurfaceRole::Raised.resolve(&ctx.theme.colors);
782 canvas.fill_rect(bounds, bg);
783
784 let line = BorderRole::DividerStrong.resolve(&ctx.theme.colors);
785 let dw = cp::GRID_LINE_THICKNESS.max(1.0);
786 canvas.fill_rect(
787 Rect::new(bounds.x, bounds.y + bounds.height - dw, bounds.width, dw),
788 line,
789 );
790
791 // Column separators. Unlike the body's vertical grid lines these are
792 // NOT gated on `GridLines` — in the header the separator *is* the
793 // resize affordance (it is the only thing showing where the grip is),
794 // so a table with `GridLines::None`/`Horizontal` — the default, and
795 // what both shipped demos use — would otherwise ask the user to grab
796 // an invisible divider. Every desktop table (QHeaderView, GtkTreeView,
797 // NSTableHeaderView) draws them unconditionally for the same reason.
798 let widths = self.link.widths.borrow();
799 if widths.len() > 1 {
800 let rtl =
801 ctx.layout_direction == teksilo_core::environment::LayoutDirection::RightToLeft;
802 let sep = BorderRole::Divider.resolve(&ctx.theme.colors);
803 let (leading_rect, middle_rect, trailing_rect) =
804 band_rects(bounds, &widths, self.boundaries, rtl);
805 let b = self.boundaries;
806 let leading_end = b.leading_count.min(widths.len());
807 let middle_end = b.middle_end.min(widths.len()).max(leading_end);
808 // Within-pane dividers (the Middle pane's are scroll-shifted and
809 // bounded to its viewport, exactly like the body's).
810 draw_band_separators(
811 canvas,
812 leading_rect,
813 &widths[..leading_end],
814 0.0,
815 rtl,
816 sep,
817 dw,
818 );
819 draw_band_separators(
820 canvas,
821 middle_rect,
822 &widths[leading_end..middle_end],
823 self.scroll_x.get(),
824 rtl,
825 sep,
826 dw,
827 );
828 draw_band_separators(
829 canvas,
830 trailing_rect,
831 &widths[middle_end..],
832 0.0,
833 rtl,
834 sep,
835 dw,
836 );
837 // Pane seams — the boundary between the last pinned column and
838 // the scrolling region. `draw_band_separators` only draws a band's
839 // *internal* boundaries, so these two would otherwise be the only
840 // column edges in the strip with no line.
841 let mut seam = |x: f32| {
842 canvas.fill_rect(Rect::new(x, bounds.y, dw, bounds.height), sep);
843 };
844 if leading_end > 0 {
845 seam(if rtl {
846 leading_rect.x
847 } else {
848 leading_rect.right() - dw
849 });
850 }
851 if middle_end < widths.len() {
852 seam(if rtl {
853 trailing_rect.right() - dw
854 } else {
855 trailing_rect.x
856 });
857 }
858 }
859 }
860
861 fn wants_post_paint(&self) -> bool {
862 // A hosting view paints the guide itself, across its rows too.
863 !self.hosted
864 }
865
866 /// The `OnRelease` resize guide. Under that policy no column moves until
867 /// the button comes up, so this line is the *only* feedback the gesture
868 /// has. Drawn over the cells, within the strip.
869 fn post_paint(&self, bounds: Rect, canvas: &mut Canvas, ctx: &PaintContext) {
870 if let Some(x) = self.link.resize_preview_x.get() {
871 let thickness = cp::GRID_LINE_THICKNESS.max(1.5);
872 canvas.fill_rect(
873 Rect::new(x - thickness * 0.5, bounds.y, thickness, bounds.height),
874 BorderRole::Focused.resolve(&ctx.theme.colors),
875 );
876 }
877 }
878
879 fn accessibility(&self, builder: &mut AccessNodeBuilder) {
880 builder.set_role(teksilo_core::accesskit::Role::Row);
881 builder.set_row_index(1);
882 }
883
884 fn children(&self) -> Vec<WidgetId> {
885 match self.bands {
886 Some(bands) => bands.iter().copied().flatten().collect(),
887 None => self.cells.clone(),
888 }
889 }
890
891 fn clips_children(&self) -> bool {
892 // A hosting view clips the strip with the rest of the table.
893 !self.hosted
894 }
895
896 fn as_any(&self) -> Option<&dyn std::any::Any> {
897 Some(self)
898 }
899}
900
901/// Draw one pane band's internal column separators inside the header strip.
902///
903/// Deliberately *not* [`super::draw_pane_dividers`], which scissors each band:
904/// the strip paints inside its view's `clips_children` scope, and
905/// `Canvas::clear_clip` resets the scissor outright rather than popping a
906/// stack — so borrowing that helper here would drop the table's clip for every
907/// header cell painted afterwards (the walker emits the enclosing `SetClip`
908/// before the children, not around each one). Separators are `line_w` wide, so
909/// range-testing each against the band is equivalent to scissoring it, and
910/// leaves the clip state untouched.
911fn draw_band_separators(
912 canvas: &mut Canvas,
913 rect: Rect,
914 slice: &[f32],
915 scroll: f32,
916 rtl: bool,
917 color: teksilo_tokens::Color,
918 line_w: f32,
919) {
920 if slice.len() < 2 || rect.width <= 0.0 {
921 return;
922 }
923 let mut emit = |x: f32| {
924 if x >= rect.x && x + line_w <= rect.right() {
925 canvas.fill_rect(Rect::new(x, rect.y, line_w, rect.height), color);
926 }
927 };
928 // Same walk (and same which-side-of-the-boundary convention) as the body's
929 // vertical grid lines, so header and body seams land on the same x.
930 if rtl {
931 let mut x = rect.right() + scroll;
932 for &w in &slice[..slice.len() - 1] {
933 x -= w;
934 emit(x);
935 }
936 } else {
937 let mut x = rect.x - scroll;
938 for &w in &slice[..slice.len() - 1] {
939 x += w;
940 emit(x - line_w);
941 }
942 }
943}
944
945/// Write the drop of `dragged` into `existing`, the order signal's current
946/// list, which may also name columns this header does not have.
947///
948/// `display` is this header's columns in their display order after the drop,
949/// each with the pane it sits in then. `display_order` sorts each pane by the
950/// columns' positions in the list (the ones the list does not name follow, in
951/// declaration order), so the list only has to put `dragged` right before the
952/// next column of its pane, or right after the previous one.
953///
954/// Only `dragged` moves. An order several views share (`bind_column_order`)
955/// carries every view's columns; re-slotting this header's whole set instead
956/// would move the columns another view shares past ids that view lacks, and
957/// reorder it though nothing it shows was dragged. Own columns the list does
958/// not name yet are appended first, in their current order, so the list
959/// reads as this header's whole order afterwards.
960pub(crate) fn move_dropped_column(
961 existing: &[String],
962 display: &[(String, PinnedSide)],
963 dragged: &str,
964) -> Vec<String> {
965 let mut out = existing.to_vec();
966 for (id, _) in display {
967 if !out.contains(id) {
968 out.push(id.clone());
969 }
970 }
971 let Some(was) = out.iter().position(|id| id == dragged) else {
972 return out;
973 };
974 out.remove(was);
975 let Some(at) = display.iter().position(|(id, _)| id == dragged) else {
976 out.insert(was, dragged.to_string());
977 return out;
978 };
979 let pane = display[at].1;
980 let next = display[at + 1..].iter().find(|(_, side)| *side == pane);
981 let prev = display[..at].iter().rev().find(|(_, side)| *side == pane);
982 let slot = |id: &String| out.iter().position(|o| o == id);
983 let to = match (next, prev) {
984 (Some((next, _)), _) => slot(next),
985 (None, Some((prev, _))) => slot(prev).map(|i| i + 1),
986 // Alone in its pane: where it sits among other panes' columns
987 // changes nothing.
988 (None, None) => None,
989 }
990 .unwrap_or(was);
991 out.insert(to, dragged.to_string());
992 out
993}