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

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