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