Filter out sub-categories, fix off-by-one index

This commit is contained in:
Roland Geider
2026-07-11 00:31:35 +02:00
parent 8ae054dfe8
commit cbb960bdef
15 changed files with 481 additions and 74 deletions

View File

@@ -91,17 +91,21 @@ final class MeasurementNotifier extends _$MeasurementNotifier {
await _repo.addLocalDriftCategory(category);
}
/// Moves the top-level category at [oldIndex] to [newIndex] and renumbers
/// all top-level categories accordingly.
///
/// Indices refer to the top-level list only (children of multi-value groups
/// keep their in-group order).
Future<void> setCategoryOrder(int oldIndex, int newIndex) async {
final categories = state.asData?.value;
if (categories == null) return;
if (oldIndex < newIndex) newIndex -= 1;
if (categories == null) {
return;
}
final reordered = List<MeasurementCategory>.from(categories);
final reordered = categories.where((c) => c.parentId == null).toList();
final moved = reordered.removeAt(oldIndex);
reordered.insert(newIndex, moved);
for (int i = 0; i < reordered.length; i++) {
await _repo.reorderCategory(reordered[i].id!, i);
}
await _repo.reorderCategories([for (final c in reordered) c.id!]);
}
}

View File

@@ -33,7 +33,7 @@ final class MeasurementNotifierProvider
MeasurementNotifier create() => MeasurementNotifier();
}
String _$measurementNotifierHash() => r'397b6739b5d49e226b1ca3bb1837b2f16c55e0f7';
String _$measurementNotifierHash() => r'2072d9a5dd3b0c64830913541d236f5dfe28fbbc';
abstract class _$MeasurementNotifier extends $StreamNotifier<List<MeasurementCategory>> {
Stream<List<MeasurementCategory>> build();

View File

@@ -56,7 +56,7 @@ class MeasurementRepository {
])..orderBy([
OrderingTerm(expression: _db.measurementCategoryTable.order),
OrderingTerm(expression: _db.measurementCategoryTable.name),
// OrderingTerm(expression: _db.measurementEntryTable.date, mode: OrderingMode.desc),
OrderingTerm(expression: _db.measurementEntryTable.date, mode: OrderingMode.desc),
]);
return joined.watch().map((rows) {
@@ -147,11 +147,17 @@ class MeasurementRepository {
await _db.into(_db.measurementCategoryTable).insert(category.toCompanion());
}
Future<void> reorderCategory(String id, int newOrder) async {
_logger.finer('Reording category id $id to order $newOrder');
final stmt = _db.update(_db.measurementCategoryTable)..where((t) => t.id.equals(id));
await stmt.write(
MeasurementCategoryTableCompanion(order: Value(newOrder)),
);
/// Persists the given display order: each category gets its list index as
/// [MeasurementCategory.order]. Categories whose order is unchanged are not
/// written, so no sync upload is queued for them.
Future<void> reorderCategories(List<String> orderedIds) async {
_logger.finer('Reordering ${orderedIds.length} categories');
await _db.transaction(() async {
for (var i = 0; i < orderedIds.length; i++) {
final stmt = _db.update(_db.measurementCategoryTable)
..where((t) => t.id.equals(orderedIds[i]) & t.order.equals(i).not());
await stmt.write(MeasurementCategoryTableCompanion(order: Value(i)));
}
});
}
}

View File

@@ -37,7 +37,7 @@ class MeasurementCategoriesScreen extends StatelessWidget {
title: Text(AppLocalizations.of(context).measurements),
actions: [
IconButton(
icon: Icon(Icons.sort),
icon: const Icon(Icons.sort),
tooltip: i18n.reorderCategories,
onPressed: () =>
Navigator.of(context).pushNamed(MeasurementCategorySortScreen.routeName),

View File

@@ -1,59 +1,79 @@
import 'package:flutter/material.dart';
import 'package:flutter_riverpod/flutter_riverpod.dart';
import 'package:wger/core/wide_screen_wrapper.dart';
import 'package:wger/core/widgets/async_value_widget.dart';
import 'package:wger/features/measurements/models/measurement_category.dart';
import 'package:wger/features/measurements/providers/measurement_notifier.dart';
import 'package:wger/l10n/generated/app_localizations.dart';
class MeasurementCategorySortScreen extends ConsumerWidget {
static const routeName = '/measurement-categories-sort';
const MeasurementCategorySortScreen({super.key});
@override
Widget build(BuildContext context, WidgetRef ref) {
final i18n = AppLocalizations.of(context);
return Scaffold(
appBar: AppBar(
title: Text(i18n.reorderCategories),
),
body: WidescreenWrapper(
child: AsyncValueWidget<List<MeasurementCategory>>(
value: ref.watch(measurementProvider),
loggerName: 'MeasurementCategorySortScreen',
data: (categories) => _SortableList(categories),
),
),
);
}
}
class _SortableList extends ConsumerWidget {
final List<MeasurementCategory> _categories;
const _SortableList(this._categories);
@override
Widget build(BuildContext context, WidgetRef ref) {
final notifier = ref.read(measurementProvider.notifier);
return ReorderableListView.builder(
// physics: const NeverScrollableScrollPhysics(),
// shrinkWrap: true,
// buildDefaultDragHandles: false,
itemCount: _categories.length,
itemBuilder: (context, index) {
final category = _categories[index];
return ListTile(
key: ValueKey(category.id),
title: Text(category.name),
subtitle: Text(category.unit),
trailing: ReorderableDelayedDragStartListener(
index: index,
child: const Icon(Icons.drag_handle),
),
);
},
onReorderItem: (oldIndex, newIndex) => notifier.setCategoryOrder(oldIndex, newIndex),
);
}
}
/*
* This file is part of wger Workout Manager <https://github.com/wger-project>.
* Copyright (c) 2026 wger Team
*
* wger Workout Manager is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
import 'package:flutter/material.dart';
import 'package:flutter_riverpod/flutter_riverpod.dart';
import 'package:wger/core/wide_screen_wrapper.dart';
import 'package:wger/core/widgets/async_value_widget.dart';
import 'package:wger/features/measurements/models/measurement_category.dart';
import 'package:wger/features/measurements/providers/measurement_notifier.dart';
import 'package:wger/l10n/generated/app_localizations.dart';
/// Drag-and-drop reordering of the top-level measurement categories.
///
/// Children of multi-value groups are not listed; they keep their in-group
/// order and follow their parent.
class MeasurementCategorySortScreen extends ConsumerWidget {
static const routeName = '/measurement-categories-sort';
const MeasurementCategorySortScreen({super.key});
@override
Widget build(BuildContext context, WidgetRef ref) {
final i18n = AppLocalizations.of(context);
return Scaffold(
appBar: AppBar(
title: Text(i18n.reorderCategories),
),
body: WidescreenWrapper(
child: AsyncValueWidget<List<MeasurementCategory>>(
value: ref.watch(measurementProvider),
loggerName: 'MeasurementCategorySortScreen',
data: (categories) => _SortableList(categories.where((c) => c.parentId == null).toList()),
),
),
);
}
}
class _SortableList extends ConsumerWidget {
final List<MeasurementCategory> _categories;
const _SortableList(this._categories);
@override
Widget build(BuildContext context, WidgetRef ref) {
final notifier = ref.read(measurementProvider.notifier);
return ReorderableListView.builder(
buildDefaultDragHandles: false,
itemCount: _categories.length,
itemBuilder: (context, index) {
final category = _categories[index];
return ListTile(
key: ValueKey(category.id),
title: Text(category.name),
subtitle: Text(category.unit),
trailing: ReorderableDragStartListener(
index: index,
child: const Icon(Icons.drag_handle),
),
);
},
onReorderItem: notifier.setCategoryOrder,
);
}
}

View File

@@ -185,4 +185,13 @@ class MockMeasurementRepository extends _i1.Mock implements _i7.MeasurementRepos
returnValueForMissingStub: _i4.Future<void>.value(),
)
as _i4.Future<void>);
@override
_i4.Future<void> reorderCategories(List<String>? orderedIds) =>
(super.noSuchMethod(
Invocation.method(#reorderCategories, [orderedIds]),
returnValue: _i4.Future<void>.value(),
returnValueForMissingStub: _i4.Future<void>.value(),
)
as _i4.Future<void>);
}

View File

@@ -20,6 +20,7 @@ import 'package:flutter_riverpod/flutter_riverpod.dart';
import 'package:flutter_test/flutter_test.dart';
import 'package:mockito/annotations.dart';
import 'package:mockito/mockito.dart';
import 'package:wger/features/measurements/models/measurement_category.dart';
import 'package:wger/features/measurements/providers/measurement_notifier.dart';
import 'package:wger/features/measurements/providers/measurement_repository.dart';
@@ -102,4 +103,62 @@ void main() {
verify(mockRepo.watchAll()).called(1);
});
});
group('setCategoryOrder', () {
// Body fat ('1') and Biceps ('2') from the shared test data plus a third
// top-level category.
final categories = [
...getMeasurementCategories(),
MeasurementCategory(id: '3', name: 'Waist', unit: 'cm'),
];
setUp(() {
when(mockRepo.watchAll()).thenAnswer((_) => Stream.value(categories));
when(mockRepo.reorderCategories(any)).thenAnswer((_) async {});
});
// Loads the notifier with its state resolved from the watchAll stream.
Future<MeasurementNotifier> loadedNotifier() async {
container.listen(measurementProvider, (_, _) {});
await pumpEventQueue();
return container.read(measurementProvider.notifier);
}
test('moves an item down (newIndex already adjusted, onReorderItem semantics)', () async {
final notifier = await loadedNotifier();
await notifier.setCategoryOrder(0, 2);
verify(mockRepo.reorderCategories(['2', '3', '1'])).called(1);
});
test('moves an item up', () async {
final notifier = await loadedNotifier();
await notifier.setCategoryOrder(2, 0);
verify(mockRepo.reorderCategories(['3', '1', '2'])).called(1);
});
test('excludes children of multi-value groups', () async {
when(mockRepo.watchAll()).thenAnswer(
(_) => Stream.value([
categories[0],
MeasurementCategory(id: '2a', name: 'Left', unit: 'cm', parentId: '2'),
categories[1],
categories[2],
]),
);
final notifier = await loadedNotifier();
await notifier.setCategoryOrder(0, 1);
verify(mockRepo.reorderCategories(['2', '1', '3'])).called(1);
});
test('does nothing while the list is still loading', () async {
when(mockRepo.watchAll()).thenAnswer((_) => const Stream.empty());
final notifier = await loadedNotifier();
await notifier.setCategoryOrder(0, 1);
verifyNever(mockRepo.reorderCategories(any));
});
});
}

View File

@@ -127,4 +127,13 @@ class MockMeasurementRepository extends _i1.Mock implements _i2.MeasurementRepos
returnValueForMissingStub: _i3.Future<void>.value(),
)
as _i3.Future<void>);
@override
_i3.Future<void> reorderCategories(List<String>? orderedIds) =>
(super.noSuchMethod(
Invocation.method(#reorderCategories, [orderedIds]),
returnValue: _i3.Future<void>.value(),
returnValueForMissingStub: _i3.Future<void>.value(),
)
as _i3.Future<void>);
}

View File

@@ -287,4 +287,40 @@ void main() {
expect(emitted, isEmpty);
});
});
group('reorderCategories', () {
test('persists the list positions as order', () async {
await repo.addLocalDriftCategory(MeasurementCategory(id: 'c1', name: 'Aaa', unit: 'cm'));
await repo.addLocalDriftCategory(MeasurementCategory(id: 'c2', name: 'Bbb', unit: 'cm'));
await repo.addLocalDriftCategory(MeasurementCategory(id: 'c3', name: 'Ccc', unit: 'cm'));
await repo.reorderCategories(['c3', 'c1', 'c2']);
final emitted = await repo.watchAll().first;
expect(emitted.map((c) => c.id), ['c3', 'c1', 'c2']);
expect(emitted.map((c) => c.order), [0, 1, 2]);
});
test('keeps the in-group order of children', () async {
await repo.addLocalDriftCategory(
MeasurementCategory(id: 'bp', name: 'Blood pressure', unit: 'mmHg'),
);
await repo.addLocalDriftCategory(
MeasurementCategory(id: 'sys', name: 'Systolic', unit: 'mmHg', parentId: 'bp', order: 0),
);
await repo.addLocalDriftCategory(
MeasurementCategory(id: 'dia', name: 'Diastolic', unit: 'mmHg', parentId: 'bp', order: 1),
);
await repo.addLocalDriftCategory(
MeasurementCategory(id: 'c1', name: 'Waist', unit: 'cm', order: 1),
);
await repo.reorderCategories(['c1', 'bp']);
final emitted = await repo.watchAll().first;
final parent = emitted.firstWhere((c) => c.id == 'bp');
expect(parent.order, 1);
expect(parent.children.map((c) => c.id), ['sys', 'dia']);
});
});
}

View File

@@ -127,4 +127,13 @@ class MockMeasurementRepository extends _i1.Mock implements _i2.MeasurementRepos
returnValueForMissingStub: _i3.Future<void>.value(),
)
as _i3.Future<void>);
@override
_i3.Future<void> reorderCategories(List<String>? orderedIds) =>
(super.noSuchMethod(
Invocation.method(#reorderCategories, [orderedIds]),
returnValue: _i3.Future<void>.value(),
returnValueForMissingStub: _i3.Future<void>.value(),
)
as _i3.Future<void>);
}

View File

@@ -0,0 +1,89 @@
/*
* This file is part of wger Workout Manager <https://github.com/wger-project>.
* Copyright (c) 2026 wger Team
*
* wger Workout Manager is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
import 'package:flutter/material.dart';
import 'package:flutter_riverpod/flutter_riverpod.dart';
import 'package:flutter_test/flutter_test.dart';
import 'package:mockito/annotations.dart';
import 'package:mockito/mockito.dart';
import 'package:wger/features/measurements/models/measurement_category.dart';
import 'package:wger/features/measurements/providers/measurement_repository.dart';
import 'package:wger/features/measurements/screens/measurement_category_sort_screen.dart';
import 'package:wger/l10n/generated/app_localizations.dart';
import '../../../../test_data/measurements.dart';
import 'measurement_category_sort_screen_test.mocks.dart';
@GenerateMocks([MeasurementRepository])
void main() {
late MockMeasurementRepository mockRepo;
// Body fat ('1') and Biceps ('2') from the shared test data plus a third
// top-level category and a group child.
final categories = [
...getMeasurementCategories(),
MeasurementCategory(id: '2a', name: 'Left', unit: 'cm', parentId: '2'),
MeasurementCategory(id: '3', name: 'Waist', unit: 'cm'),
];
setUp(() {
mockRepo = MockMeasurementRepository();
when(mockRepo.watchAll()).thenAnswer((_) => Stream.value(categories));
when(mockRepo.reorderCategories(any)).thenAnswer((_) async {});
});
Widget createSortScreen() {
return ProviderScope(
overrides: [
measurementRepositoryProvider.overrideWithValue(mockRepo),
],
child: const MaterialApp(
localizationsDelegates: AppLocalizations.localizationsDelegates,
supportedLocales: AppLocalizations.supportedLocales,
home: MeasurementCategorySortScreen(),
),
);
}
testWidgets('lists only top-level categories', (tester) async {
await tester.pumpWidget(createSortScreen());
await tester.pumpAndSettle();
expect(find.text('Body fat'), findsOneWidget);
expect(find.text('Biceps'), findsOneWidget);
expect(find.text('Waist'), findsOneWidget);
expect(find.text('Left'), findsNothing);
expect(find.byIcon(Icons.drag_handle), findsNWidgets(3));
});
testWidgets('dragging an item to the bottom persists the new order', (tester) async {
await tester.pumpWidget(createSortScreen());
await tester.pumpAndSettle();
final firstHandle = find.byIcon(Icons.drag_handle).first;
final itemHeight = tester.getSize(find.byType(ListTile).first).height;
await tester.timedDrag(
firstHandle,
Offset(0, itemHeight * 3),
const Duration(milliseconds: 300),
);
await tester.pumpAndSettle();
verify(mockRepo.reorderCategories(['2', '3', '1'])).called(1);
});
}

View File

@@ -0,0 +1,139 @@
// Mocks generated by Mockito 5.4.6 from annotations
// in wger/test/features/measurements/screens/measurement_category_sort_screen_test.dart.
// Do not manually edit this file.
// ignore_for_file: no_leading_underscores_for_library_prefixes
import 'dart:async' as _i3;
import 'package:mockito/mockito.dart' as _i1;
import 'package:wger/features/measurements/models/measurement_category.dart' as _i4;
import 'package:wger/features/measurements/models/measurement_entry.dart' as _i5;
import 'package:wger/features/measurements/providers/measurement_repository.dart' as _i2;
// ignore_for_file: type=lint
// ignore_for_file: avoid_redundant_argument_values
// ignore_for_file: avoid_setters_without_getters
// ignore_for_file: comment_references
// ignore_for_file: deprecated_member_use
// ignore_for_file: deprecated_member_use_from_same_package
// ignore_for_file: implementation_imports
// ignore_for_file: invalid_use_of_visible_for_testing_member
// ignore_for_file: must_be_immutable
// ignore_for_file: prefer_const_constructors
// ignore_for_file: unnecessary_parenthesis
// ignore_for_file: camel_case_types
// ignore_for_file: subtype_of_sealed_class
// ignore_for_file: invalid_use_of_internal_member
/// A class which mocks [MeasurementRepository].
///
/// See the documentation for Mockito's code generation for more information.
class MockMeasurementRepository extends _i1.Mock implements _i2.MeasurementRepository {
MockMeasurementRepository() {
_i1.throwOnMissingStub(this);
}
@override
_i3.Stream<List<_i4.MeasurementCategory>> watchAll() =>
(super.noSuchMethod(
Invocation.method(#watchAll, []),
returnValue: _i3.Stream<List<_i4.MeasurementCategory>>.empty(),
)
as _i3.Stream<List<_i4.MeasurementCategory>>);
@override
_i3.Stream<_i4.MeasurementCategory?> watchLocalDriftCategoryById(
String? id,
) =>
(super.noSuchMethod(
Invocation.method(#watchLocalDriftCategoryById, [id]),
returnValue: _i3.Stream<_i4.MeasurementCategory?>.empty(),
)
as _i3.Stream<_i4.MeasurementCategory?>);
@override
_i3.Future<List<_i4.MeasurementCategory>> getAllOnce() =>
(super.noSuchMethod(
Invocation.method(#getAllOnce, []),
returnValue: _i3.Future<List<_i4.MeasurementCategory>>.value(
<_i4.MeasurementCategory>[],
),
)
as _i3.Future<List<_i4.MeasurementCategory>>);
@override
_i3.Future<void> deleteLocalDrift(String? id) =>
(super.noSuchMethod(
Invocation.method(#deleteLocalDrift, [id]),
returnValue: _i3.Future<void>.value(),
returnValueForMissingStub: _i3.Future<void>.value(),
)
as _i3.Future<void>);
@override
_i3.Future<void> updateLocalDrift(_i5.MeasurementEntry? entry) =>
(super.noSuchMethod(
Invocation.method(#updateLocalDrift, [entry]),
returnValue: _i3.Future<void>.value(),
returnValueForMissingStub: _i3.Future<void>.value(),
)
as _i3.Future<void>);
@override
_i3.Future<void> addLocalDrift(_i5.MeasurementEntry? entry) =>
(super.noSuchMethod(
Invocation.method(#addLocalDrift, [entry]),
returnValue: _i3.Future<void>.value(),
returnValueForMissingStub: _i3.Future<void>.value(),
)
as _i3.Future<void>);
@override
_i3.Future<void> addLocalDriftGroupEntries(
List<_i5.MeasurementEntry>? entries,
) =>
(super.noSuchMethod(
Invocation.method(#addLocalDriftGroupEntries, [entries]),
returnValue: _i3.Future<void>.value(),
returnValueForMissingStub: _i3.Future<void>.value(),
)
as _i3.Future<void>);
@override
_i3.Future<void> deleteLocalDriftCategory(String? id) =>
(super.noSuchMethod(
Invocation.method(#deleteLocalDriftCategory, [id]),
returnValue: _i3.Future<void>.value(),
returnValueForMissingStub: _i3.Future<void>.value(),
)
as _i3.Future<void>);
@override
_i3.Future<void> updateLocalDriftCategory(
_i4.MeasurementCategory? category,
) =>
(super.noSuchMethod(
Invocation.method(#updateLocalDriftCategory, [category]),
returnValue: _i3.Future<void>.value(),
returnValueForMissingStub: _i3.Future<void>.value(),
)
as _i3.Future<void>);
@override
_i3.Future<void> addLocalDriftCategory(_i4.MeasurementCategory? category) =>
(super.noSuchMethod(
Invocation.method(#addLocalDriftCategory, [category]),
returnValue: _i3.Future<void>.value(),
returnValueForMissingStub: _i3.Future<void>.value(),
)
as _i3.Future<void>);
@override
_i3.Future<void> reorderCategories(List<String>? orderedIds) =>
(super.noSuchMethod(
Invocation.method(#reorderCategories, [orderedIds]),
returnValue: _i3.Future<void>.value(),
returnValueForMissingStub: _i3.Future<void>.value(),
)
as _i3.Future<void>);
}

View File

@@ -136,6 +136,15 @@ class MockMeasurementRepository extends _i1.Mock implements _i2.MeasurementRepos
returnValueForMissingStub: _i3.Future<void>.value(),
)
as _i3.Future<void>);
@override
_i3.Future<void> reorderCategories(List<String>? orderedIds) =>
(super.noSuchMethod(
Invocation.method(#reorderCategories, [orderedIds]),
returnValue: _i3.Future<void>.value(),
returnValueForMissingStub: _i3.Future<void>.value(),
)
as _i3.Future<void>);
}
/// A class which mocks [NutritionRepository].

View File

@@ -548,6 +548,15 @@ class MockMeasurementRepository extends _i1.Mock implements _i23.MeasurementRepo
returnValueForMissingStub: _i10.Future<void>.value(),
)
as _i10.Future<void>);
@override
_i10.Future<void> reorderCategories(List<String>? orderedIds) =>
(super.noSuchMethod(
Invocation.method(#reorderCategories, [orderedIds]),
returnValue: _i10.Future<void>.value(),
returnValueForMissingStub: _i10.Future<void>.value(),
)
as _i10.Future<void>);
}
/// A class which mocks [UserProfileRepository].

View File

@@ -127,4 +127,13 @@ class MockMeasurementRepository extends _i1.Mock implements _i2.MeasurementRepos
returnValueForMissingStub: _i3.Future<void>.value(),
)
as _i3.Future<void>);
@override
_i3.Future<void> reorderCategories(List<String>? orderedIds) =>
(super.noSuchMethod(
Invocation.method(#reorderCategories, [orderedIds]),
returnValue: _i3.Future<void>.value(),
returnValueForMissingStub: _i3.Future<void>.value(),
)
as _i3.Future<void>);
}