Sources/Orgstar/AgendaView.swift
765 lines · 32777 bytes
1import OrgApp
2import OrgDocument
3import OrgCore
4import OrgPresentation
5import SwiftUI
6
7/// The agenda window: the day/week agenda, the TODO list, tag matches and saved views.
8/// Return or a double click jumps to the entry in the main window. Keys as in Emacs's agenda:
9/// f/b/. move the span, g refreshes, l shows the log (closed and clocked), / filters
10/// (`+cat-tag<0:10-/regexp/`), \ by tag, < by the line's category, = by regexp, _ by effort,
11/// | clears filters, I/O/X clock in, out and cancel, C-c C-w refiles, $ archives, m/u/U mark
12/// and unmark, B acts on the marked entries, t cycles the TODO state, +/- change the priority, : or
13/// C-c C-q sets tags, C-c C-s / C-c C-d schedule and set a deadline, S-→/S-← move the date.
14struct AgendaView: View {
15 let workspace: WorkspaceModel
16 let session: DocumentSession
17 let commands: AppCommands
18 let scheduler: ReminderScheduler?
19 let clock: ClockModel
20 @State private var agenda: AgendaModel
21 @State private var views = AgendaViewLoader.builtIn
22 @State private var viewName = AgendaViewLoader.builtIn[0].name
23 @State private var matchText = ""
24 @State private var selection: String?
25 @State private var tick = 0
26 @State private var message: String?
27 @State private var prompt: PendingPrompt?
28 @State private var promptText = ""
29 @State private var prefix: String?
30 /// Entries marked for a bulk action.
31 @State private var marked: [EntryRef] = []
32 @State private var logMode = false
33 @State private var filter = AgendaFilter()
34 /// A filter question: its title and which filter it sets.
35 @State private var filterPrompt: (title: String, kind: Character)?
36 @State private var filterText = ""
37 /// A one-line question for an agenda action, and what to do with the answer.
38 struct TextPrompt {
39 let title: String
40 let apply: (String) -> Void
41 }
42 @State private var textPrompt: TextPrompt?
43 @State private var textAnswer = ""
44 @AppStorage("agendaSpan") private var span = 10
45 @AppStorage("agendaStartOffset") private var startOffset = -3
46 @AppStorage("agendaSubfolders") private var includeSubfolders = false
47 @AppStorage("agendaPrefixAgenda") private var prefixAgenda = PrefixFormat.defaults["agenda"]!
48 @AppStorage("agendaPrefixTodo") private var prefixTodo = PrefixFormat.defaults["todo"]!
49 @AppStorage("agendaPrefixTags") private var prefixTags = PrefixFormat.defaults["tags"]!
50 @Environment(\.openWindow) private var openWindow
51
52 static let match = "Match…"
53 static let todoMatch = "TODO Match…"
54
55 init(workspace: WorkspaceModel, session: DocumentSession, commands: AppCommands, scheduler: ReminderScheduler?, clock: ClockModel) {
56 self.workspace = workspace
57 self.session = session
58 self.commands = commands
59 self.scheduler = scheduler
60 self.clock = clock
61 _agenda = State(initialValue: AgendaModel(workspace: workspace))
62 }
63
64 /// An agenda entry by its file, heading line and where that line was.
65 struct EntryRef: Hashable {
66 let path: String
67 let line: String
68 let offset: Int
69
70 init?(_ item: AgendaItem) {
71 guard let path = item.path, let line = item.headingLine, let offset = item.headingOffset else { return nil }
72 self.path = path
73 self.line = line
74 self.offset = offset
75 }
76 }
77
78 struct PendingPrompt: Identifiable {
79 let id = UUID()
80 let prompt: Prompt
81 let command: any OrgCommand
82 let atMarker: Bool
83 let answers: [String: String]
84 let itemID: String
85 }
86
87 private struct RefreshKey: Hashable {
88 var mode: AgendaMode
89 var start: Int?
90 var span: Int
91 var startOffset: Int
92 var includeSubfolders: Bool
93 var prefix: [String]
94 var logMode: Bool
95 var files: Int
96 var changed: Int?
97 var edits: Int
98 var path: String?
99 var tick: Int
100 }
101
102 private var refreshKey: RefreshKey {
103 RefreshKey(
104 mode: agenda.mode, start: agenda.start, span: span, startOffset: startOffset, includeSubfolders: includeSubfolders, prefix: [prefixAgenda, prefixTodo, prefixTags], logMode: logMode,
105 files: workspace.files.count, changed: workspace.changedFile?.version, edits: session.editVersion,
106 path: session.path, tick: tick
107 )
108 }
109
110 private var isAgenda: Bool {
111 if case .agenda = agenda.mode { return true }
112 return false
113 }
114
115 private var isMatch: Bool { viewName == Self.match || viewName == Self.todoMatch }
116
117 private var customPrefix: Bool {
118 switch agenda.mode {
119 case .agenda: prefixAgenda != PrefixFormat.defaults["agenda"]
120 case .todo: prefixTodo != PrefixFormat.defaults["todo"]
121 case .match: prefixTags != PrefixFormat.defaults["tags"]
122 }
123 }
124
125 @Environment(\.orgTheme) private var theme
126
127 var body: some View {
128 List(selection: $selection) {
129 if isAgenda {
130 ForEach(agenda.days, id: \.day) { day in
131 Section {
132 rows(day.items.filter(filter.keeps), prefix: "\(day.day)", day: day.day)
133 } header: {
134 Text(day.header)
135 .font(.headline)
136 .foregroundStyle(day.isToday ? theme.color("agenda-today") ?? .accentColor : theme.color("agenda-date") ?? .primary)
137 }
138 }
139 } else {
140 Section {
141 rows(agenda.list.filter(filter.keeps), prefix: "list")
142 } header: {
143 Text(listTitle).font(.headline)
144 }
145 }
146 }
147 .themedListBackground(theme.color("agenda-background"))
148 .contextMenu(forSelectionType: String.self) { _ in
149 } primaryAction: { ids in
150 if let id = ids.first { jump(id) }
151 }
152 .onKeyPress(phases: .down) { press in handle(press) }
153 .safeAreaInset(edge: .bottom, spacing: 0) {
154 if let message = message ?? (filter.isEmpty ? reminderStatus : "Filter: " + filter.description) {
155 Text(message)
156 .font(.callout)
157 .frame(maxWidth: .infinity, alignment: .leading)
158 .padding(.horizontal, 12)
159 .padding(.vertical, 6)
160 .background(.bar)
161 }
162 }
163 .toolbar {
164 ToolbarItemGroup(placement: .navigation) {
165 Menu {
166 ForEach(views) { view in Button(view.name) { viewName = view.name } }
167 Divider()
168 Button(Self.match) { viewName = Self.match }
169 Button(Self.todoMatch) { viewName = Self.todoMatch }
170 } label: {
171 Label(viewName, systemImage: "calendar").labelStyle(.titleAndIcon)
172 }
173 .help("What the agenda shows")
174 if isMatch {
175 TextField("+work-boss|LEVEL>2/!TODO", text: $matchText)
176 .frame(minWidth: 220)
177 .onSubmit { applyView() }
178 }
179 }
180 ToolbarItemGroup {
181 if agenda.isComputing { ProgressView().controlSize(.small) }
182 if isAgenda {
183 Button("Earlier", systemImage: "chevron.left") { agenda.shift(forward: false) }
184 .help("Previous days (b)")
185 Button("Today") { agenda.showToday() }
186 .help("Back to today (.)")
187 Button("Later", systemImage: "chevron.right") { agenda.shift(forward: true) }
188 .help("Next days (f)")
189 }
190 }
191 }
192 .overlay {
193 if agenda.files.isEmpty {
194 ContentUnavailableView("No agenda files", systemImage: "calendar", description: Text("The agenda reads the org files at the top of each folder you add."))
195 }
196 }
197 .sheet(item: Binding(get: { prompt?.prompt.fast == nil ? nil : prompt }, set: { if $0 == nil { prompt = nil } })) { pending in
198 if let fast = pending.prompt.fast {
199 FastSelectionView(selection: fast, message: pending.prompt.message) { answer in
200 prompt = nil
201 guard let answer else { return }
202 promptText = answer
203 prompt = pending
204 answerPrompt()
205 }
206 .frame(minWidth: 420)
207 }
208 }
209 .alert(prompt?.prompt.message ?? "", isPresented: Binding(get: { prompt != nil && prompt?.prompt.fast == nil }, set: { if !$0 { prompt = nil } })) {
210 TextField("", text: $promptText)
211 Button("OK") { answerPrompt() }
212 Button("Cancel", role: .cancel) { prompt = nil }
213 } message: {
214 if let choices = prompt?.prompt.choices, !choices.isEmpty {
215 Text(choices.prefix(12).joined(separator: " "))
216 }
217 }
218 .alert(filterPrompt?.title ?? "", isPresented: Binding(get: { filterPrompt != nil }, set: { if !$0 { filterPrompt = nil } })) {
219 TextField("", text: $filterText)
220 Button("Filter") { applyFilter() }
221 Button("Cancel", role: .cancel) { filterPrompt = nil }
222 } message: {
223 if filterPrompt?.kind == "/" || filterPrompt?.kind == "\\" {
224 Text(shown.tags.sorted().prefix(20).joined(separator: " "))
225 }
226 }
227 .alert(textPrompt?.title ?? "", isPresented: Binding(get: { textPrompt != nil }, set: { if !$0 { textPrompt = nil } })) {
228 TextField("", text: $textAnswer)
229 Button("OK") {
230 let pending = textPrompt
231 let answer = textAnswer
232 textPrompt = nil
233 textAnswer = ""
234 // A follow-up question opens after this alert closes.
235 DispatchQueue.main.async { pending?.apply(answer) }
236 }
237 Button("Cancel", role: .cancel) {
238 textPrompt = nil
239 textAnswer = ""
240 }
241 }
242 .navigationTitle(viewName.replacingOccurrences(of: "…", with: ""))
243 .onChange(of: viewName) { applyView() }
244 .task(id: refreshKey) {
245 agenda.span = span
246 agenda.startOffset = startOffset
247 agenda.includeSubfolders = includeSubfolders
248 agenda.options.prefixFormat = ["agenda": prefixAgenda, "todo": prefixTodo, "tags": prefixTags]
249 agenda.options.logMode = logMode
250 let open = session.openTexts
251 await agenda.refresh(open: open)
252 }
253 .task {
254 loadViews()
255 // The time grid's "now" line and the day itself move on.
256 while !Task.isCancelled {
257 try? await Task.sleep(for: .seconds(60))
258 tick += 1
259 }
260 }
261 }
262
263 @ViewBuilder
264 private func rows(_ items: [AgendaItem], prefix: String, day: Int? = nil) -> some View {
265 ForEach(Array(items.enumerated()), id: \.offset) { index, item in
266 AgendaRow(item: item, day: day, customPrefix: customPrefix, marked: EntryRef(item).map(marked.contains) ?? false)
267 .tag("\(prefix):\(index)")
268 .selectionDisabled(item.path == nil)
269 }
270 }
271
272 @AppStorage("reminders") private var remindersEnabled = true
273
274 /// How far ahead notifications are set, as the design asks the agenda to show.
275 private var reminderStatus: String? {
276 guard let scheduler, remindersEnabled else { return nil }
277 if !scheduler.isAuthorized { return "Notifications are off for Orgstar in System Settings." }
278 guard let through = scheduler.scheduledThrough else { return nil }
279 return "Reminders are set through " + through.formatted(.dateTime.weekday(.abbreviated).day().month(.abbreviated).hour().minute()) + "."
280 }
281
282 private var listTitle: String {
283 switch agenda.mode {
284 case .todo(let keywords): "TODO items: \(keywords ?? "all")"
285 case .match(let match, let todoOnly): (todoOnly ? "TODO entries" : "Entries") + " matching \(match)"
286 case .agenda: ""
287 }
288 }
289
290 private func loadViews() {
291 let loaded = AgendaViewLoader.load()
292 views = loaded.views
293 message = loaded.problems.first
294 }
295
296 private func applyView() {
297 selection = nil
298 agenda.start = nil
299 switch viewName {
300 case Self.match, Self.todoMatch:
301 let match = matchText.trimmingCharacters(in: .whitespaces)
302 guard !match.isEmpty else { return }
303 agenda.mode = .match(match, todoOnly: viewName == Self.todoMatch)
304 default:
305 if let view = views.first(where: { $0.name == viewName }) { agenda.mode = view.mode }
306 }
307 }
308
309 // MARK: - Items
310
311 private func item(_ id: String) -> AgendaItem? {
312 let parts = id.split(separator: ":")
313 guard parts.count == 2, let index = Int(parts[1]) else { return nil }
314 let items = (parts[0] == "list" ? agenda.list : agenda.days.first { "\($0.day)" == parts[0] }?.items ?? []).filter(filter.keeps)
315 return index < items.count ? items[index] : nil
316 }
317
318 // MARK: - Filters
319
320 /// The tags and categories on the view's lines, which filter words are read against.
321 private var shown: (tags: Set<String>, categories: Set<String>) {
322 let items = (isAgenda ? agenda.days.flatMap(\.items) : agenda.list).filter { $0.path != nil }
323 return (Set(items.flatMap(\.tags)), Set(items.map(\.category)))
324 }
325
326 private func askFilter(_ kind: Character) {
327 switch kind {
328 case "/": filterText = filter.description
329 default: filterText = ""
330 }
331 let title = switch kind {
332 case "/": "Filter [+cat-tag<0:10-/regexp/]:"
333 case "\\": "Tag filter (+tag-tag):"
334 case "=": "Regexp filter (-re to drop):"
335 default: "Effort filter (<0:30, >1:00, =1:00):"
336 }
337 filterPrompt = (title, kind)
338 }
339
340 private func applyFilter() {
341 guard let kind = filterPrompt?.kind else { return }
342 filterPrompt = nil
343 let text = filterText.trimmingCharacters(in: .whitespaces)
344 var current = filter
345 switch kind {
346 case "/":
347 let (parsed, ignored) = AgendaFilter().parse(text, tags: shown.tags, categories: shown.categories)
348 current = parsed
349 if !ignored.isEmpty { message = "\(ignored.joined(separator: " ")) ignored: no line has that tag or category" }
350 case "\\":
351 // Every word as a tag.
352 current.tags = AgendaFilter().parse(text, tags: Set(text.split(whereSeparator: { "+- ".contains($0) }).map(String.init)), categories: []).filter.tags
353 case "=":
354 current.regexps = text.isEmpty ? [] : [text.hasPrefix("-") || text.hasPrefix("+") ? text : "+" + text]
355 default:
356 current.efforts = text.isEmpty ? [] : ["+" + text]
357 }
358 filter = current
359 selection = nil
360 }
361
362 /// `<`: keep only the selected line's category, or drop that filter.
363 private func toggleCategoryFilter() {
364 if !filter.categories.isEmpty {
365 filter.categories = []
366 } else if let selection, let item = item(selection) {
367 filter.categories = ["+" + item.category]
368 } else {
369 message = "No entry selected"
370 }
371 }
372
373 private func jump(_ id: String) {
374 guard let item = item(id), let path = item.path, let offset = item.markerOffset ?? item.headingOffset else { return }
375 commands.jump(path: path, offset: offset)
376 openWindow(id: "main")
377 }
378
379 // MARK: - Commands
380
381 private func handle(_ press: KeyPress) -> KeyPress.Result {
382 let control = press.modifiers.contains(.control)
383 // `C-x` and friends arrive as control characters or as letters with control.
384 func isControl(_ letter: String, _ code: String) -> Bool { control && (press.characters == letter || press.characters == code) }
385 if let pending = prefix {
386 prefix = nil
387 if pending == "C-c C-x" {
388 if isControl("s", "\u{13}") { archive() } else { message = "C-c C-x \(press.characters) is undefined" }
389 return .handled
390 }
391 if isControl("s", "\u{13}") {
392 run(SetPlanning(deadline: false))
393 } else if isControl("d", "\u{04}") {
394 run(SetPlanning(deadline: true))
395 } else if isControl("q", "\u{11}") {
396 run(SetTags())
397 } else if isControl("t", "\u{14}") {
398 run(TodoCycle())
399 } else if isControl("w", "\u{17}") {
400 refile(marked: false)
401 } else if isControl("x", "\u{18}") {
402 prefix = "C-c C-x"
403 message = "C-c C-x-"
404 } else if press.characters == "$" {
405 archive()
406 } else {
407 message = "C-c \(press.characters) is undefined"
408 }
409 return .handled
410 }
411 if isControl("c", "\u{03}") {
412 prefix = "C-c"
413 message = "C-c-"
414 return .handled
415 }
416 if press.key == .return, let selection {
417 jump(selection)
418 return .handled
419 }
420 if press.modifiers == .shift, press.key == .rightArrow || press.key == .leftArrow {
421 run(ShiftTimestampDay(later: press.key == .rightArrow), atMarker: true)
422 return .handled
423 }
424 guard press.modifiers.subtracting(.shift).isEmpty else { return .ignored }
425 switch press.characters {
426 case "f" where isAgenda: agenda.shift(forward: true)
427 case "b" where isAgenda: agenda.shift(forward: false)
428 case "." where isAgenda: agenda.showToday()
429 case "/", "\\", "=", "_": askFilter(press.characters.first!)
430 case "<": toggleCategoryFilter()
431 case "|":
432 filter = AgendaFilter()
433 message = "Filters removed"
434 case "l" where isAgenda:
435 logMode.toggle()
436 message = logMode ? "Log mode on" : "Log mode off"
437 case "g", "r":
438 loadViews()
439 tick += 1
440 case "I": clockIn()
441 case "O": message = clock.clockOut(session)
442 case "X": message = clock.clockOut(session, cancel: true)
443 case "$": archive()
444 case "m": mark(true)
445 case "u": mark(false)
446 case "U":
447 marked = []
448 message = "No entries marked"
449 case "B": askBulk()
450 case "t": run(TodoCycle())
451 case "+": run(PriorityUp())
452 case "-": run(PriorityDown())
453 case ":": run(SetTags())
454 default: return .ignored
455 }
456 return .handled
457 }
458
459 // MARK: - Clock, refile, archive, bulk
460
461 private var selectedEntry: EntryRef? { selection.flatMap(item).flatMap(EntryRef.init) }
462
463 private func clockIn() {
464 guard let entry = selectedEntry, let offset = session.locateHeading(path: entry.path, line: entry.line, near: entry.offset) else {
465 message = "No entry selected"
466 return
467 }
468 message = clock.clockIn(session, path: entry.path, at: offset)
469 tick += 1
470 }
471
472 private func archive() {
473 guard let entry = selectedEntry, let offset = session.locateHeading(path: entry.path, line: entry.line, near: entry.offset) else {
474 message = "No entry selected"
475 return
476 }
477 message = session.archive(from: (entry.path, offset))
478 tick += 1
479 }
480
481 /// Refiles the selected entry, or with `marked` the marked ones, to a target asked for in
482 /// the main window, where the list of targets is searchable.
483 private func refile(marked bulk: Bool) {
484 let entries = bulk ? marked : selectedEntry.map { [$0] } ?? []
485 guard !entries.isEmpty else {
486 message = "No entry selected"
487 return
488 }
489 let targets = workspace.refileTargets(openPath: session.path, document: session.document)
490 commands.ask(Prompt(key: "refile", message: "Refile to:", choices: targets.map(\.label))) { answer in
491 guard let answer, targets.contains(where: { $0.label == answer }) else { return }
492 message = eachEntry(entries) { entry, offset in
493 // Targets in the entry's own file from its text now, as earlier moves shift them.
494 let document = session.openDocuments.first { $0.path == entry.path }?.document
495 ?? FileManager.default.contents(atPath: entry.path).map { DocumentState(bytes: [UInt8]($0)) }
496 guard let target = workspace.refileTargets(openPath: entry.path, document: document).first(where: { $0.label == answer }) else {
497 return "Can't find \(answer) any more."
498 }
499 return session.refile(to: target, from: (entry.path, offset))
500 }
501 if bulk { marked = [] }
502 tick += 1
503 }
504 openWindow(id: "main")
505 }
506
507 /// Runs `action` on each entry, finding it again first: later entries in a file first, so
508 /// earlier ones keep their place. Returns the last message.
509 private func eachEntry(_ entries: [EntryRef], _ action: (EntryRef, Int) -> String?) -> String? {
510 var last: String?
511 var failed = 0
512 for entry in entries.sorted(by: { ($0.path, $1.offset) < ($1.path, $0.offset) }) {
513 guard let offset = session.locateHeading(path: entry.path, line: entry.line, near: entry.offset) else {
514 failed += 1
515 continue
516 }
517 last = action(entry, offset)
518 }
519 return failed > 0 ? "\(failed) marked \(failed == 1 ? "entry" : "entries") changed and \(failed == 1 ? "was" : "were") skipped" : last
520 }
521
522 private func mark(_ on: Bool) {
523 guard let entry = selectedEntry else {
524 message = "No entry selected"
525 return
526 }
527 if on {
528 if !marked.contains(entry) { marked.append(entry) }
529 } else {
530 marked.removeAll { $0 == entry }
531 }
532 message = "\(marked.count) marked"
533 }
534
535 /// `B`: an action for every marked entry.
536 private func askBulk() {
537 guard !marked.isEmpty else {
538 message = "No entries are marked"
539 return
540 }
541 textPrompt = TextPrompt(title: "Bulk action on \(marked.count): [$] archive [r] refile [t] TODO state [+] tag [-] untag [s] schedule [d] deadline") { answer in
542 switch answer.trimmingCharacters(in: .whitespaces) {
543 case "$": bulk { session.archive(from: ($0.path, $1)) }
544 case "r": refile(marked: true)
545 case "t":
546 textPrompt = TextPrompt(title: "TODO state (empty for none):") { keyword in
547 let word = keyword.trimmingCharacters(in: .whitespaces)
548 bulk { performAt($0, $1, SetTodo(keyword: word.isEmpty ? nil : word)) }
549 }
550 case "+", "-":
551 let on = answer.trimmingCharacters(in: .whitespaces) == "+"
552 textPrompt = TextPrompt(title: on ? "Tag to add:" : "Tag to remove:") { tag in
553 let tag = tag.trimmingCharacters(in: .whitespaces)
554 guard !tag.isEmpty else { return }
555 bulk { performAt($0, $1, ToggleTag(tag: tag, on: on)) }
556 }
557 case "s", "d":
558 let deadline = answer.trimmingCharacters(in: .whitespaces) == "d"
559 textPrompt = TextPrompt(title: deadline ? "Deadline (+2d, fri, 2026-10-12):" : "Schedule (+2d, fri, 2026-10-12):") { date in
560 bulk { performAt($0, $1, SetPlanning(deadline: deadline), answers: ["date": date]) }
561 }
562 default:
563 message = "No bulk action \(answer)"
564 }
565 }
566 }
567
568 private func bulk(_ action: (EntryRef, Int) -> String?) {
569 message = eachEntry(marked, action) ?? "Done with \(marked.count) entries"
570 marked = []
571 tick += 1
572 }
573
574 /// Runs `command` at the heading at `offset`, as `run` does for the selection.
575 private func performAt(_ entry: EntryRef, _ offset: Int, _ command: any OrgCommand, answers: [String: String] = [:]) -> String? {
576 switch session.perform(command, path: entry.path, at: offset, expect: (offset, entry.line), answers: answers) {
577 case .failed(let text): text
578 case .prompt: "\(command.title) needs an answer; run it on the entry itself"
579 default: nil
580 }
581 }
582
583 /// Runs `command` on the selected entry, at its heading or, with `atMarker`, at the
584 /// timestamp the entry is listed for.
585 private func run(_ command: any OrgCommand, atMarker: Bool = false, answers: [String: String] = [:], itemID: String? = nil) {
586 guard let id = itemID ?? selection, let item = item(id), let path = item.path, let start = item.headingOffset else {
587 message = "No entry selected"
588 return
589 }
590 if atMarker, ![.deadline, .upcomingDeadline, .scheduled, .pastScheduled, .timestamp].contains(item.kind) {
591 message = "Only dated entries can move"
592 return
593 }
594 let offset = atMarker ? (item.markerOffset ?? start) : start
595 let step = session.perform(command, path: path, at: offset, expect: item.headingLine.map { (start, $0) }, answers: answers)
596 switch step {
597 case .prompt(let request):
598 promptText = request.initial
599 prompt = PendingPrompt(prompt: request, command: command, atMarker: atMarker, answers: answers, itemID: id)
600 case .failed(let text):
601 message = text
602 tick += 1
603 case .external:
604 message = "Not available from the agenda"
605 case .commit:
606 message = nil
607 tick += 1
608 }
609 }
610
611 private func answerPrompt() {
612 guard let pending = prompt else { return }
613 prompt = nil
614 var answers = pending.answers
615 answers[pending.prompt.key] = promptText
616 run(pending.command, atMarker: pending.atMarker, answers: answers, itemID: pending.itemID)
617 }
618}
619
620struct AgendaRow: View {
621 let item: AgendaItem
622 /// The agenda day the row is on, for habit graphs.
623 var day: Int?
624 /// A user `org-agenda-prefix-format`: the prefix as Emacs prints it, not the columns.
625 var customPrefix = false
626 /// Marked for a bulk action.
627 var marked = false
628 @Environment(\.orgTheme) private var theme
629
630 var body: some View {
631 switch item.kind {
632 case .timeGrid:
633 HStack(spacing: 8) {
634 Text(Self.trim(item.time))
635 .monospacedDigit()
636 .frame(width: 140, alignment: .trailing)
637 VStack { Divider() }
638 }
639 .font(.caption)
640 .foregroundStyle(theme.color("agenda-time").map(AnyShapeStyle.init) ?? AnyShapeStyle(.tertiary))
641 case .currentTime:
642 HStack(spacing: 8) {
643 Text("now " + Self.trim(item.time))
644 .monospacedDigit()
645 .frame(width: 140, alignment: .trailing)
646 Rectangle().fill(theme.color("agenda-today") ?? .accentColor).frame(height: 1)
647 }
648 .font(.caption)
649 .foregroundStyle(theme.color("agenda-today") ?? .accentColor)
650 default:
651 HStack(spacing: 4) {
652 if marked { Text("›").bold().foregroundStyle(theme.color("agenda-today") ?? .accentColor) }
653 entryRow
654 }
655 }
656 }
657
658 @ViewBuilder
659 private var entryRow: some View {
660 if customPrefix {
661 HStack(spacing: 0) {
662 Text(item.prefix)
663 .font(.body.monospaced())
664 .foregroundStyle(theme.color("agenda-category") ?? .secondary)
665 title.lineLimit(1)
666 Spacer(minLength: 8)
667 if let habit = item.habit, let day { HabitGraph(cells: habit.graph(today: day), theme: theme) }
668 if !item.tags.isEmpty {
669 Text(":" + item.tags.joined(separator: ":") + ":").font(.caption).foregroundStyle(theme.color("tags") ?? .secondary)
670 }
671 }
672 } else {
673 HStack(spacing: 8) {
674 Text(item.category)
675 .lineLimit(1)
676 .foregroundStyle(theme.color("agenda-category") ?? .secondary)
677 .frame(width: 80, alignment: .leading)
678 if item.kind != .todo, item.kind != .tagsMatch {
679 Text(Self.trim(item.time))
680 .monospacedDigit()
681 .foregroundStyle(theme.color("agenda-time") ?? .primary)
682 .frame(width: 80, alignment: .leading)
683 }
684 if !item.extra.isEmpty {
685 Text(item.extra.trimmingCharacters(in: .whitespaces))
686 .monospacedDigit()
687 .foregroundStyle(leaderColor)
688 }
689 title
690 .lineLimit(1)
691 Spacer(minLength: 8)
692 if let habit = item.habit, let day {
693 HabitGraph(cells: habit.graph(today: day), theme: theme)
694 }
695 if !item.tags.isEmpty {
696 Text(":" + item.tags.joined(separator: ":") + ":")
697 .font(.caption)
698 .foregroundStyle(theme.color("tags") ?? .secondary)
699 }
700 }
701 }
702 }
703
704 static func trim(_ time: String) -> String {
705 time.trimmingCharacters(in: CharacterSet(charactersIn: " ┄."))
706 }
707
708 private var leaderColor: Color {
709 switch item.kind {
710 case .deadline: theme.color("agenda-deadline") ?? .red
711 case .upcomingDeadline: theme.color("agenda-upcoming") ?? .orange
712 case .pastScheduled: theme.color("agenda-scheduled-past") ?? .brown
713 default: theme.color("agenda-scheduled") ?? .secondary
714 }
715 }
716
717 /// The TODO keyword colored as in the editor.
718 private var title: Text {
719 let text = item.text.trimmingCharacters(in: .whitespaces)
720 guard let todo = item.todo, text.hasPrefix(todo + " ") else { return Text(text) }
721 let rest = String(text.dropFirst(todo.count))
722 let rest_ = Text(rest).foregroundColor(item.isDone ? theme.color("comment") ?? .secondary : theme.color("foreground") ?? .primary)
723 return Text(todo).foregroundColor(theme.keywordColor(todo, done: item.isDone)).bold() + rest_
724 }
725}
726
727/// org-habit's consistency graph: a cell per day, `*` where the habit was done, `!` today.
728struct HabitGraph: View {
729 let cells: [Habit.Cell]
730 var theme: ThemeSpec = .default
731
732 var body: some View {
733 HStack(spacing: 1) {
734 ForEach(cells, id: \.day) { cell in
735 Text(String(cell.glyph))
736 .font(.system(size: 9, weight: .bold, design: .monospaced))
737 .frame(width: 8, height: 14)
738 .background(color(cell.face))
739 .help(Self.label(cell))
740 }
741 }
742 .accessibilityElement(children: .ignore)
743 .accessibilityLabel("Done \(cells.filter { $0.glyph == "*" }.count) of the last \(Habit.precedingDays) days")
744 }
745
746 /// Due-state colors, lighter for days to come, as org-habit's faces.
747 func color(_ face: Habit.Face) -> Color {
748 func themed(_ key: String, _ fallback: Color) -> Color { theme.color(key) ?? fallback }
749 switch face {
750 case .clear: return themed("habit-clear", .blue).opacity(0.7)
751 case .clearFuture: return themed("habit-clear", .blue).opacity(0.35)
752 case .ready: return themed("habit-ready", .green).opacity(0.75)
753 case .readyFuture: return themed("habit-ready", .green).opacity(0.35)
754 case .alert: return themed("habit-alert", .yellow).opacity(0.85)
755 case .alertFuture: return themed("habit-alert", .yellow).opacity(0.4)
756 case .overdue: return themed("habit-overdue", .red).opacity(0.75)
757 case .overdueFuture: return themed("habit-overdue", .red).opacity(0.35)
758 }
759 }
760
761 static func label(_ cell: Habit.Cell) -> String {
762 let date = Days.date(cell.day)
763 return String(format: "%04d-%02d-%02d", date.year, date.month, date.day) + (cell.glyph == "*" ? " DONE" : "")
764 }
765}