SPB Git

Repository Public

InboxScreen.swift 19.2 KB 375 lines swift

1// SP Notes Core2// File: Sources/SPNotesFeatures/Work/Inbox/InboxScreen.swift3// Description: The inbox screen: capture box, the captures waiting for triage, a detail with the triage actions and the4//              Smart Inbox checklist (AI, under its badge, applied only on confirmation), and the undo bar. Regular: list5//              and detail side by side; compact: a list of cards and the detail in a sheet.6//7// Author: Simon-Pierre Boucher8// Contact: contact@spboucher.ai9import SPNotesAPI10import SPNotesDesign11import SPNotesSync12import SwiftUI1314public struct InboxScreen: View {15    @State private var model: InboxModel1617    public init(repositories: NotesRepositories, router: (any FeatureRouter)? = nil) {18        _model = State(initialValue: InboxModel(repositories: repositories, router: router))19    }2021    public init(model: InboxModel) { _model = State(initialValue: model) }2223    public var body: some View {24        FeatureScaffold(title: L("Boîte de réception"), subtitle: subtitle, phase: model.phase, freshness: model.freshness,25                        retry: { Task { await model.load() } },26                        actions: { FeatureIconButton("arrow.clockwise", label: L("Actualiser")) { Task { await model.load() } } }) { sizeClass in27            InboxContent(model: model, compact: sizeClass.isCompact)28        }29        .task { if model.phase == .idle { await model.load() } }30    }3132    private var subtitle: String {33        model.items.count > 1 ? LF("%lld captures à trier", model.items.count) : LF("%lld capture à trier", model.items.count)34    }35}3637struct InboxContent: View {38    @Bindable var model: InboxModel39    let compact: Bool4041    var body: some View {42        ZStack(alignment: .bottom) {43            HStack(spacing: 0) {44                list.frame(maxWidth: compact || model.selectedItem == nil ? .infinity : 440)45                if !compact, let item = model.selectedItem {46                    Divider().overlay(NVColor.line)47                    InboxDetailView(model: model, item: item).nvPanelTransition(edge: .trailing)48                }49            }50            if let action = model.lastAction {51                WorkUndoBar(message: action.message, undo: { Task { await model.undo() } }, dismiss: { model.dismissUndo() })52                    .frame(maxWidth: 520)53                    .nvCaptureScaleIn()54            }55        }56        .nvAnimation(.base, value: model.selectedId)57        .nvAnimation(.fast, value: model.lastAction)58        .sheet(item: compact ? Binding(get: { model.selectedItem }, set: { item in Task { await model.select(item?.id) } }) : .constant(nil)) { item in59            InboxDetailView(model: model, item: item).environment(\.featureSizeClass, .compact)60        }61    }6263    private var list: some View {64        VStack(alignment: .leading, spacing: 0) {65            VStack(alignment: .leading, spacing: NVSpace.sm) {66                InboxCaptureBox(model: model)67                if let failure = model.actionFailure { WorkActionFailure(failure: failure) { model.actionFailure = nil } }68            }69            .padding(.horizontal, compact ? NVSpace.lg : NVSpace.xl)70            .padding(.bottom, NVSpace.md)71            FeaturePhaseView(phase: model.phase, hasData: !model.items.isEmpty, retry: { Task { await model.load() } }) {72                NVEmptyState(systemImage: "tray", title: L("Boîte de réception vide"), message: L("Tout est trié. Les nouvelles captures arrivent ici."))73            } content: {74                ScrollView {75                    LazyVStack(spacing: NVSpace.sm) {76                        ForEach(Array(model.items.enumerated()), id: \.element.id) { index, item in77                            InboxRow(model: model, item: item, compact: compact).nvBlockReveal(index: index)78                        }79                    }80                    .padding(.horizontal, compact ? NVSpace.lg : NVSpace.xl)81                    .padding(.bottom, 96)82                }83            }84        }85    }86}8788struct InboxCaptureBox: View {89    @Bindable var model: InboxModel9091    var body: some View {92        VStack(alignment: .leading, spacing: NVSpace.sm) {93            HStack(spacing: NVSpace.sm) {94                TextField(placeholder, text: $model.captureText)95                    .workField()96                    .onSubmit { Task { await model.capture() } }97                    .accessibilityLabel(L("Texte à capturer"))98                FeatureButton(L("Capturer"), systemImage: "tray.and.arrow.down", kind: .primary) { Task { await model.capture() } }99                    .disabled(!model.canCapture)100                    .opacity(model.canCapture ? 1 : 0.5)101            }102            HStack(spacing: NVSpace.sm) {103                ForEach(InboxModel.CaptureMode.allCases) { mode in104                    NVChip(label(mode), systemImage: symbol(mode), tone: .accent, isSelected: model.captureMode == mode) { model.captureMode = mode }105                }106            }107        }108        .disabled(model.isOffline)109        .opacity(model.isOffline ? 0.6 : 1)110    }111112    private var placeholder: String {113        switch model.captureMode {114        case .note: return L("Capturer une idée…")115        case .tasks: return L("Une tâche à faire…")116        case .link: return L("https://… puis une note facultative")117        }118    }119120    private func label(_ mode: InboxModel.CaptureMode) -> String {121        switch mode {122        case .note: return L("Note")123        case .tasks: return L("Tâches")124        case .link: return L("Lien")125        }126    }127128    private func symbol(_ mode: InboxModel.CaptureMode) -> String {129        switch mode {130        case .note: return "note.text"131        case .tasks: return "checklist"132        case .link: return "link"133        }134    }135}136137struct InboxRow: View {138    @Environment(\.featureNow) private var fixedNow139    let model: InboxModel140    let item: InboxItem141    let compact: Bool142143    var body: some View {144        VStack(alignment: .leading, spacing: NVSpace.sm) {145            Button { Task { await model.select(item.id) } } label: {146                HStack(alignment: .top, spacing: NVSpace.md) {147                    Image(systemName: InboxModel.kindSymbol(item.kind))148                        .font(.system(size: 16, weight: .medium))149                        .foregroundStyle(NVColor.accent)150                        .frame(width: 32, height: 32)151                        .background(NVColor.accentSoft, in: NVRadius.shape(NVRadius.sm))152                        .accessibilityHidden(true)153                    VStack(alignment: .leading, spacing: NVSpace.xxs) {154                        Text(item.title.isEmpty ? L("Sans titre") : item.title).nvFont(.uiStrong).foregroundStyle(NVColor.fg).lineLimit(2).multilineTextAlignment(.leading)155                        if let excerpt = item.excerpt, !excerpt.isEmpty {156                            Text(excerpt).nvFont(.ui).foregroundStyle(NVColor.fgMuted).lineLimit(2).multilineTextAlignment(.leading)157                        }158                        HStack(spacing: NVSpace.sm) {159                            Text(InboxModel.kindLabel(item.kind))160                            if let date = item.inboxAt { Text(FeatureFormat.relative(date, now: fixedNow ?? Date())) }161                            if let open = item.openTasks, open > 0 { Text(open > 1 ? LF("%lld tâches", open) : LF("%lld tâche", open)) }162                        }163                        .nvFont(.micro).foregroundStyle(NVColor.fgMuted)164                    }165                    Spacer(minLength: 0)166                }167                .contentShape(Rectangle())168            }169            .buttonStyle(.plain)170            .accessibilityHint(L("Ouvre le tri de la capture"))171            HStack(spacing: NVSpace.sm) {172                FeatureButton(L("Classer"), systemImage: "folder") { Task { await model.triage(item.id, .keep()) } }173                FeatureButton(L("Tâche"), systemImage: "checkmark.circle") { Task { await model.triage(item.id, .task()) } }174                FeatureButton(L("Archiver"), systemImage: "archivebox") { Task { await model.triage(item.id, .archive) } }175            }176            .disabled(model.isOffline || model.isWorking)177            .opacity(model.isOffline ? 0.5 : 1)178        }179        .padding(NVSpace.md)180        .frame(maxWidth: .infinity, alignment: .leading)181        .background(model.selectedId == item.id ? NVColor.accentSoft : NVColor.bgElevated, in: NVRadius.shape(NVRadius.md))182        .overlay(NVRadius.shape(NVRadius.md).strokeBorder(model.selectedId == item.id ? NVColor.accent.opacity(0.5) : NVColor.line, lineWidth: 1))183    }184}185186/// Triage of one capture: every action of the API, then the Smart Inbox.187public struct InboxDetailView: View {188    @Bindable private var model: InboxModel189    private let item: InboxItem190191    public init(model: InboxModel, item: InboxItem) {192        self.model = model193        self.item = item194    }195196    public var body: some View {197        WorkDetailContainer(title: item.title.isEmpty ? L("Sans titre") : item.title, close: { Task { await model.select(nil) } }) {198            VStack(alignment: .leading, spacing: NVSpace.lg) {199                if let excerpt = item.excerpt, !excerpt.isEmpty {200                    Text(excerpt).nvFont(.body).foregroundStyle(NVColor.fg).fixedSize(horizontal: false, vertical: true)201                }202                WorkFlow(spacing: NVSpace.sm) {203                    NVChip(InboxModel.kindLabel(item.kind), systemImage: InboxModel.kindSymbol(item.kind))204                    ForEach(item.tags ?? [], id: \.self) { NVChip("#" + $0) }205                }206                if let failure = model.actionFailure { WorkActionFailure(failure: failure) { model.actionFailure = nil } }207                if model.isOffline {208                    Label(L("Hors ligne : le tri reprendra quand le serveur sera joignable."), systemImage: "wifi.slash").nvFont(.ui).foregroundStyle(NVColor.fgMuted)209                }210                triage211                Divider().overlay(NVColor.line)212                InboxSuggestionsView(model: model)213            }214        }215    }216217    private var triage: some View {218        VStack(alignment: .leading, spacing: NVSpace.sm) {219            Text(L("Trier")).nvFont(.uiStrong).foregroundStyle(NVColor.fg)220            WorkFlow(spacing: NVSpace.sm) {221                Menu {222                    ForEach([PageSection.notes, .documents, .projects, .research], id: \.self) { section in223                        Button(InboxModel.sectionLabel(section.rawValue)) { Task { await model.triage(item.id, .keep(section: section)) } }224                    }225                } label: { Label(L("Classer dans…"), systemImage: "folder") }226                .menuStyle(.borderlessButton).fixedSize()227                FeatureButton(L("En tâche"), systemImage: "checkmark.circle") { Task { await model.triage(item.id, .task()) } }228                if !model.databases.isEmpty {229                    Menu {230                        ForEach(model.databases) { database in231                            Button(database.name) { Task { await model.triage(item.id, .database(databaseId: database.id)) } }232                        }233                    } label: { Label(L("Vers une base…"), systemImage: "tablecells") }234                    .menuStyle(.borderlessButton).fixedSize()235                }236                FeatureButton(L("En référence"), systemImage: "book") { Task { await model.triage(item.id, .reference) } }237                FeatureButton(L("Archiver"), systemImage: "archivebox") { Task { await model.triage(item.id, .archive) } }238                FeatureButton(L("Corbeille"), systemImage: "trash", kind: .destructive) { Task { await model.triage(item.id, .trash) } }239            }240            FeatureButton(L("Ouvrir la page"), systemImage: "arrow.up.right.square") { model.open(item) }241        }242        .disabled(model.isOffline || model.isWorking)243    }244}245246/// The Smart Inbox: nothing is requested from a model without the button, nothing is ticked for the user, nothing is247/// applied before « Appliquer la sélection ».248struct InboxSuggestionsView: View {249    @Bindable var model: InboxModel250251    var body: some View {252        switch model.suggestionState {253        case .unknown, .checking:254            HStack(spacing: NVSpace.sm) { NVProgressDots(tone: .ai); Text(L("Recherche de suggestions déjà calculées…")).nvFont(.ui).foregroundStyle(NVColor.fgMuted) }255        case .unavailable:256            Label(L("Ce serveur ne propose pas les suggestions de tri."), systemImage: "sparkles").nvFont(.ui).foregroundStyle(NVColor.fgMuted)257        case .notGenerated:258            ask(L("Aucune suggestion n'a encore été calculée pour cette capture."))259        case .generating:260            HStack(spacing: NVSpace.sm) { NVProgressDots(tone: .ai); Text(L("Le modèle prépare des suggestions…")).nvFont(.ui).foregroundStyle(NVColor.fgMuted) }261        case .failed(let failure):262            VStack(alignment: .leading, spacing: NVSpace.sm) {263                WorkActionFailure(failure: failure) { Task { await model.select(model.selectedId) } }264                if !failure.isOffline { ask(nil) }265            }266        case .ready(let suggestions):267            if InboxModel.hasContent(suggestions), let set = suggestions.suggestions {268                checklist(suggestions, set)269            } else {270                ask(L("Le modèle n'a rien à proposer pour cette capture."))271            }272        }273    }274275    private func ask(_ note: String?) -> some View {276        VStack(alignment: .leading, spacing: NVSpace.sm) {277            Text(L("Suggestions de tri")).nvFont(.uiStrong).foregroundStyle(NVColor.fg)278            if let note { Text(note).nvFont(.ui).foregroundStyle(NVColor.fgMuted) }279            FeatureButton(L("Demander des suggestions à l'IA"), systemImage: "sparkles", kind: .ai) { Task { await model.askSuggestions() } }280                .disabled(model.isOffline)281            Text(L("Un appel payant à un modèle (quelques centièmes de cent). Rien n'est modifié sans votre accord."))282                .nvFont(.micro).foregroundStyle(NVColor.fgMuted).fixedSize(horizontal: false, vertical: true)283        }284    }285286    @ViewBuilder287    private func checklist(_ suggestions: InboxSuggestions, _ set: InboxSuggestionSet) -> some View {288        FeatureAICard(model: suggestions.model, title: L("Suggestions de tri")) {289            VStack(alignment: .leading, spacing: NVSpace.md) {290                Text(L("Cochez ce que vous voulez appliquer ; vous pouvez corriger le texte avant.")).nvFont(.ui).foregroundStyle(NVColor.fgMuted)291                    .fixedSize(horizontal: false, vertical: true)292                if set.title != nil {293                    check(isOn: $model.choice.useTitle, label: L("Titre")) {294                        TextField(L("Titre proposé"), text: $model.choice.title, axis: .vertical).workField()295                    }296                }297                if let tags = set.tags, !tags.isEmpty {298                    VStack(alignment: .leading, spacing: NVSpace.xs) {299                        Text(L("Étiquettes")).nvFont(.uiStrong).foregroundStyle(NVColor.fg)300                        WorkFlow(spacing: NVSpace.sm) {301                            ForEach(tags, id: \.name) { tag in302                                let on = model.choice.tags.contains(tag.name)303                                NVChip("#" + tag.name + (tag.existing == false ? " · " + L("nouvelle") : ""), systemImage: on ? "checkmark.square.fill" : "square", tone: .ai, isSelected: on) {304                                    if on { model.choice.tags.remove(tag.name) } else { model.choice.tags.insert(tag.name) }305                                }306                                .accessibilityAddTraits(on ? .isSelected : [])307                            }308                        }309                    }310                }311                if let destination = set.destination {312                    check(isOn: $model.choice.useDestination, label: L("Classer")) {313                        Text(destinationText(destination)).nvFont(.ui).foregroundStyle(NVColor.fg)314                        Text(L("La capture quittera la boîte de réception.")).nvFont(.micro).foregroundStyle(NVColor.fgMuted)315                    }316                }317                if let relations = set.relations, !relations.isEmpty {318                    VStack(alignment: .leading, spacing: NVSpace.xs) {319                        Text(L("Pages liées")).nvFont(.uiStrong).foregroundStyle(NVColor.fg)320                        ForEach(relations, id: \.pageId) { relation in321                            let binding = Binding(get: { model.choice.relations.contains(relation.pageId) },322                                                  set: { on in if on { model.choice.relations.insert(relation.pageId) } else { model.choice.relations.remove(relation.pageId) } })323                            check(isOn: binding, label: relation.title ?? L("Sans titre")) {324                                if let reason = relation.reason, !reason.isEmpty {325                                    Text(reason).nvFont(.micro).foregroundStyle(NVColor.fgMuted).fixedSize(horizontal: false, vertical: true)326                                }327                            }328                        }329                    }330                }331                if let summary = set.summary, !summary.isEmpty {332                    check(isOn: $model.choice.useSummary, label: L("Résumé (inséré comme bloc IA)")) {333                        TextField(L("Résumé proposé"), text: $model.choice.summary, axis: .vertical).workField()334                    }335                }336                HStack(spacing: NVSpace.sm) {337                    FeatureButton(model.choice.count > 0 ? LF("Appliquer la sélection (%lld)", model.choice.count) : L("Appliquer la sélection"), systemImage: "checkmark", kind: .ai) {338                        Task { await model.applySuggestions() }339                    }340                    .disabled(model.choice.isEmpty || model.isOffline || model.isWorking)341                    .opacity(model.choice.isEmpty ? 0.5 : 1)342                    FeatureButton(L("Régénérer"), systemImage: "arrow.clockwise") { Task { await model.askSuggestions() } }343                        .disabled(model.isOffline)344                }345            }346        }347    }348349    private func destinationText(_ destination: InboxDestinationSuggestion) -> String {350        let section = InboxModel.sectionLabel(destination.section)351        if let parent = destination.parentTitle, !parent.isEmpty { return LF("%@ › %@", section, parent) }352        return section353    }354355    private func check<Detail: View>(isOn: Binding<Bool>, label: String, @ViewBuilder detail: () -> Detail) -> some View {356        HStack(alignment: .top, spacing: NVSpace.sm) {357            Button { isOn.wrappedValue.toggle() } label: {358                Image(systemName: isOn.wrappedValue ? "checkmark.square.fill" : "square")359                    .font(.system(size: 18))360                    .foregroundStyle(isOn.wrappedValue ? NVColor.ai : NVColor.fgMuted)361                    .frame(minWidth: 32, minHeight: 32)362                    .contentShape(Rectangle())363            }364            .buttonStyle(.plain)365            .accessibilityLabel(label)366            .accessibilityValue(isOn.wrappedValue ? L("coché") : L("non coché"))367            VStack(alignment: .leading, spacing: NVSpace.xs) {368                Text(label).nvFont(.uiStrong).foregroundStyle(NVColor.fg)369                detail()370            }371            .frame(maxWidth: .infinity, alignment: .leading)372        }373    }374}375
Files main
Menu

Theme