SPB Git

Repository Public

InsightsScreens.swift 28.9 KB 476 lines swift

1// =============================================================================2//                  SP BOUCHER | SOFTWARE & RESEARCH3//             ARTIFICIAL INTELLIGENCE • FINANCE • ENGINEERING4// =============================================================================5//6// PROJECT METADATA7// -----------------------------------------------------------------------------8// Project          : SP Drive pour iPhone et iPad9// File             : Features/Next/InsightsScreens.swift10// Description      : What happened and what exists: the activity of the11//                    account, of a file or of a folder (real audit events12//                    only); the timeline of a file's versions with restore and13//                    comparison (text diff, images and PDF side by side, a14//                    plain statement for other binaries); the devices signed in15//                    to the account; and, for administrators, the state of the16//                    infrastructure.17// Module           : Features18// Repository       : https://git.spboucher.ai/sp-drive-ios19// Created          : 2026-11-1920// Last Modified    : 2026-11-1921//22// =============================================================================23// AUTHOR & PROFESSIONAL AFFILIATION24// =============================================================================25//26// Author           : Simon-Pierre Boucher27// Position         : Professor of Finance28// Institution      : Université du Québec en Outaouais (UQO)29// Department       : Département des sciences administratives30// Organization     : SP Boucher31//32// Website          : https://spboucher.ai33// Git              : https://git.spboucher.ai34//35// =============================================================================36// OFFICIAL CONTACT DIRECTORY37// =============================================================================38//39// General          : info@spboucher.ai40// Professional     : contact@spboucher.ai41// Direct           : simon@spboucher.ai42// Research         : research@spboucher.ai43// Development      : dev@spboucher.ai44// Support          : support@spboucher.ai45// Security/Admin   : admin@spboucher.ai46// Notifications    : notifications@spboucher.ai47//48// Preferred Contact: support@spboucher.ai49//50// =============================================================================51// COPYRIGHT & INTELLECTUAL PROPERTY52// =============================================================================53//54// Copyright (c) 202655// Simon-Pierre Boucher56//57// All rights reserved where applicable.58//59// This file is governed by the applicable project license,60// copyright notices, institutional agreements and relevant law.61//62// Unless expressly authorized by the applicable license or63// rights holder, copying, redistribution, sublicensing,64// publication and commercial exploitation are not permitted.65//66// Existing third-party rights and notices remain unaffected.67//68// =============================================================================69// CONFIDENTIALITY & SECURITY70// =============================================================================71//72// Classification   : Public73// Distribution     : Public repository; use is governed by the project license74// Security Contact : admin@spboucher.ai75//76// Access to this source does not independently grant permission77// to redistribute or disclose confidential materials.78//79// Do not embed credentials, private keys, access tokens,80// certificates or confidential personal information.81//82// =============================================================================83// LICENSE & MAINTENANCE84// =============================================================================85//86// License          : None specified (no license file in this repository)87// Maintainer       : Simon-Pierre Boucher88// Technical Contact: dev@spboucher.ai89//90// =============================================================================91// END OF SP BOUCHER SOURCE HEADER92// =============================================================================9394import PDFKit95import SPDriveNext96import SwiftUI9798// MARK: Activity99100/// An audit event as the server sends it, including the target's name (API-NEXT D16 — not carried by the shared package's model).101struct ActivityLine: Decodable, Identifiable, Sendable {102    struct Actor: Decodable, Sendable { var kind: String; var displayName: String?; var me: Bool? }103    struct Target: Decodable, Sendable { var type: String; var id: String?; var name: String? }104    var id: String; var at: Date; var action: String; var actor: Actor; var target: Target?; var meta: [String: NextJSON]?105106    var symbol: String {107        switch action {108        case "file.uploaded": "arrow.up.doc"; case "file.version_added": "doc.badge.plus"; case "file.version_restored": "clock.arrow.circlepath"; case "file.version_deleted": "doc.badge.minus"109        case "file.renamed", "folder.renamed": "pencil"; case "file.downloaded", "zip.downloaded": "arrow.down.circle"; case "folder.created": "folder.badge.plus"110        case "items.moved": "folder"; case "items.copied": "plus.square.on.square"; case "items.trashed": "trash"; case "items.restored": "arrow.uturn.backward"; case "items.purged": "trash.slash"111        case "scan.infected": "exclamationmark.shield"; case "submission.completed": "tray.and.arrow.down"112        default: action.hasPrefix("share.") ? "link" : action.hasPrefix("collab.") ? "person.2" : "circle"113        }114    }115    private func count(_ key: String) -> Int { Int(meta?[key]?.double ?? 0) }116    private var things: String {117        let n = count("files") + count("folders")118        return n == 1 ? String(localized: "1 élément") : String(localized: "\(n) éléments")119    }120    var sentence: String {121        let name = target?.name.map { "« \($0) »" } ?? String(localized: "un élément")122        switch action {123        case "file.uploaded": return String(localized: "\(name) a été ajouté")124        case "file.version_added": return String(localized: "Nouvelle version de \(name)")125        case "file.version_restored": return String(localized: "Une ancienne version de \(name) a été restaurée")126        case "file.version_deleted": return String(localized: "Une version de \(name) a été supprimée")127        case "file.renamed", "folder.renamed": return meta?["from"]?.string.map { String(localized: "« \($0) » renommé en \(name)") } ?? String(localized: "\(name) a été renommé")128        case "file.downloaded": return String(localized: "\(name) a été téléchargé")129        case "zip.downloaded": return String(localized: "Une archive ZIP a été téléchargée")130        case "folder.created": return String(localized: "Dossier \(name) créé")131        case "items.moved": return String(localized: "\(things) déplacé(s)")132        case "items.copied": return String(localized: "\(things) copié(s)")133        case "items.trashed": return String(localized: "\(things) mis à la corbeille")134        case "items.restored": return String(localized: "\(things) restauré(s) de la corbeille")135        case "items.purged": return String(localized: "Suppression définitive depuis la corbeille")136        case "share.created": return String(localized: "Lien de partage créé")137        case "share.updated": return String(localized: "Lien de partage modifié")138        case "share.revoked", "share.deleted": return String(localized: "Lien de partage révoqué")139        case "share.rotated": return String(localized: "Adresse d’un lien de partage renouvelée")140        case "submission.completed": return String(localized: "Dépôt reçu par un lien de dépôt")141        case "scan.infected": return String(localized: "L’antivirus a signalé un fichier")142        case "collab.member_added": return String(localized: "Membre ajouté à \(name)")143        case "collab.member_updated": return String(localized: "Rôle d’un membre modifié dans \(name)")144        case "collab.member_removed": return String(localized: "Membre retiré de \(name)")145        default: return action146        }147    }148    var who: String {149        if actor.me == true { return String(localized: "Toi") }150        return actor.displayName ?? (actor.kind == "system" ? String(localized: "Le système") : actor.kind == "public" ? String(localized: "Un visiteur (lien)") : String(localized: "Quelqu’un"))151    }152}153struct ActivityLines: Decodable, Sendable { var events: [ActivityLine]; var more: Bool }154155/// Where an activity list comes from.156enum ActivitySource: Hashable {157    case account, file(String), folder(String)158    var path: String { switch self { case .account: "/activity"; case .file(let id): "/files/\(id)/activity"; case .folder(let id): "/folders/\(id)/activity" } }159}160161struct ActivityScreen: View {162    @Environment(AppModel.self) private var model163    let source: ActivitySource164    var title = String(localized: "Activité")165    @State private var state: Loadable<[ActivityLine]> = .loading166    @State private var more = false167    @State private var loadingMore = false168169    var body: some View {170        LoadingView(state: state, retry: { await load(reset: true) }) { events in171            if events.isEmpty {172                EmptyState(symbol: "clock", title: String(localized: "Aucune activité enregistrée"), message: String(localized: "Les ajouts, versions, renommages, déplacements, partages et suppressions apparaîtront ici. Seuls les évènements réellement journalisés par le serveur sont montrés."))173            } else {174                List {175                    ForEach(Self.byDay(events), id: \.day) { group in176                        Section(group.day.formatted(date: .complete, time: .omitted)) {177                            ForEach(group.events) { e in178                                HStack(alignment: .top, spacing: SPDTheme.Space.md) {179                                    Image(systemName: e.symbol).foregroundStyle(SPDTheme.Palette.brand).frame(width: 26)180                                    VStack(alignment: .leading, spacing: 2) {181                                        Text(e.sentence).font(.body).fixedSize(horizontal: false, vertical: true)182                                        Text("\(e.who) · \(e.at.formatted(date: .omitted, time: .shortened))" + (e.meta?["via"]?.string == "grant" ? String(localized: " · par un partage") : "")).font(.caption).foregroundStyle(.secondary)183                                    }184                                }185                                .accessibilityElement(children: .combine)186                                .accessibilityIdentifier("activity.\(e.action)")187                            }188                        }189                    }190                    if more { Section { Button { Task { await load(reset: false) } } label: { HStack { Text("Afficher plus ancien"); if loadingMore { Spacer(); ProgressView() } } }.disabled(loadingMore) } }191                }192                .listStyle(.insetGrouped)193            }194        }195        .navigationTitle(title)196        .navigationBarTitleDisplayMode(source == .account ? .large : .inline)197        .refreshable { await load(reset: true) }198        .task { await load(reset: true) }199    }200201    static func byDay(_ events: [ActivityLine]) -> [(day: Date, events: [ActivityLine])] {202        Dictionary(grouping: events) { Calendar.current.startOfDay(for: $0.at) }.sorted { $0.key > $1.key }.map { ($0.key, $0.value.sorted { $0.at > $1.at }) }203    }204205    private func load(reset: Bool) async {206        loadingMore = !reset207        defer { loadingMore = false }208        do {209            let before = reset ? nil : state.value?.last?.id210            let page: ActivityLines = try await model.next.client.get(source.path, query: ["before": before, "limit": "50"])211            state = .loaded(reset ? page.events : (state.value ?? []) + page.events)212            more = page.more213        } catch { if state.value == nil { state = .failed(NextCenter.describe(error)) } }214    }215}216217// MARK: Versions218219struct VersionsScreen: View {220    @Environment(AppModel.self) private var model221    let item: DriveItem222    @State private var state: Loadable<VersionList> = .loading223    @State private var restoring: VersionInfo?224    @State private var comparing: VersionPair?225    @State private var busy = false226227    var body: some View {228        LoadingView(state: state, retry: load) { list in229            List {230                Section {231                    ForEach(Array(list.versions.enumerated()), id: \.element.id) { index, v in232                        VStack(alignment: .leading, spacing: 6) {233                            HStack {234                                Text("Version \(v.seq)").font(.body.weight(.semibold)).accessibilityIdentifier("version.\(v.seq)")235                                if v.current { Text("Actuelle").font(.caption2.weight(.bold)).padding(.horizontal, 7).padding(.vertical, 3).foregroundStyle(.white).background(SPDTheme.Palette.brand, in: Capsule()) }236                                Spacer()237                                Text(v.size.byteString).font(.caption.monospacedDigit()).foregroundStyle(.secondary)238                            }239                            Text("\(v.createdAt.formatted(date: .abbreviated, time: .shortened)) · \(v.createdBy.map { $0.me == true ? String(localized: "toi") : ($0.displayName ?? "—") } ?? String(localized: "dépôt par lien"))").font(.caption).foregroundStyle(.secondary)240                            if let note = v.note, !note.isEmpty { Text(note).font(.caption).foregroundStyle(.secondary) }241                            HStack(spacing: SPDTheme.Space.sm) {242                                if index + 1 < list.versions.count {243                                    Button { comparing = VersionPair(old: list.versions[index + 1], new: v) } label: { Label("Comparer avec la précédente", systemImage: "rectangle.split.2x1") }244                                        .accessibilityIdentifier("version.compare.\(v.seq)")245                                }246                                if !v.current { Button { restoring = v } label: { Label("Restaurer", systemImage: "clock.arrow.circlepath") }.accessibilityIdentifier("version.restore.\(v.seq)") }247                            }248                            .buttonStyle(.bordered).font(.footnote).disabled(busy)249                        }250                        .padding(.vertical, 4)251                    }252                } footer: {253                    Text("Restaurer fait de l’ancien contenu une NOUVELLE version courante : aucune version n’est effacée, l’historique reste complet.")254                }255            }256        }257        .navigationTitle("Versions")258        .navigationBarTitleDisplayMode(.inline)259        .refreshable { await load() }260        .task(id: item.versionID) { await load() }261        .confirmationDialog("Restaurer cette version ?", isPresented: Binding(get: { restoring != nil }, set: { if !$0 { restoring = nil } }), titleVisibility: .visible, presenting: restoring) { v in262            Button("Restaurer la version \(v.seq)") { restore(v) }.accessibilityIdentifier("version.confirmRestore")263            Button("Annuler", role: .cancel) {}264        } message: { v in Text("Le contenu du \(v.createdAt.formatted(date: .abbreviated, time: .shortened)) redeviendra la version courante, sous un nouveau numéro. La version actuelle reste dans l’historique.") }265        .sheet(item: $comparing) { VersionCompare(item: item, pair: $0) }266    }267268    private func load() async {269        do { state = .loaded(try await model.next.client.versions(of: item.id)) } catch { if state.value == nil { state = .failed(NextCenter.describe(error)) } }270    }271    private func restore(_ v: VersionInfo) {272        busy = true273        Task {274            await model.performNext(success: String(localized: "Version \(v.seq) restaurée comme nouvelle version")) { _ = try await model.next.client.restoreVersion(fileID: item.id, versionID: v.id) }275            await model.engine.sync()276            await load()277            busy = false278        }279    }280}281282struct VersionPair: Identifiable { let old: VersionInfo; let new: VersionInfo; var id: String { old.id + new.id } }283284/// Two versions side by side. What can be compared depends on the kind of file — and when nothing meaningful can be shown, that is said.285struct VersionCompare: View {286    @Environment(AppModel.self) private var model287    @Environment(\.dismiss) private var dismiss288    @Environment(\.horizontalSizeClass) private var sizeClass289    let item: DriveItem290    let pair: VersionPair291    enum Result { case text([TextDiff.Line]), tooLong, images(UIImage, UIImage), pdf(URL, URL), binary }292    @State private var state: Loadable<Result> = .loading293294    var body: some View {295        NavigationStack {296            LoadingView(state: state, retry: load) { result in297                switch result {298                case .text(let lines): diff(lines)299                case .tooLong: statement(String(localized: "Ces textes sont trop longs pour une comparaison ligne à ligne sur l’appareil."))300                case .images(let a, let b): sideBySide { Image(uiImage: a).resizable().scaledToFit() } right: { Image(uiImage: b).resizable().scaledToFit() }301                case .pdf(let a, let b): sideBySide { PDFPane(url: a) } right: { PDFPane(url: b) }302                case .binary: statement(String(localized: "Ce type de fichier ne peut pas être comparé visuellement."))303                }304            }305            .navigationTitle("Version \(pair.old.seq) → \(pair.new.seq)")306            .navigationBarTitleDisplayMode(.inline)307            .toolbar { ToolbarItem(placement: .cancellationAction) { Button("Fermer") { dismiss() } } }308            .task { await load() }309        }310    }311312    private func diff(_ lines: [TextDiff.Line]) -> some View {313        let s = TextDiff.summary(lines)314        return List {315            Section {316                ForEach(lines) { l in317                    HStack(alignment: .top, spacing: 6) {318                        Text(l.kind == .added ? "+" : l.kind == .removed ? "−" : " ").font(.system(.footnote, design: .monospaced).weight(.bold)).frame(width: 12)319                            .accessibilityLabel(Text(l.kind == .added ? "Ajoutée" : l.kind == .removed ? "Retirée" : "Inchangée"))320                        Text(l.text.isEmpty ? " " : l.text).font(.system(.footnote, design: .monospaced)).fixedSize(horizontal: false, vertical: true)321                    }322                    .listRowBackground(l.kind == .added ? SPDTheme.Palette.positive.opacity(0.16) : l.kind == .removed ? SPDTheme.Palette.critical.opacity(0.14) : Color.clear)323                    .listRowSeparator(.hidden).listRowInsets(EdgeInsets(top: 2, leading: 12, bottom: 2, trailing: 12))324                    .accessibilityElement(children: .combine)325                }326            } header: {327                Text(s.added == 0 && s.removed == 0 ? String(localized: "Aucune différence de texte") : String(localized: "\(s.added) ligne(s) ajoutée(s), \(s.removed) retirée(s), \(s.unchanged) inchangée(s)")).accessibilityIdentifier("diff.summary")328            }329        }330        .listStyle(.plain)331    }332333    private func sideBySide<L: View, R: View>(@ViewBuilder _ left: () -> L, @ViewBuilder right: () -> R) -> some View {334        let layout = sizeClass == .regular ? AnyLayout(HStackLayout(spacing: SPDTheme.Space.md)) : AnyLayout(VStackLayout(spacing: SPDTheme.Space.md))335        return layout {336            pane(String(localized: "Version \(pair.old.seq)"), pair.old) { left() }337            pane(String(localized: "Version \(pair.new.seq)"), pair.new) { right() }338        }339        .padding(SPDTheme.Space.md).background(SPDTheme.Palette.surface)340    }341    private func pane<C: View>(_ title: String, _ v: VersionInfo, @ViewBuilder _ content: () -> C) -> some View {342        VStack(alignment: .leading, spacing: 6) {343            Text(title).font(SPDTheme.Typo.headline)344            Text("\(v.createdAt.formatted(date: .abbreviated, time: .shortened)) · \(v.size.byteString)").font(SPDTheme.Typo.caption).foregroundStyle(.secondary)345            content().frame(maxWidth: .infinity, maxHeight: .infinity).clipShape(RoundedRectangle(cornerRadius: SPDTheme.Radius.md, style: .continuous))346        }347        .padding(SPDTheme.Space.sm).spdCard()348    }349350    private func statement(_ why: String) -> some View {351        Form {352            Section { Text(why).accessibilityIdentifier("compare.statement") }353            Section("Ce qui est certain") {354                LabeledContent("Contenu") { Text(pair.old.sha256 == pair.new.sha256 ? "Identique (même empreinte)" : "Différent (empreintes différentes)") }355                LabeledContent("Taille") { Text("\(pair.old.size.byteString) → \(pair.new.size.byteString)") }356                LabeledContent("Dates") { Text("\(pair.old.createdAt.formatted(date: .abbreviated, time: .shortened)) → \(pair.new.createdAt.formatted(date: .abbreviated, time: .shortened))") }357            }358        }359    }360361    private func load() async {362        let ext = item.fileExtension363        let dir = FileManager.default.temporaryDirectory.appendingPathComponent("SPDrive-compare-\(item.id)", isDirectory: true)364        try? FileManager.default.createDirectory(at: dir, withIntermediateDirectories: true)365        let a = dir.appendingPathComponent("v\(pair.old.seq).\(ext)"), b = dir.appendingPathComponent("v\(pair.new.seq).\(ext)")366        do {367            guard TextDiff.isText(extension: ext) || item.kind == .image || item.kind == .pdf, max(pair.old.size, pair.new.size) <= 60_000_000 else { state = .loaded(.binary); return }368            for (v, url) in [(pair.old, a), (pair.new, b)] where !IntegrityVerifier.verify(url, sha256: v.sha256) {369                try? FileManager.default.removeItem(at: url)370                try await model.next.client.downloadVersion(fileID: item.id, versionID: v.id, to: url)371            }372            if item.kind == .image, let ia = ThumbnailLoader.downsample(a, maxPixel: 1600), let ib = ThumbnailLoader.downsample(b, maxPixel: 1600) { state = .loaded(.images(ia, ib)) }373            else if item.kind == .pdf { state = .loaded(.pdf(a, b)) }374            else if TextDiff.isText(extension: ext), let ta = try? String(contentsOf: a, encoding: .utf8), let tb = try? String(contentsOf: b, encoding: .utf8) {375                let lines = await Task.detached { TextDiff.lines(old: ta, new: tb) }.value376                state = .loaded(lines.map { .text($0) } ?? .tooLong)377            } else { state = .loaded(.binary) }378        } catch { state = .failed(NextCenter.describe(error)) }379    }380}381382private struct PDFPane: UIViewRepresentable {383    let url: URL384    func makeUIView(context: Context) -> PDFView {385        let v = PDFView(); v.autoScales = true; v.displayMode = .singlePageContinuous; v.document = PDFDocument(url: url); v.backgroundColor = .secondarySystemBackground386        return v387    }388    func updateUIView(_ view: PDFView, context: Context) {}389}390391// MARK: Devices392393struct DevicesScreen: View {394    @Environment(AppModel.self) private var model395    @State private var state: Loadable<[NextSession]> = .loading396    @State private var revoking: NextSession?397398    var body: some View {399        LoadingView(state: state, retry: load) { sessions in400            List {401                Section {402                    ForEach(sessions.sorted { ($0.current ? 1 : 0, $0.lastSeenAt) > ($1.current ? 1 : 0, $1.lastSeenAt) }) { s in403                        HStack(alignment: .top, spacing: SPDTheme.Space.md) {404                            Image(systemName: Self.symbol(s)).font(.title3).foregroundStyle(SPDTheme.Palette.brand).frame(width: 30)405                            VStack(alignment: .leading, spacing: 2) {406                                HStack { Text(s.deviceName ?? Self.platformName(s)).font(.body.weight(.medium)); if s.current { Text("Cet appareil").font(.caption2.weight(.bold)).padding(.horizontal, 6).padding(.vertical, 2).foregroundStyle(.white).background(SPDTheme.Palette.positive, in: Capsule()) } }407                                Text(s.client.map { "\(Self.platformName(s)) · SP Drive \($0.version)" + ($0.os.map { " · \($0)" } ?? "") } ?? (s.kind == "device" ? String(localized: "Application (version non communiquée)") : String(localized: "Navigateur web")))408                                    .font(.caption).foregroundStyle(.secondary)409                                Text("Dernière activité : \(s.lastSeenAt.formatted(date: .abbreviated, time: .shortened)) · connecté le \(s.createdAt.formatted(date: .abbreviated, time: .omitted))").font(.caption).foregroundStyle(.secondary).fixedSize(horizontal: false, vertical: true)410                            }411                        }412                        .accessibilityElement(children: .combine)413                        .accessibilityIdentifier(s.current ? "device.current" : "device.\(s.id)")414                        .swipeActions { if !s.current { Button(role: .destructive) { revoking = s } label: { Label("Déconnecter", systemImage: "xmark.circle") } } }415                        .contextMenu { if !s.current { Button(role: .destructive) { revoking = s } label: { Label("Déconnecter cet appareil", systemImage: "xmark.circle") } } }416                    }417                } footer: { Text("Déconnecter un appareil ferme sa session tout de suite : il devra se reconnecter avec une clé d’accès. Rien n’est effacé sur le Drive.") }418            }419        }420        .navigationTitle("Appareils connectés")421        .navigationBarTitleDisplayMode(.inline)422        .refreshable { await load() }423        .task { await load() }424        .confirmationDialog("Déconnecter cet appareil ?", isPresented: Binding(get: { revoking != nil }, set: { if !$0 { revoking = nil } }), titleVisibility: .visible, presenting: revoking) { s in425            Button("Déconnecter", role: .destructive) { Task { await model.performNext(success: String(localized: "Appareil déconnecté")) { try await model.next.client.revokeSession(s.id) }; await load() } }426            Button("Annuler", role: .cancel) {}427        }428    }429    private func load() async { do { state = .loaded(try await model.next.client.sessions()) } catch { if state.value == nil { state = .failed(NextCenter.describe(error)) } } }430    static func symbol(_ s: NextSession) -> String { switch s.client?.platform { case "ios": "iphone"; case "ipados": "ipad"; case "macos": "laptopcomputer"; default: s.kind == "device" ? "apps.iphone" : "globe" } }431    static func platformName(_ s: NextSession) -> String { switch s.client?.platform { case "ios": "iPhone"; case "ipados": "iPad"; case "macos": "Mac"; default: s.kind == "device" ? String(localized: "Application") : String(localized: "Web") } }432}433434// MARK: Infrastructure (administrators)435436struct AdminScreen: View {437    @Environment(AppModel.self) private var model438    @State private var state: Loadable<AdminSystem> = .loading439440    var body: some View {441        LoadingView(state: state, retry: load) { sys in442            List {443                Section("Serveur") {444                    LabeledContent("Version") { Text(sys.version ?? "—") }445                    LabeledContent("Fonctions") { Text(sys.features.joined(separator: ", ")).font(.caption).multilineTextAlignment(.trailing) }446                }447                Section("Travailleur") {448                    LabeledContent("État") { Label(sys.worker?.alive == true ? "En marche" : "Arrêté ou silencieux", systemImage: sys.worker?.alive == true ? "checkmark.circle.fill" : "exclamationmark.triangle.fill").foregroundStyle(sys.worker?.alive == true ? SPDTheme.Palette.positive : SPDTheme.Palette.critical) }449                    if let age = sys.worker?.heartbeatAgeS { LabeledContent("Dernier signe de vie") { Text("il y a \(Int(age)) s").monospacedDigit() } }450                }451                Section("File de tâches") {452                    if sys.jobs.isEmpty { Text("Vide").foregroundStyle(.secondary) }453                    ForEach(sys.jobs) { j in LabeledContent("\(j.kind) · \(j.status)") { Text("\(j.count)").monospacedDigit() } }454                }455                if !sys.previewFailures.isEmpty {456                    Section("Aperçus en échec") { ForEach(sys.previewFailures) { f in LabeledContent(f.kind) { Text("\(f.count)").monospacedDigit() } } }457                }458                ForEach(["backup", "antivirusSignatures", "converter", "textkit"], id: \.self) { key in459                    if case .object(let o)? = sys.raw[key] {460                        Section(key) { ForEach(o.keys.sorted(), id: \.self) { k in LabeledContent(k) { Text(Self.text(o[k])).font(.caption.monospaced()).multilineTextAlignment(.trailing) } } }461                    }462                }463                Section { } footer: { Text("Lecture seule : cette vue montre ce que le serveur rapporte, elle ne commande rien.") }464            }465        }466        .navigationTitle("Infrastructure")467        .navigationBarTitleDisplayMode(.inline)468        .refreshable { await load() }469        .task { await load() }470    }471    private func load() async { do { state = .loaded(try await model.next.client.adminSystem()) } catch { if state.value == nil { state = .failed(NextCenter.describe(error)) } } }472    static func text(_ v: NextJSON?) -> String {473        switch v { case .string(let s)?: s; case .number(let n)?: n == n.rounded() ? String(Int64(n)) : String(n); case .bool(let b)?: b ? "oui" : "non"; case .null?, nil: "—"; default: "…" }474    }475}476
Files main
Menu

Theme