blib/lib/Term/Fabulous/Widget/Table.pm untested

filter: Statementstmt 0.0% 0 / 1576 Branchbran 0.0% 0 / 648 Conditioncond 0.0% 0 / 589 MC/DCmcdc 0.0% 0 / 324 Subroutinesub 0.0% 0 / 43 Podpod n/a totaltotal 0.0% 0 / 3180 CC 1 SCAR 6.9
CC
1
Cov
0%
BEGIN
2.0
BEGIN
2.0
BEGIN
2.0
CRAP 2.0
1 package Term::Fabulous::Widget::Table;
2  
3 use v5.32;
4 use warnings;
5 use feature 'signatures';
6 no warnings 'experimental::signatures';
7  
8 our $VERSION = '0.02';
9  
10 use Object::Pad 0.825;
11  
12 use Clay::UI::Role::Core::Preparable;
13 use Clay::UI::Role::Interaction::Focusable;
14 use Clay::UI::Role::Interaction::Hoverable;
15 use Term::Fabulous::Widget::Box;
16 use Term::Fabulous::Widget::ScrollBox;
17 use Term::Fabulous::Widget::Text;
18 use Term::Fabulous::Widget::TextField;
19 use Term::Fabulous::Widget::Table::Cell;
20 use Term::Fabulous::Widget::Table::ColumnChooser;
21 use Term::Fabulous::Widget::Table::Grid;
22 use Term::Fabulous::Widget::Table::HeaderView;
23 use Term::Fabulous::Widget::Table::Model;
24 use Term::Fabulous::Widget::Table::Pager;
25 use Term::Fabulous::Widget::Scrollbar;
26 use Term::Fabulous::Widget::Table::Toggle;
27  
28 class Term::Fabulous::Widget::Table
29 :isa(Term::Fabulous::Widget::Box)
30 :does(Clay::UI::Role::Interaction::Focusable)
31 :does(Clay::UI::Role::Interaction::Hoverable)
32 :does(Clay::UI::Role::Core::Preparable)
33 :strict(params)
34 {
35 use Clay::UI::Enum::Result;
36 use Feature::Compat::Try;
37 use Clay::XS qw(
38 sizing_fit sizing_fixed sizing_grow sizing_percent CLAY_LEFT_TO_RIGHT CLAY_TOP_TO_BOTTOM
39 CLAY__SIZING_TYPE_GROW CLAY__SIZING_TYPE_PERCENT
40 CLAY_ALIGN_X_LEFT CLAY_ALIGN_X_CENTER CLAY_ALIGN_X_RIGHT CLAY_ALIGN_Y_TOP
41 CLAY_TEXT_WRAP_WORDS CLAY_TEXT_WRAP_NEWLINES CLAY_TEXT_WRAP_NONE
42 CLAY_TEXT_ALIGN_LEFT CLAY_TEXT_ALIGN_CENTER CLAY_TEXT_ALIGN_RIGHT
43 );
44 use List::Util qw(any first max min none);
45 use Term::Fabulous::Viewport qw(reveal_range);
46 use Scalar::Util qw(blessed refaddr weaken);
47 use Time::HiRes ();
48 use Term::Fabulous::Check qw(boolean border_style describe non_negative_integer one_of optional string);
49 use Term::Fabulous::Enum::BorderStyle;
50 use Term::Fabulous::Event::CursorMove;
51 use Term::Fabulous::Event::Collapse;
52 use Term::Fabulous::Event::ColumnsChange;
53 use Term::Fabulous::Event::Expand;
54 use Term::Fabulous::Event::FilterChange;
55 use Term::Fabulous::Event::PageChange;
56 use Term::Fabulous::Event::RowActivate;
57 use Term::Fabulous::Event::SelectionChange;
58 use Term::Fabulous::Event::SortChange;
59 use Term::Fabulous::Termbox qw(TB_KEY_MOUSE_LEFT TB_KEY_MOUSE_RIGHT TB_MOD_MOTION TB_MOD_SHIFT TB_MOD_CTRL TB_MOD_ALT);
60 use Term::Fabulous::Widget::Table::Borders qw(resolve_borders);
61 use Term::Fabulous::Widget::Table::Filter;
62 use Term::Fabulous::Widget::Table::Style qw(style_hash merge_styles);
63  
64 use constant {
65 SELECT_COLUMN => '', # the column key of the selection column
66 EMPTY_LINE => "e\0", # the key of the line an empty view shows
67 MARK_CHECKED => '[x]',
68 MARK_UNCHECKED => '[ ]',
69 MARK_SOME => '[-]',
70 OPEN => "\x{25BE} ",
71 CLOSED => "\x{25B8} ",
72 LEAF => ' ',
73 SORT_UP => "\x{25B4}",
74 SORT_DOWN => "\x{25BE}",
75 INDENT => 2,
76 DEFAULT_PAGE_STEP => 10,
77 FALLBACK_BACKGROUND => [ 22, 25, 31, 255 ], # cells on nothing (see _base_background)
78 };
79  
80 my $CONTINUE = Clay::UI::Enum::Result->CONTINUE;
81 my $HANDLED = Clay::UI::Enum::Result->HANDLED;
82  
83 my @SELECTIONS = qw(none single multiple);
84 my %ALIGN_X = ( left => CLAY_ALIGN_X_LEFT, center => CLAY_ALIGN_X_CENTER, right => CLAY_ALIGN_X_RIGHT );
85 my %TEXT_ALIGN = ( left => CLAY_TEXT_ALIGN_LEFT, center => CLAY_TEXT_ALIGN_CENTER, right => CLAY_TEXT_ALIGN_RIGHT );
86 my %WRAP = ( words => CLAY_TEXT_WRAP_WORDS, newlines => CLAY_TEXT_WRAP_NEWLINES, none => CLAY_TEXT_WRAP_NONE );
87 my @LINE_PARAMS = qw(border_top border_right border_bottom border_left column_lines row_lines header_line);
88 my @NONE_IS_HIDDEN = ( none => Term::Fabulous::Enum::BorderStyle->Hidden ); # 'none' draws no line
89 my %NO_BOX_BORDER = map { $_ => 0 } qw(top right bottom left);
90 my @COLOR_PARAMS = qw(
91 text_color header_text_color header_background_color group_text_color group_background_color
92 cursor_color selected_color hover_color filter_background_color error_color muted_color line_color
93 );
94 my %COLOR_SLOT = (
95 text_color => 'text',
96 header_text_color => 'header.text',
97 header_background_color => 'header.background',
98 group_text_color => 'group.text',
99 group_background_color => 'group.background',
100 cursor_color => 'cursor',
101 selected_color => 'selected',
102 hover_color => 'hover',
103 filter_background_color => 'filter.background',
104 error_color => 'error',
105 muted_color => 'muted',
106 line_color => 'line.color',
107 );
108  
109 # ---------------------------------------------------------------------
110 # Parameters
111 # ---------------------------------------------------------------------
112  
113 # What the model is made of; handed over in ADJUST and dropped there.
114 field $initial_columns :param(columns) = [];
115 field $initial_rows :param(rows) = [];
116 field $initial_sort :param(sort) = [];
117 field $initial_group :param(group_by) = undef;
118 field $row_id :param = undef;
119 field $children_key :param = undef;
120 field $tree_expanded :param = 0;
121 field $initial_page_size :param(page_size) = 0;
122  
123 field $selection :param = 'none';
124 field $selection_column :param = undef;
125 field $_explicit_selection_column; # selection_column as the user set it, else undef
126 field $show_header :param(header) = 1;
127 field $filter_row :param = 0;
128 field $page_sizes :param = [ 10, 25, 50, 100 ];
129 field $show_pager :param(pager) = undef;
130 field $scrollbar :param = 1;
131 field $hover :param = 1;
132 field $tree_column :param = undef;
133 field $group_label :param = undef;
134 field $row_style :param = undef;
135 field $header_style :param = undef;
136 field $group_style :param = undef;
137 field $empty_text :param = 'No rows';
138 field $no_match_text :param = 'No rows match';
139 field $cell_padding :param = 1;
140 field $double_click_seconds :param = 0.4;
141  
142 field $border :param = 'Round';
143 field $border_top :param = undef;
144 field $border_right :param = undef;
145 field $border_bottom :param = undef;
146 field $border_left :param = undef;
147 field $column_lines :param = 'Solid';
148 field $row_lines :param = undef;
149 field $header_line :param = 'Solid';
150  
151 # ---------------------------------------------------------------------
152 # State
153 # ---------------------------------------------------------------------
154  
155 field $model :reader;
156 field %_line_style; # table-wide lines: border_* , column_lines, row_lines, header_line
157  
158 # The widgets of the table.
159 field $_header_row; # the header view and, with a scrollbar, a spacer as wide as it
160 field $_header_view;
161 field $_header_spacer;
162 field $_header_grid;
163 field $_body_row;
164 field $_body;
165 field $_body_grid;
166 field $_scrollbar;
167 field $_pager;
168 field $_chooser;
169  
170 # The header as built: a signature of what it was built from, and per
171 # grid column { cell, title, marker, mark } and { cell, field }.
172 field $_header_signature = '';
173 field @_header_cells;
174 field @_filter_cells;
175 field %_filter_text;
176 field %_filter_error;
177  
178 # The body as built: the signature of its columns, the lines by key
179 # (see _build_line) and the order of the grid's rows.
180 field $_body_signature = '';
181 field %_built;
182 field @_grid_keys;
183  
184 # The grid lines as last worked out, what they were worked out from,
185 # and a count that tells the lines' looks they changed. Changes of
186 # styles count in _style_revision.
187 field $_borders_signature = '';
188 field $_borders = [];
189 field $_borders_generation = 0;
190 field $_style_revision = 0;
191  
192 field %_row_style_of; # row id => style hash
193 field %_cell_style_of; # "id\0key" => style hash
194 field $_hover_key;
195 field $_header_cursor; # grid column index while the header has the keyboard, else undef
196 field @_last_press; # ( time, line key ) of the last left press on a line
197 field $_reveal_cursor = 0;
198 field $_shown_page = 0;
199  
200 method theme_family :common () {
201 return 'table';
202 }
203  
204 # The colors come from the theme's table family unless given. The
205 # table draws its frame itself, so it takes no bordered and has no
206 # border.enabled from the theme.
207 method themed_params :common () {
208 my %box = $class->SUPER::themed_params;
209 delete $box{bordered};
210 return (
211 %box,
212 stripe_color => [ 'stripe', 'normal', 'optional_color' ],
213 map { $_ => [ $COLOR_SLOT{$_}, 'normal', 'color' ] } @COLOR_PARAMS,
214 );
215 }
216  
217 sub BUILDARGS ( $class, %params ) {
218 _no_bordered($class) if exists $params{bordered};
219 return $class->SUPER::BUILDARGS(%params);
220 }
221  
222 sub _no_bordered ($owner) {
223 die( ( ref $owner || $owner )
224 . ": a table takes no bordered; it draws its frame itself, in the style of border (or border_top, border_right, border_bottom and border_left), and 'none' leaves a side out" );
225 }
226  
227 method bordered :override (@new) {
228 _no_bordered($self) if @new;
229 return $self->SUPER::bordered;
230 }
231  
232 # No Box border around the table's own frame.
233 method _bordered_sides :override () {
234 return \%NO_BOX_BORDER;
235 }
236  
237 # The cells, the pager and the scrollbar copy the colors
238 # (Term::Fabulous::Role::Themed).
239 method looks_changed (@names) {
240 $self->_colors_changed(@names);
241 return;
242 }
243  
244 ADJUST {
245 my $id = $self->id;
246 die "Term::Fabulous::Widget::Table: a table needs an id (its body keeps its scroll position by it)" unless defined $id;
247  
248 $self->_check_parameters;
249 $model = Term::Fabulous::Widget::Table::Model->new(
250 row_id => $row_id,
251 children_key => $children_key,
252 page_size => $initial_page_size,
253 expand_new => $tree_expanded,
254 );
255 $model->add_column($_) foreach @$initial_columns;
256 $model->set_rows($initial_rows);
257 $model->set_sort( _sort_spec($initial_sort) );
258 $model->group_by( ref $initial_group eq 'ARRAY' ? @$initial_group : $initial_group ) if defined $initial_group;
259 ( $initial_columns, $initial_rows, $initial_sort, $initial_group ) = ();
260  
261 $self->_build_frame;
262 $self->_listen;
263 $self->request_prepare;
264 }
265  
266 method _check_parameters () {
267 one_of( $self, selection => $selection, @SELECTIONS );
268 $_explicit_selection_column = boolean( $self, selection_column => $selection_column ) if defined $selection_column;
269 $selection_column = $_explicit_selection_column // ( $selection eq 'multiple' ? 1 : 0 );
270 $show_header = boolean( $self, header => $show_header );
271 $filter_row = boolean( $self, filter_row => $filter_row );
272 $scrollbar = boolean( $self, scrollbar => $scrollbar );
273 $hover = boolean( $self, hover => $hover );
274 $tree_expanded = boolean( $self, tree_expanded => $tree_expanded );
275 $show_pager = boolean( $self, pager => $show_pager ) if defined $show_pager;
276 die "Term::Fabulous::Widget::Table: page_sizes must be an array reference of positive integers, got " . describe($page_sizes)
277 unless ref $page_sizes eq 'ARRAY' && @$page_sizes && !grep { !defined || ref || !/\A[1-9][0-9]*\z/ } @$page_sizes;
278 $page_sizes = [ map { $_ + 0 } @$page_sizes ];
279  
280 foreach my $code ( [ group_label => $group_label ], [ row_style => $row_style ] ) {
281 die "Term::Fabulous::Widget::Table: $code->[0] must be a code reference, got " . describe( $code->[1] )
282 if defined $code->[1] && ref $code->[1] ne 'CODE';
283 }
284 $header_style = style_hash( $self, 'header_style', row => $header_style );
285 $group_style = style_hash( $self, 'group_style', row => $group_style );
286 $empty_text = string( $self, empty_text => $empty_text );
287 $no_match_text = string( $self, no_match_text => $no_match_text );
288 $cell_padding = $self->_padding($cell_padding);
289 die "Term::Fabulous::Widget::Table: double_click_seconds must be a number of at least 0, got " . describe($double_click_seconds)
290 unless defined $double_click_seconds && !ref $double_click_seconds && $double_click_seconds =~ /\A[0-9]*\.?[0-9]+\z/;
291  
292 my $outer = optional( \&border_style, $self, border => $border, @NONE_IS_HIDDEN );
293 my %line = (
294 border_top => $border_top,
295 border_right => $border_right,
296 border_bottom => $border_bottom,
297 border_left => $border_left,
298 column_lines => $column_lines,
299 row_lines => $row_lines,
300 header_line => $header_line,
301 );
302 foreach my $name (@LINE_PARAMS) {
303 my $value = $line{$name} // ( $name =~ /\Aborder_/ ? $outer : undef );
304 $_line_style{$name} = optional( \&border_style, $self, $name => $value, @NONE_IS_HIDDEN );
305 }
306 return;
307 }
308  
309 sub _sort_spec ($spec) {
310 die "Term::Fabulous::Widget::Table: sort must be an array reference of column keys or [ key, 'asc' or 'desc' ] pairs, got " . describe($spec)
311 unless ref $spec eq 'ARRAY';
312 return @$spec;
313 }
314  
315 method _padding ($padding) {
316 return { left => $padding, right => $padding, top => 0, bottom => 0 } if !ref $padding && defined $padding && $padding =~ /\A[0-9]+\z/;
317 die "Term::Fabulous::Widget::Table: cell_padding must be a number of cells or a hash reference of left, right, top and bottom, got " . describe($padding)
318 unless ref $padding eq 'HASH' && !grep { !/\A(?:left|right|top|bottom)\z/ } keys %$padding;
319 return { map { $_ => non_negative_integer( $self, "cell_padding $_", $padding->{$_} // 0 ) } qw(left right top bottom) };
320 }
321  
322 # ---------------------------------------------------------------------
323 # The frame of widgets: header, body with scrollbar, pager
324 # ---------------------------------------------------------------------
325  
326 method _build_frame () {
327 my $layout = $self->layout;
328 $self->layout(
329 {
330 %$layout,
331 layout_direction => CLAY_TOP_TO_BOTTOM,
332 sizing => { width => sizing_fit(), height => sizing_fit(), %{ $layout->{sizing} // {} } },
333 }
334 );
335  
336 my $id = $self->id;
337 $_body = Term::Fabulous::Widget::ScrollBox->new(
338 id => "$id/body",
339 vertical => 1,
340 horizontal => 1,
341 scrollbar => 0,
342 layout => { layout_direction => CLAY_TOP_TO_BOTTOM, sizing => { width => sizing_grow(), height => sizing_fit() } },
343 );
344 $_header_grid = Term::Fabulous::Widget::Table::Grid->new( layout => { sizing => { width => sizing_grow(), height => sizing_fit() } } );
345 $_body_grid = Term::Fabulous::Widget::Table::Grid->new( layout => { sizing => { width => sizing_grow(), height => sizing_fit() } }, share_columns_with => $_header_grid );
346 $_body->add_child($_body_grid);
347  
348 $_header_view = Term::Fabulous::Widget::Table::HeaderView->new(
349 follows => $_body,
350 layout => { sizing => { width => sizing_grow(), height => sizing_fit() } },
351 );
352 $_header_view->add_child($_header_grid);
353 $_header_row = Term::Fabulous::Widget::Box->new( layout => { layout_direction => CLAY_LEFT_TO_RIGHT, sizing => { width => sizing_grow(), height => sizing_fit() } } );
354 $_header_spacer = Term::Fabulous::Widget::Box->new( layout => { sizing => { width => sizing_fixed(1), height => sizing_grow() } } );
355 $_header_row->add_child($_header_view);
356  
357 $_body_row = Term::Fabulous::Widget::Box->new( layout => { layout_direction => CLAY_LEFT_TO_RIGHT, sizing => { width => sizing_grow(), height => sizing_fit() } } );
358 $_body_row->add_child($_body);
359 $_scrollbar = Term::Fabulous::Widget::Scrollbar->new(
360 follows => $_body,
361 thumb_color => $self->text_color,
362 track_color => $self->line_color,
363 layout => { sizing => { width => sizing_fixed(1), height => sizing_grow() } },
364 );
365  
366 $_pager = $self->_new_pager;
367 $self->_wire_pager;
368 $self->add_child( $_header_row, $_body_row );
369 return;
370 }
371  
372 method _new_pager () {
373 return Term::Fabulous::Widget::Table::Pager->new(
374 page_sizes => $page_sizes,
375 text_color => $self->text_color,
376 muted_color => $self->muted_color,
377 button_color => $self->look('pager.button'),
378 );
379 }
380  
381 # A new pager, for new page sizes or colors; prepare_layout shows it.
382 method _rebuild_pager () {
383 my $old = $_pager;
384 $_pager = $self->_new_pager;
385 $self->_wire_pager;
386 $self->remove_child($old);
387 return;
388 }
389  
390 method _wire_pager () {
391 weaken( my $weak = $self );
392 my %step = ( first => sub { 1 }, previous => sub { $weak->page - 1 }, next => sub { $weak->page + 1 }, last => sub { $weak->page_count } );
393 foreach my $name ( sort keys %step ) {
394 $_pager->button($name)->on( Activate => sub ($event) { $weak->_turn_page( $step{$name}->() ); return } );
395 }
396 $_pager->size_list->on( Change => sub ($event) { $weak->_change_page_size( $event->value ); return } );
397 return;
398 }
399  
400 # The grid columns: the selection column, then the visible columns.
401 method _grid_columns () {
402 my @columns = map { { key => $_->key, column => $_ } } $model->visible_columns;
403 unshift @columns, { key => SELECT_COLUMN, column => undef } if $selection_column && $selection ne 'none';
404 return @columns;
405 }
406  
407 # The column that shows the tree: tree_column, or the first visible one.
408 method _tree_column_key () {
409 return undef unless defined $model->children_key;
410 return $tree_column if defined $tree_column && $model->has_column($tree_column) && $model->is_column_visible($tree_column);
411 my ($first) = $model->visible_columns;
412 return defined $first ? $first->key : undef;
413 }
414  
415 # ---------------------------------------------------------------------
416 # Preparing the widgets for a frame
417 # ---------------------------------------------------------------------
418  
419 method _changed () {
420 $self->request_prepare;
421 return;
422 }
423  
424 # A change of looks or lines every cell may show.
425 method _restyle () {
426 $_style_revision++;
427 $self->request_prepare;
428 return;
429 }
430  
431 method prepare_layout () {
432 my $focus_in_cell = $self->_focus_in_cell;
433 my @grid_columns = $self->_grid_columns;
434 my @lines = $self->_body_lines;
435 $self->_prepare_width( \@grid_columns );
436 $self->_prepare_header( \@grid_columns );
437 $self->_prepare_body( \@grid_columns, \@lines );
438 $self->_dress( \@grid_columns, \@lines );
439 $self->_prepare_scrollbar;
440 $self->_prepare_pager;
441 $self->_prepare_scrolling;
442  
443 # A focused widget in a cell that was built again or removed takes
444 # the focus with it; the table takes it back.
445 $self->_focus_self if $focus_in_cell && !$self->_has_focus_within;
446 return;
447 }
448  
449 # Whether a widget inside one of the body's cells has the focus.
450 method _focus_in_cell () {
451 my $ui = $self->ui // return 0;
452 my $focused = $ui->interaction->get_focused_widget // return 0;
453 return refaddr($focused) != refaddr($self) && $self->_region_of($focused) eq 'body' ? 1 : 0;
454 }
455  
456 # The grids are as wide as their columns, unless a column grows (or is
457 # a share of the width): then they take the width of the table.
458 method _prepare_width ($grid_columns) {
459 my $stretch = any {
460 my $type = defined $_->{column} ? $_->{column}->width->{type} : -1;
461 $type == CLAY__SIZING_TYPE_GROW || $type == CLAY__SIZING_TYPE_PERCENT;
462 } @$grid_columns;
463 my $width = $stretch ? sizing_grow() : sizing_fit();
464 foreach my $widget ( $_header_row, $_header_view, $_header_grid, $_body_row, $_body, $_body_grid ) {
465 my $layout = $widget->layout;
466 next if _same( $layout->{sizing}{width}, $width );
467 $widget->layout( { %$layout, sizing => { %{ $layout->{sizing} // {} }, width => $width } } );
468 }
469 return;
470 }
471  
472 # The lines of the page, or the one line of an empty view.
473 method _body_lines () {
474 my @lines = $model->page_lines;
475 return @lines if @lines;
476 return { kind => 'empty', key => EMPTY_LINE };
477 }
478  
479 method _prepare_header ($grid_columns) {
480 my $signature = join "\0", $model->columns_revision, $show_header, $filter_row, $selection, map { $_->{key} } @$grid_columns;
481 return if $signature eq $_header_signature;
482 $_header_signature = $signature;
483 $_header_grid->clear_rows;
484 @_header_cells = @_filter_cells = ();
485 if ($show_header) {
486 @_header_cells = map { $self->_header_cell($_) } @$grid_columns;
487 $_header_grid->append_row( [ map { $_->{cell} } @_header_cells ] ) if @_header_cells;
488 }
489 if ($filter_row) {
490 @_filter_cells = map { $self->_filter_cell($_) } @$grid_columns;
491 $_header_grid->append_row( [ map { $_->{cell} } @_filter_cells ] ) if @_filter_cells;
492 }
493  
494 # Without header rows, a row no taller than nothing keeps the header
495 # grid, and with it the body, as wide as the columns.
496 $_header_grid->append_row( [ map { $self->_ruler_cell($_) } @$grid_columns ] ) unless @_header_cells || @_filter_cells;
497 return;
498 }
499  
500 method _ruler_cell ($grid_column) {
501 my $cell = $self->_new_cell( header => undef, $grid_column->{key}, $grid_column->{column} );
502 $cell->layout( { %{ $cell->layout }, sizing => { %{ $cell->layout->{sizing} }, height => sizing_fixed(0) } } );
503 return $cell;
504 }
505  
506 method _new_cell ( $part, $line_key, $column_key, $column ) {
507 my $align = defined $column ? ( $part eq 'header' ? $column->header_align : $column->align ) : 'left';
508 return Term::Fabulous::Widget::Table::Cell->new(
509 part => $part,
510 line_key => $line_key,
511 column_key => $column_key,
512 layout => {
513 sizing => { width => defined $column ? $column->width : sizing_fit(), height => sizing_fit() },
514 padding => {%$cell_padding},
515 child_alignment => { x => $ALIGN_X{$align}, y => CLAY_ALIGN_Y_TOP },
516 },
517 );
518 }
519  
520 method _header_cell ($grid_column) {
521 my $column = $grid_column->{column};
522 my $cell = $self->_new_cell( header => undef, $grid_column->{key}, $column );
523 unless ( defined $column ) {
524 my $mark = Term::Fabulous::Widget::Text->new( text => MARK_UNCHECKED );
525 $cell->add_child($mark);
526 return { cell => $cell, mark => $mark };
527 }
528 my $marker = Term::Fabulous::Widget::Text->new( text => '', wrap_mode => CLAY_TEXT_WRAP_NONE );
529 my $title;
530 my $content;
531 if ( defined $column->header ) {
532 $content = _widget_from( "column '" . $column->key . "' header", $column->header->($column) );
533 }
534 else {
535 $content = $title = Term::Fabulous::Widget::Text->new( text => $column->title, wrap_mode => $WRAP{ $column->wrap }, text_alignment => $TEXT_ALIGN{ $column->header_align } );
536 }
537 my $row = Term::Fabulous::Widget::Box->new;
538 $row->add_child( $content, $marker );
539 $cell->add_child($row);
540 return { cell => $cell, title => $title, marker => $marker };
541 }
542  
543 method _filter_cell ($grid_column) {
544 my $column = $grid_column->{column};
545 my $cell = $self->_new_cell( filter => undef, $grid_column->{key}, $column );
546 return { cell => $cell } unless defined $column && $column->filterable;
547 my $key = $column->key;
548 my $field = Term::Fabulous::Widget::TextField->new(
549 value => $_filter_text{$key} // '',
550 placeholder => "\x{2026}",
551 text_color => $self->text_color,
552 focus_background_color => $self->cursor_color,
553 layout => { sizing => { width => sizing_grow(0) } }, # one row high, as wide as the column
554 );
555 weaken( my $weak = $self );
556 $field->on( Change => sub ($event) { $weak->_filter_typed( $key, $event->value ); return } );
557 $field->on( Submit => sub ($event) { $weak->_focus_self; return } );
558 $cell->add_child($field);
559 return { cell => $cell, field => $field };
560 }
561  
562 sub _widget_from ( $what, $widget ) {
563 die "Term::Fabulous::Widget::Table: $what must return a widget, got " . describe($widget)
564 unless blessed $widget && ( $widget->DOES('Clay::UI::Role::Core::Element') || $widget->DOES('Clay::UI::Role::Core::TextNode') );
565 return $widget;
566 }
567  
568 # ---------------------------------------------------------------------
569 # The body: one grid row per line of the page
570 # ---------------------------------------------------------------------
571  
572 method _prepare_body ( $grid_columns, $lines ) {
573 my $signature = join "\0", $model->columns_revision, $selection, map { $_->{key} } @$grid_columns;
574 if ( $signature ne $_body_signature ) {
575 $_body_signature = $signature;
576 $_body_grid->clear_rows;
577 %_built = ();
578 @_grid_keys = ();
579 }
580  
581 my ( %wanted, %rebuilt );
582 foreach my $line (@$lines) {
583 my $key = $line->{key};
584 my $built = $_built{$key};
585 $wanted{$key} = 1;
586 if ( !defined $built || !$self->_still_fits( $built, $line ) ) {
587 $_built{$key} = $self->_build_line( $line, $grid_columns );
588 $rebuilt{$key} = 1 if defined $built;
589 next;
590 }
591 $built->{line} = $line;
592 $self->_refresh_row( $built, $grid_columns ) if $line->{kind} eq 'row' && $built->{revision} != $model->row_revision( $line->{id} );
593 }
594  
595 my @gone = grep { !$wanted{ $_grid_keys[$_] } || $rebuilt{ $_grid_keys[$_] } } 0 .. $#_grid_keys;
596 $_body_grid->remove_row($_) foreach reverse @gone;
597 my %gone_index = map { $_ => 1 } @gone;
598 @_grid_keys = map { $_grid_keys[$_] } grep { !$gone_index{$_} } 0 .. $#_grid_keys;
599 delete @_built{ grep { !$wanted{$_} } keys %_built };
600  
601 my %placed = map { $_ => 1 } @_grid_keys;
602 foreach my $line ( grep { !$placed{ $_->{key} } } @$lines ) {
603 my $built = $_built{ $line->{key} };
604 $built->{spanning} ? $_body_grid->append_spanning_row( $built->{cells}[0] ) : $_body_grid->append_row( $built->{cells} );
605 push @_grid_keys, $line->{key};
606 }
607  
608 my %index_of = map { $_grid_keys[$_] => $_ } 0 .. $#_grid_keys;
609 my @order = map { $index_of{ $_->{key} } } @$lines;
610 $_body_grid->reorder_rows( \@order ) if join( ',', @order ) ne join( ',', 0 .. $#order );
611 @_grid_keys = map { $_->{key} } @$lines;
612 return;
613 }
614  
615 # Whether a line built earlier can show the line now (its contents are
616 # refreshed separately).
617 method _still_fits ( $built, $line ) {
618 return 0 if $built->{kind} ne $line->{kind};
619 return 1 unless $line->{kind} eq 'row';
620 return $built->{depth} == $line->{depth} ? 1 : 0;
621 }
622  
623 method _build_line ( $line, $grid_columns ) {
624 return $self->_build_row( $line, $grid_columns ) if $line->{kind} eq 'row';
625 return $self->_build_group($line) if $line->{kind} eq 'group';
626 my $cell = $self->_new_cell( body => $line->{key}, undef, undef );
627 my $text = Term::Fabulous::Widget::Text->new( text => $model->is_filtered && $model->row_count ? $no_match_text : $empty_text );
628 $cell->add_child($text);
629 $cell->layout( { %{ $cell->layout }, sizing => { width => sizing_percent(1), height => sizing_fit() } } );
630 return { kind => 'empty', line => $line, spanning => 1, cells => [$cell], label => $text };
631 }
632  
633 # The hash a column's cell, update_cell and cell_style get.
634 method _cell_context ( $id, $column ) {
635 my $key = $column->key;
636 return {
637 value => $model->value_of( $id, $key ),
638 display => $model->display_of( $id, $key ),
639 row => $model->data_of($id),
640 id => $id,
641 column => $column,
642 table => $self,
643 };
644 }
645  
646 method _build_row ( $line, $grid_columns ) {
647 my $id = $line->{id};
648 my $tree_key = $self->_tree_column_key;
649 my %built = ( kind => 'row', line => $line, id => $id, depth => $line->{depth}, revision => $model->row_revision($id), cells => [], content => {}, text => {}, holder => {} );
650 foreach my $grid_column (@$grid_columns) {
651 my ( $key, $column ) = @{$grid_column}{qw(key column)};
652 my $cell = $self->_new_cell( body => $line->{key}, $key, $column );
653 push @{ $built{cells} }, $cell;
654 unless ( defined $column ) {
655 $built{mark} = Term::Fabulous::Widget::Text->new( text => MARK_UNCHECKED );
656 $cell->add_child( $built{mark} );
657 next;
658 }
659 my $content = $self->_cell_content( \%built, $column );
660 my $holder = $cell;
661 if ( defined $tree_key && $key eq $tree_key ) {
662 $holder = Term::Fabulous::Widget::Box->new( layout => { padding => { left => INDENT * $line->{depth} } } );
663 $built{toggle_box} = Term::Fabulous::Widget::Table::Toggle->new( line_key => $line->{key} );
664 $built{toggle} = Term::Fabulous::Widget::Text->new( text => LEAF, wrap_mode => CLAY_TEXT_WRAP_NONE );
665 $built{toggle_box}->add_child( $built{toggle} );
666 $holder->add_child( $built{toggle_box} );
667 $cell->add_child($holder);
668 }
669 $holder->add_child($content);
670 $built{holder}{$key} = $holder;
671 }
672 return \%built;
673 }
674  
675 # The widget showing a cell: the column's cell widget, or a Text.
676 method _cell_content ( $built, $column ) {
677 my $key = $column->key;
678 if ( defined $column->cell ) {
679 my $widget = _widget_from( "the cell of column '$key'", $column->cell->( $self->_cell_context( $built->{id}, $column ) ) );
680 delete $built->{text}{$key};
681 return $built->{content}{$key} = $widget;
682 }
683 my $text = Term::Fabulous::Widget::Text->new(
684 text => $model->display_of( $built->{id}, $key ),
685 wrap_mode => $WRAP{ $column->wrap },
686 text_alignment => $TEXT_ALIGN{ $column->align },
687 );
688 $built->{text}{$key} = $text;
689 return $built->{content}{$key} = $text;
690 }
691  
692 # A row whose data changed: texts are updated, cell widgets brought up
693 # to date by update_cell or built again.
694 method _refresh_row ( $built, $grid_columns ) {
695 $built->{revision} = $model->row_revision( $built->{id} );
696 foreach my $column ( map { $_->{column} } grep { defined $_->{column} } @$grid_columns ) {
697 my $key = $column->key;
698 if ( my $text = $built->{text}{$key} ) {
699 _set( $text, text => $model->display_of( $built->{id}, $key ) );
700 next;
701 }
702 if ( defined $column->update_cell ) {
703 $column->update_cell->( $built->{content}{$key}, $self->_cell_context( $built->{id}, $column ) );
704 next;
705 }
706 my $holder = $built->{holder}{$key};
707 my $old = $built->{content}{$key};
708 $holder->remove_child($old);
709 $holder->add_child( $self->_cell_content( $built, $column ) );
710 }
711 return;
712 }
713  
714 method _build_group ($line) {
715 my $cell = $self->_new_cell( body => $line->{key}, undef, undef );
716 $cell->layout( { %{ $cell->layout }, sizing => { width => sizing_percent(1), height => sizing_fit() } } );
717 my $holder = Term::Fabulous::Widget::Box->new( layout => { padding => { left => INDENT * $line->{depth} } } );
718 my $toggle = Term::Fabulous::Widget::Table::Toggle->new( line_key => $line->{key} );
719 my $glyph = Term::Fabulous::Widget::Text->new( text => OPEN, wrap_mode => CLAY_TEXT_WRAP_NONE );
720 $toggle->add_child($glyph);
721 $holder->add_child($toggle);
722 $cell->add_child($holder);
723 my %built = ( kind => 'group', line => $line, spanning => 1, cells => [$cell], holder => $holder, toggle => $glyph, toggle_box => $toggle, label_signature => '' );
724 $self->_refresh_group_label( \%built );
725 return \%built;
726 }
727  
728 # The label of a group header: group_label's text or widget, or
729 # "Title: value (count)".
730 method _refresh_group_label ($built) {
731 my $line = $built->{line};
732 my $signature = join "\0", $line->{display}, $line->{count};
733 return if $signature eq $built->{label_signature};
734 $built->{label_signature} = $signature;
735 my $label = defined $group_label ? $group_label->( $self->_group_context($line) ) : $self->_default_group_label($line);
736 if ( !ref $label && defined $built->{label} && $built->{label}->isa('Term::Fabulous::Widget::Text') ) {
737 _set( $built->{label}, text => $label );
738 return;
739 }
740 my $widget = ref $label ? _widget_from( 'group_label', $label ) : Term::Fabulous::Widget::Text->new( text => $label // '', bold => 1 );
741 $built->{holder}->remove_child( $built->{label} ) if defined $built->{label};
742 $built->{holder}->add_child($widget);
743 $built->{label} = $widget;
744 return;
745 }
746  
747 method _group_context ($line) {
748 return {
749 column => $model->column( $line->{column} ),
750 value => $line->{value},
751 display => $line->{display},
752 count => $line->{count},
753 path => [ @{ $line->{path} } ],
754 depth => $line->{depth},
755 ids => [ @{ $line->{ids} } ],
756 table => $self,
757 };
758 }
759  
760 method _default_group_label ($line) {
761 my $title = $model->column( $line->{column} )->title;
762 my $shown = length $line->{display} ? $line->{display} : '(empty)';
763 return "$title: $shown ($line->{count})";
764 }
765  
766 # ---------------------------------------------------------------------
767 # Dressing: colors, lines and markers of every cell
768 # ---------------------------------------------------------------------
769  
770 # Sets a property only when it differs, so preparing a table that did
771 # not change makes no further frame due.
772 sub _set ( $widget, $property, $value ) {
773 my $current = $widget->$property;
774 return if _same( $current, $value );
775 $widget->$property($value);
776 return;
777 }
778  
779 sub _same ( $left, $right ) {
780 return !defined $right unless defined $left;
781 return 0 unless defined $right;
782 return _flat($left) eq _flat($right);
783 }
784  
785 sub _flat ($value) {
786 return "$value" unless ref $value;
787 return 'S' . refaddr($value) if blessed $value;
788 return 'A' . join( "\x{1F}", map { _flat($_) } @$value ) if ref $value eq 'ARRAY';
789 return 'H' . join( "\x{1F}", map { "$_=" . _flat( $value->{$_} ) } sort keys %$value );
790 }
791  
792 # Whether the keyboard is in the table: the table or a widget of its
793 # body has the focus, not the header, the column chooser or the pager.
794 method _has_focus_within () {
795 my $ui = $self->ui // return 0;
796 my $interaction = $ui->interaction;
797 return 0 unless $interaction->has_focus_within($self);
798 return ( none { $interaction->has_focus_within($_) } grep { defined } $_header_view, $_chooser, $_pager ) ? 1 : 0;
799 }
800  
801 method _row_style_for ($id) {
802 my $dynamic = defined $row_style ? style_hash( $self, 'row_style result', row => $row_style->( $model->data_of($id), $id ) ) : {};
803 return merge_styles( $_row_style_of{$id}, $dynamic );
804 }
805  
806 method _cell_style_for ( $id, $column ) {
807 my $static = $_cell_style_of{ $id . "\0" . $column->key };
808 my $dynamic = defined $column->cell_style ? style_hash( $self, "column '" . $column->key . "' cell_style result", cell => $column->cell_style->( $self->_cell_context( $id, $column ) ) ) : {};
809 return merge_styles( $static, $dynamic );
810 }
811  
812 # Whether styles depend on the data of rows (row_style, a column's
813 # cell_style): then a change of a row may change its lines and looks.
814 method _styles_follow_data ($grid_columns) {
815 return 1 if defined $row_style;
816 return ( any { defined $_->{column} && defined $_->{column}->cell_style } @$grid_columns ) ? 1 : 0;
817 }
818  
819 # Colors, lines and marks of every cell. The grid lines are worked out
820 # again only when something they depend on changed; a body line is
821 # dressed again only when its look or the lines changed, so moving the
822 # cursor dresses two lines.
823 method _dress ( $grid_columns, $lines ) {
824 my $follows_data = $self->_styles_follow_data($grid_columns);
825 my @header_rows = ( ( @_header_cells ? [ \@_header_cells, 'header' ] : () ), ( @_filter_cells ? [ \@_filter_cells, 'filter' ] : () ) );
826 my $signature = join "\0", $model->columns_revision, $_style_revision, scalar @header_rows, scalar @$grid_columns,
827 map { $_->{key} . ( $follows_data && $_->{kind} eq 'row' ? ':' . $model->row_revision( $_->{id} ) : '' ) } @$lines;
828 if ( $signature ne $_borders_signature ) {
829 $_borders_signature = $signature;
830 $_borders = $self->_resolve_lines( $grid_columns, \@header_rows, $lines );
831 $_borders_generation++;
832 }
833  
834 foreach my $index ( 0 .. $#header_rows ) {
835 my ( $cells, $part ) = @{ $header_rows[$index] };
836 foreach my $column ( 0 .. $#$cells ) {
837 my $look = $part eq 'header' ? $self->_header_look( $column, $grid_columns->[$column] ) : $self->_filter_look( $cells->[$column], $grid_columns->[$column] );
838 $self->_dress_cell( $cells->[$column]{cell}, $look, $_borders->[$index][$column], \$cells->[$column]{dressed} );
839 }
840 }
841 $self->_mark_header($grid_columns) if @_header_cells;
842  
843 my $focused = $self->_has_focus_within;
844 my $cursor = $model->cursor;
845 my $data_index = 0;
846 foreach my $index ( 0 .. $#$lines ) {
847 my $line = $lines->[$index];
848 my $built = $_built{ $line->{key} };
849 my $state
850 = $focused && !defined $_header_cursor && defined $cursor && $cursor eq $line->{key} ? 'cursor'
851 : $line->{kind} eq 'row' && $model->is_selected( $line->{id} ) ? 'selected'
852 : $hover && defined $_hover_key && $_hover_key eq $line->{key} ? 'hover'
853 : '';
854 my $stripe = $line->{kind} eq 'row' && defined $self->stripe_color && $data_index++ % 2 ? 1 : 0;
855 my $look_key = join "\0", $_borders_generation, $state, $stripe, $self->_line_look_key($line);
856 next if defined $built->{look_key} && $built->{look_key} eq $look_key;
857 $built->{look_key} = $look_key;
858 $self->_dress_line( $built, $line, $grid_columns, $state, $stripe, $_borders->[ @header_rows + $index ] );
859 }
860 return;
861 }
862  
863 # What else a line's look depends on.
864 method _line_look_key ($line) {
865 return join "\0", $model->row_revision( $line->{id} ), $line->{has_children}, $line->{expanded}, $model->is_selected( $line->{id} ) if $line->{kind} eq 'row';
866 return join "\0", $line->{expanded}, $line->{count}, $line->{display} if $line->{kind} eq 'group';
867 return $model->is_filtered && $model->row_count ? 'no match' : 'empty';
868 }
869  
870 method _state_color ($state) {
871 return $state eq 'cursor' ? $self->cursor_color : $state eq 'selected' ? $self->selected_color : $state eq 'hover' ? $self->hover_color : undef;
872 }
873  
874 # The grid lines of the header rows and the lines.
875 method _resolve_lines ( $grid_columns, $header_rows, $lines ) {
876 my @border_lines = map {
877 { style => $header_style, cells => [ map { {} } @$grid_columns ] }
878 } @$header_rows;
879 foreach my $line (@$lines) {
880 if ( $line->{kind} eq 'row' ) {
881 my $id = $line->{id};
882 push @border_lines, {
883 style => $self->_row_style_for($id),
884 cells => [ map { defined $_->{column} ? $self->_cell_style_for( $id, $_->{column} ) : {} } @$grid_columns ],
885 };
886 next;
887 }
888 push @border_lines, { spanning => 1, style => $line->{kind} eq 'group' ? $group_style : {}, cells => [ {} ] };
889 }
890 return resolve_borders(
891 columns => scalar @$grid_columns,
892 header => scalar @$header_rows,
893 table => \%_line_style,
894 column_styles => [ map { defined $_->{column} ? $_->{column}->style : {} } @$grid_columns ],
895 lines => \@border_lines,
896 );
897 }
898  
899 method _dress_line ( $built, $line, $grid_columns, $state, $stripe, $borders ) {
900 my $state_color = $self->_state_color($state);
901 if ( $line->{kind} eq 'row' ) {
902 my $id = $line->{id};
903 my $row = $self->_row_style_for($id);
904 my @looks = map {
905 my $cell = defined $grid_columns->[$_]{column} ? $self->_cell_style_for( $id, $grid_columns->[$_]{column} ) : {};
906 $self->_body_look( $state_color // ( $stripe ? $self->stripe_color : undef ), $row, $cell, $grid_columns->[$_]{column}, defined $state_color );
907 } 0 .. $#$grid_columns;
908 $built->{dressed} //= [];
909 $self->_dress_cell( $built->{cells}[$_], $looks[$_], $borders->[$_], \$built->{dressed}[$_] ) foreach 0 .. $#looks;
910 $self->_mark_row( $built, $line, $grid_columns, \@looks );
911 return;
912 }
913 my $look = $line->{kind} eq 'group' ? $self->_group_look($state_color) : $self->_empty_look;
914 $self->_dress_cell( $built->{cells}[0], $look, $borders->[0], \$built->{dressed} );
915 if ( $line->{kind} eq 'group' ) {
916 $self->_refresh_group_label($built);
917 _set( $built->{toggle}, text => $line->{expanded} ? OPEN : CLOSED );
918 $self->_dress_text( $built->{toggle}, $look );
919 _set( $built->{toggle_box}, background_color => $look->{background_color} );
920 }
921 else {
922 _set( $built->{label}, text => $model->is_filtered && $model->row_count ? $no_match_text : $empty_text );
923 }
924 $self->_dress_text( $built->{label}, $look ) if defined $built->{label} && $built->{label}->isa('Term::Fabulous::Widget::Text');
925 return;
926 }
927  
928 method _header_look ( $index, $grid_column ) {
929 my $column = $grid_column->{column};
930 my $style = merge_styles( defined $column ? $column->header_style : {}, $header_style );
931 my $active = defined $_header_cursor && $_header_cursor == $index && $self->_has_focus_within;
932 return {
933 background_color => $active ? $self->cursor_color : $style->{background_color} // $self->header_background_color,
934 text_color => $style->{text_color} // $self->header_text_color,
935 bold => $style->{bold} // 1,
936 italic => $style->{italic} // 0,
937 underline => $style->{underline} // 0,
938 border_color => $style->{border_color} // $self->line_color,
939 };
940 }
941  
942 method _filter_look ( $cell, $grid_column ) {
943 my $column = $grid_column->{column};
944 if ( defined $cell->{field} ) {
945 my $error = defined $_filter_error{ $column->key };
946 _set( $cell->{field}, text_color => $error ? $self->error_color : $self->text_color );
947 }
948 return { background_color => $self->filter_background_color, border_color => $self->line_color };
949 }
950  
951 method _group_look ($state_color) {
952 my $style = $group_style;
953 return {
954 background_color => $state_color // $style->{background_color} // $self->group_background_color,
955 text_color => $style->{text_color} // $self->group_text_color,
956 bold => $style->{bold} // 1,
957 italic => $style->{italic} // 0,
958 underline => $style->{underline} // 0,
959 border_color => $style->{border_color} // $self->line_color,
960 };
961 }
962  
963 method _body_look ( $base_color, $row, $cell, $column, $state_wins ) {
964 my $column_style = defined $column ? $column->style : {};
965 my $look = merge_styles( $cell, $row, $column_style );
966 my $background = ( $state_wins ? $base_color : $look->{background_color} // $base_color ) // $self->_base_background;
967 return {
968 background_color => $background,
969 text_color => $look->{text_color} // $self->text_color,
970 bold => $look->{bold} // 0,
971 italic => $look->{italic} // 0,
972 underline => $look->{underline} // 0,
973 border_color => $look->{border_color} // $self->line_color,
974 };
975 }
976  
977 # Gives a cell its look and lines; $memo holds what it was given last
978 # time, so an unchanged cell costs one string comparison.
979 method _dress_cell ( $cell, $look, $border, $memo ) {
980 my $sides = $border->{sides};
981 my %properties = (
982 background_color => $look->{background_color},
983 border_color => $look->{border_color},
984 bordered => { map { $_ => $sides->{$_} ? 1 : 0 } qw(top right bottom left) },
985 border_corners => %{ $border->{corners} } ? $border->{corners} : undef,
986 outer_border_sides => $border->{outer},
987 map { ( "border_style_$_" => $sides->{$_} ) } qw(top right bottom left),
988 );
989 my $signature = join "\x{1E}", map { "$_=" . ( defined $properties{$_} ? _flat( $properties{$_} ) : '' ) } sort keys %properties;
990 return if defined $$memo && $$memo eq $signature;
991 $$memo = $signature;
992 $cell->$_( $properties{$_} ) foreach sort keys %properties;
993 return;
994 }
995  
996 method _dress_text ( $text, $look ) {
997 _set( $text, text_color => $look->{text_color} );
998 _set( $text, $_ => $look->{$_} // 0 ) foreach qw(bold italic underline);
999 return;
1000 }
1001  
1002 # The marks of a data row - the selection mark, the tree marker - and
1003 # the look of its texts.
1004 method _mark_row ( $built, $line, $grid_columns, $looks ) {
1005 my $tree_key = $self->_tree_column_key // "\0";
1006 foreach my $index ( 0 .. $#$grid_columns ) {
1007 my ( $key, $look ) = ( $grid_columns->[$index]{key}, $looks->[$index] );
1008 if ( $key eq SELECT_COLUMN ) {
1009 _set( $built->{mark}, text => $model->is_selected( $line->{id} ) ? MARK_CHECKED : MARK_UNCHECKED );
1010 $self->_dress_text( $built->{mark}, $look );
1011 next;
1012 }
1013 $self->_dress_text( $built->{text}{$key}, $look ) if defined $built->{text}{$key};
1014 next unless $key eq $tree_key && defined $built->{toggle};
1015 _set( $built->{toggle}, text => !$line->{has_children} ? LEAF : $line->{expanded} ? OPEN : CLOSED );
1016 $self->_dress_text( $built->{toggle}, $look );
1017 _set( $built->{toggle_box}, background_color => $look->{background_color} );
1018 }
1019 return;
1020 }
1021  
1022 method _empty_look () {
1023 return { background_color => $self->_base_background, text_color => $self->muted_color, border_color => $self->line_color, italic => 1 };
1024 }
1025  
1026 # The color of cells that have none of their own: what the table lies
1027 # on (background_below), so the cells blend in; a fixed dark color only
1028 # where there is none (Term::Fabulous::Static, no UI). Cells are always
1029 # painted: only painted cells receive the mouse.
1030 method _base_background () {
1031 return $self->background_below // FALLBACK_BACKGROUND;
1032 }
1033  
1034 method _mark_header ($grid_columns) {
1035 my @sort = @{ $model->sort_spec };
1036 foreach my $index ( 0 .. $#_header_cells ) {
1037 my $cell = $_header_cells[$index];
1038 my $look = $self->_header_look( $index, $grid_columns->[$index] );
1039 if ( defined $cell->{mark} ) {
1040 _set( $cell->{mark}, text => $self->_select_all_mark );
1041 $self->_dress_text( $cell->{mark}, $look );
1042 next;
1043 }
1044 my $key = $grid_columns->[$index]{key};
1045 my ($place) = grep { $sort[$_][0] eq $key } 0 .. $#sort;
1046 my $marker = !defined $place ? '' : ' ' . ( $sort[$place][1] eq 'asc' ? SORT_UP : SORT_DOWN ) . ( @sort > 1 ? $place + 1 : '' );
1047 _set( $cell->{marker}, text => $marker );
1048 $self->_dress_text( $cell->{marker}, $look );
1049 $self->_dress_text( $cell->{title}, $look ) if defined $cell->{title};
1050 }
1051 return;
1052 }
1053  
1054 method _select_all_mark () {
1055 my @ids = $model->filtered_row_ids;
1056 my $selected = grep { $model->is_selected($_) } @ids;
1057 return !@ids || !$selected ? MARK_UNCHECKED : $selected == @ids ? MARK_CHECKED : MARK_SOME;
1058 }
1059  
1060 # ---------------------------------------------------------------------
1061 # Scrollbar, pager, scrolling
1062 # ---------------------------------------------------------------------
1063  
1064 # The scrollbar right of the body, and a spacer as wide as it right of
1065 # the header, so that header and body are clipped at the same width.
1066 method _prepare_scrollbar () {
1067 _show_child( $_body_row, $_scrollbar, $scrollbar );
1068 _show_child( $_header_row, $_header_spacer, $scrollbar );
1069 return;
1070 }
1071  
1072 sub _show_child ( $parent, $child, $show ) {
1073 $parent->remove_child($child) unless $show;
1074 $parent->add_child($child) if $show && !$parent->has_child($child);
1075 return;
1076 }
1077  
1078 method _pager_shown () {
1079 return $show_pager // ( $model->page_size > 0 ? 1 : 0 );
1080 }
1081  
1082 method _prepare_pager () {
1083 if ( !$self->_pager_shown ) {
1084 $self->remove_child($_pager);
1085 return;
1086 }
1087 $self->add_child($_pager) unless $self->has_child($_pager);
1088 my $size = $model->page_size;
1089 my $total = $model->line_count;
1090 my $first = $size ? ( $model->page - 1 ) * $size + 1 : 1;
1091 my $last = $size ? min( $total, $first + $size - 1 ) : $total;
1092 $_pager->show( page => $model->page, page_count => $model->page_count, page_size => $size || $total || 1, first => $first, last => $last, total => $total );
1093 return;
1094 }
1095  
1096 # A new page starts at the top; a cursor that moved is scrolled into
1097 # view once the frame that lays its line out is drawn.
1098 method _prepare_scrolling () {
1099 my $ui = $self->ui // return;
1100 if ( $model->page != $_shown_page ) {
1101 $_shown_page = $model->page;
1102 $ui->scroll_to( $_body, { x => 0, y => 0 } );
1103 }
1104 return unless $_reveal_cursor;
1105 $_reveal_cursor = 0;
1106 weaken( my $weak = $self );
1107 $ui->after_draw( sub { $weak->_scroll_cursor_into_view if $weak } ) if $ui->can('after_draw');
1108 return;
1109 }
1110  
1111 # The rows of the body's content and viewport, how far it is scrolled
1112 # (Clay keeps a negative position) and where a line lies in the
1113 # content, in the last frame.
1114 method _line_box ($key) {
1115 my $ui = $self->ui // return undef;
1116 my $built = $_built{ $key // '' } // return undef;
1117 my $box = $ui->bounding_box( $built->{cells}[0] ) // return undef;
1118 my $state = $ui->scroll_state($_body) // return undef;
1119 my $body = $ui->bounding_box($_body) // return undef;
1120 my $offset = -$state->{position}{y};
1121 my $from = $box->{y} - $body->{y} + $offset;
1122 return { content => $state->{content}{height}, viewport => $state->{viewport}{height}, offset => $offset, from => $from, to => $from + $box->{height} };
1123 }
1124  
1125 method _scroll_cursor_into_view () {
1126 my $ui = $self->ui // return;
1127 my $box = $self->_line_box( $model->cursor ) // return;
1128 my $offset = reveal_range( @{$box}{qw(content viewport offset from to)} );
1129 $ui->scroll_to( $_body, { y => -$offset } ) if $offset != $box->{offset};
1130 return;
1131 }
1132  
1133 # How many lines of the page fit into the body's viewport, for PageUp
1134 # and PageDown.
1135 method _page_step () {
1136 my $ui = $self->ui // return DEFAULT_PAGE_STEP;
1137 my $state = $ui->scroll_state($_body) // return DEFAULT_PAGE_STEP;
1138 my @heights = grep { defined } map { my $built = $_built{$_}; defined $built ? ( $ui->bounding_box( $built->{cells}[0] ) // {} )->{height} : undef } @_grid_keys;
1139 return DEFAULT_PAGE_STEP unless @heights;
1140 my $average = ( List::Util::sum(@heights) / @heights ) || 1;
1141 return max( 1, int( $state->{viewport}{height} / $average ) - 1 );
1142 }
1143  
1144 # ---------------------------------------------------------------------
1145 # Input
1146 # ---------------------------------------------------------------------
1147  
1148 method _listen () {
1149 weaken( my $weak = $self );
1150 $self->on( KeyPress => sub ($event) { return $weak ? $weak->_on_key($event) : $CONTINUE } );
1151 $self->on( Mouse => sub ($event) { return $weak ? $weak->_on_mouse($event) : $CONTINUE } );
1152 $self->on( MouseMove => sub ($event) { $weak->_on_mouse_move($event) if $weak; return $CONTINUE } );
1153 foreach my $name (qw(OnFocus OnBlur)) {
1154 $self->on( $name => sub ($event) { $weak->_changed if $weak; return $CONTINUE } );
1155 }
1156 $self->on( OnHoverStopped => sub ($event) { $weak->_hover_line(undef) if $weak && refaddr( $event->target ) == refaddr($weak); return $CONTINUE } );
1157 return;
1158 }
1159  
1160 # Which part of the table a widget belongs to.
1161 method _region_of ($widget) {
1162 for ( my $node = $widget; defined $node; $node = $node->parent ) {
1163 my $address = refaddr $node;
1164 return 'body' if $address == refaddr($_body_row);
1165 return 'header' if $address == refaddr($_header_view);
1166 return 'pager' if $address == refaddr($_pager);
1167 return 'chooser' if defined $_chooser && $address == refaddr($_chooser);
1168 return 'table' if $address == refaddr($self);
1169 }
1170 return 'table';
1171 }
1172  
1173 # Whether a widget between $widget and the table takes input of its own
1174 # (a button or a field in a cell).
1175 # A widget without a background of its own is not hit by the mouse: a
1176 # click on such a button makes its cell the target, so the widgets of
1177 # the cell under the pointer count, too.
1178 method _inside_input ($event) {
1179 for ( my $node = $event->target; defined $node && refaddr($node) != refaddr($self); $node = $node->parent ) {
1180 return 1 if _takes_input($node);
1181 return $self->_input_under_pointer( $node, $event->x, $event->y ) if $node->isa('Term::Fabulous::Widget::Table::Cell');
1182 }
1183 return 0;
1184 }
1185  
1186 sub _takes_input ($widget) {
1187 return $widget->DOES('Clay::UI::Role::Interaction::Focusable') || $widget->DOES('Clay::UI::Role::Interaction::Pressable') ? 1 : 0;
1188 }
1189  
1190 method _input_under_pointer ( $widget, $x, $y ) {
1191 my $ui = $self->ui // return 0;
1192 return 0 unless $widget->can('children');
1193 foreach my $child ( @{ $widget->children } ) {
1194 my $box = $ui->bounding_box($child) // next;
1195 next unless $x >= $box->{x} && $x < $box->{x} + $box->{width} && $y >= $box->{y} && $y < $box->{y} + $box->{height};
1196 return 1 if _takes_input($child) || $self->_input_under_pointer( $child, $x, $y );
1197 }
1198 return 0;
1199 }
1200  
1201 method _on_key ($event) {
1202 my $name = $event->key_name // return $CONTINUE;
1203 my $region = $self->_region_of( $event->target );
1204 if ( $region eq 'header' ) {
1205 return $self->_on_filter_key( $event, $name );
1206 }
1207 return $CONTINUE unless $region eq 'table' || $region eq 'body';
1208 return $self->_on_header_key($name) if defined $_header_cursor;
1209 my $from_cell = $region eq 'body' && refaddr( $event->target ) != refaddr($self);
1210 return $CONTINUE unless $self->_on_body_key( $name, $from_cell );
1211 $self->_focus_self if $from_cell; # the keyboard follows the cursor out of the cell
1212 return $HANDLED;
1213 }
1214  
1215 method _on_filter_key ( $event, $name ) {
1216 if ( $name eq 'Down' ) {
1217 $self->_focus_self;
1218 return $HANDLED;
1219 }
1220 if ( $name eq 'Escape' ) {
1221 my ($cell) = grep { defined $_->{field} && refaddr( $_->{field} ) == refaddr( $event->target ) } @_filter_cells;
1222 return $CONTINUE unless defined $cell && length $cell->{field}->value;
1223 $cell->{field}->value('');
1224 $self->_filter_typed( $cell->{cell}->column_key, '' );
1225 return $HANDLED;
1226 }
1227 return $CONTINUE;
1228 }
1229  
1230 method _focus_self () {
1231 my $ui = $self->ui // return;
1232 $ui->interaction->set_focused_widget($self) if $self->can_focus;
1233 return;
1234 }
1235  
1236 # Keys on the rows. Returns whether the key was used. $from_cell: the
1237 # key comes from a widget inside a cell, which has used the keys it
1238 # wants; Space and Enter are left to it.
1239 method _on_body_key ( $name, $from_cell ) {
1240 my $cursor = $model->cursor;
1241 my $line = defined $cursor ? $model->line($cursor) : undef;
1242 my %move = (
1243 Up => -1,
1244 Down => 1,
1245 PageUp => -$self->_page_step,
1246 PageDown => $self->_page_step,
1247 );
1248 my $base = $name =~ s/\AShift\+//r;
1249 my $extend = $base ne $name && $selection eq 'multiple';
1250 if ( exists $move{$base} && ( $base eq $name || $extend ) ) {
1251 return $self->_enter_header if $base eq 'Up' && defined $line && $self->_is_first_on_page($cursor) && !$extend && $self->_header_usable;
1252 $self->_move_within_page( $move{$base}, $extend );
1253 return 1;
1254 }
1255 if ( ( $base eq 'Home' || $base eq 'End' ) && ( $base eq $name || $extend ) ) {
1256 my @lines = $model->page_lines;
1257 return 1 unless @lines;
1258 $self->_move_cursor( ( $base eq 'Home' ? $lines[0] : $lines[-1] )->{key}, extend => $extend );
1259 return 1;
1260 }
1261 my %jump = (
1262 'Ctrl+Home' => sub { $self->_move_cursor( $model->first_line_key ) },
1263 'Ctrl+End' => sub { $self->_move_cursor( $model->last_line_key ) },
1264 'Ctrl+PageUp' => sub { $self->_turn_page( $model->page - 1 ) },
1265 'Ctrl+PageDown' => sub { $self->_turn_page( $model->page + 1 ) },
1266 );
1267 if ( exists $jump{$name} ) {
1268 $jump{$name}->();
1269 return 1;
1270 }
1271 return $self->_select_all_by_user if $name eq 'Ctrl+A' && $selection eq 'multiple';
1272 return 0 unless defined $line;
1273  
1274 if ( $line->{kind} eq 'group' ) {
1275 return $self->_toggle_line( $line, !$line->{expanded} ) if $name eq 'Enter' || $name eq 'Space';
1276 return $self->_toggle_line( $line, 1 ) if $name eq '+' || ( $name eq 'Right' && !$line->{expanded} );
1277 return $self->_toggle_line( $line, 0 ) if $name eq '-' || ( $name eq 'Left' && $line->{expanded} );
1278 if ( $name eq 'Right' ) {
1279 $self->_move_cursor( $self->_line_after($cursor) );
1280 return 1;
1281 }
1282 return $self->_move_to_parent_group($line) if $name eq 'Left';
1283 return 0;
1284 }
1285 return 0 unless $line->{kind} eq 'row';
1286 if ( $name eq 'Enter' && !$from_cell ) {
1287 $self->fire_event( Term::Fabulous::Event::RowActivate->new( row_id => $line->{id}, row => $model->row( $line->{id} ) ) );
1288 return 1;
1289 }
1290 if ( $name eq 'Space' && !$from_cell ) {
1291 return $self->_toggle_selection_by_user( $line->{id} ) if $selection eq 'multiple';
1292 return $self->_select_by_user( $line->{id} ) if $selection eq 'single';
1293 return 0;
1294 }
1295 return $self->_toggle_line( $line, 1 ) if ( $name eq '+' || $name eq 'Right' ) && $line->{has_children} && !$line->{expanded};
1296 return $self->_toggle_line( $line, 0 ) if ( $name eq '-' || $name eq 'Left' ) && $line->{has_children} && $line->{expanded};
1297 if ( $name eq 'Right' && $line->{has_children} ) {
1298 $self->_move_cursor( $self->_line_after($cursor) );
1299 return 1;
1300 }
1301 return $self->_move_to_parent($line) if $name eq 'Left' && ( defined $model->parent_of( $line->{id} ) || $model->group_by );
1302 return 0;
1303 }
1304  
1305 method _header_usable () {
1306 return $show_header && @_header_cells ? 1 : 0;
1307 }
1308  
1309 method _is_first_on_page ($key) {
1310 my ($first) = $model->page_lines;
1311 return defined $first && $first->{key} eq $key ? 1 : 0;
1312 }
1313  
1314 method _line_after ($key) {
1315 my @lines = $model->page_lines;
1316 my $index = first { $lines[$_]{key} eq $key } 0 .. $#lines;
1317 return defined $index && $index < $#lines ? $lines[ $index + 1 ]{key} : $key;
1318 }
1319  
1320 method _move_within_page ( $steps, $extend ) {
1321 my @lines = $model->page_lines;
1322 return unless @lines;
1323 my $cursor = $model->cursor;
1324 my $index = first { $lines[$_]{key} eq $cursor } 0 .. $#lines;
1325 $index = max( 0, min( $#lines, ( $index // 0 ) + $steps ) );
1326 $self->_move_cursor( $lines[$index]{key}, extend => $extend );
1327 return;
1328 }
1329  
1330 method _move_to_parent ($line) {
1331 my $parent = $model->parent_of( $line->{id} );
1332 my $key = defined $parent ? Term::Fabulous::Widget::Table::Model::row_key($parent) : undef;
1333 if ( defined $key && defined $model->line_index($key) ) {
1334 $self->_move_cursor($key);
1335 return 1;
1336 }
1337 return $self->_move_to_parent_group($line);
1338 }
1339  
1340 # The nearest group header above the line, of a lower level for a group.
1341 method _move_to_parent_group ($line) {
1342 my @lines = $model->lines;
1343 my $index = $model->line_index( $line->{key} ) // return 1;
1344 my $limit = $line->{kind} eq 'group' ? $line->{depth} : 9**9;
1345 for ( my $at = $index - 1; $at >= 0; $at-- ) {
1346 next unless $lines[$at]{kind} eq 'group' && $lines[$at]{depth} < $limit;
1347 $self->_move_cursor( $lines[$at]{key} );
1348 return 1;
1349 }
1350 return 1;
1351 }
1352  
1353 # Moves the cursor as the user does: fires CursorMove, selects in
1354 # single mode, extends the selection with extend, turns the page.
1355 method _move_cursor ( $key, %options ) {
1356 return 0 unless defined $key;
1357 my $page_before = $model->page;
1358 my $anchor = $model->anchor // $model->cursor;
1359 my $moved = $model->set_cursor($key);
1360 $self->_after_cursor_moved( $moved, $page_before );
1361 my $id = Term::Fabulous::Widget::Table::Model::id_of_key($key);
1362 if ( $options{extend} && defined $anchor && defined $model->line_index($anchor) ) {
1363 $model->set_anchor($anchor);
1364 my @ids = grep { defined } map { Term::Fabulous::Widget::Table::Model::id_of_key($_) } $model->line_keys_between( $anchor, $key );
1365 $self->_select_by_user( $options{add} ? ( $model->selected_ids, @ids ) : @ids );
1366 }
1367 else {
1368 $model->set_anchor($key);
1369 $self->_select_by_user($id) if $selection eq 'single' && defined $id && $moved;
1370 }
1371 return $moved;
1372 }
1373  
1374 method _after_cursor_moved ( $moved, $page_before ) {
1375 return unless $moved || $model->page != $page_before;
1376 $_reveal_cursor = 1;
1377 $self->_changed;
1378 if ($moved) {
1379 my $line = $model->line( $model->cursor );
1380 $self->fire_event(
1381 Term::Fabulous::Event::CursorMove->new(
1382 row_id => $line->{kind} eq 'row' ? $line->{id} : undef,
1383 group_path => $line->{kind} eq 'group' ? $line->{path} : undef,
1384 )
1385 );
1386 }
1387 $self->_fire_page_change if $model->page != $page_before;
1388 return;
1389 }
1390  
1391 method _fire_page_change () {
1392 $self->fire_event( Term::Fabulous::Event::PageChange->new( page => $model->page, page_size => $model->page_size ) );
1393 return;
1394 }
1395  
1396 # Turns the page as the user does. The cursor goes to the page's first
1397 # line, as for any other move by the user: CursorMove and PageChange
1398 # fire, a range starts there, and in single mode the row is selected.
1399 method _turn_page ($page) {
1400 $page = max( 1, min( $page, $model->page_count ) );
1401 my ( $page_before, $cursor_before ) = ( $model->page, $model->cursor );
1402 return 0 unless $model->set_page($page);
1403 my $key = $model->cursor;
1404 my $moved = _same( $cursor_before, $key ) ? 0 : 1;
1405 $self->_after_cursor_moved( $moved, $page_before );
1406 $model->set_anchor($key);
1407 my $id = Term::Fabulous::Widget::Table::Model::id_of_key($key);
1408 $self->_select_by_user($id) if $selection eq 'single' && defined $id && $moved;
1409 return 1;
1410 }
1411  
1412 method _change_page_size ($size) {
1413 return unless $model->set_page_size($size);
1414 $_reveal_cursor = 1;
1415 $self->_changed;
1416 $self->_fire_page_change;
1417 return;
1418 }
1419  
1420 # Selection changes the user makes fire SelectionChange.
1421 method _select_by_user (@ids) {
1422 return $self->_selection_event( $model->set_selection(@ids) );
1423 }
1424  
1425 method _toggle_selection_by_user ($id) {
1426 return $self->_selection_event( $model->toggle_selected($id) );
1427 }
1428  
1429 method _select_all_by_user () {
1430 my @ids = $model->filtered_row_ids;
1431 my $all = @ids && !grep { !$model->is_selected($_) } @ids;
1432 return $self->_selection_event( $all ? $model->deselect(@ids) : $model->select(@ids) );
1433 }
1434  
1435 method _selection_event ( $added, $removed ) {
1436 return 1 unless @$added || @$removed;
1437 $self->_changed;
1438 $self->fire_event( Term::Fabulous::Event::SelectionChange->new( selected_ids => [ $model->selected_ids ], added_ids => $added, removed_ids => $removed ) );
1439 return 1;
1440 }
1441  
1442 # Opens or closes a group or tree row as the user does.
1443 method _toggle_line ( $line, $open ) {
1444 my $changed
1445 = $line->{kind} eq 'group'
1446 ? $model->set_group_collapsed( $line->{path}, $open ? 0 : 1 )
1447 : $model->set_expanded( $line->{id}, $open );
1448 return 1 unless $changed;
1449 $self->_changed;
1450 my $class = $open ? 'Term::Fabulous::Event::Expand' : 'Term::Fabulous::Event::Collapse';
1451 $self->fire_event(
1452 $class->new(
1453 row_id => $line->{kind} eq 'row' ? $line->{id} : undef,
1454 group_path => $line->{kind} eq 'group' ? $line->{path} : undef,
1455 )
1456 );
1457 return 1;
1458 }
1459  
1460 # The header has the keyboard: the header cursor picks a column.
1461 method _enter_header () {
1462 $_header_cursor = first { defined $_header_cells[$_]{marker} || defined $_header_cells[$_]{mark} } 0 .. $#_header_cells;
1463 $_header_cursor //= 0;
1464 $self->_changed;
1465 return 1;
1466 }
1467  
1468 method _leave_header () {
1469 $_header_cursor = undef;
1470 $_reveal_cursor = 1;
1471 $self->_changed;
1472 return $HANDLED;
1473 }
1474  
1475 method _on_header_key ($name) {
1476 my $last = $#_header_cells;
1477 return $self->_leave_header if $name eq 'Down' || $name eq 'Escape' || $last < 0;
1478 my %target = ( Left => $_header_cursor - 1, Right => $_header_cursor + 1, Home => 0, End => $last );
1479 if ( exists $target{$name} ) {
1480 $_header_cursor = max( 0, min( $last, $target{$name} ) );
1481 $self->_changed;
1482 return $HANDLED;
1483 }
1484 my @grid_columns = $self->_grid_columns;
1485 my $key = $grid_columns[$_header_cursor]{key} // return $CONTINUE;
1486 if ( $name eq 'Enter' || $name eq 'Space' ) {
1487 if ( $key eq SELECT_COLUMN ) {
1488 $self->_select_all_by_user;
1489 return $HANDLED;
1490 }
1491 $self->_sort_by_user( $key, $name eq 'Space' );
1492 return $HANDLED;
1493 }
1494 if ( $name eq 'c' ) {
1495 $self->open_column_chooser;
1496 return $HANDLED;
1497 }
1498 return $CONTINUE;
1499 }
1500  
1501 method _sort_by_user ( $key, $add ) {
1502 return unless $model->column($key)->sortable;
1503 return unless $model->cycle_sort( $key, $add );
1504 $_reveal_cursor = 1;
1505 $self->_changed;
1506 $self->fire_event( Term::Fabulous::Event::SortChange->new( sort => $model->sort_spec ) );
1507 return;
1508 }
1509  
1510 # ---------------------------------------------------------------------
1511 # Mouse
1512 # ---------------------------------------------------------------------
1513  
1514 # The table widget a mouse event is about: a toggle or a cell, and the
1515 # widget it hit. The scrollbar handles its own clicks.
1516 method _hit ($target) {
1517 for ( my $node = $target; defined $node && refaddr($node) != refaddr($self); $node = $node->parent ) {
1518 return ( toggle => $node ) if $node->isa('Term::Fabulous::Widget::Table::Toggle');
1519 return ( cell => $node ) if $node->isa('Term::Fabulous::Widget::Table::Cell');
1520 }
1521 return ();
1522 }
1523  
1524 method _on_mouse ($event) {
1525 my ( $kind, $widget ) = $self->_hit( $event->target );
1526 return $CONTINUE unless defined $kind;
1527 my $key = $event->key;
1528 my $motion = $event->modifiers & TB_MOD_MOTION;
1529 return $CONTINUE if $motion;
1530 if ( $key == TB_KEY_MOUSE_RIGHT ) {
1531 return $CONTINUE unless $kind eq 'cell' && $widget->part eq 'header';
1532 $self->open_column_chooser;
1533 return $HANDLED;
1534 }
1535 return $CONTINUE unless $key == TB_KEY_MOUSE_LEFT;
1536  
1537 if ( $kind eq 'toggle' ) {
1538 my $line = $model->line( $widget->line_key ) // return $HANDLED;
1539 $self->_move_cursor( $line->{key} );
1540 $self->_toggle_line( $line, !$line->{expanded} ) if $line->{kind} eq 'group' || $line->{has_children};
1541 return $HANDLED;
1542 }
1543 return $self->_click_header( $widget, $event ) if $widget->part eq 'header';
1544 return $CONTINUE unless $widget->part eq 'body';
1545 return $self->_click_line( $widget, $event );
1546 }
1547  
1548 method _click_header ( $cell, $event ) {
1549 $_header_cursor = undef;
1550 my $key = $cell->column_key // return $HANDLED;
1551 if ( $key eq SELECT_COLUMN ) {
1552 $self->_select_all_by_user;
1553 return $HANDLED;
1554 }
1555 my $add = $event->modifiers & ( TB_MOD_SHIFT | TB_MOD_CTRL | TB_MOD_ALT ) ? 1 : 0;
1556 $self->_sort_by_user( $key, $add );
1557 return $HANDLED;
1558 }
1559  
1560 method _click_line ( $cell, $event ) {
1561 my $line = $model->line( $cell->line_key // '' ) // return $HANDLED;
1562 my $now = Time::HiRes::time();
1563 my $double = @_last_press && $_last_press[1] eq $line->{key} && $now - $_last_press[0] <= $double_click_seconds;
1564 @_last_press = $double ? () : ( $now, $line->{key} );
1565 $_header_cursor = undef;
1566  
1567 if ( $line->{kind} eq 'group' ) {
1568 $self->_move_cursor( $line->{key} );
1569 $self->_toggle_line( $line, !$line->{expanded} );
1570 return $HANDLED;
1571 }
1572 my $in_input = $self->_inside_input($event);
1573 my $mods = $event->modifiers;
1574 my $id = $line->{id};
1575 if ( $in_input || $selection ne 'multiple' ) {
1576 $self->_move_cursor( $line->{key} );
1577 }
1578 elsif ( defined $cell->column_key && $cell->column_key eq SELECT_COLUMN || $mods & ( TB_MOD_CTRL | TB_MOD_ALT ) ) {
1579 $self->_move_cursor( $line->{key} );
1580 $self->_toggle_selection_by_user($id);
1581 }
1582 elsif ( $mods & TB_MOD_SHIFT ) {
1583 $self->_move_cursor( $line->{key}, extend => 1 );
1584 }
1585 else {
1586 $self->_move_cursor( $line->{key} );
1587 $self->_select_by_user($id);
1588 }
1589 $self->_select_by_user($id) if $selection eq 'single' && !$in_input;
1590 $self->fire_event( Term::Fabulous::Event::RowActivate->new( row_id => $id, row => $model->row($id) ) ) if $double && !$in_input;
1591 return $HANDLED;
1592 }
1593  
1594 method _on_mouse_move ($event) {
1595 return unless $hover;
1596 my ( $kind, $widget ) = $self->_hit( $event->target );
1597 my $key = defined $kind && $kind eq 'cell' && $widget->part eq 'body' ? $widget->line_key : undef;
1598 $self->_hover_line($key);
1599 return;
1600 }
1601  
1602 method _hover_line ($key) {
1603 return if _same( $key, $_hover_key );
1604 $_hover_key = $key;
1605 $self->_changed;
1606 return;
1607 }
1608  
1609 # ---------------------------------------------------------------------
1610 # The filter row
1611 # ---------------------------------------------------------------------
1612  
1613 method _filter_typed ( $key, $text ) {
1614 my $error = $self->_apply_filter_text( $key, $text );
1615 $self->fire_event( Term::Fabulous::Event::FilterChange->new( column => $key, text => $text, error => $error ) );
1616 return;
1617 }
1618  
1619 # Applies the expression of a filter field; returns the error message,
1620 # or undef.
1621 method _apply_filter_text ( $key, $text ) {
1622 my $column = $model->column($key);
1623 $_filter_text{$key} = $text;
1624 delete $_filter_error{$key};
1625 my $filter;
1626 try {
1627 $filter = Term::Fabulous::Widget::Table::Filter->parse( $text, column => $key, type => $column->type, on => $column->filter_on );
1628 }
1629 catch ($error) {
1630 $_filter_error{$key} = $error =~ s/\ATerm::Fabulous::Widget::Table::Filter: //r =~ s/\s+\z//r;
1631 }
1632 $model->set_filter( "column:$key" => $filter );
1633 $model->expand_to_matches;
1634 $_reveal_cursor = 1;
1635 $self->_changed;
1636 return $_filter_error{$key};
1637 }
1638  
1639 # =====================================================================
1640 # Public methods
1641 # =====================================================================
1642  
1643 # --- Rows ------------------------------------------------------------
1644  
1645 method rows (@new) {
1646 return $model->rows unless @new;
1647 $model->set_rows( $new[0] );
1648 $self->_rows_changed;
1649 return $self;
1650 }
1651  
1652 method _rows_changed () {
1653 %_row_style_of = map { $_ => $_row_style_of{$_} } grep { $model->has_row($_) } keys %_row_style_of;
1654 %_cell_style_of = map { $_ => $_cell_style_of{$_} } grep { $model->has_row( ( split /\0/, $_, 2 )[0] ) } keys %_cell_style_of;
1655 $model->expand_to_matches;
1656 $self->_changed;
1657 return;
1658 }
1659  
1660 method add_row ( $row, %options ) {
1661 my ($id) = $model->add_rows( [$row], %options );
1662 $self->_rows_changed;
1663 return $id;
1664 }
1665  
1666 method add_rows ( $rows, %options ) {
1667 my @ids = $model->add_rows( $rows, %options );
1668 $self->_rows_changed;
1669 return @ids;
1670 }
1671  
1672 method update_row ( $id, $changes ) {
1673 $model->update_row( $id, $changes );
1674 $self->_data_changed;
1675 return $self;
1676 }
1677  
1678 method replace_row ( $id, $row ) {
1679 $model->replace_row( $id, $row );
1680 $self->_data_changed;
1681 return $self;
1682 }
1683  
1684 method set_value ( $id, $key, $value ) {
1685 $model->column($key);
1686 $model->set_value( $id, $key, $value );
1687 $self->_data_changed;
1688 return $self;
1689 }
1690  
1691 # A row's data changed: in a filtered tree, a row that matches now is
1692 # shown, like after any change of the filters.
1693 method _data_changed () {
1694 $model->expand_to_matches;
1695 $self->_changed;
1696 return;
1697 }
1698  
1699 method value ( $id, $key ) {
1700 return $model->value_of( $self->_check_row($id), $key );
1701 }
1702  
1703 method display_value ( $id, $key ) {
1704 return $model->display_of( $self->_check_row($id), $key );
1705 }
1706  
1707 method _check_row ($id) {
1708 die "Term::Fabulous::Widget::Table: there is no row with the id " . describe($id) unless $model->has_row($id);
1709 return $id;
1710 }
1711  
1712 method remove_rows (@ids) {
1713 $model->remove_rows(@ids);
1714 $self->_rows_changed;
1715 return $self;
1716 }
1717  
1718 method remove_row ($id) {
1719 return $self->remove_rows($id);
1720 }
1721  
1722 method clear_rows () {
1723 $model->clear_rows;
1724 $self->_rows_changed;
1725 return $self;
1726 }
1727  
1728 method row ($id) { return $model->row($id) }
1729 method has_row ($id) { return $model->has_row($id) }
1730 method row_ids () { return $model->row_ids }
1731 method row_count () { return $model->row_count }
1732 method parent_of ($id) { return $model->parent_of($id) }
1733 method children_of ($id) { return $model->children_of($id) }
1734 method filtered_row_ids () { return $model->filtered_row_ids }
1735  
1736 method page_row_ids () {
1737 return map { $_->{id} } grep { $_->{kind} eq 'row' } $model->page_lines;
1738 }
1739  
1740 # --- Columns ---------------------------------------------------------
1741  
1742 method columns () { return $model->columns }
1743 method column ($key) { return $model->column($key) }
1744 method column_keys () { return $model->column_keys }
1745  
1746 method add_column ( $spec, %options ) {
1747 my @unknown = grep { $_ ne 'index' } sort keys %options;
1748 die "Term::Fabulous::Widget::Table: add_column does not accept @unknown (known: index)" if @unknown;
1749 my $column = $model->add_column( $spec, $options{index} );
1750 $self->_changed;
1751 return $column;
1752 }
1753  
1754 method remove_column ($key) {
1755 delete $_filter_text{$key};
1756 delete $_filter_error{$key};
1757 delete $_cell_style_of{$_} foreach grep { ( split /\0/, $_, 2 )[1] eq $key } keys %_cell_style_of;
1758 $model->remove_column($key);
1759 $self->_changed;
1760 return $self;
1761 }
1762  
1763 method move_column ( $key, $index ) {
1764 $model->move_column( $key, $index );
1765 $self->_changed;
1766 return $self;
1767 }
1768  
1769 method update_column ( $key, %changes ) {
1770 die "Term::Fabulous::Widget::Table: update_column cannot change the key of a column" if exists $changes{key};
1771 my $column = $model->replace_column( $model->column($key)->with(%changes) );
1772 $self->_changed;
1773 return $column;
1774 }
1775  
1776 method visible_columns () {
1777 return map { $_->key } $model->visible_columns;
1778 }
1779  
1780 method is_column_visible ($key) {
1781 return $model->is_column_visible($key);
1782 }
1783  
1784 method show_columns (@keys) {
1785 $model->set_column_visible( $_, 1 ) foreach @keys;
1786 $self->_changed;
1787 return $self;
1788 }
1789  
1790 method hide_columns (@keys) {
1791 $model->set_column_visible( $_, 0 ) foreach @keys;
1792 $self->_changed;
1793 return $self;
1794 }
1795  
1796 method set_visible_columns (@keys) {
1797 $model->set_visible_columns(@keys);
1798 $self->_changed;
1799 return $self;
1800 }
1801  
1802 method open_column_chooser () {
1803 return $self if defined $_chooser;
1804 weaken( my $weak = $self );
1805 $_chooser = Term::Fabulous::Widget::Table::ColumnChooser->new(
1806 columns => [ map { [ $_->key, length $_->title ? $_->title : $_->key, $model->is_column_visible( $_->key ) ] } $model->columns ],
1807 text_color => $self->text_color,
1808 muted_color => $self->muted_color,
1809 background_color => $self->group_background_color,
1810 bordered => 1,
1811 border_color => $self->text_color,
1812 border_style => Term::Fabulous::Enum::BorderStyle->Round,
1813 on_toggle => sub ( $key, $visible ) { $weak->_chooser_toggled( $key, $visible ) if $weak },
1814 on_close => sub () { $weak->close_column_chooser if $weak },
1815 );
1816 $self->add_child($_chooser);
1817 $_chooser->focus_first;
1818 return $self;
1819 }
1820  
1821 method close_column_chooser () {
1822 return $self unless defined $_chooser;
1823 my $closing = $_chooser;
1824 undef $_chooser;
1825 my $refocus = $self->_focus_is_inside($closing);
1826 $self->remove_child($closing);
1827 $self->_focus_self if $refocus;
1828 return $self;
1829 }
1830  
1831 method _focus_is_inside ($widget) {
1832 my $ui = $self->ui // return 0;
1833 return $ui->interaction->has_focus_within($widget);
1834 }
1835  
1836 method is_column_chooser_open () {
1837 return defined $_chooser ? 1 : 0;
1838 }
1839  
1840 method _chooser_toggled ( $key, $visible ) {
1841 $model->set_column_visible( $key, $visible );
1842 $self->_changed;
1843 $self->fire_event( Term::Fabulous::Event::ColumnsChange->new( visible => [ $self->visible_columns ] ) );
1844 return;
1845 }
1846  
1847 # --- Sorting ---------------------------------------------------------
1848  
1849 method sort_spec () {
1850 return $model->sort_spec;
1851 }
1852  
1853 method sort_by (@spec) {
1854 $_reveal_cursor = 1 if $model->set_sort(@spec);
1855 $self->_changed;
1856 return $self;
1857 }
1858  
1859 method clear_sort () {
1860 return $self->sort_by;
1861 }
1862  
1863 # --- Filtering -------------------------------------------------------
1864  
1865 method filter ( $name, $filter ) {
1866 die "Term::Fabulous::Widget::Table: filter names starting with 'column:' belong to the filter row; use filter_text"
1867 if defined $name && !ref $name && $name =~ /\Acolumn:/;
1868 $model->set_filter( $name, $filter );
1869 $model->expand_to_matches;
1870 $_reveal_cursor = 1;
1871 $self->_changed;
1872 return $self;
1873 }
1874  
1875 method remove_filter ($name) {
1876 $model->remove_filter($name);
1877 $model->expand_to_matches;
1878 $self->_changed;
1879 return $self;
1880 }
1881  
1882 method filter_names () {
1883 return grep { !/\Acolumn:/ } $model->filter_names;
1884 }
1885  
1886 method clear_filters () {
1887 %_filter_text = %_filter_error = ();
1888 _set( $_->{field}, value => '' ) foreach grep { defined $_->{field} } @_filter_cells;
1889 $model->clear_filters;
1890 $self->_changed;
1891 return $self;
1892 }
1893  
1894 method search (@new) {
1895 return $model->search unless @new;
1896 $model->search( $new[0] );
1897 $model->expand_to_matches;
1898 $_reveal_cursor = 1;
1899 $self->_changed;
1900 return $self;
1901 }
1902  
1903 method filter_text ( $key, @new ) {
1904 $model->column($key);
1905 return $_filter_text{$key} // '' unless @new;
1906 my $text = string( $self, filter_text => $new[0] // '' );
1907 my ($cell) = grep { defined $_->{field} && $_->{cell}->column_key eq $key } @_filter_cells;
1908 _set( $cell->{field}, value => $text ) if defined $cell;
1909 $self->_apply_filter_text( $key, $text );
1910 return $self;
1911 }
1912  
1913 method filter_error ($key) {
1914 $model->column($key);
1915 return $_filter_error{$key};
1916 }
1917  
1918 method filter_row (@new) {
1919 return $filter_row unless @new;
1920 $filter_row = boolean( $self, filter_row => $new[0] );
1921 $self->_changed;
1922 return $filter_row;
1923 }
1924  
1925 # --- Grouping --------------------------------------------------------
1926  
1927 method group_by (@keys) {
1928 return $model->group_by unless @keys;
1929 $model->group_by(@keys);
1930 $self->_changed;
1931 return $self;
1932 }
1933  
1934 method ungroup () {
1935 $model->group_by(undef);
1936 $self->_changed;
1937 return $self;
1938 }
1939  
1940 method is_group_expanded (@path) {
1941 return $model->is_group_collapsed(@path) ? 0 : 1;
1942 }
1943  
1944 method expand_group (@path) {
1945 $model->set_group_collapsed( \@path, 0 );
1946 $self->_changed;
1947 return $self;
1948 }
1949  
1950 method collapse_group (@path) {
1951 $model->set_group_collapsed( \@path, 1 );
1952 $self->_changed;
1953 return $self;
1954 }
1955  
1956 method expand_all_groups () {
1957 $model->set_all_groups_collapsed(0);
1958 $self->_changed;
1959 return $self;
1960 }
1961  
1962 method collapse_all_groups () {
1963 $model->set_all_groups_collapsed(1);
1964 $self->_changed;
1965 return $self;
1966 }
1967  
1968 # --- Tree ------------------------------------------------------------
1969  
1970 method is_expanded ($id) { return $model->is_expanded($id) }
1971  
1972 method expand (@ids) {
1973 $model->set_expanded( $_, 1 ) foreach @ids;
1974 $self->_changed;
1975 return $self;
1976 }
1977  
1978 method collapse (@ids) {
1979 $model->set_expanded( $_, 0 ) foreach @ids;
1980 $self->_changed;
1981 return $self;
1982 }
1983  
1984 method expand_all () {
1985 $model->set_all_expanded(1);
1986 $self->_changed;
1987 return $self;
1988 }
1989  
1990 method collapse_all () {
1991 $model->set_all_expanded(0);
1992 $self->_changed;
1993 return $self;
1994 }
1995  
1996 # --- Pages -----------------------------------------------------------
1997  
1998 method page (@new) {
1999 return $model->page unless @new;
2000 $model->set_page( $new[0] );
2001 $self->_changed;
2002 return $self;
2003 }
2004  
2005 method page_count () { return $model->page_count }
2006  
2007 method page_size (@new) {
2008 return $model->page_size unless @new;
2009 $model->set_page_size( $new[0] );
2010 $self->_changed;
2011 return $self;
2012 }
2013  
2014 method next_page () { return $self->page( min( $model->page + 1, $model->page_count ) ) }
2015 method previous_page () { return $self->page( max( $model->page - 1, 1 ) ) }
2016  
2017 # --- Selection -------------------------------------------------------
2018  
2019 # Changing the mode keeps what the new mode allows of the selection:
2020 # none of it for 'none', the first selected row for 'single'.
2021 method selection (@new) {
2022 return $selection unless @new;
2023 my $mode = one_of( $self, selection => $new[0], @SELECTIONS );
2024 $selection = $mode;
2025 my @kept = $mode eq 'none' ? () : $model->selected_ids;
2026 @kept = @kept[ 0 .. 0 ] if $mode eq 'single' && @kept > 1;
2027 $model->set_selection(@kept);
2028 $selection_column = $_explicit_selection_column // ( $mode eq 'multiple' ? 1 : 0 );
2029 $self->_changed;
2030 return $selection;
2031 }
2032  
2033 method selection_column (@new) {
2034 return $selection_column unless @new;
2035 $_explicit_selection_column = $selection_column = boolean( $self, selection_column => $new[0] );
2036 $self->_changed;
2037 return $selection_column;
2038 }
2039  
2040 method row_id (@new) {
2041 return $model->row_id unless @new;
2042 return $model->set_row_id( $new[0] );
2043 }
2044  
2045 method children_key (@new) {
2046 return $model->children_key unless @new;
2047 $model->set_children_key( $new[0] );
2048 $_body_signature = '';
2049 $self->_changed;
2050 return $model->children_key;
2051 }
2052  
2053 method tree_expanded (@new) {
2054 return $model->expand_new unless @new;
2055 return $model->expand_new( boolean( $self, tree_expanded => $new[0] ) );
2056 }
2057  
2058 method _selectable (@ids) {
2059 die "Term::Fabulous::Widget::Table: the table has selection => 'none'; nothing can be selected" if @ids && $selection eq 'none';
2060 die "Term::Fabulous::Widget::Table: a table with selection => 'single' selects one row at most" if @ids > 1 && $selection eq 'single';
2061 $self->_check_row($_) foreach @ids;
2062 return @ids;
2063 }
2064  
2065 method selected_ids () { return $model->selected_ids }
2066  
2067 method selected_rows () {
2068 return map { $model->row($_) } $model->selected_ids;
2069 }
2070 method is_selected ($id) { return $model->is_selected($id) }
2071  
2072 method set_selection (@ids) {
2073 $model->set_selection( $self->_selectable(@ids) );
2074 $self->_changed;
2075 return $self;
2076 }
2077  
2078 method select (@ids) {
2079 return $self->set_selection(@ids) if $selection eq 'single';
2080 $model->select( $self->_selectable(@ids) );
2081 $self->_changed;
2082 return $self;
2083 }
2084  
2085 method deselect (@ids) {
2086 $model->deselect( map { $self->_check_row($_) } @ids );
2087 $self->_changed;
2088 return $self;
2089 }
2090  
2091 method select_all () {
2092 die "Term::Fabulous::Widget::Table: select_all needs selection => 'multiple'" unless $selection eq 'multiple';
2093 $model->select( $model->filtered_row_ids );
2094 $self->_changed;
2095 return $self;
2096 }
2097  
2098 method clear_selection () {
2099 $model->set_selection;
2100 $self->_changed;
2101 return $self;
2102 }
2103  
2104 # --- Cursor ----------------------------------------------------------
2105  
2106 method cursor (@new) {
2107 unless (@new) {
2108 return Term::Fabulous::Widget::Table::Model::id_of_key( $model->cursor );
2109 }
2110 my $key = Term::Fabulous::Widget::Table::Model::row_key( $self->_check_row( $new[0] ) );
2111 die "Term::Fabulous::Widget::Table: row '$new[0]' is not shown (filtered out, or below a collapsed row or group)" unless defined $model->line_index($key);
2112 $model->set_cursor($key);
2113 $model->set_anchor($key);
2114 $_reveal_cursor = 1;
2115 $self->_changed;
2116 return $self;
2117 }
2118  
2119 method cursor_group () {
2120 my $line = $model->line( $model->cursor // return undef ) // return undef;
2121 return $line->{kind} eq 'group' ? [ @{ $line->{path} } ] : undef;
2122 }
2123  
2124 method scroll_to_row ($id) {
2125 return $self->cursor($id);
2126 }
2127  
2128 # --- Styles ----------------------------------------------------------
2129  
2130 method set_row_style ( $id, $style ) {
2131 $self->_check_row($id);
2132 my $checked = style_hash( $self, 'row style', row => $style );
2133 %$checked ? ( $_row_style_of{$id} = $checked ) : delete $_row_style_of{$id};
2134 $self->_restyle;
2135 return $self;
2136 }
2137  
2138 method row_style_of ($id) {
2139 return { %{ $_row_style_of{ $self->_check_row($id) } // {} } };
2140 }
2141  
2142 method set_cell_style ( $id, $key, $style ) {
2143 $self->_check_row($id);
2144 $model->column($key);
2145 my $checked = style_hash( $self, 'cell style', cell => $style );
2146 %$checked ? ( $_cell_style_of{ $id . "\0" . $key } = $checked ) : delete $_cell_style_of{ $id . "\0" . $key };
2147 $self->_restyle;
2148 return $self;
2149 }
2150  
2151 method cell_style_of ( $id, $key ) {
2152 $self->_check_row($id);
2153 $model->column($key);
2154 return { %{ $_cell_style_of{ $id . "\0" . $key } // {} } };
2155 }
2156  
2157 # --- Appearance ------------------------------------------------------
2158  
2159 method _color_property ( $name, @new ) {
2160 return @new ? $self->set_look( $name => $new[0] ) : $self->look_value($name);
2161 }
2162  
2163 # The parts that copy the table's colors take them again.
2164 method _colors_changed (@names) {
2165 my %changed = map { $_ => 1 } @names;
2166 $_scrollbar->thumb_color( $self->text_color ) if $changed{text_color};
2167 $_scrollbar->track_color( $self->line_color ) if $changed{line_color};
2168 $self->_rebuild_pager if $changed{text_color} || $changed{muted_color};
2169 $_header_signature = '' if $changed{text_color} || $changed{cursor_color}; # the filter fields take them when built
2170 $self->_restyle;
2171 return;
2172 }
2173  
2174 method text_color (@new) { return $self->_color_property( text_color => @new ) }
2175 method header_text_color (@new) { return $self->_color_property( header_text_color => @new ) }
2176 method header_background_color (@new) { return $self->_color_property( header_background_color => @new ) }
2177 method group_text_color (@new) { return $self->_color_property( group_text_color => @new ) }
2178 method group_background_color (@new) { return $self->_color_property( group_background_color => @new ) }
2179 method cursor_color (@new) { return $self->_color_property( cursor_color => @new ) }
2180 method selected_color (@new) { return $self->_color_property( selected_color => @new ) }
2181 method hover_color (@new) { return $self->_color_property( hover_color => @new ) }
2182 method filter_background_color (@new) { return $self->_color_property( filter_background_color => @new ) }
2183 method error_color (@new) { return $self->_color_property( error_color => @new ) }
2184 method muted_color (@new) { return $self->_color_property( muted_color => @new ) }
2185 method line_color (@new) { return $self->_color_property( line_color => @new ) }
2186  
2187 method stripe_color (@new) {
2188 return @new ? $self->set_look( stripe_color => $new[0] ) : $self->look_value('stripe_color');
2189 }
2190  
2191 # The table's own background is the color of its cells (see
2192 # _base_background).
2193 method background_color :override (@new) {
2194 my $color = $self->SUPER::background_color(@new);
2195 $self->_restyle if @new;
2196 return $color;
2197 }
2198  
2199 method _line_property ( $name, @new ) {
2200 return $_line_style{$name} unless @new;
2201 $_line_style{$name} = optional( \&border_style, $self, $name => $new[0], @NONE_IS_HIDDEN );
2202 $self->_restyle;
2203 return $_line_style{$name};
2204 }
2205  
2206 method border_top (@new) { return $self->_line_property( border_top => @new ) }
2207 method border_right (@new) { return $self->_line_property( border_right => @new ) }
2208 method border_bottom (@new) { return $self->_line_property( border_bottom => @new ) }
2209 method border_left (@new) { return $self->_line_property( border_left => @new ) }
2210 method column_lines (@new) { return $self->_line_property( column_lines => @new ) }
2211 method row_lines (@new) { return $self->_line_property( row_lines => @new ) }
2212 method header_line (@new) { return $self->_line_property( header_line => @new ) }
2213  
2214 # Sets the four sides of the frame; reads the style they share, or
2215 # undef when they differ.
2216 method border (@new) {
2217 if (@new) {
2218 $self->_line_property( $_ => $new[0] ) foreach qw(border_top border_right border_bottom border_left);
2219 return $_line_style{border_top};
2220 }
2221 my %names = map { ( defined $_ ? $_->name : '' ) => 1 } @_line_style{qw(border_top border_right border_bottom border_left)};
2222 return keys %names == 1 ? $_line_style{border_top} : undef;
2223 }
2224  
2225 method header (@new) {
2226 return $show_header unless @new;
2227 $show_header = boolean( $self, header => $new[0] );
2228 $self->_changed;
2229 return $show_header;
2230 }
2231  
2232 method scrollbar (@new) {
2233 return $scrollbar unless @new;
2234 $scrollbar = boolean( $self, scrollbar => $new[0] );
2235 $self->_changed;
2236 return $scrollbar;
2237 }
2238  
2239 method hover (@new) {
2240 return $hover unless @new;
2241 $hover = boolean( $self, hover => $new[0] );
2242 $_hover_key = undef unless $hover;
2243 $self->_restyle;
2244 return $hover;
2245 }
2246  
2247 method pager (@new) {
2248 return $show_pager unless @new;
2249 $show_pager = defined $new[0] ? boolean( $self, pager => $new[0] ) : undef;
2250 $self->_changed;
2251 return $show_pager;
2252 }
2253  
2254 method empty_text (@new) {
2255 return $empty_text unless @new;
2256 $empty_text = string( $self, empty_text => $new[0] );
2257 $self->_restyle;
2258 return $empty_text;
2259 }
2260  
2261 method no_match_text (@new) {
2262 return $no_match_text unless @new;
2263 $no_match_text = string( $self, no_match_text => $new[0] );
2264 $self->_restyle;
2265 return $no_match_text;
2266 }
2267  
2268 method _callback_property ( $name, $field_ref, @new ) {
2269 return $$field_ref unless @new;
2270 die "Term::Fabulous::Widget::Table: $name must be a code reference or undef, got " . describe( $new[0] )
2271 if defined $new[0] && ref $new[0] ne 'CODE';
2272 $$field_ref = $new[0];
2273 $_->{label_signature} = '' foreach grep { $_->{kind} eq 'group' } values %_built; # labels are made again
2274 $self->_restyle;
2275 return $$field_ref;
2276 }
2277  
2278 method row_style (@new) { return $self->_callback_property( row_style => \$row_style, @new ) }
2279 method group_label (@new) { return $self->_callback_property( group_label => \$group_label, @new ) }
2280  
2281 method header_style (@new) {
2282 return {%$header_style} unless @new;
2283 $header_style = style_hash( $self, 'header_style', row => $new[0] );
2284 $self->_restyle;
2285 return {%$header_style};
2286 }
2287  
2288 method group_style (@new) {
2289 return {%$group_style} unless @new;
2290 $group_style = style_hash( $self, 'group_style', row => $new[0] );
2291 $self->_restyle;
2292 return {%$group_style};
2293 }
2294  
2295 method cell_padding (@new) {
2296 return {%$cell_padding} unless @new;
2297 $cell_padding = $self->_padding( $new[0] );
2298 $_header_signature = $_body_signature = ''; # every cell is built again
2299 $self->_changed;
2300 return {%$cell_padding};
2301 }
2302  
2303 method tree_column (@new) {
2304 return $tree_column unless @new;
2305 die "Term::Fabulous::Widget::Table: tree_column must be a column key or undef, got " . describe( $new[0] ) if ref $new[0];
2306 $model->column( $new[0] ) if defined $new[0];
2307 $tree_column = $new[0];
2308 $_body_signature = '';
2309 $self->_changed;
2310 return $tree_column;
2311 }
2312  
2313 method page_sizes (@new) {
2314 return [@$page_sizes] unless @new;
2315 die "Term::Fabulous::Widget::Table: page_sizes must be an array reference of positive integers, got " . describe( $new[0] )
2316 unless ref $new[0] eq 'ARRAY' && @{ $new[0] } && !grep { !defined || ref || !/\A[1-9][0-9]*\z/ } @{ $new[0] };
2317 $page_sizes = [ map { $_ + 0 } @{ $new[0] } ];
2318 $self->_rebuild_pager;
2319 $self->_changed;
2320 return [@$page_sizes];
2321 }
2322  
2323 # --- KDL -------------------------------------------------------------
2324  
2325 method layout_properties :common () {
2326 return (
2327 $class->SUPER::layout_properties,
2328 selection => 'scalar',
2329 selection_column => 'boolean',
2330 page_size => 'scalar',
2331 pager => 'boolean',
2332 filter_row => 'boolean',
2333 header => 'boolean',
2334 scrollbar => 'boolean',
2335 hover => 'boolean',
2336 row_id => 'scalar',
2337 children_key => 'scalar',
2338 tree_expanded => 'boolean',
2339 tree_column => 'scalar',
2340 empty_text => 'scalar',
2341 no_match_text => 'scalar',
2342 column => \&_parse_column,
2343 sort => \&_parse_sort,
2344 group_by => \&_parse_group_by,
2345 lines => \&_parse_lines,
2346 cell_padding => \&_parse_cell_padding,
2347 page_sizes => \&_parse_page_sizes,
2348 );
2349 }
2350  
2351 # A table's cells come from its columns, not from child widgets.
2352 method apply_layout_node :override ($node) {
2353 my @widgets = grep { Term::Fabulous::Role::CanParseLayout::is_widget_node_name( $_->name ) } $node->children->@*;
2354 die "Term::Fabulous::Widget::Table: a table takes no child widgets (found '" . $widgets[0]->name . "'); its cells come from its columns and rows" if @widgets;
2355 return $self->SUPER::apply_layout_node($node);
2356 }
2357  
2358 # How rows are read comes first, then the columns, so every other
2359 # property can name them.
2360 method apply_layout_settings :override (@settings) {
2361 my %rank = ( row_id => 0, children_key => 0, column => 1, sort => 3, group_by => 3 );
2362 my @ordered = map { $_->[1] } sort { $a->[0] <=> $b->[0] } map { [ $rank{ $_->[0] } // 2, $_ ] } @settings;
2363 return $self->SUPER::apply_layout_settings(@ordered);
2364 }
2365  
2366 my @COLUMN_PROPERTIES = qw(title type width align header_align wrap sortable filterable filter_on compare visible);
2367 my @STYLE_PROPERTIES = qw(text_color background_color bold italic underline border_color border_left border_right row_lines);
2368  
2369 method _parse_column ($kid) {
2370 my @args = map { $_->as_perl } $kid->args->@*;
2371 die "Term::Fabulous::Widget::Table: layout property 'column' needs the column key as its one argument" unless @args == 1 && defined $args[0] && !ref $args[0];
2372 my %props = map { $_->[0] => $_->[1]->as_perl } $kid->props->@*;
2373 my %allowed = map { $_ => 1 } @COLUMN_PROPERTIES;
2374 my @unknown = grep { !$allowed{$_} } sort keys %props;
2375 die "Term::Fabulous::Widget::Table: layout property 'column' does not accept @unknown (allowed: @COLUMN_PROPERTIES)" if @unknown;
2376 my %styles;
2377 foreach my $child ( $kid->children->@* ) {
2378 my $name = $child->name;
2379 die "Term::Fabulous::Widget::Table: a column node holds only 'style' and 'header_style' nodes, got '$name'"
2380 unless $name eq 'style' || $name eq 'header_style';
2381 $styles{$name} = $self->kdl_properties( $child, @STYLE_PROPERTIES );
2382 }
2383 $self->add_column( { key => $args[0], %props, %styles } );
2384 return;
2385 }
2386  
2387 method _parse_sort ($kid) {
2388 my @args = map { $_->as_perl } $kid->args->@*;
2389 die "Term::Fabulous::Widget::Table: layout property 'sort' takes a column key and optionally asc or desc"
2390 unless ( @args == 1 || @args == 2 ) && !$kid->props->@* && !$kid->children->@*;
2391 $self->sort_by( @{ $model->sort_spec }, [ $args[0], $args[1] // 'asc' ] );
2392 return;
2393 }
2394  
2395 method _parse_group_by ($kid) {
2396 my @keys = map { $_->as_perl } $kid->args->@*;
2397 die "Term::Fabulous::Widget::Table: layout property 'group_by' takes one or more column keys" unless @keys && !$kid->props->@* && !$kid->children->@*;
2398 $self->group_by(@keys);
2399 return;
2400 }
2401  
2402 method _parse_lines ($kid) {
2403 my %line_of = ( top => 'border_top', right => 'border_right', bottom => 'border_bottom', left => 'border_left', columns => 'column_lines', rows => 'row_lines', header => 'header_line' );
2404 my $props = $self->kdl_properties( $kid, 'frame', ( sort keys %line_of ), 'color' );
2405 $self->border( $props->{frame} ) if exists $props->{frame};
2406 $self->_line_property( $line_of{$_} => $props->{$_} ) foreach grep { exists $props->{$_} } sort keys %line_of;
2407 $self->line_color( $props->{color} ) if exists $props->{color};
2408 return;
2409 }
2410  
2411 method _parse_cell_padding ($kid) {
2412 my @args = $kid->args->@*;
2413 $self->cell_padding( @args ? $self->kdl_argument($kid)->as_perl : $self->kdl_properties( $kid, qw(left right top bottom) ) );
2414 return;
2415 }
2416  
2417 method _parse_page_sizes ($kid) {
2418 my @sizes = map { $_->as_perl } $kid->args->@*;
2419 die "Term::Fabulous::Widget::Table: layout property 'page_sizes' takes one or more numbers" unless @sizes && !$kid->props->@* && !$kid->children->@*;
2420 $self->page_sizes( \@sizes );
2421 return;
2422 }
2423  
2424 # --- Widgets ---------------------------------------------------------
2425  
2426 # The widget a cell shows (its column's cell widget or a Text), once
2427 # the row is on the page and the table was prepared.
2428 method cell_widget ( $id, $key ) {
2429 my $built = $_built{ Term::Fabulous::Widget::Table::Model::row_key($id) } // return undef;
2430 return $built->{content}{$key};
2431 }
2432  
2433 method body () { return $_body }
2434 method pager_widget () { return $_pager }
2435 }
2436  
2437 1;
2438  
2439 __END__