Sources/OrgstarMobile/SettingsScreen.swift

a866e469a3568bf7a2829a8dd2a56317ced4736e
orgstar/Sources/OrgstarMobile/SettingsScreen.swift history · blame · raw

259 lines · 11612 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    @State private var badges: Bool?
 15    @Environment(\.openURL) private var openURL
 16    @Environment(\.scenePhase) private var scenePhase
 17
 18    private struct CalendarChoice {
 19        let id: String
 20        let title: String
 21        let color: RGBA?
 22    }
 23
 24    var body: some View {
 25        Form {
 26            Section {
 27                LabeledContent("Folder", value: model.configFolder?.lastPathComponent ?? "None")
 28                Button(model.configFolder == nil ? "Choose Folder…" : "Choose Another Folder…") { choosing = true }
 29                if model.configFolder != nil {
 30                    NavigationLink("Edit config.toml") { ConfigFileEditor(model: model) }
 31                    Button("Stop Using This Folder", role: .destructive) { model.setConfigFolder(nil) }
 32                }
 33                ForEach(model.configProblems, id: \.self) { Text($0).foregroundStyle(.red) }
 34            } header: {
 35                Text("Configuration")
 36            } footer: {
 37                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.")
 38            }
 39            Section("Agenda") {
 40                let _ = model.settingsVersion
 41                Toggle("Show days without entries", isOn: Binding {
 42                    OrgPreferences.agendaShowAllDates()
 43                } set: { model.set("agendaShowAllDates", to: .bool($0)) })
 44                Picker("Blocked entries", selection: Binding {
 45                    UserDefaults.standard.string(forKey: "agendaDimBlockedTasks") ?? "t"
 46                } set: { model.set("agendaDimBlockedTasks", to: .string($0)) }) {
 47                    Text("Dimmed").tag("t")
 48                    Text("Hidden").tag("invisible")
 49                    Text("Shown as usual").tag("nil")
 50                }
 51            }
 52            Section {
 53                let _ = model.settingsVersion
 54                Toggle("Not done before TODO children", isOn: Binding {
 55                    UserDefaults.standard.bool(forKey: "enforceTodoDependencies")
 56                } set: { model.set("enforceTodoDependencies", to: .bool($0)) })
 57                Toggle("Not done with unchecked boxes", isOn: Binding {
 58                    UserDefaults.standard.bool(forKey: "enforceTodoCheckboxDependencies")
 59                } set: { model.set("enforceTodoCheckboxDependencies", to: .bool($0)) })
 60            } header: {
 61                Text("TODO Dependencies")
 62            } footer: {
 63                Text("org-enforce-todo-dependencies and org-enforce-todo-checkbox-dependencies.")
 64            }
 65            Section {
 66                if badges == true {
 67                    LabeledContent("Overdue Count on Icon", value: "On")
 68                } else if badges == false {
 69                    Button("Show Overdue Count on Icon…") {
 70                        Task {
 71                            if await model.badgesEnabled(asking: true) {
 72                                badges = true
 73                                await model.updateWidgets()
 74                            } else if let url = URL(string: UIApplication.openNotificationSettingsURLString) {
 75                                openURL(url)
 76                            }
 77                        }
 78                    }
 79                }
 80            } header: {
 81                Text("Badge")
 82            } footer: {
 83                if badges == false { Text("Turn on Badges in orgstar's notification settings.") }
 84            }
 85            calendarSection
 86            Section("In use") {
 87                let _ = model.settingsVersion
 88                LabeledContent("TODO keywords", value: todoKeywords)
 89                LabeledContent("Agenda", value: agenda)
 90                LabeledContent("Reminders", value: OrgPreferences.reminders() ? "\(OrgPreferences.reminderLead()) min before" : "Off")
 91                LabeledContent("Capture templates", value: CaptureTemplates.load().templates.map(\.key).joined(separator: " "))
 92                LabeledContent("Theme", value: UserDefaults.standard.string(forKey: "themeFile").flatMap { $0.isEmpty ? nil : $0 } ?? "Default")
 93                LabeledContent("Font", value: font)
 94            }
 95        }
 96        .navigationTitle("Settings")
 97        // Read again on return from the Settings app.
 98        .task(id: scenePhase) { badges = await model.badgesEnabled(asking: false) }
 99        .fileImporter(isPresented: $choosing, allowedContentTypes: [.folder]) { result in
100            if case .success(let url) = result { model.setConfigFolder(url) }
101        }
102    }
103
104    /// `calendar-events` and `calendar-event-calendars`, written to config.toml.
105    private var calendarSection: some View {
106        let _ = model.settingsVersion
107        let on = OrgPreferences.calendarEvents()
108        let chosen = OrgPreferences.calendarEventCalendars()
109        return Section {
110            Toggle("Show Calendar Events", isOn: Binding {
111                on
112            } set: { value in
113                model.set("calendarEvents", to: .bool(value))
114                if value { Task { await requestCalendars() } }
115            })
116            if on {
117                if !CalendarEvents.isAuthorized {
118                    Button("Allow Access to Calendars…") { Task { await requestCalendars() } }
119                }
120                ForEach(calendars, id: \.id) { calendar in
121                    let shown = CalendarEvents.chooses(id: calendar.id, title: calendar.title, chosen: chosen)
122                    Button {
123                        toggle(calendar.title, shown: shown, chosen: chosen)
124                    } label: {
125                        HStack {
126                            Circle().fill(calendar.color?.swiftUI ?? .secondary).frame(width: 10, height: 10)
127                            Text(calendar.title).foregroundStyle(.primary)
128                            Spacer()
129                            if shown { Image(systemName: "checkmark").foregroundStyle(Color.accentColor) }
130                        }
131                    }
132                    .tint(.primary)
133                }
134            }
135        } header: {
136            Text("Calendar")
137        } footer: {
138            Text(on ? "Events from the checked calendars show in the agenda, read-only." : "Show events from Calendar in the agenda, read-only.")
139        }
140        .task(id: on) { loadCalendars() }
141    }
142
143    private func requestCalendars() async {
144        _ = await model.calendarEvents.requestAccess()
145        loadCalendars()
146        model.reloadConfig()
147    }
148
149    private func loadCalendars() {
150        calendars = model.calendarEvents.calendars()
151            .sorted { $0.title.localizedStandardCompare($1.title) == .orderedAscending }
152            .map { CalendarChoice(id: $0.id, title: $0.title, color: $0.color) }
153    }
154
155    /// Shows or hides a calendar's events; with every calendar checked the setting is empty.
156    /// The last checked calendar stays checked, as an empty list means every calendar.
157    private func toggle(_ title: String, shown: Bool, chosen: [String]) {
158        var titles = calendars.filter { CalendarEvents.chooses(id: $0.id, title: $0.title, chosen: chosen) }.map(\.title)
159        titles.removeAll { $0 == title }
160        if !shown { titles.append(title) }
161        guard !titles.isEmpty else { return }
162        let value = Set(titles) == Set(calendars.map(\.title)) ? "" : titles.joined(separator: ", ")
163        model.set("calendarEventCalendars", to: .string(value))
164    }
165
166    /// The span and start day, worded as the Mac's Settings word the start.
167    private var agenda: String {
168        func days(_ count: Int) -> String { count == 1 ? "1 day" : "\(count) days" }
169        let offset = OrgPreferences.agendaStartOffset()
170        let start = offset == 0 ? "today" : offset < 0 ? "\(days(-offset)) before today" : "\(days(offset)) after today"
171        return "\(days(OrgPreferences.agendaSpan())), starting \(start)"
172    }
173
174    /// The theme's family, or the system's monospaced font when it's unset or not on the device.
175    private var font: String {
176        let spec = model.theme
177        let family = spec.font.isEmpty || UIFont.fontNames(forFamilyName: spec.font).isEmpty ? "System monospaced" : spec.font
178        let missing = !spec.font.isEmpty && family != spec.font ? " (\(spec.font) isn't installed)" : ""
179        return "\(family), \(spec.fontSize) pt\(missing)"
180    }
181
182    private var todoKeywords: String {
183        OrgPreferences.orgSettings().todoSequences.map { ($0.active.map(\.name) + ["|"] + $0.done.map(\.name)).joined(separator: " ") }
184            .joined(separator: "; ")
185    }
186}
187/// The configuration folder's `config.toml` as plain text, saved when you tap Save or leave.
188struct ConfigFileEditor: View {
189    let model: MobileModel
190    @State private var text = ""
191    @State private var saved: String?
192
193    var body: some View {
194        PlainTextView(text: $text)
195            .navigationTitle("config.toml")
196            .navigationBarTitleDisplayMode(.inline)
197            .toolbar {
198                Button("Save") { save() }.disabled(text == saved)
199            }
200            .safeAreaInset(edge: .bottom) {
201                let _ = model.settingsVersion
202                if !model.configProblems.isEmpty {
203                    VStack(alignment: .leading, spacing: 4) {
204                        ForEach(model.configProblems, id: \.self) { Text($0) }
205                    }
206                    .font(.footnote)
207                    .foregroundStyle(.red)
208                    .padding()
209                    .frame(maxWidth: .infinity, alignment: .leading)
210                    .background(.bar)
211                }
212            }
213            .onAppear {
214                guard saved == nil else { return }
215                text = model.configText() ?? UserConfig.defaultTemplate
216                saved = text
217            }
218            .onDisappear { save() }
219    }
220
221    private func save() {
222        guard text != saved else { return }
223        model.saveConfig(text)
224        saved = text
225    }
226}
227
228/// A monospaced text view without smart quotes, dashes or autocorrection, which would break TOML.
229private struct PlainTextView: UIViewRepresentable {
230    @Binding var text: String
231
232    func makeUIView(context: Context) -> UITextView {
233        let view = UITextView()
234        view.font = .monospacedSystemFont(ofSize: UIFont.preferredFont(forTextStyle: .footnote).pointSize, weight: .regular)
235        view.adjustsFontForContentSizeCategory = true
236        view.autocorrectionType = .no
237        view.autocapitalizationType = .none
238        view.smartQuotesType = .no
239        view.smartDashesType = .no
240        view.smartInsertDeleteType = .no
241        view.spellCheckingType = .no
242        view.keyboardDismissMode = .interactive
243        view.delegate = context.coordinator
244        return view
245    }
246
247    func updateUIView(_ view: UITextView, context: Context) {
248        if view.text != text { view.text = text }
249    }
250
251    func makeCoordinator() -> Coordinator { Coordinator(text: $text) }
252
253    final class Coordinator: NSObject, UITextViewDelegate {
254        var text: Binding<String>
255        init(text: Binding<String>) { self.text = text }
256        func textViewDidChange(_ view: UITextView) { text.wrappedValue = view.text }
257    }
258}
259#endif