SPB Git

Repository Public

ServiceLogsScreen.swift 7.8 KB 148 lines swift

1import MCCCore2import SwiftUI34/// Bounded tail of a service's logs, as text. Each request is the typed, audited action `service.logs.tail`:5/// there is no free-form command and no stream of raw output outside that action.6struct ServiceLogsScreen: View {7    @Environment(\.mccTheme) private var theme8    @Session private var session9    let serviceID: String10    let serviceName: String11    @State private var model: LogsTailModel?12    @State private var query = ""13    @State private var matchIndex = 01415    var body: some View {16        ScreenStack {17            if let model {18                switch model.phase {19                case .preparing:20                    ProgressView(tr("state.loading")).frame(maxWidth: .infinity, minHeight: 120)21                case .catalogUnavailable(let reason):22                    UnavailableStateView(reason: reason, error: model.catalogError) { Task { await model.prepare() } }23                case .typeMissing:24                    InfoBanner(tone: .neutral, title: tr("services.logs.missing.title"), message: tr("services.logs.missing.message"))25                        .accessibilityIdentifier("logs-type-missing")26                case .typeDisabled(let reason):27                    InfoBanner(tone: .warning, title: tr("services.logs.disabled.title"), message: reason ?? tr("services.logs.disabled.message"))28                        .accessibilityIdentifier("logs-type-disabled")29                case .ready:30                    controls(model)31                    output(model)32                }33            } else {34                ProgressView(tr("state.loading")).frame(maxWidth: .infinity, minHeight: 120)35            }36        }37        .screen("service-logs", title: tr("services.logs.title", serviceName), load: prepare, reload: { await model?.request() })38        .navigationBarTitleDisplayMode(.inline)39        .onDisappear { model?.stop() }40    }4142    private func prepare() async {43        if model == nil { model = LogsTailModel(serviceID: serviceID, serviceName: serviceName, session: session) }44        if model?.phase != .ready { await model?.prepare() }45    }4647    private func controls(_ model: LogsTailModel) -> some View {48        @Bindable var model = model49        return SectionCard(tr("services.logs.request_title")) {50            if model.lineField != nil {51                let range = model.lineRange52                Stepper(value: Binding(get: { model.lineCount ?? range.lowerBound },53                                       set: { model.lineCount = ServicesLogic.clampLines($0, to: range) }),54                        in: range, step: 50) {55                    Text(tr("services.logs.lines", model.lineCount ?? range.lowerBound)).foregroundStyle(theme.textPrimary)56                }57                .frame(minHeight: Tokens.Size.touchMin)58                .accessibilityIdentifier("logs-lines")59                Text(tr("services.logs.lines_bounds", range.lowerBound, range.upperBound)).font(.footnote).foregroundStyle(theme.textTertiary)60            }61            Toggle(tr("services.logs.follow", Int(model.followInterval)), isOn: $model.follow)62                .frame(minHeight: Tokens.Size.touchMin)63                .disabled(!session.canMutate)64                .accessibilityIdentifier("logs-follow")65            HStack(spacing: Tokens.Space.s3) {66                MutationButton(title: tr("services.logs.request"), systemImage: "arrow.down.doc", identifier: "logs-request", prominent: true) {67                    Task { await model.request() }68                }69                .disabled(model.isRequesting)70                if model.isRequesting { ProgressView().accessibilityLabel(tr("state.loading")) }71            }72            if let e = model.requestError { InlineErrorView(e).accessibilityIdentifier("logs-error") }73            if model.outcomeUnknown {74                InfoBanner(tone: .warning, title: tr("services.logs.outcome_unknown"), message: nil)75            }76            Text(tr("services.logs.audited")).font(.footnote).foregroundStyle(theme.textTertiary)77        }78    }7980    @ViewBuilder private func output(_ model: LogsTailModel) -> some View {81        let ranges = LogSearch.ranges(of: query, in: model.text, limit: 500)82        let current = ranges.isEmpty ? 0 : min(matchIndex, ranges.count - 1)83        SectionCard(tr("services.logs.output")) {84            if model.receivedAt == nil {85                Text(tr("services.logs.none_yet")).font(.callout).foregroundStyle(theme.textSecondary)86            } else {87                if model.truncated {88                    InfoBanner(tone: .warning, title: tr("services.logs.truncated"), message: nil).accessibilityIdentifier("logs-truncated")89                }90                search(count: ranges.count, current: current)91                if model.text.isEmpty {92                    Text(tr("services.logs.empty")).font(.callout).foregroundStyle(theme.textSecondary)93                } else {94                    Text(highlighted(model.text, ranges: ranges, current: current))95                        .font(.footnote.monospaced())96                        .foregroundStyle(theme.textPrimary)97                        .textSelection(.enabled)98                        .frame(maxWidth: .infinity, alignment: .leading)99                        .padding(Tokens.Space.s3)100                        .background(theme.inset, in: RoundedRectangle(cornerRadius: Tokens.Radius.md))101                        .accessibilityIdentifier("logs-text")102                }103                DataStamp(receivedAt: model.receivedAt)104            }105        }106    }107108    private func search(count: Int, current: Int) -> some View {109        AdaptiveLine(spacing: Tokens.Space.s3) {110            TextField(tr("services.logs.search"), text: $query)111                .textFieldStyle(.roundedBorder)112                .textInputAutocapitalization(.never).autocorrectionDisabled()113                .frame(minHeight: Tokens.Size.touchMin)114                .accessibilityIdentifier("logs-search")115                .onChange(of: query) { matchIndex = 0 }116            if !query.trimmingCharacters(in: .whitespaces).isEmpty {117                HStack(spacing: Tokens.Space.s2) {118                    Text(count == 0 ? tr("services.logs.no_match") : tr("services.logs.match", current + 1, count))119                        .font(.footnote.monospacedDigit()).foregroundStyle(theme.textSecondary)120                        .accessibilityIdentifier("logs-match-count")121                    Button { if let i = LogSearch.step(from: current, count: count, forward: false) { matchIndex = i } } label: {122                        Label(tr("services.logs.previous"), systemImage: "chevron.up").labelStyle(.iconOnly).touchTarget()123                    }124                    .disabled(count == 0)125                    Button { if let i = LogSearch.step(from: current, count: count, forward: true) { matchIndex = i } } label: {126                        Label(tr("services.logs.next"), systemImage: "chevron.down").labelStyle(.iconOnly).touchTarget()127                    }128                    .disabled(count == 0)129                }130            }131        }132    }133134    /// Matches are underlined and tinted (not colour alone); the current one is also bold.135    private func highlighted(_ text: String, ranges: [NSRange], current: Int) -> AttributedString {136        var out = AttributedString(text)137        for (i, r) in ranges.enumerated() {138            guard let sr = Range(r, in: text), let lo = AttributedString.Index(sr.lowerBound, within: out),139                  let hi = AttributedString.Index(sr.upperBound, within: out) else { continue }140            out[lo..<hi].backgroundColor = i == current ? theme.accent : theme.accentMuted141            out[lo..<hi].foregroundColor = i == current ? theme.accentContrast : theme.textPrimary142            out[lo..<hi].underlineStyle = .single143            if i == current { out[lo..<hi].inlinePresentationIntent = .stronglyEmphasized }144        }145        return out146    }147}148
Files main
Menu

Theme