krz/moonrise

Night-sky companion for iPhone, Apple Watch and Vision Pro: what's up tonight, the Moon, planets, launches and missions, and a Library of the solar system. SwiftUI app with a Cloudflare Workers backend. astronomy cloudflare-workers ios night-sky space swiftui visionos watchos

Commit 846de7d47a

846de7d47a43133b39d8b9ad4b9e9f5705c9a580

parent: 69fc78ad7d

Unsigned

cmc <hello@cleberg.net> · 2026-10-22 04:31 UTC

Live Activities: meteor shower peak night (!132)

- `SkyEvent.zhr`, `moonIllumination` for meteor peaks; `SkyEvent.activityStart(now:)`: 10 min before dark, now if past, nil after dawn, beyond a day, or for other kinds.
- `MeteorActivityAttributes`, `MeteorLiveActivity`: countdown to dark then dark time left, progress across the dark window, ZHR, Moon %. No updates; stale at dawn.
- `MeteorFollowButton` on meteor rows in Events (overlay, outside the row's combined accessibility element); scheduled start with an alert.
- Debug sample.
- Tests: start rule; events carry ZHR and Moon.

Layout: unified · split

App/Shared/MeteorActivity.swift added +15
@@ -0,0 +1,15 @@
1import ActivityKit
2import Foundation
3
4/// Live Activity for a meteor shower's peak night. Computed on the device and never updated: the view runs on
5/// timers and goes stale at dawn. Shared by the app and the widget extension.
6struct MeteorActivityAttributes: ActivityAttributes {
7 struct ContentState: Codable, Hashable {}
8
9 var shower: String
10 var zhr: Int
11 /// The dark part of the night, or the whole night where it never gets fully dark.
12 var darkStart: Date
13 var darkEnd: Date
14 var moonIllumination: Double
15}
App/Sources/EventsScreen.swift +4
@@ -115,6 +115,7 @@ struct EventsScreen: View {
115 .padding(.top, 2) 115 .padding(.top, 2)
116 } 116 }
117 } 117 }
118 .padding(.trailing, e.activityStart(now: .now) != nil ? 44 : 0)
118 Spacer(minLength: 0) 119 Spacer(minLength: 0)
119 if link { 120 if link {
120 Image(systemName: "chevron.right").font(.footnote.weight(.semibold)).foregroundStyle(ink.opacity(0.4)).padding(.top, 6) 121 Image(systemName: "chevron.right").font(.footnote.weight(.semibold)).foregroundStyle(ink.opacity(0.4)).padding(.top, 6)
@@ -124,6 +125,9 @@ struct EventsScreen: View {
124 .overlay(alignment: .bottom) { Rectangle().fill(ink.opacity(0.12)).frame(height: 0.5) } 125 .overlay(alignment: .bottom) { Rectangle().fill(ink.opacity(0.12)).frame(height: 0.5) }
125 .contentShape(Rectangle()) 126 .contentShape(Rectangle())
126 .accessibilityElement(children: .combine) 127 .accessibilityElement(children: .combine)
128 .overlay(alignment: .topTrailing) {
129 if e.kind == .meteorShower { MeteorFollowButton(event: e).padding(.top, 2) }
130 }
127 } 131 }
128 132
129 private func symbol(_ k: SkyEvent.Kind) -> String { 133 private func symbol(_ k: SkyEvent.Kind) -> String {
App/Sources/MeteorFollowButton.swift added +65
@@ -0,0 +1,65 @@
1import ActivityKit
2import SkyEngine
3import SwiftUI
4
5/// Bell on a meteor shower row: puts the peak night on the Lock Screen from 10 minutes before dark. Hidden more
6/// than a day ahead.
7struct MeteorFollowButton: View {
8 var event: SkyEvent
9 @State private var following = false
10 @State private var message: String?
11
12 private var shower: String { event.title.replacingOccurrences(of: " peak", with: "") }
13
14 var body: some View {
15 if event.activityStart(now: .now) != nil {
16 Button {
17 following ? unfollow() : follow()
18 } label: {
19 Image(systemName: following ? "bell.fill" : "bell")
20 .font(.subheadline)
21 .frame(minWidth: 44, minHeight: 44)
22 .contentShape(Rectangle())
23 }
24 .buttonStyle(.plain)
25 .accessibilityLabel(following ? "Stop following on Lock Screen" : "Follow on Lock Screen")
26 .onAppear { following = Activity<MeteorActivityAttributes>.activities.contains { $0.attributes.shower == shower } }
27 .alert(message ?? "", isPresented: Binding { message != nil } set: { if !$0 { message = nil } }) {}
28 }
29 }
30
31 private func follow() {
32 guard ActivityAuthorizationInfo().areActivitiesEnabled else {
33 message = "Live Activities are turned off for Moonrise in Settings."
34 return
35 }
36 guard let start = event.activityStart(now: .now), let window = event.window else { return }
37 let attributes = MeteorActivityAttributes(shower: shower, zhr: event.zhr ?? 0, darkStart: window.start, darkEnd: window.end,
38 moonIllumination: event.moonIllumination ?? 0)
39 let content = ActivityContent(state: MeteorActivityAttributes.ContentState(), staleDate: window.end)
40 do {
41 if start > .now {
42 let alert = AlertConfiguration(
43 title: "\(event.title) tonight",
44 body: "Dark from \(window.start.formatted(date: .omitted, time: .shortened)). Up to \(attributes.zhr) meteors an hour under dark skies.",
45 sound: .default)
46 _ = try Activity.request(attributes: attributes, content: content, style: .standard, alertConfiguration: alert, start: start)
47 } else {
48 _ = try Activity.request(attributes: attributes, content: content)
49 }
50 following = true
51 } catch {
52 message = "Couldn't add the shower: \(error.localizedDescription)"
53 }
54 }
55
56 private func unfollow() {
57 let shower = shower
58 Task {
59 for a in Activity<MeteorActivityAttributes>.activities where a.attributes.shower == shower {
60 await a.end(nil, dismissalPolicy: .immediate)
61 }
62 following = false
63 }
64 }
65}
App/Sources/SampleActivities.swift +10
@@ -13,6 +13,7 @@ struct SampleActivitiesSection: View {
13 Button("Launch at T−5 minutes") { startLaunch() } 13 Button("Launch at T−5 minutes") { startLaunch() }
14 Button("Eclipse, first contact in 3 minutes") { startEclipse() } 14 Button("Eclipse, first contact in 3 minutes") { startEclipse() }
15 Button("G2 storm") { startStorm() } 15 Button("G2 storm") { startStorm() }
16 Button("Meteor shower, dark in 2 minutes") { startMeteors() }
16 Button("End all sample activities", role: .destructive) { Task { await endAll() } } 17 Button("End all sample activities", role: .destructive) { Task { await endAll() } }
17 if let message { 18 if let message {
18 Text(message).font(.footnote).foregroundStyle(.secondary) 19 Text(message).font(.footnote).foregroundStyle(.secondary)
@@ -53,6 +54,12 @@ struct SampleActivitiesSection: View {
53 request(StormActivityAttributes(startedAt: .now), ActivityContent(state: state, staleDate: .now.addingTimeInterval(45 * 60))) 54 request(StormActivityAttributes(startedAt: .now), ActivityContent(state: state, staleDate: .now.addingTimeInterval(45 * 60)))
54 } 55 }
55 56
57 private func startMeteors() {
58 let dark = Date.now.addingTimeInterval(120)
59 let attributes = MeteorActivityAttributes(shower: "Test", zhr: 100, darkStart: dark, darkEnd: dark.addingTimeInterval(1800), moonIllumination: 0.2)
60 request(attributes, ActivityContent(state: .init(), staleDate: attributes.darkEnd))
61 }
62
56 private func request<A: ActivityAttributes>(_ attributes: A, _ content: ActivityContent<A.ContentState>) { 63 private func request<A: ActivityAttributes>(_ attributes: A, _ content: ActivityContent<A.ContentState>) {
57 guard ActivityAuthorizationInfo().areActivitiesEnabled else { 64 guard ActivityAuthorizationInfo().areActivitiesEnabled else {
58 message = "Live Activities are turned off for Moonrise in Settings." 65 message = "Live Activities are turned off for Moonrise in Settings."
@@ -73,6 +80,9 @@ struct SampleActivitiesSection: View {
73 for a in Activity<LaunchActivityAttributes>.activities where a.attributes.launchID == "sample" { 80 for a in Activity<LaunchActivityAttributes>.activities where a.attributes.launchID == "sample" {
74 await a.end(nil, dismissalPolicy: .immediate) 81 await a.end(nil, dismissalPolicy: .immediate)
75 } 82 }
83 for a in Activity<MeteorActivityAttributes>.activities where a.attributes.shower == "Test" {
84 await a.end(nil, dismissalPolicy: .immediate)
85 }
76 for a in Activity<EclipseActivityAttributes>.activities where a.attributes.site == "Test site" { 86 for a in Activity<EclipseActivityAttributes>.activities where a.attributes.site == "Test site" {
77 await a.end(nil, dismissalPolicy: .immediate) 87 await a.end(nil, dismissalPolicy: .immediate)
78 } 88 }
App/Widgets/MeteorLiveActivity.swift added +112
@@ -0,0 +1,112 @@
1import ActivityKit
2import SwiftUI
3import WidgetKit
4
5struct MeteorLiveActivity: Widget {
6 private let ink = Color(red: 0.95, green: 0.95, blue: 0.93)
7
8 var body: some WidgetConfiguration {
9 ActivityConfiguration(for: MeteorActivityAttributes.self) { context in
10 MeteorActivityView(context: context, ink: ink)
11 .foregroundStyle(ink)
12 } dynamicIsland: { context in
13 DynamicIsland {
14 DynamicIslandExpandedRegion(.leading) {
15 Text(context.attributes.shower).font(.system(size: 14, weight: .medium)).lineLimit(1)
16 }
17 DynamicIslandExpandedRegion(.trailing) {
18 countdown(context.attributes).font(.system(size: 14, weight: .medium).monospacedDigit())
19 }
20 DynamicIslandExpandedRegion(.bottom) {
21 VStack(alignment: .leading, spacing: 6) {
22 Text(summary(context.attributes)).font(.system(size: 12)).lineLimit(1).opacity(0.8)
23 darkProgress(context.attributes, ink: ink)
24 }
25 }
26 } compactLeading: {
27 Image(systemName: "sparkles")
28 } compactTrailing: {
29 countdown(context.attributes).font(.system(size: 12).monospacedDigit())
30 } minimal: {
31 Image(systemName: "sparkles")
32 }
33 }
34 .supplementalActivityFamilies([.small])
35 }
36}
37
38private func time(_ d: Date) -> String { d.formatted(date: .omitted, time: .shortened) }
39
40/// To dark, then the dark time left.
41private func countdown(_ m: MeteorActivityAttributes) -> Text {
42 liveTimer(m.darkStart > .now ? m.darkStart : m.darkEnd)
43}
44
45private func summary(_ m: MeteorActivityAttributes) -> String {
46 "Up to \(m.zhr) an hour · dark \(time(m.darkStart))–\(time(m.darkEnd)) · Moon \(Int((m.moonIllumination * 100).rounded()))%"
47}
48
49private func darkProgress(_ m: MeteorActivityAttributes, ink: Color) -> some View {
50 ProgressView(timerInterval: m.darkStart...m.darkEnd, countsDown: false) { EmptyView() } currentValueLabel: { EmptyView() }
51 .tint(ink)
52}
53
54private struct MeteorActivityView: View {
55 @Environment(\.activityFamily) private var family
56 @Environment(\.isActivityFullscreen) private var fullscreen
57 var context: ActivityViewContext<MeteorActivityAttributes>
58 var ink: Color
59
60 private var m: MeteorActivityAttributes { context.attributes }
61
62 var body: some View {
63 Group {
64 if family == .small { small } else { medium }
65 }
66 // StandBy: black, to blend with the clock face.
67 .activityBackgroundTint(fullscreen ? .black : Color(red: 0.043, green: 0.078, blue: 0.141))
68 }
69
70 /// Apple Watch Smart Stack and CarPlay.
71 private var small: some View {
72 VStack(alignment: .leading, spacing: 2) {
73 Text(m.shower).font(.system(size: 13, weight: .medium)).lineLimit(1)
74 if context.isStale {
75 Text("Dawn \(time(m.darkEnd))").font(.system(size: 13).monospacedDigit()).opacity(0.8)
76 } else {
77 countdown(m).font(.system(size: 17, weight: .medium).monospacedDigit())
78 }
79 }
80 .frame(maxWidth: .infinity, alignment: .leading)
81 .padding(12)
82 }
83
84 private var medium: some View {
85 VStack(alignment: .leading, spacing: 8) {
86 HStack(alignment: .firstTextBaseline) {
87 Text("\(m.shower) peak").font(.system(size: 11, weight: .medium)).textCase(.uppercase).tracking(0.6).opacity(0.8)
88 Spacer()
89 if !context.isStale {
90 Text(m.darkStart > .now ? "dark in" : "dark for").font(.system(size: 11)).opacity(0.7)
91 countdown(m).font(.system(size: 17, weight: .medium).monospacedDigit()).frame(minWidth: 60, alignment: .trailing)
92 }
93 }
94 Text(summary(m)).font(.system(size: 13)).lineLimit(1)
95 if context.isStale {
96 Text("Over at dawn, \(time(m.darkEnd))").font(.system(size: 12)).opacity(0.8)
97 } else {
98 darkProgress(m, ink: ink)
99 }
100 }
101 .padding(16)
102 }
103}
104
105#if DEBUG
106#Preview("Lock Screen", as: .content, using: MeteorActivityAttributes(shower: "Orionids", zhr: 20, darkStart: .now.addingTimeInterval(-3600),
107 darkEnd: .now.addingTimeInterval(5 * 3600), moonIllumination: 0.02)) {
108 MeteorLiveActivity()
109} contentStates: {
110 MeteorActivityAttributes.ContentState()
111}
112#endif
App/Widgets/MoonriseWidgets.swift +1
@@ -22,6 +22,7 @@ struct MoonriseWidgets: WidgetBundle {
22 EclipseLiveActivity() 22 EclipseLiveActivity()
23 PassLiveActivity() 23 PassLiveActivity()
24 StormLiveActivity() 24 StormLiveActivity()
25 MeteorLiveActivity()
25 #endif 26 #endif
26 } 27 }
27} 28}
PLAN.org +3 −1
@@ -576,7 +576,9 @@ Worker; DSN Now freshness; NASA/ESA image licences; 26 LoC plates bundled.
576 Done (storm): a broadcast channel pair per storm (Kp 5 now or within 3 576 Done (storm): a broadcast channel pair per storm (Kp 5 now or within 3
577 hours, or a strongly southward wind), updated on each change of G level 577 hours, or a strongly southward wind), updated on each change of G level
578 and every 30 minutes, ended after 3 calm hours; =/v1/today.storm= names 578 and every 30 minutes, ended after 3 calm hours; =/v1/today.storm= names
579 the channels; Follow on the Sun tab's Kp section. 579 the channels; Follow on the Sun tab's Kp section. Done (meteors): a bell
580 on each peak in Events within a day; computed on the device, from 10
581 minutes before dark to dawn.
580- Push-to-start for followed launches: needs per-device tokens stored on the 582- Push-to-start for followed launches: needs per-device tokens stored on the
581 Worker, a privacy policy change and a matching App Store privacy label. 583 Worker, a privacy policy change and a matching App Store privacy label.
582 584
Packages/MoonriseKit/Sources/SkyEngine/Events.swift +14 −1
@@ -15,9 +15,21 @@ public struct SkyEvent: Sendable, Identifiable, Equatable {
15 /// When to look, for a forecast: the dark part of a meteor shower's peak night (the whole night where it never gets 15 /// When to look, for a forecast: the dark part of a meteor shower's peak night (the whole night where it never gets
16 /// fully dark), or greatest eclipse here as a zero-length interval. Nil for other events and eclipses not seen here. 16 /// fully dark), or greatest eclipse here as a zero-length interval. Nil for other events and eclipses not seen here.
17 public var window: DateInterval? 17 public var window: DateInterval?
18 /// A meteor shower's zenithal hourly rate at peak, and the Moon's lit fraction at local midnight of the peak night.
19 public var zhr: Int?
20 public var moonIllumination: Double?
18 public var id: String { "\(kind.rawValue)-\(title)-\(Int(date.timeIntervalSince1970))" } 21 public var id: String { "\(kind.rawValue)-\(title)-\(Int(date.timeIntervalSince1970))" }
19} 22}
20 23
24extension SkyEvent {
25 /// When a Lock Screen activity for a meteor shower's peak night starts: 10 minutes before dark, or `now` if that
26 /// has passed. Nil for other events, once the night is over, or more than a day ahead.
27 public func activityStart(now: Date) -> Date? {
28 guard kind == .meteorShower, let window, window.end > now, window.start.timeIntervalSince(now) <= 86_400 else { return nil }
29 return max(now, window.start.addingTimeInterval(-600))
30 }
31}
32
21/// A major annual meteor shower (International Meteor Organization working list). 33/// A major annual meteor shower (International Meteor Organization working list).
22public struct MeteorShower: Sendable { 34public struct MeteorShower: Sendable {
23 public var name: String 35 public var name: String
@@ -157,7 +169,8 @@ extension SkyEngine {
157 let dark = try? darkness(from: night.start, to: night.end, observer: observer) 169 let dark = try? darkness(from: night.start, to: night.end, observer: observer)
158 let moon = moonAndDarkness(night: night, dark: dark, 170 let moon = moonAndDarkness(night: night, dark: dark,
159 moonUp: (try? moonUp(from: night.start, to: night.end, observer: observer)) ?? [], moonIllumination: lit) 171 moonUp: (try? moonUp(from: night.start, to: night.end, observer: observer)) ?? [], moonIllumination: lit)
160 out.append(SkyEvent(kind: .meteorShower, date: d, title: "\(m.name) peak", detail: "Up to about \(m.zhr) meteors an hour under dark skies. \(moon)", visibleHere: nil, window: dark ?? night)) 172 out.append(SkyEvent(kind: .meteorShower, date: d, title: "\(m.name) peak", detail: "Up to about \(m.zhr) meteors an hour under dark skies. \(moon)", visibleHere: nil, window: dark ?? night,
173 zhr: m.zhr, moonIllumination: lit))
161 } 174 }
162 } 175 }
163 176
Packages/MoonriseKit/Tests/SkyEngineTests/MeteorActivityTests.swift added +28
@@ -0,0 +1,28 @@
1import Foundation
2import Testing
3@testable import SkyEngine
4
5private let now = Date(timeIntervalSince1970: 1_792_364_400)
6
7private func peak(darkIn seconds: TimeInterval, kind: SkyEvent.Kind = .meteorShower) -> SkyEvent {
8 SkyEvent(kind: kind, date: now, title: "Orionids peak", detail: "", visibleHere: nil,
9 window: DateInterval(start: now.addingTimeInterval(seconds), duration: 8 * 3600), zhr: 20, moonIllumination: 0.1)
10}
11
12@Test func meteorActivityStartsTenMinutesBeforeDark() {
13 #expect(peak(darkIn: 3600).activityStart(now: now) == now.addingTimeInterval(3000))
14 #expect(peak(darkIn: 300).activityStart(now: now) == now)
15 #expect(peak(darkIn: -3600).activityStart(now: now) == now)
16}
17
18@Test func noMeteorActivityAfterTheNightBeyondADayOrForOtherEvents() {
19 #expect(peak(darkIn: -8 * 3600).activityStart(now: now) == nil)
20 #expect(peak(darkIn: 86_401).activityStart(now: now) == nil)
21 #expect(peak(darkIn: 3600, kind: .opposition).activityStart(now: now) == nil)
22}
23
24@Test func meteorPeaksCarryRateAndMoon() throws {
25 let e = try #require(SkyEngine.events(from: now, observer: Observer(latitude: 41.88, longitude: -87.63)).first { $0.kind == .meteorShower })
26 #expect(e.zhr != nil)
27 #expect((0...1).contains(try #require(e.moonIllumination)))
28}