Sources/OrgstarMobile/AgendaScreen.swift

d24a6c5c43d3e63039ff8395d03b8399ecede125
orgstar/Sources/OrgstarMobile/AgendaScreen.swift

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