Sources/OrgstarMobile/AgendaScreen.swift

49c5da97098ed000be935c19462d4102812b0471
orgstar/Sources/OrgstarMobile/AgendaScreen.swift

1431 lines · 67472 bytes

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