Commit 24268e6827

24268e682739a20fab3cd23169329983589fbc58

parent: 15d134165d

Verified · cmc

cmc <hello@cleberg.net> · 2026-10-11 04:11 UTC

Split AgendaView.swift

Layout: unified · split

Sources/Orgstar/AgendaRowView.swift added +203
@@ -0,0 +1,203 @@
1import AppKit
2import OrgApp
3import OrgDocument
4import OrgCore
5import OrgPresentation
6import SwiftUI
7
8/// One agenda line: the time or status over an icon, the category above the title, progress
9/// and tags after it, and the TODO keyword and priority at the end.
10struct AgendaRowView: View {
11 let row: AgendaRow
12 /// The agenda day the row is on, for habit graphs.
13 var day: Int
14 var showsGutter = true
15 var selected = false
16 var hovered = false
17 /// Marked for a bulk action.
18 var marked = false
19 @Environment(\.orgTheme) private var theme
20
21 static let gutterWidth: CGFloat = 92
22
23 var body: some View {
24 HStack(alignment: .center, spacing: 12) {
25 if showsGutter { gutter }
26 VStack(alignment: .leading, spacing: 2) {
27 if !row.category.isEmpty { categoryLine }
28 titleLine
29 }
30 .layoutPriority(1)
31 Spacer(minLength: 8)
32 if let habit = row.item?.habit {
33 HabitGraph(cells: habit.graph(today: day), theme: theme)
34 }
35 if let todo = row.todo {
36 let color = theme.dynamic(row.isDone ? .systemGreen : .systemRed) { [theme, row] in theme.todoColor(todo, isDone: row.isDone, dark: $0) }
37 Text(todo)
38 .font(.system(size: 10, weight: .bold))
39 .foregroundStyle(color)
40 .padding(.horizontal, 7)
41 .padding(.vertical, 2)
42 .background(Capsule().fill(color.opacity(0.14)))
43 .fixedSize()
44 }
45 priorityBadge
46 .frame(width: 18)
47 }
48 .padding(.horizontal, 16)
49 .padding(.vertical, 6)
50 .frame(minHeight: 44)
51 // `org-agenda-dim-blocked-tasks`.
52 .opacity(row.isBlocked ? 0.5 : 1)
53 .background {
54 RoundedRectangle(cornerRadius: 6)
55 .fill(selected ? theme.color("selection") ?? Color.accentColor.opacity(0.2) : hovered ? Color.primary.opacity(0.05) : .clear)
56 .padding(.horizontal, 6)
57 }
58 .overlay(alignment: .leading) {
59 if marked {
60 Capsule().fill(theme.color("agenda-today") ?? .accentColor).frame(width: 3).padding(.vertical, 8).padding(.leading, 8)
61 }
62 }
63 .accessibilityElement(children: .combine)
64 }
65
66 private var statusColor: Color {
67 theme.dynamic(.secondaryLabelColor) { [theme, row] in theme.statusColor(row.status, dark: $0) }
68 }
69
70 private var gutter: some View {
71 VStack(alignment: .leading, spacing: 3) {
72 Text(row.gutter)
73 .font(.system(size: 12, weight: row.status == .overdue || row.status == .dueSoon ? .semibold : .regular).monospacedDigit())
74 .foregroundStyle(statusColor)
75 .lineLimit(1)
76 .minimumScaleFactor(0.8)
77 if let symbol {
78 Image(systemName: symbol)
79 .font(.system(size: row.icon == .event ? 8 : 10, weight: .semibold))
80 .foregroundStyle(iconColor)
81 .frame(height: 12)
82 }
83 }
84 .frame(width: Self.gutterWidth, alignment: .leading)
85 }
86
87 /// Overdue entries show a warning, done ones a check, as the status says first.
88 private var symbol: String? {
89 guard let icon = row.icon else { return nil }
90 if row.status == .overdue { return "exclamationmark.circle.fill" }
91 if row.status == .done { return "checkmark.circle.fill" }
92 switch icon {
93 case .scheduled: return "calendar"
94 case .deadline: return "flag.fill"
95 case .habit: return "repeat"
96 case .event: return "circle.fill"
97 case .timestamp: return row.start == nil ? "calendar" : "clock"
98 }
99 }
100
101 private var iconColor: Color {
102 if let event = row.event { return theme.dynamic(.systemPurple) { [theme] in theme.eventColor(event, dark: $0) } }
103 return row.status == .normal ? Color.secondary.opacity(0.8) : statusColor
104 }
105
106 private var categoryLine: some View {
107 HStack(spacing: 5) {
108 Circle()
109 .fill(row.event.map { event in theme.dynamic(.systemPurple) { [theme] in theme.eventColor(event, dark: $0) } }
110 ?? theme.dynamic { [theme, row] in theme.categoryColor(row.category, dark: $0) })
111 .frame(width: 6, height: 6)
112 Text(row.category)
113 .font(.system(size: 11))
114 .foregroundStyle(theme.color("agenda-category") ?? .secondary)
115 .lineLimit(1)
116 }
117 }
118
119 private var titleLine: some View {
120 HStack(spacing: 6) {
121 Text(row.title.isEmpty ? " " : row.title)
122 .font(.system(size: 13))
123 .strikethrough(row.isDone)
124 .foregroundStyle(row.isDone ? AnyShapeStyle(.secondary) : AnyShapeStyle(theme.color("foreground") ?? .primary))
125 .lineLimit(1)
126 .truncationMode(.tail)
127 ForEach([row.progress, row.detail].compactMap { $0 }, id: \.self) { progress in
128 Text(progress)
129 .font(.system(size: 10, weight: .semibold).monospacedDigit())
130 .foregroundStyle(.secondary)
131 .padding(.horizontal, 6)
132 .padding(.vertical, 1)
133 .background(Capsule().fill(Color.secondary.opacity(0.14)))
134 .fixedSize()
135 }
136 ForEach(row.tags, id: \.self) { tag in
137 Text(tag)
138 .font(.system(size: 10, weight: .medium))
139 .foregroundStyle(theme.color("tags") ?? .secondary)
140 .padding(.horizontal, 6)
141 .padding(.vertical, 1)
142 .background(Capsule().strokeBorder((theme.color("tags") ?? .secondary).opacity(0.35), lineWidth: 0.5))
143 .fixedSize()
144 }
145 }
146 }
147
148 @ViewBuilder
149 private var priorityBadge: some View {
150 if let priority = row.priority {
151 let color = theme.dynamic(.systemOrange) { [theme] in theme.priorityColor(priority, dark: $0) }
152 Text(priority)
153 .font(.system(size: 10, weight: .bold))
154 .foregroundStyle(color)
155 .frame(width: 18, height: 18)
156 .background(Circle().fill(color.opacity(0.14)))
157 .overlay(Circle().strokeBorder(color.opacity(0.6), lineWidth: 1))
158 .help("Priority \(priority)")
159 } else {
160 Color.clear.frame(width: 18, height: 18)
161 }
162 }
163}
164
165/// org-habit's consistency graph: a cell per day, `*` where the habit was done, `!` today.
166struct HabitGraph: View {
167 let cells: [Habit.Cell]
168 var theme: ThemeSpec = .default
169
170 var body: some View {
171 HStack(spacing: 1) {
172 ForEach(cells, id: \.day) { cell in
173 Text(String(cell.glyph))
174 .font(.system(size: 9, weight: .bold, design: .monospaced))
175 .frame(width: 8, height: 14)
176 .background(color(cell.face))
177 .help(Self.label(cell))
178 }
179 }
180 .accessibilityElement(children: .ignore)
181 .accessibilityLabel("Done \(cells.filter { $0.glyph == "*" }.count) of the last \(Habit.precedingDays) days")
182 }
183
184 /// Due-state colors, lighter for days to come, as org-habit's faces.
185 func color(_ face: Habit.Face) -> Color {
186 func themed(_ key: String, _ fallback: Color) -> Color { theme.color(key) ?? fallback }
187 switch face {
188 case .clear: return themed("habit-clear", .blue).opacity(0.7)
189 case .clearFuture: return themed("habit-clear", .blue).opacity(0.35)
190 case .ready: return themed("habit-ready", .green).opacity(0.75)
191 case .readyFuture: return themed("habit-ready", .green).opacity(0.35)
192 case .alert: return themed("habit-alert", .yellow).opacity(0.85)
193 case .alertFuture: return themed("habit-alert", .yellow).opacity(0.4)
194 case .overdue: return themed("habit-overdue", .red).opacity(0.75)
195 case .overdueFuture: return themed("habit-overdue", .red).opacity(0.35)
196 }
197 }
198
199 static func label(_ cell: Habit.Cell) -> String {
200 let date = Days.date(cell.day)
201 return String(format: "%04d-%02d-%02d", date.year, date.month, date.day) + (cell.glyph == "*" ? " DONE" : "")
202 }
203}
Sources/Orgstar/AgendaView+Actions.swift added +290
@@ -0,0 +1,290 @@
1import AppKit
2import OrgApp
3import OrgDocument
4import OrgCore
5import OrgPresentation
6import SwiftUI
7
8extension AgendaView {
9 // MARK: - Commands
10
11 func handle(_ press: KeyPress) -> KeyPress.Result {
12 let control = press.modifiers.contains(.control)
13 // `C-x` and friends arrive as control characters or as letters with control.
14 func isControl(_ letter: String, _ code: String) -> Bool { control && (press.characters == letter || press.characters == code) }
15 if let pending = prefix {
16 prefix = nil
17 if pending == "v" {
18 switch press.characters {
19 case "d" where isAgenda: setSpan(.day)
20 case "w" where isAgenda: setSpan(.week)
21 case "m" where isAgenda: setSpan(.month)
22 default: message = "v \(press.characters) is undefined"
23 }
24 if message == "v-" { message = nil }
25 return .handled
26 }
27 if pending == "C-c C-x" {
28 if isControl("s", "\u{13}") { archive() } else { message = "C-c C-x \(press.characters) is undefined" }
29 return .handled
30 }
31 if isControl("s", "\u{13}") {
32 run(SetPlanning(deadline: false))
33 } else if isControl("d", "\u{04}") {
34 run(SetPlanning(deadline: true))
35 } else if isControl("q", "\u{11}") {
36 run(SetTags())
37 } else if isControl("t", "\u{14}") {
38 run(TodoCycle())
39 } else if isControl("w", "\u{17}") {
40 refile(marked: false)
41 } else if isControl("x", "\u{18}") {
42 prefix = "C-c C-x"
43 message = "C-c C-x-"
44 } else if press.characters == "$" {
45 archive()
46 } else {
47 message = "C-c \(press.characters) is undefined"
48 }
49 return .handled
50 }
51 if isControl("c", "\u{03}") {
52 prefix = "C-c"
53 message = "C-c-"
54 return .handled
55 }
56 if isControl("n", "\u{0e}") || (press.key == .downArrow && press.modifiers.isEmpty) {
57 step(1)
58 return .handled
59 }
60 if isControl("p", "\u{10}") || (press.key == .upArrow && press.modifiers.isEmpty) {
61 step(-1)
62 return .handled
63 }
64 if press.key == .return || press.key == .tab, let selection, let line = line(selection) {
65 open(line)
66 return .handled
67 }
68 if press.key == .space, let selection {
69 jump(selection, focus: false)
70 return .handled
71 }
72 if press.modifiers == .shift, press.key == .rightArrow || press.key == .leftArrow {
73 run(ShiftTimestampDay(later: press.key == .rightArrow), atMarker: true)
74 return .handled
75 }
76 guard press.modifiers.subtracting(.shift).isEmpty else { return .ignored }
77 switch press.characters {
78 case "n": step(1)
79 case "p": step(-1)
80 case "f" where isAgenda: move(forward: true)
81 case "b" where isAgenda: move(forward: false)
82 case "." where isAgenda: goToday()
83 case "j" where isAgenda:
84 pickedDate = Self.date(anchorDay)
85 showingDatePicker = true
86 case "v" where isAgenda:
87 prefix = "v"
88 message = "v-"
89 case "d" where isAgenda: setSpan(.day)
90 case "w" where isAgenda: setSpan(.week)
91 case "k" where isAgenda: capture(on: anchorDay)
92 case "s":
93 commands.run("app.save-all")
94 message = "Saved"
95 case "/", "\\", "=", "_": askFilter(press.characters.first!)
96 case "<": toggleCategoryFilter()
97 case "|":
98 filter = AgendaFilter()
99 message = "Filters removed"
100 case "l" where isAgenda:
101 logMode.toggle()
102 message = logMode ? "Log mode on" : "Log mode off"
103 case "g", "r":
104 loadViews()
105 tick += 1
106 case "I": clockIn()
107 case "O": message = clock.clockOut(session)
108 case "X": message = clock.clockOut(session, cancel: true)
109 case "$": archive()
110 case "m": mark(true)
111 case "u": mark(false)
112 case "U":
113 marked = []
114 message = "No entries marked"
115 case "B": askBulk()
116 case "t": run(TodoCycle())
117 case "+": run(PriorityUp())
118 case "-": run(PriorityDown())
119 case ",": run(SetPriority())
120 case ":": run(SetTags())
121 default: return .ignored
122 }
123 return .handled
124 }
125
126 // MARK: - Clock, refile, archive, bulk
127
128 private var selectedEntry: EntryRef? { selection.flatMap(item).flatMap(EntryRef.init) }
129
130 func clockIn() {
131 guard let entry = selectedEntry, let offset = session.locateHeading(path: entry.path, line: entry.line, near: entry.offset) else {
132 message = "No entry selected"
133 return
134 }
135 let paths = workspace.files.filter { $0.kind == .org }.map(\.path)
136 Task {
137 let outcome = await clock.clockIn(session, target: .entry(path: entry.path, offset: offset), paths: paths, ask: commands.askClock)
138 if let jump = outcome.jump { commands.jump(path: jump.path, offset: jump.offset) }
139 message = outcome.messages.last { !$0.isEmpty }
140 tick += 1
141 }
142 }
143
144 func archive() {
145 guard let entry = selectedEntry, let offset = session.locateHeading(path: entry.path, line: entry.line, near: entry.offset) else {
146 message = "No entry selected"
147 return
148 }
149 message = session.archive(from: (entry.path, offset))
150 tick += 1
151 }
152
153 /// Refiles the selected entry, or with `marked` the marked ones, to a target asked for in
154 /// the main window, where the list of targets is searchable.
155 private func refile(marked bulk: Bool) {
156 let entries = bulk ? marked : selectedEntry.map { [$0] } ?? []
157 guard !entries.isEmpty else {
158 message = "No entry selected"
159 return
160 }
161 let targets = workspace.refileTargets(openPath: session.path, document: session.document)
162 commands.ask(Prompt(key: "refile", message: "Refile to:", choices: targets.map(\.label))) { answer in
163 guard let answer, targets.contains(where: { $0.label == answer }) else { return }
164 message = eachEntry(entries) { entry, offset in
165 // Targets in the entry's own file from its text now, as earlier moves shift them.
166 let document = session.openDocuments.first { $0.path == entry.path }?.document
167 ?? FileManager.default.contents(atPath: entry.path).map { DocumentState(bytes: [UInt8]($0)) }
168 guard let target = workspace.refileTargets(openPath: entry.path, document: document).first(where: { $0.label == answer }) else {
169 return "Can't find \(answer) any more."
170 }
171 return session.refile(to: target, from: (entry.path, offset))
172 }
173 if bulk { marked = [] }
174 tick += 1
175 }
176 openWindow(id: "main")
177 }
178
179 /// Runs `action` on each entry, finding it again first: later entries in a file first, so
180 /// earlier ones keep their place. Returns the last message.
181 private func eachEntry(_ entries: [EntryRef], _ action: (EntryRef, Int) -> String?) -> String? {
182 var last: String?
183 var failed = 0
184 for entry in entries.sorted(by: { ($0.path, $1.offset) < ($1.path, $0.offset) }) {
185 guard let offset = session.locateHeading(path: entry.path, line: entry.line, near: entry.offset) else {
186 failed += 1
187 continue
188 }
189 last = action(entry, offset)
190 }
191 return failed > 0 ? "\(failed) marked \(failed == 1 ? "entry" : "entries") changed and \(failed == 1 ? "was" : "were") skipped" : last
192 }
193
194 func mark(_ on: Bool) {
195 guard let entry = selectedEntry else {
196 message = "No entry selected"
197 return
198 }
199 if on {
200 if !marked.contains(entry) { marked.append(entry) }
201 } else {
202 marked.removeAll { $0 == entry }
203 }
204 message = "\(marked.count) marked"
205 }
206
207 /// `B`: an action for every marked entry.
208 private func askBulk() {
209 guard !marked.isEmpty else {
210 message = "No entries are marked"
211 return
212 }
213 textPrompt = TextPrompt(title: "Bulk action on \(marked.count): [$] archive [r] refile [t] TODO state [+] tag [-] untag [s] schedule [d] deadline") { answer in
214 switch answer.trimmingCharacters(in: .whitespaces) {
215 case "$": bulk { session.archive(from: ($0.path, $1)) }
216 case "r": refile(marked: true)
217 case "t":
218 textPrompt = TextPrompt(title: "TODO state (empty for none):") { keyword in
219 let word = keyword.trimmingCharacters(in: .whitespaces)
220 bulk { performAt($0, $1, SetTodo(keyword: word.isEmpty ? nil : word)) }
221 }
222 case "+", "-":
223 let on = answer.trimmingCharacters(in: .whitespaces) == "+"
224 textPrompt = TextPrompt(title: on ? "Tag to add:" : "Tag to remove:") { tag in
225 let tag = tag.trimmingCharacters(in: .whitespaces)
226 guard !tag.isEmpty else { return }
227 bulk { performAt($0, $1, ToggleTag(tag: tag, on: on)) }
228 }
229 case "s", "d":
230 let deadline = answer.trimmingCharacters(in: .whitespaces) == "d"
231 textPrompt = TextPrompt(title: deadline ? "Deadline (+2d, fri, 2026-10-12):" : "Schedule (+2d, fri, 2026-10-12):") { date in
232 bulk { performAt($0, $1, SetPlanning(deadline: deadline), answers: ["date": date]) }
233 }
234 default:
235 message = "No bulk action \(answer)"
236 }
237 }
238 }
239
240 func bulk(_ action: (EntryRef, Int) -> String?) {
241 message = eachEntry(marked, action) ?? "Done with \(marked.count) entries"
242 marked = []
243 tick += 1
244 }
245
246 /// Runs `command` at the heading at `offset`, as `run` does for the selection.
247 private func performAt(_ entry: EntryRef, _ offset: Int, _ command: any OrgCommand, answers: [String: String] = [:]) -> String? {
248 switch session.perform(command, path: entry.path, at: offset, expect: (offset, entry.line), answers: answers) {
249 case .failed(let text): text
250 case .prompt: "\(command.title) needs an answer; run it on the entry itself"
251 default: nil
252 }
253 }
254
255 /// Runs `command` on the selected entry, at its heading or, with `atMarker`, at the
256 /// timestamp the entry is listed for.
257 func run(_ command: any OrgCommand, atMarker: Bool = false, answers: [String: String] = [:], itemID: String? = nil) {
258 guard let id = itemID ?? selection, let item = item(id), let path = item.path, let start = item.headingOffset else {
259 message = "No entry selected"
260 return
261 }
262 if atMarker, ![.deadline, .upcomingDeadline, .scheduled, .pastScheduled, .timestamp].contains(item.kind) {
263 message = "Only dated entries can move"
264 return
265 }
266 let offset = atMarker ? (item.markerOffset ?? start) : start
267 let step = session.perform(command, path: path, at: offset, expect: item.headingLine.map { (start, $0) }, answers: answers)
268 switch step {
269 case .prompt(let request):
270 promptText = request.initial
271 prompt = PendingPrompt(prompt: request, command: command, atMarker: atMarker, answers: answers, itemID: id)
272 case .failed(let text):
273 message = text
274 tick += 1
275 case .external:
276 message = "Not available from the agenda"
277 case .commit:
278 message = nil
279 tick += 1
280 }
281 }
282
283 func answerPrompt() {
284 guard let pending = prompt else { return }
285 prompt = nil
286 var answers = pending.answers
287 answers[pending.prompt.key] = promptText
288 run(pending.command, atMarker: pending.atMarker, answers: answers, itemID: pending.itemID)
289 }
290}
Sources/Orgstar/AgendaView+Toolbar.swift added +289
@@ -0,0 +1,289 @@
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 = anchor - (Days.weekday(anchor) + 6) % 7
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}
Sources/Orgstar/AgendaView.swift +34 −795
@@ -31,44 +31,44 @@ struct AgendaView: View {
3131 let commands: AppCommands
3232 let scheduler: ReminderScheduler?
3333 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 = ""
34 @State var agenda: AgendaModel
35 @State var views = AgendaViewLoader.builtIn
36 @State var viewName = AgendaViewLoader.builtIn[0].name
37 @State var matchText = ""
3838 /// 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
39 @State var selection: String?
40 @State var tick = 0
4141 /// The time the now line shows, kept to the minute while the agenda is open.
42 @State private var now = Date()
42 @State var now = Date()
4343 /// The view picker moved to the agenda for a followed timestamp, which sets its own days.
44 @State private var keepRequestedDays = false
45 @State private var message: String?
46 @State private var prompt: PendingPrompt?
47 @State private var promptText = ""
48 @State private var prefix: String?
44 @State var keepRequestedDays = false
45 @State var message: String?
46 @State var prompt: PendingPrompt?
47 @State var promptText = ""
48 @State var prefix: String?
4949 /// Entries marked for a bulk action.
50 @State private var marked: [EntryRef] = []
51 @State private var logMode = false
52 @State private var filter = AgendaFilter()
50 @State var marked: [EntryRef] = []
51 @State var logMode = false
52 @State var filter = AgendaFilter()
5353 /// A filter question: its title and which filter it sets.
54 @State private var filterPrompt: (title: String, kind: Character)?
55 @State private var filterText = ""
54 @State var filterPrompt: (title: String, kind: Character)?
55 @State var filterText = ""
5656 /// A one-line question for an agenda action, and what to do with the answer.
5757 struct TextPrompt {
5858 let title: String
5959 let apply: (String) -> Void
6060 }
61 @State private var textPrompt: TextPrompt?
61 @State var textPrompt: TextPrompt?
6262 @State private var textAnswer = ""
6363 /// Day, week or month chosen with `v`; nil shows the span the settings or the view give.
64 @State private var spanKind: AgendaSpan?
65 @State private var showingDatePicker = false
66 @State private var pickedDate = Date()
64 @State var spanKind: AgendaSpan?
65 @State var showingDatePicker = false
66 @State var pickedDate = Date()
6767 @AppStorage("agendaOverdueExpanded") private var overdueShown = true
6868 @State private var hovered: String?
6969 @FocusState private var focused: Bool
70 @AppStorage("agendaSpan") private var span = 10
71 @AppStorage("agendaStartOffset") private var startOffset = 0
70 @AppStorage("agendaSpan") var span = 10
71 @AppStorage("agendaStartOffset") var startOffset = 0
7272 @AppStorage("agendaSubfolders") private var includeSubfolders = false
7373 @AppStorage("agendaShowAllDates") private var showAllDates = false
7474 @AppStorage("calendarEvents") private var calendarEventsOn = false
@@ -76,7 +76,7 @@ struct AgendaView: View {
7676 @AppStorage("agendaPrefixAgenda") private var prefixAgenda = PrefixFormat.defaults["agenda"]!
7777 @AppStorage("agendaPrefixTodo") private var prefixTodo = PrefixFormat.defaults["todo"]!
7878 @AppStorage("agendaPrefixTags") private var prefixTags = PrefixFormat.defaults["tags"]!
79 @Environment(\.openWindow) private var openWindow
79 @Environment(\.openWindow) var openWindow
8080
8181 static let match = "Match…"
8282 static let todoMatch = "TODO Match…"
@@ -163,7 +163,7 @@ struct AgendaView: View {
163163 let workspace: WorkspaceModel
164164 let refresh: () async -> Void
165165
166 private var key: RefreshKey {
166 var key: RefreshKey {
167167 var key = base
168168 key.files = workspace.files.count
169169 key.changed = workspace.changedFile?.version
@@ -181,13 +181,13 @@ struct AgendaView: View {
181181 }
182182 }
183183
184 private var isAgenda: Bool {
184 var isAgenda: Bool {
185185 if case .agenda = agenda.mode { return true }
186186 return false
187187 }
188188
189 private var isMatch: Bool { viewName == Self.match || viewName == Self.todoMatch }
190 private var isSearch: Bool { viewName == Self.search || viewName == Self.todoSearch }
189 var isMatch: Bool { viewName == Self.match || viewName == Self.todoMatch }
190 var isSearch: Bool { viewName == Self.search || viewName == Self.todoSearch }
191191
192192 @Environment(\.orgTheme) private var theme
193193
@@ -209,7 +209,7 @@ struct AgendaView: View {
209209 }
210210
211211 /// The lines in order, as up and down move through them.
212 private func lines(_ groups: [AgendaDayGroup]) -> [Line] {
212 func lines(_ groups: [AgendaDayGroup]) -> [Line] {
213213 guard isAgenda else { return listRows.enumerated().map { Line(id: "list:\($0.offset)", row: $0.element, day: agenda.today) } }
214214 return groups.flatMap { group in
215215 (overdueShown ? group.overdue.enumerated().map { Line(id: "\(group.day):o\($0.offset)", row: $0.element, day: group.day) } : [])
@@ -217,7 +217,7 @@ struct AgendaView: View {
217217 }
218218 }
219219
220 private func line(_ id: String) -> Line? { lines(groups).first { $0.id == id } }
220 func line(_ id: String) -> Line? { lines(groups).first { $0.id == id } }
221221
222222 var body: some View {
223223 let groups = self.groups
@@ -486,234 +486,14 @@ struct AgendaView: View {
486486 }
487487 }
488488
489 // MARK: - Toolbar
490
491 @ToolbarContentBuilder
492 private var toolbar: some ToolbarContent {
493 ToolbarItemGroup(placement: .navigation) {
494 Menu {
495 ForEach(views) { view in Button(view.name) { viewName = view.name } }
496 Divider()
497 Button(Self.match) { viewName = Self.match }
498 Button(Self.todoMatch) { viewName = Self.todoMatch }
499 Button(Self.search) { viewName = Self.search }
500 Button(Self.todoSearch) { viewName = Self.todoSearch }
501 } label: {
502 Label(viewName, systemImage: "calendar").labelStyle(.titleAndIcon)
503 }
504 .help("What the agenda shows")
505 if isMatch || isSearch {
506 TextField(isSearch ? "Phrase or +word -word {regexp}" : "+work-boss|LEVEL>2/!TODO", text: $matchText)
507 .frame(minWidth: 220)
508 .onSubmit { applyView() }
509 }
510 }
511 ToolbarItemGroup {
512 if agenda.isComputing { ProgressView().controlSize(.small) }
513 if isAgenda {
514 Picker("Span", selection: Binding(get: { spanKind }, set: { if let kind = $0 { setSpan(kind) } })) {
515 Text("Day").tag(AgendaSpan?.some(.day))
516 Text("Week").tag(AgendaSpan?.some(.week))
517 Text("Month").tag(AgendaSpan?.some(.month))
518 }
519 .pickerStyle(.segmented)
520 .labelsHidden()
521 .help("Show a day, week or month (v d, v w, v m)")
522 ControlGroup {
523 Button("Earlier", systemImage: "chevron.left") { move(forward: false) }
524 .help("Previous days (b)")
525 Button("Today") { goToday() }
526 .help("Back to today (.)")
527 Button("Later", systemImage: "chevron.right") { move(forward: true) }
528 .help("Next days (f)")
529 }
530 Button("Go to Date", systemImage: "calendar") {
531 pickedDate = Self.date(anchorDay)
532 showingDatePicker = true
533 }
534 .help("Go to a date (j)")
535 .popover(isPresented: $showingDatePicker, arrowEdge: .bottom) {
536 DatePicker("Date", selection: $pickedDate, displayedComponents: .date)
537 .datePickerStyle(.graphical)
538 .labelsHidden()
539 .padding()
540 .onChange(of: pickedDate) {
541 showingDatePicker = false
542 goTo(Days.absolute(pickedDate, calendar: .current))
543 }
544 }
545 }
546 Menu {
547 Button("Filter…") { askFilter("/") }
548 Button("By Tag…") { askFilter("\\") }
549 Button("By Category of Selected Line") { toggleCategoryFilter() }
550 Button("By Regexp…") { askFilter("=") }
551 Button("By Effort…") { askFilter("_") }
552 Divider()
553 Button("Remove Filters") { filter = AgendaFilter() }
554 .disabled(filter.isEmpty)
555 } label: {
556 Label("Filter", systemImage: filter.isEmpty ? "line.3.horizontal.decrease.circle" : "line.3.horizontal.decrease.circle.fill")
557 } primaryAction: {
558 askFilter("/")
559 }
560 .help("Filter the entries (/, \\, <, =, _; | removes)")
561 }
562 }
563
564 /// The span shown, as the window's title: `Week of 5 Oct 2026`.
565 private var title: String {
566 guard isAgenda else { return viewName.replacingOccurrences(of: "…", with: "") }
567 guard let first = agenda.days.first?.day, let last = agenda.days.last?.day else { return "Agenda" }
568 switch spanKind {
569 case .day: return Self.format(first, "EEEE d MMMM yyyy")
570 case .week: return "Week of " + Self.format(first, "d MMM yyyy")
571 case .month: return Self.format(first, "MMMM yyyy")
572 case nil:
573 if first == last { return Self.format(first, "EEEE d MMMM yyyy") }
574 let sameYear = Days.date(first).year == Days.date(last).year
575 return Self.format(first, sameYear ? "d MMM" : "d MMM yyyy") + " – " + Self.format(last, "d MMM yyyy")
576 }
577 }
578
579 // MARK: - Span
580
581 /// The day `v`, `j` and `k` start from: the selected line's, else today when shown, else the first.
582 private var anchorDay: Int {
583 if let selection, let day = Int(selection.prefix { $0 != ":" }) { return day }
584 let days = agenda.days.map(\.day)
585 if days.contains(agenda.today) || days.isEmpty { return agenda.today }
586 return days[0]
587 }
588
589 /// `org-agenda-day-view`, `-week-view`, `-month-view`: the day, the week from Monday
590 /// (`org-agenda-start-on-weekday`), or the month around `anchor`.
591 private func setSpan(_ kind: AgendaSpan, around anchor: Int? = nil) {
592 let anchor = anchor ?? anchorDay
593 spanKind = kind
594 selection = nil
595 switch kind {
596 case .day:
597 agenda.mode = .agenda(span: 1, startOffset: nil)
598 agenda.start = anchor
599 case .week:
600 agenda.mode = .agenda(span: 7, startOffset: nil)
601 agenda.start = anchor - (Days.weekday(anchor) + 6) % 7
602 case .month:
603 let d = Days.date(anchor)
604 let first = Days.absolute(year: d.year, month: d.month, day: 1)
605 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)
606 agenda.mode = .agenda(span: next - first, startOffset: nil)
607 agenda.start = first
608 }
609 }
610
611 private func move(forward: Bool) {
612 selection = nil
613 if spanKind == .month, let first = agenda.days.first?.day {
614 setSpan(.month, around: forward ? first + 31 : first - 1)
615 } else {
616 agenda.shift(forward: forward)
617 }
618 }
619
620 private func goToday() {
621 if let spanKind { setSpan(spanKind, around: agenda.today) } else { agenda.showToday() }
622 selection = nil
623 }
624
625 /// `org-agenda-goto-date`.
626 private func goTo(_ day: Int) {
627 if let spanKind { setSpan(spanKind, around: day) } else { agenda.start = day }
628 selection = nil
629 }
630
631 /// Capture on `day`, as `org-agenda-capture`.
632 private func capture(on day: Int) {
633 commands.capture(on: day)
634 NSApp.activate()
635 openWindow(id: "capture")
636 }
637
638 static func date(_ day: Int) -> Date {
639 let d = Days.date(day)
640 return Calendar.current.date(from: DateComponents(year: d.year, month: d.month, day: d.day)) ?? Date()
641 }
642
643 static func format(_ day: Int, _ pattern: String) -> String {
644 let formatter = DateFormatter()
645 formatter.dateFormat = pattern
646 return formatter.string(from: date(day))
647 }
648
649 static func hhmm(_ date: Date) -> Int {
650 let c = Calendar.current.dateComponents([.hour, .minute], from: date)
651 return (c.hour ?? 0) * 100 + (c.minute ?? 0)
652 }
653
654 @AppStorage("reminders") private var remindersEnabled = true
655
656 /// How far ahead notifications are set, as the design asks the agenda to show.
657 private var reminderStatus: String? {
658 guard let scheduler, remindersEnabled else { return nil }
659 if !scheduler.isAuthorized { return "Notifications are off for orgstar in System Settings." }
660 guard let through = scheduler.scheduledThrough else { return nil }
661 return "Reminders are set through " + through.formatted(.dateTime.weekday(.abbreviated).day().month(.abbreviated).hour().minute()) + "."
662 }
663
664 private var listTitle: String {
665 switch agenda.mode {
666 case .todo(let keywords): "TODO items: \(keywords ?? "all")"
667 case .match(let match, let todoOnly): (todoOnly ? "TODO entries" : "Entries") + " matching \(match)"
668 case .search(let string, let todoOnly): (todoOnly ? "TODO entries" : "Entries") + " containing \(string)"
669 case .agenda: ""
670 }
671 }
672
673 private func loadViews() {
674 let loaded = AgendaViewLoader.load()
675 views = loaded.views
676 message = loaded.problems.first
677 }
678
679 /// The days of a followed timestamp, in the agenda view.
680 private func showRequestedDays() {
681 guard let request = commands.agendaRequest else { return }
682 commands.agendaRequest = nil
683 selection = nil
684 spanKind = nil
685 if viewName != AgendaViewLoader.builtIn[0].name {
686 keepRequestedDays = true
687 viewName = AgendaViewLoader.builtIn[0].name
688 }
689 agenda.mode = .agenda(span: request.days, startOffset: nil)
690 agenda.start = request.start
691 }
692
693 private func applyView() {
694 if keepRequestedDays { return keepRequestedDays = false }
695 selection = nil
696 spanKind = nil
697 agenda.start = nil
698 switch viewName {
699 case Self.match, Self.todoMatch:
700 let match = matchText.trimmingCharacters(in: .whitespaces)
701 guard !match.isEmpty else { return }
702 agenda.mode = .match(match, todoOnly: viewName == Self.todoMatch)
703 case Self.search, Self.todoSearch:
704 guard matchText.contains(where: { !$0.isWhitespace }) else { return }
705 agenda.mode = .search(matchText, todoOnly: viewName == Self.todoSearch)
706 default:
707 if let view = views.first(where: { $0.name == viewName }) { agenda.mode = view.mode }
708 }
709 }
489 @AppStorage("reminders") var remindersEnabled = true
710490
711491 // MARK: - Items
712492
713 private func item(_ id: String) -> AgendaItem? { line(id)?.row.item }
493 func item(_ id: String) -> AgendaItem? { line(id)?.row.item }
714494
715495 /// Return and double click: the entry in the main window, or the event in Calendar.
716 private func open(_ line: Line) {
496 func open(_ line: Line) {
717497 selection = line.id
718498 if let event = line.row.event { openEvent(event) } else { jump(line.id) }
719499 }
@@ -727,552 +507,11 @@ struct AgendaView: View {
727507 }
728508
729509 /// Moves the selection by `step` lines.
730 private func step(_ step: Int) {
510 func step(_ step: Int) {
731511 let all = lines(groups)
732512 guard !all.isEmpty else { return }
733513 let index = selection.flatMap { id in all.firstIndex { $0.id == id } }
734514 let next = index.map { min(max($0 + step, 0), all.count - 1) } ?? (step > 0 ? 0 : all.count - 1)
735515 selection = all[next].id
736516 }
737
738 // MARK: - Filters
739
740 /// The tags and categories on the view's lines, which filter words are read against.
741 private var shown: (tags: Set<String>, categories: Set<String>) {
742 let items = (isAgenda ? agenda.days.flatMap(\.items) : agenda.list).filter { $0.path != nil }
743 return (Set(items.flatMap(\.tags)), Set(items.map(\.category)))
744 }
745
746 private func askFilter(_ kind: Character) {
747 switch kind {
748 case "/": filterText = filter.description
749 default: filterText = ""
750 }
751 let title = switch kind {
752 case "/": "Filter [+cat-tag<0:10-/regexp/]:"
753 case "\\": "Tag filter (+tag-tag):"
754 case "=": "Regexp filter (-re to drop):"
755 default: "Effort filter (<0:30, >1:00, =1:00):"
756 }
757 filterPrompt = (title, kind)
758 }
759
760 private func applyFilter() {
761 guard let kind = filterPrompt?.kind else { return }
762 filterPrompt = nil
763 let text = filterText.trimmingCharacters(in: .whitespaces)
764 var current = filter
765 switch kind {
766 case "/":
767 let (parsed, ignored) = AgendaFilter().parse(text, tags: shown.tags, categories: shown.categories)
768 current = parsed
769 if !ignored.isEmpty { message = "\(ignored.joined(separator: " ")) ignored: no line has that tag or category" }
770 case "\\":
771 // Every word as a tag.
772 current.tags = AgendaFilter().parse(text, tags: Set(text.split(whereSeparator: { "+- ".contains($0) }).map(String.init)), categories: []).filter.tags
773 case "=":
774 current.regexps = text.isEmpty ? [] : [text.hasPrefix("-") || text.hasPrefix("+") ? text : "+" + text]
775 default:
776 current.efforts = text.isEmpty ? [] : ["+" + text]
777 }
778 filter = current
779 selection = nil
780 }
781
782 /// `<`: keep only the selected line's category, or drop that filter.
783 private func toggleCategoryFilter() {
784 if !filter.categories.isEmpty {
785 filter.categories = []
786 } else if let selection, let item = item(selection) {
787 filter.categories = ["+" + item.category]
788 } else {
789 message = "No entry selected"
790 }
791 }
792
793 /// The entry in the main window; with `focus` false the agenda keeps the keys (SPC).
794 private func jump(_ id: String, focus: Bool = true) {
795 guard let item = item(id), let path = item.path, let offset = item.markerOffset ?? item.headingOffset else { return }
796 commands.jump(path: path, offset: offset)
797 if focus { openWindow(id: "main") }
798 }
799
800 // MARK: - Commands
801
802 private func handle(_ press: KeyPress) -> KeyPress.Result {
803 let control = press.modifiers.contains(.control)
804 // `C-x` and friends arrive as control characters or as letters with control.
805 func isControl(_ letter: String, _ code: String) -> Bool { control && (press.characters == letter || press.characters == code) }
806 if let pending = prefix {
807 prefix = nil
808 if pending == "v" {
809 switch press.characters {
810 case "d" where isAgenda: setSpan(.day)
811 case "w" where isAgenda: setSpan(.week)
812 case "m" where isAgenda: setSpan(.month)
813 default: message = "v \(press.characters) is undefined"
814 }
815 if message == "v-" { message = nil }
816 return .handled
817 }
818 if pending == "C-c C-x" {
819 if isControl("s", "\u{13}") { archive() } else { message = "C-c C-x \(press.characters) is undefined" }
820 return .handled
821 }
822 if isControl("s", "\u{13}") {
823 run(SetPlanning(deadline: false))
824 } else if isControl("d", "\u{04}") {
825 run(SetPlanning(deadline: true))
826 } else if isControl("q", "\u{11}") {
827 run(SetTags())
828 } else if isControl("t", "\u{14}") {
829 run(TodoCycle())
830 } else if isControl("w", "\u{17}") {
831 refile(marked: false)
832 } else if isControl("x", "\u{18}") {
833 prefix = "C-c C-x"
834 message = "C-c C-x-"
835 } else if press.characters == "$" {
836 archive()
837 } else {
838 message = "C-c \(press.characters) is undefined"
839 }
840 return .handled
841 }
842 if isControl("c", "\u{03}") {
843 prefix = "C-c"
844 message = "C-c-"
845 return .handled
846 }
847 if isControl("n", "\u{0e}") || (press.key == .downArrow && press.modifiers.isEmpty) {
848 step(1)
849 return .handled
850 }
851 if isControl("p", "\u{10}") || (press.key == .upArrow && press.modifiers.isEmpty) {
852 step(-1)
853 return .handled
854 }
855 if press.key == .return || press.key == .tab, let selection, let line = line(selection) {
856 open(line)
857 return .handled
858 }
859 if press.key == .space, let selection {
860 jump(selection, focus: false)
861 return .handled
862 }
863 if press.modifiers == .shift, press.key == .rightArrow || press.key == .leftArrow {
864 run(ShiftTimestampDay(later: press.key == .rightArrow), atMarker: true)
865 return .handled
866 }
867 guard press.modifiers.subtracting(.shift).isEmpty else { return .ignored }
868 switch press.characters {
869 case "n": step(1)
870 case "p": step(-1)
871 case "f" where isAgenda: move(forward: true)
872 case "b" where isAgenda: move(forward: false)
873 case "." where isAgenda: goToday()
874 case "j" where isAgenda:
875 pickedDate = Self.date(anchorDay)
876 showingDatePicker = true
877 case "v" where isAgenda:
878 prefix = "v"
879 message = "v-"
880 case "d" where isAgenda: setSpan(.day)
881 case "w" where isAgenda: setSpan(.week)
882 case "k" where isAgenda: capture(on: anchorDay)
883 case "s":
884 commands.run("app.save-all")
885 message = "Saved"
886 case "/", "\\", "=", "_": askFilter(press.characters.first!)
887 case "<": toggleCategoryFilter()
888 case "|":
889 filter = AgendaFilter()
890 message = "Filters removed"
891 case "l" where isAgenda:
892 logMode.toggle()
893 message = logMode ? "Log mode on" : "Log mode off"
894 case "g", "r":
895 loadViews()
896 tick += 1
897 case "I": clockIn()
898 case "O": message = clock.clockOut(session)
899 case "X": message = clock.clockOut(session, cancel: true)
900 case "$": archive()
901 case "m": mark(true)
902 case "u": mark(false)
903 case "U":
904 marked = []
905 message = "No entries marked"
906 case "B": askBulk()
907 case "t": run(TodoCycle())
908 case "+": run(PriorityUp())
909 case "-": run(PriorityDown())
910 case ",": run(SetPriority())
911 case ":": run(SetTags())
912 default: return .ignored
913 }
914 return .handled
915 }
916
917 // MARK: - Clock, refile, archive, bulk
918
919 private var selectedEntry: EntryRef? { selection.flatMap(item).flatMap(EntryRef.init) }
920
921 private func clockIn() {
922 guard let entry = selectedEntry, let offset = session.locateHeading(path: entry.path, line: entry.line, near: entry.offset) else {
923 message = "No entry selected"
924 return
925 }
926 let paths = workspace.files.filter { $0.kind == .org }.map(\.path)
927 Task {
928 let outcome = await clock.clockIn(session, target: .entry(path: entry.path, offset: offset), paths: paths, ask: commands.askClock)
929 if let jump = outcome.jump { commands.jump(path: jump.path, offset: jump.offset) }
930 message = outcome.messages.last { !$0.isEmpty }
931 tick += 1
932 }
933 }
934
935 private func archive() {
936 guard let entry = selectedEntry, let offset = session.locateHeading(path: entry.path, line: entry.line, near: entry.offset) else {
937 message = "No entry selected"
938 return
939 }
940 message = session.archive(from: (entry.path, offset))
941 tick += 1
942 }
943
944 /// Refiles the selected entry, or with `marked` the marked ones, to a target asked for in
945 /// the main window, where the list of targets is searchable.
946 private func refile(marked bulk: Bool) {
947 let entries = bulk ? marked : selectedEntry.map { [$0] } ?? []
948 guard !entries.isEmpty else {
949 message = "No entry selected"
950 return
951 }
952 let targets = workspace.refileTargets(openPath: session.path, document: session.document)
953 commands.ask(Prompt(key: "refile", message: "Refile to:", choices: targets.map(\.label))) { answer in
954 guard let answer, targets.contains(where: { $0.label == answer }) else { return }
955 message = eachEntry(entries) { entry, offset in
956 // Targets in the entry's own file from its text now, as earlier moves shift them.
957 let document = session.openDocuments.first { $0.path == entry.path }?.document
958 ?? FileManager.default.contents(atPath: entry.path).map { DocumentState(bytes: [UInt8]($0)) }
959 guard let target = workspace.refileTargets(openPath: entry.path, document: document).first(where: { $0.label == answer }) else {
960 return "Can't find \(answer) any more."
961 }
962 return session.refile(to: target, from: (entry.path, offset))
963 }
964 if bulk { marked = [] }
965 tick += 1
966 }
967 openWindow(id: "main")
968 }
969
970 /// Runs `action` on each entry, finding it again first: later entries in a file first, so
971 /// earlier ones keep their place. Returns the last message.
972 private func eachEntry(_ entries: [EntryRef], _ action: (EntryRef, Int) -> String?) -> String? {
973 var last: String?
974 var failed = 0
975 for entry in entries.sorted(by: { ($0.path, $1.offset) < ($1.path, $0.offset) }) {
976 guard let offset = session.locateHeading(path: entry.path, line: entry.line, near: entry.offset) else {
977 failed += 1
978 continue
979 }
980 last = action(entry, offset)
981 }
982 return failed > 0 ? "\(failed) marked \(failed == 1 ? "entry" : "entries") changed and \(failed == 1 ? "was" : "were") skipped" : last
983 }
984
985 private func mark(_ on: Bool) {
986 guard let entry = selectedEntry else {
987 message = "No entry selected"
988 return
989 }
990 if on {
991 if !marked.contains(entry) { marked.append(entry) }
992 } else {
993 marked.removeAll { $0 == entry }
994 }
995 message = "\(marked.count) marked"
996 }
997
998 /// `B`: an action for every marked entry.
999 private func askBulk() {
1000 guard !marked.isEmpty else {
1001 message = "No entries are marked"
1002 return
1003 }
1004 textPrompt = TextPrompt(title: "Bulk action on \(marked.count): [$] archive [r] refile [t] TODO state [+] tag [-] untag [s] schedule [d] deadline") { answer in
1005 switch answer.trimmingCharacters(in: .whitespaces) {
1006 case "$": bulk { session.archive(from: ($0.path, $1)) }
1007 case "r": refile(marked: true)
1008 case "t":
1009 textPrompt = TextPrompt(title: "TODO state (empty for none):") { keyword in
1010 let word = keyword.trimmingCharacters(in: .whitespaces)
1011 bulk { performAt($0, $1, SetTodo(keyword: word.isEmpty ? nil : word)) }
1012 }
1013 case "+", "-":
1014 let on = answer.trimmingCharacters(in: .whitespaces) == "+"
1015 textPrompt = TextPrompt(title: on ? "Tag to add:" : "Tag to remove:") { tag in
1016 let tag = tag.trimmingCharacters(in: .whitespaces)
1017 guard !tag.isEmpty else { return }
1018 bulk { performAt($0, $1, ToggleTag(tag: tag, on: on)) }
1019 }
1020 case "s", "d":
1021 let deadline = answer.trimmingCharacters(in: .whitespaces) == "d"
1022 textPrompt = TextPrompt(title: deadline ? "Deadline (+2d, fri, 2026-10-12):" : "Schedule (+2d, fri, 2026-10-12):") { date in
1023 bulk { performAt($0, $1, SetPlanning(deadline: deadline), answers: ["date": date]) }
1024 }
1025 default:
1026 message = "No bulk action \(answer)"
1027 }
1028 }
1029 }
1030
1031 private func bulk(_ action: (EntryRef, Int) -> String?) {
1032 message = eachEntry(marked, action) ?? "Done with \(marked.count) entries"
1033 marked = []
1034 tick += 1
1035 }
1036
1037 /// Runs `command` at the heading at `offset`, as `run` does for the selection.
1038 private func performAt(_ entry: EntryRef, _ offset: Int, _ command: any OrgCommand, answers: [String: String] = [:]) -> String? {
1039 switch session.perform(command, path: entry.path, at: offset, expect: (offset, entry.line), answers: answers) {
1040 case .failed(let text): text
1041 case .prompt: "\(command.title) needs an answer; run it on the entry itself"
1042 default: nil
1043 }
1044 }
1045
1046 /// Runs `command` on the selected entry, at its heading or, with `atMarker`, at the
1047 /// timestamp the entry is listed for.
1048 private func run(_ command: any OrgCommand, atMarker: Bool = false, answers: [String: String] = [:], itemID: String? = nil) {
1049 guard let id = itemID ?? selection, let item = item(id), let path = item.path, let start = item.headingOffset else {
1050 message = "No entry selected"
1051 return
1052 }
1053 if atMarker, ![.deadline, .upcomingDeadline, .scheduled, .pastScheduled, .timestamp].contains(item.kind) {
1054 message = "Only dated entries can move"
1055 return
1056 }
1057 let offset = atMarker ? (item.markerOffset ?? start) : start
1058 let step = session.perform(command, path: path, at: offset, expect: item.headingLine.map { (start, $0) }, answers: answers)
1059 switch step {
1060 case .prompt(let request):
1061 promptText = request.initial
1062 prompt = PendingPrompt(prompt: request, command: command, atMarker: atMarker, answers: answers, itemID: id)
1063 case .failed(let text):
1064 message = text
1065 tick += 1
1066 case .external:
1067 message = "Not available from the agenda"
1068 case .commit:
1069 message = nil
1070 tick += 1
1071 }
1072 }
1073
1074 private func answerPrompt() {
1075 guard let pending = prompt else { return }
1076 prompt = nil
1077 var answers = pending.answers
1078 answers[pending.prompt.key] = promptText
1079 run(pending.command, atMarker: pending.atMarker, answers: answers, itemID: pending.itemID)
1080 }
1081}
1082
1083/// One agenda line: the time or status over an icon, the category above the title, progress
1084/// and tags after it, and the TODO keyword and priority at the end.
1085struct AgendaRowView: View {
1086 let row: AgendaRow
1087 /// The agenda day the row is on, for habit graphs.
1088 var day: Int
1089 var showsGutter = true
1090 var selected = false
1091 var hovered = false
1092 /// Marked for a bulk action.
1093 var marked = false
1094 @Environment(\.orgTheme) private var theme
1095
1096 static let gutterWidth: CGFloat = 92
1097
1098 var body: some View {
1099 HStack(alignment: .center, spacing: 12) {
1100 if showsGutter { gutter }
1101 VStack(alignment: .leading, spacing: 2) {
1102 if !row.category.isEmpty { categoryLine }
1103 titleLine
1104 }
1105 .layoutPriority(1)
1106 Spacer(minLength: 8)
1107 if let habit = row.item?.habit {
1108 HabitGraph(cells: habit.graph(today: day), theme: theme)
1109 }
1110 if let todo = row.todo {
1111 let color = theme.dynamic(row.isDone ? .systemGreen : .systemRed) { [theme, row] in theme.todoColor(todo, isDone: row.isDone, dark: $0) }
1112 Text(todo)
1113 .font(.system(size: 10, weight: .bold))
1114 .foregroundStyle(color)
1115 .padding(.horizontal, 7)
1116 .padding(.vertical, 2)
1117 .background(Capsule().fill(color.opacity(0.14)))
1118 .fixedSize()
1119 }
1120 priorityBadge
1121 .frame(width: 18)
1122 }
1123 .padding(.horizontal, 16)
1124 .padding(.vertical, 6)
1125 .frame(minHeight: 44)
1126 // `org-agenda-dim-blocked-tasks`.
1127 .opacity(row.isBlocked ? 0.5 : 1)
1128 .background {
1129 RoundedRectangle(cornerRadius: 6)
1130 .fill(selected ? theme.color("selection") ?? Color.accentColor.opacity(0.2) : hovered ? Color.primary.opacity(0.05) : .clear)
1131 .padding(.horizontal, 6)
1132 }
1133 .overlay(alignment: .leading) {
1134 if marked {
1135 Capsule().fill(theme.color("agenda-today") ?? .accentColor).frame(width: 3).padding(.vertical, 8).padding(.leading, 8)
1136 }
1137 }
1138 .accessibilityElement(children: .combine)
1139 }
1140
1141 private var statusColor: Color {
1142 theme.dynamic(.secondaryLabelColor) { [theme, row] in theme.statusColor(row.status, dark: $0) }
1143 }
1144
1145 private var gutter: some View {
1146 VStack(alignment: .leading, spacing: 3) {
1147 Text(row.gutter)
1148 .font(.system(size: 12, weight: row.status == .overdue || row.status == .dueSoon ? .semibold : .regular).monospacedDigit())
1149 .foregroundStyle(statusColor)
1150 .lineLimit(1)
1151 .minimumScaleFactor(0.8)
1152 if let symbol {
1153 Image(systemName: symbol)
1154 .font(.system(size: row.icon == .event ? 8 : 10, weight: .semibold))
1155 .foregroundStyle(iconColor)
1156 .frame(height: 12)
1157 }
1158 }
1159 .frame(width: Self.gutterWidth, alignment: .leading)
1160 }
1161
1162 /// Overdue entries show a warning, done ones a check, as the status says first.
1163 private var symbol: String? {
1164 guard let icon = row.icon else { return nil }
1165 if row.status == .overdue { return "exclamationmark.circle.fill" }
1166 if row.status == .done { return "checkmark.circle.fill" }
1167 switch icon {
1168 case .scheduled: return "calendar"
1169 case .deadline: return "flag.fill"
1170 case .habit: return "repeat"
1171 case .event: return "circle.fill"
1172 case .timestamp: return row.start == nil ? "calendar" : "clock"
1173 }
1174 }
1175
1176 private var iconColor: Color {
1177 if let event = row.event { return theme.dynamic(.systemPurple) { [theme] in theme.eventColor(event, dark: $0) } }
1178 return row.status == .normal ? Color.secondary.opacity(0.8) : statusColor
1179 }
1180
1181 private var categoryLine: some View {
1182 HStack(spacing: 5) {
1183 Circle()
1184 .fill(row.event.map { event in theme.dynamic(.systemPurple) { [theme] in theme.eventColor(event, dark: $0) } }
1185 ?? theme.dynamic { [theme, row] in theme.categoryColor(row.category, dark: $0) })
1186 .frame(width: 6, height: 6)
1187 Text(row.category)
1188 .font(.system(size: 11))
1189 .foregroundStyle(theme.color("agenda-category") ?? .secondary)
1190 .lineLimit(1)
1191 }
1192 }
1193
1194 private var titleLine: some View {
1195 HStack(spacing: 6) {
1196 Text(row.title.isEmpty ? " " : row.title)
1197 .font(.system(size: 13))
1198 .strikethrough(row.isDone)
1199 .foregroundStyle(row.isDone ? AnyShapeStyle(.secondary) : AnyShapeStyle(theme.color("foreground") ?? .primary))
1200 .lineLimit(1)
1201 .truncationMode(.tail)
1202 ForEach([row.progress, row.detail].compactMap { $0 }, id: \.self) { progress in
1203 Text(progress)
1204 .font(.system(size: 10, weight: .semibold).monospacedDigit())
1205 .foregroundStyle(.secondary)
1206 .padding(.horizontal, 6)
1207 .padding(.vertical, 1)
1208 .background(Capsule().fill(Color.secondary.opacity(0.14)))
1209 .fixedSize()
1210 }
1211 ForEach(row.tags, id: \.self) { tag in
1212 Text(tag)
1213 .font(.system(size: 10, weight: .medium))
1214 .foregroundStyle(theme.color("tags") ?? .secondary)
1215 .padding(.horizontal, 6)
1216 .padding(.vertical, 1)
1217 .background(Capsule().strokeBorder((theme.color("tags") ?? .secondary).opacity(0.35), lineWidth: 0.5))
1218 .fixedSize()
1219 }
1220 }
1221 }
1222
1223 @ViewBuilder
1224 private var priorityBadge: some View {
1225 if let priority = row.priority {
1226 let color = theme.dynamic(.systemOrange) { [theme] in theme.priorityColor(priority, dark: $0) }
1227 Text(priority)
1228 .font(.system(size: 10, weight: .bold))
1229 .foregroundStyle(color)
1230 .frame(width: 18, height: 18)
1231 .background(Circle().fill(color.opacity(0.14)))
1232 .overlay(Circle().strokeBorder(color.opacity(0.6), lineWidth: 1))
1233 .help("Priority \(priority)")
1234 } else {
1235 Color.clear.frame(width: 18, height: 18)
1236 }
1237 }
1238}
1239
1240/// org-habit's consistency graph: a cell per day, `*` where the habit was done, `!` today.
1241struct HabitGraph: View {
1242 let cells: [Habit.Cell]
1243 var theme: ThemeSpec = .default
1244
1245 var body: some View {
1246 HStack(spacing: 1) {
1247 ForEach(cells, id: \.day) { cell in
1248 Text(String(cell.glyph))
1249 .font(.system(size: 9, weight: .bold, design: .monospaced))
1250 .frame(width: 8, height: 14)
1251 .background(color(cell.face))
1252 .help(Self.label(cell))
1253 }
1254 }
1255 .accessibilityElement(children: .ignore)
1256 .accessibilityLabel("Done \(cells.filter { $0.glyph == "*" }.count) of the last \(Habit.precedingDays) days")
1257 }
1258
1259 /// Due-state colors, lighter for days to come, as org-habit's faces.
1260 func color(_ face: Habit.Face) -> Color {
1261 func themed(_ key: String, _ fallback: Color) -> Color { theme.color(key) ?? fallback }
1262 switch face {
1263 case .clear: return themed("habit-clear", .blue).opacity(0.7)
1264 case .clearFuture: return themed("habit-clear", .blue).opacity(0.35)
1265 case .ready: return themed("habit-ready", .green).opacity(0.75)
1266 case .readyFuture: return themed("habit-ready", .green).opacity(0.35)
1267 case .alert: return themed("habit-alert", .yellow).opacity(0.85)
1268 case .alertFuture: return themed("habit-alert", .yellow).opacity(0.4)
1269 case .overdue: return themed("habit-overdue", .red).opacity(0.75)
1270 case .overdueFuture: return themed("habit-overdue", .red).opacity(0.35)
1271 }
1272 }
1273
1274 static func label(_ cell: Habit.Cell) -> String {
1275 let date = Days.date(cell.day)
1276 return String(format: "%04d-%02d-%02d", date.year, date.month, date.day) + (cell.glyph == "*" ? " DONE" : "")
1277 }
1278517}