SPB Git

Repository Public

NoteRemindersView.swift 9.7 KB 201 lines swift

1// SP Notes iOS2// File: Features/Reminders/NoteRemindersView.swift3// Description: Reminders of one note: add (date and time, optional label), mark done, delete. A reminder is saved on the device and4//              syncs as a task; the notification permission is asked when the first one is saved, and a refusal is shown plainly.5//6// Author: Simon-Pierre Boucher7// Contact: contact@spboucher.ai8import SPNotesCore9import SwiftUI10import UIKit1112/// Rules of the reminders, independent of the views.13enum ReminderLogic {14    static let maxLabelLength = 2001516    static func cleanLabel(_ label: String) -> String {17        String(label.replacingOccurrences(of: "\n", with: " ").trimmingCharacters(in: .whitespacesAndNewlines).prefix(maxLabelLength))18    }1920    /// The date proposed for a new reminder: the next full hour, at least 30 minutes away.21    static func defaultDate(from now: Date = Date(), calendar: Calendar = .current) -> Date {22        let later = now.addingTimeInterval(30 * 60)23        let start = calendar.dateInterval(of: .hour, for: later)?.start ?? later24        return calendar.date(byAdding: .hour, value: 1, to: start) ?? later25    }2627    /// A reminder can be saved for a moment that is still to come (a minute of tolerance for the time spent in the form).28    static func isValid(dueAt: Date, now: Date = Date()) -> Bool { dueAt > now.addingTimeInterval(-60) }2930    struct Sections: Equatable {31        var upcoming: [ReminderRecord] = []32        var overdue: [ReminderRecord] = []33        var done: [ReminderRecord] = []34        var isEmpty: Bool { upcoming.isEmpty && overdue.isEmpty && done.isEmpty }35    }3637    /// Deleted reminders (waiting for the server) are hidden; open ones are split around `now`, soonest first; done ones last.38    static func sections(_ reminders: [ReminderRecord], now: Date = Date()) -> Sections {39        var out = Sections()40        for reminder in reminders where !reminder.deleted {41            if reminder.done { out.done.append(reminder) }42            else if let due = reminder.dueAt, due < now { out.overdue.append(reminder) }43            else { out.upcoming.append(reminder) }44        }45        let byDate: (ReminderRecord, ReminderRecord) -> Bool = { ($0.dueAt ?? .distantFuture) < ($1.dueAt ?? .distantFuture) }46        out.upcoming.sort(by: byDate)47        out.overdue.sort(by: byDate)48        out.done.sort { $0.updatedAt > $1.updatedAt }49        return out50    }5152    @MainActor static func title(_ reminder: ReminderRecord, noteTitle: String) -> String {53        reminder.title.isEmpty ? AppModel.displayTitle(noteTitle) : reminder.title54    }5556    static func dateLabel(_ date: Date?) -> String {57        guard let date else { return String(localized: "Sans date") }58        return date.formatted(date: .complete, time: .shortened)59    }60}6162struct NoteRemindersView: View {63    let noteId: String64    let noteTitle: String6566    @Environment(AppModel.self) private var app67    @Environment(\.dismiss) private var dismiss68    @State private var reminders: [ReminderRecord] = []69    @State private var loaded = false70    @State private var label = ""71    @State private var dueAt = ReminderLogic.defaultDate()72    @State private var notificationsRefused = false73    @State private var errorMessage: String?74    @State private var isSaving = false75    @FocusState private var labelFocused: Bool7677    private var sections: ReminderLogic.Sections { ReminderLogic.sections(reminders) }7879    var body: some View {80        NavigationStack {81            Form {82                Section {83                    DatePicker("Date et heure", selection: $dueAt, in: Date()..., displayedComponents: [.date, .hourAndMinute])84                        .accessibilityIdentifier("reminder-date")85                    TextField("Libellé (facultatif)", text: $label)86                        .focused($labelFocused)87                        .submitLabel(.done)88                        .accessibilityIdentifier("reminder-label")89                    Button { Task { await add() } } label: {90                        HStack { Text("Ajouter le rappel").bold(); if isSaving { Spacer(); ProgressView() } }91                    }92                    .disabled(isSaving || !ReminderLogic.isValid(dueAt: dueAt))93                    .accessibilityIdentifier("reminder-add")94                } header: { Text("Nouveau rappel") } footer: {95                    if notificationsRefused {96                        VStack(alignment: .leading, spacing: 6) {97                            Label("Les notifications sont refusées pour SP Notes : le rappel est enregistré et synchronisé comme tâche, mais cet appareil ne te préviendra pas.", systemImage: "bell.slash")98                                .foregroundStyle(Color.spWarning)99                            Button("Ouvrir les réglages") {100                                if let url = URL(string: UIApplication.openNotificationSettingsURLString) { UIApplication.shared.open(url) }101                            }102                            .font(.footnote)103                        }104                        .accessibilityIdentifier("reminder-refused")105                    } else {106                        Text("Le rappel reste sur l’appareil et se synchronise comme tâche de cette note.")107                    }108                }109                if !sections.overdue.isEmpty { section("En retard", sections.overdue, overdue: true) }110                if !sections.upcoming.isEmpty { section("À venir", sections.upcoming, overdue: false) }111                if !sections.done.isEmpty { section("Faits", sections.done, overdue: false) }112                if loaded && sections.isEmpty {113                    Section { Text("Aucun rappel pour cette note.").font(.subheadline).foregroundStyle(Color.spTextSecondary) }114                }115            }116            .scrollContentBackground(.hidden)117            .background(Color.spBackground)118            .navigationTitle("Rappels")119            .navigationBarTitleDisplayMode(.inline)120            .toolbar { ToolbarItem(placement: .confirmationAction) { Button("OK") { dismiss() }.accessibilityIdentifier("reminders-close") } }121            .task(id: app.feed.reminders) { await load() }122            .alert("Rappel non enregistré", isPresented: Binding(get: { errorMessage != nil }, set: { if !$0 { errorMessage = nil } })) {123                Button("OK", role: .cancel) {}124            } message: { Text(errorMessage ?? "") }125        }126        .accessibilityIdentifier("reminders-sheet")127    }128129    private func section(_ title: LocalizedStringKey, _ items: [ReminderRecord], overdue: Bool) -> some View {130        Section(title) {131            ForEach(items) { reminder in132                HStack(spacing: 12) {133                    Button { Task { await toggle(reminder) } } label: {134                        Image(systemName: reminder.done ? "checkmark.circle.fill" : "circle")135                            .font(.title3)136                            .foregroundStyle(reminder.done ? Color.spSuccess : Color.spMuted)137                    }138                    .buttonStyle(.plain)139                    .frame(minWidth: 44, minHeight: 44)140                    .accessibilityLabel(reminder.done ? "Marquer comme à faire" : "Marquer comme fait")141                    VStack(alignment: .leading, spacing: 2) {142                        Text(ReminderLogic.title(reminder, noteTitle: noteTitle))143                            .font(.body).foregroundStyle(Color.spText).strikethrough(reminder.done)144                        HStack(spacing: 4) {145                            if overdue { Image(systemName: "exclamationmark.circle").accessibilityHidden(true) }146                            Text(overdue ? String(localized: "En retard · \(ReminderLogic.dateLabel(reminder.dueAt))") : ReminderLogic.dateLabel(reminder.dueAt))147                        }148                        .font(.caption)149                        .foregroundStyle(overdue ? Color.spDanger : Color.spTextSecondary)150                    }151                }152                .swipeActions(edge: .trailing) {153                    Button(role: .destructive) { Task { await delete(reminder) } } label: { Label("Supprimer", systemImage: "trash") }154                }155                .contextMenu {156                    Button { Task { await toggle(reminder) } } label: { Label(reminder.done ? "Marquer comme à faire" : "Marquer comme fait", systemImage: "checkmark.circle") }157                    Button(role: .destructive) { Task { await delete(reminder) } } label: { Label("Supprimer", systemImage: "trash") }158                }159                .accessibilityIdentifier("reminder-row")160            }161        }162    }163164    private func load() async {165        reminders = (try? await app.store.reminders(pageId: noteId)) ?? []166        loaded = true167    }168169    private func add() async {170        guard !isSaving else { return }171        isSaving = true172        defer { isSaving = false }173        labelFocused = false174        do {175            let result = try await app.addReminder(noteId: noteId, noteTitle: AppModel.displayTitle(noteTitle), label: label, dueAt: dueAt)176            notificationsRefused = !result.notifies177            label = ""178            dueAt = ReminderLogic.defaultDate()179            Haptics.success()180            await load()181        } catch {182            errorMessage = error.localizedDescription183        }184    }185186    private func toggle(_ reminder: ReminderRecord) async {187        do {188            try await app.setReminderDone(reminder.id, done: !reminder.done, noteTitle: AppModel.displayTitle(noteTitle), notifies: !notificationsRefused)189            Haptics.tap()190            await load()191        } catch { errorMessage = error.localizedDescription }192    }193194    private func delete(_ reminder: ReminderRecord) async {195        do {196            try await app.removeReminder(reminder.id)197            await load()198        } catch { errorMessage = error.localizedDescription }199    }200}201
Files main
Menu

Theme