SPB Git

Repository Public MIT

FeedbackDescriptors.swift 30.7 KB 597 lines swift

1// =============================================================================2//                  SP BOUCHER | SOFTWARE & RESEARCH3//             ARTIFICIAL INTELLIGENCE • FINANCE • ENGINEERING4// =============================================================================5//6// Project          : SP GlassKit7// File             : Apps/GlassStudio/Kit/Descriptors/FeedbackDescriptors.swift8// Module           : GlassStudio9// Repository       : https://git.spboucher.ai/sp-glasskit10// Project Website  : https://glass.spboucher.ai11// Created          : 2026-12-0212// Last Modified    : 2026-12-0213//14// Author           : Simon-Pierre Boucher15// Position         : Professor of Finance16// Institution      : Université du Québec en Outaouais (UQO)17// Organization     : SP Boucher18// Website          : https://spboucher.ai19// Git              : https://git.spboucher.ai20//21// Preferred Contact: contact@spboucher.ai22// Development      : dev@spboucher.ai23// Support          : support@spboucher.ai24// Security/Admin   : admin@spboucher.ai25//26// Copyright (c) 202627// Simon-Pierre Boucher28// All rights reserved where applicable. This file is governed by the29// applicable project license, copyright notices and relevant law.30// Existing third-party rights and notices remain unaffected.31//32// License          : MIT33//34// Do not embed credentials, private keys, access tokens,35// certificates or confidential personal information.36//37// =============================================================================38// END OF SP BOUCHER SOURCE HEADER39// =============================================================================4041import SwiftUI42import SPGlassKit4344extension ComponentCatalog {45    static var feedbackDescriptors: [ComponentDescriptor] {46        [glassToast, glassAlert, glassBanner, glassBadge, glassProgress]47    }4849    private static func call(_ name: String, _ arguments: [String]) -> String {50        "\(name)(\(arguments.joined(separator: ", ")))"51    }5253    private static func optional(_ text: String) -> String? { text.isEmpty ? nil : text }5455    // MARK: GlassToast5657    private static var glassToast: ComponentDescriptor {58        ComponentDescriptor(59            "glass-toast",60            fields: [61                .text("message", "Message", default: "Saved to Drafts", maxLength: 100),62                .text("title", "Title", default: "", maxLength: 40),63                .text("symbol", "Symbol", default: "checkmark.circle", maxLength: 40),64                .choice("placement", "Placement", options: [.init("bottom", "Bottom"), .init("top", "Top")]),65                .toggle("action", "Action button", default: true),66                .toggle("persistent", "Persistent"),67            ],68            variants: [69                ComponentVariant("action", "Without action", ["message": .text("Link copied"), "symbol": .text("link"), "action": .bool(false)]),70                ComponentVariant("persistent", "Persistent", ["message": .text("You are offline"), "title": .text("Connection"), "symbol": .text("wifi.slash"), "persistent": .bool(true)]),71                ComponentVariant("top", "Top", ["placement": .choice("top")]),72            ],73            prefersStage: false,74            preview: { values in75                let action = values.bool("action") ? GlassToastAction(L("Undo")) {} : nil76                let title = optional(values.text("title")), symbol = optional(values.text("symbol"))77                // A stable identifier: showing the toast again replaces it instead of stacking a duplicate.78                ToastPreview(79                    toast: values.bool("persistent")80                        ? .persistent(values.text("message"), title: title, systemImage: symbol, id: "studio-preview", action: action)81                        : GlassToast(values.text("message"), title: title, systemImage: symbol, id: "studio-preview", action: action),82                    placement: values.choice("placement") == "top" ? .top : .bottom83                )84                .id(values)85            },86            snippet: { values in87                var arguments = [SwiftLiteral.string(values.text("message"))]88                if !values.text("title").isEmpty { arguments.append("title: \(SwiftLiteral.string(values.text("title")))") }89                if !values.text("symbol").isEmpty { arguments.append("systemImage: \(SwiftLiteral.string(values.text("symbol")))") }90                if values.bool("action") { arguments.append("action: GlassToastAction(\"Undo\") { }") }91                let toast = call(values.bool("persistent") ? "GlassToast.persistent" : "GlassToast", arguments)92                let host = values.choice("placement") == "top" ? ".glassToastHost(toasts, placement: .top)" : ".glassToastHost(toasts)"93                return "// In a real view, keep the centre in @State and apply the host once near the root of the scene.\nlet toasts = GlassToastCenter()\nGlassButton(\"Show toast\", systemImage: \"bell\") {\n    toasts.show(\(toast))\n}\n.frame(maxWidth: .infinity, minHeight: 240)\n\(host)"94            }95        )96    }9798    // MARK: GlassAlert99100    private static var glassAlert: ComponentDescriptor {101        ComponentDescriptor(102            "glass-alert",103            fields: [104                .text("title", "Title", default: "Delete this draft?", maxLength: 60),105                .text("message", "Message", default: "“Budget 2027” will be removed from every device. This cannot be undone.", maxLength: 160),106                .choice("style", "Style", options: [.init("alert", "Alert"), .init("confirmation", "Confirmation dialog")]),107                .choice("buttons", "Buttons", options: [.init("ok", "OK only"), .init("save", "Save, discard, cancel"), .init("delete", "Destructive only")], default: "delete"),108            ],109            variants: [110                ComponentVariant("unsaved", "Unsaved changes", ["title": .text("Save changes?"), "message": .text("Your edits to “Budget 2027” will be lost otherwise."), "buttons": .choice("save")]),111                ComponentVariant("ok", "OK only", ["title": .text("Export finished"), "message": .text("The file was written to Documents."), "buttons": .choice("ok")]),112                ComponentVariant("confirmation", "Destructive confirmation", ["title": .text("Delete this draft?"), "message": .text("This cannot be undone."), "style": .choice("confirmation"), "buttons": .choice("delete")]),113            ],114            prefersStage: false,115            preview: { values in116                AlertPreview(117                    title: values.text("title"),118                    message: optional(values.text("message")),119                    style: values.choice("style") == "confirmation" ? .confirmation : .alert,120                    buttons: values.choice("buttons")121                )122            },123            snippet: { values in124                var arguments = ["title: \(SwiftLiteral.string(values.text("title")))"]125                if !values.text("message").isEmpty { arguments.append("message: \(SwiftLiteral.string(values.text("message")))") }126                if values.choice("style") == "confirmation" { arguments.append("style: .confirmation") }127                switch values.choice("buttons") {128                case "save": arguments.append("buttons: [GlassAlertButton(\"Save\") { }, .destructive(\"Discard\") { }, .cancel()]")129                case "delete": arguments.append("buttons: [.destructive(\"Delete\") { }]")130                default: break131                }132                return "// Bind the alert to your own @State GlassAlert? and set it from the button.\nGlassButton(\"Show alert\", systemImage: \"exclamationmark.bubble\") { }\n    .glassAlert(.constant(GlassAlert(\n        \(arguments.joined(separator: ",\n        "))\n    )))"133            }134        )135    }136137    // MARK: GlassBanner138139    private static var glassBanner: ComponentDescriptor {140        ComponentDescriptor(141            "glass-banner",142            fields: [143                .choice("severity", "Severity", options: [.init("information", "Information"), .init("success", "Success"), .init("warning", "Warning"), .init("error", "Error")]),144                .text("title", "Title", default: "Maintenance on Sunday", maxLength: 80),145                .text("message", "Message", default: "The service will be read-only from 2:00 to 4:00.", maxLength: 200),146                .toggle("action", "Action button"),147                .toggle("dismissible", "Dismiss button"),148            ],149            variants: [150                ComponentVariant("success", "Success", ["severity": .choice("success"), "title": .text("Payment received"), "message": .text("")]),151                ComponentVariant("warning", "Warning", ["severity": .choice("warning"), "title": .text("Your card expires soon"), "message": .text("Update your payment method before the end of the month."), "dismissible": .bool(true)]),152                ComponentVariant("error", "Error", ["severity": .choice("error"), "title": .text("Synchronisation failed"), "message": .text("The server did not answer."), "action": .bool(true)]),153            ],154            isComposable: true,155            prefersStage: false,156            preview: { values in157                BannerPreview(158                    severity: GlassBannerSeverity(rawValue: values.choice("severity")) ?? .information,159                    title: values.text("title"),160                    message: optional(values.text("message")),161                    hasAction: values.bool("action"),162                    isDismissible: values.bool("dismissible")163                )164                .id(values)165            },166            snippet: { values in167                var arguments = [SwiftLiteral.enumCase(values.choice("severity"), fallback: "information"), "title: \(SwiftLiteral.string(values.text("title")))"]168                if !values.text("message").isEmpty { arguments.append("message: \(SwiftLiteral.string(values.text("message")))") }169                if values.bool("action") { arguments.append("action: GlassBannerAction(\"Retry\") { }") }170                if values.bool("dismissible") { arguments.append("onDismiss: { }") }171                return call("GlassBanner", arguments)172            }173        )174    }175176    // MARK: GlassBadge177178    private static var glassBadge: ComponentDescriptor {179        let tones = [InspectorField.Option("neutral", "Neutral"), .init("accent", "Accent"), .init("success", "Success"), .init("warning", "Warning"), .init("critical", "Critical")]180        return ComponentDescriptor(181            "glass-badge",182            fields: [183                .choice("kind", "Content", options: [.init("text", "Text"), .init("count", "Count"), .init("status", "Status")]),184                .text("label", "Label", default: "New", maxLength: 24),185                .number("count", "Count", in: 0...150, default: 7),186                .choice("tone", "Tone", options: tones, default: "accent"),187            ],188            variants: [189                ComponentVariant("count", "Count", ["kind": .choice("count"), "tone": .choice("critical")]),190                ComponentVariant("capped", "Capped count", ["kind": .choice("count"), "count": .number(150), "tone": .choice("critical")]),191                ComponentVariant("status", "Status", ["kind": .choice("status"), "label": .text("Online"), "tone": .choice("success")]),192            ],193            isComposable: true,194            prefersStage: false,195            preview: { values in196                let tone = GlassBadgeTone(rawValue: values.choice("tone")) ?? .neutral197                BadgePreview(kind: values.choice("kind"), label: values.text("label"), count: Int(values.number("count")), tone: tone)198            },199            snippet: { values in200                let tone = "tone: \(SwiftLiteral.enumCase(values.choice("tone"), fallback: "neutral"))"201                switch values.choice("kind") {202                case "count":203                    return call("GlassBadge", ["count: \(SwiftLiteral.number(values.number("count")))"] + (values.choice("tone") == "critical" ? [] : [tone]))204                case "status":205                    return call("GlassBadge", ["status: \(SwiftLiteral.string(values.text("label")))", tone])206                default:207                    return call("GlassBadge", [SwiftLiteral.string(values.text("label"))] + (values.choice("tone") == "neutral" ? [] : [tone]))208                }209            }210        )211    }212213    // MARK: GlassProgress214215    private static var glassProgress: ComponentDescriptor {216        ComponentDescriptor(217            "glass-progress",218            fields: [219                .text("label", "Label", default: "Uploading sample.pdf", maxLength: 60),220                .choice("style", "Style", options: [.init("linear", "Linear"), .init("circular", "Circular"), .init("ring", "Ring"), .init("steps", "Steps")]),221                .toggle("indeterminate", "Indeterminate"),222                .number("percent", "Percent complete", in: 0...100, step: 5, default: 30),223                .toggle("showsPercent", "Show percentage", default: true),224                .toggle("cancellable", "Cancel button"),225            ],226            variants: [227                ComponentVariant("circular", "Circular", ["style": .choice("circular"), "label": .text("Storage used"), "percent": .number(80)]),228                ComponentVariant("ring", "Ring", ["style": .choice("ring"), "label": .text("Storage used"), "percent": .number(80)]),229                ComponentVariant("indeterminate", "Indeterminate", ["indeterminate": .bool(true), "label": .text("Connecting")]),230                ComponentVariant("cancellable", "With cancel", ["cancellable": .bool(true)]),231            ],232            isComposable: true,233            prefersStage: false,234            preview: { values in235                let label: LocalizedStringKey? = values.text("label").isEmpty ? nil : LocalizedStringKey(values.text("label"))236                let style = GlassProgressStyle(rawValue: values.choice("style")) ?? .linear237                ProgressPreview(238                    label: label,239                    percent: values.bool("indeterminate") ? nil : values.number("percent"),240                    style: style,241                    showsPercent: values.bool("showsPercent"),242                    isCancellable: values.bool("cancellable")243                )244                .id(values)245            },246            snippet: { values in247                var arguments: [String] = []248                if !values.text("label").isEmpty { arguments.append(SwiftLiteral.string(values.text("label"))) }249                if values.choice("style") == "steps" {250                    arguments += ["step: \(SwiftLiteral.number((values.number("percent") / 25).rounded()))", "of: 4"]251                    if !values.bool("showsPercent") { arguments.append("showsCount: false") }252                    if values.bool("cancellable") { arguments.append("onCancel: { }") }253                    return call("GlassProgress", arguments)254                }255                if !values.bool("indeterminate") { arguments += ["value: \(SwiftLiteral.number(values.number("percent")))", "total: 100"] }256                if ["circular", "ring"].contains(values.choice("style")) { arguments.append("style: \(SwiftLiteral.enumCase(values.choice("style"), fallback: "linear"))") }257                if !values.bool("indeterminate"), !values.bool("showsPercent") { arguments.append("showsPercent: false") }258                if values.bool("cancellable") { arguments.append("onCancel: { }") }259                return call("GlassProgress", arguments)260            }261        )262    }263}264265// MARK: - Preview support266267/// The configured progress above the rest of the family: rings, steps and an indeterminate state. The268/// cancel button really cancels, with a way to start again.269private struct ProgressPreview: View {270    let label: LocalizedStringKey?271    /// `nil` for an indeterminate progress.272    let percent: Double?273    let style: GlassProgressStyle274    let showsPercent: Bool275    let isCancellable: Bool276    @State private var isCancelled = false277278    private var onCancel: (@MainActor () -> Void)? {279        guard isCancellable else { return nil }280        return { isCancelled = true }281    }282283    var body: some View {284        GlassCard {285            VStack(alignment: .leading, spacing: 16) {286                Group {287                    if isCancelled {288                        HStack {289                            Text(verbatim: L("Cancelled")).foregroundStyle(.secondary)290                            Spacer()291                            GlassButton(verbatim: L("Restart"), size: .small) { isCancelled = false }292                        }293                    } else if style == .steps {294                        GlassProgress(label, step: Int(((percent ?? 0) / 25).rounded()), of: 4, showsCount: showsPercent, onCancel: onCancel)295                    } else if let percent {296                        GlassProgress(label, value: percent, total: 100, style: style, showsPercent: showsPercent, onCancel: onCancel)297                    } else {298                        GlassProgress(label, style: style, onCancel: onCancel)299                    }300                }301                .frame(maxWidth: .infinity, minHeight: 44, alignment: style == .ring ? .center : .leading)302                PreviewHairline()303                Text(verbatim: L("Rings")).previewEyebrow()304                HStack(alignment: .top, spacing: 0) {305                    GlassProgress(LocalizedStringKey(L("Storage")), value: 0.8, style: .ring).frame(maxWidth: .infinity)306                    GlassProgress(LocalizedStringKey(L("Battery")), value: 0.46, style: .ring).frame(maxWidth: .infinity)307                    GlassProgress(LocalizedStringKey(L("Daily goal")), value: 0.62, style: .ring).frame(maxWidth: .infinity)308                }309                PreviewHairline()310                Text(verbatim: L("Steps and waiting")).previewEyebrow()311                GlassProgress(LocalizedStringKey(L("Shipping address")), step: 2, of: 4)312                GlassProgress(LocalizedStringKey(L("Connecting to the printer")), style: .circular)313            }314            .frame(maxWidth: .infinity, alignment: .leading)315        }316        .frame(maxWidth: 460)317    }318}319320/// The configured badge in a row, above the family: tones, quiet styles, counts on icons and statuses.321private struct BadgePreview: View {322    let kind: String323    let label: String324    let count: Int325    let tone: GlassBadgeTone326    @GlassThemed private var theme327328    @ViewBuilder private var configured: some View {329        switch kind {330        case "count": GlassBadge(count: count, tone: tone)331        case "status": GlassBadge(status: label, tone: tone)332        default: GlassBadge(label, tone: tone)333        }334    }335336    private static let tones: [(String, GlassBadgeTone)] = [("New", .accent), ("Beta", .neutral), ("Paid", .success), ("Due soon", .warning), ("Failed", .critical)]337    private static let statuses: [(String, GlassBadgeTone)] = [("Online", .success), ("Away", .warning), ("Offline", .neutral), ("Blocked", .critical)]338339    var body: some View {340        GlassCard {341            VStack(alignment: .leading, spacing: 14) {342                HStack(spacing: 12) {343                    GlassIconTile(systemImage: "tray.full.fill", tone: .accent, size: 36)344                    VStack(alignment: .leading, spacing: 1) {345                        Text(verbatim: L("Inbox")).font(theme.font(.headline)).foregroundStyle(theme.color(.textPrimary))346                        Text(verbatim: L("Updated a minute ago")).font(theme.font(.caption)).foregroundStyle(theme.color(.textSecondary))347                    }348                    Spacer(minLength: 8)349                    configured350                }351                PreviewHairline()352                Text(verbatim: L("Tones")).previewEyebrow()353                row { ForEach(Self.tones, id: \.0) { GlassBadge(L($0.0), tone: $0.1) } }354                row { ForEach(Self.tones, id: \.0) { GlassBadge(L($0.0), tone: $0.1, style: .soft) } }355                PreviewHairline()356                Text(verbatim: L("Counts")).previewEyebrow()357                HStack(spacing: 22) {358                    icon("bell.fill").glassBadge(count: 7)359                    icon("envelope.fill").glassBadge(count: 128)360                    icon("cart.fill").glassBadge(count: 2, tone: .accent)361                    icon("bubble.left.fill").glassBadge(count: 0)362                }363                .padding(.top, 4)364                PreviewHairline()365                Text(verbatim: L("Status")).previewEyebrow()366                row { ForEach(Self.statuses, id: \.0) { GlassBadge(status: L($0.0), tone: $0.1) } }367                row { ForEach(Self.statuses.prefix(3), id: \.0) { GlassBadge(status: L($0.0), tone: $0.1, style: .soft) } }368            }369            .frame(maxWidth: .infinity, alignment: .leading)370        }371        .frame(maxWidth: 460)372    }373374    /// A row that keeps its badges on one line and scales them down slightly on a very narrow canvas.375    private func row(@ViewBuilder _ content: () -> some View) -> some View {376        ViewThatFits(in: .horizontal) {377            HStack(spacing: 8) { content() }378            HStack(spacing: 4) { content() }.scaleEffect(0.86, anchor: .leading)379        }380    }381382    private func icon(_ name: String) -> some View {383        Image(systemName: name)384            .font(.system(size: 19, weight: .medium))385            .foregroundStyle(theme.color(.textPrimary))386            .frame(width: 44, height: 44)387            .background(theme.color(.textPrimary).opacity(0.07), in: RoundedRectangle(cornerRadius: 12, style: .continuous))388            .accessibilityHidden(true)389    }390}391392/// A mock drafts screen with the toast already on screen. "Save draft" posts the configured toast to the393/// real centre; the host draws it over the scene.394private struct ToastPreview: View {395    let toast: GlassToast396    let placement: GlassToastPlacement397    @State private var center = GlassToastCenter()398    @GlassThemed private var theme399400    private static let drafts: [(String, String, String)] = [401        ("Budget 2027", "Edited today, 09:41", "doc.text.fill"),402        ("Welcome letter", "Edited yesterday", "envelope.fill"),403        ("Site visit notes", "Edited on Monday", "pencil.and.list.clipboard"),404        ("Lease renewal", "Edited last week", "signature"),405    ]406407    var body: some View {408        VStack(alignment: .leading, spacing: 0) {409            HStack {410                Text(verbatim: L("Drafts")).font(theme.font(.title)).foregroundStyle(theme.color(.textPrimary))411                Spacer()412                GlassButton(verbatim: L("Save draft"), systemImage: "square.and.arrow.down", size: .small) { center.show(toast) }413            }414            .padding(.horizontal, 18)415            .padding(.top, placement == .top ? 84 : 18)416            .padding(.bottom, 10)417            ForEach(Self.drafts, id: \.0) { draft in418                HStack(spacing: 12) {419                    GlassIconTile(systemImage: draft.2, tone: .neutral, size: 34)420                    VStack(alignment: .leading, spacing: 1) {421                        Text(verbatim: L(draft.0)).font(theme.font(.body).weight(.medium)).foregroundStyle(theme.color(.textPrimary))422                        Text(verbatim: L(draft.1)).font(theme.font(.caption)).foregroundStyle(theme.color(.textSecondary))423                    }424                    Spacer()425                }426                .padding(.horizontal, 18)427                .padding(.vertical, 9)428                PreviewHairline().padding(.leading, 64)429            }430            Spacer(minLength: 0)431        }432        .frame(maxWidth: .infinity, maxHeight: .infinity, alignment: .top)433        .background(alignment: .bottom) {434            // Something for the glass to sit on: the foot of the screen carries a picture.435            ListingArtwork(subject: .hills).frame(height: 150).opacity(placement == .bottom ? 1 : 0)436        }437        .background(alignment: .top) {438            ListingArtwork(subject: .coast).frame(height: 76).opacity(placement == .top ? 1 : 0)439        }440        .glassToastHost(center, placement: placement)441        .previewScene(height: 440)442        // The toast is on screen from the start and stays; the button posts the timed one.443        .onAppear { center.show(.persistent(toast.message, title: toast.title, systemImage: toast.systemImage, id: toast.id, action: toast.action)) }444        .onDisappear { center.dismissAll() }445    }446}447448/// A faithful inline drawing of the dialog over a dimmed mock document, and a button that presents the real,449/// system-drawn alert or confirmation dialog.450private struct AlertPreview: View {451    let title: String452    let message: String?453    let style: GlassAlertStyle454    let buttons: String455    @State private var alert: GlassAlert?456    @GlassThemed private var theme457458    private var alertButtons: [GlassAlertButton] {459        switch buttons {460        case "save": [GlassAlertButton(L("Save")), .destructive(L("Discard")) {}, .cancel()]461        case "delete": [.destructive(L("Delete")) {}]462        default: []463        }464    }465466    private var description: GlassAlert {467        GlassAlert(title: title, message: message, style: style, buttons: alertButtons)468    }469470    var body: some View {471        VStack(spacing: 14) {472            ZStack(alignment: style == .confirmation ? .bottom : .center) {473                document474                Color.black.opacity(theme.isDark ? 0.45 : 0.22)475                dialog.padding(style == .confirmation ? 14 : 28)476            }477            .previewScene(height: 400)478            GlassButton(verbatim: style == .confirmation ? L("Present the real dialog") : L("Present the real alert"), systemImage: "exclamationmark.bubble", size: .small) {479                alert = description480            }481            .glassAlert($alert)482        }483    }484485    /// The mock document behind the dialog: a title bar, then a picture that fills the page.486    private var document: some View {487        VStack(alignment: .leading, spacing: 12) {488            HStack(alignment: .center, spacing: 12) {489                GlassIconTile(systemImage: "doc.text.fill", tone: .accent, size: 36)490                VStack(alignment: .leading, spacing: 1) {491                    Text(verbatim: L("Budget 2027")).font(theme.font(.headline)).foregroundStyle(theme.color(.textPrimary))492                    Text(verbatim: L("Draft · edited today, 09:41")).font(theme.font(.caption)).foregroundStyle(theme.color(.textSecondary))493                }494                Spacer(minLength: 0)495            }496            ListingArtwork(subject: .courtyard)497                .frame(maxHeight: .infinity)498                .clipShape(RoundedRectangle(cornerRadius: 14, style: .continuous))499        }500        .padding(16)501        .frame(maxWidth: .infinity, maxHeight: .infinity, alignment: .topLeading)502        .accessibilityHidden(true)503    }504505    /// The dialog as the system lays it out: title, message, then the validated buttons in their safe order.506    private var dialog: some View {507        let validated = description.validatedButtons508        let defaultIndex = GlassAlertValidator.defaultButtonIndex(in: validated)509        let stacked = validated.count > 2 || style == .confirmation510        return VStack(alignment: .leading, spacing: 14) {511            VStack(alignment: .leading, spacing: 6) {512                Text(verbatim: title).font(theme.font(.headline)).foregroundStyle(theme.color(.textPrimary))513                if let message, !message.isEmpty {514                    Text(verbatim: message).font(theme.font(.callout)).foregroundStyle(theme.color(.textSecondary))515                }516            }517            .frame(maxWidth: .infinity, alignment: .leading)518            .padding(.horizontal, 6)519            .padding(.top, 4)520            let row = ForEach(Array(validated.enumerated()), id: \.offset) { index, button in521                mockButton(button, isDefault: index == defaultIndex && button.role == .default)522            }523            if stacked {524                VStack(spacing: 8) { row }525            } else {526                // The system puts the cancel button first in a pair.527                HStack(spacing: 8) {528                    ForEach(Array(validated.enumerated().reversed()), id: \.offset) { index, button in529                        mockButton(button, isDefault: index == defaultIndex && button.role == .default)530                    }531                }532            }533        }534        .padding(16)535        .frame(maxWidth: style == .confirmation ? .infinity : 300)536        .glassSurface(.regular.tinted(.none), in: RoundedRectangle(cornerRadius: 30, style: .continuous))537        .accessibilityElement(children: .combine)538        .accessibilityLabel(Text(verbatim: L("Inline drawing of the dialog")))539    }540541    private func mockButton(_ button: GlassAlertButton, isDefault: Bool) -> some View {542        let isDestructive = button.role == .destructive543        return Text(verbatim: button.title)544            .font(theme.font(.body).weight(isDefault || button.role == .cancel ? .semibold : .medium))545            .foregroundStyle(isDefault ? theme.onColor(.primary) : (isDestructive ? theme.color(.destructive) : theme.color(.textPrimary)))546            .lineLimit(1)547            .frame(maxWidth: .infinity, minHeight: 46)548            .background(isDefault ? theme.color(.primary) : theme.color(.textPrimary).opacity(0.1), in: Capsule())549    }550}551552/// The configured banner above the three other severities. Its dismiss button really dismisses it, with a553/// way to bring it back.554private struct BannerPreview: View {555    let severity: GlassBannerSeverity556    let title: String557    let message: String?558    let hasAction: Bool559    let isDismissible: Bool560    @State private var isShown = true561    @State private var retryCount = 0562563    private static let others: [(GlassBannerSeverity, String, String)] = [564        (.information, "A new version is available", "Restart the app to install version 4.2."),565        (.success, "Payment received", "Receipt R-2291 was sent to your inbox."),566        (.warning, "Your card expires soon", "Update your payment method before the end of the month."),567        (.error, "Synchronisation failed", "The server did not answer. Your changes are kept on this device."),568    ]569570    private var action: GlassBannerAction? {571        guard hasAction else { return nil }572        return GlassBannerAction(verbatim: L("Retry")) { retryCount += 1 }573    }574575    private var onDismiss: (@MainActor () -> Void)? {576        guard isDismissible else { return nil }577        return { isShown = false }578    }579580    var body: some View {581        VStack(alignment: .leading, spacing: 12) {582            if isShown {583                GlassBanner(severity, verbatim: title, message: message, action: action, onDismiss: onDismiss)584                if retryCount > 0 {585                    Text(verbatim: StudioL10n.string("Action performed %d times", retryCount)).font(.caption).foregroundStyle(.secondary)586                }587            } else {588                GlassButton(verbatim: L("Show banner"), size: .small) { isShown = true }589            }590            ForEach(Self.others.filter { $0.0 != severity }, id: \.1) { other in591                GlassBanner(other.0, verbatim: L(other.1), message: L(other.2))592            }593        }594        .frame(maxWidth: 460)595    }596}597
Files main
Menu

Theme