Sources/OrgstarMobile/SettingsScreen.swift

ed75375eb5b1fd99336b7369fc806c4c9f911dca
orgstar/Sources/OrgstarMobile/SettingsScreen.swift

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

Global

⌘K
Command palette & jump
/
Focus search
?
Show this help
g d
Dashboard
g e
Explore repositories
g n
Notifications

Repository & editor

t
Find file in repository
y
Copy immutable SHA permalink
g c
Code tab
g i
Issues tab
g m
Merge requests tab
g b
Builds tab
⌘↵
Submit active form