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

filter: Statementstmt 0.0% 0 / 785 Branchbran 0.0% 0 / 310 Conditioncond 0.0% 0 / 239 MC/DCmcdc 0.0% 0 / 144 Subroutinesub 0.0% 0 / 13 Podpod n/a totaltotal 0.0% 0 / 1491 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::Model;
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 Term::Fabulous::Widget::Table::Column;
13 use Term::Fabulous::Widget::Table::Filter;
14  
15 class Term::Fabulous::Widget::Table::Model :strict(params) {
16 use List::Util qw(any first max min uniq);
17 use POSIX ();
18 use Scalar::Util qw(blessed refaddr);
19 use Term::Fabulous::Check qw(describe one_of);
20 use Term::Fabulous::Widget::Table::Value qw(is_blank);
21  
22 # A line of the view is a data row or a group header. Its key names it
23 # across rebuilds: "r" or "g", a NUL, then the row id or the group key.
24 use constant { ROW_PREFIX => "r\0", GROUP_PREFIX => "g\0" };
25  
26 field $row_id :param :reader = undef; # a key, a code reference, or undef for ids of our own
27 field $children_key :param :reader = undef; # the key of nested rows, or undef for flat data
28 field $page_size :param :reader = 0;
29 field $expand_new :param = 0; # whether rows added with children start expanded
30  
31 # Columns, in order, and the keys of the hidden ones.
32 field @_columns;
33 field %_column_by_key;
34 field %_hidden;
35  
36 # Rows by id: { id, data, parent, children => [ ids ], revision }; the
37 # data order is the order of @_roots and of every children list.
38 field %_row;
39 field @_roots;
40 field $_next_id = 1;
41 field %_rank; # row id => its place in data order; empty until asked for
42  
43 # Per row id: a copy of the data for callbacks, raw values and display
44 # texts by column key. Dropped when the row or the column changes.
45 field %_copy;
46 field %_raw;
47 field %_display;
48 field %_id_of_copy; # refaddr of a copy => row id
49 field %_search_text; # row id => the folded display texts of the visible columns
50  
51 # How the rows are shown.
52 field @_sort; # [ key, 1 or -1 ]
53 field %_filter; # name => Filter
54 field @_filter_names; # in the order they were set
55 field $_search = '';
56 field @_group_by; # column keys, outermost first
57 field %_collapsed_group; # group key => 1
58 field %_expanded; # row id => 1
59 field $_page = 1;
60  
61 # Selection and cursor.
62 field %_selected;
63 field $_cursor; # a line key, or undef
64 field $_cursor_index; # the cursor's place in the view before the last change
65 field $_anchor; # the line key a range selection extends from
66  
67 # The computed view, undef when anything it depends on changed.
68 field $_view;
69  
70 # Counts every change of the data, the columns or the view state, so
71 # the table can tell whether its widgets are up to date.
72 field $revision :reader = 0;
73 field $columns_revision :reader = 0;
74  
75 ADJUST {
76 die "Term::Fabulous::Widget::Table::Model: row_id must be a column key or a code reference, got " . describe($row_id)
77 if defined $row_id && !( ref $row_id eq 'CODE' || ( !ref $row_id && length $row_id ) );
78 die "Term::Fabulous::Widget::Table::Model: children_key must be a non-empty string, got " . describe($children_key)
79 if defined $children_key && ( ref $children_key || !length $children_key );
80 $page_size = _page_size($page_size);
81 $expand_new = $expand_new ? 1 : 0;
82 }
83  
84 # How rows are read can change only while there are none.
85 method _check_no_rows ($what) {
86 die "Term::Fabulous::Widget::Table::Model: $what can only be changed while there are no rows" if %_row;
87 return;
88 }
89  
90 method set_row_id ($new) {
91 $self->_check_no_rows('row_id');
92 die "Term::Fabulous::Widget::Table::Model: row_id must be a column key or a code reference, got " . describe($new)
93 if defined $new && !( ref $new eq 'CODE' || ( !ref $new && length $new ) );
94 $row_id = $new;
95 return $row_id;
96 }
97  
98 method set_children_key ($new) {
99 $self->_check_no_rows('children_key');
100 die "Term::Fabulous::Widget::Table::Model: children_key must be a non-empty string, got " . describe($new)
101 if defined $new && ( ref $new || !length $new );
102 $children_key = $new;
103 $self->_changed;
104 return $children_key;
105 }
106  
107 method expand_new (@new) {
108 return $expand_new unless @new;
109 $expand_new = $new[0] ? 1 : 0;
110 return $expand_new;
111 }
112  
113 sub _page_size ($size) {
114 die "Term::Fabulous::Widget::Table::Model: page_size must be a non-negative integer (0 for no pages), got " . describe($size)
115 unless defined $size && !ref $size && $size =~ /\A[0-9]+\z/;
116 return $size + 0;
117 }
118  
119 # A change the view depends on.
120 method _changed () {
121 $revision++;
122 $_cursor_index = $_view->{index_of}{$_cursor} if defined $_view && defined $_cursor;
123 undef $_view;
124 return;
125 }
126  
127 # A change of what is shown of the view (page, selection, cursor).
128 method _touched () {
129 $revision++;
130 return;
131 }
132  
133 # =====================================================================
134 # Columns
135 # =====================================================================
136  
137 method _column_from ($spec) {
138 return $spec if blessed $spec && $spec->isa('Term::Fabulous::Widget::Table::Column');
139 die "Term::Fabulous::Widget::Table::Model: a column must be a hash reference of column parameters or a Term::Fabulous::Widget::Table::Column, got " . describe($spec)
140 unless ref $spec eq 'HASH';
141 return Term::Fabulous::Widget::Table::Column->new(%$spec);
142 }
143  
144 method _columns_changed ( $keys = undef ) {
145 $columns_revision++;
146 if ( defined $keys ) {
147 delete $_->@{@$keys} foreach values %_raw, values %_display;
148 }
149 else {
150 %_raw = %_display = ();
151 }
152 %_search_text = ();
153 $self->_changed;
154 return;
155 }
156  
157 method has_column ($key) {
158 return defined $key && exists $_column_by_key{$key} ? 1 : 0;
159 }
160  
161 method column ($key) {
162 return $_column_by_key{ $key // '' } // die "Term::Fabulous::Widget::Table::Model: there is no column " . describe($key);
163 }
164  
165 method columns () {
166 return @_columns;
167 }
168  
169 method column_keys () {
170 return map { $_->key } @_columns;
171 }
172  
173 method visible_columns () {
174 return grep { !$_hidden{ $_->key } } @_columns;
175 }
176  
177 method type_of ($key) {
178 return $self->column($key)->type;
179 }
180  
181 method add_column ( $spec, $index = undef ) {
182 my $column = $self->_column_from($spec);
183 die "Term::Fabulous::Widget::Table::Model: there is a column '" . $column->key . "' already" if exists $_column_by_key{ $column->key };
184 $index //= scalar @_columns;
185 _check_index( 'column index', $index, scalar @_columns );
186 splice @_columns, $index, 0, $column;
187 $_column_by_key{ $column->key } = $column;
188 $_hidden{ $column->key } = 1 unless $column->visible;
189 $self->_columns_changed( [ $column->key ] );
190 return $column;
191 }
192  
193 method replace_column ($column) {
194 my $key = $column->key;
195 my $index = $self->_column_index($key);
196 $_columns[$index] = $_column_by_key{$key} = $column;
197 $self->_columns_changed( [$key] );
198 return $column;
199 }
200  
201 method remove_column ($key) {
202 my $index = $self->_column_index($key);
203 splice @_columns, $index, 1;
204 delete $_column_by_key{$key};
205 delete $_hidden{$key};
206 @_sort = grep { $_->[0] ne $key } @_sort;
207 @_group_by = grep { $_ ne $key } @_group_by;
208 my @comparing = grep {
209 my $name = $_;
210 any { $_ eq $key } $_filter{$name}->columns
211 } @_filter_names;
212 $self->remove_filter($_) foreach @comparing;
213 $self->_columns_changed( [$key] );
214 return;
215 }
216  
217 method move_column ( $key, $index ) {
218 my $from = $self->_column_index($key);
219 _check_index( 'column index', $index, $#_columns );
220 my ($column) = splice @_columns, $from, 1;
221 splice @_columns, $index, 0, $column;
222 $self->_columns_changed( [] );
223 return;
224 }
225  
226 method _column_index ($key) {
227 $self->column($key);
228 return first { $_columns[$_]->key eq $key } 0 .. $#_columns;
229 }
230  
231 sub _check_index ( $what, $index, $last ) {
232 die "Term::Fabulous::Widget::Table::Model: $what must be an integer from 0 to $last, got " . describe($index)
233 unless defined $index && !ref $index && $index =~ /\A[0-9]+\z/ && $index <= $last;
234 return;
235 }
236  
237 method is_column_visible ($key) {
238 $self->column($key);
239 return $_hidden{$key} ? 0 : 1;
240 }
241  
242 method set_column_visible ( $key, $visible ) {
243 $self->column($key);
244 return if ( $_hidden{$key} ? 0 : 1 ) == ( $visible ? 1 : 0 );
245 $visible ? delete $_hidden{$key} : ( $_hidden{$key} = 1 );
246 $self->_columns_changed( [] );
247 return;
248 }
249  
250 method set_visible_columns (@keys) {
251 $self->column($_) foreach @keys;
252 my %shown = map { $_ => 1 } @keys;
253 my %hidden = map { $_ => 1 } grep { !$shown{$_} } $self->column_keys;
254 return if join( "\0", sort keys %hidden ) eq join( "\0", sort keys %_hidden );
255 %_hidden = %hidden;
256 $self->_columns_changed( [] );
257 return;
258 }
259  
260 # =====================================================================
261 # Rows
262 # =====================================================================
263  
264 method _id_for ($data) {
265 return $_next_id++ unless defined $row_id;
266 my $id = ref $row_id ? $row_id->( {%$data} ) : $data->{$row_id};
267 die "Term::Fabulous::Widget::Table::Model: a row has no id (row_id " . ( ref $row_id ? 'returned' : "key '$row_id' holds" ) . " " . describe($id) . ")"
268 unless defined $id && !ref $id && length $id;
269 return $id;
270 }
271  
272 # Splits input rows into records (children first taken out of the
273 # data) without storing anything: ( [ top-level ids ], { id => record } ).
274 # $taken holds the ids that are in use already.
275 method _records_for ( $rows, $parent, $taken ) {
276 die "Term::Fabulous::Widget::Table::Model: rows must be an array reference of hash references, got " . describe($rows)
277 unless ref $rows eq 'ARRAY';
278 my ( @records, %by_id );
279 my $collect;
280 $collect = sub ( $list, $parent_id ) {
281 my @ids;
282 foreach my $row (@$list) {
283 die "Term::Fabulous::Widget::Table::Model: a row must be a hash reference, got " . describe($row) unless ref $row eq 'HASH';
284 my %data = %$row;
285 my $nested = defined $children_key ? delete $data{$children_key} : undef;
286 die "Term::Fabulous::Widget::Table::Model: the '$children_key' of a row must be an array reference of rows, got " . describe($nested)
287 if defined $nested && ref $nested ne 'ARRAY';
288 my $id = $self->_id_for( \%data );
289 die "Term::Fabulous::Widget::Table::Model: two rows have the id '$id'" if exists $by_id{$id} || exists $taken->{$id};
290  
291 # A record starts at the model's revision, which is above the
292 # revision of every earlier row with its id (a row's change
293 # counts in both), so the table refreshes what it showed.
294 my $record = { id => $id, data => \%data, parent => $parent_id, children => [], revision => $revision };
295 $by_id{$id} = $record;
296 push @records, $record;
297 push @ids, $id;
298 $record->{children} = $collect->( $nested, $id ) if defined $nested;
299 }
300 return \@ids;
301 };
302 my $top_ids = $collect->( $rows, $parent );
303 undef $collect;
304 return ( $top_ids, \%by_id );
305 }
306  
307 method set_rows ($rows) {
308 my ( $top_ids, $by_id ) = $self->_records_for( $rows, undef, {} ); # the new rows replace all
309 %_row = %$by_id;
310 @_roots = @$top_ids;
311 %_copy = %_raw = %_display = %_id_of_copy = %_search_text = ();
312 %_expanded = $expand_new ? map { $_->{id} => 1 } grep { @{ $_->{children} } } values %_row : ();
313 %_selected = map { $_ => 1 } grep { exists $_row{$_} } keys %_selected;
314 %_rank = ();
315 $self->_changed;
316 return $top_ids;
317 }
318  
319 method add_rows ( $rows, %options ) {
320 my @unknown = grep { $_ ne 'parent' && $_ ne 'index' } sort keys %options;
321 die "Term::Fabulous::Widget::Table::Model: add_rows does not accept @unknown (known: index, parent)" if @unknown;
322 my $parent = $options{parent};
323 die "Term::Fabulous::Widget::Table::Model: a parent row needs a table with children_key (tree data)" if defined $parent && !defined $children_key;
324 my $siblings = defined $parent ? $self->_record($parent)->{children} : \@_roots;
325 my $index = $options{index} // scalar @$siblings;
326 _check_index( 'row index', $index, scalar @$siblings );
327  
328 my ( $top_ids, $by_id ) = $self->_records_for( $rows, $parent, \%_row );
329 @_row{ keys %$by_id } = values %$by_id;
330 splice @$siblings, $index, 0, @$top_ids;
331 if ($expand_new) {
332 $_expanded{ $_->{id} } = 1 foreach grep { @{ $_->{children} } } values %$by_id;
333 }
334 %_rank = ();
335 $self->_changed;
336 return @$top_ids;
337 }
338  
339 method _record ($id) {
340 return $_row{ $id // '' } // die "Term::Fabulous::Widget::Table::Model: there is no row with the id " . describe($id);
341 }
342  
343 method has_row ($id) {
344 return defined $id && exists $_row{$id} ? 1 : 0;
345 }
346  
347 method _row_changed ($record) {
348 my $id = $record->{id};
349 $record->{revision}++;
350 my $copy = delete $_copy{$id};
351 delete $_id_of_copy{ refaddr $copy } if defined $copy;
352 delete $_raw{$id};
353 delete $_display{$id};
354 delete $_search_text{$id};
355 $self->_changed;
356 return;
357 }
358  
359 method update_row ( $id, $changes ) {
360 my $record = $self->_record($id);
361 die "Term::Fabulous::Widget::Table::Model: update_row needs a hash reference of changes, got " . describe($changes) unless ref $changes eq 'HASH';
362 die "Term::Fabulous::Widget::Table::Model: update_row cannot change '$children_key'; add or remove the child rows instead"
363 if defined $children_key && exists $changes->{$children_key};
364 my %data = ( %{ $record->{data} }, %$changes );
365 $self->_check_kept_id( $id, \%data );
366 $record->{data} = \%data;
367 $self->_row_changed($record);
368 return;
369 }
370  
371 method replace_row ( $id, $data ) {
372 my $record = $self->_record($id);
373 die "Term::Fabulous::Widget::Table::Model: replace_row needs a hash reference, got " . describe($data) unless ref $data eq 'HASH';
374 my %copy = %$data;
375 delete $copy{$children_key} if defined $children_key;
376 $self->_check_kept_id( $id, \%copy );
377 $record->{data} = \%copy;
378 $self->_row_changed($record);
379 return;
380 }
381  
382 # A row keeps its id: data that would give it another one dies.
383 method _check_kept_id ( $id, $data ) {
384 return unless defined $row_id;
385 my $new = ref $row_id ? $row_id->( {%$data} ) : $data->{$row_id};
386 die "Term::Fabulous::Widget::Table::Model: the change would give row '$id' the id " . describe($new) . "; ids cannot change"
387 unless defined $new && !ref $new && "$new" eq "$id";
388 return;
389 }
390  
391 method set_value ( $id, $key, $value ) {
392 return $self->update_row( $id, { $key => $value } );
393 }
394  
395 # Every sibling list loses its removed rows in one pass, then the rows
396 # and their descendants are forgotten.
397 method remove_rows (@ids) {
398 my @records = map { $self->_record($_) } @ids;
399 my %gone = map { $_->{id} => 1 } @records;
400 my %lists = map { my $siblings = $self->_siblings_of($_); ( refaddr $siblings => $siblings ) } @records;
401 @$_ = grep { !$gone{$_} } @$_ foreach values %lists;
402 foreach my $record (@records) {
403 $self->_forget($record) if exists $_row{ $record->{id} }; # not removed with an ancestor
404 }
405 %_rank = ();
406 $self->_changed;
407 return;
408 }
409  
410 # The list of ids a row is in: its parent's children or the top level.
411 method _siblings_of ($record) {
412 return defined $record->{parent} ? $_row{ $record->{parent} }{children} : \@_roots;
413 }
414  
415 method _forget ($record) {
416 $self->_forget( $_row{$_} ) foreach @{ $record->{children} };
417 my $id = $record->{id};
418 delete $_row{$id};
419 delete $_expanded{$id};
420 delete $_selected{$id};
421 my $copy = delete $_copy{$id};
422 delete $_id_of_copy{ refaddr $copy } if defined $copy;
423 delete $_raw{$id};
424 delete $_display{$id};
425 delete $_search_text{$id};
426 return;
427 }
428  
429 method clear_rows () {
430 %_row = %_copy = %_raw = %_display = %_id_of_copy = %_search_text = %_expanded = %_selected = %_rank = ();
431 @_roots = ();
432 $self->_changed;
433 return;
434 }
435  
436 method row_count () {
437 return scalar keys %_row;
438 }
439  
440 # Every row id, depth-first in data order.
441 method row_ids () {
442 my @ids;
443 my $walk;
444 $walk = sub ($list) {
445 foreach my $id (@$list) {
446 push @ids, $id;
447 $walk->( $_row{$id}{children} );
448 }
449 };
450 $walk->( \@_roots );
451 undef $walk;
452 return @ids;
453 }
454  
455 method row ($id) {
456 return { %{ $self->_record($id)->{data} } };
457 }
458  
459 method row_revision ($id) {
460 return $self->_record($id)->{revision};
461 }
462  
463 # The rows as given to set_rows: copies, with the children nested back.
464 method rows () {
465 my $nest;
466 $nest = sub ($ids) {
467 return [
468 map {
469 my $record = $_row{$_};
470 my %data = %{ $record->{data} };
471 $data{$children_key} = $nest->( $record->{children} ) if defined $children_key && @{ $record->{children} };
472 \%data;
473 } @$ids
474 ];
475 };
476 my $rows = $nest->( \@_roots );
477 undef $nest;
478 return $rows;
479 }
480  
481 method parent_of ($id) {
482 return $self->_record($id)->{parent};
483 }
484  
485 method children_of ($id) {
486 return @{ $self->_record($id)->{children} };
487 }
488  
489 method depth_of ($id) {
490 my $depth = 0;
491 for ( my $parent = $self->_record($id)->{parent}; defined $parent; $parent = $_row{$parent}{parent} ) {
492 $depth++;
493 }
494 return $depth;
495 }
496  
497 # The copy of a row's data the callbacks get; the same copy until the
498 # row changes.
499 method data_of ($id) {
500 return $_copy{$id} //= do {
501 my $copy = { %{ $self->_record($id)->{data} } };
502 $_id_of_copy{ refaddr $copy } = $id;
503 $copy;
504 };
505 }
506  
507 # Raw value and display text of a cell, by row id or by the copy of a
508 # row's data (for filters). What code computes (a column's value code,
509 # its mutators) is kept until the row or the column changes; a plain
510 # entry of the data is read directly. A hash the table did not hand out
511 # is read without the cache.
512 method _id_of_row ($row) {
513 return ref $row ? $_id_of_copy{ refaddr $row } : $row;
514 }
515  
516 method value_of ( $row, $key ) {
517 my $column = $_column_by_key{ $key // '' } // $self->column($key);
518 my $id = $self->_id_of_row($row);
519 return $column->value_of($row) unless defined $id;
520 my $record = $_row{$id} // $self->_record($id);
521 return $record->{data}{$key} unless $column->computes_value;
522 my $cache = $_raw{$id} //= {};
523 return $cache->{$key} if exists $cache->{$key};
524 return $cache->{$key} = $column->value_of( $self->data_of($id) );
525 }
526  
527 method display_of ( $row, $key ) {
528 my $column = $_column_by_key{ $key // '' } // $self->column($key);
529 my $id = $self->_id_of_row($row);
530 return $column->display_of( $column->value_of($row), $row ) unless defined $id;
531 unless ( $column->has_mutators ) {
532 my $raw = $self->value_of( $id, $key );
533 return defined $raw ? "$raw" : '';
534 }
535 my $cache = $_display{$id} //= {};
536 return $cache->{$key} if exists $cache->{$key};
537 return $cache->{$key} = $column->display_of( $self->value_of( $id, $key ), $self->data_of($id) );
538 }
539  
540 # =====================================================================
541 # Sorting
542 # =====================================================================
543  
544 # [ [ key, 'asc' or 'desc' ], ... ]
545 method sort_spec () {
546 return [ map { [ $_->[0], $_->[1] > 0 ? 'asc' : 'desc' ] } @_sort ];
547 }
548  
549 method set_sort (@spec) {
550 my ( @sort, %seen );
551 foreach my $entry (@spec) {
552 my ( $key, $direction ) = ref $entry eq 'ARRAY' ? @$entry : ( $entry, 'asc' );
553 $self->column($key);
554 one_of( $self, 'sort direction', $direction, qw(asc desc) );
555 die "Term::Fabulous::Widget::Table::Model: the column '$key' is in the sort twice" if $seen{$key}++;
556 push @sort, [ $key, $direction eq 'asc' ? 1 : -1 ];
557 }
558 return 0 if _same_sort( \@sort, \@_sort );
559 @_sort = @sort;
560 $self->_changed;
561 return 1;
562 }
563  
564 sub _same_sort ( $left, $right ) {
565 return join( "\0", map { @$_ } @$left ) eq join( "\0", map { @$_ } @$right ) ? 1 : 0;
566 }
567  
568 # What a click on a header does: ascending, descending, unsorted. With
569 # $add, the column is added to (or cycled within) the sort; without,
570 # it becomes the only sort key.
571 method cycle_sort ( $key, $add = 0 ) {
572 $self->column($key);
573 my ($current) = grep { $_->[0] eq $key } @_sort;
574 my $next = !defined $current ? 1 : $current->[1] > 0 ? -1 : 0;
575 my @sort = $add ? ( grep { $_->[0] ne $key } @_sort ) : ();
576 if ($next) {
577 my $position = $add && defined $current ? ( first { $_sort[$_][0] eq $key } 0 .. $#_sort ) : scalar @sort;
578 splice @sort, $position, 0, [ $key, $next ];
579 }
580 return $self->set_sort( map { [ $_->[0], $_->[1] > 0 ? 'asc' : 'desc' ] } @sort );
581 }
582  
583 # Orders sibling rows by the sort, then by data order. Named comparators
584 # order by sort keys computed once per row; a comparator of the user's
585 # is called for every comparison.
586 method _sorted (@ids) {
587 return @ids unless @_sort && @ids > 1;
588 my @plans;
589 foreach my $entry (@_sort) {
590 my ( $key, $direction ) = @$entry;
591 my $column = $self->column($key);
592 if ( $column->has_custom_compare ) {
593 push @plans, [ 'custom', $column, $key, $direction ];
594 next;
595 }
596 my %sort_key = map { $_ => $column->sort_key( $self->value_of( $_, $key ) ) } @ids;
597 push @plans, [ $column->sorts_numerically ? 'number' : 'text', \%sort_key, $key, $direction ];
598 }
599 my %order;
600 @order{@ids} = 0 .. $#ids; # the ids come in data order
601 my @sorted = sort {
602 my $result = 0;
603 foreach my $plan (@plans) {
604 my ( $kind, $what, $key, $direction ) = @$plan;
605 if ( $kind eq 'custom' ) {
606 $result = $what->order( $self->value_of( $a, $key ), $self->value_of( $b, $key ), $self->data_of($a), $self->data_of($b), $direction );
607 }
608 else {
609 my ( $left, $right ) = ( $what->{$a}, $what->{$b} );
610 $result
611 = !defined $left || !defined $right ? ( defined $left ? -1 : defined $right ? 1 : 0 )
612 : $kind eq 'number' ? $direction * ( $left <=> $right )
613 : $direction * ( $left cmp $right );
614 }
615 last if $result;
616 }
617 $result || $order{$a} <=> $order{$b};
618 } @ids;
619 return @sorted;
620 }
621  
622 # =====================================================================
623 # Filtering
624 # =====================================================================
625  
626 method set_filter ( $name, $filter ) {
627 die "Term::Fabulous::Widget::Table::Model: a filter name must be a non-empty string, got " . describe($name)
628 unless defined $name && !ref $name && length $name;
629 return $self->remove_filter($name) unless defined $filter;
630 $filter = Term::Fabulous::Widget::Table::Filter->new( test => $filter ) if ref $filter eq 'CODE';
631 die "Term::Fabulous::Widget::Table::Model: a filter must be a Term::Fabulous::Widget::Table::Filter, a code reference or undef, got " . describe($filter)
632 unless blessed $filter && $filter->isa('Term::Fabulous::Widget::Table::Filter');
633 $filter->check($self);
634 push @_filter_names, $name unless exists $_filter{$name};
635 $_filter{$name} = $filter;
636 $self->_changed;
637 return 1;
638 }
639  
640 method remove_filter ($name) {
641 return 0 unless defined $name && exists $_filter{$name};
642 delete $_filter{$name};
643 @_filter_names = grep { $_ ne $name } @_filter_names;
644 $self->_changed;
645 return 1;
646 }
647  
648 method clear_filters () {
649 return 0 unless @_filter_names || length $_search;
650 %_filter = ();
651 @_filter_names = ();
652 $_search = '';
653 $self->_changed;
654 return 1;
655 }
656  
657 method filter ($name) {
658 return $_filter{ $name // '' };
659 }
660  
661 method filter_names () {
662 return @_filter_names;
663 }
664  
665 method search (@new) {
666 return $_search unless @new;
667 my ($text) = @new;
668 $text //= '';
669 die "Term::Fabulous::Widget::Table::Model: search needs a string, got " . describe($text) if ref $text;
670 return $_search if $text eq $_search;
671 $_search = $text;
672 $self->_changed;
673 return $_search;
674 }
675  
676 method is_filtered () {
677 return @_filter_names || length $_search ? 1 : 0;
678 }
679  
680 # Whether a row matches every filter and the search; $searched are the
681 # keys of the columns the search looks at, $wanted the folded search.
682 method _matches ( $id, $searched, $wanted ) {
683 if (@_filter_names) {
684 my $row = $self->data_of($id);
685 foreach my $name (@_filter_names) {
686 return 0 unless $_filter{$name}->matches( $row, $self );
687 }
688 }
689 return 1 unless length $wanted;
690 my $text = $_search_text{$id} //= fc join "\0", map { $self->display_of( $id, $_ ) } @$searched;
691 return index( $text, $wanted ) >= 0 ? 1 : 0;
692 }
693  
694 # The rows a filter lets through: those that match, and their
695 # ancestors, so a matching row is never cut off from its tree.
696 method _passing () {
697 return { map { $_ => 1 } keys %_row } unless $self->is_filtered;
698 my @searched = map { $_->key } $self->visible_columns;
699 my $wanted = fc $_search;
700 my %passing;
701 foreach my $id ( grep { $self->_matches( $_, \@searched, $wanted ) } keys %_row ) {
702 for ( my $node = $id; defined $node && !$passing{$node}; $node = $_row{$node}{parent} ) {
703 $passing{$node} = 1;
704 }
705 }
706 return \%passing;
707 }
708  
709 # Expands every row that leads to a matching row, so a filter shows
710 # what it found. Returns whether anything was expanded.
711 method expand_to_matches () {
712 return 0 unless $self->is_filtered && defined $children_key;
713 my $passing = $self->_passing;
714 my @closed = grep {
715 !$_expanded{$_}
716 && ( any { $passing->{$_} } @{ $_row{$_}{children} } )
717 } keys %$passing;
718 return 0 unless @closed;
719 $_expanded{$_} = 1 foreach @closed;
720 $self->_changed;
721 return 1;
722 }
723  
724 # =====================================================================
725 # Grouping
726 # =====================================================================
727  
728 method group_by (@keys) {
729 return @_group_by unless @keys;
730 @keys = () if @keys == 1 && !defined $keys[0];
731 $self->column($_) foreach @keys;
732 my %seen;
733 die "Term::Fabulous::Widget::Table::Model: group_by names a column twice" if grep { $seen{$_}++ } @keys;
734 @_group_by = @keys;
735 $self->_changed;
736 return @_group_by;
737 }
738  
739 # A group key: the values of its path, each as defined-ness and text.
740 sub _group_key (@values) {
741 return join "\0", map { defined $_ ? "d$_" : 'u' } @values;
742 }
743  
744 method group_key_of (@path) {
745 return _group_key(@path);
746 }
747  
748 method is_group_collapsed (@path) {
749 return $_collapsed_group{ _group_key(@path) } ? 1 : 0;
750 }
751  
752 method set_group_collapsed ( $path, $collapsed ) {
753 die "Term::Fabulous::Widget::Table::Model: a group path must be an array reference of group values" unless ref $path eq 'ARRAY';
754 my $key = _group_key(@$path);
755 return 0 if ( $_collapsed_group{$key} ? 1 : 0 ) == ( $collapsed ? 1 : 0 );
756 $collapsed ? ( $_collapsed_group{$key} = 1 ) : delete $_collapsed_group{$key};
757 $self->_changed;
758 return 1;
759 }
760  
761 method set_all_groups_collapsed ($collapsed) {
762 %_collapsed_group = $collapsed ? map { $_ => 1 } $self->_all_group_keys : ();
763 $self->_changed;
764 return;
765 }
766  
767 # =====================================================================
768 # Tree
769 # =====================================================================
770  
771 method is_expanded ($id) {
772 $self->_record($id);
773 return $_expanded{$id} ? 1 : 0;
774 }
775  
776 method set_expanded ( $id, $expanded ) {
777 $self->_record($id);
778 return 0 if ( $_expanded{$id} ? 1 : 0 ) == ( $expanded ? 1 : 0 );
779 $expanded ? ( $_expanded{$id} = 1 ) : delete $_expanded{$id};
780 $self->_changed;
781 return 1;
782 }
783  
784 method set_all_expanded ($expanded) {
785 %_expanded = $expanded ? map { $_->{id} => 1 } grep { @{ $_->{children} } } values %_row : ();
786 $self->_changed;
787 return;
788 }
789  
790 # =====================================================================
791 # The view: filtered, sorted, grouped, flattened, paged
792 # =====================================================================
793  
794 # The view, computed when it is needed after a change. A new view
795 # settles the cursor and the page: the cursor stays on a line of the
796 # view and the page is the cursor's page.
797 method _view () {
798 return $_view if defined $_view;
799 $_view = $self->_compute_view;
800 $self->_settle_cursor;
801 return $_view;
802 }
803  
804 # The view: every passing row in order, grouped and sorted once; the
805 # lines are what of it is open, the filtered ids all of it.
806 method _compute_view () {
807 my $tree = $self->_ordered_tree;
808 my ( @lines, @filtered );
809 my $walk_rows;
810 $walk_rows = sub ( $ids, $depth, $shown ) {
811 foreach my $id (@$ids) {
812 push @filtered, $id;
813 my $children = $tree->{children}{$id};
814 my $open = @$children && $_expanded{$id} ? 1 : 0;
815 push @lines, { kind => 'row', key => ROW_PREFIX . $id, id => $id, depth => $depth, has_children => @$children ? 1 : 0, expanded => $open } if $shown;
816 $walk_rows->( $children, $depth + 1, $shown && $open );
817 }
818 };
819 my $walk_groups;
820 $walk_groups = sub ( $groups, $shown ) {
821 foreach my $group (@$groups) {
822 my $collapsed = $_collapsed_group{ $group->{group_key} } ? 1 : 0;
823 if ($shown) {
824 my %line = %$group;
825 delete @line{qw(groups rows)};
826 push @lines, { %line, kind => 'group', key => GROUP_PREFIX . $group->{group_key}, expanded => $collapsed ? 0 : 1 };
827 }
828 defined $group->{groups} ? $walk_groups->( $group->{groups}, $shown && !$collapsed ) : $walk_rows->( $group->{rows}, 0, $shown && !$collapsed );
829 }
830 };
831 defined $tree->{groups} ? $walk_groups->( $tree->{groups}, 1 ) : $walk_rows->( $tree->{rows}, 0, 1 );
832 undef $walk_rows;
833 undef $walk_groups;
834  
835 my $pages = $page_size ? max( 1, POSIX::ceil( @lines / $page_size ) ) : 1;
836 my %index_of = map { $lines[$_]{key} => $_ } 0 .. $#lines;
837 return { lines => \@lines, index_of => \%index_of, filtered => \@filtered, page_count => $pages };
838 }
839  
840 # The passing rows, ordered: { children => { id => [ sorted passing
841 # child ids ] }, and groups => [ group ... ] or rows => [ sorted
842 # top-level ids ] }. A group has the keys of a group line (see Lines)
843 # and groups or rows of its own.
844 method _ordered_tree () {
845 my $passing = $self->_passing;
846 my %children;
847 my $sort_children;
848 $sort_children = sub ($ids) {
849 foreach my $id (@$ids) {
850 $children{$id} = [ $self->_sorted( grep { $passing->{$_} } @{ $_row{$id}{children} } ) ];
851 $sort_children->( $children{$id} );
852 }
853 };
854 my $count = sub ($ids) {
855 my $total = 0;
856 my @todo = @$ids;
857 while ( defined( my $id = shift @todo ) ) {
858 $total++;
859 push @todo, @{ $children{$id} };
860 }
861 return $total;
862 };
863 my $group_level;
864 $group_level = sub ( $ids, $level, @path ) {
865 if ( $level > $#_group_by ) {
866 my @rows = $self->_sorted(@$ids);
867 $sort_children->( \@rows );
868 return { rows => \@rows };
869 }
870 my @groups;
871 foreach my $group ( $self->_groups( $ids, $level ) ) {
872 my @group_path = ( @path, $group->{value} );
873 my $inside = $group_level->( $group->{ids}, $level + 1, @group_path );
874 push @groups, { %$group, %$inside, group_key => _group_key(@group_path), path => \@group_path, depth => $level };
875 }
876 return { groups => \@groups };
877 };
878 my $tree = $group_level->( [ grep { $passing->{$_} } @_roots ], 0 );
879 undef $group_level;
880 undef $sort_children;
881  
882 # Counts need the children sorted (they are the passing ones).
883 my $add_counts;
884 $add_counts = sub ($groups) {
885 foreach my $group (@$groups) {
886 $group->{count} = $count->( $group->{ids} );
887 $add_counts->( $group->{groups} ) if defined $group->{groups};
888 }
889 };
890 $add_counts->( $tree->{groups} ) if defined $tree->{groups};
891 undef $add_counts;
892 $tree->{children} = \%children;
893 return $tree;
894 }
895  
896 # The keys of every group, collapsed or not, inside collapsed ones too.
897 method _all_group_keys () {
898 my $tree = $self->_ordered_tree;
899 my @keys;
900 my @todo = @{ $tree->{groups} // [] };
901 while ( defined( my $group = shift @todo ) ) {
902 push @keys, $group->{group_key};
903 push @todo, @{ $group->{groups} // [] };
904 }
905 return @keys;
906 }
907  
908 # The groups of some top-level rows at a grouping level, ordered by
909 # their value: ascending, or as the sort orders the group column. Each
910 # is { column, value, display, ids }.
911 method _groups ( $ids, $level ) {
912 my $key = $_group_by[$level];
913 my $column = $self->column($key);
914 my ( @order, %group_of );
915 foreach my $id (@$ids) {
916 my $value = $self->value_of( $id, $key );
917 my $group_key = _group_key($value);
918 push @order, $group_key unless $group_of{$group_key};
919 $group_of{$group_key} //= { column => $key, value => $value, display => $self->display_of( $id, $key ), ids => [], first => $id };
920 push @{ $group_of{$group_key}{ids} }, $id;
921 }
922 my ($sorted) = grep { $_->[0] eq $key } @_sort;
923 my $direction = defined $sorted ? $sorted->[1] : 1;
924 my @groups = map { $group_of{$_} } @order;
925 @groups = sort { $column->order( $a->{value}, $b->{value}, $self->data_of( $a->{first} ), $self->data_of( $b->{first} ), $direction ) } @groups;
926 delete $_->{first} foreach @groups;
927 return @groups;
928 }
929  
930 method lines () {
931 return map { +{%$_} } @{ $self->_view->{lines} };
932 }
933  
934 method line_count () {
935 return scalar @{ $self->_view->{lines} };
936 }
937  
938 method line ($key) {
939 my $index = $self->_view->{index_of}{ $key // '' } // return undef;
940 return { %{ $self->_view->{lines}[$index] } };
941 }
942  
943 method line_index ($key) {
944 return $self->_view->{index_of}{ $key // '' };
945 }
946  
947 method filtered_row_ids () {
948 return @{ $self->_view->{filtered} };
949 }
950  
951 sub row_key ($id) { return ROW_PREFIX . $id }
952 sub group_key ($key) { return GROUP_PREFIX . $key }
953  
954 sub id_of_key ($key) {
955 return defined $key && index( $key, ROW_PREFIX ) == 0 ? substr( $key, length ROW_PREFIX ) : undef;
956 }
957  
958 # =====================================================================
959 # Pages
960 # =====================================================================
961  
962 method set_page_size ($size) {
963 $size = _page_size($size);
964 return 0 if $size == $page_size;
965 $page_size = $size;
966 $self->_changed; # the page follows the cursor
967 return 1;
968 }
969  
970 method page_count () {
971 return $self->_view->{page_count};
972 }
973  
974 method page () {
975 $self->_view;
976 return $_page;
977 }
978  
979 # Turns to a page (kept within the pages) and puts the cursor on its
980 # first line. Returns whether the page changed.
981 method set_page ($page) {
982 die "Term::Fabulous::Widget::Table::Model: a page must be a whole number from 1, got " . describe($page)
983 unless defined $page && !ref $page && $page =~ /\A[0-9]+\z/ && $page >= 1;
984 $page = min( $page + 0, $self->page_count );
985 return 0 if $page == $self->page;
986 $_page = $page;
987 my ($first) = $self->_lines_of_page($_page);
988 $_cursor = $first->{key};
989 $self->_touched;
990 return 1;
991 }
992  
993 # The lines of the current page.
994 method page_lines () {
995 return map { +{%$_} } $self->_lines_of_page( $self->page );
996 }
997  
998 method _lines_of_page ($page) {
999 my @lines = @{ $self->_view->{lines} };
1000 return @lines unless $page_size;
1001 my $first = ( $page - 1 ) * $page_size;
1002 my $last = min( $first + $page_size, scalar @lines ) - 1;
1003 return @lines[ $first .. $last ];
1004 }
1005  
1006 method page_of_line ($key) {
1007 my $index = $self->line_index($key) // return undef;
1008 return $page_size ? 1 + int( $index / $page_size ) : 1;
1009 }
1010  
1011 # Turns to the page of the cursor; returns whether the page changed.
1012 method _show_cursor_page () {
1013 my $page = $self->page_of_line($_cursor) // return 0;
1014 return 0 if $page == $self->page;
1015 $_page = $page;
1016 return 1;
1017 }
1018  
1019 # =====================================================================
1020 # Selection
1021 # =====================================================================
1022  
1023 method selected_ids () {
1024 return $self->_in_data_order( keys %_selected );
1025 }
1026  
1027 # Sorts row ids by data order (row_ids), whose ranks are kept until
1028 # rows are set, added or removed.
1029 method _in_data_order (@ids) {
1030 unless (%_rank) {
1031 my @order = $self->row_ids;
1032 @_rank{@order} = 0 .. $#order;
1033 }
1034 my @sorted = sort { $_rank{$a} <=> $_rank{$b} } @ids;
1035 return @sorted;
1036 }
1037  
1038 method is_selected ($id) {
1039 return defined $id && $_selected{$id} ? 1 : 0;
1040 }
1041  
1042 # Sets the selection; returns ( [ added ], [ removed ] ), both in data
1043 # order.
1044 method set_selection (@ids) {
1045 $self->_record($_) foreach @ids;
1046 my %new = map { $_ => 1 } @ids;
1047 my @added = grep { !$_selected{$_} } keys %new;
1048 my @removed = grep { !$new{$_} } keys %_selected;
1049 return ( [], [] ) unless @added || @removed;
1050 %_selected = %new;
1051 $revision++;
1052 return ( [ $self->_in_data_order(@added) ], [ $self->_in_data_order(@removed) ] );
1053 }
1054  
1055 # Like set_selection, select and deselect return ( [ added ], [ removed ] )
1056 # with the ids as strings, but sort only the rows they change.
1057 method select (@ids) {
1058 $self->_record($_) foreach @ids;
1059 my @added = grep { !$_selected{$_} } uniq map { "$_" } @ids;
1060 return ( [], [] ) unless @added;
1061 @_selected{@added} = (1) x @added;
1062 $revision++;
1063 return ( [ $self->_in_data_order(@added) ], [] );
1064 }
1065  
1066 method deselect (@ids) {
1067 $self->_record($_) foreach @ids;
1068 my @removed = grep { $_selected{$_} } uniq map { "$_" } @ids;
1069 return ( [], [] ) unless @removed;
1070 delete @_selected{@removed};
1071 $revision++;
1072 return ( [], [ $self->_in_data_order(@removed) ] );
1073 }
1074  
1075 method toggle_selected ($id) {
1076 return $self->is_selected($id) ? $self->deselect($id) : $self->select($id);
1077 }
1078  
1079 # =====================================================================
1080 # Cursor
1081 # =====================================================================
1082  
1083 method cursor () {
1084 $self->_view;
1085 return $_cursor;
1086 }
1087  
1088 method anchor () {
1089 return $_anchor;
1090 }
1091  
1092 method set_anchor ($key) {
1093 $_anchor = $key;
1094 return;
1095 }
1096  
1097 # Puts the cursor on a line of the view, and turns to its page.
1098 # Returns whether it moved.
1099 method set_cursor ($key) {
1100 die "Term::Fabulous::Widget::Table::Model: the cursor needs a line of the view, got " . describe($key)
1101 unless defined $key && defined $self->line_index($key);
1102 my $before = $self->cursor;
1103 $_cursor = $key;
1104 my $turned = $self->_show_cursor_page;
1105 my $moved = !defined $before || $before ne $key ? 1 : 0;
1106 $self->_touched if $moved || $turned;
1107 return $moved;
1108 }
1109  
1110 # The cursor stays on a line of the view: when its line is gone
1111 # (filtered out, below a collapsed row or group, removed) it moves to
1112 # the line that now stands for it - the nearest shown ancestor, or its
1113 # group - or to the first line of the page. Only an empty view has no
1114 # cursor. The page is the cursor's page.
1115 method _settle_cursor () {
1116 unless ( @{ $_view->{lines} } ) {
1117 ( $_cursor, $_page ) = ( undef, 1 );
1118 return;
1119 }
1120 $_page = max( 1, min( $_page, $_view->{page_count} ) );
1121 $_cursor = $self->_stand_in_for_cursor unless defined $_cursor && defined $_view->{index_of}{$_cursor};
1122 $_page = $self->page_of_line($_cursor);
1123 return;
1124 }
1125  
1126 method _stand_in_for_cursor () {
1127 my $view = $_view;
1128 my $id = id_of_key($_cursor);
1129 if ( defined $id && exists $_row{$id} ) {
1130 for ( my $node = $_row{$id}{parent}; defined $node; $node = $_row{$node}{parent} ) {
1131 return ROW_PREFIX . $node if defined $view->{index_of}{ ROW_PREFIX . $node };
1132 }
1133 my @groups = grep { $_->{kind} eq 'group' && $self->_group_holds( $_, $id ) } @{ $view->{lines} };
1134 return $groups[-1]{key} if @groups;
1135 }
1136 my $lines = $view->{lines};
1137 return $lines->[ min( $_cursor_index // 0, $#$lines ) ]{key};
1138 }
1139  
1140 method _group_holds ( $group, $id ) {
1141 my $top = $id;
1142 $top = $_row{$top}{parent} while defined $_row{$top}{parent};
1143 my @path = map { $self->value_of( $top, $_ ) } @_group_by[ 0 .. $#{ $group->{path} } ];
1144 return _group_key(@path) eq $group->{group_key} ? 1 : 0;
1145 }
1146  
1147 # The line key $steps lines from the cursor (negative: up), kept within
1148 # the lines of the whole view; undef when there is no cursor (the view
1149 # is empty).
1150 method line_after_cursor ($steps) {
1151 my $lines = $self->_view->{lines};
1152 my $cursor = $self->cursor // return undef;
1153 my $index = $self->line_index($cursor) + $steps;
1154 return $lines->[ max( 0, min( $#$lines, $index ) ) ]{key};
1155 }
1156  
1157 method first_line_key () {
1158 my $lines = $self->_view->{lines};
1159 return @$lines ? $lines->[0]{key} : undef;
1160 }
1161  
1162 method last_line_key () {
1163 my $lines = $self->_view->{lines};
1164 return @$lines ? $lines->[-1]{key} : undef;
1165 }
1166  
1167 # The keys of the lines from one line to another, both included, in
1168 # view order.
1169 method line_keys_between ( $from, $to ) {
1170 my ( $first, $last ) = map { $self->line_index($_) // die "Term::Fabulous::Widget::Table::Model: no line " . describe($_) } $from, $to;
1171 ( $first, $last ) = ( $last, $first ) if $first > $last;
1172 return map { $_->{key} } @{ $self->_view->{lines} }[ $first .. $last ];
1173 }
1174 }
1175  
1176 1;
1177  
1178 __END__