Files
todos/App/Sources/Views/TaskList/TaskListContent.swift
T

238 lines
7.8 KiB
Swift

import SwiftData
import SwiftUI
extension TaskListView {
/// Internal content view that manages the dynamic SwiftData query for tasks.
///
/// This view is responsible for querying and displaying the list of tasks based on the specified
/// group and completion status filter. It exists as a separate view to enable dynamic query
/// updates when filter parameters change.
struct Content: View {
// MARK: Type aliases
/// Closure type for handling task deletion operations.
///
/// - Parameters:
/// - todos: The current array of todo tasks.
/// - offsets: The index set of tasks to delete.
typealias DeleteClosure = ([Todo], IndexSet) -> Void
/// Closure type for handling task reorder operations.
///
/// - Parameters:
/// - todos: The current array of todo tasks.
/// - source: The index set of items being moved.
/// - destination: The destination index for the moved items.
typealias ReorderClosure = ([Todo], IndexSet, Int) -> Void
// MARK: Properties
/// Query to fetch todo tasks filtered by group and completion status.
///
/// This query is initialized with a todo fetch descriptor that applies predicates
/// based on the group type and completion filter. SwiftData automatically
/// monitors changes and updates the view when the underlying data changes.
///
/// Tasks are sorted by their `order` property first, then by date-based criteria
/// specific to each group, enabling both manual and automatic ordering.
@Query
private var todos: [Todo]
/// Indicates whether tasks in this view can be reordered through drag and drop.
///
/// This value is derived from the ``TodoGroup/canReorder`` property and
/// determines whether the `.onMove` modifier is applied to the task list.
private let canReorder: Bool
/// Closure called when tasks are deleted through swipe-to-delete.
///
/// This closure is invoked by the `.onDelete` modifier and is responsible for
/// removing the selected tasks from the model context.
private let onDelete: DeleteClosure
/// Closure called when tasks are reordered through drag and drop.
///
/// This closure is invoked by the `.onMove` modifier and is responsible for
/// updating the `order` property of affected tasks to reflect their new positions.
private let onReorder: ReorderClosure
// MARK: Initializers
/// Creates a content view with a configured task query and reorder handler.
///
/// This initializer sets up a query with a fetch descriptor that filters
/// tasks based on the specified group and completion status. When these parameters
/// change, SwiftUI recreates the view with new values, causing the query to update.
///
/// The reordering capability is automatically determined based on the
/// ``TodoGroup/canReorder`` property. For groups that support reordering,
/// the provided closure will be called when users drag and drop tasks to new positions.
///
/// - Parameters:
/// - group: The todo group category to filter by (today, upcoming, overdue, or completed).
/// - showCompleted: Whether to include completed tasks in the results. Only applies to groups other than `.completed`.
/// - onReorder: A closure called when tasks are reordered.
/// - onDelete: A closure called when tasks are deleted.
init(
group: TodoGroup,
showCompleted: Bool,
onDelete: @escaping DeleteClosure,
onReorder: @escaping ReorderClosure
) {
self._todos = .init(
FetchDescriptor<Todo>(
group: group,
showCompleted: showCompleted
)
)
self.canReorder = group.canReorder
self.onDelete = onDelete
self.onReorder = onReorder
}
// MARK: Body
/// The content and behavior of the view.
///
/// Displays either a content unavailable state or a list of tasks
/// based on whether any tasks match the current filters.
///
/// When tasks are present, displays them in a grouped list. The list supports
/// drag and drop reordering for groups where `canReorder` is true, allowing
/// users to manually prioritize tasks within the group. For groups where
/// reordering is disabled (such as completed tasks), the list is displayed
/// in read-only mode with chronological sorting.
var body: some View {
Group {
if todos.isEmpty {
ContentUnavailableView(
"view.task-list-content.content-unavailable.title",
systemImage: "checkmark.circle"
)
}
else {
List {
items
}
.listStyle(.grouped)
.onTapGesture {
resignFocus()
}
}
}
}
}
}
// MARK: - Helpers
private extension TaskListView.Content {
// MARK: Computed
/// A view that renders the task items with appropriate modifiers.
///
/// This computed property constructs a `ForEach` view over the tasks and conditionally
/// applies the `.onMove` modifier based on the `canReorder` capability. This approach
/// ensures that:
/// - All todo task lists support swipe-to-delete via `.onDelete`
/// - Only todo task groups that can be manually reordered enable drag-and-drop via `.onMove`
@ViewBuilder
var items: some View {
let items = ForEach(todos) {
TaskListView.Item($0)
}
.onDelete { offsets in
onDelete(todos, offsets)
}
if canReorder {
items.onMove { source, destination in
onReorder(todos, source, destination)
}
}
else {
items
}
}
// MARK: Functions
/// Dismisses the keyboard by resigning first responder status.
///
/// This function sends a `resignFirstResponder` action through the responder chain,
/// causing any active text field or text view to resign its first responder status
/// and dismiss the keyboard.
func resignFocus() {
UIApplication.shared.sendAction(
#selector(UIResponder.resignFirstResponder),
to: nil,
from: nil,
for: nil
)
}
}
// MARK: - Previews
#Preview(
"Task list content when there are no tasks",
traits: .emptyContainer
) {
TaskListView.Content(
group: .today,
showCompleted: .random()
) { _, _ in
// On delete closure
} onReorder: { _, _, _ in
// On reorder closure
}
}
#Preview(
"Task list content when completed tasks not shown",
traits: .sampleTasks
) {
TaskListView.Content(
group: .today,
showCompleted: false
) { _, _ in
// On delete closure
} onReorder: { _, _, _ in
// On reorder closure
}
}
#Preview(
"Task list content when completed tasks shown",
traits: .sampleTasks
) {
TaskListView.Content(
group: .today,
showCompleted: true
) { _, _ in
// On delete closure
} onReorder: { _, _, _ in
// On reorder closure
}
}
#Preview(
"Task list content when only completed tasks shown",
traits: .sampleTasks
) {
TaskListView.Content(
group: .completed,
showCompleted: .random()
) { _, _ in
// On delete closure
} onReorder: { _, _, _ in
// On reorder closure
}
}