8000 fix(sort): make custom sort work as a single, consistent ordering by ahmet-cetinkaya · Pull Request #300 · ahmet-cetinkaya/whph · GitHub
[go: up one dir, main page]

Skip to content

fix(sort): make custom sort work as a single, consistent ordering - #300

Merged
ahmet-cetinkaya merged 47 commits into
mainfrom
fix/reorder-drag-drop-lands-wrong-position
Aug 30, 2026
Merged

ahmet-cetinkaya merged 47 commits into
mainfrom
fix/reorder-drag-drop-lands-wrong-position

Conversation

@ahmet-cetinkaya
@ahmet-cetinkaya ahmet-cetinkaya commented Jul 19, 2026 •
Copy link
Copy Markdown
Owner

Context

Custom sorting in Habits and Tasks had several interacting correctness and UX problems:

  • Repeated midpoint insertion with numeric ranks eventually produced collisions.
  • Grouping and custom ordering could disagree about the visible sequence.
  • Drop indices, pagination, collapsed groups, and optimistic rendering could make an item land in the wrong position or appear to snap back.
  • Custom sort had competing controls and no way to hide drag handles without disabling reordering.
  • A visible schedule tooltip could remain attached to a sliver child while reorder detached it, causing a Flutter null-check crash.

This PR addresses the ordering model, migration path, query semantics, reorder UI, and regression coverage as one end-to-end change.

Important

The ordering scheme moves from double to a LexoRank-style base-62 fractional string rank. Sync already requires exact version equality, preventing mixed-schema devices from exchanging incompatible order values.

Related dependency

What changed

Ordering and persistence

  • Converted Habit, Task, TaskStatus, and Note order values to string ranks.
  • Added schema v35 to v36 migration with order-preserving backfill and deterministic created_date, then id, tie-breakers.
  • Added collision-safe sibling placement and transactional renormalization.
  • Aligned task sibling scope with the persisted parent instead of caller-provided state.
  • Normalized legacy backup ranks before deserialization and after persistence.
  • Hardened migration backup, rollback, partial-migration detection, and large-dataset behavior.

Query and grouping behavior

  • Custom sort and enabled grouping now coexist: manual ranks order items inside each active group.
  • A stale saved groupOption is ignored while grouping is disabled, so it cannot silently partition global custom order.
  • Groups use deterministic translated-label ordering.
  • Stable rank, creation date, and ID ordering removes undefined SQLite ties.

Reorder UI

  • Removed the legacy forceOriginalLayout path; useCustomOrder is the single custom-sort switch.
  • Added a persisted drag-indicator visibility control in the sort dialog, localized across all supported languages.
  • When indicators are hidden, cards remain reorderable through delayed whole-card long press.
  • Same-group drops are accepted; cross-group drops are rejected instead of silently clamped.
  • Optimistic reorder invalidates derived caches immediately, preventing snap-back before refresh.
  • Archived habits remain non-draggable without desynchronizing visual indices.
  • Pagination, collapsed groups, pre-removal sliver indices, and load-more rows are covered by regressions.

Today page behavior

  • Habits can use either grid or list while custom sort indicators are hidden.
  • The grid/list control remains visible and functional in that state.
  • Showing custom sort indicators enters editing mode: Today Habits is forced to list and the grid/list control is hidden until editing mode ends.
  • The stored grid/list preference is preserved and restored when indicators are hidden again.

Tooltip crash fix

  • Replaced the schedule button framework tooltip overlay with a layout-aware OverlayPortal implementation.
  • Drag state closes the overlay synchronously before sliver reparenting.
  • Detached or singular paint transforms render no tooltip instead of calling localToGlobal on an invalid sliver child.
  • Translated hover text and accessibility semantics are preserved.

Verification

  • rps format passed: 973 Dart files checked, 0 additional changes.
  • rps lint passed: Flutter Analyze reports No issues found; unused-file, Markdown, Shellcheck, and ktlint checks pass.
  • rps check passed with 2,229 Flutter tests.
  • Migration and upgrade-path tests cover v35 to v36 ordering, partition scope, rollback, foreign keys, and hostile legacy values.
  • Real widget gestures cover handle drag, delayed whole-card drag, grouped reorder, optimistic refresh, tooltip hover plus drag, and Today grid/list transitions.
  • The reported PopupMenuButton<ScheduleOption> reorder crash was manually confirmed resolved.

Reviewer focus

  1. Verify custom sort ordering inside enabled groups and global ordering when grouping is disabled.
  2. Toggle drag indicators and confirm hidden indicators retain whole-card long-press reorder.
  3. On Today Habits, confirm grid/list is selectable with indicators hidden and locked to list with indicators visible.
  4. Hover a task schedule button, immediately start reorder, and confirm no tooltip exception occurs.
  5. Review schema v36 migration and downgrade implications.

Caution

This changes the on-disk schema and sync representation of order. Mixed-version sync is blocked by exact version validation, but downgrading after migration requires restoring a compatible backup.

Custom-order lists (always-on reorderable tasks/habits) frequently
dropped items at the wrong position: an item would snap to a seemingly
arbitrary slot after the post-drop refresh.

Root cause: the UI computed fragile fractional ranks that collided as
midpoint gaps collapsed below minimumOrderGap (and with duplicate or
near-zero orders from sync/migration), while the command handler
persisted the UI value blindly. The optimistic local reorder and the
persisted order disagreed, so the debounced refresh re-sorted by the
wrong order and the item jumped.

Redesign the reorder->persist->re-render cycle around a positional,
single-source-of-truth contract:

- Handlers (UpdateTaskOrderCommand, UpdateHabitOrderCommand) now take a
  target index plus before/after neighbor id hints instead of a
  pre-computed order. They load the authoritative order-sorted sibling
  set, compute a gap-safe rank between the real neighbors via
  OrderRank.neighborRank, and renormalize the whole set on any collision
  before placing the item exactly at its slot.
- Add NormalizeTaskOrdersCommand (mirrors NormalizeHabitOrdersCommand)
  for batch order repair.
- Fix a latent registration bug: UpdateTaskOrderCommand was registered
  with return type void but sent expecting UpdateTaskOrderResponse.
- UI (tasks_list, habits_list) drops all client-side fractional math and
  sends positional commands; on-load normalization now triggers on
  duplicates and collapsed gaps, not only near-zero values.
- Bump acore-flutter submodule for OrderRank.neighborRank /
  needsNormalization.

Notes (batch order) and tags (settings-stored order) use different
mechanisms and are unaffected. All logic is shared Dart, so the fix
covers Android, Windows and Linux.

Add order_rank_test.dart (13 cases) locking neighbor placement,
collision throwing and collapsed-gap detection.
@gemini-code-assist gemini-code-assist Bot left a comment
Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Code Review

This pull request refactors the habit and task ordering system to use a robust, positional approach where the backend serves as the single source of truth for rank computation. It introduces a new NormalizeTaskOrdersCommand to batch-renormalize task orders, updates the update order commands to use target indices and neighbor hints, and integrates these changes into the UI. The feedback highlights two critical improvements: optimizing the task re-normalization handler to perform batch updates via updateMultiple instead of individual database updates in a loop, and refining the UI-side order normalization check to prevent potential infinite loops when custom ordering is inactive or when sibling sets are mixed.

Important

The consumer version of Gemini Code Assist on GitHub is being sunset. Starting June 18, 2026, new organization installations will be blocked, and all code review activity will officially cea 10BC8 se on July 17, 2026.
For more details on the timeline and next steps, please review the Help Documentation.

Comment on lines 119 to 135
Future<double> _renormalizeAndPlace(Task task, List<Task> siblings, int position) async {
final now = DateTime.now().toUtc();
final ordered = List<Task>.from(siblings);
final clampedPosition = position.clamp(0, ordered.length);
ordered.insert(clampedPosition, task);

double step = OrderRank.initialStep;
double placedOrder = OrderRank.initialStep;
for (final t in ordered) {
t.order = step;
t.modifiedDate = now;
await _taskRepository.update(t);
if (t.id == task.id) placedOrder = step;
step += OrderRank.initialStep;
}
return placedOrder;
}
Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

high

Updating each task individually in a loop (await _taskRepository.update(t)) is highly inefficient and can cause significant performance bottlenecks, database locks, or UI lag when there are many sibling tasks. Since _taskRepository supports batch updates via updateMultiple, we should perform the updates in a single batch operation after the loop.

  Future<double> _renormalizeAndPlace(Task task, List<Task> siblings, int position) async {
    final now = DateTime.now().toUtc();
    final ordered = List<Task>.from(siblings);
    final clampedPosition = position.clamp(0, ordered.length);
    ordered.insert(clampedPosition, task);

    double step = OrderRank.initialStep;
    double placedOrder = OrderRank.initialStep;
    for (final t in ordered) {
      t.order = step;
      t.modifiedDate = now;
      if (t.id == task.id) placedOrder = step;
      step += OrderRank.initialStep;
    }

    await _taskRepository.updateMultiple(ordered);
    return placedOrder;
  }

Comment on lines 526 to 531
bool _shouldNormalizeOrders(List<TaskListItem> items) {
return items.any((item) => item.order.abs() < 1e-10 || (item.order > 0 && item.order < 1e-6));
if (items.any((item) => item.order.abs() < 1e-10 || (item.order > 0 && item.order < 1e-6))) {
return true;
}
return OrderRank.needsNormalization(items.map((item) => item.order).toList());
}
Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

high

Automatic on-load normalization can trigger an infinite loop of refresh() -> _normalizeTaskOrders() -> refresh() if the displayed list contains mixed sibling sets (e.g., when widget.includeSubTasks is true, or when sorting by non-custom fields like date/priority where tasks from different parent tasks are mixed together). In these cases, duplicate order values are perfectly normal and expected because order is only unique within a single sibling set. To prevent infinite loops, we should only evaluate and trigger normalization when custom ordering is active and we are not mixing sibling sets.

  bool _shouldNormalizeOrders(List<TaskListItem> items) {
    if (widget.sortConfig?.useCustomOrder != true || widget.includeSubTasks) {
      return false;
    }
    if (items.any((item) => item.order.abs() < 1e-10 || (item.order > 0 && item.order < 1e-6))) {
      return true;
    }
    return OrderRank.needsNormalization(items.map((item) => item.order).toList());
  }

Address review findings on the drag-and-drop reorder redesign:

- Extract SiblingReorderService<T> (core/application/shared) as the single
  owner of resolve-position -> gap-safe-rank -> renormalize-on-collision;
  UpdateTaskOrder/UpdateHabitOrder handlers become thin adapters, removing
  ~95% duplicated logic that had already diverged.
- Fix non-transactional task renormalization: the handler now persists the
  renumbered set via a single transactional updateMultiple instead of a
  per-item update() loop, eliminating partial-write order corruption that
  could propagate via sync.
- Route both normalize commands and renumbering through
  OrderRank.assignSequential; drop IHabitRepository.updateAll and converge
  all habit bulk writes on the inherited transactional updateMultiple.
- UI (tasks_list, habits_list): compute reducedGroup once and reuse it for
  the optimistic reorder and neighbor-id resolution so they cannot desync;
  extract _applyOptimisticReorder; centralize near-zero detection via
  OrderRank.hasNearZeroOrder.
- Restore consistent error logging on the habit side (add Logger import;
  log onReorderComplete failures, refresh failures, and normalization
  failures) to match the task side.
- Align HabitListItem.order to non-null double (matching Task.order),
  removing scattered ?? 0.0 fallbacks.
- Bump acore-flutter submodule for the InvalidNeighborOrderException /
  cannotFit / hasNearZeroOrder / assignSequential additions and dead-code
  removal.

Extend order_rank_test.dart to 30 cases covering the new exception,
cannotFit, maxOrder overflow, and assignSequential.
Adds Zed editor tasks and debug launch config to drive Flutter through
`nix develop` on NixOS, where native tooling (ninja, CMake, GTK/X11/
Wayland libs) is only available inside the flake dev shell.

- scripts/zed_nix_flutter.sh: wraps the Dart debug adapter's flutter
  invocation in `nix develop --command`.
- scripts/zed_nix_run.sh: same wrapping for Zed run tasks (run, test,
  codegen, check), parameterized by target subdir.
- .zed/debug.json: F5 debug config pointing at src/lib/main.dart, target
  device pinned via the `deviceId` field (not a `-d` CLI flag — the
  debug adapter launches the real `flutter run` internally over DAP, so
  a flag injected into the wrapper's argv never reaches it).
- .zed/tasks.json: run/demo/test/pub-get/codegen/check tasks.
Habit, Task, TaskStatus and Note all carry an order value read by the
shared OrderRank utility, so they move to string ranks together.
Legacy numeric values arriving from JSON are converted through
fromLegacyDouble instead of being silently dropped.

BREAKING CHANGE: entity 'order' is now String.
Rebuilds habit, task, task_status and note tables with a TEXT order
column and backfills existing rows in their current display order
(order, created_date, id) so no user-visible sequence changes.

Items that shared an order value had no defined sequence before; they
now sort deterministically by created_date then id.
Tasks scoped reordering to parent_task_id while habits scoped globally,
so the two features disagreed on what a sibling is. Both now resolve
the drop target from the neighbour ids first and fall back to the page
index only when no identity hint is available, which keeps a drop
correct even when the list is filtered or paginated.
The group ORDER BY was appended ahead of the custom order, so a manual
sequence only held inside a group and looked shuffled once grouping was
switched off. Custom sort now orders first, with created_date and id as
a stable tie-breaker so equal ranks no longer depend on SQLite's
arbitrary row order.
Backup restore deserializes through generated mapper factories, which
bypass the entity constructors that would have converted a numeric
order. Legacy, malformed, absent and wrong-typed ranks are now
normalized on the map before deserialization, and orders are
renormalized after persistence so a restored file lands in a canonical
rank space.
A separate persisted forceOriginalLayout toggle could disable dragging
while the custom sort switch still read as on, leaving no way to tell
why items would not move. That toggle is gone: enabling custom sort
enables dragging and suppresses grouping, and the grouping button
renders disabled instead of silently losing its effect.

Switching to board mode still applies status grouping unconditionally,
since a board is grouped by status by definition, but it now carries
the custom sort setting forward to order cards inside each column.
Selected tags are looked up in the loaded tag page, so a selection that
paginated out was dropped from the display entirely. The label supplied
with the initial selection is now retained as a fallback.
SC2016 flags the single-quoted inner bash program, whose positional
parameters are meant to be expanded by that inner shell, not the outer
one.
@ahmet-cetinkaya ahmet-cetinkaya changed the title fix(reorder): make drag-and-drop land exactly where dropped fix(sort): make custom sort work as a single, consistent ordering Aug 23, 2026
@ahmet-cetinkaya ahmet-cetinkaya added bug Something isn't working ui User interface and user experience issues task-management Task creation, editing, and management features labels Aug 23, 2026
Existing coverage used handful-sized fixtures with clean numeric orders.
Real databases accumulate negative, zero, denormal and overflow-prone
values through sync and older migrations, and hold far more rows than a
single rank digit can address. Adds 500 habits plus those boundary
values and asserts sequence preservation, canonical distinct ranks and
compact rank width.
…ller's

A flat 'show sub-tasks' list can display a subtask alongside root tasks
in the same visual list. The command trusted a caller-supplied
parentTaskId for sibling scope, so dragging a subtask in that flat
view ranked it against root tasks instead of its real siblings —
renormalization then silently reordered untouched sibling subtasks.

Scope is now always read from the persisted task, which can't disagree
with where the task actually lives. The redundant parentTaskId field
is removed from the command entirely rather than left as an unused
footgun.
createBackupBeforeMigration caught every exception, logged a warning,
and returned normally — a data-rewriting migration then proceeded with
no recovery copy on a full disk, permission error, or partial copy.
Failures now surface as a StateError, which the onUpgrade handler's
existing catch already rethrows before the migration transaction
starts. The copy is also verified by size after completion, so a
truncated copy is caught rather than trusted.
No existing coverage exercised a failure occurring inside the
migration's enclosing transaction. Forces a StateError after the
migration steps complete but still inside db.transaction(), then
asserts the schema, column types, and original numeric orders are all
unchanged, foreign keys are intact, and a subsequent clean migration
still succeeds.

Verified by mutation: temporarily removing the transaction wrapper
from the test (simulating the bug this test exists to catch) turns
this test red; restoring it returns to green.
_orderedTaskIds rebuilt each parent's accumulator list on every row via
[...(list ?? const []), item], which is O(n) per row and O(n²) for a
single large sibling partition (e.g. a task with hundreds of
subtasks). Replaced with putIfAbsent + add, which is O(1) amortized
per row.

Extends the scale test with a 500-row single-parent partition to
exercise this path; the prior fixtures only had single-row partitions
that couldn't expose the quadratic cost. Also splits the canonical
distinct-rank assertion into a per-parent-scoped variant, since ranks
are only required to be distinct within a sibling partition, not
across the whole task table.
Notes were excluded from _normalizeImportedOrders, so a legacy or
malformed backup with duplicate note ranks (e.g. several notes sharing
'0.0') imported successfully but left their relative display order
undefined — the query sorted by order alone with no tie-breaker
guarantee across a shared rank.

Adds NormalizeNoteOrdersCommand mirroring the existing habit
normalizer (global scope, no parent partitioning — notes don't nest)
and wires it into the same post-persistence normalization pass.

Verified by mutation: temporarily removing the new normalize call from
import_data_command.dart turns the new regression test red; restoring
it returns to green.
…ing it

The idempotence guard checked only habit_table's column type, so a
database where habit_table had already been converted to TEXT but
note_table, task_status_table, or task_table had not — from an
interrupted migration or manual edit — would return early and treat
the conversion as complete, leaving the remaining tables on legacy
REAL orders with no error.

Now checks all four ranked tables: a fully-converted or fully-legacy
state proceeds as before, but a mixed state throws a StateError
directing the user to restore from backup rather than silently
leaving the database in an inconsistent, partially-migrated state.

Verified by mutation: temporarily reverting to the single-table check
turns the new regression test red; restoring returns to green.
computePlacement took a setOrder callback that mutated the moved
entity and, on renormalization, every sibling in the caller's list —
contradicting the project's immutability rule and leaving entities
mutated even if the subsequent repository write failed.

It now returns rank assignments as data (order, and renumberedOrder
keyed by id) without touching any entity. Callers apply the rank(s) to
their own entities in the single place they already do so: immediately
before the repository write, matching this codebase's existing pattern
for other single-field updates.

Verified by mutation: temporarily reintroducing a write-back into the
renormalization path turns the new not-mutated assertions red;
restoring returns to green.
Both reorder handlers re-sorted the sibling list in Dart immediately
after fetching it already sorted by SQL. Verified the repository's SQL
ORDER BY on the order column uses SQLite's default BINARY collation
(no COLLATE NOCASE), which agrees byte-for-byte with Dart's
String.compareTo for OrderRank's ASCII base-62 alphabet, so the second
sort was strictly redundant, not defensive.

Added a real-database integration test with mixed-case ranks (digit,
uppercase, lowercase) that would fail if SQL and Dart collation ever
diverged, since unit tests using mocked repositories can't exercise
actual SQLite comparison behavior.
…trips

_normalizeImportedOrders issued one NormalizeTaskOrdersCommand mediator
call per distinct parentTaskId found in the backup, each doing its own
repository fetch and update. A backup with many distinct parent
scopes (deeply nested projects, many top-level task groups) turned
into that many sequential round-trips during import.

Replaced with a single taskRepository.getAll() covering every
non-deleted task, grouped by parentTaskId in memory, normalized
per-group, and persisted in one updateMultiple() batch — one fetch,
one write, regardless of how many distinct parents exist.
NormalizeTaskOrdersCommand itself is unchanged and still used by
tasks_list.dart for its original single-scope use case.

Verified by mutation: temporarily reverting to N fetch+update
round-trips (one per parent scope) turns the new call-count
assertions red; restoring the consolidated pass returns to green.
@ahmet-cetinkaya
ahmet-cetinkaya merged commit 1164c1b into main Aug 30, 2026
3 checks passed
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

bug Something isn't working task-management Task creation, editing, and management features ui User interface and user experience issues

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant

0