Sources/OrgstarMobile/AgendaScreen.swift

design-themes-widgets
orgstar/Sources/OrgstarMobile/AgendaScreen.swift history · blame · raw

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