krz/orgstar

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

Sources/OrgstarMobile/SettingsScreen.swift

2fa201330f61c801f777baa3f2943d49d8758cda
orgstar/Sources/OrgstarMobile/SettingsScreen.swift history · blame · raw

141 lines · 6565 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            Section("Agenda") {
 36                let _ = model.settingsVersion
 37                Toggle("Show days without entries", isOn: Binding {
 38                    OrgPreferences.agendaShowAllDates()
 39                } set: { model.set("agendaShowAllDates", to: .bool($0)) })
 40            }
 41            calendarSection
 42            Section("In use") {
 43                let _ = model.settingsVersion
 44                LabeledContent("TODO keywords", value: todoKeywords)
 45                LabeledContent("Agenda", value: agenda)
 46                LabeledContent("Reminders", value: OrgPreferences.reminders() ? "\(OrgPreferences.reminderLead()) min before" : "Off")
 47                LabeledContent("Capture templates", value: CaptureTemplates.load().templates.map(\.key).joined(separator: " "))
 48                LabeledContent("Theme", value: UserDefaults.standard.string(forKey: "themeFile").flatMap { $0.isEmpty ? nil : $0 } ?? "Default")
 49                LabeledContent("Font", value: font)
 50            }
 51        }
 52        .navigationTitle("Settings")
 53        .fileImporter(isPresented: $choosing, allowedContentTypes: [.folder]) { result in
 54            if case .success(let url) = result { model.setConfigFolder(url) }
 55        }
 56    }
 57
 58    /// `calendar-events` and `calendar-event-calendars`, written to config.toml.
 59    private var calendarSection: some View {
 60        let _ = model.settingsVersion
 61        let on = OrgPreferences.calendarEvents()
 62        let chosen = OrgPreferences.calendarEventCalendars()
 63        return Section {
 64            Toggle("Show Calendar Events", isOn: Binding {
 65                on
 66            } set: { value in
 67                model.set("calendarEvents", to: .bool(value))
 68                if value { Task { await requestCalendars() } }
 69            })
 70            if on {
 71                if !CalendarEvents.isAuthorized {
 72                    Button("Allow Access to Calendars…") { Task { await requestCalendars() } }
 73                }
 74                ForEach(calendars, id: \.id) { calendar in
 75                    let shown = CalendarEvents.chooses(id: calendar.id, title: calendar.title, chosen: chosen)
 76                    Button {
 77                        toggle(calendar.title, shown: shown, chosen: chosen)
 78                    } label: {
 79                        HStack {
 80                            Circle().fill(calendar.color?.swiftUI ?? .secondary).frame(width: 10, height: 10)
 81                            Text(calendar.title).foregroundStyle(.primary)
 82                            Spacer()
 83                            if shown { Image(systemName: "checkmark").foregroundStyle(Color.accentColor) }
 84                        }
 85                    }
 86                    .tint(.primary)
 87                }
 88            }
 89        } header: {
 90            Text("Calendar")
 91        } footer: {
 92            Text(on ? "Events from the checked calendars show in the agenda, read-only." : "Show events from Calendar in the agenda, read-only.")
 93        }
 94        .task(id: on) { loadCalendars() }
 95    }
 96
 97    private func requestCalendars() async {
 98        _ = await model.calendarEvents.requestAccess()
 99        loadCalendars()
100        model.reloadConfig()
101    }
102
103    private func loadCalendars() {
104        calendars = model.calendarEvents.calendars()
105            .sorted { $0.title.localizedStandardCompare($1.title) == .orderedAscending }
106            .map { CalendarChoice(id: $0.id, title: $0.title, color: $0.color) }
107    }
108
109    /// Shows or hides a calendar's events; with every calendar checked the setting is empty.
110    /// The last checked calendar stays checked, as an empty list means every calendar.
111    private func toggle(_ title: String, shown: Bool, chosen: [String]) {
112        var titles = calendars.filter { CalendarEvents.chooses(id: $0.id, title: $0.title, chosen: chosen) }.map(\.title)
113        titles.removeAll { $0 == title }
114        if !shown { titles.append(title) }
115        guard !titles.isEmpty else { return }
116        let value = Set(titles) == Set(calendars.map(\.title)) ? "" : titles.joined(separator: ", ")
117        model.set("calendarEventCalendars", to: .string(value))
118    }
119
120    /// The span and start day, worded as the Mac's Settings word the start.
121    private var agenda: String {
122        func days(_ count: Int) -> String { count == 1 ? "1 day" : "\(count) days" }
123        let offset = OrgPreferences.agendaStartOffset()
124        let start = offset == 0 ? "today" : offset < 0 ? "\(days(-offset)) before today" : "\(days(offset)) after today"
125        return "\(days(OrgPreferences.agendaSpan())), starting \(start)"
126    }
127
128    /// The theme's family, or the system's monospaced font when it's unset or not on the device.
129    private var font: String {
130        let spec = model.theme
131        let family = spec.font.isEmpty || UIFont.fontNames(forFamilyName: spec.font).isEmpty ? "System monospaced" : spec.font
132        let missing = !spec.font.isEmpty && family != spec.font ? " (\(spec.font) isn't installed)" : ""
133        return "\(family), \(spec.fontSize) pt\(missing)"
134    }
135
136    private var todoKeywords: String {
137        OrgPreferences.orgSettings().todoSequences.map { ($0.active.map(\.name) + ["|"] + $0.done.map(\.name)).joined(separator: " ") }
138            .joined(separator: "; ")
139    }
140}
141#endif