Sources/OrgstarMobile/AgendaScreen.swift

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