### Swift Authentication Service Usage Example Source: https://context7.com/gmini9999/rollingpaper/llms.txt Demonstrates how to use the `AuthService` protocol with a mock implementation. This example showcases asynchronous sign-in using `async/await`, error handling for different `AuthError` cases, and signing out. It also includes an example of observing session changes using Combine publishers. ```swift // Usage example with mock service Task { let authService = MockAuthService() // Sign in with Apple do { let session = try await authService.signIn(with: .apple) print("Signed in as \(session.displayName) via \(session.provider.displayName)") // Output: "Signed in as Jamie Rivera via Apple" } catch let error as AuthError { switch error { case .cancelled: print("User cancelled") case .failed(let reason): print("Failed: \(reason ?? \"unknown\")") case .timedOut: print("Timeout occurred") } } // Sign out await authService.signOut() print("Signed out successfully") } // Observe session changes with Combine var cancellables = Set() authService.sessionPublisher .sink { session in if let session = session { print("Session active: \(session.displayName)") } else { print("No active session") } } .store(in: &cancellables) ``` -------------------------------- ### RPButton Component Usage Examples in Swift Source: https://context7.com/gmini9999/rollingpaper/llms.txt Demonstrates various ways to use the RPButton component in Swift with different variants, sizes, and configurations. Includes examples for primary, secondary with icons, destructive, link styles, and disabled states. ```swift // Usage examples VStack(spacing: .rpSpaceM) { // Primary action button RPButton("Continue", variant: .primary, size: .large) { print("Primary action") } // Secondary with icon RPButton("Cancel", variant: .secondary, size: .medium, leadingIcon: Image(systemName: "xmark")) { print("Cancel action") } // Destructive action RPButton("Delete Account", variant: .destructive, size: .large) { print("Delete action") } // Link style RPButton("Learn More", variant: .link, size: .small, fillsWidth: false) { print("Link action") } // Disabled state RPButton("Submit", variant: .primary, isEnabled: false) { print("Won't execute") } } ``` -------------------------------- ### RPToast Component Definition and Usage (SwiftUI) Source: https://context7.com/gmini9999/rollingpaper/llms.txt Defines the RPToast structure for creating toast notifications, including styles and actions. It also includes the RPToastCenter class for managing toast display and provides usage examples for different toast types and scenarios. ```swift import SwiftUI public struct RPToast: Identifiable { public struct Action { public let title: String private let handler: () -> Void public init(title: String, handler: @escaping () -> Void) { self.title = title self.handler = handler } public func perform() { handler() } } public enum Style { case neutral // Default gray case success // Green/accent color case warning // Orange case critical // Red/danger color } public let id: UUID public let title: String? public let message: String public let style: Style public let action: Action? public init(id: UUID = UUID(), title: String? = nil, message: String, style: Style = .neutral, action: Action? = nil) { self.id = id self.title = title self.message = message self.style = style self.action = action } } // Toast center for managing display @MainActor final class RPToastCenter: ObservableObject { static let shared = RPToastCenter() @Published var currentToast: RPToast? func show(_ toast: RPToast, duration: TimeInterval = 3.0) { currentToast = toast Task { try? await Task.sleep(nanoseconds: UInt64(duration * 1_000_000_000)) if currentToast?.id == toast.id { dismiss() } } } func dismiss() { currentToast = nil } } // Usage examples // Success toast RPToastCenter.shared.show( RPToast( title: "Success", message: "Your changes have been saved", style: .success ), duration: 2.0 ) // Error toast with action RPToastCenter.shared.show( RPToast( title: "Connection Error", message: "Unable to reach server", style: .critical, action: RPToast.Action(title: "Retry") { print("Retry action") } ), duration: 5.0 ) // Warning toast RPToastCenter.shared.show( RPToast( message: "Low battery - save your work", style: .warning ) ) // Simple info toast RPToastCenter.shared.show( RPToast(message: "Paper copied to clipboard") ) // Dismiss programmatically RPToastCenter.shared.dismiss() ``` -------------------------------- ### Adaptive Content View Implementation (SwiftUI) Source: https://context7.com/gmini9999/rollingpaper/llms.txt Demonstrates how to use the AdaptiveLayoutContext within a SwiftUI View to dynamically adapt the layout based on the detected breakpoint. It uses a GeometryReader to get layout information and switches between different view structures (VStack, LazyVGrid) for compact, medium, and expanded breakpoints. ```swift // Usage in SwiftUI views struct AdaptiveContentView: View { @Environment(\.adaptiveLayoutContext) private var layout var body: some View { GeometryReader { proxy in let context = AdaptiveLayoutContext.resolve( proxy: proxy, horizontalSizeClass: .regular, // Example values, these would typically come from environment verticalSizeClass: .regular ) Group { switch context.breakpoint { case .compact: // Single column layout for iPhone VStack(spacing: 12) { ForEach(items) { item in // Assuming 'items' is defined elsewhere ItemCard(item: item) // Assuming 'ItemCard' is defined elsewhere } } case .medium: // Two column layout for iPad portrait LazyVGrid(columns: [ GridItem(.flexible()), GridItem(.flexible()) ], spacing: 16) { ForEach(items) { item in ItemCard(item: item) } } case .expanded: // Three column layout for iPad landscape LazyVGrid(columns: [ GridItem(.flexible()), GridItem(.flexible()), GridItem(.flexible()) ], spacing: 20) { ForEach(items) { item in ItemCard(item: item) } } } } .adaptiveContentContainer() .environment(\.adaptiveLayoutContext, context) } } } ``` -------------------------------- ### SwiftUI Color Token System Source: https://context7.com/gmini9999/rollingpaper/llms.txt Defines a color token system for SwiftUI applications with support for light and dark modes. It uses a TokenStore to map token names to hex color values. Usage examples demonstrate applying these colors to Text and Button elements. ```swift import SwiftUI public enum RPColorToken: String { case primary = "rpColorPrimary" case primaryAlt = "rpColorPrimaryAlt" case accent = "rpColorAccent" case danger = "rpColorDanger" case surface = "rpColorSurface" case surfaceAlt = "rpColorSurfaceAlt" case textPrimary = "rpColorTextPrimary" case textInverse = "rpColorTextInverse" } extension Color { static func rp(_ token: RPColorToken, scheme: ColorScheme) -> Color { let key = scheme == .dark ? "(token.rawValue)Dark" : token.rawValue let hex: String = TokenStore.shared.value(for: key) ?? "#CCCCCC" return Color(hex: hex) } // Convenience accessors static var rpPrimary: Color { rp(.primary, scheme: .current) } static var rpPrimaryAlt: Color { rp(.primaryAlt, scheme: .current) } static var rpAccent: Color { rp(.accent, scheme: .current) } static var rpDanger: Color { rp(.danger, scheme: .current) } static var rpTextPrimary: Color { rp(.textPrimary, scheme: .current) } static var rpTextInverse: Color { rp(.textInverse, scheme: .current) } static var rpSurface: Color { rp(.surface, scheme: .current) } static var rpSurfaceAlt: Color { rp(.surfaceAlt, scheme: .current) } } // Usage examples Text("Primary Text") .foregroundColor(.rpPrimary) Button("Action") { } .background(Color.rpAccent) VStack { Text("Content") } .background(Color.rpSurface) .foregroundColor(.rpTextPrimary) // Danger state Text("Error Message") .foregroundColor(.rpDanger) ``` -------------------------------- ### SwiftUI Spacing Token System Source: https://context7.com/gmini9999/rollingpaper/llms.txt Provides a spacing token system in SwiftUI using CGFloat values for consistent layout margins and spacing. It defines various predefined spacing constants from xxs to xxl. Usage examples demonstrate applying these spacing tokens to VStack and HStack elements. ```swift import SwiftUI public enum RPSpaceToken: CGFloat { case xxs = 4 case xs = 8 case s = 12 case m = 16 case l = 24 case xl = 32 case xxl = 48 } extension CGFloat { static var rpSpaceXXS: CGFloat { RPSpaceToken.xxs.rawValue } static var rpSpaceXS: CGFloat { RPSpaceToken.xs.rawValue } static var rpSpaceS: CGFloat { RPSpaceToken.s.rawValue } static var rpSpaceM: CGFloat { RPSpaceToken.m.rawValue } static var rpSpaceL: CGFloat { RPSpaceToken.l.rawValue } static var rpSpaceXL: CGFloat { RPSpaceToken.xl.rawValue } static var rpSpaceXXL: CGFloat { RPSpaceToken.xxl.rawValue } } // Usage examples VStack(spacing: .rpSpaceM) { Text("Item 1") Text("Item 2") Text("Item 3") } .padding(.rpSpaceL) HStack(spacing: .rpSpaceS) { Image(systemName: "star.fill") Text("Featured") } .padding(.horizontal, .rpSpaceXL) .padding(.vertical, .rpSpaceM) ``` -------------------------------- ### SwiftUI Font Token System Source: https://context7.com/gmini9999/rollingpaper/llms.txt Implements a font token system for SwiftUI applications with support for Dynamic Type. It defines various font styles and weights, making it easy to apply consistent typography. Usage examples show how to set font styles on Text views. ```swift import SwiftUI public enum RPFontToken: String { case headingL = "rpFontHeadingL" // 28pt semibold case headingM = "rpFontHeadingM" // 22pt semibold case bodyL = "rpFontBodyL" // 17pt regular case bodyM = "rpFontBodyM" // 15pt regular case caption = "rpFontCaption" // 13pt regular } extension Font { static var rpHeadingL: Font { .system(size: 28, weight: .semibold, design: .default) } static var rpHeadingM: Font { .system(size: 22, weight: .semibold, design: .default) } static var rpBodyL: Font { .system(size: 17, weight: .regular, design: .default) } static var rpBodyM: Font { .system(size: 15, weight: .regular, design: .default) } static var rpCaption: Font { .system(size: 13, weight: .regular, design: .default) } } // Usage examples Text("Large Heading") .font(.rpHeadingL) Text("Medium Heading") .font(.rpHeadingM) Text("Body text with regular weight") .font(.rpBodyL) Text("Smaller body text") .font(.rpBodyM) Text("Caption or metadata") .font(.rpCaption) .foregroundColor(.secondary) ``` -------------------------------- ### SwiftUI App Entry Point Initialization Source: https://context7.com/gmini9999/rollingpaper/llms.txt Initializes the main SwiftUI application, demonstrating dependency injection for authentication and interface providers. It supports both default initialization with mock services and custom initialization for testing or production environments. ```swift import SwiftUI @main @MainActor struct RollingPaperApp: App { @StateObject private var interfaceProvider: InterfaceProvider private let authService: AuthService // Default initialization with mock service init() { self.init(authService: MockAuthService()) } // Custom initialization for testing or production Firebase init(authService: AuthService) { let provider = InterfaceProvider() _interfaceProvider = StateObject(wrappedValue: provider) self.authService = authService } var body: some Scene { WindowGroup { AppNavigationView(authService: authService) .environmentObject(interfaceProvider) .interface(interfaceProvider) } } } // Launch the app with custom configuration @main struct CustomRollingPaperApp: App { var body: some Scene { WindowGroup { RollingPaperApp(authService: MockAuthService( configuration: MockAuthServiceConfiguration( latencyRange: 0.3...0.8, failureProbability: 0.10, cancellationProbability: 0.05, simulatedNames: [ .apple: ["Test User", "Demo User"], .google: ["Sample User"] ] ) )) } } } ``` -------------------------------- ### Swift Mock Authentication Service Implementation Source: https://context7.com/gmini9999/rollingpaper/llms.txt Implements a mock authentication service using Swift's Combine framework. It simulates user sign-in and sign-out processes with configurable latency, failure rates, and cancellation probabilities. Dependencies include Combine and Foundation. It takes an optional configuration and persistence object, returning a UserSession upon successful sign-in or throwing an AuthError. ```swift import Combine import Foundation struct MockAuthServiceConfiguration: Sendable { let latencyRange: ClosedRange let failureProbability: Double let cancellationProbability: Double let simulatedNames: [AuthProvider: [String]] static let standard = MockAuthServiceConfiguration( latencyRange: 0.5...1.2, // Random delay between 500ms-1200ms failureProbability: 0.15, // 15% chance of failure cancellationProbability: 0.05, // 5% chance of cancellation simulatedNames: [ .apple: ["Jamie Rivera", "Chris Han", "Minseo Kim", "Alex Garcia"], .google: ["Jordan Chen", "Taylor Singh", "Yuna Lee", "Owen Park"] ] ) } @MainActor final class MockAuthService: AuthService { @Published private var session: UserSession? var currentSession: UserSession? { session } var sessionPublisher: AnyPublisher { $session.eraseToAnyPublisher() } private let configuration: MockAuthServiceConfiguration private let persistence: SessionPersistence init(configuration: MockAuthServiceConfiguration? = nil, persistence: SessionPersistence? = nil) { self.configuration = configuration ?? .standard self.persistence = persistence ?? UserDefaultsSessionPersistence() self._session = Published(initialValue: self.persistence.loadSession()) } func signIn(with provider: AuthProvider) async throws -> UserSession { // Simulate network latency let delay = Double.random(in: configuration.latencyRange) try await Task.sleep(nanoseconds: UInt64(delay * 1_000_000_000)) // Simulate random failures let outcome = Double.random(in: 0...1) if outcome < configuration.failureProbability { throw AuthError.failed() } if outcome < configuration.failureProbability + configuration.cancellationProbability { throw AuthError.cancelled } // Create successful session let names = configuration.simulatedNames[provider] ?? [] let displayName = names.randomElement() ?? "\(provider.displayName) User" let session = UserSession(displayName: displayName, provider: provider) self.session = session persistence.save(session: session) return session } func signOut() async { session = nil persistence.clear() } } // Usage with custom configuration let quickAuthService = MockAuthService( configuration: MockAuthServiceConfiguration( latencyRange: 0.1...0.3, // Fast responses for testing failureProbability: 0.0, // Never fail cancellationProbability: 0.0, // Never cancel simulatedNames: [ .apple: ["Test User"], .google: ["Test User"] ] ) ) Task { let session = try await quickAuthService.signIn(with: .google) print("Quick login: \(session.displayName)") } ``` -------------------------------- ### Swift Navigation Coordinator with Deep Link Support Source: https://context7.com/gmini9999/rollingpaper/llms.txt This Swift code defines a navigation system for an application, including route definitions, a coordinator class for managing navigation state, and deep link handling. It leverages Combine and SwiftUI for reactive programming and UI updates. Dependencies include Combine and SwiftUI frameworks. ```swift import Combine import SwiftUI // Define application routes enum AppRoute: Hashable { case launch case auth case home case paper(PaperRoute) } enum PaperRoute: Hashable { case create case detail(id: String) case share(id: String) } // Navigation coordinator final class NavigationCoordinator: ObservableObject { @Published var path: [AppRoute] = [] @Published var presentedPaperRoute: PaperRoute? // Note: This property seems unused in the provided snippet. func navigate(to route: AppRoute) { path.append(route) } func reset(to route: AppRoute) { path = [route] } func handle(deepLink url: URL) { // Assuming DeepLinkParser is defined elsewhere and returns an AppRoute or nil guard let route = DeepLinkParser.parse(url: url) else { return } switch route { case .launch: path = [] case .auth: path = [.auth] case .home: path = [.home] case .paper(let paperRoute): path = [.home, .paper(paperRoute)] } } } // Placeholder for DeepLinkParser (must be implemented separately) class DeepLinkParser { static func parse(url: URL) -> AppRoute? { // Example parsing logic - replace with actual implementation if url.host == "paper" { if let id = url.pathComponents.last { return .paper(.detail(id: id)) } } return nil } } // Usage example (within a SwiftUI View context) struct ContentView: View { @StateObject var coordinator = NavigationCoordinator() var body: some View { NavigationView { HomeView() .navigationDestination(for: AppRoute.self) { route in switch route { case .auth: AuthView() case .home: HomeView() case .paper(let paperRoute): PaperView(route: paperRoute) case .launch: // Handle launch route if necessary, potentially by dismissing presented views EmptyView() // Or some launch screen view } } } .environmentObject(coordinator) // Make coordinator available throughout the environment .onOpenURL { url in coordinator.handle(deepLink: url) } } } // Placeholder views (must be defined separately) struct HomeView: View { var body: some View { Text("Home View") } } struct AuthView: View { var body: some View { Text("Auth View") } } struct PaperView: View { let route: PaperRoute var body: some View { Text("Paper View: \(route.description)") } // Improved description for PaperRoute } extension PaperRoute: CustomStringConvertible { var description: String { switch self { case .create: return "Create" case .detail(let id): return "Detail (ID: \(id))" case .share(let id): return "Share (ID: \(id))" } } } /* // Example of how to use the coordinator outside the NavigationView setup: // Navigate to specific paper // coordinator.navigate(to: .paper(.detail(id: "paper-123"))) // Reset to home // coordinator.reset(to: .home) // Handle deep link (example URL) // let url = URL(string: "rollingpaper://paper/paper-456")! // coordinator.handle(deepLink: url) */ ``` -------------------------------- ### Swift Authentication ViewModel with Combine and SwiftUI Source: https://context7.com/gmini9999/rollingpaper/llms.txt Manages authentication states, handles sign-in/sign-out operations, and provides user feedback. It uses Combine for session observation and includes a timeout mechanism for network requests. Dependencies include Combine and Foundation. Inputs are `AuthProvider` and `AuthService`, outputs are `State` and `Feedback`. ```swift import Combine import Foundation @MainActor final class AuthViewModel: ObservableObject { enum State: Equatable { case signedOut case loading(AuthProvider) case authenticated(UserSession) case failure(AuthProvider, AuthError) var isAuthenticated: Bool { if case .authenticated = self { return true } return false } } struct Feedback: Identifiable, Equatable { enum Kind { case success, failure } let id = UUID() let kind: Kind let title: String? let message: String let timestamp: Date } @Published private(set) var state: State @Published private(set) var isProcessing: Bool = false @Published private(set) var feedback: Feedback? private let service: AuthService private let timeoutInterval: TimeInterval private var cancellables = Set() init(service: AuthService, timeoutInterval: TimeInterval = 8) { self.service = service self.timeoutInterval = timeoutInterval self.state = service.currentSession.map { .authenticated($0) } ?? .signedOut // Observe session changes service.sessionPublisher .receive(on: RunLoop.main) .sink { [weak self] session in guard let self = self else { return } if let session = session { self.state = .authenticated(session) } else if case .failure = self.state { // Keep failure state visible } else { self.state = .signedOut } } .store(in: &cancellables) } func signIn(with provider: AuthProvider) async { guard !isProcessing else { return } state = .loading(provider) isProcessing = true feedback = nil // Start timeout timer let timeoutTask = Task { try? await Task.sleep(nanoseconds: UInt64(timeoutInterval * 1_000_000_000)) await MainActor.run { if self.isProcessing { self.handleTimeout(provider: provider) } } } do { let session = try await service.signIn(with: provider) timeoutTask.cancel() isProcessing = false state = .authenticated(session) feedback = Feedback( kind: .success, title: "Login Successful", message: "Welcome, \(session.displayName)!", timestamp: Date() ) } catch let error as AuthError { timeoutTask.cancel() isProcessing = false state = .failure(provider, error) feedback = Feedback( kind: .failure, title: "Login Failed", message: error.errorDescription ?? "Unknown error", timestamp: Date() ) } } func signOut() async { guard !isProcessing else { return } isProcessing = true await service.signOut() isProcessing = false state = .signedOut } private func handleTimeout(provider: AuthProvider) { isProcessing = false state = .failure(provider, .timedOut) feedback = Feedback( kind: .failure, title: "Connection Timeout", message: "The request took too long", timestamp: Date() ) } } // Usage in SwiftUI struct AuthView: View { @StateObject private var viewModel: AuthViewModel init(authService: AuthService) { _viewModel = StateObject(wrappedValue: AuthViewModel(service: authService)) } var body: some View { VStack { if case .loading(let provider) = viewModel.state { ProgressView("Signing in with \(provider.displayName)..." ) } else { Button("Sign in with Apple") { Task { await viewModel.signIn(with: .apple) } } Button("Sign in with Google") { Task { await viewModel.signIn(with: .google) } } } } .alert(item: $viewModel.feedback) { feedback in Alert( title: Text(feedback.title ?? ""), message: Text(feedback.message), dismissButton: .default(Text("OK")) ) } } } ``` -------------------------------- ### Swift Authentication Service Protocol and Models Source: https://context7.com/gmini9999/rollingpaper/llms.txt Defines the core authentication service protocol (`AuthService`) with methods for signing in and out, and observing session changes. It also includes models for authentication providers (`AuthProvider`), user sessions (`UserSession`), and potential authentication errors (`AuthError`). This provides a clear contract for any authentication implementation and defines the data structures involved. ```swift import Combine import Foundation // Define authentication service protocol protocol AuthService: AnyObject { var currentSession: UserSession? { get } var sessionPublisher: AnyPublisher { get } @discardableResult func signIn(with provider: AuthProvider) async throws -> UserSession func signOut() async } // Authentication models enum AuthProvider: String, Codable { case apple case google var displayName: String { switch self { case .apple: return "Apple" case .google: return "Google" } } } struct UserSession: Codable, Equatable, Sendable { let id: UUID let displayName: String let provider: AuthProvider let createdAt: Date } enum AuthError: Error, LocalizedError { case cancelled case failed(reason: String? = nil) case timedOut var errorDescription: String? { switch self { case .cancelled: return "User cancelled login" case .failed(let reason): return "Login failed: \(reason ?? \"Unknown error\")" case .timedOut: return "Login request timed out" } } } ``` -------------------------------- ### SwiftUI Interface Provider for Theme and Accessibility State Source: https://context7.com/gmini9999/rollingpaper/llms.txt Manages global theme (color scheme) and accessibility states (reduce motion, dynamic type) in a SwiftUI application. It utilizes Combine for observing accessibility changes and can be observed by views using @EnvironmentObject. Dependencies include SwiftUI and Combine. ```swift import SwiftUI import Combine @MainActor final class InterfaceProvider: ObservableObject { @Published var colorScheme: ColorScheme = .light @Published var reduceMotion: Bool = UIAccessibility.isReduceMotionEnabled @Published var dynamicType: DynamicTypeSize = .medium private var cancellables = Set() init() { observeAccessibilityChanges() } func set(colorScheme: ColorScheme) { self.colorScheme = colorScheme } func set(reduceMotion: Bool) { self.reduceMotion = reduceMotion } func set(dynamicType: DynamicTypeSize) { self.dynamicType = dynamicType } private func observeAccessibilityChanges() { NotificationCenter.default .publisher(for: UIAccessibility.reduceMotionStatusDidChangeNotification) .map { _ in UIAccessibility.isReduceMotionEnabled } .sink { [weak self] isEnabled in self?.reduceMotion = isEnabled } .store(in: &cancellables) } } // Usage in app initialization @main struct MyApp: App { @StateObject private var interfaceProvider = InterfaceProvider() var body: some Scene { WindowGroup { ContentView() .environmentObject(interfaceProvider) .preferredColorScheme(interfaceProvider.colorScheme) } } } // Usage in views struct SettingsView: View { @EnvironmentObject var interfaceProvider: InterfaceProvider var body: some View { VStack { Picker("Theme", selection: $interfaceProvider.colorScheme) { Text("Light").tag(ColorScheme.light) Text("Dark").tag(ColorScheme.dark) } Toggle("Reduce Motion", isOn: $interfaceProvider.reduceMotion) Text("Current type size: \(interfaceProvider.dynamicType.description)") } } } // Access in view modifiers extension View { func adaptiveAnimation(_ animation: Animation) -> some View { modifier(AdaptiveAnimationModifier(animation: animation)) } } private struct AdaptiveAnimationModifier: ViewModifier { @EnvironmentObject var interfaceProvider: InterfaceProvider let animation: Animation func body(content: Content) -> some View { content.animation( interfaceProvider.reduceMotion ? nil : animation, value: UUID() ) } } ``` -------------------------------- ### Adaptive Layout Context Resolution and Breakpoint Handling (Swift) Source: https://context7.com/gmini9999/rollingpaper/llms.txt Defines an AdaptiveLayoutContext to represent the current layout state based on screen width, idiom, and orientation. It includes a static method `resolve` to determine the breakpoint and device characteristics from a GeometryProxy. This context is crucial for making adaptive UI decisions. ```swift import SwiftUI struct AdaptiveLayoutContext: Equatable { enum Breakpoint: Equatable { case compact // < 600pt width case medium // 600pt - 900pt width case expanded // > 900pt width } let breakpoint: Breakpoint let idiom: UIUserInterfaceIdiom let isLandscape: Bool let width: CGFloat let height: CGFloat var isPad: Bool { idiom == .pad } var isPhone: Bool { idiom == .phone } static func resolve( proxy: GeometryProxy, horizontalSizeClass: UserInterfaceSizeClass?, verticalSizeClass: UserInterfaceSizeClass? ) -> AdaptiveLayoutContext { let size = proxy.size let width = size.width let height = size.height let isLandscape = width > height let idiom = UIDevice.current.userInterfaceIdiom let breakpoint: Breakpoint switch width { case ..<600: breakpoint = .compact case 600..<900: breakpoint = .medium default: breakpoint = .expanded } return AdaptiveLayoutContext( breakpoint: breakpoint, idiom: idiom, isLandscape: isLandscape, width: width, height: height ) } var columnVisibilityPreference: NavigationSplitViewVisibility { switch breakpoint { case .compact: return .detailOnly case .medium: return .doubleColumn case .expanded: return .all } } } ``` -------------------------------- ### Implement Haptic Feedback System in Swift Source: https://context7.com/gmini9999/rollingpaper/llms.txt Provides an accessibility-aware haptic feedback system using UIKit. It supports various feedback types like impact, notification, and selection, and allows for custom intensity. The system respects accessibility settings like reduced motion. ```swift import UIKit public enum RPHapticFeedback { case impact(UIImpactFeedbackGenerator.FeedbackStyle) case notification(UINotificationFeedbackGenerator.FeedbackType) case selection case custom(intensity: CGFloat) var requiresStrongFeedback: Bool { switch self { case .notification, .custom: return true default: return false } } } public protocol RPHapticTriggering { func trigger(_ feedback: RPHapticFeedback) func prepare() } public final class RPHapticEngine: RPHapticTriggering { public static let shared = RPHapticEngine() public var isEnabled: Bool = true public var allowStrongFeedback: Bool = !UIAccessibility.isReduceMotionEnabled private let impactGenerator = UIImpactFeedbackGenerator(style: .medium) private let notificationGenerator = UINotificationFeedbackGenerator() private let selectionGenerator = UISelectionFeedbackGenerator() public func prepare() { guard isEnabled else { return } impactGenerator.prepare() notificationGenerator.prepare() selectionGenerator.prepare() } public func trigger(_ feedback: RPHapticFeedback) { guard isEnabled else { return } switch feedback { case .impact(let style): let resolvedStyle = allowStrongFeedback ? style : .medium UIImpactFeedbackGenerator(style: resolvedStyle).impactOccurred() case .notification(let type): guard allowStrongFeedback || !feedback.requiresStrongFeedback else { return } notificationGenerator.notificationOccurred(type) case .selection: selectionGenerator.selectionChanged() case .custom(let intensity): guard allowStrongFeedback || intensity < 1 else { return } UIImpactFeedbackGenerator(style: .medium) .impactOccurred(intensity: max(0, min(1, intensity))) } } } // Usage examples let haptics = RPHapticEngine.shared // Prepare for immediate feedback haptics.prepare() // Button tap haptics.trigger(.impact(.light)) // Selection change in picker haptics.trigger(.selection) // Success notification haptics.trigger(.notification(.success)) // Error notification haptics.trigger(.notification(.error)) // Warning notification haptics.trigger(.notification(.warning)) // Custom intensity (0.0 - 1.0) haptics.trigger(.custom(intensity: 0.5)) // Heavy impact for important actions haptics.trigger(.impact(.heavy)) // Disable haptics haptics.isEnabled = false haptics.trigger(.selection) // No effect ``` -------------------------------- ### Implement Session Persistence using UserDefaults and JSON in Swift Source: https://context7.com/gmini9999/rollingpaper/llms.txt A session persistence mechanism that leverages UserDefaults for storage and JSON encoding/decoding for data serialization. It supports loading, saving, and clearing user session data, with customizable storage keys and date formatting. ```swift import Foundation protocol SessionPersistence { func loadSession() -> UserSession? func save(session: UserSession?) func clear() } final class UserDefaultsSessionPersistence: SessionPersistence { private enum Constants { static let storageKey = "auth.mock.session" } private let userDefaults: UserDefaults private let key: String private let encoder: JSONEncoder private let decoder: JSONDecoder init(userDefaults: UserDefaults = .standard, key: String = Constants.storageKey) { self.userDefaults = userDefaults self.key = key self.encoder = JSONEncoder() self.encoder.dateEncodingStrategy = .iso8601 self.decoder = JSONDecoder() self.decoder.dateDecodingStrategy = .iso8601 } func loadSession() -> UserSession? { guard let data = userDefaults.data(forKey: key) else { return nil } return try? decoder.decode(UserSession.self, from: data) } func save(session: UserSession?) { guard let session else { userDefaults.removeObject(forKey: key) return } guard let data = try? encoder.encode(session) else { return } userDefaults.set(data, forKey: key) } func clear() { userDefaults.removeObject(forKey: key) } } // Usage examples let persistence = UserDefaultsSessionPersistence() // Save session let session = UserSession( id: UUID(), displayName: "John Doe", provider: .apple, createdAt: Date() ) persistence.save(session: session) // Load session if let loadedSession = persistence.loadSession() { print("Restored session for \(loadedSession.displayName)") } else { print("No saved session") } // Clear session persistence.clear() // Custom storage key let customPersistence = UserDefaultsSessionPersistence( userDefaults: .standard, key: "custom.auth.key" ) ``` -------------------------------- ### Adaptive Padding and Max Width Modifier (SwiftUI) Source: https://context7.com/gmini9999/rollingpaper/llms.txt Implements a ViewModifier, `AdaptiveContentContainerModifier`, that applies adaptive padding and maximum width based on the current breakpoint. This modifier helps to ensure consistent spacing and content centering across different screen sizes. It also includes a convenience extension function `adaptiveContentContainer()` for easier application. ```swift // Adaptive padding modifier extension View { func adaptiveContentContainer() -> some View { modifier(AdaptiveContentContainerModifier()) } } private struct AdaptiveContentContainerModifier: ViewModifier { @Environment(\.adaptiveLayoutContext) private var layout func body(content: Content) -> some View { let (horizontalPadding, verticalPadding, maxWidth): (CGFloat, CGFloat, CGFloat?) = { switch layout.breakpoint { case .compact: return (16, 20, nil) case .medium: return (24, 24, 720) case .expanded: return (32, 32, 960) } }() return content .padding(.horizontal, horizontalPadding) .padding(.vertical, verticalPadding) .frame(maxWidth: maxWidth, alignment: .center) .frame(maxWidth: .infinity, alignment: .center) } } ``` -------------------------------- ### RPButton Component Definition in Swift Source: https://context7.com/gmini9999/rollingpaper/llms.txt Defines the RPButton struct in Swift, including its enum types for variants and sizes. This component allows for customizable button appearances and actions within a SwiftUI application. ```swift import SwiftUI public enum RPButtonVariant { case primary // Filled with primary color case secondary // Outlined with border case tertiary // Text only with subtle border case destructive // Filled with danger color case link // Underlined text style } public enum RPButtonSize { case large // 52pt height, 22pt font case medium // 44pt height, 15pt font case small // 36pt height, 15pt font } public struct RPButton: View { private let title: String private let variant: RPButtonVariant private let size: RPButtonSize private let leadingIcon: Image? private let trailingIcon: Image? private let isEnabled: Bool private let fillsWidth: Bool private let action: () -> Void public init(_ title: String, variant: RPButtonVariant = .primary, size: RPButtonSize = .large, leadingIcon: Image? = nil, trailingIcon: Image? = nil, isEnabled: Bool = true, fillsWidth: Bool = true, action: @escaping () -> Void) { self.title = title self.variant = variant self.size = size self.leadingIcon = leadingIcon self.trailingIcon = trailingIcon self.isEnabled = isEnabled self.fillsWidth = fillsWidth self.action = action } public var body: some View { Button(action: action) { HStack(spacing: size.iconSpacing) { if let leadingIcon { leadingIcon } Text(title).font(size.font).lineLimit(1) if let trailingIcon { trailingIcon } } .padding(.horizontal, size.horizontalPadding) .padding(.vertical, size.verticalPadding) .frame(maxWidth: fillsWidth ? .infinity : nil) } .buttonStyle(RPButtonStyle(variant: variant, size: size, isEnabled: isEnabled)) .disabled(!isEnabled) } } ``` === COMPLETE CONTENT === This response contains all available snippets from this library. No additional content exists. Do not make further requests.