Sources/Orgstar/AgendaView.swift

58f3b73e8ff337e5a15111fbb32c0d57cf2346da
orgstar/Sources/Orgstar/AgendaView.swift history · blame · raw

661 lines · 29600 bytes

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