Sources/Orgstar/AgendaView.swift

848c7b130274052f194a17fccd4e33e6bb30851d
orgstar/Sources/Orgstar/AgendaView.swift history · blame · raw

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