SPB Git

Repository Public

StorageCenter.swift 13.4 KB 179 lines swift

1// Author: Simon-Pierre Boucher — contact@spboucher.ai2// File: Features/Next/StorageCenter.swift3// Description: Storage Command Center (server 2.0): what the account really stores, by kind and by folder with drill-down, the largest files, growth over 90 days, and duplicates (identical content, look-alike images). Everything is a view of facts: nothing is ever deleted automatically — removing a file is always an explicit action on that file.4import Charts5import SPDriveCore6import SPDriveNext7import SwiftUI89struct StorageCenter: View {10    let model: AppModel11    let nav: Navigator12    @State private var overview: Loadable<StorageOverview> = .loading13    @State private var kind: String?14    @State private var folder: Loadable<StorageFolder>?15    @State private var duplicates: Loadable<Duplicates>?16    @State private var similar = false1718    var body: some View {19        Group {20            switch overview {21            case .loading: ProgressView().frame(maxWidth: .infinity, minHeight: 160)22            case .failed(let m): Label(m, systemImage: "wifi.slash").foregroundStyle(SPDTheme.textSecondary).frame(maxWidth: .infinity, alignment: .leading).spdCard()23            case .ready(let o): content(o)24            }25        }26        .task(id: model.revision) { await load() }27    }28    @ViewBuilder private func content(_ o: StorageOverview) -> some View {29        card("Espace", "internaldrive") {30            QuotaBar(used: o.quota.used, limit: o.quota.limit)31            HStack { stat(Fmt.bytes(o.quota.used), "Réellement stocké"); stat(Fmt.bytes(max(0, o.quota.limit - o.quota.used)), "Disponible"); stat(Fmt.bytes(o.trashBytes), "Retenu par la corbeille"); stat(Fmt.bytes(o.oldVersionBytes), "Retenu par d’anciennes versions") }32            Text("\(o.counts.files) fichiers, \(o.counts.folders) dossiers, \(o.counts.versions) versions. « Réellement stocké » compte chaque contenu une seule fois : deux fichiers identiques n’occupent qu’une place.").font(SPDTheme.Typo.caption).foregroundStyle(SPDTheme.textSecondary)33        }34        card("Par type", "square.grid.2x2") {35            let total = max(1, o.byKind.reduce(0) { $0 + $1.bytes })36            GeometryReader { g in37                HStack(spacing: 2) {38                    ForEach(o.byKind) { k in39                        RoundedRectangle(cornerRadius: 3).fill(NextText.kindColor(k.kind)).opacity(kind == nil || kind == k.kind ? 1 : 0.25)40                            .frame(width: max(3, (g.size.width - CGFloat(o.byKind.count) * 2) * CGFloat(k.bytes) / CGFloat(total)))41                            .onTapGesture { kind = kind == k.kind ? nil : k.kind }.help("\(NextText.kind(k.kind)) : \(Fmt.bytes(k.bytes))")42                            .accessibilityLabel("\(NextText.kind(k.kind)), \(Fmt.bytes(k.bytes))").accessibilityAddTraits(.isButton)43                    }44                }45            }.frame(height: 18).spdMotion(.select, value: kind)46            FlowRow(spacing: SPDTheme.Space.sm) {47                ForEach(o.byKind) { k in48                    Button { kind = kind == k.kind ? nil : k.kind } label: {49                        HStack(spacing: 5) { Circle().fill(NextText.kindColor(k.kind)).frame(width: 8, height: 8); Text(NextText.kind(k.kind)).font(SPDTheme.Typo.callout); Text("\(Fmt.bytes(k.bytes)) · \(k.files)").font(SPDTheme.Typo.caption).foregroundStyle(SPDTheme.textSecondary) }50                            .padding(.horizontal, 8).padding(.vertical, 3).background(kind == k.kind ? SPDTheme.selection : SPDTheme.surface, in: Capsule())51                    }.buttonStyle(.plain)52                }53            }54            if let kind {55                let files = o.largest.filter { NextText.kindOf($0) == kind }56                Text(files.isEmpty ? "Aucun des 20 plus gros fichiers n’est de ce type." : "Les plus gros fichiers de ce type").font(SPDTheme.Typo.caption).foregroundStyle(SPDTheme.textSecondary)57                ForEach(files.prefix(6)) { f in fileRow(f) }58            }59        }60        card("Par dossier", "folder") {61            switch folder {62            case .none, .loading: ProgressView().controlSize(.small)63            case .failed(let m): Text(m).foregroundStyle(SPDTheme.textSecondary)64            case .ready(let f):65                HStack(spacing: 3) {66                    ForEach(Array(f.breadcrumbs.enumerated()), id: \.element.id) { i, c in67                        if i > 0 { Image(systemName: "chevron.compact.right").font(.caption).foregroundStyle(SPDTheme.textTertiary) }68                        Button(i == 0 ? "Mon Drive" : c.name) { Task { await drill(i == 0 ? "root" : c.id) } }.buttonStyle(.link).font(i == f.breadcrumbs.count - 1 ? SPDTheme.Typo.bodyStrong : SPDTheme.Typo.callout)69                            .accessibilityIdentifier("storage-crumb-\(i)")70                    }71                    Spacer()72                    Text("\(Fmt.bytes(f.total.bytes)) · \(f.total.files) fichiers").font(SPDTheme.Typo.caption).foregroundStyle(SPDTheme.textSecondary).monospacedDigit()73                }74                let top = max(1, max(f.children.map(\.bytes).max() ?? 0, f.direct.bytes))75                ForEach(f.children.sorted { $0.bytes > $1.bytes }.prefix(14)) { c in76                    Button { Task { await drill(c.folder.id) } } label: { bar(c.folder.name, "folder.fill", c.bytes, c.files, top, chevron: true) }.buttonStyle(.plain).help("Voir l’intérieur de « \(c.folder.name) »").accessibilityIdentifier("storage-folder")77                }78                if f.direct.files > 0 { bar("Fichiers directement ici", "doc", f.direct.bytes, f.direct.files, top, chevron: false) }79                if f.children.isEmpty, !f.files.isEmpty { ForEach(f.files.prefix(6)) { fileRow($0) } }80                if f.children.isEmpty, f.files.isEmpty { Text("Dossier vide.").font(SPDTheme.Typo.callout).foregroundStyle(SPDTheme.textSecondary) }81            }82        }83        card("Croissance sur 90 jours", "chart.bar") {84            if o.growth.isEmpty { Text("Aucun ajout dans les 90 derniers jours.").foregroundStyle(SPDTheme.textSecondary) }85            else {86                Chart(o.growth) { d in87                    BarMark(x: .value("Jour", NextClient.parseDate(d.date) ?? Date(), unit: .day), y: .value("Octets ajoutés", d.bytes)).foregroundStyle(SPDTheme.brand).cornerRadius(2)88                }89                .chartYAxis { AxisMarks { v in AxisGridLine(); AxisValueLabel { if let b = v.as(Int64.self) { Text(Fmt.bytes(b)) } } } }90                .chartXScale(domain: (Calendar.current.date(byAdding: .day, value: -90, to: Date()) ?? Date())...Date())91                .frame(height: 130)92                .accessibilityLabel("Octets ajoutés par jour")93                let sum = o.growth.reduce(0) { $0 + $1.bytes }94                Text("\(Fmt.bytes(sum)) ajoutés en \(o.growth.count) jour\(o.growth.count > 1 ? "s" : "") d’activité (\(o.growth.reduce(0) { $0 + $1.versions }) versions). Seuls les jours avec des ajouts ont une barre.").font(SPDTheme.Typo.caption).foregroundStyle(SPDTheme.textSecondary)95            }96        }97        card("Fichiers les plus volumineux", "arrow.up.right.square") {98            if o.largest.isEmpty { Text("Aucun fichier.").foregroundStyle(SPDTheme.textSecondary) }99            ForEach(o.largest.prefix(10)) { fileRow($0) }100        }101        card("Doublons", "doc.on.doc") {102            HStack {103                Picker("Mode", selection: $similar) { Text("Contenu identique").tag(false); if model.has(.similarImages) { Text("Images qui se ressemblent").tag(true) } }.pickerStyle(.segmented).fixedSize().labelsHidden()104                Spacer()105                Text(similar ? "Images redimensionnées, réencodées ou converties." : "\(o.duplicates.groups) groupe\(o.duplicates.groups > 1 ? "s" : "") · \(Fmt.bytes(o.duplicates.duplicateBytes ?? 0)) en copies").font(SPDTheme.Typo.caption).foregroundStyle(SPDTheme.textSecondary)106            }107            Text(similar ? "Ces images ne sont pas identiques : regardez-les avant de décider. Rien n’est supprimé automatiquement." : "Un contenu identique n’est stocké qu’une fois : retirer un doublon range votre Drive mais ne libère pas d’espace. Rien n’est supprimé automatiquement.").font(SPDTheme.Typo.caption).foregroundStyle(SPDTheme.textSecondary)108            switch duplicates {109            case .none, .loading: ProgressView().controlSize(.small)110            case .failed(let m): Text(m).foregroundStyle(SPDTheme.textSecondary)111            case .ready(let d):112                if d.groups.isEmpty { Label(similar ? "Aucune image ressemblante trouvée." : "Aucun doublon.", systemImage: "checkmark.circle").foregroundStyle(SPDTheme.positive).font(SPDTheme.Typo.callout) }113                ForEach(d.groups.prefix(8)) { g in114                    VStack(alignment: .leading, spacing: 3) {115                        Text(similar ? "\(g.files.count) images proches" : "\(g.files.count) copies de \(Fmt.bytes(g.size ?? g.files.first?.size ?? 0))\(g.distinctNames == true ? " sous des noms différents" : "")").font(SPDTheme.Typo.caption.weight(.semibold)).foregroundStyle(SPDTheme.textSecondary)116                        ForEach(g.files) { f in fileRow(f, trash: true) }117                    }118                    .padding(SPDTheme.Space.sm).background(SPDTheme.surface, in: RoundedRectangle(cornerRadius: SPDTheme.Radius.sm))119                }120                if d.groups.count > 8 { Text("\(d.groups.count - 8) autres groupes.").font(SPDTheme.Typo.caption).foregroundStyle(SPDTheme.textSecondary) }121            }122        }123        .task(id: similar) { await loadDuplicates() }124    }125    private func fileRow(_ f: NextFile, trash: Bool = false) -> some View {126        NextFileRow(model: model, file: f) {127            HStack(spacing: SPDTheme.Space.sm) {128                Text(Fmt.bytes(f.size)).font(SPDTheme.Typo.caption).foregroundStyle(SPDTheme.textSecondary).monospacedDigit()129                Button("Afficher") { model.show(f, in: nav) }.controlSize(.small)130                if trash { Button("Corbeille…", role: .destructive) { if let i = model.item(f.id) { model.trash([i]); model.banner = Banner(text: "« \(f.name) » est dans la corbeille : vous pouvez l’en ressortir.", isError: false) } }.controlSize(.small).disabled(model.item(f.id) == nil).help("Met ce fichier-ci à la corbeille (récupérable)") }131            }132        }133    }134    private func bar(_ name: String, _ symbol: String, _ bytes: Int64, _ files: Int, _ top: Int64, chevron: Bool) -> some View {135        HStack(spacing: SPDTheme.Space.sm) {136            Image(systemName: symbol).foregroundStyle(SPDTheme.brand).frame(width: 18)137            Text(name).font(SPDTheme.Typo.callout).lineLimit(1).frame(width: 190, alignment: .leading)138            GeometryReader { g in Capsule().fill(SPDTheme.brand.opacity(0.75)).frame(width: max(3, g.size.width * CGFloat(bytes) / CGFloat(top))) }.frame(height: 8)139            Text("\(Fmt.bytes(bytes)) · \(files)").font(SPDTheme.Typo.caption).foregroundStyle(SPDTheme.textSecondary).monospacedDigit().frame(width: 120, alignment: .trailing)140            Image(systemName: "chevron.right").font(.caption2).foregroundStyle(SPDTheme.textTertiary).opacity(chevron ? 1 : 0)141        }.contentShape(Rectangle())142    }143    private func card<C: View>(_ title: String, _ symbol: String, @ViewBuilder _ content: () -> C) -> some View {144        VStack(alignment: .leading, spacing: 10) { Label(title, systemImage: symbol).font(SPDTheme.Typo.headline); content() }.frame(maxWidth: .infinity, alignment: .leading).spdCard()145    }146    private func stat(_ value: String, _ label: String) -> some View {147        VStack(alignment: .leading, spacing: 1) { Text(value).font(SPDTheme.Typo.figure); Text(label).font(SPDTheme.Typo.caption).foregroundStyle(SPDTheme.textSecondary) }.frame(maxWidth: .infinity, alignment: .leading).accessibilityElement(children: .combine)148    }149    private func load() async {150        guard let next = model.next else { return }151        do { overview = .ready(try await next.storageOverview()) } catch { if overview.value == nil { overview = .failed(NextText.error(error)) } }152        if folder?.value == nil { await drill("root") }153        await loadDuplicates()154    }155    private func drill(_ id: String) async {156        guard let next = model.next else { return }157        do { folder = .ready(try await next.storageFolder(id)) } catch { folder = .failed(NextText.error(error)) }158    }159    private func loadDuplicates() async {160        guard let next = model.next else { return }161        do { duplicates = .ready(try await next.duplicates(similar ? .similarImages : .exact)) } catch { duplicates = .failed(NextText.error(error)) }162    }163}164extension NextText {165    /// The storage kind of a file, from its extension (the same eight kinds as the server's breakdown).166    static func kindOf(_ f: NextFile) -> String {167        let e = f.fileExtension168        if ["png", "jpg", "jpeg", "gif", "heic", "webp", "tiff", "tif", "bmp", "svg"].contains(e) { return "image" }169        if e == "pdf" { return "pdf" }170        if ["doc", "docx", "odt", "rtf", "pages", "ppt", "pptx", "odp", "key"].contains(e) { return "document" }171        if ["xls", "xlsx", "ods", "csv", "numbers", "tsv"].contains(e) { return "sheet" }172        if ["mp4", "mov", "m4v", "avi", "mkv", "webm"].contains(e) { return "video" }173        if ["mp3", "m4a", "wav", "flac", "aac", "ogg", "aiff"].contains(e) { return "audio" }174        if ["zip", "tar", "gz", "7z", "rar", "bz2", "xz", "dmg"].contains(e) { return "archive" }175        if ["txt", "md", "json", "xml", "yaml", "yml", "html", "log", "tex"].contains(e) { return "text" }176        return "other"177    }178}179
Files main
Menu

Theme