Line data Source code
1 : import 'dart:math' as math;
2 :
3 : import 'package:flutter/widgets.dart';
4 : import 'package:fossui/src/components/button/foss_button.dart';
5 : import 'package:fossui/src/components/pagination/pagination_window.dart';
6 : import 'package:fossui/src/foundation/foss_since.dart';
7 : import 'package:fossui/src/icons/foss_glyph.dart';
8 : import 'package:fossui/src/theme/theme.dart';
9 :
10 : part 'foss_pagination_style.dart';
11 :
12 : /// The width one slot occupies at rest: a [FossButton]'s minimum tap extent.
13 : /// Only a large text scale pushes a page number past it.
14 : const double _minSlot = 48;
15 :
16 : /// The ellipsis mark, drawn larger than a button's icon so three dots read as
17 : /// three dots.
18 : const double _ellipsisGlyph = 20;
19 :
20 : /// {@category Layout}
21 : /// {@template foss.pagination.preview}
22 : /// <img src="https://fossui.org/components/pagination/overview/light.png"
23 : /// alt="FossPagination, light theme" width="480"
24 : /// style="max-width:100%;height:auto" />
25 : /// <img src="https://fossui.org/components/pagination/overview/dark.png"
26 : /// alt="FossPagination, dark theme" width="480"
27 : /// style="max-width:100%;height:auto" />
28 : ///
29 : /// See the
30 : /// [pagination documentation ↗](https://fossui.org/docs/components/pagination)
31 : /// or try it live in the
32 : /// [playground ↗](https://play.fossui.org/components/#/?path=components/pagination/fosspagination/playground).
33 : /// {@endtemplate}
34 : ///
35 : /// A row that walks through pages: a previous control, a windowed run of page
36 : /// numbers with an ellipsis wherever the run is cut, and a next control.
37 : ///
38 : /// It is controlled. [page] is the current page and [pageCount] the total, both
39 : /// 1-based, and [onPageChanged] reports the page the user asked for. Passing a
40 : /// null [onPageChanged] makes the whole row inert and dimmed.
41 : ///
42 : /// [siblingCount] is how many pages sit either side of the current one, and it
43 : /// is an upper bound: when the width it is given cannot hold that many slots,
44 : /// the row uses the largest count that fits, so it does not overflow a phone.
45 : /// That figure ignores [page], so the row does not resize while the user pages.
46 : /// Narrower than seven slots, the first and last pages and the ellipses give
47 : /// way to a plain run of neighbors around the current page, down to the
48 : /// previous control, the current page, and the next control.
49 : ///
50 : /// Because the row reads the width it is given, it cannot report an intrinsic
51 : /// size. Give it a width instead of placing it in a `Table` cell or an
52 : /// `IntrinsicWidth`.
53 : ///
54 : /// {@macro foss.customize}
55 : ///
56 : /// Every control is a square [FossButton], so hover, pressed, focus, and
57 : /// disabled all behave the way buttons do elsewhere. The chevrons follow the
58 : /// reading direction and the ellipsis is not focusable.
59 : ///
60 : /// See also [FossPaginationStyle] for one-off overrides.
61 : ///
62 : /// ```dart
63 : /// FossPagination(
64 : /// page: page,
65 : /// pageCount: 10,
66 : /// onPageChanged: (p) => setState(() => page = p),
67 : /// );
68 : /// ```
69 : @FossSince('0.1.2')
70 : class FossPagination extends StatelessWidget {
71 : /// {@macro foss.pagination.preview}
72 : ///
73 : /// Creates a pagination row. [page] is 1-based and must fall within
74 : /// [pageCount]; a null [onPageChanged] disables every control.
75 2 : const FossPagination({
76 : required this.page,
77 : required this.pageCount,
78 : required this.onPageChanged,
79 : this.siblingCount = 1,
80 : this.label = 'Pagination',
81 : this.pageLabel,
82 : this.previousLabel = 'Go to previous page',
83 : this.nextLabel = 'Go to next page',
84 : this.moreLabel = 'More pages',
85 : this.style,
86 : super.key,
87 4 : }) : assert(pageCount >= 1, 'pageCount must be at least 1.'),
88 : assert(
89 6 : page >= 1 && page <= pageCount,
90 : 'page must be between 1 and pageCount.',
91 : ),
92 4 : assert(siblingCount >= 0, 'siblingCount cannot be negative.');
93 :
94 : /// The current page, 1-based and within [pageCount].
95 : final int page;
96 :
97 : /// The total number of pages, at least 1.
98 : final int pageCount;
99 :
100 : /// Called with the page the user asked for. Null disables the whole row.
101 : ///
102 : /// Tapping the current page does not call it.
103 : final ValueChanged<int>? onPageChanged;
104 :
105 : /// The pages shown either side of [page], as a ceiling. A narrow row uses
106 : /// fewer. Defaults to 1.
107 : final int siblingCount;
108 :
109 : /// Names the row for assistive technology. Defaults to `'Pagination'`.
110 : final String label;
111 :
112 : /// Builds each page button's accessibility label. Defaults to `'Page $n'`.
113 : final String Function(int page)? pageLabel;
114 :
115 : /// Accessibility label for the previous control.
116 : final String previousLabel;
117 :
118 : /// Accessibility label for the next control.
119 : final String nextLabel;
120 :
121 : /// Accessibility label for an ellipsis, which announces the pages it hides.
122 : final String moreLabel;
123 :
124 : /// Per-instance overrides layered on the theme-resolved style.
125 : final FossPaginationStyle? style;
126 :
127 2 : @override
128 : Widget build(BuildContext context) {
129 2 : final theme = context.fossTheme;
130 6 : final numberStyle = theme.typography.base.medium;
131 4 : final slot = math.max(_minSlot, _numberExtent(context, numberStyle));
132 4 : final visuals = _PaginationVisuals.resolve(theme, style, slot: slot);
133 :
134 2 : return Semantics(
135 : container: true,
136 2 : label: label,
137 2 : child: LayoutBuilder(
138 2 : builder: (context, constraints) {
139 2 : final entries = _fittedEntries(
140 2 : constraints.maxWidth,
141 2 : gap: visuals.gap,
142 : slot: slot,
143 : );
144 2 : return Row(
145 : mainAxisSize: MainAxisSize.min,
146 2 : spacing: visuals.gap,
147 2 : children: [
148 6 : _step(visuals, target: page - 1, forward: false),
149 2 : for (final entry in entries)
150 : if (entry case final n?)
151 2 : _pageButton(n, visuals, numberStyle)
152 : else
153 2 : _ellipsis(visuals),
154 6 : _step(visuals, target: page + 1, forward: true),
155 : ],
156 : );
157 : },
158 : ),
159 : );
160 : }
161 :
162 : /// Measures the widest page number so the slot pitch stays right when a large
163 : /// text scale grows the digits past the button's tap extent.
164 2 : double _numberExtent(BuildContext context, TextStyle style) {
165 2 : final painter = TextPainter(
166 6 : text: TextSpan(text: '$pageCount', style: style),
167 : textDirection: TextDirection.ltr,
168 2 : textScaler: MediaQuery.textScalerOf(context),
169 2 : )..layout();
170 2 : final width = painter.width;
171 2 : painter.dispose();
172 : return width;
173 : }
174 :
175 : /// The page entries for the widest row that fits [maxWidth], with at most
176 : /// [siblingCount] siblings. An unbounded width takes the request as-is.
177 2 : List<int?> _fittedEntries(
178 : double maxWidth, {
179 : required double gap,
180 : required double slot,
181 : }) {
182 2 : if (!maxWidth.isFinite) {
183 1 : return pageWindow(
184 1 : page: page,
185 1 : pageCount: pageCount,
186 1 : siblingCount: siblingCount,
187 : );
188 : }
189 : // Two slots go to the previous and next controls; the rest hold pages.
190 10 : final pages = ((maxWidth + gap) / (slot + gap)).floor() - 2;
191 : // The boundary pages and ellipses need five, so below that the row keeps
192 : // a plain run around the current page.
193 2 : if (pages < 5) {
194 1 : return pageRun(
195 1 : page: page,
196 1 : pageCount: pageCount,
197 1 : length: math.max(pages, 1),
198 : );
199 : }
200 2 : return pageWindow(
201 2 : page: page,
202 2 : pageCount: pageCount,
203 8 : siblingCount: ((pages - 5) ~/ 2).clamp(0, siblingCount),
204 : );
205 : }
206 :
207 1 : void _go(int next) {
208 4 : if (next != page) onPageChanged?.call(next);
209 : }
210 :
211 : /// The previous or next control. Off either end it has no target, so it
212 : /// takes a null callback and [FossButton] dims it and drops it from focus.
213 2 : Widget _step(
214 : _PaginationVisuals visuals, {
215 : required int target,
216 : required bool forward,
217 : }) {
218 8 : final live = onPageChanged != null && target >= 1 && target <= pageCount;
219 2 : return FossButton.icon(
220 2 : onPressed: live ? () => _go(target) : null,
221 2 : variant: visuals.inactiveVariant,
222 2 : size: visuals.buttonSize,
223 4 : semanticLabel: forward ? nextLabel : previousLabel,
224 2 : icon: _Chevron(forward: forward),
225 : );
226 : }
227 :
228 2 : Widget _pageButton(int n, _PaginationVisuals visuals, TextStyle numberStyle) {
229 4 : final current = n == page;
230 2 : final button = FossButton.icon(
231 4 : onPressed: onPageChanged == null ? null : () => _go(n),
232 4 : variant: current ? visuals.activeVariant : visuals.inactiveVariant,
233 2 : size: visuals.buttonSize,
234 5 : semanticLabel: pageLabel?.call(n) ?? 'Page $n',
235 2 : icon: _PageNumber(n, style: numberStyle),
236 : );
237 : // Selection is the closest thing Flutter has to marking the current item in
238 : // a set of page links.
239 2 : return current ? Semantics(selected: true, child: button) : button;
240 : }
241 :
242 : /// The cut marker: as wide as a page button so the row's pitch stays even,
243 : /// and inert, so only its label reaches assistive technology.
244 4 : Widget _ellipsis(_PaginationVisuals visuals) => Semantics(
245 : // Its own node, or the label folds into the row's and the row announces
246 : // every ellipsis as part of its name.
247 : container: true,
248 2 : label: moreLabel,
249 2 : child: SizedBox(
250 2 : width: visuals.ellipsisWidth,
251 2 : child: Center(
252 2 : child: FossGlyphIcon(
253 4 : EllipsisGlyph(visuals.ellipsisColor),
254 : size: _ellipsisGlyph,
255 : ),
256 : ),
257 : ),
258 : );
259 : }
260 :
261 : /// A page number drawn in the enclosing button's resolved foreground, so it
262 : /// stays legible under any [FossButtonVariant] the style picks for the current
263 : /// page. Centred because the button floors its content to a square and a bare
264 : /// [Text] would paint in that square's corner.
265 : class _PageNumber extends StatelessWidget {
266 2 : const _PageNumber(this.page, {required this.style});
267 :
268 : final int page;
269 : final TextStyle style;
270 :
271 2 : @override
272 : Widget build(BuildContext context) {
273 : final color =
274 4 : IconTheme.of(context).color ?? context.fossTheme.colors.foreground;
275 2 : return Center(
276 : widthFactor: 1,
277 : heightFactor: 1,
278 : // The number is the whole label, and the button already announces it.
279 2 : child: ExcludeSemantics(
280 10 : child: Text('$page', style: style.copyWith(color: color)),
281 : ),
282 : );
283 : }
284 : }
285 :
286 : /// A step chevron pointing along the reading direction, drawn in the enclosing
287 : /// button's resolved icon color and size.
288 : ///
289 : /// The two glyphs are swapped rather than mirrored with a transform, so the
290 : /// stroke caps stay where the glyph put them.
291 : class _Chevron extends StatelessWidget {
292 2 : const _Chevron({required this.forward});
293 :
294 : final bool forward;
295 :
296 2 : @override
297 : Widget build(BuildContext context) {
298 2 : final icon = IconTheme.of(context);
299 4 : final ltr = Directionality.of(context) == TextDirection.ltr;
300 2 : final color = icon.color ?? context.fossTheme.colors.foreground;
301 : // A bare glyph paints into whatever box it is handed, and the button floors
302 : // its content to a square, so centre it or it draws at the button's size.
303 2 : return Center(
304 : widthFactor: 1,
305 : heightFactor: 1,
306 2 : child: FossGlyphIcon(
307 8 : forward == ltr ? ChevronRightGlyph(color) : ChevronLeftGlyph(color),
308 2 : size: icon.size,
309 : ),
310 : );
311 : }
312 : }
313 :
314 : /// The resolved row appearance: the gap, the button shape, and the ellipsis.
315 : @immutable
316 : class _PaginationVisuals {
317 2 : const _PaginationVisuals({
318 : required this.gap,
319 : required this.buttonSize,
320 : required this.activeVariant,
321 : required this.inactiveVariant,
322 : required this.ellipsisColor,
323 : required this.ellipsisWidth,
324 : });
325 :
326 2 : factory _PaginationVisuals.resolve(
327 : FossThemeData theme,
328 : FossPaginationStyle? s, {
329 : required double slot,
330 2 : }) => _PaginationVisuals(
331 6 : gap: s?.gap ?? theme.spacing(1),
332 2 : buttonSize: s?.buttonSize ?? FossButtonSize.md,
333 2 : activeVariant: s?.activeVariant ?? FossButtonVariant.outline,
334 2 : inactiveVariant: s?.inactiveVariant ?? FossButtonVariant.ghost,
335 6 : ellipsisColor: s?.ellipsisColor ?? theme.colors.mutedForeground,
336 : // Matching the button's occupied width keeps every slot the same size, so
337 : // the row holds its width as ellipses come and go.
338 2 : ellipsisWidth: s?.ellipsisWidth ?? slot,
339 : );
340 :
341 : final double gap;
342 : final FossButtonSize buttonSize;
343 : final FossButtonVariant activeVariant;
344 : final FossButtonVariant inactiveVariant;
345 : final Color ellipsisColor;
346 : final double ellipsisWidth;
347 : }
|