Repository Public
1// SP Drive iOS2// File: Features/Offline/OfflineScreen.swift3// Description: What this device holds: items explicitly kept offline and copies left by recent openings, with their size and a way to free them.4//5// Author: Simon-Pierre Boucher6// Contact: contact@spboucher.ai7import SwiftUI8import UIKit910extension Notification.Name {11 /// Asks the browser to open a file; `object` is the item identifier (String).12 static let openDriveItem = Notification.Name("ai.spboucher.spdrive.openItem")13}1415/// "cet iPhone" / "cet iPad": local-only actions always name the device, so they are never mistaken for a deletion on the Drive.16enum DeviceWording {17 @MainActor static var thisDevice: String { UIDevice.current.userInterfaceIdiom == .pad ? "cet iPad" : "cet iPhone" }18 @MainActor static var removeLocal: String { "Retirer de \(thisDevice)" }19}2021/// What the screen shows, computed off the main thread (walking the ancestors of every local copy can be long on a big Drive).22private struct OfflineSnapshot: Sendable, Equatable {23 struct Entry: Sendable, Equatable, Identifiable {24 let item: DriveItem25 let state: LocalState26 /// Pinned folders: files of the folder present on this device, and their bytes.27 var folderFiles = 028 var folderBytes: Int64 = 029 var id: String { item.id }30 }31 var pinned: [Entry] = []32 var recent: [Entry] = []33 var offlineFiles = 034 var offlineBytes: Int64 = 035 var cacheFiles = 036 var cacheBytes: Int64 = 03738 static func load(from store: DriveStore) -> OfflineSnapshot {39 var snap = OfflineSnapshot()40 let usage = store.localUsage()41 snap.offlineFiles = usage.offlineFiles; snap.offlineBytes = usage.offlineBytes42 snap.cacheFiles = usage.cacheFiles; snap.cacheBytes = usage.cacheBytes4344 let pinnedPairs = store.localItems(pinnedOnly: true).filter { !$0.0.isTrashed }45 let pinnedIDs = Set(pinnedPairs.map { $0.0.id })46 // nearest pinned ancestor of a folder, memoised: each folder of the tree is looked up once47 var ancestorCache: [String: String?] = [:]48 func pinnedAncestor(of folderID: String?) -> String? {49 var chain: [String] = []50 var current = folderID51 var found: String?52 var hops = 053 while let id = current, hops < 256 {54 if let known = ancestorCache[id] { found = known; break }55 if pinnedIDs.contains(id) { found = id; ancestorCache[id] = id; break }56 chain.append(id)57 current = store.item(id)?.parentID58 hops += 159 }60 for id in chain { ancestorCache[id] = found }61 return found62 }6364 var perFolder: [String: (files: Int, bytes: Int64)] = [:]65 for (item, state) in store.localItems(pinnedOnly: false) where !state.pinned && state.hasCopy && !item.isFolder {66 if let folder = pinnedAncestor(of: item.parentID) {67 // kept through its folder: counted with the folder, not listed one by one68 var agg = perFolder[folder] ?? (0, 0)69 agg.files += 1; agg.bytes += state.localSize70 perFolder[folder] = agg71 } else {72 snap.recent.append(Entry(item: item, state: state))73 }74 }75 snap.pinned = pinnedPairs.map { item, state in76 var e = Entry(item: item, state: state)77 if let agg = perFolder[item.id] { e.folderFiles = agg.files; e.folderBytes = agg.bytes }78 return e79 }80 snap.recent.sort { ($0.state.openedAt ?? $0.state.downloadedAt ?? .distantPast) > ($1.state.openedAt ?? $1.state.downloadedAt ?? .distantPast) }81 return snap82 }83}8485struct OfflineScreen: View {86 @Environment(AppModel.self) private var model87 @State private var snapshot: OfflineSnapshot?8889 var body: some View {90 let version = model.itemsVersion91 Group {92 if let snap = snapshot {93 if snap.pinned.isEmpty && snap.recent.isEmpty {94 EmptyState(symbol: "arrow.down.circle", title: "Rien hors ligne pour l’instant",95 message: "Pour garder un fichier ou un dossier sur \(DeviceWording.thisDevice), touche-le longuement dans ton Drive, puis choisis « Garder hors ligne ». Il restera lisible sans réseau et se mettra à jour tout seul.")96 .accessibilityIdentifier("offline.empty")97 } else {98 list(snap)99 }100 } else {101 ProgressView().frame(maxWidth: .infinity, maxHeight: .infinity)102 }103 }104 .navigationTitle("Hors ligne")105 .task(id: version) {106 let store = model.store107 let fresh = await Task.detached(priority: .userInitiated) { OfflineSnapshot.load(from: store) }.value108 if !Task.isCancelled, fresh != snapshot { snapshot = fresh }109 }110 }111112 private func list(_ snap: OfflineSnapshot) -> some View {113 List {114 Section {115 VStack(alignment: .leading, spacing: 4) {116 Label("\(snap.offlineFiles) fichier\(snap.offlineFiles > 1 ? "s" : "") · \(snap.offlineBytes.byteString) gardés hors ligne", systemImage: "arrow.down.circle.fill")117 .font(.subheadline.weight(.semibold))118 if snap.cacheFiles > 0 {119 Text("Plus \(snap.cacheFiles) copie\(snap.cacheFiles > 1 ? "s" : "") récente\(snap.cacheFiles > 1 ? "s" : "") (\(snap.cacheBytes.byteString)) qu’iOS peut reprendre s’il manque d’espace.")120 .font(.caption).foregroundStyle(.secondary)121 }122 }123 .accessibilityElement(children: .combine)124 .accessibilityIdentifier("offline.summary")125 }126 if !snap.pinned.isEmpty {127 Section {128 ForEach(snap.pinned) { row($0, pinned: true) }129 } header: {130 Text("Gardés hors ligne")131 } footer: {132 Text("Ces éléments restent sur \(DeviceWording.thisDevice) et suivent les changements du Drive. Un dossier garde aussi ce qu’on y ajoutera.")133 }134 }135 if !snap.recent.isEmpty {136 Section {137 ForEach(snap.recent) { row($0, pinned: false) }138 } header: {139 Text("Copies récentes sur cet appareil")140 } footer: {141 Text("Des fichiers que tu as ouverts ou ajoutés ici. Les retirer libère de l’espace sur \(DeviceWording.thisDevice) ; ils restent sur le Drive.")142 }143 }144 }145 .listStyle(.insetGrouped)146 .accessibilityIdentifier("offline.list")147 }148149 @ViewBuilder150 private func row(_ entry: OfflineSnapshot.Entry, pinned: Bool) -> some View {151 Group {152 if entry.item.isFolder {153 NavigationLink(value: FolderRoute(id: entry.item.id)) { OfflineRow(entry: entry, badge: model.badge(entry.item)) }154 } else {155 Button {156 NotificationCenter.default.post(name: .openDriveItem, object: entry.item.id)157 } label: {158 OfflineRow(entry: entry, badge: model.badge(entry.item))159 }160 .buttonStyle(.plain)161 .accessibilityHint("Ouvre le fichier")162 }163 }164 .swipeActions(edge: .trailing, allowsFullSwipe: false) {165 Button { remove(entry, pinned: pinned) } label: { Label(DeviceWording.removeLocal, systemImage: "iphone.slash") }.tint(.orange)166 }167 .contextMenu {168 Button { remove(entry, pinned: pinned) } label: { Label("\(DeviceWording.removeLocal) (reste sur le Drive)", systemImage: "iphone.slash") }169 }170 .accessibilityIdentifier("offline.row.\(entry.item.id)")171 }172173 /// Frees the local copy only. The file on the Drive is never touched, and edits not yet sent are never discarded.174 private func remove(_ entry: OfflineSnapshot.Entry, pinned: Bool) {175 let id = entry.item.id, name = entry.item.name176 Task {177 if pinned {178 await model.engine.unpin(id)179 let keptForEdits: Bool180 if entry.item.isFolder {181 let inside = Set(model.store.descendants(of: id, filesOnly: true).map(\.id))182 keptForEdits = model.store.allLocalStates().contains { $0.dirty && $0.hasCopy && inside.contains($0.itemID) }183 } else {184 keptForEdits = model.store.localState(id).map { $0.dirty && $0.hasCopy } ?? false185 }186 model.toast = keptForEdits187 ? Toast(text: "« \(name) » n’est plus gardé hors ligne. Les modifications pas encore envoyées restent ici jusqu’à leur envoi.", style: .info)188 : Toast(text: "Retiré de \(DeviceWording.thisDevice). « \(name) » reste sur le Drive.", style: .success)189 } else if await model.engine.removeLocalCopy(id) {190 model.toast = Toast(text: "Retiré de \(DeviceWording.thisDevice). « \(name) » reste sur le Drive.", style: .success)191 } else {192 Haptics.warning()193 model.toast = Toast(text: "« \(name) » contient des modifications pas encore envoyées. Elles doivent d’abord être envoyées au Drive.", style: .error)194 }195 }196 }197}198199private struct OfflineRow: View {200 let entry: OfflineSnapshot.Entry201 let badge: SyncBadge202203 var body: some View {204 HStack(spacing: 12) {205 KindIcon(kind: entry.item.kind)206 VStack(alignment: .leading, spacing: 3) {207 Text(entry.item.name).font(.body).lineLimit(2).foregroundStyle(.primary)208 Text(detail).font(.caption).foregroundStyle(.secondary)209 if entry.state.dirty {210 Label("Modifications en attente d’envoi", systemImage: "clock.arrow.2.circlepath")211 .font(.caption).foregroundStyle(.orange)212 }213 }214 Spacer(minLength: 8)215 SyncBadgeView(badge: badge)216 }217 .padding(.vertical, 2)218 .contentShape(Rectangle())219 .accessibilityElement(children: .combine)220 }221222 private var detail: String {223 if entry.item.isFolder {224 return entry.folderFiles == 0225 ? "Dossier · aucun fichier sur cet appareil pour l’instant"226 : "Dossier · \(entry.folderFiles) fichier\(entry.folderFiles > 1 ? "s" : "") · \(entry.folderBytes.byteString) sur cet appareil"227 }228 guard entry.state.hasCopy else { return "\(entry.item.size.byteString) · pas encore téléchargé" }229 var parts = ["\(entry.state.localSize.byteString) sur cet appareil"]230 if let at = entry.state.openedAt { parts.append("ouvert \(at.shortRelative)") }231 return parts.joined(separator: " · ")232 }233}234