Repository Public
1// SP Drive iOS2// File: Features/MyDrive/FolderScreen.swift3// Description: The file explorer: one folder of the Drive as a list or a grid, with sorting, filtering, multiple selection, swipe actions,4// context menus, drag and drop, and the « add » menu (folder, files, photos, camera, document scanner).5//6// Author: Simon-Pierre Boucher7// Contact: contact@spboucher.ai8import PhotosUI9import SwiftUI10import UniformTypeIdentifiers1112/// « Mon Drive »: the root folder, once the first synchronisation has told the device which folder that is.13struct DriveRootScreen: View {14 @Environment(AppModel.self) private var model15 var body: some View {16 if let root = model.rootID {17 FolderScreen(folderID: root)18 } else {19 VStack(spacing: 16) {20 if model.network.online { ProgressView("Première synchronisation…") }21 else { EmptyState(symbol: "wifi.slash", title: "Hors ligne", message: "La première synchronisation demande une connexion à Internet.", action: ("Réessayer", { Task { await model.refresh() } })) }22 }23 .navigationTitle("Mon Drive")24 .task { await model.refresh() }25 }26 }27}2829struct FolderScreen: View {30 @Environment(AppModel.self) private var model31 @Environment(\.horizontalSizeClass) private var sizeClass32 let folderID: String3334 /// Cards grow with the text size: fewer, wider columns instead of truncated names.35 @ScaledMetric(relativeTo: .footnote) private var cardWidthCompact: CGFloat = 10436 @ScaledMetric(relativeTo: .footnote) private var cardWidthRegular: CGFloat = 14837 @AppStorage("browser.grid") private var grid = false38 @AppStorage("browser.sort") private var sortRaw = DriveStore.Sort.name.rawValue39 @AppStorage("browser.ascending") private var ascending = true40 @State private var filter: FileKind?41 @State private var actions = ItemActions()42 @State private var selection: Set<String> = []43 @State private var editMode: EditMode = .inactive44 @State private var filterText = ""45 @State private var newFolder = false46 @State private var newFolderName = ""47 @State private var importingFiles = false48 @State private var pickingPhotos = false49 @State private var photoItems: [PhotosPickerItem] = []50 @State private var camera = false51 @State private var scanner = false52 @State private var scannedPages: ScannedPages?53 @State private var dropTargeted = false5455 private var sort: DriveStore.Sort { DriveStore.Sort(rawValue: sortRaw) ?? .name }56 private var folder: DriveItem? { _ = model.itemsVersion; return model.store.item(folderID) }57 private var isRoot: Bool { folder?.parentID == nil }5859 private var items: [DriveItem] {60 _ = model.itemsVersion61 var all = model.store.children(of: folderID, sort: sort, ascending: ascending)62 if let filter { all = all.filter { $0.isFolder || $0.kind == filter } }63 if !filterText.isEmpty {64 let key = DriveStore.searchKey(filterText)65 all = all.filter { DriveStore.searchKey($0.name).contains(key) }66 }67 return all68 }6970 var body: some View {71 let items = items72 Group {73 if folder == nil || folder?.isTrashed == true {74 EmptyState(symbol: "folder.badge.questionmark", title: "Dossier introuvable", message: "Ce dossier n’existe plus sur ton Drive ou se trouve dans la corbeille.")75 } else if items.isEmpty {76 emptyState77 } else if grid {78 gridView(items)79 } else {80 listView(items)81 }82 }83 .navigationTitle(isRoot ? String(localized: "Mon Drive") : (folder?.name ?? ""))84 .navigationBarTitleDisplayMode(isRoot ? .large : .inline)85 .searchable(text: $filterText, placement: .navigationBarDrawer(displayMode: .automatic), prompt: "Filtrer ce dossier")86 .refreshable { await model.refresh() }87 .toolbar { toolbar(items) }88 .environment(\.editMode, $editMode)89 .itemActions(actions)90 .overlay { if dropTargeted { RoundedRectangle(cornerRadius: 20).strokeBorder(Theme.gradient, style: StrokeStyle(lineWidth: 3, dash: [10, 6])).padding(8).allowsHitTesting(false) } }91 .dropDestination(for: URL.self) { urls, _ in importURLs(urls, into: folderID); return !urls.isEmpty } isTargeted: { dropTargeted = $0 }92 .alert("Nouveau dossier", isPresented: $newFolder) {93 TextField("Nom du dossier", text: $newFolderName)94 Button("Annuler", role: .cancel) {}95 Button("Créer") { createFolder() }96 }97 .fileImporter(isPresented: $importingFiles, allowedContentTypes: [.item], allowsMultipleSelection: true) { result in98 if case .success(let urls) = result { importURLs(urls, into: folderID) }99 }100 .photosPicker(isPresented: $pickingPhotos, selection: $photoItems, maxSelectionCount: 50, matching: .any(of: [.images, .videos]), preferredItemEncoding: .current)101 .onChange(of: photoItems) { _, picked in102 guard !picked.isEmpty else { return }103 photoItems = []104 Task { await importPhotos(picked) }105 }106 .fullScreenCover(isPresented: $camera) { CameraPicker { url in importOwned([url]) }.ignoresSafeArea() }107 .fullScreenCover(isPresented: $scanner) { DocumentScanner { pages in scannedPages = ScannedPages(images: pages) }.ignoresSafeArea() }108 .sheet(item: $scannedPages) { pages in ScanReviewSheet(pages: pages, folderID: folderID) }109 .onReceive(NotificationCenter.default.publisher(for: .driveCommand)) { note in110 switch note.object as? DriveCommand {111 case .newFolder: newFolderName = ""; newFolder = true112 case .importFiles: importingFiles = true113 case .list: grid = false114 case .grid: grid = true115 case .scan: startScan()116 case .select: editMode = editMode == .active ? .inactive : .active117 case .selectAll: editMode = .active; selection = Set(items.map(\.id))118 case .trashSelection: let chosen = items.filter { selection.contains($0.id) }; if !chosen.isEmpty { actions.confirmingTrash = chosen }119 case .inspector:120 if actions.inspectorShown { actions.inspectorShown = false }121 else if let target = items.first(where: { selection.contains($0.id) }) ?? folder { actions.details(target) }122 default: break123 }124 }125 .onChange(of: editMode) { _, mode in if mode == .inactive { selection = [] } }126 .accessibilityIdentifier("folder.\(isRoot ? "root" : folder?.name ?? "")")127 }128129 // MARK: Layouts130131 private func listView(_ items: [DriveItem]) -> some View {132 List(selection: $selection) {133 ForEach(items) { item in134 row(item)135 .swipeActions(edge: .trailing, allowsFullSwipe: false) {136 Button(role: .destructive) { actions.confirmingTrash = [item] } label: { Label("Supprimer", systemImage: "trash") }137 Button { actions.sheet = .move([item]) } label: { Label("Déplacer", systemImage: "folder") }.tint(.indigo)138 }139 .swipeActions(edge: .leading, allowsFullSwipe: true) {140 Button { actions.toggleStar([item], model: model) } label: { Label(item.starred ? "Retirer" : "Favori", systemImage: item.starred ? "star.slash" : "star.fill") }.tint(.yellow)141 if !item.isLocalOnly {142 let pinned = model.store.localState(item.id)?.pinned == true143 Button { actions.setOffline(item, !pinned, model: model) } label: { Label(pinned ? "En ligne" : "Hors ligne", systemImage: pinned ? "icloud" : "arrow.down.circle.fill") }.tint(.green)144 }145 }146 .tag(item.id)147 }148 Section { } footer: { footer(items) }149 }150 .listStyle(.plain)151 }152153 @ViewBuilder154 private func row(_ item: DriveItem) -> some View {155 Group {156 if item.isFolder {157 NavigationLink(value: FolderRoute(id: item.id)) { ItemRowView(item: item, onMore: more(item)) }158 .dropDestination(for: DraggedItem.self) { dragged, _ in moveDragged(dragged, into: item) } // drop on a folder row = move into it159 } else {160 Button { if editMode == .inactive { actions.open(item, model: model) } } label: { ItemRowView(item: item, onMore: more(item)) }.buttonStyle(.plain)161 }162 }163 .contextMenu { ItemMenu(item: item, actions: actions) }164 .accessibilityActions {165 Button("Plus d’actions") { actions.sheet = .actions(item) }166 Button(item.starred ? "Retirer des favoris" : "Ajouter aux favoris") { actions.toggleStar([item], model: model) }167 Button("Informations et versions") { actions.details(item) }168 }169 .draggable(DraggedItem(id: item.id, name: item.name, isFolder: item.isFolder)) {170 // the drag preview is rendered outside the view tree: it needs the model handed to it171 ItemRowView(item: item).padding(8).frame(width: 280).background(.background, in: RoundedRectangle(cornerRadius: 12)).environment(model)172 }173 }174175 private func gridView(_ items: [DriveItem]) -> some View {176 ScrollView {177 LazyVGrid(columns: [GridItem(.adaptive(minimum: min(sizeClass == .regular ? cardWidthRegular : cardWidthCompact, 320)), spacing: 12, alignment: .top)], spacing: 12) {178 ForEach(items) { item in179 let selected = selection.contains(item.id)180 Group {181 if editMode == .active {182 Button { Haptics.selection(); if selected { selection.remove(item.id) } else { selection.insert(item.id) } } label: { ItemGridCell(item: item, selected: selected, selecting: true) }.buttonStyle(.plain)183 } else if item.isFolder {184 NavigationLink(value: FolderRoute(id: item.id, zoom: true)) { ItemGridCell(item: item) }.buttonStyle(.plain)185 .dropDestination(for: DraggedItem.self) { dragged, _ in moveDragged(dragged, into: item) }186 } else {187 Button { actions.open(item, model: model) } label: { ItemGridCell(item: item) }.buttonStyle(.plain)188 }189 }190 .contextMenu { ItemMenu(item: item, actions: actions) }191 .draggable(DraggedItem(id: item.id, name: item.name, isFolder: item.isFolder)) {192 // rendered outside the view tree: it needs the model handed to it193 ItemGridCell(item: item).frame(width: 150).environment(model)194 }195 .accessibilityActions { Button("Plus d’actions") { actions.sheet = .actions(item) } }196 }197 }198 .padding(12)199 footer(items).padding(.bottom, 24)200 }201 }202203 private func footer(_ items: [DriveItem]) -> some View {204 let files = items.filter { !$0.isFolder }205 let folders = items.count - files.count206 let total = files.reduce(Int64(0)) { $0 + $1.size }207 return Text("\(folders) dossier\(folders > 1 ? "s" : ""), \(files.count) fichier\(files.count > 1 ? "s" : "")\(files.isEmpty ? "" : " · \(total.byteString)")")208 .font(.footnote).foregroundStyle(.secondary).frame(maxWidth: .infinity).listRowSeparator(.hidden)209 }210211 @ViewBuilder212 private var emptyState: some View {213 if filter != nil || !filterText.isEmpty {214 EmptyState(symbol: "line.3.horizontal.decrease.circle", title: "Aucun résultat", message: "Aucun élément de ce dossier ne correspond au filtre.", action: ("Effacer le filtre", { filter = nil; filterText = "" }))215 } else {216 // a smart empty state: the ways to fill this folder, one tap each (the scanner only where there is a camera)217 EmptyState(symbol: "folder", title: String(localized: "Dossier vide"),218 message: model.network.online ? String(localized: "Ajoute des fichiers depuis cet appareil, tes photos ou une autre app. Tu peux aussi les glisser ici.")219 : String(localized: "Tu es hors ligne : ce que tu ajoutes ici partira au retour du réseau."),220 action: (String(localized: "Importer des fichiers"), { importingFiles = true }),221 more: [.init(id: "photos", label: String(localized: "Photos"), symbol: "photo.on.rectangle") { pickingPhotos = true }]222 + (canScan ? [.init(id: "scan", label: String(localized: "Numériser"), symbol: "doc.viewfinder") { startScan() }] : [])223 + [.init(id: "folder", label: String(localized: "Dossier"), symbol: "folder.badge.plus") { newFolderName = ""; newFolder = true }])224 }225 }226227 // MARK: Toolbar228229 @ToolbarContentBuilder230 private func toolbar(_ items: [DriveItem]) -> some ToolbarContent {231 if editMode == .active {232 ToolbarItem(placement: .topBarLeading) {233 Button(selection.count == items.count ? "Tout désélectionner" : "Tout sélectionner") { selection = selection.count == items.count ? [] : Set(items.map(\.id)) }234 }235 ToolbarItem(placement: .topBarTrailing) { Button("OK") { editMode = .inactive }.bold() }236 ToolbarItemGroup(placement: .bottomBar) {237 let chosen = items.filter { selection.contains($0.id) }238 Button { actions.sheet = .move(chosen) } label: { Label("Déplacer", systemImage: "folder") }.disabled(chosen.isEmpty)239 Spacer()240 Button { actions.toggleStar(chosen, model: model) } label: { Label("Favori", systemImage: "star") }.disabled(chosen.isEmpty)241 Spacer()242 Button { for i in chosen where !i.isLocalOnly { actions.setOffline(i, true, model: model) } } label: { Label("Hors ligne", systemImage: "arrow.down.circle") }.disabled(chosen.isEmpty)243 Spacer()244 Button { actions.duplicate(chosen.filter { !$0.isLocalOnly }, model: model) } label: { Label("Dupliquer", systemImage: "plus.square.on.square") }.disabled(chosen.isEmpty)245 Spacer()246 Button(role: .destructive) { actions.confirmingTrash = chosen } label: { Label("Supprimer", systemImage: "trash") }.disabled(chosen.isEmpty)247 }248 } else {249 ToolbarItem(placement: .topBarTrailing) {250 Menu {251 Button { newFolderName = ""; newFolder = true } label: { Label("Nouveau dossier", systemImage: "folder.badge.plus") }252 Divider()253 Button { importingFiles = true } label: { Label("Importer depuis Fichiers", systemImage: "doc.badge.plus") }254 Button { pickingPhotos = true } label: { Label("Photos et vidéos", systemImage: "photo.on.rectangle") }255 if UIImagePickerController.isSourceTypeAvailable(.camera) {256 Button { camera = true } label: { Label("Prendre une photo", systemImage: "camera") }257 }258 if canScan { Button { startScan() } label: { Label("Numériser un document", systemImage: "doc.viewfinder") } }259 } label: { Label("Ajouter", systemImage: "plus.circle.fill") }260 .accessibilityIdentifier("add")261 }262 ToolbarItem(placement: .topBarTrailing) {263 Menu {264 Button { editMode = .active } label: { Label("Sélectionner", systemImage: "checkmark.circle") }.disabled(items.isEmpty)265 Picker("Affichage", selection: $grid) {266 Label("Liste", systemImage: "list.bullet").tag(false)267 Label("Grille", systemImage: "square.grid.2x2").tag(true)268 }269 Menu {270 Picker("Trier par", selection: $sortRaw) { ForEach(DriveStore.Sort.allCases, id: \.rawValue) { Text($0.label).tag($0.rawValue) } }271 Picker("Ordre", selection: $ascending) { Text("Croissant").tag(true); Text("Décroissant").tag(false) }272 } label: { Label("Trier", systemImage: "arrow.up.arrow.down") }273 Menu {274 Picker("Filtrer", selection: $filter) {275 Text("Tout").tag(FileKind?.none)276 ForEach([FileKind.image, .pdf, .document, .sheet, .slides, .video, .audio, .archive, .text, .code], id: \.self) { Label($0.label, systemImage: $0.symbol).tag(FileKind?.some($0)) }277 }278 } label: { Label(filter == nil ? "Filtrer" : "Filtre : \(filter!.label)", systemImage: "line.3.horizontal.decrease.circle") }279 if model.next.has(.ai), model.network.online, items.contains(where: { !$0.isFolder }) {280 Button { actions.sheet = .suggest(items.filter { !$0.isFolder }) } label: { Label("Suggestions de rangement (IA)", systemImage: "wand.and.stars") }281 }282 if let folder, !isRoot {283 Divider()284 Button { actions.details(folder) } label: { Label("Informations sur le dossier", systemImage: "info.circle") }285 Button { actions.sheet = .share(folder) } label: { Label("Partager le dossier…", systemImage: "link") }286 Button { actions.sheet = .deposit(folder) } label: { Label("Lien de dépôt…", systemImage: "tray.and.arrow.down") }287 if model.next.has(.collab) { Button { actions.sheet = .members(folder) } label: { Label("Membres et rôles…", systemImage: "person.2") } }288 if model.next.has(.ai) { Button { actions.sheet = .ask(folder) } label: { Label("Interroger ce dossier", systemImage: "sparkles") } }289 if model.next.has(.activity) { Button { actions.sheet = .activity(folder) } label: { Label("Activité du dossier", systemImage: "clock") } }290 }291 } label: { Label("Options", systemImage: filter == nil ? "ellipsis.circle" : "line.3.horizontal.decrease.circle.fill") }292 .accessibilityIdentifier("options")293 }294 }295 }296297 // MARK: Actions298299 private func more(_ item: DriveItem) -> (() -> Void)? { editMode == .active ? nil : { Haptics.tap(); actions.sheet = .actions(item) } }300301 private var canScan: Bool { DocumentScanner.isAvailable || AppConfiguration.isUITest }302 /// On a device, the document camera. In the simulator (no camera) the UI tests feed the same pipeline with generated pages.303 private func startScan() {304 if DocumentScanner.isAvailable { scanner = true }305 else if AppConfiguration.isUITest { scannedPages = ScannedPages(images: ScanFixtures.pages()) }306 }307308 private func createFolder() {309 let name = newFolderName310 Task { await model.perform { _ = try await model.engine.createFolder(name: name, in: folderID); Haptics.success() } }311 }312313 private func moveDragged(_ dragged: [DraggedItem], into folder: DriveItem) -> Bool {314 let ids = dragged.map(\.id).filter { $0 != folder.id }315 guard !ids.isEmpty else { return false }316 Task { await model.perform(success: "Déplacé dans « \(folder.name) »") { try await model.engine.move(ids, to: folder.id) } }317 return true318 }319320 /// Files lent by another app or by the Files picker: read under their security scope and copied at once.321 private func importURLs(_ urls: [URL], into parent: String) {322 Task {323 var count = 0324 for url in urls {325 let scoped = url.startAccessingSecurityScopedResource()326 defer { if scoped { url.stopAccessingSecurityScopedResource() } }327 var isDir: ObjCBool = false328 guard FileManager.default.fileExists(atPath: url.path, isDirectory: &isDir) else { continue }329 await model.perform {330 if isDir.boolValue { count += try await importDirectory(url, into: parent) }331 else { _ = try await model.engine.importFile(at: url, into: parent); count += 1 }332 }333 }334 if count > 0 { Haptics.success(); model.toast = Toast(text: count == 1 ? "1 fichier ajouté à la file d’envoi" : "\(count) fichiers ajoutés à la file d’envoi", style: .success) }335 }336 }337338 /// A dropped folder is recreated on the Drive with its content.339 private func importDirectory(_ url: URL, into parent: String) async throws -> Int {340 let created = try await model.engine.createFolder(name: url.lastPathComponent, in: parent)341 var count = 0342 for child in try FileManager.default.contentsOfDirectory(at: url, includingPropertiesForKeys: [.isDirectoryKey], options: [.skipsHiddenFiles]) {343 if (try? child.resourceValues(forKeys: [.isDirectoryKey]).isDirectory) == true { count += try await importDirectory(child, into: created.id) }344 else { _ = try await model.engine.importFile(at: child, into: created.id); count += 1 }345 }346 return count347 }348349 /// Temporary files this app created (camera, scanner, photo export): moved into the upload queue.350 private func importOwned(_ urls: [URL]) {351 Task {352 for url in urls { await model.perform { _ = try await model.engine.importFile(at: url, into: folderID, move: true) } }353 if !urls.isEmpty { Haptics.success(); model.toast = Toast(text: urls.count == 1 ? "Ajouté à la file d’envoi" : "\(urls.count) éléments ajoutés à la file d’envoi", style: .success) }354 }355 }356357 /// The system picker hands over only what the user chose: no access to the photo library is requested.358 private func importPhotos(_ picked: [PhotosPickerItem]) async {359 var urls: [URL] = []360 for p in picked {361 if let file = try? await p.loadTransferable(type: PickedMedia.self) { urls.append(file.url) }362 }363 if urls.count < picked.count { model.toast = Toast(text: "Certains éléments n’ont pas pu être lus.", style: .error) }364 importOwned(urls)365 }366}367368/// What travels during a drag inside the app (and, for files, the file itself towards other apps on iPad).369struct DraggedItem: Codable, Transferable, Sendable {370 let id: String371 let name: String372 let isFolder: Bool373374 static var transferRepresentation: some TransferRepresentation {375 CodableRepresentation(contentType: .spDriveItem)376 FileRepresentation(exportedContentType: .data) { item in377 guard !item.isFolder, let engine = DragSupport.engine else { throw EngineError.notFound }378 return SentTransferredFile(try await engine.localCopy(of: item.id))379 }380 .exportingCondition { !$0.isFolder }381 }382}383384extension UTType {385 static let spDriveItem = UTType(exportedAs: "ai.spboucher.spdrive.item")386}387388enum DragSupport {389 nonisolated(unsafe) static var engine: SyncEngine?390}391392/// A photo or video chosen in the system picker, received as a file (never decoded in memory).393struct PickedMedia: Transferable {394 let url: URL395 static var transferRepresentation: some TransferRepresentation {396 FileRepresentation(importedContentType: .item) { received in397 let dir = FileManager.default.temporaryDirectory.appendingPathComponent("picked-\(UUID().uuidString)", isDirectory: true)398 try FileManager.default.createDirectory(at: dir, withIntermediateDirectories: true)399 let dest = dir.appendingPathComponent(received.file.lastPathComponent)400 try FileManager.default.copyItem(at: received.file, to: dest)401 return PickedMedia(url: dest)402 }403 }404}405