Sources/Orgstar/AgendaSidebar.swift
183 lines · 8197 bytes
1import OrgApp
2import OrgCore
3import OrgPresentation
4import SwiftUI
5
6/// The sidebar's Agenda tab: the agenda, or one of the named views, as a narrow list beside the
7/// editor. A click on an entry shows it in the editor. It follows the Agenda window's span and
8/// files, and shows Calendar events and Reminders only once the Agenda window has asked for them.
9struct AgendaSidebar: View {
10 let workspace: WorkspaceModel
11 let session: DocumentSession
12 let commands: AppCommands
13 /// Changes every hour, so that the day rolls over.
14 let hour: Int
15 @State private var agenda: AgendaModel
16 @State private var views = AgendaViewLoader.builtIn
17 @AppStorage("sidebarAgendaView") private var viewName = AgendaViewLoader.builtIn[0].name
18 @AppStorage("agendaSpan") private var span = 10
19 @AppStorage("agendaStartOffset") private var startOffset = 0
20 @AppStorage("agendaStartOnWeekday") private var startOnWeekday = "1"
21 @AppStorage("agendaSubfolders") private var includeSubfolders = false
22 @AppStorage("agendaFiles") private var agendaFileList = ""
23 @Environment(\.orgTheme) private var theme
24 @Environment(\.colorScheme) private var colorScheme
25 @Environment(\.openWindow) private var openWindow
26
27 init(workspace: WorkspaceModel, session: DocumentSession, commands: AppCommands, hour: Int) {
28 self.workspace = workspace
29 self.session = session
30 self.commands = commands
31 self.hour = hour
32 _agenda = State(initialValue: AgendaModel(workspace: workspace))
33 }
34
35 private struct Key: Equatable {
36 var view: String
37 var mode: AgendaMode?
38 var settings: [String]
39 var hidden: Set<String>
40 var files: Int
41 var changed: Int?
42 var edits: Int
43 var hour: Int
44 }
45
46 private var view: AgendaViewDefinition { views.first { $0.name == viewName } ?? AgendaViewLoader.builtIn[0] }
47
48 /// A section of rows under a header: a day, or a list or block's title.
49 private struct Group: Identifiable {
50 let id: String
51 let header: String
52 var isToday = false
53 var rows: [AgendaRow]
54 }
55
56 private var groups: [Group] {
57 func days(_ groups: [AgendaDayGroup], prefix: String) -> [Group] {
58 groups.map { day in
59 // Org pads the day's name with spaces.
60 Group(id: "\(prefix)\(day.day)", header: day.header.split(whereSeparator: \.isWhitespace).joined(separator: " "),
61 isToday: day.isToday, rows: day.overdue + day.rows)
62 }
63 }
64 func list(_ items: [AgendaItem]) -> [AgendaRow] {
65 items.compactMap { AgendaRow(item: $0, day: agenda.today, today: agenda.today) }
66 }
67 switch agenda.mode {
68 case .agenda:
69 return days(agenda.groups(), prefix: "")
70 case .blocks:
71 return agenda.blocks.enumerated().flatMap { index, block in
72 block.isAgenda
73 ? days(agenda.groups(block, showAllDates: false, filter: AgendaFilter()), prefix: "b\(index):")
74 : [Group(id: "b\(index)", header: block.header, rows: list(block.list))]
75 }
76 default:
77 return [Group(id: "list", header: agenda.viewSettings[agenda.mode]?.header ?? agenda.mode.title, rows: list(agenda.list))]
78 }
79 }
80
81 var body: some View {
82 let groups = groups
83 List {
84 if groups.allSatisfy(\.rows.isEmpty) {
85 Text("Nothing scheduled").foregroundStyle(.secondary)
86 }
87 ForEach(groups) { group in
88 if !group.rows.isEmpty {
89 Section {
90 ForEach(Array(group.rows.enumerated()), id: \.offset) { _, row in line(row) }
91 } header: {
92 Text(group.header).foregroundStyle((group.isToday ? theme.color("agenda-today") : theme.color("sidebar-header")) ?? .secondary)
93 }
94 }
95 }
96 }
97 .safeAreaInset(edge: .top, spacing: 0) {
98 HStack {
99 Menu {
100 ForEach(views) { view in Button(view.name) { viewName = view.name } }
101 Divider()
102 Button("Open Agenda Window") { openWindow(id: "agenda") }
103 } label: {
104 Text(view.name)
105 }
106 .menuStyle(.borderlessButton)
107 .fixedSize()
108 .help("The agenda view shown here; add views in views.toml")
109 Spacer()
110 }
111 .padding(.horizontal, 12)
112 .padding(.vertical, 4)
113 }
114 .task(id: Key(
115 view: viewName, mode: views.first { $0.name == viewName }?.mode, settings: ["\(span)", "\(startOffset)", startOnWeekday, "\(includeSubfolders)", agendaFileList],
116 hidden: HiddenFolders.shared.all, files: workspace.files.count, changed: workspace.changedFile?.version, edits: session.editVersion, hour: hour
117 )) { await refresh() }
118 }
119
120 @ViewBuilder
121 private func line(_ row: AgendaRow) -> some View {
122 let label = HStack(alignment: .firstTextBaseline, spacing: 6) {
123 if !row.gutter.isEmpty {
124 Text(row.gutter)
125 .font(.caption)
126 .monospacedDigit()
127 .foregroundStyle(theme.dynamic(.secondaryLabelColor) { [theme] in theme.statusColor(row.status, dark: $0) })
128 .frame(width: 52, alignment: .trailing)
129 .lineLimit(1)
130 .minimumScaleFactor(0.7)
131 }
132 VStack(alignment: .leading, spacing: 1) {
133 HStack(alignment: .firstTextBaseline, spacing: 4) {
134 if let todo = row.todo {
135 Text(todo)
136 .font(.caption.bold())
137 .foregroundStyle(theme.dynamic(row.isDone ? .systemGreen : .systemRed) { [theme] in theme.todoColor(todo, isDone: row.isDone, dark: $0) })
138 }
139 Text(row.title.isEmpty ? "(untitled)" : row.title)
140 .lineLimit(2)
141 .strikethrough(row.isDone)
142 .foregroundStyle(row.isDone ? .secondary : theme.color("sidebar-foreground") ?? .primary)
143 }
144 if !row.category.isEmpty {
145 Text(row.category).font(.caption2).foregroundStyle(.secondary).lineLimit(1)
146 }
147 }
148 }
149 .opacity(row.isBlocked ? 0.5 : 1)
150 if let item = row.item, let path = item.path, let offset = item.headingOffset ?? item.markerOffset {
151 Button {
152 commands.jump(path: path, offset: offset)
153 } label: {
154 label.frame(maxWidth: .infinity, alignment: .leading).contentShape(Rectangle())
155 }
156 .buttonStyle(.plain)
157 .help((path as NSString).lastPathComponent)
158 } else {
159 label
160 }
161 }
162
163 private func refresh() async {
164 let loaded = AgendaViewLoader.load()
165 views = loaded.views
166 agenda.viewSettings = AgendaViewLoader.settings(loaded.views)
167 agenda.mode = view.mode
168 agenda.span = span
169 agenda.startOffset = startOffset
170 agenda.startOnWeekday = Int(startOnWeekday)
171 agenda.includeSubfolders = includeSubfolders
172 agenda.excludeArchives = OrgPreferences.agendaExcludeArchives()
173 agenda.hiddenFolders = HiddenFolders.shared.all
174 agenda.agendaFiles = OrgPreferences.agendaFiles()
175 agenda.options = OrgPreferences.agendaOptions(agenda.options)
176 let pro = ProAccess.shared.isUnlocked
177 agenda.calendarEvents = pro && OrgPreferences.calendarEvents() && CalendarEvents.isAuthorized ? CalendarAccess.events : nil
178 agenda.calendarNames = OrgPreferences.calendarEventCalendars()
179 agenda.reminderLists = pro && OrgPreferences.agendaReminders() && ReminderLists.isAuthorized ? CalendarAccess.reminders : nil
180 agenda.reminderListNames = OrgPreferences.agendaReminderLists()
181 await agenda.refresh(open: session.openTexts)
182 }
183}