Sources/OrgstarMobile/OrgstarMobileApp.swift

1d52ac3e828cb73639dc1c0cd5b6c9f0795b14a7
orgstar/Sources/OrgstarMobile/OrgstarMobileApp.swift history · blame · raw

175 lines · 7080 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        .navigationDestination(for: EditorRoute.self) { route in
 54            EditorScreen(path: route.path, offset: route.offset, workspace: workspace, session: session)
 55        }
 56    }
 57}
 58
 59/// An org-protocol capture, or a plain one.
 60struct CaptureRequest: Identifiable {
 61    let id = UUID()
 62    var template: String?
 63    var properties: [String: String] = [:]
 64}
 65
 66struct RootView: View {
 67    let model: MobileModel
 68    let workspace: WorkspaceModel
 69    let agenda: AgendaModel
 70    @State private var capture: CaptureRequest?
 71    @State private var tab = AppTab.agenda
 72    @State private var agendaPath = NavigationPath()
 73    @State private var hour = 0
 74    @Environment(\.scenePhase) private var scenePhase
 75
 76    private var session: DocumentSession { model.session }
 77
 78    private struct ReminderKey: Equatable {
 79        var files: Int
 80        var changed: Int?
 81        var edits: Int
 82        var settings: Int
 83        var active: Bool
 84        var hour: Int
 85    }
 86
 87    var body: some View {
 88        TabView(selection: $tab) {
 89            Tab("Agenda", systemImage: "calendar", value: .agenda) {
 90                NavigationStack(path: $agendaPath) {
 91                    AgendaScreen(workspace: workspace, session: session, agenda: agenda, scheduler: model.scheduler)
 92                        .toolbar { captureButton }
 93                        .readerDestination(workspace: workspace, session: session)
 94                }
 95            }
 96            Tab("Folders", systemImage: "folder", value: .folders) {
 97                NavigationStack {
 98                    FoldersScreen(workspace: workspace)
 99                        .toolbar { captureButton }
100                        .readerDestination(workspace: workspace, session: session)
101                }
102            }
103            Tab("Settings", systemImage: "gearshape", value: .settings) {
104                NavigationStack { SettingsScreen(model: model) }
105            }
106            Tab(value: .search, role: .search) {
107                NavigationStack {
108                    SearchScreen(workspace: workspace, session: session)
109                        .readerDestination(workspace: workspace, session: session)
110                }
111            }
112        }
113        .onChange(of: model.openRequest) {
114            guard let route = model.openRequest else { return }
115            model.openRequest = nil
116            tab = .agenda
117            agendaPath.append(route)
118        }
119        .onChange(of: workspace.changedFile?.version) {
120            // An open file takes in what changed on disk.
121            if let path = workspace.changedFile?.path { session.fileChanged(path) }
122        }
123        .sheet(item: $capture) { request in
124            CaptureScreen(workspace: workspace, session: session, request: request)
125        }
126        .task {
127            // Development: `ORGSTAR_ROOT` adds a folder at launch, as on the Mac.
128            if let root = ProcessInfo.processInfo.environment["ORGSTAR_ROOT"] { try? await workspace.addRoot(URL(fileURLWithPath: root)) }
129            workspace.startWatching()
130            await workspace.refresh()
131        }
132        .task {
133            while !Task.isCancelled {
134                try? await Task.sleep(for: .seconds(3600))
135                hour += 1
136            }
137        }
138        // Reminders follow the files, the settings, coming back to the app and the hour.
139        .task(id: ReminderKey(files: workspace.files.count, changed: workspace.changedFile?.version, edits: session.editVersion,
140                              settings: model.settingsVersion, active: scenePhase == .active, hour: hour)) {
141            guard scenePhase == .active else { return }
142            try? await Task.sleep(for: .seconds(1))
143            guard !Task.isCancelled else { return }
144            await model.updateReminders()
145        }
146        .onChange(of: scenePhase) { _, phase in
147            // Unsaved edits are written before the app may be stopped.
148            if phase == .background {
149                for path in session.dirtyPaths { _ = session.save(path) }
150            }
151            // Files and settings synced while away; not every sync tool tells file presenters.
152            guard phase == .active else { return }
153            model.reloadConfig()
154            Task { await workspace.refresh() }
155        }
156        .onOpenURL { url in
157            if case .capture(let template, let properties)? = OrgProtocol.parse(url.absoluteString) {
158                capture = CaptureRequest(template: template, properties: properties)
159            }
160        }
161    }
162
163    private var captureButton: some ToolbarContent {
164        ToolbarItem(placement: .primaryAction) {
165            Button("Capture", systemImage: "square.and.pencil") { capture = CaptureRequest() }
166        }
167    }
168}
169#else
170/// The iOS app has nothing to run elsewhere.
171@main
172enum OrgstarMobileUnavailable {
173    static func main() { print("Orgstar for iOS runs on iPhone and iPad.") }
174}
175#endif