iOS: overdue count on the app icon !210

merged merged by cmc on 2026-10-10 19:17 UTC · krz/orgstar:overdue-badge into main

6 files changed, +109 −4

Layout: unified · split

Sources/OrgApp/OverdueBadge.swift added +22
@@ -0,0 +1,22 @@
1import Foundation
2import OrgPresentation
3
4/// The app icon's badge: the entries in the agenda's Overdue section that aren't done.
5public enum OverdueBadge {
6 /// The count for each day from `today`, for `days` days, if nothing is done meanwhile: today's
7 /// overdue entries, then each day's scheduled and deadline entries once their day has passed.
8 public static func counts(_ groups: [AgendaDayGroup], today: Int, days: Int) -> [Int] {
9 func key(_ row: AgendaRow) -> String? {
10 guard let item = row.item, !row.isDone, item.habit == nil, row.planningDay != nil else { return nil }
11 return "\(item.path):\(item.headingOffset ?? item.markerOffset)"
12 }
13 var overdue = Set(groups.first { $0.day == today }?.overdue.compactMap(key) ?? [])
14 var counts = [overdue.count]
15 for day in today..<(today + days - 1) {
16 let rows = groups.first { $0.day == day }?.rows ?? []
17 overdue.formUnion(rows.filter { $0.planningDay == day }.compactMap(key))
18 counts.append(overdue.count)
19 }
20 return counts
21 }
22}
Sources/OrgApp/ReminderScheduler.swift +8 −1
@@ -77,7 +77,14 @@ public struct SystemReminderCenter: ReminderCenter {
7777 let settings = await center.notificationSettings()
7878 switch settings.authorizationStatus {
7979 case .authorized, .provisional: return true
80 case .notDetermined: return (try? await center.requestAuthorization(options: [.alert, .sound])) ?? false
80 case .notDetermined:
81 // iOS shows the overdue count on the icon.
82 #if os(iOS)
83 let options: UNAuthorizationOptions = [.alert, .sound, .badge]
84 #else
85 let options: UNAuthorizationOptions = [.alert, .sound]
86 #endif
87 return (try? await center.requestAuthorization(options: options)) ?? false
8188 default: return false
8289 }
8390 }
Sources/OrgstarMobile/MobileModel.swift +25 −2
@@ -7,6 +7,7 @@ import OrgIndex
77import OrgPresentation
88import OrgWorkspace
99import UIKit
10import UserNotifications
1011import WidgetKit
1112
1213/// The app's models, and the settings from the configuration folder: a folder you choose
@@ -246,11 +247,11 @@ final class MobileModel {
246247 }
247248
248249 /// The widgets' agenda: today and the next days in the app group's container, with the
249 /// widgets reloaded when it changed.
250 /// widgets reloaded when it changed; and the icon's overdue badge.
250251 func updateWidgets() async {
251252 let interval = Perf.begin("widgets.update")
252253 defer { interval.end() }
253 guard let workspace, let file = AgendaSnapshot.file() else { return }
254 guard let workspace else { return }
254255 let days = AgendaModel(workspace: workspace, cache: agenda?.cache ?? AgendaSourceCache())
255256 days.mode = .agenda(span: AgendaSnapshot.dayCount, startOffset: 0)
256257 if let agenda {
@@ -261,8 +262,30 @@ final class MobileModel {
261262 days.calendarNames = agenda.calendarNames
262263 }
263264 await days.refresh(open: session.openTexts)
265 await updateBadge(OverdueBadge.counts(days.groups(), today: days.today, days: AgendaSnapshot.dayCount))
266 guard let file = AgendaSnapshot.file() else { return }
264267 let snapshot = AgendaSnapshot(groups: days.groups(), today: days.today, theme: theme, generated: Date())
265268 if (try? snapshot.write(to: file)) == true { WidgetCenter.shared.reloadAllTimelines() }
266269 }
270
271 /// Today's count on the icon, and each later day's set for its midnight by a notification
272 /// that only changes the badge.
273 private func updateBadge(_ counts: [Int]) async {
274 let center = UNUserNotificationCenter.current()
275 guard await SystemReminderCenter().authorize(), await center.notificationSettings().badgeSetting == .enabled else { return }
276 try? await center.setBadgeCount(counts.first ?? 0)
277 center.removePendingNotificationRequests(withIdentifiers: (1..<AgendaSnapshot.dayCount).map(Self.badgeID))
278 let today = Calendar.current.startOfDay(for: Date())
279 for (offset, count) in counts.enumerated().dropFirst() {
280 guard let midnight = Calendar.current.date(byAdding: .day, value: offset, to: today) else { continue }
281 let content = UNMutableNotificationContent()
282 content.badge = NSNumber(value: count)
283 let components = Calendar.current.dateComponents([.year, .month, .day, .hour, .minute], from: midnight)
284 let trigger = UNCalendarNotificationTrigger(dateMatching: components, repeats: false)
285 try? await center.add(UNNotificationRequest(identifier: Self.badgeID(offset), content: content, trigger: trigger))
286 }
287 }
288
289 static func badgeID(_ offset: Int) -> String { "badge.\(offset)" }
267290}
268291#endif
Sources/OrgstarMobile/OrgstarMobileApp.swift +3 −1
@@ -45,7 +45,9 @@ final class AppDelegate: NSObject, UIApplicationDelegate, UNUserNotificationCent
4545 }
4646
4747 nonisolated func userNotificationCenter(_ center: UNUserNotificationCenter, willPresent notification: UNNotification) async -> UNNotificationPresentationOptions {
48 [.banner, .sound, .list]
48 // A midnight badge update shows nothing else.
49 if notification.request.content.badge != nil { return [.badge] }
50 return [.banner, .sound, .list]
4951 }
5052
5153 nonisolated func userNotificationCenter(_ center: UNUserNotificationCenter, didReceive response: UNNotificationResponse) async {
Tests/OrgAppTests/OverdueBadgeTests.swift added +49
@@ -0,0 +1,49 @@
1import Foundation
2import OrgCore
3import OrgPresentation
4import Testing
5@testable import OrgApp
6
7struct OverdueBadgeTests {
8 static let file = """
9 * TODO Send forms
10 DEADLINE: <2026-10-02 Fri>
11 * TODO Water plants
12 SCHEDULED: <2026-10-05 Mon>
13 * DONE Took out bins
14 SCHEDULED: <2026-10-05 Mon>
15 * Standup
16 SCHEDULED: <2026-10-05 Mon 08:00>
17 * TODO Call the bank
18 SCHEDULED: <2026-10-06 Tue 09:30> DEADLINE: <2026-10-08 Thu>
19 * TODO Renew passport
20 DEADLINE: <2026-10-09 Fri>
21 * TODO Stretch
22 SCHEDULED: <2026-10-05 Mon .+1d>
23 :PROPERTIES:
24 :STYLE: habit
25 :END:
26 * Dentist <2026-10-06 Tue 13:50>
27 """
28
29 static let today = Days.absolute(year: 2026, month: 10, day: 5)
30
31 static func groups(today: Int) -> [AgendaDayGroup] {
32 let source = AgendaSource(path: "/notes/life.org", text: file, defaults: .default)
33 return AgendaRows.groups(Agenda.list([source], start: today, days: 7, today: today, now: (10, 0)), today: today)
34 }
35
36 /// The entries in the agenda's own Overdue section on each later day; an entry past both its
37 /// scheduled day and its deadline has two rows there.
38 @Test func projectsWhatTheAgendaShowsOnLaterDays() {
39 let counts = OverdueBadge.counts(Self.groups(today: Self.today), today: Self.today, days: 7)
40 let actual = (0..<7).map { k in
41 let day = Self.today + k
42 let rows = Self.groups(today: day).first { $0.day == day }?.overdue.filter { !$0.isDone && $0.item?.habit == nil } ?? []
43 return Set(rows.compactMap { $0.item?.headingOffset }).count
44 }
45 #expect(counts == actual)
46 // Send forms; then Water plants and Standup; Call the bank; Renew passport after the 9th.
47 #expect(counts == [1, 3, 4, 4, 4, 5, 5])
48 }
49}
docs/manual/guide/14-ios.org +2
@@ -262,6 +262,8 @@ With =reminders= on, orgstar schedules a notification before each timed agenda e
262262
263263iOS lets an app schedule at most 64 notifications, and orgstar schedules more only while it runs. It updates them when files or settings change, when you return to the app, and every hour while it is open. The agenda's status line says how far ahead reminders are set ("Reminders are set through …"), or that notifications are off for orgstar in the system Settings app.
264264
265The app icon's badge counts the entries in the agenda's Overdue section that aren't done: past their scheduled day or their deadline, habits left out. An entry past both counts once. orgstar sets each of the next six midnights' counts ahead, so the badge stays right while the app is closed. Turn it off in Settings ▸ Notifications ▸ orgstar ▸ Badges.
266
265267* Export
266268
267269Export (in the reader's toolbar and the editor's More menu) offers HTML and Markdown. Either opens the share sheet with a file named after the org file, which you can send to another app or keep with Save to Files. The export reads the file's setup files and follows its export keywords, as the Mac's HTML and Markdown export does.