SPB Git

Repository Public

DepositLinkEditor.swift 32.1 KB 711 lines swift

1// SP Drive iOS2// File: Features/Shared/DepositLinkEditor.swift3// Description: Deposit links (« liens de dépôt »): creation sheet with a destination-folder browser, detail screen (state, pause,4//              limits, rotation, revocation, deletion) and the deposits received through a link.5//6// Author: Simon-Pierre Boucher7// Contact: contact@spboucher.ai8import SwiftUI910// MARK: - Form shared by creation and edition1112/// Editable settings of a deposit link (the password is handled apart: the server never returns it).13struct DepositForm: Equatable {14    static let mib: Int64 = 1 << 2015    static let gib: Int64 = 1 << 3016    static let fileLimits: [Int64] = [10 * mib, 50 * mib, 100 * mib, 200 * mib, 500 * mib, gib, 2 * gib]17    static let totalLimits: [Int64] = [500 * mib, gib, 2 * gib, 5 * gib, 10 * gib, 20 * gib, 50 * gib]1819    var title = ""20    var description = ""21    var expiryEnabled = false22    var expiry = LinkExpiryFields.defaultDate23    var maxFileBytes: Int64 = 200 * DepositForm.mib24    var maxTotalBytes: Int64 = 5 * DepositForm.gib25    var maxFilesPerSubmission = 2026    var maxSubmissions: Int?27    var subfolderPerSubmission = true28    var notifyOwner = true2930    init() {}3132    init(link: DepositLink) {33        title = link.title34        description = link.description35        expiryEnabled = link.expiresAt != nil36        expiry = link.expiresAt ?? LinkExpiryFields.defaultDate37        maxFileBytes = link.maxFileBytes38        maxTotalBytes = link.maxTotalBytes39        maxFilesPerSubmission = link.maxFilesPerSubmission40        maxSubmissions = link.maxSubmissions41        subfolderPerSubmission = link.subfolderPerSubmission42        notifyOwner = link.notifyOwner43    }4445    var trimmedTitle: String { title.trimmingCharacters(in: .whitespacesAndNewlines) }46    var problem: String? {47        if trimmedTitle.isEmpty { return "Donne un titre au lien : c’est ce que verront les personnes qui déposent." }48        if maxTotalBytes < maxFileBytes { return "La limite totale doit être au moins égale à la limite par fichier." }49        if let m = maxSubmissions, m < 1 { return "Le nombre maximal de dépôts doit être d’au moins 1." }50        return nil51    }5253    /// Every setting, for a creation.54    var allSettings: DepositSettings {55        var s = DepositSettings()56        s.title = trimmedTitle57        s.description = description.trimmingCharacters(in: .whitespacesAndNewlines)58        if expiryEnabled { s.expiresAt = .some(expiry) }59        s.maxFileBytes = maxFileBytes60        s.maxTotalBytes = maxTotalBytes61        s.maxFilesPerSubmission = maxFilesPerSubmission62        if let maxSubmissions { s.maxSubmissions = .some(maxSubmissions) }63        s.subfolderPerSubmission = subfolderPerSubmission64        s.notifyOwner = notifyOwner65        return s66    }6768    /// Only what differs from `link`, for an update.69    func changes(from link: DepositLink) -> DepositSettings {70        let old = DepositForm(link: link)71        var s = DepositSettings()72        if trimmedTitle != link.title { s.title = trimmedTitle }73        if description != old.description { s.description = description.trimmingCharacters(in: .whitespacesAndNewlines) }74        if expiryEnabled != old.expiryEnabled || (expiryEnabled && expiry != old.expiry) { s.expiresAt = .some(expiryEnabled ? expiry : nil) }75        if maxFileBytes != old.maxFileBytes { s.maxFileBytes = maxFileBytes }76        if maxTotalBytes != old.maxTotalBytes { s.maxTotalBytes = maxTotalBytes }77        if maxFilesPerSubmission != old.maxFilesPerSubmission { s.maxFilesPerSubmission = maxFilesPerSubmission }78        if maxSubmissions != old.maxSubmissions { s.maxSubmissions = .some(maxSubmissions) }79        if subfolderPerSubmission != old.subfolderPerSubmission { s.subfolderPerSubmission = subfolderPerSubmission }80        if notifyOwner != old.notifyOwner { s.notifyOwner = notifyOwner }81        return s82    }8384    /// "200 Mo", "5 Go": the limits are powers of two on the server, shown as round numbers.85    static func sizeLabel(_ bytes: Int64) -> String {86        if bytes >= gib, bytes % gib == 0 { return "\(bytes / gib) Go" }87        if bytes >= mib, bytes % mib == 0 { return "\(bytes / mib) Mo" }88        return bytes.formatted(.byteCount(style: .binary))89    }90}9192/// The form sections of a deposit link.93struct DepositFormFields: View {94    @Binding var form: DepositForm9596    private func options(_ base: [Int64], including value: Int64) -> [Int64] { Array(Set(base + [value])).sorted() }9798    var body: some View {99        Section {100            TextField("Titre (ex. : Documents pour le dossier)", text: $form.title)101                .accessibilityIdentifier("deposit.title")102            TextField("Consignes pour les déposants (facultatif)", text: $form.description, axis: .vertical)103                .lineLimit(2...6)104                .accessibilityIdentifier("deposit.description")105        } header: {106            Text("Présentation")107        } footer: {108            Text("Le titre et les consignes sont affichés sur la page de dépôt.")109        }110        Section("Limites") {111            Picker("Taille max. par fichier", selection: $form.maxFileBytes) {112                ForEach(options(DepositForm.fileLimits, including: form.maxFileBytes), id: \.self) { Text(DepositForm.sizeLabel($0)).tag($0) }113            }114            Picker("Total max. reçu", selection: $form.maxTotalBytes) {115                ForEach(options(DepositForm.totalLimits, including: form.maxTotalBytes), id: \.self) { Text(DepositForm.sizeLabel($0)).tag($0) }116            }117            Stepper(value: $form.maxFilesPerSubmission, in: 1...200) {118                LabeledContent("Fichiers par dépôt", value: "\(form.maxFilesPerSubmission)")119            }120            LabeledContent("Nombre max. de dépôts") {121                TextField("Illimité", value: $form.maxSubmissions, format: .number).keyboardType(.numberPad).multilineTextAlignment(.trailing)122            }123            LinkExpiryFields(enabled: $form.expiryEnabled, date: $form.expiry)124        }125        Section {126            Toggle("Un sous-dossier par dépôt", isOn: $form.subfolderPerSubmission)127            Toggle("M’avertir à chaque dépôt", isOn: $form.notifyOwner)128        } header: {129            Text("Réception")130        } footer: {131            Text(form.subfolderPerSubmission ? "Chaque dépôt est rangé dans son propre sous-dossier du dossier de destination." : "Tous les fichiers arrivent directement dans le dossier de destination.")132        }133    }134}135136// MARK: - Creation sheet137138/// Sheet « Nouveau lien de dépôt ».139struct DepositLinkEditor: View {140    @Environment(AppModel.self) private var model141    @Environment(\.dismiss) private var dismiss142    private let fixedFolder: Bool143144    @State private var destination: DriveItem?145    @State private var form = DepositForm()146    @State private var password = ""147    @State private var isCreating = false148    @State private var createdURL: URL?149150    init(folder: DriveItem?) {151        fixedFolder = folder != nil152        _destination = State(initialValue: folder)153    }154155    private var passwordValid: Bool { password.isEmpty || password.count >= 4 }156    private var destinationProblem: String? {157        guard let destination else { return "Choisis le dossier qui recevra les fichiers." }158        if destination.isLocalOnly { return "Ce dossier n’est pas encore sur le Drive. Attends la fin de la synchronisation." }159        if destination.isTrashed { return "Ce dossier est dans la corbeille." }160        return nil161    }162    private var canCreate: Bool { destinationProblem == nil && form.problem == nil && passwordValid && !isCreating }163164    var body: some View {165        let _ = model.itemsVersion166        NavigationStack {167            Form {168                if let createdURL {169                    Section {170                        LinkRevealView(url: createdURL, subject: form.trimmedTitle, identifier: "deposit.url")171                    } footer: {172                        Text("Les personnes qui ont ce lien peuvent seulement envoyer des fichiers dans « \(destinationName) ». Elles ne voient jamais le contenu du dossier.")173                    }174                    Section { Button("Terminé") { dismiss() }.accessibilityIdentifier("deposit.done") }175                } else {176                    destinationSection177                    DepositFormFields(form: $form)178                    Section {179                        SecureField("Mot de passe (facultatif)", text: $password)180                            .textContentType(.newPassword)181                            .accessibilityIdentifier("deposit.password")182                    } header: {183                        Text("Protection")184                    } footer: {185                        if !passwordValid { Text("Le mot de passe doit compter au moins 4 caractères.").foregroundStyle(.red) }186                    }187                    Section {188                        Button {189                            Task { await create() }190                        } label: {191                            if isCreating { ProgressView().tint(.white) } else { Label("Créer le lien de dépôt", systemImage: "tray.and.arrow.down.fill") }192                        }193                        .buttonStyle(GradientButtonStyle())194                        .disabled(!canCreate)195                        .listRowInsets(EdgeInsets())196                        .listRowBackground(Color.clear)197                        .accessibilityIdentifier("deposit.create")198                    } footer: {199                        if let p = destinationProblem ?? form.problem { Text(p) }200                    }201                }202            }203            .navigationTitle("Lien de dépôt")204            .navigationBarTitleDisplayMode(.inline)205            .toolbar { ToolbarItem(placement: .cancellationAction) { Button(createdURL == nil ? "Annuler" : "Fermer") { dismiss() }.accessibilityIdentifier("deposit.close") } }206        }207        .sheetToast()208        .interactiveDismissDisabled(isCreating)209    }210211    private var destinationName: String { destination.map { $0.parentID == nil ? "Mon Drive" : $0.name } ?? "" }212213    private var destinationSection: some View {214        Section {215            if fixedFolder {216                HStack(spacing: 12) {217                    KindIcon(kind: .folder)218                    Text(destinationName).lineLimit(2)219                }220                .accessibilityElement(children: .combine)221            } else {222                NavigationLink {223                    DepositFolderPicker(selection: $destination)224                } label: {225                    HStack(spacing: 12) {226                        KindIcon(kind: .folder)227                        if destination != nil { Text(destinationName).lineLimit(2) } else { Text("Choisir un dossier").foregroundStyle(.secondary) }228                    }229                }230                .accessibilityIdentifier("deposit.folder")231            }232        } header: {233            Text("Dossier de destination")234        } footer: {235            Text("Les fichiers déposés arrivent dans ce dossier. Les déposants ne peuvent qu’envoyer : ils ne voient rien de ton Drive.")236        }237    }238239    private func create() async {240        guard canCreate, let destination else { return }241        isCreating = true242        defer { isCreating = false }243        var settings = form.allSettings244        if !password.isEmpty { settings.password = .some(password) }245        await model.perform {246            let result = try await model.api.createDepositLink(folderID: destination.id, settings: settings)247            createdURL = result.url248            password = ""249            Haptics.success()250        }251    }252}253254/// Minimal folder browser over the local mirror: walk down, pick the folder shown.255struct DepositFolderPicker: View {256    @Environment(AppModel.self) private var model257    @Environment(\.dismiss) private var dismiss258    @Binding var selection: DriveItem?259    /// Folder being browsed; `nil` until the view appears (then the root).260    @State private var currentID: String?261262    var body: some View {263        let _ = model.itemsVersion264        let current = (currentID ?? model.store.rootID).flatMap { model.store.item($0) }265        Group {266            if let current {267                let folders = model.store.children(of: current.id).filter { $0.isFolder && !$0.isTrashed }268                List {269                    if let parent = current.parentID {270                        Button { currentID = parent } label: { Label("Dossier parent", systemImage: "arrow.turn.left.up") }271                            .accessibilityIdentifier("deposit.picker.up")272                    }273                    Section {274                        if folders.isEmpty { Text("Aucun sous-dossier ici.").foregroundStyle(.secondary) }275                        ForEach(folders) { folder in276                            Button { currentID = folder.id } label: {277                                HStack(spacing: 12) {278                                    KindIcon(kind: .folder, size: 32)279                                    Text(folder.name).foregroundStyle(.primary).lineLimit(2)280                                    Spacer()281                                    Image(systemName: "chevron.right").font(.footnote.weight(.semibold)).foregroundStyle(.tertiary).accessibilityHidden(true)282                                }283                            }284                            .accessibilityHint("Ouvre ce dossier")285                        }286                    } header: {287                        Text(current.parentID == nil ? "Mon Drive" : current.name)288                    }289                }290                .safeAreaInset(edge: .bottom) {291                    Button {292                        selection = current293                        dismiss()294                    } label: {295                        Text(current.parentID == nil ? "Choisir « Mon Drive »" : "Choisir « \(current.name) »").lineLimit(1)296                    }297                    .buttonStyle(GradientButtonStyle())298                    .disabled(current.isLocalOnly)299                    .padding()300                    .background(.bar)301                    .accessibilityIdentifier("deposit.picker.choose")302                }303            } else {304                EmptyState(symbol: "folder.badge.questionmark", title: "Drive pas encore synchronisé", message: "Les dossiers apparaîtront ici après la première synchronisation.")305            }306        }307        .navigationTitle("Destination")308        .navigationBarTitleDisplayMode(.inline)309        .onAppear { if currentID == nil { currentID = selection?.id ?? model.store.rootID } }310    }311}312313// MARK: - List row314315/// One deposit link in a list.316struct DepositLinkRow: View {317    let link: DepositLink318319    var body: some View {320        HStack(spacing: 12) {321            Image(systemName: "tray.and.arrow.down.fill")322                .font(.system(size: 18, weight: .semibold))323                .foregroundStyle(.white)324                .frame(width: 40, height: 40)325                .background(Theme.gradient, in: RoundedRectangle(cornerRadius: 10, style: .continuous))326                .accessibilityHidden(true)327            VStack(alignment: .leading, spacing: 4) {328                Text(link.title).font(.body).lineLimit(2)329                Label(link.folderName ?? "Dossier supprimé", systemImage: "folder").font(.footnote).foregroundStyle(.secondary).lineLimit(1)330                HStack(spacing: 10) {331                    LinkStatusChip(depositState: link.state)332                    Text(link.submissions == 1 ? "1 dépôt" : "\(link.submissions) dépôts")333                    Text(link.bytesReceived.byteString)334                    if link.hasPassword { Image(systemName: "lock.fill").accessibilityLabel("Protégé par mot de passe") }335                }336                .font(.caption)337                .foregroundStyle(.secondary)338            }339        }340        .padding(.vertical, 2)341        .accessibilityElement(children: .combine)342    }343}344345// MARK: - Detail346347/// Navigation value of one deposit (submission) of a link.348struct DepositSubmissionRoute: Hashable { let id: String; let ref: String }349350/// One deposit link: state, settings, new URL on demand, revocation, deletion, and what was received.351struct DepositLinkDetailView: View {352    @Environment(AppModel.self) private var model353    @Environment(\.dismiss) private var dismiss354    @State private var link: DepositLink355    @State private var form: DepositForm356    @State private var newPassword = ""357    @State private var revealedURL: URL?358    @State private var submissions: [DepositSubmission] = []359    @State private var submissionsPhase: LinkLoadPhase = .loading360    @State private var busy = false361    @State private var confirmRotate = false362    @State private var confirmRevoke = false363    @State private var confirmDelete = false364365    init(link: DepositLink) {366        _link = State(initialValue: link)367        _form = State(initialValue: DepositForm(link: link))368    }369370    private var isRevoked: Bool { link.revokedAt != nil || link.state == "revoked" }371    private var targetMissing: Bool { link.state == "target_missing" }372    private var passwordValid: Bool { newPassword.isEmpty || newPassword.count >= 4 }373    private var isDirty: Bool { form != DepositForm(link: link) || !newPassword.isEmpty }374375    var body: some View {376        Form {377            summarySection378            if let revealedURL {379                Section { LinkRevealView(url: revealedURL, subject: link.title, identifier: "deposit.url") }380            }381            if !isRevoked {382                DepositFormFields(form: $form)383                passwordSection384                Section {385                    Button("Enregistrer les réglages") { Task { await save() } }386                        .disabled(!isDirty || form.problem != nil || !passwordValid)387                        .accessibilityIdentifier("deposit.save")388                } footer: {389                    if isDirty, let p = form.problem { Text(p).foregroundStyle(.red) }390                }391                Section {392                    Button { confirmRotate = true } label: { Label("Générer un nouveau lien", systemImage: "arrow.triangle.2.circlepath") }393                        .accessibilityIdentifier("deposit.rotate")394                } header: {395                    Text("Adresse du lien")396                } footer: {397                    Text("L’adresse n’est affichée qu’à la création. Pour l’obtenir de nouveau, génère un nouveau lien : l’ancienne adresse sera invalidée.")398                }399            }400            submissionsSection401            Section {402                if !isRevoked {403                    Button("Révoquer le lien", role: .destructive) { confirmRevoke = true }404                        .accessibilityIdentifier("deposit.revoke")405                }406                Button("Supprimer le lien", role: .destructive) { confirmDelete = true }407                    .accessibilityIdentifier("deposit.delete")408            } footer: {409                Text("Les fichiers déjà reçus restent dans ton Drive, même après la révocation ou la suppression du lien.")410            }411        }412        .navigationTitle(link.title)413        .navigationBarTitleDisplayMode(.inline)414        .disabled(busy)415        .navigationDestination(for: DepositSubmissionRoute.self) { DepositSubmissionDetailView(route: $0) }416        .refreshable { await reload(); await loadSubmissions() }417        .task { await loadSubmissions() }418        .confirmationDialog("Générer un nouveau lien ?", isPresented: $confirmRotate, titleVisibility: .visible) {419            Button("Générer un nouveau lien") { Task { await rotate() } }420            Button("Annuler", role: .cancel) {}421        } message: {422            Text("L’adresse actuelle cessera de fonctionner immédiatement. Les personnes qui doivent encore déposer devront recevoir la nouvelle.")423        }424        .confirmationDialog("Révoquer ce lien de dépôt ?", isPresented: $confirmRevoke, titleVisibility: .visible) {425            Button("Révoquer", role: .destructive) { Task { await revoke() } }426            Button("Annuler", role: .cancel) {}427        } message: {428            Text("Plus personne ne pourra déposer avec ce lien. Les fichiers reçus restent dans ton Drive.")429        }430        .confirmationDialog("Supprimer ce lien de dépôt ?", isPresented: $confirmDelete, titleVisibility: .visible) {431            Button("Supprimer le lien", role: .destructive) { Task { await purge() } }432            Button("Annuler", role: .cancel) {}433        } message: {434            Text("Le lien et l’historique de ses dépôts seront effacés. Les fichiers reçus restent dans ton Drive.")435        }436    }437438    private var summarySection: some View {439        Section {440            HStack(spacing: 12) {441                KindIcon(kind: .folder, size: 44)442                VStack(alignment: .leading, spacing: 4) {443                    Text(link.folderName ?? "Dossier supprimé").font(.headline).lineLimit(2)444                    LinkStatusChip(depositState: link.state)445                }446            }447            .accessibilityElement(children: .combine)448            LabeledContent("Dépôts reçus", value: link.maxSubmissions.map { "\(link.submissions) sur \($0)" } ?? "\(link.submissions)")449            LabeledContent("Volume reçu", value: "\(link.bytesReceived.byteString) sur \(DepositForm.sizeLabel(link.maxTotalBytes))")450            LabeledContent("Créé", value: link.createdAt.linkDateTime)451            if let e = link.expiresAt { LabeledContent(e < .now ? "Expiré" : "Expire", value: e.linkDateTime) }452            if let r = link.revokedAt { LabeledContent("Révoqué", value: r.linkDateTime) }453            if !link.allowedExtensions.isEmpty { LabeledContent("Types acceptés", value: link.allowedExtensions.joined(separator: ", ")) }454            if !targetMissing {455                NavigationLink(value: FolderRoute(id: link.folderId)) { Label("Voir les fichiers reçus", systemImage: "folder") }456                    .accessibilityIdentifier("deposit.openFolder")457            }458            if !isRevoked {459                Button {460                    Task { await setActive(!link.active) }461                } label: {462                    Label(link.active ? "Mettre en pause" : "Reprendre les dépôts", systemImage: link.active ? "pause.circle" : "play.circle")463                }464                .accessibilityIdentifier("deposit.pause")465            }466        } footer: {467            if !isRevoked, !link.active { Text("En pause : la page de dépôt refuse les envois jusqu’à la reprise.") }468        }469    }470471    private var passwordSection: some View {472        Section {473            LabeledContent("Mot de passe", value: link.hasPassword ? "Activé" : "Aucun")474            SecureField(link.hasPassword ? "Nouveau mot de passe" : "Ajouter un mot de passe", text: $newPassword)475                .textContentType(.newPassword)476            if link.hasPassword {477                Button("Retirer le mot de passe", role: .destructive) { Task { await removePassword() } }478            }479        } footer: {480            if !passwordValid { Text("Le mot de passe doit compter au moins 4 caractères.").foregroundStyle(.red) }481        }482    }483484    @ViewBuilder private var submissionsSection: some View {485        Section("Dépôts") {486            switch submissionsPhase {487            case .loading:488                HStack { ProgressView(); Text("Chargement…").foregroundStyle(.secondary) }489            case .offline:490                Label("Connexion requise pour voir les dépôts.", systemImage: "wifi.slash").foregroundStyle(.secondary)491            case .failed(let message):492                Label(message, systemImage: "exclamationmark.triangle").foregroundStyle(.secondary)493            case .ready:494                if submissions.isEmpty { Text("Aucun dépôt reçu pour l’instant.").foregroundStyle(.secondary) }495                ForEach(submissions) { s in496                    NavigationLink(value: DepositSubmissionRoute(id: s.id, ref: s.ref)) { DepositSubmissionRow(submission: s) }497                }498            }499        }500        .accessibilityIdentifier("deposit.submissions")501    }502503    private func adopt(_ l: DepositLink) {504        link = l505        form = DepositForm(link: l)506        newPassword = ""507    }508509    /// Re-reads the link (state, counters) from the server.510    private func reload() async {511        guard let fresh = try? await model.api.depositLinks().first(where: { $0.id == link.id }) else { return }512        if isDirty { link = fresh } else { adopt(fresh) }513    }514515    private func loadSubmissions() async {516        do {517            submissions = try await model.api.depositSubmissions(linkID: link.id)518            submissionsPhase = .ready519        } catch {520            if let p = LinkLoadPhase.failure(error), submissions.isEmpty { submissionsPhase = p }521        }522    }523524    private func save() async {525        var s = form.changes(from: link)526        if !newPassword.isEmpty { s.password = .some(newPassword) }527        busy = true528        defer { busy = false }529        await model.perform(success: "Réglages enregistrés") {530            adopt(try await model.api.updateDepositLink(id: link.id, settings: s))531        }532    }533534    private func removePassword() async {535        var s = DepositSettings()536        s.password = .some(nil)537        busy = true538        defer { busy = false }539        await model.perform(success: "Mot de passe retiré") {540            link = try await model.api.updateDepositLink(id: link.id, settings: s)541            newPassword = ""542        }543    }544545    private func setActive(_ active: Bool) async {546        var s = DepositSettings()547        s.active = active548        busy = true549        defer { busy = false }550        await model.perform(success: active ? "Dépôts repris" : "Lien mis en pause") {551            link = try await model.api.updateDepositLink(id: link.id, settings: s)552        }553    }554555    private func rotate() async {556        busy = true557        defer { busy = false }558        await model.perform {559            revealedURL = try await model.api.rotateDepositLink(id: link.id)560            Haptics.success()561        }562    }563564    private func revoke() async {565        busy = true566        defer { busy = false }567        await model.perform(success: "Lien révoqué") {568            try await model.api.revokeDepositLink(id: link.id)569            revealedURL = nil570        }571        await reload()572    }573574    private func purge() async {575        busy = true576        defer { busy = false }577        await model.perform(success: "Lien supprimé") {578            try await model.api.revokeDepositLink(id: link.id, purge: true)579            dismiss()580        }581    }582}583584/// One deposit in the list of a link.585private struct DepositSubmissionRow: View {586    let submission: DepositSubmission587588    private var sender: String {589        let parts = [submission.name, submission.email].filter { !$0.isEmpty }590        return parts.isEmpty ? "Déposant anonyme" : parts.joined(separator: " · ")591    }592593    var body: some View {594        VStack(alignment: .leading, spacing: 4) {595            HStack {596                Text(submission.ref).font(.subheadline.monospaced().weight(.semibold))597                Spacer()598                Text(submission.createdAt.shortRelative).font(.caption).foregroundStyle(.secondary)599            }600            Text(sender).font(.footnote).foregroundStyle(.secondary).lineLimit(2)601            HStack(spacing: 10) {602                Label(submission.placed == 1 ? "1 reçu" : "\(submission.placed) reçus", systemImage: "checkmark.circle").foregroundStyle(.green)603                if submission.rejected > 0 {604                    Label(submission.rejected == 1 ? "1 refusé" : "\(submission.rejected) refusés", systemImage: "xmark.octagon").foregroundStyle(.red)605                }606                Text(submission.bytes.byteString).foregroundStyle(.secondary)607            }608            .font(.caption)609        }610        .padding(.vertical, 2)611        .accessibilityElement(children: .combine)612    }613}614615/// The files of one deposit, each with what the server did with it.616struct DepositSubmissionDetailView: View {617    @Environment(AppModel.self) private var model618    let route: DepositSubmissionRoute619    @State private var detail: DepositSubmissionDetail?620    @State private var phase: LinkLoadPhase = .loading621622    var body: some View {623        Group {624            if let detail {625                List {626                    Section {627                        LabeledContent("Référence", value: detail.ref)628                        if !detail.name.isEmpty { LabeledContent("Nom", value: detail.name) }629                        if !detail.email.isEmpty { LabeledContent("Courriel", value: detail.email) }630                        LabeledContent("Reçu", value: detail.createdAt.linkDateTime)631                        LabeledContent("État", value: Self.statusLabel(detail.status))632                        if let folder = detail.folderId {633                            NavigationLink(value: FolderRoute(id: folder)) { Label("Ouvrir le dossier de ce dépôt", systemImage: "folder") }634                                .accessibilityIdentifier("submission.openFolder")635                        }636                    }637                    Section(detail.items.count == 1 ? "1 fichier" : "\(detail.items.count) fichiers") {638                        ForEach(detail.items) { item in639                            HStack(spacing: 12) {640                                KindIcon(kind: FileKind(extension: (item.name as NSString).pathExtension.lowercased()), size: 32)641                                VStack(alignment: .leading, spacing: 3) {642                                    Text(item.name).lineLimit(2)643                                    Text(item.size.byteString).font(.caption).foregroundStyle(.secondary)644                                    if let code = item.rejectCode, !code.isEmpty {645                                        Text(Self.rejectLabel(code)).font(.caption).foregroundStyle(.red)646                                    }647                                }648                                Spacer(minLength: 8)649                                itemChip(item.status)650                            }651                            .accessibilityElement(children: .combine)652                        }653                    }654                }655                .refreshable { await load() }656            } else {657                switch phase {658                case .offline:659                    EmptyState(symbol: "wifi.slash", title: "Connexion requise", message: "Le détail d’un dépôt se lit sur le serveur. Reconnecte-toi pour l’afficher.", action: ("Réessayer", { Task { await load() } }))660                case .failed(let message):661                    EmptyState(symbol: "exclamationmark.triangle", title: "Dépôt indisponible", message: message, action: ("Réessayer", { Task { await load() } }))662                default:663                    ProgressView("Chargement…")664                }665            }666        }667        .navigationTitle("Dépôt \(route.ref)")668        .navigationBarTitleDisplayMode(.inline)669        .task { await load() }670    }671672    private func itemChip(_ status: String) -> LinkStatusChip {673        switch status {674        case "placed": LinkStatusChip(label: "Reçu", color: .green)675        case "rejected": LinkStatusChip(label: "Refusé", color: .red)676        case "pending", "uploading", "scanning": LinkStatusChip(label: "En cours", color: .orange)677        default: LinkStatusChip(label: status, color: .gray)678        }679    }680681    static func statusLabel(_ status: String) -> String {682        switch status {683        case "completed", "complete", "done": "Terminé"684        case "pending", "open", "uploading": "En cours"685        case "rejected": "Refusé"686        case "expired": "Expiré"687        default: status688        }689    }690691    static func rejectLabel(_ code: String) -> String {692        switch code {693        case "infected": "Signalé par l’antivirus"694        case "file_too_large", "too_large": "Fichier trop volumineux"695        case "extension", "bad_extension", "extension_not_allowed": "Type de fichier non accepté"696        case "quota", "quota_exceeded": "Espace insuffisant sur le Drive"697        case "total_exceeded", "full": "Limite totale du lien atteinte"698        default: "Refusé (\(code))"699        }700    }701702    private func load() async {703        do {704            detail = try await model.api.depositSubmission(id: route.id)705            phase = .ready706        } catch {707            if let p = LinkLoadPhase.failure(error), detail == nil { phase = p }708        }709    }710}711
Files main
Menu

Theme