SPB Git

Repository Public

CollectionsView.swift 18.4 KB 247 lines swift

1// Author: Simon-Pierre Boucher — contact@spboucher.ai2// File: Features/Next/CollectionsView.swift3// Description: Smart collections: saved rules that gather files wherever they are (a collection references files, it never copies them). The section lists a collection's files; the rule builder composes conditions with the fields, operators and values the server accepts, and shows the live result before saving.4import SPDriveCore5import SPDriveNext6import SwiftUI78enum CollectionLook {9    static func color(_ name: String?) -> Color {10        switch name { case "red": Color(red: 0.84, green: 0.27, blue: 0.25); case "orange": Color(red: 0.93, green: 0.52, blue: 0.18); case "amber": Color(red: 0.85, green: 0.65, blue: 0.13); case "green": Color(red: 0.20, green: 0.62, blue: 0.40)11        case "teal": Color(red: 0.16, green: 0.60, blue: 0.62); case "blue": Color(red: 0.25, green: 0.48, blue: 0.92); case "violet": SPDTheme.brand; case "pink": Color(red: 0.88, green: 0.36, blue: 0.62); default: SPDTheme.textSecondary }12    }13    static func colorName(_ c: String) -> String { ["slate": "Ardoise", "red": "Rouge", "orange": "Orange", "amber": "Ambre", "green": "Vert", "teal": "Sarcelle", "blue": "Bleu", "violet": "Violet", "pink": "Rose"][c] ?? c }14    /// The server stores a free identifier; the clients agree on SF Symbol names.15    static func symbol(_ icon: String?) -> String { (icon?.isEmpty == false ? icon! : "square.stack.3d.up") }16    static let symbols = ["square.stack.3d.up", "doc.text", "photo", "film", "music.note", "tablecells", "archivebox", "star", "clock", "link", "tray.full", "briefcase"]17    static func field(_ f: String) -> String {18        ["kind": "Type", "ext": "Extension", "name": "Nom", "text": "Contenu", "size": "Taille", "modified": "Modifié", "created": "Créé", "starred": "Favori", "shared": "Partagé", "untagged": "Sans étiquette", "folder": "Dossier", "tag": "Étiquette"][f] ?? f19    }20    static func op(_ o: String, field: String) -> String {21        switch o { case "is": ["starred", "shared", "untagged"].contains(field) ? "est" : (field == "folder" ? "est dans" : "est"); case "isNot": field == "folder" ? "n’est pas dans" : "n’est pas"; case "contains": "contient"22        case "gt": ["modified", "created"].contains(field) ? "après le" : "plus grand que"; case "lt": ["modified", "created"].contains(field) ? "avant le" : "plus petit que"; case "within": "dans les derniers"; default: o }23    }24    /// A rule said in words.25    @MainActor static func describe(_ rule: CollectionRule, model: AppModel) -> String {26        rule.conditions.map { c -> String in27            let v: String28            switch c.value {29            case .bool(let b): v = b ? "oui" : "non"30            case .number(let n): v = c.field == "size" ? Fmt.bytes(Int64(n)) : (c.op == "within" ? "\(Int(n)) jours" : "\(Int(n))")31            case .string(let s): v = c.field == "kind" ? NextText.kind(s) : c.field == "folder" ? "« \(model.item(s)?.name ?? "dossier") »" : "« \(s) »"32            }33            return "\(field(c.field).lowercased()) \(op(c.op, field: c.field)) \(v)"34        }.joined(separator: rule.match == "any" ? " ou " : " et ")35    }36}3738struct CollectionsView: View {39    @Environment(AppModel.self) private var model40    @Environment(Navigator.self) private var nav41    @State private var items: Loadable<CollectionItems> = .loading42    @State private var confirmDelete: SmartCollection?4344    private var current: SmartCollection? { model.collections.first { $0.id == nav.collectionID } ?? model.collections.first }45    var body: some View {46        Group {47            if model.collections.isEmpty {48                SPDEmptyState(symbol: "square.stack.3d.up", title: "Aucune collection", message: "Une collection rassemble des fichiers selon une règle — « les PDF modifiés ce mois-ci », « les images de plus de 10 Mo » — où qu’ils soient rangés. Elle se met à jour toute seule et ne copie rien.") {49                    Button("Créer une collection…") { nav.sheet = .collection(nil) }.buttonStyle(.borderedProminent).accessibilityIdentifier("new-collection")50                }51            } else if let c = current {52                VStack(spacing: 0) {53                    HStack(spacing: SPDTheme.Space.sm) {54                        Image(systemName: CollectionLook.symbol(c.icon)).foregroundStyle(CollectionLook.color(c.color)).font(.title3)55                        VStack(alignment: .leading, spacing: 0) {56                            Text(c.name).font(SPDTheme.Typo.headline)57                            Text((c.rule.match == "any" ? "Au moins une condition : " : "Toutes les conditions : ") + CollectionLook.describe(c.rule, model: model)).font(SPDTheme.Typo.caption).foregroundStyle(SPDTheme.textSecondary).lineLimit(2)58                        }59                        Spacer()60                    }61                    .padding(SPDTheme.Space.md).background(.bar).overlay(alignment: .bottom) { Rectangle().fill(SPDTheme.hairline).frame(height: 1) }62                    switch items {63                    case .loading: ProgressView().frame(maxWidth: .infinity, maxHeight: .infinity)64                    case .failed(let m): SPDEmptyState(symbol: "wifi.slash", title: "Collection indisponible", message: m) { Button("Réessayer") { Task { await load(c) } } }65                    case .ready(let r):66                        if r.files.isEmpty { SPDEmptyState(symbol: CollectionLook.symbol(c.icon), title: "Rien pour l’instant", message: "Aucun fichier ne répond à cette règle en ce moment. La collection se remplira d’elle-même.") { Button("Modifier la règle…") { nav.sheet = .collection(c) } } }67                        else {68                            List(selection: Binding(get: { nav.selection }, set: { nav.selection = $0 })) {69                                ForEach(r.files) { f in70                                    NextFileRow(model: model, file: f) { Text("\(Fmt.bytes(f.size)) · \(f.modified.map(Fmt.day) ?? "")").font(SPDTheme.Typo.caption).foregroundStyle(SPDTheme.textSecondary).monospacedDigit() }71                                        .tag(f.id).padding(.vertical, 2)72                                        .contextMenu {73                                            Button("Afficher dans son dossier", systemImage: "folder") { model.show(f, in: nav) }74                                            Button("Ouvrir", systemImage: "arrow.up.forward.app") { Task { await model.open(f.item(model)) } }75                                            Button("Télécharger", systemImage: "arrow.down.circle") { Task { await model.download([f.item(model)]) } }76                                        }77                                }78                                if r.total > r.files.count { Text("\(r.total - r.files.count) autres fichiers répondent à la règle.").font(SPDTheme.Typo.caption).foregroundStyle(SPDTheme.textSecondary) }79                            }80                            .listStyle(.inset)81                            .contextMenu(forSelectionType: String.self) { _ in } primaryAction: { ids in if let f = r.files.first(where: { ids.contains($0.id) }) { model.show(f, in: nav) } }82                        }83                    }84                }85                .task(id: "\(c.id)|\(c.updatedAt?.timeIntervalSince1970 ?? 0)|\(model.revision)") { await load(c) }86            }87        }88        .navigationTitle(current?.name ?? "Collections")89        .navigationSubtitle(items.value.map { "\($0.total) fichier\($0.total > 1 ? "s" : "")" } ?? "")90        .toolbar {91            ToolbarItemGroup {92                Button { nav.sheet = .collection(nil) } label: { Label("Nouvelle collection", systemImage: "plus") }.help("Nouvelle collection")93                if let c = current {94                    Button { nav.sheet = .collection(c) } label: { Label("Modifier", systemImage: "slider.horizontal.3") }.help("Modifier la règle")95                    Button(role: .destructive) { confirmDelete = c } label: { Label("Supprimer la collection", systemImage: "trash") }.help("Supprimer la collection (les fichiers ne sont pas touchés)")96                }97            }98        }99        .confirmationDialog("Supprimer la collection « \(confirmDelete?.name ?? "") » ?", isPresented: Binding(get: { confirmDelete != nil }, set: { if !$0 { confirmDelete = nil } })) {100            Button("Supprimer la collection", role: .destructive) { if let c = confirmDelete { Task { try? await model.next?.deleteCollection(c.id); nav.collectionID = nil; await model.refreshCollections() } } }101            Button("Annuler", role: .cancel) {}102        } message: { Text("Seule la règle est supprimée. Aucun fichier n’est modifié ni supprimé.") }103    }104    private func load(_ c: SmartCollection) async {105        guard let next = model.next else { return }106        do { items = .ready(try await next.collectionItems(c.id)) } catch { items = .failed(NextText.error(error)) }107    }108}109110/// One condition being edited (kept loosely typed while the person composes it).111struct ConditionDraft: Identifiable {112    let id = UUID()113    var field = "kind", op = "is"114    var text = "pdf", number = 30.0, flag = true, date = Date(), unit = 1_000_000.0115    init() {}116    init(_ c: RuleCondition) {117        field = c.field; op = c.op118        switch c.value {119        case .bool(let b): flag = b120        case .number(let n): if c.field == "size" { unit = n >= 1e9 ? 1e9 : n >= 1e6 ? 1e6 : 1e3; number = n / unit } else { number = n }121        case .string(let s): if ["modified", "created"].contains(c.field), let d = NextClient.parseDate(s) { date = d } else { text = s }122        }123    }124    var valueKind: String { CollectionRule.fields.first { $0.field == field }?.value ?? "string" }125    var ops: [String] { CollectionRule.fields.first { $0.field == field }?.ops ?? ["is"] }126    /// nil while the condition is incomplete.127    var condition: RuleCondition? {128        switch valueKind {129        case "bool": return RuleCondition(field: field, op: "is", value: .bool(flag))130        case "bytes": return number > 0 ? RuleCondition(field: field, op: op, value: .number((number * unit).rounded())) : nil131        case "date":132            if op == "within" { return number >= 1 ? RuleCondition(field: field, op: op, value: .number(number.rounded())) : nil }133            let f = DateFormatter(); f.calendar = Calendar(identifier: .gregorian); f.dateFormat = "yyyy-MM-dd"134            return RuleCondition(field: field, op: op, value: .string(f.string(from: date)))135        default:136            let t = text.trimmingCharacters(in: .whitespaces)137            return t.isEmpty ? nil : RuleCondition(field: field, op: op, value: .string(field == "ext" ? t.lowercased().trimmingCharacters(in: CharacterSet(charactersIn: ".")) : t))138        }139    }140}141142struct CollectionEditor: View {143    let model: AppModel144    let nav: Navigator145    let existing: SmartCollection?146    @Environment(\.dismiss) private var dismiss147    @State private var name = ""148    @State private var icon = "square.stack.3d.up"149    @State private var color = "violet"150    @State private var matchAll = true151    @State private var conditions: [ConditionDraft] = [ConditionDraft()]152    @State private var sortBy = "updated"153    @State private var sortDesc = true154    @State private var preview: Loadable<CollectionItems> = .loading155    @State private var error: String?156    @State private var busy = false157158    private var rule: CollectionRule? {159        let c = conditions.compactMap(\.condition)160        guard c.count == conditions.count, !c.isEmpty else { return nil }161        return CollectionRule(match: matchAll ? "all" : "any", conditions: c, sort: .init(by: sortBy, dir: sortDesc ? "desc" : "asc"))162    }163    private var folders: [DriveItem] { model.rootID.map { root in model.children(of: root).filter(\.isFolder).flatMap { f in [f] + model.children(of: f.id).filter(\.isFolder) } } ?? [] }164    var body: some View {165        VStack(alignment: .leading, spacing: 0) {166            VStack(alignment: .leading, spacing: 2) {167                Text(existing == nil ? "Nouvelle collection" : "Modifier la collection").font(SPDTheme.Typo.title)168                Text("Une règle, pas un dossier : les fichiers restent où ils sont.").font(SPDTheme.Typo.callout).foregroundStyle(SPDTheme.textSecondary)169            }.padding(SPDTheme.Space.lg)170            Form {171                Section("Présentation") {172                    TextField("Nom", text: $name).accessibilityIdentifier("collection-name")173                    Picker("Symbole", selection: $icon) { ForEach(CollectionLook.symbols, id: \.self) { Image(systemName: $0).tag($0) } }.pickerStyle(.segmented)174                    Picker("Couleur", selection: $color) { ForEach(CollectionRule.colors, id: \.self) { c in Label(CollectionLook.colorName(c), systemImage: "circle.fill").foregroundStyle(CollectionLook.color(c)).tag(c) } }175                }176                Section("Règle") {177                    Picker("Garder les fichiers qui remplissent", selection: $matchAll) { Text("toutes les conditions").tag(true); Text("au moins une condition").tag(false) }178                    ForEach($conditions) { $c in179                        HStack(spacing: SPDTheme.Space.sm) {180                            Picker("Champ", selection: $c.field) { ForEach(CollectionRule.fields.map(\.field).filter { $0 != "tag" }, id: \.self) { Text(CollectionLook.field($0)).tag($0) } }.labelsHidden().frame(width: 130)181                                .onChange(of: c.field) { _, f in c.op = c.ops.first ?? "is"; if f == "kind" { c.text = "pdf" } else if f == "folder" { c.text = folders.first?.id ?? "" } else if ["ext", "name", "text"].contains(f) { c.text = "" } }182                            if c.valueKind != "bool" { Picker("Opérateur", selection: $c.op) { ForEach(c.ops, id: \.self) { Text(CollectionLook.op($0, field: c.field)).tag($0) } }.labelsHidden().frame(width: 150) }183                            value($c)184                            Spacer(minLength: 0)185                            Button { conditions.removeAll { $0.id == c.id } } label: { Image(systemName: "minus.circle") }.buttonStyle(.plain).foregroundStyle(SPDTheme.textSecondary).disabled(conditions.count == 1).accessibilityLabel("Retirer la condition")186                        }187                    }188                    Button("Ajouter une condition", systemImage: "plus.circle") { conditions.append(ConditionDraft()) }.buttonStyle(.link).disabled(conditions.count >= 20)189                    HStack { Picker("Trier par", selection: $sortBy) { Text("Date de modification").tag("updated"); Text("Nom").tag("name"); Text("Taille").tag("size"); Text("Date de création").tag("created") }; Toggle("Décroissant", isOn: $sortDesc) }190                }191                Section("Résultat en ce moment") {192                    switch preview {193                    case .loading: Text(rule == nil ? "Complétez les conditions pour voir le résultat." : "Calcul…").foregroundStyle(SPDTheme.textSecondary)194                    case .failed(let m): Label(m, systemImage: "exclamationmark.triangle").foregroundStyle(SPDTheme.warning)195                    case .ready(let r):196                        Text("\(r.total) fichier\(r.total > 1 ? "s" : "")").font(SPDTheme.Typo.bodyStrong)197                        ForEach(r.files.prefix(5)) { NextFileRow(model: model, file: $0) }198                    }199                }200                if let error { Section { Label(error, systemImage: "exclamationmark.triangle.fill").foregroundStyle(SPDTheme.critical) } }201            }202            .formStyle(.grouped)203            HStack {204                Spacer()205                Button("Annuler", role: .cancel) { dismiss() }.keyboardShortcut(.cancelAction)206                Button(existing == nil ? "Créer" : "Enregistrer") { Task { await save() } }.keyboardShortcut(.defaultAction).buttonStyle(.borderedProminent)207                    .disabled(busy || rule == nil || name.trimmingCharacters(in: .whitespaces).isEmpty).accessibilityIdentifier("save-collection")208            }.padding(SPDTheme.Space.lg)209        }210        .frame(width: 680, height: 660)211        .onAppear {212            guard let e = existing else { return }213            name = e.name; icon = CollectionLook.symbol(e.icon); color = e.color ?? "violet"; matchAll = e.rule.match != "any"214            conditions = e.rule.conditions.map(ConditionDraft.init); sortBy = e.rule.sort?.by ?? "updated"; sortDesc = e.rule.sort?.dir != "asc"215        }216        .task(id: rule) {217            guard let rule, let next = model.next else { preview = .loading; return }218            try? await Task.sleep(nanoseconds: 350_000_000); if Task.isCancelled { return }219            do { preview = .ready(try await next.previewCollection(rule, limit: 5)) } catch { if !Task.isCancelled { preview = .failed(NextText.error(error)) } }220        }221    }222    @ViewBuilder private func value(_ c: Binding<ConditionDraft>) -> some View {223        switch c.wrappedValue.valueKind {224        case "kind": Picker("Valeur", selection: c.text) { ForEach(CollectionRule.kinds, id: \.self) { Text(NextText.kind($0)).tag($0) } }.labelsHidden().frame(width: 170)225        case "bool": Picker("Valeur", selection: c.flag) { Text("oui").tag(true); Text("non").tag(false) }.pickerStyle(.segmented).labelsHidden().frame(width: 110)226        case "bytes":227            TextField("Taille", value: c.number, format: .number).frame(width: 70)228            Picker("Unité", selection: c.unit) { Text("Ko").tag(1e3); Text("Mo").tag(1e6); Text("Go").tag(1e9) }.labelsHidden().frame(width: 70)229        case "date":230            if c.wrappedValue.op == "within" { TextField("Jours", value: c.number, format: .number).frame(width: 60); Text("jours") }231            else { DatePicker("Date", selection: c.date, displayedComponents: .date).labelsHidden() }232        case "folder": Picker("Dossier", selection: c.text) { ForEach(folders) { f in Text(model.path(to: f.id).map(\.name).joined(separator: " › ")).tag(f.id) } }.labelsHidden().frame(maxWidth: 240)233        default: TextField(c.wrappedValue.field == "ext" ? "pdf" : "texte", text: c.text).frame(maxWidth: 220)234        }235    }236    private func save() async {237        guard let rule, let next = model.next else { return }238        busy = true; defer { busy = false }239        let draft = CollectionDraft(name: name.trimmingCharacters(in: .whitespaces), icon: icon, color: color, rule: rule)240        do {241            let saved: SmartCollection242            if let e = existing { saved = try await next.updateCollection(e.id, draft) } else { saved = try await next.createCollection(draft) }243            await model.refreshCollections(); nav.collectionID = saved.id; nav.section = .collections; dismiss()244        } catch { self.error = NextText.error(error) }245    }246}247
Files main
Menu

Theme