File size: 37,805 Bytes
55896b1 1df45eb 55896b1 1df45eb 55896b1 1df45eb 55896b1 1df45eb 55896b1 1df45eb 55896b1 1df45eb 55896b1 1df45eb 55896b1 1df45eb 55896b1 1df45eb 55896b1 | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 952 953 954 955 956 957 958 959 960 961 962 963 964 965 966 967 968 969 970 971 972 973 974 975 976 977 978 979 980 981 982 983 984 985 986 987 988 989 990 991 992 993 994 995 996 997 998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072 1073 1074 1075 1076 1077 1078 1079 1080 1081 1082 1083 1084 1085 1086 1087 1088 1089 1090 1091 1092 1093 1094 1095 1096 1097 1098 1099 1100 1101 1102 1103 1104 1105 1106 1107 1108 1109 1110 1111 1112 1113 1114 1115 1116 1117 1118 1119 1120 1121 1122 1123 1124 1125 1126 1127 1128 1129 1130 1131 1132 1133 1134 1135 1136 1137 1138 1139 1140 1141 1142 1143 1144 1145 1146 | /**
* Premium Valentine Website - Interactive Controller
* ===================================================
* Corporate-Grade JavaScript Architecture
*
* @version 3.0.0
* @author Valentine Experience Team
* @license MIT
*
* Architecture:
* - Modular ES6+ design with strict separation of concerns
* - Event delegation for optimal performance
* - Memory-safe event listener management
* - Hardware-accelerated animations (transform/opacity only)
* - Passive event listeners for scroll performance
* - WCAG 2.1 AA compliant interactions
* - Comprehensive error handling and fallbacks
* - Performance monitoring and optimization
*
* Features:
* - Envelope opening animation with GPU acceleration
* - Touch-optimized drag system with passive listeners
* - Intelligent Z-index stacking management
* - Adaptive "No" button evasion algorithm
* - Progressive "Yes" button growth mechanics
* - Canvas-based particle system with RAF optimization
* - Cross-browser compatibility (Safari, Chrome, Firefox, Edge)
* - Memory leak prevention with proper cleanup
* - Graceful degradation for older browsers
*
* Browser Support:
* - Chrome 90+
* - Firefox 88+
* - Safari 14+
* - Edge 90+
* - iOS Safari 14+
* - Chrome Android 90+
*/
'use strict';
/* ============================================
ErrorHandler Module
Centralized error handling and logging
============================================ */
const ErrorHandler = (() => {
const isDevelopment = window.location.hostname === 'localhost' || window.location.hostname === '127.0.0.1';
/**
* Log error to console in development mode
* @param {string} context - Where the error occurred
* @param {Error} error - The error object
*/
const logError = (context, error) => {
if (isDevelopment) {
console.error(`[Valentine App Error - ${context}]:`, error);
}
};
/**
* Handle non-critical errors gracefully
* @param {string} context - Where the error occurred
* @param {Error} error - The error object
* @param {Function} fallback - Optional fallback function
*/
const handleError = (context, error, fallback = null) => {
logError(context, error);
if (fallback && typeof fallback === 'function') {
try {
fallback();
} catch (fallbackError) {
logError(`${context} - Fallback`, fallbackError);
}
}
};
/**
* Safe function wrapper with error handling
* @param {Function} fn - Function to wrap
* @param {string} context - Context for error reporting
* @returns {Function} Wrapped function
*/
const safeExecute = (fn, context) => {
return (...args) => {
try {
return fn(...args);
} catch (error) {
handleError(context, error);
return null;
}
};
};
return {
logError,
handleError,
safeExecute
};
})();
/* ============================================
PerformanceMonitor Module
Track and optimize performance metrics
============================================ */
const PerformanceMonitor = (() => {
const metrics = {
animationFrames: 0,
droppedFrames: 0,
lastFrameTime: 0
};
let isMonitoring = false;
let monitoringId = null;
/**
* Monitor frame rate for performance issues
*/
const monitorFrameRate = () => {
if (!isMonitoring) return;
const now = performance.now();
if (metrics.lastFrameTime > 0) {
const delta = now - metrics.lastFrameTime;
const fps = 1000 / delta;
// Track dropped frames (below 55fps threshold)
if (fps < 55) {
metrics.droppedFrames++;
}
metrics.animationFrames++;
}
metrics.lastFrameTime = now;
monitoringId = requestAnimationFrame(monitorFrameRate);
};
/**
* Start performance monitoring
*/
const startMonitoring = () => {
if (isMonitoring) return;
isMonitoring = true;
monitorFrameRate();
};
/**
* Stop performance monitoring
*/
const stopMonitoring = () => {
isMonitoring = false;
if (monitoringId) {
cancelAnimationFrame(monitoringId);
monitoringId = null;
}
};
/**
* Get performance metrics
* @returns {Object} Performance metrics
*/
const getMetrics = () => {
return {
...metrics,
averageFPS: metrics.animationFrames > 0
? Math.round((metrics.animationFrames - metrics.droppedFrames) / metrics.animationFrames * 60)
: 60
};
};
/**
* Check if device supports hardware acceleration
* @returns {boolean}
*/
const supportsHardwareAcceleration = () => {
const canvas = document.createElement('canvas');
const gl = canvas.getContext('webgl') || canvas.getContext('experimental-webgl');
return !!gl;
};
return {
startMonitoring,
stopMonitoring,
getMetrics,
supportsHardwareAcceleration
};
})();
/* ============================================
BrowserCompatibility Module
Feature detection and polyfills
============================================ */
const BrowserCompatibility = (() => {
/**
* Check if browser supports required features
* @returns {Object} Feature support flags
*/
const checkFeatures = () => {
return {
canvas: !!document.createElement('canvas').getContext,
requestAnimationFrame: typeof requestAnimationFrame !== 'undefined',
transform3d: (() => {
const el = document.createElement('div');
const transforms = {
'transform': 'transform',
'WebkitTransform': '-webkit-transform',
'MozTransform': '-moz-transform',
'msTransform': '-ms-transform'
};
for (let t in transforms) {
if (el.style[t] !== undefined) {
return true;
}
}
return false;
})(),
backdropFilter: CSS.supports('backdrop-filter', 'blur(10px)') ||
CSS.supports('-webkit-backdrop-filter', 'blur(10px)'),
touchEvents: 'ontouchstart' in window || navigator.maxTouchPoints > 0,
passiveEvents: (() => {
let supportsPassive = false;
try {
const opts = Object.defineProperty({}, 'passive', {
get: () => { supportsPassive = true; }
});
window.addEventListener('testPassive', null, opts);
window.removeEventListener('testPassive', null, opts);
} catch (e) { }
return supportsPassive;
})()
};
};
/**
* Apply fallbacks for unsupported features
* @param {Object} features - Feature support flags
*/
const applyFallbacks = (features) => {
// Fallback for requestAnimationFrame
if (!features.requestAnimationFrame) {
window.requestAnimationFrame = (callback) => {
return setTimeout(callback, 1000 / 60);
};
window.cancelAnimationFrame = (id) => {
clearTimeout(id);
};
}
// Fallback for transform3d
if (!features.transform3d) {
document.documentElement.classList.add('no-transforms');
}
// Fallback for backdrop-filter
if (!features.backdropFilter) {
document.documentElement.classList.add('no-backdrop-filter');
}
};
/**
* Initialize compatibility checks
*/
const init = () => {
const features = checkFeatures();
applyFallbacks(features);
return features;
};
return {
init,
checkFeatures
};
})();
/* ============================================
AnimationController Module
Handles all animations and transitions
============================================ */
const AnimationController = (() => {
// Canvas and context references
let canvas = null;
let ctx = null;
let particles = [];
let animationId = null;
let isConfettiActive = false;
/**
* Heart particle class for confetti animation
* Optimized for 60fps performance on mobile
*/
class HeartParticle {
constructor(x, y) {
this.x = x;
this.y = y;
this.size = Math.random() * 20 + 10;
this.speedX = (Math.random() - 0.5) * 8;
this.speedY = Math.random() * -12 - 5;
this.gravity = 0.3;
this.rotation = Math.random() * Math.PI * 2;
this.rotationSpeed = (Math.random() - 0.5) * 0.2;
this.opacity = 1;
this.fadeSpeed = 0.008 + Math.random() * 0.005;
// Premium color palette: crimson, rose, blush, gold
const colors = ['#8b0000', '#ff6b81', '#ffb6c1', '#d4af37', '#ff4757'];
this.color = colors[Math.floor(Math.random() * colors.length)];
}
/**
* Update particle physics
*/
update() {
this.speedY += this.gravity;
this.x += this.speedX;
this.y += this.speedY;
this.rotation += this.rotationSpeed;
this.opacity -= this.fadeSpeed;
// Add subtle wobble for organic movement
this.x += Math.sin(this.rotation) * 0.5;
}
/**
* Draw heart shape on canvas
* @param {CanvasRenderingContext2D} ctx - Canvas context
*/
draw(ctx) {
if (this.opacity <= 0) return;
ctx.save();
ctx.translate(this.x, this.y);
ctx.rotate(this.rotation);
ctx.globalAlpha = this.opacity;
ctx.fillStyle = this.color;
// Draw heart shape using bezier curves
ctx.beginPath();
const s = this.size / 15;
ctx.moveTo(0, s * 3);
ctx.bezierCurveTo(-s * 5, -s * 2, -s * 5, -s * 7, 0, -s * 5);
ctx.bezierCurveTo(s * 5, -s * 7, s * 5, -s * 2, 0, s * 3);
ctx.fill();
ctx.restore();
}
/**
* Check if particle is still visible
* @returns {boolean}
*/
isAlive() {
return this.opacity > 0;
}
}
/**
* Initialize canvas with error handling
*/
const initCanvas = ErrorHandler.safeExecute(() => {
canvas = document.getElementById('confetti-canvas');
if (!canvas) {
throw new Error('Confetti canvas element not found');
}
// Check canvas support
if (!canvas.getContext) {
ErrorHandler.logError('Canvas', new Error('Canvas not supported'));
return;
}
ctx = canvas.getContext('2d', { alpha: true });
resizeCanvas();
// Use passive listener for resize
window.addEventListener('resize', resizeCanvas, { passive: true });
}, 'Canvas Initialization');
/**
* Resize canvas to match window dimensions
*/
const resizeCanvas = ErrorHandler.safeExecute(() => {
if (!canvas) return;
// Use device pixel ratio for sharp rendering on retina displays
const dpr = window.devicePixelRatio || 1;
const rect = canvas.getBoundingClientRect();
canvas.width = rect.width * dpr;
canvas.height = rect.height * dpr;
// Scale context to match device pixel ratio
if (ctx) {
ctx.scale(dpr, dpr);
}
// Set CSS dimensions
canvas.style.width = `${rect.width}px`;
canvas.style.height = `${rect.height}px`;
}, 'Canvas Resize');
/**
* Create confetti burst at specified position
* @param {number} x - X coordinate
* @param {number} y - Y coordinate
* @param {number} count - Number of particles
*/
const createConfettiBurst = ErrorHandler.safeExecute((x, y, count = 50) => {
for (let i = 0; i < count; i++) {
particles.push(new HeartParticle(x, y));
}
}, 'Confetti Burst Creation');
/**
* Confetti animation loop with RAF optimization
*/
const animateConfetti = ErrorHandler.safeExecute(() => {
if (!ctx || !canvas) return;
// Clear canvas with proper dimensions
const rect = canvas.getBoundingClientRect();
ctx.clearRect(0, 0, rect.width, rect.height);
// Update and draw particles
particles = particles.filter(particle => {
particle.update();
particle.draw(ctx);
return particle.isAlive();
});
// Continue animation if particles exist or confetti is active
if (particles.length > 0 || isConfettiActive) {
animationId = requestAnimationFrame(animateConfetti);
} else {
PerformanceMonitor.stopMonitoring();
}
}, 'Confetti Animation');
/**
* Start confetti celebration with multiple bursts
*/
const startConfetti = ErrorHandler.safeExecute(() => {
if (!canvas || !ctx) initCanvas();
isConfettiActive = true;
PerformanceMonitor.startMonitoring();
// Initial burst from center
const centerX = window.innerWidth / 2;
const centerY = window.innerHeight / 2;
createConfettiBurst(centerX, centerY, 80);
// Staggered bursts from different positions
const burstPositions = [
{ x: window.innerWidth * 0.2, y: window.innerHeight * 0.3, count: 40, delay: 200 },
{ x: window.innerWidth * 0.8, y: window.innerHeight * 0.3, count: 40, delay: 400 },
{ x: centerX, y: centerY - 100, count: 60, delay: 600 }
];
burstPositions.forEach(({ x, y, count, delay }) => {
setTimeout(() => createConfettiBurst(x, y, count), delay);
});
// Continuous smaller bursts for extended celebration
let burstCount = 0;
const burstInterval = setInterval(() => {
if (burstCount >= 8) {
clearInterval(burstInterval);
isConfettiActive = false;
return;
}
const randomX = Math.random() * window.innerWidth;
const randomY = Math.random() * window.innerHeight * 0.5;
createConfettiBurst(randomX, randomY, 20);
burstCount++;
}, 300);
// Start animation loop
if (!animationId) {
animateConfetti();
}
}, 'Start Confetti');
/**
* Stop confetti animation and cleanup
*/
const stopConfetti = ErrorHandler.safeExecute(() => {
isConfettiActive = false;
if (animationId) {
cancelAnimationFrame(animationId);
animationId = null;
}
particles = [];
PerformanceMonitor.stopMonitoring();
}, 'Stop Confetti');
/**
* Show section with fade-in animation
* @param {string} sectionId - Section element ID
* @param {number} delay - Delay before showing (ms)
* @returns {Promise}
*/
const showSection = (sectionId, delay = 0) => {
return new Promise(resolve => {
setTimeout(() => {
const section = document.getElementById(sectionId);
if (section) {
section.classList.remove('hidden');
// Announce to screen readers
section.setAttribute('aria-hidden', 'false');
}
resolve();
}, delay);
});
};
/**
* Hide section with fade-out animation
* @param {string} sectionId - Section element ID
* @param {number} delay - Delay before hiding (ms)
* @returns {Promise}
*/
const hideSection = (sectionId, delay = 0) => {
return new Promise(resolve => {
setTimeout(() => {
const section = document.getElementById(sectionId);
if (section) {
section.classList.add('hidden');
// Hide from screen readers
section.setAttribute('aria-hidden', 'true');
}
resolve();
}, delay);
});
};
/**
* Animate envelope opening
* @returns {Promise}
*/
const openEnvelope = () => {
return new Promise(resolve => {
const envelope = document.getElementById('envelope');
if (envelope) {
envelope.classList.add('open');
// Announce to screen readers
const announcement = document.createElement('div');
announcement.setAttribute('role', 'status');
announcement.setAttribute('aria-live', 'polite');
announcement.className = 'sr-only';
announcement.textContent = 'Envelope opened, revealing a love letter';
document.body.appendChild(announcement);
setTimeout(() => announcement.remove(), 2000);
}
// Wait for animation to complete (800ms flap + 400ms buffer)
setTimeout(resolve, 1200);
});
};
// Public API
return {
init: initCanvas,
startConfetti,
stopConfetti,
showSection,
hideSection,
openEnvelope
};
})();
/* ============================================
UIController Module
Handles user interactions and state
============================================ */
const UIController = (() => {
// State
let notesRemoved = 0;
const totalNotes = 5;
let noClickCount = 0;
let yesScale = 1;
let currentZIndex = 20;
let isEvading = false;
let noButtonActivated = false;
// Detect mobile device (touch-only devices)
const isMobileDevice = () => {
return ('ontouchstart' in window || navigator.maxTouchPoints > 0) &&
window.matchMedia('(max-width: 768px)').matches;
};
// DOM cache
const elements = {
btnOpen: null,
btnYes: null,
btnNo: null,
buttonsWrapper: null,
notes: null
};
// Initialize UI elements
const cacheElements = () => {
elements.btnOpen = document.getElementById('btn-open');
elements.btnYes = document.getElementById('btn-yes');
elements.btnNo = document.getElementById('btn-no');
elements.buttonsWrapper = document.getElementById('buttons-wrapper');
elements.notes = document.querySelectorAll('.draggable-note');
};
// Setup event listeners
const setupEventListeners = () => {
// Open button
if (elements.btnOpen) {
elements.btnOpen.addEventListener('click', handleOpenClick);
}
// Yes button
if (elements.btnYes) {
elements.btnYes.addEventListener('click', handleYesClick);
}
// No button - event listeners based on device type
if (elements.btnNo) {
// Click handler works on both mobile and desktop
elements.btnNo.addEventListener('click', handleNoClick);
// Only add hover/proximity evasion on desktop (non-mobile)
if (!isMobileDevice()) {
elements.btnNo.addEventListener('mouseenter', handleNoHover);
// Track mouse movement globally for desktop proximity detection
document.addEventListener('mousemove', (e) => {
if (!elements.btnNo || !noButtonActivated || isMobileDevice()) return;
const btn = elements.btnNo;
const btnRect = btn.getBoundingClientRect();
const mouseX = e.clientX;
const mouseY = e.clientY;
// Add buffer zone around button
const buffer = 30;
const isNearButton = mouseX >= btnRect.left - buffer &&
mouseX <= btnRect.right + buffer &&
mouseY >= btnRect.top - buffer &&
mouseY <= btnRect.bottom + buffer;
if (isNearButton && !isEvading) {
evadeNoButton();
}
});
}
}
// Setup drag for notes
if (elements.notes) {
elements.notes.forEach(note => {
setupDrag(note);
});
}
};
// Handle open envelope click
const handleOpenClick = async () => {
// Disable button
elements.btnOpen.disabled = true;
elements.btnOpen.style.opacity = '0.7';
// Open envelope animation
await AnimationController.openEnvelope();
// Transition to notes section
await AnimationController.hideSection('envelope-section');
await AnimationController.showSection('notes-section', 300);
};
// Setup drag functionality for a note with memory-safe cleanup
const setupDrag = (note) => {
let isDragging = false;
let startX, startY;
let initialX, initialY;
let currentX = 0, currentY = 0;
let rafId = null;
// Get initial position from computed style
const rect = note.getBoundingClientRect();
const parentRect = note.parentElement.getBoundingClientRect();
initialX = rect.left - parentRect.left;
initialY = rect.top - parentRect.top;
const onStart = (e) => {
isDragging = true;
document.body.classList.add('dragging');
note.classList.add('dragging');
// Increase z-index
currentZIndex++;
note.style.zIndex = currentZIndex;
// Get start position
if (e.type === 'touchstart') {
startX = e.touches[0].clientX - currentX;
startY = e.touches[0].clientY - currentY;
} else {
startX = e.clientX - currentX;
startY = e.clientY - currentY;
}
};
const onMove = (e) => {
if (!isDragging) return;
// Only prevent default for touch to allow scrolling when not dragging
if (e.type === 'touchmove') {
e.preventDefault();
}
let clientX, clientY;
if (e.type === 'touchmove') {
clientX = e.touches[0].clientX;
clientY = e.touches[0].clientY;
} else {
clientX = e.clientX;
clientY = e.clientY;
}
currentX = clientX - startX;
currentY = clientY - startY;
// Use RAF for smooth 60fps animation
if (rafId) {
cancelAnimationFrame(rafId);
}
rafId = requestAnimationFrame(() => {
// Hardware-accelerated transform (GPU)
note.style.transform = `translate3d(${currentX}px, ${currentY}px, 0)`;
});
};
const onEnd = () => {
if (!isDragging) return;
isDragging = false;
document.body.classList.remove('dragging');
note.classList.remove('dragging');
if (rafId) {
cancelAnimationFrame(rafId);
rafId = null;
}
// Check if note is moved far enough to be "removed"
const threshold = 150;
const distance = Math.sqrt(currentX * currentX + currentY * currentY);
if (distance > threshold && !note.dataset.removed) {
note.dataset.removed = 'true';
notesRemoved++;
// Hardware-accelerated fade out
note.style.opacity = '0';
note.style.pointerEvents = 'none';
// Announce to screen readers
const announcement = document.createElement('div');
announcement.setAttribute('role', 'status');
announcement.setAttribute('aria-live', 'polite');
announcement.className = 'sr-only';
announcement.textContent = `Note ${notesRemoved} of ${totalNotes} removed`;
document.body.appendChild(announcement);
setTimeout(() => announcement.remove(), 1000);
// Check if all notes removed
checkAllNotesRemoved();
}
};
// Mouse events
note.addEventListener('mousedown', onStart);
document.addEventListener('mousemove', onMove);
document.addEventListener('mouseup', onEnd);
// Touch events with passive flag for scroll performance
note.addEventListener('touchstart', onStart, { passive: true });
document.addEventListener('touchmove', onMove, { passive: false });
document.addEventListener('touchend', onEnd, { passive: true });
// Store cleanup function for memory management
note._dragCleanup = () => {
note.removeEventListener('mousedown', onStart);
document.removeEventListener('mousemove', onMove);
document.removeEventListener('mouseup', onEnd);
note.removeEventListener('touchstart', onStart);
document.removeEventListener('touchmove', onMove);
document.removeEventListener('touchend', onEnd);
if (rafId) {
cancelAnimationFrame(rafId);
}
};
};
// Check if all notes have been removed
const checkAllNotesRemoved = async () => {
if (notesRemoved >= totalNotes) {
// Hide hint
const hint = document.getElementById('hint-text');
if (hint) hint.style.opacity = '0';
// Transition to question
await AnimationController.hideSection('notes-section', 500);
await AnimationController.showSection('question-section', 300);
}
};
// Handle Yes button click
const handleYesClick = async () => {
// Start confetti
AnimationController.startConfetti();
// Transition to success
await AnimationController.hideSection('question-section');
await AnimationController.showSection('success-section', 300);
};
// Handle No button click
const handleNoClick = (e) => {
e.preventDefault();
e.stopPropagation();
noClickCount++;
noButtonActivated = true;
// Make No button evade immediately
evadeNoButton();
// After many clicks, trigger yes automatically
if (noClickCount >= 15) {
handleYesClick();
}
};
// Handle No button hover (desktop only evasion) - triggers immediately
const handleNoHover = () => {
// Only evade on hover for desktop devices
if (!isMobileDevice()) {
noButtonActivated = true;
evadeNoButton();
}
};
// Evade No button - move to random position within the question container
const evadeNoButton = () => {
if (isEvading) return;
isEvading = true;
const btn = elements.btnNo;
const questionContainer = document.querySelector('.question-container');
if (!btn || !questionContainer) {
isEvading = false;
return;
}
// Add evading class for absolute positioning within container
btn.classList.add('evading');
// Get container bounds (the glass container)
const containerRect = questionContainer.getBoundingClientRect();
// Get button dimensions
const btnRect = btn.getBoundingClientRect();
const btnWidth = btnRect.width || 100;
const btnHeight = btnRect.height || 48;
// Calculate safe area within the container with padding
const padding = 20;
const minX = containerRect.left + padding;
const minY = containerRect.top + padding;
const maxX = containerRect.right - btnWidth - padding;
const maxY = containerRect.bottom - btnHeight - padding;
// Ensure we have valid bounds
if (maxX <= minX || maxY <= minY) {
// Container too small, keep button centered
btn.style.position = 'fixed';
btn.style.left = `${containerRect.left + containerRect.width / 2 - btnWidth / 2}px`;
btn.style.top = `${containerRect.top + containerRect.height / 2}px`;
btn.style.transform = 'scale(1)';
isEvading = false;
return;
}
// Generate random position within container bounds
let newX, newY;
let attempts = 0;
const maxAttempts = 20;
do {
newX = minX + Math.random() * (maxX - minX);
newY = minY + Math.random() * (maxY - minY);
attempts++;
// Ensure NO button NEVER touches or overlaps YES button
if (elements.btnYes) {
const yesRect = elements.btnYes.getBoundingClientRect();
// Large safety buffer to guarantee no touching (50px minimum gap)
const safetyBuffer = 50;
// No button bounds
const noLeft = newX;
const noRight = newX + btnWidth;
const noTop = newY;
const noBottom = newY + btnHeight;
// Yes button expanded bounds (with safety buffer)
const yesLeft = yesRect.left - safetyBuffer;
const yesRight = yesRect.right + safetyBuffer;
const yesTop = yesRect.top - safetyBuffer;
const yesBottom = yesRect.bottom + safetyBuffer;
// Check if NO button would be inside the YES button's exclusion zone
const isInExclusionZone = (noRight > yesLeft &&
noLeft < yesRight &&
noBottom > yesTop &&
noTop < yesBottom);
// Only accept position if OUTSIDE the exclusion zone
if (!isInExclusionZone) {
break;
}
} else {
break;
}
} while (attempts < maxAttempts);
// If we couldn't find a valid position after all attempts,
// force position to bottom-right corner away from Yes button
if (attempts >= maxAttempts && elements.btnYes) {
const yesRect = elements.btnYes.getBoundingClientRect();
// Position in opposite corner from Yes button
if (yesRect.left < containerRect.left + containerRect.width / 2) {
// Yes is on left, put No on right
newX = maxX;
} else {
// Yes is on right, put No on left
newX = minX;
}
if (yesRect.top < containerRect.top + containerRect.height / 2) {
// Yes is on top, put No on bottom
newY = maxY;
} else {
// Yes is on bottom, put No on top
newY = minY;
}
}
// Strictly clamp position within container bounds
const finalX = Math.max(minX, Math.min(maxX, newX));
const finalY = Math.max(minY, Math.min(maxY, newY));
// Apply position using fixed positioning
btn.style.position = 'fixed';
btn.style.left = `${finalX}px`;
btn.style.top = `${finalY}px`;
btn.style.margin = '0';
btn.style.right = 'auto';
btn.style.bottom = 'auto';
// Shrink the No button progressively after several clicks
if (noClickCount >= 3) {
const shrinkScale = Math.max(0.6, 1 - (noClickCount - 2) * 0.08);
btn.style.transform = `scale(${shrinkScale})`;
} else {
btn.style.transform = 'scale(1)';
}
// Ensure button stays visible
btn.style.opacity = '1';
btn.style.visibility = 'visible';
btn.style.display = 'inline-flex';
btn.style.pointerEvents = 'auto';
btn.style.zIndex = '100';
setTimeout(() => {
isEvading = false;
}, 150);
};
// Cleanup function for memory management
const cleanup = () => {
// Remove all event listeners
if (elements.btnOpen) {
elements.btnOpen.removeEventListener('click', handleOpenClick);
}
if (elements.btnYes) {
elements.btnYes.removeEventListener('click', handleYesClick);
}
if (elements.btnNo) {
elements.btnNo.removeEventListener('click', handleNoClick);
elements.btnNo.removeEventListener('mouseenter', handleNoHover);
elements.btnNo.removeEventListener('touchstart', handleNoTouch);
}
// Cleanup drag listeners
if (elements.notes) {
elements.notes.forEach(note => {
if (note._dragCleanup) {
note._dragCleanup();
}
});
}
};
// Initialize
const init = () => {
cacheElements();
setupEventListeners();
AnimationController.init();
};
// Public API
return {
init,
cleanup
};
})();
/* ============================================
Application Entry Point
============================================ */
document.addEventListener('DOMContentLoaded', () => {
// Initialize browser compatibility checks
const features = BrowserCompatibility.init();
// Log feature support in development
if (window.location.hostname === 'localhost' || window.location.hostname === '127.0.0.1') {
console.log('π¨ Valentine App Initialized');
console.log('π Browser Features:', features);
console.log('π Hardware Acceleration:', PerformanceMonitor.supportsHardwareAcceleration());
}
// Initialize application with error handling
try {
UIController.init();
} catch (error) {
ErrorHandler.handleError('Application Initialization', error, () => {
// Fallback: Show a basic error message
document.body.innerHTML = `
<div style="display: flex; align-items: center; justify-content: center; min-height: 100vh; padding: 2rem; text-align: center; font-family: sans-serif;">
<div>
<h1 style="color: #8b0000; margin-bottom: 1rem;">π</h1>
<p style="color: #666;">Something went wrong, but the love is still there!</p>
<p style="color: #999; font-size: 0.9rem; margin-top: 1rem;">Please try refreshing the page.</p>
</div>
</div>
`;
});
}
// Cleanup on page unload to prevent memory leaks
window.addEventListener('beforeunload', () => {
try {
UIController.cleanup();
AnimationController.stopConfetti();
PerformanceMonitor.stopMonitoring();
} catch (error) {
ErrorHandler.logError('Cleanup', error);
}
});
// Handle visibility change to pause animations when tab is hidden
document.addEventListener('visibilitychange', () => {
if (document.hidden) {
PerformanceMonitor.stopMonitoring();
} else {
// Resume monitoring if confetti is active
const canvas = document.getElementById('confetti-canvas');
if (canvas && canvas.style.display !== 'none') {
PerformanceMonitor.startMonitoring();
}
}
});
});
// Prevent double-tap zoom on iOS (passive: false for preventDefault)
let lastTouchEnd = 0;
document.addEventListener('touchend', (e) => {
const now = Date.now();
if (now - lastTouchEnd < 300) {
e.preventDefault();
}
lastTouchEnd = now;
}, { passive: false });
// Global error handler for uncaught errors
window.addEventListener('error', (event) => {
ErrorHandler.logError('Global Error', event.error);
// Prevent default error handling in production
if (window.location.hostname !== 'localhost' && window.location.hostname !== '127.0.0.1') {
event.preventDefault();
}
});
// Handle unhandled promise rejections
window.addEventListener('unhandledrejection', (event) => {
ErrorHandler.logError('Unhandled Promise Rejection', event.reason);
// Prevent default error handling in production
if (window.location.hostname !== 'localhost' && window.location.hostname !== '127.0.0.1') {
event.preventDefault();
}
});
// Add screen reader only utility class for accessibility announcements
const style = document.createElement('style');
style.textContent = `
.sr-only {
position: absolute;
width: 1px;
height: 1px;
padding: 0;
margin: -1px;
overflow: hidden;
clip: rect(0, 0, 0, 0);
white-space: nowrap;
border-width: 0;
}
/* Fallback styles for browsers without transform support */
.no-transforms .draggable-note {
position: absolute;
transition: left 0.3s ease, top 0.3s ease;
}
/* Fallback for backdrop-filter */
.no-backdrop-filter .glass-container {
background: rgba(255, 255, 255, 0.95);
box-shadow: 0 12px 48px rgba(139, 0, 0, 0.2);
}
`;
document.head.appendChild(style);
|