Sources/Orgstar/ModeLine.swift

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