krz/orgstar

A native macOS editor for org-mode files. editor org-mode swift

Sources/OrgstarMobile/SettingsScreen.swift

3a3dedba062790e1580c66d38606eda4b02cb501
orgstar/Sources/OrgstarMobile/SettingsScreen.swift history · blame · raw

132 lines · 6088 bytes

  1#if os(iOS)
  2import OrgApp
  3import OrgCore
  4import OrgPresentation
  5import SwiftUI
  6import UIKit
  7
  8/// Where settings come from: a folder with the Mac's `config.toml` and `capture.toml`, kept in
  9/// sync by iCloud Drive or another app.
 10struct SettingsScreen: View {
 11    let model: MobileModel
 12    @State private var choosing = false
 13    @State private var calendars: [CalendarChoice] = []
 14
 15    private struct CalendarChoice {
 16        let id: String
 17        let title: String
 18        let color: RGBA?
 19    }
 20
 21    var body: some View {
 22        Form {
 23            Section {
 24                LabeledContent("Folder", value: model.configFolder?.lastPathComponent ?? "None")
 25                Button(model.configFolder == nil ? "Choose Folder…" : "Choose Another Folder…") { choosing = true }
 26                if model.configFolder != nil {
 27                    Button("Stop Using This Folder", role: .destructive) { model.setConfigFolder(nil) }
 28                }
 29                ForEach(model.configProblems, id: \.self) { Text($0).foregroundStyle(.red) }
 30            } header: {
 31                Text("Configuration")
 32            } footer: {
 33                Text("A folder with config.toml and capture.toml, such as a synced copy of ~/.config/orgstar from your Mac. Changes to them apply as they sync.")
 34            }
 35            calendarSection
 36            Section("In use") {
 37                let _ = model.settingsVersion
 38                LabeledContent("TODO keywords", value: todoKeywords)
 39                LabeledContent("Agenda", value: agenda)
 40                LabeledContent("Reminders", value: OrgPreferences.reminders() ? "\(OrgPreferences.reminderLead()) min before" : "Off")
 41                LabeledContent("Capture templates", value: CaptureTemplates.load().templates.map(\.key).joined(separator: " "))
 42                LabeledContent("Theme", value: UserDefaults.standard.string(forKey: "themeFile").flatMap { $0.isEmpty ? nil : $0 } ?? "Default")
 43                LabeledContent("Font", value: font)
 44            }
 45        }
 46        .navigationTitle("Settings")
 47        .fileImporter(isPresented: $choosing, allowedContentTypes: [.folder]) { result in
 48            if case .success(let url) = result { model.setConfigFolder(url) }
 49        }
 50    }
 51
 52    /// `calendar-events` and `calendar-event-calendars`, written to config.toml.
 53    private var calendarSection: some View {
 54        let _ = model.settingsVersion
 55        let on = OrgPreferences.calendarEvents()
 56        let chosen = OrgPreferences.calendarEventCalendars()
 57        return Section {
 58            Toggle("Show Calendar Events", isOn: Binding {
 59                on
 60            } set: { value in
 61                model.set("calendarEvents", to: .bool(value))
 62                if value { Task { await requestCalendars() } }
 63            })
 64            if on {
 65                if !CalendarEvents.isAuthorized {
 66                    Button("Allow Access to Calendars…") { Task { await requestCalendars() } }
 67                }
 68                ForEach(calendars, id: \.id) { calendar in
 69                    let shown = CalendarEvents.chooses(id: calendar.id, title: calendar.title, chosen: chosen)
 70                    Button {
 71                        toggle(calendar.title, shown: shown, chosen: chosen)
 72                    } label: {
 73                        HStack {
 74                            Circle().fill(calendar.color?.swiftUI ?? .secondary).frame(width: 10, height: 10)
 75                            Text(calendar.title).foregroundStyle(.primary)
 76                            Spacer()
 77                            if shown { Image(systemName: "checkmark").foregroundStyle(Color.accentColor) }
 78                        }
 79                    }
 80                    .tint(.primary)
 81                }
 82            }
 83        } header: {
 84            Text("Calendar")
 85        } footer: {
 86            Text(on ? "Events from the checked calendars show in the agenda, read-only." : "Show events from Calendar in the agenda, read-only.")
 87        }
 88        .task(id: on) { loadCalendars() }
 89    }
 90
 91    private func requestCalendars() async {
 92        _ = await model.calendarEvents.requestAccess()
 93        loadCalendars()
 94        model.reloadConfig()
 95    }
 96
 97    private func loadCalendars() {
 98        calendars = model.calendarEvents.calendars()
 99            .sorted { $0.title.localizedStandardCompare($1.title) == .orderedAscending }
100            .map { CalendarChoice(id: $0.id, title: $0.title, color: $0.color) }
101    }
102
103    /// Shows or hides a calendar's events; with every calendar checked the setting is empty.
104    private func toggle(_ title: String, shown: Bool, chosen: [String]) {
105        var titles = chosen.isEmpty ? calendars.map(\.title) : chosen
106        if shown { titles.removeAll { $0 == title } } else { titles.append(title) }
107        let value = Set(titles) == Set(calendars.map(\.title)) ? "" : titles.joined(separator: ", ")
108        model.set("calendarEventCalendars", to: .string(value))
109    }
110
111    /// The span and start day, worded as the Mac's Settings word the start.
112    private var agenda: String {
113        func days(_ count: Int) -> String { count == 1 ? "1 day" : "\(count) days" }
114        let offset = OrgPreferences.agendaStartOffset()
115        let start = offset == 0 ? "today" : offset < 0 ? "\(days(-offset)) before today" : "\(days(offset)) after today"
116        return "\(days(OrgPreferences.agendaSpan())), starting \(start)"
117    }
118
119    /// The theme's family, or the system's monospaced font when it's unset or not on the device.
120    private var font: String {
121        let spec = model.theme
122        let family = spec.font.isEmpty || UIFont.fontNames(forFamilyName: spec.font).isEmpty ? "System monospaced" : spec.font
123        let missing = !spec.font.isEmpty && family != spec.font ? " (\(spec.font) isn't installed)" : ""
124        return "\(family), \(spec.fontSize) pt\(missing)"
125    }
126
127    private var todoKeywords: String {
128        OrgPreferences.orgSettings().todoSequences.map { ($0.active.map(\.name) + ["|"] + $0.done.map(\.name)).joined(separator: " ") }
129            .joined(separator: "; ")
130    }
131}
132#endif