Sources/OrgstarMobile/AgendaScreen.swift
cmc Agenda prompts, Week of titles and notification status through the catalog
e633d6bf48 19 hours ago1352 lines · 63208 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 let 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(\.dynamicTypeSize) private var typeSize
21 @Environment(\.openURL) private var openURL
22 @State private var tick = 0
23 /// The time the now line shows, kept to the minute while the agenda is open.
24 @State private var now = Date()
25 @State private var views = AgendaViewLoader.builtIn
26 @State private var viewName = "Agenda"
27 @State private var filter = AgendaFilter()
28 @State private var showingFilter = false
29 @State private var asking: Asking?
30 @State private var prompt: EditorScreen.PromptRequest?
31 @State private var refiling: AgendaItem?
32 /// An event being changed, or an entry being added to a calendar.
33 @State private var eventRequest: EventRequest?
34 @State private var archiving: AgendaItem?
35 @State private var deleting: AgendaItem?
36 /// The day, week or month shown; nil for `org-agenda-span` and `org-agenda-start-day`.
37 @State private var range: SpanRange?
38 /// The mode `range` set, to notice when something else changes the view.
39 @State private var rangeMode: AgendaMode?
40 @State private var jumping = false
41 @State private var rescheduling: AgendaRow?
42 @AppStorage("agendaOverdueExpanded") private var overdueExpanded = true
43 @State private var done = 0
44 @State private var moved = 0
45 /// `org-agenda-log-mode`: closed entries and clocked time on each day.
46 @State private var logMode = false
47 /// Selecting entries for bulk actions, as `m` marks them in Org's agenda, and those marked.
48 @State private var selecting = false
49 @State private var marked: [Mark] = []
50 @State private var bulkRefiling = false
51 @State private var bulkArchiving = false
52 @State private var bulkPlanning: BulkPlanning?
53 @State private var showingBoard = false
54 /// The entry open in its sheet.
55 @State private var editing: AgendaItem?
56
57 /// A marked entry: its heading line, to find it again.
58 private struct Mark: Hashable {
59 let path: String
60 let line: String
61 let offset: Int
62
63 init?(_ item: AgendaItem?) {
64 guard let item, let path = item.path, let line = item.headingLine, let offset = item.headingOffset else { return nil }
65 (self.path, self.line, self.offset) = (path, line, offset)
66 }
67 }
68
69 private enum BulkPlanning: String, Identifiable {
70 case schedule, deadline
71 var id: String { rawValue }
72 }
73
74 /// A match typed for the tag and property view, or a search string.
75 private enum Asking: Identifiable {
76 case match, search
77 /// A name for the match or search showing, to keep it as a view.
78 case save
79 var id: Self { self }
80 }
81
82 enum SpanRange: String, CaseIterable, Identifiable {
83 case day, week, month
84 var id: String { rawValue }
85 var title: LocalizedStringKey { LocalizedStringKey(rawValue.capitalized) }
86 }
87
88 private struct Key: Equatable {
89 var files: Int
90 var changed: Int?
91 var edits: Int
92 var tick: Int
93 var mode: AgendaMode
94 var start: Int?
95 var span: Int
96 var startOffset: Int
97 var subfolders: Bool
98 var hidden: Set<String>
99 var settings: Int
100 var logMode: Bool
101 }
102
103 /// The same models: the root redrawing for navigation leaves the list alone.
104 nonisolated static func == (a: Self, b: Self) -> Bool {
105 a.workspace === b.workspace && a.session === b.session && a.agenda === b.agenda && a.scheduler === b.scheduler
106 }
107
108 private var isDark: Bool { colorScheme == .dark }
109 private var theme: ThemeSpec { model.theme }
110
111 var body: some View {
112 List {
113 // With no folders the empty state stands alone, not over a column of empty days.
114 if workspace.rootPaths.isEmpty {
115 } else if case .agenda = agenda.mode {
116 let _ = model.settingsVersion
117 ForEach(Perf.measure("agenda.groups") { agenda.groups(showAllDates: OrgPreferences.agendaShowAllDates(), filter: filter) }) { group in
118 dayGroup(group)
119 }
120 } else if case .blocks = agenda.mode {
121 // A block's title over its days, or over its entries.
122 ForEach(Array(agenda.blocks.enumerated()), id: \.offset) { _, block in
123 if block.isAgenda {
124 Section { } header: { Text(block.header).font(.headline) }
125 ForEach(agenda.groups(block, showAllDates: OrgPreferences.agendaShowAllDates(), filter: filter)) { group in
126 dayGroup(group)
127 }
128 } else {
129 Section {
130 let rows = block.list.filter(filter.keeps).compactMap { AgendaRow(item: $0, day: agenda.today, today: agenda.today) }
131 if rows.isEmpty, !agenda.isComputing { Text("No entries").foregroundStyle(.secondary) }
132 ForEach(rows) { item in Deferred { row(item, day: agenda.today) } }
133 } header: {
134 Text(block.header).font(.headline)
135 }
136 }
137 }
138 } else {
139 let rows = agenda.list.filter(filter.keeps).compactMap { AgendaRow(item: $0, day: agenda.today, today: agenda.today) }
140 if rows.isEmpty, !agenda.isComputing { Text("No entries").foregroundStyle(.secondary) }
141 ForEach(rows) { item in Deferred { row(item, day: agenda.today) } }
142 }
143 if let reminderStatus {
144 Section { } footer: { Text(reminderStatus) }
145 }
146 }
147 .listStyle(.insetGrouped)
148 .listSectionSpacing(.compact)
149 // The now line is shorter than a row.
150 .environment(\.defaultMinListRowHeight, 16)
151 .navigationTitle(title)
152 .navigationSubtitle(shownFolders ?? "")
153 .navigationBarTitleDisplayMode(.inline)
154 .sensoryFeedback(.success, trigger: done)
155 .sensoryFeedback(.impact(weight: .light), trigger: moved)
156 .onChange(of: agenda.start) {
157 // Days a followed timestamp asked for.
158 if agenda.start != nil, case .agenda = agenda.mode { viewName = "Agenda" }
159 }
160 .onChange(of: agenda.mode) {
161 if agenda.mode != rangeMode { range = nil }
162 }
163 .overlay {
164 if workspace.rootPaths.isEmpty {
165 ContentUnavailableView("No Folders", systemImage: "folder", description: Text("Add a folder of org files under Folders."))
166 }
167 }
168 .message($message)
169 .safeAreaInset(edge: .bottom) {
170 if !workspace.rootPaths.isEmpty {
171 if selecting { bulkBar } else { bottomBar }
172 }
173 }
174 .sheet(isPresented: $bulkRefiling) {
175 RefileSheet(targets: workspace.refileTargets(openPath: session.path, document: session.document)) { target in
176 bulkRefiling = false
177 guard let target else { return }
178 bulk { path, offset in
179 // Targets in the entry's own file from its text now, as earlier moves shift them.
180 let document = session.openDocuments.first { $0.path == path }?.document
181 ?? FileManager.default.contents(atPath: path).map { DocumentState(bytes: [UInt8]($0)) }
182 guard let current = workspace.refileTargets(openPath: path, document: document).first(where: { $0.label == target.label }) else {
183 return "Can't find \(target.label) any more."
184 }
185 return session.refile(to: current, from: (path, offset))
186 }
187 }
188 }
189 .sheet(item: $bulkPlanning) { kind in
190 DateSheet(title: kind == .deadline ? "Deadline" : "Schedule", action: "Set", initial: date(agenda.today)) { picked in
191 bulkPlanning = nil
192 guard let picked else { return }
193 let d = Days.date(Days.absolute(picked, calendar: .current))
194 let answer = String(format: "%04d-%02d-%02d", d.year, d.month, d.day)
195 bulk { perform(SetPlanning(deadline: kind == .deadline), $0, $1, answers: ["date": answer]) }
196 }
197 }
198 .confirmationDialog("Archive \(marked.count) entries?", isPresented: $bulkArchiving, titleVisibility: .visible) {
199 Button("Archive", role: .destructive) { bulk { session.archive(from: ($0, $1)) } }
200 }
201 .toolbar {
202 ToolbarItem(placement: .topBarLeading) {
203 Menu {
204 ForEach(views) { definition in
205 Button(definition.name) { show(definition) }
206 }
207 Button("Tags and Properties…") { asking = .match }
208 Button("Search…") { asking = .search }
209 if canSaveView { Button("Save as View…") { asking = .save } }
210 Divider()
211 if case .agenda = agenda.mode {
212 Button("Go to Date…", systemImage: "calendar") { jumping = true }
213 }
214 Button("Filter…", systemImage: filter.isEmpty ? "line.3.horizontal.decrease" : "line.3.horizontal.decrease.circle.fill") { showingFilter = true }
215 Button("Select", systemImage: "checkmark.circle") { selecting = true }
216 Divider()
217 Button("Board", systemImage: "rectangle.split.3x1") { showingBoard = true }
218 } label: {
219 Label("Views", systemImage: "list.bullet.rectangle")
220 }
221 }
222 if workspace.rootPaths.count > 1 || shownFolders != nil {
223 ToolbarItem(placement: .topBarTrailing) { foldersMenu }
224 }
225 }
226 .fullScreenCover(isPresented: $showingBoard) {
227 BoardScreen(workspace: workspace, session: session) { showingBoard = false }
228 }
229 .sheet(isPresented: $showingFilter) {
230 FilterSheet(filter: $filter, items: shownItems)
231 }
232 .sheet(isPresented: $jumping) {
233 DateSheet(title: "Go to Date", action: "Go", initial: date(firstDay)) { picked in
234 jumping = false
235 if let picked { jump(to: Days.absolute(picked, calendar: .current)) }
236 }
237 }
238 .sheet(item: $rescheduling) { row in
239 DateSheet(title: row.icon == .deadline ? "Deadline" : "Schedule", action: "Set", initial: date(row.planningDay ?? agenda.today)) { picked in
240 rescheduling = nil
241 if let picked, let item = row.item { reschedule(row, item, to: Days.absolute(picked, calendar: .current)) }
242 }
243 }
244 .sheet(item: $asking) { kind in
245 if kind == .save {
246 PromptSheet(prompt: Prompt(key: "view-name", message: String(localized: "Name for this view:"))) { saveView($0) }
247 } else if kind == .search {
248 PromptSheet(prompt: Prompt(key: "search", message: String(localized: "Search: a phrase, or +word -word {regexp}; * for headlines, ! for TODO entries"))) { answer in
249 asking = nil
250 guard let answer, answer.contains(where: { !$0.isWhitespace }) else { return }
251 agenda.mode = .search(answer, todoOnly: false)
252 viewName = answer
253 }
254 } else {
255 PromptSheet(prompt: Prompt(key: "match", message: String(localized: "Match: tags and properties, as +work-home or TODO=\"WAIT\""))) { answer in
256 asking = nil
257 guard let answer, !answer.isEmpty else { return }
258 agenda.mode = .match(answer, todoOnly: false)
259 viewName = answer
260 }
261 }
262 }
263 .sheet(item: $prompt) { request in
264 PromptSheet(prompt: request.prompt) { answer in
265 prompt = nil
266 request.reply(answer)
267 }
268 }
269 .sheet(item: $eventRequest) { request in
270 NavigationStack {
271 EventSheet(request: request, events: model.calendarEvents) { result in
272 eventRequest = nil
273 if let result {
274 message = result
275 tick += 1
276 }
277 }
278 .navigationTitle(request.event == nil ? "Add to Calendar" : "Edit Event")
279 .navigationBarTitleDisplayMode(.inline)
280 }
281 }
282 .sheet(item: $editing) { item in
283 EntrySheet(item: item, workspace: workspace, session: session) { saved, open in
284 editing = nil
285 if saved { tick += 1 }
286 if let open { model.openRequest = .offset(open.path, open.offset) }
287 }
288 }
289 .sheet(item: $refiling) { item in
290 RefileSheet(targets: workspace.refileTargets(openPath: session.path, document: session.document)) { target in
291 refiling = nil
292 if let target { refile(item, to: target) }
293 }
294 }
295 .confirmationDialog("Archive this entry?", isPresented: Binding { archiving != nil } set: { if !$0 { archiving = nil } }, titleVisibility: .visible) {
296 Button("Archive", role: .destructive) {
297 if let item = archiving { archive(item) }
298 archiving = nil
299 }
300 } message: {
301 Text(archiving?.text ?? "")
302 }
303 .confirmationDialog("Delete this entry?", isPresented: Binding { deleting != nil } set: { if !$0 { deleting = nil } }, titleVisibility: .visible) {
304 Button("Delete", role: .destructive) {
305 // `org-cut-subtree`: the heading and everything under it.
306 if let item = deleting { run(CopySubtree(cut: true), on: item) }
307 deleting = nil
308 }
309 } message: {
310 Text("\(deleting?.text ?? "")\n\nThe heading and every line under it are removed from the file.")
311 }
312 .refreshable {
313 await workspace.refresh()
314 await agenda.refresh(open: session.openTexts)
315 }
316 .task { loadViews() }
317 // The now line moves each minute; a new day refreshes the statuses.
318 .task {
319 while !Task.isCancelled {
320 let next = Calendar.current.nextDate(after: Date(), matching: DateComponents(second: 0), matchingPolicy: .nextTime) ?? Date().addingTimeInterval(60)
321 try? await Task.sleep(for: .seconds(next.timeIntervalSinceNow))
322 now = Date()
323 if Days.absolute(now, calendar: .current) != agenda.today { tick += 1 }
324 }
325 }
326 // Calendar and Reminders access are asked for when calendar-events and
327 // agenda-reminders are turned on.
328 .task(id: model.settingsVersion) {
329 if OrgPreferences.calendarEvents(), !CalendarEvents.isAuthorized, await model.calendarEvents.requestAccess() { tick += 1 }
330 if OrgPreferences.agendaReminders(), !ReminderLists.isAuthorized, await model.reminderLists.requestAccess() { tick += 1 }
331 }
332 .background { Refresher(workspace: workspace, session: session, agenda: agenda, model: model, tick: tick, logMode: logMode) }
333 }
334
335 /// Shows or hides each folder's files; folders the Focus hides stay hidden.
336 private var foldersMenu: some View {
337 let hidden = HiddenFolders.shared
338 let hides = !hidden.all.isDisjoint(with: workspace.rootPaths)
339 return Menu {
340 Button("All Folders", systemImage: "folder") { hidden.manual = [] }
341 .disabled(hidden.manual.isEmpty)
342 Section(hidden.focus.isDisjoint(with: workspace.rootPaths) ? "" : "Dimmed folders are hidden by the current Focus.") {
343 ForEach(workspace.rootPaths, id: \.self) { root in
344 Toggle((root as NSString).lastPathComponent, isOn: Binding {
345 !hidden.all.contains(root)
346 } set: { shown in
347 if shown { hidden.manual.remove(root) } else { hidden.manual.insert(root) }
348 })
349 .disabled(hidden.focus.contains(root))
350 }
351 }
352 } label: {
353 Label("Folders", systemImage: hides ? "folder.fill" : "folder")
354 }
355 }
356
357 /// The folders shown, by name, while some are hidden.
358 private var shownFolders: String? {
359 let hidden = HiddenFolders.shared.all
360 guard !hidden.isDisjoint(with: workspace.rootPaths) else { return nil }
361 let shown = workspace.rootPaths.filter { !hidden.contains($0) }
362 return shown.isEmpty ? "No folders" : shown.map { ($0 as NSString).lastPathComponent }.joined(separator: ", ")
363 }
364
365 /// Refreshes the agenda when files, edits or settings change. Its own view, so that what it
366 /// watches redraws only it, not the whole list.
367 private struct Refresher: View {
368 let workspace: WorkspaceModel
369 let session: DocumentSession
370 let agenda: AgendaModel
371 let model: MobileModel
372 let tick: Int
373 let logMode: Bool
374
375 var body: some View {
376 Color.clear
377 .task(id: Key(files: workspace.files.count, changed: workspace.changedFile?.version, edits: session.editVersion, tick: tick,
378 mode: agenda.mode, start: agenda.start, span: agenda.span, startOffset: agenda.startOffset,
379 subfolders: agenda.includeSubfolders, hidden: HiddenFolders.shared.all, settings: model.settingsVersion, logMode: logMode)) {
380 // Changes come in bursts (a folder scan, typing); a newer one cancels this wait.
381 try? await Task.sleep(for: .milliseconds(150))
382 guard !Task.isCancelled else { return }
383 agenda.options.logMode = logMode
384 agenda.hiddenFolders = HiddenFolders.shared.all
385 await agenda.refresh(open: session.openTexts)
386 }
387 }
388 }
389
390 private var shownItems: [AgendaItem] {
391 if case .agenda = agenda.mode { return agenda.days.flatMap(\.items).filter(\.isEntry) }
392 if case .blocks = agenda.mode { return agenda.blocks.flatMap { $0.days.flatMap(\.items).filter(\.isEntry) + $0.list } }
393 return agenda.list
394 }
395
396 private func loadViews() {
397 let loaded = AgendaViewLoader.load()
398 views = loaded.views
399 agenda.viewSettings = AgendaViewLoader.settings(loaded.views)
400 if let problem = loaded.problems.first { message = problem }
401 }
402
403 /// A typed match or search is showing, which isn't a named view yet.
404 private var canSaveView: Bool {
405 switch agenda.mode {
406 case .match, .search: return !views.contains { $0.mode == agenda.mode }
407 default: return false
408 }
409 }
410
411 /// Adds the match or search showing to `views.toml` as `name`, then shows it as that view.
412 private func saveView(_ name: String?) {
413 asking = nil
414 guard let name else { return }
415 do {
416 try AgendaViewLoader.save(name: name, mode: agenda.mode)
417 loadViews()
418 viewName = name.trimmingCharacters(in: .whitespacesAndNewlines)
419 } catch {
420 message = "\(error)"
421 }
422 }
423
424 private func show(_ definition: AgendaViewDefinition) {
425 viewName = definition.name
426 agenda.mode = definition.mode
427 }
428
429 /// How far ahead notifications are set, as the design asks the agenda to show: iOS keeps
430 /// at most 64, and sets no more while the app isn't opened.
431 private var reminderStatus: String? {
432 guard OrgPreferences.reminders() else { return nil }
433 if !scheduler.isAuthorized { return String(localized: "Notifications are off for orgstar in Settings.") }
434 guard let through = scheduler.scheduledThrough else { return nil }
435 return String(localized: "Notifications are set through \(through.formatted(.dateTime.weekday(.abbreviated).day().month(.abbreviated).hour().minute())). Open orgstar to set later ones.")
436 }
437
438 // MARK: - Days
439
440 /// A day under its header. On today, the entries from earlier days come first, in a group
441 /// of their own headed Overdue.
442 @ViewBuilder
443 private func dayGroup(_ group: AgendaDayGroup) -> some View {
444 if group.isToday, !group.overdue.isEmpty {
445 Section {
446 Button {
447 withAnimation { overdueExpanded.toggle() }
448 } label: {
449 HStack(spacing: 6) {
450 Text("Overdue").font(.subheadline.weight(.semibold))
451 Text("\(group.overdue.count)").font(.subheadline.monospacedDigit())
452 Spacer()
453 Image(systemName: "chevron.right")
454 .font(.caption.weight(.semibold))
455 .rotationEffect(.degrees(overdueExpanded ? 90 : 0))
456 }
457 .foregroundStyle(themed(theme.statusColor(.overdue, dark: isDark), .red))
458 .contentShape(Rectangle())
459 }
460 .buttonStyle(.plain)
461 .accessibilityValue(overdueExpanded ? "Expanded" : "Collapsed")
462 if overdueExpanded {
463 ForEach(group.overdue) { item in Deferred { row(item, day: group.day) } }
464 }
465 } header: {
466 header(group)
467 }
468 if !group.rows.isEmpty {
469 Section {
470 day(group)
471 }
472 }
473 } else {
474 Section {
475 day(group)
476 } header: {
477 header(group)
478 }
479 }
480 }
481
482 private func day(_ group: AgendaDayGroup) -> some View {
483 Group {
484 if group.rows.isEmpty {
485 Text("Nothing scheduled").font(.subheadline).foregroundStyle(.secondary)
486 }
487 // One view per element, so the list counts its rows without building them.
488 ForEach(lines(group)) { line in
489 switch line {
490 case .now: NowLine(time: now, color: todayColor)
491 case .grid(let time): GridLineRow(time: time)
492 case .row(let item): Deferred { row(item, day: group.day) }
493 }
494 }
495 }
496 }
497
498 /// A day's rows, with the grid and now lines among them as lines of their own.
499 private enum DayLine: Identifiable {
500 case now
501 case grid(Int)
502 case row(AgendaRow)
503
504 var id: String {
505 switch self {
506 case .row(let row): row.id
507 case .grid(let time): "grid \(time)"
508 case .now: "now"
509 }
510 }
511 }
512
513 private func lines(_ group: AgendaDayGroup) -> [DayLine] {
514 let c = Calendar.current.dateComponents([.hour, .minute], from: now)
515 return group.lines(now: (c.hour ?? 0) * 100 + (c.minute ?? 0)).map { line in
516 switch line {
517 case .row(let index): .row(group.rows[index])
518 case .grid(let time): .grid(time)
519 case .now: .now
520 }
521 }
522 }
523
524 private var todayColor: Color { themed(theme.color("agenda-today", dark: isDark), .accentColor) }
525
526 private func header(_ group: AgendaDayGroup) -> some View {
527 let day = date(group.day).formatted(.dateTime.weekday(.abbreviated).day().month(.abbreviated))
528 let color = group.isToday ? todayColor : group.day < agenda.today ? Color.secondary : themed(theme.color("agenda-date", dark: isDark), .primary)
529 return HStack(alignment: .firstTextBaseline) {
530 Text(group.relativeName(today: agenda.today).map { $0 + " · " + day } ?? day)
531 .font(.subheadline.weight(group.isToday ? .bold : .semibold))
532 .foregroundStyle(color)
533 Spacer()
534 Button("Add to \(day)", systemImage: "plus.circle") { model.captureRequest = CaptureRequest(day: group.day) }
535 .labelStyle(.iconOnly)
536 .font(.body)
537 .foregroundStyle(group.isToday ? todayColor : .secondary)
538 }
539 .textCase(nil)
540 }
541
542 // MARK: - Span
543
544 /// The first day shown, as `Days` numbers it, and how many.
545 private var shown: (first: Int, span: Int) { agenda.shown(today: agenda.today) }
546
547 private var firstDay: Int { shown.first }
548
549 private var todayShown: Bool { (shown.first..<(shown.first + shown.span)).contains(agenda.today) }
550
551 /// The span: `Thu 8 Oct`, `Week of 5 Oct`, `October 2026`, or the days, `5 – 14 Oct`.
552 private var title: String {
553 guard case .agenda = agenda.mode else { return viewName }
554 if viewName != "Agenda", range == nil, agenda.start == nil { return viewName }
555 let (first, span) = shown
556 let start = date(first)
557 if span == 1 { return start.formatted(.dateTime.weekday(.abbreviated).day().month(.abbreviated)) }
558 if span == 7, first == weekStart(first) { return String(localized: "Week of \(start.formatted(.dateTime.day().month(.abbreviated)))", comment: "Agenda title; the date is the week's first day") }
559 let d = Days.date(first)
560 if d.day == 1, span == Days.absolute(year: d.year, month: d.month + 1, day: 1) - first {
561 return start.formatted(.dateTime.month(.wide).year())
562 }
563 return start.formatted(.dateTime.day().month(.abbreviated)) + " – " + date(first + span - 1).formatted(.dateTime.day().month(.abbreviated))
564 }
565
566 private func weekStart(_ day: Int) -> Int {
567 Days.weekStart(day, on: agenda.startOnWeekday)
568 }
569
570 /// Shows `range` around `day`; nil returns to the configured span.
571 private func show(_ range: SpanRange?, around day: Int) {
572 self.range = range
573 let mode: AgendaMode
574 let start: Int?
575 switch range {
576 case .day:
577 (mode, start) = (.agenda(span: 1, startOffset: 0), day)
578 case .week:
579 (mode, start) = (.agenda(span: 7, startOffset: 0), weekStart(day))
580 case .month:
581 let d = Days.date(day)
582 let first = Days.absolute(year: d.year, month: d.month, day: 1)
583 (mode, start) = (.agenda(span: Days.absolute(year: d.year, month: d.month + 1, day: 1) - first, startOffset: 0), first)
584 case nil:
585 (mode, start) = (.agenda(span: nil, startOffset: nil), day == agenda.today ? nil : day)
586 }
587 rangeMode = mode
588 viewName = "Agenda"
589 agenda.mode = mode
590 agenda.start = start
591 }
592
593 private func step(forward: Bool) {
594 if range == nil, case .agenda = agenda.mode {
595 agenda.shift(forward: forward)
596 } else {
597 let (first, span) = shown
598 show(range, around: forward ? first + span : first - 1)
599 }
600 }
601
602 private func jump(to day: Int) {
603 show(range, around: day)
604 }
605
606 private func goToday() {
607 if range == nil { show(nil, around: agenda.today) } else { show(range, around: agenda.today) }
608 }
609
610 /// The bar while selecting: the count, the bulk actions (`B` in Org's agenda) and Done.
611 private var bulkBar: some View {
612 VStack(spacing: 8) {
613 HStack(spacing: 12) {
614 Text("\(marked.count) selected").font(.footnote.weight(.semibold).monospacedDigit()).padding(.leading, 12)
615 Menu {
616 Button("TODO State…", systemImage: "checkmark.circle") { askBulkTodo() }
617 Button("Add Tag…", systemImage: "tag") { askBulkTag(on: true) }
618 Button("Remove Tag…", systemImage: "tag.slash") { askBulkTag(on: false) }
619 Button("Schedule…", systemImage: "calendar") { bulkPlanning = .schedule }
620 Button("Deadline…", systemImage: "calendar.badge.exclamationmark") { bulkPlanning = .deadline }
621 Divider()
622 Button("Refile…", systemImage: "arrow.turn.down.right") { bulkRefiling = true }
623 Button("Archive…", systemImage: "archivebox", role: .destructive) { bulkArchiving = true }
624 } label: {
625 Text("Actions").font(.body.weight(.semibold)).frame(minHeight: 44)
626 }
627 .disabled(marked.isEmpty)
628 Button("Done") {
629 selecting = false
630 marked = []
631 }
632 .font(.body.weight(.semibold))
633 .frame(minHeight: 44)
634 .padding(.trailing, 12)
635 }
636 .glassEffect(.regular.interactive(), in: Capsule())
637 }
638 .padding(.bottom, 8)
639 .frame(maxWidth: .infinity)
640 }
641
642 private var bottomBar: some View {
643 VStack(spacing: 8) {
644 if !filter.isEmpty {
645 Text("Filter: " + filter.description).font(.footnote).padding(.horizontal, 12).padding(.vertical, 6)
646 .glassEffect(.regular, in: Capsule())
647 }
648 if case .agenda = agenda.mode {
649 HStack(spacing: 2) {
650 barButton("Earlier", "chevron.left") { step(forward: false) }
651 // At accessibility sizes Today goes into the span menu, so the bar fits.
652 if !typeSize.isAccessibilitySize {
653 Button("Today") { goToday() }
654 .font(.subheadline.weight(.semibold))
655 .padding(.horizontal, 8)
656 .frame(minHeight: 44)
657 .contentShape(Rectangle())
658 }
659 Menu {
660 if typeSize.isAccessibilitySize {
661 Button("Today") { goToday() }
662 }
663 Picker("Span", selection: Binding { range } set: { show($0, around: $0 == nil || todayShown ? agenda.today : firstDay) }) {
664 ForEach(SpanRange.allCases) { Text($0.title).tag(Optional($0)) }
665 Text("\(agenda.span) Days").tag(SpanRange?.none)
666 }
667 Toggle("Log Mode", systemImage: "clock.arrow.circlepath", isOn: $logMode)
668 } label: {
669 (range.map { Text($0.title) } ?? Text("\(agenda.span) Days"))
670 .font(.subheadline.weight(.semibold).monospacedDigit())
671 .lineLimit(1)
672 .frame(minWidth: 52, minHeight: 44)
673 .contentShape(Rectangle())
674 }
675 .accessibilityLabel("Span")
676 barButton(LocalizedStringResource("agenda.later", defaultValue: "Later", comment: "Shows the next days in the agenda"), "chevron.right") { step(forward: true) }
677 }
678 .padding(.horizontal, 6)
679 .glassEffect(.regular.interactive(), in: Capsule())
680 }
681 }
682 .padding(.bottom, 8)
683 .frame(maxWidth: .infinity)
684 }
685
686 private func barButton(_ title: LocalizedStringResource, _ image: String, action: @escaping () -> Void) -> some View {
687 Button(String(localized: title), systemImage: image, action: action)
688 .labelStyle(.iconOnly)
689 .font(.body.weight(.medium))
690 .frame(minWidth: 44, minHeight: 44)
691 .contentShape(Rectangle())
692 }
693
694 // MARK: - Rows
695
696 private func row(_ row: AgendaRow, day: Int) -> some View {
697 Group {
698 if selecting {
699 if let mark = Mark(row.item) {
700 Button {
701 if let index = marked.firstIndex(of: mark) { marked.remove(at: index) } else { marked.append(mark) }
702 } label: {
703 HStack(spacing: 10) {
704 Image(systemName: marked.contains(mark) ? "checkmark.circle.fill" : "circle")
705 .foregroundStyle(marked.contains(mark) ? Color.accentColor : .secondary)
706 .font(.title3)
707 AgendaRowView(row: row, day: day, theme: theme, dark: isDark)
708 }
709 }
710 .tint(.primary)
711 .accessibilityAddTraits(marked.contains(mark) ? .isSelected : [])
712 } else {
713 AgendaRowView(row: row, day: day, theme: theme, dark: isDark).opacity(0.5)
714 }
715 } else if let item = row.item, item.path != nil, item.headingLine != nil, item.headingOffset != nil {
716 Button { editing = item } label: { AgendaRowView(row: row, day: day, theme: theme, dark: isDark) }
717 .tint(.primary)
718 } else if let item = row.item, let path = item.path, let offset = item.headingOffset ?? item.markerOffset {
719 NavigationLink(value: ReaderRoute.offset(path, offset)) { AgendaRowView(row: row, day: day, theme: theme, dark: isDark) }
720 } else if let event = row.event {
721 // An event opens for editing; a reminder opens in Reminders.
722 Button {
723 if event.isReminder {
724 if let url = URL(string: "x-apple-reminderkit://REMCDReminder/\(event.id)") { openURL(url) }
725 } else {
726 eventRequest = EventRequest(draft: EventDraft(event), event: event)
727 }
728 } label: {
729 AgendaRowView(row: row, day: day, theme: theme, dark: isDark)
730 }
731 .tint(.primary)
732 } else {
733 AgendaRowView(row: row, day: day, theme: theme, dark: isDark)
734 }
735 }
736 .swipeActions(edge: .trailing) {
737 if let item = row.item, item.todo != nil, !item.isDone, item.doneKeyword != nil {
738 Button(String(localized: "agenda.mark-done", defaultValue: "Done", comment: "Swipe action that marks the entry done"), systemImage: "checkmark") { markDone(item) }.tint(.green)
739 Button("Next State", systemImage: "arrow.right.circle") { run("org.todo.next", on: item) }.tint(.blue)
740 }
741 // Last, so a full swipe doesn't reach it; it asks first.
742 if let item = row.item, item.path != nil, item.headingLine != nil {
743 Button("Delete", systemImage: "trash") { deleting = item }.tint(.red)
744 }
745 }
746 .swipeActions(edge: .leading) {
747 if canReschedule(row), let item = row.item {
748 Button("Tomorrow", systemImage: "sunrise") { reschedule(row, item, to: agenda.today + 1) }.tint(.orange)
749 Button("Next Week", systemImage: "calendar.badge.plus") { reschedule(row, item, to: weekStart(agenda.today) + 7) }.tint(.indigo)
750 Button("Pick Date", systemImage: "calendar") { rescheduling = row }.tint(.gray)
751 }
752 }
753 .contextMenu {
754 if let event = row.event, !event.isReminder {
755 Button("Edit Event…", systemImage: "pencil") { eventRequest = EventRequest(draft: EventDraft(event), event: event) }
756 // Calendar can't be asked for one event by URL; it opens on the event's day.
757 Button("Show in Calendar", systemImage: "calendar") {
758 if let url = URL(string: "calshow:\(event.start.timeIntervalSinceReferenceDate)") { openURL(url) }
759 }
760 }
761 if let item = row.item, item.path != nil {
762 if let mark = Mark(item) {
763 Button("Select", systemImage: "checkmark.circle") {
764 selecting = true
765 if !marked.contains(mark) { marked.append(mark) }
766 }
767 }
768 Button("TODO State…", systemImage: "checkmark.circle") { run("org.todo.cycle", on: item) }
769 if canReschedule(row) {
770 Menu("Reschedule", systemImage: "calendar.badge.clock") {
771 Button("Tomorrow") { reschedule(row, item, to: agenda.today + 1) }
772 Button("Next Week") { reschedule(row, item, to: weekStart(agenda.today) + 7) }
773 Button("Pick Date…") { rescheduling = row }
774 }
775 }
776 Button("Schedule…", systemImage: "calendar") { run("org.schedule", on: item) }
777 Button("Deadline…", systemImage: "calendar.badge.exclamationmark") { run("org.deadline", on: item) }
778 Button("Tags…", systemImage: "tag") { run("org.tags.set", on: item) }
779 Button("Priority…", systemImage: "exclamationmark.circle") { run("org.priority.set", on: item) }
780 Button("Clock In", systemImage: "stopwatch") {
781 if let (path, offset) = locate(item) { clockIn(path, offset) }
782 }
783 Button("Add to Calendar…", systemImage: "calendar.badge.plus") {
784 eventRequest = EventRequest(draft: .entry(row.title, day: day, start: row.start, end: row.end))
785 }
786 Divider()
787 Button("Refile…", systemImage: "arrow.turn.down.right") { refiling = item }
788 Button("Archive…", systemImage: "archivebox") { archiving = item }
789 if item.headingLine != nil {
790 Button("Delete…", systemImage: "trash", role: .destructive) { deleting = item }
791 }
792 }
793 }
794 }
795
796 // MARK: - Actions
797
798 /// Entries with a heading, not done, that a schedule or deadline can move.
799 private func canReschedule(_ row: AgendaRow) -> Bool {
800 guard let item = row.item, item.path != nil, item.headingLine != nil, !row.isDone else { return false }
801 return item.todo != nil || row.icon == .scheduled || row.icon == .deadline || row.icon == .habit
802 }
803
804 /// Moves the row's deadline (on a deadline row) or schedule to `day`, keeping its times,
805 /// as `org-agenda-schedule` and `org-agenda-deadline` with a date typed.
806 private func reschedule(_ row: AgendaRow, _ item: AgendaItem, to day: Int) {
807 let d = Days.date(day)
808 var answer = String(format: "%04d-%02d-%02d", d.year, d.month, d.day)
809 if let start = row.start {
810 answer += String(format: " %02d:%02d", start / 100 % 24, start % 100)
811 if let end = row.end { answer += String(format: "-%02d:%02d", end / 100 % 24, end % 100) }
812 }
813 run(row.icon == .deadline ? "org.deadline" : "org.schedule", on: item, answers: ["date": answer])
814 moved += 1
815 }
816
817 /// The heading of `item` now, found again by its line in case the file changed.
818 private func locate(_ item: AgendaItem) -> (path: String, offset: Int)? {
819 guard let path = item.path, let line = item.headingLine, let near = item.headingOffset,
820 let offset = session.locateHeading(path: path, line: line, near: near) else {
821 message = "The entry changed; the agenda has been refreshed."
822 tick += 1
823 return nil
824 }
825 return (path, offset)
826 }
827
828 /// `org-agenda-clock-in`: `org-clock-in` at the entry, dangling clocks resolved first.
829 private func clockIn(_ path: String, _ offset: Int) {
830 let paths = workspace.files.filter { $0.kind == .org }.map(\.path)
831 Task {
832 let outcome = await clock.clockIn(session, target: .entry(path: path, offset: offset), paths: paths, ask: model.clockPrompts.ask)
833 if let jump = outcome.jump { model.openRequest = .offset(jump.path, jump.offset) }
834 message = outcome.messages.last { !$0.isEmpty }
835 }
836 }
837
838 /// Runs a command at the entry's heading, asking what it asks.
839 private func run(_ id: String, on item: AgendaItem, answers: [String: String] = [:]) {
840 guard let command = Commands.command(id) else { return }
841 run(command, on: item, answers: answers)
842 }
843
844 private func run(_ command: any OrgCommand, on item: AgendaItem, answers: [String: String] = [:]) {
845 guard let (path, offset) = locate(item), let line = item.headingLine else { return }
846 switch session.perform(command, path: path, at: offset, expect: (offset, line), answers: answers) {
847 case .prompt(let request):
848 prompt = EditorScreen.PromptRequest(prompt: request) { answer in
849 guard let answer else { return }
850 run(command, on: item, answers: answers.merging([request.key: answer]) { $1 })
851 }
852 case .failed(let text):
853 message = text
854 case .external(let request):
855 message = MobileEditor.unavailable(request, title: command.title)
856 case .commit:
857 message = nil
858 }
859 tick += 1
860 }
861
862 // MARK: - Bulk actions
863
864 /// Runs `action` on each marked entry, found again first; later entries in a file first,
865 /// so earlier ones keep their place. Selection ends; the last message shows.
866 private func bulk(_ action: (String, Int) -> String?) {
867 var last: String?
868 var failed = 0
869 for mark in marked.sorted(by: { ($0.path, $1.offset) < ($1.path, $0.offset) }) {
870 guard let offset = session.locateHeading(path: mark.path, line: mark.line, near: mark.offset) else {
871 failed += 1
872 continue
873 }
874 last = action(mark.path, offset)
875 }
876 message = failed > 0 ? String(localized: "\(failed) selected entries changed and were skipped") : last
877 marked = []
878 selecting = false
879 tick += 1
880 }
881
882 /// `command` at the heading at `offset` in `path`; a message when it doesn't apply.
883 private func perform(_ command: any OrgCommand, _ path: String, _ offset: Int, answers: [String: String] = [:]) -> String? {
884 switch session.perform(command, path: path, at: offset, expect: nil, answers: answers) {
885 case .failed(let text): text
886 case .prompt: String(localized: "\(CommandTitle.localized(command.title)) needs an answer; run it on the entry itself", comment: "A command run from the agenda that asks a question")
887 case .external(let request): MobileEditor.unavailable(request, title: command.title)
888 case .commit: nil
889 }
890 }
891
892 private func askBulkTodo() {
893 let keywords = OrgPreferences.orgSettings().todoSequences.flatMap { $0.active.map(\.name) + $0.done.map(\.name) }
894 prompt = EditorScreen.PromptRequest(prompt: Prompt(key: "todo", message: String(localized: "TODO state (empty for none):"), choices: keywords)) { answer in
895 guard let answer else { return }
896 let word = answer.trimmingCharacters(in: .whitespaces)
897 bulk { perform(SetTodo(keyword: word.isEmpty ? nil : word), $0, $1) }
898 }
899 }
900
901 private func askBulkTag(on: Bool) {
902 prompt = EditorScreen.PromptRequest(prompt: Prompt(key: "tag", message: on ? String(localized: "Tag to add:") : String(localized: "Tag to remove:"))) { answer in
903 guard let tag = answer?.trimmingCharacters(in: .whitespaces), !tag.isEmpty else { return }
904 bulk { perform(ToggleTag(tag: tag, on: on), $0, $1) }
905 }
906 }
907
908 private func markDone(_ item: AgendaItem) {
909 guard let keyword = item.doneKeyword else { return }
910 run(SetTodo(keyword: keyword), on: item)
911 done += 1
912 }
913
914 private func refile(_ item: AgendaItem, to target: RefileTarget) {
915 guard let (path, offset) = locate(item) else { return }
916 // Targets in the entry's own file come from its text now.
917 let document = session.openDocuments.first { $0.path == path }?.document
918 ?? FileManager.default.contents(atPath: path).map { DocumentState(bytes: [UInt8]($0)) }
919 guard let current = workspace.refileTargets(openPath: path, document: document).first(where: { $0.label == target.label }) else {
920 message = "Can't find \(target.label) any more."
921 return
922 }
923 message = session.refile(to: current, from: (path, offset))
924 tick += 1
925 }
926
927 private func archive(_ item: AgendaItem) {
928 guard let (path, offset) = locate(item) else { return }
929 message = session.archive(from: (path, offset))
930 tick += 1
931 }
932
933 private func date(_ day: Int) -> Date {
934 let d = Days.date(day)
935 return Calendar.current.date(from: DateComponents(year: d.year, month: d.month, day: d.day)) ?? Date()
936 }
937
938 private func themed(_ color: RGBA?, _ fallback: Color) -> Color { color?.swiftUI ?? fallback }
939}
940
941extension RGBA {
942 var swiftUI: Color { Color(.sRGB, red: red, green: green, blue: blue, opacity: alpha) }
943}
944
945/// One agenda line: the time or status over an icon; above the title the
946/// category, progress and tags, with the TODO keyword and priority at the end; a habit's graph under it.
947struct AgendaRowView: View {
948 let row: AgendaRow
949 /// The day the row is on, for habit graphs.
950 let day: Int
951 let theme: ThemeSpec
952 let dark: Bool
953 @Environment(\.dynamicTypeSize) private var typeSize
954 @ScaledMetric(relativeTo: .subheadline) private var gutterWidth: CGFloat = 82
955 @ScaledMetric(relativeTo: .caption2) private var badgeSize: CGFloat = 18
956 @Environment(\.colorSchemeContrast) private var contrast
957 @Environment(\.accessibilityDifferentiateWithoutColor) private var withoutColor
958
959 /// Increase Contrast: keyword and priority badges are filled with their colour.
960 private var highContrast: Bool { contrast == .increased }
961
962 /// TODO and match lists have no times or statuses.
963 private var hasGutter: Bool { !row.gutter.isEmpty || row.icon != nil }
964
965 var body: some View {
966 Group {
967 // At accessibility sizes the gutter is a line of its own above the rest.
968 if typeSize.isAccessibilitySize {
969 VStack(alignment: .leading, spacing: 4) {
970 if hasGutter { stackedGutter }
971 content
972 }
973 } else {
974 HStack(alignment: .top, spacing: 10) {
975 if hasGutter { gutter.frame(width: gutterWidth, alignment: .leading) }
976 content
977 }
978 }
979 }
980 .padding(.vertical, 2)
981 // Blocked entries dim, as `org-agenda-dim-blocked-tasks`.
982 .opacity(row.isBlocked ? 0.5 : row.isDone ? 0.75 : 1)
983 }
984
985 private var content: some View {
986 VStack(alignment: .leading, spacing: 2) {
987 HStack(alignment: .top, spacing: 5) {
988 // Wraps instead of truncating the tags.
989 FlowLayout(spacing: 5, lineSpacing: 3) {
990 if !row.category.isEmpty {
991 HStack(spacing: 5) {
992 Circle().fill(categoryColor).frame(width: 7, height: 7)
993 Text(row.category).lineLimit(1)
994 }
995 }
996 if let detail = row.prefixDetail { Text(detail).lineLimit(1).truncationMode(.middle) }
997 ForEach([row.progress, row.detail].compactMap { $0 }, id: \.self) { progress in
998 Text(progress).monospacedDigit()
999 .padding(.horizontal, 5)
1000 .background(.quaternary.opacity(0.7), in: Capsule())
1001 }
1002 ForEach(row.tags, id: \.self) { tag in
1003 Text(tag).lineLimit(1)
1004 .padding(.horizontal, 5)
1005 .background(.quaternary.opacity(0.7), in: Capsule())
1006 }
1007 }
1008 Spacer(minLength: 4)
1009 marks
1010 }
1011 .font(.caption)
1012 .foregroundStyle(.secondary)
1013 Text(row.title.isEmpty ? " " : row.title)
1014 .font(.body)
1015 .strikethrough(row.isDone)
1016 .foregroundStyle(row.isDone ? .secondary : .primary)
1017 if let habit = row.item?.habit {
1018 HabitStrip(cells: habit.graph(today: day), theme: theme, dark: dark).padding(.top, 3)
1019 }
1020 }
1021 }
1022
1023 /// The TODO keyword and the priority, on the category's line.
1024 private var marks: some View {
1025 HStack(spacing: 5) {
1026 if let todo = row.todo {
1027 let color = theme.todoColor(todo, isDone: row.isDone, dark: dark)?.swiftUI ?? .secondary
1028 HStack(spacing: 2) {
1029 // Done or not without telling green from red.
1030 if withoutColor, row.isDone { Image(systemName: "checkmark") }
1031 Text(todo)
1032 }
1033 .font(.caption2.weight(.semibold))
1034 .foregroundStyle(highContrast ? Color(.systemBackground) : color)
1035 .padding(.horizontal, 6).padding(.vertical, 2)
1036 .background(highContrast ? color : color.opacity(0.14), in: Capsule())
1037 .overlay { if withoutColor, !highContrast { Capsule().strokeBorder(color, lineWidth: 1) } }
1038 }
1039 if let priority = row.priority {
1040 let color = theme.priorityColor(priority, dark: dark)?.swiftUI ?? .orange
1041 Text(priority)
1042 .font(.caption2.weight(.bold))
1043 .foregroundStyle(highContrast ? Color(.systemBackground) : color)
1044 .frame(width: badgeSize, height: badgeSize)
1045 .background(highContrast ? color : color.opacity(0.14), in: Circle())
1046 .overlay(Circle().strokeBorder(color, lineWidth: 1.2))
1047 .accessibilityLabel("Priority \(priority)")
1048 }
1049 }
1050 .fixedSize()
1051 }
1052
1053 private var statusColor: Color {
1054 theme.statusColor(row.status, dark: dark)?.swiftUI ?? .secondary
1055 }
1056
1057 private var categoryColor: Color {
1058 if let event = row.event { return theme.eventColor(event, dark: dark)?.swiftUI ?? .purple }
1059 return theme.categoryColor(row.category, dark: dark).swiftUI
1060 }
1061
1062 /// The start over the end for timed rows, else the status; the icon under them.
1063 private var gutter: some View {
1064 VStack(alignment: .leading, spacing: 2) {
1065 let lines = row.gutterLines
1066 if row.start != nil {
1067 Text(lines[0])
1068 .font(.subheadline.monospacedDigit().weight(.semibold))
1069 .foregroundStyle(row.status == .normal ? Color.primary : row.status == .done ? Color.secondary : statusColor)
1070 if lines.count > 1 {
1071 Text(lines[1]).font(.caption.monospacedDigit()).foregroundStyle(.secondary)
1072 }
1073 } else if !row.gutter.isEmpty {
1074 Text(row.gutter)
1075 .font(.caption.weight(.medium).monospacedDigit())
1076 .foregroundStyle(statusColor)
1077 .lineLimit(2)
1078 .fixedSize(horizontal: false, vertical: true)
1079 }
1080 if let symbol = row.symbol {
1081 Image(systemName: symbol)
1082 .font(.caption2.weight(.semibold))
1083 .imageScale(row.icon == .event ? .small : .medium)
1084 .foregroundStyle(iconColor)
1085 }
1086 }
1087 }
1088
1089 /// The gutter as one line, the icon first, for accessibility sizes.
1090 private var stackedGutter: some View {
1091 HStack(alignment: .firstTextBaseline, spacing: 6) {
1092 if let symbol = row.symbol {
1093 Image(systemName: symbol)
1094 .font(.caption.weight(.semibold))
1095 .imageScale(row.icon == .event ? .small : .medium)
1096 .foregroundStyle(iconColor)
1097 }
1098 Text(row.gutter)
1099 .font(.subheadline.weight(.semibold).monospacedDigit())
1100 .foregroundStyle(row.start != nil && row.status == .normal ? Color.primary : statusColor)
1101 }
1102 }
1103
1104 private var iconColor: Color {
1105 if row.isEvent { return categoryColor }
1106 return row.status == .normal ? Color(.tertiaryLabel) : statusColor
1107 }
1108}
1109
1110/// An `org-agenda-time-grid` line.
1111struct GridLineRow: View {
1112 let time: Int
1113
1114 var body: some View {
1115 HStack(spacing: 6) {
1116 Text(String(format: "%02d:%02d", time / 100, time % 100))
1117 .font(.caption2.monospacedDigit())
1118 Rectangle().fill(Color(.separator)).frame(height: 0.5)
1119 }
1120 .foregroundStyle(.tertiary)
1121 .listRowInsets(EdgeInsets(top: 0, leading: 16, bottom: 0, trailing: 16))
1122 .listRowSeparator(.hidden)
1123 .padding(.vertical, 5)
1124 .accessibilityHidden(true)
1125 }
1126}
1127
1128/// The current time between timed rows, as Org's `now - - -` line.
1129struct NowLine: View {
1130 let time: Date
1131 let color: Color
1132
1133 var body: some View {
1134 HStack(spacing: 6) {
1135 Text(time.formatted(date: .omitted, time: .shortened))
1136 .font(.caption2.weight(.semibold).monospacedDigit())
1137 .foregroundStyle(color)
1138 Circle().fill(color).frame(width: 6, height: 6)
1139 Rectangle().fill(color).frame(height: 1.5)
1140 }
1141 .listRowInsets(EdgeInsets(top: 0, leading: 16, bottom: 0, trailing: 16))
1142 .listRowSeparator(.hidden)
1143 .padding(.vertical, 5)
1144 .accessibilityLabel("Now")
1145 }
1146}
1147
1148/// org-habit's consistency graph, compact: a bar per day, a dot where the habit was done,
1149/// today outlined.
1150struct HabitStrip: View {
1151 let cells: [Habit.Cell]
1152 let theme: ThemeSpec
1153 let dark: Bool
1154
1155 var body: some View {
1156 HStack(spacing: 1) {
1157 ForEach(cells, id: \.day) { cell in
1158 RoundedRectangle(cornerRadius: 1.5)
1159 .fill(color(cell.face))
1160 .frame(width: 4, height: 12)
1161 .overlay {
1162 if cell.glyph == "*" { Circle().fill(.white.opacity(0.9)).frame(width: 3, height: 3) }
1163 }
1164 .overlay {
1165 if cell.glyph == "!" { RoundedRectangle(cornerRadius: 1.5).strokeBorder(Color.primary, lineWidth: 1) }
1166 }
1167 }
1168 }
1169 .accessibilityElement(children: .ignore)
1170 .accessibilityLabel("Done \(cells.filter { $0.glyph == "*" }.count) of the last \(Habit.precedingDays) days")
1171 }
1172
1173 /// Due-state colors, lighter for days to come, as org-habit's faces.
1174 private func color(_ face: Habit.Face) -> Color {
1175 func themed(_ key: String, _ fallback: Color) -> Color { theme.color(key, dark: dark)?.swiftUI ?? fallback }
1176 switch face {
1177 case .clear: return themed("habit-clear", .blue).opacity(0.7)
1178 case .clearFuture: return themed("habit-clear", .blue).opacity(0.3)
1179 case .ready: return themed("habit-ready", .green).opacity(0.8)
1180 case .readyFuture: return themed("habit-ready", .green).opacity(0.3)
1181 case .alert: return themed("habit-alert", .yellow).opacity(0.85)
1182 case .alertFuture: return themed("habit-alert", .yellow).opacity(0.35)
1183 case .overdue: return themed("habit-overdue", .red).opacity(0.8)
1184 case .overdueFuture: return themed("habit-overdue", .red).opacity(0.3)
1185 }
1186 }
1187}
1188
1189/// A date to go to or to schedule on.
1190struct DateSheet: View {
1191 let title: LocalizedStringKey
1192 let action: LocalizedStringKey
1193 let initial: Date
1194 let done: (Date?) -> Void
1195 @State private var date = Date()
1196
1197 var body: some View {
1198 NavigationStack {
1199 DatePicker(title, selection: $date, displayedComponents: .date)
1200 .datePickerStyle(.graphical)
1201 .padding(.horizontal)
1202 .navigationTitle(title)
1203 .navigationBarTitleDisplayMode(.inline)
1204 .toolbar {
1205 ToolbarItem(placement: .cancellationAction) { Button("Cancel") { done(nil) } }
1206 ToolbarItem(placement: .confirmationAction) { Button(action) { done(date) } }
1207 }
1208 Spacer()
1209 }
1210 .presentationDetents([.medium, .large])
1211 .onAppear { date = initial }
1212 }
1213}
1214
1215// Module names on both, so the Xcode target, where OrgCore is another package, doesn't warn.
1216extension OrgCore.AgendaItem: Swift.Identifiable {
1217 public var id: String { "\(path ?? "")|\(headingOffset ?? -1)|\(kind.rawValue)|\(text)" }
1218
1219 /// An entry, not a time-grid line.
1220 var isEntry: Bool { kind != .timeGrid && kind != .currentTime }
1221}
1222
1223/// Org's agenda filter: tags and categories of the entries shown, kept or left out, or the
1224/// filter typed as `/` takes it.
1225struct FilterSheet: View {
1226 @Binding var filter: AgendaFilter
1227 let items: [AgendaItem]
1228 @State private var typed = ""
1229 @Environment(\.dismiss) private var dismiss
1230
1231 var body: some View {
1232 let tags = Set(items.flatMap(\.tags)).sorted()
1233 let categories = Set(items.filter { $0.path != nil }.map(\.category)).sorted()
1234 NavigationStack {
1235 Form {
1236 Section {
1237 TextField("+work-home", text: $typed)
1238 .autocorrectionDisabled()
1239 .textInputAutocapitalization(.never)
1240 .onSubmit(apply)
1241 } footer: {
1242 Text("As Org's / filter: +keep and -drop tags or categories, <0:30 for effort, /regexp/.")
1243 }
1244 if !tags.isEmpty {
1245 Section("Tags") { ForEach(tags, id: \.self) { term($0, in: \.tags) } }
1246 }
1247 if !categories.isEmpty {
1248 Section("Categories") { ForEach(categories, id: \.self) { term($0, in: \.categories) } }
1249 }
1250 }
1251 .navigationTitle("Filter")
1252 .navigationBarTitleDisplayMode(.inline)
1253 .toolbar {
1254 ToolbarItem(placement: .cancellationAction) { Button("Clear") { filter = AgendaFilter(); dismiss() } }
1255 ToolbarItem(placement: .confirmationAction) { Button("Done") { apply(); dismiss() } }
1256 }
1257 }
1258 .onAppear { typed = filter.description }
1259 }
1260
1261 /// Keep, leave out, or no filter on `name`.
1262 private func term(_ name: String, in list: WritableKeyPath<AgendaFilter, [String]>) -> some View {
1263 let state = filter[keyPath: list].contains("+" + name) ? 1 : filter[keyPath: list].contains("-" + name) ? -1 : 0
1264 return Button {
1265 var terms = filter[keyPath: list].filter { $0.dropFirst() != Substring(name) }
1266 if state == 0 { terms.append("+" + name) } else if state == 1 { terms.append("-" + name) }
1267 filter[keyPath: list] = terms
1268 typed = filter.description
1269 } label: {
1270 HStack {
1271 Text(name).foregroundStyle(.primary)
1272 Spacer()
1273 Text(state == 1 ? "Keep" : state == -1 ? "Leave out" : "").foregroundStyle(.secondary)
1274 }
1275 }
1276 }
1277
1278 private func apply() {
1279 guard typed != filter.description else { return }
1280 let tags = Set(items.flatMap(\.tags))
1281 let categories = Set(items.map(\.category))
1282 filter = AgendaFilter().parse(typed, tags: tags, categories: categories).filter
1283 }
1284}
1285
1286/// Where to refile an entry: each file, at its end, and the headings in it down to level 3,
1287/// as the Mac's prompt offers them, searchable by their path.
1288struct RefileSheet: View {
1289 let targets: [RefileTarget]
1290 /// `org-refile-allow-creating-parent-nodes`: `parent/new` in the search field offers to
1291 /// add the heading.
1292 var create: ((RefileTarget, String) -> Void)?
1293 var title = String(localized: "Refile to")
1294 let choose: (RefileTarget?) -> Void
1295 @State private var query = ""
1296
1297 /// Targets by file, in the order given, each file's own row first.
1298 private var files: [(path: String, targets: [RefileTarget])] {
1299 var order: [String] = []
1300 var byPath: [String: [RefileTarget]] = [:]
1301 for target in targets where query.isEmpty || target.label.localizedCaseInsensitiveContains(query) {
1302 if byPath[target.path] == nil { order.append(target.path) }
1303 byPath[target.path, default: []].append(target)
1304 }
1305 return order.map { ($0, byPath[$0] ?? []) }
1306 }
1307
1308 var body: some View {
1309 NavigationStack {
1310 List {
1311 if let create, let (parent, child) = RefileSettings.newNode(query, in: targets) {
1312 Button {
1313 create(parent, child)
1314 } label: {
1315 Label("New heading “\(child)” under \(parent.label)", systemImage: "plus")
1316 }
1317 }
1318 ForEach(files, id: \.path) { file in
1319 Section {
1320 ForEach(file.targets, id: \.self) { target in
1321 Button {
1322 choose(target)
1323 } label: {
1324 HStack(spacing: 6) {
1325 if target.start == nil {
1326 Image(systemName: "doc.text").foregroundStyle(.secondary)
1327 Text(target.label)
1328 } else {
1329 Text(String(repeating: " ", count: max(0, target.level - 1)) + target.title)
1330 }
1331 }
1332 }
1333 .foregroundStyle(.primary)
1334 }
1335 }
1336 }
1337 }
1338 .searchable(text: $query, placement: .navigationBarDrawer(displayMode: .always))
1339 .navigationTitle(title)
1340 .navigationBarTitleDisplayMode(.inline)
1341 .toolbar { ToolbarItem(placement: .cancellationAction) { Button("Cancel") { choose(nil) } } }
1342 }
1343 }
1344}
1345/// A view built when the list draws it: a list makes every row's view up front, and a row's
1346/// actions and menus cost more than the row.
1347private struct Deferred<Content: View>: View {
1348 @ViewBuilder let content: () -> Content
1349
1350 var body: some View { content() }
1351}
1352#endif