OpenBrowserHomeTransition.swift 2.83 KB
//
//  OpenBrowserHomeTransition.swift
//  browser
//
//  Created by Artem Talko on 23.11.2023.
//

import UIKit

final class OpenBrowserHomeTransition: NSObject, UIViewControllerAnimatedTransitioning {
    private var operation: UINavigationController.Operation
    
    init( operation: UINavigationController.Operation ) {
        self.operation = operation
        
        super.init()
    }
    
    func transitionDuration(using transitionContext: UIViewControllerContextTransitioning?) -> TimeInterval {
        return 0.5
    }
    
    func animateTransition(using transitionContext: UIViewControllerContextTransitioning) {
        guard let toController = transitionContext.viewController(forKey: .to),
              let fromController = transitionContext.viewController(forKey: .from) else {
            transitionContext.completeTransition(true)
            return
        }
        switch operation {
        case .push :
            pushController(fromController: fromController, toController: toController, transitionContext: transitionContext)
        case .pop:
            print("error: VC was popped")
            break
        case .none:
            transitionContext.completeTransition(true)
            return
        @unknown default:
            break
        }
    }
}

extension OpenBrowserHomeTransition {
    private func pushController(fromController: UIViewController, toController: UIViewController, transitionContext: UIViewControllerContextTransitioning) {
        let container = transitionContext.containerView
        
        if let browserHomeViewController = toController as? BrowserHomeViewController {
            toController.view.frame = CGRect(x: 0, y: container.bounds.height, width: container.bounds.width, height: container.bounds.height)
            
            container.addSubview(toController.view)
            
            UIView.animate(withDuration: transitionDuration(using: transitionContext), animations: {
                toController.view.frame = container.bounds
                fromController.view.alpha = 0.5
            }, completion: { _ in
                transitionContext.completeTransition(!transitionContext.transitionWasCancelled)
                fromController.view.alpha = 1.0
            })
        } else {
            toController.view.frame = CGRect(x: 0, y: -toController.view.frame.height, width: toController.view.frame.width, height: toController.view.frame.height)
            
            container.addSubview(toController.view)
            
            UIView.animate(withDuration: transitionDuration(using: transitionContext), animations: {
                toController.view.frame = CGRect(x: 0, y: 0, width: toController.view.frame.width, height: toController.view.frame.height)
            }, completion: { _ in
                transitionContext.completeTransition(true)
            })
        }
       
    }
}