Sources/Orgstar/AgendaSidebar.swift

73b5c3d29343d6a3801f3a9a591fa434c01c9f06
orgstar/Sources/Orgstar/AgendaSidebar.swift

185 lines · 8530 bytes

7 symbols in this file
  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    @Environment(\.textScale) private var scale
 28
 29    init(workspace: WorkspaceModel, session: DocumentSession, commands: AppCommands, hour: Int, showsAgenda: Binding<Bool>) {
 30        self.workspace = workspace
 31        self.session = session
 32        self.commands = commands
 33        self.hour = hour
 34        _showsAgenda = showsAgenda
 35        _agenda = State(initialValue: AgendaModel(workspace: workspace))
 36    }
 37
 38    private struct Key: Equatable {
 39        var view: String
 40        var mode: AgendaMode?
 41        var settings: [String]
 42        var hidden: Set<String>
 43        var files: Int
 44        var changed: Int?
 45        var edits: Int
 46        var hour: Int
 47    }
 48
 49    private var view: AgendaViewDefinition { views.first { $0.name == viewName } ?? AgendaViewLoader.builtIn[0] }
 50
 51    /// A section of rows under a header: a day, or a list or block's title.
 52    private struct Group: Identifiable {
 53        let id: String
 54        let header: String
 55        var isToday = false
 56        var rows: [AgendaRow]
 57    }
 58
 59    private var groups: [Group] {
 60        func days(_ groups: [AgendaDayGroup], prefix: String) -> [Group] {
 61            groups.map { day in
 62                // Org pads the day's name with spaces.
 63                Group(id: "\(prefix)\(day.day)", header: day.header.split(whereSeparator: \.isWhitespace).joined(separator: " "),
 64                      isToday: day.isToday, rows: day.overdue + day.rows)
 65            }
 66        }
 67        func list(_ items: [AgendaItem]) -> [AgendaRow] {
 68            items.compactMap { AgendaRow(item: $0, day: agenda.today, today: agenda.today) }
 69        }
 70        switch agenda.mode {
 71        case .agenda:
 72            return days(agenda.groups(), prefix: "")
 73        case .blocks:
 74            return agenda.blocks.enumerated().flatMap { index, block in
 75                block.isAgenda
 76                    ? days(agenda.groups(block, showAllDates: false, filter: AgendaFilter()), prefix: "b\(index):")
 77                    : [Group(id: "b\(index)", header: block.header, rows: list(block.list))]
 78            }
 79        default:
 80            return [Group(id: "list", header: agenda.viewSettings[agenda.mode]?.header ?? agenda.mode.title, rows: list(agenda.list))]
 81        }
 82    }
 83
 84    var body: some View {
 85        let groups = groups
 86        List {
 87            if groups.allSatisfy(\.rows.isEmpty) {
 88                Text("Nothing scheduled").font(.scaled(.body, scale)).foregroundStyle(.secondary)
 89            }
 90            ForEach(groups) { group in
 91                if !group.rows.isEmpty {
 92                    Section {
 93                        ForEach(Array(group.rows.enumerated()), id: \.offset) { _, row in line(row) }
 94                    } header: {
 95                        Text(group.header).font(.scaled(.subheadline, scale).weight(.semibold)).foregroundStyle((group.isToday ? theme.color("agenda-today") : theme.color("sidebar-header")) ?? .secondary)
 96                    }
 97                }
 98            }
 99        }
100        .listStyle(.sidebar)
101        .themedListBackground(theme.color("sidebar-background", in: colorScheme))
102        .safeAreaInset(edge: .bottom, spacing: 0) {
103            SidebarBar(showsAgenda: $showsAgenda) {
104                Menu {
105                    ForEach(views) { view in Button(view.name) { viewName = view.name } }
106                    Divider()
107                    Button("Open Agenda Window") { openWindow(id: "agenda") }
108                } label: {
109                    Text(view.name)
110                }
111                .fixedSize()
112                .help("The agenda view shown here; add views in views.toml")
113            }
114        }
115        .task(id: Key(
116            view: viewName, mode: views.first { $0.name == viewName }?.mode, settings: ["\(span)", "\(startOffset)", startOnWeekday, "\(includeSubfolders)", agendaFileList],
117            hidden: HiddenFolders.shared.all, files: workspace.files.count, changed: workspace.changedFile?.version, edits: session.editVersion, hour: hour
118        )) { await refresh() }
119    }
120
121    @ViewBuilder
122    private func line(_ row: AgendaRow) -> some View {
123        let label = HStack(alignment: .firstTextBaseline, spacing: 6) {
124            if !row.gutter.isEmpty {
125                Text(row.gutter)
126                    .font(.scaled(.caption, scale))
127                    .monospacedDigit()
128                    .foregroundStyle(theme.dynamic(.secondaryLabelColor) { [theme] in theme.statusColor(row.status, dark: $0) })
129                    .frame(width: 52 * scale, alignment: .trailing)
130                    .lineLimit(1)
131                    .minimumScaleFactor(0.7)
132            }
133            VStack(alignment: .leading, spacing: 1) {
134                HStack(alignment: .firstTextBaseline, spacing: 4) {
135                    if let todo = row.todo {
136                        Text(todo)
137                            .font(.scaled(.caption, scale).bold())
138                            .foregroundStyle(theme.dynamic(row.isDone ? .systemGreen : .systemRed) { [theme] in theme.todoColor(todo, isDone: row.isDone, dark: $0) })
139                    }
140                    Text(row.title.isEmpty ? "(untitled)" : row.title)
141                        .font(.scaled(.body, scale))
142                        .lineLimit(2)
143                        .strikethrough(row.isDone)
144                        .foregroundStyle(row.isDone ? .secondary : theme.color("sidebar-foreground") ?? .primary)
145                }
146                if !row.category.isEmpty {
147                    Text(row.category).font(.scaled(.caption2, scale)).foregroundStyle(.secondary).lineLimit(1)
148                }
149            }
150        }
151        .opacity(row.isBlocked ? 0.5 : 1)
152        if let item = row.item, let path = item.path, let offset = item.headingOffset ?? item.markerOffset {
153            Button {
154                commands.jump(path: path, offset: offset)
155            } label: {
156                label.frame(maxWidth: .infinity, alignment: .leading).contentShape(Rectangle())
157            }
158            .buttonStyle(.plain)
159            .help((path as NSString).lastPathComponent)
160        } else {
161            label
162        }
163    }
164
165    private func refresh() async {
166        let loaded = AgendaViewLoader.load()
167        views = loaded.views
168        agenda.viewSettings = AgendaViewLoader.settings(loaded.views)
169        agenda.mode = view.mode
170        agenda.span = span
171        agenda.startOffset = startOffset
172        agenda.startOnWeekday = Int(startOnWeekday)
173        agenda.includeSubfolders = includeSubfolders
174        agenda.excludeArchives = OrgPreferences.agendaExcludeArchives()
175        agenda.hiddenFolders = HiddenFolders.shared.all
176        agenda.agendaFiles = OrgPreferences.agendaFiles()
177        agenda.options = OrgPreferences.agendaOptions(agenda.options)
178        let pro = ProAccess.shared.isUnlocked
179        agenda.calendarEvents = pro && OrgPreferences.calendarEvents() && CalendarEvents.isAuthorized ? CalendarAccess.events : nil
180        agenda.calendarNames = OrgPreferences.calendarEventCalendars()
181        agenda.reminderLists = pro && OrgPreferences.agendaReminders() && ReminderLists.isAuthorized ? CalendarAccess.reminders : nil
182        agenda.reminderListNames = OrgPreferences.agendaReminderLists()
183        await agenda.refresh(open: session.openTexts)
184    }
185}
Keyboard shortcuts

Global

⌘K
Command palette & jump
/
Focus search
?
Show this help
g d
Dashboard
g e
Explore repositories
g n
Notifications

Repository & editor

t
Find file in repository
y
Copy immutable SHA permalink
g c
Code tab
g i
Issues tab
g m
Merge requests tab
g b
Builds tab
⌘↵
Submit active form