SPB Git

Repository Public License

LunarFeedback.swift 13.8 KB 347 lines swift

1import SwiftUI23/// Semantic status shared by badges, banners and toasts.4public enum LunarStatus: String, Sendable, CaseIterable {5    case neutral, accent, success, warning, danger67    /// The symbol shown next to the text, so that status never relies on colour alone.8    public var symbolName: String {9        switch self {10        case .neutral: "circle.fill"11        case .accent: "sparkle"12        case .success: "checkmark.circle.fill"13        case .warning: "exclamationmark.triangle.fill"14        case .danger: "xmark.octagon.fill"15        }16    }1718    func color(in theme: LunarTheme) -> LunarRGBA {19        switch self {20        case .neutral: theme.textSecondary21        case .accent: theme.accent22        case .success: theme.success23        case .warning: theme.warning24        case .danger: theme.danger25        }26    }27}2829/// A small status pill: counts, states, tags.30public struct LunarBadge: View {31    @Environment(\.lunarTheme) private var theme32    @Environment(\.accessibilityDifferentiateWithoutColor) private var differentiateWithoutColor33    private let text: String34    private let status: LunarStatus35    private let icon: LunarIcon?3637    public init(_ text: String, status: LunarStatus = .neutral, icon: LunarIcon? = nil) {38        self.text = text39        self.status = status40        self.icon = icon41    }4243    public var body: some View {44        let color = status.color(in: theme)45        HStack(spacing: LunarSpacing.unit) {46            if let icon {47                LunarIconView(icon, size: 12)48            } else if differentiateWithoutColor && status != .neutral {49                LunarIconView(.symbol(status.symbolName), size: 12)50            }51            Text(text).lunarFont(.caption).lunarTabularDigits().lineLimit(1)52        }53        .foregroundStyle(color)54        .padding(.horizontal, LunarSpacing.xs)55        .frame(minHeight: 22)56        .background { Capsule(style: .continuous).fill(color.withAlpha(theme.isDark ? 0.16 : 0.11)) }57        .overlay { Capsule(style: .continuous).strokeBorder(color.withAlpha(0.32), lineWidth: 1) }58        .accessibilityElement(children: .combine)59    }60}6162/// Drives the phase of indeterminate indicators. Stops entirely under Reduce Motion and in snapshot renders.63private struct LunarIndeterminatePhase<Content: View>: View {64    @Environment(\.accessibilityReduceMotion) private var reduceMotion65    @Environment(\.lunarRenderMode) private var renderMode66    let period: Double67    @ViewBuilder var content: (_ phase: Double, _ animating: Bool) -> Content6869    var body: some View {70        if reduceMotion || renderMode == .snapshot {71            content(0.3, false)72        } else {73            TimelineView(.animation(minimumInterval: 1.0 / 30.0)) { timeline in74                let t = timeline.date.timeIntervalSinceReferenceDate75                content(t.truncatingRemainder(dividingBy: period) / period, true)76            }77        }78    }79}8081/// A thin linear progress bar. Pass `nil` for indeterminate.82public struct LunarProgressBar: View {83    @Environment(\.lunarTheme) private var theme84    private let value: Double?85    private let label: String86    private let height: CGFloat8788    /// - Parameter value: `0…1`, or `nil` while the amount of work is unknown.89    public init(value: Double?, label: String = "Progress", height: CGFloat = LunarSpacing.unit) {90        self.value = value.map { min(1, max(0, $0)) }91        self.label = label92        self.height = height93    }9495    public var body: some View {96        GeometryReader { proxy in97            let width = proxy.size.width98            ZStack(alignment: .leading) {99                Capsule().fill(theme.textPrimary.withAlpha(theme.isDark ? 0.10 : 0.09))100                if let value {101                    Capsule().fill(fill).frame(width: max(height, width * value))102                        .lunarAnimation(.smooth, value: value)103                } else {104                    LunarIndeterminatePhase(period: 1.6) { phase, animating in105                        let segment = width * 0.34106                        // Static under Reduce Motion: a centred, dimmer segment that still says "working".107                        Capsule().fill(fill)108                            .frame(width: segment)109                            .offset(x: animating ? -segment + (width + segment) * phase : (width - segment) / 2)110                            .opacity(animating ? 1 : 0.7)111                    }112                }113            }114            .clipShape(Capsule())115        }116        .frame(height: height)117        .accessibilityElement()118        .accessibilityLabel(label)119        .accessibilityValue(value.map { "\(Int(($0 * 100).rounded())) percent" } ?? "In progress")120        .accessibilityAddTraits(.updatesFrequently)121    }122123    private var fill: LinearGradient {124        LinearGradient(colors: [theme.accentSecondary.color, theme.accent.color], startPoint: .leading,125                       endPoint: .trailing)126    }127}128129/// A circular progress ring. Pass `nil` for indeterminate.130public struct LunarProgressRing: View {131    @Environment(\.lunarTheme) private var theme132    private let value: Double?133    private let label: String134    private let size: CGFloat135    private let lineWidth: CGFloat136137    public init(value: Double?, label: String = "Progress", size: CGFloat = 28, lineWidth: CGFloat? = nil) {138        self.value = value.map { min(1, max(0, $0)) }139        self.label = label140        self.size = size141        self.lineWidth = lineWidth ?? max(2, size / 10)142    }143144    public var body: some View {145        ZStack {146            Circle().stroke(theme.textPrimary.withAlpha(theme.isDark ? 0.10 : 0.09), lineWidth: lineWidth)147            if let value {148                arc(to: value).rotationEffect(.degrees(-90)).lunarAnimation(.smooth, value: value)149            } else {150                LunarIndeterminatePhase(period: 1.1) { phase, _ in151                    arc(to: 0.28).rotationEffect(.degrees(phase * 360 - 90))152                }153            }154        }155        .padding(lineWidth / 2)156        .frame(width: size, height: size)157        .accessibilityElement()158        .accessibilityLabel(label)159        .accessibilityValue(value.map { "\(Int(($0 * 100).rounded())) percent" } ?? "In progress")160        .accessibilityAddTraits(.updatesFrequently)161    }162163    private func arc(to fraction: Double) -> some View {164        Circle()165            .trim(from: 0, to: max(0.001, fraction))166            .stroke(AngularGradient(colors: [theme.accentSecondary.color, theme.accent.color], center: .center,167                                    startAngle: .degrees(0), endAngle: .degrees(360 * max(0.05, fraction))),168                    style: StrokeStyle(lineWidth: lineWidth, lineCap: .round))169    }170}171172/// A full-area message for a view with nothing to show yet.173public struct LunarEmptyState: View {174    @Environment(\.lunarTheme) private var theme175    private let icon: LunarIcon176    private let title: String177    private let message: String178    private let actionTitle: String?179    private let action: (() -> Void)?180    private let status: LunarStatus181182    public init(icon: LunarIcon, title: String, message: String, actionTitle: String? = nil,183                action: (() -> Void)? = nil) {184        self.init(icon: icon, title: title, message: message, actionTitle: actionTitle, action: action,185                  status: .accent)186    }187188    init(icon: LunarIcon, title: String, message: String, actionTitle: String?, action: (() -> Void)?,189         status: LunarStatus) {190        self.icon = icon191        self.title = title192        self.message = message193        self.actionTitle = actionTitle194        self.action = action195        self.status = status196    }197198    public var body: some View {199        let color = status.color(in: theme)200        VStack(spacing: LunarSpacing.md) {201            ZStack {202                // The glyph sits on a small orbit: two thin rings and a satellite.203                Circle().fill(RadialGradient(colors: [color.withAlpha(theme.isDark ? 0.22 : 0.14).color,204                                                      color.withAlpha(0).color],205                                             center: .center, startRadius: 4, endRadius: 56))206                    .frame(width: 112, height: 112)207                Circle().strokeBorder(color.withAlpha(0.20), lineWidth: 1).frame(width: 96, height: 96)208                Circle().strokeBorder(color.withAlpha(0.42), lineWidth: 1).frame(width: 64, height: 64)209                Circle().fill(color).frame(width: 6, height: 6).offset(x: 34, y: -34)210                LunarIconView(icon, size: 30).foregroundStyle(color)211            }212            .accessibilityHidden(true)213            VStack(spacing: LunarSpacing.unit + 2) {214                Text(title).lunarFont(.title2).foregroundStyle(theme.textPrimary)215                    .accessibilityAddTraits(.isHeader)216                Text(message).lunarFont(.callout).foregroundStyle(theme.textSecondary)217                    .fixedSize(horizontal: false, vertical: true)218            }219            .multilineTextAlignment(.center)220            if let actionTitle, let action {221                Button(actionTitle, action: action)222                    .buttonStyle(.lunar(status == .danger ? .secondary : .primary))223                    .padding(.top, LunarSpacing.unit)224            }225        }226        .frame(maxWidth: 360)227        .padding(LunarSpacing.lg)228    }229}230231/// A full-area message for a failure, with an optional recovery action.232public struct LunarErrorState: View {233    private let title: String234    private let message: String235    private let retryTitle: String?236    private let retry: (() -> Void)?237238    public init(title: String, message: String, retryTitle: String? = nil, retry: (() -> Void)? = nil) {239        self.title = title240        self.message = message241        self.retryTitle = retryTitle242        self.retry = retry243    }244245    public var body: some View {246        LunarEmptyState(icon: .symbol("exclamationmark.triangle"), title: title, message: message,247                        actionTitle: retryTitle, action: retry, status: .danger)248    }249}250251/// An inline message across the top of a view or panel.252public struct LunarBanner: View {253    @Environment(\.lunarTheme) private var theme254    private let status: LunarStatus255    private let title: String256    private let message: String?257    private let actionTitle: String?258    private let action: (() -> Void)?259    private let onDismiss: (() -> Void)?260261    public init(_ status: LunarStatus = .accent, title: String, message: String? = nil, actionTitle: String? = nil,262                action: (() -> Void)? = nil, onDismiss: (() -> Void)? = nil) {263        self.status = status264        self.title = title265        self.message = message266        self.actionTitle = actionTitle267        self.action = action268        self.onDismiss = onDismiss269    }270271    public var body: some View {272        let color = status.color(in: theme)273        HStack(alignment: .center, spacing: LunarSpacing.sm) {274            LunarIconView(.symbol(status.symbolName), size: 18).foregroundStyle(color)275            VStack(alignment: .leading, spacing: 2) {276                Text(title).lunarFont(.bodyEmphasized).foregroundStyle(theme.textPrimary)277                if let message {278                    Text(message).lunarFont(.footnote).foregroundStyle(theme.textSecondary)279                        .fixedSize(horizontal: false, vertical: true)280                }281            }282            Spacer(minLength: LunarSpacing.xs)283            if let actionTitle, let action {284                Button(actionTitle, action: action).buttonStyle(.lunar(.secondary, size: .compact))285            }286            if let onDismiss {287                LunarIconButton(systemName: "xmark", label: "Dismiss", diameter: LunarMetrics.controlHeightCompact,288                                action: onDismiss)289            }290        }291        .padding(.horizontal, LunarSpacing.md)292        .padding(.vertical, LunarSpacing.sm)293        .lunarGlass(.sm, style: .dense, elevation: .raised)294        .overlay(alignment: .leading) {295            Capsule().fill(color).frame(width: 3).padding(.vertical, LunarSpacing.sm).padding(.leading, 6)296        }297        .accessibilityElement(children: .contain)298    }299}300301/// A transient capsule message floating over content.302public struct LunarToast: View {303    @Environment(\.lunarTheme) private var theme304    private let status: LunarStatus305    private let text: String306307    public init(_ text: String, status: LunarStatus = .neutral) {308        self.text = text309        self.status = status310    }311312    public var body: some View {313        HStack(spacing: LunarSpacing.xs) {314            LunarIconView(.symbol(status.symbolName), size: 16).foregroundStyle(status.color(in: theme))315            Text(text).lunarFont(.subheadline).foregroundStyle(theme.textPrimary).lineLimit(2)316        }317        .padding(.horizontal, LunarSpacing.md)318        .frame(minHeight: LunarMetrics.controlHeight + LunarSpacing.unit)319        .lunarGlass(.capsule, style: .dense, elevation: .floating)320        .accessibilityElement(children: .combine)321        .accessibilityAddTraits(.isStaticText)322    }323}324325#Preview("Feedback") {326    VStack(spacing: LunarSpacing.md) {327        HStack {328            LunarBadge("12", status: .accent)329            LunarBadge("Secure", status: .success)330            LunarBadge("Tracker", status: .warning)331            LunarBadge("Blocked", status: .danger)332        }333        LunarProgressBar(value: 0.62)334        LunarProgressBar(value: nil)335        HStack { LunarProgressRing(value: 0.7); LunarProgressRing(value: nil) }336        LunarBanner(.warning, title: "Connection is not private", message: "The certificate expired yesterday.",337                    actionTitle: "Details", action: {}, onDismiss: {})338        LunarToast("Link copied", status: .success)339        LunarEmptyState(icon: .glyph(.memory), title: "No memories yet",340                        message: "Pages you keep will gather here.", actionTitle: "Learn more") {}341    }342    .padding(LunarSpacing.xl)343    .frame(width: 460)344    .background(LunarWindowBackground())345    .lunarTheme(LunarThemes.lunar.dark)346}347
Files main
Menu

Theme