Sources/Orgstar/AgendaView+Toolbar.swift

design-themes-widgets
orgstar/Sources/Orgstar/AgendaView+Toolbar.swift history · blame · raw

350 lines · 14739 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                Divider()
 22                Button("Save as View…") { saveView() }
 23                    .disabled(!canSaveView)
 24            } label: {
 25                Label(viewName, systemImage: "calendar").labelStyle(.titleAndIcon)
 26            }
 27            .help("What the agenda shows")
 28            if isMatch || isSearch {
 29                TextField(isSearch ? "Phrase or +word -word {regexp}" : "+work-boss|LEVEL>2/!TODO", text: $matchText)
 30                    .frame(minWidth: 220)
 31                    .onSubmit { applyView() }
 32            }
 33        }
 34        ToolbarItemGroup {
 35            if agenda.isComputing { ProgressView().controlSize(.small) }
 36            if isAgenda {
 37                Picker("Span", selection: Binding(get: { spanKind }, set: { if let kind = $0 { setSpan(kind) } })) {
 38                    Text("Day").tag(AgendaSpan?.some(.day))
 39                    Text("Week").tag(AgendaSpan?.some(.week))
 40                    Text("Month").tag(AgendaSpan?.some(.month))
 41                }
 42                .pickerStyle(.segmented)
 43                .labelsHidden()
 44                .help("Show a day, week or month (v d, v w, v m)")
 45                ControlGroup {
 46                    Button("Earlier", systemImage: "chevron.left") { move(forward: false) }
 47                        .help("Previous days (b)")
 48                    Button("Today") { goToday() }
 49                        .help("Back to today (.)")
 50                    Button(String(localized: "agenda.later", defaultValue: "Later", comment: "Shows the next days in the agenda"), systemImage: "chevron.right") { move(forward: true) }
 51                        .help("Next days (f)")
 52                }
 53                Button("Go to Date", systemImage: "calendar") {
 54                    pickedDate = Self.date(anchorDay)
 55                    showingDatePicker = true
 56                }
 57                .help("Go to a date (j)")
 58                .popover(isPresented: $showingDatePicker, arrowEdge: .bottom) {
 59                    DatePicker("Date", selection: $pickedDate, displayedComponents: .date)
 60                        .datePickerStyle(.graphical)
 61                        .labelsHidden()
 62                        .padding()
 63                        .onChange(of: pickedDate) {
 64                            showingDatePicker = false
 65                            goTo(Days.absolute(pickedDate, calendar: .current))
 66                        }
 67                }
 68            }
 69            if workspace.rootPaths.count > 1 || hidesFolders { foldersMenu }
 70            Menu {
 71                Button("Filter…") { askFilter("/") }
 72                Button("By Tag…") { askFilter("\\") }
 73                Button("By Category of Selected Line") { toggleCategoryFilter() }
 74                Button("By Regexp…") { askFilter("=") }
 75                Button("By Effort…") { askFilter("_") }
 76                Divider()
 77                Button("Remove Filters") { filter = AgendaFilter() }
 78                    .disabled(filter.isEmpty)
 79            } label: {
 80                Label("Filter", systemImage: filter.isEmpty ? "line.3.horizontal.decrease.circle" : "line.3.horizontal.decrease.circle.fill")
 81            } primaryAction: {
 82                askFilter("/")
 83            }
 84            .help("Filter the entries (/, \\, <, =, _; | removes)")
 85        }
 86    }
 87
 88    /// Shows or hides each folder's files; folders the Focus hides stay hidden.
 89    private var foldersMenu: some View {
 90        let hidden = HiddenFolders.shared
 91        return Menu {
 92            Button("All Folders") { hidden.manual = [] }
 93                .disabled(hidden.manual.isEmpty)
 94            Divider()
 95            ForEach(workspace.rootPaths, id: \.self) { root in
 96                Toggle((root as NSString).lastPathComponent, isOn: Binding {
 97                    !hidden.all.contains(root)
 98                } set: { shown in
 99                    if shown { hidden.manual.remove(root) } else { hidden.manual.insert(root) }
100                })
101                .disabled(hidden.focus.contains(root))
102            }
103            if !hidden.focus.isDisjoint(with: workspace.rootPaths) {
104                Divider()
105                Text("Dimmed folders are hidden by the current Focus.")
106            }
107        } label: {
108            Label("Folders", systemImage: hidesFolders ? "folder.fill" : "folder")
109        }
110        .help("The folders the agenda shows")
111    }
112
113    /// Some folder is hidden.
114    var hidesFolders: Bool { !HiddenFolders.shared.all.isDisjoint(with: workspace.rootPaths) }
115
116    /// The folders shown, by name, while some are hidden.
117    var shownFolders: String? {
118        guard hidesFolders else { return nil }
119        let shown = workspace.rootPaths.filter { !HiddenFolders.shared.all.contains($0) }
120        return shown.isEmpty ? "No folders" : shown.map { ($0 as NSString).lastPathComponent }.joined(separator: ", ")
121    }
122
123    /// The span shown, as the window's title: `Week of 5 Oct 2026`.
124    var title: String {
125        guard isAgenda else { return viewName.replacingOccurrences(of: "…", with: "") }
126        guard let first = agenda.days.first?.day, let last = agenda.days.last?.day else { return "Agenda" }
127        switch spanKind {
128        case .day: return Self.format(first, "EEEE d MMMM yyyy")
129        case .week: return "Week of " + Self.format(first, "d MMM yyyy")
130        case .month: return Self.format(first, "MMMM yyyy")
131        case nil:
132            if first == last { return Self.format(first, "EEEE d MMMM yyyy") }
133            let sameYear = Days.date(first).year == Days.date(last).year
134            return Self.format(first, sameYear ? "d MMM" : "d MMM yyyy") + " – " + Self.format(last, "d MMM yyyy")
135        }
136    }
137
138    // MARK: - Span
139
140    /// The day `v`, `j` and `k` start from: the selected line's, else today when shown, else the first.
141    var anchorDay: Int {
142        if let selection, let day = Int(selection.prefix { $0 != ":" }) { return day }
143        let days = agenda.days.map(\.day)
144        if days.contains(agenda.today) || days.isEmpty { return agenda.today }
145        return days[0]
146    }
147
148    /// `org-agenda-day-view`, `-week-view`, `-month-view`: the day, the week from Monday
149    /// (`org-agenda-start-on-weekday`), or the month around `anchor`.
150    func setSpan(_ kind: AgendaSpan, around anchor: Int? = nil) {
151        let anchor = anchor ?? anchorDay
152        spanKind = kind
153        selection = nil
154        switch kind {
155        case .day:
156            agenda.mode = .agenda(span: 1, startOffset: nil)
157            agenda.start = anchor
158        case .week:
159            agenda.mode = .agenda(span: 7, startOffset: nil)
160            agenda.start = Days.weekStart(anchor, on: agenda.startOnWeekday)
161        case .month:
162            let d = Days.date(anchor)
163            let first = Days.absolute(year: d.year, month: d.month, day: 1)
164            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)
165            agenda.mode = .agenda(span: next - first, startOffset: nil)
166            agenda.start = first
167        }
168    }
169
170    func move(forward: Bool) {
171        selection = nil
172        if spanKind == .month, let first = agenda.days.first?.day {
173            setSpan(.month, around: forward ? first + 31 : first - 1)
174        } else {
175            agenda.shift(forward: forward)
176        }
177    }
178
179    func goToday() {
180        if let spanKind { setSpan(spanKind, around: agenda.today) } else { agenda.showToday() }
181        selection = nil
182    }
183
184    /// `org-agenda-goto-date`.
185    private func goTo(_ day: Int) {
186        if let spanKind { setSpan(spanKind, around: day) } else { agenda.start = day }
187        selection = nil
188    }
189
190    /// Capture on `day`, as `org-agenda-capture`.
191    func capture(on day: Int) {
192        commands.capture(on: day)
193        NSApp.activate()
194        openWindow(id: "capture")
195    }
196
197    static func date(_ day: Int) -> Date {
198        let d = Days.date(day)
199        return Calendar.current.date(from: DateComponents(year: d.year, month: d.month, day: d.day)) ?? Date()
200    }
201
202    static func format(_ day: Int, _ pattern: String) -> String {
203        let formatter = DateFormatter()
204        formatter.dateFormat = pattern
205        return formatter.string(from: date(day))
206    }
207
208    static func hhmm(_ date: Date) -> Int {
209        let c = Calendar.current.dateComponents([.hour, .minute], from: date)
210        return (c.hour ?? 0) * 100 + (c.minute ?? 0)
211    }
212    /// How far ahead notifications are set, as the design asks the agenda to show.
213    var reminderStatus: String? {
214        guard let scheduler, remindersEnabled else { return nil }
215        if !scheduler.isAuthorized { return "Notifications are off for orgstar in System Settings." }
216        guard let through = scheduler.scheduledThrough else { return nil }
217        return "Reminders are set through " + through.formatted(.dateTime.weekday(.abbreviated).day().month(.abbreviated).hour().minute()) + "."
218    }
219
220    var listTitle: String {
221        if case .agenda = agenda.mode { return "" }
222        return agenda.viewSettings[agenda.mode]?.header ?? agenda.mode.title
223    }
224
225    /// A typed match or search is showing, which isn't a named view yet.
226    var canSaveView: Bool {
227        guard isMatch || isSearch else { return false }
228        switch agenda.mode {
229        case .match, .search: return true
230        default: return false
231        }
232    }
233
234    /// Asks for a name and adds the match or search showing to `views.toml`, then shows it as
235    /// that view.
236    func saveView() {
237        let mode = agenda.mode
238        textPrompt = TextPrompt(title: String(localized: "Name for this view:")) { name in
239            do {
240                try AgendaViewLoader.save(name: name, mode: mode)
241                loadViews()
242                viewName = name.trimmingCharacters(in: .whitespacesAndNewlines)
243            } catch {
244                message = "\(error)"
245            }
246        }
247    }
248
249    func loadViews() {
250        let loaded = AgendaViewLoader.load()
251        views = loaded.views
252        agenda.viewSettings = AgendaViewLoader.settings(loaded.views)
253        message = loaded.problems.first
254    }
255
256    /// The days of a followed timestamp, in the agenda view.
257    func showRequestedDays() {
258        guard let request = commands.agendaRequest else { return }
259        commands.agendaRequest = nil
260        selection = nil
261        spanKind = nil
262        if viewName != AgendaViewLoader.builtIn[0].name {
263            keepRequestedDays = true
264            viewName = AgendaViewLoader.builtIn[0].name
265        }
266        agenda.mode = .agenda(span: request.days, startOffset: nil)
267        agenda.start = request.start
268    }
269
270    func applyView() {
271        if keepRequestedDays { return keepRequestedDays = false }
272        selection = nil
273        spanKind = nil
274        agenda.start = nil
275        switch viewName {
276        case Self.match, Self.todoMatch:
277            let match = matchText.trimmingCharacters(in: .whitespaces)
278            guard !match.isEmpty else { return }
279            agenda.mode = .match(match, todoOnly: viewName == Self.todoMatch)
280        case Self.search, Self.todoSearch:
281            guard matchText.contains(where: { !$0.isWhitespace }) else { return }
282            agenda.mode = .search(matchText, todoOnly: viewName == Self.todoSearch)
283        default:
284            if let view = views.first(where: { $0.name == viewName }) { agenda.mode = view.mode }
285        }
286    }
287
288    // MARK: - Filters
289
290    /// The tags and categories on the view's lines, which filter words are read against.
291    var shown: (tags: Set<String>, categories: Set<String>) {
292        let shown = isBlocks ? agenda.blocks.flatMap { $0.days.flatMap(\.items) + $0.list } : isAgenda ? agenda.days.flatMap(\.items) : agenda.list
293        let items = shown.filter { $0.path != nil }
294        return (Set(items.flatMap(\.tags)), Set(items.map(\.category)))
295    }
296
297    func askFilter(_ kind: Character) {
298        switch kind {
299        case "/": filterText = filter.description
300        default: filterText = ""
301        }
302        let title = switch kind {
303        case "/": "Filter [+cat-tag<0:10-/regexp/]:"
304        case "\\": "Tag filter (+tag-tag):"
305        case "=": "Regexp filter (-re to drop):"
306        default: "Effort filter (<0:30, >1:00, =1:00):"
307        }
308        filterPrompt = (title, kind)
309    }
310
311    func applyFilter() {
312        guard let kind = filterPrompt?.kind else { return }
313        filterPrompt = nil
314        let text = filterText.trimmingCharacters(in: .whitespaces)
315        var current = filter
316        switch kind {
317        case "/":
318            let (parsed, ignored) = AgendaFilter().parse(text, tags: shown.tags, categories: shown.categories)
319            current = parsed
320            if !ignored.isEmpty { message = "\(ignored.joined(separator: " ")) ignored: no line has that tag or category" }
321        case "\\":
322            // Every word as a tag.
323            current.tags = AgendaFilter().parse(text, tags: Set(text.split(whereSeparator: { "+- ".contains($0) }).map(String.init)), categories: []).filter.tags
324        case "=":
325            current.regexps = text.isEmpty ? [] : [text.hasPrefix("-") || text.hasPrefix("+") ? text : "+" + text]
326        default:
327            current.efforts = text.isEmpty ? [] : ["+" + text]
328        }
329        filter = current
330        selection = nil
331    }
332
333    /// `<`: keep only the selected line's category, or drop that filter.
334    func toggleCategoryFilter() {
335        if !filter.categories.isEmpty {
336            filter.categories = []
337        } else if let selection, let item = item(selection) {
338            filter.categories = ["+" + item.category]
339        } else {
340            message = "No entry selected"
341        }
342    }
343
344    /// The entry in the main window; with `focus` false the agenda keeps the keys (SPC).
345    func jump(_ id: String, focus: Bool = true) {
346        guard let item = item(id), let path = item.path, let offset = item.markerOffset ?? item.headingOffset else { return }
347        commands.jump(path: path, offset: offset)
348        if focus { openWindow(id: "main") }
349    }
350}