SPB Git

Repository Public MIT

ArenaHistory.swift 9.9 KB 216 lines swift

1// =============================================================================2//                  SP BOUCHER | SOFTWARE & RESEARCH3//             ARTIFICIAL INTELLIGENCE • FINANCE • ENGINEERING4// =============================================================================5//6// PROJECT METADATA7// -----------------------------------------------------------------------------8// Project          : ORIX Astra9// File             : Packages/AstraUI/Sources/Arena/ArenaHistory.swift10// Module           : Arena11// Repository       : https://git.spboucher.ai/orix-astra12// Created          : 2026-11-2113// Last Modified    : 2026-11-2114//15// =============================================================================16// AUTHOR & PROFESSIONAL AFFILIATION17// =============================================================================18//19// Author           : Simon-Pierre Boucher20// Position         : Professor of Finance21// Institution      : Université du Québec en Outaouais (UQO)22// Department       : Département des sciences administratives23// Organization     : SP Boucher24//25// Website          : https://spboucher.ai26// Git              : https://git.spboucher.ai27//28// =============================================================================29// OFFICIAL CONTACT DIRECTORY30// =============================================================================31//32// General          : info@spboucher.ai33// Professional     : contact@spboucher.ai34// Direct           : simon@spboucher.ai35// Research         : research@spboucher.ai36// Development      : dev@spboucher.ai37// Support          : support@spboucher.ai38// Security/Admin   : admin@spboucher.ai39// Notifications    : notifications@spboucher.ai40//41// Preferred Contact: support@spboucher.ai42//43// =============================================================================44// COPYRIGHT & INTELLECTUAL PROPERTY45// =============================================================================46//47// Copyright (c) 202648// Simon-Pierre Boucher49//50// All rights reserved where applicable.51//52// This file is governed by the applicable project license,53// copyright notices, institutional agreements and relevant law.54//55// Unless expressly authorized by the applicable license or56// rights holder, copying, redistribution, sublicensing,57// publication and commercial exploitation are not permitted.58//59// Existing third-party rights and notices remain unaffected.60//61// =============================================================================62// CONFIDENTIALITY & SECURITY63// =============================================================================64//65// Classification   : Public66// Distribution     : Public repository; use is governed by the project license67// Security Contact : admin@spboucher.ai68//69// Access to this source does not independently grant permission70// to redistribute or disclose confidential materials.71//72// Do not embed credentials, private keys, access tokens,73// certificates or confidential personal information.74//75// =============================================================================76// LICENSE & MAINTENANCE77// =============================================================================78//79// License          : Proprietary, all rights reserved (see license file)80// License File     : LICENSE81// Maintainer       : Simon-Pierre Boucher82// Technical Contact: dev@spboucher.ai83//84// =============================================================================85// END OF SP BOUCHER SOURCE HEADER86// =============================================================================8788import SwiftUI89import AstraCore90import AstraDesign91import AstraPersistence9293/// Past comparisons: open, rename, delete.94struct ArenaHistoryView: View {95    @Environment(AppModel.self) private var app96    let onOpen: (String) -> Void9798    @State private var sessions: [ArenaSessionRecord]?99    @State private var error: String?100    @State private var renaming: ArenaSessionRecord?101    @State private var newTitle = ""102    @State private var deleting: ArenaSessionRecord?103104    var body: some View {105        Group {106            if let sessions {107                if sessions.isEmpty {108                    EmptyStateView(symbol: "clock.arrow.circlepath", title: "No comparison yet", message: "Every comparison you run is kept here with its answers and measurements, on this iPhone only.")109                        .frame(maxWidth: .infinity, maxHeight: .infinity)110                } else {111                    List {112                        ForEach(sessions) { session in113                            Button { onOpen(session.id) } label: { row(session) }114                                .buttonStyle(.plain)115                                .listRowBackground(AstraColor.surface)116                                .swipeActions(edge: .trailing, allowsFullSwipe: false) {117                                    Button(role: .destructive) { deleting = session } label: { Label("Delete", systemImage: "trash") }118                                    Button { newTitle = session.title; renaming = session } label: { Label("Rename", systemImage: "pencil") }.tint(AstraColor.indigo)119                                }120                                .contextMenu {121                                    Button { newTitle = session.title; renaming = session } label: { Label("Rename", systemImage: "pencil") }122                                    Button(role: .destructive) { deleting = session } label: { Label("Delete", systemImage: "trash") }123                                }124                                .accessibilityIdentifier("arena-session-row")125                        }126                    }127                    .listStyle(.insetGrouped).scrollContentBackground(.hidden)128                }129            } else if let error {130                EmptyStateView(symbol: "exclamationmark.triangle", title: "History could not be read", message: error) {131                    Button("Try again") { Task { await load() } }.buttonStyle(AstraSecondaryButtonStyle())132                }133                .frame(maxWidth: .infinity, maxHeight: .infinity)134            } else { LabLoading() }135        }136        .background(Starfield(density: 0.4))137        .navigationTitle("History").navigationBarTitleDisplayMode(.inline)138        .task {139            for await _ in app.store.changes(in: AstraTable.arena) { await load() }140        }141        .alert("Rename comparison", isPresented: Binding(get: { renaming != nil }, set: { if !$0 { renaming = nil } })) {142            TextField("Title", text: $newTitle)143            Button("Save") { if let target = renaming { rename(target, to: newTitle) } }144            Button("Cancel", role: .cancel) {}145        }146        .confirmationDialog("Delete this comparison?", isPresented: Binding(get: { deleting != nil }, set: { if !$0 { deleting = nil } }), titleVisibility: .visible) {147            Button("Delete", role: .destructive) { if let target = deleting { delete(target) } }148            Button("Cancel", role: .cancel) {}149        } message: { Text("Its answers and measurements are removed. Usage already recorded in Lab is kept.") }150    }151152    private func row(_ session: ArenaSessionRecord) -> some View {153        VStack(alignment: .leading, spacing: AstraSpace.xs) {154            Text(session.title.isEmpty ? "Untitled comparison" : session.title).font(AstraFont.bodyEmphasis).foregroundStyle(AstraColor.textPrimary).lineLimit(2)155            Text(session.prompt).font(AstraFont.caption).foregroundStyle(AstraColor.textSecondary).lineLimit(2)156            HStack(spacing: AstraSpace.xs) {157                AstraBadge(LabFormat.dateTime(session.createdAt), symbol: "calendar")158                if session.blind { AstraBadge("Blind", symbol: "eye.slash", tone: .accent) }159            }160        }161        .frame(maxWidth: .infinity, minHeight: AstraSpace.hit, alignment: .leading)162        .padding(.vertical, AstraSpace.xs)163        .contentShape(Rectangle())164        .accessibilityElement(children: .combine)165        .accessibilityHint("Opens the comparison")166    }167168    private func load() async {169        do { sessions = try await app.store.arenaSessions(); error = nil }170        catch { if sessions == nil { self.error = AstraError.wrap(error).message } }171    }172173    private func rename(_ session: ArenaSessionRecord, to title: String) {174        let store = app.store175        Task {176            do { try await store.renameArenaSession(id: session.id, title: title.trimmingCharacters(in: .whitespacesAndNewlines)) }177            catch { app.show(AstraError.wrap(error).message, .error) }178        }179    }180181    private func delete(_ session: ArenaSessionRecord) {182        let store = app.store183        Task {184            do { try await store.deleteArenaSession(id: session.id); app.show("Comparison deleted", .success) }185            catch { app.show(AstraError.wrap(error).message, .error) }186        }187    }188}189190/// A comparison opened from history, with its own controller so a retry here never disturbs a run in progress.191struct ArenaStoredSessionView: View {192    @Environment(AppModel.self) private var app193    let sessionID: String194    let onReuse: (ArenaSessionRecord, [ModelRef]) -> Void195    @State private var controller: ArenaController?196197    var body: some View {198        Group {199            if let controller, controller.session != nil {200                ArenaSessionView(controller: controller, onReuse: onReuse)201            } else if let failure = controller?.failure {202                EmptyStateView(symbol: "exclamationmark.triangle", title: "This comparison could not be opened", message: failure.message)203                    .frame(maxWidth: .infinity, maxHeight: .infinity).background(Starfield(density: 0.4))204            } else {205                LabLoading().frame(maxHeight: .infinity).background(Starfield(density: 0.4))206            }207        }208        .task {209            guard controller == nil else { return }210            let fresh = ArenaController(store: app.store, library: app.library, orchestrator: app.orchestrator)211            controller = fresh212            await fresh.load(sessionID: sessionID)213        }214    }215}216
Files main
Menu

Theme