Sources/Orgstar/AgendaView+Toolbar.swift
289 lines · 12138 bytes
1import AppKit
2import OrgApp
3import OrgDocument
4import OrgCore
5import OrgPresentation
6import SwiftUI
7
8extension AgendaView {
9 // MARK: - Toolbar
10
11 @ToolbarContentBuilder
12 var toolbar: some ToolbarContent {
13 ToolbarItemGroup(placement: .navigation) {
14 Menu {
15 ForEach(views) { view in Button(view.name) { viewName = view.name } }
16 Divider()
17 Button(Self.match) { viewName = Self.match }
18 Button(Self.todoMatch) { viewName = Self.todoMatch }
19 Button(Self.search) { viewName = Self.search }
20 Button(Self.todoSearch) { viewName = Self.todoSearch }
21 } label: {
22 Label(viewName, systemImage: "calendar").labelStyle(.titleAndIcon)
23 }
24 .help("What the agenda shows")
25 if isMatch || isSearch {
26 TextField(isSearch ? "Phrase or +word -word {regexp}" : "+work-boss|LEVEL>2/!TODO", text: $matchText)
27 .frame(minWidth: 220)
28 .onSubmit { applyView() }
29 }
30 }
31 ToolbarItemGroup {
32 if agenda.isComputing { ProgressView().controlSize(.small) }
33 if isAgenda {
34 Picker("Span", selection: Binding(get: { spanKind }, set: { if let kind = $0 { setSpan(kind) } })) {
35 Text("Day").tag(AgendaSpan?.some(.day))
36 Text("Week").tag(AgendaSpan?.some(.week))
37 Text("Month").tag(AgendaSpan?.some(.month))
38 }
39 .pickerStyle(.segmented)
40 .labelsHidden()
41 .help("Show a day, week or month (v d, v w, v m)")
42 ControlGroup {
43 Button("Earlier", systemImage: "chevron.left") { move(forward: false) }
44 .help("Previous days (b)")
45 Button("Today") { goToday() }
46 .help("Back to today (.)")
47 Button("Later", systemImage: "chevron.right") { move(forward: true) }
48 .help("Next days (f)")
49 }
50 Button("Go to Date", systemImage: "calendar") {
51 pickedDate = Self.date(anchorDay)
52 showingDatePicker = true
53 }
54 .help("Go to a date (j)")
55 .popover(isPresented: $showingDatePicker, arrowEdge: .bottom) {
56 DatePicker("Date", selection: $pickedDate, displayedComponents: .date)
57 .datePickerStyle(.graphical)
58 .labelsHidden()
59 .padding()
60 .onChange(of: pickedDate) {
61 showingDatePicker = false
62 goTo(Days.absolute(pickedDate, calendar: .current))
63 }
64 }
65 }
66 Menu {
67 Button("Filter…") { askFilter("/") }
68 Button("By Tag…") { askFilter("\\") }
69 Button("By Category of Selected Line") { toggleCategoryFilter() }
70 Button("By Regexp…") { askFilter("=") }
71 Button("By Effort…") { askFilter("_") }
72 Divider()
73 Button("Remove Filters") { filter = AgendaFilter() }
74 .disabled(filter.isEmpty)
75 } label: {
76 Label("Filter", systemImage: filter.isEmpty ? "line.3.horizontal.decrease.circle" : "line.3.horizontal.decrease.circle.fill")
77 } primaryAction: {
78 askFilter("/")
79 }
80 .help("Filter the entries (/, \\, <, =, _; | removes)")
81 }
82 }
83
84 /// The span shown, as the window's title: `Week of 5 Oct 2026`.
85 var title: String {
86 guard isAgenda else { return viewName.replacingOccurrences(of: "…", with: "") }
87 guard let first = agenda.days.first?.day, let last = agenda.days.last?.day else { return "Agenda" }
88 switch spanKind {
89 case .day: return Self.format(first, "EEEE d MMMM yyyy")
90 case .week: return "Week of " + Self.format(first, "d MMM yyyy")
91 case .month: return Self.format(first, "MMMM yyyy")
92 case nil:
93 if first == last { return Self.format(first, "EEEE d MMMM yyyy") }
94 let sameYear = Days.date(first).year == Days.date(last).year
95 return Self.format(first, sameYear ? "d MMM" : "d MMM yyyy") + " – " + Self.format(last, "d MMM yyyy")
96 }
97 }
98
99 // MARK: - Span
100
101 /// The day `v`, `j` and `k` start from: the selected line's, else today when shown, else the first.
102 var anchorDay: Int {
103 if let selection, let day = Int(selection.prefix { $0 != ":" }) { return day }
104 let days = agenda.days.map(\.day)
105 if days.contains(agenda.today) || days.isEmpty { return agenda.today }
106 return days[0]
107 }
108
109 /// `org-agenda-day-view`, `-week-view`, `-month-view`: the day, the week from Monday
110 /// (`org-agenda-start-on-weekday`), or the month around `anchor`.
111 func setSpan(_ kind: AgendaSpan, around anchor: Int? = nil) {
112 let anchor = anchor ?? anchorDay
113 spanKind = kind
114 selection = nil
115 switch kind {
116 case .day:
117 agenda.mode = .agenda(span: 1, startOffset: nil)
118 agenda.start = anchor
119 case .week:
120 agenda.mode = .agenda(span: 7, startOffset: nil)
121 agenda.start = Days.weekStart(anchor, on: agenda.startOnWeekday)
122 case .month:
123 let d = Days.date(anchor)
124 let first = Days.absolute(year: d.year, month: d.month, day: 1)
125 let next = d.month == 12 ? Days.absolute(year: d.year + 1, month: 1, day: 1) : Days.absolute(year: d.year, month: d.month + 1, day: 1)
126 agenda.mode = .agenda(span: next - first, startOffset: nil)
127 agenda.start = first
128 }
129 }
130
131 func move(forward: Bool) {
132 selection = nil
133 if spanKind == .month, let first = agenda.days.first?.day {
134 setSpan(.month, around: forward ? first + 31 : first - 1)
135 } else {
136 agenda.shift(forward: forward)
137 }
138 }
139
140 func goToday() {
141 if let spanKind { setSpan(spanKind, around: agenda.today) } else { agenda.showToday() }
142 selection = nil
143 }
144
145 /// `org-agenda-goto-date`.
146 private func goTo(_ day: Int) {
147 if let spanKind { setSpan(spanKind, around: day) } else { agenda.start = day }
148 selection = nil
149 }
150
151 /// Capture on `day`, as `org-agenda-capture`.
152 func capture(on day: Int) {
153 commands.capture(on: day)
154 NSApp.activate()
155 openWindow(id: "capture")
156 }
157
158 static func date(_ day: Int) -> Date {
159 let d = Days.date(day)
160 return Calendar.current.date(from: DateComponents(year: d.year, month: d.month, day: d.day)) ?? Date()
161 }
162
163 static func format(_ day: Int, _ pattern: String) -> String {
164 let formatter = DateFormatter()
165 formatter.dateFormat = pattern
166 return formatter.string(from: date(day))
167 }
168
169 static func hhmm(_ date: Date) -> Int {
170 let c = Calendar.current.dateComponents([.hour, .minute], from: date)
171 return (c.hour ?? 0) * 100 + (c.minute ?? 0)
172 }
173 /// How far ahead notifications are set, as the design asks the agenda to show.
174 var reminderStatus: String? {
175 guard let scheduler, remindersEnabled else { return nil }
176 if !scheduler.isAuthorized { return "Notifications are off for orgstar in System Settings." }
177 guard let through = scheduler.scheduledThrough else { return nil }
178 return "Reminders are set through " + through.formatted(.dateTime.weekday(.abbreviated).day().month(.abbreviated).hour().minute()) + "."
179 }
180
181 var listTitle: String {
182 switch agenda.mode {
183 case .todo(let keywords): "TODO items: \(keywords ?? "all")"
184 case .match(let match, let todoOnly): (todoOnly ? "TODO entries" : "Entries") + " matching \(match)"
185 case .search(let string, let todoOnly): (todoOnly ? "TODO entries" : "Entries") + " containing \(string)"
186 case .agenda: ""
187 }
188 }
189
190 func loadViews() {
191 let loaded = AgendaViewLoader.load()
192 views = loaded.views
193 message = loaded.problems.first
194 }
195
196 /// The days of a followed timestamp, in the agenda view.
197 func showRequestedDays() {
198 guard let request = commands.agendaRequest else { return }
199 commands.agendaRequest = nil
200 selection = nil
201 spanKind = nil
202 if viewName != AgendaViewLoader.builtIn[0].name {
203 keepRequestedDays = true
204 viewName = AgendaViewLoader.builtIn[0].name
205 }
206 agenda.mode = .agenda(span: request.days, startOffset: nil)
207 agenda.start = request.start
208 }
209
210 func applyView() {
211 if keepRequestedDays { return keepRequestedDays = false }
212 selection = nil
213 spanKind = nil
214 agenda.start = nil
215 switch viewName {
216 case Self.match, Self.todoMatch:
217 let match = matchText.trimmingCharacters(in: .whitespaces)
218 guard !match.isEmpty else { return }
219 agenda.mode = .match(match, todoOnly: viewName == Self.todoMatch)
220 case Self.search, Self.todoSearch:
221 guard matchText.contains(where: { !$0.isWhitespace }) else { return }
222 agenda.mode = .search(matchText, todoOnly: viewName == Self.todoSearch)
223 default:
224 if let view = views.first(where: { $0.name == viewName }) { agenda.mode = view.mode }
225 }
226 }
227
228 // MARK: - Filters
229
230 /// The tags and categories on the view's lines, which filter words are read against.
231 var shown: (tags: Set<String>, categories: Set<String>) {
232 let items = (isAgenda ? agenda.days.flatMap(\.items) : agenda.list).filter { $0.path != nil }
233 return (Set(items.flatMap(\.tags)), Set(items.map(\.category)))
234 }
235
236 func askFilter(_ kind: Character) {
237 switch kind {
238 case "/": filterText = filter.description
239 default: filterText = ""
240 }
241 let title = switch kind {
242 case "/": "Filter [+cat-tag<0:10-/regexp/]:"
243 case "\\": "Tag filter (+tag-tag):"
244 case "=": "Regexp filter (-re to drop):"
245 default: "Effort filter (<0:30, >1:00, =1:00):"
246 }
247 filterPrompt = (title, kind)
248 }
249
250 func applyFilter() {
251 guard let kind = filterPrompt?.kind else { return }
252 filterPrompt = nil
253 let text = filterText.trimmingCharacters(in: .whitespaces)
254 var current = filter
255 switch kind {
256 case "/":
257 let (parsed, ignored) = AgendaFilter().parse(text, tags: shown.tags, categories: shown.categories)
258 current = parsed
259 if !ignored.isEmpty { message = "\(ignored.joined(separator: " ")) ignored: no line has that tag or category" }
260 case "\\":
261 // Every word as a tag.
262 current.tags = AgendaFilter().parse(text, tags: Set(text.split(whereSeparator: { "+- ".contains($0) }).map(String.init)), categories: []).filter.tags
263 case "=":
264 current.regexps = text.isEmpty ? [] : [text.hasPrefix("-") || text.hasPrefix("+") ? text : "+" + text]
265 default:
266 current.efforts = text.isEmpty ? [] : ["+" + text]
267 }
268 filter = current
269 selection = nil
270 }
271
272 /// `<`: keep only the selected line's category, or drop that filter.
273 func toggleCategoryFilter() {
274 if !filter.categories.isEmpty {
275 filter.categories = []
276 } else if let selection, let item = item(selection) {
277 filter.categories = ["+" + item.category]
278 } else {
279 message = "No entry selected"
280 }
281 }
282
283 /// The entry in the main window; with `focus` false the agenda keeps the keys (SPC).
284 func jump(_ id: String, focus: Bool = true) {
285 guard let item = item(id), let path = item.path, let offset = item.markerOffset ?? item.headingOffset else { return }
286 commands.jump(path: path, offset: offset)
287 if focus { openWindow(id: "main") }
288 }
289}