|
| 1 | +// |
| 2 | +// View+Alert.swift |
| 3 | +// PresentationShared |
| 4 | +// |
| 5 | +// Created by opfic on 7/30/26. |
| 6 | +// |
| 7 | + |
| 8 | +import ComposableArchitecture |
| 9 | +import SwiftUI |
| 10 | + |
| 11 | +public extension View { |
| 12 | + @preconcurrency @MainActor |
| 13 | + @ViewBuilder |
| 14 | + func prominentAlert<State, Action, AlertAction>( |
| 15 | + _ store: Store<State, Action>, |
| 16 | + state: KeyPath<State, AlertState<AlertAction>?>, |
| 17 | + action: CaseKeyPath<Action, PresentationAction<AlertAction>> |
| 18 | + ) -> some View where State: ObservableState { |
| 19 | + @Bindable var store = store |
| 20 | + let item = $store.scope(state: state, action: action) |
| 21 | + let alertStore = item.wrappedValue |
| 22 | + let alertState = store.state[keyPath: state] |
| 23 | + |
| 24 | + alert( |
| 25 | + alertState.map(\.title).map(Text.init) ?? Text(verbatim: ""), |
| 26 | + isPresented: Binding(item), |
| 27 | + presenting: alertState, |
| 28 | + actions: { alertState in |
| 29 | + ForEach(alertState.buttons) { button in |
| 30 | + let usesDefaultAction = alertState.usesDefaultAction(for: button) |
| 31 | + |
| 32 | + Button( |
| 33 | + role: alertState.buttonRole(for: button), |
| 34 | + action: { |
| 35 | + button.withAction { action in |
| 36 | + if let action { |
| 37 | + alertStore?.send(action) |
| 38 | + } |
| 39 | + } |
| 40 | + } |
| 41 | + ) { |
| 42 | + Text(button.label) |
| 43 | + } |
| 44 | + .keyboardShortcut( |
| 45 | + usesDefaultAction ? .defaultAction : nil |
| 46 | + ) |
| 47 | + } |
| 48 | + }, |
| 49 | + message: { |
| 50 | + $0.message.map(Text.init) |
| 51 | + } |
| 52 | + ) |
| 53 | + } |
| 54 | +} |
| 55 | + |
| 56 | +extension AlertState { |
| 57 | + func buttonRole(for button: ButtonState<Action>) -> ButtonRole? { |
| 58 | + if #available(iOS 26, *), usesDefaultAction(for: button) { return .confirm } |
| 59 | + if buttons.count == 1 { return nil } |
| 60 | + return button.role.map(ButtonRole.init) |
| 61 | + } |
| 62 | + |
| 63 | + func usesDefaultAction(for button: ButtonState<Action>) -> Bool { |
| 64 | + guard 1 < buttons.count else { return true } |
| 65 | + return buttons.first { $0.role == .destructive }?.id == button.id |
| 66 | + } |
| 67 | +} |
0 commit comments