import 'package:flutter/physics.dart';
import 'package:flutter/widgets.dart';

PageRouteBuilder springPageRoute(Widget page) {
  return PageRouteBuilder(
    pageBuilder: (_, __, ___) => page,
    transitionDuration: const Duration(milliseconds: 1500),
    reverseTransitionDuration: const Duration(milliseconds: 500),
    transitionsBuilder: (context, animation, secondaryAnimation, child) {
      final spring = SpringDescription(mass: 1, stiffness: 100, damping: 15);

      final curvedAnimation = animation.drive(
        Tween<double>(begin: 0.0, end: 1.0).chain(CurveTween(curve: _SpringCurve(spring))),
      );

      final offsetAnimation = Tween<Offset>(
        begin: const Offset(-1.0, 0.0), // slide from left
        end: Offset.zero,
      ).animate(curvedAnimation);

      return SlideTransition(
        position: offsetAnimation,
        child: child,
      );
    },
  );
}

class _SpringCurve extends Curve {
  final SpringDescription spring;

  _SpringCurve(this.spring);

  @override
  double transform(double t) {
    final sim = SpringSimulation(spring, 0, 1, 0);
    return sim.x(t * 1.5); // scale time so it completes properly
  }
}
