Sources/Orgstar/AgendaSidebar.swift
183 lines · 8292 bytes
1import OrgApp
2import OrgCore
3import OrgPresentation
4import SwiftUI
5
6/// The sidebar's agenda: 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 @Binding var showsAgenda: Bool
16 @State private var agenda: AgendaModel
17 @State private var views = AgendaViewLoader.builtIn
18 @AppStorage("sidebarAgendaView") private var viewName = AgendaViewLoader.builtIn[0].name
19 @AppStorage("agendaSpan") private var span = 10
20 @AppStorage("agendaStartOffset") private var startOffset = 0
21 @AppStorage("agendaStartOnWeekday") private var startOnWeekday = "1"
22 @AppStorage("agendaSubfolders") private var includeSubfolders = false
23 @AppStorage("agendaFiles") private var agendaFileList = ""
24 @Environment(\.orgTheme) private var theme
25 @Environment(\.colorScheme) private var colorScheme
26 @Environment(\.openWindow) private var openWindow
27
28 init(workspace: WorkspaceModel, session: DocumentSession, commands: AppCommands, hour: Int, showsAgenda: Binding<Bool>) {
29 self.workspace = workspace
30 self.session = session
31 self.commands = commands
32 self.hour = hour
33 _showsAgenda = showsAgenda
34 _agenda = State(initialValue: AgendaModel(workspace: workspace))
35 }
36
37 private struct Key: Equatable {
38 var view: String
39 var mode: AgendaMode?
40 var settings: [String]
41 var hidden: Set<String>
42 var files: Int
43 var changed: Int?
44 var edits: Int
45 var hour: Int
46 }
47
48 private var view: AgendaViewDefinition { views.first { $0.name == viewName } ?? AgendaViewLoader.builtIn[0] }
49
50 /// A section of rows under a header: a day, or a list or block's title.
51 private struct Group: Identifiable {
52 let id: String
53 let header: String
54 var isToday = false
55 var rows: [AgendaRow]
56 }
57
58 private var groups: [Group] {
59 func days(_ groups: [AgendaDayGroup], prefix: String) -> [Group] {
60 groups.map { day in
61 // Org pads the day's name with spaces.
62 Group(id: "\(prefix)\(day.day)", header: day.header.split(whereSeparator: \.isWhitespace).joined(separator: " "),
63 isToday: day.isToday, rows: day.overdue + day.rows)
64 }
65 }
66 func list(_ items: [AgendaItem]) -> [AgendaRow] {
67 items.compactMap { AgendaRow(item: $0, day: agenda.today, today: agenda.today) }
68 }
69 switch agenda.mode {
70 case .agenda:
71 return days(agenda.groups(), prefix: "")
72 case .blocks:
73 return agenda.blocks.enumerated().flatMap { index, block in
74 block.isAgenda
75 ? days(agenda.groups(block, showAllDates: false, filter: AgendaFilter()), prefix: "b\(index):")
76 : [Group(id: "b\(index)", header: block.header, rows: list(block.list))]
77 }
78 default:
79 return [Group(id: "list", header: agenda.viewSettings[agenda.mode]?.header ?? agenda.mode.title, rows: list(agenda.list))]
80 }
81 }
82
83 var body: some View {
84 let groups = groups
85 List {
86 if groups.allSatisfy(\.rows.isEmpty) {
87 Text("Nothing scheduled").foregroundStyle(.secondary)
88 }
89 ForEach(groups) { group in
90 if !group.rows.isEmpty {
91 Section {
92 ForEach(Array(group.rows.enumerated()), id: \.offset) { _, row in line(row) }
93 } header: {
94 Text(group.header).foregroundStyle((group.isToday ? theme.color("agenda-today") : theme.color("sidebar-header")) ?? .secondary)
95 }
96 }
97 }
98 }
99 .listStyle(.sidebar)
100 .themedListBackground(theme.color("sidebar-background", in: colorScheme))
101 .safeAreaInset(edge: .bottom, spacing: 0) {
102 SidebarBar(showsAgenda: $showsAgenda) {
103 Menu {
104 ForEach(views) { view in Button(view.name) { viewName = view.name } }
105 Divider()
106 Button("Open Agenda Window") { openWindow(id: "agenda") }
107 } label: {
108 Text(view.name)
109 }
110 .fixedSize()
111 .help("The agenda view shown here; add views in views.toml")
112 }
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}