SPB Git

Repository Public

TodayScreen.swift 11.5 KB 230 lines swift

1// SP Notes iOS2// File: Features/Home/TodayScreen.swift3// Description: « Aujourd’hui »: what matters now, built from the local store — the tasks due today or overdue, what waits in the4//              inbox, the pinned notes and the recent ones (the 1.0 home content). Works offline. The server's daily brief is5//              a hosted section added later.6//7// Author: Simon-Pierre Boucher8// Contact: contact@spboucher.ai9import SPNotesCore10import SPNotesDesign11import SwiftUI1213/// What « Aujourd’hui » shows of the tasks (pure, tested).14struct TodayTasks: Equatable {15    var overdue: [TaskItem] = []16    var today: [TaskItem] = []17    static let shown = 61819    init(_ tasks: [TaskItem] = [], now: Date = Date(), calendar: Calendar = .current) {20        for group in TaskGrouping.groups(tasks, showDone: false, now: now, calendar: calendar) {21            if group.kind == .overdue { overdue = group.tasks }22            if group.kind == .today { today = group.tasks }23        }24    }2526    var count: Int { overdue.count + today.count }27    /// Overdue first, then today's, limited to what fits the screen.28    var rows: [TaskItem] { Array((overdue + today).prefix(Self.shown)) }29    var hidden: Int { max(0, count - Self.shown) }3031    func summary(inbox: Int) -> String {32        var parts: [String] = []33        if !today.isEmpty { parts.append(today.count == 1 ? String(localized: "1 tâche aujourd’hui") : String(localized: "\(today.count) tâches aujourd’hui")) }34        if !overdue.isEmpty { parts.append(String(localized: "\(overdue.count) en retard")) }35        if inbox > 0 { parts.append(inbox == 1 ? String(localized: "1 capture à trier") : String(localized: "\(inbox) captures à trier")) }36        return parts.isEmpty ? String(localized: "Rien d’urgent. Bonne journée.") : parts.joined(separator: " · ")37    }38}3940struct TodayScreen: View {41    @Environment(AppModel.self) private var app42    @Environment(ShellState.self) private var shell43    @State private var counts: ListCounts?44    @State private var pinned: [PageSummary] = []45    @State private var recent: [PageSummary] = []46    @State private var tasks = TodayTasks()47    @State private var pendingTasks: Set<String> = []48    @State private var pageTitles: [String: String] = [:]49    @State private var loaded = false5051    private var commands: NoteCommands { NoteCommands(app: app, shell: shell) }52    private struct ReloadKey: Equatable { var lists: Int; var tasks: TasksReloadKey }5354    var body: some View {55        List {56            Section {57                VStack(alignment: .leading, spacing: NVSpace.xs) {58                    Text(Date.now.formatted(.dateTime.weekday(.wide).day().month(.wide)).capitalizedFirst)59                        .nvFont(.h1).foregroundStyle(NVColor.fg).accessibilityAddTraits(.isHeader)60                    Text(tasks.summary(inbox: counts?.inbox ?? 0)).font(.subheadline).foregroundStyle(NVColor.fgMuted)61                        .accessibilityIdentifier("today-summary")62                }63                .frame(maxWidth: .infinity, alignment: .leading)64                .padding(.top, NVSpace.xs)65            }66            .listRowSeparator(.hidden)67            .listRowBackground(Color.clear)6869            if app.session == .expired {70                Section { SessionExpiredBanner() }.listRowBackground(NVColor.bgElevated)71            }7273            Section {74                ForEach(tasks.rows) { task in75                    TaskRow(task: task, isPending: pendingTasks.contains(task.id), pageTitle: task.pageId.flatMap { pageTitles[$0] },76                            onToggle: { complete(task) }, onOpen: { shell.go(to: .tasks) },77                            onOpenNote: task.pageId == nil ? nil : { if let id = task.pageId { shell.open(note: id, blockId: task.blockId) } })78                        .listRowInsets(EdgeInsets(top: 0, leading: NVSpace.lg, bottom: 0, trailing: NVSpace.lg))79                        .listRowBackground(NVColor.bg)80                }81                Button { shell.go(to: .tasks) } label: {82                    HStack {83                        Label(tasks.count == 0 ? String(localized: "Rien de prévu aujourd’hui — voir les tâches") : (tasks.hidden > 0 ? String(localized: "Voir les \(tasks.count) tâches du jour") : String(localized: "Toutes les tâches")),84                              systemImage: "checklist")85                            .foregroundStyle(NVColor.accent)86                        Spacer()87                        Image(systemName: "chevron.right").font(.footnote.weight(.semibold)).foregroundStyle(NVColor.fgMuted).accessibilityHidden(true)88                    }89                    .frame(minHeight: 36)90                    .contentShape(Rectangle())91                }92                .buttonStyle(.plain)93                .listRowBackground(NVColor.bg)94                .accessibilityIdentifier("today-tasks")95                Button { shell.go(to: .inbox) } label: {96                    HStack {97                        Label("Boîte de réception", systemImage: "tray").foregroundStyle(NVColor.accent)98                        Spacer()99                        if let inbox = counts?.inbox, inbox > 0 { NVChip("\(inbox)", tone: .accent).accessibilityLabel(InboxText.summary(count: inbox)) }100                        Image(systemName: "chevron.right").font(.footnote.weight(.semibold)).foregroundStyle(NVColor.fgMuted).accessibilityHidden(true)101                    }102                    .frame(minHeight: 36)103                    .contentShape(Rectangle())104                }105                .buttonStyle(.plain)106                .listRowBackground(NVColor.bg)107                .accessibilityIdentifier("today-inbox")108            } header: { NVSectionHeader(String(localized: "À faire")).textCase(nil) }109110            if !pinned.isEmpty {111                Section {112                    ScrollView(.horizontal, showsIndicators: false) {113                        HStack(alignment: .top, spacing: 12) {114                            ForEach(pinned) { note in115                                Button { shell.open(note: note.id) } label: { PinnedCard(note: note) }116                                    .buttonStyle(.plain)117                                    .contextMenu {118                                        Button { Task { await commands.togglePin(note) } } label: { Label("Désépingler", systemImage: "pin.slash") }119                                    }120                            }121                        }122                        .padding(.horizontal, 20)123                        .padding(.vertical, 2)124                    }125                    .listRowInsets(EdgeInsets())126                    .listRowBackground(Color.clear)127                    .listRowSeparator(.hidden)128                } header: { NVSectionHeader(String(localized: "Épinglées")).textCase(nil) }129            }130131            Section {132                if recent.isEmpty, loaded {133                    VStack(alignment: .leading, spacing: 6) {134                        Text("Aucune note pour l’instant").font(.headline).foregroundStyle(Color.spText)135                        Text("Touche le crayon en haut à droite, ou le bouton Capture, pour écrire ta première note. Elle est enregistrée sur cet appareil à l’instant.")136                            .font(.subheadline).foregroundStyle(Color.spTextSecondary)137                    }138                    .padding(.vertical, 6)139                    .listRowBackground(NVColor.bg)140                    .accessibilityIdentifier("home-empty")141                }142                ForEach(recent) { note in143                    Button { shell.open(note: note.id) } label: { NoteRow(note: note) }144                        .buttonStyle(.plain)145                        .listRowBackground(NVColor.bg)146                        .accessibilityIdentifier("recent-row")147                        .swipeActions(edge: .trailing) {148                            Button(role: .destructive) { Task { await commands.trash([note.id]) } } label: { Label("Supprimer", systemImage: "trash") }149                        }150                        .swipeActions(edge: .leading) {151                            Button { Task { await commands.togglePin(note) } } label: { Label(note.pinned ? "Désépingler" : "Épingler", systemImage: note.pinned ? "pin.slash" : "pin") }.tint(.orange)152                        }153                        .draggable(NoteTransfer(ids: [note.id]))154                }155            } header: { NVSectionHeader(String(localized: "Récentes")).textCase(nil) }156        }157        .listStyle(.plain)158        .listSectionSpacing(.compact)159        .environment(\.defaultMinListHeaderHeight, 0)160        .scrollContentBackground(.hidden)161        .background(Color.spBackground)162        .refreshable { await app.syncAndWait() }163        .navigationTitle("Aujourd’hui")164        .navigationBarTitleDisplayMode(.inline)165        .toolbar {166            if shell.isCompact {167                ToolbarItem(placement: .topBarLeading) {168                    Button { shell.sheet = .settings } label: { Label("Réglages", systemImage: "gearshape") }169                        .accessibilityIdentifier("settings")170                }171                ToolbarItem(placement: .topBarTrailing) { SyncIndicator() }172            }173            ToolbarItem(placement: .primaryAction) { NewNoteButton(source: nil) }174        }175        .task(id: ReloadKey(lists: app.feed.lists, tasks: app.tasksReloadKey)) { await load() }176        .accessibilityIdentifier("today-screen")177    }178179    private func complete(_ task: TaskItem) {180        Haptics.tap()181        Task {182            do { try await app.repositories.tasks.setDone(id: task.id, true) } catch { shell.show(AppModel.describe(error)) }183            await load()184        }185    }186187    private func load() async {188        if let fresh = try? await app.store.counts() { counts = fresh }189        pinned = ((try? await app.store.summaries(list: .pinned, limit: 12)) ?? []).filter { $0.kind != .folder }190        recent = Array(((try? await app.store.summaries(list: .recent, limit: 12)) ?? []).filter { $0.kind != .folder }.prefix(6))191        let model = TasksModel(app: app)192        await model.load()193        tasks = TodayTasks(model.tasks)194        pendingTasks = model.pending195        pageTitles = model.pageTitles196        loaded = true197    }198}199200private extension String {201    var capitalizedFirst: String { prefix(1).uppercased() + dropFirst() }202}203204/// A pinned note as a small card of the horizontal strip.205struct PinnedCard: View {206    let note: PageSummary207208    var body: some View {209        VStack(alignment: .leading, spacing: 6) {210            HStack(alignment: .firstTextBaseline, spacing: 4) {211                Text(AppModel.displayTitle(note.title)).font(.subheadline.weight(.semibold)).foregroundStyle(Color.spText).lineLimit(2)212                Spacer(minLength: 2)213                Image(systemName: "pin.fill").font(.caption2).foregroundStyle(Color.accentColor).accessibilityHidden(true)214            }215            Text(note.preview.isEmpty ? String(localized: "Aucun texte") : note.preview)216                .font(.footnote).foregroundStyle(Color.spTextSecondary).lineLimit(3)217                .frame(maxWidth: .infinity, alignment: .leading)218            Spacer(minLength: 0)219            Text(note.updatedAt.listLabel).font(.caption).foregroundStyle(Color.spMuted)220        }221        .padding(12)222        .frame(width: 168, alignment: .topLeading)223        .frame(minHeight: 118, alignment: .topLeading)224        .nvCard(radius: NVRadius.lg)225        .contentShape(RoundedRectangle(cornerRadius: NVRadius.lg, style: .continuous))226        .accessibilityElement(children: .combine)227        .accessibilityIdentifier("pinned-card")228    }229}230
Files main
Menu

Theme