Sources/Orgstar/AgendaView.swift

cc2ed5c2b61a55a3a4d932add582f53e496c6d2b
orgstar/Sources/Orgstar/AgendaView.swift

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