Sources/OrgstarMobile/AgendaScreen.swift
927 lines · 41486 bytes
1#if os(iOS)
2import OrgApp
3import OrgCore
4import OrgDocument
5import OrgPresentation
6import SwiftUI
7
8/// The agenda over the workspace's agenda files: the day/week view, the TODO list, tag and
9/// property matches, text search and the views in `views.toml`, with Org's filters and the
10/// agenda's actions on each entry.
11struct AgendaScreen: View, Equatable {
12 let workspace: WorkspaceModel
13 let session: DocumentSession
14 @Bindable var agenda: AgendaModel
15 let scheduler: ReminderScheduler
16 @State private var message: String?
17 @Environment(ClockModel.self) private var clock
18 @Environment(MobileModel.self) private var model
19 @Environment(\.colorScheme) private var colorScheme
20 @Environment(\.openURL) private var openURL
21 @State private var tick = 0
22 /// The time the now line shows, kept to the minute while the agenda is open.
23 @State private var now = Date()
24 @State private var views = AgendaViewLoader.builtIn
25 @State private var viewName = "Agenda"
26 @State private var filter = AgendaFilter()
27 @State private var showingFilter = false
28 @State private var asking: Asking?
29 @State private var prompt: EditorScreen.PromptRequest?
30 @State private var refiling: AgendaItem?
31 @State private var archiving: AgendaItem?
32 /// The day, week or month shown; nil for `org-agenda-span` and `org-agenda-start-day`.
33 @State private var range: SpanRange?
34 /// The mode `range` set, to notice when something else changes the view.
35 @State private var rangeMode: AgendaMode?
36 @State private var jumping = false
37 @State private var rescheduling: AgendaRow?
38 @AppStorage("agendaOverdueExpanded") private var overdueExpanded = true
39 @State private var done = 0
40 @State private var moved = 0
41 /// `org-agenda-log-mode`: closed entries and clocked time on each day.
42 @State private var logMode = false
43
44 /// A match typed for the tag and property view, or a search string.
45 private enum Asking: Identifiable {
46 case match, search
47 var id: Self { self }
48 }
49
50 enum SpanRange: String, CaseIterable, Identifiable {
51 case day, week, month
52 var id: String { rawValue }
53 var title: String { rawValue.capitalized }
54 }
55
56 private struct Key: Equatable {
57 var files: Int
58 var changed: Int?
59 var edits: Int
60 var tick: Int
61 var mode: AgendaMode
62 var start: Int?
63 var span: Int
64 var startOffset: Int
65 var subfolders: Bool
66 var settings: Int
67 var logMode: Bool
68 }
69
70 /// The same models: the root redrawing for navigation leaves the list alone.
71 nonisolated static func == (a: Self, b: Self) -> Bool {
72 a.workspace === b.workspace && a.session === b.session && a.agenda === b.agenda && a.scheduler === b.scheduler
73 }
74
75 private var isDark: Bool { colorScheme == .dark }
76 private var theme: ThemeSpec { model.theme }
77
78 var body: some View {
79 List {
80 // With no folders the empty state stands alone, not over a column of empty days.
81 if workspace.rootPaths.isEmpty {
82 } else if case .agenda = agenda.mode {
83 let _ = model.settingsVersion
84 ForEach(Perf.measure("agenda.groups") { agenda.groups(showAllDates: OrgPreferences.agendaShowAllDates(), filter: filter) }) { group in
85 Section {
86 day(group)
87 } header: {
88 header(group)
89 }
90 }
91 } else {
92 let rows = agenda.list.filter(filter.keeps).compactMap { AgendaRow(item: $0, day: agenda.today, today: agenda.today) }
93 if rows.isEmpty, !agenda.isComputing { Text("No entries").foregroundStyle(.secondary) }
94 ForEach(rows) { item in Deferred { row(item, day: agenda.today) } }
95 }
96 if let reminderStatus {
97 Section { } footer: { Text(reminderStatus) }
98 }
99 }
100 .listStyle(.insetGrouped)
101 .listSectionSpacing(.compact)
102 // The now line is shorter than a row.
103 .environment(\.defaultMinListRowHeight, 16)
104 .navigationTitle(title)
105 .navigationBarTitleDisplayMode(.inline)
106 .sensoryFeedback(.success, trigger: done)
107 .sensoryFeedback(.impact(weight: .light), trigger: moved)
108 .onChange(of: agenda.start) {
109 // Days a followed timestamp asked for.
110 if agenda.start != nil, case .agenda = agenda.mode { viewName = "Agenda" }
111 }
112 .onChange(of: agenda.mode) {
113 if agenda.mode != rangeMode { range = nil }
114 }
115 .overlay {
116 if workspace.rootPaths.isEmpty {
117 ContentUnavailableView("No folders", systemImage: "folder", description: Text("Add a folder of org files under Folders."))
118 }
119 }
120 .safeAreaInset(edge: .bottom) {
121 if !workspace.rootPaths.isEmpty { bottomBar }
122 }
123 .toolbar {
124 ToolbarItem(placement: .topBarLeading) {
125 Menu {
126 ForEach(views) { definition in
127 Button(definition.name) { show(definition) }
128 }
129 Button("Tags and Properties…") { asking = .match }
130 Button("Search…") { asking = .search }
131 } label: {
132 Label("Views", systemImage: "list.bullet.rectangle")
133 }
134 }
135 }
136 .sheet(isPresented: $showingFilter) {
137 FilterSheet(filter: $filter, items: shownItems)
138 }
139 .sheet(isPresented: $jumping) {
140 DateSheet(title: "Go to Date", action: "Go", initial: date(firstDay)) { picked in
141 jumping = false
142 if let picked { jump(to: Days.absolute(picked, calendar: .current)) }
143 }
144 }
145 .sheet(item: $rescheduling) { row in
146 DateSheet(title: row.icon == .deadline ? "Deadline" : "Schedule", action: "Set", initial: date(row.planningDay ?? agenda.today)) { picked in
147 rescheduling = nil
148 if let picked, let item = row.item { reschedule(row, item, to: Days.absolute(picked, calendar: .current)) }
149 }
150 }
151 .sheet(item: $asking) { kind in
152 if kind == .search {
153 PromptSheet(prompt: Prompt(key: "search", message: "Search: a phrase, or +word -word {regexp}; * for headlines, ! for TODO entries")) { answer in
154 asking = nil
155 guard let answer, answer.contains(where: { !$0.isWhitespace }) else { return }
156 agenda.mode = .search(answer, todoOnly: false)
157 viewName = answer
158 }
159 } else {
160 PromptSheet(prompt: Prompt(key: "match", message: "Match: tags and properties, as +work-home or TODO=\"WAIT\"")) { answer in
161 asking = nil
162 guard let answer, !answer.isEmpty else { return }
163 agenda.mode = .match(answer, todoOnly: false)
164 viewName = answer
165 }
166 }
167 }
168 .sheet(item: $prompt) { request in
169 PromptSheet(prompt: request.prompt) { answer in
170 prompt = nil
171 request.reply(answer)
172 }
173 }
174 .sheet(item: $refiling) { item in
175 RefileSheet(targets: workspace.refileTargets(openPath: session.path, document: session.document)) { target in
176 refiling = nil
177 if let target { refile(item, to: target) }
178 }
179 }
180 .confirmationDialog("Archive this entry?", isPresented: Binding { archiving != nil } set: { if !$0 { archiving = nil } }, titleVisibility: .visible) {
181 Button("Archive", role: .destructive) {
182 if let item = archiving { archive(item) }
183 archiving = nil
184 }
185 } message: {
186 Text(archiving?.text ?? "")
187 }
188 .refreshable {
189 await workspace.refresh()
190 await agenda.refresh(open: session.openTexts)
191 }
192 .task {
193 let loaded = AgendaViewLoader.load()
194 views = loaded.views
195 if let problem = loaded.problems.first { message = problem }
196 }
197 // The now line moves each minute; a new day refreshes the statuses.
198 .task {
199 while !Task.isCancelled {
200 let next = Calendar.current.nextDate(after: Date(), matching: DateComponents(second: 0), matchingPolicy: .nextTime) ?? Date().addingTimeInterval(60)
201 try? await Task.sleep(for: .seconds(next.timeIntervalSinceNow))
202 now = Date()
203 if Days.absolute(now, calendar: .current) != agenda.today { tick += 1 }
204 }
205 }
206 // Calendar access is asked for when calendar-events is turned on.
207 .task(id: model.settingsVersion) {
208 guard OrgPreferences.calendarEvents(), !CalendarEvents.isAuthorized else { return }
209 if await model.calendarEvents.requestAccess() { tick += 1 }
210 }
211 .background { Refresher(workspace: workspace, session: session, agenda: agenda, model: model, tick: tick, logMode: logMode) }
212 }
213
214 /// Refreshes the agenda when files, edits or settings change. Its own view, so that what it
215 /// watches redraws only it, not the whole list.
216 private struct Refresher: View {
217 let workspace: WorkspaceModel
218 let session: DocumentSession
219 let agenda: AgendaModel
220 let model: MobileModel
221 let tick: Int
222 let logMode: Bool
223
224 var body: some View {
225 Color.clear
226 .task(id: Key(files: workspace.files.count, changed: workspace.changedFile?.version, edits: session.editVersion, tick: tick,
227 mode: agenda.mode, start: agenda.start, span: agenda.span, startOffset: agenda.startOffset,
228 subfolders: agenda.includeSubfolders, settings: model.settingsVersion, logMode: logMode)) {
229 // Changes come in bursts (a folder scan, typing); a newer one cancels this wait.
230 try? await Task.sleep(for: .milliseconds(150))
231 guard !Task.isCancelled else { return }
232 agenda.options.logMode = logMode
233 await agenda.refresh(open: session.openTexts)
234 }
235 }
236 }
237
238 private var shownItems: [AgendaItem] {
239 if case .agenda = agenda.mode { return agenda.days.flatMap(\.items).filter(\.isEntry) }
240 return agenda.list
241 }
242
243 private func show(_ definition: AgendaViewDefinition) {
244 viewName = definition.name
245 agenda.mode = definition.mode
246 }
247
248 /// How far ahead notifications are set, as the design asks the agenda to show: iOS keeps
249 /// at most 64, and sets no more while the app isn't opened.
250 private var reminderStatus: String? {
251 guard OrgPreferences.reminders() else { return nil }
252 if !scheduler.isAuthorized { return "Notifications are off for orgstar in Settings." }
253 guard let through = scheduler.scheduledThrough else { return nil }
254 return "Reminders are set through " + through.formatted(.dateTime.weekday(.abbreviated).day().month(.abbreviated).hour().minute())
255 + ". Open orgstar to set later ones."
256 }
257
258 // MARK: - Days
259
260 private func day(_ group: AgendaDayGroup) -> some View {
261 Group {
262 if group.isToday, !group.overdue.isEmpty {
263 Button {
264 withAnimation { overdueExpanded.toggle() }
265 } label: {
266 HStack(spacing: 6) {
267 Image(systemName: "chevron.right")
268 .font(.caption.weight(.semibold))
269 .rotationEffect(.degrees(overdueExpanded ? 90 : 0))
270 Text("Overdue").font(.subheadline.weight(.semibold))
271 Text("\(group.overdue.count)").font(.subheadline.monospacedDigit())
272 Spacer()
273 }
274 .foregroundStyle(themed(theme.statusColor(.overdue, dark: isDark), .red))
275 .contentShape(Rectangle())
276 }
277 .buttonStyle(.plain)
278 if overdueExpanded {
279 ForEach(group.overdue) { item in Deferred { row(item, day: group.day) } }
280 }
281 }
282 if group.isEmpty {
283 Text("Nothing scheduled").font(.subheadline).foregroundStyle(.secondary)
284 }
285 // One view per element, so the list counts its rows without building them.
286 ForEach(lines(group)) { line in
287 switch line {
288 case .now: NowLine(time: now, color: todayColor)
289 case .row(let item): Deferred { row(item, day: group.day) }
290 }
291 }
292 }
293 }
294
295 /// A day's rows, with the now line among them as a line of its own.
296 private enum DayLine: Identifiable {
297 case now
298 case row(AgendaRow)
299
300 var id: String {
301 if case .row(let row) = self { return row.id }
302 return "now"
303 }
304 }
305
306 private func lines(_ group: AgendaDayGroup) -> [DayLine] {
307 var lines = group.rows.map(DayLine.row)
308 if let at = nowIndex(group) { lines.insert(.now, at: at) }
309 return lines
310 }
311
312 private func nowIndex(_ group: AgendaDayGroup) -> Int? {
313 let c = Calendar.current.dateComponents([.hour, .minute], from: now)
314 return group.nowIndex(now: (c.hour ?? 0) * 100 + (c.minute ?? 0))
315 }
316
317 private var todayColor: Color { themed(theme.color("agenda-today", dark: isDark), .accentColor) }
318
319 private func header(_ group: AgendaDayGroup) -> some View {
320 let day = date(group.day).formatted(.dateTime.weekday(.abbreviated).day().month(.abbreviated))
321 let color = group.isToday ? todayColor : group.day < agenda.today ? Color.secondary : themed(theme.color("agenda-date", dark: isDark), .primary)
322 return HStack(alignment: .firstTextBaseline) {
323 Text(group.relativeName(today: agenda.today).map { $0 + " · " + day } ?? day)
324 .font(.subheadline.weight(group.isToday ? .bold : .semibold))
325 .foregroundStyle(color)
326 Spacer()
327 Button("Add to \(day)", systemImage: "plus.circle") { model.captureRequest = CaptureRequest(day: group.day) }
328 .labelStyle(.iconOnly)
329 .font(.body)
330 .foregroundStyle(group.isToday ? todayColor : .secondary)
331 }
332 .textCase(nil)
333 }
334
335 // MARK: - Span
336
337 /// The first day shown, as `Days` numbers it, and how many.
338 private var shown: (first: Int, span: Int) {
339 var span = agenda.span
340 var offset = agenda.startOffset
341 if case .agenda(let viewSpan, let viewStart) = agenda.mode {
342 span = viewSpan ?? span
343 offset = viewStart ?? offset
344 }
345 return (agenda.start ?? agenda.today + offset, span)
346 }
347
348 private var firstDay: Int { shown.first }
349
350 private var todayShown: Bool { (shown.first..<(shown.first + shown.span)).contains(agenda.today) }
351
352 /// The span: `Thu 8 Oct`, `Week of 5 Oct`, `October 2026`, or the days, `5 – 14 Oct`.
353 private var title: String {
354 guard case .agenda = agenda.mode else { return viewName }
355 if viewName != "Agenda", range == nil, agenda.start == nil { return viewName }
356 let (first, span) = shown
357 let start = date(first)
358 if span == 1 { return start.formatted(.dateTime.weekday(.abbreviated).day().month(.abbreviated)) }
359 if span == 7, first == weekStart(first) { return "Week of " + start.formatted(.dateTime.day().month(.abbreviated)) }
360 let d = Days.date(first)
361 if d.day == 1, span == Days.absolute(year: d.year, month: d.month + 1, day: 1) - first {
362 return start.formatted(.dateTime.month(.wide).year())
363 }
364 return start.formatted(.dateTime.day().month(.abbreviated)) + " – " + date(first + span - 1).formatted(.dateTime.day().month(.abbreviated))
365 }
366
367 private func weekStart(_ day: Int) -> Int {
368 day - (Days.weekday(day) + 6) % 7
369 }
370
371 /// Shows `range` around `day`; nil returns to the configured span.
372 private func show(_ range: SpanRange?, around day: Int) {
373 self.range = range
374 let mode: AgendaMode
375 let start: Int?
376 switch range {
377 case .day:
378 (mode, start) = (.agenda(span: 1, startOffset: 0), day)
379 case .week:
380 (mode, start) = (.agenda(span: 7, startOffset: 0), weekStart(day))
381 case .month:
382 let d = Days.date(day)
383 let first = Days.absolute(year: d.year, month: d.month, day: 1)
384 (mode, start) = (.agenda(span: Days.absolute(year: d.year, month: d.month + 1, day: 1) - first, startOffset: 0), first)
385 case nil:
386 (mode, start) = (.agenda(span: nil, startOffset: nil), day == agenda.today ? nil : day)
387 }
388 rangeMode = mode
389 viewName = "Agenda"
390 agenda.mode = mode
391 agenda.start = start
392 }
393
394 private func step(forward: Bool) {
395 if range == nil, case .agenda = agenda.mode {
396 agenda.shift(forward: forward)
397 } else {
398 let (first, span) = shown
399 show(range, around: forward ? first + span : first - 1)
400 }
401 }
402
403 private func jump(to day: Int) {
404 show(range, around: day)
405 }
406
407 private func goToday() {
408 if range == nil { show(nil, around: agenda.today) } else { show(range, around: agenda.today) }
409 }
410
411 private var bottomBar: some View {
412 VStack(spacing: 8) {
413 if let status = message ?? (filter.isEmpty ? nil : "Filter: " + filter.description) {
414 Text(status).font(.footnote).padding(.horizontal, 12).padding(.vertical, 6)
415 .glassEffect(.regular, in: Capsule())
416 .onTapGesture { message = nil }
417 }
418 HStack(spacing: 2) {
419 let isAgenda = if case .agenda = agenda.mode { true } else { false }
420 if isAgenda {
421 barButton("Earlier", "chevron.left") { step(forward: false) }
422 }
423 barButton("Filter", filter.isEmpty ? "line.3.horizontal.decrease" : "line.3.horizontal.decrease.circle.fill") { showingFilter = true }
424 if isAgenda {
425 barButton("Today", "smallcircle.filled.circle") { goToday() }
426 barButton("Go to Date", "calendar") { jumping = true }
427 Menu {
428 Picker("Span", selection: Binding { range } set: { show($0, around: $0 == nil || todayShown ? agenda.today : firstDay) }) {
429 ForEach(SpanRange.allCases) { Text($0.title).tag(Optional($0)) }
430 Text("\(agenda.span) Days").tag(SpanRange?.none)
431 }
432 Toggle("Log Mode", systemImage: "clock.arrow.circlepath", isOn: $logMode)
433 } label: {
434 Text(range?.title ?? "\(agenda.span) Days")
435 .font(.footnote.weight(.semibold).monospacedDigit())
436 .lineLimit(1)
437 .frame(minWidth: 52, minHeight: 44)
438 .contentShape(Rectangle())
439 }
440 .accessibilityLabel("Span")
441 barButton("Later", "chevron.right") { step(forward: true) }
442 } else {
443 barButton("Agenda", "calendar") { show(nil, around: agenda.today) }
444 }
445 }
446 .padding(.horizontal, 6)
447 .glassEffect(.regular.interactive(), in: Capsule())
448 }
449 .padding(.bottom, 8)
450 .frame(maxWidth: .infinity)
451 }
452
453 private func barButton(_ title: String, _ image: String, action: @escaping () -> Void) -> some View {
454 Button(title, systemImage: image, action: action)
455 .labelStyle(.iconOnly)
456 .font(.body.weight(.medium))
457 .frame(width: 44, height: 44)
458 .contentShape(Rectangle())
459 }
460
461 // MARK: - Rows
462
463 private func row(_ row: AgendaRow, day: Int) -> some View {
464 Group {
465 if let item = row.item, let path = item.path, let offset = item.headingOffset ?? item.markerOffset {
466 NavigationLink(value: ReaderRoute.offset(path, offset)) { AgendaRowView(row: row, day: day, theme: theme, dark: isDark) }
467 } else if let event = row.event {
468 // Calendar can't be asked for one event by URL; it opens on the event's day.
469 Button {
470 if let url = URL(string: "calshow:\(event.start.timeIntervalSinceReferenceDate)") { openURL(url) }
471 } label: {
472 AgendaRowView(row: row, day: day, theme: theme, dark: isDark)
473 }
474 .tint(.primary)
475 } else {
476 AgendaRowView(row: row, day: day, theme: theme, dark: isDark)
477 }
478 }
479 .swipeActions(edge: .trailing) {
480 if let item = row.item, item.todo != nil, !item.isDone, item.doneKeyword != nil {
481 Button("Done", systemImage: "checkmark") { markDone(item) }.tint(.green)
482 Button("Next State", systemImage: "arrow.right.circle") { run("org.todo.next", on: item) }.tint(.blue)
483 }
484 }
485 .swipeActions(edge: .leading) {
486 if canReschedule(row), let item = row.item {
487 Button("Tomorrow", systemImage: "sunrise") { reschedule(row, item, to: agenda.today + 1) }.tint(.orange)
488 Button("Next Week", systemImage: "calendar.badge.plus") { reschedule(row, item, to: weekStart(agenda.today) + 7) }.tint(.indigo)
489 Button("Pick Date", systemImage: "calendar") { rescheduling = row }.tint(.gray)
490 }
491 }
492 .contextMenu {
493 if let item = row.item, item.path != nil {
494 Button("TODO State…", systemImage: "checkmark.circle") { run("org.todo.cycle", on: item) }
495 if canReschedule(row) {
496 Menu("Reschedule", systemImage: "calendar.badge.clock") {
497 Button("Tomorrow") { reschedule(row, item, to: agenda.today + 1) }
498 Button("Next Week") { reschedule(row, item, to: weekStart(agenda.today) + 7) }
499 Button("Pick Date…") { rescheduling = row }
500 }
501 }
502 Button("Schedule…", systemImage: "calendar") { run("org.schedule", on: item) }
503 Button("Deadline…", systemImage: "calendar.badge.exclamationmark") { run("org.deadline", on: item) }
504 Button("Tags…", systemImage: "tag") { run("org.tags.set", on: item) }
505 Button("Priority…", systemImage: "exclamationmark.circle") { run("org.priority.set", on: item) }
506 Button("Clock In", systemImage: "stopwatch") {
507 if let (path, offset) = locate(item) { clockIn(path, offset) }
508 }
509 Divider()
510 Button("Refile…", systemImage: "arrow.turn.down.right") { refiling = item }
511 Button("Archive…", systemImage: "archivebox") { archiving = item }
512 }
513 }
514 }
515
516 // MARK: - Actions
517
518 /// Entries with a heading, not done, that a schedule or deadline can move.
519 private func canReschedule(_ row: AgendaRow) -> Bool {
520 guard let item = row.item, item.path != nil, item.headingLine != nil, !row.isDone else { return false }
521 return item.todo != nil || row.icon == .scheduled || row.icon == .deadline || row.icon == .habit
522 }
523
524 /// Moves the row's deadline (on a deadline row) or schedule to `day`, keeping its times,
525 /// as `org-agenda-schedule` and `org-agenda-deadline` with a date typed.
526 private func reschedule(_ row: AgendaRow, _ item: AgendaItem, to day: Int) {
527 let d = Days.date(day)
528 var answer = String(format: "%04d-%02d-%02d", d.year, d.month, d.day)
529 if let start = row.start {
530 answer += String(format: " %02d:%02d", start / 100 % 24, start % 100)
531 if let end = row.end { answer += String(format: "-%02d:%02d", end / 100 % 24, end % 100) }
532 }
533 run(row.icon == .deadline ? "org.deadline" : "org.schedule", on: item, answers: ["date": answer])
534 moved += 1
535 }
536
537 /// The heading of `item` now, found again by its line in case the file changed.
538 private func locate(_ item: AgendaItem) -> (path: String, offset: Int)? {
539 guard let path = item.path, let line = item.headingLine, let near = item.headingOffset,
540 let offset = session.locateHeading(path: path, line: line, near: near) else {
541 message = "The entry changed; the agenda has been refreshed."
542 tick += 1
543 return nil
544 }
545 return (path, offset)
546 }
547
548 /// `org-agenda-clock-in`: `org-clock-in` at the entry, dangling clocks resolved first.
549 private func clockIn(_ path: String, _ offset: Int) {
550 let paths = workspace.files.filter { $0.kind == .org }.map(\.path)
551 Task {
552 let outcome = await clock.clockIn(session, target: .entry(path: path, offset: offset), paths: paths, ask: model.clockPrompts.ask)
553 if let jump = outcome.jump { model.openRequest = .offset(jump.path, jump.offset) }
554 message = outcome.messages.last { !$0.isEmpty }
555 }
556 }
557
558 /// Runs a command at the entry's heading, asking what it asks.
559 private func run(_ id: String, on item: AgendaItem, answers: [String: String] = [:]) {
560 guard let command = Commands.command(id) else { return }
561 run(command, on: item, answers: answers)
562 }
563
564 private func run(_ command: any OrgCommand, on item: AgendaItem, answers: [String: String] = [:]) {
565 guard let (path, offset) = locate(item), let line = item.headingLine else { return }
566 switch session.perform(command, path: path, at: offset, expect: (offset, line), answers: answers) {
567 case .prompt(let request):
568 prompt = EditorScreen.PromptRequest(prompt: request) { answer in
569 guard let answer else { return }
570 run(command, on: item, answers: answers.merging([request.key: answer]) { $1 })
571 }
572 case .failed(let text):
573 message = text
574 case .external(let request):
575 message = MobileEditor.unavailable(request, title: command.title)
576 case .commit:
577 message = nil
578 }
579 tick += 1
580 }
581
582 private func markDone(_ item: AgendaItem) {
583 guard let keyword = item.doneKeyword else { return }
584 run(SetTodo(keyword: keyword), on: item)
585 done += 1
586 }
587
588 private func refile(_ item: AgendaItem, to target: RefileTarget) {
589 guard let (path, offset) = locate(item) else { return }
590 // Targets in the entry's own file come from its text now.
591 let document = session.openDocuments.first { $0.path == path }?.document
592 ?? FileManager.default.contents(atPath: path).map { DocumentState(bytes: [UInt8]($0)) }
593 guard let current = workspace.refileTargets(openPath: path, document: document).first(where: { $0.label == target.label }) else {
594 message = "Can't find \(target.label) any more."
595 return
596 }
597 message = session.refile(to: current, from: (path, offset))
598 tick += 1
599 }
600
601 private func archive(_ item: AgendaItem) {
602 guard let (path, offset) = locate(item) else { return }
603 message = session.archive(from: (path, offset))
604 tick += 1
605 }
606
607 private func date(_ day: Int) -> Date {
608 let d = Days.date(day)
609 return Calendar.current.date(from: DateComponents(year: d.year, month: d.month, day: d.day)) ?? Date()
610 }
611
612 private func themed(_ color: RGBA?, _ fallback: Color) -> Color { color?.swiftUI ?? fallback }
613}
614
615extension RGBA {
616 var swiftUI: Color { Color(.sRGB, red: red, green: green, blue: blue, opacity: alpha) }
617}
618
619/// One agenda line: the time or status with an icon in the gutter; the category, title,
620/// progress and tags; the TODO keyword and priority on the right.
621struct AgendaRowView: View {
622 let row: AgendaRow
623 /// The day the row is on, for habit graphs.
624 let day: Int
625 let theme: ThemeSpec
626 let dark: Bool
627
628 var body: some View {
629 HStack(alignment: .top, spacing: 10) {
630 // TODO and match lists have no times or statuses.
631 if !row.gutter.isEmpty || row.icon != nil { gutter.frame(width: 82, alignment: .leading) }
632 VStack(alignment: .leading, spacing: 2) {
633 HStack(spacing: 5) {
634 if !row.category.isEmpty {
635 Circle().fill(categoryColor).frame(width: 7, height: 7)
636 Text(row.category).lineLimit(1).layoutPriority(1)
637 }
638 ForEach([row.progress, row.detail].compactMap { $0 }, id: \.self) { progress in
639 Text(progress).monospacedDigit()
640 .padding(.horizontal, 5)
641 .background(.quaternary.opacity(0.7), in: Capsule())
642 }
643 ForEach(row.tags.prefix(3), id: \.self) { tag in
644 Text(tag).lineLimit(1)
645 .padding(.horizontal, 5)
646 .background(.quaternary.opacity(0.7), in: Capsule())
647 }
648 Spacer(minLength: 4)
649 marks
650 }
651 .font(.caption)
652 .foregroundStyle(.secondary)
653 Text(row.title.isEmpty ? " " : row.title)
654 .font(.body)
655 .strikethrough(row.isDone)
656 .foregroundStyle(row.isDone ? .secondary : .primary)
657 if let habit = row.item?.habit {
658 HabitStrip(cells: habit.graph(today: day), theme: theme, dark: dark).padding(.top, 3)
659 }
660 }
661 }
662 .padding(.vertical, 2)
663 // Blocked entries dim, as `org-agenda-dim-blocked-tasks`.
664 .opacity(row.isBlocked ? 0.5 : row.isDone ? 0.75 : 1)
665 }
666
667 /// The TODO keyword and the priority, on the category's line.
668 private var marks: some View {
669 HStack(spacing: 5) {
670 if let todo = row.todo {
671 let color = theme.todoColor(todo, isDone: row.isDone, dark: dark)?.swiftUI ?? .secondary
672 Text(todo)
673 .font(.caption2.weight(.semibold))
674 .foregroundStyle(color)
675 .padding(.horizontal, 6).padding(.vertical, 2)
676 .background(color.opacity(0.14), in: Capsule())
677 }
678 if let priority = row.priority {
679 let color = theme.priorityColor(priority, dark: dark)?.swiftUI ?? .orange
680 Text(priority)
681 .font(.caption2.weight(.bold))
682 .foregroundStyle(color)
683 .frame(width: 18, height: 18)
684 .background(color.opacity(0.14), in: Circle())
685 .overlay(Circle().strokeBorder(color, lineWidth: 1.2))
686 .accessibilityLabel("Priority \(priority)")
687 }
688 }
689 .fixedSize()
690 }
691
692 private var statusColor: Color {
693 theme.statusColor(row.status, dark: dark)?.swiftUI ?? .secondary
694 }
695
696 private var categoryColor: Color {
697 if let event = row.event { return theme.eventColor(event, dark: dark)?.swiftUI ?? .purple }
698 return theme.categoryColor(row.category, dark: dark).swiftUI
699 }
700
701 /// The start over the end for timed rows, else the status; the icon under them.
702 private var gutter: some View {
703 HStack(alignment: .firstTextBaseline, spacing: 4) {
704 Image(systemName: icon ?? "circle").font(.caption2.weight(.semibold)).foregroundStyle(iconColor)
705 .frame(width: 14)
706 .opacity(icon == nil ? 0 : 1)
707 VStack(alignment: .leading, spacing: 1) {
708 if row.start != nil {
709 let parts = row.gutter.split(separator: "–", maxSplits: 1)
710 Text(parts.first.map(String.init) ?? row.gutter)
711 .font(.subheadline.monospacedDigit().weight(.semibold))
712 .foregroundStyle(row.status == .normal ? Color.primary : row.status == .done ? Color.secondary : statusColor)
713 if parts.count > 1 {
714 Text(parts[1]).font(.caption.monospacedDigit()).foregroundStyle(.secondary)
715 }
716 } else if !row.gutter.isEmpty {
717 Text(row.gutter)
718 .font(.caption.weight(.medium).monospacedDigit())
719 .foregroundStyle(statusColor)
720 .lineLimit(1)
721 .allowsTightening(true)
722 .minimumScaleFactor(0.8)
723 }
724 }
725 }
726 }
727
728 private var icon: String? {
729 switch row.icon {
730 case .scheduled: row.status == .overdue ? "exclamationmark.circle.fill" : "calendar"
731 case .deadline: row.status == .overdue ? "exclamationmark.triangle.fill" : "flag.fill"
732 case .habit: "repeat"
733 case .event: "calendar"
734 case .timestamp: "clock"
735 case nil: nil
736 }
737 }
738
739 private var iconColor: Color {
740 if row.isEvent { return categoryColor }
741 return row.status == .normal ? Color(.tertiaryLabel) : statusColor
742 }
743}
744
745/// The current time between timed rows, as Org's `now - - -` line.
746struct NowLine: View {
747 let time: Date
748 let color: Color
749
750 var body: some View {
751 HStack(spacing: 6) {
752 Text(time.formatted(date: .omitted, time: .shortened))
753 .font(.caption2.weight(.semibold).monospacedDigit())
754 .foregroundStyle(color)
755 Circle().fill(color).frame(width: 6, height: 6)
756 Rectangle().fill(color).frame(height: 1.5)
757 }
758 .listRowInsets(EdgeInsets(top: 0, leading: 16, bottom: 0, trailing: 16))
759 .listRowSeparator(.hidden)
760 .frame(height: 16)
761 .accessibilityLabel("Now")
762 }
763}
764
765/// org-habit's consistency graph, compact: a bar per day, a dot where the habit was done,
766/// today outlined.
767struct HabitStrip: View {
768 let cells: [Habit.Cell]
769 let theme: ThemeSpec
770 let dark: Bool
771
772 var body: some View {
773 HStack(spacing: 1) {
774 ForEach(cells, id: \.day) { cell in
775 RoundedRectangle(cornerRadius: 1.5)
776 .fill(color(cell.face))
777 .frame(width: 4, height: 12)
778 .overlay {
779 if cell.glyph == "*" { Circle().fill(.white.opacity(0.9)).frame(width: 3, height: 3) }
780 }
781 .overlay {
782 if cell.glyph == "!" { RoundedRectangle(cornerRadius: 1.5).strokeBorder(Color.primary, lineWidth: 1) }
783 }
784 }
785 }
786 .accessibilityElement(children: .ignore)
787 .accessibilityLabel("Done \(cells.filter { $0.glyph == "*" }.count) of the last \(Habit.precedingDays) days")
788 }
789
790 /// Due-state colors, lighter for days to come, as org-habit's faces.
791 private func color(_ face: Habit.Face) -> Color {
792 func themed(_ key: String, _ fallback: Color) -> Color { theme.color(key, dark: dark)?.swiftUI ?? fallback }
793 switch face {
794 case .clear: return themed("habit-clear", .blue).opacity(0.7)
795 case .clearFuture: return themed("habit-clear", .blue).opacity(0.3)
796 case .ready: return themed("habit-ready", .green).opacity(0.8)
797 case .readyFuture: return themed("habit-ready", .green).opacity(0.3)
798 case .alert: return themed("habit-alert", .yellow).opacity(0.85)
799 case .alertFuture: return themed("habit-alert", .yellow).opacity(0.35)
800 case .overdue: return themed("habit-overdue", .red).opacity(0.8)
801 case .overdueFuture: return themed("habit-overdue", .red).opacity(0.3)
802 }
803 }
804}
805
806/// A date to go to or to schedule on.
807struct DateSheet: View {
808 let title: String
809 let action: String
810 let initial: Date
811 let done: (Date?) -> Void
812 @State private var date = Date()
813
814 var body: some View {
815 NavigationStack {
816 DatePicker(title, selection: $date, displayedComponents: .date)
817 .datePickerStyle(.graphical)
818 .padding(.horizontal)
819 .navigationTitle(title)
820 .navigationBarTitleDisplayMode(.inline)
821 .toolbar {
822 ToolbarItem(placement: .cancellationAction) { Button("Cancel") { done(nil) } }
823 ToolbarItem(placement: .confirmationAction) { Button(action) { done(date) } }
824 }
825 Spacer()
826 }
827 .presentationDetents([.medium, .large])
828 .onAppear { date = initial }
829 }
830}
831
832extension AgendaItem: @retroactive Identifiable {
833 public var id: String { "\(path ?? "")|\(headingOffset ?? -1)|\(kind.rawValue)|\(text)" }
834
835 /// An entry, not a time-grid line.
836 var isEntry: Bool { kind != .timeGrid && kind != .currentTime }
837}
838
839/// Org's agenda filter: tags and categories of the entries shown, kept or left out, or the
840/// filter typed as `/` takes it.
841struct FilterSheet: View {
842 @Binding var filter: AgendaFilter
843 let items: [AgendaItem]
844 @State private var typed = ""
845 @Environment(\.dismiss) private var dismiss
846
847 var body: some View {
848 let tags = Set(items.flatMap(\.tags)).sorted()
849 let categories = Set(items.filter { $0.path != nil }.map(\.category)).sorted()
850 NavigationStack {
851 Form {
852 Section {
853 TextField("+work-home", text: $typed)
854 .autocorrectionDisabled()
855 .textInputAutocapitalization(.never)
856 .onSubmit(apply)
857 } footer: {
858 Text("As Org's / filter: +keep and -drop tags or categories, <0:30 for effort, /regexp/.")
859 }
860 if !tags.isEmpty {
861 Section("Tags") { ForEach(tags, id: \.self) { term($0, in: \.tags) } }
862 }
863 if !categories.isEmpty {
864 Section("Categories") { ForEach(categories, id: \.self) { term($0, in: \.categories) } }
865 }
866 }
867 .navigationTitle("Filter")
868 .navigationBarTitleDisplayMode(.inline)
869 .toolbar {
870 ToolbarItem(placement: .cancellationAction) { Button("Clear") { filter = AgendaFilter(); dismiss() } }
871 ToolbarItem(placement: .confirmationAction) { Button("Done") { apply(); dismiss() } }
872 }
873 }
874 .onAppear { typed = filter.description }
875 }
876
877 /// Keep, leave out, or no filter on `name`.
878 private func term(_ name: String, in list: WritableKeyPath<AgendaFilter, [String]>) -> some View {
879 let state = filter[keyPath: list].contains("+" + name) ? 1 : filter[keyPath: list].contains("-" + name) ? -1 : 0
880 return Button {
881 var terms = filter[keyPath: list].filter { $0.dropFirst() != Substring(name) }
882 if state == 0 { terms.append("+" + name) } else if state == 1 { terms.append("-" + name) }
883 filter[keyPath: list] = terms
884 typed = filter.description
885 } label: {
886 HStack {
887 Text(name).foregroundStyle(.primary)
888 Spacer()
889 Text(state == 1 ? "Keep" : state == -1 ? "Leave out" : "").foregroundStyle(.secondary)
890 }
891 }
892 }
893
894 private func apply() {
895 guard typed != filter.description else { return }
896 let tags = Set(items.flatMap(\.tags))
897 let categories = Set(items.map(\.category))
898 filter = AgendaFilter().parse(typed, tags: tags, categories: categories).filter
899 }
900}
901
902/// Files to refile an entry to, at their end, searchable. Headings within them aren't offered.
903struct RefileSheet: View {
904 let targets: [RefileTarget]
905 let choose: (RefileTarget?) -> Void
906 @State private var query = ""
907
908 var body: some View {
909 NavigationStack {
910 List(targets.filter { $0.start == nil && (query.isEmpty || $0.label.localizedCaseInsensitiveContains(query)) }, id: \.self) { target in
911 Button(target.label) { choose(target) }.foregroundStyle(.primary)
912 }
913 .searchable(text: $query, placement: .navigationBarDrawer(displayMode: .always))
914 .navigationTitle("Refile to")
915 .navigationBarTitleDisplayMode(.inline)
916 .toolbar { ToolbarItem(placement: .cancellationAction) { Button("Cancel") { choose(nil) } } }
917 }
918 }
919}
920/// A view built when the list draws it: a list makes every row's view up front, and a row's
921/// actions and menus cost more than the row.
922private struct Deferred<Content: View>: View {
923 @ViewBuilder let content: () -> Content
924
925 var body: some View { content() }
926}
927#endif