Sources/Orgstar/AgendaView+Toolbar.swift

8c691f12299d61cfcb74e8583609abd3243a5140
orgstar/Sources/Orgstar/AgendaView+Toolbar.swift

350 lines · 15223 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`, with the year when it isn't
124    /// the current one.
125    var title: String {
126        guard isAgenda else { return viewName.replacingOccurrences(of: "…", with: "") }
127        guard let first = agenda.days.first?.day, let last = agenda.days.last?.day else { return String(localized: "Agenda") }
128        let thisYear = Days.date(agenda.today).year
129        let year = Days.date(first).year == thisYear && Days.date(last).year == thisYear ? "" : " yyyy"
130        switch spanKind {
131        case .day: return Self.format(first, "EEEE d MMMM" + year)
132        case .week: return String(localized: "Week of \(Self.format(first, "d MMM" + year))", comment: "Agenda title; the date is the week's first day")
133        case .month: return Self.format(first, "MMMM" + year)
134        case nil:
135            if first == last { return Self.format(first, "EEEE d MMMM" + year) }
136            let sameYear = Days.date(first).year == Days.date(last).year
137            return Self.format(first, sameYear ? "d MMM" : "d MMM yyyy") + " – " + Self.format(last, "d MMM" + year)
138        }
139    }
140
141    // MARK: - Span
142
143    /// The day `v`, `j` and `k` start from: the selected line's, else today when shown, else the first.
144    var anchorDay: Int {
145        if let selection, let day = Int(selection.prefix { $0 != ":" }) { return day }
146        let days = agenda.days.map(\.day)
147        if days.contains(agenda.today) || days.isEmpty { return agenda.today }
148        return days[0]
149    }
150
151    /// `org-agenda-day-view`, `-week-view`, `-month-view`: the day, the week from Monday
152    /// (`org-agenda-start-on-weekday`), or the month around `anchor`.
153    func setSpan(_ kind: AgendaSpan, around anchor: Int? = nil) {
154        let anchor = anchor ?? anchorDay
155        spanKind = kind
156        selection = nil
157        switch kind {
158        case .day:
159            agenda.mode = .agenda(span: 1, startOffset: nil)
160            agenda.start = anchor
161        case .week:
162            agenda.mode = .agenda(span: 7, startOffset: nil)
163            agenda.start = Days.weekStart(anchor, on: agenda.startOnWeekday)
164        case .month:
165            let d = Days.date(anchor)
166            let first = Days.absolute(year: d.year, month: d.month, day: 1)
167            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)
168            agenda.mode = .agenda(span: next - first, startOffset: nil)
169            agenda.start = first
170        }
171    }
172
173    func move(forward: Bool) {
174        selection = nil
175        if spanKind == .month, let first = agenda.days.first?.day {
176            setSpan(.month, around: forward ? first + 31 : first - 1)
177        } else {
178            agenda.shift(forward: forward)
179        }
180    }
181
182    func goToday() {
183        if let spanKind { setSpan(spanKind, around: agenda.today) } else { agenda.showToday() }
184        selection = nil
185    }
186
187    /// `org-agenda-goto-date`.
188    private func goTo(_ day: Int) {
189        if let spanKind { setSpan(spanKind, around: day) } else { agenda.start = day }
190        selection = nil
191    }
192
193    /// Capture on `day`, as `org-agenda-capture`.
194    func capture(on day: Int) {
195        commands.capture(on: day)
196        NSApp.activate()
197        openWindow(id: "capture")
198    }
199
200    static func date(_ day: Int) -> Date {
201        let d = Days.date(day)
202        return Calendar.current.date(from: DateComponents(year: d.year, month: d.month, day: d.day)) ?? Date()
203    }
204
205    static func format(_ day: Int, _ pattern: String) -> String {
206        let formatter = DateFormatter()
207        formatter.dateFormat = pattern
208        return formatter.string(from: date(day))
209    }
210
211    static func hhmm(_ date: Date) -> Int {
212        let c = Calendar.current.dateComponents([.hour, .minute], from: date)
213        return (c.hour ?? 0) * 100 + (c.minute ?? 0)
214    }
215    /// How far ahead notifications are set, as the design asks the agenda to show.
216    var reminderStatus: String? {
217        guard let scheduler, remindersEnabled else { return nil }
218        if !scheduler.isAuthorized { return String(localized: "Notifications are off for orgstar in System Settings.") }
219        guard let through = scheduler.scheduledThrough else { return nil }
220        return String(localized: "Notifications are set through \(through.formatted(.dateTime.weekday(.abbreviated).day().month(.abbreviated).hour().minute())).")
221    }
222
223    var listTitle: String {
224        if case .agenda = agenda.mode { return "" }
225        return agenda.viewSettings[agenda.mode]?.header ?? agenda.mode.title
226    }
227
228    /// A typed match or search is showing, which isn't a named view yet.
229    var canSaveView: Bool {
230        guard isMatch || isSearch else { return false }
231        switch agenda.mode {
232        case .match, .search: return true
233        default: return false
234        }
235    }
236
237    /// Asks for a name and adds the match or search showing to `views.toml`, then shows it as
238    /// that view.
239    func saveView() {
240        let mode = agenda.mode
241        ask(Prompt(key: "name", message: String(localized: "Name for this view:"))) { name in
242            do {
243                try AgendaViewLoader.save(name: name, mode: mode)
244                loadViews()
245                viewName = name.trimmingCharacters(in: .whitespacesAndNewlines)
246            } catch {
247                message = "\(error)"
248            }
249        }
250    }
251
252    func loadViews() {
253        let loaded = AgendaViewLoader.load()
254        views = loaded.views
255        agenda.viewSettings = AgendaViewLoader.settings(loaded.views)
256        message = loaded.problems.first
257    }
258
259    /// The days of a followed timestamp, in the agenda view.
260    func showRequestedDays() {
261        guard let request = commands.agendaRequest else { return }
262        commands.agendaRequest = nil
263        selection = nil
264        spanKind = nil
265        if viewName != AgendaViewLoader.builtIn[0].name {
266            keepRequestedDays = true
267            viewName = AgendaViewLoader.builtIn[0].name
268        }
269        agenda.mode = .agenda(span: request.days, startOffset: nil)
270        agenda.start = request.start
271    }
272
273    func applyView() {
274        if keepRequestedDays { return keepRequestedDays = false }
275        selection = nil
276        spanKind = nil
277        agenda.start = nil
278        switch viewName {
279        case Self.match, Self.todoMatch:
280            let match = matchText.trimmingCharacters(in: .whitespaces)
281            guard !match.isEmpty else { return }
282            agenda.mode = .match(match, todoOnly: viewName == Self.todoMatch)
283        case Self.search, Self.todoSearch:
284            guard matchText.contains(where: { !$0.isWhitespace }) else { return }
285            agenda.mode = .search(matchText, todoOnly: viewName == Self.todoSearch)
286        default:
287            if let view = views.first(where: { $0.name == viewName }) { agenda.mode = view.mode }
288        }
289    }
290
291    // MARK: - Filters
292
293    /// The tags and categories on the view's lines, which filter words are read against.
294    var shown: (tags: Set<String>, categories: Set<String>) {
295        let shown = isBlocks ? agenda.blocks.flatMap { $0.days.flatMap(\.items) + $0.list } : isAgenda ? agenda.days.flatMap(\.items) : agenda.list
296        let items = shown.filter { $0.path != nil }
297        return (Set(items.flatMap(\.tags)), Set(items.map(\.category)))
298    }
299
300    func askFilter(_ kind: Character) {
301        let title = switch kind {
302        case "/": String(localized: "Filter [+cat-tag<0:10-/regexp/]:")
303        case "\\": String(localized: "Tag filter (+tag-tag):")
304        case "=": String(localized: "Regexp filter (-re to drop):")
305        default: String(localized: "Effort filter (<0:30, >1:00, =1:00):")
306        }
307        let tags = kind == "/" || kind == "\\" ? shown.tags.sorted() : []
308        ask(Prompt(key: "filter", message: title, initial: kind == "/" ? filter.description : "", choices: tags, requireMatch: false)) { text in
309            applyFilter(kind, text)
310        }
311    }
312
313    func applyFilter(_ kind: Character, _ answer: String) {
314        let text = answer.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}
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