Sources/Orgstar/ModeLine.swift

153 lines · 6794 bytes

  1import OrgApp
  2import OrgCore
  3import OrgPresentation
  4import SwiftUI
  5
  6/// The line under the editor: evil state, unsaved mark and the headings around the caret on
  7/// the left; the running clock, the selection's counts, line and column, the file's words,
  8/// anything unusual about its encoding and the git branch on the right.
  9struct ModeLine: View {
 10    let session: DocumentSession
 11    let commands: AppCommands
 12    let clock: ClockModel
 13    /// Runs an app command (clock out, go to the clocked entry).
 14    let perform: (String) -> Void
 15    @Environment(\.orgTheme) private var theme
 16    @State private var words: Int?
 17    @State private var crlf = false
 18    @State private var branch: String?
 19
 20    var body: some View {
 21        let text = commands.editor?.document.text ?? ""
 22        let selection = commands.selection
 23        HStack(spacing: 10) {
 24            if let state = commands.editorState { StateTag(state: state) }
 25            if session.isDirty {
 26                Image(systemName: "circle.fill")
 27                    .font(.system(size: 6))
 28                    .foregroundStyle(.secondary)
 29                    .help("Unsaved changes")
 30                    .accessibilityLabel("Unsaved changes")
 31            }
 32            breadcrumb(at: selection.location)
 33            Spacer(minLength: 12)
 34            if let running = clock.running {
 35                Menu {
 36                    Button("Clock Out") { perform("app.clock.out") }
 37                    Button("Cancel Clock") { perform("app.clock.cancel") }
 38                    Button("Go to Clocked Entry") { perform("app.clock.goto") }
 39                } label: {
 40                    TimelineView(.periodic(from: .now, by: 30)) { context in
 41                        Text("⏱ \(clockElapsed(running, now: context.date)) \(running.heading)")
 42                            .font(.system(.caption, design: .monospaced))
 43                    }
 44                }
 45                .menuStyle(.borderlessButton)
 46                .menuIndicator(.hidden)
 47                .fixedSize()
 48                .foregroundStyle(theme.color("modeline-highlight") ?? .primary)
 49                .help("Clocked in since \(running.startedAt.formatted(date: .omitted, time: .shortened))")
 50            }
 51            if let timer = TimerModel.shared.timer {
 52                Menu {
 53                    Button(timer.paused == nil ? "Pause Timer" : "Continue Timer") { commands.editor?.run("org.timer.pause") }
 54                    Button("Stop Timer") { commands.editor?.run("org.timer.stop") }
 55                } label: {
 56                    TimelineView(.periodic(from: .now, by: 1)) { context in
 57                        Text(timer.modeLine(now: context.date)).font(.system(.caption, design: .monospaced))
 58                    }
 59                }
 60                .menuStyle(.borderlessButton)
 61                .menuIndicator(.hidden)
 62                .fixedSize()
 63                .help(timer.isCountdown ? "Countdown timer" : "Relative timer")
 64            }
 65            if selection.length > 0, let region = region(text, selection) {
 66                Text("\(region.lines) \(region.lines == 1 ? "line" : "lines"), \(region.words) \(region.words == 1 ? "word" : "words"), \(region.characters) chars")
 67                    .help("Selection (count-words-region)")
 68            }
 69            let position = TextStats.position(in: text, at: selection.location + selection.length)
 70            Text("\(position.line):\(position.column)")
 71                .help("Line \(position.line), column \(position.column)")
 72            if let words {
 73                Text("\(words.formatted()) \(words == 1 ? "word" : "words")")
 74                    .help("Words in the file (count-words)")
 75            }
 76            ForEach(encodingNotes, id: \.self) { note in
 77                Text(note).foregroundStyle(.orange)
 78            }
 79            if let branch {
 80                Label(branch, systemImage: "arrow.triangle.branch")
 81                    .labelStyle(.titleAndIcon)
 82                    .help("Git branch")
 83            }
 84        }
 85        .font(.system(.caption, design: .monospaced))
 86        .monospacedDigit()
 87        .lineLimit(1)
 88        .foregroundStyle(theme.color("modeline-foreground") ?? .secondary)
 89        .padding(.horizontal, 10)
 90        .frame(height: 22)
 91        .background { if let bg = theme.color("modeline-background") { bg } else { Rectangle().fill(.bar) } }
 92        .overlay(alignment: .top) { Divider() }
 93        .task(id: session.path) {
 94            // HEAD changes outside the app, so look again every few seconds.
 95            while !Task.isCancelled {
 96                let path = session.path
 97                branch = await Task.detached(priority: .utility) { path.flatMap(GitBranch.current) }.value
 98                try? await Task.sleep(for: .seconds(5))
 99            }
100        }
101        .task(id: WordsKey(path: session.path, version: session.editVersion)) {
102            guard let text = commands.editor?.document.text ?? session.document?.text else {
103                words = nil
104                return
105            }
106            (words, crlf) = await Task.detached(priority: .utility) { (TextStats.words(in: text), text.contains("\r\n")) }.value
107        }
108    }
109
110    private struct WordsKey: Hashable {
111        var path: String?
112        var version: Int
113    }
114
115    /// The outline path of the heading containing `offset`, outermost first.
116    @ViewBuilder
117    private func breadcrumb(at offset: Int) -> some View {
118        let path = outlinePath(at: offset)
119        if !path.isEmpty {
120            Text(path.joined(separator: " › "))
121                .truncationMode(.head)
122                .foregroundStyle(theme.color("modeline-highlight") ?? .primary)
123                .help(path.joined(separator: " › "))
124        }
125    }
126
127    private func outlinePath(at offset: Int) -> [String] {
128        let outline = session.outline
129        var path: [String] = []
130        var current = outline.lastIndex { $0.start <= offset }
131        while let i = current {
132            path.insert(outline[i].title.isEmpty ? "(untitled)" : outline[i].title, at: 0)
133            current = outline[i].parent
134        }
135        return path
136    }
137
138    private func region(_ text: String, _ range: NSRange) -> (lines: Int, words: Int, characters: Int)? {
139        let ns = text as NSString
140        guard NSMaxRange(range) <= ns.length else { return nil }
141        return TextStats.region(ns.substring(with: range))
142    }
143
144    /// Only what differs from UTF-8 with LF endings.
145    private var encodingNotes: [String] {
146        guard let document = session.document else { return [] }
147        var notes: [String] = []
148        if session.isReadOnly { notes.append("Read-only") }
149        if document.source.hasBOM { notes.append("BOM") }
150        if crlf { notes.append("CRLF") }
151        return notes
152    }
153}