SPB Git

Repository Public

CollectionsScreen.swift 21.7 KB 367 lines swift

1// SP Drive iOS2// File: Features/Next/CollectionsScreen.swift3// Description: Smart collections — saved rules that gather files wherever they are (a collection references files, it never copies them):4//              the list, a rule builder with a live count, and the results. Also the tags editor of a file (tags are what many rules use).5//6// Author: Simon-Pierre Boucher7// Contact: contact@spboucher.ai8import SPDriveNext9import SwiftUI1011extension Color {12    /// The nine names shared by tags and collections on every client.13    static func named(_ name: String?) -> Color {14        switch name { case "red": .red; case "orange": .orange; case "amber": .yellow; case "green": .green; case "teal": .teal; case "blue": .blue; case "violet": .purple; case "pink": .pink; default: .gray }15    }16}1718struct CollectionsScreen: View {19    @Environment(AppModel.self) private var model20    @State private var state: Loadable<[SmartCollection]> = .loading21    @State private var editing: CollectionEdit?2223    var body: some View {24        LoadingView(state: state, retry: load) { collections in25            if collections.isEmpty {26                EmptyState(symbol: "sparkles.rectangle.stack", title: String(localized: "Aucune collection"),27                           message: String(localized: "Une collection rassemble des fichiers d’après une règle (type, étiquette, date, texte…), où qu’ils soient rangés. Elle ne copie rien."),28                           action: (String(localized: "Créer une collection"), { editing = CollectionEdit(existing: nil) }))29            } else {30                List {31                    ForEach(collections) { c in32                        NavigationLink { CollectionResults(collection: c) { await load() } } label: {33                            HStack(spacing: SPDTheme.Space.md) {34                                Image(systemName: Self.symbol(c.icon)).font(.title3).foregroundStyle(.white).frame(width: 40, height: 40).background(Color.named(c.color).gradient, in: RoundedRectangle(cornerRadius: SPDTheme.Radius.md, style: .continuous))35                                VStack(alignment: .leading, spacing: 2) {36                                    Text(c.name).font(.body)37                                    Text(CollectionRuleText.summary(c.rule)).font(.caption).foregroundStyle(.secondary).lineLimit(2)38                                }39                                Spacer(minLength: 4)40                                if let n = c.count { Text("\(n)").font(.subheadline.monospacedDigit()).foregroundStyle(.secondary) }41                            }42                        }43                        .accessibilityIdentifier("collection.\(c.name)")44                        .swipeActions {45                            Button(role: .destructive) { Task { await model.performNext { try await model.next.client.deleteCollection(c.id) }; await load() } } label: { Label("Supprimer", systemImage: "trash") }46                            Button { editing = CollectionEdit(existing: c) } label: { Label("Modifier", systemImage: "slider.horizontal.3") }.tint(.indigo)47                        }48                    }49                    Section { } footer: { Text("Supprimer une collection ne supprime aucun fichier.") }50                }51            }52        }53        .navigationTitle("Collections")54        .toolbar { ToolbarItem(placement: .topBarTrailing) { Button { editing = CollectionEdit(existing: nil) } label: { Label("Nouvelle collection", systemImage: "plus") }.accessibilityIdentifier("collections.add") } }55        .sheet(item: $editing) { e in CollectionEditor(existing: e.existing) { await load() } }56        .refreshable { await load() }57        .task { await load() }58    }5960    private func load() async {61        do { state = .loaded(try await model.next.client.collections()) } catch { if state.value == nil { state = .failed(NextCenter.describe(error)) } }62    }6364    static func symbol(_ icon: String?) -> String {65        switch icon { case "tag": "tag.fill"; case "star": "star.fill"; case "photo", "image": "photo.fill"; case "doc", "file": "doc.fill"; case "clock": "clock.fill"; case "folder": "folder.fill"; default: "sparkles.rectangle.stack.fill" }66    }67}6869struct CollectionEdit: Identifiable { let id = UUID(); let existing: SmartCollection? }7071/// A rule said in words.72enum CollectionRuleText {73    static let fieldLabels: [String: String] = ["kind": "Type", "ext": "Extension", "name": "Nom", "text": "Texte du document", "size": "Taille", "modified": "Modifié", "created": "Créé",74                                                "starred": "Favori", "shared": "Partagé par lien", "untagged": "Sans étiquette", "folder": "Dossier", "tag": "Étiquette"]75    static let opLabels: [String: String] = ["is": "est", "isNot": "n’est pas", "contains": "contient", "gt": "plus que", "lt": "moins que", "within": "dans les derniers"]76    static let kindLabels: [String: String] = ["image": "Image", "pdf": "PDF", "document": "Document", "sheet": "Feuille de calcul", "video": "Vidéo", "audio": "Audio", "archive": "Archive", "text": "Texte"]7778    static func value(_ c: RuleCondition) -> String {79        switch c.value {80        case .bool(let b): return b ? String(localized: "oui") : String(localized: "non")81        case .number(let n):82            if c.field == "size" { return Int64(n).byteString }83            if c.op == "within" { return String(localized: "\(Int(n)) jours") }84            return String(Int(n))85        case .string(let s): return c.field == "kind" ? (kindLabels[s] ?? s) : (c.field == "tag" || c.field == "folder") ? "…" : s86        }87    }88    static func summary(_ rule: CollectionRule) -> String {89        let parts = rule.conditions.map { "\(fieldLabels[$0.field] ?? $0.field) \(opLabels[$0.op] ?? $0.op) \(value($0))" }90        return parts.joined(separator: rule.match == "any" ? String(localized: " ou ") : String(localized: " et "))91    }92}9394struct CollectionEditor: View {95    @Environment(AppModel.self) private var model96    @Environment(\.dismiss) private var dismiss97    let existing: SmartCollection?98    let saved: () async -> Void99    @State private var name = ""100    @State private var color = "blue"101    @State private var matchAll = true102    @State private var conditions: [EditableCondition] = [EditableCondition()]103    @State private var tags: [DriveTag] = []104    @State private var previewCount: Int?105    @State private var previewError: String?106    @State private var saving = false107    @State private var pickingFolderFor: UUID?108109    struct EditableCondition: Identifiable, Equatable {110        let id = UUID()111        var field = "kind", op = "is"112        var text = "pdf"113        var flag = true114        var number: Double = 30115        var condition: RuleCondition? {116            let kind = CollectionRule.fields.first { $0.field == field }?.value ?? "string"117            switch kind {118            case "bool": return RuleCondition(field: field, op: op, value: .bool(flag))119            case "bytes": return RuleCondition(field: field, op: op, value: .number(number * 1_000_000))120            case "date":121                // `within` counts days; `gt` / `lt` take a date: the builder offers the relative form, the commonest on a phone122                return op == "within" ? RuleCondition(field: field, op: op, value: .number(number)) : RuleCondition(field: field, op: op, value: .string(ISO8601DateFormatter().string(from: Date.now.addingTimeInterval(-number * 86_400))))123            default: return text.trimmingCharacters(in: .whitespaces).isEmpty ? nil : RuleCondition(field: field, op: op, value: .string(text.trimmingCharacters(in: .whitespaces)))124            }125        }126    }127128    private var rule: CollectionRule? {129        let c = conditions.compactMap(\.condition)130        return c.count == conditions.count && !c.isEmpty ? CollectionRule(match: matchAll ? "all" : "any", conditions: c) : nil131    }132133    var body: some View {134        NavigationStack {135            Form {136                Section("Collection") {137                    TextField("Nom", text: $name).accessibilityIdentifier("collection.name")138                    ScrollView(.horizontal, showsIndicators: false) {139                        HStack(spacing: 10) {140                            ForEach(CollectionRule.colors, id: \.self) { c in141                                Button { color = c; Haptics.selection() } label: { Circle().fill(Color.named(c).gradient).frame(width: 30, height: 30).overlay { if color == c { Image(systemName: "checkmark").font(.caption.weight(.bold)).foregroundStyle(.white) } } }142                                    .buttonStyle(.plain).accessibilityLabel(Text(c)).accessibilityAddTraits(color == c ? .isSelected : [])143                            }144                        }.padding(.vertical, 2)145                    }146                }147                Section {148                    Picker("Les fichiers qui remplissent", selection: $matchAll) { Text("toutes les conditions").tag(true); Text("au moins une").tag(false) }149                    ForEach($conditions) { $c in conditionRow($c) }150                        .onDelete { conditions.remove(atOffsets: $0) }151                    Button { conditions.append(EditableCondition(field: "name", op: "contains", text: "")) } label: { Label("Ajouter une condition", systemImage: "plus.circle") }.accessibilityIdentifier("collection.addCondition")152                } header: { Text("Règle") }153                Section {154                    if let previewError { Label(previewError, systemImage: "exclamationmark.triangle").foregroundStyle(SPDTheme.Palette.critical).font(.footnote) }155                    else if let previewCount { Label(previewCount == 1 ? String(localized: "1 fichier correspond en ce moment") : String(localized: "\(previewCount) fichiers correspondent en ce moment"), systemImage: "eye").accessibilityIdentifier("collection.preview") }156                    else if rule == nil { Text("Complète chaque condition pour voir ce que la règle rassemble.").foregroundStyle(.secondary).font(.footnote) }157                    else { ProgressView() }158                } footer: { Text("La collection suit ton Drive : un fichier y entre ou en sort quand il se met à remplir la règle ou cesse de la remplir.") }159            }160            .navigationTitle(existing == nil ? String(localized: "Nouvelle collection") : String(localized: "Modifier la collection"))161            .navigationBarTitleDisplayMode(.inline)162            .toolbar {163                ToolbarItem(placement: .cancellationAction) { Button("Annuler") { dismiss() } }164                ToolbarItem(placement: .confirmationAction) { Button("Enregistrer") { save() }.bold().disabled(saving || rule == nil || name.trimmingCharacters(in: .whitespaces).isEmpty).accessibilityIdentifier("collection.save") }165            }166            .sheet(item: Binding(get: { pickingFolderFor.map { IdentifiedID(id: $0) } }, set: { pickingFolderFor = $0?.id })) { target in167                FolderPicker(title: String(localized: "Choisir"), excluding: [], startAt: nil) { folder in if let i = conditions.firstIndex(where: { $0.id == target.id }) { conditions[i].text = folder } }168            }169            .task {170                tags = (try? await model.next.client.tags()) ?? []171                if let existing {172                    name = existing.name; color = existing.color ?? "blue"; matchAll = existing.rule.match != "any"173                    conditions = existing.rule.conditions.map { c in174                        var e = EditableCondition(field: c.field, op: c.op)175                        switch c.value { case .bool(let b): e.flag = b; case .number(let n): e.number = c.field == "size" ? n / 1_000_000 : n; case .string(let s): e.text = s }176                        return e177                    }178                }179            }180            .task(id: rule) { await preview() }181        }182    }183184    @ViewBuilder private func conditionRow(_ c: Binding<EditableCondition>) -> some View {185        let spec = CollectionRule.fields.first { $0.field == c.wrappedValue.field }186        VStack(alignment: .leading, spacing: 8) {187            HStack {188                Picker("Critère", selection: c.field) { ForEach(CollectionRule.fields, id: \.field) { Text(LocalizedStringKey(CollectionRuleText.fieldLabels[$0.field] ?? $0.field)).tag($0.field) } }.labelsHidden()189                Picker("Opérateur", selection: c.op) { ForEach(spec?.ops ?? ["is"], id: \.self) { Text(LocalizedStringKey(CollectionRuleText.opLabels[$0] ?? $0)).tag($0) } }.labelsHidden()190            }191            switch spec?.value {192            case "kind": Picker("Type", selection: c.text) { ForEach(CollectionRule.kinds, id: \.self) { Text(LocalizedStringKey(CollectionRuleText.kindLabels[$0] ?? $0)).tag($0) } }.pickerStyle(.menu)193            case "bool": Toggle(isOn: c.flag) { Text("Oui") }194            case "bytes": Stepper(value: c.number, in: 1...50_000, step: c.wrappedValue.number >= 100 ? 50 : 5) { Text("\(Int(c.wrappedValue.number)) Mo") }195            case "date": Stepper(value: c.number, in: 1...3650, step: c.wrappedValue.number >= 60 ? 30 : 1) { Text(c.wrappedValue.op == "within" ? "\(Int(c.wrappedValue.number)) jours" : "il y a \(Int(c.wrappedValue.number)) jours") }196            case "tag":197                if tags.isEmpty { Text("Aucune étiquette : crée-en une depuis la feuille d’un fichier.").font(.footnote).foregroundStyle(.secondary) }198                else { Picker("Étiquette", selection: c.text) { ForEach(tags) { Label($0.name, systemImage: "tag.fill").tag($0.id) } }.pickerStyle(.menu) }199            case "folder":200                Button { pickingFolderFor = c.wrappedValue.id } label: { Label(model.store.item(c.wrappedValue.text)?.name ?? String(localized: "Choisir un dossier…"), systemImage: "folder") }201            default: TextField(c.wrappedValue.field == "ext" ? "pdf" : "Texte", text: c.text).textInputAutocapitalization(.never).autocorrectionDisabled().accessibilityIdentifier("collection.value")202            }203        }204        .onChange(of: c.wrappedValue.field) { _, field in205            // a new criterion starts with an operator and a value that are valid for it206            let s = CollectionRule.fields.first { $0.field == field }207            c.wrappedValue.op = s?.ops.first ?? "is"208            c.wrappedValue.text = s?.value == "kind" ? "pdf" : s?.value == "tag" ? (tags.first?.id ?? "") : ""209        }210    }211212    private func preview() async {213        previewError = nil214        guard let rule else { previewCount = nil; return }215        try? await Task.sleep(for: .milliseconds(400))216        guard !Task.isCancelled else { return }217        do { previewCount = try await model.next.client.previewCollection(rule, limit: 1).total } catch { if !Task.isCancelled { previewCount = nil; previewError = NextCenter.describe(error) } }218    }219220    private func save() {221        guard let rule else { return }222        saving = true223        let draft = CollectionDraft(name: name.trimmingCharacters(in: .whitespaces), icon: existing?.icon, color: color, rule: rule)224        Task {225            await model.performNext(success: String(localized: "Collection enregistrée")) {226                if let existing { _ = try await model.next.client.updateCollection(existing.id, draft) } else { _ = try await model.next.client.createCollection(draft) }227                await saved()228                dismiss()229            }230            saving = false231        }232    }233}234235struct IdentifiedID: Identifiable { let id: UUID }236237struct CollectionResults: View {238    @Environment(AppModel.self) private var model239    let collection: SmartCollection240    let changed: () async -> Void241    @State private var state: Loadable<CollectionItems> = .loading242    @State private var actions = ItemActions()243244    var body: some View {245        LoadingView(state: state, retry: load) { items in246            if items.files.isEmpty {247                EmptyState(symbol: "tray", title: String(localized: "Aucun fichier pour l’instant"), message: String(localized: "Aucun fichier ne remplit cette règle : \(CollectionRuleText.summary(collection.rule))."))248            } else {249                List {250                    Section { NextFileList(files: items.files, actions: actions) } header: { Text(CollectionRuleText.summary(collection.rule)) } footer: {251                        Text(items.total > items.files.count ? String(localized: "\(items.files.count) premiers fichiers sur \(items.total).") : (items.total == 1 ? String(localized: "1 fichier") : String(localized: "\(items.total) fichiers")))252                    }253                }254                .listStyle(.plain)255            }256        }257        .navigationTitle(collection.name)258        .navigationBarTitleDisplayMode(.inline)259        .refreshable { await load() }260        .task { await load() }261        .itemActions(actions)262    }263264    private func load() async {265        do {266            let items = try await model.next.client.collectionItems(collection.id)267            if items.files.contains(where: { model.store.item($0.id) == nil }) { await model.engine.sync() }268            state = .loaded(items)269        } catch { if state.value == nil { state = .failed(NextCenter.describe(error)) } }270    }271}272273/// Files returned by a 2.0 call, shown with the explorer's rows when the mirror knows them (same actions as everywhere).274struct NextFileList: View {275    @Environment(AppModel.self) private var model276    let files: [NextFile]277    let actions: ItemActions278    var body: some View {279        let _ = model.itemsVersion280        ForEach(files) { f in281            if let item = model.store.item(f.id) {282                Button { actions.open(item, model: model) } label: { ItemRowView(item: item, showLocation: true, onMore: { actions.sheet = .actions(item) }) }.buttonStyle(.plain)283            } else {284                Label { VStack(alignment: .leading) { Text(f.name); Text(f.size.byteString).font(.caption).foregroundStyle(.secondary) } } icon: { KindIcon(kind: f.fileKind, size: 36) }285            }286        }287    }288}289290// MARK: Tags of a file291292struct TagsEditor: View {293    @Environment(AppModel.self) private var model294    @Environment(\.dismiss) private var dismiss295    let item: DriveItem296    @State private var state: Loadable<[DriveTag]> = .loading297    @State private var selected: Set<String> = []298    @State private var newName = ""299    @State private var newColor = "blue"300301    var body: some View {302        NavigationStack {303            LoadingView(state: state, retry: load) { tags in304                List {305                    Section {306                        if tags.isEmpty { Text("Aucune étiquette pour l’instant.").foregroundStyle(.secondary) }307                        ForEach(tags) { tag in308                            Button { toggle(tag) } label: {309                                HStack {310                                    Image(systemName: "tag.fill").foregroundStyle(Color.named(tag.color))311                                    Text(tag.name).foregroundStyle(.primary)312                                    Spacer()313                                    if selected.contains(tag.id) { Image(systemName: "checkmark").foregroundStyle(SPDTheme.Palette.brand).accessibilityLabel(Text("Appliquée")) }314                                }315                            }316                            .accessibilityIdentifier("tag.\(tag.name)")317                            .swipeActions { Button(role: .destructive) { Task { await model.performNext { try await model.next.client.deleteTag(tag.id) }; await load() } } label: { Label("Supprimer l’étiquette", systemImage: "trash") } }318                        }319                    } header: { Text("Étiquettes de « \(item.name) »") } footer: { Text("Supprimer une étiquette la retire de tous les fichiers ; aucun fichier n’est supprimé.") }320                    Section("Nouvelle étiquette") {321                        TextField("Nom", text: $newName).accessibilityIdentifier("tag.newName")322                        ScrollView(.horizontal, showsIndicators: false) {323                            HStack(spacing: 10) {324                                ForEach(DriveTag.colors, id: \.self) { c in325                                    Button { newColor = c } label: { Circle().fill(Color.named(c)).frame(width: 28, height: 28).overlay { if newColor == c { Image(systemName: "checkmark").font(.caption2.weight(.bold)).foregroundStyle(.white) } } }.buttonStyle(.plain).accessibilityLabel(Text(c))326                                }327                            }328                        }329                        Button("Créer et appliquer") { create() }.disabled(newName.trimmingCharacters(in: .whitespaces).isEmpty).accessibilityIdentifier("tag.create")330                    }331                }332            }333            .navigationTitle("Étiquettes")334            .navigationBarTitleDisplayMode(.inline)335            .toolbar { ToolbarItem(placement: .confirmationAction) { Button("OK") { dismiss() }.accessibilityIdentifier("tags.done") } }336            .task { await load() }337        }338        .presentationDetents([.medium, .large])339    }340341    private func load() async {342        do {343            async let all = model.next.client.tags()344            async let mine = model.next.client.tagIDs(of: item.id)345            selected = Set(try await mine)346            state = .loaded(try await all)347        } catch { if state.value == nil { state = .failed(NextCenter.describe(error)) } }348    }349    private func toggle(_ tag: DriveTag) {350        var next = selected351        if next.contains(tag.id) { next.remove(tag.id) } else { next.insert(tag.id) }352        Haptics.selection()353        Task { await model.performNext { try await model.next.client.setTags(of: item.id, to: Array(next)); selected = next }; await load() }354    }355    private func create() {356        let name = newName.trimmingCharacters(in: .whitespaces)357        Task {358            await model.performNext {359                let tag = try await model.next.client.createTag(name: name, color: newColor)360                try await model.next.client.setTags(of: item.id, to: Array(selected.union([tag.id])))361                newName = ""362            }363            await load()364        }365    }366}367
Files main
Menu

Theme