Repository navigation
feat(habits): add custom sort functionality with drag-and-drop support - #42
Conversation
Implement comprehensive custom sort system for habits that mirrors the existing task functionality: - Add order field to Habit entity and database schema - Create UpdateHabitOrderCommand with proper order calculation logic - Implement drag-and-drop reordering in habits list UI with visual feedback - Add custom sort option to habit list options menu - Include drag handles in both compact and full view modes - Fix UI/Backend synchronization issues with proper order value handling - Auto-calculate order for new habits to maintain proper sorting sequence - Update database migration to assign default order values to existing habits The implementation ensures habits can be manually reordered just like tasks, with persistent order values and smooth drag-and-drop experience across all view modes.
There was a problem hiding this comment.
Summary of Changes
Hello @ahmet-cetinkaya, I'm Gemini Code Assist1! I'm currently reviewing this pull request and will post my feedback shortly. In the meantime, here's a summary to help you and other reviewers quickly get up to speed!
This pull request introduces a significant enhancement to the habit management feature by enabling custom sorting with drag-and-drop functionality. The core purpose is to provide users with the flexibility to manually organize their habits in any desired sequence, moving beyond predefined sorting options. This involves fundamental changes to the data model to support an 'order' property, the implementation of new commands for updating habit order, and comprehensive updates to the user interface to facilitate the drag-and-drop interaction. The impact is a more personalized and efficient habit tracking experience, allowing users to prioritize and arrange their habits according to their personal workflow.
Highlights
- Custom Habit Sorting: Users can now manually reorder their habits using an intuitive drag-and-drop interface, providing greater control over their habit organization.
- Database Schema Update: A new 'order' field has been added to the Habit entity and its corresponding database schema, along with a migration to ensure existing habits receive an initial order value.
- Automatic Order Calculation: New habits are automatically assigned an order value upon creation, maintaining a consistent sequence without manual intervention.
- Enhanced User Interface: Dedicated UI components, including drag handles in both compact and full view modes, have been implemented to facilitate the reordering process.
- UI-Backend Synchronization: The system ensures seamless synchronization between visual reordering actions in the UI and the persistence of these changes in the backend database.
Using Gemini Code Assist
The full guide for Gemini Code Assist can be found on our documentation page, here are some quick tips.
Invoking Gemini
You can request assistance from Gemini at any point in your pull request via creating an issue comment (i.e. comment on the pull request page) using either /gemini <command> or @gemini-code-assist <command>. Below is a summary of the supported commands.
| Feature | Command | Description |
|---|---|---|
| Code Review | /gemini review |
Performs a code review for the current pull request in its current state. |
| Pull Request Summary | /gemini summary |
Provides a summary of the current pull request in its current state. |
| Comment | @gemini-code-assist | Responds in comments when explicitly tagged, both in issue comments and review comments. |
| Help | /gemini help |
Displays a list of available commands. |
Customization
To customize Gemini Code Assist for GitHub experience, repository maintainers can create a configuration file and/or provide a custom code review style guide (such as PEP-8 for Python) by creating and adding files to a .gemini/ folder in the base of the repository. Detailed instructions can be found here.
Limitations & Feedback
Gemini Code Assist may make mistakes. Please leave feedback on any instances where its feedback is incorrect or counter productive. You can react with 👍 and 👎 on @gemini-code-assist comments. If you're interested in giving your feedback about your experience with Gemini Code Assist for Github and other Google products, sign up here.
You can also get AI-powered code generation, chat, as well as code reviews directly in the IDE at no cost with the Gemini Code Assist IDE Extension.
Footnotes
-
Review the Privacy Notices, Generative AI Prohibited Use Policy, Terms of Service, and learn how to configure Gemini Code Assist in GitHub here. Gemini can make mistakes, so double check it and use code with caution. ↩
There was a problem hiding this comment.
Code Review
This pull request introduces custom sorting for habits using drag-and-drop, which is a great feature. The implementation is comprehensive, covering database migrations, new commands for ordering, and UI components for reordering. My review focuses on improving performance, consistency, and code clarity. I've identified a potential performance bottleneck in the order normalization logic, suggested simplifications in command and UI logic, and recommended refactoring for better maintainability.
| for (var h in allHabits) { | ||
| h.order = orderStep; | ||
| h.modifiedDate = DateTime.now().toUtc(); | ||
| await _habitRepository.update(h); | ||
| orderStep += OrderRank.initialStep; | ||
| } |
There was a problem hiding this comment.
Updating habits inside a for loop results in multiple database calls, which is inefficient and can lead to performance issues, especially with a large number of habits. It's better to perform these updates in a single batch operation.
Consider adding a batch update method to your IHabitRepository, like updateAll(List<Habit> habits), that can update multiple records in a single transaction.
| final double beforeHabitOrder; | ||
| final double afterHabitOrder; | ||
|
|
||
| UpdateHabitOrderCommand({ | ||
| required this.habitId, | ||
| required this.beforeHabitOrder, | ||
| required this.afterHabitOrder, |
There was a problem hiding this comment.
The beforeHabitOrder parameter is unused in the command handler. This, along with the validation logic for afterHabitOrder (lines 51-63), suggests some redundancy with the UI layer (habits_list.dart), which already calculates a target order.
To improve clarity and maintain a single source of truth:
- Remove the unused
beforeHabitOrderparameter. - Consider removing the validation logic for
afterHabitOrderif the command can trust the value from the UI. If validation is necessary here as a safeguard, ensure the logic is consistent with the UI's calculation to prevent discrepancies.
final double afterHabitOrder;
UpdateHabitOrderCommand({
required this.habitId,
required this.afterHabitOrder,
});| if (newIndex == 0) { | ||
| final firstOrder = existingOrders.isNotEmpty ? existingOrders.first : OrderRank.initialStep; | ||
|
|
||
| if (firstOrder <= 0 || firstOrder < 1e-10) { | ||
| targetOrder = OrderRank.initialStep / 2; | ||
| } else if (firstOrder < 1e-6) { | ||
| targetOrder = firstOrder / 1000; | ||
| } else { | ||
| targetOrder = firstOrder - OrderRank.initialStep; | ||
| if (targetOrder <= 0) { | ||
| targetOrder = firstOrder / 2; | ||
| } | ||
| } | ||
| } else { | ||
| targetOrder = OrderRank.getTargetOrder(existingOrders, newIndex); | ||
| } |
There was a problem hiding this comment.
The logic to calculate targetOrder when moving an item to the first position (newIndex == 0) is quite complex and contains several special cases. This can be hard to maintain and reason about.
Consider simplifying this by enhancing the OrderRank.getTargetOrder utility to handle this edge case internally. A single, robust method for calculating the target order for any position would make the code cleaner and more reliable.
| !_filterByArchived) | ||
| SizedBox( | ||
| width: daysToShow * 46.0, | ||
| width: daysToShow * 46.0 + AppTheme.size3XSmall + (_sortConfig.useCustomOrder ? AppTheme.iconSizeMedium + AppTheme.sizeSmall + AppTheme.size2XSmall + AppTheme.size2XSmall : 0), |
There was a problem hiding this comment.
This width calculation is complex and relies on magic numbers (e.g., 46.0) and a combination of theme constants. This makes it brittle and hard to maintain. If the layout of HabitCard's trailing widgets changes, this calculation will need to be updated manually.
Consider refactoring this logic into a private helper method with a descriptive name, like _calculateCalendarHeaderWidth(). Inside the method, you can add comments explaining what each part of the calculation represents, or better yet, define constants for these magic numbers.
- Add layout toggle functionality to tasks following habits pattern - Add forceOriginalLayout parameter to TaskList component - Update TaskListOptions with toggle button and persistence - Extend TaskListOptionSettings model for layout state - Add layout toggle to TasksPage and Today page integration - Fix calendar header spacing in HabitsPage based on reordering mode - Add translations for layout toggle tooltips across 22 languages - Implement consistent layout toggle pattern between habits and tasks
…fied command - Add updateAll method to IHabitRepository for batch updates - Implement batch transaction in DriftHabitRepository - Remove unused beforeHabitOrder parameter from UpdateHabitOrderCommand - Simplify command handler to trust UI calculations - Use batch update for normalization instead of individual updates - Reduce database calls from N to 1 in normalization scenario
- Remove complex conditional logic for newIndex == 0 case - Use OrderRank.getTargetOrder consistently for all positions - Eliminate code duplication between UI and utility function - Improve maintainability and reduce complexity - Fix indentation issues in _onReorder method
…hods - Add constants for calendar day width and drag handle width - Create _calculateCalendarHeaderWidth helper method - Create _calculateCalendarSpacingWidth helper method - Replace magic numbers with descriptive constants - Improve maintainability and readability of layout calculations - Add documentation for helper methods
|
/gemini review |
There was a problem hiding this comment.
Code Review
This is a great pull request that adds a significant and well-requested feature: custom sorting for habits with drag-and-drop support. The implementation is thorough, covering database migrations, application logic, and extensive UI changes. The attention to detail, such as ensuring UI alignment during drag-and-drop and providing a layout toggle, is commendable. I've found one important issue in the re-normalization logic and a minor inconsistency in how new habit orders are calculated. Once these are addressed, this will be a solid addition to the app.
| } on RankGapTooSmallException { | ||
| // Normalize all orders if gaps are too small | ||
| final allHabits = await _habitRepository.getAll( | ||
| customWhereFilter: CustomWhereFilter('deleted_date IS NULL', []), | ||
| customOrder: [CustomOrder(field: "order")], | ||
| ); | ||
|
|
||
| allHabits.sort((a, b) => a.order.compareTo(b.order)); | ||
|
|
||
| // Assign new normalized orders | ||
| double orderStep = OrderRank.initialStep; | ||
| final habitsToUpdate = <Habit>[]; | ||
|
|
||
| for (var h in allHabits) { | ||
| h.order = orderStep; | ||
| h.modifiedDate = DateTime.now().toUtc(); | ||
| habitsToUpdate.add(h); | ||
| orderStep += OrderRank.initialStep; | ||
| } | ||
|
|
||
| // Batch update all habits | ||
| await _habitRepository.updateAll(habitsToUpdate); | ||
|
|
||
| return UpdateHabitOrderResponse(habit.id, habit.order); | ||
| } |
There was a problem hiding this comment.
The re-normalization logic in the catch block for RankGapTooSmallException has a flaw. It fetches all habits and re-sorts them based on their existing order from the database. This ignores the request.newOrder and the user's intent to move a habit. As a result, if re-normalization is triggered, the habit that was moved will likely revert to a position based on its old order, not the new one.
To fix this, the logic should incorporate the intended move before re-normalizing. You can do this by finding the moved habit in the allHabits list, updating its order to request.newOrder, and then re-sorting the list before proceeding with the re-normalization loop. The returned order should also be the final normalized order.
} on RankGapTooSmallException {
// Normalize all orders if gaps are too small
final allHabits = await _habitRepository.getAll(
customWhereFilter: CustomWhereFilter('deleted_date IS NULL', []),
// No custom order needed, we will sort manually after adjusting the moved habit.
);
// Find the moved habit and update its order to reflect the user's intent.
final movedHabitIndex = allHabits.indexWhere((h) => h.id == request.habitId);
if (movedHabitIndex != -1) {
allHabits[movedHabitIndex].order = request.newOrder;
}
allHabits.sort((a, b) => a.order.compareTo(b.order));
// Assign new normalized orders.
double orderStep = OrderRank.initialStep;
final habitsToUpdate = <Habit>[];
for (var h in allHabits) {
h.order = orderStep;
h.modifiedDate = DateTime.now().toUtc();
habitsToUpdate.add(h);
orderStep += OrderRank.initialStep;
}
// Batch update all habits.
await _habitRepository.updateAll(habitsToUpdate);
// Find the final normalized order for the moved habit.
final finalOrder = habitsToUpdate.firstWhere((h) => h.id == request.habitId).order;
return UpdateHabitOrderResponse(request.habitId, finalOrder);
}
| const int orderStep = 1000; | ||
| final lastOrder = lastHabits.items.isNotEmpty ? lastHabits.items.first.order : 0; | ||
| final newOrder = ((lastOrder + orderStep).toDouble()); |
There was a problem hiding this comment.
A hardcoded orderStep of 1000 is used here for new habits. Elsewhere in the application, like in UpdateHabitOrderCommand, OrderRank.initialStep is used for order calculations and re-normalization. To maintain consistency and make the code easier to manage, it would be better to use OrderRank.initialStep here as well.
| const int orderStep = 1000; | |
| final lastOrder = lastHabits.items.isNotEmpty ? lastHabits.items.first.order : 0; | |
| final newOrder = ((lastOrder + orderStep).toDouble()); | |
| final lastOrder = lastHabits.items.isNotEmpty ? lastHabits.items.first.order : 0; | |
| final newOrder = (lastOrder + OrderRank.initialStep).toDouble(); |
- Fix re-normalization to preserve user intent during RankGapTooSmallException - Update moved habit's order before sorting to maintain drag operation intent - Return final normalized order for the moved habit after batch update - Replace hardcoded 1000 with OrderRank.initialStep in SaveHabitCommand - Ensure consistency across all order calculation operations
|
/gemini review |
There was a problem hiding this comment.
Code Review
This pull request introduces custom sorting with drag-and-drop for habits, mirroring the existing functionality for tasks. The changes are comprehensive, covering database schema migrations, new application commands for updating order, and significant UI updates to support reordering in various list views.
The implementation is solid, especially the use of fractional indexing for ordering and the robust error handling for rank gap issues. The UI changes are well-thought-out, with considerations for alignment and user experience in both compact and full views.
I have a few suggestions to improve the implementation further:
- In
UpdateHabitOrderCommandHandler, there's an unreachable code block for re-normalizing orders, which is a critical piece of logic that should be made active. - A minor performance improvement can be made in the same handler by avoiding calls to
DateTime.now()inside a loop. - In
HabitsList, the response from the order update command is ignored, which could lead to a minor UI glitch if a full re-normalization occurs on the backend.
Overall, this is a great feature addition with high-quality code. Addressing these points will make it even more robust.
| try { | ||
| // Trust the calculated order from UI | ||
| habit.order = request.newOrder; | ||
| habit.modifiedDate = DateTime.now().toUtc(); | ||
| await _habitRepository.update(habit); | ||
|
|
||
| return UpdateHabitOrderResponse(habit.id, request.newOrder); | ||
| } on RankGapTooSmallException { | ||
| // Normalize all orders if gaps are too small | ||
| final allHabits = await _habitRepository.getAll( | ||
| customWhereFilter: CustomWhereFilter('deleted_date IS NULL', []), | ||
| ); | ||
|
|
||
| // Find the moved habit and update its order to reflect the user's intent | ||
| final movedHabitIndex = allHabits.indexWhere((h) => h.id == request.habitId); | ||
| if (movedHabitIndex != -1) { | ||
| allHabits[movedHabitIndex].order = request.newOrder; | ||
| } | ||
|
|
||
| allHabits.sort((a, b) => a.order.compareTo(b.order)); | ||
|
|
||
| // Assign new normalized orders | ||
| double orderStep = OrderRank.initialStep; | ||
| final habitsToUpdate = <Habit>[]; | ||
|
|
||
| for (var h in allHabits) { | ||
| h.order = orderStep; | ||
| h.modifiedDate = DateTime.now().toUtc(); | ||
| habitsToUpdate.add(h); | ||
| orderStep += OrderRank.initialStep; | ||
| } | ||
|
|
||
| // Batch update all habits | ||
| await _habitRepository.updateAll(habitsToUpdate); | ||
|
|
||
| // Find the final normalized order for the moved habit | ||
| final finalOrder = habitsToUpdate.firstWhere((h) => h.id == request.habitId).order; | ||
| return UpdateHabitOrderResponse(request.habitId, finalOrder); | ||
| } |
There was a problem hiding this comment.
The catch (RankGapTooSmallException) block is unreachable because the code inside the try block does not throw this exception. As a result, the crucial logic for re-normalizing habit orders when rank gaps become too small will never be executed. This could lead to reordering failures over time.
The RankGapTooSmallException is typically thrown by ranking utility functions like OrderRank.getTargetOrder, which is currently used in the UI layer (habits_list.dart). This means the re-normalization logic in the catch block is currently dead code.
To fix this, you could consider creating a separate command for re-normalization that the UI can call when it catches RankGapTooSmallException. This would make the re-normalization logic reachable and the system more robust against ranking failures.
| double orderStep = OrderRank.initialStep; | ||
| final habitsToUpdate = <Habit>[]; | ||
|
|
||
| for (var h in allHabits) { | ||
| h.order = orderStep; | ||
| h.modifiedDate = DateTime.now().toUtc(); | ||
| habitsToUpdate.add(h); | ||
| orderStep += OrderRank.initialStep; | ||
| } |
There was a problem hiding this comment.
DateTime.now().toUtc() is called on each iteration of the loop. This is inefficient and can result in slightly different modifiedDate timestamps for each habit within the same batch update. It's better practice to define the timestamp once outside the loop and use the same value for all items in the transaction to ensure consistency.
| double orderStep = OrderRank.initialStep; | |
| final habitsToUpdate = <Habit>[]; | |
| for (var h in allHabits) { | |
| h.order = orderStep; | |
| h.modifiedDate = DateTime.now().toUtc(); | |
| habitsToUpdate.add(h); | |
| orderStep += OrderRank.initialStep; | |
| } | |
| double orderStep = OrderRank.initialStep; | |
| final habitsToUpdate = <Habit>[]; | |
| final now = DateTime.now().toUtc(); | |
| for (var h in allHabits) { | |
| h.order = orderStep; | |
| h.modifiedDate = now; | |
| habitsToUpdate.add(h); | |
| orderStep += OrderRank.initialStep; | |
| } |
| await AsyncErrorHandler.executeVoid( | ||
| context: context, | ||
| errorMessage: _translationService.translate(SharedTranslationKeys.unexpectedError), | ||
| operation: () async { | ||
| await _mediator.send<UpdateHabitOrderCommand, UpdateHabitOrderResponse>( | ||
| UpdateHabitOrderCommand( | ||
| habitId: habit.id, | ||
| newOrder: targetOrder, | ||
| ), | ||
| ); | ||
| } | ||
|
|
||
| final habit = _habitList!.items[index]; | ||
| return Padding( | ||
| padding: const EdgeInsets.symmetric(vertical: AppTheme.size3XSmall), | ||
| child: HabitCard( | ||
| key: ValueKey(habit.id), | ||
| habit: habit, | ||
| onOpenDetails: () => widget.onClickHabit(habit), | ||
| isMiniLayout: false, | ||
| dateRange: widget.dateRange, | ||
| isDateLabelShowing: false, | ||
| onRecordCreated: (_) => widget.onHabitCompleted?.call(), | ||
| onRecordDeleted: (_) => widget.onHabitCompleted?.call(), | ||
| isDense: AppThemeHelper.isScreenSmallerThan(context, AppTheme.screenMedium), | ||
| ), | ||
| }, | ||
| onSuccess: () { | ||
| _dragStateNotifier.stopDragging(); | ||
| // Don't call onReorderComplete to avoid unnecessary refresh | ||
| }, | ||
| onError: (_) { | ||
| _dragStateNotifier.stopDragging(); | ||
| refresh(); // Refresh to restore correct order on error | ||
| }, | ||
| ); |
There was a problem hiding this comment.
The optimistic UI update in _onReorder is great for responsiveness. However, it doesn't account for cases where the backend might perform a re-normalization of all habit orders. The UpdateHabitOrderCommand returns an UpdateHabitOrderResponse containing the final order value, but this is currently ignored. If a re-normalization occurs, the targetOrder calculated in the UI will differ from the final server order, causing a UI jump on the next refresh.
To fix this, you should use the order from the response to update the local state. You can achieve this by changing AsyncErrorHandler.executeVoid to a variant that returns the operation's result, and then in the onSuccess callback, update the moved item in your local _habitList with the final order from the response. This will ensure the UI remains perfectly in sync with the backend.
- Remove unreachable RankGapTooSmallException catch block from UpdateHabitOrderCommand - Create separate NormalizeHabitOrdersCommand for proper order re-normalization - Update UI to handle RankGapTooSmallException by calling normalization command - Use single timestamp for batch updates to ensure consistency - Handle UpdateHabitOrderResponse to sync UI with backend re-normalization - Prevent UI jumps when backend performs order adjustments - Remove unused imports and variables
- Remove extensive debug print statements from habits_list.dart - Keep temporary fix for position 0 drag issue until OrderRank is fixed - Fix requires full app restart to test core package changes
- Update acore submodule with improved OrderRank utility - Remove temporary UI layer fix from habits_list.dart - Use proper OrderRank.getTargetOrder for all position calculations - Simplifies position 0 logic to always subtract initialStep
- Use manual calculation for position 0: firstOrder - initialStep - Use OrderRank utility for other positions - Clean implementation without debug logging - Resolves drag-to-top functionality completely
feat(habits): add custom sort functionality with drag-and-drop support
Summary
What Changed
orderfield to Habit entity and database schema with migrationUpdateHabitOrderCommandwith proper order calculation logicSaveHabitCommandTest Plan
Technical Details
This implementation mirrors the existing task custom sort functionality, providing users with the ability to manually organize their habits. The solution includes proper fractional ordering using
OrderRankutility and comprehensive error handling.Fixes #40