Sources/Orgstar/AgendaView.swift

ba73817ee7c251b64177f28b1cb0b6f2a8583b88
orgstar/Sources/Orgstar/AgendaView.swift

517 lines · 22343 bytes

  1import AppKit
  2import OrgApp
  3import OrgDocument
  4import OrgCore
  5import OrgPresentation
  6import SwiftUI
  7
  8/// The days an agenda shows, as Org's `v d`, `v w` and `v m`.
  9enum AgendaSpan: String, CaseIterable {
 10    case day, week, month
 11}
 12
 13/// The app's one reader of Calendar events, for the agenda and Settings.
 14@MainActor
 15enum CalendarAccess {
 16    static let events = CalendarEvents()
 17}
 18
 19/// The agenda window: the day/week agenda, the TODO list, tag matches, text search and saved views.
 20/// Return or a double click jumps to the entry in the main window. Keys as in Emacs's agenda:
 21/// n/p (or the arrows) move between lines, f/b/. move the span, j picks a date, v d/v w/v m (or
 22/// d/w) show a day, week or month, g refreshes, l shows the log (closed and clocked), / filters
 23/// (`+cat-tag<0:10-/regexp/`), \ by tag, < by the line's category, = by regexp, _ by effort,
 24/// | clears filters, I/O/X clock in, out and cancel, C-c C-w refiles, $ archives, m/u/U mark
 25/// and unmark, B acts on the marked entries, t cycles the TODO state, +/- change the priority and
 26/// , sets it, : or C-c C-q sets tags, C-c C-s / C-c C-d schedule and set a deadline, S-→/S-← move
 27/// the date, k captures on the line's day, s saves all files, TAB and SPC show the entry.
 28struct AgendaView: View {
 29    let workspace: WorkspaceModel
 30    let session: DocumentSession
 31    let commands: AppCommands
 32    let scheduler: ReminderScheduler?
 33    let clock: ClockModel
 34    @State var agenda: AgendaModel
 35    @State var views = AgendaViewLoader.builtIn
 36    @State var viewName = AgendaViewLoader.builtIn[0].name
 37    @State var matchText = ""
 38    /// The selected line: `day:index` (`day:o` + index in the overdue group), or `list:index`.
 39    @State var selection: String?
 40    @State var tick = 0
 41    /// The time the now line shows, kept to the minute while the agenda is open.
 42    @State var now = Date()
 43    /// The view picker moved to the agenda for a followed timestamp, which sets its own days.
 44    @State var keepRequestedDays = false
 45    @State var message: String?
 46    @State var prompt: PendingPrompt?
 47    @State var promptText = ""
 48    @State var prefix: String?
 49    /// Entries marked for a bulk action.
 50    @State var marked: [EntryRef] = []
 51    @State var logMode = false
 52    @State var filter = AgendaFilter()
 53    /// A filter question: its title and which filter it sets.
 54    @State var filterPrompt: (title: String, kind: Character)?
 55    @State var filterText = ""
 56    /// A one-line question for an agenda action, and what to do with the answer.
 57    struct TextPrompt {
 58        let title: String
 59        let apply: (String) -> Void
 60    }
 61    @State var textPrompt: TextPrompt?
 62    @State private var textAnswer = ""
 63    /// Day, week or month chosen with `v`; nil shows the span the settings or the view give.
 64    @State var spanKind: AgendaSpan?
 65    @State var showingDatePicker = false
 66    @State var pickedDate = Date()
 67    @AppStorage("agendaOverdueExpanded") private var overdueShown = true
 68    @State private var hovered: String?
 69    @FocusState private var focused: Bool
 70    @AppStorage("agendaSpan") var span = 10
 71    @AppStorage("agendaStartOffset") var startOffset = 0
 72    @AppStorage("agendaSubfolders") private var includeSubfolders = false
 73    @AppStorage("agendaShowAllDates") private var showAllDates = false
 74    @AppStorage("calendarEvents") private var calendarEventsOn = false
 75    @AppStorage("calendarEventCalendars") private var calendarNames = ""
 76    @AppStorage("agendaPrefixAgenda") private var prefixAgenda = PrefixFormat.defaults["agenda"]!
 77    @AppStorage("agendaPrefixTodo") private var prefixTodo = PrefixFormat.defaults["todo"]!
 78    @AppStorage("agendaPrefixTags") private var prefixTags = PrefixFormat.defaults["tags"]!
 79    @Environment(\.openWindow) var openWindow
 80
 81    static let match = "Match…"
 82    static let todoMatch = "TODO Match…"
 83    static let search = "Search…"
 84    static let todoSearch = "TODO Search…"
 85
 86    init(workspace: WorkspaceModel, session: DocumentSession, commands: AppCommands, scheduler: ReminderScheduler?, clock: ClockModel) {
 87        self.workspace = workspace
 88        self.session = session
 89        self.commands = commands
 90        self.scheduler = scheduler
 91        self.clock = clock
 92        _agenda = State(initialValue: AgendaModel(workspace: workspace))
 93    }
 94
 95    /// An agenda entry by its file, heading line and where that line was.
 96    struct EntryRef: Hashable {
 97        let path: String
 98        let line: String
 99        let offset: Int
100
101        init?(_ item: AgendaItem) {
102            guard let path = item.path, let line = item.headingLine, let offset = item.headingOffset else { return nil }
103            self.path = path
104            self.line = line
105            self.offset = offset
106        }
107    }
108
109    struct PendingPrompt: Identifiable {
110        let id = UUID()
111        let prompt: Prompt
112        let command: any OrgCommand
113        let atMarker: Bool
114        let answers: [String: String]
115        let itemID: String
116    }
117
118    private struct RefreshKey: Hashable {
119        var mode: AgendaMode
120        var start: Int?
121        var span: Int
122        var startOffset: Int
123        var includeSubfolders: Bool
124        var prefix: [String]
125        var logMode: Bool
126        var calendars: [String]
127        var files: Int
128        var changed: Int?
129        var edits: Int
130        var path: String?
131        var tick: Int
132    }
133
134    /// The settings part of the refresh key; `Refresher` adds the files and edits, so that
135    /// they redraw only it.
136    private var refreshKey: RefreshKey {
137        RefreshKey(
138            mode: agenda.mode, start: agenda.start, span: span, startOffset: startOffset, includeSubfolders: includeSubfolders, prefix: [prefixAgenda, prefixTodo, prefixTags], logMode: logMode,
139            calendars: calendarEventsOn ? [calendarNames] : [], files: 0, changed: nil, edits: 0, path: nil, tick: tick
140        )
141    }
142
143    private func refresh() async {
144        agenda.span = span
145        agenda.startOffset = startOffset
146        agenda.includeSubfolders = includeSubfolders
147        agenda.options.prefixFormat = ["agenda": prefixAgenda, "todo": prefixTodo, "tags": prefixTags]
148        agenda.options.logMode = logMode
149        agenda.options = OrgPreferences.agendaOptions(agenda.options)
150        agenda.calendarNames = OrgPreferences.calendarEventCalendars()
151        if calendarEventsOn, isAgenda {
152            agenda.calendarEvents = await CalendarAccess.events.requestAccess() ? CalendarAccess.events : nil
153        } else {
154            agenda.calendarEvents = nil
155        }
156        await agenda.refresh(open: session.openTexts)
157    }
158
159    /// Refreshes the agenda when the settings, files or edits change, once a burst of them ends.
160    private struct Refresher: View {
161        let base: RefreshKey
162        let session: DocumentSession
163        let workspace: WorkspaceModel
164        let refresh: () async -> Void
165
166        var key: RefreshKey {
167            var key = base
168            key.files = workspace.files.count
169            key.changed = workspace.changedFile?.version
170            key.edits = session.editVersion
171            key.path = session.path
172            return key
173        }
174
175        var body: some View {
176            Color.clear.task(id: key) {
177                try? await Task.sleep(for: .milliseconds(150))
178                guard !Task.isCancelled else { return }
179                await refresh()
180            }
181        }
182    }
183
184    var isAgenda: Bool {
185        if case .agenda = agenda.mode { return true }
186        return false
187    }
188
189    var isMatch: Bool { viewName == Self.match || viewName == Self.todoMatch }
190    var isSearch: Bool { viewName == Self.search || viewName == Self.todoSearch }
191
192    @Environment(\.orgTheme) private var theme
193
194    // MARK: - Lines
195
196    /// A selectable line: its selection id, the row, and the day it is on.
197    struct Line {
198        let id: String
199        let row: AgendaRow
200        let day: Int
201    }
202
203    private var groups: [AgendaDayGroup] {
204        isAgenda ? agenda.groups(showAllDates: showAllDates, filter: filter) : []
205    }
206
207    private var listRows: [AgendaRow] {
208        isAgenda ? [] : agenda.list.filter(filter.keeps).compactMap { AgendaRow(item: $0, day: agenda.today, today: agenda.today) }
209    }
210
211    /// The lines in order, as up and down move through them.
212    func lines(_ groups: [AgendaDayGroup]) -> [Line] {
213        guard isAgenda else { return listRows.enumerated().map { Line(id: "list:\($0.offset)", row: $0.element, day: agenda.today) } }
214        return groups.flatMap { group in
215            (overdueShown ? group.overdue.enumerated().map { Line(id: "\(group.day):o\($0.offset)", row: $0.element, day: group.day) } : [])
216                + group.rows.enumerated().map { Line(id: "\(group.day):\($0.offset)", row: $0.element, day: group.day) }
217        }
218    }
219
220    func line(_ id: String) -> Line? { lines(groups).first { $0.id == id } }
221
222    var body: some View {
223        let groups = self.groups
224        _ = tick
225        return ScrollViewReader { proxy in
226            ScrollView {
227                LazyVStack(alignment: .leading, spacing: 0, pinnedViews: [.sectionHeaders]) {
228                    if isAgenda {
229                        ForEach(groups) { group in
230                            Section {
231                                dayRows(group)
232                            } header: {
233                                dayHeader(group).id("day\(group.day)")
234                            }
235                        }
236                    } else {
237                        Section {
238                            ForEach(Array(listRows.enumerated()), id: \.offset) { index, row in
239                                rowView(Line(id: "list:\(index)", row: row, day: agenda.today), showsGutter: false)
240                            }
241                        } header: {
242                            header { Text(listTitle).font(.system(size: 13, weight: .semibold)) }
243                        }
244                    }
245                }
246                .padding(.bottom, 12)
247            }
248            .onChange(of: selection) {
249                if let selection { proxy.scrollTo(selection) }
250            }
251            .onChange(of: agenda.days.first?.day) {
252                if groups.contains(where: \.isToday) { proxy.scrollTo("day\(agenda.today)", anchor: .top) }
253            }
254        }
255        .background(theme.color("agenda-background") ?? Color(nsColor: .textBackgroundColor))
256        .focusable()
257        .focusEffectDisabled()
258        .focused($focused)
259        .onAppear { focused = true }
260        .onKeyPress(phases: .down) { press in handle(press) }
261        .safeAreaInset(edge: .bottom, spacing: 0) {
262            if let message = message ?? (filter.isEmpty ? reminderStatus : "Filter: " + filter.description) {
263                Text(message)
264                    .font(.callout)
265                    .frame(maxWidth: .infinity, alignment: .leading)
266                    .padding(.horizontal, 12)
267                    .padding(.vertical, 6)
268                    .background(.bar)
269            }
270        }
271        .toolbar { toolbar }
272        .overlay {
273            if agenda.files.isEmpty {
274                ContentUnavailableView("No agenda files", systemImage: "calendar", description: Text("The agenda reads the org files at the top of each folder you add."))
275            }
276        }
277        .sheet(item: Binding(get: { prompt?.prompt.fast == nil ? nil : prompt }, set: { if $0 == nil { prompt = nil } })) { pending in
278            if let fast = pending.prompt.fast {
279                FastSelectionView(selection: fast, message: pending.prompt.message) { answer in
280                    prompt = nil
281                    guard let answer else { return }
282                    promptText = answer
283                    prompt = pending
284                    answerPrompt()
285                }
286                .frame(minWidth: 420)
287            }
288        }
289        .alert(prompt?.prompt.message ?? "", isPresented: Binding(get: { prompt != nil && prompt?.prompt.fast == nil }, set: { if !$0 { prompt = nil } })) {
290            TextField("", text: $promptText)
291            Button("OK") { answerPrompt() }
292            Button("Cancel", role: .cancel) { prompt = nil }
293        } message: {
294            if let choices = prompt?.prompt.choices, !choices.isEmpty {
295                Text(choices.prefix(12).joined(separator: "  "))
296            }
297        }
298        .alert(filterPrompt?.title ?? "", isPresented: Binding(get: { filterPrompt != nil }, set: { if !$0 { filterPrompt = nil } })) {
299            TextField("", text: $filterText)
300            Button("Filter") { applyFilter() }
301            Button("Cancel", role: .cancel) { filterPrompt = nil }
302        } message: {
303            if filterPrompt?.kind == "/" || filterPrompt?.kind == "\\" {
304                Text(shown.tags.sorted().prefix(20).joined(separator: "  "))
305            }
306        }
307        .alert(textPrompt?.title ?? "", isPresented: Binding(get: { textPrompt != nil }, set: { if !$0 { textPrompt = nil } })) {
308            TextField("", text: $textAnswer)
309            Button("OK") {
310                let pending = textPrompt
311                let answer = textAnswer
312                textPrompt = nil
313                textAnswer = ""
314                // A follow-up question opens after this alert closes.
315                DispatchQueue.main.async { pending?.apply(answer) }
316            }
317            Button("Cancel", role: .cancel) {
318                textPrompt = nil
319                textAnswer = ""
320            }
321        }
322        .navigationTitle(title)
323        .navigationSubtitle(isAgenda && viewName != AgendaViewLoader.builtIn[0].name ? viewName : "")
324        .onChange(of: viewName) { applyView() }
325        .onChange(of: commands.agendaRequest?.start, initial: true) { showRequestedDays() }
326        .onChange(of: commands.agendaRequest?.days) { showRequestedDays() }
327        .background { Refresher(base: refreshKey, session: session, workspace: workspace, refresh: refresh) }
328        .task {
329            loadViews()
330            // The now line moves each minute; a new day refreshes the statuses.
331            while !Task.isCancelled {
332                let next = Calendar.current.nextDate(after: Date(), matching: DateComponents(second: 0), matchingPolicy: .nextTime) ?? Date().addingTimeInterval(60)
333                try? await Task.sleep(for: .seconds(next.timeIntervalSinceNow))
334                now = Date()
335                if Days.absolute(now, calendar: .current) != agenda.today { tick += 1 }
336            }
337        }
338    }
339
340    // MARK: - Days
341
342    private var todayColor: Color { theme.color("agenda-today") ?? .accentColor }
343
344    @ViewBuilder
345    private func dayRows(_ group: AgendaDayGroup) -> some View {
346        if group.isToday, !group.overdue.isEmpty {
347            overdueHeader(count: group.overdue.count)
348            if overdueShown {
349                ForEach(Array(group.overdue.enumerated()), id: \.element.id) { index, row in
350                    rowView(Line(id: "\(group.day):o\(index)", row: row, day: group.day))
351                }
352                Divider().padding(.leading, 16).padding(.vertical, 4)
353            }
354        }
355        if group.isEmpty {
356            Text("Nothing scheduled")
357                .font(.callout)
358                .foregroundStyle(.secondary)
359                .padding(.horizontal, 16)
360                .padding(.vertical, 10)
361        }
362        let nowAt = group.nowIndex(now: Self.hhmm(now))
363        ForEach(Array(group.rows.enumerated()), id: \.element.id) { index, row in
364            if index == nowAt { nowLine }
365            rowView(Line(id: "\(group.day):\(index)", row: row, day: group.day))
366        }
367        if let nowAt, nowAt == group.rows.count { nowLine }
368    }
369
370    private func header(@ViewBuilder _ content: () -> some View) -> some View {
371        HStack(spacing: 6) { content() }
372            .padding(.horizontal, 16)
373            .frame(height: 30)
374            .frame(maxWidth: .infinity, alignment: .leading)
375            .background(theme.color("agenda-background") ?? Color(nsColor: .textBackgroundColor))
376            .overlay(alignment: .bottom) { Divider() }
377    }
378
379    private func dayHeader(_ group: AgendaDayGroup) -> some View {
380        let past = group.day < agenda.today
381        let color = group.isToday ? todayColor : past ? Color.secondary : theme.color("agenda-date") ?? .primary
382        return header {
383            if let relative = group.relativeName(today: agenda.today) {
384                Text(relative)
385                    .font(.system(size: 13, weight: .bold))
386                    .foregroundStyle(color)
387                Text("·").foregroundStyle(.tertiary)
388            }
389            Text(Self.format(group.day, Days.date(group.day).year == Days.date(agenda.today).year ? "EEEE d MMMM" : "EEEE d MMMM yyyy"))
390                .font(.system(size: 13, weight: group.isToday ? .bold : .semibold))
391                .foregroundStyle(color)
392            Spacer()
393            Button {
394                capture(on: group.day)
395            } label: {
396                Image(systemName: "plus")
397                    .font(.system(size: 12, weight: .semibold))
398                    .frame(width: 22, height: 22)
399                    .contentShape(Rectangle())
400            }
401            .buttonStyle(.borderless)
402            .foregroundStyle(group.isToday ? todayColor : .secondary)
403            .help("Capture an entry scheduled on this day (k)")
404        }
405    }
406
407    private func overdueHeader(count: Int) -> some View {
408        let color = theme.dynamic(.systemRed) { [theme] in theme.statusColor(.overdue, dark: $0) }
409        return Button {
410            withAnimation(.snappy(duration: 0.2)) { overdueShown.toggle() }
411            if !overdueShown, selection?.contains(":o") == true { selection = nil }
412        } label: {
413            HStack(spacing: 6) {
414                Image(systemName: "chevron.right")
415                    .font(.system(size: 10, weight: .bold))
416                    .rotationEffect(.degrees(overdueShown ? 90 : 0))
417                Text("Overdue").font(.system(size: 12, weight: .semibold))
418                Text("\(count)")
419                    .font(.system(size: 10, weight: .bold).monospacedDigit())
420                    .padding(.horizontal, 6)
421                    .padding(.vertical, 1)
422                    .background(Capsule().fill(color.opacity(0.15)))
423                Spacer()
424            }
425            .foregroundStyle(color)
426            .padding(.horizontal, 16)
427            .padding(.top, 8)
428            .padding(.bottom, 4)
429            .contentShape(Rectangle())
430        }
431        .buttonStyle(.plain)
432        .help(overdueShown ? "Hide entries from earlier days" : "Show entries from earlier days")
433    }
434
435    private var nowLine: some View {
436        HStack(spacing: 6) {
437            Text(now.formatted(.dateTime.hour(.twoDigits(amPM: .omitted)).minute()))
438                .font(.system(size: 10, weight: .semibold).monospacedDigit())
439                .frame(width: AgendaRowView.gutterWidth, alignment: .leading)
440            Circle().frame(width: 6, height: 6)
441            Rectangle().frame(height: 1)
442        }
443        .foregroundStyle(todayColor)
444        .padding(.horizontal, 16)
445        .frame(height: 10)
446        .accessibilityLabel("Now")
447    }
448
449    private func rowView(_ line: Line, showsGutter: Bool = true) -> some View {
450        AgendaRowView(
451            row: line.row, day: line.day, showsGutter: showsGutter, selected: selection == line.id, hovered: hovered == line.id,
452            marked: line.row.item.flatMap(EntryRef.init).map(marked.contains) ?? false
453        )
454        .id(line.id)
455        .contentShape(Rectangle())
456        .onHover { inside in
457            if inside { hovered = line.id } else if hovered == line.id { hovered = nil }
458        }
459        .onTapGesture(count: 2) { open(line) }
460        .simultaneousGesture(TapGesture().onEnded {
461            selection = line.id
462            focused = true
463        })
464        .contextMenu { menu(line) }
465    }
466
467    @ViewBuilder
468    private func menu(_ line: Line) -> some View {
469        if let event = line.row.event {
470            Button("Show in Calendar") { openEvent(event) }
471        } else if line.row.item != nil {
472            Button("Open") { selection = line.id; jump(line.id) }
473            Divider()
474            Button("Cycle TODO State") { selection = line.id; run(TodoCycle()) }
475            Button("Set Priority…") { selection = line.id; run(SetPriority()) }
476            Button("Set Tags…") { selection = line.id; run(SetTags()) }
477            Button("Schedule…") { selection = line.id; run(SetPlanning(deadline: false)) }
478            Button("Set Deadline…") { selection = line.id; run(SetPlanning(deadline: true)) }
479            Divider()
480            Button("Clock In") { selection = line.id; clockIn() }
481            Button(EntryRef(line.row.item!).map(marked.contains) == true ? "Unmark" : "Mark") {
482                selection = line.id
483                mark(!(EntryRef(line.row.item!).map(marked.contains) ?? false))
484            }
485            Button("Archive") { selection = line.id; archive() }
486        }
487    }
488
489    @AppStorage("reminders") var remindersEnabled = true
490
491    // MARK: - Items
492
493    func item(_ id: String) -> AgendaItem? { line(id)?.row.item }
494
495    /// Return and double click: the entry in the main window, or the event in Calendar.
496    func open(_ line: Line) {
497        selection = line.id
498        if let event = line.row.event { openEvent(event) } else { jump(line.id) }
499    }
500
501    /// Calendar shows an event from its identifier (`AgendaEvent.id` adds `@` and the start).
502    private func openEvent(_ event: AgendaEvent) {
503        let identifier = event.id.split(separator: "@").dropLast().joined(separator: "@")
504        guard !identifier.isEmpty, let encoded = identifier.addingPercentEncoding(withAllowedCharacters: .urlPathAllowed),
505              let url = URL(string: "ical://ekevent/\(encoded)?method=show&options=more") else { return }
506        NSWorkspace.shared.open(url)
507    }
508
509    /// Moves the selection by `step` lines.
510    func step(_ step: Int) {
511        let all = lines(groups)
512        guard !all.isEmpty else { return }
513        let index = selection.flatMap { id in all.firstIndex { $0.id == id } }
514        let next = index.map { min(max($0 + step, 0), all.count - 1) } ?? (step > 0 ? 0 : all.count - 1)
515        selection = all[next].id
516    }
517}
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