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

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