SPB Git

Repository Public

StorageScreen.swift 10.5 KB 209 lines swift

1// SP Drive iOS2// File: Features/Settings/StorageScreen.swift3// Description: Storage dashboard: space used on the Drive, space used on this device, pending transfers, and actions that only ever free local space.4//5// Author: Simon-Pierre Boucher6// Contact: contact@spboucher.ai7import SwiftUI89struct StorageScreen: View {10    @Environment(AppModel.self) private var model11    /// Sizes measured on disk (thumbnails; partial downloads and upload snapshots), computed off the main thread.12    @State private var thumbnailBytes: Int64?13    @State private var workingBytes: Int64?14    @State private var measureToken = 015    @State private var clearing = false1617    var body: some View {18        let _ = model.itemsVersion19        let _ = model.transfersVersion20        let usage = model.store.localUsage()21        let counts = model.store.itemCount()22        let waiting = model.store.transfers(states: [.queued, .running, .paused])23        let waitingBytes = waiting.reduce(Int64(0)) { $0 + max(0, $1.size - $1.done) }24        let device = DeviceWording.thisDevice2526        List {27            driveSection(counts: counts)2829            Section {30                LabeledContent {31                    Text(usage.offlineBytes.byteString).monospacedDigit()32                } label: {33                    Label("Gardés hors ligne", systemImage: "arrow.down.circle.fill")34                    Text("\(usage.offlineFiles) fichier\(usage.offlineFiles > 1 ? "s" : "")")35                }36                .accessibilityIdentifier("storage.offline")37                LabeledContent {38                    Text(usage.cacheBytes.byteString).monospacedDigit()39                } label: {40                    Label("Cache (copies récentes)", systemImage: "clock.arrow.circlepath")41                    Text("\(usage.cacheFiles) fichier\(usage.cacheFiles > 1 ? "s" : "")")42                }43                .accessibilityIdentifier("storage.cache")44                LabeledContent {45                    measured(thumbnailBytes)46                } label: {47                    Label("Vignettes", systemImage: "photo.on.rectangle")48                }49                LabeledContent {50                    measured(workingBytes)51                } label: {52                    Label("Transferts en cours de route", systemImage: "arrow.up.arrow.down")53                    Text("Téléchargements partiels et fichiers en attente d’envoi")54                }55            } header: {56                Text("Sur \(device)")57            } footer: {58                Text("Les fichiers gardés hors ligne ne sont jamais repris par iOS. Le cache et les vignettes peuvent l’être s’il manque d’espace.")59            }6061            Section("Transferts en attente") {62                NavigationLink(destination: TransfersScreen()) {63                    LabeledContent {64                        Text(waiting.isEmpty ? "Aucun" : "\(waiting.count) · \(waitingBytes.byteString) restants").monospacedDigit()65                    } label: {66                        Label("Téléchargements", systemImage: "arrow.up.arrow.down.circle")67                        Text("Envois et téléchargements")68                    }69                }70                .accessibilityIdentifier("storage.transfers")71            }7273            Section {74                Button {75                    clearing = true76                    Task {77                        let freed = await model.engine.clearCache()78                        clearing = false79                        measureToken += 180                        Haptics.success()81                        model.toast = Toast(text: freed > 0 ? "\(freed.byteString) libérés sur \(device)" : "Cache vidé (vignettes comprises)", style: .success)82                    }83                } label: {84                    HStack {85                        Label("Vider le cache", systemImage: "wind")86                        if clearing { Spacer(); ProgressView() }87                    }88                }89                .disabled(clearing)90                .accessibilityIdentifier("storage.clearCache")91                NavigationLink(destination: OfflineScreen()) { Label("Gérer les fichiers hors ligne", systemImage: "arrow.down.circle") }92                    .accessibilityIdentifier("storage.manageOffline")93                NavigationLink(destination: LargestFilesScreen()) { Label("Fichiers volumineux", systemImage: "chart.bar.doc.horizontal") }94                    .accessibilityIdentifier("storage.largest")95            } header: {96                Text("Libérer de l’espace sur \(device)")97            } footer: {98                Text("« Vider le cache » retire les copies récentes et les vignettes ; les fichiers gardés hors ligne et les modifications pas encore envoyées sont conservés. Tout ce qui se fait ici est « Retirer de \(device) » : rien n’est supprimé du Drive, et tout se retélécharge au besoin. « Supprimer du Drive », qui libère ton espace MacLustr, se fait depuis le fichier lui-même, puis dans la corbeille.")99            }100        }101        .listStyle(.insetGrouped)102        .navigationTitle("Stockage")103        .accessibilityIdentifier("storage.list")104        .refreshable { await model.refreshAccount(); measureToken += 1 }105        .task { await model.refreshAccount() }106        .task(id: measureToken) {107            let files = model.files108            let sizes = await Task.detached(priority: .utility) {109                (thumbs: LocalFiles.directorySize(files.thumbnails),110                 working: [files.partials, files.chunks, files.outbox, files.staging].reduce(Int64(0)) { $0 + LocalFiles.directorySize($1) })111            }.value112            guard !Task.isCancelled else { return }113            thumbnailBytes = sizes.thumbs114            workingBytes = sizes.working115        }116    }117118    @ViewBuilder119    private func measured(_ bytes: Int64?) -> some View {120        if let bytes { Text(bytes.byteString).monospacedDigit() } else { ProgressView() }121    }122123    @ViewBuilder124    private func driveSection(counts: (files: Int, folders: Int)) -> some View {125        Section {126            if let q = model.account?.quota, q.limit > 0 {127                let free = max(0, q.limit - q.used)128                let fraction = min(1, Double(q.used) / Double(q.limit))129                VStack(alignment: .leading, spacing: 8) {130                    HStack(alignment: .firstTextBaseline) {131                        Text(q.used.byteString).font(.title2.weight(.semibold)).monospacedDigit()132                        Text("utilisés sur \(q.limit.byteString)").font(.subheadline).foregroundStyle(.secondary)133                    }134                    ProgressView(value: fraction)135                        .tint(fraction >= 1 ? .red : fraction >= 0.9 ? .orange : Color("AccentColor"))136                        .accessibilityHidden(true)137                    Text(free > 0 ? "\(free.byteString) libres · \(Int((fraction * 100).rounded())) % utilisés" : "Ton Drive est plein : les nouveaux envois sont refusés.")138                        .font(.caption)139                        .foregroundStyle(free > 0 ? AnyShapeStyle(.secondary) : AnyShapeStyle(.red))140                }141                .padding(.vertical, 4)142                .accessibilityElement(children: .combine)143                .accessibilityIdentifier("storage.quota")144            } else {145                Label(model.network.online ? "Chargement de l’espace du Drive…" : "Espace du Drive indisponible hors ligne", systemImage: model.network.online ? "hourglass" : "wifi.slash")146                    .foregroundStyle(.secondary)147                    .accessibilityIdentifier("storage.quotaUnavailable")148            }149            LabeledContent("Fichiers", value: counts.files.formatted())150            LabeledContent("Dossiers", value: counts.folders.formatted())151        } header: {152            Text("Drive MacLustr")153        } footer: {154            Text("L’espace du Drive est calculé par le serveur. Les nombres de fichiers et de dossiers viennent de l’index de cet appareil (corbeille exclue).")155        }156    }157}158159/// The 30 largest files of the Drive (from the local index, so it works offline).160struct LargestFilesScreen: View {161    @Environment(AppModel.self) private var model162163    var body: some View {164        let _ = model.itemsVersion165        let files = model.store.largestFiles(limit: 30)166        Group {167            if files.isEmpty {168                EmptyState(symbol: "chart.bar.doc.horizontal", title: "Aucun fichier", message: "Ton Drive ne contient encore aucun fichier.")169            } else {170                List {171                    Section {172                        ForEach(files) { item in173                            Button {174                                NotificationCenter.default.post(name: .openDriveItem, object: item.id)175                            } label: {176                                HStack(spacing: 12) {177                                    KindIcon(kind: item.kind)178                                    VStack(alignment: .leading, spacing: 3) {179                                        Text(item.name).font(.body).lineLimit(2).foregroundStyle(.primary)180                                        Text(location(of: item)).font(.caption).foregroundStyle(.secondary).lineLimit(1)181                                    }182                                    Spacer(minLength: 8)183                                    Text(item.size.byteString).font(.subheadline.weight(.medium)).monospacedDigit().foregroundStyle(.secondary)184                                    SyncBadgeView(badge: model.badge(item))185                                }186                                .contentShape(Rectangle())187                            }188                            .buttonStyle(.plain)189                            .accessibilityElement(children: .combine)190                            .accessibilityHint("Ouvre le fichier")191                            .accessibilityIdentifier("storage.largest.\(item.id)")192                        }193                    } footer: {194                        Text("Tailles sur le Drive. Ouvre un fichier pour le « Supprimer du Drive » (il ira dans la corbeille) ; « Retirer de \(DeviceWording.thisDevice) » ne libère que l’espace local.")195                    }196                }197                .listStyle(.insetGrouped)198            }199        }200        .navigationTitle("Fichiers volumineux")201    }202203    /// Folder path of the item, without the root: "Projets › 2026".204    private func location(of item: DriveItem) -> String {205        let folders = model.store.path(to: item.id).dropLast().dropFirst().map(\.name)206        return folders.isEmpty ? "Mon Drive" : folders.joined(separator: " › ")207    }208}209
Files main
Menu

Theme