Sources/OrgstarMobile/OrgstarMobileApp.swift

3f183dc5a69542840ae20a73ec755d1148b354dd
orgstar/Sources/OrgstarMobile/OrgstarMobileApp.swift history · blame · raw

168 lines · 6702 bytes

  1#if os(iOS)
  2import OrgApp
  3import OrgCore
  4import SwiftUI
  5import UserNotifications
  6
  7/// Orgstar on iPhone and iPad: the agenda, capture, and the folders they read.
  8@main
  9struct OrgstarMobileApp: App {
 10    @UIApplicationDelegateAdaptor private var delegate: AppDelegate
 11    @State private var model = MobileModel()
 12
 13    var body: some Scene {
 14        WindowGroup {
 15            if let workspace = model.workspace, let agenda = model.agenda {
 16                RootView(model: model, workspace: workspace, agenda: agenda)
 17                    .onAppear { delegate.model = model }
 18            } else {
 19                ContentUnavailableView("Can't open the index", systemImage: "exclamationmark.triangle", description: Text(model.failure ?? ""))
 20            }
 21        }
 22    }
 23}
 24
 25/// Reminders show while the app is open too, and open their entry when tapped.
 26final class AppDelegate: NSObject, UIApplicationDelegate, UNUserNotificationCenterDelegate {
 27    @MainActor var model: MobileModel?
 28
 29    func application(_ application: UIApplication, didFinishLaunchingWithOptions options: [UIApplication.LaunchOptionsKey: Any]? = nil) -> Bool {
 30        UNUserNotificationCenter.current().delegate = self
 31        return true
 32    }
 33
 34    nonisolated func userNotificationCenter(_ center: UNUserNotificationCenter, willPresent notification: UNNotification) async -> UNNotificationPresentationOptions {
 35        [.banner, .sound, .list]
 36    }
 37
 38    nonisolated func userNotificationCenter(_ center: UNUserNotificationCenter, didReceive response: UNNotificationResponse) async {
 39        let info = response.notification.request.content.userInfo
 40        guard let path = info["path"] as? String, let offset = info["offset"] as? Int else { return }
 41        await MainActor.run { model?.openRequest = .offset(path, offset) }
 42    }
 43}
 44
 45enum AppTab: Hashable { case agenda, folders, settings, search }
 46
 47extension View {
 48    /// Readers pushed for `ReaderRoute`s.
 49    func readerDestination(workspace: WorkspaceModel, session: DocumentSession) -> some View {
 50        navigationDestination(for: ReaderRoute.self) { route in
 51            ReaderScreen(route: route, workspace: workspace, session: session)
 52        }
 53    }
 54}
 55
 56/// An org-protocol capture, or a plain one.
 57struct CaptureRequest: Identifiable {
 58    let id = UUID()
 59    var template: String?
 60    var properties: [String: String] = [:]
 61}
 62
 63struct RootView: View {
 64    let model: MobileModel
 65    let workspace: WorkspaceModel
 66    let agenda: AgendaModel
 67    @State private var capture: CaptureRequest?
 68    @State private var tab = AppTab.agenda
 69    @State private var agendaPath = NavigationPath()
 70    @State private var hour = 0
 71    @Environment(\.scenePhase) private var scenePhase
 72
 73    private var session: DocumentSession { model.session }
 74
 75    private struct ReminderKey: Equatable {
 76        var files: Int
 77        var changed: Int?
 78        var edits: Int
 79        var settings: Int
 80        var active: Bool
 81        var hour: Int
 82    }
 83
 84    var body: some View {
 85        TabView(selection: $tab) {
 86            Tab("Agenda", systemImage: "calendar", value: .agenda) {
 87                NavigationStack(path: $agendaPath) {
 88                    AgendaScreen(workspace: workspace, session: session, agenda: agenda, scheduler: model.scheduler)
 89                        .toolbar { captureButton }
 90                        .readerDestination(workspace: workspace, session: session)
 91                }
 92            }
 93            Tab("Folders", systemImage: "folder", value: .folders) {
 94                NavigationStack {
 95                    FoldersScreen(workspace: workspace)
 96                        .toolbar { captureButton }
 97                        .readerDestination(workspace: workspace, session: session)
 98                }
 99            }
100            Tab("Settings", systemImage: "gearshape", value: .settings) {
101                NavigationStack { SettingsScreen(model: model) }
102            }
103            Tab(value: .search, role: .search) {
104                NavigationStack {
105                    SearchScreen(workspace: workspace, session: session)
106                        .readerDestination(workspace: workspace, session: session)
107                }
108            }
109        }
110        .onChange(of: model.openRequest) {
111            guard let route = model.openRequest else { return }
112            model.openRequest = nil
113            tab = .agenda
114            agendaPath.append(route)
115        }
116        .onChange(of: workspace.changedFile?.version) {
117            // An open file takes in what changed on disk.
118            if let path = workspace.changedFile?.path { session.fileChanged(path) }
119        }
120        .sheet(item: $capture) { request in
121            CaptureScreen(workspace: workspace, session: session, request: request)
122        }
123        .task {
124            // Development: `ORGSTAR_ROOT` adds a folder at launch, as on the Mac.
125            if let root = ProcessInfo.processInfo.environment["ORGSTAR_ROOT"] { try? await workspace.addRoot(URL(fileURLWithPath: root)) }
126            workspace.startWatching()
127            await workspace.refresh()
128        }
129        .task {
130            while !Task.isCancelled {
131                try? await Task.sleep(for: .seconds(3600))
132                hour += 1
133            }
134        }
135        // Reminders follow the files, the settings, coming back to the app and the hour.
136        .task(id: ReminderKey(files: workspace.files.count, changed: workspace.changedFile?.version, edits: session.editVersion,
137                              settings: model.settingsVersion, active: scenePhase == .active, hour: hour)) {
138            guard scenePhase == .active else { return }
139            try? await Task.sleep(for: .seconds(1))
140            guard !Task.isCancelled else { return }
141            await model.updateReminders()
142        }
143        .onChange(of: scenePhase) { _, phase in
144            // Files and settings synced while away; not every sync tool tells file presenters.
145            guard phase == .active else { return }
146            model.reloadConfig()
147            Task { await workspace.refresh() }
148        }
149        .onOpenURL { url in
150            if case .capture(let template, let properties)? = OrgProtocol.parse(url.absoluteString) {
151                capture = CaptureRequest(template: template, properties: properties)
152            }
153        }
154    }
155
156    private var captureButton: some ToolbarContent {
157        ToolbarItem(placement: .primaryAction) {
158            Button("Capture", systemImage: "square.and.pencil") { capture = CaptureRequest() }
159        }
160    }
161}
162#else
163/// The iOS app has nothing to run elsewhere.
164@main
165enum OrgstarMobileUnavailable {
166    static func main() { print("Orgstar for iOS runs on iPhone and iPad.") }
167}
168#endif