Repository Public
1//2// VQuant iOS3// File: VQuantWidgets/VQuantWidgets.swift4// Description: Home-screen and Lock-screen widgets: markets, watchlist, a favourite asset, server jobs. They display the5// snapshot the app left in the shared container, always with the time the values were fetched.6//7// Author: Simon-Pierre Boucher8// Contact: contact@spboucher.ai9//1011import AppIntents12import SwiftUI13import WidgetKit1415struct SnapshotEntry: TimelineEntry {16 let date: Date17 let snapshot: WidgetSnapshot?18 var symbol: String?19 /// Values older than this are flagged as stale on the widget.20 static let staleAfter: TimeInterval = 30 * 6021 var isStale: Bool { snapshot.map { date.timeIntervalSince($0.fetchedAt) > Self.staleAfter } ?? true }22}2324/// The widgets have no network access of their own and hold no credential: the app refreshes the snapshot when it25/// is used and during background refreshes. The timeline only re-reads the file and ages the "as of" label.26struct SnapshotProvider: TimelineProvider {27 func placeholder(in context: Context) -> SnapshotEntry { SnapshotEntry(date: Date(), snapshot: nil) }28 func getSnapshot(in context: Context, completion: @escaping (SnapshotEntry) -> Void) {29 completion(SnapshotEntry(date: Date(), snapshot: WidgetSnapshot.load(from: SharedContainer.snapshotURL)))30 }31 func getTimeline(in context: Context, completion: @escaping (Timeline<SnapshotEntry>) -> Void) {32 let snap = WidgetSnapshot.load(from: SharedContainer.snapshotURL)33 let now = Date()34 // Two entries: now, and the moment the data becomes stale, so the warning appears without a reload.35 var entries = [SnapshotEntry(date: now, snapshot: snap)]36 if let s = snap, s.fetchedAt.addingTimeInterval(SnapshotEntry.staleAfter) > now { entries.append(SnapshotEntry(date: s.fetchedAt.addingTimeInterval(SnapshotEntry.staleAfter + 1), snapshot: snap)) }37 completion(Timeline(entries: entries, policy: .after(now.addingTimeInterval(15 * 60))))38 }39}4041// MARK: - shared pieces4243struct AsOfLabel: View {44 let entry: SnapshotEntry45 var body: some View {46 if let s = entry.snapshot {47 HStack(spacing: 3) {48 if entry.isStale { Image(systemName: "clock.badge.exclamationmark") }49 Text(entry.isStale ? "Données de \(s.fetchedAt.formatted(date: .omitted, time: .shortened))" : "À \(s.fetchedAt.formatted(date: .omitted, time: .shortened))")50 }51 .font(.system(size: 10, weight: .medium)).foregroundStyle(entry.isStale ? Theme.warning : Theme.textSecondary)52 .accessibilityLabel(entry.isStale ? "Données anciennes, relevées à \(s.fetchedAt.formatted(date: .omitted, time: .shortened))" : "Relevé à \(s.fetchedAt.formatted(date: .omitted, time: .shortened))")53 }54 }55}5657struct WidgetRow: View {58 let row: WidgetSnapshot.Row59 var body: some View {60 HStack(spacing: 6) {61 Text(row.symbol.replacingOccurrences(of: "^", with: "")).font(.caption.weight(.semibold)).lineLimit(1)62 Spacer(minLength: 4)63 Text(Fmt.price(row.price)).font(.caption.monospacedDigit())64 Text(Fmt.percent(row.changePercent)).font(.caption2.monospacedDigit().weight(.semibold)).foregroundStyle(Theme.direction(row.changePercent))65 .frame(minWidth: 54, alignment: .trailing)66 }67 .accessibilityElement(children: .combine)68 }69}7071struct WidgetEmpty: View {72 var signedOut: Bool73 var body: some View {74 VStack(spacing: 6) {75 SparkleMark().frame(width: 28, height: 28)76 Text(signedOut ? "Connectez-vous dans VQuant" : "Ouvrez VQuant pour charger les données").font(.caption2).multilineTextAlignment(.center).foregroundStyle(Theme.textSecondary)77 }78 }79}8081struct WidgetHeader: View {82 let title: String83 let entry: SnapshotEntry84 var body: some View {85 HStack {86 SparkleMark().frame(width: 14, height: 14)87 Text(title).font(.caption.weight(.semibold))88 Spacer()89 AsOfLabel(entry: entry)90 }91 }92}9394// MARK: - Markets9596struct MarketsWidget: Widget {97 var body: some WidgetConfiguration {98 StaticConfiguration(kind: "VQuantMarkets", provider: SnapshotProvider()) { entry in99 MarketsWidgetView(entry: entry).containerBackground(Theme.background, for: .widget)100 }101 .configurationDisplayName("Marchés")102 .description("Les grands indices, avec l’heure du relevé.")103 .supportedFamilies([.systemSmall, .systemMedium, .accessoryRectangular])104 }105}106107struct MarketsWidgetView: View {108 let entry: SnapshotEntry109 @Environment(\.widgetFamily) private var family110 var body: some View {111 if let s = entry.snapshot, s.signedIn, !s.indices.isEmpty {112 switch family {113 case .accessoryRectangular:114 VStack(alignment: .leading, spacing: 1) { ForEach(s.indices.prefix(3)) { r in115 HStack { Text(r.name ?? r.symbol).lineLimit(1); Spacer(); Text(Fmt.percent(r.changePercent)).monospacedDigit() }.font(.caption2)116 } }117 default:118 VStack(alignment: .leading, spacing: 5) {119 WidgetHeader(title: "Marchés", entry: entry)120 ForEach(s.indices.prefix(family == .systemSmall ? 3 : 4)) { r in121 if family == .systemSmall { smallRow(r) } else { WidgetRow(row: WidgetSnapshot.Row(symbol: r.name ?? r.symbol, name: nil, price: r.price, changePercent: r.changePercent)) }122 }123 Spacer(minLength: 0)124 }125 .widgetURL(URL(string: "vquant://markets"))126 }127 } else { WidgetEmpty(signedOut: entry.snapshot?.signedIn == false) }128 }129 private func smallRow(_ r: WidgetSnapshot.Row) -> some View {130 HStack {131 Text(r.name ?? r.symbol).font(.caption2).lineLimit(1)132 Spacer(minLength: 2)133 Text(Fmt.percent(r.changePercent)).font(.caption2.monospacedDigit().weight(.semibold)).foregroundStyle(Theme.direction(r.changePercent))134 }135 }136}137138// MARK: - Watchlist139140struct WatchlistWidget: Widget {141 var body: some WidgetConfiguration {142 StaticConfiguration(kind: "VQuantWatchlist", provider: SnapshotProvider()) { entry in143 WatchlistWidgetView(entry: entry).containerBackground(Theme.background, for: .widget)144 }145 .configurationDisplayName("Liste de suivi")146 .description("Les actifs de votre liste de suivi synchronisée, avec l’heure du relevé.")147 .supportedFamilies([.systemMedium, .systemLarge])148 }149}150151struct WatchlistWidgetView: View {152 let entry: SnapshotEntry153 @Environment(\.widgetFamily) private var family154 var body: some View {155 if let s = entry.snapshot, s.signedIn, !s.watchlist.isEmpty {156 VStack(alignment: .leading, spacing: 5) {157 WidgetHeader(title: s.watchlistName ?? "Liste de suivi", entry: entry)158 ForEach(s.watchlist.prefix(family == .systemLarge ? 8 : 4)) { r in159 Link(destination: URL(string: "vquant://asset/\(r.symbol.addingPercentEncoding(withAllowedCharacters: .urlPathAllowed) ?? r.symbol)")!) { WidgetRow(row: r) }160 }161 Spacer(minLength: 0)162 }163 } else { WidgetEmpty(signedOut: entry.snapshot?.signedIn == false) }164 }165}166167// MARK: - Favourite asset (configurable)168169struct SymbolEntity: AppEntity {170 static let typeDisplayRepresentation: TypeDisplayRepresentation = "Actif"171 static let defaultQuery = SymbolQuery()172 var id: String173 var name: String?174 var displayRepresentation: DisplayRepresentation { DisplayRepresentation(title: "\(id)", subtitle: name.map { "\($0)" }) }175}176177/// The choices are the device's watchlist.178struct SymbolQuery: EntityQuery {179 func entities(for identifiers: [String]) async throws -> [SymbolEntity] {180 let list = WatchlistFile(url: SharedContainer.watchlistURL).load()181 return identifiers.map { id in SymbolEntity(id: id, name: list.first { $0.symbol == id }?.name) }182 }183 func suggestedEntities() async throws -> [SymbolEntity] {184 WatchlistFile(url: SharedContainer.watchlistURL).load().map { SymbolEntity(id: $0.symbol, name: $0.name) }185 }186 func defaultResult() async -> SymbolEntity? { try? await suggestedEntities().first }187}188189struct FavouriteAssetConfiguration: WidgetConfigurationIntent {190 static let title: LocalizedStringResource = "Actif favori"191 static let description = IntentDescription("Choisissez un actif de votre liste de suivi.")192 @Parameter(title: "Actif") var asset: SymbolEntity?193}194195struct FavouriteProvider: AppIntentTimelineProvider {196 func placeholder(in context: Context) -> SnapshotEntry { SnapshotEntry(date: Date(), snapshot: nil) }197 func snapshot(for configuration: FavouriteAssetConfiguration, in context: Context) async -> SnapshotEntry {198 SnapshotEntry(date: Date(), snapshot: WidgetSnapshot.load(from: SharedContainer.snapshotURL), symbol: configuration.asset?.id)199 }200 func timeline(for configuration: FavouriteAssetConfiguration, in context: Context) async -> Timeline<SnapshotEntry> {201 let snap = WidgetSnapshot.load(from: SharedContainer.snapshotURL), now = Date()202 var entries = [SnapshotEntry(date: now, snapshot: snap, symbol: configuration.asset?.id)]203 if let s = snap, s.fetchedAt.addingTimeInterval(SnapshotEntry.staleAfter) > now {204 entries.append(SnapshotEntry(date: s.fetchedAt.addingTimeInterval(SnapshotEntry.staleAfter + 1), snapshot: snap, symbol: configuration.asset?.id))205 }206 return Timeline(entries: entries, policy: .after(now.addingTimeInterval(15 * 60)))207 }208}209210struct FavouriteAssetWidget: Widget {211 var body: some WidgetConfiguration {212 AppIntentConfiguration(kind: "VQuantFavourite", intent: FavouriteAssetConfiguration.self, provider: FavouriteProvider()) { entry in213 FavouriteWidgetView(entry: entry).containerBackground(Theme.background, for: .widget)214 }215 .configurationDisplayName("Actif favori")216 .description("Le cours d’un actif de votre liste de suivi.")217 .supportedFamilies([.systemSmall, .accessoryRectangular, .accessoryInline])218 }219}220221struct FavouriteWidgetView: View {222 let entry: SnapshotEntry223 @Environment(\.widgetFamily) private var family224 private var row: WidgetSnapshot.Row? {225 guard let s = entry.snapshot, s.signedIn else { return nil }226 return s.watchlist.first { $0.symbol == entry.symbol } ?? (entry.symbol == nil ? s.watchlist.first : nil)227 }228 var body: some View {229 if let r = row {230 switch family {231 case .accessoryInline: Text("\(r.symbol) \(Fmt.price(r.price)) \(Fmt.percent(r.changePercent))")232 case .accessoryRectangular:233 VStack(alignment: .leading) { Text(r.symbol).font(.headline); Text("\(Fmt.price(r.price)) \(Fmt.percent(r.changePercent))").font(.caption.monospacedDigit()); AsOfLabel(entry: entry) }234 default:235 VStack(alignment: .leading, spacing: 4) {236 HStack { Text(r.symbol.replacingOccurrences(of: "^", with: "")).font(.headline); Spacer(); SparkleMark().frame(width: 14, height: 14) }237 if let n = r.name { Text(n).font(.caption2).foregroundStyle(Theme.textSecondary).lineLimit(1) }238 Spacer(minLength: 0)239 Text(Fmt.price(r.price)).font(.title2.weight(.semibold).monospacedDigit()).minimumScaleFactor(0.6)240 Text(Fmt.percent(r.changePercent)).font(.caption.monospacedDigit().weight(.semibold)).foregroundStyle(Theme.direction(r.changePercent))241 AsOfLabel(entry: entry)242 }243 .widgetURL(URL(string: "vquant://asset/\(r.symbol.addingPercentEncoding(withAllowedCharacters: .urlPathAllowed) ?? r.symbol)"))244 }245 } else if entry.symbol != nil, entry.snapshot?.signedIn == true {246 Text("Aucun cours relevé pour \(entry.symbol!). Ouvrez VQuant.").font(.caption2).foregroundStyle(Theme.textSecondary)247 } else { WidgetEmpty(signedOut: entry.snapshot?.signedIn == false) }248 }249}250251// MARK: - Server jobs252253/// Research on the server: what runs, what waits for an authorisation, and the latest studies of the account.254/// (Kind kept from 1.0 so a widget already on a Home Screen keeps working.)255struct JobsWidget: Widget {256 var body: some WidgetConfiguration {257 StaticConfiguration(kind: "VQuantJobs", provider: SnapshotProvider()) { entry in258 JobsWidgetView(entry: entry).containerBackground(Theme.background, for: .widget)259 }260 .configurationDisplayName("Recherche")261 .description("Les études en cours sur le serveur, les demandes d’autorisation et les dernières études, telles que relevées à l’heure indiquée.")262 .supportedFamilies([.systemSmall, .systemMedium])263 }264}265266struct JobsWidgetView: View {267 let entry: SnapshotEntry268 @Environment(\.widgetFamily) private var family269 var body: some View {270 if let s = entry.snapshot, s.signedIn {271 let running = s.jobs.filter { $0.status == "running" }272 let studies = s.research ?? []273 let approvals = s.pendingApprovals ?? 0274 VStack(alignment: .leading, spacing: 5) {275 WidgetHeader(title: "Recherche", entry: entry)276 if approvals > 0 {277 Label("\(approvals) autorisation\(approvals > 1 ? "s" : "") en attente", systemImage: "hand.raised.fill").font(.caption2.weight(.semibold)).foregroundStyle(Theme.warning)278 }279 if family == .systemSmall {280 Text("\(running.count)").font(.system(.title, design: .monospaced).weight(.medium))281 Text(running.count > 1 ? "études en cours" : "étude en cours").font(.caption2).foregroundStyle(Theme.textSecondary)282 if let first = running.first ?? s.jobs.first { Text(first.query).font(.caption2).lineLimit(2).privacySensitive() }283 } else {284 if s.jobs.isEmpty && studies.isEmpty { Text("Aucune étude dans les dernières 24 heures.").font(.caption2).foregroundStyle(Theme.textSecondary) }285 ForEach(s.jobs.prefix(approvals > 0 ? 2 : 3)) { j in286 HStack(spacing: 6) {287 Image(systemName: j.status == "running" ? "hourglass" : j.status == "done" ? "checkmark.circle.fill" : "exclamationmark.triangle.fill")288 .font(.caption2).foregroundStyle(j.status == "running" ? Theme.orange : j.status == "done" ? Theme.up : Theme.down)289 // The question itself is personal: hidden on the Lock Screen and in redacted contexts.290 Text(j.query).font(.caption2).lineLimit(1).privacySensitive()291 Spacer(minLength: 2)292 Text(j.status == "running" ? "en cours" : j.status == "done" ? "terminée" : "arrêtée").font(.system(size: 10)).foregroundStyle(Theme.textSecondary)293 }294 .accessibilityElement(children: .combine)295 }296 if s.jobs.count < 3 {297 ForEach(studies.prefix(3 - min(3, s.jobs.count))) { st in298 HStack(spacing: 6) {299 Image(systemName: "flask").font(.caption2).foregroundStyle(Theme.textSecondary)300 Text(st.title).font(.caption2).lineLimit(1).privacySensitive()301 Spacer(minLength: 2)302 Text(st.updatedAt.formatted(.relative(presentation: .numeric, unitsStyle: .narrow))).font(.system(size: 10)).foregroundStyle(Theme.textSecondary)303 }304 .accessibilityElement(children: .combine)305 }306 }307 }308 Spacer(minLength: 0)309 }310 .widgetURL(URL(string: approvals > 0 ? "vquant://approvals" : "vquant://research"))311 } else { WidgetEmpty(signedOut: entry.snapshot?.signedIn == false) }312 }313}314315@main316struct VQuantWidgetBundle: WidgetBundle {317 var body: some Widget {318 MarketsWidget()319 WatchlistWidget()320 FavouriteAssetWidget()321 JobsWidget()322 }323}324