Sources/Orgstar/AgendaView.swift

25119f4b2ffb63711ac162144288a075b8e1fe7d
orgstar/Sources/Orgstar/AgendaView.swift

666 lines · 29918 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 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            } else if !isAgenda, !isBlocks, listRows.isEmpty {
364                ContentUnavailableView(
365                    "No entries", systemImage: "checklist",
366                    description: Text(filter.isEmpty ? "Nothing in the agenda files matches this view." : "Nothing matches the filter.")
367                )
368            }
369        }
370        .sheet(item: $eventRequest) { request in
371            EventSheet(request: request, events: CalendarAccess.events) { result in
372                eventRequest = nil
373                if let result {
374                    message = result
375                    tick += 1
376                }
377            }
378        }
379        .sheet(item: Binding(get: { prompt?.prompt.fast == nil ? nil : prompt }, set: { if $0 == nil { prompt = nil } })) { pending in
380            if let fast = pending.prompt.fast {
381                FastSelectionView(selection: fast, message: pending.prompt.message) { answer in
382                    prompt = nil
383                    guard let answer else { return }
384                    promptText = answer
385                    prompt = pending
386                    answerPrompt()
387                }
388                .frame(minWidth: 420)
389            }
390        }
391        .alert(prompt?.prompt.message ?? "", isPresented: Binding(get: { prompt != nil && prompt?.prompt.fast == nil }, set: { if !$0 { prompt = nil } })) {
392            TextField("", text: $promptText)
393            Button("OK") { answerPrompt() }
394            Button("Cancel", role: .cancel) { prompt = nil }
395        } message: {
396            if let choices = prompt?.prompt.choices, !choices.isEmpty {
397                Text(choices.prefix(12).joined(separator: "  "))
398            }
399        }
400        .alert(filterPrompt?.title ?? "", isPresented: Binding(get: { filterPrompt != nil }, set: { if !$0 { filterPrompt = nil } })) {
401            TextField("", text: $filterText)
402            Button("Filter") { applyFilter() }
403            Button("Cancel", role: .cancel) { filterPrompt = nil }
404        } message: {
405            if filterPrompt?.kind == "/" || filterPrompt?.kind == "\\" {
406                Text(shown.tags.sorted().prefix(20).joined(separator: "  "))
407            }
408        }
409        .alert(textPrompt?.title ?? "", isPresented: Binding(get: { textPrompt != nil }, set: { if !$0 { textPrompt = nil } })) {
410            TextField("", text: $textAnswer)
411            Button("OK") {
412                let pending = textPrompt
413                let answer = textAnswer
414                textPrompt = nil
415                textAnswer = ""
416                // A follow-up question opens after this alert closes.
417                DispatchQueue.main.async { pending?.apply(answer) }
418            }
419            Button("Cancel", role: .cancel) {
420                textPrompt = nil
421                textAnswer = ""
422            }
423        }
424        .navigationTitle(title)
425        .navigationSubtitle(([isAgenda && viewName != AgendaViewLoader.builtIn[0].name ? viewName : ""] + [shownFolders ?? ""]).filter { !$0.isEmpty }.joined(separator: " · "))
426        .onChange(of: viewName) { applyView() }
427        .onChange(of: commands.agendaRequest?.start, initial: true) { showRequestedDays() }
428        .onChange(of: commands.agendaRequest?.days) { showRequestedDays() }
429        .background { Refresher(base: refreshKey, session: session, workspace: workspace, refresh: refresh) }
430        .task {
431            loadViews()
432            // The now line moves each minute; a new day refreshes the statuses.
433            while !Task.isCancelled {
434                let next = Calendar.current.nextDate(after: Date(), matching: DateComponents(second: 0), matchingPolicy: .nextTime) ?? Date().addingTimeInterval(60)
435                try? await Task.sleep(for: .seconds(next.timeIntervalSinceNow))
436                now = Date()
437                if Days.absolute(now, calendar: .current) != agenda.today { tick += 1 }
438            }
439        }
440    }
441
442    // MARK: - Days
443
444    private var todayColor: Color { theme.color("agenda-today") ?? .accentColor }
445
446    @ViewBuilder
447    private func dayRows(_ group: AgendaDayGroup, prefix: String = "") -> some View {
448        if group.isToday, !group.overdue.isEmpty {
449            overdueHeader(count: group.overdue.count)
450            if overdueShown {
451                ForEach(Array(group.overdue.enumerated()), id: \.element.id) { index, _ in
452                    rowView(dayLine(group, index, prefix: prefix, overdue: true))
453                }
454                Divider().padding(.leading, 16).padding(.vertical, 4)
455            }
456        }
457        if group.isEmpty {
458            Text("Nothing scheduled")
459                .font(.callout)
460                .foregroundStyle(.secondary)
461                .padding(.horizontal, 16)
462                .padding(.vertical, 10)
463        }
464        // Identified by row, not place, so a refresh that moves rows doesn't reuse one row's view
465        // for another.
466        let lines = group.lines(now: Self.hhmm(now)).map { line in
467            switch line {
468            case .row(let index): (Self.key(group.rows[index], day: group.day, prefix: prefix), line)
469            case .grid(let time): ("grid\(time)", line)
470            case .now: ("now", line)
471            }
472        }
473        ForEach(lines, id: \.0) { _, line in
474            switch line {
475            case .row(let index): rowView(dayLine(group, index, prefix: prefix))
476            case .grid(let time): gridLine(time)
477            case .now: nowLine
478            }
479        }
480    }
481
482    /// An `org-agenda-time-grid` line.
483    private func gridLine(_ time: Int) -> some View {
484        HStack(spacing: 6) {
485            Text(String(format: "%02d:%02d", time / 100, time % 100))
486                .font(.caption.monospacedDigit())
487                .frame(width: gutterWidth, alignment: .leading)
488            GridRule().stroke(style: StrokeStyle(lineWidth: 0.5, dash: [2, 3])).frame(height: 1)
489        }
490        .foregroundStyle(.tertiary)
491        .padding(.horizontal, 16)
492        .padding(.vertical, 4)
493        .accessibilityHidden(true)
494    }
495
496    private func header(@ViewBuilder _ content: () -> some View) -> some View {
497        HStack(spacing: 6) { content() }
498            .padding(.horizontal, 16)
499            .frame(minHeight: 30)
500            .frame(maxWidth: .infinity, alignment: .leading)
501            .background(theme.color("agenda-background") ?? Color(nsColor: .textBackgroundColor))
502            .overlay(alignment: .bottom) { Divider() }
503    }
504
505    private func dayHeader(_ group: AgendaDayGroup) -> some View {
506        let past = group.day < agenda.today
507        let color = group.isToday ? todayColor : past ? Color.secondary : theme.color("agenda-date") ?? .primary
508        return header {
509            if let relative = group.relativeName(today: agenda.today) {
510                Text(relative)
511                    .font(.body.weight(.bold))
512                    .foregroundStyle(color)
513                Text("·").foregroundStyle(.tertiary)
514            }
515            Text(Self.format(group.day, Days.date(group.day).year == Days.date(agenda.today).year ? "EEEE d MMMM" : "EEEE d MMMM yyyy"))
516                .font(.body.weight(group.isToday ? .bold : .semibold))
517                .foregroundStyle(color)
518            Spacer()
519            Button {
520                capture(on: group.day)
521            } label: {
522                Image(systemName: "plus")
523                    .font(.callout.weight(.semibold))
524                    .frame(width: 22, height: 22)
525                    .contentShape(Rectangle())
526            }
527            .buttonStyle(.borderless)
528            .foregroundStyle(group.isToday ? todayColor : .secondary)
529            .help("Capture an entry scheduled on this day (k)")
530        }
531    }
532
533    private func overdueHeader(count: Int) -> some View {
534        let color = theme.dynamic(.systemRed) { [theme] in theme.statusColor(.overdue, dark: $0) }
535        return Button {
536            withAnimation(.snappy(duration: 0.2)) { overdueShown.toggle() }
537            if !overdueShown, selection?.contains(":o") == true { selection = nil }
538        } label: {
539            HStack(spacing: 6) {
540                Image(systemName: "chevron.right")
541                    .font(.caption.weight(.bold))
542                    .rotationEffect(.degrees(overdueShown ? 90 : 0))
543                Text("Overdue").font(.callout.weight(.semibold))
544                Text("\(count)")
545                    .font(.caption.weight(.bold).monospacedDigit())
546                    .padding(.horizontal, 6)
547                    .padding(.vertical, 1)
548                    .background(Capsule().fill(color.opacity(0.15)))
549                Spacer()
550            }
551            .foregroundStyle(color)
552            .padding(.horizontal, 16)
553            .padding(.top, 8)
554            .padding(.bottom, 4)
555            .contentShape(Rectangle())
556        }
557        .buttonStyle(.plain)
558        .help(overdueShown ? "Hide entries from earlier days" : "Show entries from earlier days")
559    }
560
561    private var nowLine: some View {
562        HStack(spacing: 6) {
563            Text(now.formatted(.dateTime.hour(.twoDigits(amPM: .omitted)).minute()))
564                .font(.caption.weight(.semibold).monospacedDigit())
565                .frame(width: gutterWidth, alignment: .leading)
566            Circle().frame(width: 6, height: 6)
567            Rectangle().frame(height: 1)
568        }
569        .foregroundStyle(todayColor)
570        .padding(.horizontal, 16)
571        .padding(.vertical, 4)
572        .accessibilityLabel("Now")
573    }
574
575    private func rowView(_ line: Line, showsGutter: Bool = true) -> some View {
576        AgendaRowView(
577            row: line.row, day: line.day, showsGutter: showsGutter, selected: selection == line.id, hovered: hovered == line.id,
578            marked: line.row.item.flatMap(EntryRef.init).map(marked.contains) ?? false
579        )
580        .id(line.viewID)
581        .contentShape(Rectangle())
582        .onHover { inside in
583            if inside { hovered = line.id } else if hovered == line.id { hovered = nil }
584        }
585        .onTapGesture(count: 2) { open(line) }
586        .simultaneousGesture(TapGesture().onEnded {
587            selection = line.id
588            focused = true
589        })
590        .contextMenu { menu(line) }
591    }
592
593    @ViewBuilder
594    private func menu(_ line: Line) -> some View {
595        if let event = line.row.event {
596            Button(event.isReminder ? "Show in Reminders" : "Show in Calendar") { openEvent(event) }
597            if !event.isReminder {
598                Button("Edit Event…") { eventRequest = EventRequest(draft: EventDraft(event), event: event) }
599            }
600        } else if line.row.item != nil {
601            Button("Open") { selection = line.id; jump(line.id) }
602            Divider()
603            Button("Cycle TODO State") { selection = line.id; run(TodoCycle()) }
604            Button("Set Priority…") { selection = line.id; run(SetPriority()) }
605            Button("Set Tags…") { selection = line.id; run(SetTags()) }
606            Button("Schedule…") { selection = line.id; run(SetPlanning(deadline: false)) }
607            Button("Set Deadline…") { selection = line.id; run(SetPlanning(deadline: true)) }
608            Divider()
609            Button("Add to Calendar…") {
610                guard ProAccess.shared.allows(.calendar) else { return }
611                eventRequest = EventRequest(draft: .entry(line.row.title, day: line.day, start: line.row.start, end: line.row.end))
612            }
613            Divider()
614            Button("Clock In") { selection = line.id; clockIn() }
615            Button(EntryRef(line.row.item!).map(marked.contains) == true ? "Unmark" : "Mark") {
616                selection = line.id
617                mark(!(EntryRef(line.row.item!).map(marked.contains) ?? false))
618            }
619            Button("Archive") { selection = line.id; archive() }
620        }
621    }
622
623    @AppStorage("reminders") var remindersEnabled = true
624
625    // MARK: - Items
626
627    func item(_ id: String) -> AgendaItem? { line(id)?.row.item }
628
629    /// Return and double click: the entry in the main window, or the event in Calendar or Reminders.
630    func open(_ line: Line) {
631        selection = line.id
632        if let event = line.row.event { openEvent(event) } else { jump(line.id) }
633    }
634
635    /// Calendar shows an event from its identifier (`AgendaEvent.id` adds `@` and the start);
636    /// Reminders a reminder from its own.
637    private func openEvent(_ event: AgendaEvent) {
638        if event.isReminder {
639            if let url = URL(string: "x-apple-reminderkit://REMCDReminder/\(event.id)") { NSWorkspace.shared.open(url) }
640            return
641        }
642        let identifier = event.id.split(separator: "@").dropLast().joined(separator: "@")
643        guard !identifier.isEmpty, let encoded = identifier.addingPercentEncoding(withAllowedCharacters: .urlPathAllowed),
644              let url = URL(string: "ical://ekevent/\(encoded)?method=show&options=more") else { return }
645        NSWorkspace.shared.open(url)
646    }
647
648    /// Moves the selection by `step` lines.
649    func step(_ step: Int) {
650        let all = lines(groups)
651        guard !all.isEmpty else { return }
652        let index = selection.flatMap { id in all.firstIndex { $0.id == id } }
653        let next = index.map { min(max($0 + step, 0), all.count - 1) } ?? (step > 0 ? 0 : all.count - 1)
654        selection = all[next].id
655    }
656}
657
658/// A horizontal line through the middle of its frame.
659struct GridRule: Shape {
660    func path(in rect: CGRect) -> Path {
661        Path { path in
662            path.move(to: CGPoint(x: rect.minX, y: rect.midY))
663            path.addLine(to: CGPoint(x: rect.maxX, y: rect.midY))
664        }
665    }
666}
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