Sources/Orgstar/AgendaView.swift

9a7439fd01e4ce5041bc5fab90542f083143ae10
orgstar/Sources/Orgstar/AgendaView.swift history · blame · raw

1278 lines · 55502 bytes

   1import AppKit
   2import OrgApp
   3import OrgDocument
   4import OrgCore
   5import OrgPresentation
   6import SwiftUI
   7
   8/// The days an agenda shows, as Org's `v d`, `v w` and `v m`.
   9enum AgendaSpan: String, CaseIterable {
  10    case day, week, month
  11}
  12
  13/// The app's one reader of Calendar events, for the agenda and Settings.
  14@MainActor
  15enum CalendarAccess {
  16    static let events = CalendarEvents()
  17}
  18
  19/// The agenda window: the day/week agenda, the TODO list, tag matches, text search and saved views.
  20/// Return or a double click jumps to the entry in the main window. Keys as in Emacs's agenda:
  21/// n/p (or the arrows) move between lines, f/b/. move the span, j picks a date, v d/v w/v m (or
  22/// d/w) show a day, week or month, g refreshes, l shows the log (closed and clocked), / filters
  23/// (`+cat-tag<0:10-/regexp/`), \ by tag, < by the line's category, = by regexp, _ by effort,
  24/// | clears filters, I/O/X clock in, out and cancel, C-c C-w refiles, $ archives, m/u/U mark
  25/// and unmark, B acts on the marked entries, t cycles the TODO state, +/- change the priority and
  26/// , sets it, : or C-c C-q sets tags, C-c C-s / C-c C-d schedule and set a deadline, S-→/S-← move
  27/// the date, k captures on the line's day, s saves all files, TAB and SPC show the entry.
  28struct AgendaView: View {
  29    let workspace: WorkspaceModel
  30    let session: DocumentSession
  31    let commands: AppCommands
  32    let scheduler: ReminderScheduler?
  33    let clock: ClockModel
  34    @State private var agenda: AgendaModel
  35    @State private var views = AgendaViewLoader.builtIn
  36    @State private var viewName = AgendaViewLoader.builtIn[0].name
  37    @State private var matchText = ""
  38    /// The selected line: `day:index` (`day:o` + index in the overdue group), or `list:index`.
  39    @State private var selection: String?
  40    @State private var tick = 0
  41    /// The time the now line shows, kept to the minute while the agenda is open.
  42    @State private var now = Date()
  43    /// The view picker moved to the agenda for a followed timestamp, which sets its own days.
  44    @State private var keepRequestedDays = false
  45    @State private var message: String?
  46    @State private var prompt: PendingPrompt?
  47    @State private var promptText = ""
  48    @State private var prefix: String?
  49    /// Entries marked for a bulk action.
  50    @State private var marked: [EntryRef] = []
  51    @State private var logMode = false
  52    @State private var filter = AgendaFilter()
  53    /// A filter question: its title and which filter it sets.
  54    @State private var filterPrompt: (title: String, kind: Character)?
  55    @State private var filterText = ""
  56    /// A one-line question for an agenda action, and what to do with the answer.
  57    struct TextPrompt {
  58        let title: String
  59        let apply: (String) -> Void
  60    }
  61    @State private var textPrompt: TextPrompt?
  62    @State private var textAnswer = ""
  63    /// Day, week or month chosen with `v`; nil shows the span the settings or the view give.
  64    @State private var spanKind: AgendaSpan?
  65    @State private var showingDatePicker = false
  66    @State private var pickedDate = Date()
  67    @AppStorage("agendaOverdueExpanded") private var overdueShown = true
  68    @State private var hovered: String?
  69    @FocusState private var focused: Bool
  70    @AppStorage("agendaSpan") private var span = 10
  71    @AppStorage("agendaStartOffset") private var startOffset = 0
  72    @AppStorage("agendaSubfolders") private var includeSubfolders = false
  73    @AppStorage("agendaShowAllDates") private var showAllDates = false
  74    @AppStorage("calendarEvents") private var calendarEventsOn = false
  75    @AppStorage("calendarEventCalendars") private var calendarNames = ""
  76    @AppStorage("agendaPrefixAgenda") private var prefixAgenda = PrefixFormat.defaults["agenda"]!
  77    @AppStorage("agendaPrefixTodo") private var prefixTodo = PrefixFormat.defaults["todo"]!
  78    @AppStorage("agendaPrefixTags") private var prefixTags = PrefixFormat.defaults["tags"]!
  79    @Environment(\.openWindow) private var openWindow
  80
  81    static let match = "Match…"
  82    static let todoMatch = "TODO Match…"
  83    static let search = "Search…"
  84    static let todoSearch = "TODO Search…"
  85
  86    init(workspace: WorkspaceModel, session: DocumentSession, commands: AppCommands, scheduler: ReminderScheduler?, clock: ClockModel) {
  87        self.workspace = workspace
  88        self.session = session
  89        self.commands = commands
  90        self.scheduler = scheduler
  91        self.clock = clock
  92        _agenda = State(initialValue: AgendaModel(workspace: workspace))
  93    }
  94
  95    /// An agenda entry by its file, heading line and where that line was.
  96    struct EntryRef: Hashable {
  97        let path: String
  98        let line: String
  99        let offset: Int
 100
 101        init?(_ item: AgendaItem) {
 102            guard let path = item.path, let line = item.headingLine, let offset = item.headingOffset else { return nil }
 103            self.path = path
 104            self.line = line
 105            self.offset = offset
 106        }
 107    }
 108
 109    struct PendingPrompt: Identifiable {
 110        let id = UUID()
 111        let prompt: Prompt
 112        let command: any OrgCommand
 113        let atMarker: Bool
 114        let answers: [String: String]
 115        let itemID: String
 116    }
 117
 118    private struct RefreshKey: Hashable {
 119        var mode: AgendaMode
 120        var start: Int?
 121        var span: Int
 122        var startOffset: Int
 123        var includeSubfolders: Bool
 124        var prefix: [String]
 125        var logMode: Bool
 126        var calendars: [String]
 127        var files: Int
 128        var changed: Int?
 129        var edits: Int
 130        var path: String?
 131        var tick: Int
 132    }
 133
 134    /// The settings part of the refresh key; `Refresher` adds the files and edits, so that
 135    /// they redraw only it.
 136    private var refreshKey: RefreshKey {
 137        RefreshKey(
 138            mode: agenda.mode, start: agenda.start, span: span, startOffset: startOffset, includeSubfolders: includeSubfolders, prefix: [prefixAgenda, prefixTodo, prefixTags], logMode: logMode,
 139            calendars: calendarEventsOn ? [calendarNames] : [], files: 0, changed: nil, edits: 0, path: nil, tick: tick
 140        )
 141    }
 142
 143    private func refresh() async {
 144        agenda.span = span
 145        agenda.startOffset = startOffset
 146        agenda.includeSubfolders = includeSubfolders
 147        agenda.options.prefixFormat = ["agenda": prefixAgenda, "todo": prefixTodo, "tags": prefixTags]
 148        agenda.options.logMode = logMode
 149        agenda.options = OrgPreferences.agendaOptions(agenda.options)
 150        agenda.calendarNames = OrgPreferences.calendarEventCalendars()
 151        if calendarEventsOn, isAgenda {
 152            agenda.calendarEvents = await CalendarAccess.events.requestAccess() ? CalendarAccess.events : nil
 153        } else {
 154            agenda.calendarEvents = nil
 155        }
 156        await agenda.refresh(open: session.openTexts)
 157    }
 158
 159    /// Refreshes the agenda when the settings, files or edits change, once a burst of them ends.
 160    private struct Refresher: View {
 161        let base: RefreshKey
 162        let session: DocumentSession
 163        let workspace: WorkspaceModel
 164        let refresh: () async -> Void
 165
 166        private var key: RefreshKey {
 167            var key = base
 168            key.files = workspace.files.count
 169            key.changed = workspace.changedFile?.version
 170            key.edits = session.editVersion
 171            key.path = session.path
 172            return key
 173        }
 174
 175        var body: some View {
 176            Color.clear.task(id: key) {
 177                try? await Task.sleep(for: .milliseconds(150))
 178                guard !Task.isCancelled else { return }
 179                await refresh()
 180            }
 181        }
 182    }
 183
 184    private var isAgenda: Bool {
 185        if case .agenda = agenda.mode { return true }
 186        return false
 187    }
 188
 189    private var isMatch: Bool { viewName == Self.match || viewName == Self.todoMatch }
 190    private var isSearch: Bool { viewName == Self.search || viewName == Self.todoSearch }
 191
 192    @Environment(\.orgTheme) private var theme
 193
 194    // MARK: - Lines
 195
 196    /// A selectable line: its selection id, the row, and the day it is on.
 197    struct Line {
 198        let id: String
 199        let row: AgendaRow
 200        let day: Int
 201    }
 202
 203    private var groups: [AgendaDayGroup] {
 204        isAgenda ? agenda.groups(showAllDates: showAllDates, filter: filter) : []
 205    }
 206
 207    private var listRows: [AgendaRow] {
 208        isAgenda ? [] : agenda.list.filter(filter.keeps).compactMap { AgendaRow(item: $0, day: agenda.today, today: agenda.today) }
 209    }
 210
 211    /// The lines in order, as up and down move through them.
 212    private func lines(_ groups: [AgendaDayGroup]) -> [Line] {
 213        guard isAgenda else { return listRows.enumerated().map { Line(id: "list:\($0.offset)", row: $0.element, day: agenda.today) } }
 214        return groups.flatMap { group in
 215            (overdueShown ? group.overdue.enumerated().map { Line(id: "\(group.day):o\($0.offset)", row: $0.element, day: group.day) } : [])
 216                + group.rows.enumerated().map { Line(id: "\(group.day):\($0.offset)", row: $0.element, day: group.day) }
 217        }
 218    }
 219
 220    private func line(_ id: String) -> Line? { lines(groups).first { $0.id == id } }
 221
 222    var body: some View {
 223        let groups = self.groups
 224        _ = tick
 225        return ScrollViewReader { proxy in
 226            ScrollView {
 227                LazyVStack(alignment: .leading, spacing: 0, pinnedViews: [.sectionHeaders]) {
 228                    if isAgenda {
 229                        ForEach(groups) { group in
 230                            Section {
 231                                dayRows(group)
 232                            } header: {
 233                                dayHeader(group).id("day\(group.day)")
 234                            }
 235                        }
 236                    } else {
 237                        Section {
 238                            ForEach(Array(listRows.enumerated()), id: \.offset) { index, row in
 239                                rowView(Line(id: "list:\(index)", row: row, day: agenda.today), showsGutter: false)
 240                            }
 241                        } header: {
 242                            header { Text(listTitle).font(.system(size: 13, weight: .semibold)) }
 243                        }
 244                    }
 245                }
 246                .padding(.bottom, 12)
 247            }
 248            .onChange(of: selection) {
 249                if let selection { proxy.scrollTo(selection) }
 250            }
 251            .onChange(of: agenda.days.first?.day) {
 252                if groups.contains(where: \.isToday) { proxy.scrollTo("day\(agenda.today)", anchor: .top) }
 253            }
 254        }
 255        .background(theme.color("agenda-background") ?? Color(nsColor: .textBackgroundColor))
 256        .focusable()
 257        .focusEffectDisabled()
 258        .focused($focused)
 259        .onAppear { focused = true }
 260        .onKeyPress(phases: .down) { press in handle(press) }
 261        .safeAreaInset(edge: .bottom, spacing: 0) {
 262            if let message = message ?? (filter.isEmpty ? reminderStatus : "Filter: " + filter.description) {
 263                Text(message)
 264                    .font(.callout)
 265                    .frame(maxWidth: .infinity, alignment: .leading)
 266                    .padding(.horizontal, 12)
 267                    .padding(.vertical, 6)
 268                    .background(.bar)
 269            }
 270        }
 271        .toolbar { toolbar }
 272        .overlay {
 273            if agenda.files.isEmpty {
 274                ContentUnavailableView("No agenda files", systemImage: "calendar", description: Text("The agenda reads the org files at the top of each folder you add."))
 275            }
 276        }
 277        .sheet(item: Binding(get: { prompt?.prompt.fast == nil ? nil : prompt }, set: { if $0 == nil { prompt = nil } })) { pending in
 278            if let fast = pending.prompt.fast {
 279                FastSelectionView(selection: fast, message: pending.prompt.message) { answer in
 280                    prompt = nil
 281                    guard let answer else { return }
 282                    promptText = answer
 283                    prompt = pending
 284                    answerPrompt()
 285                }
 286                .frame(minWidth: 420)
 287            }
 288        }
 289        .alert(prompt?.prompt.message ?? "", isPresented: Binding(get: { prompt != nil && prompt?.prompt.fast == nil }, set: { if !$0 { prompt = nil } })) {
 290            TextField("", text: $promptText)
 291            Button("OK") { answerPrompt() }
 292            Button("Cancel", role: .cancel) { prompt = nil }
 293        } message: {
 294            if let choices = prompt?.prompt.choices, !choices.isEmpty {
 295                Text(choices.prefix(12).joined(separator: "  "))
 296            }
 297        }
 298        .alert(filterPrompt?.title ?? "", isPresented: Binding(get: { filterPrompt != nil }, set: { if !$0 { filterPrompt = nil } })) {
 299            TextField("", text: $filterText)
 300            Button("Filter") { applyFilter() }
 301            Button("Cancel", role: .cancel) { filterPrompt = nil }
 302        } message: {
 303            if filterPrompt?.kind == "/" || filterPrompt?.kind == "\\" {
 304                Text(shown.tags.sorted().prefix(20).joined(separator: "  "))
 305            }
 306        }
 307        .alert(textPrompt?.title ?? "", isPresented: Binding(get: { textPrompt != nil }, set: { if !$0 { textPrompt = nil } })) {
 308            TextField("", text: $textAnswer)
 309            Button("OK") {
 310                let pending = textPrompt
 311                let answer = textAnswer
 312                textPrompt = nil
 313                textAnswer = ""
 314                // A follow-up question opens after this alert closes.
 315                DispatchQueue.main.async { pending?.apply(answer) }
 316            }
 317            Button("Cancel", role: .cancel) {
 318                textPrompt = nil
 319                textAnswer = ""
 320            }
 321        }
 322        .navigationTitle(title)
 323        .navigationSubtitle(isAgenda && viewName != AgendaViewLoader.builtIn[0].name ? viewName : "")
 324        .onChange(of: viewName) { applyView() }
 325        .onChange(of: commands.agendaRequest?.start, initial: true) { showRequestedDays() }
 326        .onChange(of: commands.agendaRequest?.days) { showRequestedDays() }
 327        .background { Refresher(base: refreshKey, session: session, workspace: workspace, refresh: refresh) }
 328        .task {
 329            loadViews()
 330            // The now line moves each minute; a new day refreshes the statuses.
 331            while !Task.isCancelled {
 332                let next = Calendar.current.nextDate(after: Date(), matching: DateComponents(second: 0), matchingPolicy: .nextTime) ?? Date().addingTimeInterval(60)
 333                try? await Task.sleep(for: .seconds(next.timeIntervalSinceNow))
 334                now = Date()
 335                if Days.absolute(now, calendar: .current) != agenda.today { tick += 1 }
 336            }
 337        }
 338    }
 339
 340    // MARK: - Days
 341
 342    private var todayColor: Color { theme.color("agenda-today") ?? .accentColor }
 343
 344    @ViewBuilder
 345    private func dayRows(_ group: AgendaDayGroup) -> some View {
 346        if group.isToday, !group.overdue.isEmpty {
 347            overdueHeader(count: group.overdue.count)
 348            if overdueShown {
 349                ForEach(Array(group.overdue.enumerated()), id: \.element.id) { index, row in
 350                    rowView(Line(id: "\(group.day):o\(index)", row: row, day: group.day))
 351                }
 352                Divider().padding(.leading, 16).padding(.vertical, 4)
 353            }
 354        }
 355        if group.isEmpty {
 356            Text("Nothing scheduled")
 357                .font(.callout)
 358                .foregroundStyle(.secondary)
 359                .padding(.horizontal, 16)
 360                .padding(.vertical, 10)
 361        }
 362        let nowAt = group.nowIndex(now: Self.hhmm(now))
 363        ForEach(Array(group.rows.enumerated()), id: \.element.id) { index, row in
 364            if index == nowAt { nowLine }
 365            rowView(Line(id: "\(group.day):\(index)", row: row, day: group.day))
 366        }
 367        if let nowAt, nowAt == group.rows.count { nowLine }
 368    }
 369
 370    private func header(@ViewBuilder _ content: () -> some View) -> some View {
 371        HStack(spacing: 6) { content() }
 372            .padding(.horizontal, 16)
 373            .frame(height: 30)
 374            .frame(maxWidth: .infinity, alignment: .leading)
 375            .background(theme.color("agenda-background") ?? Color(nsColor: .textBackgroundColor))
 376            .overlay(alignment: .bottom) { Divider() }
 377    }
 378
 379    private func dayHeader(_ group: AgendaDayGroup) -> some View {
 380        let past = group.day < agenda.today
 381        let color = group.isToday ? todayColor : past ? Color.secondary : theme.color("agenda-date") ?? .primary
 382        return header {
 383            if let relative = group.relativeName(today: agenda.today) {
 384                Text(relative)
 385                    .font(.system(size: 13, weight: .bold))
 386                    .foregroundStyle(color)
 387                Text("·").foregroundStyle(.tertiary)
 388            }
 389            Text(Self.format(group.day, Days.date(group.day).year == Days.date(agenda.today).year ? "EEEE d MMMM" : "EEEE d MMMM yyyy"))
 390                .font(.system(size: 13, weight: group.isToday ? .bold : .semibold))
 391                .foregroundStyle(color)
 392            Spacer()
 393            Button {
 394                capture(on: group.day)
 395            } label: {
 396                Image(systemName: "plus")
 397                    .font(.system(size: 12, weight: .semibold))
 398                    .frame(width: 22, height: 22)
 399                    .contentShape(Rectangle())
 400            }
 401            .buttonStyle(.borderless)
 402            .foregroundStyle(group.isToday ? todayColor : .secondary)
 403            .help("Capture an entry scheduled on this day (k)")
 404        }
 405    }
 406
 407    private func overdueHeader(count: Int) -> some View {
 408        let color = theme.dynamic(.systemRed) { [theme] in theme.statusColor(.overdue, dark: $0) }
 409        return Button {
 410            withAnimation(.snappy(duration: 0.2)) { overdueShown.toggle() }
 411            if !overdueShown, selection?.contains(":o") == true { selection = nil }
 412        } label: {
 413            HStack(spacing: 6) {
 414                Image(systemName: "chevron.right")
 415                    .font(.system(size: 10, weight: .bold))
 416                    .rotationEffect(.degrees(overdueShown ? 90 : 0))
 417                Text("Overdue").font(.system(size: 12, weight: .semibold))
 418                Text("\(count)")
 419                    .font(.system(size: 10, weight: .bold).monospacedDigit())
 420                    .padding(.horizontal, 6)
 421                    .padding(.vertical, 1)
 422                    .background(Capsule().fill(color.opacity(0.15)))
 423                Spacer()
 424            }
 425            .foregroundStyle(color)
 426            .padding(.horizontal, 16)
 427            .padding(.top, 8)
 428            .padding(.bottom, 4)
 429            .contentShape(Rectangle())
 430        }
 431        .buttonStyle(.plain)
 432        .help(overdueShown ? "Hide entries from earlier days" : "Show entries from earlier days")
 433    }
 434
 435    private var nowLine: some View {
 436        HStack(spacing: 6) {
 437            Text(now.formatted(.dateTime.hour(.twoDigits(amPM: .omitted)).minute()))
 438                .font(.system(size: 10, weight: .semibold).monospacedDigit())
 439                .frame(width: AgendaRowView.gutterWidth, alignment: .leading)
 440            Circle().frame(width: 6, height: 6)
 441            Rectangle().frame(height: 1)
 442        }
 443        .foregroundStyle(todayColor)
 444        .padding(.horizontal, 16)
 445        .frame(height: 10)
 446        .accessibilityLabel("Now")
 447    }
 448
 449    private func rowView(_ line: Line, showsGutter: Bool = true) -> some View {
 450        AgendaRowView(
 451            row: line.row, day: line.day, showsGutter: showsGutter, selected: selection == line.id, hovered: hovered == line.id,
 452            marked: line.row.item.flatMap(EntryRef.init).map(marked.contains) ?? false
 453        )
 454        .id(line.id)
 455        .contentShape(Rectangle())
 456        .onHover { inside in
 457            if inside { hovered = line.id } else if hovered == line.id { hovered = nil }
 458        }
 459        .onTapGesture(count: 2) { open(line) }
 460        .simultaneousGesture(TapGesture().onEnded {
 461            selection = line.id
 462            focused = true
 463        })
 464        .contextMenu { menu(line) }
 465    }
 466
 467    @ViewBuilder
 468    private func menu(_ line: Line) -> some View {
 469        if let event = line.row.event {
 470            Button("Show in Calendar") { openEvent(event) }
 471        } else if line.row.item != nil {
 472            Button("Open") { selection = line.id; jump(line.id) }
 473            Divider()
 474            Button("Cycle TODO State") { selection = line.id; run(TodoCycle()) }
 475            Button("Set Priority…") { selection = line.id; run(SetPriority()) }
 476            Button("Set Tags…") { selection = line.id; run(SetTags()) }
 477            Button("Schedule…") { selection = line.id; run(SetPlanning(deadline: false)) }
 478            Button("Set Deadline…") { selection = line.id; run(SetPlanning(deadline: true)) }
 479            Divider()
 480            Button("Clock In") { selection = line.id; clockIn() }
 481            Button(EntryRef(line.row.item!).map(marked.contains) == true ? "Unmark" : "Mark") {
 482                selection = line.id
 483                mark(!(EntryRef(line.row.item!).map(marked.contains) ?? false))
 484            }
 485            Button("Archive") { selection = line.id; archive() }
 486        }
 487    }
 488
 489    // MARK: - Toolbar
 490
 491    @ToolbarContentBuilder
 492    private var toolbar: some ToolbarContent {
 493        ToolbarItemGroup(placement: .navigation) {
 494            Menu {
 495                ForEach(views) { view in Button(view.name) { viewName = view.name } }
 496                Divider()
 497                Button(Self.match) { viewName = Self.match }
 498                Button(Self.todoMatch) { viewName = Self.todoMatch }
 499                Button(Self.search) { viewName = Self.search }
 500                Button(Self.todoSearch) { viewName = Self.todoSearch }
 501            } label: {
 502                Label(viewName, systemImage: "calendar").labelStyle(.titleAndIcon)
 503            }
 504            .help("What the agenda shows")
 505            if isMatch || isSearch {
 506                TextField(isSearch ? "Phrase or +word -word {regexp}" : "+work-boss|LEVEL>2/!TODO", text: $matchText)
 507                    .frame(minWidth: 220)
 508                    .onSubmit { applyView() }
 509            }
 510        }
 511        ToolbarItemGroup {
 512            if agenda.isComputing { ProgressView().controlSize(.small) }
 513            if isAgenda {
 514                Picker("Span", selection: Binding(get: { spanKind }, set: { if let kind = $0 { setSpan(kind) } })) {
 515                    Text("Day").tag(AgendaSpan?.some(.day))
 516                    Text("Week").tag(AgendaSpan?.some(.week))
 517                    Text("Month").tag(AgendaSpan?.some(.month))
 518                }
 519                .pickerStyle(.segmented)
 520                .labelsHidden()
 521                .help("Show a day, week or month (v d, v w, v m)")
 522                ControlGroup {
 523                    Button("Earlier", systemImage: "chevron.left") { move(forward: false) }
 524                        .help("Previous days (b)")
 525                    Button("Today") { goToday() }
 526                        .help("Back to today (.)")
 527                    Button("Later", systemImage: "chevron.right") { move(forward: true) }
 528                        .help("Next days (f)")
 529                }
 530                Button("Go to Date", systemImage: "calendar") {
 531                    pickedDate = Self.date(anchorDay)
 532                    showingDatePicker = true
 533                }
 534                .help("Go to a date (j)")
 535                .popover(isPresented: $showingDatePicker, arrowEdge: .bottom) {
 536                    DatePicker("Date", selection: $pickedDate, displayedComponents: .date)
 537                        .datePickerStyle(.graphical)
 538                        .labelsHidden()
 539                        .padding()
 540                        .onChange(of: pickedDate) {
 541                            showingDatePicker = false
 542                            goTo(Days.absolute(pickedDate, calendar: .current))
 543                        }
 544                }
 545            }
 546            Menu {
 547                Button("Filter…") { askFilter("/") }
 548                Button("By Tag…") { askFilter("\\") }
 549                Button("By Category of Selected Line") { toggleCategoryFilter() }
 550                Button("By Regexp…") { askFilter("=") }
 551                Button("By Effort…") { askFilter("_") }
 552                Divider()
 553                Button("Remove Filters") { filter = AgendaFilter() }
 554                    .disabled(filter.isEmpty)
 555            } label: {
 556                Label("Filter", systemImage: filter.isEmpty ? "line.3.horizontal.decrease.circle" : "line.3.horizontal.decrease.circle.fill")
 557            } primaryAction: {
 558                askFilter("/")
 559            }
 560            .help("Filter the entries (/, \\, <, =, _; | removes)")
 561        }
 562    }
 563
 564    /// The span shown, as the window's title: `Week of 5 Oct 2026`.
 565    private var title: String {
 566        guard isAgenda else { return viewName.replacingOccurrences(of: "…", with: "") }
 567        guard let first = agenda.days.first?.day, let last = agenda.days.last?.day else { return "Agenda" }
 568        switch spanKind {
 569        case .day: return Self.format(first, "EEEE d MMMM yyyy")
 570        case .week: return "Week of " + Self.format(first, "d MMM yyyy")
 571        case .month: return Self.format(first, "MMMM yyyy")
 572        case nil:
 573            if first == last { return Self.format(first, "EEEE d MMMM yyyy") }
 574            let sameYear = Days.date(first).year == Days.date(last).year
 575            return Self.format(first, sameYear ? "d MMM" : "d MMM yyyy") + " – " + Self.format(last, "d MMM yyyy")
 576        }
 577    }
 578
 579    // MARK: - Span
 580
 581    /// The day `v`, `j` and `k` start from: the selected line's, else today when shown, else the first.
 582    private var anchorDay: Int {
 583        if let selection, let day = Int(selection.prefix { $0 != ":" }) { return day }
 584        let days = agenda.days.map(\.day)
 585        if days.contains(agenda.today) || days.isEmpty { return agenda.today }
 586        return days[0]
 587    }
 588
 589    /// `org-agenda-day-view`, `-week-view`, `-month-view`: the day, the week from Monday
 590    /// (`org-agenda-start-on-weekday`), or the month around `anchor`.
 591    private func setSpan(_ kind: AgendaSpan, around anchor: Int? = nil) {
 592        let anchor = anchor ?? anchorDay
 593        spanKind = kind
 594        selection = nil
 595        switch kind {
 596        case .day:
 597            agenda.mode = .agenda(span: 1, startOffset: nil)
 598            agenda.start = anchor
 599        case .week:
 600            agenda.mode = .agenda(span: 7, startOffset: nil)
 601            agenda.start = anchor - (Days.weekday(anchor) + 6) % 7
 602        case .month:
 603            let d = Days.date(anchor)
 604            let first = Days.absolute(year: d.year, month: d.month, day: 1)
 605            let next = d.month == 12 ? Days.absolute(year: d.year + 1, month: 1, day: 1) : Days.absolute(year: d.year, month: d.month + 1, day: 1)
 606            agenda.mode = .agenda(span: next - first, startOffset: nil)
 607            agenda.start = first
 608        }
 609    }
 610
 611    private func move(forward: Bool) {
 612        selection = nil
 613        if spanKind == .month, let first = agenda.days.first?.day {
 614            setSpan(.month, around: forward ? first + 31 : first - 1)
 615        } else {
 616            agenda.shift(forward: forward)
 617        }
 618    }
 619
 620    private func goToday() {
 621        if let spanKind { setSpan(spanKind, around: agenda.today) } else { agenda.showToday() }
 622        selection = nil
 623    }
 624
 625    /// `org-agenda-goto-date`.
 626    private func goTo(_ day: Int) {
 627        if let spanKind { setSpan(spanKind, around: day) } else { agenda.start = day }
 628        selection = nil
 629    }
 630
 631    /// Capture on `day`, as `org-agenda-capture`.
 632    private func capture(on day: Int) {
 633        commands.capture(on: day)
 634        NSApp.activate()
 635        openWindow(id: "capture")
 636    }
 637
 638    static func date(_ day: Int) -> Date {
 639        let d = Days.date(day)
 640        return Calendar.current.date(from: DateComponents(year: d.year, month: d.month, day: d.day)) ?? Date()
 641    }
 642
 643    static func format(_ day: Int, _ pattern: String) -> String {
 644        let formatter = DateFormatter()
 645        formatter.dateFormat = pattern
 646        return formatter.string(from: date(day))
 647    }
 648
 649    static func hhmm(_ date: Date) -> Int {
 650        let c = Calendar.current.dateComponents([.hour, .minute], from: date)
 651        return (c.hour ?? 0) * 100 + (c.minute ?? 0)
 652    }
 653
 654    @AppStorage("reminders") private var remindersEnabled = true
 655
 656    /// How far ahead notifications are set, as the design asks the agenda to show.
 657    private var reminderStatus: String? {
 658        guard let scheduler, remindersEnabled else { return nil }
 659        if !scheduler.isAuthorized { return "Notifications are off for Orgstar in System Settings." }
 660        guard let through = scheduler.scheduledThrough else { return nil }
 661        return "Reminders are set through " + through.formatted(.dateTime.weekday(.abbreviated).day().month(.abbreviated).hour().minute()) + "."
 662    }
 663
 664    private var listTitle: String {
 665        switch agenda.mode {
 666        case .todo(let keywords): "TODO items: \(keywords ?? "all")"
 667        case .match(let match, let todoOnly): (todoOnly ? "TODO entries" : "Entries") + " matching \(match)"
 668        case .search(let string, let todoOnly): (todoOnly ? "TODO entries" : "Entries") + " containing \(string)"
 669        case .agenda: ""
 670        }
 671    }
 672
 673    private func loadViews() {
 674        let loaded = AgendaViewLoader.load()
 675        views = loaded.views
 676        message = loaded.problems.first
 677    }
 678
 679    /// The days of a followed timestamp, in the agenda view.
 680    private func showRequestedDays() {
 681        guard let request = commands.agendaRequest else { return }
 682        commands.agendaRequest = nil
 683        selection = nil
 684        spanKind = nil
 685        if viewName != AgendaViewLoader.builtIn[0].name {
 686            keepRequestedDays = true
 687            viewName = AgendaViewLoader.builtIn[0].name
 688        }
 689        agenda.mode = .agenda(span: request.days, startOffset: nil)
 690        agenda.start = request.start
 691    }
 692
 693    private func applyView() {
 694        if keepRequestedDays { return keepRequestedDays = false }
 695        selection = nil
 696        spanKind = nil
 697        agenda.start = nil
 698        switch viewName {
 699        case Self.match, Self.todoMatch:
 700            let match = matchText.trimmingCharacters(in: .whitespaces)
 701            guard !match.isEmpty else { return }
 702            agenda.mode = .match(match, todoOnly: viewName == Self.todoMatch)
 703        case Self.search, Self.todoSearch:
 704            guard matchText.contains(where: { !$0.isWhitespace }) else { return }
 705            agenda.mode = .search(matchText, todoOnly: viewName == Self.todoSearch)
 706        default:
 707            if let view = views.first(where: { $0.name == viewName }) { agenda.mode = view.mode }
 708        }
 709    }
 710
 711    // MARK: - Items
 712
 713    private func item(_ id: String) -> AgendaItem? { line(id)?.row.item }
 714
 715    /// Return and double click: the entry in the main window, or the event in Calendar.
 716    private func open(_ line: Line) {
 717        selection = line.id
 718        if let event = line.row.event { openEvent(event) } else { jump(line.id) }
 719    }
 720
 721    /// Calendar shows an event from its identifier (`AgendaEvent.id` adds `@` and the start).
 722    private func openEvent(_ event: AgendaEvent) {
 723        let identifier = event.id.split(separator: "@").dropLast().joined(separator: "@")
 724        guard !identifier.isEmpty, let encoded = identifier.addingPercentEncoding(withAllowedCharacters: .urlPathAllowed),
 725              let url = URL(string: "ical://ekevent/\(encoded)?method=show&options=more") else { return }
 726        NSWorkspace.shared.open(url)
 727    }
 728
 729    /// Moves the selection by `step` lines.
 730    private func step(_ step: Int) {
 731        let all = lines(groups)
 732        guard !all.isEmpty else { return }
 733        let index = selection.flatMap { id in all.firstIndex { $0.id == id } }
 734        let next = index.map { min(max($0 + step, 0), all.count - 1) } ?? (step > 0 ? 0 : all.count - 1)
 735        selection = all[next].id
 736    }
 737
 738    // MARK: - Filters
 739
 740    /// The tags and categories on the view's lines, which filter words are read against.
 741    private var shown: (tags: Set<String>, categories: Set<String>) {
 742        let items = (isAgenda ? agenda.days.flatMap(\.items) : agenda.list).filter { $0.path != nil }
 743        return (Set(items.flatMap(\.tags)), Set(items.map(\.category)))
 744    }
 745
 746    private func askFilter(_ kind: Character) {
 747        switch kind {
 748        case "/": filterText = filter.description
 749        default: filterText = ""
 750        }
 751        let title = switch kind {
 752        case "/": "Filter [+cat-tag<0:10-/regexp/]:"
 753        case "\\": "Tag filter (+tag-tag):"
 754        case "=": "Regexp filter (-re to drop):"
 755        default: "Effort filter (<0:30, >1:00, =1:00):"
 756        }
 757        filterPrompt = (title, kind)
 758    }
 759
 760    private func applyFilter() {
 761        guard let kind = filterPrompt?.kind else { return }
 762        filterPrompt = nil
 763        let text = filterText.trimmingCharacters(in: .whitespaces)
 764        var current = filter
 765        switch kind {
 766        case "/":
 767            let (parsed, ignored) = AgendaFilter().parse(text, tags: shown.tags, categories: shown.categories)
 768            current = parsed
 769            if !ignored.isEmpty { message = "\(ignored.joined(separator: " ")) ignored: no line has that tag or category" }
 770        case "\\":
 771            // Every word as a tag.
 772            current.tags = AgendaFilter().parse(text, tags: Set(text.split(whereSeparator: { "+- ".contains($0) }).map(String.init)), categories: []).filter.tags
 773        case "=":
 774            current.regexps = text.isEmpty ? [] : [text.hasPrefix("-") || text.hasPrefix("+") ? text : "+" + text]
 775        default:
 776            current.efforts = text.isEmpty ? [] : ["+" + text]
 777        }
 778        filter = current
 779        selection = nil
 780    }
 781
 782    /// `<`: keep only the selected line's category, or drop that filter.
 783    private func toggleCategoryFilter() {
 784        if !filter.categories.isEmpty {
 785            filter.categories = []
 786        } else if let selection, let item = item(selection) {
 787            filter.categories = ["+" + item.category]
 788        } else {
 789            message = "No entry selected"
 790        }
 791    }
 792
 793    /// The entry in the main window; with `focus` false the agenda keeps the keys (SPC).
 794    private func jump(_ id: String, focus: Bool = true) {
 795        guard let item = item(id), let path = item.path, let offset = item.markerOffset ?? item.headingOffset else { return }
 796        commands.jump(path: path, offset: offset)
 797        if focus { openWindow(id: "main") }
 798    }
 799
 800    // MARK: - Commands
 801
 802    private func handle(_ press: KeyPress) -> KeyPress.Result {
 803        let control = press.modifiers.contains(.control)
 804        // `C-x` and friends arrive as control characters or as letters with control.
 805        func isControl(_ letter: String, _ code: String) -> Bool { control && (press.characters == letter || press.characters == code) }
 806        if let pending = prefix {
 807            prefix = nil
 808            if pending == "v" {
 809                switch press.characters {
 810                case "d" where isAgenda: setSpan(.day)
 811                case "w" where isAgenda: setSpan(.week)
 812                case "m" where isAgenda: setSpan(.month)
 813                default: message = "v \(press.characters) is undefined"
 814                }
 815                if message == "v-" { message = nil }
 816                return .handled
 817            }
 818            if pending == "C-c C-x" {
 819                if isControl("s", "\u{13}") { archive() } else { message = "C-c C-x \(press.characters) is undefined" }
 820                return .handled
 821            }
 822            if isControl("s", "\u{13}") {
 823                run(SetPlanning(deadline: false))
 824            } else if isControl("d", "\u{04}") {
 825                run(SetPlanning(deadline: true))
 826            } else if isControl("q", "\u{11}") {
 827                run(SetTags())
 828            } else if isControl("t", "\u{14}") {
 829                run(TodoCycle())
 830            } else if isControl("w", "\u{17}") {
 831                refile(marked: false)
 832            } else if isControl("x", "\u{18}") {
 833                prefix = "C-c C-x"
 834                message = "C-c C-x-"
 835            } else if press.characters == "$" {
 836                archive()
 837            } else {
 838                message = "C-c \(press.characters) is undefined"
 839            }
 840            return .handled
 841        }
 842        if isControl("c", "\u{03}") {
 843            prefix = "C-c"
 844            message = "C-c-"
 845            return .handled
 846        }
 847        if isControl("n", "\u{0e}") || (press.key == .downArrow && press.modifiers.isEmpty) {
 848            step(1)
 849            return .handled
 850        }
 851        if isControl("p", "\u{10}") || (press.key == .upArrow && press.modifiers.isEmpty) {
 852            step(-1)
 853            return .handled
 854        }
 855        if press.key == .return || press.key == .tab, let selection, let line = line(selection) {
 856            open(line)
 857            return .handled
 858        }
 859        if press.key == .space, let selection {
 860            jump(selection, focus: false)
 861            return .handled
 862        }
 863        if press.modifiers == .shift, press.key == .rightArrow || press.key == .leftArrow {
 864            run(ShiftTimestampDay(later: press.key == .rightArrow), atMarker: true)
 865            return .handled
 866        }
 867        guard press.modifiers.subtracting(.shift).isEmpty else { return .ignored }
 868        switch press.characters {
 869        case "n": step(1)
 870        case "p": step(-1)
 871        case "f" where isAgenda: move(forward: true)
 872        case "b" where isAgenda: move(forward: false)
 873        case "." where isAgenda: goToday()
 874        case "j" where isAgenda:
 875            pickedDate = Self.date(anchorDay)
 876            showingDatePicker = true
 877        case "v" where isAgenda:
 878            prefix = "v"
 879            message = "v-"
 880        case "d" where isAgenda: setSpan(.day)
 881        case "w" where isAgenda: setSpan(.week)
 882        case "k" where isAgenda: capture(on: anchorDay)
 883        case "s":
 884            commands.run("app.save-all")
 885            message = "Saved"
 886        case "/", "\\", "=", "_": askFilter(press.characters.first!)
 887        case "<": toggleCategoryFilter()
 888        case "|":
 889            filter = AgendaFilter()
 890            message = "Filters removed"
 891        case "l" where isAgenda:
 892            logMode.toggle()
 893            message = logMode ? "Log mode on" : "Log mode off"
 894        case "g", "r":
 895            loadViews()
 896            tick += 1
 897        case "I": clockIn()
 898        case "O": message = clock.clockOut(session)
 899        case "X": message = clock.clockOut(session, cancel: true)
 900        case "$": archive()
 901        case "m": mark(true)
 902        case "u": mark(false)
 903        case "U":
 904            marked = []
 905            message = "No entries marked"
 906        case "B": askBulk()
 907        case "t": run(TodoCycle())
 908        case "+": run(PriorityUp())
 909        case "-": run(PriorityDown())
 910        case ",": run(SetPriority())
 911        case ":": run(SetTags())
 912        default: return .ignored
 913        }
 914        return .handled
 915    }
 916
 917    // MARK: - Clock, refile, archive, bulk
 918
 919    private var selectedEntry: EntryRef? { selection.flatMap(item).flatMap(EntryRef.init) }
 920
 921    private func clockIn() {
 922        guard let entry = selectedEntry, let offset = session.locateHeading(path: entry.path, line: entry.line, near: entry.offset) else {
 923            message = "No entry selected"
 924            return
 925        }
 926        let paths = workspace.files.filter { $0.kind == .org }.map(\.path)
 927        Task {
 928            let outcome = await clock.clockIn(session, target: .entry(path: entry.path, offset: offset), paths: paths, ask: commands.askClock)
 929            if let jump = outcome.jump { commands.jump(path: jump.path, offset: jump.offset) }
 930            message = outcome.messages.last { !$0.isEmpty }
 931            tick += 1
 932        }
 933    }
 934
 935    private func archive() {
 936        guard let entry = selectedEntry, let offset = session.locateHeading(path: entry.path, line: entry.line, near: entry.offset) else {
 937            message = "No entry selected"
 938            return
 939        }
 940        message = session.archive(from: (entry.path, offset))
 941        tick += 1
 942    }
 943
 944    /// Refiles the selected entry, or with `marked` the marked ones, to a target asked for in
 945    /// the main window, where the list of targets is searchable.
 946    private func refile(marked bulk: Bool) {
 947        let entries = bulk ? marked : selectedEntry.map { [$0] } ?? []
 948        guard !entries.isEmpty else {
 949            message = "No entry selected"
 950            return
 951        }
 952        let targets = workspace.refileTargets(openPath: session.path, document: session.document)
 953        commands.ask(Prompt(key: "refile", message: "Refile to:", choices: targets.map(\.label))) { answer in
 954            guard let answer, targets.contains(where: { $0.label == answer }) else { return }
 955            message = eachEntry(entries) { entry, offset in
 956                // Targets in the entry's own file from its text now, as earlier moves shift them.
 957                let document = session.openDocuments.first { $0.path == entry.path }?.document
 958                    ?? FileManager.default.contents(atPath: entry.path).map { DocumentState(bytes: [UInt8]($0)) }
 959                guard let target = workspace.refileTargets(openPath: entry.path, document: document).first(where: { $0.label == answer }) else {
 960                    return "Can't find \(answer) any more."
 961                }
 962                return session.refile(to: target, from: (entry.path, offset))
 963            }
 964            if bulk { marked = [] }
 965            tick += 1
 966        }
 967        openWindow(id: "main")
 968    }
 969
 970    /// Runs `action` on each entry, finding it again first: later entries in a file first, so
 971    /// earlier ones keep their place. Returns the last message.
 972    private func eachEntry(_ entries: [EntryRef], _ action: (EntryRef, Int) -> String?) -> String? {
 973        var last: String?
 974        var failed = 0
 975        for entry in entries.sorted(by: { ($0.path, $1.offset) < ($1.path, $0.offset) }) {
 976            guard let offset = session.locateHeading(path: entry.path, line: entry.line, near: entry.offset) else {
 977                failed += 1
 978                continue
 979            }
 980            last = action(entry, offset)
 981        }
 982        return failed > 0 ? "\(failed) marked \(failed == 1 ? "entry" : "entries") changed and \(failed == 1 ? "was" : "were") skipped" : last
 983    }
 984
 985    private func mark(_ on: Bool) {
 986        guard let entry = selectedEntry else {
 987            message = "No entry selected"
 988            return
 989        }
 990        if on {
 991            if !marked.contains(entry) { marked.append(entry) }
 992        } else {
 993            marked.removeAll { $0 == entry }
 994        }
 995        message = "\(marked.count) marked"
 996    }
 997
 998    /// `B`: an action for every marked entry.
 999    private func askBulk() {
1000        guard !marked.isEmpty else {
1001            message = "No entries are marked"
1002            return
1003        }
1004        textPrompt = TextPrompt(title: "Bulk action on \(marked.count): [$] archive [r] refile [t] TODO state [+] tag [-] untag [s] schedule [d] deadline") { answer in
1005            switch answer.trimmingCharacters(in: .whitespaces) {
1006            case "$": bulk { session.archive(from: ($0.path, $1)) }
1007            case "r": refile(marked: true)
1008            case "t":
1009                textPrompt = TextPrompt(title: "TODO state (empty for none):") { keyword in
1010                    let word = keyword.trimmingCharacters(in: .whitespaces)
1011                    bulk { performAt($0, $1, SetTodo(keyword: word.isEmpty ? nil : word)) }
1012                }
1013            case "+", "-":
1014                let on = answer.trimmingCharacters(in: .whitespaces) == "+"
1015                textPrompt = TextPrompt(title: on ? "Tag to add:" : "Tag to remove:") { tag in
1016                    let tag = tag.trimmingCharacters(in: .whitespaces)
1017                    guard !tag.isEmpty else { return }
1018                    bulk { performAt($0, $1, ToggleTag(tag: tag, on: on)) }
1019                }
1020            case "s", "d":
1021                let deadline = answer.trimmingCharacters(in: .whitespaces) == "d"
1022                textPrompt = TextPrompt(title: deadline ? "Deadline (+2d, fri, 2026-10-12):" : "Schedule (+2d, fri, 2026-10-12):") { date in
1023                    bulk { performAt($0, $1, SetPlanning(deadline: deadline), answers: ["date": date]) }
1024                }
1025            default:
1026                message = "No bulk action \(answer)"
1027            }
1028        }
1029    }
1030
1031    private func bulk(_ action: (EntryRef, Int) -> String?) {
1032        message = eachEntry(marked, action) ?? "Done with \(marked.count) entries"
1033        marked = []
1034        tick += 1
1035    }
1036
1037    /// Runs `command` at the heading at `offset`, as `run` does for the selection.
1038    private func performAt(_ entry: EntryRef, _ offset: Int, _ command: any OrgCommand, answers: [String: String] = [:]) -> String? {
1039        switch session.perform(command, path: entry.path, at: offset, expect: (offset, entry.line), answers: answers) {
1040        case .failed(let text): text
1041        case .prompt: "\(command.title) needs an answer; run it on the entry itself"
1042        default: nil
1043        }
1044    }
1045
1046    /// Runs `command` on the selected entry, at its heading or, with `atMarker`, at the
1047    /// timestamp the entry is listed for.
1048    private func run(_ command: any OrgCommand, atMarker: Bool = false, answers: [String: String] = [:], itemID: String? = nil) {
1049        guard let id = itemID ?? selection, let item = item(id), let path = item.path, let start = item.headingOffset else {
1050            message = "No entry selected"
1051            return
1052        }
1053        if atMarker, ![.deadline, .upcomingDeadline, .scheduled, .pastScheduled, .timestamp].contains(item.kind) {
1054            message = "Only dated entries can move"
1055            return
1056        }
1057        let offset = atMarker ? (item.markerOffset ?? start) : start
1058        let step = session.perform(command, path: path, at: offset, expect: item.headingLine.map { (start, $0) }, answers: answers)
1059        switch step {
1060        case .prompt(let request):
1061            promptText = request.initial
1062            prompt = PendingPrompt(prompt: request, command: command, atMarker: atMarker, answers: answers, itemID: id)
1063        case .failed(let text):
1064            message = text
1065            tick += 1
1066        case .external:
1067            message = "Not available from the agenda"
1068        case .commit:
1069            message = nil
1070            tick += 1
1071        }
1072    }
1073
1074    private func answerPrompt() {
1075        guard let pending = prompt else { return }
1076        prompt = nil
1077        var answers = pending.answers
1078        answers[pending.prompt.key] = promptText
1079        run(pending.command, atMarker: pending.atMarker, answers: answers, itemID: pending.itemID)
1080    }
1081}
1082
1083/// One agenda line: the time or status over an icon, the category above the title, progress
1084/// and tags after it, and the TODO keyword and priority at the end.
1085struct AgendaRowView: View {
1086    let row: AgendaRow
1087    /// The agenda day the row is on, for habit graphs.
1088    var day: Int
1089    var showsGutter = true
1090    var selected = false
1091    var hovered = false
1092    /// Marked for a bulk action.
1093    var marked = false
1094    @Environment(\.orgTheme) private var theme
1095
1096    static let gutterWidth: CGFloat = 92
1097
1098    var body: some View {
1099        HStack(alignment: .center, spacing: 12) {
1100            if showsGutter { gutter }
1101            VStack(alignment: .leading, spacing: 2) {
1102                if !row.category.isEmpty { categoryLine }
1103                titleLine
1104            }
1105            .layoutPriority(1)
1106            Spacer(minLength: 8)
1107            if let habit = row.item?.habit {
1108                HabitGraph(cells: habit.graph(today: day), theme: theme)
1109            }
1110            if let todo = row.todo {
1111                let color = theme.dynamic(row.isDone ? .systemGreen : .systemRed) { [theme, row] in theme.todoColor(todo, isDone: row.isDone, dark: $0) }
1112                Text(todo)
1113                    .font(.system(size: 10, weight: .bold))
1114                    .foregroundStyle(color)
1115                    .padding(.horizontal, 7)
1116                    .padding(.vertical, 2)
1117                    .background(Capsule().fill(color.opacity(0.14)))
1118                    .fixedSize()
1119            }
1120            priorityBadge
1121                .frame(width: 18)
1122        }
1123        .padding(.horizontal, 16)
1124        .padding(.vertical, 6)
1125        .frame(minHeight: 44)
1126        // `org-agenda-dim-blocked-tasks`.
1127        .opacity(row.isBlocked ? 0.5 : 1)
1128        .background {
1129            RoundedRectangle(cornerRadius: 6)
1130                .fill(selected ? theme.color("selection") ?? Color.accentColor.opacity(0.2) : hovered ? Color.primary.opacity(0.05) : .clear)
1131                .padding(.horizontal, 6)
1132        }
1133        .overlay(alignment: .leading) {
1134            if marked {
1135                Capsule().fill(theme.color("agenda-today") ?? .accentColor).frame(width: 3).padding(.vertical, 8).padding(.leading, 8)
1136            }
1137        }
1138        .accessibilityElement(children: .combine)
1139    }
1140
1141    private var statusColor: Color {
1142        theme.dynamic(.secondaryLabelColor) { [theme, row] in theme.statusColor(row.status, dark: $0) }
1143    }
1144
1145    private var gutter: some View {
1146        VStack(alignment: .leading, spacing: 3) {
1147            Text(row.gutter)
1148                .font(.system(size: 12, weight: row.status == .overdue || row.status == .dueSoon ? .semibold : .regular).monospacedDigit())
1149                .foregroundStyle(statusColor)
1150                .lineLimit(1)
1151                .minimumScaleFactor(0.8)
1152            if let symbol {
1153                Image(systemName: symbol)
1154                    .font(.system(size: row.icon == .event ? 8 : 10, weight: .semibold))
1155                    .foregroundStyle(iconColor)
1156                    .frame(height: 12)
1157            }
1158        }
1159        .frame(width: Self.gutterWidth, alignment: .leading)
1160    }
1161
1162    /// Overdue entries show a warning, done ones a check, as the status says first.
1163    private var symbol: String? {
1164        guard let icon = row.icon else { return nil }
1165        if row.status == .overdue { return "exclamationmark.circle.fill" }
1166        if row.status == .done { return "checkmark.circle.fill" }
1167        switch icon {
1168        case .scheduled: return "calendar"
1169        case .deadline: return "flag.fill"
1170        case .habit: return "repeat"
1171        case .event: return "circle.fill"
1172        case .timestamp: return row.start == nil ? "calendar" : "clock"
1173        }
1174    }
1175
1176    private var iconColor: Color {
1177        if let event = row.event { return theme.dynamic(.systemPurple) { [theme] in theme.eventColor(event, dark: $0) } }
1178        return row.status == .normal ? Color.secondary.opacity(0.8) : statusColor
1179    }
1180
1181    private var categoryLine: some View {
1182        HStack(spacing: 5) {
1183            Circle()
1184                .fill(row.event.map { event in theme.dynamic(.systemPurple) { [theme] in theme.eventColor(event, dark: $0) } }
1185                    ?? theme.dynamic { [theme, row] in theme.categoryColor(row.category, dark: $0) })
1186                .frame(width: 6, height: 6)
1187            Text(row.category + (row.event?.location.map { " · " + $0 } ?? ""))
1188                .font(.system(size: 11))
1189                .foregroundStyle(theme.color("agenda-category") ?? .secondary)
1190                .lineLimit(1)
1191        }
1192    }
1193
1194    private var titleLine: some View {
1195        HStack(spacing: 6) {
1196            Text(row.title.isEmpty ? " " : row.title)
1197                .font(.system(size: 13))
1198                .strikethrough(row.isDone)
1199                .foregroundStyle(row.isDone ? AnyShapeStyle(.secondary) : AnyShapeStyle(theme.color("foreground") ?? .primary))
1200                .lineLimit(1)
1201                .truncationMode(.tail)
1202            ForEach([row.progress, row.detail].compactMap { $0 }, id: \.self) { progress in
1203                Text(progress)
1204                    .font(.system(size: 10, weight: .semibold).monospacedDigit())
1205                    .foregroundStyle(.secondary)
1206                    .padding(.horizontal, 6)
1207                    .padding(.vertical, 1)
1208                    .background(Capsule().fill(Color.secondary.opacity(0.14)))
1209                    .fixedSize()
1210            }
1211            ForEach(row.tags, id: \.self) { tag in
1212                Text(tag)
1213                    .font(.system(size: 10, weight: .medium))
1214                    .foregroundStyle(theme.color("tags") ?? .secondary)
1215                    .padding(.horizontal, 6)
1216                    .padding(.vertical, 1)
1217                    .background(Capsule().strokeBorder((theme.color("tags") ?? .secondary).opacity(0.35), lineWidth: 0.5))
1218                    .fixedSize()
1219            }
1220        }
1221    }
1222
1223    @ViewBuilder
1224    private var priorityBadge: some View {
1225        if let priority = row.priority {
1226            let color = theme.dynamic(.systemOrange) { [theme] in theme.priorityColor(priority, dark: $0) }
1227            Text(priority)
1228                .font(.system(size: 10, weight: .bold))
1229                .foregroundStyle(color)
1230                .frame(width: 18, height: 18)
1231                .background(Circle().fill(color.opacity(0.14)))
1232                .overlay(Circle().strokeBorder(color.opacity(0.6), lineWidth: 1))
1233                .help("Priority \(priority)")
1234        } else {
1235            Color.clear.frame(width: 18, height: 18)
1236        }
1237    }
1238}
1239
1240/// org-habit's consistency graph: a cell per day, `*` where the habit was done, `!` today.
1241struct HabitGraph: View {
1242    let cells: [Habit.Cell]
1243    var theme: ThemeSpec = .default
1244
1245    var body: some View {
1246        HStack(spacing: 1) {
1247            ForEach(cells, id: \.day) { cell in
1248                Text(String(cell.glyph))
1249                    .font(.system(size: 9, weight: .bold, design: .monospaced))
1250                    .frame(width: 8, height: 14)
1251                    .background(color(cell.face))
1252                    .help(Self.label(cell))
1253            }
1254        }
1255        .accessibilityElement(children: .ignore)
1256        .accessibilityLabel("Done \(cells.filter { $0.glyph == "*" }.count) of the last \(Habit.precedingDays) days")
1257    }
1258
1259    /// Due-state colors, lighter for days to come, as org-habit's faces.
1260    func color(_ face: Habit.Face) -> Color {
1261        func themed(_ key: String, _ fallback: Color) -> Color { theme.color(key) ?? fallback }
1262        switch face {
1263        case .clear: return themed("habit-clear", .blue).opacity(0.7)
1264        case .clearFuture: return themed("habit-clear", .blue).opacity(0.35)
1265        case .ready: return themed("habit-ready", .green).opacity(0.75)
1266        case .readyFuture: return themed("habit-ready", .green).opacity(0.35)
1267        case .alert: return themed("habit-alert", .yellow).opacity(0.85)
1268        case .alertFuture: return themed("habit-alert", .yellow).opacity(0.4)
1269        case .overdue: return themed("habit-overdue", .red).opacity(0.75)
1270        case .overdueFuture: return themed("habit-overdue", .red).opacity(0.35)
1271        }
1272    }
1273
1274    static func label(_ cell: Habit.Cell) -> String {
1275        let date = Days.date(cell.day)
1276        return String(format: "%04d-%02d-%02d", date.year, date.month, date.day) + (cell.glyph == "*" ? " DONE" : "")
1277    }
1278}