import 'dart:math' as math; import 'dart:ui' as ui; import 'package:flutter/material.dart'; import 'package:flutter/physics.dart'; import 'package:flutter/scheduler.dart'; import 'glass_refraction.dart'; class GlassDock extends StatefulWidget { const GlassDock({ super.key, required this.selectedIndex, required this.onSelected, }); final int selectedIndex; final ValueChanged onSelected; @override State createState() => _GlassDockState(); } class _GlassDockState extends State with TickerProviderStateMixin { static const _height = 58.0, _inset = 3.0; double _width = 264; double get _travel => (_width - _inset * 2) / 3; static const _blue = Color(0xFF007AFF); late final AnimationController _motion = AnimationController.unbounded( vsync: this, value: widget.selectedIndex.toDouble(), ); late final AnimationController _press = AnimationController.unbounded( vsync: this, value: 0, ); late final AnimationController _tap = AnimationController( vsync: this, duration: const Duration(milliseconds: 620), ); late final AnimationController _sway = AnimationController.unbounded( vsync: this, ); late final AnimationController _ripple = AnimationController( vsync: this, duration: const Duration(milliseconds: 620), ); void _wakeRipple() { if (!_reduceMotion && !_ripple.isAnimating) _ripple.forward(from: 0); } double _swayTarget = 0, _swayVelocity = 0, _dragTarget = 0, _dragVelocity = 0; Duration? _elasticLastTick; late final Ticker _elasticTicker = createTicker(_tickElastic); void _startElastic() { if (!_elasticTicker.isActive) { _elasticLastTick = null; _elasticTicker.start(); } } // Keep one clock alive while input changes its targets. Restarting a spring // on every pointer event repeatedly paints t=0 under continuous dragging. void _tickElastic(Duration elapsed) { final seconds = _elasticLastTick == null ? 1 / 60 : ((elapsed - _elasticLastTick!).inMicroseconds / 1000000).clamp( 0.0, 0.25, ); _elasticLastTick = elapsed; if (_drag == null) { _swayTarget = _tap.isAnimating ? (_motion.velocity / 14).clamp(-0.85, 0.85) : 0; } final sway = _advanceSpring( _sway.value, _swayVelocity, _swayTarget, 220, 18, seconds, ); final drag = _advanceSpring( _dragFollow.value, _dragVelocity, _dragTarget, 680, 28, seconds, ); _swayVelocity = sway.$2; _dragVelocity = drag.$2; _sway.value = sway.$1; _dragFollow.value = drag.$1; if (!_tap.isAnimating && (_sway.value - _swayTarget).abs() < 0.0005 && _swayVelocity.abs() < 0.005 && (_dragFollow.value - _dragTarget).abs() < 0.0005 && _dragVelocity.abs() < 0.005) { _sway.value = _swayTarget; _dragFollow.value = _dragTarget; _swayVelocity = _dragVelocity = 0; _elasticTicker.stop(); _elasticLastTick = null; } } (double, double) _advanceSpring( double value, double velocity, double target, double stiffness, double damping, double seconds, ) { final steps = math.max(1, (seconds * 120).ceil()); final step = seconds / steps; for (var i = 0; i < steps; i++) { velocity += (stiffness * (target - value) - damping * velocity) * step; value += velocity * step; } return (value, velocity); } void _swayTo(double target) { _swayTarget = _reduceMotion ? 0 : target; if (_reduceMotion) { _sway.value = 0; _swayVelocity = 0; return; } _startElastic(); } bool _reduceMotion = false; late int _targetIndex; @override void initState() { super.initState(); _targetIndex = widget.selectedIndex; _dragTarget = widget.selectedIndex.toDouble(); } double get _pressure => _press.value.clamp(0.0, 1.18); double get _tapBloom { if (_reduceMotion) return 0; final t = _tap.value; final tail = t <= 0.5 ? 1.0 : Curves.easeInOut.transform((2 * (1 - t)).clamp(0.0, 1.0)); return math.sin(math.pi * t) * tail; } void _pressTo(double target) { if (_reduceMotion) { _press.value = target; return; } _press.animateWith( SpringSimulation( const SpringDescription(mass: 1, stiffness: 440, damping: 17), _press.value, target, _press.velocity, ), ); } @override void didChangeDependencies() { super.didChangeDependencies(); _reduceMotion = MediaQuery.disableAnimationsOf(context); if (_reduceMotion) { _motion.value = widget.selectedIndex.toDouble(); _press.value = 0; _tap.value = 0; _ripple.value = 0; _elasticTicker.stop(); _elasticLastTick = null; _swayTarget = _swayVelocity = _dragVelocity = 0; _dragTarget = _drag ?? widget.selectedIndex.toDouble(); _dragFollow.value = _drag ?? widget.selectedIndex.toDouble(); _sway.value = 0; } } late final AnimationController _dragFollow = AnimationController.unbounded( vsync: this, value: widget.selectedIndex.toDouble(), ); void _followDragTo(double target) { _dragTarget = target; if (_reduceMotion) { _dragFollow.value = target; _dragVelocity = 0; return; } _startElastic(); } double? _drag; double _dragSpeed = 0; double get _position => (_drag != null ? _dragFollow.value : _motion.value).clamp(-0.12, 2.12); void _moveTo(int index, {double velocity = 0, bool springyTap = false}) { _targetIndex = index; if (_reduceMotion) { _motion.value = index.toDouble(); return; } _motion.animateWith( SpringSimulation( springyTap ? const SpringDescription(mass: 1, stiffness: 350, damping: 20) : const SpringDescription(mass: 1, stiffness: 360, damping: 26), _position, index.toDouble(), velocity, ), ); } void _select(int index, {bool elastic = false, double velocity = 0}) { final position = _position; final releaseVelocity = elastic ? velocity.clamp(-8.0, 8.0) : _motion.velocity; setState(() => _drag = null); _motion.value = position; _moveTo(index, velocity: releaseVelocity, springyTap: !elastic); // Retarget the position spring without resetting an in-flight size pulse. // Restarting that pulse at its peak made the glass edges jump on quick taps. if (!elastic && !_reduceMotion && !_tap.isAnimating) { _tap.forward(from: 0); } _pressTo(0); _swayTo(0); widget.onSelected(index); } @override void didUpdateWidget(GlassDock oldWidget) { super.didUpdateWidget(oldWidget); // The parent acknowledges onSelected with a rebuild. Restarting here used // to erase the release velocity and start a second spring for the same tab. if (widget.selectedIndex != _targetIndex && _drag == null) { _moveTo(widget.selectedIndex, velocity: _motion.velocity); } } @override void dispose() { _elasticTicker.dispose(); _motion.dispose(); _press.dispose(); _tap.dispose(); _sway.dispose(); _ripple.dispose(); _dragFollow.dispose(); super.dispose(); } Widget _glass({required Widget child, bool lens = false}) { final pressure = math.max(_pressure.clamp(0.0, 1.0), _tapBloom * 0.85); final content = CustomPaint( foregroundPainter: _GlassRimPainter(lens: lens, pressure: pressure), child: DecoratedBox( decoration: BoxDecoration( gradient: LinearGradient( begin: Alignment.topLeft, end: Alignment.bottomRight, colors: lens ? [ Color.lerp( const Color(0xFFA1A4AA).withValues(alpha: 0.28), const Color(0xFFD8DBE0).withValues(alpha: 0.0252), pressure, )!, Color.lerp( const Color(0xFF8E939B).withValues(alpha: 0.21), const Color(0xFFC3C7CE).withValues(alpha: 0.0144), pressure, )!, Color.lerp( const Color(0xFFB4B7BC).withValues(alpha: 0.26), const Color(0xFFE5E7EB).withValues(alpha: 0.0216), pressure, )!, ] : [ Colors.white.withValues(alpha: 0.29), const Color(0xFFFDFEFF).withValues(alpha: 0.17), Colors.white.withValues(alpha: 0.23), ], ), ), child: child, ), ); return ClipRRect( borderRadius: BorderRadius.circular(40), child: GlassRefraction( strength: lens ? 0.78 + pressure * 0.70 : 0.98, blurSigma: lens ? 1.6 - pressure * 0.6 : 1.5, child: content, ), ); } @override Widget build(BuildContext context) => LayoutBuilder( builder: (context, constraints) { _width = math.min( constraints.maxWidth, MediaQuery.sizeOf(context).width >= 600 ? 300.0 : 264.0, ); final viewport = MediaQuery.sizeOf(context).width; final availableWidth = math.min( viewport > 0 ? viewport : constraints.maxWidth, constraints.maxWidth, ); final edgeAllowance = math.max(0.0, (availableWidth - _width) / 2 - 8); return AnimatedBuilder( animation: Listenable.merge([ _motion, _press, _tap, _sway, _ripple, _dragFollow, ]), builder: (context, _) { final press = _pressure; final pulse = _reduceMotion ? 0.0 : math.sin(math.pi * _tap.value); // Travel stretches horizontally; landing squeezes then rebounds // vertically. Endpoints are zero so quick retargets remain continuous. final tapWave = _reduceMotion ? 0.0 : math.sin(2 * math.pi * _tap.value); final tapStretch = tapWave >= 0 ? tapWave * 0.24 : tapWave * 0.08; final tapRise = tapWave >= 0 ? -tapWave * 0.045 : -tapWave * 0.15; // Pointer movement wakes a finite ripple; pauses do not start idle loops. final dragWave = _reduceMotion ? 0.0 : math.sin(2 * math.pi * _ripple.value) * press.clamp(0.0, 1.0); final dragStretch = dragWave * (dragWave >= 0 ? 0.10 : 0.06); final tapInflate = _tapBloom * 0.30; final speed = _reduceMotion ? 0.0 : (_drag != null ? _dragSpeed : _motion.velocity).abs(); final stretch = (speed / 80).clamp(0.0, 0.08) + tapStretch + tapInflate + press * 0.30 + dragStretch; final lensWidth = _travel * (1 + stretch); final lensHeight = (_height - _inset * 2) * (1 + press * 0.31 + tapRise + tapInflate - dragWave * 0.08 - (speed / 180).clamp(0.0, 0.035)); // Resize real glass bounds: sampling stays aligned without scaling text. final sway = _reduceMotion ? 0.0 : _sway.value.clamp(-1.2, 1.2); final bodyGrowth = press * 12 + pulse * 7 + sway.abs() * 4; final bodyHeight = _height + press * 5 + pulse * 3 - sway.abs() * 0.8; final dockShift = sway * 8; final leadingPull = sway * 6; return SizedBox( width: _width, height: _height, child: Stack( clipBehavior: Clip.none, children: [ Positioned( left: dockShift, top: 0, width: _width, height: _height, child: DecoratedBox( decoration: BoxDecoration( borderRadius: BorderRadius.circular(40), boxShadow: [ BoxShadow( color: const Color(0xFF4C6078) .withValues(alpha: 0.05), blurRadius: 14, offset: const Offset(0, 4), ), ], ), child: Stack( clipBehavior: Clip.none, children: [ Positioned( left: -bodyGrowth / 2 + math.min(leadingPull, 0), top: (_height - bodyHeight) / 2, width: _width + bodyGrowth + leadingPull.abs(), height: bodyHeight, child: _glass(child: const SizedBox.expand()), ), Positioned( left: (_inset + _position * _travel - (lensWidth - _travel) / 2) .clamp( -edgeAllowance - dockShift, _width + edgeAllowance - dockShift - lensWidth, ), top: (_height - lensHeight) / 2, width: lensWidth, height: lensHeight, child: IgnorePointer( child: _glass( lens: true, child: const SizedBox.expand(), ), ), ), Positioned( left: _inset, right: _inset, top: _inset, bottom: _inset, child: Row( children: [ _item(0, Icons.calendar_month_rounded, '课表'), _item(1, Icons.assignment_rounded, '考试'), _item( 2, Icons.person_rounded, '个人设置', caption: '我的', ), ], ), ), ], ), ), ), ], ), ); }, ); }, ); Widget _item(int index, IconData icon, String label, {String? caption}) => Expanded( child: Semantics( label: label, button: true, selected: index == widget.selectedIndex, excludeSemantics: true, onTap: () => _select(index), child: GestureDetector( // Selection must not replace the symbol's active animation state. key: ValueKey('dock-item-$index'), behavior: HitTestBehavior.opaque, onTapDown: index == widget.selectedIndex ? (_) => _pressTo(_reduceMotion ? 0 : 1) : null, onTapCancel: () { if (_drag == null) _pressTo(0); }, onTap: () => _select(index), onHorizontalDragStart: index == widget.selectedIndex ? (_) { final start = _position.clamp(0.0, 2.0); _dragFollow.value = start; _dragTarget = start; _dragVelocity = _motion.velocity; _motion.stop(); _wakeRipple(); _pressTo(_reduceMotion ? 0 : 1); setState(() { _drag = start; _dragSpeed = 0; }); } : null, onHorizontalDragUpdate: index == widget.selectedIndex ? (details) => setState(() { _dragSpeed = details.delta.dx / _travel * 60; _wakeRipple(); _swayTo((_dragSpeed / 8).clamp(-1.0, 1.0)); _drag = (_drag! + details.delta.dx / _travel).clamp( 0.0, 2.0, ); _followDragTo(_drag!); }) : null, onHorizontalDragEnd: index == widget.selectedIndex ? (details) => _select( (_drag ?? _position).round().clamp(0, 2), elastic: true, velocity: _dragVelocity, ) : null, onHorizontalDragCancel: index == widget.selectedIndex ? () { if (!mounted) return; final position = _position; setState(() => _drag = null); _motion.value = position; _moveTo(widget.selectedIndex, velocity: _dragVelocity); _pressTo(0); _swayTo(0); } : null, child: Center( child: Column( mainAxisSize: MainAxisSize.min, children: [ AnimatedScale( scale: index == _position.round().clamp(0, 2) ? 1 + _pressure * 0.08 : 1, duration: const Duration(milliseconds: 130), child: _DockSymbol( active: (_position - index).abs() < 0.28, reduceMotion: _reduceMotion, child: Icon( icon, key: index == widget.selectedIndex ? const Key('dock-cursor') : null, size: 25, color: index == _position.round().clamp(0, 2) ? _blue : _blue.withValues(alpha: 0.72), shadows: [ Shadow( color: Colors.white.withValues( alpha: index == _position.round().clamp(0, 2) ? 0.60 : 0.38, ), blurRadius: 8, ), Shadow( color: Colors.white.withValues( alpha: index == _position.round().clamp(0, 2) ? 0.95 : 0.85, ), blurRadius: 2.8, ), Shadow( color: Colors.white.withValues( alpha: index == _position.round().clamp(0, 2) ? 0.34 : 0.22, ), blurRadius: 1.4, ), ], ), ), ), const SizedBox(height: 2), Flexible( child: FittedBox( fit: BoxFit.scaleDown, child: Text( caption ?? label, maxLines: 1, style: TextStyle( fontSize: 11, height: 1.1, fontWeight: FontWeight.w600, color: index == _position.round().clamp(0, 2) ? _blue : _blue.withValues(alpha: 0.62), ), ), ), ), ], ), ), ), ), ); } /// Plays once on entry. Remaining over a symbol does not restart its animation. class _DockSymbol extends StatefulWidget { const _DockSymbol({ required this.active, required this.reduceMotion, required this.child, }); final bool active, reduceMotion; final Widget child; @override State<_DockSymbol> createState() => _DockSymbolState(); } class _DockSymbolState extends State<_DockSymbol> with SingleTickerProviderStateMixin { late final AnimationController _bounce = AnimationController( vsync: this, duration: const Duration(milliseconds: 440), ); @override void didUpdateWidget(_DockSymbol oldWidget) { super.didUpdateWidget(oldWidget); if (widget.reduceMotion || !widget.active) { _bounce.value = 0; } else if (!oldWidget.active) { _bounce.forward(from: 0); } } @override void dispose() { _bounce.dispose(); super.dispose(); } @override Widget build(BuildContext context) => AnimatedBuilder( animation: _bounce, child: widget.child, builder: (context, child) { final lift = widget.reduceMotion ? 0.0 : math.sin(math.pi * _bounce.value); return Transform.translate( offset: Offset(0, -3.5 * lift), child: Transform.scale(scale: 1 + lift * 0.16, child: child), ); }, ); } /// A white, rounded bevel catches light around a translucent milky body. /// Highlights stay at the edge; the backdrop remains visible beneath the glass. class _GlassRimPainter extends CustomPainter { const _GlassRimPainter({required this.lens, required this.pressure}); final bool lens; final double pressure; @override void paint(Canvas canvas, Size size) { final edge = lens ? const Color(0xFF7B838F) : const Color(0xFF9CAABD); // A quiet grey selection at rest; the glossy lens rim returns on touch. final opacity = lens ? 0.25 + pressure * 0.75 : 1.0; final bounds = Offset.zero & size; final outer = RRect.fromRectAndRadius( bounds.deflate(0.7), Radius.circular(size.height / 2), ); final inner = RRect.fromRectAndRadius( bounds.deflate(2.2), Radius.circular(size.height / 2 - 1.5), ); canvas.drawRRect( outer, Paint() ..style = PaintingStyle.stroke ..strokeWidth = lens ? 1.2 : 1.6 ..maskFilter = MaskFilter.blur(BlurStyle.normal, lens ? 1.05 : 1.0) ..shader = ui.Gradient.linear( bounds.topLeft, bounds.bottomRight, [ Colors.white.withValues(alpha: (lens ? 0.24 : 0.42) * opacity), edge.withValues(alpha: 0.04 * opacity), Colors.white.withValues(alpha: (lens ? 0.14 : 0.30) * opacity), ], [0.0, 0.55, 1.0], ), ); canvas.drawRRect( outer, Paint() ..style = PaintingStyle.stroke ..strokeWidth = lens ? 0.85 : 0.65 ..shader = ui.Gradient.sweep( bounds.center, [ Colors.white.withValues(alpha: 0.84 * opacity), edge.withValues(alpha: (lens ? 0.30 : 0.15) * opacity), Colors.white.withValues(alpha: 0.10 * opacity), Colors.white.withValues(alpha: 0.82 * opacity), edge.withValues(alpha: 0.12 * opacity), Colors.white.withValues(alpha: 0.84 * opacity), ], [0.0, 0.18, 0.38, 0.60, 0.80, 1.0], TileMode.clamp, -math.pi / 2, math.pi * 1.5, ), ); canvas.drawRRect( inner, Paint() ..style = PaintingStyle.stroke ..strokeWidth = 0.35 ..shader = ui.Gradient.linear( bounds.topLeft, bounds.bottomRight, [ Colors.white.withValues(alpha: (lens ? 0.20 : 0.34) * opacity), edge.withValues(alpha: (lens ? 0.13 : 0.07) * opacity), Colors.white.withValues(alpha: (lens ? 0.28 : 0.40) * opacity), ], [0.0, 0.5, 1.0], ), ); final shine = Path() ..moveTo(size.height * 0.32, 4) ..quadraticBezierTo( size.width * 0.5, 1.8, size.width - size.height * 0.35, 4, ); canvas.drawPath( shine, Paint() ..style = PaintingStyle.stroke ..strokeCap = StrokeCap.round ..strokeWidth = 0.8 ..shader = ui.Gradient.linear( Offset.zero, Offset(size.width, 0), [ Colors.white.withValues(alpha: 0), Colors.white.withValues(alpha: 0.50 * opacity), Colors.white.withValues(alpha: 0), ], [0.0, 0.5, 1.0], ), ); } @override bool shouldRepaint(_GlassRimPainter oldDelegate) => oldDelegate.lens != lens || oldDelegate.pressure != pressure; }