Repository Public
1// SP Drive iOS2// File: Features/Shared/ShareLinkEditor.swift3// Description: Share links of a file or folder: creation sheet, detail screen (settings, rotation, revocation, access log), and the4// small views shared by every link screen (status chip, one-time URL card, expiry fields).5//6// Author: Simon-Pierre Boucher7// Contact: contact@spboucher.ai8import SwiftUI9import UIKit1011// MARK: - Shared pieces of the link screens1213/// Loading state of a list that only exists on the server.14enum LinkLoadPhase: Equatable {15 case loading, ready, offline16 case failed(String)1718 /// Phase for a failed load; `nil` when the load was merely cancelled (the previous state stays).19 @MainActor static func failure(_ error: Error) -> LinkLoadPhase? {20 if error is CancellationError { return nil }21 if let e = error as? RemoteError, e == .offline { return .offline }22 return .failed(AppModel.describe(error))23 }24}2526/// Coloured capsule for the state of a share link, a deposit link or a deposited file.27struct LinkStatusChip: View {28 let label: String29 let color: Color3031 init(label: String, color: Color) { self.label = label; self.color = color }3233 init(shareStatus: String) {34 switch shareStatus {35 case "active": self.init(label: "Actif", color: .green)36 case "revoked": self.init(label: "Révoqué", color: .red)37 case "expired": self.init(label: "Expiré", color: .orange)38 case "exhausted": self.init(label: "Épuisé", color: .orange)39 case "target_missing": self.init(label: "Cible supprimée", color: .gray)40 default: self.init(label: shareStatus, color: .gray)41 }42 }4344 init(depositState: String) {45 switch depositState {46 case "open": self.init(label: "Ouvert", color: .green)47 case "paused": self.init(label: "En pause", color: .orange)48 case "revoked": self.init(label: "Révoqué", color: .red)49 case "expired": self.init(label: "Expiré", color: .orange)50 case "full": self.init(label: "Plein", color: .orange)51 case "target_missing": self.init(label: "Dossier supprimé", color: .gray)52 default: self.init(label: depositState, color: .gray)53 }54 }5556 var body: some View {57 Text(label)58 .font(.caption.weight(.semibold))59 .foregroundStyle(color)60 .padding(.horizontal, 8).padding(.vertical, 3)61 .background(color.opacity(0.15), in: Capsule())62 .accessibilityLabel("État : \(label)")63 }64}6566/// The URL of a link right after its creation or rotation: the only moment the server gives it in clear.67struct LinkRevealView: View {68 let url: URL69 /// Subject proposed to the system share sheet.70 let subject: String71 /// Accessibility identifier of the URL text ("share.url", "deposit.url").72 let identifier: String73 @State private var copied = false74 @State private var showingQR = false7576 var body: some View {77 VStack(alignment: .leading, spacing: 12) {78 Label("Ton lien est prêt", systemImage: "checkmark.seal.fill")79 .font(.headline)80 .foregroundStyle(.green)81 Text(url.absoluteString)82 .font(.callout.monospaced())83 .textSelection(.enabled)84 .padding(12)85 .frame(maxWidth: .infinity, alignment: .leading)86 .background(.quaternary.opacity(0.5), in: RoundedRectangle(cornerRadius: Theme.corner, style: .continuous))87 .accessibilityLabel("Adresse du lien")88 .accessibilityValue(url.absoluteString)89 .accessibilityIdentifier(identifier)90 HStack(spacing: 12) {91 Button {92 UIPasteboard.general.string = url.absoluteString93 Haptics.success()94 copied = true95 } label: {96 Label(copied ? "Copié" : "Copier", systemImage: copied ? "checkmark" : "doc.on.doc").frame(maxWidth: .infinity)97 }98 .buttonStyle(.borderedProminent)99 .accessibilityIdentifier("\(identifier).copy")100 SwiftUI.ShareLink(item: url, subject: Text(subject)) {101 Label("Partager", systemImage: "square.and.arrow.up").frame(maxWidth: .infinity)102 }103 .buttonStyle(.bordered)104 .accessibilityIdentifier("\(identifier).share")105 }106 // the QR code is drawn on this device from the link above: scanning it opens the same address107 Button { withAnimation { showingQR.toggle() } } label: { Label(showingQR ? "Masquer le code QR" : "Afficher le code QR", systemImage: "qrcode") }108 .buttonStyle(.bordered)109 .accessibilityIdentifier("\(identifier).qrToggle")110 if showingQR { QRCodeView(url: url).frame(maxWidth: .infinity) }111 Label("Copie-le maintenant : pour ta sécurité, ce lien ne sera plus jamais affiché. Si tu le perds, tu devras en générer un nouveau.", systemImage: "exclamationmark.triangle.fill")112 .font(.footnote)113 .foregroundStyle(.orange)114 }115 .padding(.vertical, 4)116 .task(id: copied) {117 guard copied else { return }118 try? await Task.sleep(for: .seconds(2))119 copied = false120 }121 }122}123124/// Optional expiry date: a switch, then a date in the future.125struct LinkExpiryFields: View {126 @Binding var enabled: Bool127 @Binding var date: Date128129 nonisolated static var defaultDate: Date { Calendar.current.date(byAdding: .day, value: 7, to: .now) ?? .now.addingTimeInterval(7 * 86_400) }130131 var body: some View {132 Toggle("Date d’expiration", isOn: $enabled)133 if enabled {134 DatePicker("Expire le", selection: $date, in: Date.now..., displayedComponents: [.date, .hourAndMinute])135 }136 }137}138139/// Sheets sit above the root view, so they show the app's toast themselves.140private struct SheetToastModifier: ViewModifier {141 @Environment(AppModel.self) private var model142 func body(content: Content) -> some View {143 @Bindable var model = model144 content.toast($model.toast)145 }146}147148extension View {149 /// Shows the app-wide toast (errors of `model.perform`) inside a sheet.150 func sheetToast() -> some View { modifier(SheetToastModifier()) }151}152153extension Date {154 /// "12 nov. 2026 à 14:32" — for detail screens.155 var linkDateTime: String { formatted(date: .abbreviated, time: .shortened) }156}157158/// One share link in a list.159struct ShareLinkRow: View {160 let share: ShareLink161 /// Show the target (lists of all links) or the label (links of one item).162 var showsTarget = true163164 private var kind: FileKind { share.type == "folder" ? .folder : FileKind(extension: (share.targetName as NSString).pathExtension.lowercased()) }165 private var title: String {166 if showsTarget { return share.targetName.isEmpty ? "Élément supprimé" : share.targetName }167 return share.label.isEmpty ? "Lien du \(share.createdAt.shortRelative)" : share.label168 }169 private var expiryText: String? {170 guard let e = share.expiresAt else { return nil }171 return e < .now ? "Expiré le \(e.linkDateTime)" : "Expire le \(e.linkDateTime)"172 }173174 var body: some View {175 HStack(spacing: 12) {176 KindIcon(kind: kind)177 VStack(alignment: .leading, spacing: 4) {178 Text(title).font(.body).lineLimit(2)179 if showsTarget, !share.label.isEmpty { Text(share.label).font(.footnote).foregroundStyle(.secondary).lineLimit(1) }180 HStack(spacing: 10) {181 LinkStatusChip(shareStatus: share.status)182 Label("\(share.viewCount)", systemImage: "eye")183 .accessibilityLabel("\(share.viewCount) consultations")184 if share.canDownload {185 Label("\(share.downloadCount)", systemImage: "arrow.down.circle")186 .accessibilityLabel("\(share.downloadCount) téléchargements")187 }188 if share.hasPassword { Image(systemName: "lock.fill").accessibilityLabel("Protégé par mot de passe") }189 }190 .font(.caption)191 .foregroundStyle(.secondary)192 if let expiryText { Text(expiryText).font(.caption).foregroundStyle(.secondary) }193 }194 }195 .padding(.vertical, 2)196 .accessibilityElement(children: .combine)197 }198}199200// MARK: - Creation sheet201202/// Sheet « Partager »: the links that already exist for an item, and the form that creates a new one.203struct ShareLinkEditor: View {204 @Environment(AppModel.self) private var model205 @Environment(\.dismiss) private var dismiss206 private let item: DriveItem207208 @State private var existing: [ShareLink] = []209 @State private var phase: LinkLoadPhase = .loading210 @State private var createdURL: URL?211 @State private var isCreating = false212213 @State private var label = ""214 @State private var canDownload = true215 @State private var password = ""216 @State private var expiryEnabled = false217 @State private var expiry = LinkExpiryFields.defaultDate218 @State private var maxViews: Int?219 @State private var maxDownloads: Int?220 @State private var singleUse = false221222 init(item: DriveItem) { self.item = item }223224 /// Why this item cannot be shared from here, if it cannot.225 private var blocker: String? {226 if item.parentID == nil { return "La racine du Drive ne peut pas être partagée. Partage plutôt un dossier ou un fichier." }227 if item.isLocalOnly { return "Cet élément n’est pas encore sur le Drive. Tu pourras le partager dès qu’il sera synchronisé." }228 if item.isTrashed { return "Un élément dans la corbeille ne peut pas être partagé." }229 return nil230 }231 private var passwordValid: Bool { password.isEmpty || password.count >= 4 }232 private var limitsValid: Bool { (maxViews ?? 1) > 0 && (maxDownloads ?? 1) > 0 }233 private var canCreate: Bool { passwordValid && limitsValid && !isCreating }234235 var body: some View {236 NavigationStack {237 Form {238 Section {239 HStack(spacing: 12) {240 KindIcon(kind: item.kind, size: 44)241 VStack(alignment: .leading, spacing: 2) {242 Text(item.name).font(.headline).lineLimit(2)243 Text(item.isFolder ? "Dossier" : "\(item.kind.label) · \(item.size.byteString)").font(.footnote).foregroundStyle(.secondary)244 }245 }246 .accessibilityElement(children: .combine)247 }248 if let blocker {249 Section { Label(blocker, systemImage: "info.circle").foregroundStyle(.secondary) }250 } else if let createdURL {251 Section {252 LinkRevealView(url: createdURL, subject: item.name, identifier: "share.url")253 Button("Créer un autre lien") { resetForm() }254 .accessibilityIdentifier("share.createAnother")255 }256 } else {257 creationForm258 }259 existingSection260 }261 .navigationTitle("Partager")262 .navigationBarTitleDisplayMode(.inline)263 .toolbar { ToolbarItem(placement: .cancellationAction) { Button("Fermer") { dismiss() }.accessibilityIdentifier("share.close") } }264 .navigationDestination(for: ShareLink.self) { ShareLinkDetailView(share: $0) }265 .task { await loadExisting() }266 }267 .sheetToast()268 }269270 @ViewBuilder private var creationForm: some View {271 Section {272 TextField("Nom du lien (facultatif)", text: $label)273 .accessibilityIdentifier("share.label")274 Toggle("Autoriser le téléchargement", isOn: $canDownload)275 .accessibilityIdentifier("share.canDownload")276 } header: {277 Text("Nouveau lien")278 } footer: {279 Text(canDownload ? "Les personnes qui ont le lien peuvent consulter et télécharger." : "Consultation seulement : le téléchargement est bloqué par le serveur.")280 }281 Section {282 SecureField("Mot de passe (facultatif)", text: $password)283 .textContentType(.newPassword)284 .accessibilityIdentifier("share.password")285 LinkExpiryFields(enabled: $expiryEnabled, date: $expiry)286 } header: {287 Text("Protection")288 } footer: {289 if !passwordValid { Text("Le mot de passe doit compter au moins 4 caractères.").foregroundStyle(.red) }290 }291 Section {292 LabeledContent("Consultations max.") {293 TextField("Illimité", value: $maxViews, format: .number).keyboardType(.numberPad).multilineTextAlignment(.trailing)294 }295 if canDownload {296 LabeledContent("Téléchargements max.") {297 TextField("Illimité", value: $maxDownloads, format: .number).keyboardType(.numberPad).multilineTextAlignment(.trailing)298 }299 }300 Toggle("Usage unique", isOn: $singleUse)301 } header: {302 Text("Limites")303 } footer: {304 if !limitsValid { Text("Une limite doit être d’au moins 1.").foregroundStyle(.red) }305 else { Text("Usage unique : le lien cesse de fonctionner après sa première utilisation.") }306 }307 Section {308 Button {309 Task { await create() }310 } label: {311 if isCreating { ProgressView().tint(.white) } else { Label("Créer le lien", systemImage: "link.badge.plus") }312 }313 .buttonStyle(GradientButtonStyle())314 .disabled(!canCreate)315 .listRowInsets(EdgeInsets())316 .listRowBackground(Color.clear)317 .accessibilityIdentifier("share.create")318 }319 }320321 @ViewBuilder private var existingSection: some View {322 Section {323 switch phase {324 case .loading:325 HStack { ProgressView(); Text("Chargement des liens…").foregroundStyle(.secondary) }326 case .offline:327 Label("Connexion requise pour voir et créer des liens.", systemImage: "wifi.slash").foregroundStyle(.secondary)328 case .failed(let message):329 Label(message, systemImage: "exclamationmark.triangle").foregroundStyle(.secondary)330 Button("Réessayer") { Task { await loadExisting() } }331 case .ready:332 if existing.isEmpty {333 Text("Aucun lien pour cet élément.").foregroundStyle(.secondary)334 } else {335 ForEach(existing) { share in336 NavigationLink(value: share) { ShareLinkRow(share: share, showsTarget: false) }337 }338 }339 }340 } header: {341 Text("Liens existants")342 } footer: {343 if phase == .ready, !existing.isEmpty { Text("L’adresse d’un lien existant ne peut plus être affichée. Ouvre un lien pour en générer une nouvelle.") }344 }345 }346347 private func resetForm() {348 createdURL = nil349 label = ""; canDownload = true; password = ""; expiryEnabled = false; expiry = LinkExpiryFields.defaultDate350 maxViews = nil; maxDownloads = nil; singleUse = false351 }352353 private func loadExisting() async {354 guard blocker == nil else { phase = .ready; return }355 do {356 existing = try await model.api.shares(fileID: item.isFolder ? nil : item.id, folderID: item.isFolder ? item.id : nil)357 phase = .ready358 } catch {359 if let p = LinkLoadPhase.failure(error), existing.isEmpty || p == .offline { phase = p }360 }361 }362363 private func create() async {364 guard canCreate else { return }365 isCreating = true366 defer { isCreating = false }367 var settings = ShareSettings()368 let name = label.trimmingCharacters(in: .whitespacesAndNewlines)369 if !name.isEmpty { settings.label = name }370 settings.canDownload = canDownload371 if !password.isEmpty { settings.password = .some(password) }372 if expiryEnabled { settings.expiresAt = .some(expiry) }373 if let maxViews { settings.maxViews = .some(maxViews) }374 if canDownload, let maxDownloads { settings.maxDownloads = .some(maxDownloads) }375 settings.singleUse = singleUse376 await model.perform {377 let result = try await model.api.createShare(item: item, settings: settings)378 createdURL = result.url379 password = ""380 Haptics.success()381 }382 await loadExisting()383 }384}385386// MARK: - Detail387388/// One share link: its state, its settings, a new URL on demand, revocation, deletion, and who used it.389struct ShareLinkDetailView: View {390 @Environment(AppModel.self) private var model391 @Environment(\.dismiss) private var dismiss392 @State private var share: ShareLink393 @State private var revealedURL: URL?394 @State private var events: [ShareEvent] = []395 @State private var eventsPhase: LinkLoadPhase = .loading396 @State private var busy = false397 @State private var confirmRotate = false398 @State private var confirmRevoke = false399 @State private var confirmDelete = false400401 @State private var label: String402 @State private var canDownload: Bool403 @State private var newPassword = ""404 @State private var expiryEnabled: Bool405 @State private var expiry: Date406 @State private var maxViews: Int?407 @State private var maxDownloads: Int?408 @State private var singleUse: Bool409410 init(share: ShareLink) {411 _share = State(initialValue: share)412 _label = State(initialValue: share.label)413 _canDownload = State(initialValue: share.canDownload)414 _expiryEnabled = State(initialValue: share.expiresAt != nil)415 _expiry = State(initialValue: share.expiresAt ?? LinkExpiryFields.defaultDate)416 _maxViews = State(initialValue: share.maxViews)417 _maxDownloads = State(initialValue: share.maxDownloads)418 _singleUse = State(initialValue: share.singleUse)419 }420421 private var isRevoked: Bool { share.revokedAt != nil || share.status == "revoked" }422 private var kind: FileKind { share.type == "folder" ? .folder : FileKind(extension: (share.targetName as NSString).pathExtension.lowercased()) }423 private var passwordValid: Bool { newPassword.isEmpty || newPassword.count >= 4 }424 private var limitsValid: Bool { (maxViews ?? 1) > 0 && (maxDownloads ?? 1) > 0 }425 private var isDirty: Bool {426 label != share.label || canDownload != share.canDownload || !newPassword.isEmpty427 || expiryEnabled != (share.expiresAt != nil) || (expiryEnabled && expiry != share.expiresAt)428 || maxViews != share.maxViews || maxDownloads != share.maxDownloads || singleUse != share.singleUse429 }430431 var body: some View {432 Form {433 summarySection434 if let revealedURL {435 Section { LinkRevealView(url: revealedURL, subject: share.targetName, identifier: "share.url") }436 }437 if !isRevoked {438 settingsSection439 linkSection440 }441 eventsSection442 dangerSection443 }444 .navigationTitle(share.label.isEmpty ? "Lien de partage" : share.label)445 .navigationBarTitleDisplayMode(.inline)446 .disabled(busy)447 .refreshable { await reload(); await loadEvents() }448 .task { await loadEvents() }449 .confirmationDialog("Générer un nouveau lien ?", isPresented: $confirmRotate, titleVisibility: .visible) {450 Button("Générer un nouveau lien") { Task { await rotate() } }451 Button("Annuler", role: .cancel) {}452 } message: {453 Text("L’adresse actuelle cessera de fonctionner immédiatement. Les personnes qui l’ont déjà devront recevoir la nouvelle.")454 }455 .confirmationDialog("Révoquer ce lien ?", isPresented: $confirmRevoke, titleVisibility: .visible) {456 Button("Révoquer", role: .destructive) { Task { await revoke() } }457 Button("Annuler", role: .cancel) {}458 } message: {459 Text("Le lien cesse de fonctionner tout de suite. Son journal d’accès est conservé.")460 }461 .confirmationDialog("Supprimer ce lien ?", isPresented: $confirmDelete, titleVisibility: .visible) {462 Button("Supprimer le lien et son journal", role: .destructive) { Task { await purge() } }463 Button("Annuler", role: .cancel) {}464 } message: {465 Text("Le lien et son journal d’accès seront effacés définitivement. L’élément partagé reste dans ton Drive.")466 }467 }468469 private var summarySection: some View {470 Section {471 HStack(spacing: 12) {472 KindIcon(kind: kind, size: 44)473 VStack(alignment: .leading, spacing: 4) {474 Text(share.targetName.isEmpty ? "Élément supprimé" : share.targetName).font(.headline).lineLimit(2)475 LinkStatusChip(shareStatus: share.status)476 }477 }478 .accessibilityElement(children: .combine)479 LabeledContent("Consultations", value: share.maxViews.map { "\(share.viewCount) sur \($0)" } ?? "\(share.viewCount)")480 LabeledContent("Téléchargements", value: !share.canDownload ? "Bloqués" : share.maxDownloads.map { "\(share.downloadCount) sur \($0)" } ?? "\(share.downloadCount)")481 LabeledContent("Créé", value: share.createdAt.linkDateTime)482 LabeledContent("Dernier accès", value: share.lastAccessAt?.linkDateTime ?? "Jamais")483 if let e = share.expiresAt { LabeledContent(e < .now ? "Expiré" : "Expire", value: e.linkDateTime) }484 if let r = share.revokedAt { LabeledContent("Révoqué", value: r.linkDateTime) }485 }486 }487488 @ViewBuilder private var settingsSection: some View {489 Section {490 TextField("Nom du lien", text: $label)491 Toggle("Autoriser le téléchargement", isOn: $canDownload)492 LinkExpiryFields(enabled: $expiryEnabled, date: $expiry)493 LabeledContent("Consultations max.") {494 TextField("Illimité", value: $maxViews, format: .number).keyboardType(.numberPad).multilineTextAlignment(.trailing)495 }496 LabeledContent("Téléchargements max.") {497 TextField("Illimité", value: $maxDownloads, format: .number).keyboardType(.numberPad).multilineTextAlignment(.trailing)498 }499 Toggle("Usage unique", isOn: $singleUse)500 } header: {501 Text("Réglages")502 } footer: {503 if !limitsValid { Text("Une limite doit être d’au moins 1.").foregroundStyle(.red) }504 }505 Section {506 LabeledContent("Mot de passe", value: share.hasPassword ? "Activé" : "Aucun")507 SecureField(share.hasPassword ? "Nouveau mot de passe" : "Ajouter un mot de passe", text: $newPassword)508 .textContentType(.newPassword)509 if share.hasPassword {510 Button("Retirer le mot de passe", role: .destructive) { Task { await removePassword() } }511 }512 } footer: {513 if !passwordValid { Text("Le mot de passe doit compter au moins 4 caractères.").foregroundStyle(.red) }514 }515 Section {516 Button("Enregistrer les réglages") { Task { await save() } }517 .disabled(!isDirty || !passwordValid || !limitsValid)518 .accessibilityIdentifier("share.save")519 }520 }521522 private var linkSection: some View {523 Section {524 Button { confirmRotate = true } label: { Label("Générer un nouveau lien", systemImage: "arrow.triangle.2.circlepath") }525 .accessibilityIdentifier("share.rotate")526 } header: {527 Text("Adresse du lien")528 } footer: {529 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.")530 }531 }532533 @ViewBuilder private var eventsSection: some View {534 Section("Journal d’accès") {535 switch eventsPhase {536 case .loading:537 HStack { ProgressView(); Text("Chargement…").foregroundStyle(.secondary) }538 case .offline:539 Label("Connexion requise pour lire le journal.", systemImage: "wifi.slash").foregroundStyle(.secondary)540 case .failed(let message):541 Label(message, systemImage: "exclamationmark.triangle").foregroundStyle(.secondary)542 case .ready:543 if events.isEmpty { Text("Personne n’a encore utilisé ce lien.").foregroundStyle(.secondary) }544 ForEach(events) { ShareEventRow(event: $0) }545 }546 }547 }548549 private var dangerSection: some View {550 Section {551 if !isRevoked {552 Button("Révoquer le lien", role: .destructive) { confirmRevoke = true }553 .accessibilityIdentifier("share.revoke")554 }555 Button("Supprimer le lien et son journal", role: .destructive) { confirmDelete = true }556 .accessibilityIdentifier("share.delete")557 }558 }559560 private func adopt(_ s: ShareLink) {561 share = s562 label = s.label; canDownload = s.canDownload; newPassword = ""563 expiryEnabled = s.expiresAt != nil; expiry = s.expiresAt ?? LinkExpiryFields.defaultDate564 maxViews = s.maxViews; maxDownloads = s.maxDownloads; singleUse = s.singleUse565 }566567 /// Re-reads the link (counters, status) from the server.568 private func reload() async {569 let isFolder = share.type == "folder"570 guard let list = try? await model.api.shares(fileID: isFolder ? nil : share.targetId, folderID: isFolder ? share.targetId : nil),571 let fresh = list.first(where: { $0.id == share.id }) else { return }572 if isDirty { share = fresh } else { adopt(fresh) }573 }574575 private func loadEvents() async {576 do {577 events = try await model.api.shareEvents(id: share.id)578 eventsPhase = .ready579 } catch {580 if let p = LinkLoadPhase.failure(error), events.isEmpty { eventsPhase = p }581 }582 }583584 private func save() async {585 var s = ShareSettings()586 if label != share.label { s.label = label.trimmingCharacters(in: .whitespacesAndNewlines) }587 if canDownload != share.canDownload { s.canDownload = canDownload }588 if !newPassword.isEmpty { s.password = .some(newPassword) }589 if expiryEnabled != (share.expiresAt != nil) || (expiryEnabled && expiry != share.expiresAt) { s.expiresAt = .some(expiryEnabled ? expiry : nil) }590 if maxViews != share.maxViews { s.maxViews = .some(maxViews) }591 if maxDownloads != share.maxDownloads { s.maxDownloads = .some(maxDownloads) }592 if singleUse != share.singleUse { s.singleUse = singleUse }593 busy = true594 defer { busy = false }595 await model.perform(success: "Réglages enregistrés") {596 adopt(try await model.api.updateShare(id: share.id, settings: s))597 }598 }599600 private func removePassword() async {601 var s = ShareSettings()602 s.password = .some(nil)603 busy = true604 defer { busy = false }605 await model.perform(success: "Mot de passe retiré") {606 let fresh = try await model.api.updateShare(id: share.id, settings: s)607 if isDirty { share = fresh; newPassword = "" } else { adopt(fresh) }608 }609 }610611 private func rotate() async {612 busy = true613 defer { busy = false }614 await model.perform {615 revealedURL = try await model.api.rotateShare(id: share.id)616 Haptics.success()617 }618 await reload()619 }620621 private func revoke() async {622 busy = true623 defer { busy = false }624 await model.perform(success: "Lien révoqué") {625 try await model.api.revokeShare(id: share.id)626 revealedURL = nil627 }628 await reload()629 }630631 private func purge() async {632 busy = true633 defer { busy = false }634 await model.perform(success: "Lien supprimé") {635 try await model.api.revokeShare(id: share.id, purge: true)636 dismiss()637 }638 }639}640641/// One line of a share link's access log.642private struct ShareEventRow: View {643 let event: ShareEvent644645 private var title: String {646 switch event.kind {647 case "view", "open": "Consultation"648 case "download": "Téléchargement"649 case "preview": "Aperçu"650 case "password", "unlock": "Saisie du mot de passe"651 case "list": "Affichage du contenu"652 case "zip": "Téléchargement en archive"653 default: event.kind654 }655 }656657 var body: some View {658 HStack(alignment: .top, spacing: 12) {659 Image(systemName: event.ok ? "checkmark.circle.fill" : "xmark.octagon.fill")660 .foregroundStyle(event.ok ? .green : .red)661 .accessibilityLabel(event.ok ? "Accepté" : "Refusé")662 VStack(alignment: .leading, spacing: 2) {663 Text(title).font(.subheadline.weight(.medium))664 Text("\(event.at.linkDateTime) · \(event.ip)").font(.caption).foregroundStyle(.secondary)665 if !event.detail.isEmpty { Text(event.detail).font(.caption).foregroundStyle(.secondary) }666 if !event.userAgent.isEmpty { Text(event.userAgent).font(.caption2).foregroundStyle(.tertiary).lineLimit(2) }667 }668 }669 .accessibilityElement(children: .combine)670 }671}672