Sources/Orgstar/AgendaView+Toolbar.swift

524b5afe95ec3f3e3d1daba761a9e181f09cf88a
orgstar/Sources/Orgstar/AgendaView+Toolbar.swift history · blame · raw

287 lines · 12079 bytes

  1import AppKit
  2import OrgApp
  3import OrgDocument
  4import OrgCore
  5import OrgPresentation
  6import SwiftUI
  7
  8extension AgendaView {
  9    // MARK: - Toolbar
 10
 11    @ToolbarContentBuilder
 12    var toolbar: some ToolbarContent {
 13        ToolbarItemGroup(placement: .navigation) {
 14            Menu {
 15                ForEach(views) { view in Button(view.name) { viewName = view.name } }
 16                Divider()
 17                Button(Self.match) { viewName = Self.match }
 18                Button(Self.todoMatch) { viewName = Self.todoMatch }
 19                Button(Self.search) { viewName = Self.search }
 20                Button(Self.todoSearch) { viewName = Self.todoSearch }
 21            } label: {
 22                Label(viewName, systemImage: "calendar").labelStyle(.titleAndIcon)
 23            }
 24            .help("What the agenda shows")
 25            if isMatch || isSearch {
 26                TextField(isSearch ? "Phrase or +word -word {regexp}" : "+work-boss|LEVEL>2/!TODO", text: $matchText)
 27                    .frame(minWidth: 220)
 28                    .onSubmit { applyView() }
 29            }
 30        }
 31        ToolbarItemGroup {
 32            if agenda.isComputing { ProgressView().controlSize(.small) }
 33            if isAgenda {
 34                Picker("Span", selection: Binding(get: { spanKind }, set: { if let kind = $0 { setSpan(kind) } })) {
 35                    Text("Day").tag(AgendaSpan?.some(.day))
 36                    Text("Week").tag(AgendaSpan?.some(.week))
 37                    Text("Month").tag(AgendaSpan?.some(.month))
 38                }
 39                .pickerStyle(.segmented)
 40                .labelsHidden()
 41                .help("Show a day, week or month (v d, v w, v m)")
 42                ControlGroup {
 43                    Button("Earlier", systemImage: "chevron.left") { move(forward: false) }
 44                        .help("Previous days (b)")
 45                    Button("Today") { goToday() }
 46                        .help("Back to today (.)")
 47                    Button("Later", systemImage: "chevron.right") { move(forward: true) }
 48                        .help("Next days (f)")
 49                }
 50                Button("Go to Date", systemImage: "calendar") {
 51                    pickedDate = Self.date(anchorDay)
 52                    showingDatePicker = true
 53                }
 54                .help("Go to a date (j)")
 55                .popover(isPresented: $showingDatePicker, arrowEdge: .bottom) {
 56                    DatePicker("Date", selection: $pickedDate, displayedComponents: .date)
 57                        .datePickerStyle(.graphical)
 58                        .labelsHidden()
 59                        .padding()
 60                        .onChange(of: pickedDate) {
 61                            showingDatePicker = false
 62                            goTo(Days.absolute(pickedDate, calendar: .current))
 63                        }
 64                }
 65            }
 66            Menu {
 67                Button("Filter…") { askFilter("/") }
 68                Button("By Tag…") { askFilter("\\") }
 69                Button("By Category of Selected Line") { toggleCategoryFilter() }
 70                Button("By Regexp…") { askFilter("=") }
 71                Button("By Effort…") { askFilter("_") }
 72                Divider()
 73                Button("Remove Filters") { filter = AgendaFilter() }
 74                    .disabled(filter.isEmpty)
 75            } label: {
 76                Label("Filter", systemImage: filter.isEmpty ? "line.3.horizontal.decrease.circle" : "line.3.horizontal.decrease.circle.fill")
 77            } primaryAction: {
 78                askFilter("/")
 79            }
 80            .help("Filter the entries (/, \\, <, =, _; | removes)")
 81        }
 82    }
 83
 84    /// The span shown, as the window's title: `Week of 5 Oct 2026`.
 85    var title: String {
 86        guard isAgenda else { return viewName.replacingOccurrences(of: "…", with: "") }
 87        guard let first = agenda.days.first?.day, let last = agenda.days.last?.day else { return "Agenda" }
 88        switch spanKind {
 89        case .day: return Self.format(first, "EEEE d MMMM yyyy")
 90        case .week: return "Week of " + Self.format(first, "d MMM yyyy")
 91        case .month: return Self.format(first, "MMMM yyyy")
 92        case nil:
 93            if first == last { return Self.format(first, "EEEE d MMMM yyyy") }
 94            let sameYear = Days.date(first).year == Days.date(last).year
 95            return Self.format(first, sameYear ? "d MMM" : "d MMM yyyy") + " – " + Self.format(last, "d MMM yyyy")
 96        }
 97    }
 98
 99    // MARK: - Span
100
101    /// The day `v`, `j` and `k` start from: the selected line's, else today when shown, else the first.
102    var anchorDay: Int {
103        if let selection, let day = Int(selection.prefix { $0 != ":" }) { return day }
104        let days = agenda.days.map(\.day)
105        if days.contains(agenda.today) || days.isEmpty { return agenda.today }
106        return days[0]
107    }
108
109    /// `org-agenda-day-view`, `-week-view`, `-month-view`: the day, the week from Monday
110    /// (`org-agenda-start-on-weekday`), or the month around `anchor`.
111    func setSpan(_ kind: AgendaSpan, around anchor: Int? = nil) {
112        let anchor = anchor ?? anchorDay
113        spanKind = kind
114        selection = nil
115        switch kind {
116        case .day:
117            agenda.mode = .agenda(span: 1, startOffset: nil)
118            agenda.start = anchor
119        case .week:
120            agenda.mode = .agenda(span: 7, startOffset: nil)
121            agenda.start = Days.weekStart(anchor, on: agenda.startOnWeekday)
122        case .month:
123            let d = Days.date(anchor)
124            let first = Days.absolute(year: d.year, month: d.month, day: 1)
125            let next = d.month == 12 ? Days.absolute(year: d.year + 1, month: 1, day: 1) : Days.absolute(year: d.year, month: d.month + 1, day: 1)
126            agenda.mode = .agenda(span: next - first, startOffset: nil)
127            agenda.start = first
128        }
129    }
130
131    func move(forward: Bool) {
132        selection = nil
133        if spanKind == .month, let first = agenda.days.first?.day {
134            setSpan(.month, around: forward ? first + 31 : first - 1)
135        } else {
136            agenda.shift(forward: forward)
137        }
138    }
139
140    func goToday() {
141        if let spanKind { setSpan(spanKind, around: agenda.today) } else { agenda.showToday() }
142        selection = nil
143    }
144
145    /// `org-agenda-goto-date`.
146    private func goTo(_ day: Int) {
147        if let spanKind { setSpan(spanKind, around: day) } else { agenda.start = day }
148        selection = nil
149    }
150
151    /// Capture on `day`, as `org-agenda-capture`.
152    func capture(on day: Int) {
153        commands.capture(on: day)
154        NSApp.activate()
155        openWindow(id: "capture")
156    }
157
158    static func date(_ day: Int) -> Date {
159        let d = Days.date(day)
160        return Calendar.current.date(from: DateComponents(year: d.year, month: d.month, day: d.day)) ?? Date()
161    }
162
163    static func format(_ day: Int, _ pattern: String) -> String {
164        let formatter = DateFormatter()
165        formatter.dateFormat = pattern
166        return formatter.string(from: date(day))
167    }
168
169    static func hhmm(_ date: Date) -> Int {
170        let c = Calendar.current.dateComponents([.hour, .minute], from: date)
171        return (c.hour ?? 0) * 100 + (c.minute ?? 0)
172    }
173    /// How far ahead notifications are set, as the design asks the agenda to show.
174    var reminderStatus: String? {
175        guard let scheduler, remindersEnabled else { return nil }
176        if !scheduler.isAuthorized { return "Notifications are off for orgstar in System Settings." }
177        guard let through = scheduler.scheduledThrough else { return nil }
178        return "Reminders are set through " + through.formatted(.dateTime.weekday(.abbreviated).day().month(.abbreviated).hour().minute()) + "."
179    }
180
181    var listTitle: String {
182        if case .agenda = agenda.mode { return "" }
183        return agenda.viewSettings[agenda.mode]?.header ?? agenda.mode.title
184    }
185
186    func loadViews() {
187        let loaded = AgendaViewLoader.load()
188        views = loaded.views
189        agenda.viewSettings = AgendaViewLoader.settings(loaded.views)
190        message = loaded.problems.first
191    }
192
193    /// The days of a followed timestamp, in the agenda view.
194    func showRequestedDays() {
195        guard let request = commands.agendaRequest else { return }
196        commands.agendaRequest = nil
197        selection = nil
198        spanKind = nil
199        if viewName != AgendaViewLoader.builtIn[0].name {
200            keepRequestedDays = true
201            viewName = AgendaViewLoader.builtIn[0].name
202        }
203        agenda.mode = .agenda(span: request.days, startOffset: nil)
204        agenda.start = request.start
205    }
206
207    func applyView() {
208        if keepRequestedDays { return keepRequestedDays = false }
209        selection = nil
210        spanKind = nil
211        agenda.start = nil
212        switch viewName {
213        case Self.match, Self.todoMatch:
214            let match = matchText.trimmingCharacters(in: .whitespaces)
215            guard !match.isEmpty else { return }
216            agenda.mode = .match(match, todoOnly: viewName == Self.todoMatch)
217        case Self.search, Self.todoSearch:
218            guard matchText.contains(where: { !$0.isWhitespace }) else { return }
219            agenda.mode = .search(matchText, todoOnly: viewName == Self.todoSearch)
220        default:
221            if let view = views.first(where: { $0.name == viewName }) { agenda.mode = view.mode }
222        }
223    }
224
225    // MARK: - Filters
226
227    /// The tags and categories on the view's lines, which filter words are read against.
228    var shown: (tags: Set<String>, categories: Set<String>) {
229        let shown = isBlocks ? agenda.blocks.flatMap { $0.days.flatMap(\.items) + $0.list } : isAgenda ? agenda.days.flatMap(\.items) : agenda.list
230        let items = shown.filter { $0.path != nil }
231        return (Set(items.flatMap(\.tags)), Set(items.map(\.category)))
232    }
233
234    func askFilter(_ kind: Character) {
235        switch kind {
236        case "/": filterText = filter.description
237        default: filterText = ""
238        }
239        let title = switch kind {
240        case "/": "Filter [+cat-tag<0:10-/regexp/]:"
241        case "\\": "Tag filter (+tag-tag):"
242        case "=": "Regexp filter (-re to drop):"
243        default: "Effort filter (<0:30, >1:00, =1:00):"
244        }
245        filterPrompt = (title, kind)
246    }
247
248    func applyFilter() {
249        guard let kind = filterPrompt?.kind else { return }
250        filterPrompt = nil
251        let text = filterText.trimmingCharacters(in: .whitespaces)
252        var current = filter
253        switch kind {
254        case "/":
255            let (parsed, ignored) = AgendaFilter().parse(text, tags: shown.tags, categories: shown.categories)
256            current = parsed
257            if !ignored.isEmpty { message = "\(ignored.joined(separator: " ")) ignored: no line has that tag or category" }
258        case "\\":
259            // Every word as a tag.
260            current.tags = AgendaFilter().parse(text, tags: Set(text.split(whereSeparator: { "+- ".contains($0) }).map(String.init)), categories: []).filter.tags
261        case "=":
262            current.regexps = text.isEmpty ? [] : [text.hasPrefix("-") || text.hasPrefix("+") ? text : "+" + text]
263        default:
264            current.efforts = text.isEmpty ? [] : ["+" + text]
265        }
266        filter = current
267        selection = nil
268    }
269
270    /// `<`: keep only the selected line's category, or drop that filter.
271    func toggleCategoryFilter() {
272        if !filter.categories.isEmpty {
273            filter.categories = []
274        } else if let selection, let item = item(selection) {
275            filter.categories = ["+" + item.category]
276        } else {
277            message = "No entry selected"
278        }
279    }
280
281    /// The entry in the main window; with `focus` false the agenda keeps the keys (SPC).
282    func jump(_ id: String, focus: Bool = true) {
283        guard let item = item(id), let path = item.path, let offset = item.markerOffset ?? item.headingOffset else { return }
284        commands.jump(path: path, offset: offset)
285        if focus { openWindow(id: "main") }
286    }
287}