| @@ -0,0 +1,167 @@ |
| 1 | import Answers |
| 2 | import Feeds |
| 3 | import SkyEngine |
| 4 | import SwiftUI |
| 5 | import WidgetKit |
| 6 | |
| 7 | /// Backend base URL from Info.plist (MOONRISE_API_URL build setting). |
| 8 | let widgetAPIBase: URL? = (Bundle.main.object(forInfoDictionaryKey: "MoonriseAPIURL") as? String) |
| 9 | .flatMap { $0.isEmpty ? nil : URL(string: $0) } |
| 10 | |
| 11 | /// The place the Sky tab last used (a fix or the city chosen in Settings), shared through the App Group. |
| 12 | func sharedPlace() -> Place? { |
| 13 | Place.shared.flatMap(Place.saved) |
| 14 | } |
| 15 | |
| 16 | /// Runs `work` and hands its result to a WidgetKit completion handler, which is not Sendable. |
| 17 | func deliver<T>(_ completion: @escaping (T) -> Void, _ work: @escaping @Sendable () async -> T) { |
| 18 | nonisolated(unsafe) let completion = completion |
| 19 | Task { completion(await work()) } |
| 20 | } |
| 21 | |
| 22 | // MARK: - Kp |
| 23 | |
| 24 | struct KpEntry: TimelineEntry { |
| 25 | var date: Date |
| 26 | var weather: SpaceWeather? |
| 27 | } |
| 28 | |
| 29 | struct KpProvider: TimelineProvider { |
| 30 | func placeholder(in context: Context) -> KpEntry { |
| 31 | KpEntry(date: .now, weather: SpaceWeather(kpNow: 2.33, observedAt: .now, kpNext24h: 4)) |
| 32 | } |
| 33 | |
| 34 | func getSnapshot(in context: Context, completion: @escaping (KpEntry) -> Void) { |
| 35 | if context.isPreview { return completion(placeholder(in: context)) } |
| 36 | deliver(completion) { KpEntry(date: .now, weather: try? await SpaceWeather.fetch(base: widgetAPIBase)) } |
| 37 | } |
| 38 | |
| 39 | /// The backend polls SWPC every 5 minutes; widgets refresh every 30, or 15 after a failure. |
| 40 | func getTimeline(in context: Context, completion: @escaping (Timeline<KpEntry>) -> Void) { |
| 41 | deliver(completion) { |
| 42 | let weather = try? await SpaceWeather.fetch(base: widgetAPIBase) |
| 43 | let next = Date.now.addingTimeInterval(weather == nil ? 15 * 60 : 30 * 60) |
| 44 | return Timeline(entries: [KpEntry(date: .now, weather: weather)], policy: .after(next)) |
| 45 | } |
| 46 | } |
| 47 | } |
| 48 | |
| 49 | struct KpWidgetView: View { |
| 50 | @Environment(\.widgetFamily) var family |
| 51 | var entry: KpEntry |
| 52 | |
| 53 | private func kp(_ v: Double) -> String { v.formatted(.number.precision(.fractionLength(1))) } |
| 54 | |
| 55 | var body: some View { |
| 56 | if let w = entry.weather { |
| 57 | switch family { |
| 58 | case .accessoryCircular: |
| 59 | Gauge(value: min(w.kpNow, 9), in: 0...9) { Text("Kp") } currentValueLabel: { Text(kp(w.kpNow)) } |
| 60 | .gaugeStyle(.accessoryCircular) |
| 61 | case .accessoryInline: |
| 62 | Text("Kp \(kp(w.kpNow))" + (w.kpNext24h.map { " · up to \(kp($0)) today" } ?? "")) |
| 63 | default: |
| 64 | VStack(alignment: .leading, spacing: 1) { |
| 65 | Text("KP INDEX").font(.system(size: 11, weight: .medium)).tracking(0.6).widgetAccentable() |
| 66 | Text("\(kp(w.kpNow)) now").font(.system(size: 17, weight: .medium)).monospacedDigit() |
| 67 | if let next = w.kpNext24h { |
| 68 | Text("Up to \(kp(next)) in 24 h" + (SpaceWeather.gScale(next).map { ", G\($0)" } ?? "")) |
| 69 | .font(.system(size: 13)).monospacedDigit() |
| 70 | } |
| 71 | } |
| 72 | .frame(maxWidth: .infinity, alignment: .leading) |
| 73 | } |
| 74 | } else { |
| 75 | Text(family == .accessoryCircular ? "Kp" : "Kp unavailable") |
| 76 | } |
| 77 | } |
| 78 | } |
| 79 | |
| 80 | struct KpWidget: Widget { |
| 81 | var body: some WidgetConfiguration { |
| 82 | StaticConfiguration(kind: "kp", provider: KpProvider()) { entry in |
| 83 | KpWidgetView(entry: entry).containerBackground(.clear, for: .widget) |
| 84 | } |
| 85 | .configurationDisplayName("Kp index") |
| 86 | .description("Geomagnetic activity now and the highest forecast in the next 24 hours. Data: NOAA SWPC.") |
| 87 | .supportedFamilies([.accessoryCircular, .accessoryInline, .accessoryRectangular]) |
| 88 | } |
| 89 | } |
| 90 | |
| 91 | // MARK: - Next launch |
| 92 | |
| 93 | struct LaunchEntry: TimelineEntry { |
| 94 | var date: Date |
| 95 | var launch: Launch? |
| 96 | } |
| 97 | |
| 98 | struct NextLaunchProvider: TimelineProvider { |
| 99 | func placeholder(in context: Context) -> LaunchEntry { LaunchEntry(date: .now, launch: nil) } |
| 100 | |
| 101 | func getSnapshot(in context: Context, completion: @escaping (LaunchEntry) -> Void) { |
| 102 | deliver(completion) { LaunchEntry(date: .now, launch: await Self.next()) } |
| 103 | } |
| 104 | |
| 105 | /// Hourly, and again 15 minutes after the launch so the next one replaces it. |
| 106 | func getTimeline(in context: Context, completion: @escaping (Timeline<LaunchEntry>) -> Void) { |
| 107 | deliver(completion) { |
| 108 | let launch = await Self.next() |
| 109 | var refresh = Date.now.addingTimeInterval(3600) |
| 110 | if let net = launch?.net { refresh = min(refresh, net.addingTimeInterval(15 * 60)) } |
| 111 | return Timeline(entries: [LaunchEntry(date: .now, launch: launch)], policy: .after(refresh)) |
| 112 | } |
| 113 | } |
| 114 | |
| 115 | private static func next() async -> Launch? { |
| 116 | guard let base = widgetAPIBase, let list = try? await LaunchFeed.fetch(base: base) else { return nil } |
| 117 | return list.launches.first { $0.net > .now.addingTimeInterval(-15 * 60) } |
| 118 | } |
| 119 | } |
| 120 | |
| 121 | struct NextLaunchWidgetView: View { |
| 122 | @Environment(\.widgetFamily) var family |
| 123 | var entry: LaunchEntry |
| 124 | |
| 125 | var body: some View { |
| 126 | if let l = entry.launch { |
| 127 | let soon = l.net.timeIntervalSince(entry.date) < 24 * 3600 |
| 128 | switch family { |
| 129 | case .accessoryInline: |
| 130 | if soon { |
| 131 | Text("\(l.rocket) \(Text(l.net, style: .relative))") |
| 132 | } else { |
| 133 | Text("\(l.rocket) \(l.net.formatted(.dateTime.weekday(.abbreviated).hour().minute()))") |
| 134 | } |
| 135 | default: |
| 136 | VStack(alignment: .leading, spacing: 1) { |
| 137 | Text(l.rocket).font(.system(size: 15, weight: .medium)).lineLimit(1).widgetAccentable() |
| 138 | Text(l.mission ?? l.name).font(.system(size: 13)).lineLimit(1) |
| 139 | if soon { |
| 140 | HStack(spacing: 2) { |
| 141 | Text(l.net > entry.date ? "T−" : "T+") |
| 142 | Text(l.net, style: .timer) |
| 143 | } |
| 144 | .font(.system(size: 13, weight: .medium)).monospacedDigit() |
| 145 | } else { |
| 146 | Text(l.net.formatted(.dateTime.weekday(.abbreviated).day().month(.abbreviated).hour().minute())) |
| 147 | .font(.system(size: 13)).monospacedDigit() |
| 148 | } |
| 149 | } |
| 150 | .frame(maxWidth: .infinity, alignment: .leading) |
| 151 | } |
| 152 | } else { |
| 153 | Text("No launch data") |
| 154 | } |
| 155 | } |
| 156 | } |
| 157 | |
| 158 | struct NextLaunchWidget: Widget { |
| 159 | var body: some WidgetConfiguration { |
| 160 | StaticConfiguration(kind: "next-launch", provider: NextLaunchProvider()) { entry in |
| 161 | NextLaunchWidgetView(entry: entry).containerBackground(.clear, for: .widget) |
| 162 | } |
| 163 | .configurationDisplayName("Next launch") |
| 164 | .description("The next rocket launch with a countdown. Data: Launch Library 2.") |
| 165 | .supportedFamilies([.accessoryInline, .accessoryRectangular]) |
| 166 | } |
| 167 | } |