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

filter: Statementstmt 0.0% 0 / 307 Branchbran 0.0% 0 / 120 Conditioncond 0.0% 0 / 110 MC/DCmcdc 0.0% 0 / 65 Subroutinesub 0.0% 0 / 14 Podpod n/a totaltotal 0.0% 0 / 616 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::VirtualList;
2  
3 use v5.32;
4 use warnings;
5 use feature 'signatures';
6 no warnings 'experimental::signatures';
7  
8 use Object::Pad 0.825;
9  
10 use Clay::UI::Role::Core::Preparable;
11 use Term::Fabulous::Widget::ScrollBox;
12  
13 our $VERSION = '0.05';
14  
15 class Term::Fabulous::Widget::VirtualList
16 :isa(Term::Fabulous::Widget::ScrollBox)
17 :does(Clay::UI::Role::Core::Preparable)
18 :strict(params)
19 {
20 use Clay::UI::Role::Layout::HasParent qw(is_widget);
21 use Clay::XS qw(sizing_fit sizing_fixed sizing_grow CLAY_TOP_TO_BOTTOM CLAY_ALIGN_X_LEFT);
22 use List::Util qw(max min);
23 use Scalar::Util qw(refaddr);
24 use Term::Fabulous::Check qw(describe non_negative_integer optional);
25 use Term::Fabulous::Scrolling qw(scroll_offset);
26 use Term::Fabulous::Widget::Box;
27  
28 field $count :param = 0;
29 field $build :param;
30 field $estimate :param = 1;
31 field $overscan :param = undef;
32  
33 # The column holds the window: a spacer as tall as the items above it,
34 # the attached items, a spacer as tall as the items below it.
35 field $_column;
36 field %_spacer; # above => Box, below => Box
37 field %_spacer_rows; # the rows each spacer was last sized to
38  
39 # Per item: the built widget, the slot that is attached to the column
40 # for it (the widget itself, or a box around a text widget), the rows
41 # measured in a frame and the rows the estimate gave, both for a width
42 # of $_columns. The offsets are the row each item starts at, with the
43 # total after the last; they are dropped whenever a height changes.
44 field @_built;
45 field @_slot;
46 field %_index_by_widget; # refaddr => item index, for every built widget
47 field @_measured;
48 field @_estimated;
49 field $_columns = 0;
50 field $_gap = 0;
51 field $_offsets;
52  
53 # The attached items, first to last (undef when none), and whether the
54 # next preparation must choose them again whatever the viewport shows.
55 field $_first;
56 field $_last;
57 field $_window_stale = 1;
58  
59 # The item scroll_to_item wants at the top, until a frame shows it
60 # measured; and the anchor rebuild took before it forgot the heights.
61 field $_target;
62 field $_kept_anchor;
63  
64 ADJUST {
65 $count = non_negative_integer( $self, count => $count );
66 $build = _checked_builder( $self, $build );
67 $estimate = _checked_estimate( $self, $estimate );
68 $overscan = non_negative_integer( $self, overscan => $overscan ) if defined $overscan;
69  
70 $_column = Term::Fabulous::Widget::Box->new( layout => $self->_column_layout );
71 %_spacer = map { $_ => Term::Fabulous::Widget::Box->new( layout => { sizing => { width => sizing_fixed(0), height => sizing_fixed(0) } } ) } qw(above below);
72 $self->add_internal_children($_column);
73 $self->request_prepare;
74 }
75  
76 sub _checked_builder ( $owner, $code ) {
77 die ref($owner) . ': build must be a code reference that returns the widget of an item, got ' . describe($code) unless ref $code eq 'CODE';
78 return $code;
79 }
80  
81 # The estimate is kept as a function of the item and the width; a
82 # number of rows becomes one.
83 sub _checked_estimate ( $owner, $value ) {
84 return $value if ref $value eq 'CODE';
85 die ref($owner) . ': estimate must be a code reference or a non-negative integer number of rows, got ' . describe($value)
86 unless defined $value && !ref $value && $value =~ /\A[0-9]+\z/;
87 my $rows = $value + 0;
88 return sub { $rows };
89 }
90  
91 # ---------------------------------------------------------------------
92 # Parameters
93 # ---------------------------------------------------------------------
94  
95 method count (@new) {
96 return $count unless @new;
97 my $new_count = non_negative_integer( $self, count => $new[0] );
98 $self->_drop_items_from($new_count);
99 $count = $new_count;
100 $self->_forget_offsets;
101 $_window_stale = 1;
102 $self->request_prepare;
103 return $count;
104 }
105  
106 method build (@new) {
107 return $build unless @new;
108 $build = _checked_builder( $self, $new[0] );
109 $self->rebuild;
110 return $build;
111 }
112  
113 method estimate (@new) {
114 return $estimate unless @new;
115 $estimate = _checked_estimate( $self, $new[0] );
116 @_estimated = ();
117 $self->_forget_offsets;
118 $self->request_prepare;
119 return $estimate;
120 }
121  
122 method overscan (@new) {
123 return $overscan unless @new;
124 $overscan = optional( \&non_negative_integer, $self, overscan => $new[0] );
125 $_window_stale = 1;
126 $self->request_prepare;
127 return $overscan;
128 }
129  
130 # Forgets every built widget and every height: the next frame builds
131 # the window again from build and estimate, with the item at the top
132 # of the viewport where it is now.
133 method rebuild () {
134 $_kept_anchor = $self->_current_anchor;
135 $self->_drop_items_from(0);
136 @_measured = ();
137 @_estimated = ();
138 $self->_forget_offsets;
139 $_window_stale = 1;
140 $self->request_prepare;
141 return $self;
142 }
143  
144 # The anchor for what the last frame shows, undef without a frame.
145 method _current_anchor () {
146 my $ui = $self->ui // return undef;
147 my $geometry = $self->_geometry($ui) // return undef;
148 return $count ? $self->_anchor( $geometry->{top} ) : undef;
149 }
150  
151 method item ($index) {
152 return $self->_item( $self->_checked_index( item => $index ) );
153 }
154  
155 method scroll_to_item ($index) {
156 $_target = $self->_checked_index( scroll_to_item => $index );
157 $self->request_prepare;
158 return $self;
159 }
160  
161 method window () {
162 return defined $_first ? { first => $_first, last => $_last } : undef;
163 }
164  
165 method visible_items () {
166 my $ui = $self->ui // return undef;
167 my $geometry = $self->_geometry($ui) // return undef;
168 return undef unless $count;
169 return { first => $self->_item_at( $geometry->{top} ), last => $self->_item_at( _last_row( $geometry->{top}, $geometry->{viewport} ) ) };
170 }
171  
172 method _checked_index ( $method, $index ) {
173 die ref($self) . ": $method needs an item index, got " . describe($index) unless defined $index && !ref $index && $index =~ /\A[0-9]+\z/;
174 die ref($self) . ": $method: item $index does not exist, the list has $count items" unless $index < $count;
175 return $index + 0;
176 }
177  
178 # ---------------------------------------------------------------------
179 # Children: the list builds its own
180 # ---------------------------------------------------------------------
181  
182 method add_child :override (@kids) { die $self->_unsupported('add_child') }
183 method insert_children :override ( $offset, @kids ) { die $self->_unsupported('insert_children') }
184 method clear_children :override () { die $self->_unsupported('clear_children') }
185 method remove_child :override (@kids) { die $self->_unsupported('remove_child') }
186 method remove_child_with_id :override ($target_id) { die $self->_unsupported('remove_child_with_id') }
187 method remove_children_with :override ($predicate) { die $self->_unsupported('remove_children_with') }
188  
189 method _unsupported ($method) {
190 return ref($self) . ": $method is not supported; a VirtualList builds its children from build, set count and build instead";
191 }
192  
193 # A list whose place in a tree changed is prepared for its new place.
194 method tree_changed :override () {
195 $self->SUPER::tree_changed;
196 $self->request_prepare;
197 return;
198 }
199  
200 # ---------------------------------------------------------------------
201 # Items and their heights
202 # ---------------------------------------------------------------------
203  
204 method _item ($index) {
205 return $_built[$index] //= $self->_build_item($index);
206 }
207  
208 method _build_item ($index) {
209 my $widget = $build->($index);
210 die ref($self) . ": build must return a widget for item $index, got " . describe($widget)
211 unless is_widget($widget);
212 die ref($self) . ": build returned a widget that already has a parent for item $index" if defined $widget->parent;
213 my $other = $_index_by_widget{ refaddr $widget };
214 die ref($self) . ": build returned the widget of item $other again for item $index" if defined $other;
215 $_index_by_widget{ refaddr $widget } = $index;
216 return $widget;
217 }
218  
219 # A text widget is laid out inside a box of its own, so that the slot
220 # can carry padding and a border some day; any other widget is attached
221 # as it is.
222 method _slot ($index) {
223 return $_slot[$index] //= _new_slot( $self->_item($index) );
224 }
225  
226 sub _new_slot ($item) {
227 return $item unless $item->DOES('Clay::UI::Role::Core::TextNode');
228 my $slot = Term::Fabulous::Widget::Box->new;
229 $slot->add_child($item);
230 return $slot;
231 }
232  
233 # Forgets the widgets and the heights of the items from $from on: when
234 # the list grows again, the items at these indices are new ones. Those
235 # still attached leave the column at the next preparation.
236 method _drop_items_from ($from) {
237 delete @_index_by_widget{ map { refaddr $_ } grep { defined } @_built[ $from .. $#_built ] };
238 $#_built = $from - 1;
239 $#_slot = $from - 1;
240 $#_measured = $from - 1 if $#_measured >= $from;
241 $#_estimated = $from - 1 if $#_estimated >= $from;
242 ( $_first, $_last ) = ( undef, undef ) if defined $_first && $_first >= $from;
243 $_last = min( $_last, $from - 1 ) if defined $_last;
244 $_target = undef if defined $_target && $_target >= $from;
245 return;
246 }
247  
248 method _rows_of ($index) {
249 return $_measured[$index] // ( $_estimated[$index] //= $self->_estimated_rows($index) );
250 }
251  
252 method _estimated_rows ($index) {
253 my $rows = $estimate->( $index, $_columns );
254 die ref($self) . ": estimate must return a non-negative integer number of rows for item $index, got " . describe($rows)
255 unless defined $rows && !ref $rows && $rows =~ /\A[0-9]+\z/;
256 return $rows + 0;
257 }
258  
259 # Every height is for one width: a new width starts over.
260 method _forget_heights ($columns) {
261 $_columns = $columns;
262 @_measured = ();
263 @_estimated = ();
264 $self->_forget_offsets;
265 return;
266 }
267  
268 method _forget_offsets () {
269 $_offsets = undef;
270 return;
271 }
272  
273 # [ the first row of each item, the total height ]: items follow each
274 # other with the gap between them.
275 method _offsets () {
276 return $_offsets if defined $_offsets;
277 my ( $row, @offsets ) = (0);
278 foreach my $index ( 0 .. $count - 1 ) {
279 push @offsets, $row;
280 $row += $self->_rows_of($index) + $_gap;
281 }
282 push @offsets, $count ? $row - $_gap : 0;
283 return $_offsets = \@offsets;
284 }
285  
286 # The item a row belongs to: the last one starting at or before it.
287 method _item_at ($row) {
288 my $offsets = $self->_offsets;
289 my ( $low, $high ) = ( 0, $count - 1 );
290 while ( $low < $high ) {
291 my $middle = int( ( $low + $high + 1 ) / 2 );
292 if ( $offsets->[$middle] <= $row ) { $low = $middle }
293 else { $high = $middle - 1 }
294 }
295 return $low;
296 }
297  
298 # ---------------------------------------------------------------------
299 # Preparing a frame
300 # ---------------------------------------------------------------------
301  
302 # Where the last frame put the list: the width the items wrap to, the
303 # rows of the viewport and the first row it shows; undef before the
304 # first frame, or while the list is not laid out.
305 method _geometry ($ui) {
306 my $state = $ui->scroll_state($self) // return undef;
307 my $column = $ui->bounding_box($_column) // return undef;
308 return {
309 columns => int( $column->{width} + 0.5 ),
310 viewport => int( $state->{viewport}{height} + 0.5 ),
311 top => int( scroll_offset( $ui, $self ) + 0.5 ),
312 };
313 }
314  
315 # The last row a viewport of $viewport rows shows from $top on.
316 sub _last_row ( $top, $viewport ) {
317 return $top + max( $viewport, 1 ) - 1;
318 }
319  
320 # Brings the column up to date with the frame about to be laid out:
321 # learns the heights the last frame gave the attached items, keeps the
322 # item at the top of the viewport where it was (or shows the target
323 # item), then attaches the items the viewport and the overscan need.
324 method prepare_layout () {
325 my $ui = $self->ui // return;
326 $self->_prepare_column;
327  
328 my $geometry = $self->_geometry($ui);
329 my ( $top, $viewport ) = ( 0, $ui->height );
330 if ( defined $geometry ) {
331 my $anchor = $_kept_anchor // ( $count ? $self->_anchor( $geometry->{top} ) : undef );
332 $_kept_anchor = undef;
333 $self->_harvest( $ui, $geometry );
334 ( $top, $viewport ) = ( $self->_place( $ui, $geometry, $anchor ), $geometry->{viewport} );
335 }
336 elsif ( $_columns != $ui->width ) {
337 $self->_forget_heights( $ui->width );
338 }
339  
340 $self->_choose_window( $top, $viewport );
341 $self->_arrange;
342 $self->each_frame( sub ($list) { $list->_frame_drawn; return 0 }, name => 'window' );
343 return;
344 }
345  
346 # The items take the list's gap and horizontal alignment.
347 method _column_layout () {
348 my $layout = $self->layout;
349 return {
350 layout_direction => CLAY_TOP_TO_BOTTOM,
351 sizing => { width => sizing_grow(), height => sizing_fit() },
352 child_gap => $layout->{child_gap} // 0,
353 child_alignment => { x => $layout->{child_alignment}{x} // CLAY_ALIGN_X_LEFT },
354 };
355 }
356  
357 method _prepare_column () {
358 my $layout = $self->_column_layout;
359 my $before = $_column->layout;
360 $_column->layout($layout) if $layout->{child_gap} != $before->{child_gap} || $layout->{child_alignment}{x} != $before->{child_alignment}{x};
361 return if $_gap == $layout->{child_gap};
362 $_gap = $layout->{child_gap};
363 $self->_forget_offsets;
364 return;
365 }
366  
367 # What the user is looking at, as an item and a row offset from its
368 # start, so that it can be found again once heights have changed. A
369 # measured item makes a firm anchor: the nearest one at or below the
370 # top of the viewport (the rows between them are about to be measured,
371 # so the offset, negative, comes out exact), else the nearest one above
372 # (nothing between them changes, so the position holds). With no
373 # measured item near, the item at the top as the model places it.
374 method _anchor ($top) {
375 my $index = $self->_item_at($top);
376 my $measured = $self->_measured_from( $index, 1 ) // $self->_measured_from( $index - 1, -1 );
377 my $anchor = $measured // $index;
378 return { index => $anchor, within => $top - $self->_offsets->[$anchor], firm => defined $measured ? 1 : 0 };
379 }
380  
381 # The first measured item from $index on, walking in $direction.
382 method _measured_from ( $index, $direction ) {
383 for ( my $candidate = $index; $candidate >= 0 && $candidate < $count; $candidate += $direction ) {
384 return $candidate if defined $_measured[$candidate];
385 }
386 return undef;
387 }
388  
389 # The row that puts the anchor back where it was. An offset into the
390 # item at the top (the anchor the model gave) stays inside the item
391 # when the item turns out shorter; a firm anchor's offset spans the
392 # items between and is kept as it is.
393 method _row_of_anchor ($anchor) {
394 my $index = min( $anchor->{index}, $count - 1 );
395 my $within = $anchor->{within};
396 $within = min( $within, max( 0, $self->_rows_of($index) - 1 ) ) unless $anchor->{firm};
397 return max( 0, $self->_offsets->[$index] + $within );
398 }
399  
400 # The heights the last frame gave the attached items, for its width.
401 method _harvest ( $ui, $geometry ) {
402 $self->_forget_heights( $geometry->{columns} ) if $geometry->{columns} != $_columns;
403 return unless defined $_first;
404 foreach my $index ( $_first .. $_last ) {
405 my $rows = $self->_frame_rows( $ui, $index ) // next;
406 next if defined $_measured[$index] && $_measured[$index] == $rows;
407 $_measured[$index] = $rows;
408 $self->_forget_offsets;
409 }
410 return;
411 }
412  
413 # The rows an attached item took in the last frame, undef when the
414 # frame did not lay it out.
415 method _frame_rows ( $ui, $index ) {
416 my $box = $ui->bounding_box( $_slot[$index] ) // return undef;
417 return int( $box->{height} + 0.5 );
418 }
419  
420 # The first row this frame shows: the target item's, else the anchor's
421 # with the heights learnt. Moves the scroll position when that differs
422 # from where the last frame was, and returns the row it got.
423 method _place ( $ui, $geometry, $anchor ) {
424 my $wanted = $geometry->{top};
425 if ( defined $_target ) {
426 $wanted = $self->_offsets->[$_target];
427 $_target = undef if defined $_measured[$_target];
428 }
429 elsif ( defined $anchor ) {
430 $wanted = $self->_row_of_anchor($anchor);
431 }
432 return $wanted if $wanted == $geometry->{top};
433 my $position = $ui->scroll_to( $self, { y => -$wanted } ) // return $geometry->{top};
434 return int( -$position->{y} + 0.5 );
435 }
436  
437 # Keeps the window while it covers the viewport; otherwise chooses the
438 # items of the viewport and an overscan of rows on either side.
439 method _choose_window ( $top, $viewport ) {
440 unless ($count) {
441 ( $_first, $_last ) = ( undef, undef );
442 return;
443 }
444 my $last_row = _last_row( $top, $viewport );
445 return if !$_window_stale && $self->_covers( $top, $last_row );
446 my $margin = $overscan // $viewport;
447 ( $_first, $_last ) = ( $self->_item_at( max( 0, $top - $margin ) ), $self->_item_at( $last_row + $margin ) );
448 $_window_stale = 0;
449 return;
450 }
451  
452 method _covers ( $top, $last_row ) {
453 return defined $_first && $_first <= $self->_item_at($top) && $_last >= $self->_item_at($last_row) ? 1 : 0;
454 }
455  
456 # Makes the column's children the spacers and the window: what leaves
457 # is detached, what enters is inserted where it belongs, what stays is
458 # not touched (so it keeps focus and hover). A slot that leaves with
459 # the focus hands it to its focus heir, the list itself or the nearest
460 # ancestor that can take it, so the keys keep working where they did.
461 method _arrange () {
462 my @wanted;
463 if ( defined $_first ) {
464 push @wanted, $_spacer{above} if $_first > 0;
465 push @wanted, map { $self->_slot($_) } $_first .. $_last;
466 push @wanted, $_spacer{below} if $_last < $count - 1;
467 }
468 $self->_size_spacers;
469  
470 my %stays = map { refaddr($_) => 1 } @wanted;
471 $_column->remove_children_with( sub { !$stays{ refaddr $_ } } );
472  
473 my @runs; # [ $offset, @children ]: the entering children, run by run
474 foreach my $index ( 0 .. $#wanted ) {
475 my $child = $wanted[$index];
476 next if $self->_holds($child);
477 push @runs, [$index] unless @runs && $runs[-1][0] + $#{ $runs[-1] } == $index;
478 push @{ $runs[-1] }, $child;
479 }
480 foreach my $run (@runs) {
481 my ( $offset, @children ) = @$run;
482 $_column->insert_children( $offset, @children );
483 }
484 return;
485 }
486  
487 method _holds ($child) {
488 my $parent = $child->parent;
489 return defined $parent && refaddr($parent) == refaddr($_column) ? 1 : 0;
490 }
491  
492 # A spacer stands in for the items on its side of the window; the gap
493 # between it and the window is Clay's.
494 method _size_spacers () {
495 return unless defined $_first;
496 my $offsets = $self->_offsets;
497 $self->_size_spacer( above => $offsets->[$_first] - $_gap ) if $_first > 0;
498 $self->_size_spacer( below => $offsets->[$count] - ( $offsets->[$_last] + $self->_rows_of($_last) ) - $_gap ) if $_last < $count - 1;
499 return;
500 }
501  
502 method _size_spacer ( $side, $rows ) {
503 return if defined $_spacer_rows{$side} && $_spacer_rows{$side} == $rows;
504 $_spacer_rows{$side} = $rows;
505 $_spacer{$side}->layout( { sizing => { width => sizing_fixed(0), height => sizing_fixed($rows) } } );
506 return;
507 }
508  
509 # ---------------------------------------------------------------------
510 # After a frame
511 # ---------------------------------------------------------------------
512  
513 # After every frame the list checks whether the frame showed something
514 # it was not prepared for: a new width, items still unmeasured, or a
515 # position the window does not cover (reached by scroll_to or by Clay's
516 # own clamping). Each preparation registers the check (each_frame), so
517 # it runs while the list is in a UI.
518 method _frame_drawn () {
519 $self->request_prepare if $self->_needs_prepare( $self->ui );
520 return;
521 }
522  
523 method _needs_prepare ($ui) {
524 my $geometry = $self->_geometry($ui) // return 0;
525 return 1 if $geometry->{columns} != $_columns;
526 return 1 if defined $_first && grep { $self->_frame_differs( $ui, $_ ) } $_first .. $_last;
527 return 0 unless $count;
528 return $self->_covers( $geometry->{top}, _last_row( $geometry->{top}, $geometry->{viewport} ) ) ? 0 : 1;
529 }
530  
531 # Whether the last frame gave an attached item a height the list does
532 # not know yet.
533 method _frame_differs ( $ui, $index ) {
534 my $rows = $self->_frame_rows( $ui, $index ) // return 0;
535 return !defined $_measured[$index] || $_measured[$index] != $rows ? 1 : 0;
536 }
537 }
538  
539 1;
540  
541 __END__