Sources/Orgstar/AgendaView.swift
1245 lines · 53582 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, for the agenda and Settings.
14@MainActor
15enum CalendarAccess {
16 static let events = CalendarEvents()
17}
18
19/// The agenda window: the day/week agenda, the TODO list, tag matches and saved views.
20/// Return or a double click jumps to the entry in the main window. Keys as in Emacs's agenda:
21/// n/p (or the arrows) move between lines, f/b/. move the span, j picks a date, v d/v w/v m (or
22/// d/w) show a day, week or month, g refreshes, l shows the log (closed and clocked), / filters
23/// (`+cat-tag<0:10-/regexp/`), \ by tag, < by the line's category, = by regexp, _ by effort,
24/// | clears filters, I/O/X clock in, out and cancel, C-c C-w refiles, $ archives, m/u/U mark
25/// and unmark, B acts on the marked entries, t cycles the TODO state, +/- change the priority and
26/// , 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
27/// the date, k captures on the line's day, s saves all files, TAB and SPC show the entry.
28struct AgendaView: View {
29 let workspace: WorkspaceModel
30 let session: DocumentSession
31 let commands: AppCommands
32 let scheduler: ReminderScheduler?
33 let clock: ClockModel
34 @State private var agenda: AgendaModel
35 @State private var views = AgendaViewLoader.builtIn
36 @State private var viewName = AgendaViewLoader.builtIn[0].name
37 @State private var matchText = ""
38 /// The selected line: `day:index` (`day:o` + index in the overdue group), or `list:index`.
39 @State private var selection: String?
40 @State private var tick = 0
41 /// The view picker moved to the agenda for a followed timestamp, which sets its own days.
42 @State private var keepRequestedDays = false
43 @State private var message: String?
44 @State private var prompt: PendingPrompt?
45 @State private var promptText = ""
46 @State private var prefix: String?
47 /// Entries marked for a bulk action.
48 @State private var marked: [EntryRef] = []
49 @State private var logMode = false
50 @State private var filter = AgendaFilter()
51 /// A filter question: its title and which filter it sets.
52 @State private var filterPrompt: (title: String, kind: Character)?
53 @State private var filterText = ""
54 /// A one-line question for an agenda action, and what to do with the answer.
55 struct TextPrompt {
56 let title: String
57 let apply: (String) -> Void
58 }
59 @State private var textPrompt: TextPrompt?
60 @State private var textAnswer = ""
61 /// Day, week or month chosen with `v`; nil shows the span the settings or the view give.
62 @State private var spanKind: AgendaSpan?
63 @State private var showingDatePicker = false
64 @State private var pickedDate = Date()
65 @State private var overdueShown = true
66 @State private var hovered: String?
67 @FocusState private var focused: Bool
68 @AppStorage("agendaSpan") private var span = 10
69 @AppStorage("agendaStartOffset") private var startOffset = -3
70 @AppStorage("agendaSubfolders") private var includeSubfolders = false
71 @AppStorage("agendaShowAllDates") private var showAllDates = false
72 @AppStorage("calendarEvents") private var calendarEventsOn = false
73 @AppStorage("calendarEventCalendars") private var calendarNames = ""
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 @Environment(\.openWindow) private var openWindow
78
79 static let match = "Match…"
80 static let todoMatch = "TODO Match…"
81
82 init(workspace: WorkspaceModel, session: DocumentSession, commands: AppCommands, scheduler: ReminderScheduler?, clock: ClockModel) {
83 self.workspace = workspace
84 self.session = session
85 self.commands = commands
86 self.scheduler = scheduler
87 self.clock = clock
88 _agenda = State(initialValue: AgendaModel(workspace: workspace))
89 }
90
91 /// An agenda entry by its file, heading line and where that line was.
92 struct EntryRef: Hashable {
93 let path: String
94 let line: String
95 let offset: Int
96
97 init?(_ item: AgendaItem) {
98 guard let path = item.path, let line = item.headingLine, let offset = item.headingOffset else { return nil }
99 self.path = path
100 self.line = line
101 self.offset = offset
102 }
103 }
104
105 struct PendingPrompt: Identifiable {
106 let id = UUID()
107 let prompt: Prompt
108 let command: any OrgCommand
109 let atMarker: Bool
110 let answers: [String: String]
111 let itemID: String
112 }
113
114 private struct RefreshKey: Hashable {
115 var mode: AgendaMode
116 var start: Int?
117 var span: Int
118 var startOffset: Int
119 var includeSubfolders: Bool
120 var prefix: [String]
121 var logMode: Bool
122 var calendars: [String]
123 var files: Int
124 var changed: Int?
125 var edits: Int
126 var path: String?
127 var tick: Int
128 }
129
130 private var refreshKey: RefreshKey {
131 RefreshKey(
132 mode: agenda.mode, start: agenda.start, span: span, startOffset: startOffset, includeSubfolders: includeSubfolders, prefix: [prefixAgenda, prefixTodo, prefixTags], logMode: logMode,
133 calendars: calendarEventsOn ? [calendarNames] : [], files: workspace.files.count, changed: workspace.changedFile?.version, edits: session.editVersion,
134 path: session.path, tick: tick
135 )
136 }
137
138 private var isAgenda: Bool {
139 if case .agenda = agenda.mode { return true }
140 return false
141 }
142
143 private var isMatch: Bool { viewName == Self.match || viewName == Self.todoMatch }
144
145 @Environment(\.orgTheme) private var theme
146
147 // MARK: - Lines
148
149 /// A selectable line: its selection id, the row, and the day it is on.
150 struct Line {
151 let id: String
152 let row: AgendaRow
153 let day: Int
154 }
155
156 private var groups: [AgendaDayGroup] {
157 isAgenda ? agenda.groups(showAllDates: showAllDates, keep: filter.keeps) : []
158 }
159
160 private var listRows: [AgendaRow] {
161 isAgenda ? [] : agenda.list.filter(filter.keeps).compactMap { AgendaRow(item: $0, day: agenda.today, today: agenda.today) }
162 }
163
164 /// The lines in order, as up and down move through them.
165 private func lines(_ groups: [AgendaDayGroup]) -> [Line] {
166 guard isAgenda else { return listRows.enumerated().map { Line(id: "list:\($0.offset)", row: $0.element, day: agenda.today) } }
167 return groups.flatMap { group in
168 (overdueShown ? group.overdue.enumerated().map { Line(id: "\(group.day):o\($0.offset)", row: $0.element, day: group.day) } : [])
169 + group.rows.enumerated().map { Line(id: "\(group.day):\($0.offset)", row: $0.element, day: group.day) }
170 }
171 }
172
173 private func line(_ id: String) -> Line? { lines(groups).first { $0.id == id } }
174
175 var body: some View {
176 let groups = self.groups
177 _ = tick
178 return ScrollViewReader { proxy in
179 ScrollView {
180 LazyVStack(alignment: .leading, spacing: 0, pinnedViews: [.sectionHeaders]) {
181 if isAgenda {
182 ForEach(groups) { group in
183 Section {
184 dayRows(group)
185 } header: {
186 dayHeader(group).id("day\(group.day)")
187 }
188 }
189 } else {
190 Section {
191 ForEach(Array(listRows.enumerated()), id: \.offset) { index, row in
192 rowView(Line(id: "list:\(index)", row: row, day: agenda.today), showsGutter: false)
193 }
194 } header: {
195 header { Text(listTitle).font(.system(size: 13, weight: .semibold)) }
196 }
197 }
198 }
199 .padding(.bottom, 12)
200 }
201 .onChange(of: selection) {
202 if let selection { proxy.scrollTo(selection) }
203 }
204 .onChange(of: agenda.days.first?.day) {
205 if groups.contains(where: \.isToday) { proxy.scrollTo("day\(agenda.today)", anchor: .top) }
206 }
207 }
208 .background(theme.color("agenda-background") ?? Color(nsColor: .textBackgroundColor))
209 .focusable()
210 .focusEffectDisabled()
211 .focused($focused)
212 .onAppear { focused = true }
213 .onKeyPress(phases: .down) { press in handle(press) }
214 .safeAreaInset(edge: .bottom, spacing: 0) {
215 if let message = message ?? (filter.isEmpty ? reminderStatus : "Filter: " + filter.description) {
216 Text(message)
217 .font(.callout)
218 .frame(maxWidth: .infinity, alignment: .leading)
219 .padding(.horizontal, 12)
220 .padding(.vertical, 6)
221 .background(.bar)
222 }
223 }
224 .toolbar { toolbar }
225 .overlay {
226 if agenda.files.isEmpty {
227 ContentUnavailableView("No agenda files", systemImage: "calendar", description: Text("The agenda reads the org files at the top of each folder you add."))
228 }
229 }
230 .sheet(item: Binding(get: { prompt?.prompt.fast == nil ? nil : prompt }, set: { if $0 == nil { prompt = nil } })) { pending in
231 if let fast = pending.prompt.fast {
232 FastSelectionView(selection: fast, message: pending.prompt.message) { answer in
233 prompt = nil
234 guard let answer else { return }
235 promptText = answer
236 prompt = pending
237 answerPrompt()
238 }
239 .frame(minWidth: 420)
240 }
241 }
242 .alert(prompt?.prompt.message ?? "", isPresented: Binding(get: { prompt != nil && prompt?.prompt.fast == nil }, set: { if !$0 { prompt = nil } })) {
243 TextField("", text: $promptText)
244 Button("OK") { answerPrompt() }
245 Button("Cancel", role: .cancel) { prompt = nil }
246 } message: {
247 if let choices = prompt?.prompt.choices, !choices.isEmpty {
248 Text(choices.prefix(12).joined(separator: " "))
249 }
250 }
251 .alert(filterPrompt?.title ?? "", isPresented: Binding(get: { filterPrompt != nil }, set: { if !$0 { filterPrompt = nil } })) {
252 TextField("", text: $filterText)
253 Button("Filter") { applyFilter() }
254 Button("Cancel", role: .cancel) { filterPrompt = nil }
255 } message: {
256 if filterPrompt?.kind == "/" || filterPrompt?.kind == "\\" {
257 Text(shown.tags.sorted().prefix(20).joined(separator: " "))
258 }
259 }
260 .alert(textPrompt?.title ?? "", isPresented: Binding(get: { textPrompt != nil }, set: { if !$0 { textPrompt = nil } })) {
261 TextField("", text: $textAnswer)
262 Button("OK") {
263 let pending = textPrompt
264 let answer = textAnswer
265 textPrompt = nil
266 textAnswer = ""
267 // A follow-up question opens after this alert closes.
268 DispatchQueue.main.async { pending?.apply(answer) }
269 }
270 Button("Cancel", role: .cancel) {
271 textPrompt = nil
272 textAnswer = ""
273 }
274 }
275 .navigationTitle(title)
276 .navigationSubtitle(isAgenda && viewName != AgendaViewLoader.builtIn[0].name ? viewName : "")
277 .onChange(of: viewName) { applyView() }
278 .onChange(of: commands.agendaRequest?.start, initial: true) { showRequestedDays() }
279 .onChange(of: commands.agendaRequest?.days) { showRequestedDays() }
280 .task(id: refreshKey) {
281 agenda.span = span
282 agenda.startOffset = startOffset
283 agenda.includeSubfolders = includeSubfolders
284 agenda.options.prefixFormat = ["agenda": prefixAgenda, "todo": prefixTodo, "tags": prefixTags]
285 agenda.options.logMode = logMode
286 agenda.options = OrgPreferences.agendaOptions(agenda.options)
287 agenda.calendarNames = OrgPreferences.calendarEventCalendars()
288 if calendarEventsOn, isAgenda {
289 agenda.calendarEvents = await CalendarAccess.events.requestAccess() ? CalendarAccess.events : nil
290 } else {
291 agenda.calendarEvents = nil
292 }
293 let open = session.openTexts
294 await agenda.refresh(open: open)
295 }
296 .task {
297 loadViews()
298 // The time grid's "now" line and the day itself move on.
299 while !Task.isCancelled {
300 try? await Task.sleep(for: .seconds(60))
301 tick += 1
302 }
303 }
304 }
305
306 // MARK: - Days
307
308 private var todayColor: Color { theme.color("agenda-today") ?? .accentColor }
309
310 @ViewBuilder
311 private func dayRows(_ group: AgendaDayGroup) -> some View {
312 if group.isToday, !group.overdue.isEmpty {
313 overdueHeader(count: group.overdue.count)
314 if overdueShown {
315 ForEach(Array(group.overdue.enumerated()), id: \.element.id) { index, row in
316 rowView(Line(id: "\(group.day):o\(index)", row: row, day: group.day))
317 }
318 Divider().padding(.leading, 16).padding(.vertical, 4)
319 }
320 }
321 if group.isEmpty {
322 Text("Nothing scheduled")
323 .font(.callout)
324 .foregroundStyle(.secondary)
325 .padding(.horizontal, 16)
326 .padding(.vertical, 10)
327 }
328 let now = group.nowIndex(now: Self.hhmm(Date()))
329 ForEach(Array(group.rows.enumerated()), id: \.element.id) { index, row in
330 if index == now { nowLine }
331 rowView(Line(id: "\(group.day):\(index)", row: row, day: group.day))
332 }
333 if let now, now == group.rows.count { nowLine }
334 }
335
336 private func header(@ViewBuilder _ content: () -> some View) -> some View {
337 HStack(spacing: 6) { content() }
338 .padding(.horizontal, 16)
339 .frame(height: 30)
340 .frame(maxWidth: .infinity, alignment: .leading)
341 .background(theme.color("agenda-background") ?? Color(nsColor: .textBackgroundColor))
342 .overlay(alignment: .bottom) { Divider() }
343 }
344
345 private func dayHeader(_ group: AgendaDayGroup) -> some View {
346 let past = group.day < agenda.today
347 let color = group.isToday ? todayColor : past ? Color.secondary : theme.color("agenda-date") ?? .primary
348 return header {
349 if let relative = Self.relativeName(group.day, today: agenda.today) {
350 Text(relative)
351 .font(.system(size: 13, weight: .bold))
352 .foregroundStyle(color)
353 Text("·").foregroundStyle(.tertiary)
354 }
355 Text(Self.format(group.day, Days.date(group.day).year == Days.date(agenda.today).year ? "EEEE d MMMM" : "EEEE d MMMM yyyy"))
356 .font(.system(size: 13, weight: group.isToday ? .bold : .semibold))
357 .foregroundStyle(color)
358 Spacer()
359 Button {
360 capture(on: group.day)
361 } label: {
362 Image(systemName: "plus")
363 .font(.system(size: 12, weight: .semibold))
364 .frame(width: 22, height: 22)
365 .contentShape(Rectangle())
366 }
367 .buttonStyle(.borderless)
368 .foregroundStyle(group.isToday ? todayColor : .secondary)
369 .help("Capture an entry scheduled on this day (k)")
370 }
371 }
372
373 private func overdueHeader(count: Int) -> some View {
374 let color = theme.dynamic(.systemRed) { [theme] in theme.statusColor(.overdue, dark: $0) }
375 return Button {
376 withAnimation(.snappy(duration: 0.2)) { overdueShown.toggle() }
377 if !overdueShown, selection?.contains(":o") == true { selection = nil }
378 } label: {
379 HStack(spacing: 6) {
380 Image(systemName: "chevron.right")
381 .font(.system(size: 10, weight: .bold))
382 .rotationEffect(.degrees(overdueShown ? 90 : 0))
383 Text("Overdue").font(.system(size: 12, weight: .semibold))
384 Text("\(count)")
385 .font(.system(size: 10, weight: .bold).monospacedDigit())
386 .padding(.horizontal, 6)
387 .padding(.vertical, 1)
388 .background(Capsule().fill(color.opacity(0.15)))
389 Spacer()
390 }
391 .foregroundStyle(color)
392 .padding(.horizontal, 16)
393 .padding(.top, 8)
394 .padding(.bottom, 4)
395 .contentShape(Rectangle())
396 }
397 .buttonStyle(.plain)
398 .help(overdueShown ? "Hide entries from earlier days" : "Show entries from earlier days")
399 }
400
401 private var nowLine: some View {
402 HStack(spacing: 6) {
403 Text(Date().formatted(.dateTime.hour(.twoDigits(amPM: .omitted)).minute()))
404 .font(.system(size: 10, weight: .semibold).monospacedDigit())
405 .frame(width: AgendaRowView.gutterWidth, alignment: .leading)
406 Circle().frame(width: 6, height: 6)
407 Rectangle().frame(height: 1)
408 }
409 .foregroundStyle(todayColor)
410 .padding(.horizontal, 16)
411 .frame(height: 10)
412 .accessibilityLabel("Now")
413 }
414
415 private func rowView(_ line: Line, showsGutter: Bool = true) -> some View {
416 AgendaRowView(
417 row: line.row, day: line.day, showsGutter: showsGutter, selected: selection == line.id, hovered: hovered == line.id,
418 marked: line.row.item.flatMap(EntryRef.init).map(marked.contains) ?? false
419 )
420 .id(line.id)
421 .contentShape(Rectangle())
422 .onHover { inside in
423 if inside { hovered = line.id } else if hovered == line.id { hovered = nil }
424 }
425 .onTapGesture(count: 2) { open(line) }
426 .simultaneousGesture(TapGesture().onEnded {
427 selection = line.id
428 focused = true
429 })
430 .contextMenu { menu(line) }
431 }
432
433 @ViewBuilder
434 private func menu(_ line: Line) -> some View {
435 if let event = line.row.event {
436 Button("Show in Calendar") { openEvent(event) }
437 } else if line.row.item != nil {
438 Button("Open") { selection = line.id; jump(line.id) }
439 Divider()
440 Button("Cycle TODO State") { selection = line.id; run(TodoCycle()) }
441 Button("Set Priority…") { selection = line.id; run(SetPriority()) }
442 Button("Set Tags…") { selection = line.id; run(SetTags()) }
443 Button("Schedule…") { selection = line.id; run(SetPlanning(deadline: false)) }
444 Button("Set Deadline…") { selection = line.id; run(SetPlanning(deadline: true)) }
445 Divider()
446 Button("Clock In") { selection = line.id; clockIn() }
447 Button(EntryRef(line.row.item!).map(marked.contains) == true ? "Unmark" : "Mark") {
448 selection = line.id
449 mark(!(EntryRef(line.row.item!).map(marked.contains) ?? false))
450 }
451 Button("Archive") { selection = line.id; archive() }
452 }
453 }
454
455 // MARK: - Toolbar
456
457 @ToolbarContentBuilder
458 private var toolbar: some ToolbarContent {
459 ToolbarItemGroup(placement: .navigation) {
460 Menu {
461 ForEach(views) { view in Button(view.name) { viewName = view.name } }
462 Divider()
463 Button(Self.match) { viewName = Self.match }
464 Button(Self.todoMatch) { viewName = Self.todoMatch }
465 } label: {
466 Label(viewName, systemImage: "calendar").labelStyle(.titleAndIcon)
467 }
468 .help("What the agenda shows")
469 if isMatch {
470 TextField("+work-boss|LEVEL>2/!TODO", text: $matchText)
471 .frame(minWidth: 220)
472 .onSubmit { applyView() }
473 }
474 }
475 ToolbarItemGroup {
476 if agenda.isComputing { ProgressView().controlSize(.small) }
477 if isAgenda {
478 Picker("Span", selection: Binding(get: { spanKind }, set: { if let kind = $0 { setSpan(kind) } })) {
479 Text("Day").tag(AgendaSpan?.some(.day))
480 Text("Week").tag(AgendaSpan?.some(.week))
481 Text("Month").tag(AgendaSpan?.some(.month))
482 }
483 .pickerStyle(.segmented)
484 .labelsHidden()
485 .help("Show a day, week or month (v d, v w, v m)")
486 ControlGroup {
487 Button("Earlier", systemImage: "chevron.left") { move(forward: false) }
488 .help("Previous days (b)")
489 Button("Today") { goToday() }
490 .help("Back to today (.)")
491 Button("Later", systemImage: "chevron.right") { move(forward: true) }
492 .help("Next days (f)")
493 }
494 Button("Go to Date", systemImage: "calendar") {
495 pickedDate = Self.date(anchorDay)
496 showingDatePicker = true
497 }
498 .help("Go to a date (j)")
499 .popover(isPresented: $showingDatePicker, arrowEdge: .bottom) {
500 DatePicker("Date", selection: $pickedDate, displayedComponents: .date)
501 .datePickerStyle(.graphical)
502 .labelsHidden()
503 .padding()
504 .onChange(of: pickedDate) {
505 showingDatePicker = false
506 goTo(Days.absolute(pickedDate, calendar: .current))
507 }
508 }
509 }
510 Menu {
511 Button("Filter…") { askFilter("/") }
512 Button("By Tag…") { askFilter("\\") }
513 Button("By Category of Selected Line") { toggleCategoryFilter() }
514 Button("By Regexp…") { askFilter("=") }
515 Button("By Effort…") { askFilter("_") }
516 Divider()
517 Button("Remove Filters") { filter = AgendaFilter() }
518 .disabled(filter.isEmpty)
519 } label: {
520 Label("Filter", systemImage: filter.isEmpty ? "line.3.horizontal.decrease.circle" : "line.3.horizontal.decrease.circle.fill")
521 } primaryAction: {
522 askFilter("/")
523 }
524 .help("Filter the entries (/, \\, <, =, _; | removes)")
525 }
526 }
527
528 /// The span shown, as the window's title: `Week of 5 Oct 2026`.
529 private var title: String {
530 guard isAgenda else { return viewName.replacingOccurrences(of: "…", with: "") }
531 guard let first = agenda.days.first?.day, let last = agenda.days.last?.day else { return "Agenda" }
532 switch spanKind {
533 case .day: return Self.format(first, "EEEE d MMMM yyyy")
534 case .week: return "Week of " + Self.format(first, "d MMM yyyy")
535 case .month: return Self.format(first, "MMMM yyyy")
536 case nil:
537 if first == last { return Self.format(first, "EEEE d MMMM yyyy") }
538 let sameYear = Days.date(first).year == Days.date(last).year
539 return Self.format(first, sameYear ? "d MMM" : "d MMM yyyy") + " – " + Self.format(last, "d MMM yyyy")
540 }
541 }
542
543 // MARK: - Span
544
545 /// The day `v`, `j` and `k` start from: the selected line's, else today when shown, else the first.
546 private var anchorDay: Int {
547 if let selection, let day = Int(selection.prefix { $0 != ":" }) { return day }
548 let days = agenda.days.map(\.day)
549 if days.contains(agenda.today) || days.isEmpty { return agenda.today }
550 return days[0]
551 }
552
553 /// `org-agenda-day-view`, `-week-view`, `-month-view`: the day, the week from Monday
554 /// (`org-agenda-start-on-weekday`), or the month around `anchor`.
555 private func setSpan(_ kind: AgendaSpan, around anchor: Int? = nil) {
556 let anchor = anchor ?? anchorDay
557 spanKind = kind
558 selection = nil
559 switch kind {
560 case .day:
561 agenda.mode = .agenda(span: 1, startOffset: nil)
562 agenda.start = anchor
563 case .week:
564 agenda.mode = .agenda(span: 7, startOffset: nil)
565 agenda.start = anchor - (Days.weekday(anchor) + 6) % 7
566 case .month:
567 let d = Days.date(anchor)
568 let first = Days.absolute(year: d.year, month: d.month, day: 1)
569 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)
570 agenda.mode = .agenda(span: next - first, startOffset: nil)
571 agenda.start = first
572 }
573 }
574
575 private func move(forward: Bool) {
576 selection = nil
577 if spanKind == .month, let first = agenda.days.first?.day {
578 setSpan(.month, around: forward ? first + 31 : first - 1)
579 } else {
580 agenda.shift(forward: forward)
581 }
582 }
583
584 private func goToday() {
585 if let spanKind { setSpan(spanKind, around: agenda.today) } else { agenda.showToday() }
586 selection = nil
587 }
588
589 /// `org-agenda-goto-date`.
590 private func goTo(_ day: Int) {
591 if let spanKind { setSpan(spanKind, around: day) } else { agenda.start = day }
592 selection = nil
593 }
594
595 /// Capture on `day`, as `org-agenda-capture`.
596 private func capture(on day: Int) {
597 commands.capture(on: day)
598 NSApp.activate()
599 openWindow(id: "capture")
600 }
601
602 static func date(_ day: Int) -> Date {
603 let d = Days.date(day)
604 return Calendar.current.date(from: DateComponents(year: d.year, month: d.month, day: d.day)) ?? Date()
605 }
606
607 static func format(_ day: Int, _ pattern: String) -> String {
608 let formatter = DateFormatter()
609 formatter.dateFormat = pattern
610 return formatter.string(from: date(day))
611 }
612
613 static func relativeName(_ day: Int, today: Int) -> String? {
614 switch day - today {
615 case 0: "Today"
616 case 1: "Tomorrow"
617 case -1: "Yesterday"
618 default: nil
619 }
620 }
621
622 static func hhmm(_ date: Date) -> Int {
623 let c = Calendar.current.dateComponents([.hour, .minute], from: date)
624 return (c.hour ?? 0) * 100 + (c.minute ?? 0)
625 }
626
627 @AppStorage("reminders") private var remindersEnabled = true
628
629 /// How far ahead notifications are set, as the design asks the agenda to show.
630 private var reminderStatus: String? {
631 guard let scheduler, remindersEnabled else { return nil }
632 if !scheduler.isAuthorized { return "Notifications are off for Orgstar in System Settings." }
633 guard let through = scheduler.scheduledThrough else { return nil }
634 return "Reminders are set through " + through.formatted(.dateTime.weekday(.abbreviated).day().month(.abbreviated).hour().minute()) + "."
635 }
636
637 private var listTitle: String {
638 switch agenda.mode {
639 case .todo(let keywords): "TODO items: \(keywords ?? "all")"
640 case .match(let match, let todoOnly): (todoOnly ? "TODO entries" : "Entries") + " matching \(match)"
641 case .agenda: ""
642 }
643 }
644
645 private func loadViews() {
646 let loaded = AgendaViewLoader.load()
647 views = loaded.views
648 message = loaded.problems.first
649 }
650
651 /// The days of a followed timestamp, in the agenda view.
652 private func showRequestedDays() {
653 guard let request = commands.agendaRequest else { return }
654 commands.agendaRequest = nil
655 selection = nil
656 spanKind = nil
657 if viewName != AgendaViewLoader.builtIn[0].name {
658 keepRequestedDays = true
659 viewName = AgendaViewLoader.builtIn[0].name
660 }
661 agenda.mode = .agenda(span: request.days, startOffset: nil)
662 agenda.start = request.start
663 }
664
665 private func applyView() {
666 if keepRequestedDays { return keepRequestedDays = false }
667 selection = nil
668 spanKind = nil
669 agenda.start = nil
670 switch viewName {
671 case Self.match, Self.todoMatch:
672 let match = matchText.trimmingCharacters(in: .whitespaces)
673 guard !match.isEmpty else { return }
674 agenda.mode = .match(match, todoOnly: viewName == Self.todoMatch)
675 default:
676 if let view = views.first(where: { $0.name == viewName }) { agenda.mode = view.mode }
677 }
678 }
679
680 // MARK: - Items
681
682 private func item(_ id: String) -> AgendaItem? { line(id)?.row.item }
683
684 /// Return and double click: the entry in the main window, or the event in Calendar.
685 private func open(_ line: Line) {
686 selection = line.id
687 if let event = line.row.event { openEvent(event) } else { jump(line.id) }
688 }
689
690 /// Calendar shows an event from its identifier (`AgendaEvent.id` adds `@` and the start).
691 private func openEvent(_ event: AgendaEvent) {
692 let identifier = event.id.split(separator: "@").dropLast().joined(separator: "@")
693 guard !identifier.isEmpty, let encoded = identifier.addingPercentEncoding(withAllowedCharacters: .urlPathAllowed),
694 let url = URL(string: "ical://ekevent/\(encoded)?method=show&options=more") else { return }
695 NSWorkspace.shared.open(url)
696 }
697
698 /// Moves the selection by `step` lines.
699 private func step(_ step: Int) {
700 let all = lines(groups)
701 guard !all.isEmpty else { return }
702 let index = selection.flatMap { id in all.firstIndex { $0.id == id } }
703 let next = index.map { min(max($0 + step, 0), all.count - 1) } ?? (step > 0 ? 0 : all.count - 1)
704 selection = all[next].id
705 }
706
707 // MARK: - Filters
708
709 /// The tags and categories on the view's lines, which filter words are read against.
710 private var shown: (tags: Set<String>, categories: Set<String>) {
711 let items = (isAgenda ? agenda.days.flatMap(\.items) : agenda.list).filter { $0.path != nil }
712 return (Set(items.flatMap(\.tags)), Set(items.map(\.category)))
713 }
714
715 private func askFilter(_ kind: Character) {
716 switch kind {
717 case "/": filterText = filter.description
718 default: filterText = ""
719 }
720 let title = switch kind {
721 case "/": "Filter [+cat-tag<0:10-/regexp/]:"
722 case "\\": "Tag filter (+tag-tag):"
723 case "=": "Regexp filter (-re to drop):"
724 default: "Effort filter (<0:30, >1:00, =1:00):"
725 }
726 filterPrompt = (title, kind)
727 }
728
729 private func applyFilter() {
730 guard let kind = filterPrompt?.kind else { return }
731 filterPrompt = nil
732 let text = filterText.trimmingCharacters(in: .whitespaces)
733 var current = filter
734 switch kind {
735 case "/":
736 let (parsed, ignored) = AgendaFilter().parse(text, tags: shown.tags, categories: shown.categories)
737 current = parsed
738 if !ignored.isEmpty { message = "\(ignored.joined(separator: " ")) ignored: no line has that tag or category" }
739 case "\\":
740 // Every word as a tag.
741 current.tags = AgendaFilter().parse(text, tags: Set(text.split(whereSeparator: { "+- ".contains($0) }).map(String.init)), categories: []).filter.tags
742 case "=":
743 current.regexps = text.isEmpty ? [] : [text.hasPrefix("-") || text.hasPrefix("+") ? text : "+" + text]
744 default:
745 current.efforts = text.isEmpty ? [] : ["+" + text]
746 }
747 filter = current
748 selection = nil
749 }
750
751 /// `<`: keep only the selected line's category, or drop that filter.
752 private func toggleCategoryFilter() {
753 if !filter.categories.isEmpty {
754 filter.categories = []
755 } else if let selection, let item = item(selection) {
756 filter.categories = ["+" + item.category]
757 } else {
758 message = "No entry selected"
759 }
760 }
761
762 /// The entry in the main window; with `focus` false the agenda keeps the keys (SPC).
763 private func jump(_ id: String, focus: Bool = true) {
764 guard let item = item(id), let path = item.path, let offset = item.markerOffset ?? item.headingOffset else { return }
765 commands.jump(path: path, offset: offset)
766 if focus { openWindow(id: "main") }
767 }
768
769 // MARK: - Commands
770
771 private func handle(_ press: KeyPress) -> KeyPress.Result {
772 let control = press.modifiers.contains(.control)
773 // `C-x` and friends arrive as control characters or as letters with control.
774 func isControl(_ letter: String, _ code: String) -> Bool { control && (press.characters == letter || press.characters == code) }
775 if let pending = prefix {
776 prefix = nil
777 if pending == "v" {
778 switch press.characters {
779 case "d" where isAgenda: setSpan(.day)
780 case "w" where isAgenda: setSpan(.week)
781 case "m" where isAgenda: setSpan(.month)
782 default: message = "v \(press.characters) is undefined"
783 }
784 if message == "v-" { message = nil }
785 return .handled
786 }
787 if pending == "C-c C-x" {
788 if isControl("s", "\u{13}") { archive() } else { message = "C-c C-x \(press.characters) is undefined" }
789 return .handled
790 }
791 if isControl("s", "\u{13}") {
792 run(SetPlanning(deadline: false))
793 } else if isControl("d", "\u{04}") {
794 run(SetPlanning(deadline: true))
795 } else if isControl("q", "\u{11}") {
796 run(SetTags())
797 } else if isControl("t", "\u{14}") {
798 run(TodoCycle())
799 } else if isControl("w", "\u{17}") {
800 refile(marked: false)
801 } else if isControl("x", "\u{18}") {
802 prefix = "C-c C-x"
803 message = "C-c C-x-"
804 } else if press.characters == "$" {
805 archive()
806 } else {
807 message = "C-c \(press.characters) is undefined"
808 }
809 return .handled
810 }
811 if isControl("c", "\u{03}") {
812 prefix = "C-c"
813 message = "C-c-"
814 return .handled
815 }
816 if isControl("n", "\u{0e}") || (press.key == .downArrow && press.modifiers.isEmpty) {
817 step(1)
818 return .handled
819 }
820 if isControl("p", "\u{10}") || (press.key == .upArrow && press.modifiers.isEmpty) {
821 step(-1)
822 return .handled
823 }
824 if press.key == .return || press.key == .tab, let selection, let line = line(selection) {
825 open(line)
826 return .handled
827 }
828 if press.key == .space, let selection {
829 jump(selection, focus: false)
830 return .handled
831 }
832 if press.modifiers == .shift, press.key == .rightArrow || press.key == .leftArrow {
833 run(ShiftTimestampDay(later: press.key == .rightArrow), atMarker: true)
834 return .handled
835 }
836 guard press.modifiers.subtracting(.shift).isEmpty else { return .ignored }
837 switch press.characters {
838 case "n": step(1)
839 case "p": step(-1)
840 case "f" where isAgenda: move(forward: true)
841 case "b" where isAgenda: move(forward: false)
842 case "." where isAgenda: goToday()
843 case "j" where isAgenda:
844 pickedDate = Self.date(anchorDay)
845 showingDatePicker = true
846 case "v" where isAgenda:
847 prefix = "v"
848 message = "v-"
849 case "d" where isAgenda: setSpan(.day)
850 case "w" where isAgenda: setSpan(.week)
851 case "k" where isAgenda: capture(on: anchorDay)
852 case "s":
853 commands.run("app.save-all")
854 message = "Saved"
855 case "/", "\\", "=", "_": askFilter(press.characters.first!)
856 case "<": toggleCategoryFilter()
857 case "|":
858 filter = AgendaFilter()
859 message = "Filters removed"
860 case "l" where isAgenda:
861 logMode.toggle()
862 message = logMode ? "Log mode on" : "Log mode off"
863 case "g", "r":
864 loadViews()
865 tick += 1
866 case "I": clockIn()
867 case "O": message = clock.clockOut(session)
868 case "X": message = clock.clockOut(session, cancel: true)
869 case "$": archive()
870 case "m": mark(true)
871 case "u": mark(false)
872 case "U":
873 marked = []
874 message = "No entries marked"
875 case "B": askBulk()
876 case "t": run(TodoCycle())
877 case "+": run(PriorityUp())
878 case "-": run(PriorityDown())
879 case ",": run(SetPriority())
880 case ":": run(SetTags())
881 default: return .ignored
882 }
883 return .handled
884 }
885
886 // MARK: - Clock, refile, archive, bulk
887
888 private var selectedEntry: EntryRef? { selection.flatMap(item).flatMap(EntryRef.init) }
889
890 private func clockIn() {
891 guard let entry = selectedEntry, let offset = session.locateHeading(path: entry.path, line: entry.line, near: entry.offset) else {
892 message = "No entry selected"
893 return
894 }
895 let paths = workspace.files.filter { $0.kind == .org }.map(\.path)
896 Task {
897 let outcome = await clock.clockIn(session, target: .entry(path: entry.path, offset: offset), paths: paths, ask: commands.askClock)
898 if let jump = outcome.jump { commands.jump(path: jump.path, offset: jump.offset) }
899 message = outcome.messages.last { !$0.isEmpty }
900 tick += 1
901 }
902 }
903
904 private func archive() {
905 guard let entry = selectedEntry, let offset = session.locateHeading(path: entry.path, line: entry.line, near: entry.offset) else {
906 message = "No entry selected"
907 return
908 }
909 message = session.archive(from: (entry.path, offset))
910 tick += 1
911 }
912
913 /// Refiles the selected entry, or with `marked` the marked ones, to a target asked for in
914 /// the main window, where the list of targets is searchable.
915 private func refile(marked bulk: Bool) {
916 let entries = bulk ? marked : selectedEntry.map { [$0] } ?? []
917 guard !entries.isEmpty else {
918 message = "No entry selected"
919 return
920 }
921 let targets = workspace.refileTargets(openPath: session.path, document: session.document)
922 commands.ask(Prompt(key: "refile", message: "Refile to:", choices: targets.map(\.label))) { answer in
923 guard let answer, targets.contains(where: { $0.label == answer }) else { return }
924 message = eachEntry(entries) { entry, offset in
925 // Targets in the entry's own file from its text now, as earlier moves shift them.
926 let document = session.openDocuments.first { $0.path == entry.path }?.document
927 ?? FileManager.default.contents(atPath: entry.path).map { DocumentState(bytes: [UInt8]($0)) }
928 guard let target = workspace.refileTargets(openPath: entry.path, document: document).first(where: { $0.label == answer }) else {
929 return "Can't find \(answer) any more."
930 }
931 return session.refile(to: target, from: (entry.path, offset))
932 }
933 if bulk { marked = [] }
934 tick += 1
935 }
936 openWindow(id: "main")
937 }
938
939 /// Runs `action` on each entry, finding it again first: later entries in a file first, so
940 /// earlier ones keep their place. Returns the last message.
941 private func eachEntry(_ entries: [EntryRef], _ action: (EntryRef, Int) -> String?) -> String? {
942 var last: String?
943 var failed = 0
944 for entry in entries.sorted(by: { ($0.path, $1.offset) < ($1.path, $0.offset) }) {
945 guard let offset = session.locateHeading(path: entry.path, line: entry.line, near: entry.offset) else {
946 failed += 1
947 continue
948 }
949 last = action(entry, offset)
950 }
951 return failed > 0 ? "\(failed) marked \(failed == 1 ? "entry" : "entries") changed and \(failed == 1 ? "was" : "were") skipped" : last
952 }
953
954 private func mark(_ on: Bool) {
955 guard let entry = selectedEntry else {
956 message = "No entry selected"
957 return
958 }
959 if on {
960 if !marked.contains(entry) { marked.append(entry) }
961 } else {
962 marked.removeAll { $0 == entry }
963 }
964 message = "\(marked.count) marked"
965 }
966
967 /// `B`: an action for every marked entry.
968 private func askBulk() {
969 guard !marked.isEmpty else {
970 message = "No entries are marked"
971 return
972 }
973 textPrompt = TextPrompt(title: "Bulk action on \(marked.count): [$] archive [r] refile [t] TODO state [+] tag [-] untag [s] schedule [d] deadline") { answer in
974 switch answer.trimmingCharacters(in: .whitespaces) {
975 case "$": bulk { session.archive(from: ($0.path, $1)) }
976 case "r": refile(marked: true)
977 case "t":
978 textPrompt = TextPrompt(title: "TODO state (empty for none):") { keyword in
979 let word = keyword.trimmingCharacters(in: .whitespaces)
980 bulk { performAt($0, $1, SetTodo(keyword: word.isEmpty ? nil : word)) }
981 }
982 case "+", "-":
983 let on = answer.trimmingCharacters(in: .whitespaces) == "+"
984 textPrompt = TextPrompt(title: on ? "Tag to add:" : "Tag to remove:") { tag in
985 let tag = tag.trimmingCharacters(in: .whitespaces)
986 guard !tag.isEmpty else { return }
987 bulk { performAt($0, $1, ToggleTag(tag: tag, on: on)) }
988 }
989 case "s", "d":
990 let deadline = answer.trimmingCharacters(in: .whitespaces) == "d"
991 textPrompt = TextPrompt(title: deadline ? "Deadline (+2d, fri, 2026-10-12):" : "Schedule (+2d, fri, 2026-10-12):") { date in
992 bulk { performAt($0, $1, SetPlanning(deadline: deadline), answers: ["date": date]) }
993 }
994 default:
995 message = "No bulk action \(answer)"
996 }
997 }
998 }
999
1000 private func bulk(_ action: (EntryRef, Int) -> String?) {
1001 message = eachEntry(marked, action) ?? "Done with \(marked.count) entries"
1002 marked = []
1003 tick += 1
1004 }
1005
1006 /// Runs `command` at the heading at `offset`, as `run` does for the selection.
1007 private func performAt(_ entry: EntryRef, _ offset: Int, _ command: any OrgCommand, answers: [String: String] = [:]) -> String? {
1008 switch session.perform(command, path: entry.path, at: offset, expect: (offset, entry.line), answers: answers) {
1009 case .failed(let text): text
1010 case .prompt: "\(command.title) needs an answer; run it on the entry itself"
1011 default: nil
1012 }
1013 }
1014
1015 /// Runs `command` on the selected entry, at its heading or, with `atMarker`, at the
1016 /// timestamp the entry is listed for.
1017 private func run(_ command: any OrgCommand, atMarker: Bool = false, answers: [String: String] = [:], itemID: String? = nil) {
1018 guard let id = itemID ?? selection, let item = item(id), let path = item.path, let start = item.headingOffset else {
1019 message = "No entry selected"
1020 return
1021 }
1022 if atMarker, ![.deadline, .upcomingDeadline, .scheduled, .pastScheduled, .timestamp].contains(item.kind) {
1023 message = "Only dated entries can move"
1024 return
1025 }
1026 let offset = atMarker ? (item.markerOffset ?? start) : start
1027 let step = session.perform(command, path: path, at: offset, expect: item.headingLine.map { (start, $0) }, answers: answers)
1028 switch step {
1029 case .prompt(let request):
1030 promptText = request.initial
1031 prompt = PendingPrompt(prompt: request, command: command, atMarker: atMarker, answers: answers, itemID: id)
1032 case .failed(let text):
1033 message = text
1034 tick += 1
1035 case .external:
1036 message = "Not available from the agenda"
1037 case .commit:
1038 message = nil
1039 tick += 1
1040 }
1041 }
1042
1043 private func answerPrompt() {
1044 guard let pending = prompt else { return }
1045 prompt = nil
1046 var answers = pending.answers
1047 answers[pending.prompt.key] = promptText
1048 run(pending.command, atMarker: pending.atMarker, answers: answers, itemID: pending.itemID)
1049 }
1050}
1051
1052/// One agenda line: the time or status over an icon, the category above the title, progress
1053/// and tags after it, and the TODO keyword and priority at the end.
1054struct AgendaRowView: View {
1055 let row: AgendaRow
1056 /// The agenda day the row is on, for habit graphs.
1057 var day: Int
1058 var showsGutter = true
1059 var selected = false
1060 var hovered = false
1061 /// Marked for a bulk action.
1062 var marked = false
1063 @Environment(\.orgTheme) private var theme
1064
1065 static let gutterWidth: CGFloat = 92
1066
1067 var body: some View {
1068 HStack(alignment: .center, spacing: 12) {
1069 if showsGutter { gutter }
1070 VStack(alignment: .leading, spacing: 2) {
1071 if !row.category.isEmpty { categoryLine }
1072 titleLine
1073 }
1074 .layoutPriority(1)
1075 Spacer(minLength: 8)
1076 if let habit = row.item?.habit {
1077 HabitGraph(cells: habit.graph(today: day), theme: theme)
1078 }
1079 if let todo = row.todo {
1080 let color = theme.dynamic(row.isDone ? .systemGreen : .systemRed) { [theme, row] in theme.todoColor(todo, isDone: row.isDone, dark: $0) }
1081 Text(todo)
1082 .font(.system(size: 10, weight: .bold))
1083 .foregroundStyle(color)
1084 .padding(.horizontal, 7)
1085 .padding(.vertical, 2)
1086 .background(Capsule().fill(color.opacity(0.14)))
1087 .fixedSize()
1088 }
1089 priorityBadge
1090 .frame(width: 18)
1091 }
1092 .padding(.horizontal, 16)
1093 .padding(.vertical, 6)
1094 .frame(minHeight: 44)
1095 .background {
1096 RoundedRectangle(cornerRadius: 6)
1097 .fill(selected ? theme.color("selection") ?? Color.accentColor.opacity(0.2) : hovered ? Color.primary.opacity(0.05) : .clear)
1098 .padding(.horizontal, 6)
1099 }
1100 .overlay(alignment: .leading) {
1101 if marked {
1102 Capsule().fill(theme.color("agenda-today") ?? .accentColor).frame(width: 3).padding(.vertical, 8).padding(.leading, 8)
1103 }
1104 }
1105 .accessibilityElement(children: .combine)
1106 }
1107
1108 private var statusColor: Color {
1109 theme.dynamic(.secondaryLabelColor) { [theme, row] in theme.statusColor(row.status, dark: $0) }
1110 }
1111
1112 private var gutter: some View {
1113 VStack(alignment: .leading, spacing: 3) {
1114 Text(row.gutter)
1115 .font(.system(size: 12, weight: row.status == .overdue || row.status == .dueSoon ? .semibold : .regular).monospacedDigit())
1116 .foregroundStyle(statusColor)
1117 .lineLimit(1)
1118 .minimumScaleFactor(0.8)
1119 if let symbol {
1120 Image(systemName: symbol)
1121 .font(.system(size: row.icon == .event ? 8 : 10, weight: .semibold))
1122 .foregroundStyle(iconColor)
1123 .frame(height: 12)
1124 }
1125 }
1126 .frame(width: Self.gutterWidth, alignment: .leading)
1127 }
1128
1129 /// Overdue entries show a warning, done ones a check, as the status says first.
1130 private var symbol: String? {
1131 guard let icon = row.icon else { return nil }
1132 if row.status == .overdue { return "exclamationmark.circle.fill" }
1133 if row.status == .done { return "checkmark.circle.fill" }
1134 switch icon {
1135 case .scheduled: return "calendar"
1136 case .deadline: return "flag.fill"
1137 case .habit: return "repeat"
1138 case .event: return "circle.fill"
1139 case .timestamp: return row.start == nil ? "calendar" : "clock"
1140 }
1141 }
1142
1143 private var iconColor: Color {
1144 if let event = row.event { return theme.dynamic(.systemPurple) { [theme] in theme.eventColor(event, dark: $0) } }
1145 return row.status == .normal ? Color.secondary.opacity(0.8) : statusColor
1146 }
1147
1148 private var categoryLine: some View {
1149 HStack(spacing: 5) {
1150 Circle()
1151 .fill(row.event.map { event in theme.dynamic(.systemPurple) { [theme] in theme.eventColor(event, dark: $0) } }
1152 ?? theme.dynamic { [theme, row] in theme.categoryColor(row.category, dark: $0) })
1153 .frame(width: 6, height: 6)
1154 Text(row.category + (row.event?.location.map { " · " + $0 } ?? ""))
1155 .font(.system(size: 11))
1156 .foregroundStyle(theme.color("agenda-category") ?? .secondary)
1157 .lineLimit(1)
1158 }
1159 }
1160
1161 private var titleLine: some View {
1162 HStack(spacing: 6) {
1163 Text(row.title.isEmpty ? " " : row.title)
1164 .font(.system(size: 13))
1165 .strikethrough(row.isDone)
1166 .foregroundStyle(row.isDone ? AnyShapeStyle(.secondary) : AnyShapeStyle(theme.color("foreground") ?? .primary))
1167 .lineLimit(1)
1168 .truncationMode(.tail)
1169 if let progress = row.progress {
1170 Text(progress)
1171 .font(.system(size: 10, weight: .semibold).monospacedDigit())
1172 .foregroundStyle(.secondary)
1173 .padding(.horizontal, 6)
1174 .padding(.vertical, 1)
1175 .background(Capsule().fill(Color.secondary.opacity(0.14)))
1176 .fixedSize()
1177 }
1178 ForEach(row.tags, id: \.self) { tag in
1179 Text(tag)
1180 .font(.system(size: 10, weight: .medium))
1181 .foregroundStyle(theme.color("tags") ?? .secondary)
1182 .padding(.horizontal, 6)
1183 .padding(.vertical, 1)
1184 .background(Capsule().strokeBorder((theme.color("tags") ?? .secondary).opacity(0.35), lineWidth: 0.5))
1185 .fixedSize()
1186 }
1187 }
1188 }
1189
1190 @ViewBuilder
1191 private var priorityBadge: some View {
1192 if let priority = row.priority {
1193 let color = theme.dynamic(.systemOrange) { [theme] in theme.priorityColor(priority, dark: $0) }
1194 Text(priority)
1195 .font(.system(size: 10, weight: .bold))
1196 .foregroundStyle(color)
1197 .frame(width: 18, height: 18)
1198 .background(Circle().fill(color.opacity(0.14)))
1199 .overlay(Circle().strokeBorder(color.opacity(0.6), lineWidth: 1))
1200 .help("Priority \(priority)")
1201 } else {
1202 Color.clear.frame(width: 18, height: 18)
1203 }
1204 }
1205}
1206
1207/// org-habit's consistency graph: a cell per day, `*` where the habit was done, `!` today.
1208struct HabitGraph: View {
1209 let cells: [Habit.Cell]
1210 var theme: ThemeSpec = .default
1211
1212 var body: some View {
1213 HStack(spacing: 1) {
1214 ForEach(cells, id: \.day) { cell in
1215 Text(String(cell.glyph))
1216 .font(.system(size: 9, weight: .bold, design: .monospaced))
1217 .frame(width: 8, height: 14)
1218 .background(color(cell.face))
1219 .help(Self.label(cell))
1220 }
1221 }
1222 .accessibilityElement(children: .ignore)
1223 .accessibilityLabel("Done \(cells.filter { $0.glyph == "*" }.count) of the last \(Habit.precedingDays) days")
1224 }
1225
1226 /// Due-state colors, lighter for days to come, as org-habit's faces.
1227 func color(_ face: Habit.Face) -> Color {
1228 func themed(_ key: String, _ fallback: Color) -> Color { theme.color(key) ?? fallback }
1229 switch face {
1230 case .clear: return themed("habit-clear", .blue).opacity(0.7)
1231 case .clearFuture: return themed("habit-clear", .blue).opacity(0.35)
1232 case .ready: return themed("habit-ready", .green).opacity(0.75)
1233 case .readyFuture: return themed("habit-ready", .green).opacity(0.35)
1234 case .alert: return themed("habit-alert", .yellow).opacity(0.85)
1235 case .alertFuture: return themed("habit-alert", .yellow).opacity(0.4)
1236 case .overdue: return themed("habit-overdue", .red).opacity(0.75)
1237 case .overdueFuture: return themed("habit-overdue", .red).opacity(0.35)
1238 }
1239 }
1240
1241 static func label(_ cell: Habit.Cell) -> String {
1242 let date = Days.date(cell.day)
1243 return String(format: "%04d-%02d-%02d", date.year, date.month, date.day) + (cell.glyph == "*" ? " DONE" : "")
1244 }
1245}