Repository Public
1// Author: Simon-Pierre Boucher — contact@spboucher.ai2// File: Features/Inbox/InboxScreen.swift3// Description: Inbox triage: every capture waiting to be filed, with one-gesture actions — file it in a space or a folder, turn it into a task, archive it, delete it — and an undo for each. Works offline: the actions are local page changes and task-outbox operations that the synchronisation sends later.4import SwiftUI5import SPNotesCore6import SPNotesStore7import SPNotesSync8import SPNotesDesign910@Observable final class InboxModel {11 private(set) var items: [PageSummary] = []12 private(set) var isLoaded = false13 /// The last triage, kept so that it can be reversed.14 private(set) var lastAction: Done?15 @ObservationIgnored weak var env: AppEnvironment?16 @ObservationIgnored private let store: NotesStore17 @ObservationIgnored private let repositories: NotesRepositories18 @ObservationIgnored private var watcher: Task<Void, Never>?1920 enum Action: Equatable { case file(section: String?, parentId: String?), task, archive, trash }21 /// What a triage did, with what is needed to reverse it exactly.22 struct Done: Equatable { let pageId: String; let action: Action; let inboxAt: Date; let previousSection: String; let previousParent: String?; let taskId: String?; let title: String }2324 init(store: NotesStore, repositories: NotesRepositories) { self.store = store; self.repositories = repositories }2526 func start() async {27 await load()28 watcher = Task { [weak self] in guard let self else { return }; for await change in await self.store.changes() { if case .pages = change { await self.load() } else if case .reset = change { await self.load() } } }29 }30 func load() async { items = (try? await store.summaries(list: .inbox, limit: 500)) ?? []; isLoaded = true }3132 /// Applies a triage action. Local first: the capture leaves the inbox at once, whatever the network.33 @discardableResult func triage(_ id: String, _ action: Action) async -> Bool {34 guard let env, !env.isBlocked, let page = try? await store.page(id: id), let inboxAt = page.inboxAt else { return false }35 await env.existingSession(id)?.saveNow(reason: nil)36 var taskId: String?37 do {38 switch action {39 case .file(let section, let parent):40 if section != nil || parent != nil { _ = try await store.move(id: id, parentId: parent, section: section) }41 _ = try await store.setInbox(id: id, at: nil)42 case .task:43 taskId = try await repositories.tasks.create(title: Format.title(page.title), pageId: id).id44 _ = try await store.setInbox(id: id, at: nil)45 case .archive: _ = try await store.setArchived(id: id, true); _ = try await store.setInbox(id: id, at: nil)46 case .trash: _ = try await store.trash(id: id)47 }48 } catch RepositoryError.unsupported { env.toasts.show("Le serveur ne synchronise pas encore les tâches (version 2.x).", isError: true); return false }49 catch { env.toasts.error(error); return false }50 let done = Done(pageId: id, action: action, inboxAt: inboxAt, previousSection: page.section, previousParent: page.parentId, taskId: taskId, title: Format.title(page.title))51 lastAction = done52 await load(); await env.tasks.load(); env.syncMonitor.localChange()53 env.toasts.show(Self.summary(done), symbol: "tray.and.arrow.down", action: .init(title: "Annuler") { [weak self] in Task { await self?.undo() } })54 return true55 }5657 static func summary(_ d: Done) -> String {58 switch d.action { case .file: "« \(d.title) » classée"; case .task: "« \(d.title) » convertie en tâche"; case .archive: "« \(d.title) » archivée"; case .trash: "« \(d.title) » placée dans la corbeille" }59 }6061 /// Reverses the last triage: the capture is back in the inbox with its capture date, where it was.62 @discardableResult func undo() async -> Bool {63 guard let d = lastAction, let env else { return false }64 do {65 switch d.action {66 case .file: _ = try await store.move(id: d.pageId, parentId: d.previousParent, section: d.previousSection)67 case .task: if let t = d.taskId { try await repositories.tasks.delete(id: t) }68 case .archive: _ = try await store.setArchived(id: d.pageId, false)69 case .trash: _ = try await store.restore(id: d.pageId)70 }71 _ = try await store.setInbox(id: d.pageId, at: d.inboxAt)72 } catch { env.toasts.error(error); return false }73 lastAction = nil74 await load(); await env.tasks.load(); env.syncMonitor.localChange()75 env.toasts.show("Remise dans la boîte de réception", symbol: "arrow.uturn.backward")76 return true77 }78}7980struct InboxScreen: View {81 @Environment(AppEnvironment.self) private var env82 @Bindable var model: InboxModel83 let router: FeatureRouting84 @State private var selection: String?8586 var body: some View {87 VStack(spacing: 0) {88 PanelHeader(title: "Boîte de réception", subtitle: model.items.isEmpty ? "Tout est classé" : model.items.count == 1 ? "1 capture à classer" : "\(model.items.count) captures à classer") {89 if model.lastAction != nil { Button { Task { await model.undo() } } label: { Label("Annuler le dernier classement", systemImage: "arrow.uturn.backward") }.keyboardShortcut("z", modifiers: [.command, .option]).accessibilityIdentifier("inbox-undo") }90 }91 .padding(.horizontal, NVSpace.xl).padding(.top, NVSpace.xl).padding(.bottom, NVSpace.md)92 Divider().overlay(NVColor.line)93 if model.items.isEmpty, model.isLoaded {94 NVEmptyState(systemImage: "tray", title: "Boîte de réception vide", message: "Les notes rapides, la sélection envoyée par le menu Services et ce que tu déposes sur la fenêtre de capture arrivent ici, en attendant d'être classés.").frame(maxHeight: .infinity)95 } else {96 ScrollView {97 LazyVStack(spacing: NVSpace.md) {98 ForEach(Array(model.items.enumerated()), id: \.element.id) { i, item in99 InboxCard(item: item, selected: selection == item.id, model: model, router: router).nvBlockReveal(index: i).onTapGesture { selection = item.id }100 }101 }102 .padding(NVSpace.xl).frame(maxWidth: NVSpace.readingMeasure + NVSpace.huge).frame(maxWidth: .infinity)103 }104 }105 }106 .background(NVColor.bg)107 .task { await model.load() }108 .accessibilityIdentifier("inbox-screen")109 }110}111112private struct InboxCard: View {113 @Environment(AppEnvironment.self) private var env114 let item: PageSummary, selected: Bool115 let model: InboxModel116 let router: FeatureRouting117 var body: some View {118 VStack(alignment: .leading, spacing: NVSpace.sm) {119 HStack(alignment: .firstTextBaseline, spacing: NVSpace.sm) {120 if let icon = item.icon, !icon.isEmpty { Text(icon) }121 Text(Format.title(item.title)).nvFont(.h3).lineLimit(2)122 Spacer()123 Text(Format.short(item.inboxAt ?? item.updatedAt)).nvFont(.micro).foregroundStyle(NVColor.fgMuted)124 SyncDot(state: item.syncState)125 }126 if !item.preview.isEmpty { Text(item.preview).nvFont(.ui).foregroundStyle(NVColor.fgMuted).lineLimit(3).frame(maxWidth: .infinity, alignment: .leading) }127 HStack(spacing: NVSpace.sm) {128 Menu {129 Button("Garder dans « Notes »") { act(.file(section: nil, parentId: nil)) }130 ForEach(LibraryModel.sections.filter { $0.id != item.section }, id: \.id) { s in Button("Espace « \(s.label) »") { act(.file(section: s.id, parentId: nil)) } }131 let folders = flat(env.library.folders).filter { $0.id != item.id }.prefix(30)132 if !folders.isEmpty { Divider(); ForEach(Array(folders)) { f in Button("Dossier « \(Format.title(f.title)) »") { act(.file(section: nil, parentId: f.id)) } } }133 } label: { Label("Classer", systemImage: "folder") } primaryAction: { act(.file(section: nil, parentId: nil)) }.fixedSize().accessibilityIdentifier("inbox-file")134 Button { act(.task) } label: { Label("Convertir en tâche", systemImage: "checklist") }.accessibilityIdentifier("inbox-task")135 Button { act(.archive) } label: { Label("Archiver", systemImage: "archivebox") }.accessibilityIdentifier("inbox-archive")136 Button(role: .destructive) { act(.trash) } label: { Label("Supprimer", systemImage: "trash") }.accessibilityIdentifier("inbox-trash")137 Spacer()138 Button("Ouvrir") { router.openPage(id: item.id, blockId: nil) }.buttonStyle(.link)139 }.controlSize(.small)140 }141 .padding(NVSpace.lg).nvCard(radius: NVRadius.lg)142 .overlay(NVRadius.shape(NVRadius.lg).strokeBorder(selected ? NVColor.accent.opacity(0.6) : .clear, lineWidth: 1.5))143 .contentShape(Rectangle())144 .accessibilityElement(children: .contain).accessibilityIdentifier("inbox-card")145 }146 private func act(_ a: InboxModel.Action) { Task { await model.triage(item.id, a) } }147 private func flat(_ nodes: [FolderNode]) -> [PageSummary] { nodes.flatMap { [$0.page] + flat($0.children ?? []) } }148}149