SPB Git

Repository Public License

Components+FamilyAFeedback.swift 13.8 KB 294 lines swift

1import PrismCore2import PrismLogicRuntime3import PrismObjectModel4import SwiftUI56/// Routes the feedback and time components of family A.7struct FamilyAFeedback: View {8    static let types: Set<String> = [9        "prism.callout", "prism.emptyState", "prism.skeleton", "prism.banner", "prism.spinner", "prism.confirm", "prism.loadingOverlay",10        "prism.clock", "prism.countdown",11    ]12    let o: PrismObject1314    var body: some View {15        switch o.type {16        case "prism.callout": CalloutComponent(o: o)17        case "prism.emptyState": EmptyStateComponent(o: o)18        case "prism.skeleton": SkeletonComponent(o: o)19        case "prism.banner": BannerComponent(o: o)20        case "prism.spinner": SpinnerComponent(o: o)21        case "prism.confirm": ConfirmComponent(o: o)22        case "prism.loadingOverlay": LoadingOverlayComponent(o: o)23        case "prism.clock": ClockComponent(o: o)24        default: CountdownComponent(o: o)25        }26    }27}2829/// A tinted note: symbol, title and text.30struct CalloutComponent: View {31    @Environment(AppRuntime.self) private var runtime32    @Environment(\.prismTheme) private var theme33    let o: PrismObject3435    var body: some View {36        let tone = FA.tone(runtime, o, default: "info")37        let tint = theme.tint(tone)38        let text = runtime.string(o.props["text"])39        let fallback = tone == "danger" ? "exclamationmark.octagon.fill" : tone == "warning" ? "exclamationmark.triangle.fill" : tone == "success" ? "checkmark.circle.fill" : "lightbulb.fill"40        HStack(alignment: .top, spacing: 12) {41            Image(systemName: SymbolName.safe(runtime.string(o.props["symbol"]), fallback: fallback)).font(.title3).foregroundStyle(tint).frame(width: 26).accessibilityHidden(true)42            VStack(alignment: .leading, spacing: 3) {43                Text(runtime.string(o.props["title"])).font(.headline).fixedSize(horizontal: false, vertical: true)44                if !text.isEmpty { Text(text).font(.callout).foregroundStyle(.secondary).fixedSize(horizontal: false, vertical: true) }45            }46            Spacer(minLength: 0)47        }48        .padding(14)49        .background(tint.opacity(0.1), in: RoundedRectangle(cornerRadius: theme.radius, style: .continuous))50        .accessibilityElement(children: .combine)51    }52}5354/// What to show when there is nothing to show, with an optional action.55struct EmptyStateComponent: View {56    @Environment(AppRuntime.self) private var runtime57    let o: PrismObject5859    var body: some View {60        let message = runtime.string(o.props["message"])61        let action = runtime.string(o.props["actionTitle"])62        let connected = FA.connected(o, "click")63        VStack(spacing: 8) {64            Image(systemName: SymbolName.safe(runtime.string(o.props["symbol"]), fallback: "tray")).font(.system(size: 40)).foregroundStyle(.secondary).padding(.bottom, 4).accessibilityHidden(true)65            Text(runtime.string(o.props["title"])).font(.title3.weight(.semibold)).multilineTextAlignment(.center)66            if !message.isEmpty { Text(message).font(.callout).foregroundStyle(.secondary).multilineTextAlignment(.center).fixedSize(horizontal: false, vertical: true) }67            if !action.isEmpty {68                Button(action) { runtime.fire("click", on: o.id) }69                    .buttonStyle(.borderedProminent).padding(.top, 6)70                    .disabled(!connected).help(connected ? "" : "No action is connected to this button yet.")71            }72        }73        .padding(24)74        .frame(maxWidth: .infinity)75    }76}7778/// Grey bars standing in for content that is loading.79struct SkeletonComponent: View {80    @Environment(\.accessibilityReduceMotion) private var reduceMotion81    let o: PrismObject82    @State private var dimmed = false8384    var body: some View {85        let lines = min(max(o.props["lines"]?.intValue ?? 3, 1), 12)86        let animated = o.props["animated"]?.boolValue != false && !reduceMotion87        HStack(alignment: .top, spacing: 12) {88            if o.props["avatar"]?.boolValue == true { Circle().fill(.quaternary).frame(width: 40, height: 40) }89            VStack(alignment: .leading, spacing: 10) {90                ForEach(0..<lines, id: \.self) { i in91                    RoundedRectangle(cornerRadius: 4).fill(.quaternary).frame(height: 12).frame(maxWidth: .infinity)92                        .padding(.trailing, i == lines - 1 && lines > 1 ? 140 : i % 2 == 1 ? 36 : 0)93                }94            }95        }96        .frame(maxWidth: 520, alignment: .leading)97        .opacity(dimmed ? 0.45 : 1)98        .task(id: animated) {99            dimmed = false100            guard animated else { return }101            withAnimation(.easeInOut(duration: 0.9).repeatForever(autoreverses: true)) { dimmed = true }102        }103        .accessibilityElement(children: .ignore)104        .accessibilityLabel("Loading")105    }106}107108/// A full-width message that can be dismissed.109struct BannerComponent: View {110    @Environment(AppRuntime.self) private var runtime111    @Environment(\.prismTheme) private var theme112    @Environment(\.prismDesign) private var design113    let o: PrismObject114    @State private var dismissed = false115116    var body: some View {117        let tone = FA.tone(runtime, o, default: "info")118        let tint = theme.tint(tone)119        let message = runtime.string(o.props["message"])120        let fallback = tone == "danger" ? "exclamationmark.octagon.fill" : tone == "warning" ? "exclamationmark.triangle.fill" : tone == "success" ? "checkmark.circle.fill" : "info.circle.fill"121        let bound = runtime.bindingPath(o.props["presented"]) != nil122        let shown = runtime.bool(o.props["presented"], default: true) && (bound || !dismissed)123        if shown || design != nil {124            HStack(alignment: .firstTextBaseline, spacing: 10) {125                Image(systemName: SymbolName.safe(runtime.string(o.props["symbol"]), fallback: fallback)).foregroundStyle(tint).accessibilityHidden(true)126                VStack(alignment: .leading, spacing: 2) {127                    Text(runtime.string(o.props["title"])).font(.callout.weight(.semibold)).fixedSize(horizontal: false, vertical: true)128                    if !message.isEmpty { Text(message).font(.callout).foregroundStyle(.secondary).fixedSize(horizontal: false, vertical: true) }129                }130                Spacer(minLength: 8)131                if o.props["dismissible"]?.boolValue != false {132                    Button { dismiss() } label: { Image(systemName: "xmark").font(.caption.weight(.semibold)) }133                        .buttonStyle(.borderless).accessibilityLabel("Dismiss")134                }135            }136            .padding(.horizontal, 14).padding(.vertical, 10)137            .frame(maxWidth: .infinity, alignment: .leading)138            .background(tint.opacity(0.14), in: RoundedRectangle(cornerRadius: theme.radius, style: .continuous))139            .opacity(shown ? 1 : 0.35)140        }141    }142143    private func dismiss() {144        if let path = runtime.bindingPath(o.props["presented"]) { runtime.setState(path, .bool(false)) } else { dismissed = true }145        runtime.fire("dismiss", on: o.id)146    }147}148149/// An indeterminate progress indicator with a label.150struct SpinnerComponent: View {151    @Environment(AppRuntime.self) private var runtime152    let o: PrismObject153154    var body: some View {155        let label = runtime.string(o.props["label"])156        let size = o.props["size"]?.stringValue157        HStack(spacing: 8) {158            ProgressView().controlSize(size == "small" ? .small : size == "large" ? .large : .regular)159            if !label.isEmpty { Text(label).font(size == "small" ? .callout : .body).foregroundStyle(.secondary) }160        }161        .accessibilityElement(children: .ignore)162        .accessibilityLabel(label.isEmpty ? "Loading" : label)163        .accessibilityAddTraits(.updatesFrequently)164    }165}166167/// A confirmation dialog shown while a state key is true.168struct ConfirmComponent: View {169    @Environment(AppRuntime.self) private var runtime170    @Environment(\.prismDesign) private var design171    let o: PrismObject172173    var body: some View {174        let title = runtime.string(o.props["title"])175        let message = runtime.string(o.props["message"])176        let presented = Binding(177            get: { runtime.resolve(o.props["presented"]).isTruthy },178            set: { new in if let path = runtime.bindingPath(o.props["presented"]) { runtime.setState(path, .bool(new)) } }179        )180        if design != nil {181            Label("Confirmation: \(title)", systemImage: "questionmark.bubble").font(.caption).foregroundStyle(.secondary)182        } else {183            Color.clear.frame(width: 0, height: 0).accessibilityHidden(true)184                .confirmationDialog(title, isPresented: presented, titleVisibility: .visible) {185                    Button(o.props["confirmTitle"].map { runtime.string($0) } ?? "Confirm", role: o.props["destructive"]?.boolValue == true ? .destructive : nil) {186                        presented.wrappedValue = false187                        runtime.fire("confirm", on: o.id)188                    }189                    Button(o.props["cancelTitle"].map { runtime.string($0) } ?? "Cancel", role: .cancel) {190                        presented.wrappedValue = false191                        runtime.fire("cancelled", on: o.id)192                    }193                } message: {194                    Text(message)195                }196        }197    }198}199200/// Dims its children and shows a spinner while `loading` is true.201struct LoadingOverlayComponent: View {202    @Environment(AppRuntime.self) private var runtime203    @Environment(\.prismTheme) private var theme204    let o: PrismObject205206    var body: some View {207        let loading = runtime.bool(o.props["loading"], default: false)208        let label = runtime.string(o.props["label"])209        VStack(alignment: .leading, spacing: theme.spacing) { ChildrenView(ids: o.children) }210            .frame(maxWidth: .infinity, alignment: .leading)211            .opacity(loading ? 0.35 : 1)212            .disabled(loading)213            .accessibilityHidden(loading)214            .overlay {215                if loading {216                    VStack(spacing: 8) {217                        ProgressView()218                        if !label.isEmpty { Text(label).font(.callout).foregroundStyle(.secondary) }219                    }220                    .padding(16)221                    .background(.regularMaterial, in: RoundedRectangle(cornerRadius: theme.radius, style: .continuous))222                    .accessibilityElement(children: .ignore)223                    .accessibilityLabel(label.isEmpty ? "Loading" : label)224                }225            }226    }227}228229/// The current time or date, refreshed every second.230struct ClockComponent: View {231    @Environment(AppRuntime.self) private var runtime232    @Environment(\.prismTheme) private var theme233    let o: PrismObject234235    var body: some View {236        let format = o.props["format"]?.stringValue ?? "timeWithSeconds"237        let zone = o.props["timeZone"]?.stringValue.flatMap(TimeZone.init(identifier:)) ?? .current238        TimelineView(.periodic(from: .now, by: 1)) { context in239            Text(FamilyATime.clock(context.date, format: format, timeZone: zone, locale: runtime.locale))240                .font(FA.font(o.props["style"]?.stringValue ?? "title")).monospacedDigit()241                .foregroundStyle(theme.color(FA.tone(runtime, o)))242        }243        .accessibilityAddTraits(.updatesFrequently)244    }245}246247/// The time left until a date, ticking every second; fires `complete` when it reaches zero.248struct CountdownComponent: View {249    @Environment(AppRuntime.self) private var runtime250    @Environment(\.prismTheme) private var theme251    @Environment(\.prismDesign) private var design252    let o: PrismObject253254    var body: some View {255        let label = runtime.string(o.props["label"])256        VStack(alignment: .leading, spacing: 6) {257            if !label.isEmpty { Text(label).font(.callout).foregroundStyle(.secondary) }258            if let target = FamilyATime.target(runtime.string(o.props["until"])) {259                TimelineView(.periodic(from: .now, by: 1)) { context in260                    let left = FamilyATime.remaining(from: context.date, to: target)261                    face(left)262                        // Only a countdown that runs out while it is on screen completes; one that opens already over does not.263                        .onChange(of: left.isOver) { was, now in if now, !was, design == nil { runtime.fire("complete", on: o.id) } }264                }265            } else {266                Label("Not a date: use YYYY-MM-DD or an ISO date and time.", systemImage: "calendar.badge.exclamationmark").font(.callout).foregroundStyle(.secondary)267            }268        }269    }270271    @ViewBuilder272    private func face(_ left: FamilyATime.Remaining) -> some View {273        let tint = theme.color(FA.tone(runtime, o))274        if left.isOver {275            Text(o.props["doneText"].map { runtime.string($0) } ?? "Time's up").font(.title2.weight(.semibold)).foregroundStyle(tint)276        } else {277            let units = [(left.days, "days"), (left.hours, "hours"), (left.minutes, "min")] + (o.props["showSeconds"]?.boolValue != false ? [(left.seconds, "sec")] : [])278            HStack(spacing: 8) {279                ForEach(Array(units.enumerated()), id: \.offset) { index, unit in280                    VStack(spacing: 0) {281                        Text(index == 0 ? "\(unit.0)" : String(format: "%02d", unit.0)).font(.title2.weight(.semibold)).monospacedDigit().foregroundStyle(tint)282                        Text(unit.1).font(.caption2).foregroundStyle(.secondary)283                    }284                    .frame(minWidth: 44).padding(.vertical, 6).padding(.horizontal, 4)285                    .background(.quaternary.opacity(0.5), in: RoundedRectangle(cornerRadius: 8))286                }287            }288            .accessibilityElement(children: .ignore)289            .accessibilityLabel("Time remaining")290            .accessibilityValue("\(left.days) days, \(left.hours) hours, \(left.minutes) minutes, \(left.seconds) seconds")291        }292    }293}294
Files main
Menu

Theme