1use crate::{
2 LayoutNode, Point, Rect, ScrollLayout, TextMeasurer, TransformSpace,
3 linear::{AxisInfo, fit_axis},
4 place_in_direction,
5};
6use std::sync::Arc;
7use xrack_runtime::{
8 LayoutDirection, ListMetrics, Node, TableColumnOrder, TableColumnWindow, resizable_table_column,
9};
10
11#[derive(Clone, Debug, PartialEq)]
13pub struct TableGeometry {
14 pub header: Rect,
15 pub body: Rect,
16 pub row_header: Rect,
17 pub columns: Vec<Rect>,
18 pub horizontal: ScrollLayout,
19 direction: LayoutDirection,
20 order: TableColumnOrder,
21 hidden_positions: Vec<usize>,
22 frozen: Vec<bool>,
23 frozen_count: usize,
24 frozen_end: usize,
25 frozen_width: f32,
26}
27
28const MAX_COLUMN_WIDTH: f32 = 1_000_000.0;
29const GRIP_RADIUS: f32 = 5.0;
30const MIN_SCROLLABLE_WIDTH: f32 = 32.0;
31
32pub(crate) struct PaneClip {
33 pub bounds: Rect,
34 pub space: Option<Arc<TransformSpace>>,
35}
36
37pub(crate) fn column_limits(column: &Node, viewport_width: f32) -> (f32, f32) {
38 let default_min = column
39 .relative_length("width", viewport_width)
40 .map_or(24.0, |width| width.clamp(0.0, 24.0));
41 let min = column
42 .relative_length("min-width", viewport_width)
43 .unwrap_or(default_min)
44 .max(0.0);
45 let max = column
46 .relative_length("max-width", viewport_width)
47 .unwrap_or(MAX_COLUMN_WIDTH)
48 .max(min);
49 (min, max)
50}
51
52#[doc(hidden)]
53pub fn table_heading_font_size(text: &impl TextMeasurer) -> f32 {
54 (text.default_font_size().unwrap_or(15.0) * text.text_scale()).clamp(1.0, 512.0)
55}
56
57pub(crate) fn header_height(node: &Node, height: f32, preferred: f32) -> f32 {
58 const BASELINE: f32 = 34.0;
59 if let Some(explicit) = node.length("header-height") {
60 return explicit.clamp(16.0, 128.0).min(height);
61 }
62 let available = if preferred > BASELINE {
64 height
65 - (height - BASELINE)
66 .max(0.0)
67 .min(ListMetrics::row_height(node))
68 } else {
69 height
70 };
71 preferred.clamp(16.0, 128.0).min(available)
72}
73
74impl TableGeometry {
75 pub fn new(node: &Node, bounds: Rect) -> Option<Self> {
76 Self::with_offset(
77 node,
78 bounds,
79 bounds,
80 0.0,
81 node.layout_direction().unwrap_or_default(),
82 header_height(node, bounds.height, 34.0),
83 )
84 }
85
86 pub(crate) fn with_offset(
87 node: &Node,
88 bounds: Rect,
89 clip: Rect,
90 requested: f32,
91 direction: LayoutDirection,
92 header_height: f32,
93 ) -> Option<Self> {
94 let header = node.table_header.as_ref()?;
95 let rows = Rect::new(
96 bounds.x,
97 bounds.y + header_height,
98 bounds.width,
99 bounds.height - header_height,
100 );
101 let gutter = node
102 .relative_length("row-header-width", bounds.width)
103 .filter(|width| width.is_finite())
104 .unwrap_or_default()
105 .clamp(0.0, (bounds.width - MIN_SCROLLABLE_WIDTH).max(0.0));
106 let body = place_in_direction(
107 Rect::new(rows.x + gutter, rows.y, rows.width - gutter, rows.height),
108 rows,
109 direction,
110 );
111 let row_header = place_in_direction(
112 Rect::new(rows.x, rows.y, gutter, rows.height),
113 rows,
114 direction,
115 );
116 let header_bounds = Rect::new(body.x, bounds.y, body.width, body.y - bounds.y);
117 let tracks = header.columns.iter().map(|column| {
118 if !column.is_visible() {
119 return AxisInfo::fixed(0.0);
120 }
121 let (min, max) = column_limits(column, body.width);
122 if let Some(width) = column.relative_length("width", body.width) {
123 return AxisInfo::fixed(width.clamp(min, max));
124 }
125 let preferred = column
126 .relative_length("preferred-width", body.width)
127 .unwrap_or(min)
128 .clamp(min, max);
129 let stretch = column.float("horizontal-stretch").unwrap_or(1.0).max(0.0);
130 AxisInfo {
131 min,
132 preferred,
133 max: if stretch == 0.0 { preferred } else { max },
134 stretch,
135 }
136 });
137 let mut widths = fit_axis(tracks, body.width);
138 for (index, (width, override_width)) in
139 widths.iter_mut().zip(&header.column_widths).enumerate()
140 {
141 if let Some(override_width) = override_width
142 && header.columns[index].is_visible()
143 {
144 let (min, max) = column_limits(&header.columns[index], body.width);
145 *width = (*override_width as f32).clamp(min, max);
146 }
147 }
148 let total_width = widths.iter().sum::<f32>();
149 let horizontal = ScrollLayout::new(requested, total_width - body.width);
150 let order = node.table_column_order.clone();
151 let requested_frozen =
152 usize::try_from(node.int("frozen-columns").unwrap_or(0)).unwrap_or(0);
153 let visible = place_in_direction(body.intersect(clip), body, direction);
154 let visible_right = (visible.x + visible.width - body.x).clamp(0.0, body.width);
155 let limit = if total_width > visible_right {
156 (visible_right - MIN_SCROLLABLE_WIDTH).max(0.0)
157 } else {
158 visible_right
159 };
160 let mut frozen_width = 0.0;
161 let mut frozen_count = 0;
162 let mut frozen_end = 0;
163 let mut frozen = Vec::new();
164 for (visual, column) in order
165 .iter(widths.len())
166 .enumerate()
167 .filter(|&(_, column)| widths[column] > 0.0)
168 .take(requested_frozen)
169 {
170 let end = frozen_width + widths[column];
171 if end > limit {
172 break;
173 }
174 if frozen.is_empty() {
175 frozen.resize(widths.len(), false);
176 }
177 frozen[column] = true;
178 frozen_width = end;
179 frozen_count += 1;
180 frozen_end = visual + 1;
181 }
182 let mut x = body.x;
183 let mut columns = vec![Rect::default(); widths.len()];
184 let mut hidden_positions = Vec::new();
185 for (visual, index) in order.iter(widths.len()).enumerate() {
186 if visual == frozen_end {
187 x -= horizontal.offset;
188 }
189 let width = widths[index];
190 if width == 0.0 {
191 hidden_positions.push(visual);
192 }
193 columns[index] = place_in_direction(
194 Rect::new(x, bounds.y, width, header_bounds.height),
195 body,
196 direction,
197 );
198 x += width;
199 }
200 Some(Self {
201 header: header_bounds,
202 body,
203 row_header,
204 columns,
205 horizontal,
206 direction,
207 order,
208 hidden_positions,
209 frozen,
210 frozen_count,
211 frozen_end,
212 frozen_width,
213 })
214 }
215
216 pub(crate) fn rows_area(&self) -> Rect {
217 Rect::new(
218 self.row_header.x.min(self.body.x),
219 self.body.y,
220 self.row_header.width + self.body.width,
221 self.body.height,
222 )
223 }
224
225 pub(crate) fn column_window(&self, clip: Rect) -> TableColumnWindow {
226 let clip = self.body.intersect(clip);
227 TableColumnWindow::new(self.columns.iter().enumerate().map(|(index, column)| {
228 let cell = Rect::new(column.x, self.body.y, column.width, self.body.height);
229 let visible = cell.intersect(self.column_clip(index, clip));
230 visible.width > 0.0 && visible.height > 0.0
231 }))
232 }
233
234 pub fn row_header_cell(&self, row: Rect) -> Rect {
235 Rect::new(self.row_header.x, row.y, self.row_header.width, row.height)
236 }
237
238 #[doc(hidden)]
240 pub fn header_cell_bounds(&self, column: usize, clip: Rect) -> Option<Rect> {
241 let cell = self
242 .columns
243 .get(column)?
244 .intersect(self.column_clip(column, self.header.intersect(clip)));
245 (cell.width > 0.0 && cell.height > 0.0).then_some(cell)
246 }
247
248 pub fn visual_columns(&self) -> impl DoubleEndedIterator<Item = usize> + ExactSizeIterator {
249 self.order.iter(self.columns.len())
250 }
251
252 pub fn visual_index(&self, column: usize) -> Option<usize> {
253 self.order.visual_index(self.columns.len(), column)
254 }
255
256 pub fn is_column_visible(&self, column: usize) -> bool {
257 self.columns
258 .get(column)
259 .is_some_and(|bounds| bounds.width > 0.0)
260 }
261
262 pub fn visible_columns(&self) -> impl DoubleEndedIterator<Item = usize> {
263 self.visual_columns()
264 .filter(|&column| self.is_column_visible(column))
265 }
266
267 pub fn visible_column_count(&self) -> usize {
268 self.columns.len() - self.hidden_positions.len()
269 }
270
271 pub fn visible_column_index(&self, column: usize) -> Option<usize> {
272 if !self.is_column_visible(column) {
273 return None;
274 }
275 let visual = self.visual_index(column)?;
276 Some(
277 visual
278 - self
279 .hidden_positions
280 .partition_point(|&hidden| hidden < visual),
281 )
282 }
283
284 pub fn is_frozen(&self, column: usize) -> bool {
285 self.frozen.get(column).copied().unwrap_or(false)
286 }
287
288 pub fn mirrored(&self) -> bool {
289 self.direction == LayoutDirection::RightToLeft
290 }
291
292 pub(crate) fn logical_delta(&self, delta: f32) -> f32 {
293 if self.mirrored() { -delta } else { delta }
294 }
295
296 fn mirror_x(&self, x: f32) -> f32 {
297 if self.mirrored() {
298 self.body.x + self.body.width - (x - self.body.x)
299 } else {
300 x
301 }
302 }
303
304 fn mirror_rect(&self, rect: Rect) -> Rect {
305 place_in_direction(rect, self.body, self.direction)
306 }
307
308 #[doc(hidden)]
310 pub fn content_bounds(&self, cell: Rect, start: f32, width: f32) -> Rect {
311 place_in_direction(
312 Rect::new(cell.x + start, cell.y, width, cell.height),
313 cell,
314 self.direction,
315 )
316 }
317
318 fn scrollable_band(&self, band: Rect) -> Rect {
319 let width = if self.frozen_count == self.visible_column_count() {
320 0.0
321 } else {
322 (band.width - self.frozen_width).max(0.0)
323 };
324 self.content_bounds(band, self.frozen_width, width)
325 }
326
327 pub fn scrollable_header(&self) -> Rect {
328 self.scrollable_band(self.header)
329 }
330
331 pub fn scrollable_body(&self) -> Rect {
332 self.scrollable_band(self.body)
333 }
334
335 pub(crate) fn frozen_body(&self) -> Rect {
336 self.content_bounds(self.body, 0.0, self.frozen_width)
337 }
338
339 pub fn column_clip(&self, column: usize, band: Rect) -> Rect {
341 if self.frozen_width == 0.0 {
342 return band;
343 }
344 let pane = if self.is_frozen(column) {
345 self.frozen_body()
346 } else {
347 self.scrollable_body()
348 };
349 Rect::new(pane.x, band.y, pane.width, band.height).intersect(band)
350 }
351
352 pub fn frozen_boundary(&self) -> Option<f32> {
353 (self.frozen_width > 0.0 && self.frozen_count < self.visible_column_count())
354 .then(|| self.mirror_x(self.header.x + self.frozen_width))
355 }
356
357 pub(crate) fn column_scroll_extent(&self, column: usize) -> Option<(f32, f32)> {
358 let bounds = self
359 .columns
360 .get(column)
361 .filter(|bounds| bounds.width > 0.0 && !self.is_frozen(column))?;
362 let viewport = self.mirror_rect(self.scrollable_body());
363 let bounds = self.mirror_rect(*bounds);
364 Some((bounds.x - viewport.x + self.horizontal.offset, bounds.width))
365 }
366
367 pub(crate) fn reveal_column(&self, column: usize) -> f32 {
368 let Some((start, width)) = self.column_scroll_extent(column) else {
369 return self.horizontal.offset;
370 };
371 let available = self.scrollable_body().width;
372 self.horizontal
373 .revealing(start, width.min(available), available)
374 .offset
375 }
376
377 pub(crate) fn column_drop(&self, from: usize, point: Point) -> Option<(usize, f32)> {
378 if !self.header.contains(point) {
379 return None;
380 }
381 let x = self.mirror_x(point.x);
382 let frozen = self.frozen_width > 0.0 && x < self.header.x + self.frozen_width;
383 let (start, end, pane) = if frozen {
384 (
385 0,
386 self.frozen_end,
387 Rect::new(
388 self.header.x,
389 self.header.y,
390 self.frozen_width,
391 self.header.height,
392 ),
393 )
394 } else {
395 (
396 self.frozen_end,
397 self.columns.len(),
398 self.mirror_rect(self.scrollable_header()),
399 )
400 };
401 let mut insertion = None;
402 for (visual, column) in self
403 .visual_columns()
404 .enumerate()
405 .skip(start)
406 .take(end - start)
407 {
408 if !self.is_column_visible(column) {
409 continue;
410 }
411 let bounds = self.mirror_rect(self.columns[column]);
412 let visible = if self.frozen_width == 0.0 {
413 bounds
414 } else {
415 bounds.intersect(pane)
416 };
417 if bounds.x >= pane.x + pane.width
418 || visible.width > 0.0 && x < visible.x + visible.width * 0.5
419 {
420 insertion = Some((visual, bounds.x));
421 break;
422 }
423 insertion = Some((visual + 1, bounds.x + bounds.width));
424 }
425 let (slot, marker) = insertion?;
426 let to = slot - usize::from(slot > from);
427 if from == to {
428 return None;
429 }
430 Some((to, self.mirror_x(marker.clamp(pane.x, pane.x + pane.width))))
431 }
432
433 pub(crate) fn column_at(&self, point: Point) -> Option<usize> {
434 self.visible_columns().find(|&column| {
435 self.columns[column]
436 .intersect(self.column_clip(column, self.header))
437 .contains(point)
438 })
439 }
440
441 pub(crate) fn body_column_at(&self, point: Point) -> Option<usize> {
442 if !self.body.contains(point) {
443 return None;
444 }
445 self.column_at(Point {
446 x: point.x,
447 y: self.header.y,
448 })
449 }
450
451 pub(crate) fn resize_at(&self, node: &Node, clip: Rect, point: Point) -> Option<usize> {
452 let visible = clip.intersect(self.header);
453 if !visible.contains(point) || !node.boolean("resizable-columns", false) {
454 return None;
455 }
456 self.columns
457 .iter()
458 .enumerate()
459 .filter_map(|(index, bounds)| {
460 let column = resizable_table_column(node, index)?;
461 let (min, max) = column_limits(column, self.header.width);
462 let bounds = self.mirror_rect(*bounds);
463 let edge = bounds.x + bounds.width;
464 let distance = (self.mirror_x(point.x) - edge).abs();
465 let pane = self.mirror_rect(self.column_clip(index, visible));
466 (max > min
467 && bounds.width > 0.0
468 && edge > pane.x
469 && edge <= pane.x + pane.width
470 && distance <= GRIP_RADIUS)
471 .then_some((index, distance))
472 })
473 .min_by(|(_, a), (_, b)| a.total_cmp(b))
474 .map(|(index, _)| index)
475 }
476
477 pub(crate) fn row_resize_at(
478 &self,
479 node: &Node,
480 layout: &LayoutNode,
481 point: Point,
482 ) -> Option<usize> {
483 let visible = self.rows_area().intersect(layout.clip);
484 if !visible.contains(point) || !node.boolean("resizable-rows", false) {
485 return None;
486 }
487 node.children
488 .iter()
489 .zip(&layout.children)
490 .enumerate()
491 .filter_map(|(slot, (row, item))| {
492 row.row_key?;
493 let end = item.bounds.y + item.bounds.height;
494 let distance = (end - point.y).abs();
495 (item.visible
496 && item.bounds.height > 0.0
497 && end > visible.y
498 && end <= visible.y + visible.height
499 && distance <= GRIP_RADIUS)
500 .then_some((slot, distance))
501 })
502 .min_by(|(_, a), (_, b)| a.total_cmp(b))
503 .map(|(slot, _)| slot)
504 }
505}