Files
swiper/SWIPE_ANIMATIONS.md
Aodhan Collins 5e893a0c9d Bug fixes
2025-07-31 01:38:07 +01:00

12 KiB

Enhanced Swipe Animation System

A comprehensive physics-based animation system for the image swiper app, providing realistic swipe interactions with spring effects, momentum calculations, and dynamic visual feedback.

Overview

The enhanced swipe animation system consists of several key components:

  • SwipePhysics Engine: Core physics calculations for realistic motion
  • EnhancedSwipeCard: Advanced swipe card component with visual effects
  • SwipeIntegrationManager: Seamless switching between animation modes
  • Visual Effects System: Dynamic feedback during swipe gestures

Features

🎯 Physics-Based Animations

  • Spring Effects: Realistic spring-back animations when swipe threshold isn't met
  • Momentum Calculations: Velocity-based swipe detection and exit animations
  • Smooth Transitions: 60fps animations with proper GPU acceleration

🎨 Visual Feedback

  • Dynamic Blur: Motion blur effects based on swipe velocity
  • Color Shifts: Direction-based hue rotation for visual feedback
  • 3D Transforms: Enhanced perspective and rotation effects
  • Particle Effects: Trailing particles during swipe gestures

📱 Device Optimization

  • Adaptive Quality: Automatic animation quality adjustment based on device capabilities
  • Performance Monitoring: Real-time FPS tracking and optimization
  • Reduced Motion Support: Accessibility compliance for motion-sensitive users

⚙️ Customization

  • Multiple Modes: Original, Enhanced Lite, and Full Enhanced modes
  • User Settings: Configurable physics parameters and visual effects
  • Debug Tools: Performance metrics and state inspection

Architecture

Core Components

SwipePhysics Class

import { SwipePhysics } from './js/swipe-physics.js';

const physics = new SwipePhysics({
    springTension: 300,     // Spring stiffness
    springFriction: 30,     // Damping coefficient
    mass: 1,                // Object mass
    velocityThreshold: 0.5, // Minimum velocity for momentum
    momentumDecay: 0.95     // Momentum decay rate
});

Key Methods:

  • updatePosition(x, y, timestamp): Track position and calculate velocity
  • animateSpringTo(targetX, targetY, onUpdate, onComplete): Spring-back animation
  • animateMomentumExit(direction, onUpdate, onComplete): Momentum-based exit
  • getVelocityMagnitude(): Current velocity magnitude
  • hasSwipeMomentum(threshold): Check if swipe has sufficient momentum

EnhancedSwipeCard Component

import EnhancedSwipeCard from './components/enhanced-swipe-card.js';

const swipeCard = new EnhancedSwipeCard({
    container: document.querySelector('.swipe-container'),
    onSwipe: (direction) => console.log('Swiped:', direction),
    threshold: 100,
    velocityThreshold: 2,
    springTension: 280,
    springFriction: 25
});

Features:

  • Physics-based drag interactions
  • Enhanced 3D tilt effects
  • Visual feedback during swipes
  • Smooth loading animations
  • Performance optimizations

SwipeIntegrationManager

import { swipeIntegration } from './js/swipe-integration.js';

// Initialize with automatic mode detection
await swipeIntegration.initialize(container, onSwipe);

// Switch modes dynamically
await swipeIntegration.switchMode('enhanced');

// Update configuration
swipeIntegration.updateConfig({
    enablePhysics: true,
    enableVisualEffects: true,
    animationQuality: 'high'
});

Animation Modes

Original Mode

  • Use Case: Low-end devices, reduced motion preferences
  • Features: Basic swipe detection, simple CSS transitions
  • Performance: Minimal CPU/GPU usage

Enhanced Lite Mode

  • Use Case: Mobile devices, moderate performance
  • Features: Physics-based springs, reduced visual effects
  • Performance: Balanced performance and visual quality

Enhanced Mode

  • Use Case: Desktop, high-performance devices
  • Features: Full physics simulation, all visual effects
  • Performance: Maximum visual quality, GPU-accelerated

Physics Implementation

Spring Dynamics

The system uses Hooke's Law with damping for realistic spring behavior:

F = -kx - cv

Where:

  • F = Spring force
  • k = Spring tension (stiffness)
  • x = Displacement from rest position
  • c = Friction coefficient (damping)
  • v = Velocity

Velocity Tracking

Velocity is calculated using time-weighted sampling:

const velocity = (currentPosition - previousPosition) / deltaTime;

Multiple samples are averaged with recent values weighted more heavily for smooth velocity calculations.

Momentum-Based Actions

Swipe actions are triggered by either:

  1. Distance threshold: Displacement exceeds minimum distance
  2. Velocity threshold: Swipe velocity exceeds minimum speed

Visual Effects

Dynamic Blur

Motion blur is applied based on velocity magnitude:

filter: blur(${velocity * 0.1}px);

Color Temperature Shifts

Direction-based hue rotation provides visual feedback:

  • Left (Discard): Red shift (-30°)
  • Right (Keep): Green shift (120°)
  • Up (Favorite): Blue shift (240°)
  • Down (Review): Yellow shift (60°)

3D Transforms

Enhanced perspective transforms create depth:

transform: 
    perspective(1200px)
    rotateX(${rotationX}deg)
    rotateY(${rotationY}deg)
    translateZ(${depth}px)
    scale3d(${scale}, ${scale}, 1);

Performance Optimizations

GPU Acceleration

  • transform3d() for hardware acceleration
  • will-change property for optimization hints
  • backface-visibility: hidden to prevent flickering

Frame Rate Monitoring

// Automatic quality adjustment based on FPS
if (fps < 30 && animationQuality === 'high') {
    animationQuality = 'medium';
}

Memory Management

  • Particle system with limited count
  • Velocity history with bounded size
  • Automatic cleanup of animation frames

Configuration Options

Physics Parameters

{
    springTension: 300,        // Spring stiffness (50-500)
    springFriction: 30,        // Damping coefficient (10-50)
    mass: 1,                   // Object mass (0.5-2.0)
    velocityThreshold: 0.5,    // Minimum velocity for momentum
    momentumDecay: 0.95,       // Momentum decay rate (0.8-0.98)
    maxVelocity: 50,          // Maximum velocity clamp
    dampingRatio: 0.8,        // Overall damping (0.1-1.0)
    precision: 0.01,          // Animation stop precision
    maxDuration: 2000         // Maximum animation duration (ms)
}

Visual Effects

{
    maxBlur: 8,               // Maximum blur amount (px)
    maxOpacity: 0.3,          // Maximum opacity reduction
    colorShiftIntensity: 0.2, // Color shift strength
    particleCount: 20,        // Maximum particles
    enable3DTilt: true,       // Enable 3D tilt effects
    enableParticles: true,    // Enable particle trails
    enableHaptics: true       // Enable haptic feedback
}

Usage Examples

Basic Integration

import { swipeIntegration } from './js/swipe-integration.js';

document.addEventListener('DOMContentLoaded', async () => {
    const container = document.querySelector('.swipe-container');
    
    await swipeIntegration.initialize(container, (direction) => {
        console.log('Swiped:', direction);
        // Handle swipe action
    });
});

Custom Configuration

// Configure before initialization
swipeIntegration.updateConfig({
    enablePhysics: true,
    enableVisualEffects: true,
    animationQuality: 'high',
    springTension: 320,
    springFriction: 25
});

await swipeIntegration.initialize(container, onSwipe);

Mode Switching

// Switch to enhanced mode
await swipeIntegration.switchMode('enhanced');

// Switch to lite mode for performance
await swipeIntegration.switchMode('enhanced-lite');

// Fallback to original mode
await swipeIntegration.switchMode('original');

Settings Panel

import { createSwipeSettingsPanel } from './js/swipe-integration.js';

// Create settings panel
const settingsPanel = createSwipeSettingsPanel(swipeIntegration);
document.body.appendChild(settingsPanel);

Browser Compatibility

Supported Features

  • Modern Browsers: Full enhanced mode support
  • Safari: Full support with vendor prefixes
  • Mobile Browsers: Enhanced lite mode recommended
  • Legacy Browsers: Automatic fallback to original mode

Required APIs

  • requestAnimationFrame (required)
  • performance.now() (required)
  • CSS transforms (required)
  • CSS filters (optional, for visual effects)
  • Vibration API (optional, for haptic feedback)

Accessibility

Reduced Motion Support

@media (prefers-reduced-motion: reduce) {
    .enhanced-card {
        animation: none !important;
        transition: none !important;
    }
}

High Contrast Mode

@media (prefers-contrast: high) {
    .enhanced-hint {
        background: rgba(0, 0, 0, 0.95);
        border-width: 3px;
    }
}

Keyboard Navigation

  • Arrow Keys: Trigger swipe actions
  • WASD Keys: Alternative swipe controls
  • Ctrl/Cmd + ,: Open settings panel
  • Escape: Close modals and panels

Debugging

Debug Mode

swipeIntegration.updateConfig({ debugMode: true });

// Access debug information
const debugInfo = swipeIntegration.getDebugInfo();
console.log('Debug Info:', debugInfo);

Performance Metrics

const metrics = swipeIntegration.getPerformanceMetrics();
console.log('Performance:', metrics);

State Inspection

// Access global debug objects
console.log('Swipe State:', window.enhancedSwipeState);
console.log('Swipe Card:', window.enhancedSwipeCard);
console.log('Integration:', window.swipeIntegration);

Troubleshooting

Common Issues

Poor Performance

  • Solution: Switch to 'enhanced-lite' or 'original' mode
  • Check: Device memory and CPU capabilities
  • Adjust: Reduce particle count and visual effects

Animations Not Working

  • Check: Browser support for CSS transforms
  • Verify: JavaScript modules are loading correctly
  • Test: Fallback to original mode

Touch Events Not Responding

  • Check: Touch event listeners are properly attached
  • Verify: touch-action: none is applied to card element
  • Test: Mouse events as fallback

Performance Tips

  1. Use Enhanced Lite on Mobile: Better performance with good visual quality
  2. Monitor Frame Rate: Enable debug mode to track performance
  3. Reduce Particle Count: Lower particle count for better performance
  4. Disable Visual Effects: Turn off blur and color effects on low-end devices

Future Enhancements

Planned Features

  • Card Stacking: Multiple cards with depth layering
  • Gesture Recognition: Advanced swipe patterns
  • Sound Effects: Audio feedback for actions
  • Custom Animations: User-defined animation curves

API Improvements

  • React Integration: React component wrapper
  • Vue Integration: Vue component wrapper
  • TypeScript Support: Full type definitions
  • Web Components: Custom element implementation

Contributing

Development Setup

# Clone repository
git clone <repository-url>

# Install dependencies
npm install

# Start development server
npm run dev

# Build for production
npm run build

Testing

# Run unit tests
npm test

# Run performance tests
npm run test:performance

# Run accessibility tests
npm run test:a11y

Code Style

  • Use ESLint configuration
  • Follow JSDoc conventions
  • Maintain 80% test coverage
  • Use semantic versioning

License

This enhanced swipe animation system is part of the image swiper application and follows the same licensing terms.


For more information, see the individual component documentation files or contact the development team.