Repository Public
1// SP Notes iOS2// File: Features/Attachments/NoteAttachmentsView.swift3// Description: The files of one note: where each one is (on the device, to download, waiting for upload, failed), preview, share,4// "keep offline", download and delete. Also the loader that brings an attachment on the device before QuickLook.5//6// Author: Simon-Pierre Boucher7// Contact: contact@spboucher.ai8import SPNotesCore9import SwiftUI10import UIKit1112/// How an attachment is described in the list.13enum AttachmentPresentation {14 struct Status: Equatable {15 var text: String16 var symbol: String17 var isProblem: Bool18 }1920 static func status(_ record: AttachmentRecord) -> Status {21 switch record.state {22 case .local:23 return record.uploaded24 ? Status(text: String(localized: "Sur l’appareil"), symbol: "checkmark.circle", isProblem: false)25 : Status(text: String(localized: "En attente d’envoi"), symbol: "arrow.up.circle", isProblem: false)26 case .remote: return Status(text: String(localized: "À télécharger"), symbol: "icloud.and.arrow.down", isProblem: false)27 case .downloading: return Status(text: String(localized: "Téléchargement…"), symbol: "arrow.down.circle", isProblem: false)28 case .pendingUpload: return Status(text: String(localized: "En attente d’envoi"), symbol: "arrow.up.circle", isProblem: false)29 case .uploading: return Status(text: String(localized: "Envoi en cours…"), symbol: "arrow.up.circle", isProblem: false)30 case .failed: return Status(text: String(localized: "Échec de l’envoi"), symbol: "exclamationmark.triangle", isProblem: true)31 }32 }3334 static func symbol(mime: String, filename: String) -> String {35 if mime.hasPrefix("image/") { return "photo" }36 if mime == "application/pdf" { return "doc.richtext" }37 if mime.hasPrefix("audio/") { return "waveform" }38 if mime.hasPrefix("video/") { return "film" }39 if mime.hasPrefix("text/") { return "doc.plaintext" }40 switch (filename as NSString).pathExtension.lowercased() {41 case "zip", "gz", "tar", "7z": return "doc.zipper"42 case "xls", "xlsx", "csv", "numbers": return "tablecells"43 case "ppt", "pptx", "key": return "rectangle.on.rectangle"44 case "doc", "docx", "pages", "rtf": return "doc.text"45 default: return "doc"46 }47 }4849 static func size(_ bytes: Int64) -> String { ByteCountFormatter.string(fromByteCount: bytes, countStyle: .file) }5051 /// The editable source stored next to a drawing: an implementation detail, not listed.52 /// 2.0: the ink JSON of a `drawing` block (`drawing-<id>.ink.json`) is one too.53 static func isDrawingSource(_ record: AttachmentRecord) -> Bool {54 record.filename.hasSuffix(".pkdrawing") || (record.filename.hasPrefix("drawing-") && record.filename.hasSuffix(".ink.json"))55 }5657 /// The source file that goes with a drawing picture (`drawing-<id>.png` → `drawing-<id>.pkdrawing`).58 static func drawingCompanion(of record: AttachmentRecord, in all: [AttachmentRecord]) -> AttachmentRecord? {59 guard record.filename.hasPrefix("drawing-"), record.filename.hasSuffix(".png") else { return nil }60 let name = String(record.filename.dropLast(4)) + ".pkdrawing"61 return all.first { $0.filename == name }62 }6364 /// True when the file is on this device right now.65 static func isOnDevice(_ record: AttachmentRecord) -> Bool {66 record.localPath != nil && [.local, .pendingUpload, .uploading, .failed].contains(record.state)67 }68}6970// MARK: - Loader (download if needed, then QuickLook)7172/// Brings an attachment on the device, with a visible progress state, then previews it. Says so when the file is not on the73/// device and there is no network.74struct AttachmentPreviewLoader: View {75 let attachmentId: String76 let name: String7778 enum Phase: Equatable { case loading, ready(URL), offline, failed(String) }7980 @Environment(AppModel.self) private var app81 @Environment(\.dismiss) private var dismiss82 @State private var phase: Phase = .loading8384 var body: some View {85 Group {86 switch phase {87 case .ready(let url) where AttachmentPreview.canPreview(url):88 AttachmentPreview(url: url).ignoresSafeArea()89 default:90 NavigationStack {91 content92 .background(Color.spBackground)93 .navigationTitle(name.isEmpty ? String(localized: "Fichier") : name)94 .navigationBarTitleDisplayMode(.inline)95 .toolbar { ToolbarItem(placement: .cancellationAction) { Button("Fermer") { dismiss() }.accessibilityIdentifier("attachment-loader-close") } }96 }97 }98 }99 .task { await load() }100 .accessibilityIdentifier("attachment-loader")101 }102103 @ViewBuilder private var content: some View {104 switch phase {105 case .loading:106 VStack(spacing: 12) {107 ProgressView()108 Text("Préparation du fichier…").font(.subheadline).foregroundStyle(Color.spTextSecondary)109 }110 .frame(maxWidth: .infinity, maxHeight: .infinity)111 case .ready(let url):112 EmptyStateView(symbol: "doc", title: "Aperçu indisponible", message: "Ce type de fichier ne peut pas être affiché ici. Tu peux l’ouvrir dans une autre app.", actionTitle: "Partager…") {113 ShareSheet.present(urls: [url])114 }115 case .offline:116 EmptyStateView(symbol: "wifi.slash", title: "Fichier pas sur l’appareil", message: "Ce fichier n’a pas encore été téléchargé et tu es hors ligne. Il sera disponible une fois le réseau revenu.", actionTitle: "Réessayer") {117 Task { await load() }118 }119 case .failed(let message):120 EmptyStateView(symbol: "exclamationmark.triangle", title: "Téléchargement impossible", message: LocalizedStringKey(message), actionTitle: "Réessayer") {121 Task { await load() }122 }123 }124 }125126 private func load() async {127 phase = .loading128 phase = await Self.resolve(attachmentId, app: app)129 }130131 /// The local file of an attachment (downloaded if needed), or why it cannot be had now.132 @MainActor133 static func resolve(_ id: String, app: AppModel) async -> Phase {134 let record = try? await app.store.attachment(id: id)135 let onDevice = record.map { $0.localPath != nil && app.files.exists(relativePath: $0.localPath ?? "") } ?? false136 if !onDevice {137 if !app.network.isOnline { return .offline }138 if app.session != .signedIn { return .failed(String(localized: "Ce fichier est sur le serveur : connecte-toi pour le télécharger.")) }139 }140 do {141 return .ready(try await app.localFile(forAttachment: id))142 } catch let error as APIError where error.isOffline {143 return .offline144 } catch let error as APIError where error.isNotFound {145 return .failed(String(localized: "Ce fichier n’existe plus sur le serveur."))146 } catch {147 return .failed(String(localized: "Le fichier n’a pas pu être téléchargé. Réessaie dans un instant."))148 }149 }150}151152// MARK: - List153154struct NoteAttachmentsView: View {155 let noteId: String156 /// Removes the blocks that show an attachment from the open note; returns how many were removed. nil when no editor is open.157 var removeBlocks: ((String) -> Int)?158159 private struct Preview: Identifiable { let id: String; let name: String }160161 @Environment(AppModel.self) private var app162 @Environment(\.dismiss) private var dismiss163 @State private var all: [AttachmentRecord] = []164 @State private var loaded = false165 @State private var preview: Preview?166 @State private var busy: Set<String> = []167 @State private var pendingDelete: AttachmentRecord?168 @State private var notice: String?169170 private var listed: [AttachmentRecord] { all.filter { !AttachmentPresentation.isDrawingSource($0) } }171172 var body: some View {173 NavigationStack {174 List {175 if loaded && listed.isEmpty {176 Section {177 Text("Aucune pièce jointe. Ajoute une photo, une numérisation ou un fichier depuis le bouton « + » du clavier.")178 .font(.subheadline).foregroundStyle(Color.spTextSecondary)179 }180 }181 if !listed.isEmpty {182 Section {183 ForEach(listed) { record in row(record) }184 } footer: {185 Text("« Garder hors ligne » conserve le fichier sur cet appareil même quand la place manque.")186 }187 }188 }189 .listStyle(.insetGrouped)190 .scrollContentBackground(.hidden)191 .background(Color.spBackground)192 .navigationTitle("Pièces jointes")193 .navigationBarTitleDisplayMode(.inline)194 .toolbar { ToolbarItem(placement: .confirmationAction) { Button("OK") { dismiss() }.accessibilityIdentifier("attachments-close") } }195 .task(id: app.feed.attachments &+ app.feed.structure) { await load() }196 .fullScreenCover(item: $preview) { item in AttachmentPreviewLoader(attachmentId: item.id, name: item.name) }197 .confirmationDialog("Supprimer cette pièce jointe ?", isPresented: Binding(get: { pendingDelete != nil }, set: { if !$0 { pendingDelete = nil } }), titleVisibility: .visible, presenting: pendingDelete) { record in198 Button("Supprimer", role: .destructive) { Task { await delete(record) } }199 Button("Annuler", role: .cancel) {}200 } message: { record in201 Text(removeBlocks == nil202 ? "« \(record.filename) » sera supprimé de l’appareil et du serveur. Pense à retirer aussi son bloc dans le texte de la note."203 : "« \(record.filename) » sera supprimé de l’appareil et du serveur, et son bloc retiré du texte de la note.")204 }205 .alert("Pièces jointes", isPresented: Binding(get: { notice != nil }, set: { if !$0 { notice = nil } })) {206 Button("OK", role: .cancel) {}207 } message: { Text(notice ?? "") }208 }209 .accessibilityIdentifier("attachments-sheet")210 }211212 private func row(_ record: AttachmentRecord) -> some View {213 let status = AttachmentPresentation.status(record)214 return HStack(spacing: 12) {215 Button { preview = Preview(id: record.id, name: record.filename) } label: {216 HStack(spacing: 12) {217 Image(systemName: AttachmentPresentation.symbol(mime: record.mime, filename: record.filename))218 .font(.title3).foregroundStyle(Color.accentColor).frame(width: 30).accessibilityHidden(true)219 VStack(alignment: .leading, spacing: 2) {220 Text(record.filename).font(.body).foregroundStyle(Color.spText).lineLimit(2)221 HStack(spacing: 4) {222 Image(systemName: status.symbol).accessibilityHidden(true)223 Text("\(status.text) · \(AttachmentPresentation.size(record.size))")224 if record.keepOffline { Image(systemName: "pin.fill").accessibilityLabel("Gardé hors ligne") }225 }226 .font(.caption)227 .foregroundStyle(status.isProblem ? Color.spDanger : Color.spTextSecondary)228 if status.isProblem, let error = record.lastError, !error.isEmpty {229 Text(error).font(.caption2).foregroundStyle(Color.spMuted).lineLimit(2)230 }231 }232 Spacer(minLength: 0)233 }234 .frame(minHeight: 44)235 .contentShape(Rectangle())236 }237 .buttonStyle(.plain)238 .accessibilityHint("Affiche un aperçu")239 if busy.contains(record.id) { ProgressView() }240 Menu {241 Button { preview = Preview(id: record.id, name: record.filename) } label: { Label("Aperçu", systemImage: "eye") }242 Button { Task { await share(record) } } label: { Label("Partager…", systemImage: "square.and.arrow.up") }243 if record.state == .remote {244 Button { Task { await download(record) } } label: { Label("Télécharger maintenant", systemImage: "icloud.and.arrow.down") }245 }246 Toggle(isOn: Binding(get: { record.keepOffline }, set: { value in Task { await setKeepOffline(record, value) } })) {247 Label("Garder hors ligne", systemImage: "pin")248 }249 Divider()250 Button(role: .destructive) { pendingDelete = record } label: { Label("Supprimer", systemImage: "trash") }251 } label: {252 Image(systemName: "ellipsis.circle").font(.title3).frame(minWidth: 44, minHeight: 44)253 }254 .accessibilityLabel("Actions pour \(record.filename)")255 .accessibilityIdentifier("attachment-menu")256 }257 .swipeActions(edge: .trailing) {258 Button(role: .destructive) { pendingDelete = record } label: { Label("Supprimer", systemImage: "trash") }259 }260 .accessibilityIdentifier("attachment-row")261 }262263 private func load() async {264 all = (try? await app.store.attachments(pageId: noteId)) ?? []265 loaded = true266 }267268 private func withBusy(_ id: String, _ body: () async -> Void) async {269 busy.insert(id)270 await body()271 busy.remove(id)272 await load()273 }274275 private func explain(_ phase: AttachmentPreviewLoader.Phase) {276 switch phase {277 case .offline: notice = String(localized: "Ce fichier n’est pas sur l’appareil et tu es hors ligne.")278 case .failed(let message): notice = message279 default: break280 }281 }282283 private func download(_ record: AttachmentRecord) async {284 await withBusy(record.id) { explain(await AttachmentPreviewLoader.resolve(record.id, app: app)) }285 }286287 private func share(_ record: AttachmentRecord) async {288 await withBusy(record.id) {289 let phase = await AttachmentPreviewLoader.resolve(record.id, app: app)290 if case .ready(let url) = phase { ShareSheet.present(urls: [url]) } else { explain(phase) }291 }292 }293294 private func setKeepOffline(_ record: AttachmentRecord, _ keep: Bool) async {295 do {296 try await app.setKeepOffline(attachment: record.id, keep)297 await load()298 if keep, record.state == .remote {299 if app.network.isOnline && app.session == .signedIn { await download(record) }300 else { notice = String(localized: "Le fichier sera téléchargé et gardé dès que le réseau sera disponible.") }301 }302 } catch { notice = error.localizedDescription }303 }304305 private func delete(_ record: AttachmentRecord) async {306 do {307 let companion = AttachmentPresentation.drawingCompanion(of: record, in: all)308 try await app.deleteAttachment(record.id)309 if let companion { try? await app.deleteAttachment(companion.id) }310 let removed = removeBlocks?(record.id)311 await load()312 if removeBlocks == nil {313 notice = String(localized: "Fichier supprimé. Son bloc est encore dans le texte de la note : retire-le en ouvrant la note.")314 } else if removed == 0 {315 notice = String(localized: "Fichier supprimé. Aucun bloc ne l’affichait dans le texte.")316 }317 } catch { notice = error.localizedDescription }318 }319}320