Sources/OrgstarMobile/SettingsScreen.swift

67fadc8623384f6d91328737ca7ed676afd81653
orgstar/Sources/OrgstarMobile/SettingsScreen.swift

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