SPB Git

Repository Public

VQuantApp.swift 22.1 KB 474 lines swift

1//2//  VQuant iOS3//  File: VQuant/App/VQuantApp.swift4//  Description: Application entry point: scenes (main window, per-asset windows on iPad), lifecycle, background refresh,5//               and the root view that switches between sign-in, the lock screen and the app.6//7//  Author: Simon-Pierre Boucher8//  Contact: contact@spboucher.ai9//1011import CoreSpotlight12import SwiftUI13import VQuantKit14import VQuantUI1516@main17struct VQuantApp: App {18    @State private var model = AppModel()19    @Environment(\.scenePhase) private var phase2021    init() { Appearance.install() }2223    var body: some Scene {24        WindowGroup {25            RootView()26                .environment(model)27                .task {28                    model.notifications.onOpen = { url in model.router.handle(url, compact: UIDevice.current.userInterfaceIdiom == .phone) }29                    AppIntentsBridge.shared.model = model30                    if let url = AppIntentsBridge.shared.pending { AppIntentsBridge.shared.pending = nil; AppIntentsBridge.shared.open(url) }31                    await model.bootstrap()32                    if let url = model.configuration.initialURL { model.router.handle(url, compact: UIDevice.current.userInterfaceIdiom == .phone) }33                    await model.refreshHome()34                }35        }36        .onChange(of: phase) { _, new in37            switch new {38            case .active: model.sceneBecameActive()39            case .inactive: model.sceneResignedActive()40            case .background: model.sceneEnteredBackground()41            @unknown default: break42            }43        }44        .backgroundTask(.appRefresh(BackgroundRefresh.identifier)) {45            let (api, a, q) = await MainActor.run { (model.api, model.preferences.notifyAnalyses, model.preferences.notifyQuant) }46            guard await MainActor.run(body: { model.isSignedIn }) else { return }47            // iOS decides when this runs. It pulls the account's changes into the replica, then checks what ended.48            _ = await model.next.sync.syncNow()49            await model.next.hub.refreshApprovals()50            await BackgroundRefresh.run(api: api, notifyAnalyses: a, notifyQuant: q)51            await MainActor.run { model.writeWidgetSnapshot() }52        }53        .commands { AppCommands(model: model) }5455        // iPad: any destination can live in its own window (Stage Manager, external display, side by side).56        WindowGroup("VQuant", id: "route", for: Route.self) { $route in57            if let route {58                NavigationStack { RouteView(route: route).navigationDestinations() }59                    .environment(model)60                    .modifier(SessionGate())61            }62        }63        // 1.0 opened asset windows with this id; kept so a window restored by the system still opens.64        WindowGroup("Actif", id: "asset", for: String.self) { $symbol in65            if let symbol {66                NavigationStack { AssetView(symbol: symbol).navigationDestinations() }67                    .environment(model)68                    .modifier(SessionGate())69            }70        }71    }72}7374/// Navigation-bar titles in New York (the display serif of the design system), tab bar and bars on the paper tone.75@MainActor76enum Appearance {77    static func install() {78        func serif(_ style: UIFont.TextStyle, weight: UIFont.Weight) -> UIFont {79            let base = UIFont.preferredFont(forTextStyle: style)80            let d = base.fontDescriptor.withDesign(.serif)?.addingAttributes([.traits: [UIFontDescriptor.TraitKey.weight: weight]]) ?? base.fontDescriptor81            return UIFontMetrics(forTextStyle: style).scaledFont(for: UIFont(descriptor: d, size: base.pointSize))82        }83        let nav = UINavigationBar.appearance()84        nav.largeTitleTextAttributes = [.font: serif(.largeTitle, weight: .semibold)]85        nav.titleTextAttributes = [.font: serif(.headline, weight: .semibold)]86    }87}8889/// Hardware-keyboard shortcuts (iPad): every destination and main command, listed in the ⌘-hold overlay.90struct AppCommands: Commands {91    let model: AppModel92    @Environment(\.openWindow) private var openWindow9394    private func go(_ route: Route) { model.router.open(route, compact: false) }9596    var body: some Commands {97        CommandGroup(replacing: .newItem) {98            Button("Nouvelle recherche") { model.router.compose(mode: .research) }.keyboardShortcut("n")99            Button("Nouvelle analyse rapide") { model.router.compose(mode: .fast) }.keyboardShortcut("n", modifiers: [.command, .shift])100            Button("Nouvelle note") { model.router.open(.note("new"), compact: false) }.keyboardShortcut("n", modifiers: [.command, .option])101            Button("Nouvelle fenêtre") { openWindow(id: "route", value: model.router.padDetail[model.router.section] ?? Route.terminal) }.keyboardShortcut("n", modifiers: [.command, .option, .shift])102            Divider()103            Button("Rechercher partout") { model.router.showSearch = true }.keyboardShortcut("k")104            Button("Rechercher un actif") { model.router.open(.search, compact: false) }.keyboardShortcut("f", modifiers: [.command, .shift])105        }106        CommandMenu("Aller à") {107            ForEach(Array(AppSection.padSidebar.enumerated()), id: \.element) { i, s in108                Button(s.title) { model.router.section = s }.keyboardShortcut(KeyEquivalent(Character(String((i + 1) % 10))), modifiers: .command)109            }110        }111        CommandMenu("Recherche") {112            Button("Demandes d’autorisation") { go(.approvals) }.keyboardShortcut("a", modifiers: [.command, .shift])113            Button("Arrêter l’étude affichée") { stopVisible() }.keyboardShortcut(".", modifiers: .command)114            Button("Afficher ou masquer l’inspecteur") { model.router.showInspector.toggle() }.keyboardShortcut("i", modifiers: [.command, .option])115            Divider()116            Button("Projets du studio") { go(.studio) }.keyboardShortcut("p", modifiers: [.command, .shift])117            Button("Consommation et coûts") { go(.usage) }.keyboardShortcut("u", modifiers: [.command, .shift])118        }119        CommandMenu("Marchés") {120            Button("Terminal") { go(.terminal) }.keyboardShortcut("t")121            Button("Santé des fournisseurs de données") { go(.dataHealth) }.keyboardShortcut("d", modifiers: [.command, .shift])122        }123        CommandMenu("Quant Lab") {124            Button("Catalogue des moteurs") { go(.quant) }.keyboardShortcut("l")125            Button("Prix et grecques d’une option") { go(.quickCalc("option")) }.keyboardShortcut("o", modifiers: [.command, .option])126            Button("VaR d’une position") { go(.quickCalc("var")) }.keyboardShortcut("v", modifiers: [.command, .option])127            Button("Taille de position") { go(.quickCalc("sizing")) }.keyboardShortcut("s", modifiers: [.command, .option])128        }129        CommandGroup(after: .toolbar) {130            Button("Actualiser") { Task { await model.refreshHome() } }.keyboardShortcut("r")131            Button("Synchroniser maintenant") { Task { await model.next.sync.syncNow() } }.keyboardShortcut("s", modifiers: [.command, .shift])132        }133    }134135    private func stopVisible() {136        guard let id = model.notifications.visibleJobId, let c = model.research.controller(forJob: id) else { return }137        Task { await c.cancel() }138    }139}140141/// Covers a scene with the sign-in screen or the lock screen when needed.142struct SessionGate: ViewModifier {143    @Environment(AppModel.self) private var model144    func body(content: Content) -> some View {145        ZStack {146            if model.isSignedIn { content } else { SignInView() }147            if model.isSignedIn && model.lock.isLocked { LockView().transition(.opacity) }148            else if model.isSignedIn && model.lock.isObscured && model.lock.isEnabled { PrivacyCover() }149        }150        .preferredColorScheme(model.preferences.appearance.scheme)151        .tint(Theme.orange)152        .vqTheme(model.preferences.theme)153        .onChange(of: model.preferences.colourVisionSafe, initial: true) { _, cvd in Theme.upDown = cvd ? .cvd : .classic }154    }155}156157struct RootView: View {158    @Environment(AppModel.self) private var model159    @Environment(\.horizontalSizeClass) private var sizeClass160161    var body: some View {162        @Bindable var router = model.router163        Group {164            if sizeClass == .compact { PhoneRoot() } else { PadRoot() }165        }166        .modifier(SessionGate())167        .onOpenURL { url in168            if url.scheme == "vquant" { model.router.handle(url, compact: sizeClass == .compact) }169            else if url.path.hasPrefix("/setup/") { Task { await model.enrol(invitation: url.absoluteString) } }170            else if url.isFileURL { model.router.compose(mode: .research, files: [url]) }171        }172        .onContinueUserActivity(CSSearchableItemActionType) { activity in173            if let id = activity.userInfo?[CSSearchableItemActivityIdentifier] as? String, let url = URL(string: id) { model.router.handle(url, compact: sizeClass == .compact) }174        }175        .onContinueUserActivity("ai.spboucher.vquant.asset") { activity in176            if let s = (activity.userInfo?["symbol"] as? String).flatMap(WatchlistFile.normalise) { model.router.open(.asset(s), compact: sizeClass == .compact) }177        }178        .sheet(isPresented: $router.showComposer) { ComposerSheet().paperBackground().environment(model).vqTheme(model.preferences.theme).tint(Theme.orange) }179        .sheet(isPresented: $router.showSearch) { UniversalSearchSheet().paperBackground().environment(model).vqTheme(model.preferences.theme).tint(Theme.orange) }180    }181}182183/// Shown over the content in the app switcher when the lock is enabled.184struct PrivacyCover: View {185    var body: some View {186        ZStack {187            Theme.background.ignoresSafeArea()188            SparkleMark().frame(width: 72, height: 72)189        }190        .accessibilityHidden(true)191    }192}193194struct LockView: View {195    @Environment(AppModel.self) private var model196    var body: some View {197        ZStack {198            Theme.background.ignoresSafeArea()199            VStack(spacing: 18) {200                SparkleMark().frame(width: 64, height: 64)201                Text("VQuant est verrouillé").font(.title3.weight(.semibold))202                if let e = model.lock.lastError { Text(e).font(.footnote).foregroundStyle(Theme.down).multilineTextAlignment(.center) }203                Button {204                    Task { await model.lock.unlock() }205                } label: {206                    Label("Déverrouiller avec \(AppLock.biometryName)", systemImage: AppLock.biometrySymbol).frame(maxWidth: 320)207                }208                .buttonStyle(.borderedProminent).controlSize(.large)209                .accessibilityIdentifier("unlock-button")210                Button("Se déconnecter", role: .destructive) { Task { await model.signOut() } }.font(.footnote)211            }212            .padding(32)213        }214        .task { await model.lock.unlock() }215    }216}217218// MARK: - iPhone: five tabs219220struct PhoneRoot: View {221    @Environment(AppModel.self) private var model222    var body: some View {223        @Bindable var router = model.router224        TabView(selection: $router.section) {225            ForEach(AppSection.phoneTabs) { section in226                NavigationStack(path: router.path(section)) {227                    SectionRoot(section: section).navigationDestinations()228                }229                .tabItem { Label(section.title, systemImage: section.systemImage) }230                .tag(section)231                .badge(section == .research ? model.next.hub.pending.count : 0)232                .accessibilityIdentifier("tab-\(section.rawValue)")233            }234        }235    }236}237238// MARK: - iPad: sidebar, list column, detail239240struct PadRoot: View {241    @Environment(AppModel.self) private var model242    @State private var visibility: NavigationSplitViewVisibility = .all243244    var body: some View {245        @Bindable var router = model.router246        let section = padSection247        Group {248            if section.hasListColumn {249                NavigationSplitView(columnVisibility: $visibility) {250                    sidebar251                } content: {252                    PadListColumn(section: section)253                        .environment(\.padSelect) { route in router.padDetail[section] = route; router.paths[section] = [] }254                        .navigationSplitViewColumnWidth(min: 280, ideal: 340, max: 460)255                } detail: {256                    NavigationStack(path: router.path(section)) {257                        PadDetailRoot(section: section, route: router.padDetail[section]).navigationDestinations()258                    }259                    .id("\(section.rawValue)-\(String(describing: router.padDetail[section]))")260                }261            } else {262                NavigationSplitView(columnVisibility: $visibility) {263                    sidebar264                } detail: {265                    NavigationStack(path: router.path(section)) {266                        SectionRoot(section: section).navigationDestinations()267                    }268                    .id(section)269                }270            }271        }272        .navigationSplitViewStyle(.balanced)273        // A workspace needs the width: opening one folds the sidebar and the list (the toolbar button brings them back).274        .onChange(of: router.padDetail[.workspaces]) { _, route in if route != nil, section == .workspaces { visibility = .detailOnly } }275        .onChange(of: section) { _, s in if s != .workspaces, visibility == .detailOnly { visibility = .all } }276    }277278    private var sidebar: some View {279        @Bindable var router = model.router280        return List(selection: Binding(get: { Optional(padSection) }, set: { if let s = $0 { router.section = s } })) {281            Section {282                ForEach([AppSection.home, .research]) { row($0) }283            }284            Section {285                ForEach([AppSection.markets, .quant, .portfolio]) { row($0) }286            } header: { header("Marchés et calculs") }287            Section {288                ForEach([AppSection.studio, .workspaces, .library]) { row($0) }289            } header: { header("Travaux") }290            Section {291                ForEach([AppSection.agent, .settings]) { row($0) }292            } header: { header("Compte") }293        }294        .navigationTitle("VQuant")295        .listStyle(.sidebar)296        .safeAreaInset(edge: .bottom) { SidebarStatus().padding(12) }297        .navigationSplitViewColumnWidth(min: 200, ideal: 240, max: 300)298    }299300    private func header(_ t: String) -> some View { Text(t).font(.subheadline.weight(.semibold)).foregroundStyle(Color.primary) }301302    /// `more` only exists on the iPhone; on the iPad it maps to the settings.303    private var padSection: AppSection { model.router.section == .more ? .settings : model.router.section }304305    private func row(_ s: AppSection) -> some View {306        NavigationLink(value: s) {307            Label(s.title, systemImage: s.systemImage)308                .badge(s == .research ? model.next.hub.pending.count : 0)309        }310        .accessibilityIdentifier("sidebar-\(s.rawValue)")311    }312}313314/// The list column of a three-column section (iPad).315struct PadListColumn: View {316    let section: AppSection317    // Prominent section headers: the system's small grey headers do not reach 4.5:1 on the column's background.318    var body: some View { content.paperBackground().environment(\.headerProminence, .increased) }319    @ViewBuilder private var content: some View {320        switch section {321        case .research: ResearchView()322        case .markets: MarketsView()323        case .quant: LabView()324        case .portfolio: PortfoliosListView()325        case .studio: StudioView()326        case .workspaces: WorkspacesView()327        case .library: LibraryView()328        default: EmptyView()329        }330    }331}332333/// The detail column of a three-column section: the selected item, or the section's landing view.334struct PadDetailRoot: View {335    let section: AppSection336    let route: Route?337    @Environment(AppModel.self) private var model338    var body: some View {339        if let route { RouteView(route: route) } else {340            switch section {341            case .research: ResearchLanding()342            case .markets: TerminalView()343            case .quant: LabLanding()344            case .portfolio: PortfolioView(portfolioId: model.next.portfolios.selectedId)345            case .studio: PadPlaceholder(title: "Research Studio", message: "Choisissez un projet, ou créez-en un : question, hypothèses, analyses, calculs, notes et revues automatisées au même endroit.", systemImage: "books.vertical")346            case .workspaces: PadPlaceholder(title: "Espaces de travail", message: "Un espace de travail assemble des panneaux (graphique, cotation, liste, états financiers, note, portefeuille…) dans une disposition synchronisée avec le web et le Mac.", systemImage: "rectangle.split.3x1")347            case .library: PadPlaceholder(title: "Bibliothèque", message: "Choisissez un rapport partagé.", systemImage: "tray.full")348            default: EmptyView()349            }350        }351    }352}353354struct PadPlaceholder: View {355    var title: String356    var message: String357    var systemImage: String358    var body: some View {359        ContentUnavailableView { Label(title, systemImage: systemImage) } description: { Text(message) }360            .frame(maxWidth: .infinity, maxHeight: .infinity)361            .background(Theme.background)362    }363}364365/// Bottom of the iPad sidebar: sync state, queued writes, running server jobs.366struct SidebarStatus: View {367    @Environment(AppModel.self) private var model368    var body: some View {369        VStack(alignment: .leading, spacing: 6) {370            let running = model.research.running.count + model.next.lab.running.count371            if running > 0 {372                Label("\(running) tâche\(running > 1 ? "s" : "") en cours sur le serveur", systemImage: "server.rack").font(.caption).foregroundStyle(Theme.orange)373            }374            SyncStatusChip()375        }376        .frame(maxWidth: .infinity, alignment: .leading)377    }378}379380struct SectionRoot: View {381    let section: AppSection382    @Environment(AppModel.self) private var model383    var body: some View { content.paperBackground() }384    @ViewBuilder private var content: some View {385        switch section {386        case .home: HomeView()387        case .markets: MarketsView()388        case .research: ResearchView()389        case .portfolio: PortfolioView(portfolioId: model.next.portfolios.selectedId)390        case .more: MoreView()391        case .quant: LabView()392        case .studio: StudioView()393        case .workspaces: WorkspacesView()394        case .agent: AgentView()395        case .library: LibraryView()396        case .settings: SettingsView()397        }398    }399}400401/// The view of a destination, wherever it is shown (pushed, detail column, own window).402struct RouteView: View {403    let route: Route404    var body: some View { content.paperBackground() }405    @ViewBuilder private var content: some View {406        switch route {407        case .asset(let s): AssetView(symbol: s)408        case .conversation(let id): ConversationView(sessionId: id)409        case .run(let id): RunView(jobId: id)410        case .quantTool(let id): LabFormView(toolId: id)411        case .quantJob(let id): LabJobView(jobId: id)412        case .sharedReport(let id): SharedReportView(shareId: id)413        case .quant: LabView()414        case .agent: AgentView()415        case .library: LibraryView()416        case .settings: SettingsView()417        case .search: SymbolSearchView()418        case .researchSession(let id): ResearchSessionView(workspaceId: id)419        case .approvals: ApprovalsView()420        case .terminal: TerminalView()421        case .statements(let s): StatementsView(symbol: s)422        case .chart(let s): ChartWorkstation(symbol: s)423        case .quickCalc(let k): QuickCalcView(kind: k)424        case .portfolios: PortfoliosListView()425        case .portfolio(let id): PortfolioView(portfolioId: id)426        case .studio: StudioView()427        case .project(let id): ProjectView(projectId: id)428        case .note(let id): NoteView(noteId: id)429        case .review(let id): ReviewView(reviewId: id)430        case .workspaces: WorkspacesView()431        case .workspace(let id): WorkspaceView(workspaceId: id)432        case .usage: UsageView()433        case .syncStatus: SyncStatusView()434        case .dataHealth: DataHealthView()435        }436    }437}438439extension View {440    func navigationDestinations() -> some View {441        navigationDestination(for: Route.self) { RouteView(route: $0) }442    }443}444445/// The "Plus" tab of the iPhone: everything that is not one of the four main tabs.446struct MoreView: View {447    @Environment(AppModel.self) private var model448    var body: some View {449        List {450            Section("Calculs") {451                RouteLink(.quant) { Label("Quant Lab", systemImage: "function") }.accessibilityIdentifier("more-quant")452                RouteLink(.quickCalc("option")) { Label("Prix et grecques d’une option", systemImage: "chart.line.uptrend.xyaxis") }453                RouteLink(.quickCalc("var")) { Label("VaR d’une position", systemImage: "exclamationmark.shield") }454                RouteLink(.quickCalc("sizing")) { Label("Taille de position", systemImage: "scalemass") }455            }456            Section("Travaux") {457                RouteLink(.studio) { Label("Research Studio", systemImage: "books.vertical") }.accessibilityIdentifier("more-studio")458                RouteLink(.workspaces) { Label("Espaces de travail", systemImage: "rectangle.split.3x1") }.accessibilityIdentifier("more-workspaces")459                RouteLink(.library) { Label("Bibliothèque de rapports", systemImage: "tray.full") }460            }461            Section("Agent et compte") {462                RouteLink(.agent) { Label("Agent : mémoire et veilles", systemImage: "brain") }463                RouteLink(.usage) { Label("Consommation et coûts", systemImage: "gauge.with.dots.needle.33percent") }464                RouteLink(.syncStatus) { Label("Synchronisation", systemImage: "arrow.triangle.2.circlepath") }.accessibilityIdentifier("more-sync")465                RouteLink(.settings) { Label("Réglages", systemImage: "gearshape") }.accessibilityIdentifier("more-settings")466            }467            if let a = model.account {468                Section { KeyValueRow(key: "Compte", value: a.name.isEmpty ? a.id : a.name) }469            }470        }471        .navigationTitle("Plus")472    }473}474
Files main
Menu

Theme