Line data Source code
1 : import 'dart:math' as math;
2 :
3 : /// The page numbers to render for [page] of [pageCount], where a null entry is
4 : /// an ellipsis standing in for a run of hidden pages.
5 : ///
6 : /// Below the threshold of `2 * siblingCount + 5` every page is listed. Above it
7 : /// the list is always exactly that long: whichever end has no ellipsis extends
8 : /// its run to make up the difference. That keeps the row a fixed width as the
9 : /// user pages through, at the cost of occasionally spending an ellipsis on a
10 : /// single hidden page.
11 : ///
12 : /// Internal to the pagination component and not part of the public surface.
13 : ///
14 : /// ```dart
15 : /// pageWindow(page: 5, pageCount: 10, siblingCount: 1);
16 : /// // [1, null, 4, 5, 6, null, 10]
17 : /// ```
18 3 : List<int?> pageWindow({
19 : required int page,
20 : required int pageCount,
21 : required int siblingCount,
22 : }) {
23 6 : final slots = 2 * siblingCount + 5;
24 11 : if (pageCount <= slots) return [for (var i = 1; i <= pageCount; i++) i];
25 :
26 6 : final left = math.max(page - siblingCount, 1);
27 6 : final right = math.min(page + siblingCount, pageCount);
28 :
29 : // The inclusive run between the two boundary pages. Near an end it anchors to
30 : // that end and grows; in the middle it is the sibling run itself.
31 : final (start, end) = switch (left) {
32 7 : <= 2 => (2, 2 * siblingCount + 3),
33 6 : _ when right >= pageCount - 1 => (
34 6 : pageCount - 2 * siblingCount - 2,
35 2 : pageCount - 1,
36 : ),
37 : _ => (left, right),
38 : };
39 :
40 3 : return [
41 : 1,
42 6 : if (start > 2) null,
43 9 : for (var i = start; i <= end; i++) i,
44 9 : if (end < pageCount - 1) null,
45 3 : pageCount,
46 : ];
47 : }
48 :
49 : /// A consecutive run of at most [length] pages holding [page], shifted inward
50 : /// at either end, for a row too narrow to hold the boundary pages and ellipses.
51 : ///
52 : /// ```dart
53 : /// pageRun(page: 5, pageCount: 10, length: 3);
54 : /// // [4, 5, 6]
55 : /// ```
56 2 : List<int> pageRun({
57 : required int page,
58 : required int pageCount,
59 : required int length,
60 : }) {
61 2 : final count = math.min(length, pageCount);
62 12 : final start = (page - (count - 1) ~/ 2).clamp(1, pageCount - count + 1);
63 10 : return [for (var i = start; i < start + count; i++) i];
64 : }
|