Sources/Orgstar/AgendaView.swift

524b5afe95ec3f3e3d1daba761a9e181f09cf88a
orgstar/Sources/Orgstar/AgendaView.swift history · blame · raw

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