8000 feat(tasks): add calendar view by ahmet-cetinkaya · Pull Request #286 · ahmet-cetinkaya/whph · GitHub
[go: up one dir, main page]

Skip to content

feat(tasks): add calendar view - #286

Merged
ahmet-cetinkaya merged 10 commits into
mainfrom
feat/task-calendar-view
Jun 12, 2026
Merged

ahmet-cetinkaya merged 10 commits into
mainfrom
feat/task-calendar-view

Conversation

@ahmet-cetinkaya
Copy link
Copy Markdown
Owner

🚀 Motivation and Context

Introduces a calendar view for task management, allowing users to visualize and plan tasks across time. This addresses the need for a more structured time-based overview of tasks within WHPH.

⚙️ Implementation Details

  • Integrated Kalender package to render a calendar-based task view.
  • Added an unplanned tasks panel alongside the calendar to surface tasks without scheduled dates.
  • Localized all calendar sub-view labels using the existing easy_localization YAML pipeline.
  • Introduced human-readable estimated time input (e.g. "1h 30m") for tasks, replacing raw minute fields in the UI.
  • Applied style formatting across affected files for consistency.

📋 Checklist for Reviewer

  • Tests passed locally.
  • Commit history is clean and descriptive.
  • Documentation updated (if applicable).
  • Code quality standards were met (e.g., linter passed).

🔗 Related [optional]

N/A

- Add TaskCalendarEvent adapter for kalender CalendarEvent<T>
- Add TaskCalendarService for event loading and modification
- Add TaskCalendarView with month/week/day/schedule sub-views
- Integrate calendar view into TasksPage with 3-way view toggle
- Add calendar localization keys (22 locales)
- Fix lifecycle issues with UniqueKey for complete widget disposal
- Add kalender ^0.15.0 dependency

Uses UniqueKey to force CalendarView widget disposal during
view transitions, preventing 'deactivated widget' errors
when accessing LocationProvider during layout rebuilds.
Add a side panel to the calendar view that displays tasks without a
scheduled date. This allows users to quickly drag or tap tasks to
schedule them on the calendar.

- Implement `UnplannedTasksPanel` component.
- Add `TaskCalendarService` logic for managing unplanned tasks and
  task "arming" for scheduling.
- Integrate calendar filters (tags, search, sorting, grouping) with
  the calendar view.
- Add localization support for the new calendar features and panel.
Integrate translation support for the calendar view modes (month, week, day, and schedule) by replacing hardcoded English strings with localized keys.

- Add `sub_view` translation keys to all supported language locale files.
- Define new translation constants in `TaskTranslationKeys`.
- Update `TaskCalendarView` to utilize `_translationService` for sub-view labels.
- Pass the current locale to the `CalendarView` component.
Replaces the standard numeric input with a specialized `EstimatedTimeInput` component across task creation and detail views. This new component provides a more intuitive user experience by using a wheel picker for selecting days, hours, and minutes, and displays durations in a localized, human-readable format.

- Implement `EstimatedTimeInput` with a responsive picker dialog.
- Refactor `QuickAddTaskDialog`, `TaskCard`, and `TaskTimeSection` to use the new input.
- Enhance `SharedUiConstants.formatDurationHuman` to support days, hours, and minutes.
- Add `days_short` translation keys to all supported locales.
@ahmet-cetinkaya ahmet-cetinkaya added the enhancement New feature or request label Jun 11, 2026
@ahmet-cetinkaya ahmet-cetinkaya self-assigned this Jun 11, 2026
@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 introduces a new calendar view feature for tasks, integrating the kalender package, adding localized translation keys across multiple languages, and replacing the generic NumericInput with a custom wheel-picker-based EstimatedTimeInput. Key feedback highlights a critical data loss issue in TaskCalendarService where dragging or resizing tasks overwrites other fields with null, and a loading bug in TaskCalendarView where fast scrolling ignores range changes during active loads. Additionally, reviewers noted a memory leak in TasksPage due to an undisposed calendar service, a missing didUpdateWidget implementation in TaskCalendarView, eager widget instantiation in UnplannedTasksPanel's list view, a lack of defensive checks for negative inputs in EstimatedTimeInput, and a minor style violation regarding curly braces in SharedUiConstants.

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 cease on July 17, 2026.
For more details on the timeline and next steps, please review the Help Documentation.

Comment on lines +110 to +133
Future<void> handleEventChanged(
CalendarEvent<TaskCalendarEventData> original,
CalendarEvent<TaskCalendarEventData> updated,
) async {
final data = updated.data;
if (data == null) return;

final durationDiff = updated.duration.inMinutes - original.duration.inMinutes;
final hasTimeChange = durationDiff != 0;

try {
await _mediator.send<SaveTaskCommand, SaveTaskCommandResponse>(
SaveTaskCommand(
id: data.taskId,
title: data.title,
plannedDate: updated.dateTimeRange.start,
estimatedTime: hasTimeChange ? updated.duration.inMinutes : null,
),
);
} catch (e) {
debugPrint('TaskCalendarService: Failed to save event change: $e');
_reloadCurrentRange();
}
}
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.

critical

Dragging or resizing a task on the calendar triggers handleEventChanged, which currently calls SaveTaskCommand with only the id, title, plannedDate, and estimatedTime. Because SaveTaskCommand is a full save command (as evidenced by assignTaskToDate querying and passing all fields), omitting fields like priority, description, deadlineDate, order, and statusId will cause them to be cleared/overwritten with null in the database. This leads to critical data loss.

To fix this, query the existing task details first using GetTaskQuery before sending the SaveTaskCommand, ensuring all other fields are preserved.

  Future<void> handleEventChanged(
    CalendarEvent<TaskCalendarEventData> original,
    CalendarEvent<TaskCalendarEventData> updated,
  ) async {
    final data = updated.data;
    if (data == null) return;

    final durationDiff = updated.duration.inMinutes - original.duration.inMinutes;
    final hasTimeChange = durationDiff != 0;

    try {
      final task = await _mediator.send<GetTaskQuery, GetTaskQueryResponse>(
        GetTaskQuery(id: data.taskId),
      );

      await _mediator.send<SaveTaskCommand, SaveTaskCommandResponse>(
        SaveTaskCommand(
          id: task.id,
          title: task.title,
          plannedDate: updated.dateTimeRange.start,
          priority: task.priority,
          description: task.description,
          deadlineDate: task.deadlineDate,
          estimatedTime: hasTimeChange ? updated.duration.inMinutes : task.estimatedTime,
          order: task.order,
          statusId: task.statusId,
        ),
      );
    } catch (e) {
      debugPrint('TaskCalendarService: Failed to save event change: $e');
      _reloadCurrentRange();
    }
  }

Comment on lines +91 to +110
void _onVisibleRangeChanged() {
if (!mounted || _isLoading) return;

final range = widget.calendarService.calendarController.visibleDateTimeRange.value;
if (range != null) _loadEventsForRange(range);
}

Future<void> _loadEventsForRange(DateTimeRange range) async {
if (!mounted || _isLoading) return;

_isLoading = true;

try {
await widget.calendarService.loadEventsForRange(range);
} catch (e) {
debugPrint('TaskCalendarView: Error loading events: $e');
} finally {
if (mounted) _isLoading = false;
}
}
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

When the user scrolls quickly through the calendar, _onVisibleRangeChanged is triggered multiple times. If _isLoading is true, any range changes are completely ignored. This means when the current load finishes, the calendar will not load the events for the newly scrolled range, leaving the user with an empty or outdated view. Additionally, concurrent asynchronous loads can cause race conditions where an older request completes after a newer one and overwrites the events.

We can resolve both issues by keeping track of a _pendingRange and loading it sequentially once the current load finishes.

  DateTimeRange? _pendingRange;

  void _onVisibleRangeChanged() {
    if (!mounted) return;

    final range = widget.calendarService.calendarController.visibleDateTimeRange.value;
    if (range == null) return;

    if (_isLoading) {
      _pendingRange = range;
      return;
    }

    _loadEventsForRange(range);
  }

  Future<void> _loadEventsForRange(DateTimeRange range) async {
    _isLoading = true;
    _pendingRange = null;

    try {
      await widget.calendarService.loadEventsForRange(range);
    } catch (e) {
      debugPrint('TaskCalendarView: Error loading events: $e');
    } finally {
      if (mounted) {
        _isLoading = false;
        if (_pendingRange != null) {
          _loadEventsForRange(_pendingRange!);
        }
      }
    }
  }

Comment on lines +273 to +274
if (mode == TaskViewMode.calendar) {
_calendarService ??= TaskCalendarService(container.resolve<Mediator>());
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

_calendarService is a ChangeNotifier created dynamically in _onViewModeChange but is never disposed in TasksPage.dispose(). This will cause memory leaks because the service holds references to eventsController and calendarController, both of which are also ChangeNotifiers.

Please add _calendarService?.dispose(); to the dispose() method of _TasksPageState.

Comment on lines +49 to +56
@override
void initState() {
super.initState();
_addTasksServiceListeners();
WidgetsBinding.instance.addPostFrameCallback((_) {
if (mounted) _loadInitialEvents();
});
}
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.

medium

The state class does not implement didUpdateWidget. If the parent widget rebuilds and passes a different TaskCalendarService instance, the listeners will remain attached to the old service, and the new service will not be listened to. Implement didUpdateWidget to properly dispose of listeners on the old service and attach them to the new one.

  @override
  void initState() {
    super.initState();
    _addTasksServiceListeners();
    WidgetsBinding.instance.addPostFrameCallback((_) {
      if (mounted) _loadInitialEvents();
    });
  }

  @override
  void didUpdateWidget(covariant TaskCalendarView oldWidget) {
    super.didUpdateWidget(oldWidget);
    if (oldWidget.calendarService != widget.calendarService) {
      if (_listenerAdded) {
        oldWidget.calendarService.calendarController.visibleDateTimeRange.removeListener(_onVisibleRangeChanged);
        _listenerAdded = false;
      }
      widget.calendarService.resetEventsController();
      if (!_listenerAdded) {
        widget.calendarService.calendarController.visibleDateTimeRange.addListener(_onVisibleRangeChanged);
        _listenerAdded = true;
      }
      _loadInitialEvents();
    }
  }

Comment on lines +65 to +74
: Builder(
builder: (context) {
final items = _buildItems();
return ListView.builder(
padding: const EdgeInsets.all(AppTheme.sizeSmall),
itemCount: items.length,
itemBuilder: (context, index) => items[index],
);
},
),
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.

medium

Using ListView.builder with a pre-built list of widgets (items[index]) created eagerly by _buildItems() completely defeats the purpose of lazy loading. All widgets in the list are instantiated eagerly in memory, which can cause significant UI thread jank and high memory usage when the list of unplanned tasks is large (up to 500 items).

To fix this, separate the data representation from the widget representation by building a list of lightweight "display items" (e.g., using a sealed class or enum) and instantiating the widgets lazily inside the itemBuilder.

              : Builder(
                  builder: (context) {
                    final items = _buildPanelItems();
                    return ListView.builder(
                      padding: const EdgeInsets.all(AppTheme.sizeSmall),
                      itemCount: items.length,
                      itemBuilder: (context, index) {
                        final item = items[index];
                        if (item is _HeaderItem) {
                          return _GroupHeader(label: item.label);
                        } else if (item is _TaskItem) {
                          final task = item.task;
                          return Padding(
                            padding: const EdgeInsets.only(bottom: AppTheme.sizeXSmall),
                            child: _UnplannedTaskCard(
                              task: task,
                              isArmed: task.id == armedTaskId,
                              onArm: () => onArm(task),
                              onOpenDetails: () => onOpenDetails(task),
                            ),
                          );
                        }
                        return const SizedBox.shrink();
                      },
                    );
                  },
                ),

Comment on lines +80 to +102
List<Widget> _buildItems() {
final items = <Widget>[];
String? currentGroup;

for (final task in tasks) {
final groupName = task.groupName;
if (groupName != null && groupName != currentGroup) {
currentGroup = groupName;
items.add(_GroupHeader(label: groupLabelResolver(task)));
}
items.add(Padding(
padding: const EdgeInsets.only(bottom: AppTheme.sizeXSmall),
child: _UnplannedTaskCard(
task: task,
isArmed: task.id == armedTaskId,
onArm: () => onArm(task),
onOpenDetails: () => onOpenDetails(task),
),
));
}

return items;
}
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.

medium

Replace the eager _buildItems widget builder with a lazy _buildPanelItems data mapper and helper classes to support efficient virtualized rendering in the ListView.builder.

  List<_PanelItem> _buildPanelItems() {
    final items = <_PanelItem>[];
    String? currentGroup;

    for (final task in tasks) {
      final groupName = task.groupName;
      if (groupName != null && groupName != currentGroup) {
        currentGroup = groupName;
        items.add(_HeaderItem(groupLabelResolver(task)));
      }
      items.add(_TaskItem(task));
    }

    return items;
  }
}

sealed class _PanelItem {}

class _HeaderItem extends _PanelItem {
  final String label;
  _HeaderItem(this.label);
}

class _TaskItem extends _PanelItem {
  final TaskListItem task;
  _TaskItem(this.task);
}
1798

Comment on lines +84 to +91
@override
void initState() {
super.initState();
_days = widget.initialMinutes ~/ 1440;
final remaining = widget.initialMinutes % 1440;
_hours = remaining ~/ 60;
_minutes = remaining % 60;
}
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.

medium

If widget.initialMinutes is negative, the integer division (~/) and modulo (%) operations will produce unexpected values (e.g., -100 minutes would be parsed as 0 days, 22 hours, and 20 minutes). Add a defensive check to clamp the initial minutes to a minimum of 0.

Suggested change
@override
void initState() {
super.initState();
_days = widget.initialMinutes ~/ 1440;
final remaining = widget.initialMinutes % 1440;
_hours = remaining ~/ 60;
_minutes = remaining % 60;
}
@override
void initState() {
super.initState();
final initialMinutes = widget.initialMinutes < 0 ? 0 : widget.initialMinutes;
_days = initialMinutes ~/ 1440;
final remaining = initialMinutes % 1440;
_hours = remaining ~/ 60;
_minutes = remaining % 60;
}

Comment on lines +50 to +51
if (remainingMinutes > 0)
parts.add('$remainingMinutes${translationService.translate(SharedTranslationKeys.minutesShort)}');
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.

medium

Adhere to the standard Dart style guide (curly_braces_in_flow_control_structures) by using curly braces for all control flow structures, including single-line if statements.

Suggested change
if (remainingMinutes > 0)
parts.add('$remainingMinutes${translationService.translate(SharedTranslationKeys.minutesShort)}');
if (remainingMinutes > 0) {
parts.add('$remainingMinutes${translationService.translate(SharedTranslationKeys.minutesShort)}');
}

Improve calendar view reliability and component efficiency.
Prevent data loss during task updates by ensuring full task
details are retrieved before saving changes. Optimize the
unplanned tasks panel grouping logic and enhance error
visibility with standardized logging. Refine the estimated
time input for better UX and stricter duration constraints.
Address critical and high-priority issues from PR #286 review:
- Make TaskListItem.id/title final for immutability
- Register TaskCalendarService via DI container
- Remove duplicated _isPanelOpen state (view/service sync)
- Encapsulate eventsController as private with getter
- Replace resetEventsController with clearEvents
- Extract CalendarSubView to own file
- Add stack traces to all Logger.error calls
- Remove dead taskId params from notification methods
- Add ==/hashCode to TaskCalendarEventData
- Remove dead isAllDay method
- Replace nested ternaries with switch expressions
- Replace magic number 1440 with named constant
- Deduplicate filter propagation in tasks_page
Enable efficient handling of large task sets by implementing
pagination for calendar events and unplanned tasks. Add
infinite scrolling to the unplanned tasks panel.
…ssues

- Fix panel not appearing when toggle button tapped by wrapping Row in ListenableBuilder
- Add MonthBodyConfiguration and MultiDayBodyConfiguration to silence calendar warnings
- Implement onCreateTask callback to open QuickAddTaskDialog with selected date
- Change emptyDay to always show in schedule view (was hiding empty slots)
- Add custom short day name translations using SharedTranslationKeys for schedule view
- Remove unplanned tasks count badge from panel toggle button
@ahmet-cetinkaya
ahmet-cetinkaya marked this pull request as ready for review June 12, 2026 01:49
@ahmet-cetinkaya
ahmet-cetinkaya merged commit 9a7c3a9 into main Jun 12, 2026
3 checks passed
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

enhancement New feature or request

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant

0