Sources/Orgstar/AgendaView.swift

241525746419a10a1816afce1593ecb62ebea46b
orgstar/Sources/Orgstar/AgendaView.swift

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