Repository Public
1// SP Drive iOS2// File: WidgetExtension/SPDriveWidgets.swift3// Description: Home-screen and lock-screen widgets: recent files, favourite folders, storage, transfer status, quick upload. They render4// the snapshot the app writes into the group container — no network, no keychain, no database — and open the app through5// `spdrive://` links.6//7// Author: Simon-Pierre Boucher8// Contact: contact@spboucher.ai9import SwiftUI10import WidgetKit1112// MARK: Timeline1314struct SnapshotEntry: TimelineEntry {15 let date: Date16 let snapshot: WidgetSnapshot17 let directory: URL?18}1920struct SnapshotProvider: TimelineProvider {21 static let sample = WidgetSnapshot(signedIn: true, recent: [22 .init(id: "1", name: "Rapport annuel.pdf", symbol: "doc.richtext.fill", size: 2_400_000, modifiedAt: .now.addingTimeInterval(-900), thumbnail: nil),23 .init(id: "2", name: "Budget 2027.xlsx", symbol: "tablecells.fill", size: 180_000, modifiedAt: .now.addingTimeInterval(-7200), thumbnail: nil),24 .init(id: "3", name: "Photo de chantier.jpg", symbol: "photo.fill", size: 3_100_000, modifiedAt: .now.addingTimeInterval(-86_400), thumbnail: nil),25 .init(id: "4", name: "Notes de réunion.md", symbol: "text.alignleft", size: 4_000, modifiedAt: .now.addingTimeInterval(-172_800), thumbnail: nil),26 ], favoriteFolders: [.init(id: "a", name: "Projets", itemCount: 12), .init(id: "b", name: "Factures", itemCount: 48), .init(id: "c", name: "Photos", itemCount: 230), .init(id: "d", name: "Cours", itemCount: 9)],27 storage: .init(used: 42_000_000_000, limit: 100_000_000_000, offlineBytes: 1_200_000_000),28 transfers: .init(uploads: 2, downloads: 1, failed: 0, doneBytes: 46_000_000, totalBytes: 120_000_000, hold: nil))2930 func placeholder(in context: Context) -> SnapshotEntry { SnapshotEntry(date: .now, snapshot: Self.sample, directory: nil) }31 func getSnapshot(in context: Context, completion: @escaping (SnapshotEntry) -> Void) { completion(context.isPreview ? placeholder(in: context) : current()) }32 func getTimeline(in context: Context, completion: @escaping (Timeline<SnapshotEntry>) -> Void) {33 // the app reloads the timelines when its data changes; this refresh only keeps relative dates honest34 completion(Timeline(entries: [current()], policy: .after(.now.addingTimeInterval(30 * 60))))35 }36 private func current() -> SnapshotEntry {37 let dir = WidgetSnapshot.directory()38 return SnapshotEntry(date: .now, snapshot: WidgetSnapshot.read(from: dir) ?? .signedOut, directory: dir)39 }40}4142// MARK: Shared pieces4344private let brand = LinearGradient(colors: [Color("GradA"), Color("GradB")], startPoint: .topLeading, endPoint: .bottomTrailing)4546private extension Int64 { var bytes: String { formatted(.byteCount(style: .file)) } }4748private struct Header: View {49 let title: LocalizedStringKey50 let symbol: String51 var body: some View {52 HStack(spacing: 6) {53 Image(systemName: symbol).font(.caption.weight(.bold)).foregroundStyle(brand)54 Text(title).font(.caption.weight(.semibold)).foregroundStyle(.secondary).lineLimit(1)55 Spacer(minLength: 0)56 }57 }58}5960/// Shown instead of content when there is none to show: signed out, or names hidden by the app lock.61private struct Unavailable: View {62 let snapshot: WidgetSnapshot63 var body: some View {64 VStack(spacing: 6) {65 Image(systemName: snapshot.signedIn ? "lock.fill" : "person.crop.circle.badge.exclamationmark").font(.title3).foregroundStyle(brand)66 Text(snapshot.signedIn ? "Verrouillé : ouvre SP Drive" : "Ouvre SP Drive pour te connecter").font(.caption).multilineTextAlignment(.center).foregroundStyle(.secondary)67 }68 .frame(maxWidth: .infinity, maxHeight: .infinity)69 }70}7172private struct FileRow: View {73 let file: WidgetSnapshot.File74 let directory: URL?75 var body: some View {76 Link(destination: SPDriveLink.file(file.id)) {77 HStack(spacing: 8) {78 thumb.frame(width: 28, height: 28).clipShape(RoundedRectangle(cornerRadius: 6, style: .continuous))79 VStack(alignment: .leading, spacing: 0) {80 Text(file.name).font(.caption.weight(.medium)).lineLimit(1).truncationMode(.middle)81 Text("\(file.size.bytes) · \(file.modifiedAt, style: .relative)").font(.caption2).foregroundStyle(.secondary).lineLimit(1)82 }83 Spacer(minLength: 0)84 }85 }86 .accessibilityElement(children: .combine)87 }88 @ViewBuilder private var thumb: some View {89 if let name = file.thumbnail, let directory, let image = UIImage(contentsOfFile: directory.appendingPathComponent("thumbs").appendingPathComponent(name).path) {90 Image(uiImage: image).resizable().scaledToFill()91 } else {92 ZStack { Color("AccentColor").opacity(0.14); Image(systemName: file.symbol).font(.caption.weight(.semibold)).foregroundStyle(Color("AccentColor")) }93 }94 }95}9697// MARK: Recent files9899struct RecentFilesWidget: Widget {100 var body: some WidgetConfiguration {101 StaticConfiguration(kind: "ai.spboucher.spdrive.recent", provider: SnapshotProvider()) { entry in102 RecentFilesView(entry: entry).containerBackground(.fill.tertiary, for: .widget).widgetURL(SPDriveLink.recent)103 }104 .configurationDisplayName("Fichiers récents")105 .description("Les derniers fichiers ajoutés ou modifiés dans ton Drive.")106 .supportedFamilies([.systemSmall, .systemMedium, .systemLarge])107 }108}109110private struct RecentFilesView: View {111 @Environment(\.widgetFamily) private var family112 let entry: SnapshotEntry113 var body: some View {114 let count = family == .systemLarge ? 7 : family == .systemMedium ? 3 : 2115 VStack(alignment: .leading, spacing: family == .systemSmall ? 6 : 8) {116 Header(title: "Récents", symbol: "clock.fill")117 if entry.snapshot.recent.isEmpty {118 if !entry.snapshot.signedIn || entry.snapshot.redacted { Unavailable(snapshot: entry.snapshot) }119 else { Text("Aucun fichier pour l’instant.").font(.caption).foregroundStyle(.secondary).frame(maxHeight: .infinity, alignment: .top) }120 } else {121 ForEach(entry.snapshot.recent.prefix(count)) { FileRow(file: $0, directory: entry.directory) }122 Spacer(minLength: 0)123 }124 }125 }126}127128// MARK: Favourite folders129130struct FavoriteFoldersWidget: Widget {131 var body: some WidgetConfiguration {132 StaticConfiguration(kind: "ai.spboucher.spdrive.folders", provider: SnapshotProvider()) { entry in133 FavoriteFoldersView(entry: entry).containerBackground(.fill.tertiary, for: .widget)134 }135 .configurationDisplayName("Dossiers favoris")136 .description("Tes dossiers favoris, à un toucher.")137 .supportedFamilies([.systemSmall, .systemMedium])138 }139}140141private struct FavoriteFoldersView: View {142 @Environment(\.widgetFamily) private var family143 let entry: SnapshotEntry144 var body: some View {145 let folders = entry.snapshot.favoriteFolders.prefix(family == .systemMedium ? 4 : 2)146 VStack(alignment: .leading, spacing: 8) {147 Header(title: "Favoris", symbol: "star.fill")148 if folders.isEmpty {149 if !entry.snapshot.signedIn || entry.snapshot.redacted { Unavailable(snapshot: entry.snapshot) }150 else { Text("Ajoute un dossier aux favoris dans SP Drive.").font(.caption).foregroundStyle(.secondary).frame(maxHeight: .infinity, alignment: .top) }151 } else {152 LazyVGrid(columns: Array(repeating: GridItem(.flexible(), spacing: 8), count: family == .systemMedium ? 2 : 1), spacing: 8) {153 ForEach(Array(folders)) { f in154 Link(destination: SPDriveLink.folder(f.id)) {155 HStack(spacing: 8) {156 Image(systemName: "folder.fill").foregroundStyle(brand)157 VStack(alignment: .leading, spacing: 0) {158 Text(f.name).font(.caption.weight(.semibold)).lineLimit(1)159 Text(f.itemCount == 1 ? "1 élément" : "\(f.itemCount) éléments").font(.caption2).foregroundStyle(.secondary)160 }161 Spacer(minLength: 0)162 }163 .padding(8)164 .background(.background.opacity(0.6), in: RoundedRectangle(cornerRadius: 10, style: .continuous))165 }166 .accessibilityElement(children: .combine)167 }168 }169 Spacer(minLength: 0)170 }171 }172 }173}174175// MARK: Storage176177struct StorageWidget: Widget {178 var body: some WidgetConfiguration {179 StaticConfiguration(kind: "ai.spboucher.spdrive.storage", provider: SnapshotProvider()) { entry in180 StorageView(entry: entry).containerBackground(.fill.tertiary, for: .widget).widgetURL(SPDriveLink.storage)181 }182 .configurationDisplayName("Stockage")183 .description("L’espace utilisé sur ton Drive et sur cet appareil.")184 .supportedFamilies([.systemSmall, .accessoryCircular, .accessoryRectangular])185 }186}187188private struct StorageView: View {189 @Environment(\.widgetFamily) private var family190 let entry: SnapshotEntry191 var body: some View {192 if let s = entry.snapshot.storage {193 switch family {194 case .accessoryCircular:195 Gauge(value: s.fraction) { Image(systemName: "externaldrive.fill") } currentValueLabel: { Text("\(Int(s.fraction * 100))") }196 .gaugeStyle(.accessoryCircularCapacity)197 .accessibilityLabel(Text("Stockage SP Drive")).accessibilityValue(Text("\(Int(s.fraction * 100)) %"))198 case .accessoryRectangular:199 VStack(alignment: .leading, spacing: 2) {200 Text("SP Drive").font(.headline)201 Gauge(value: s.fraction) { EmptyView() }.gaugeStyle(.accessoryLinearCapacity)202 Text("\(s.used.bytes) sur \(s.limit.bytes)").font(.caption2)203 }204 default:205 VStack(alignment: .leading, spacing: 6) {206 Header(title: "Stockage", symbol: "externaldrive.fill")207 Spacer(minLength: 0)208 Text("\(Int(s.fraction * 100)) %").font(.system(.title, design: .rounded).weight(.bold)).foregroundStyle(brand)209 ProgressView(value: s.fraction).tint(Color("AccentColor"))210 Text("\(s.used.bytes) sur \(s.limit.bytes)").font(.caption2).foregroundStyle(.secondary).lineLimit(1).minimumScaleFactor(0.8)211 Text("Hors ligne : \(s.offlineBytes.bytes)").font(.caption2).foregroundStyle(.secondary).lineLimit(1).minimumScaleFactor(0.8)212 }213 .accessibilityElement(children: .combine)214 }215 } else if family == .systemSmall {216 Unavailable(snapshot: entry.snapshot)217 } else {218 Image(systemName: "externaldrive.badge.questionmark").accessibilityLabel(Text("Stockage indisponible"))219 }220 }221}222223// MARK: Transfers224225struct TransfersWidget: Widget {226 var body: some WidgetConfiguration {227 StaticConfiguration(kind: "ai.spboucher.spdrive.transfers", provider: SnapshotProvider()) { entry in228 TransfersView(entry: entry).containerBackground(.fill.tertiary, for: .widget).widgetURL(SPDriveLink.transfers)229 }230 .configurationDisplayName("Transferts")231 .description("Ce qui est en cours d’envoi ou de téléchargement, tel que l’app l’a vu en dernier.")232 .supportedFamilies([.systemSmall, .accessoryRectangular])233 }234}235236private struct TransfersView: View {237 @Environment(\.widgetFamily) private var family238 let entry: SnapshotEntry239240 private var holdText: LocalizedStringKey? {241 switch entry.snapshot.transfers.hold {242 case "offline": "Hors ligne"243 case "waitingForWiFi": "En attente du Wi-Fi"244 case "lowDataMode": "Données réduites"245 case "lowPowerMode": "Économie d’énergie"246 case "lowBattery": "Batterie faible"247 default: nil248 }249 }250 private var line: LocalizedStringKey {251 let t = entry.snapshot.transfers252 if t.active == 0 { return t.failed > 0 ? "\(t.failed) interrompu(s)" : "Tout est à jour" }253 return "\(t.uploads) envoi(s) · \(t.downloads) téléch."254 }255256 var body: some View {257 let t = entry.snapshot.transfers258 if family == .accessoryRectangular {259 VStack(alignment: .leading, spacing: 2) {260 Label("SP Drive", systemImage: "arrow.up.arrow.down").font(.headline)261 Text(line).font(.caption)262 if let holdText { Text(holdText).font(.caption2) } else if t.active > 0 { ProgressView(value: t.fraction) }263 }264 } else if !entry.snapshot.signedIn {265 Unavailable(snapshot: entry.snapshot)266 } else {267 VStack(alignment: .leading, spacing: 6) {268 Header(title: "Transferts", symbol: "arrow.up.arrow.down.circle.fill")269 Spacer(minLength: 0)270 if t.active > 0 {271 Text("\(Int(t.fraction * 100)) %").font(.system(.title, design: .rounded).weight(.bold)).foregroundStyle(brand)272 ProgressView(value: t.fraction).tint(Color("AccentColor"))273 } else {274 Image(systemName: t.failed > 0 ? "exclamationmark.circle.fill" : "checkmark.circle.fill").font(.title).foregroundStyle(t.failed > 0 ? Color("Danger") : Color("Success"))275 }276 Text(line).font(.caption.weight(.medium)).lineLimit(2)277 if let holdText { Label(holdText, systemImage: "pause.circle").font(.caption2).foregroundStyle(Color("Warning")) }278 else { Text(entry.snapshot.generatedAt, style: .relative).font(.caption2).foregroundStyle(.secondary) }279 if entry.snapshot.conflicts > 0 { Label("\(entry.snapshot.conflicts) conflit(s)", systemImage: "exclamationmark.triangle.fill").font(.caption2).foregroundStyle(Color("Warning")) }280 }281 .accessibilityElement(children: .combine)282 }283 }284}285286// MARK: Quick upload287288struct QuickUploadWidget: Widget {289 var body: some WidgetConfiguration {290 StaticConfiguration(kind: "ai.spboucher.spdrive.upload", provider: SnapshotProvider()) { entry in291 QuickUploadView(entry: entry).containerBackground(for: .widget) { brand }292 }293 .configurationDisplayName("Envoi rapide")294 .description("Ajoute un fichier ou numérise un document en un toucher.")295 .supportedFamilies([.systemSmall, .systemMedium, .accessoryCircular])296 }297}298299private struct QuickUploadView: View {300 @Environment(\.widgetFamily) private var family301 let entry: SnapshotEntry302 var body: some View {303 switch family {304 case .accessoryCircular:305 ZStack { AccessoryWidgetBackground(); Image(systemName: "arrow.up.doc.fill").font(.title2) }306 .widgetURL(SPDriveLink.upload).accessibilityLabel(Text("Envoyer un fichier vers SP Drive"))307 case .systemMedium:308 HStack(spacing: 12) {309 tile("Importer", "arrow.up.doc.fill", SPDriveLink.upload)310 tile("Numériser", "doc.viewfinder.fill", SPDriveLink.scan)311 tile("Rechercher", "magnifyingglass", SPDriveLink.search)312 }313 default:314 VStack(alignment: .leading, spacing: 6) {315 Image(systemName: "arrow.up.doc.fill").font(.largeTitle).foregroundStyle(.white)316 Spacer(minLength: 0)317 Text("Envoyer vers SP Drive").font(.headline).foregroundStyle(.white)318 Text("Fichier, photo ou numérisation").font(.caption2).foregroundStyle(.white.opacity(0.85))319 }320 .frame(maxWidth: .infinity, alignment: .leading)321 .widgetURL(SPDriveLink.upload)322 .accessibilityElement(children: .combine)323 }324 }325 private func tile(_ title: LocalizedStringKey, _ symbol: String, _ url: URL) -> some View {326 Link(destination: url) {327 VStack(spacing: 8) {328 Image(systemName: symbol).font(.title2)329 Text(title).font(.caption.weight(.semibold)).lineLimit(1).minimumScaleFactor(0.8)330 }331 .foregroundStyle(.white)332 .frame(maxWidth: .infinity, maxHeight: .infinity)333 .background(.white.opacity(0.18), in: RoundedRectangle(cornerRadius: 14, style: .continuous))334 }335 }336}337338@main339struct SPDriveWidgetBundle: WidgetBundle {340 var body: some Widget {341 RecentFilesWidget()342 FavoriteFoldersWidget()343 StorageWidget()344 TransfersWidget()345 QuickUploadWidget()346 }347}348