Customizable SwiftUI auth UI: content slots, per-screen state, and theming
維護者通常 5 天內回覆
評估
- 難度
- 4/5
- 預估耗時
- 3-5 天
- 新手友好度
- 45/100
- Issue 類型
- 功能
- 描述清晰度
- 描述清楚
- 活躍度
- 活躍
- 技術堆疊
- swift
研究方向
The issue describes extending AuthPickerView and related screens with content slots and state structs. Start by examining the existing AuthPickerView, AuthPickerContentView, and the various auth screen views (EmailAuthView, PasswordRecoveryView, etc.) to understand the current state management and navigation. The reference implementation is on the branch 'auth-picker-view-picker-content'. Look at how FirebaseUI-Android's FirebaseAuthScreen models content slots. The goal is to implement per-screen state structs (like EmailAuthContentState) that expose Bindings and actions, keeping the library's flow logic intact. Testing involves ensuring existing call sites compile and render identically.
由索引模型根據 Issue 內容生成。
描述
Proposal to make the SwiftUI auth UI customizable at three levels: theming, layout, and per-screen markup, while AuthService keeps owning navigation, MFA resolution, account conflicts, anonymous upgrade, reauthentication, loading state and error reporting.
Most of this is already built. Rounds 1 to 3 below are implemented on auth-picker-view-picker-content and were opened as #1369, which I closed on 2026-07-29 while it was still marked wip. This issue restates that work as a merge-ready design and adds the piece it does not have: per-screen state structs.
Reference implementation for the slot model is FirebaseUI-Android's FirebaseAuthScreen, which ships seven content slots, each receiving a state object.
Problem
On main, AuthPickerView owns the sheet, the NavigationStack, navigator.routes and the navigationDestination(for: AuthView.self) switch, all private. A consumer has three options today: replace a provider's button via registerProvider(providerWithButton:), call renderButtons() and lay them out themselves, or bypass AuthPickerView entirely. The third means reimplementing navigation, MFA resolution, account conflicts, anonymous upgrade and reauth, which the README already lists as the caller's problem.
There is no middle ground where the library keeps driving the flow and the app supplies the pixels.
Principles
- Purely additive. Every existing call site compiles and renders identically with no source change.
- No
AnyViewerasure in the slot mechanism. Use the generic-with-constrained-default-init pattern, the same technique SwiftUI uses for.overlay()and.background()chains. - Styling defaults are
nil, andnilmeans today's exact appearance. - Brand-mandated provider button styling stays out of consumer reach. The
ProviderStylepresets for Facebook, Apple, Google and Twitter are each provider's required appearance, not a design choice this library made.
Part 1: slots and theming (implemented on the branch)
1.1 Route-level substitution
public struct AuthPickerView<Content: View, PickerContent: View, DestinationContent: View>
public init(@ViewBuilder content: @escaping () -> Content = { EmptyView() })
where PickerContent == AuthPickerContentView<DefaultProviderButtonsLayout>,
DestinationContent == AuthPickerDestinationView
func pickerContent<New: View>(@ViewBuilder _ content: @escaping () -> New)
-> AuthPickerView<Content, New, DestinationContent>
func pickerDestination<New: View>(@ViewBuilder _ content: @escaping (AuthView) -> New)
-> AuthPickerView<Content, PickerContent, New>
Both hooks are needed, not one. A .background() chained outside AuthPickerView never reaches the sheet's content because .sheet starts a separate presentation, and a .background() chained only on the root content never reaches pushed screens, because each gets its own opaque backing surface at the UIKit layer. .tint() crosses both boundaries because it is an environment value. .background() does not.
pickerDestination is more general than a fixed slot list: it hands over the AuthView case, so it covers every current route and any route added later without an API change.
1.2 Method picker layout
public struct AuthPickerContentView<AuthMethodPicker: View>: View
public init() where AuthMethodPicker == DefaultProviderButtonsLayout
public init(
@ViewBuilder authMethodPicker: @escaping (
[AuthProviderUI],
@escaping (AuthProviderUI) -> Void
) -> AuthMethodPicker
)
Supported by AuthService.registeredProviders (public read-only view of the previously private array), AuthService.triggerSignIn(for:) for generic dispatch, and AuthProviderAction, an opt-in protocol extending AuthProviderUI with triggerAction() async throws for providers whose sign-in produces no credential. PhoneAuthProviderAuthUI conforms. Eight of eleven providers need no protocol change at all, because they already route through the public signIn(_:).
handleProviderSelected centralizes the MFA, account-conflict and error handling that is currently duplicated inline in each provider's own button view, so a custom layout behaves identically to the default one.
1.3 Theming
public struct AuthTextFieldStyle: Sendable // tint, containerColor, secondaryColor, errorColor, cornerRadius
public struct AuthCTAButtonStyle: Sendable // backgroundColor, contentColor, shape, font
public struct AuthTypography: Sendable // fontFamily, resolved per Font.TextStyle, Dynamic Type preserved
extension View {
func authTextFieldStyle(_ style: AuthTextFieldStyle) -> some View
func authCTAButtonStyle(_ style: AuthCTAButtonStyle) -> some View
func authTypography(_ typography: AuthTypography) -> some View
}
All three are environment-injected, so they reach every screen in the subtree including pushed destinations. .authCTAButtonStyle() with no argument is the internal call-site modifier that replaced 21 bare .buttonStyle(.borderedProminent) calls, and .authFont(_:weight:) replaced the bare .font(_:) calls.
Part 2: per-screen state structs (the new part)
.pickerDestination lets a consumer return their own view for .passwordRecovery, but that view starts from nothing. It declares its own @State private var email, runs its own FormValidators, calls authService itself, inspects SignInOutcome for .mfaRequired, forwards to mfaHandler, catches AuthServiceError.accountConflict for accountConflictHandler, and routes the rest to reportError.
That plumbing is what a state struct absorbs, and it is the difference between "replace a screen" meaning presentation only and meaning presentation plus reimplementation.
2.1 Shape
Each default screen view gains a content-slot initializer. The library view stays the state owner, the @State stays exactly where it already is, and only the markup moves out.
public struct EmailAuthView<Content: View>: View {
public init() where Content == DefaultEmailAuthContent
public init(@ViewBuilder content: @escaping (EmailAuthContentState) -> Content)
}
This is the same generic-with-constrained-default-init pattern AuthPickerView and AuthPickerContentView already use on the branch, so it is a third application of a reviewed shape rather than a new idea. Every existing EmailAuthView() call site keeps working.
2.2 Two-way fields are Binding, not value plus setter
FirebaseUI-Android models a field as a value plus an onChange closure because that is what Compose's TextField takes. SwiftUI's TextField takes a Binding, so these structs should expose Binding<String> directly. Porting Android's shape literally would push Binding(get:set:) onto every consumer at every field.
// idiomatic
TextField("Email", text: state.email)
// what a literal port would cost
TextField("Email", text: Binding(get: { state.email }, set: state.onEmailChange))
Actions stay closures, derived values stay let.
2.3 Every struct carries the same three derived values
isLoading, errorMessage and isValid. isValid matters specifically because validation currently lives inside each view as FormValidators calls, so without it a custom view either reimplements the rules or ships a CTA that is always enabled.
2.4 Inventory
One struct per screen, each reflecting the @State that screen already holds.
| Screen | State struct | Fields (Binding) | Actions | Derived |
|---|---|---|---|---|
EmailAuthView |
EmailAuthContentState |
email, password, confirmPassword |
signIn, signUp, goToPasswordRecovery, goToEmailLink, switchFlow |
flow: AuthenticationFlow, isValid, isLoading, errorMessage |
PasswordRecoveryView |
PasswordRecoveryContentState |
email |
sendResetLink, dismissSuccess |
didSend, sentEmail, isValid, isLoading, errorMessage |
EmailLinkView |
EmailLinkContentState |
email |
sendSignInLink, dismissAlert |
didSend, isValid, isLoading, errorMessage |
UpdatePasswordView |
UpdatePasswordContentState |
password, confirmPassword |
updatePassword |
isValid, isLoading, errorMessage |
EnterPhoneNumberView |
PhoneNumberContentState |
phoneNumber, selectedCountry |
sendCode |
allowedCountries, isValid, isLoading, errorMessage |
EnterVerificationCodeView |
VerificationCodeContentState |
verificationCode |
verify, resendCode, changeNumber |
fullPhoneNumber, resendCountdown, isValid, isLoading, errorMessage |
MFAEnrolmentView |
MFAEnrollmentContentState |
selectedFactorType, phoneNumber, selectedCountry, verificationCode, totpCode, displayName |
sendCode, enroll, copySecret |
allowedFactors, totpSecret, totpQRCodeURL, didCopySecret, isValid, isLoading, errorMessage |
MFAResolutionView |
MFAResolutionContentState |
selectedHintIndex, verificationCode, totpCode |
sendCode, resolve |
hints: [MultiFactorInfo], isValid, isLoading, errorMessage |
MFAManagementView |
MFAManagementContentState |
none | unenroll(_:), goToEnrollment, refresh |
enrolledFactors: [MultiFactorInfo], isLoading, errorMessage |
SignedInView |
SignedInContentState |
displayName |
signOut, deleteAccount, updatePassword, verifyEmail, goToMFAManagement |
user: User?, isEmailVerified, isLoading, errorMessage |
Reauthentication needs no struct of its own. ReauthenticationCoordinator already sits behind UpdatePasswordView, MFAEnrolmentView and MFAManagementView, so it stays where it is and the consumer never sees it. This is a deliberate divergence from Android, where reauth is a first-class routed screen with its own state object.
2.5 Worked example
public struct EmailAuthContentState {
public let flow: AuthenticationFlow
public let email: Binding<String>
public let password: Binding<String>
public let confirmPassword: Binding<String>
public let isValid: Bool
public let isLoading: Bool
public let errorMessage: String?
public let signIn: () -> Void
public let signUp: () -> Void
public let switchFlow: () -> Void
public let goToPasswordRecovery: () -> Void
public let goToEmailLink: () -> Void
}
signIn is the whole point. It wraps the Task, awaits authService.signIn(email:password:), matches .mfaRequired and calls mfaHandler, catches AuthServiceError.accountConflict and calls accountConflictHandler, sends anything else to reportError, and flips isLoading around all of it. The consumer writes a button.
Consumer side:
AuthPickerView { authenticatedApp }
.pickerContent {
AuthPickerContentView { providers, onProviderSelected in
SpotlightMethodPicker(providers: providers, onProviderSelected: onProviderSelected)
}
}
.pickerDestination { screen in
switch screen {
case .enterPhoneNumber:
EnterPhoneNumberView { state in
MyPhoneEntry(state: state)
}
default:
AuthPickerDestinationView(screen: screen)
}
}
struct MyPhoneEntry: View {
let state: PhoneNumberContentState
var body: some View {
VStack(spacing: 16) {
CountrySelector(selection: state.selectedCountry, allowed: state.allowedCountries)
TextField("Phone number", text: state.phoneNumber)
.keyboardType(.phonePad)
if let error = state.errorMessage {
Text(error).foregroundStyle(.red)
}
Button("Send code", action: state.sendCode)
.disabled(!state.isValid || state.isLoading)
}
}
}
No @State, no validator, no AuthService, no MFA branch, no error routing.
Part 3: how the layers compose
Three tiers, picked per need, mixable in one app.
- Theme only.
.authTextFieldStyle,.authCTAButtonStyle,.authTypography, plus.tintand.backgroundthrough.pickerContentand.pickerDestination. - Layout.
AuthPickerContentView(authMethodPicker:)for the method list,.pickerDestinationto swap whole routes. - Markup. A screen's content-slot initializer, driven by its state struct.
Tier 3 is per screen, so a consumer can hand-build the phone flow and keep the stock MFA screens, which is the common case and the one that is impossible today.
Non-goals and scope boundaries
- Branded provider buttons stay non-themeable. Eight of nine
AuthProviderButton(call sites use brand-mandatedProviderStylepresets. - The email-link button is not an
AuthProviderUI. It is special-cased insideAuthService.renderButtons()and driven byauthService.emailLinkSignInEnabled, so it does not appear inregisteredProviders. A customauthMethodPickerlayout that wants it must render it separately, exactly asrenderButtons()does internally today. LegacySignInRecoveryViewis presented as its own sheet fromAuthPickerViewrather than as anAuthViewroute, so it sits outsidepickerDestination. Either give it a content slot in the same pass or leave it stock, but do not route it.- No change to
AuthProviderUI's existing requirements.AuthProviderActionis additive and opt-in, becauseAuthProviderUIis public and third parties conform to it.
Sequencing
- Fix the two compile errors the automated review caught on #1369:
.strikethroughcalled on a custom view modifier instead of onText, inAuthTextField.swiftandVerificationCodeInputField.swift. Also applyAuthTypographyto typed text inSecureFieldandTextField, not just placeholders. - Bring
auth-picker-view-picker-contentup to date with currentmainand land Part 1 as its own PR. It is already built and was verified against a consumer app. - Land per-screen state structs incrementally, one PR per screen or per flow group, each purely additive. Start with
EnterPhoneNumberViewandEnterVerificationCodeView: two screens, the smallest state, and they prove theBindingergonomics before the MFA screens, which carry the largest state and have the most to gain. - Add a full-customization sample to the example app supplying custom markup for every screen, matching what FirebaseUI-Android ships. Without it, nothing catches the case where a state struct omits a value the default view reads off
authServicedirectly.
Open questions
- Should
errorMessagebeString?or a typed error? Android uses the localized string because the library already owns localization viaauthService.string.localizedErrorMessage(for:). A typed error lets a consumer branch on the case at the cost of localizing it themselves. Proposal: shipString?, add a typederror: AuthServiceError?alongside it only if a real consumer needs it. MFAManagementContentState.unenroll(_:)is destructive and can trigger reauthentication. Confirm the coordinator's sheet still presents correctly when the surrounding markup is consumer-supplied.- Does
SignedInViewbelong in the inventory at all? It is the post-auth screen, and a consumer replacing it may prefer to pass their own view toAuthPickerView's trailing closure instead. Cheap to ship, possibly redundant.
- 主要語言
- Swift
- 星號
- 1.6k
- 分支
- 496
- 平均合併
- 3 天 23 小時
- 30 天內合併 PR
- 5
環境準備
- 沒有 Dockerfile 或 Docker Compose 檔案
- 有 Pull Request 範本
- 閱讀貢獻指南
從這裡開始
- 先讀完整個 Issue,再讀專案的貢獻指南。
- 在 Issue 下留言說明你要接手 —— 這能避免兩個人做同樣的事。
- Fork 儲存庫,在一個分支上完成修改。
- 送出 Pull Request,並在描述裡引用這個 Issue 編號。
firebase/FirebaseUI-iOS 的其他 Issue
-
VerificationCodeInputField: iPad Return key clears/hides OTP fields可能已有人在做 @amansingh1207 於 3 天前認領。 未關閉needs attention
難度 2/5 1-3 小時 新手友好度 82/100
firebase/FirebaseUI-iOS#1407 ·
維護者通常 5 天內回覆
查看 firebase/FirebaseUI-iOS 的全部 Issue
相似的 Issue
-
難度 2/5 1-3 小時 新手友好度 75/100
維護者通常 1 天內回覆
-
[BUG] File transcription skips audio chunks shorter than one second可能已有人在做 @sabbah13 今天認領。 未關閉
難度 2/5 1-3 小時 新手友好度 72/100
altic-dev/FluidVoice#1161 ·
維護者通常 1 天內回覆
-
swift.md: `Date(myString, strategy: .iso8601)` example omits `try` — the initializer is throwing未關閉
難度 1/5 1 小時以內 新手友好度 88/100
-
難度 2/5 1-3 小時 新手友好度 62/100
githubnext/desktop-tools#25 ·
維護者通常 1 天內回覆
-
bug core p3
難度 2/5 1-3 小時 新手友好度 70/100
RunanywhereAI/runanywhere-sdks#1083 ·
維護者通常 5 天內回覆