Sources/OrgstarMobile/AgendaScreen.swift
930 lines · 41675 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 location = row.event?.location {
658 Label(location, systemImage: "mappin").font(.caption).foregroundStyle(.secondary).lineLimit(1)
659 }
660 if let habit = row.item?.habit {
661 HabitStrip(cells: habit.graph(today: day), theme: theme, dark: dark).padding(.top, 3)
662 }
663 }
664 }
665 .padding(.vertical, 2)
666 // Blocked entries dim, as `org-agenda-dim-blocked-tasks`.
667 .opacity(row.isBlocked ? 0.5 : row.isDone ? 0.75 : 1)
668 }
669
670 /// The TODO keyword and the priority, on the category's line.
671 private var marks: some View {
672 HStack(spacing: 5) {
673 if let todo = row.todo {
674 let color = theme.todoColor(todo, isDone: row.isDone, dark: dark)?.swiftUI ?? .secondary
675 Text(todo)
676 .font(.caption2.weight(.semibold))
677 .foregroundStyle(color)
678 .padding(.horizontal, 6).padding(.vertical, 2)
679 .background(color.opacity(0.14), in: Capsule())
680 }
681 if let priority = row.priority {
682 let color = theme.priorityColor(priority, dark: dark)?.swiftUI ?? .orange
683 Text(priority)
684 .font(.caption2.weight(.bold))
685 .foregroundStyle(color)
686 .frame(width: 18, height: 18)
687 .background(color.opacity(0.14), in: Circle())
688 .overlay(Circle().strokeBorder(color, lineWidth: 1.2))
689 .accessibilityLabel("Priority \(priority)")
690 }
691 }
692 .fixedSize()
693 }
694
695 private var statusColor: Color {
696 theme.statusColor(row.status, dark: dark)?.swiftUI ?? .secondary
697 }
698
699 private var categoryColor: Color {
700 if let event = row.event { return theme.eventColor(event, dark: dark)?.swiftUI ?? .purple }
701 return theme.categoryColor(row.category, dark: dark).swiftUI
702 }
703
704 /// The start over the end for timed rows, else the status; the icon under them.
705 private var gutter: some View {
706 HStack(alignment: .firstTextBaseline, spacing: 4) {
707 Image(systemName: icon ?? "circle").font(.caption2.weight(.semibold)).foregroundStyle(iconColor)
708 .frame(width: 14)
709 .opacity(icon == nil ? 0 : 1)
710 VStack(alignment: .leading, spacing: 1) {
711 if row.start != nil {
712 let parts = row.gutter.split(separator: "–", maxSplits: 1)
713 Text(parts.first.map(String.init) ?? row.gutter)
714 .font(.subheadline.monospacedDigit().weight(.semibold))
715 .foregroundStyle(row.status == .normal ? Color.primary : row.status == .done ? Color.secondary : statusColor)
716 if parts.count > 1 {
717 Text(parts[1]).font(.caption.monospacedDigit()).foregroundStyle(.secondary)
718 }
719 } else if !row.gutter.isEmpty {
720 Text(row.gutter)
721 .font(.caption.weight(.medium).monospacedDigit())
722 .foregroundStyle(statusColor)
723 .lineLimit(1)
724 .allowsTightening(true)
725 .minimumScaleFactor(0.8)
726 }
727 }
728 }
729 }
730
731 private var icon: String? {
732 switch row.icon {
733 case .scheduled: row.status == .overdue ? "exclamationmark.circle.fill" : "calendar"
734 case .deadline: row.status == .overdue ? "exclamationmark.triangle.fill" : "flag.fill"
735 case .habit: "repeat"
736 case .event: "calendar"
737 case .timestamp: "clock"
738 case nil: nil
739 }
740 }
741
742 private var iconColor: Color {
743 if row.isEvent { return categoryColor }
744 return row.status == .normal ? Color(.tertiaryLabel) : statusColor
745 }
746}
747
748/// The current time between timed rows, as Org's `now - - -` line.
749struct NowLine: View {
750 let time: Date
751 let color: Color
752
753 var body: some View {
754 HStack(spacing: 6) {
755 Text(time.formatted(date: .omitted, time: .shortened))
756 .font(.caption2.weight(.semibold).monospacedDigit())
757 .foregroundStyle(color)
758 Circle().fill(color).frame(width: 6, height: 6)
759 Rectangle().fill(color).frame(height: 1.5)
760 }
761 .listRowInsets(EdgeInsets(top: 0, leading: 16, bottom: 0, trailing: 16))
762 .listRowSeparator(.hidden)
763 .frame(height: 16)
764 .accessibilityLabel("Now")
765 }
766}
767
768/// org-habit's consistency graph, compact: a bar per day, a dot where the habit was done,
769/// today outlined.
770struct HabitStrip: View {
771 let cells: [Habit.Cell]
772 let theme: ThemeSpec
773 let dark: Bool
774
775 var body: some View {
776 HStack(spacing: 1) {
777 ForEach(cells, id: \.day) { cell in
778 RoundedRectangle(cornerRadius: 1.5)
779 .fill(color(cell.face))
780 .frame(width: 4, height: 12)
781 .overlay {
782 if cell.glyph == "*" { Circle().fill(.white.opacity(0.9)).frame(width: 3, height: 3) }
783 }
784 .overlay {
785 if cell.glyph == "!" { RoundedRectangle(cornerRadius: 1.5).strokeBorder(Color.primary, lineWidth: 1) }
786 }
787 }
788 }
789 .accessibilityElement(children: .ignore)
790 .accessibilityLabel("Done \(cells.filter { $0.glyph == "*" }.count) of the last \(Habit.precedingDays) days")
791 }
792
793 /// Due-state colors, lighter for days to come, as org-habit's faces.
794 private func color(_ face: Habit.Face) -> Color {
795 func themed(_ key: String, _ fallback: Color) -> Color { theme.color(key, dark: dark)?.swiftUI ?? fallback }
796 switch face {
797 case .clear: return themed("habit-clear", .blue).opacity(0.7)
798 case .clearFuture: return themed("habit-clear", .blue).opacity(0.3)
799 case .ready: return themed("habit-ready", .green).opacity(0.8)
800 case .readyFuture: return themed("habit-ready", .green).opacity(0.3)
801 case .alert: return themed("habit-alert", .yellow).opacity(0.85)
802 case .alertFuture: return themed("habit-alert", .yellow).opacity(0.35)
803 case .overdue: return themed("habit-overdue", .red).opacity(0.8)
804 case .overdueFuture: return themed("habit-overdue", .red).opacity(0.3)
805 }
806 }
807}
808
809/// A date to go to or to schedule on.
810struct DateSheet: View {
811 let title: String
812 let action: String
813 let initial: Date
814 let done: (Date?) -> Void
815 @State private var date = Date()
816
817 var body: some View {
818 NavigationStack {
819 DatePicker(title, selection: $date, displayedComponents: .date)
820 .datePickerStyle(.graphical)
821 .padding(.horizontal)
822 .navigationTitle(title)
823 .navigationBarTitleDisplayMode(.inline)
824 .toolbar {
825 ToolbarItem(placement: .cancellationAction) { Button("Cancel") { done(nil) } }
826 ToolbarItem(placement: .confirmationAction) { Button(action) { done(date) } }
827 }
828 Spacer()
829 }
830 .presentationDetents([.medium, .large])
831 .onAppear { date = initial }
832 }
833}
834
835extension AgendaItem: @retroactive Identifiable {
836 public var id: String { "\(path ?? "")|\(headingOffset ?? -1)|\(kind.rawValue)|\(text)" }
837
838 /// An entry, not a time-grid line.
839 var isEntry: Bool { kind != .timeGrid && kind != .currentTime }
840}
841
842/// Org's agenda filter: tags and categories of the entries shown, kept or left out, or the
843/// filter typed as `/` takes it.
844struct FilterSheet: View {
845 @Binding var filter: AgendaFilter
846 let items: [AgendaItem]
847 @State private var typed = ""
848 @Environment(\.dismiss) private var dismiss
849
850 var body: some View {
851 let tags = Set(items.flatMap(\.tags)).sorted()
852 let categories = Set(items.filter { $0.path != nil }.map(\.category)).sorted()
853 NavigationStack {
854 Form {
855 Section {
856 TextField("+work-home", text: $typed)
857 .autocorrectionDisabled()
858 .textInputAutocapitalization(.never)
859 .onSubmit(apply)
860 } footer: {
861 Text("As Org's / filter: +keep and -drop tags or categories, <0:30 for effort, /regexp/.")
862 }
863 if !tags.isEmpty {
864 Section("Tags") { ForEach(tags, id: \.self) { term($0, in: \.tags) } }
865 }
866 if !categories.isEmpty {
867 Section("Categories") { ForEach(categories, id: \.self) { term($0, in: \.categories) } }
868 }
869 }
870 .navigationTitle("Filter")
871 .navigationBarTitleDisplayMode(.inline)
872 .toolbar {
873 ToolbarItem(placement: .cancellationAction) { Button("Clear") { filter = AgendaFilter(); dismiss() } }
874 ToolbarItem(placement: .confirmationAction) { Button("Done") { apply(); dismiss() } }
875 }
876 }
877 .onAppear { typed = filter.description }
878 }
879
880 /// Keep, leave out, or no filter on `name`.
881 private func term(_ name: String, in list: WritableKeyPath<AgendaFilter, [String]>) -> some View {
882 let state = filter[keyPath: list].contains("+" + name) ? 1 : filter[keyPath: list].contains("-" + name) ? -1 : 0
883 return Button {
884 var terms = filter[keyPath: list].filter { $0.dropFirst() != Substring(name) }
885 if state == 0 { terms.append("+" + name) } else if state == 1 { terms.append("-" + name) }
886 filter[keyPath: list] = terms
887 typed = filter.description
888 } label: {
889 HStack {
890 Text(name).foregroundStyle(.primary)
891 Spacer()
892 Text(state == 1 ? "Keep" : state == -1 ? "Leave out" : "").foregroundStyle(.secondary)
893 }
894 }
895 }
896
897 private func apply() {
898 guard typed != filter.description else { return }
899 let tags = Set(items.flatMap(\.tags))
900 let categories = Set(items.map(\.category))
901 filter = AgendaFilter().parse(typed, tags: tags, categories: categories).filter
902 }
903}
904
905/// Files to refile an entry to, at their end, searchable. Headings within them aren't offered.
906struct RefileSheet: View {
907 let targets: [RefileTarget]
908 let choose: (RefileTarget?) -> Void
909 @State private var query = ""
910
911 var body: some View {
912 NavigationStack {
913 List(targets.filter { $0.start == nil && (query.isEmpty || $0.label.localizedCaseInsensitiveContains(query)) }, id: \.self) { target in
914 Button(target.label) { choose(target) }.foregroundStyle(.primary)
915 }
916 .searchable(text: $query, placement: .navigationBarDrawer(displayMode: .always))
917 .navigationTitle("Refile to")
918 .navigationBarTitleDisplayMode(.inline)
919 .toolbar { ToolbarItem(placement: .cancellationAction) { Button("Cancel") { choose(nil) } } }
920 }
921 }
922}
923/// A view built when the list draws it: a list makes every row's view up front, and a row's
924/// actions and menus cost more than the row.
925private struct Deferred<Content: View>: View {
926 @ViewBuilder let content: () -> Content
927
928 var body: some View { content() }
929}
930#endif