├── .gitattributes ├── .gitignore ├── .swiftpm └── xcode │ └── package.xcworkspace │ ├── contents.xcworkspacedata │ └── xcshareddata │ └── IDEWorkspaceChecks.plist ├── LICENSE ├── Package.resolved ├── Package.swift ├── README.md ├── Sources └── SwiftUIFlows │ ├── Examples │ ├── Example+Preview.swift │ ├── FullScreenExampleView.swift │ └── PopoverExampleView.swift │ ├── FlowBuilder+Dismiss.swift │ ├── FlowBuilder+Present.swift │ ├── FlowBuilder.swift │ ├── FlowLifecycle.swift │ ├── Flows │ ├── FullScreenFlow.swift │ ├── PopoverConfig.swift │ ├── PopoversFlow.swift │ └── SheetFlow.swift │ ├── View+FlowBuilder.swift │ └── guts │ ├── DragRestrictions.swift │ └── View+RoundedCorners.swift └── Tests └── SwiftUIFlowsTests └── SwiftUIFlowsTests.swift /.gitattributes: -------------------------------------------------------------------------------- 1 | # Auto detect text files and perform LF normalization 2 | * text=auto 3 | -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | # Xcode 2 | # 3 | # gitignore contributors: remember to update Global/Xcode.gitignore, Objective-C.gitignore & Swift.gitignore 4 | 5 | ## User settings 6 | xcuserdata/ 7 | 8 | ## compatibility with Xcode 8 and earlier (ignoring not required starting Xcode 9) 9 | *.xcscmblueprint 10 | *.xccheckout 11 | 12 | ## compatibility with Xcode 3 and earlier (ignoring not required starting Xcode 4) 13 | build/ 14 | DerivedData/ 15 | *.moved-aside 16 | *.pbxuser 17 | !default.pbxuser 18 | *.mode1v3 19 | !default.mode1v3 20 | *.mode2v3 21 | !default.mode2v3 22 | *.perspectivev3 23 | !default.perspectivev3 24 | 25 | ## Obj-C/Swift specific 26 | *.hmap 27 | 28 | ## App packaging 29 | *.ipa 30 | *.dSYM.zip 31 | *.dSYM 32 | 33 | ## Playgrounds 34 | timeline.xctimeline 35 | playground.xcworkspace 36 | 37 | # Swift Package Manager 38 | # 39 | # Add this line if you want to avoid checking in source code from Swift Package Manager dependencies. 40 | # Packages/ 41 | # Package.pins 42 | # Package.resolved 43 | # *.xcodeproj 44 | # 45 | # Xcode automatically generates this directory with a .xcworkspacedata file and xcuserdata 46 | # hence it is not needed unless you have added a package configuration file to your project 47 | # .swiftpm 48 | 49 | .build/ 50 | 51 | # CocoaPods 52 | # 53 | # We recommend against adding the Pods directory to your .gitignore. However 54 | # you should judge for yourself, the pros and cons are mentioned at: 55 | # https://guides.cocoapods.org/using/using-cocoapods.html#should-i-check-the-pods-directory-into-source-control 56 | # 57 | # Pods/ 58 | # 59 | # Add this line if you want to avoid checking in source code from the Xcode workspace 60 | # *.xcworkspace 61 | 62 | # Carthage 63 | # 64 | # Add this line if you want to avoid checking in source code from Carthage dependencies. 65 | # Carthage/Checkouts 66 | 67 | Carthage/Build/ 68 | 69 | # Accio dependency management 70 | Dependencies/ 71 | .accio/ 72 | 73 | # fastlane 74 | # 75 | # It is recommended to not store the screenshots in the git repo. 76 | # Instead, use fastlane to re-generate the screenshots whenever they are needed. 77 | # For more information about the recommended setup visit: 78 | # https://docs.fastlane.tools/best-practices/source-control/#source-control 79 | 80 | fastlane/report.xml 81 | fastlane/Preview.html 82 | fastlane/screenshots/**/*.png 83 | fastlane/test_output 84 | 85 | # Code Injection 86 | # 87 | # After new code Injection tools there's a generated folder /iOSInjectionProject 88 | # https://github.com/johnno1962/injectionforxcode 89 | 90 | iOSInjectionProject/ 91 | -------------------------------------------------------------------------------- /.swiftpm/xcode/package.xcworkspace/contents.xcworkspacedata: -------------------------------------------------------------------------------- 1 | 2 | 4 | 6 | 7 | 8 | -------------------------------------------------------------------------------- /.swiftpm/xcode/package.xcworkspace/xcshareddata/IDEWorkspaceChecks.plist: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | IDEDidComputeMac32BitWarning 6 | 7 | 8 | 9 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | Apache License 2 | Version 2.0, January 2004 3 | http://www.apache.org/licenses/ 4 | 5 | TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION 6 | 7 | 1. Definitions. 8 | 9 | "License" shall mean the terms and conditions for use, reproduction, 10 | and distribution as defined by Sections 1 through 9 of this document. 11 | 12 | "Licensor" shall mean the copyright owner or entity authorized by 13 | the copyright owner that is granting the License. 14 | 15 | "Legal Entity" shall mean the union of the acting entity and all 16 | other entities that control, are controlled by, or are under common 17 | control with that entity. For the purposes of this definition, 18 | "control" means (i) the power, direct or indirect, to cause the 19 | direction or management of such entity, whether by contract or 20 | otherwise, or (ii) ownership of fifty percent (50%) or more of the 21 | outstanding shares, or (iii) beneficial ownership of such entity. 22 | 23 | "You" (or "Your") shall mean an individual or Legal Entity 24 | exercising permissions granted by this License. 25 | 26 | "Source" form shall mean the preferred form for making modifications, 27 | including but not limited to software source code, documentation 28 | source, and configuration files. 29 | 30 | "Object" form shall mean any form resulting from mechanical 31 | transformation or translation of a Source form, including but 32 | not limited to compiled object code, generated documentation, 33 | and conversions to other media types. 34 | 35 | "Work" shall mean the work of authorship, whether in Source or 36 | Object form, made available under the License, as indicated by a 37 | copyright notice that is included in or attached to the work 38 | (an example is provided in the Appendix below). 39 | 40 | "Derivative Works" shall mean any work, whether in Source or Object 41 | form, that is based on (or derived from) the Work and for which the 42 | editorial revisions, annotations, elaborations, or other modifications 43 | represent, as a whole, an original work of authorship. For the purposes 44 | of this License, Derivative Works shall not include works that remain 45 | separable from, or merely link (or bind by name) to the interfaces of, 46 | the Work and Derivative Works thereof. 47 | 48 | "Contribution" shall mean any work of authorship, including 49 | the original version of the Work and any modifications or additions 50 | to that Work or Derivative Works thereof, that is intentionally 51 | submitted to Licensor for inclusion in the Work by the copyright owner 52 | or by an individual or Legal Entity authorized to submit on behalf of 53 | the copyright owner. For the purposes of this definition, "submitted" 54 | means any form of electronic, verbal, or written communication sent 55 | to the Licensor or its representatives, including but not limited to 56 | communication on electronic mailing lists, source code control systems, 57 | and issue tracking systems that are managed by, or on behalf of, the 58 | Licensor for the purpose of discussing and improving the Work, but 59 | excluding communication that is conspicuously marked or otherwise 60 | designated in writing by the copyright owner as "Not a Contribution." 61 | 62 | "Contributor" shall mean Licensor and any individual or Legal Entity 63 | on behalf of whom a Contribution has been received by Licensor and 64 | subsequently incorporated within the Work. 65 | 66 | 2. Grant of Copyright License. Subject to the terms and conditions of 67 | this License, each Contributor hereby grants to You a perpetual, 68 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 69 | copyright license to reproduce, prepare Derivative Works of, 70 | publicly display, publicly perform, sublicense, and distribute the 71 | Work and such Derivative Works in Source or Object form. 72 | 73 | 3. Grant of Patent License. Subject to the terms and conditions of 74 | this License, each Contributor hereby grants to You a perpetual, 75 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 76 | (except as stated in this section) patent license to make, have made, 77 | use, offer to sell, sell, import, and otherwise transfer the Work, 78 | where such license applies only to those patent claims licensable 79 | by such Contributor that are necessarily infringed by their 80 | Contribution(s) alone or by combination of their Contribution(s) 81 | with the Work to which such Contribution(s) was submitted. If You 82 | institute patent litigation against any entity (including a 83 | cross-claim or counterclaim in a lawsuit) alleging that the Work 84 | or a Contribution incorporated within the Work constitutes direct 85 | or contributory patent infringement, then any patent licenses 86 | granted to You under this License for that Work shall terminate 87 | as of the date such litigation is filed. 88 | 89 | 4. Redistribution. You may reproduce and distribute copies of the 90 | Work or Derivative Works thereof in any medium, with or without 91 | modifications, and in Source or Object form, provided that You 92 | meet the following conditions: 93 | 94 | (a) You must give any other recipients of the Work or 95 | Derivative Works a copy of this License; and 96 | 97 | (b) You must cause any modified files to carry prominent notices 98 | stating that You changed the files; and 99 | 100 | (c) You must retain, in the Source form of any Derivative Works 101 | that You distribute, all copyright, patent, trademark, and 102 | attribution notices from the Source form of the Work, 103 | excluding those notices that do not pertain to any part of 104 | the Derivative Works; and 105 | 106 | (d) If the Work includes a "NOTICE" text file as part of its 107 | distribution, then any Derivative Works that You distribute must 108 | include a readable copy of the attribution notices contained 109 | within such NOTICE file, excluding those notices that do not 110 | pertain to any part of the Derivative Works, in at least one 111 | of the following places: within a NOTICE text file distributed 112 | as part of the Derivative Works; within the Source form or 113 | documentation, if provided along with the Derivative Works; or, 114 | within a display generated by the Derivative Works, if and 115 | wherever such third-party notices normally appear. The contents 116 | of the NOTICE file are for informational purposes only and 117 | do not modify the License. You may add Your own attribution 118 | notices within Derivative Works that You distribute, alongside 119 | or as an addendum to the NOTICE text from the Work, provided 120 | that such additional attribution notices cannot be construed 121 | as modifying the License. 122 | 123 | You may add Your own copyright statement to Your modifications and 124 | may provide additional or different license terms and conditions 125 | for use, reproduction, or distribution of Your modifications, or 126 | for any such Derivative Works as a whole, provided Your use, 127 | reproduction, and distribution of the Work otherwise complies with 128 | the conditions stated in this License. 129 | 130 | 5. Submission of Contributions. Unless You explicitly state otherwise, 131 | any Contribution intentionally submitted for inclusion in the Work 132 | by You to the Licensor shall be under the terms and conditions of 133 | this License, without any additional terms or conditions. 134 | Notwithstanding the above, nothing herein shall supersede or modify 135 | the terms of any separate license agreement you may have executed 136 | with Licensor regarding such Contributions. 137 | 138 | 6. Trademarks. This License does not grant permission to use the trade 139 | names, trademarks, service marks, or product names of the Licensor, 140 | except as required for reasonable and customary use in describing the 141 | origin of the Work and reproducing the content of the NOTICE file. 142 | 143 | 7. Disclaimer of Warranty. Unless required by applicable law or 144 | agreed to in writing, Licensor provides the Work (and each 145 | Contributor provides its Contributions) on an "AS IS" BASIS, 146 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or 147 | implied, including, without limitation, any warranties or conditions 148 | of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A 149 | PARTICULAR PURPOSE. You are solely responsible for determining the 150 | appropriateness of using or redistributing the Work and assume any 151 | risks associated with Your exercise of permissions under this License. 152 | 153 | 8. Limitation of Liability. In no event and under no legal theory, 154 | whether in tort (including negligence), contract, or otherwise, 155 | unless required by applicable law (such as deliberate and grossly 156 | negligent acts) or agreed to in writing, shall any Contributor be 157 | liable to You for damages, including any direct, indirect, special, 158 | incidental, or consequential damages of any character arising as a 159 | result of this License or out of the use or inability to use the 160 | Work (including but not limited to damages for loss of goodwill, 161 | work stoppage, computer failure or malfunction, or any and all 162 | other commercial damages or losses), even if such Contributor 163 | has been advised of the possibility of such damages. 164 | 165 | 9. Accepting Warranty or Additional Liability. While redistributing 166 | the Work or Derivative Works thereof, You may choose to offer, 167 | and charge a fee for, acceptance of support, warranty, indemnity, 168 | or other liability obligations and/or rights consistent with this 169 | License. However, in accepting such obligations, You may act only 170 | on Your own behalf and on Your sole responsibility, not on behalf 171 | of any other Contributor, and only if You agree to indemnify, 172 | defend, and hold each Contributor harmless for any liability 173 | incurred by, or claims asserted against, such Contributor by reason 174 | of your accepting any such warranty or additional liability. 175 | 176 | END OF TERMS AND CONDITIONS 177 | 178 | APPENDIX: How to apply the Apache License to your work. 179 | 180 | To apply the Apache License to your work, attach the following 181 | boilerplate notice, with the fields enclosed by brackets "[]" 182 | replaced with your own identifying information. (Don't include 183 | the brackets!) The text should be enclosed in the appropriate 184 | comment syntax for the file format. We also recommend that a 185 | file or class name and description of purpose be included on the 186 | same "printed page" as the copyright notice for easier 187 | identification within third-party archives. 188 | 189 | Copyright [2023] [Vivienne Fosh] 190 | 191 | Licensed under the Apache License, Version 2.0 (the "License"); 192 | you may not use this file except in compliance with the License. 193 | You may obtain a copy of the License at 194 | 195 | http://www.apache.org/licenses/LICENSE-2.0 196 | 197 | Unless required by applicable law or agreed to in writing, software 198 | distributed under the License is distributed on an "AS IS" BASIS, 199 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 200 | See the License for the specific language governing permissions and 201 | limitations under the License. 202 | -------------------------------------------------------------------------------- /Package.resolved: -------------------------------------------------------------------------------- 1 | { 2 | "pins" : [ 3 | { 4 | "identity" : "swiftui-introspect", 5 | "kind" : "remoteSourceControl", 6 | "location" : "https://github.com/siteline/SwiftUI-Introspect", 7 | "state" : { 8 | "revision" : "ccb973cfff703cba53fb88197413485c060eb26b", 9 | "version" : "0.10.0" 10 | } 11 | } 12 | ], 13 | "version" : 2 14 | } 15 | -------------------------------------------------------------------------------- /Package.swift: -------------------------------------------------------------------------------- 1 | // swift-tools-version: 5.8 2 | // The swift-tools-version declares the minimum version of Swift required to build this package. 3 | 4 | import PackageDescription 5 | 6 | let package = Package( 7 | name: "SwiftUIFlows", 8 | platforms: [.iOS(.v15), .macOS(.v13)], 9 | products: [ 10 | // Products define the executables and libraries a package produces, and make them visible to other packages. 11 | .library( 12 | name: "SwiftUIFlows", 13 | targets: ["SwiftUIFlows"]), 14 | ], 15 | dependencies: [ 16 | // Dependencies declare other packages that this package depends on. 17 | .package(url: "https://github.com/siteline/SwiftUI-Introspect", from: "0.10.0"), 18 | ], 19 | targets: [ 20 | // Targets are the basic building blocks of a package. A target can define a module or a test suite. 21 | // Targets can depend on other targets in this package, and on products in packages this package depends on. 22 | .target( 23 | name: "SwiftUIFlows", 24 | dependencies: [ 25 | .product(name: "SwiftUIIntrospect", package: "swiftui-introspect") 26 | ]), 27 | .testTarget( 28 | name: "SwiftUIFlowsTests", 29 | dependencies: ["SwiftUIFlows"]), 30 | ] 31 | ) 32 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # SwiftUI Flows 2 | 3 | 4 | ![Simulator Screen Recording - iPhone 14 - 2023-10-02 at 21 46 04](https://github.com/lonkly/SwiftUI-Flows/assets/1292110/52e8b6de-edb0-4c9d-b00b-258a9ad946ea) 5 | 6 | 7 | 🚀 SwiftUIFlows: Ultimate Navigation for Apple Ecosystem 🍎 8 | 9 | Seamlessly present modal screens, popups, and more in SwiftUI, across iOS and Mac! 10 | 11 | 📱 What Can SwiftUIFlows Do? 12 | 13 | - Full-screen Displays: Dive into immersive content. 14 | - Sheet-styled Modals: Classic, yet elegant. 15 | - Custom-sized Modals: Your size, your rules. 16 | - Popovers: The cherry on top for contextual info. 17 | 18 | 🌟 Why Choose SwiftUIFlows? 19 | 20 | - Declarative & Clean: Say goodbye to scattered navigation logic and constant flag checking, like @State private var isPresentingMyScreen = false. 21 | - Streamlined Flows: Easy-to-write navigation flows that save you time and reduce boilerplate. No more manual callbacks and dismissals. 22 | - Multiple Modals: Show any number of modals in a view, and control their presentation and dismissal with ease. 23 | - Custom Popups: Design and present popups as unique as your app. 24 | 25 | 💡 Features At A Glance: 26 | 27 | - Light & Swift: Zero dependencies. Built with the KISS (Keep It Simple, Stupid) principle. 28 | - Cross-Platform: Designed for both iOS and Mac. 29 | - Supercharged Fullscreen & Popups: Uses ZStack for native, enhanced presentations. 30 | - Limitless Customization: Style it, modify it, make it yours. 31 | 32 | 33 | ## Simple FlowBuilder Example: 34 | 35 | ``` 36 | @MainActor class ExampleFlow: FlowBuilder { 37 | func presentSomePopup() { 38 | presentPopup(Example1View(showDismiss: true, flow: self)) 39 | } 40 | 41 | func presentFullScreen() { 42 | presentFullScreen(Example2View(showDismiss: true, flow: self)) 43 | } 44 | 45 | func presentAnotherPopup() { 46 | presentPopup(Example3View(showDismiss: true, flow: self)) 47 | } 48 | } 49 | ``` 50 | 51 | ## [Example Project](https://github.com/lonkly/SwiftUIFlows-Examples) 52 | ## Usage Example: 53 | 54 | ``` 55 | flow.presentSomePopup() // popup 56 | flow.presentFullScreen() // full-screen 57 | flow.presentAnotherPopup() // another popup 58 | } 59 | ``` 60 | 61 | ## More Avdanced FlowBuilder Example: 62 | ``` 63 | import SwiftUIFlows 64 | 65 | @MainActor class RootFlow: FlowBuilder { 66 | 67 | func showVerified(viewModel: AuthVM) { 68 | presentFullScreen( 69 | VerifiedView(viewModel: viewModel, completion: { [weak self] in 70 | self?.dismissFullScreen() 71 | }) 72 | ) 73 | } 74 | 75 | func showAnythingYouWant(view: AnyView) { 76 | presentFullScreen( 77 | view 78 | .onAppear { 79 | self.dismissFullScreen() 80 | } 81 | ) 82 | } 83 | } 84 | ``` 85 | 86 | ## Projects already using SwiftUI-Flows: 87 | 88 | [Stakes](https://apps.apple.com/us/app/stakes-predict-sports/id1564167571?shortlink=website&c=Website%20Button&pid=Website&af_channel=Website%20Button&source_caller=ui) 89 | 90 | ### Contributions and feature requests are welcome! 91 | -------------------------------------------------------------------------------- /Sources/SwiftUIFlows/Examples/Example+Preview.swift: -------------------------------------------------------------------------------- 1 | // 2 | // SwiftUIFlows.swift 3 | // Copyright [2023] [Vivienne Fosh] 4 | // 5 | // Created by Vivienne Fosh on 09.06.2023. 6 | // 7 | 8 | import Foundation 9 | import SwiftUI 10 | 11 | /// This is an example, showing that any view can hold it's own flow and be able to present other screens or popups I do not recommend passing flows to nested views as it creates unnecessary binding, but it is totally legal to do so, because FlowBuilder is a class. Provided that you have only 1 flow at a time it is safe to pass it through @EnvironmentObject 12 | struct ContentView: View { 13 | @StateObject var flow = ExampleFlow(isPresented: .constant(true)) 14 | 15 | @StateObject var anotherFlow = ExampleFlow(isPresented: .constant(true)) 16 | 17 | func presentAll() { 18 | 19 | flow.presentExample1() 20 | flow.presentExample2() 21 | anotherFlow.presentExample3() 22 | } 23 | 24 | var body: some View { 25 | 26 | VStack { 27 | 28 | HStack { 29 | VStack(alignment: .leading, spacing: 10) { 30 | Text("Root View") 31 | .font(.largeTitle) 32 | Text("shows fullscreen and 2 popups after delay. tap the button to invoke manually") 33 | .font(.title3) 34 | } 35 | .padding() 36 | .foregroundStyle(.black) 37 | 38 | Spacer() 39 | } 40 | 41 | Spacer() 42 | 43 | Button(action: { 44 | 45 | presentAll() 46 | 47 | }) { 48 | Text("Show Everything") 49 | .font(.title3) 50 | .tint(.black) 51 | .foregroundColor(.black) 52 | } 53 | .buttonStyle(.borderedProminent) 54 | .foregroundStyle(.black) 55 | 56 | 57 | Spacer() 58 | } 59 | 60 | .onAppear { 61 | // Task { 62 | // try? Task.sleep(nanoseconds: 3_000_000_000) 63 | // presentAll() 64 | // } 65 | } 66 | 67 | // This line is required for flow to present native iOS sheets 68 | .sheetFlow(flow) 69 | // This line is required for flow to present full-screen views 70 | .fullScreenFlow(flow) 71 | // This line is required for flow to present popovers. You can provide different configs for respective flows 72 | .popupFlow(flow, config: PopoverConfig( 73 | width: 320, 74 | height: 300, 75 | dismissOnTapOutside: { 76 | flow.dismissPopup() 77 | }, 78 | dismissBySwipeDown: { 79 | flow.dismissPopup() 80 | }, 81 | verticalAlignment: .center 82 | )) 83 | .popupFlow(anotherFlow, config: PopoverConfig( 84 | width: 180, 85 | height: 200, 86 | dismissOnTapOutside: { 87 | anotherFlow.dismissPopup() 88 | }, 89 | dismissBySwipeDown: { 90 | anotherFlow.dismissPopup() 91 | }, 92 | horizontalAlignment: .trailing, 93 | verticalAlignment: .top, 94 | offsetX: -20, 95 | offsetY: 10 96 | )) 97 | .background(Color.purple) 98 | 99 | } 100 | } 101 | 102 | @MainActor open class ExampleFlow: FlowBuilder { 103 | func presentExample1() { 104 | presentPopup( 105 | PopupExampleView(showDismissButton: true) 106 | .environmentObject(self) 107 | ) 108 | } 109 | 110 | /// only thing special about these methods is how you actually want to present you view - via popup, fullscreen or a modal sheet. 111 | func presentExample2() { 112 | presentFullScreen( 113 | FullscreenExampleView(showDismissButton: true) 114 | .environmentObject(self) 115 | ) 116 | } 117 | 118 | func presentExample3() { 119 | presentPopup( 120 | PopupExample2View(showDismissButton: true) 121 | .environmentObject(self) 122 | ) 123 | } 124 | } 125 | 126 | struct previewz: PreviewProvider { 127 | static var previews: some View { 128 | ContentView() 129 | } 130 | } 131 | 132 | -------------------------------------------------------------------------------- /Sources/SwiftUIFlows/Examples/FullScreenExampleView.swift: -------------------------------------------------------------------------------- 1 | // 2 | // File.swift 3 | // 4 | // 5 | // Created by Vivienne Fosh on 24.08.2023. 6 | // 7 | 8 | import SwiftUI 9 | 10 | struct FullscreenExampleView: View { 11 | var showDismissButton = true 12 | @EnvironmentObject var flow: ExampleFlow 13 | 14 | var body: some View { 15 | VStack { 16 | if showDismissButton { 17 | HStack { 18 | Spacer() 19 | Button { 20 | withAnimation { 21 | flow.dismissFullScreen() 22 | } 23 | } label: { 24 | Text("Dismiss") 25 | .foregroundColor(Color.black) 26 | } 27 | .buttonStyle(.borderedProminent) 28 | .padding() 29 | } 30 | } 31 | Spacer() 32 | 33 | 34 | Text("FullScreen View") 35 | .font(.largeTitle) 36 | .foregroundColor(Color.black) 37 | 38 | Spacer() 39 | } 40 | .onAppear { 41 | print("FullScreen appeared") 42 | } 43 | .onDisappear { 44 | print("FullScreen disappeared") 45 | } 46 | .foregroundStyle(Color.primary) 47 | .background(.yellow) 48 | } 49 | } 50 | 51 | // To see how pure View looks 52 | struct FullscreenExampleView_Preview: PreviewProvider { 53 | static var previews: some View { 54 | FullscreenExampleView() 55 | .environmentObject(ExampleFlow(isPresented: .constant(true))) 56 | } 57 | } 58 | -------------------------------------------------------------------------------- /Sources/SwiftUIFlows/Examples/PopoverExampleView.swift: -------------------------------------------------------------------------------- 1 | // 2 | // File.swift 3 | // 4 | // 5 | // Created by Vivienne Fosh on 24.08.2023. 6 | // 7 | 8 | import SwiftUI 9 | 10 | // Big popup in the center 11 | struct PopupExampleView: View { 12 | var showDismissButton = true 13 | @EnvironmentObject var flow: ExampleFlow 14 | @Environment(\.dismiss) var dismiss 15 | 16 | var body: some View { 17 | VStack { 18 | Spacer() 19 | //HStack { Spacer() } 20 | 21 | Text("Popup 1") 22 | .font(.title) 23 | .padding() 24 | 25 | Text("Drag a bit to move, or a lot to dismiss, or") 26 | .padding(.horizontal) 27 | .multilineTextAlignment(.center) 28 | 29 | if showDismissButton { 30 | HStack { 31 | Spacer() 32 | Button { 33 | withAnimation { 34 | flow.dismissPopup() 35 | } 36 | } label: { 37 | Text("Dismiss") 38 | .tint(.black) 39 | .foregroundColor(.black) 40 | } 41 | .buttonStyle(.borderedProminent) 42 | .foregroundStyle(Color.primary) 43 | Spacer() 44 | } 45 | } 46 | 47 | Spacer() 48 | } 49 | .onAppear { 50 | print("PopupExample1 appeared") 51 | } 52 | .onDisappear { 53 | print("PopupExample1 disappeared") 54 | } 55 | .background(.red) 56 | } 57 | } 58 | 59 | // Small Popover 60 | struct PopupExample2View: View { 61 | var showDismissButton = true 62 | @EnvironmentObject var flow: ExampleFlow 63 | @Environment(\.dismiss) var dismiss 64 | 65 | var body: some View { 66 | VStack { 67 | HStack { Spacer() } 68 | 69 | Spacer() 70 | 71 | Text("Popup 2") 72 | .font(.title) 73 | .padding() 74 | 75 | if showDismissButton { 76 | HStack { 77 | Spacer() 78 | 79 | Button { 80 | withAnimation { 81 | flow.dismissPopup() 82 | } 83 | } label: { 84 | Text("Dismiss") 85 | .tint(.black) 86 | .foregroundColor(Color.black) 87 | } 88 | .buttonStyle(.borderedProminent) 89 | .padding() 90 | 91 | Spacer() 92 | } 93 | } 94 | 95 | Spacer() 96 | } 97 | .onAppear { 98 | print("PopupExample2 appeared") 99 | } 100 | .onDisappear { 101 | print("PopupExample2 disappeared") 102 | } 103 | .background(Color(red: 20/255, green: 80/255, blue: 163/255)) 104 | } 105 | } 106 | 107 | // To see how pure View looks 108 | struct PopupExample2View_Preview: PreviewProvider { 109 | static var previews: some View { 110 | PopupExampleView() 111 | .environmentObject(ExampleFlow(isPresented: .constant(true))) 112 | PopupExample2View() 113 | .environmentObject(ExampleFlow(isPresented: .constant(true))) 114 | } 115 | } 116 | -------------------------------------------------------------------------------- /Sources/SwiftUIFlows/FlowBuilder+Dismiss.swift: -------------------------------------------------------------------------------- 1 | // 2 | // File.swift 3 | // Copyright [2023] [Vivienne Fosh] 4 | // 5 | // Created by Vivienne Fosh on 09.08.2023. 6 | // 7 | 8 | import Foundation 9 | import SwiftUI 10 | 11 | @MainActor public extension FlowBuilder { 12 | 13 | @MainActor private func dismissFromTop(of presentations: inout [AnyView]) { 14 | withAnimation { 15 | if !presentations.isEmpty { 16 | presentations.removeLast() 17 | } else { 18 | isPresented.wrappedValue = false 19 | } 20 | } 21 | } 22 | 23 | /// Dismisses top-level popup from your View. 24 | @MainActor func dismissPopup() { 25 | dismissFromTop(of: &presentingPopups) 26 | } 27 | 28 | /// Dismisses top-level modal full-screen from your View. 29 | @MainActor func dismissFullScreen() { 30 | dismissFromTop(of: &presentingFullScreens) 31 | } 32 | 33 | /// Dismisses top-level modal sheet from your View. 34 | func dismissSheet() { 35 | _ = presentingSheets.popLast() 36 | } 37 | 38 | } 39 | -------------------------------------------------------------------------------- /Sources/SwiftUIFlows/FlowBuilder+Present.swift: -------------------------------------------------------------------------------- 1 | // 2 | // FlowBuilder+Present.swift 3 | // Copyright [2023] [Vivienne Fosh] 4 | // 5 | // Created by Vivienne Fosh on 09.08.2023. 6 | // 7 | 8 | import Foundation 9 | import SwiftUI 10 | 11 | /// This extension provides a wrapper, that determines how your router will present the View 12 | public extension FlowBuilder { 13 | 14 | /// Present as a native iOS sheet with animation 15 | @MainActor func presentSheet(_ view: V) { 16 | presentingSheets.append(AnyView(view)) 17 | } 18 | 19 | /// Present as a full-screen 20 | @MainActor func presentFullScreen(_ view: V) { 21 | presentingFullScreens.append(AnyView(view)) 22 | } 23 | 24 | /// Present as a popup 25 | @MainActor func presentPopup(_ view: V) { 26 | presentingPopups.append(AnyView(view)) 27 | } 28 | } 29 | -------------------------------------------------------------------------------- /Sources/SwiftUIFlows/FlowBuilder.swift: -------------------------------------------------------------------------------- 1 | // 2 | // FlowBuilder.swift 3 | // Copyright [2023] [Vivienne Fosh] 4 | // 5 | // Created by Vivienne Fosh on 05.06.2023. 6 | // 7 | 8 | import Foundation 9 | import SwiftUI 10 | 11 | @MainActor open class FlowBuilder: ObservableObject { 12 | @Published var presentingSheets: [AnyView] = [] 13 | @Published var presentingFullScreens: [AnyView] = [] 14 | @Published var presentingPopups: [AnyView] = [] 15 | 16 | @Published var isPresented: Binding 17 | 18 | var currentSheetIndex: Int? { 19 | presentingSheets.isEmpty ? nil : presentingSheets.count - 1 20 | } 21 | 22 | var currentPopoverIndex: Int? { 23 | presentingPopups.isEmpty ? nil : presentingPopups.count - 1 24 | } 25 | 26 | var currentFullscreenIndex: Int? { 27 | presentingFullScreens.isEmpty ? nil : presentingFullScreens.count - 1 28 | } 29 | 30 | public init(isPresented: Binding) { 31 | self.isPresented = isPresented 32 | } 33 | 34 | public func addPopup(_ view: AnyView) { 35 | presentingPopups.append(view) 36 | } 37 | 38 | public func addFullScreen(_ view: AnyView) { 39 | presentingFullScreens.append(view) 40 | } 41 | 42 | public func addSheet(_ view: AnyView) { 43 | presentingSheets.append(view) 44 | } 45 | } 46 | -------------------------------------------------------------------------------- /Sources/SwiftUIFlows/FlowLifecycle.swift: -------------------------------------------------------------------------------- 1 | // 2 | // FlowLifecycle.swift 3 | // Copyright [2023] [Vivienne Fosh] 4 | // 5 | // Created by Vivienne Fosh on 09.08.2023. 6 | // 7 | 8 | import Foundation 9 | import SwiftUI 10 | 11 | /// Closures won't really work, because there is no way to efficiently update them alongside the View, therefore OnAppear and OnDisappear are provided 12 | extension View { 13 | func fullscreenOnAppear(_ block: @escaping () -> Void) -> some View { 14 | environment(\.fullScreensOnAppear, block) 15 | } 16 | 17 | func fullscreenOnDisappear(_ block: @escaping () -> Void) -> some View { 18 | environment(\.fullScreensOnDisappear, block) 19 | } 20 | } 21 | 22 | /// By default we do nothing. 23 | private struct AppearKey: EnvironmentKey { 24 | static let defaultValue: (() -> Void) = { } 25 | } 26 | 27 | private struct DisappearKey: EnvironmentKey { 28 | static let defaultValue: (() -> Void) = { } 29 | } 30 | 31 | 32 | /// These methods will fire on Every onAppear / onDisappear of Every full-screen/ popup / sheet that participates in the flow. 33 | /// I strongly recommend that for general use-cases you still write separate onAppear/onDisappear logic. 34 | extension EnvironmentValues { 35 | var fullScreensOnAppear: () -> Void { 36 | get { self[AppearKey.self] } 37 | set { self[AppearKey.self] = newValue } 38 | } 39 | 40 | var fullScreensOnDisappear: () -> Void { 41 | get { self[DisappearKey.self] } 42 | set { self[DisappearKey.self] = newValue } 43 | } 44 | 45 | var popupsOnAppear: () -> Void { 46 | get { self[AppearKey.self] } 47 | set { self[AppearKey.self] = newValue } 48 | } 49 | 50 | var popupsOnDisappear: () -> Void { 51 | get { self[DisappearKey.self] } 52 | set { self[DisappearKey.self] = newValue } 53 | } 54 | } 55 | -------------------------------------------------------------------------------- /Sources/SwiftUIFlows/Flows/FullScreenFlow.swift: -------------------------------------------------------------------------------- 1 | // 2 | // FullScreenFlow.swift 3 | // Copyright [2023] [Vivienne Fosh] 4 | // 5 | // Created by Vivienne Fosh on 09.06.2023. 6 | // 7 | 8 | import Foundation 9 | import SwiftUI 10 | import SwiftUIIntrospect 11 | #if canImport(UIKit) 12 | import UIKit 13 | #elseif canImport(AppKit) 14 | import AppKit 15 | #endif 16 | 17 | struct FullScreenFlowModifier: ViewModifier { 18 | @ObservedObject var builder: FlowBuilder 19 | 20 | #if os(iOS) 21 | @State private var tabBar: UITabBar? 22 | #endif 23 | 24 | @Environment(\.fullScreensOnAppear) var onAppear 25 | @Environment(\.fullScreensOnDisappear) var onDisappear 26 | 27 | func body(content: Content) -> some View { 28 | ZStack { 29 | content 30 | 31 | if #available(iOS 16.0, *) { 32 | overlay 33 | .toolbar(.hidden) 34 | .onAppear { onAppear() } 35 | .onDisappear { onDisappear() } 36 | .transition(.move(edge: .bottom).combined(with: .opacity)) 37 | } else { 38 | overlay 39 | #if os(iOS) 40 | .introspect(.tabView, on: .iOS(.v15)) { tabbarVC in 41 | tabBar = tabbarVC.tabBar 42 | tabBar?.isHidden = true 43 | 44 | } 45 | #endif 46 | .onAppear { onAppear() } 47 | .onDisappear { 48 | #if os(iOS) 49 | tabBar?.isHidden = false 50 | #endif 51 | onDisappear() 52 | } 53 | .transition(.move(edge: .bottom).combined(with: .opacity)) 54 | } 55 | 56 | } 57 | } 58 | 59 | @ViewBuilder 60 | var overlay: some View { 61 | if let presentingView = builder.currentFullScreenView { 62 | presentingView 63 | .frame(maxWidth: .infinity, maxHeight: .infinity) 64 | .ignoresSafeArea(.all, edges: .bottom) 65 | .zIndex(100) 66 | 67 | } 68 | } 69 | } 70 | 71 | extension FlowBuilder { 72 | var currentFullScreenView: AnyView? { 73 | guard let idx = currentFullscreenIndex else { return nil } 74 | return presentingFullScreens[idx] 75 | } 76 | } 77 | -------------------------------------------------------------------------------- /Sources/SwiftUIFlows/Flows/PopoverConfig.swift: -------------------------------------------------------------------------------- 1 | // 2 | // File.swift 3 | // 4 | // 5 | // Created by Vivienne Fosh on 24.08.2023. 6 | // 7 | 8 | import SwiftUI 9 | 10 | public struct PopoverConfig { 11 | var width: CGFloat 12 | var height: CGFloat 13 | 14 | var transition: AnyTransition 15 | var backgroundColor: Color 16 | 17 | var dismissOnTapOutside: (() -> Void)? 18 | var dismissBySwipe: (() -> Void)? 19 | 20 | var corners: RectCorner 21 | var cornerRadius: CGFloat 22 | 23 | var shadowColor: Color 24 | var shadowRadius: CGFloat 25 | var shadowOffX: CGFloat 26 | var shadowOffY: CGFloat 27 | 28 | var animation: Animation 29 | 30 | var horizontalAlignment: HorizontalAlignment 31 | var verticalAlignment: VerticalAlignment 32 | 33 | var alignment: Alignment { 34 | Alignment(horizontal: horizontalAlignment, vertical: verticalAlignment) 35 | } 36 | 37 | var offsetX: CGFloat 38 | var offsetY: CGFloat 39 | 40 | var onTapPopover: (() -> Void)? 41 | 42 | 43 | var borderColor: Color 44 | var borderWidth: CGFloat 45 | 46 | var contentPadding: EdgeInsets 47 | 48 | var backgroundBlurRadius: CGFloat 49 | 50 | var isDraggable: Bool 51 | 52 | var dragRestrictions: DragRestrictions = [.all] // Assuming you'd define a DragRestrictions type 53 | 54 | var overlayColor: Color 55 | 56 | var interactiveDismissThreshold: CGFloat 57 | 58 | public init(width: CGFloat, 59 | height: CGFloat, 60 | transition: AnyTransition = .move(edge: .bottom).combined(with: .opacity), 61 | backgroundColor: Color = .black.opacity(0.5), 62 | dismissOnTapOutside: (() -> Void)? = nil, 63 | dismissBySwipeDown: (() -> Void)? = nil, 64 | corners: RectCorner = [.topLeft, .topRight, .bottomLeft, .bottomRight], 65 | cornerRadius: CGFloat = 12, 66 | 67 | shadowColor: Color = .black.opacity(0.12), 68 | shadowRadius: CGFloat = 8, 69 | shadowOffX: CGFloat = 0, 70 | shadowOffY: CGFloat = -1, 71 | 72 | animation: Animation = .default, 73 | 74 | horizontalAlignment: HorizontalAlignment = .center, 75 | verticalAlignment: VerticalAlignment = .bottom, 76 | 77 | offsetX: CGFloat = 0, 78 | offsetY: CGFloat = 0, 79 | 80 | onTapPopover: (() -> Void)? = nil, 81 | borderColor: Color = .clear, 82 | borderWidth: CGFloat = 0, 83 | contentPadding: EdgeInsets = .init(top: 8, leading: 8, bottom: 8, trailing: 8), 84 | backgroundBlurRadius: CGFloat = 0, 85 | isDraggable: Bool = true, 86 | dragRestrictions: DragRestrictions = [.all], 87 | 88 | overlayColor: Color = .black.opacity(0.3), 89 | interactiveDismissThreshold: CGFloat = 50 90 | ) { 91 | self.width = width 92 | self.height = height 93 | self.transition = transition 94 | self.backgroundColor = backgroundColor 95 | self.dismissOnTapOutside = dismissOnTapOutside 96 | self.dismissBySwipe = dismissBySwipeDown 97 | self.corners = corners 98 | self.cornerRadius = cornerRadius 99 | self.shadowColor = shadowColor 100 | self.shadowRadius = shadowRadius 101 | self.shadowOffX = shadowOffX 102 | self.shadowOffY = shadowOffY 103 | self.animation = animation 104 | self.horizontalAlignment = horizontalAlignment 105 | self.verticalAlignment = verticalAlignment 106 | self.offsetX = offsetX 107 | self.offsetY = offsetY 108 | self.onTapPopover = onTapPopover 109 | self.borderColor = borderColor 110 | self.borderWidth = borderWidth 111 | self.contentPadding = contentPadding 112 | self.backgroundBlurRadius = backgroundBlurRadius 113 | self.isDraggable = isDraggable 114 | self.dragRestrictions = dragRestrictions 115 | self.overlayColor = overlayColor 116 | self.interactiveDismissThreshold = interactiveDismissThreshold 117 | } 118 | } 119 | 120 | 121 | -------------------------------------------------------------------------------- /Sources/SwiftUIFlows/Flows/PopoversFlow.swift: -------------------------------------------------------------------------------- 1 | // 2 | // PopoverFlow.swift 3 | // Copyright [2023] [Vivienne Fosh] 4 | // 5 | // Created by Vivienne Fosh on 26.06.2023. 6 | // 7 | 8 | import SwiftUI 9 | 10 | struct PopoverFlowModifier: ViewModifier { 11 | 12 | let config: PopoverConfig 13 | 14 | @State private var animationValue = false 15 | @State private var dragOffset = CGSize.zero 16 | 17 | @ObservedObject var builder: FlowBuilder 18 | 19 | func body(content: Content) -> some View { 20 | ZStack(alignment: .bottom) { 21 | content 22 | presentedView 23 | } 24 | } 25 | 26 | @ViewBuilder 27 | var presentedView: some View { 28 | if let presentingView = builder.currentPopoverView { 29 | ZStack(alignment: config.alignment) { 30 | config.backgroundColor 31 | .ignoresSafeArea() 32 | .zIndex(6668) 33 | .onTapGesture { 34 | withAnimation { 35 | animationValue = false 36 | } 37 | config.dismissOnTapOutside?() 38 | } 39 | .transition(config.transition) 40 | .animation(config.animation, value: animationValue) 41 | 42 | presentingView 43 | .frame(width: config.width, height: config.height) 44 | .padding(config.contentPadding) 45 | .background( 46 | RoundedRectangle(cornerRadius: config.cornerRadius) 47 | .strokeBorder(config.borderColor, lineWidth: config.borderWidth) 48 | ) 49 | .shadow(color: config.shadowColor, 50 | radius: config.shadowRadius, 51 | x: config.shadowOffX, 52 | y: config.shadowOffY) 53 | 54 | .roundedCorners(radius: config.cornerRadius, corners: config.corners) 55 | .zIndex(6669) // always on top 56 | .scaleEffect(animationValue ? 1 : 0) 57 | .animation(config.animation, value: animationValue) 58 | .transition(config.transition) 59 | .gesture((config.isDraggable || (config.dismissBySwipe != nil)) ? 60 | DragGesture(minimumDistance: 10 , coordinateSpace: .local) 61 | .onChanged { value in 62 | if config.dismissBySwipe != nil || config.isDraggable { 63 | if config.dragRestrictions.contains(.up) && value.translation.height < 0 { 64 | dragOffset.height += value.translation.height 65 | } 66 | if config.dragRestrictions.contains(.down) && value.translation.height > 0 { 67 | dragOffset.height += value.translation.height 68 | } 69 | if config.dragRestrictions.contains(.left) && value.translation.width < 0 { 70 | dragOffset.width += value.translation.width 71 | } 72 | if config.dragRestrictions.contains(.right) && value.translation.width > 0 { 73 | dragOffset.width += value.translation.width 74 | } 75 | } 76 | } 77 | .onEnded { val in 78 | guard config.dismissBySwipe != nil || config.isDraggable else { return } 79 | 80 | let exceededHeightThreshold = abs(val.translation.height + val.predictedEndTranslation.height) > config.interactiveDismissThreshold 81 | let exceededWidthThreshold = abs(val.translation.width + val.predictedEndTranslation.width) > config.interactiveDismissThreshold 82 | 83 | let swipeVertical = (config.dragRestrictions.contains(.up) || config.dragRestrictions.contains(.down)) && exceededHeightThreshold 84 | let swipeHorizontal = (config.dragRestrictions.contains(.left) || config.dragRestrictions.contains(.right)) && exceededWidthThreshold 85 | 86 | if swipeVertical || swipeHorizontal { 87 | withAnimation { 88 | animationValue = false 89 | } 90 | config.dismissBySwipe?() 91 | } 92 | } : nil 93 | ) 94 | .onAppear { 95 | withAnimation { 96 | animationValue = true 97 | } 98 | } 99 | .onDisappear { 100 | withAnimation { 101 | animationValue = false 102 | dragOffset = .zero 103 | } 104 | } 105 | .offset(x: config.offsetX + dragOffset.width, y: config.offsetY + dragOffset.height) 106 | .simultaneousGesture(TapGesture(count: 1).onEnded { config.onTapPopover?() } ) 107 | } 108 | } 109 | } 110 | } 111 | 112 | extension FlowBuilder { 113 | var currentPopoverView: AnyView? { 114 | guard let idx = currentPopoverIndex else { return nil } 115 | return presentingPopups[idx] 116 | } 117 | } 118 | -------------------------------------------------------------------------------- /Sources/SwiftUIFlows/Flows/SheetFlow.swift: -------------------------------------------------------------------------------- 1 | // 2 | // SheetFlow.swift 3 | // Copyright [2023] [Vivienne Fosh] 4 | // 5 | // Created by Vivienne Fosh on 09.06.2023. 6 | // 7 | 8 | import Foundation 9 | import SwiftUI 10 | 11 | extension Int: Identifiable { 12 | public var id: Int { self.hashValue } 13 | } 14 | 15 | struct SheetFlowModifier: ViewModifier { 16 | @ObservedObject var builder: FlowBuilder 17 | 18 | private var currentSheet: Binding { 19 | Binding( 20 | get: { 21 | return builder.currentSheetIndex 22 | }, 23 | set: { 24 | if $0 == nil { 25 | builder.dismissSheet() 26 | } 27 | } 28 | ) 29 | } 30 | 31 | func body(content: Content) -> some View { 32 | content 33 | .sheet(item: currentSheet, onDismiss: {}) { index in 34 | builder.presentingSheets[index] 35 | } 36 | } 37 | } 38 | -------------------------------------------------------------------------------- /Sources/SwiftUIFlows/View+FlowBuilder.swift: -------------------------------------------------------------------------------- 1 | // 2 | // View+FlowBuilder.swift 3 | // Copyright [2023] [Vivienne Fosh] 4 | // 5 | // Created by Vivienne Fosh on 09.08.2023. 6 | // 7 | 8 | import Foundation 9 | import SwiftUI 10 | 11 | /// This extension provides the hook method that your parent view, that stores that flow object should have, or the magic won't work. Add one for each type of flows you want to use. 12 | /// Basically what it does it creates bindings for all possible modals, so that you never have to 13 | public extension View { 14 | @MainActor func sheetFlow(_ builder: FlowBuilder) -> some View { 15 | return self.modifier(SheetFlowModifier(builder: builder)) 16 | } 17 | 18 | 19 | @MainActor func fullScreenFlow(_ builder: FlowBuilder) -> some View { 20 | self.modifier(FullScreenFlowModifier(builder: builder)) 21 | } 22 | 23 | 24 | @MainActor func popupFlow(_ builder: FlowBuilder, config: PopoverConfig) -> some View { 25 | return self.modifier(PopoverFlowModifier(config: config, builder: builder)) 26 | } 27 | } 28 | -------------------------------------------------------------------------------- /Sources/SwiftUIFlows/guts/DragRestrictions.swift: -------------------------------------------------------------------------------- 1 | // 2 | // File.swift 3 | // 4 | // 5 | // Created by Vivienne Fosh on 01.10.2023. 6 | // 7 | 8 | import Foundation 9 | 10 | public struct DragRestrictions: OptionSet { 11 | public let rawValue: Int 12 | 13 | public init(rawValue: Int) { 14 | self.rawValue = rawValue 15 | } 16 | 17 | public static let horizontal = DragRestrictions(rawValue: 1 << 0) 18 | public static let vertical = DragRestrictions(rawValue: 1 << 1) 19 | public static let left = DragRestrictions(rawValue: 1 << 2) 20 | public static let right = DragRestrictions(rawValue: 1 << 3) 21 | public static let up = DragRestrictions(rawValue: 1 << 4) 22 | public static let down = DragRestrictions(rawValue: 1 << 5) 23 | 24 | // Convenience groupings 25 | public static let all: DragRestrictions = [.horizontal, .vertical] 26 | public static let horizontalOnly: DragRestrictions = [.left, .right] 27 | public static let verticalOnly: DragRestrictions = [.up, .down] 28 | } 29 | -------------------------------------------------------------------------------- /Sources/SwiftUIFlows/guts/View+RoundedCorners.swift: -------------------------------------------------------------------------------- 1 | // 2 | // View+RoundedCorners.swift 3 | // Copyright [2023] [Vivienne Fosh] 4 | // 5 | // Created by Vivienne Fosh on 09.08.2023. 6 | // 7 | 8 | import Foundation 9 | import SwiftUI 10 | 11 | public struct RectCorner: OptionSet, Sendable { 12 | 13 | public let rawValue: Int 14 | 15 | public static let topLeft = RectCorner(rawValue: 1 << 0) 16 | public static let topRight = RectCorner(rawValue: 1 << 1) 17 | public static let bottomRight = RectCorner(rawValue: 1 << 2) 18 | public static let bottomLeft = RectCorner(rawValue: 1 << 3) 19 | 20 | public static let allCorners: RectCorner = [.topLeft, topRight, .bottomLeft, .bottomRight] 21 | 22 | public init(rawValue: Int) { 23 | self.rawValue = rawValue 24 | } 25 | } 26 | 27 | 28 | public struct RoundedCornersShape: Shape { 29 | 30 | var radius: CGFloat = .zero 31 | var corners: RectCorner = .allCorners 32 | 33 | public func path(in rect: CGRect) -> Path { 34 | var path = Path() 35 | 36 | let p1 = CGPoint(x: rect.minX, y: corners.contains(.topLeft) ? rect.minY + radius : rect.minY ) 37 | let p2 = CGPoint(x: corners.contains(.topLeft) ? rect.minX + radius : rect.minX, y: rect.minY ) 38 | 39 | let p3 = CGPoint(x: corners.contains(.topRight) ? rect.maxX - radius : rect.maxX, y: rect.minY ) 40 | let p4 = CGPoint(x: rect.maxX, y: corners.contains(.topRight) ? rect.minY + radius : rect.minY ) 41 | 42 | let p5 = CGPoint(x: rect.maxX, y: corners.contains(.bottomRight) ? rect.maxY - radius : rect.maxY ) 43 | let p6 = CGPoint(x: corners.contains(.bottomRight) ? rect.maxX - radius : rect.maxX, y: rect.maxY ) 44 | 45 | let p7 = CGPoint(x: corners.contains(.bottomLeft) ? rect.minX + radius : rect.minX, y: rect.maxY ) 46 | let p8 = CGPoint(x: rect.minX, y: corners.contains(.bottomLeft) ? rect.maxY - radius : rect.maxY ) 47 | 48 | 49 | path.move(to: p1) 50 | path.addArc(tangent1End: CGPoint(x: rect.minX, y: rect.minY), 51 | tangent2End: p2, 52 | radius: radius) 53 | path.addLine(to: p3) 54 | path.addArc(tangent1End: CGPoint(x: rect.maxX, y: rect.minY), 55 | tangent2End: p4, 56 | radius: radius) 57 | path.addLine(to: p5) 58 | path.addArc(tangent1End: CGPoint(x: rect.maxX, y: rect.maxY), 59 | tangent2End: p6, 60 | radius: radius) 61 | path.addLine(to: p7) 62 | path.addArc(tangent1End: CGPoint(x: rect.minX, y: rect.maxY), 63 | tangent2End: p8, 64 | radius: radius) 65 | path.closeSubpath() 66 | 67 | return path 68 | } 69 | } 70 | 71 | public extension View { 72 | func roundedCorners(radius: CGFloat, corners: RectCorner) -> some View { 73 | clipShape( RoundedCornersShape(radius: radius, corners: corners) ) 74 | } 75 | } 76 | -------------------------------------------------------------------------------- /Tests/SwiftUIFlowsTests/SwiftUIFlowsTests.swift: -------------------------------------------------------------------------------- 1 | import XCTest 2 | @testable import SwiftUIFlows 3 | 4 | final class SwiftUIFlowsTests: XCTestCase { 5 | func testExample() throws { 6 | } 7 | } 8 | --------------------------------------------------------------------------------