Repository Public
1// SP Drive iOS2// File: Features/Next/StorageCenter.swift3// Description: The storage command centre: what takes room on the Drive, by kind and by folder (tap to drill down), the largest files,4// how it grew, and duplicates (identical content, or similar images). Nothing here deletes anything by itself: every5// removal is a file the user chose, sent to the Drive's trash after a confirmation.6//7// Author: Simon-Pierre Boucher8// Contact: contact@spboucher.ai9import Charts10import SPDriveNext11import SwiftUI1213struct StorageCenter: View {14 @Environment(AppModel.self) private var model15 @State private var state: Loadable<StorageOverview> = .loading16 @State private var selectedKind: String?17 @State private var actions = ItemActions()1819 static func kindLabel(_ k: String) -> String { CollectionRuleText.kindLabels[k].map { String(localized: String.LocalizationValue($0)) } ?? (k == "other" || k == "none" ? String(localized: "Autres") : k) }20 static func kindColor(_ k: String) -> Color {21 switch k { case "image": .pink; case "pdf": .red; case "document": .blue; case "sheet": .green; case "video": .purple; case "audio": .teal; case "archive": .brown; case "text": .gray; default: .secondary }22 }2324 var body: some View {25 LoadingView(state: state, retry: load) { o in26 List {27 Section {28 VStack(alignment: .leading, spacing: SPDTheme.Space.md) {29 HStack(alignment: .firstTextBaseline) {30 Text(o.quota.used.byteString).font(SPDTheme.Typo.display)31 Text("sur \(o.quota.limit.byteString)").font(SPDTheme.Typo.callout.weight(.medium)).foregroundStyle(.secondary)32 }33 .accessibilityElement(children: .combine).accessibilityIdentifier("storage.used")34 // one bar, one segment per kind: tapping a segment (or its legend) selects the kind35 Chart(o.byKind) { k in36 BarMark(x: .value("Octets", k.bytes), y: .value("", "Drive"))37 .foregroundStyle(Self.kindColor(k.kind).opacity(selectedKind == nil || selectedKind == k.kind ? 1 : 0.25))38 .accessibilityLabel(Text(Self.kindLabel(k.kind))).accessibilityValue(Text(k.bytes.byteString))39 }40 .chartXAxis(.hidden).chartYAxis(.hidden).chartLegend(.hidden)41 .frame(height: 26).clipShape(Capsule())42 ForEach(o.byKind.sorted { $0.bytes > $1.bytes }) { k in43 Button { withAnimation(SPDTheme.Motion.hover) { selectedKind = selectedKind == k.kind ? nil : k.kind }; Haptics.selection() } label: {44 HStack {45 Circle().fill(Self.kindColor(k.kind)).frame(width: 10, height: 10)46 Text(Self.kindLabel(k.kind)).foregroundStyle(.primary)47 Spacer()48 Text(k.files == 1 ? String(localized: "1 fichier") : String(localized: "\(k.files) fichiers")).font(.caption).foregroundStyle(.secondary)49 Text(k.bytes.byteString).font(.subheadline.monospacedDigit()).frame(minWidth: 72, alignment: .trailing)50 }51 .padding(.vertical, 2).contentShape(Rectangle())52 .opacity(selectedKind == nil || selectedKind == k.kind ? 1 : 0.45)53 }54 .buttonStyle(.plain)55 .accessibilityAddTraits(selectedKind == k.kind ? .isSelected : [])56 .accessibilityIdentifier("storage.kind.\(k.kind)")57 }58 }59 .padding(.vertical, 4)60 } footer: {61 Text("Fichiers actuels : \(o.liveBytes.byteString) · corbeille : \(o.trashBytes.byteString) · anciennes versions : \(o.oldVersionBytes.byteString). \(o.counts.files) fichiers, \(o.counts.folders) dossiers, \(o.counts.versions) versions.")62 }6364 Section("Par dossier") {65 if o.byFolder.isEmpty { Text("Aucun dossier.").foregroundStyle(.secondary) }66 ForEach(o.byFolder.sorted { $0.bytes > $1.bytes }) { f in67 if f.direct == true { folderRow(String(localized: "Fichiers à la racine"), f.files, f.bytes, of: o.liveBytes) }68 else { NavigationLink { StorageFolderScreen(folderID: f.folder.id, total: o.liveBytes) } label: { folderRow(f.folder.displayName, f.files, f.bytes, of: o.liveBytes) }.accessibilityIdentifier("storage.folder.\(f.folder.name)") }69 }70 }7172 if !o.growth.isEmpty {73 Section {74 Chart(o.growth) { d in BarMark(x: .value("Jour", Self.day(d.date), unit: .day), y: .value("Octets", d.bytes)).foregroundStyle(SPDTheme.Palette.brand) }75 .chartYAxis { AxisMarks { v in AxisGridLine(); AxisValueLabel { if let b = v.as(Int64.self) { Text(b.byteString) } } } }76 .frame(height: 150)77 .accessibilityLabel(Text("Octets ajoutés par jour sur 90 jours"))78 } header: { Text("Croissance (90 jours)") } footer: {79 Text("Ajouté sur la période : \(o.growth.reduce(Int64(0)) { $0 + $1.bytes }.byteString) en \(o.growth.reduce(0) { $0 + $1.versions }) versions.")80 }81 }8283 Section("Fichiers les plus volumineux") {84 let largest = o.largest.filter { f in selectedKind.map { (f.kind ?? "other") == $0 } ?? true }85 if largest.isEmpty { Text("Aucun fichier de ce type parmi les plus volumineux.").foregroundStyle(.secondary) }86 NextFileList(files: Array(largest.prefix(15)), actions: actions)87 }8889 Section {90 NavigationLink { DuplicatesScreen(similarAvailable: model.next.has(.similarImages)) } label: {91 LabeledContent { Text(o.duplicates.groups == 0 ? String(localized: "Aucun") : "\(o.duplicates.groups)").monospacedDigit() } label: { Label("Doublons", systemImage: "doc.on.doc") }92 }93 .accessibilityIdentifier("storage.duplicates")94 } footer: {95 Text(o.duplicates.groups == 0 ? String(localized: "Aucun contenu en double.")96 : String(localized: "\(o.duplicates.groups) contenu(s) présent(s) sous plusieurs noms (\((o.duplicates.duplicateBytes ?? 0).byteString) de copies). Un contenu identique n’est stocké qu’une fois : retirer un doublon range ton Drive, cela ne libère pas d’espace."))97 }98 }99 .listStyle(.insetGrouped)100 }101 .navigationTitle("Stockage")102 .refreshable { await load() }103 .task { await load() }104 .itemActions(actions)105 }106107 private func folderRow(_ name: String, _ files: Int, _ bytes: Int64, of total: Int64) -> some View {108 VStack(alignment: .leading, spacing: 4) {109 HStack { Label(name, systemImage: "folder.fill").lineLimit(1); Spacer(); Text(bytes.byteString).font(.subheadline.monospacedDigit()) }110 ProgressView(value: total > 0 ? min(1, Double(bytes) / Double(total)) : 0).tint(SPDTheme.Palette.brand)111 Text(files == 1 ? String(localized: "1 fichier") : String(localized: "\(files) fichiers")).font(.caption).foregroundStyle(.secondary)112 }113 .accessibilityElement(children: .combine)114 }115116 static func day(_ s: String) -> Date { (try? Date(s, strategy: .iso8601.year().month().day())) ?? .now }117118 private func load() async {119 do {120 let o = try await model.next.client.storageOverview()121 if o.largest.contains(where: { model.store.item($0.id) == nil }) { await model.engine.sync() }122 state = .loaded(o)123 } catch { if state.value == nil { state = .failed(NextCenter.describe(error)) } }124 }125}126127/// One folder of the Drive, by weight: its sub-folders (drill down) and its own files.128struct StorageFolderScreen: View {129 @Environment(AppModel.self) private var model130 let folderID: String131 let total: Int64132 @State private var state: Loadable<StorageFolder> = .loading133 @State private var actions = ItemActions()134135 var body: some View {136 LoadingView(state: state, retry: load) { f in137 List {138 Section {139 LabeledContent("Total") { Text("\(f.total.bytes.byteString) · \(f.total.files) fichiers") }140 LabeledContent("Directement dans ce dossier") { Text("\(f.direct.bytes.byteString) · \(f.direct.files) fichiers") }141 } header: { Text(f.breadcrumbs.map(\.name).filter { !$0.isEmpty }.joined(separator: " › ")) }142 if !f.children.isEmpty {143 Section("Sous-dossiers") {144 ForEach(f.children.sorted { $0.bytes > $1.bytes }) { c in145 NavigationLink { StorageFolderScreen(folderID: c.folder.id, total: f.total.bytes) } label: {146 VStack(alignment: .leading, spacing: 4) {147 HStack { Label(c.folder.displayName, systemImage: "folder.fill"); Spacer(); Text(c.bytes.byteString).font(.subheadline.monospacedDigit()) }148 ProgressView(value: f.total.bytes > 0 ? min(1, Double(c.bytes) / Double(f.total.bytes)) : 0).tint(SPDTheme.Palette.brand)149 }150 }151 }152 }153 }154 if !f.files.isEmpty { Section("Fichiers de ce dossier, du plus lourd au plus léger") { NextFileList(files: f.files.sorted { $0.size > $1.size }, actions: actions) } }155 }156 }157 .navigationTitle(state.value?.folder.displayName.isEmpty == false ? state.value!.folder.displayName : String(localized: "Mon Drive"))158 .navigationBarTitleDisplayMode(.inline)159 .task { await load() }160 .itemActions(actions)161 }162 private func load() async { do { state = .loaded(try await model.next.client.storageFolder(folderID)) } catch { state = .failed(NextCenter.describe(error)) } }163}164165struct DuplicatesScreen: View {166 @Environment(AppModel.self) private var model167 let similarAvailable: Bool168 @State private var mode = DuplicateMode.exact169 @State private var state: Loadable<[DuplicateGroup]> = .loading170 @State private var trashing: NextFile?171172 var body: some View {173 VStack(spacing: 0) {174 if similarAvailable {175 Picker("Mode", selection: $mode) { Text("Contenu identique").tag(DuplicateMode.exact); Text("Images similaires").tag(DuplicateMode.similarImages) }176 .pickerStyle(.segmented).padding(.horizontal).padding(.vertical, 8).accessibilityIdentifier("duplicates.mode")177 }178 LoadingView(state: state, retry: load) { groups in179 if groups.isEmpty {180 EmptyState(symbol: "checkmark.circle", title: mode == .exact ? String(localized: "Aucun doublon") : String(localized: "Aucune image similaire"), message: String(localized: "Rien à ranger de ce côté."))181 } else {182 List {183 ForEach(groups) { g in184 Section {185 ForEach(g.files) { f in186 HStack(spacing: SPDTheme.Space.md) {187 if let item = model.store.item(f.id) { ItemThumbnail(item: item, size: 44) } else { KindIcon(kind: f.fileKind, size: 44) }188 VStack(alignment: .leading, spacing: 2) {189 Text(f.name).lineLimit(2)190 Text("\(Self.location(f, model: model)) · \(f.size.byteString)").font(.caption).foregroundStyle(.secondary).lineLimit(1)191 }192 Spacer(minLength: 4)193 Button(role: .destructive) { trashing = f } label: { Image(systemName: "trash") }.buttonStyle(.borderless).accessibilityLabel(Text("Mettre \(f.name) à la corbeille")).accessibilityIdentifier("duplicate.trash.\(f.name)")194 }195 }196 } header: {197 Text(mode == .exact ? (g.distinctNames == true ? String(localized: "Même contenu, noms différents") : String(localized: "Même contenu")) : String(localized: "Images proches"))198 }199 }200 Section { } footer: { Text("Rien n’est supprimé automatiquement. Chaque fichier que tu retires va dans la corbeille du Drive, d’où il peut être restauré.") }201 }202 }203 }204 }205 .navigationTitle("Doublons")206 .navigationBarTitleDisplayMode(.inline)207 .task(id: mode) { state = .loading; await load() }208 .confirmationDialog("Mettre ce fichier à la corbeille ?", isPresented: Binding(get: { trashing != nil }, set: { if !$0 { trashing = nil } }), titleVisibility: .visible, presenting: trashing) { f in209 Button("Mettre « \(f.name) » à la corbeille", role: .destructive) {210 Task { await model.perform(success: String(localized: "Déplacé dans la corbeille")) { try await model.engine.trash([f.id]) }; try? await Task.sleep(for: .seconds(1)); await load() }211 }.accessibilityIdentifier("duplicate.confirm")212 Button("Annuler", role: .cancel) {}213 } message: { _ in Text("Les autres exemplaires ne sont pas touchés. Le fichier reste restaurable depuis la corbeille.") }214 }215 static func location(_ f: NextFile, model: AppModel) -> String {216 guard let folder = f.folderId.flatMap(model.store.item) else { return String(localized: "Mon Drive") }217 return folder.parentID == nil ? String(localized: "Mon Drive") : folder.name218 }219 private func load() async {220 do {221 let d = try await model.next.client.duplicates(mode)222 if d.groups.flatMap(\.files).contains(where: { model.store.item($0.id) == nil }) { await model.engine.sync() }223 state = .loaded(d.groups)224 } catch { state = .failed(NextCenter.describe(error)) }225 }226}227