frzi / swiftui-router

Path-based routing in SwiftUI
MIT License
900 stars 43 forks source link

Navigation transition direction parameter #26

Closed Escapado closed 3 years ago

Escapado commented 3 years ago

Hi,

We are using SwiftUIRouter in our application but some usecases came up where we programmatically route using navigator.navigate and would like to have control over the resulting NavigationActions direction since we use that to animate the route transition and sometimes we want to go 'deeper' but route-wise the code will classify it as 'sideways'. An example would be navigating from /auth/login to /auth/reset/mail to reset/auth/reset/confirm where we would like to go .deeper in that order and .higher in reverse.

Maybe navigator.navigate could accept an optional direction parameter to override the default behaviour. @frzi let me know what you think. In case this is a good idea I'd be happy to open a PR if it helps.

frzi commented 3 years ago

Truth be told I'm not very keen on being able to override expected behaviour of the framework. Being able to override the direction with Navigator.navigate(to:) means we'd also have to take this in account with Navigator.goBack and Navigator.goForward. Most of all the thought of NavigationAction.direction being unpredictable doesn't sit well with me.

If you're not satisfied with the logic of NavigationAction.direction you can easily add your own: 😄

extension NavigationAction {
    public var alternativeDirection: Direction {
        let currentComponents = currentPath.split(separator: "/")
        let previousComponents = previousPath.split(separator: "/")

        if currentComponents.count > previousComponents.count {
            return .deeper
        }
        else if currentComponents.count == previousComponents.count {
            return .sideways
        }
        else {
            return .higher
        }
    }
}

In this case instead of navigator.lastAction?.direction you'd use navigator.lastAction?.alternativeDirection

Escapado commented 3 years ago

Thank you so much for your quick reply. That's totally fair and we will go with an extension just as you suggested. :)