Repository Public
1// SP Notes Core2// File: Sources/SPNotesFeatures/Work/Tasks/TasksScreen.swift3// Description: The tasks screen: quick add, filter, sections by due day, a detail editor (side inspector on regular, sheet4// on compact), sync state per task and the operations the server refused.5//6// Author: Simon-Pierre Boucher7// Contact: contact@spboucher.ai8import SPNotesAPI9import SPNotesDesign10import SPNotesSync11import SwiftUI1213public struct TasksScreen: View {14 @State private var model: TasksModel1516 public init(repositories: NotesRepositories, router: (any FeatureRouter)? = nil, pageId: String? = nil) {17 _model = State(initialValue: TasksModel(repositories: repositories, router: router, pageId: pageId))18 }1920 public init(model: TasksModel) { _model = State(initialValue: model) }2122 public var body: some View {23 FeatureScaffold(title: L("Tâches"), subtitle: subtitle, phase: model.phase, retry: { Task { await model.load() } }) { sizeClass in24 TasksContent(model: model, compact: sizeClass.isCompact)25 }26 .task { if model.phase == .idle { await model.load() } }27 .task { await model.observe() }28 }2930 private var subtitle: String {31 var parts = [model.openCount > 1 ? LF("%lld tâches ouvertes", model.openCount) : LF("%lld tâche ouverte", model.openCount)]32 if model.waitingCount > 0 { parts.append(LF("%lld en attente de synchronisation", model.waitingCount)) }33 return parts.joined(separator: " · ")34 }35}3637struct TasksContent: View {38 @Bindable var model: TasksModel39 let compact: Bool4041 var body: some View {42 HStack(spacing: 0) {43 list44 if !compact, let task = model.selectedTask {45 Divider().overlay(NVColor.line)46 TaskDetailView(model: model, task: task).frame(width: 360).nvPanelTransition(edge: .trailing)47 }48 }49 .nvAnimation(.base, value: model.selectedTaskId)50 .sheet(item: compact ? Binding(get: { model.selectedTask }, set: { model.selectedTaskId = $0?.id }) : .constant(nil)) { task in51 TaskDetailView(model: model, task: task).environment(\.featureSizeClass, .compact)52 }53 }5455 private var list: some View {56 VStack(alignment: .leading, spacing: 0) {57 VStack(alignment: .leading, spacing: NVSpace.md) {58 TaskQuickAdd(model: model, compact: compact)59 HStack(spacing: NVSpace.sm) {60 filterChip(L("Ouvertes"), .open)61 filterChip(L("Terminées"), .done)62 filterChip(L("Toutes"), .all)63 }64 if model.isReadOnly {65 Label(L("Ce serveur ne gère pas encore la modification des tâches depuis l'app. La liste reste consultable."), systemImage: "lock")66 .nvFont(.ui).foregroundStyle(NVColor.fgMuted)67 }68 if let failure = model.actionFailure {69 WorkActionFailure(failure: failure) { model.actionFailure = nil }70 }71 if !model.problems.isEmpty { TaskProblemsCard(model: model) }72 }73 .padding(.horizontal, compact ? NVSpace.lg : NVSpace.xl)74 .padding(.bottom, NVSpace.md)7576 FeaturePhaseView(phase: model.phase, hasData: !model.tasks.isEmpty, retry: { Task { await model.load() } }) {77 NVEmptyState(systemImage: "checklist", title: emptyTitle, message: L("Ajoutez une tâche ci-dessus ; elle sera synchronisée dès que possible, même créée hors ligne."))78 } content: {79 ScrollView {80 LazyVStack(alignment: .leading, spacing: NVSpace.lg) {81 ForEach(model.sections) { section in82 VStack(alignment: .leading, spacing: NVSpace.xs) {83 HStack(spacing: NVSpace.sm) {84 Text(section.group.title).nvFont(.uiStrong)85 .foregroundStyle(section.group == .overdue ? NVColor.dangerText : NVColor.fgMuted)86 Text("\(section.tasks.count)").nvFont(.micro).foregroundStyle(NVColor.fgMuted)87 }88 .accessibilityElement(children: .combine)89 .accessibilityAddTraits(.isHeader)90 VStack(spacing: 0) {91 ForEach(Array(section.tasks.enumerated()), id: \.element.id) { index, task in92 if index > 0 { Divider().overlay(NVColor.line).padding(.leading, 44) }93 TaskRow(model: model, task: task, group: section.group, compact: compact)94 }95 }96 .nvCard(radius: NVRadius.md)97 }98 }99 }100 .padding(.horizontal, compact ? NVSpace.lg : NVSpace.xl)101 .padding(.bottom, NVSpace.xl)102 .frame(maxWidth: compact ? .infinity : 860, alignment: .leading)103 }104 }105 }106 .frame(maxWidth: .infinity, alignment: .topLeading)107 }108109 private var emptyTitle: String {110 switch model.filter {111 case .open: return L("Aucune tâche ouverte")112 case .done: return L("Aucune tâche terminée")113 case .all: return L("Aucune tâche")114 }115 }116117 private func filterChip(_ title: String, _ filter: TaskFilter) -> some View {118 NVChip(title, tone: .accent, isSelected: model.filter == filter) { Task { await model.setFilter(filter) } }119 .accessibilityAddTraits(model.filter == filter ? .isSelected : [])120 }121}122123struct TaskQuickAdd: View {124 @Bindable var model: TasksModel125 let compact: Bool126127 var body: some View {128 HStack(spacing: NVSpace.sm) {129 TextField(L("Nouvelle tâche…"), text: $model.draftTitle)130 .workField()131 .onSubmit { Task { await model.add() } }132 .disabled(model.isReadOnly)133 .accessibilityLabel(L("Titre de la nouvelle tâche"))134 Menu {135 ForEach(TaskPriority.allCases.reversed(), id: \.self) { priority in136 Button(TasksModel.priorityLabel(priority.rawValue)) { model.draftPriority = priority }137 }138 } label: {139 Image(systemName: "flag").foregroundStyle(priorityColor(model.draftPriority.rawValue)).frame(minWidth: 36, minHeight: 36)140 }141 .menuStyle(.borderlessButton)142 .fixedSize()143 .accessibilityLabel(LF("Priorité : %@", TasksModel.priorityLabel(model.draftPriority.rawValue)))144 FeatureButton(compact ? L("Ajouter") : L("Ajouter la tâche"), systemImage: "plus", kind: .primary) { Task { await model.add() } }145 .disabled(!model.canAdd)146 .opacity(model.canAdd ? 1 : 0.5)147 }148 }149}150151func priorityColor(_ priority: String?) -> Color {152 switch priority {153 case TaskPriority.high.rawValue: return NVColor.danger154 case TaskPriority.low.rawValue: return NVColor.fgFaint155 default: return NVColor.warning156 }157}158159struct TaskRow: View {160 let model: TasksModel161 let task: TaskItem162 let group: TasksModel.Group163 let compact: Bool164165 var body: some View {166 HStack(alignment: .top, spacing: NVSpace.sm) {167 Button { Task { await model.toggle(task) } } label: {168 Image(systemName: task.isDone ? "checkmark.circle.fill" : (task.status == TaskStatus.doing.rawValue ? "circle.dotted.circle" : "circle"))169 .font(.system(size: 20))170 .foregroundStyle(task.isDone ? NVColor.success : NVColor.fgMuted)171 .frame(minWidth: compact ? 44 : 32, minHeight: compact ? 44 : 32)172 .contentShape(Rectangle())173 }174 .buttonStyle(.plain)175 .disabled(model.isReadOnly)176 .accessibilityLabel(task.isDone ? LF("Rouvrir « %@ »", task.title) : LF("Terminer « %@ »", task.title))177178 Button { model.selectedTaskId = task.id } label: {179 VStack(alignment: .leading, spacing: NVSpace.xs) {180 Text(task.title)181 .nvFont(.body)182 .foregroundStyle(task.isDone ? NVColor.fgMuted : NVColor.fg)183 .strikethrough(task.isDone, color: NVColor.fgMuted)184 .multilineTextAlignment(.leading)185 WorkFlow(spacing: NVSpace.sm) {186 if let due = TasksModel.dueLabel(task) {187 Label(due, systemImage: "calendar").nvFont(.micro)188 .foregroundStyle(group == .overdue ? NVColor.dangerText : NVColor.fgMuted)189 }190 if task.status == TaskStatus.doing.rawValue {191 Label(L("En cours"), systemImage: "play.circle").nvFont(.micro).foregroundStyle(NVColor.accent)192 }193 if task.priority == TaskPriority.high.rawValue {194 Label(L("Haute"), systemImage: "flag.fill").nvFont(.micro).foregroundStyle(NVColor.dangerText)195 }196 if let page = task.pageTitle, !page.isEmpty {197 Label(page, systemImage: "doc.text").nvFont(.micro).foregroundStyle(NVColor.fgMuted).lineLimit(1)198 }199 if model.pendingIds.contains(task.id) {200 Label(L("À synchroniser"), systemImage: "arrow.triangle.2.circlepath").nvFont(.micro).foregroundStyle(NVColor.fgMuted)201 }202 }203 }204 .frame(maxWidth: .infinity, alignment: .leading)205 .padding(.vertical, NVSpace.sm)206 .contentShape(Rectangle())207 }208 .buttonStyle(.plain)209 .accessibilityHint(L("Ouvre le détail de la tâche"))210 }211 .padding(.horizontal, NVSpace.sm)212 .background(model.selectedTaskId == task.id ? NVColor.accentSoft : .clear)213 }214}215216/// The tasks the server refused: each with its error, « Réessayer » and « Abandonner ».217struct TaskProblemsCard: View {218 let model: TasksModel219220 var body: some View {221 VStack(alignment: .leading, spacing: NVSpace.sm) {222 Label(L("Modifications refusées par le serveur"), systemImage: "exclamationmark.triangle")223 .nvFont(.uiStrong).foregroundStyle(NVColor.dangerText)224 ForEach(model.problems) { operation in225 VStack(alignment: .leading, spacing: NVSpace.xs) {226 Text(model.describe(operation)).nvFont(.ui).foregroundStyle(NVColor.fg)227 if let error = operation.lastError, !error.isEmpty {228 Text(error).nvFont(.micro).foregroundStyle(NVColor.fgMuted).fixedSize(horizontal: false, vertical: true)229 }230 HStack(spacing: NVSpace.sm) {231 FeatureButton(L("Réessayer"), systemImage: "arrow.clockwise") { Task { await model.retry(operation) } }232 FeatureButton(L("Abandonner"), kind: .destructive) { Task { await model.discard(operation) } }233 }234 }235 }236 }237 .padding(NVSpace.md)238 .frame(maxWidth: .infinity, alignment: .leading)239 .background(NVColor.danger.opacity(0.08), in: NVRadius.shape(NVRadius.md))240 .overlay(NVRadius.shape(NVRadius.md).strokeBorder(NVColor.danger.opacity(0.35), lineWidth: 1))241 }242}243244/// Editor of one task. Every change is saved at once (offline-first).245public struct TaskDetailView: View {246 private let model: TasksModel247 private let task: TaskItem248 @State private var title: String249 @State private var hasDue: Bool250 @State private var due: Date251252 public init(model: TasksModel, task: TaskItem) {253 self.model = model254 self.task = task255 _title = State(initialValue: task.title)256 _hasDue = State(initialValue: task.dueAt != nil)257 // The picker works in the user's calendar: show the UTC date part as a local day.258 let day = TasksModel.dueDay(task) ?? WorkDay.string(Date(), timeZone: .current)259 _due = State(initialValue: WorkDay.date(day, hour: 12, timeZone: .current) ?? Date())260 }261262 public var body: some View {263 WorkDetailContainer(title: L("Tâche"), close: { model.selectedTaskId = nil }) {264 VStack(alignment: .leading, spacing: NVSpace.lg) {265 WorkFormRow(label: L("Titre")) {266 TextField(L("Titre"), text: $title, axis: .vertical)267 .workField()268 .onSubmit { Task { await model.rename(title, id: task.id) } }269 .disabled(model.isReadOnly)270 if title != task.title {271 FeatureButton(L("Enregistrer le titre"), kind: .primary) { Task { await model.rename(title, id: task.id) } }272 }273 }274 WorkFormRow(label: L("État")) {275 HStack(spacing: NVSpace.sm) {276 ForEach(TaskStatus.allCases, id: \.self) { status in277 NVChip(TasksModel.statusLabel(status.rawValue), tone: status == .done ? .success : .accent, isSelected: task.status == status.rawValue) {278 Task { await model.setStatus(status, id: task.id) }279 }280 }281 }282 }283 WorkFormRow(label: L("Priorité")) {284 HStack(spacing: NVSpace.sm) {285 ForEach(TaskPriority.allCases, id: \.self) { priority in286 NVChip(TasksModel.priorityLabel(priority.rawValue), systemImage: "flag", tone: priority == .high ? .danger : .neutral,287 isSelected: (task.priority ?? TaskPriority.medium.rawValue) == priority.rawValue) {288 Task { await model.setPriority(priority, id: task.id) }289 }290 }291 }292 }293 WorkFormRow(label: L("Échéance")) {294 Toggle(L("Avec une échéance"), isOn: $hasDue)295 .nvFont(.ui).foregroundStyle(NVColor.fg)296 .onChange(of: hasDue) { _, value in297 Task { await model.setDue(day: value ? WorkDay.string(due, timeZone: .current) : nil, id: task.id) }298 }299 if hasDue {300 DatePicker(L("Jour"), selection: $due, displayedComponents: .date)301 .labelsHidden()302 .onChange(of: due) { _, value in303 Task { await model.setDue(day: WorkDay.string(value, timeZone: .current), id: task.id) }304 }305 }306 }307 .disabled(model.isReadOnly)308 if task.pageId != nil {309 WorkFormRow(label: L("Page")) {310 FeatureButton(task.pageTitle.flatMap { $0.isEmpty ? nil : $0 } ?? L("Ouvrir la page"), systemImage: "doc.text") { model.openPage(of: task) }311 }312 }313 if model.pendingIds.contains(task.id) {314 Label(L("Modifiée sur cet appareil ; sera envoyée à la prochaine synchronisation."), systemImage: "arrow.triangle.2.circlepath")315 .nvFont(.ui).foregroundStyle(NVColor.fgMuted)316 }317 if let failure = model.actionFailure { WorkActionFailure(failure: failure) { model.actionFailure = nil } }318 Divider().overlay(NVColor.line)319 FeatureButton(L("Supprimer la tâche"), systemImage: "trash", kind: .destructive) { Task { await model.delete(id: task.id) } }320 .disabled(model.isReadOnly)321 }322 }323 }324}325