Sources/Orgstar/ClockViews.swift

1569d791fbc3c0618d100bc101222d3bfc5f56d9
orgstar/Sources/Orgstar/ClockViews.swift history · blame · raw

140 lines · 5566 bytes

  1import AppKit
  2import OrgApp
  3import OrgCore
  4import SwiftUI
  5
  6/// Elapsed time of the running clock, `H:MM`.
  7func clockElapsed(_ running: ClockModel.Running, now: Date) -> String {
  8    let minutes = max(0, Int(now.timeIntervalSince(running.startedAt) / 60))
  9    return String(format: "%d:%02d", minutes / 60, minutes % 60)
 10}
 11
 12/// The menu bar item while a clock runs: elapsed time, and clock out, cancel and go to.
 13@MainActor
 14final class ClockStatusItem: NSObject {
 15    private var item: NSStatusItem?
 16    private var timer: Timer?
 17    private var running: ClockModel.Running?
 18    private let run: (String) -> Void
 19
 20    init(run: @escaping (String) -> Void) {
 21        self.run = run
 22    }
 23
 24    func update(_ running: ClockModel.Running?) {
 25        self.running = running
 26        guard let running else {
 27            timer?.invalidate()
 28            timer = nil
 29            if let item { NSStatusBar.system.removeStatusItem(item) }
 30            item = nil
 31            return
 32        }
 33        if item == nil {
 34            item = NSStatusBar.system.statusItem(withLength: NSStatusItem.variableLength)
 35            timer = Timer.scheduledTimer(withTimeInterval: 30, repeats: true) { [weak self] _ in
 36                MainActor.assumeIsolated { self?.refresh() }
 37            }
 38        }
 39        let menu = NSMenu()
 40        menu.addItem(withTitle: running.heading, action: nil, keyEquivalent: "")
 41        menu.addItem(.separator())
 42        for (title, id) in [("Clock Out", "app.clock.out"), ("Cancel Clock", "app.clock.cancel"), ("Go to Clocked Entry", "app.clock.goto"), ("Clock Report", "app.clock.report")] {
 43            let entry = NSMenuItem(title: title, action: #selector(choose(_:)), keyEquivalent: "")
 44            entry.target = self
 45            entry.representedObject = id
 46            menu.addItem(entry)
 47        }
 48        item?.menu = menu
 49        refresh()
 50    }
 51
 52    private func refresh() {
 53        guard let running else { return }
 54        item?.button?.title = "⏱ " + clockElapsed(running, now: Date())
 55    }
 56
 57    @objc private func choose(_ sender: NSMenuItem) {
 58        if let id = sender.representedObject as? String {
 59            NSApp.activate()
 60            run(id)
 61        }
 62    }
 63}
 64
 65/// Clocked time per day and heading (`ClockReport.timeReport`) for chosen files and dates.
 66struct ClockReportView: View {
 67    let workspace: WorkspaceModel
 68    @State private var start = Calendar.current.date(byAdding: .day, value: -6, to: Date()) ?? Date()
 69    @State private var end = Date()
 70    @State private var limit = false
 71    @State private var selected: Set<String> = []
 72    @State private var report = ""
 73
 74    private var candidates: [FileEntry] { workspace.files.filter { $0.kind == .org } }
 75
 76    var body: some View {
 77        HSplitView {
 78            List(candidates, selection: $selected) { file in
 79                Text(file.relativePath).tag(file.path)
 80            }
 81            .frame(minWidth: 180, idealWidth: 220, maxWidth: 320)
 82            VStack(alignment: .leading, spacing: 8) {
 83                HStack {
 84                    Toggle("From", isOn: $limit)
 85                    DatePicker("", selection: $start, displayedComponents: .date).labelsHidden().disabled(!limit)
 86                    Text("to")
 87                    DatePicker("", selection: $end, displayedComponents: .date).labelsHidden().disabled(!limit)
 88                    Spacer()
 89                    Button("Copy") {
 90                        NSPasteboard.general.clearContents()
 91                        NSPasteboard.general.setString(report, forType: .string)
 92                    }
 93                    Button("Save…", action: saveReport)
 94                }
 95                ScrollView([.horizontal, .vertical]) {
 96                    Text(report.isEmpty ? "Choose files with clocked time." : report)
 97                        .font(.body.monospaced())
 98                        .textSelection(.enabled)
 99                        .fixedSize()
100                        .padding(4)
101                }
102                .defaultScrollAnchor(.topLeading)
103                .frame(maxWidth: .infinity, maxHeight: .infinity, alignment: .topLeading)
104            }
105            .padding(12)
106        }
107        .navigationTitle("Clock Report")
108        .onAppear {
109            if selected.isEmpty {
110                selected = Set(candidates.filter { (try? String(contentsOfFile: $0.path, encoding: .utf8))?.contains("CLOCK: [") ?? false }.map(\.path))
111            }
112            compute()
113        }
114        .onChange(of: selected) { compute() }
115        .onChange(of: start) { compute() }
116        .onChange(of: end) { compute() }
117        .onChange(of: limit) { compute() }
118    }
119
120    private func day(_ date: Date) -> String {
121        let c = Calendar.current.dateComponents([.year, .month, .day], from: date)
122        return String(format: "%04d-%02d-%02d", c.year!, c.month!, c.day!)
123    }
124
125    private func compute() {
126        var entries: [ClockReport.Entry] = []
127        for path in selected.sorted() {
128            guard let text = try? String(contentsOfFile: path, encoding: .utf8) else { continue }
129            entries += ClockReport.entries(text, settings: workspace.settings.org)
130        }
131        report = selected.isEmpty ? "" : ClockReport.timeReport(entries, start: limit ? day(start) : nil, end: limit ? day(end) : nil)
132    }
133
134    private func saveReport() {
135        let panel = NSSavePanel()
136        panel.nameFieldStringValue = "time-report.org"
137        guard panel.runModal() == .OK, let url = panel.url else { return }
138        try? report.write(to: url, atomically: true, encoding: .utf8)
139    }
140}