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