Sources/Orgstar/AgendaView.swift

427abbbee0d20a70754de8e0e0846dae001f9c92
orgstar/Sources/Orgstar/AgendaView.swift history · blame · raw

440 lines · 18101 bytes

  1import OrgApp
  2import OrgCore
  3import OrgPresentation
  4import SwiftUI
  5
  6/// The agenda window: the day/week agenda, the TODO list, tag matches and saved views.
  7/// Return or a double click jumps to the entry in the main window. Keys as in Emacs's agenda:
  8/// f/b/. move the span, g refreshes, t cycles the TODO state, +/- change the priority, : or
  9/// C-c C-q sets tags, C-c C-s / C-c C-d schedule and set a deadline, S-→/S-← move the date.
 10struct AgendaView: View {
 11    let workspace: WorkspaceModel
 12    let session: DocumentSession
 13    let commands: AppCommands
 14    let scheduler: ReminderScheduler?
 15    @State private var agenda: AgendaModel
 16    @State private var views = AgendaViewLoader.builtIn
 17    @State private var viewName = AgendaViewLoader.builtIn[0].name
 18    @State private var matchText = ""
 19    @State private var selection: String?
 20    @State private var tick = 0
 21    @State private var message: String?
 22    @State private var prompt: PendingPrompt?
 23    @State private var promptText = ""
 24    @State private var prefix = false
 25    @AppStorage("agendaSpan") private var span = 10
 26    @AppStorage("agendaStartOffset") private var startOffset = -3
 27    @AppStorage("agendaSubfolders") private var includeSubfolders = false
 28    @Environment(\.openWindow) private var openWindow
 29
 30    static let match = "Match…"
 31    static let todoMatch = "TODO Match…"
 32
 33    init(workspace: WorkspaceModel, session: DocumentSession, commands: AppCommands, scheduler: ReminderScheduler?) {
 34        self.workspace = workspace
 35        self.session = session
 36        self.commands = commands
 37        self.scheduler = scheduler
 38        _agenda = State(initialValue: AgendaModel(workspace: workspace))
 39    }
 40
 41    struct PendingPrompt: Identifiable {
 42        let id = UUID()
 43        let prompt: Prompt
 44        let command: any OrgCommand
 45        let atMarker: Bool
 46        let answers: [String: String]
 47        let itemID: String
 48    }
 49
 50    private struct RefreshKey: Hashable {
 51        var mode: AgendaMode
 52        var start: Int?
 53        var span: Int
 54        var startOffset: Int
 55        var includeSubfolders: Bool
 56        var files: Int
 57        var changed: Int?
 58        var edits: Int
 59        var path: String?
 60        var tick: Int
 61    }
 62
 63    private var refreshKey: RefreshKey {
 64        RefreshKey(
 65            mode: agenda.mode, start: agenda.start, span: span, startOffset: startOffset, includeSubfolders: includeSubfolders,
 66            files: workspace.files.count, changed: workspace.changedFile?.version, edits: session.editVersion,
 67            path: session.path, tick: tick
 68        )
 69    }
 70
 71    private var isAgenda: Bool {
 72        if case .agenda = agenda.mode { return true }
 73        return false
 74    }
 75
 76    private var isMatch: Bool { viewName == Self.match || viewName == Self.todoMatch }
 77
 78    @Environment(\.orgTheme) private var theme
 79
 80    var body: some View {
 81        List(selection: $selection) {
 82            if isAgenda {
 83                ForEach(agenda.days, id: \.day) { day in
 84                    Section {
 85                        rows(day.items, prefix: "\(day.day)", day: day.day)
 86                    } header: {
 87                        Text(day.header)
 88                            .font(.headline)
 89                            .foregroundStyle(day.isToday ? theme.color("agenda-today") ?? .accentColor : theme.color("agenda-date") ?? .primary)
 90                    }
 91                }
 92            } else {
 93                Section {
 94                    rows(agenda.list, prefix: "list")
 95                } header: {
 96                    Text(listTitle).font(.headline)
 97                }
 98            }
 99        }
100        .themedListBackground(theme.color("agenda-background"))
101        .contextMenu(forSelectionType: String.self) { _ in
102        } primaryAction: { ids in
103            if let id = ids.first { jump(id) }
104        }
105        .onKeyPress(phases: .down) { press in handle(press) }
106        .safeAreaInset(edge: .bottom, spacing: 0) {
107            if let message = message ?? reminderStatus {
108                Text(message)
109                    .font(.callout)
110                    .frame(maxWidth: .infinity, alignment: .leading)
111                    .padding(.horizontal, 12)
112                    .padding(.vertical, 6)
113                    .background(.bar)
114            }
115        }
116        .toolbar {
117            ToolbarItemGroup(placement: .navigation) {
118                Menu {
119                    ForEach(views) { view in Button(view.name) { viewName = view.name } }
120                    Divider()
121                    Button(Self.match) { viewName = Self.match }
122                    Button(Self.todoMatch) { viewName = Self.todoMatch }
123                } label: {
124                    Label(viewName, systemImage: "calendar").labelStyle(.titleAndIcon)
125                }
126                .help("What the agenda shows")
127                if isMatch {
128                    TextField("+work-boss|LEVEL>2/!TODO", text: $matchText)
129                        .frame(minWidth: 220)
130                        .onSubmit { applyView() }
131                }
132            }
133            ToolbarItemGroup {
134                if agenda.isComputing { ProgressView().controlSize(.small) }
135                if isAgenda {
136                    Button("Earlier", systemImage: "chevron.left") { agenda.shift(forward: false) }
137                        .help("Previous days (b)")
138                    Button("Today") { agenda.showToday() }
139                        .help("Back to today (.)")
140                    Button("Later", systemImage: "chevron.right") { agenda.shift(forward: true) }
141                        .help("Next days (f)")
142                }
143            }
144        }
145        .overlay {
146            if agenda.files.isEmpty {
147                ContentUnavailableView("No agenda files", systemImage: "calendar", description: Text("The agenda reads the org files at the top of each folder you add."))
148            }
149        }
150        .alert(prompt?.prompt.message ?? "", isPresented: Binding(get: { prompt != nil }, set: { if !$0 { prompt = nil } })) {
151            TextField("", text: $promptText)
152            Button("OK") { answerPrompt() }
153            Button("Cancel", role: .cancel) { prompt = nil }
154        } message: {
155            if let choices = prompt?.prompt.choices, !choices.isEmpty {
156                Text(choices.prefix(12).joined(separator: "  "))
157            }
158        }
159        .navigationTitle(viewName.replacingOccurrences(of: "…", with: ""))
160        .onChange(of: viewName) { applyView() }
161        .task(id: refreshKey) {
162            agenda.span = span
163            agenda.startOffset = startOffset
164            agenda.includeSubfolders = includeSubfolders
165            let open = session.path.flatMap { path in session.document.map { (path, $0.text) } }
166            await agenda.refresh(open: open)
167        }
168        .task {
169            loadViews()
170            // The time grid's "now" line and the day itself move on.
171            while !Task.isCancelled {
172                try? await Task.sleep(for: .seconds(60))
173                tick += 1
174            }
175        }
176    }
177
178    @ViewBuilder
179    private func rows(_ items: [AgendaItem], prefix: String, day: Int? = nil) -> some View {
180        ForEach(Array(items.enumerated()), id: \.offset) { index, item in
181            AgendaRow(item: item, day: day)
182                .tag("\(prefix):\(index)")
183                .selectionDisabled(item.path == nil)
184        }
185    }
186
187    @AppStorage("reminders") private var remindersEnabled = true
188
189    /// How far ahead notifications are set, as the design asks the agenda to show.
190    private var reminderStatus: String? {
191        guard let scheduler, remindersEnabled else { return nil }
192        if !scheduler.isAuthorized { return "Notifications are off for Orgstar in System Settings." }
193        guard let through = scheduler.scheduledThrough else { return nil }
194        return "Reminders are set through " + through.formatted(.dateTime.weekday(.abbreviated).day().month(.abbreviated).hour().minute()) + "."
195    }
196
197    private var listTitle: String {
198        switch agenda.mode {
199        case .todo(let keywords): "TODO items: \(keywords ?? "all")"
200        case .match(let match, let todoOnly): (todoOnly ? "TODO entries" : "Entries") + " matching \(match)"
201        case .agenda: ""
202        }
203    }
204
205    private func loadViews() {
206        let loaded = AgendaViewLoader.load()
207        views = loaded.views
208        message = loaded.problems.first
209    }
210
211    private func applyView() {
212        selection = nil
213        agenda.start = nil
214        switch viewName {
215        case Self.match, Self.todoMatch:
216            let match = matchText.trimmingCharacters(in: .whitespaces)
217            guard !match.isEmpty else { return }
218            agenda.mode = .match(match, todoOnly: viewName == Self.todoMatch)
219        default:
220            if let view = views.first(where: { $0.name == viewName }) { agenda.mode = view.mode }
221        }
222    }
223
224    // MARK: - Items
225
226    private func item(_ id: String) -> AgendaItem? {
227        let parts = id.split(separator: ":")
228        guard parts.count == 2, let index = Int(parts[1]) else { return nil }
229        let items = parts[0] == "list" ? agenda.list : agenda.days.first { "\($0.day)" == parts[0] }?.items ?? []
230        return index < items.count ? items[index] : nil
231    }
232
233    private func jump(_ id: String) {
234        guard let item = item(id), let path = item.path, let offset = item.markerOffset ?? item.headingOffset else { return }
235        commands.jump(path: path, offset: offset)
236        openWindow(id: "main")
237    }
238
239    // MARK: - Commands
240
241    private func handle(_ press: KeyPress) -> KeyPress.Result {
242        let control = press.modifiers.contains(.control)
243        if prefix {
244            prefix = false
245            switch (control, press.characters) {
246            case (true, "\u{13}"), (true, "s"): run(SetPlanning(deadline: false))
247            case (true, "\u{04}"), (true, "d"): run(SetPlanning(deadline: true))
248            case (true, "\u{11}"), (true, "q"): run(SetTags())
249            case (true, "\u{14}"), (true, "t"): run(TodoCycle())
250            default: message = "C-c \(press.characters) is undefined"
251            }
252            return .handled
253        }
254        if control, press.characters == "c" || press.characters == "\u{03}" {
255            prefix = true
256            message = "C-c-"
257            return .handled
258        }
259        if press.key == .return, let selection {
260            jump(selection)
261            return .handled
262        }
263        if press.modifiers == .shift, press.key == .rightArrow || press.key == .leftArrow {
264            run(ShiftTimestampDay(later: press.key == .rightArrow), atMarker: true)
265            return .handled
266        }
267        guard press.modifiers.subtracting(.shift).isEmpty else { return .ignored }
268        switch press.characters {
269        case "f" where isAgenda: agenda.shift(forward: true)
270        case "b" where isAgenda: agenda.shift(forward: false)
271        case "." where isAgenda: agenda.showToday()
272        case "g", "r":
273            loadViews()
274            tick += 1
275        case "t": run(TodoCycle())
276        case "+": run(PriorityUp())
277        case "-": run(PriorityDown())
278        case ":": run(SetTags())
279        default: return .ignored
280        }
281        return .handled
282    }
283
284    /// Runs `command` on the selected entry, at its heading or, with `atMarker`, at the
285    /// timestamp the entry is listed for.
286    private func run(_ command: any OrgCommand, atMarker: Bool = false, answers: [String: String] = [:], itemID: String? = nil) {
287        guard let id = itemID ?? selection, let item = item(id), let path = item.path, let start = item.headingOffset else {
288            message = "No entry selected"
289            return
290        }
291        if atMarker, ![.deadline, .upcomingDeadline, .scheduled, .pastScheduled, .timestamp].contains(item.kind) {
292            message = "Only dated entries can move"
293            return
294        }
295        let offset = atMarker ? (item.markerOffset ?? start) : start
296        let step = session.perform(command, path: path, at: offset, expect: item.headingLine.map { (start, $0) }, answers: answers)
297        switch step {
298        case .prompt(let request):
299            promptText = request.initial
300            prompt = PendingPrompt(prompt: request, command: command, atMarker: atMarker, answers: answers, itemID: id)
301        case .failed(let text):
302            message = text
303            tick += 1
304        case .external:
305            message = "Not available from the agenda"
306        case .commit:
307            message = nil
308            tick += 1
309        }
310    }
311
312    private func answerPrompt() {
313        guard let pending = prompt else { return }
314        prompt = nil
315        var answers = pending.answers
316        answers[pending.prompt.key] = promptText
317        run(pending.command, atMarker: pending.atMarker, answers: answers, itemID: pending.itemID)
318    }
319}
320
321struct AgendaRow: View {
322    let item: AgendaItem
323    /// The agenda day the row is on, for habit graphs.
324    var day: Int?
325    @Environment(\.orgTheme) private var theme
326
327    var body: some View {
328        switch item.kind {
329        case .timeGrid:
330            HStack(spacing: 8) {
331                Text(Self.trim(item.time))
332                    .monospacedDigit()
333                    .frame(width: 140, alignment: .trailing)
334                VStack { Divider() }
335            }
336            .font(.caption)
337            .foregroundStyle(theme.color("agenda-time").map(AnyShapeStyle.init) ?? AnyShapeStyle(.tertiary))
338        case .currentTime:
339            HStack(spacing: 8) {
340                Text("now " + Self.trim(item.time))
341                    .monospacedDigit()
342                    .frame(width: 140, alignment: .trailing)
343                Rectangle().fill(theme.color("agenda-today") ?? .accentColor).frame(height: 1)
344            }
345            .font(.caption)
346            .foregroundStyle(theme.color("agenda-today") ?? .accentColor)
347        default:
348            HStack(spacing: 8) {
349                Text(item.category)
350                    .lineLimit(1)
351                    .foregroundStyle(theme.color("agenda-category") ?? .secondary)
352                    .frame(width: 80, alignment: .leading)
353                if item.kind != .todo, item.kind != .tagsMatch {
354                    Text(Self.trim(item.time))
355                        .monospacedDigit()
356                        .foregroundStyle(theme.color("agenda-time") ?? .primary)
357                        .frame(width: 80, alignment: .leading)
358                }
359                if !item.extra.isEmpty {
360                    Text(item.extra.trimmingCharacters(in: .whitespaces))
361                        .monospacedDigit()
362                        .foregroundStyle(leaderColor)
363                }
364                title
365                    .lineLimit(1)
366                Spacer(minLength: 8)
367                if let habit = item.habit, let day {
368                    HabitGraph(cells: habit.graph(today: day), theme: theme)
369                }
370                if !item.tags.isEmpty {
371                    Text(":" + item.tags.joined(separator: ":") + ":")
372                        .font(.caption)
373                        .foregroundStyle(theme.color("tags") ?? .secondary)
374                }
375            }
376        }
377    }
378
379    static func trim(_ time: String) -> String {
380        time.trimmingCharacters(in: CharacterSet(charactersIn: " ┄."))
381    }
382
383    private var leaderColor: Color {
384        switch item.kind {
385        case .deadline: theme.color("agenda-deadline") ?? .red
386        case .upcomingDeadline: theme.color("agenda-upcoming") ?? .orange
387        case .pastScheduled: theme.color("agenda-scheduled-past") ?? .brown
388        default: theme.color("agenda-scheduled") ?? .secondary
389        }
390    }
391
392    /// The TODO keyword colored as in the editor.
393    private var title: Text {
394        let text = item.text.trimmingCharacters(in: .whitespaces)
395        guard let todo = item.todo, text.hasPrefix(todo + " ") else { return Text(text) }
396        let rest = String(text.dropFirst(todo.count))
397        let rest_ = Text(rest).foregroundColor(item.isDone ? theme.color("comment") ?? .secondary : theme.color("foreground") ?? .primary)
398        return Text(todo).foregroundColor(theme.keywordColor(todo, done: item.isDone)).bold() + rest_
399    }
400}
401
402/// org-habit's consistency graph: a cell per day, `*` where the habit was done, `!` today.
403struct HabitGraph: View {
404    let cells: [Habit.Cell]
405    var theme: ThemeSpec = .default
406
407    var body: some View {
408        HStack(spacing: 1) {
409            ForEach(cells, id: \.day) { cell in
410                Text(String(cell.glyph))
411                    .font(.system(size: 9, weight: .bold, design: .monospaced))
412                    .frame(width: 8, height: 14)
413                    .background(color(cell.face))
414                    .help(Self.label(cell))
415            }
416        }
417        .accessibilityElement(children: .ignore)
418        .accessibilityLabel("Done \(cells.filter { $0.glyph == "*" }.count) of the last \(Habit.precedingDays) days")
419    }
420
421    /// Due-state colors, lighter for days to come, as org-habit's faces.
422    func color(_ face: Habit.Face) -> Color {
423        func themed(_ key: String, _ fallback: Color) -> Color { theme.color(key) ?? fallback }
424        switch face {
425        case .clear: return themed("habit-clear", .blue).opacity(0.7)
426        case .clearFuture: return themed("habit-clear", .blue).opacity(0.35)
427        case .ready: return themed("habit-ready", .green).opacity(0.75)
428        case .readyFuture: return themed("habit-ready", .green).opacity(0.35)
429        case .alert: return themed("habit-alert", .yellow).opacity(0.85)
430        case .alertFuture: return themed("habit-alert", .yellow).opacity(0.4)
431        case .overdue: return themed("habit-overdue", .red).opacity(0.75)
432        case .overdueFuture: return themed("habit-overdue", .red).opacity(0.35)
433        }
434    }
435
436    static func label(_ cell: Habit.Cell) -> String {
437        let date = Days.date(cell.day)
438        return String(format: "%04d-%02d-%02d", date.year, date.month, date.day) + (cell.glyph == "*" ? " DONE" : "")
439    }
440}