Sources/Orgstar/ModeLine.swift

design-themes-widgets
orgstar/Sources/Orgstar/ModeLine.swift history · blame · raw

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