Repository Public
1// =============================================================================2// SP BOUCHER | SOFTWARE & RESEARCH3// ARTIFICIAL INTELLIGENCE • FINANCE • ENGINEERING4// =============================================================================5//6// PROJECT METADATA7// -----------------------------------------------------------------------------8// Project : SP Drive pour iPhone et iPad9// File : Features/MyDrive/ItemActions.swift10// Description : Everything that can be done to files and folders, in one11// place so every list (folder, recents, favourites, search,12// offline) offers the same actions: open, rename, move,13// duplicate, favourite, keep offline, share, details,14// delete.15// Module : Features16// Repository : https://git.spboucher.ai/sp-drive-ios17// Created : 2026-11-1918// Last Modified : 2026-11-1919//20// =============================================================================21// AUTHOR & PROFESSIONAL AFFILIATION22// =============================================================================23//24// Author : Simon-Pierre Boucher25// Position : Professor of Finance26// Institution : Université du Québec en Outaouais (UQO)27// Department : Département des sciences administratives28// Organization : SP Boucher29//30// Website : https://spboucher.ai31// Git : https://git.spboucher.ai32//33// =============================================================================34// OFFICIAL CONTACT DIRECTORY35// =============================================================================36//37// General : info@spboucher.ai38// Professional : contact@spboucher.ai39// Direct : simon@spboucher.ai40// Research : research@spboucher.ai41// Development : dev@spboucher.ai42// Support : support@spboucher.ai43// Security/Admin : admin@spboucher.ai44// Notifications : notifications@spboucher.ai45//46// Preferred Contact: support@spboucher.ai47//48// =============================================================================49// COPYRIGHT & INTELLECTUAL PROPERTY50// =============================================================================51//52// Copyright (c) 202653// Simon-Pierre Boucher54//55// All rights reserved where applicable.56//57// This file is governed by the applicable project license,58// copyright notices, institutional agreements and relevant law.59//60// Unless expressly authorized by the applicable license or61// rights holder, copying, redistribution, sublicensing,62// publication and commercial exploitation are not permitted.63//64// Existing third-party rights and notices remain unaffected.65//66// =============================================================================67// CONFIDENTIALITY & SECURITY68// =============================================================================69//70// Classification : Public71// Distribution : Public repository; use is governed by the project license72// Security Contact : admin@spboucher.ai73//74// Access to this source does not independently grant permission75// to redistribute or disclose confidential materials.76//77// Do not embed credentials, private keys, access tokens,78// certificates or confidential personal information.79//80// =============================================================================81// LICENSE & MAINTENANCE82// =============================================================================83//84// License : None specified (no license file in this repository)85// Maintainer : Simon-Pierre Boucher86// Technical Contact: dev@spboucher.ai87//88// =============================================================================89// END OF SP BOUCHER SOURCE HEADER90// =============================================================================9192import SwiftUI93import UIKit94import UniformTypeIdentifiers9596struct PreviewRequest: Identifiable {97 let id = UUID()98 let item: DriveItem99 let url: URL100}101102@MainActor @Observable103final class ItemActions {104 enum Sheet: Identifiable {105 case move([DriveItem]), copy([DriveItem]), details(DriveItem), share(DriveItem), deposit(DriveItem), editText(DriveItem, URL), export(URL)106 /// The contextual bottom sheet of an item.107 case actions(DriveItem)108 // SP Drive 2.0109 case tags(DriveItem), ask(DriveItem), versions(DriveItem), members(DriveItem), activity(DriveItem), suggest([DriveItem])110 /// The two versions of a file in conflict, and the choice.111 case conflict(ConflictRecord)112 /// PDF annotation (Apple Pencil); saving creates a new version.113 case annotate(DriveItem, URL)114 var id: String {115 switch self {116 case .suggest(let i): "suggest-\(i.count)-\(i.first?.id ?? "")"117 case .tags(let i): "tags-\(i.id)"; case .ask(let i): "ask-\(i.id)"; case .versions(let i): "versions-\(i.id)"; case .members(let i): "members-\(i.id)"; case .activity(let i): "activity-\(i.id)"118 case .actions(let i): "actions-\(i.id)"; case .annotate(let i, _): "annotate-\(i.id)"; case .conflict(let c): "conflict-\(c.id)"119 case .move(let i): "move-\(i.map(\.id).joined())"; case .copy(let i): "copy-\(i.map(\.id).joined())"; case .details(let i): "details-\(i.id)"; case .share(let i): "share-\(i.id)"120 case .deposit(let i): "deposit-\(i.id)"; case .editText(let i, _): "text-\(i.id)"; case .export(let u): "export-\(u.path)"121 }122 }123 }124 var sheet: Sheet?125 var preview: PreviewRequest?126 var renaming: DriveItem?127 var renameText = ""128 var confirmingTrash: [DriveItem] = []129 /// Identifier of the file being fetched before it opens.130 var openingID: String?131 @ObservationIgnored private var openTask: Task<Void, Never>?132 /// On a wide layout, « informations » opens the inspector column instead of a sheet.133 var prefersInspector = false134 var inspected: DriveItem?135 var inspectorShown = false136137 func details(_ item: DriveItem) {138 if prefersInspector { inspected = item; inspectorShown = true; if sheet != nil { sheet = nil } } else { sheet = .details(item) }139 }140141 func annotate(_ item: DriveItem, model: AppModel) {142 Task { await model.perform { sheet = .annotate(item, try await model.engine.localCopy(of: item.id)) } }143 }144145 /// Opens a file: uses the verified local copy, or downloads it first (with progress in the row's badge).146 func open(_ item: DriveItem, model: AppModel) {147 guard !item.isFolder else { return }148 if item.isInfected { model.toast = Toast(text: "Ce fichier a été signalé par l’antivirus et ne peut pas être ouvert.", style: .error); return }149 // a file in conflict opens on the choice: the user must not edit further without knowing150 if let c = model.store.conflict(itemID: item.id) { Haptics.warning(); sheet = .conflict(c); return }151 openTask?.cancel()152 openingID = item.id153 openTask = Task {154 defer { if openingID == item.id { openingID = nil } }155 await model.perform {156 let url = try await model.engine.localCopy(of: item.id)157 try Task.checkCancellation()158 preview = PreviewRequest(item: model.store.item(item.id) ?? item, url: url)159 }160 }161 }162163 func cancelOpening() { openTask?.cancel(); openingID = nil }164165 func beginRename(_ item: DriveItem) {166 renameText = item.name167 renaming = item168 }169170 func commitRename(model: AppModel) {171 guard let item = renaming else { return }172 let name = renameText173 renaming = nil174 Task { await model.perform { try await model.engine.rename(item.id, to: name) } }175 }176177 func toggleStar(_ items: [DriveItem], model: AppModel) {178 let star = !items.allSatisfy(\.starred)179 Haptics.tap()180 Task { await model.perform { try await model.engine.setStarred(items.map(\.id), star) } }181 }182183 func setOffline(_ item: DriveItem, _ on: Bool, model: AppModel) {184 Haptics.tap()185 Task {186 if on { await model.perform(success: item.isFolder ? "Dossier gardé hors ligne" : "Fichier gardé hors ligne") { try await model.engine.pin(item.id) } }187 else { await model.engine.unpin(item.id) }188 }189 }190191 func removeDownload(_ item: DriveItem, model: AppModel) {192 Task {193 if await model.engine.removeLocalCopy(item.id) { model.toast = Toast(text: "Copie retirée de cet appareil. Le fichier reste sur ton Drive.") }194 else { model.toast = Toast(text: "Ce fichier contient des modifications pas encore envoyées.", style: .error) }195 }196 }197198 func trash(_ items: [DriveItem], model: AppModel) {199 confirmingTrash = []200 Haptics.tap()201 Task { await model.perform(success: items.count == 1 ? "Déplacé dans la corbeille" : "\(items.count) éléments déplacés dans la corbeille") { try await model.engine.trash(items.map(\.id)) } }202 }203204 func duplicate(_ items: [DriveItem], model: AppModel) {205 Task {206 await model.perform(success: "Copie créée") {207 // grouped by parent: each copy lands next to its original, under a free name chosen by the server208 for (parent, group) in Dictionary(grouping: items, by: { $0.parentID ?? "" }) where !parent.isEmpty { try await model.engine.copy(group.map(\.id), to: parent) }209 }210 }211 }212213 /// Hands the file itself to another app (system share sheet: AirDrop, « Enregistrer dans Fichiers », open in…).214 func export(_ item: DriveItem, model: AppModel) {215 Task { await model.perform { sheet = .export(try await model.engine.localCopy(of: item.id)) } }216 }217218 func editText(_ item: DriveItem, model: AppModel) {219 Task { await model.perform { sheet = .editText(item, try await model.engine.localCopy(of: item.id)) } }220 }221}222223extension DriveItem {224 var isEditableText: Bool { !isFolder && (kind == .text || kind == .code) && size <= 2_000_000 }225}226227/// The context menu of an item (also used for the « … » button).228struct ItemMenu: View {229 @Environment(AppModel.self) private var model230 @Environment(\.openWindow) private var openWindow231 let item: DriveItem232 let actions: ItemActions233234 var body: some View {235 let badge = model.badge(item)236 let pinned = model.store.localState(item.id)?.pinned == true237 if !item.isFolder {238 Button { actions.open(item, model: model) } label: { Label("Ouvrir", systemImage: "eye") }239 if item.isEditableText { Button { actions.editText(item, model: model) } label: { Label("Modifier le texte", systemImage: "square.and.pencil") } }240 Button { actions.export(item, model: model) } label: { Label("Ouvrir dans une autre app…", systemImage: "square.and.arrow.up") }241 }242 Divider()243 if !item.isLocalOnly {244 Button { actions.sheet = .share(item) } label: { Label("Partager par lien…", systemImage: "link") }245 if item.isFolder { Button { actions.sheet = .deposit(item) } label: { Label("Lien de dépôt…", systemImage: "tray.and.arrow.down") } }246 }247 if item.isFolder, UIDevice.current.userInterfaceIdiom == .pad, UIApplication.shared.supportsMultipleScenes {248 Button { openWindow(id: "browser", value: item.id) } label: { Label("Ouvrir dans une nouvelle fenêtre", systemImage: "macwindow.badge.plus") }249 }250 Button { actions.toggleStar([item], model: model) } label: { Label(item.starred ? "Retirer des favoris" : "Ajouter aux favoris", systemImage: item.starred ? "star.slash" : "star") }251 if !item.isLocalOnly {252 Button { actions.setOffline(item, !pinned, model: model) } label: { Label(pinned ? "Ne plus garder hors ligne" : "Garder hors ligne", systemImage: pinned ? "arrow.down.circle.badge.xmark" : "arrow.down.circle") }253 if !item.isFolder, !pinned, badge == .available {254 Button { actions.removeDownload(item, model: model) } label: { Label("Retirer de cet appareil", systemImage: "iphone.slash") }255 }256 }257 Divider()258 Button { actions.beginRename(item) } label: { Label("Renommer", systemImage: "pencil") }259 Button { actions.sheet = .move([item]) } label: { Label("Déplacer…", systemImage: "folder") }260 if !item.isLocalOnly { Button { actions.duplicate([item], model: model) } label: { Label("Dupliquer", systemImage: "plus.square.on.square") } }261 if item.kind == .pdf, !item.isTrashed { Button { actions.annotate(item, model: model) } label: { Label("Annoter le PDF", systemImage: "pencil.tip.crop.circle") } }262 Button { actions.details(item) } label: { Label("Informations et versions", systemImage: "info.circle") }263 Divider()264 Button(role: .destructive) { actions.confirmingTrash = [item] } label: { Label("Supprimer du Drive", systemImage: "trash") }265 }266}267268/// Attaches the sheets, alerts and the viewer driven by an `ItemActions` to a screen.269struct ItemActionsHost: ViewModifier {270 @Environment(AppModel.self) private var model271 @Bindable var actions: ItemActions272 @Environment(\.horizontalSizeClass) private var sizeClass273 /// Only the screen in front answers « open this item » requests coming from elsewhere in the app.274 @State private var visible = false275276 func body(content: Content) -> some View {277 content278 .sheet(item: $actions.sheet) { sheet in279 switch sheet {280 case .move(let items): FolderPicker(title: "Déplacer vers", excluding: Set(items.filter(\.isFolder).map(\.id)), startAt: items.first?.parentID) { dest in281 Task { await model.perform(success: "Déplacé") { try await model.engine.move(items.map(\.id), to: dest) } }282 }283 case .copy(let items): FolderPicker(title: "Copier vers", excluding: [], startAt: items.first?.parentID) { dest in284 Task { await model.perform(success: "Copié") { try await model.engine.copy(items.map(\.id), to: dest) } }285 }286 case .details(let item): ItemDetailsView(item: item).presentationDetents([.medium, .large]).presentationDragIndicator(.visible)287 case .actions(let item): ItemActionSheet(item: item, actions: actions)288 case .conflict(let c): ConflictSheet(conflict: c)289 case .tags(let item): TagsEditor(item: item)290 case .suggest(let items): SuggestionsSheet(items: items)291 case .ask(let item): NavigationStack { AskScreen(scope: AskScope(kind: item.isFolder ? .folder(item.id) : .file(item.id), name: item.name), modal: true) }292 case .versions(let item): NavigationStack { VersionsScreen(item: item).toolbar { ToolbarItem(placement: .cancellationAction) { Button("Fermer") { actions.sheet = nil } } } }293 case .members(let item): NavigationStack { MembersScreen(folder: item).toolbar { ToolbarItem(placement: .cancellationAction) { Button("Fermer") { actions.sheet = nil } } } }294 case .activity(let item): NavigationStack { ActivityScreen(source: item.isFolder ? .folder(item.id) : .file(item.id), title: item.name).toolbar { ToolbarItem(placement: .cancellationAction) { Button("Fermer") { actions.sheet = nil } } } }295 case .annotate(let item, let url): PDFAnnotator(item: item, url: url)296 case .share(let item): ShareLinkEditor(item: item)297 case .deposit(let item): DepositLinkEditor(folder: item)298 case .editText(let item, let url): TextEditorScreen(item: item, url: url)299 case .export(let url): ActivitySheet(url: url).presentationDetents([.medium, .large])300 }301 }302 .fullScreenCover(item: $actions.preview) { request in303 // the thumbnail grows into the full preview and shrinks back into it304 FilePreview(request: request).ignoresSafeArea().zoomDestination(request.item.id)305 }306 .onChange(of: sizeClass, initial: true) { _, c in actions.prefersInspector = c == .regular; if c != .regular { actions.inspectorShown = false } }307 .inspector(isPresented: $actions.inspectorShown) {308 Group {309 if let item = actions.inspected { ItemInspector(item: item, actions: actions) }310 else { ContentUnavailableView("Aucune sélection", systemImage: "sidebar.right", description: Text("Choisis « Informations » sur un élément pour l’afficher ici.")) }311 }312 .inspectorColumnWidth(min: 300, ideal: 360, max: 460)313 }314 .alert("Renommer", isPresented: Binding(get: { actions.renaming != nil }, set: { if !$0 { actions.renaming = nil } })) {315 TextField("Nom", text: $actions.renameText).textInputAutocapitalization(.never).autocorrectionDisabled()316 Button("Annuler", role: .cancel) { actions.renaming = nil }317 Button("Renommer") { actions.commitRename(model: model) }318 }319 // an alert rather than an action sheet: on iPad a sheet becomes a popover with no sensible anchor for a multiple selection320 .alert(trashTitle, isPresented: Binding(get: { !actions.confirmingTrash.isEmpty }, set: { if !$0 { actions.confirmingTrash = [] } })) {321 Button("Supprimer du Drive", role: .destructive) { actions.trash(actions.confirmingTrash, model: model) }322 Button("Annuler", role: .cancel) {}323 } message: {324 Text("L’élément ira dans la corbeille du Drive, sur tous tes appareils. Tu pourras le restaurer. Pour libérer seulement de l’espace sur cet appareil, utilise « Retirer de cet appareil ».")325 }326 .overlay {327 if actions.openingID != nil {328 VStack(spacing: 12) {329 ProgressView()330 Text("Ouverture…").font(.subheadline)331 Button("Annuler") { actions.cancelOpening() }.font(.subheadline)332 }333 .padding(24)334 .background(.regularMaterial, in: RoundedRectangle(cornerRadius: 18, style: .continuous))335 .accessibilityIdentifier("opening")336 }337 }338 .onReceive(NotificationCenter.default.publisher(for: .openDriveItem)) { note in339 if visible, let id = note.object as? String, let item = model.store.item(id) { actions.open(item, model: model) }340 }341 .onAppear { visible = true }342 .onDisappear { visible = false }343 }344345 private var trashTitle: String {346 let n = actions.confirmingTrash.count347 return n == 1 ? "Supprimer « \(actions.confirmingTrash[0].name) » du Drive ?" : "Supprimer \(n) éléments du Drive ?"348 }349}350351extension View {352 func itemActions(_ actions: ItemActions) -> some View { modifier(ItemActionsHost(actions: actions)) }353}354355struct ActivitySheet: UIViewControllerRepresentable {356 let url: URL357 func makeUIViewController(context: Context) -> UIActivityViewController { UIActivityViewController(activityItems: [url], applicationActivities: nil) }358 func updateUIViewController(_ controller: UIActivityViewController, context: Context) {}359}360