Sources/OrgstarMobile/AgendaScreen.swift

990043b7ec74ea1681276e57e1adbb253f3de1ef
orgstar/Sources/OrgstarMobile/AgendaScreen.swift

1317 lines · 61515 bytes

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

Global

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

Repository & editor

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