Sources/Orgstar/AgendaView.swift

8747c1880dce12825eeb095776dcba284ca4f646
orgstar/Sources/Orgstar/AgendaView.swift history · blame · raw

452 lines · 18632 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        .sheet(item: Binding(get: { prompt?.prompt.fast == nil ? nil : prompt }, set: { if $0 == nil { prompt = nil } })) { pending in
151            if let fast = pending.prompt.fast {
152                FastSelectionView(selection: fast, message: pending.prompt.message) { answer in
153                    prompt = nil
154                    guard let answer else { return }
155                    promptText = answer
156                    prompt = pending
157                    answerPrompt()
158                }
159                .frame(minWidth: 420)
160            }
161        }
162        .alert(prompt?.prompt.message ?? "", isPresented: Binding(get: { prompt != nil && prompt?.prompt.fast == nil }, set: { if !$0 { prompt = nil } })) {
163            TextField("", text: $promptText)
164            Button("OK") { answerPrompt() }
165            Button("Cancel", role: .cancel) { prompt = nil }
166        } message: {
167            if let choices = prompt?.prompt.choices, !choices.isEmpty {
168                Text(choices.prefix(12).joined(separator: "  "))
169            }
170        }
171        .navigationTitle(viewName.replacingOccurrences(of: "…", with: ""))
172        .onChange(of: viewName) { applyView() }
173        .task(id: refreshKey) {
174            agenda.span = span
175            agenda.startOffset = startOffset
176            agenda.includeSubfolders = includeSubfolders
177            let open = session.openTexts
178            await agenda.refresh(open: open)
179        }
180        .task {
181            loadViews()
182            // The time grid's "now" line and the day itself move on.
183            while !Task.isCancelled {
184                try? await Task.sleep(for: .seconds(60))
185                tick += 1
186            }
187        }
188    }
189
190    @ViewBuilder
191    private func rows(_ items: [AgendaItem], prefix: String, day: Int? = nil) -> some View {
192        ForEach(Array(items.enumerated()), id: \.offset) { index, item in
193            AgendaRow(item: item, day: day)
194                .tag("\(prefix):\(index)")
195                .selectionDisabled(item.path == nil)
196        }
197    }
198
199    @AppStorage("reminders") private var remindersEnabled = true
200
201    /// How far ahead notifications are set, as the design asks the agenda to show.
202    private var reminderStatus: String? {
203        guard let scheduler, remindersEnabled else { return nil }
204        if !scheduler.isAuthorized { return "Notifications are off for Orgstar in System Settings." }
205        guard let through = scheduler.scheduledThrough else { return nil }
206        return "Reminders are set through " + through.formatted(.dateTime.weekday(.abbreviated).day().month(.abbreviated).hour().minute()) + "."
207    }
208
209    private var listTitle: String {
210        switch agenda.mode {
211        case .todo(let keywords): "TODO items: \(keywords ?? "all")"
212        case .match(let match, let todoOnly): (todoOnly ? "TODO entries" : "Entries") + " matching \(match)"
213        case .agenda: ""
214        }
215    }
216
217    private func loadViews() {
218        let loaded = AgendaViewLoader.load()
219        views = loaded.views
220        message = loaded.problems.first
221    }
222
223    private func applyView() {
224        selection = nil
225        agenda.start = nil
226        switch viewName {
227        case Self.match, Self.todoMatch:
228            let match = matchText.trimmingCharacters(in: .whitespaces)
229            guard !match.isEmpty else { return }
230            agenda.mode = .match(match, todoOnly: viewName == Self.todoMatch)
231        default:
232            if let view = views.first(where: { $0.name == viewName }) { agenda.mode = view.mode }
233        }
234    }
235
236    // MARK: - Items
237
238    private func item(_ id: String) -> AgendaItem? {
239        let parts = id.split(separator: ":")
240        guard parts.count == 2, let index = Int(parts[1]) else { return nil }
241        let items = parts[0] == "list" ? agenda.list : agenda.days.first { "\($0.day)" == parts[0] }?.items ?? []
242        return index < items.count ? items[index] : nil
243    }
244
245    private func jump(_ id: String) {
246        guard let item = item(id), let path = item.path, let offset = item.markerOffset ?? item.headingOffset else { return }
247        commands.jump(path: path, offset: offset)
248        openWindow(id: "main")
249    }
250
251    // MARK: - Commands
252
253    private func handle(_ press: KeyPress) -> KeyPress.Result {
254        let control = press.modifiers.contains(.control)
255        if prefix {
256            prefix = false
257            switch (control, press.characters) {
258            case (true, "\u{13}"), (true, "s"): run(SetPlanning(deadline: false))
259            case (true, "\u{04}"), (true, "d"): run(SetPlanning(deadline: true))
260            case (true, "\u{11}"), (true, "q"): run(SetTags())
261            case (true, "\u{14}"), (true, "t"): run(TodoCycle())
262            default: message = "C-c \(press.characters) is undefined"
263            }
264            return .handled
265        }
266        if control, press.characters == "c" || press.characters == "\u{03}" {
267            prefix = true
268            message = "C-c-"
269            return .handled
270        }
271        if press.key == .return, let selection {
272            jump(selection)
273            return .handled
274        }
275        if press.modifiers == .shift, press.key == .rightArrow || press.key == .leftArrow {
276            run(ShiftTimestampDay(later: press.key == .rightArrow), atMarker: true)
277            return .handled
278        }
279        guard press.modifiers.subtracting(.shift).isEmpty else { return .ignored }
280        switch press.characters {
281        case "f" where isAgenda: agenda.shift(forward: true)
282        case "b" where isAgenda: agenda.shift(forward: false)
283        case "." where isAgenda: agenda.showToday()
284        case "g", "r":
285            loadViews()
286            tick += 1
287        case "t": run(TodoCycle())
288        case "+": run(PriorityUp())
289        case "-": run(PriorityDown())
290        case ":": run(SetTags())
291        default: return .ignored
292        }
293        return .handled
294    }
295
296    /// Runs `command` on the selected entry, at its heading or, with `atMarker`, at the
297    /// timestamp the entry is listed for.
298    private func run(_ command: any OrgCommand, atMarker: Bool = false, answers: [String: String] = [:], itemID: String? = nil) {
299        guard let id = itemID ?? selection, let item = item(id), let path = item.path, let start = item.headingOffset else {
300            message = "No entry selected"
301            return
302        }
303        if atMarker, ![.deadline, .upcomingDeadline, .scheduled, .pastScheduled, .timestamp].contains(item.kind) {
304            message = "Only dated entries can move"
305            return
306        }
307        let offset = atMarker ? (item.markerOffset ?? start) : start
308        let step = session.perform(command, path: path, at: offset, expect: item.headingLine.map { (start, $0) }, answers: answers)
309        switch step {
310        case .prompt(let request):
311            promptText = request.initial
312            prompt = PendingPrompt(prompt: request, command: command, atMarker: atMarker, answers: answers, itemID: id)
313        case .failed(let text):
314            message = text
315            tick += 1
316        case .external:
317            message = "Not available from the agenda"
318        case .commit:
319            message = nil
320            tick += 1
321        }
322    }
323
324    private func answerPrompt() {
325        guard let pending = prompt else { return }
326        prompt = nil
327        var answers = pending.answers
328        answers[pending.prompt.key] = promptText
329        run(pending.command, atMarker: pending.atMarker, answers: answers, itemID: pending.itemID)
330    }
331}
332
333struct AgendaRow: View {
334    let item: AgendaItem
335    /// The agenda day the row is on, for habit graphs.
336    var day: Int?
337    @Environment(\.orgTheme) private var theme
338
339    var body: some View {
340        switch item.kind {
341        case .timeGrid:
342            HStack(spacing: 8) {
343                Text(Self.trim(item.time))
344                    .monospacedDigit()
345                    .frame(width: 140, alignment: .trailing)
346                VStack { Divider() }
347            }
348            .font(.caption)
349            .foregroundStyle(theme.color("agenda-time").map(AnyShapeStyle.init) ?? AnyShapeStyle(.tertiary))
350        case .currentTime:
351            HStack(spacing: 8) {
352                Text("now " + Self.trim(item.time))
353                    .monospacedDigit()
354                    .frame(width: 140, alignment: .trailing)
355                Rectangle().fill(theme.color("agenda-today") ?? .accentColor).frame(height: 1)
356            }
357            .font(.caption)
358            .foregroundStyle(theme.color("agenda-today") ?? .accentColor)
359        default:
360            HStack(spacing: 8) {
361                Text(item.category)
362                    .lineLimit(1)
363                    .foregroundStyle(theme.color("agenda-category") ?? .secondary)
364                    .frame(width: 80, alignment: .leading)
365                if item.kind != .todo, item.kind != .tagsMatch {
366                    Text(Self.trim(item.time))
367                        .monospacedDigit()
368                        .foregroundStyle(theme.color("agenda-time") ?? .primary)
369                        .frame(width: 80, alignment: .leading)
370                }
371                if !item.extra.isEmpty {
372                    Text(item.extra.trimmingCharacters(in: .whitespaces))
373                        .monospacedDigit()
374                        .foregroundStyle(leaderColor)
375                }
376                title
377                    .lineLimit(1)
378                Spacer(minLength: 8)
379                if let habit = item.habit, let day {
380                    HabitGraph(cells: habit.graph(today: day), theme: theme)
381                }
382                if !item.tags.isEmpty {
383                    Text(":" + item.tags.joined(separator: ":") + ":")
384                        .font(.caption)
385                        .foregroundStyle(theme.color("tags") ?? .secondary)
386                }
387            }
388        }
389    }
390
391    static func trim(_ time: String) -> String {
392        time.trimmingCharacters(in: CharacterSet(charactersIn: " ┄."))
393    }
394
395    private var leaderColor: Color {
396        switch item.kind {
397        case .deadline: theme.color("agenda-deadline") ?? .red
398        case .upcomingDeadline: theme.color("agenda-upcoming") ?? .orange
399        case .pastScheduled: theme.color("agenda-scheduled-past") ?? .brown
400        default: theme.color("agenda-scheduled") ?? .secondary
401        }
402    }
403
404    /// The TODO keyword colored as in the editor.
405    private var title: Text {
406        let text = item.text.trimmingCharacters(in: .whitespaces)
407        guard let todo = item.todo, text.hasPrefix(todo + " ") else { return Text(text) }
408        let rest = String(text.dropFirst(todo.count))
409        let rest_ = Text(rest).foregroundColor(item.isDone ? theme.color("comment") ?? .secondary : theme.color("foreground") ?? .primary)
410        return Text(todo).foregroundColor(theme.keywordColor(todo, done: item.isDone)).bold() + rest_
411    }
412}
413
414/// org-habit's consistency graph: a cell per day, `*` where the habit was done, `!` today.
415struct HabitGraph: View {
416    let cells: [Habit.Cell]
417    var theme: ThemeSpec = .default
418
419    var body: some View {
420        HStack(spacing: 1) {
421            ForEach(cells, id: \.day) { cell in
422                Text(String(cell.glyph))
423                    .font(.system(size: 9, weight: .bold, design: .monospaced))
424                    .frame(width: 8, height: 14)
425                    .background(color(cell.face))
426                    .help(Self.label(cell))
427            }
428        }
429        .accessibilityElement(children: .ignore)
430        .accessibilityLabel("Done \(cells.filter { $0.glyph == "*" }.count) of the last \(Habit.precedingDays) days")
431    }
432
433    /// Due-state colors, lighter for days to come, as org-habit's faces.
434    func color(_ face: Habit.Face) -> Color {
435        func themed(_ key: String, _ fallback: Color) -> Color { theme.color(key) ?? fallback }
436        switch face {
437        case .clear: return themed("habit-clear", .blue).opacity(0.7)
438        case .clearFuture: return themed("habit-clear", .blue).opacity(0.35)
439        case .ready: return themed("habit-ready", .green).opacity(0.75)
440        case .readyFuture: return themed("habit-ready", .green).opacity(0.35)
441        case .alert: return themed("habit-alert", .yellow).opacity(0.85)
442        case .alertFuture: return themed("habit-alert", .yellow).opacity(0.4)
443        case .overdue: return themed("habit-overdue", .red).opacity(0.75)
444        case .overdueFuture: return themed("habit-overdue", .red).opacity(0.35)
445        }
446    }
447
448    static func label(_ cell: Habit.Cell) -> String {
449        let date = Days.date(cell.day)
450        return String(format: "%04d-%02d-%02d", date.year, date.month, date.day) + (cell.glyph == "*" ? " DONE" : "")
451    }
452}