Sources/Orgstar/AgendaView.swift

d4ccb12cca1f5f07b8acf23dc1cac828bb6a1498
orgstar/Sources/Orgstar/AgendaView.swift

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