List tasks feature (#4)

This PR contains the work done to implement the **List Tasks** feature, and to integrate it into the main content view of the app.

Reviewed-on: rock-n-code/todos-app#4
Co-authored-by: Javier Cicchelli <javier@rock-n-code.com>
Co-committed-by: Javier Cicchelli <javier@rock-n-code.com>
This commit was merged in pull request #4.
This commit is contained in:
2026-02-10 15:31:52 +00:00
committed by javier
parent 0b8e5d8bd0
commit 2a3323b8e6
11 changed files with 679 additions and 45 deletions
@@ -0,0 +1,54 @@
import Foundation
import SwiftData
/// Extension providing convenient initializers for fetching todos by group category.
///
/// This extension allows creating fetch descriptors that automatically filter and sort todos
/// based on their completion status and due dates according to the specified `TodoGroup`.
extension FetchDescriptor where T == Todo {
/// Creates a fetch descriptor for todos filtered and sorted by a specific group.
///
/// This initializer provides a convenient way to fetch todos categorized by their temporal
/// relevance and completion status. Each group applies appropriate predicates and sort orders:
///
/// - **Completed**: All tasks marked as done, sorted by completion date (most recent first)
/// - **Overdue**: Incomplete tasks with due dates before today, sorted by due date (most recent first)
/// - **Today**: Incomplete tasks due today, sorted by due date (earliest first)
/// - **Upcoming**: Incomplete tasks due after today, sorted by due date (earliest first)
///
/// - Parameters:
/// - group: The todo group category to filter by.
/// - calendar: The calendar to use for date calculations. Defaults to `.current`.
init(
group: TodoGroup,
calendar: Calendar = .current
) {
let today = calendar.startOfDay(for: .now)
let tomorrow = calendar.date(byAdding: .day, value: 1, to: today) ?? today
switch group {
case .completed:
self.init(
predicate: #Predicate { $0.completed != nil },
sortBy: [.init(\.completed, order: .reverse)]
)
case .overdue:
self.init(
predicate: #Predicate { $0.completed == nil && $0.due < today },
sortBy: [.init(\.due, order: .reverse)]
)
case .today:
self.init(
predicate: #Predicate { $0.completed == nil && $0.due >= today && $0.due < tomorrow },
sortBy: [.init(\.due, order: .forward)]
)
case .upcoming:
self.init(
predicate: #Predicate { $0.completed == nil && $0.due >= tomorrow },
sortBy: [.init(\.due, order: .forward)]
)
}
}
}
@@ -0,0 +1,77 @@
import SwiftUI
/// A custom toggle style designed for task completion indication.
///
/// This style renders a circular checkbox that visually represents completion state:
/// - **Off state**: An empty circle with a secondary-colored stroke border
/// - **On state**: A circle with a primary-colored stroke border containing a filled inner circle
///
/// ## Usage
///
/// Apply this style to any `Toggle` view using the `.completion` static accessor:
///
/// ```swift
/// Toggle("Complete task", isOn: $isCompleted)
/// .toggleStyle(.completion)
/// ```
struct CompletionToggleStyle: ToggleStyle {
// MARK: Functions
func makeBody(configuration: Configuration) -> some View {
Button {
configuration.isOn.toggle()
} label: {
HStack(alignment: .top, spacing: 12) {
ZStack {
Circle()
.strokeBorder(
configuration.isOn ? .primary : .secondary,
lineWidth: 2
)
.frame(width: 24, height: 24)
if configuration.isOn {
Circle()
.fill(.primary)
.frame(width: 16, height: 16)
}
}
}
}
.animation(
.easeInOut,
value: configuration.isOn
)
.buttonStyle(.plain)
}
}
// MARK: - Toggle Style Extension
extension ToggleStyle where Self == CompletionToggleStyle {
/// A toggle style for task completion with a circular checkbox design.
///
/// This convenience accessor provides easy access to the ``CompletionToggleStyle``
/// for use with SwiftUI's toggle style modifier.
static var completion: CompletionToggleStyle {
CompletionToggleStyle()
}
}
// MARK: - Previews
#Preview("Completion toggle style") {
@Previewable
@State
var isOn = false
Toggle(
"Unchecked task",
isOn: $isOn
)
.toggleStyle(.completion)
}
@@ -0,0 +1,43 @@
import SwiftData
import SwiftUI
extension TaskListView {
/// View model for managing the logic for the task list view.
///
/// This observable class encapsulates the state and business logic for the task list view.
/// It follows the MVVM pattern to separate presentation logic from the view layer.
///
/// ## Responsibilities
/// - Providing the navigation title for the current group
@Observable
final class ViewModel {
// MARK: Properties
/// The task group to display tasks for.
///
/// This property determines which tasks are fetched and displayed in the list.
private let group: TodoGroup
// MARK: Initialization
/// Initializes a new view model instance for a specific task group.
///
/// - Parameter group: The task group to display tasks for.
init(group: TodoGroup) {
self.group = group
}
// MARK: Computed
/// The navigation title for the current task group.
///
/// This computed property provides the localized title for the current group,
/// suitable for display in a navigation bar.
///
/// - Returns: The localized title key for the current group.
var navigationTitle: LocalizedStringKey { group.title }
}
}
@@ -0,0 +1,148 @@
import SwiftUI
extension TaskListView {
/// A view that displays a single editable todo task in a list.
///
/// This view provides a comprehensive interface for viewing and editing task information,
/// including:
/// - A completion toggle using a circular checkbox design
/// - An editable title field with multi-line support
/// - An optional note field that appears when the task has notes
/// - A date picker for selecting the task's due date
///
/// The view automatically adjusts its appearance based on completion state, dimming
/// completed tasks to provide visual feedback. All text fields support automatic
/// capitalization and keyboard correction for improved user experience.
struct Item: View {
// MARK: Properties
/// The todo task to display.
@Bindable
private var item: Todo
// MARK: Initializers
/// Creates a new task list item view for the specified todo.
///
/// The item is wrapped in a `@Bindable` property wrapper to enable two-way
/// data binding for editing task properties directly within the view.
///
/// - Parameter item: The todo task to display and edit.
init(_ item: Todo) {
_item = Bindable(item)
}
// MARK: Body
/// The content and behavior of the view.
///
/// Renders an editable task list item with a completion toggle, title field,
/// optional note field, and date picker. The view's foreground color automatically
/// adjusts based on completion state, and changes animate smoothly.
var body: some View {
HStack(
alignment: .top,
spacing: 16
) {
Toggle(
"view.task-list-item.placeholder.completed",
isOn: isCompleted
)
.toggleStyle(.completion)
VStack(
alignment: .leading,
spacing: 8
) {
TextField(
"view.task-list-item.placeholder.title",
text: $item.title,
axis: .vertical
)
.font(.headline)
if showNote {
TextField(
"view.task-list-item.placeholder.note",
text: note,
axis: .vertical
)
.font(.subheadline)
}
DatePicker(selection: $item.due, displayedComponents: .date) {
Image(systemName: "calendar")
}
.frame(width: 160)
.disabled(isCompleted.wrappedValue)
}
.autocapitalization(.sentences)
.autocorrectionDisabled(false)
.foregroundStyle(foregroundColor)
.keyboardType(.asciiCapable)
}
.animation(
.easeInOut,
value: item.completed
)
}
}
}
// MARK: - Helpers
private extension TaskListView.Item {
// MARK: Bindings
var isCompleted: Binding<Bool> {
.init {
item.completed != nil
} set: {
item.completed = $0 ? .now : nil
}
}
var note: Binding<String> {
.init {
item.note ?? ""
} set: {
item.note = $0.isEmpty ? nil : $0
}
}
// MARK: Computed
var foregroundColor: Color {
item.completed == nil ? .primary : .secondary
}
var showNote: Bool {
guard let note = item.note else {
return false
}
return note.trimmingCharacters(in: .whitespacesAndNewlines).isEmpty == false
}
}
// MARK: - Previews
#Preview("Task list item") {
@Previewable
var todo: Todo = .init(
title: "Complete project documentation",
note: "Add detailed comments and README",
due: .now,
completed: nil
)
List {
TaskListView.Item(todo)
}
.listStyle(.grouped)
}
+99
View File
@@ -0,0 +1,99 @@
import SwiftData
import SwiftUI
/// A view that displays all todo tasks for a specific task group.
///
/// This view shows a filtered list of tasks based on the selected group (today, upcoming, past, or completed).
/// The view uses a view model to separate business logic from presentation.
struct TaskListView: View {
// MARK: Properties
/// Query to fetch todos filtered by the current group.
@Query
private var tasks: [Todo]
/// The view model managing the business logic for this view.
@State
private var viewModel: ViewModel
// MARK: Initialization
/// Creates a new task list view for a specific group.
/// - Parameter group: The todo group to display tasks for.
init(group: TodoGroup) {
_tasks = .init(FetchDescriptor<Todo>(group: group))
_viewModel = .init(initialValue: ViewModel(group: group))
}
// MARK: Body
/// The content and behavior of the view.
///
/// Displays a list of tasks filtered by the current group.
var body: some View {
Group {
if tasks.isEmpty {
ContentUnavailableView(
"view.task-list.content-unavailable.title",
systemImage: "checkmark.circle"
)
} else {
List {
ForEach(tasks) { todo in
Item(todo)
}
}
.listStyle(.grouped)
}
}
.navigationTitle(viewModel.navigationTitle)
}
}
// MARK: - Previews
#Preview(
"Task list with empty tasks",
traits: .emptyContainer
) {
NavigationStack {
TaskListView(group: .today)
}
}
#Preview(
"Task list - today",
traits: .sampleTasks
) {
NavigationStack {
TaskListView(group: .today)
}
}
#Preview(
"Task list - upcoming",
traits: .sampleTasks
) {
NavigationStack {
TaskListView(group: .upcoming)
}
}
#Preview(
"Task list - overdue",
traits: .sampleTasks
) {
NavigationStack {
TaskListView(group: .overdue)
}
}
#Preview(
"Task list - completed",
traits: .sampleTasks
) {
NavigationStack {
TaskListView(group: .completed)
}
}