aboutsummaryrefslogtreecommitdiff
path: root/lib/widgets/stats
diff options
context:
space:
mode:
Diffstat (limited to 'lib/widgets/stats')
-rw-r--r--lib/widgets/stats/date/axis.dart97
-rw-r--r--lib/widgets/stats/date/histogram.dart386
-rw-r--r--lib/widgets/stats/filter_table.dart124
-rw-r--r--lib/widgets/stats/mime_donut.dart43
-rw-r--r--lib/widgets/stats/percent_text.dart33
-rw-r--r--lib/widgets/stats/stats_page.dart439
-rw-r--r--lib/widgets/stats/top_page.dart128
7 files changed, 1250 insertions, 0 deletions
diff --git a/lib/widgets/stats/date/axis.dart b/lib/widgets/stats/date/axis.dart
new file mode 100644
index 0000000..01bca20
--- /dev/null
+++ b/lib/widgets/stats/date/axis.dart
@@ -0,0 +1,97 @@
+import 'dart:math';
+
+import 'package:aves/model/filters/date.dart';
+import 'package:aves/utils/time_utils.dart';
+import 'package:charts_flutter/flutter.dart' as charts;
+import 'package:intl/intl.dart';
+
+// cf charts.DateTimeTickFormatter factory internals for default formats
+class TimeAxisSpec {
+ final List<charts.TickSpec<DateTime>> tickSpecs;
+
+ TimeAxisSpec(this.tickSpecs);
+
+ factory TimeAxisSpec.forLevel({
+ required String locale,
+ required DateLevel level,
+ required DateTime first,
+ required DateTime last,
+ }) {
+ switch (level) {
+ case DateLevel.ymd:
+ return TimeAxisSpec.days(locale, first, last);
+ case DateLevel.ym:
+ return TimeAxisSpec.months(locale, first, last);
+ case DateLevel.y:
+ default:
+ return TimeAxisSpec.years(locale, first, last);
+ }
+ }
+
+ factory TimeAxisSpec.days(String locale, DateTime first, DateTime last) {
+ final daysTickLongFormat = DateFormat.MMMd(locale);
+ final daysTickShortFormat = DateFormat.d(locale);
+
+ first = first.date;
+ last = last.date;
+ final rangeDays = last.difference(first).inHumanDays;
+ final delta = max(1, (rangeDays / 5).ceil());
+
+ List<charts.TickSpec<DateTime>> ticks = [];
+ int lastContext = -1;
+ DateFormat dateFormat;
+ for (int i = 0; i < rangeDays; i += delta) {
+ final tickDate = first.addDays(i);
+ if (lastContext != tickDate.month) {
+ lastContext = tickDate.month;
+ dateFormat = daysTickLongFormat;
+ } else {
+ dateFormat = daysTickShortFormat;
+ }
+ ticks.add(charts.TickSpec<DateTime>(tickDate, label: dateFormat.format(tickDate)));
+ }
+ return TimeAxisSpec(ticks);
+ }
+
+ factory TimeAxisSpec.months(String locale, DateTime first, DateTime last) {
+ final monthsTickLongFormat = DateFormat.yMMM(locale);
+ final monthsTickShortFormat = DateFormat.MMM(locale);
+
+ first = DateTime(first.year, first.month);
+ last = DateTime(last.year, last.month);
+ final rangeMonths = last.month - first.month + (last.month < first.month ? 12 : 0);
+ if (rangeMonths < 12) {
+ first = first.addMonths(-((12 - rangeMonths) / 2).floor());
+ }
+
+ List<charts.TickSpec<DateTime>> ticks = [];
+ int lastContext = -1;
+ DateFormat dateFormat;
+ for (int i = 0; i < DateTime.monthsPerYear; i += 3) {
+ final tickDate = first.addMonths(2 + i);
+ if (lastContext != tickDate.year) {
+ lastContext = tickDate.year;
+ dateFormat = monthsTickLongFormat;
+ } else {
+ dateFormat = monthsTickShortFormat;
+ }
+ ticks.add(charts.TickSpec<DateTime>(tickDate, label: dateFormat.format(tickDate)));
+ }
+ return TimeAxisSpec(ticks);
+ }
+
+ factory TimeAxisSpec.years(String locale, DateTime first, DateTime last) {
+ final dateFormat = DateFormat.y(locale);
+
+ final firstYear = first.year;
+ final lastYear = last.year;
+ final delta = max(1, ((lastYear - firstYear) / 5).ceil());
+
+ List<charts.TickSpec<DateTime>> ticks = [];
+ for (int year = firstYear; year <= lastYear; year += delta) {
+ final tickDate = DateTime(year);
+ ticks.add(charts.TickSpec<DateTime>(tickDate, label: dateFormat.format(tickDate)));
+ }
+ return TimeAxisSpec(ticks);
+ }
+}
diff --git a/lib/widgets/stats/date/histogram.dart b/lib/widgets/stats/date/histogram.dart
new file mode 100644
index 0000000..acc6cb2
--- /dev/null
+++ b/lib/widgets/stats/date/histogram.dart
@@ -0,0 +1,386 @@
+import 'dart:async';
+import 'dart:math';
+
+import 'package:aves/model/entry/entry.dart';
+import 'package:aves/model/entry/sort.dart';
+import 'package:aves/model/filters/date.dart';
+import 'package:aves/theme/durations.dart';
+import 'package:aves/theme/themes.dart';
+import 'package:aves/utils/time_utils.dart';
+import 'package:aves/widgets/common/extensions/build_context.dart';
+import 'package:aves/widgets/common/fx/transitions.dart';
+import 'package:aves/widgets/common/identity/aves_filter_chip.dart';
+import 'package:aves/widgets/stats/date/axis.dart';
+import 'package:charts_flutter/flutter.dart' as charts;
+import 'package:collection/collection.dart';
+import 'package:equatable/equatable.dart';
+import 'package:flutter/foundation.dart';
+import 'package:flutter/material.dart';
+import 'package:flutter/scheduler.dart';
+import 'package:intl/intl.dart';
+import 'package:provider/provider.dart';
+
+class Histogram extends StatefulWidget {
+ final Set<AvesEntry> entries;
+ final Duration animationDuration;
+ final AFilterCallback onFilterSelection;
+
+ const Histogram({
+ super.key,
+ required this.entries,
+ required this.animationDuration,
+ required this.onFilterSelection,
+ });
+
+ @override
+ State<Histogram> createState() => _HistogramState();
+}
+
+class _HistogramState extends State<Histogram> with AutomaticKeepAliveClientMixin {
+ DateLevel _level = DateLevel.y;
+ DateTime? _firstDate, _lastDate;
+ final Map<DateTime, int> _entryCountPerDate = {};
+ final ValueNotifier<_EntryByDate?> _selection = ValueNotifier(null);
+ List<_EntryByDate>? _seriesData;
+ late Future<List<_EntryByDate>?> _interpolatedDataLoader;
+ late Future<void> _areaChartLoader;
+
+ static const histogramHeight = 200.0;
+
+ Duration get animationDuration => widget.animationDuration;
+
+ @override
+ void initState() {
+ super.initState();
+
+ final entriesByDateDescending = List.of(widget.entries)..sort(AvesEntrySort.compareByDate);
+ var lastDate = entriesByDateDescending.firstWhereOrNull((entry) => entry.bestDate != null)?.bestDate;
+ var firstDate = entriesByDateDescending.lastWhereOrNull((entry) => entry.bestDate != null)?.bestDate;
+
+ if (lastDate != null && firstDate != null) {
+ final rangeDays = lastDate.difference(firstDate).inHumanDays;
+ if (rangeDays > 1) {
+ if (rangeDays <= 31) {
+ _level = DateLevel.ymd;
+ } else if (rangeDays <= 365) {
+ _level = DateLevel.ym;
+ }
+
+ late DateTime Function(DateTime) normalizeDate;
+ switch (_level) {
+ case DateLevel.ymd:
+ normalizeDate = (v) => DateTime(v.year, v.month, v.day);
+ case DateLevel.ym:
+ normalizeDate = (v) => DateTime(v.year, v.month);
+ default:
+ normalizeDate = (v) => DateTime(v.year);
+ }
+ _firstDate = normalizeDate(firstDate);
+ _lastDate = normalizeDate(lastDate);
+
+ final dates = entriesByDateDescending.map((entry) => entry.bestDate).nonNulls;
+ _entryCountPerDate.addAll(groupBy<DateTime, DateTime>(dates, normalizeDate).map((k, v) => MapEntry(k, v.length)));
+ if (_entryCountPerDate.isNotEmpty) {
+ // discrete points
+ _seriesData = _entryCountPerDate.entries.map((kv) {
+ return _EntryByDate(date: kv.key, entryCount: kv.value);
+ }).toList();
+
+ // smooth curve
+ _interpolatedDataLoader = compute<_DataInterpolationArg, List<_EntryByDate>?>(
+ _computeInterpolatedData,
+ _DataInterpolationArg(
+ firstDate: _firstDate,
+ lastDate: _lastDate,
+ level: _level,
+ entryCountPerDate: _entryCountPerDate,
+ ));
+ _areaChartLoader = _interpolatedDataLoader.then((_) => Future.delayed(animationDuration * timeDilation));
+ }
+ }
+ }
+ }
+
+ static List<_EntryByDate>? _computeInterpolatedData(_DataInterpolationArg arg) {
+ final firstDate = arg.firstDate;
+ final lastDate = arg.lastDate;
+ final level = arg.level;
+ final entryCountPerDate = arg.entryCountPerDate;
+
+ if (firstDate == null || lastDate == null) return null;
+
+ final xRange = lastDate.difference(firstDate);
+ final xRangeInMillis = xRange.inMilliseconds;
+ late int xCount;
+ late DateTime Function(DateTime date) incrementDate;
+ switch (level) {
+ case DateLevel.ymd:
+ xCount = xRange.inHumanDays;
+ incrementDate = (date) => DateTime(date.year, date.month, date.day + 1);
+ case DateLevel.ym:
+ xCount = (xRange.inHumanDays / 30.5).round();
+ incrementDate = (date) => DateTime(date.year, date.month + 1);
+ default:
+ xCount = lastDate.year - firstDate.year;
+ incrementDate = (date) => DateTime(date.year + 1);
+ }
+ final yMax = entryCountPerDate.values.reduce(max).toDouble();
+ final xInterval = yMax / xCount;
+ final controlPoints = <Offset>[];
+ var date = firstDate;
+ for (int i = 0; i <= xCount; i++) {
+ controlPoints.add(Offset(i * xInterval, (entryCountPerDate[date] ?? 0).toDouble()));
+ date = incrementDate(date);
+ }
+ final interpolatedPoints = controlPoints.length > 3 ? CatmullRomSpline(controlPoints).generateSamples().map((sample) => sample.value).toList() : controlPoints;
+ final interpolatedData = interpolatedPoints.map((p) {
+ final date = firstDate.add(Duration(milliseconds: p.dx * xRangeInMillis ~/ yMax));
+ final entryCount = p.dy.clamp(0, yMax);
+ return _EntryByDate(date: date, entryCount: entryCount);
+ }).toList();
+
+ return interpolatedData;
+ }
+
+ @override
+ Widget build(BuildContext context) {
+ super.build(context);
+
+ if (_seriesData == null) return const SizedBox();
+
+ return FutureBuilder<List<_EntryByDate>?>(
+ future: _interpolatedDataLoader,
+ builder: (context, snapshot) {
+ final interpolatedData = snapshot.data;
+ return Column(
+ mainAxisSize: MainAxisSize.min,
+ children: [
+ Container(
+ padding: const EdgeInsets.symmetric(horizontal: 8),
+ height: histogramHeight,
+ child: AnimatedSwitcher(
+ duration: animationDuration,
+ child: interpolatedData != null
+ ? Stack(
+ children: [
+ FutureBuilder<void>(
+ future: _areaChartLoader,
+ builder: (context, snapshot) {
+ Widget child = const SizedBox();
+ if (snapshot.connectionState == ConnectionState.done) {
+ child = _buildChart(context, interpolatedData, isInterpolated: true, isArea: true);
+ }
+ return AnimatedSwitcher(
+ duration: animationDuration,
+ child: child,
+ );
+ },
+ ),
+ _buildChart(context, interpolatedData, isInterpolated: true, isArea: false),
+ _buildChart(context, _seriesData!, isInterpolated: false, isArea: false),
+ ],
+ )
+ : const SizedBox(),
+ ),
+ ),
+ _buildSelectionRow(),
+ ],
+ );
+ },
+ );
+ }
+
+ Widget _buildChart(BuildContext context, List<_EntryByDate> seriesData, {required bool isInterpolated, required bool isArea}) {
+ final drawArea = isInterpolated && isArea;
+ final drawLine = isInterpolated && !isArea;
+ final drawPoints = !isInterpolated;
+
+ final colorScheme = Theme.of(context).colorScheme;
+ final accentColor = colorScheme.primary;
+ final axisColor = charts.ColorUtil.fromDartColor(drawPoints ? colorScheme.onSurface : Colors.transparent);
+ final measureLineColor = charts.ColorUtil.fromDartColor(drawPoints ? colorScheme.onSurface.withValues(alpha: .1) : Colors.transparent);
+ final histogramLineColor = charts.ColorUtil.fromDartColor(drawLine ? accentColor : Colors.white);
+ final histogramPointStrikeColor = charts.ColorUtil.fromDartColor(drawPoints ? colorScheme.onSurface : Colors.transparent);
+ final histogramPointFillColor = charts.ColorUtil.fromDartColor(Themes.firstLayerColor(context));
+
+ final series = [
+ if (drawLine || drawArea)
+ charts.Series<_EntryByDate, DateTime>(
+ id: 'curve',
+ data: seriesData,
+ domainFn: (d, i) => d.date,
+ measureFn: (d, i) => d.entryCount,
+ colorFn: (d, i) => histogramLineColor,
+ ),
+ if (drawPoints && !drawArea)
+ charts.Series<_EntryByDate, DateTime>(
+ id: 'points',
+ data: seriesData,
+ domainFn: (d, i) => d.date,
+ measureFn: (d, i) => d.entryCount,
+ colorFn: (d, i) => histogramPointStrikeColor,
+ fillColorFn: (d, i) => histogramPointFillColor,
+ )..setAttribute(charts.rendererIdKey, 'customPoint'),
+ ];
+
+ final locale = context.locale;
+ final timeAxisSpec = _firstDate != null && _lastDate != null
+ ? TimeAxisSpec.forLevel(
+ locale: locale,
+ level: _level,
+ first: _firstDate!,
+ last: _lastDate!,
+ )
+ : null;
+ final tickFormatter = NumberFormat.decimalPattern(locale);
+
+ final domainAxis = charts.DateTimeAxisSpec(
+ renderSpec: charts.SmallTickRendererSpec(
+ labelStyle: charts.TextStyleSpec(color: axisColor),
+ lineStyle: charts.LineStyleSpec(color: axisColor),
+ ),
+ tickProviderSpec: timeAxisSpec != null && timeAxisSpec.tickSpecs.isNotEmpty ? charts.StaticDateTimeTickProviderSpec(timeAxisSpec.tickSpecs) : null,
+ );
+
+ Widget chart = charts.TimeSeriesChart(
+ series,
+ animate: false,
+ animationDuration: animationDuration,
+ domainAxis: domainAxis,
+ primaryMeasureAxis: charts.NumericAxisSpec(
+ renderSpec: charts.GridlineRendererSpec(
+ labelStyle: charts.TextStyleSpec(color: axisColor),
+ lineStyle: charts.LineStyleSpec(color: measureLineColor),
+ ),
+ tickFormatterSpec: charts.BasicNumericTickFormatterSpec((v) {
+ // localize and hide 0
+ return (v == null || v == 0) ? '' : tickFormatter.format(v);
+ }),
+ ),
+ defaultRenderer: charts.LineRendererConfig(
+ includeArea: drawArea,
+ areaOpacity: 1,
+ ),
+ customSeriesRenderers: [
+ charts.PointRendererConfig(
+ customRendererId: 'customPoint',
+ strokeWidthPx: 2,
+ symbolRenderer: _CircleSymbolRenderer(isSolid: false),
+ ),
+ ],
+ defaultInteractions: false,
+ behaviors: drawPoints
+ ? [
+ charts.SelectNearest(),
+ charts.LinePointHighlighter(
+ defaultRadiusPx: 8,
+ radiusPaddingPx: 2,
+ showHorizontalFollowLine: charts.LinePointHighlighterFollowLineType.nearest,
+ showVerticalFollowLine: charts.LinePointHighlighterFollowLineType.nearest,
+ ),
+ ]
+ : null,
+ selectionModels: [
+ charts.SelectionModelConfig(
+ changedListener: (model) => _selection.value = model.selectedDatum.firstOrNull?.datum as _EntryByDate?,
+ )
+ ],
+ );
+ if (drawArea) {
+ chart = ShaderMask(
+ shaderCallback: LinearGradient(
+ begin: Alignment.topCenter,
+ end: Alignment.bottomCenter,
+ colors: [
+ accentColor,
+ accentColor.withAlpha(0),
+ ],
+ ).createShader,
+ blendMode: BlendMode.srcIn,
+ child: chart,
+ );
+ }
+ return chart;
+ }
+
+ Widget _buildSelectionRow() {
+ final countFormatter = NumberFormat.decimalPattern(context.locale);
+
+ return ValueListenableBuilder<_EntryByDate?>(
+ valueListenable: _selection,
+ builder: (context, selection, child) {
+ late Widget child;
+ if (selection == null) {
+ child = const SizedBox();
+ } else {
+ final filter = DateFilter(_level, selection.date);
+ final count = selection.entryCount;
+ child = Padding(
+ padding: const EdgeInsets.all(8),
+ child: Row(
+ children: [
+ AvesFilterChip(
+ filter: filter,
+ onTap: widget.onFilterSelection,
+ ),
+ const Spacer(),
+ Text(
+ countFormatter.format(count),
+ style: TextStyle(
+ color: Theme.of(context).colorScheme.onSurfaceVariant,
+ ),
+ textAlign: TextAlign.end,
+ ),
+ ],
+ ),
+ );
+ }
+
+ return AnimatedSwitcher(
+ duration: context.read<DurationsData>().formTransition,
+ switchInCurve: Curves.easeInOutCubic,
+ switchOutCurve: Curves.easeInOutCubic,
+ transitionBuilder: AvesTransitions.formTransitionBuilder,
+ child: child,
+ );
+ },
+ );
+ }
+
+ @override
+ bool get wantKeepAlive => true;
+}
+
+@immutable
+class _EntryByDate extends Equatable {
+ final DateTime date;
+ final num entryCount;
+
+ @override
+ List<Object?> get props => [date, entryCount];
+
+ const _EntryByDate({
+ required this.date,
+ required this.entryCount,
+ });
+}
+
+class _CircleSymbolRenderer extends charts.CircleSymbolRenderer {
+ _CircleSymbolRenderer({super.isSolid = true});
+
+ @override
+ charts.Color? getSolidFillColor(charts.Color? fillColor) => fillColor;
+}
+
+class _DataInterpolationArg {
+ final DateLevel level;
+ final DateTime? firstDate, lastDate;
+ final Map<DateTime, int> entryCountPerDate;
+
+ const _DataInterpolationArg({
+ required this.level,
+ required this.firstDate,
+ required this.lastDate,
+ required this.entryCountPerDate,
+ });
+}
diff --git a/lib/widgets/stats/filter_table.dart b/lib/widgets/stats/filter_table.dart
new file mode 100644
index 0000000..b3d36a4
--- /dev/null
+++ b/lib/widgets/stats/filter_table.dart
@@ -0,0 +1,124 @@
+import 'package:aves/model/filters/filters.dart';
+import 'package:aves/model/settings/settings.dart';
+import 'package:aves/theme/themes.dart';
+import 'package:aves/widgets/common/extensions/build_context.dart';
+import 'package:aves/widgets/common/identity/aves_filter_chip.dart';
+import 'package:aves/widgets/stats/percent_text.dart';
+import 'package:aves_model/aves_model.dart';
+import 'package:flutter/material.dart';
+import 'package:intl/intl.dart';
+import 'package:percent_indicator/linear_percent_indicator.dart';
+import 'package:provider/provider.dart';
+
+class FilterTable<T extends Comparable> extends StatelessWidget {
+ final int totalEntryCount;
+ final Map<T, int> entryCountMap;
+ final CollectionFilter Function(T key) filterBuilder;
+ final bool sortByCount;
+ final int? maxRowCount;
+ final AFilterCallback onFilterSelection;
+
+ const FilterTable({
+ super.key,
+ required this.totalEntryCount,
+ required this.entryCountMap,
+ required this.filterBuilder,
+ required this.sortByCount,
+ required this.maxRowCount,
+ required this.onFilterSelection,
+ });
+
+ static const chipWidth = 160.0;
+ static const countWidth = 32.0;
+ static const percentIndicatorMinWidth = 80.0;
+
+ @override
+ Widget build(BuildContext context) {
+ final countFormatter = NumberFormat.decimalPattern(context.locale);
+ final animate = context.select<Settings, bool>((v) => v.animate);
+
+ final sortedEntries = entryCountMap.entries.toList();
+ if (sortByCount) {
+ sortedEntries.sort((kv1, kv2) {
+ final c = kv2.value.compareTo(kv1.value);
+ return c != 0 ? c : kv1.key.compareTo(kv2.key);
+ });
+ }
+
+ final textScaler = MediaQuery.textScalerOf(context);
+ final lineHeight = textScaler.scale(16);
+ final barRadius = Radius.circular(lineHeight / 2);
+ final isRtl = context.isRtl;
+
+ return Padding(
+ padding: const EdgeInsetsDirectional.only(start: AvesFilterChip.outlineWidth / 2 + 6, end: 8),
+ child: LayoutBuilder(
+ builder: (context, constraints) {
+ final showPercentIndicator = constraints.maxWidth - (chipWidth + countWidth) > percentIndicatorMinWidth;
+ final displayedEntries = maxRowCount != null ? sortedEntries.take(maxRowCount!) : sortedEntries;
+ final isMonochrome = settings.themeColorMode == AvesThemeColorMode.monochrome;
+ return Table(
+ children: displayedEntries.map((kv) {
+ final filter = filterBuilder(kv.key);
+ final count = kv.value;
+ final percent = count / totalEntryCount;
+ final colorScheme = Theme.of(context).colorScheme;
+ return TableRow(
+ children: [
+ Container(
+ // the `Table` `border` property paints on the cells and does not add margins,
+ // so we define margins here instead, but they should be symmetric
+ // to keep all cells vertically aligned on the center/middle
+ margin: const EdgeInsets.symmetric(vertical: 4),
+ alignment: AlignmentDirectional.centerStart,
+ child: AvesFilterChip(
+ filter: filter,
+ onTap: onFilterSelection,
+ ),
+ ),
+ if (showPercentIndicator)
+ FutureBuilder<Color>(
+ future: filter.color(context),
+ builder: (context, snapshot) {
+ final color = snapshot.data;
+ return Stack(
+ // use a stack instead of `center` field, so that the widgets
+ // are centered even when the center child has larger height
+ alignment: Alignment.center,
+ children: [
+ LinearPercentIndicator(
+ percent: percent,
+ lineHeight: lineHeight,
+ backgroundColor: Themes.secondLayerColor(context),
+ progressColor: isMonochrome ? colorScheme.primary : color,
+ animation: animate,
+ isRTL: isRtl,
+ barRadius: barRadius,
+ padding: EdgeInsets.symmetric(horizontal: lineHeight),
+ ),
+ LinearPercentIndicatorText(percent: percent),
+ ],
+ );
+ },
+ ),
+ Text(
+ countFormatter.format(count),
+ style: TextStyle(
+ color: colorScheme.onSurfaceVariant,
+ ),
+ textAlign: TextAlign.end,
+ ),
+ ],
+ );
+ }).toList(),
+ columnWidths: const {
+ 0: MaxColumnWidth(IntrinsicColumnWidth(), FixedColumnWidth(chipWidth)),
+ 2: MaxColumnWidth(IntrinsicColumnWidth(), FixedColumnWidth(countWidth)),
+ },
+ defaultVerticalAlignment: TableCellVerticalAlignment.middle,
+ );
+ },
+ ),
+ );
+ }
+}
diff --git a/lib/widgets/stats/mime_donut.dart b/lib/widgets/stats/mime_donut.dart
new file mode 100644
index 0000000..45fcf5a
--- /dev/null
+++ b/lib/widgets/stats/mime_donut.dart
@@ -0,0 +1,43 @@
+import 'package:aves/model/filters/mime.dart';
+import 'package:aves/theme/colors.dart';
+import 'package:aves/utils/mime_utils.dart';
+import 'package:aves/widgets/common/extensions/build_context.dart';
+import 'package:aves/widgets/common/identity/aves_donut.dart';
+import 'package:aves/widgets/common/identity/aves_filter_chip.dart';
+import 'package:flutter/material.dart';
+import 'package:intl/intl.dart';
+import 'package:provider/provider.dart';
+
+class MimeDonut extends StatelessWidget {
+ final IconData icon;
+ final Map<String, int> byMimeTypes;
+ final Duration animationDuration;
+ final AFilterCallback onFilterSelection;
+
+ const MimeDonut({
+ super.key,
+ required this.icon,
+ required this.byMimeTypes,
+ required this.animationDuration,
+ required this.onFilterSelection,
+ });
+
+ @override
+ Widget build(BuildContext context) {
+ final countFormatter = NumberFormat.decimalPattern(context.locale);
+
+ String formatKey(d) => MimeUtils.displayType(d.key);
+ return AvesDonut(
+ title: Icon(icon),
+ byTypes: byMimeTypes,
+ animationDuration: animationDuration,
+ formatKey: formatKey,
+ formatValue: countFormatter.format,
+ colorize: (context, d) {
+ final colors = context.read<AvesColorsData>();
+ return colors.fromString(formatKey(d));
+ },
+ onTap: (d) => onFilterSelection(MimeFilter(d.key)),
+ );
+ }
+}
diff --git a/lib/widgets/stats/percent_text.dart b/lib/widgets/stats/percent_text.dart
new file mode 100644
index 0000000..ed7247b
--- /dev/null
+++ b/lib/widgets/stats/percent_text.dart
@@ -0,0 +1,33 @@
+import 'package:aves/theme/styles.dart';
+import 'package:aves/theme/themes.dart';
+import 'package:aves/widgets/common/basic/text/outlined.dart';
+import 'package:aves/widgets/common/extensions/build_context.dart';
+import 'package:aves/widgets/common/extensions/theme.dart';
+import 'package:flutter/material.dart';
+import 'package:intl/intl.dart';
+
+class LinearPercentIndicatorText extends StatelessWidget {
+ final double percent;
+
+ const LinearPercentIndicatorText({
+ super.key,
+ required this.percent,
+ });
+
+ @override
+ Widget build(BuildContext context) {
+ final percentFormatter = NumberFormat.percentPattern(context.locale);
+
+ return OutlinedText(
+ textSpans: [
+ TextSpan(
+ text: percentFormatter.format(percent),
+ style: TextStyle(
+ shadows: Theme.of(context).isDark ? AStyles.embossShadows : null,
+ ),
+ )
+ ],
+ outlineColor: Themes.firstLayerColor(context),
+ );
+ }
+}
diff --git a/lib/widgets/stats/stats_page.dart b/lib/widgets/stats/stats_page.dart
new file mode 100644
index 0000000..0cf3b93
--- /dev/null
+++ b/lib/widgets/stats/stats_page.dart
@@ -0,0 +1,439 @@
+import 'dart:async';
+
+import 'package:aves/model/entry/entry.dart';
+import 'package:aves/model/filters/covered/location.dart';
+import 'package:aves/model/filters/covered/stored_album.dart';
+import 'package:aves/model/filters/covered/tag.dart';
+import 'package:aves/model/filters/filters.dart';
+import 'package:aves/model/filters/rating.dart';
+import 'package:aves/model/settings/settings.dart';
+import 'package:aves/model/source/collection_lens.dart';
+import 'package:aves/model/source/collection_source.dart';
+import 'package:aves/theme/durations.dart';
+import 'package:aves/theme/format.dart';
+import 'package:aves/theme/icons.dart';
+import 'package:aves/theme/styles.dart';
+import 'package:aves/theme/themes.dart';
+import 'package:aves/utils/file_utils.dart';
+import 'package:aves/widgets/collection/collection_page.dart';
+import 'package:aves/widgets/common/action_mixins/feedback.dart';
+import 'package:aves/widgets/common/action_mixins/vault_aware.dart';
+import 'package:aves/widgets/common/basic/insets.dart';
+import 'package:aves/widgets/common/basic/scaffold.dart';
+import 'package:aves/widgets/common/basic/tv_edge_focus.dart';
+import 'package:aves/widgets/common/extensions/build_context.dart';
+import 'package:aves/widgets/common/identity/empty.dart';
+import 'package:aves/widgets/stats/date/histogram.dart';
+import 'package:aves/widgets/stats/filter_table.dart';
+import 'package:aves/widgets/stats/mime_donut.dart';
+import 'package:aves/widgets/stats/percent_text.dart';
+import 'package:aves/widgets/stats/top_page.dart';
+import 'package:aves/widgets/viewer/controls/notifications.dart';
+import 'package:collection/collection.dart';
+import 'package:flutter/material.dart';
+import 'package:flutter/scheduler.dart';
+import 'package:flutter_staggered_animations/flutter_staggered_animations.dart';
+import 'package:percent_indicator/linear_percent_indicator.dart';
+import 'package:provider/provider.dart';
+
+class StatsPage extends StatefulWidget {
+ static const routeName = '/collection/stats';
+
+ final Set<AvesEntry> entries;
+ final CollectionSource source;
+ final CollectionLens? parentCollection;
+
+ const StatsPage({
+ super.key,
+ required this.entries,
+ required this.source,
+ this.parentCollection,
+ });
+
+ @override
+ State<StatsPage> createState() => _StatsPageState();
+}
+
+class _StatsPageState extends State<StatsPage> with FeedbackMixin, VaultAwareMixin {
+ final Map<String, int> _entryCountPerCountry = {}, _entryCountPerState = {}, _entryCountPerPlace = {};
+ final Map<String, int> _entryCountPerTag = {}, _entryCountPerAlbum = {};
+ final Map<int, int> _entryCountPerRating = Map.fromEntries(List.generate(7, (i) => MapEntry(5 - i, 0)));
+ late final ValueNotifier<bool> _isPageAnimatingNotifier;
+ int _totalSizeBytes = 0;
+ int _totalDurationMillis = 0;
+
+ Set<AvesEntry> get entries => widget.entries;
+
+ @override
+ void initState() {
+ super.initState();
+
+ _isPageAnimatingNotifier = ValueNotifier(true);
+ Future.delayed(ADurations.pageTransitionLoose * timeDilation).then((_) {
+ if (!mounted) return;
+ _isPageAnimatingNotifier.value = false;
+ });
+
+ entries.forEach((entry) {
+ _totalSizeBytes += entry.sizeBytes ?? 0;
+ _totalDurationMillis += entry.durationMillis ?? 0;
+
+ if (entry.hasAddress) {
+ final address = entry.addressDetails!;
+ var country = address.countryName;
+ if (country != null && country.isNotEmpty) {
+ country += '${LocationFilter.locationSeparator}${address.countryCode}';
+ _entryCountPerCountry[country] = (_entryCountPerCountry[country] ?? 0) + 1;
+ }
+ var state = address.stateName;
+ if (state != null && state.isNotEmpty) {
+ state += '${LocationFilter.locationSeparator}${address.stateCode}';
+ _entryCountPerState[state] = (_entryCountPerState[state] ?? 0) + 1;
+ }
+ final place = address.place;
+ if (place != null && place.isNotEmpty) {
+ _entryCountPerPlace[place] = (_entryCountPerPlace[place] ?? 0) + 1;
+ }
+ }
+
+ entry.tags.forEach((tag) {
+ _entryCountPerTag[tag] = (_entryCountPerTag[tag] ?? 0) + 1;
+ });
+
+ final album = entry.directory;
+ if (album != null) {
+ _entryCountPerAlbum[album] = (_entryCountPerAlbum[album] ?? 0) + 1;
+ }
+
+ final rating = entry.rating;
+ _entryCountPerRating[rating] = (_entryCountPerRating[rating] ?? 0) + 1;
+ });
+ }
+
+ @override
+ void dispose() {
+ _isPageAnimatingNotifier.dispose();
+ super.dispose();
+ }
+
+ @override
+ Widget build(BuildContext context) {
+ final useTvLayout = settings.useTvLayout;
+ return ValueListenableBuilder<bool>(
+ valueListenable: _isPageAnimatingNotifier,
+ builder: (context, animating, child) {
+ final l10n = context.l10n;
+
+ Widget child = const SizedBox();
+
+ if (!animating) {
+ final durations = context.watch<DurationsData>();
+
+ if (entries.isEmpty) {
+ child = EmptyContent(
+ icon: AIcons.image,
+ text: l10n.collectionEmptyImages,
+ );
+ } else {
+ final chartAnimationDuration = context.read<DurationsData>().chartTransition;
+
+ final byMimeTypes = groupBy<AvesEntry, String>(entries, (entry) => entry.mimeType).map<String, int>((k, v) => MapEntry(k, v.length));
+ final imagesByMimeTypes = Map.fromEntries(byMimeTypes.entries.where((kv) => kv.key.startsWith('image')));
+ final videoByMimeTypes = Map.fromEntries(byMimeTypes.entries.where((kv) => kv.key.startsWith('video')));
+ final mimeDonuts = Wrap(
+ alignment: WrapAlignment.center,
+ crossAxisAlignment: WrapCrossAlignment.center,
+ children: [
+ MimeDonut(
+ icon: AIcons.image,
+ byMimeTypes: imagesByMimeTypes,
+ animationDuration: chartAnimationDuration,
+ onFilterSelection: (filter) => _onFilterSelection(context, filter),
+ ),
+ MimeDonut(
+ icon: AIcons.video,
+ byMimeTypes: videoByMimeTypes,
+ animationDuration: chartAnimationDuration,
+ onFilterSelection: (filter) => _onFilterSelection(context, filter),
+ ),
+ ],
+ );
+
+ final showRatings = _entryCountPerRating.entries.any((kv) => kv.key != 0 && kv.value > 0);
+ final source = widget.source;
+ child = NotificationListener<SelectFilterNotification>(
+ onNotification: (notification) {
+ _onFilterSelection(context, notification.filter);
+ return true;
+ },
+ child: AnimationLimiter(
+ child: ListView(
+ children: AnimationConfiguration.toStaggeredList(
+ duration: durations.staggeredAnimation,
+ delay: durations.staggeredAnimationDelay * timeDilation,
+ childAnimationBuilder: (child) => SlideAnimation(
+ verticalOffset: 50.0,
+ child: FadeInAnimation(
+ child: child,
+ ),
+ ),
+ children: [
+ const TvEdgeFocus(),
+ mimeDonuts,
+ Histogram(
+ entries: entries,
+ animationDuration: chartAnimationDuration,
+ onFilterSelection: (filter) => _onFilterSelection(context, filter),
+ ),
+ const SizedBox(height: 16),
+ _buildTotalSizeIndicator(context),
+ if (_totalDurationMillis > 0) ...[
+ const SizedBox(height: 16),
+ _buildTotalDurationIndicator(),
+ ],
+ const SizedBox(height: 16),
+ _LocationIndicator(entries: entries),
+ ..._buildFilterSection<String>(context, l10n.statsTopCountriesSectionTitle, _entryCountPerCountry, (v) => LocationFilter(LocationLevel.country, v)),
+ ..._buildFilterSection<String>(context, l10n.statsTopStatesSectionTitle, _entryCountPerState, (v) => LocationFilter(LocationLevel.state, v)),
+ ..._buildFilterSection<String>(context, l10n.statsTopPlacesSectionTitle, _entryCountPerPlace, (v) => LocationFilter(LocationLevel.place, v)),
+ ..._buildFilterSection<String>(context, l10n.statsTopTagsSectionTitle, _entryCountPerTag, TagFilter.new),
+ ..._buildFilterSection<String>(context, l10n.statsTopAlbumsSectionTitle, _entryCountPerAlbum, (v) => StoredAlbumFilter(v, source.getStoredAlbumDisplayName(context, v))),
+ if (showRatings) ..._buildFilterSection<int>(context, l10n.searchRatingSectionTitle, _entryCountPerRating, RatingFilter.new, sortByCount: false, maxRowCount: null),
+ ],
+ ),
+ ),
+ ),
+ );
+ }
+ }
+
+ return AvesScaffold(
+ appBar: AppBar(
+ automaticallyImplyLeading: !useTvLayout,
+ title: Text(l10n.statsPageTitle),
+ ),
+ body: GestureAreaProtectorStack(
+ child: SafeArea(
+ bottom: false,
+ child: TooltipTheme(
+ data: TooltipTheme.of(context).copyWith(
+ preferBelow: false,
+ ),
+ child: child,
+ ),
+ ),
+ ),
+ );
+ },
+ );
+ }
+
+ Widget _buildTotalSizeIndicator(BuildContext context) {
+ return Padding(
+ padding: const EdgeInsets.symmetric(horizontal: 16),
+ child: Row(
+ mainAxisSize: MainAxisSize.min,
+ children: [
+ const Icon(AIcons.size),
+ const SizedBox(width: 16),
+ Expanded(
+ child: Text(formatFileSize(context.locale, _totalSizeBytes)),
+ ),
+ ],
+ ),
+ );
+ }
+
+ Widget _buildTotalDurationIndicator() {
+ return Padding(
+ padding: const EdgeInsets.symmetric(horizontal: 16),
+ child: Row(
+ mainAxisSize: MainAxisSize.min,
+ children: [
+ const Icon(AIcons.videoPlay),
+ const SizedBox(width: 16),
+ Expanded(
+ child: Text(formatFriendlyDuration(Duration(milliseconds: _totalDurationMillis))),
+ ),
+ ],
+ ),
+ );
+ }
+
+ List<Widget> _buildFilterSection<T extends Comparable>(
+ BuildContext context,
+ String title,
+ Map<T, int> entryCountMap,
+ CollectionFilter Function(T key) filterBuilder, {
+ bool sortByCount = true,
+ int? maxRowCount = 3,
+ }) {
+ if (entryCountMap.isEmpty) return [];
+
+ final totalEntryCount = entries.length;
+ final hasMore = maxRowCount != null && entryCountMap.length > maxRowCount;
+ final onHeaderPressed = hasMore
+ ? () => Navigator.maybeOf(context)?.push(
+ MaterialPageRoute(
+ settings: const RouteSettings(name: StatsTopPage.routeName),
+ builder: (context) => StatsTopPage(
+ title: title,
+ totalEntryCount: totalEntryCount,
+ entryCountMap: entryCountMap,
+ filterBuilder: filterBuilder,
+ sortByCount: sortByCount,
+ onFilterSelection: (filter) => _onFilterSelection(context, filter),
+ ),
+ ),
+ )
+ : null;
+ Widget header = Text(
+ title,
+ style: AStyles.knownTitleText,
+ );
+ if (settings.useTvLayout) {
+ header = Padding(
+ padding: const EdgeInsets.all(16),
+ child: Row(
+ mainAxisSize: MainAxisSize.min,
+ children: [
+ header,
+ const SizedBox(width: 16),
+ Icon(AIcons.next, color: hasMore ? null : Theme.of(context).disabledColor),
+ ],
+ ),
+ );
+ header = Container(
+ padding: const EdgeInsets.symmetric(vertical: 12),
+ alignment: AlignmentDirectional.centerStart,
+ // prevent ink response when tapping the header does nothing,
+ // because otherwise Play Store reviewers think it is broken navigation
+ child: onHeaderPressed != null
+ ? InkWell(
+ onTap: onHeaderPressed,
+ borderRadius: const BorderRadius.all(Radius.circular(123)),
+ child: header,
+ )
+ : Focus(child: header),
+ );
+ } else {
+ header = Padding(
+ padding: const EdgeInsets.all(16),
+ child: Row(
+ children: [
+ header,
+ const Spacer(),
+ IconButton(
+ icon: const Icon(AIcons.next),
+ onPressed: onHeaderPressed,
+ tooltip: MaterialLocalizations.of(context).moreButtonTooltip,
+ ),
+ ],
+ ),
+ );
+ }
+
+ return [
+ header,
+ FilterTable(
+ totalEntryCount: totalEntryCount,
+ entryCountMap: entryCountMap,
+ filterBuilder: filterBuilder,
+ sortByCount: sortByCount,
+ maxRowCount: maxRowCount,
+ onFilterSelection: (filter) => _onFilterSelection(context, filter),
+ ),
+ ];
+ }
+
+ Future<void> _onFilterSelection(BuildContext context, CollectionFilter filter) async {
+ if (!await unlockFilter(context, filter)) return;
+
+ if (widget.parentCollection != null) {
+ _applyToParentCollectionPage(context, filter);
+ } else {
+ _jumpToCollectionPage(context, filter);
+ }
+ }
+
+ void _applyToParentCollectionPage(BuildContext context, CollectionFilter filter) {
+ widget.parentCollection!.addFilters({filter});
+ // We delay closing the current page after applying the filter selection
+ // so that hero animation target is ready in the `FilterBar`,
+ // even when the target is a child of an `AnimatedList`.
+ // Do not use `WidgetsBinding.instance.addPostFrameCallback`,
+ // as it may not trigger if there is no subsequent build.
+ Future.delayed(const Duration(milliseconds: 100), () => Navigator.maybeOf(context)?.popUntil((route) => route.settings.name == CollectionPage.routeName));
+ }
+
+ void _jumpToCollectionPage(BuildContext context, CollectionFilter filter) {
+ Navigator.maybeOf(context)?.pushAndRemoveUntil(
+ MaterialPageRoute(
+ settings: const RouteSettings(name: CollectionPage.routeName),
+ builder: (context) => CollectionPage(
+ source: widget.source,
+ filters: {filter},
+ ),
+ ),
+ (route) => false,
+ );
+ }
+}
+
+class _LocationIndicator extends StatelessWidget {
+ final Set<AvesEntry> entries;
+
+ const _LocationIndicator({required this.entries});
+
+ @override
+ Widget build(BuildContext context) {
+ final theme = Theme.of(context);
+ final catalogued = entries.where((entry) => entry.isCatalogued);
+ final withGps = catalogued.where((entry) => entry.hasGps);
+ final withGpsCount = withGps.length;
+ final withGpsPercent = withGpsCount / entries.length;
+ final textScaler = MediaQuery.textScalerOf(context);
+ final lineHeight = textScaler.scale(16);
+ final barRadius = Radius.circular(lineHeight / 2);
+ return Padding(
+ padding: const EdgeInsets.symmetric(horizontal: 16),
+ child: Column(
+ children: [
+ Row(
+ mainAxisSize: MainAxisSize.min,
+ children: [
+ const Icon(AIcons.location),
+ Expanded(
+ child: Stack(
+ // use a stack instead of `center` field, so that the widgets
+ // are centered even when the center child has larger height
+ alignment: Alignment.center,
+ children: [
+ LinearPercentIndicator(
+ percent: withGpsPercent,
+ lineHeight: lineHeight,
+ backgroundColor: Themes.secondLayerColor(context),
+ progressColor: theme.colorScheme.primary,
+ animation: context.select<Settings, bool>((v) => v.animate),
+ isRTL: context.isRtl,
+ barRadius: barRadius,
+ padding: EdgeInsets.symmetric(horizontal: lineHeight),
+ ),
+ LinearPercentIndicatorText(percent: withGpsPercent),
+ ],
+ ),
+ ),
+ // end padding to match leading, so that inside label is aligned with outside label below
+ const SizedBox(width: 24),
+ ],
+ ),
+ const SizedBox(height: 8),
+ Text(
+ context.l10n.statsWithGps(withGpsCount),
+ textAlign: TextAlign.center,
+ ),
+ ],
+ ),
+ );
+ }
+}
diff --git a/lib/widgets/stats/top_page.dart b/lib/widgets/stats/top_page.dart
new file mode 100644
index 0000000..3531a0e
--- /dev/null
+++ b/lib/widgets/stats/top_page.dart
@@ -0,0 +1,128 @@
+import 'dart:convert';
+import 'dart:typed_data';
+
+import 'package:aves/model/filters/covered/stored_album.dart';
+import 'package:aves/model/filters/filters.dart';
+import 'package:aves/model/settings/settings.dart';
+import 'package:aves/ref/locales.dart';
+import 'package:aves/ref/mime_types.dart';
+import 'package:aves/services/common/services.dart';
+import 'package:aves/theme/icons.dart';
+import 'package:aves/widgets/common/action_mixins/feedback.dart';
+import 'package:aves/widgets/common/basic/insets.dart';
+import 'package:aves/widgets/common/basic/scaffold.dart';
+import 'package:aves/widgets/common/extensions/build_context.dart';
+import 'package:aves/widgets/common/extensions/media_query.dart';
+import 'package:aves/widgets/common/identity/aves_filter_chip.dart';
+import 'package:aves/widgets/stats/filter_table.dart';
+import 'package:aves/widgets/viewer/controls/notifications.dart';
+import 'package:csv/csv.dart';
+import 'package:flutter/material.dart';
+import 'package:intl/intl.dart';
+import 'package:provider/provider.dart';
+
+class StatsTopPage<T extends Comparable> extends StatelessWidget with FeedbackMixin {
+ static const routeName = '/collection/stats/top';
+
+ final String title;
+ final int totalEntryCount;
+ final Map<T, int> entryCountMap;
+ final CollectionFilter Function(T key) filterBuilder;
+ final bool sortByCount;
+ final AFilterCallback onFilterSelection;
+
+ const StatsTopPage({
+ super.key,
+ required this.title,
+ required this.totalEntryCount,
+ required this.entryCountMap,
+ required this.filterBuilder,
+ required this.sortByCount,
+ required this.onFilterSelection,
+ });
+
+ @override
+ Widget build(BuildContext context) {
+ return AvesScaffold(
+ appBar: AppBar(
+ automaticallyImplyLeading: !settings.useTvLayout,
+ title: Text(title),
+ actions: [
+ IconButton(
+ icon: Icon(AIcons.fileExport),
+ onPressed: () => _export(context),
+ tooltip: context.l10n.settingsActionExport,
+ ),
+ ],
+ ),
+ body: GestureAreaProtectorStack(
+ child: SafeArea(
+ bottom: false,
+ child: Builder(builder: (context) {
+ return NotificationListener<SelectFilterNotification>(
+ onNotification: (notification) {
+ onFilterSelection(notification.filter);
+ return true;
+ },
+ child: SingleChildScrollView(
+ padding: const EdgeInsets.symmetric(vertical: 8) +
+ EdgeInsets.only(
+ bottom: context.select<MediaQueryData, double>((mq) => mq.effectiveBottomPadding),
+ ),
+ child: FilterTable(
+ totalEntryCount: totalEntryCount,
+ entryCountMap: entryCountMap,
+ filterBuilder: filterBuilder,
+ sortByCount: sortByCount,
+ maxRowCount: null,
+ onFilterSelection: onFilterSelection,
+ ),
+ ),
+ );
+ }),
+ ),
+ ),
+ );
+ }
+
+ Future<void> _export(BuildContext context) async {
+ final sortedEntries = entryCountMap.entries.toList();
+ if (sortByCount) {
+ sortedEntries.sort((kv1, kv2) {
+ final c = kv2.value.compareTo(kv1.value);
+ return c != 0 ? c : kv1.key.compareTo(kv2.key);
+ });
+ }
+
+ final csv = const ListToCsvConverter().convert([
+ [title, '#'],
+ ...sortedEntries.map((kv) {
+ final filter = filterBuilder(kv.key);
+ final count = kv.value;
+
+ String label;
+ switch (filter) {
+ case StoredAlbumFilter _:
+ label = filter.album;
+ default:
+ label = filter.getLabel(context);
+ }
+ return [label, count];
+ })
+ ]);
+
+ const mimeType = MimeTypes.csv;
+ final success = await storageService.createFile(
+ 'aves-stats-${DateFormat('yyyyMMdd_HHmmss', asciiLocale).format(DateTime.now())}${MimeTypes.extensionFor(mimeType)}',
+ mimeType,
+ Uint8List.fromList(utf8.encode(csv)),
+ );
+ if (success != null) {
+ if (success) {
+ showFeedback(context, FeedbackType.info, context.l10n.genericSuccessFeedback);
+ } else {
+ showFeedback(context, FeedbackType.warn, context.l10n.genericFailureFeedback);
+ }
+ }
+ }
+}