Sources/OrgstarMobile/AgendaScreen.swift

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