Repository Public
1// Author: Simon-Pierre Boucher — contact@spboucher.ai2// File: Features/Next/NextSupport.swift3// Description: What the SP Drive 2.0 screens share: turning the server's 2.0 objects into the app's items, French wording of the 2.0 errors and activity events, a row for a file that comes from a 2.0 answer, highlighted search snippets.4import SPDriveCore5import SPDriveNext6import SwiftUI78extension NextFile {9 /// The app's item for this file: the mirror's when it knows the file, otherwise built from the answer.10 @MainActor func item(_ model: AppModel) -> DriveItem {11 if let known = model.item(id) { return known }12 return DriveItem(id: id, kind: .file, name: name, parentID: folderId, size: size, sha256: sha256 ?? "", versionID: versionId, versionSeq: versionSeq ?? 1, versionCount: versions ?? 1,13 contentAt: contentAt ?? updatedAt ?? Date(), createdAt: createdAt ?? Date(), updatedAt: updatedAt ?? Date(), starred: starred, trashedAt: trashedAt, rev: rev ?? 0,14 scan: scan ?? "clean", hasThumbnail: thumb, previewKind: kind ?? "none")15 }16}17extension NextFolder {18 @MainActor func item(_ model: AppModel) -> DriveItem {19 model.item(id) ?? DriveItem(id: id, kind: .folder, name: name, parentID: parentId, createdAt: createdAt ?? Date(), updatedAt: updatedAt ?? Date(), starred: starred, trashedAt: trashedAt, rev: rev ?? 0)20 }21}2223enum NextText {24 /// A sentence for an error of the 2.0 endpoints.25 static func error(_ error: Error) -> String {26 let e = NextError.wrap(error)27 switch e.code {28 case "offline": return "Serveur injoignable. Réessayez une fois la connexion revenue."29 case "unauthenticated": return "La session est terminée. Reconnectez-vous."30 case "forbidden": return "Votre rôle dans ce dossier partagé ne permet pas cette action."31 case "not_found": return "Introuvable : l’élément a été supprimé, déplacé, ou l’accès a été retiré."32 case "rate_limited": return "Trop de demandes en peu de temps : réessayez dans un instant."33 case "busy": return "Le modèle du serveur est occupé\(e.retryAfterSeconds.map { " : réessayez dans \(Int($0)) s" } ?? " : réessayez dans un instant")."34 case "too_many_streams": return "Le serveur a atteint son nombre maximal de connexions en direct ; la synchronisation continue par vérification périodique."35 case "too_many_pending_uploads": return "Trop d’envois inachevés dans ce dossier partagé : terminez-les ou attendez leur expiration (24 h)."36 case "ai_unavailable": return "Aucun modèle n’est configuré sur ce serveur."37 case "ai_external_disabled": return "Les fournisseurs externes ne sont pas autorisés (réglage du serveur ou de votre compte)."38 case "provider_not_configured": return "Ce fournisseur n’est pas configuré sur le serveur."39 case "provider_unknown", "model_unknown": return "Ce modèle n’est pas proposé par le serveur."40 case "ai_bad_answer": return "Le modèle a répondu dans un format inutilisable."41 case "provider_auth": return "Le serveur n’a pas pu s’authentifier auprès du fournisseur du modèle."42 case "provider_unreachable", "provider_unavailable": return "Le fournisseur du modèle ne répond pas."43 case "provider_rate_limited": return "Le fournisseur du modèle limite les demandes : réessayez plus tard."44 case "provider_refused": return "Le modèle a refusé de répondre à cette question."45 case "already_member": return "Cette personne a déjà accès à ce dossier."46 case "root_immutable": return "Le dossier racine ne peut pas être partagé."47 case "name_conflict": return "Ce nom est déjà pris."48 case "too_many_collections": return "Vous avez atteint le nombre maximal de collections (100)."49 case "invalid_request": return "Demande refusée par le serveur (valeur invalide)."50 case "quota_exceeded": return "Espace insuffisant chez le propriétaire du dossier."51 default: return e.errorDescription ?? e.code52 }53 }54 static func role(_ r: GrantRole) -> String { switch r { case .viewer: "Lecture"; case .editor: "Modification"; case .uploader: "Dépôt seulement" } }55 static func roleDetail(_ r: GrantRole) -> String {56 switch r { case .viewer: "Parcourir, lire, télécharger"; case .editor: "Lire, créer, renommer, déplacer, téléverser, mettre à la corbeille"; case .uploader: "Envoyer des fichiers, sans rien voir du dossier" }57 }58 static func kind(_ k: String) -> String {59 ["image": "Images", "pdf": "PDF", "document": "Documents", "sheet": "Feuilles de calcul", "video": "Vidéos", "audio": "Audio", "archive": "Archives", "text": "Texte", "other": "Autres"][k] ?? k60 }61 static func kindColor(_ k: String) -> Color {62 switch k { case "image": Color(red: 0.36, green: 0.62, blue: 0.95); case "pdf": Color(red: 0.86, green: 0.33, blue: 0.30); case "document": SPDTheme.brandIndigo; case "sheet": Color(red: 0.20, green: 0.62, blue: 0.42)63 case "video": Color(red: 0.80, green: 0.45, blue: 0.85); case "audio": Color(red: 0.93, green: 0.60, blue: 0.22); case "archive": Color(red: 0.55, green: 0.48, blue: 0.40); case "text": SPDTheme.brand; default: SPDTheme.textTertiary }64 }65 /// What happened, in words (API-NEXT §7.2).66 static func activity(_ e: ActivityEvent) -> (symbol: String, text: String) {67 let m = e.meta ?? [:]68 func n(_ key: String) -> Int { m[key]?.int ?? 0 }69 func items() -> String { let f = n("files"), d = n("folders"); return [f > 0 ? "\(f) fichier\(f > 1 ? "s" : "")" : nil, d > 0 ? "\(d) dossier\(d > 1 ? "s" : "")" : nil].compactMap { $0 }.joined(separator: " et ") }70 switch e.action {71 case "file.uploaded": return ("arrow.up.doc", "Fichier ajouté")72 case "file.version_added": return ("doc.badge.plus", "Nouvelle version")73 case "file.version_restored": return ("clock.arrow.circlepath", "Version \(n("from")) restaurée")74 case "file.version_deleted": return ("minus.circle", "Version supprimée")75 case "file.renamed", "folder.renamed": return ("pencil", m["from"]?.string.map { "Renommé (avant : « \($0) »)" } ?? "Renommé")76 case "ai.suggested": return ("sparkles", "Suggestions de rangement demandées")77 case "file.downloaded": return ("arrow.down.circle", "Téléchargé")78 case "folder.created": return ("folder.badge.plus", "Dossier créé")79 case "items.moved": return ("folder", "Déplacement de \(items())")80 case "items.copied": return ("plus.square.on.square", "Copie de \(items())")81 case "items.trashed": return ("trash", "Mise à la corbeille de \(items())")82 case "items.restored": return ("arrow.uturn.backward", "Restauration de \(items())")83 case "items.purged": return ("trash.slash", m["all"]?.bool == true ? "Corbeille vidée" : "Suppression définitive de \(items())")84 case "zip.downloaded": return ("archivebox", "Archive téléchargée (\(n("files")) fichiers)")85 case "share.created": return ("link.badge.plus", "Lien de partage créé")86 case "share.updated": return ("link", "Lien de partage modifié")87 case "share.revoked": return ("link.badge.minus", "Lien de partage révoqué")88 case "share.deleted": return ("link.badge.minus", "Lien de partage retiré")89 case "share.rotated": return ("arrow.triangle.2.circlepath", "Adresse du lien renouvelée")90 case "submission.completed": return ("tray.and.arrow.down", "Dépôt reçu (\(n("placed")) fichier\(n("placed") > 1 ? "s" : ""))")91 case "scan.infected": return ("exclamationmark.shield", "Fichier bloqué par l’antivirus")92 case "collab.member_added": return ("person.badge.plus", "Membre ajouté (\(GrantRole(rawValue: m["role"]?.string ?? "").map(role) ?? "?"))")93 case "collab.member_updated": return ("person.crop.circle.badge.checkmark", "Rôle d’un membre modifié (\(GrantRole(rawValue: m["role"]?.string ?? "").map(role) ?? "?"))")94 case "collab.member_removed": return ("person.badge.minus", "Membre retiré")95 case "collab.workspace_named": return ("character.cursor.ibeam", "Espace de travail nommé")96 default: return ("circle", e.action)97 }98 }99 static func actor(_ e: ActivityEvent) -> String {100 switch e.actor.kind { case "system": "SP Drive"; case "anonymous": "Visiteur anonyme"; default: e.actor.me == true ? "Vous" : (e.actor.displayName ?? "Quelqu’un") }101 }102}103104/// A search snippet with its matched words set off (weight and a quiet wash — never colour alone).105struct SnippetText: View {106 let match: SearchMatch107 var body: some View {108 var out = AttributedString()109 for run in match.snippetRuns {110 var piece = AttributedString(run.text)111 if run.matched { piece.font = SPDTheme.Typo.callout.weight(.semibold); piece.foregroundColor = SPDTheme.textPrimary; piece.backgroundColor = SPDTheme.brandWash }112 out.append(piece)113 }114 return Text(out).font(SPDTheme.Typo.callout).foregroundStyle(SPDTheme.textSecondary).lineLimit(3)115 }116}117118/// One file of a 2.0 answer (collection, storage, duplicates, activity…): picture, name, where it is, and a trailing detail.119struct NextFileRow<Trailing: View>: View {120 let model: AppModel121 let file: NextFile122 var subtitle: String?123 @ViewBuilder var trailing: () -> Trailing124 var body: some View {125 let item = file.item(model)126 HStack(spacing: SPDTheme.Space.sm) {127 ItemThumbnail(model: model, item: item, side: 24)128 VStack(alignment: .leading, spacing: 1) {129 Text(file.name).font(SPDTheme.Typo.body).lineLimit(1).truncationMode(.middle)130 Text(subtitle ?? location(item)).font(SPDTheme.Typo.caption).foregroundStyle(SPDTheme.textTertiary).lineLimit(1).truncationMode(.head)131 }132 Spacer(minLength: SPDTheme.Space.sm)133 trailing()134 }135 .accessibilityElement(children: .combine)136 }137 private func location(_ item: DriveItem) -> String {138 let path = model.path(to: item.id).dropLast().map(\.name).joined(separator: " › ")139 return path.isEmpty ? "Mon Drive" : "Mon Drive › " + path140 }141}142extension NextFileRow where Trailing == Text {143 init(model: AppModel, file: NextFile, subtitle: String? = nil) { self.init(model: model, file: file, subtitle: subtitle) { Text(Fmt.bytes(file.size)).font(SPDTheme.Typo.caption).foregroundStyle(SPDTheme.textSecondary).monospacedDigit() } }144}145extension AppModel {146 /// Shows a file of a 2.0 answer in the browser: its folder, with the file selected.147 func show(_ file: NextFile, in nav: Navigator) {148 nav.searchText = ""; nav.go(to: file.folderId == rootID ? nil : file.folderId); nav.selection = [file.id]149 }150}151152/// Loading, failing or showing: the three states of a screen fed by one request.153enum Loadable<T> { case loading, failed(String), ready(T)154 var value: T? { if case .ready(let v) = self { return v }; return nil }155}156