Sources/OrgstarMobile/AgendaScreen.swift

bd275bd1a81b85a03549d5435d6a0bd32c2cbd66
orgstar/Sources/OrgstarMobile/AgendaScreen.swift

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