diff --git a/.storybook/utils/mocks/animationContext.tsx b/.storybook/utils/mocks/animationContext.tsx index ae286c6b..bdb5a278 100644 --- a/.storybook/utils/mocks/animationContext.tsx +++ b/.storybook/utils/mocks/animationContext.tsx @@ -9,106 +9,12 @@ import React from 'react'; import { AnimationContext, AnimationContextType } from '../../../src/context/AnimationContext'; import type { Decorator } from '../index'; -// Define standard variants to use across components -const defaultFadeIn = { - hidden: { opacity: 0 }, - visible: { opacity: 1, transition: { duration: 0.5 } } -}; - -const defaultSlideUp = { - hidden: { opacity: 0, y: 20 }, - visible: { opacity: 1, y: 0, transition: { duration: 0.5 } } -}; - -const defaultScale = { - hidden: { opacity: 0, scale: 0.8 }, - visible: { opacity: 1, scale: 1, transition: { duration: 0.5 } } -}; - -const defaultPulse = { - hidden: { opacity: 0.6 }, - visible: { - opacity: [0.6, 1, 0.6], - transition: { - repeat: Infinity, - duration: 2, - ease: "easeInOut" as const - } - } -}; - -const defaultMatrix = { - hidden: { opacity: 0 }, - visible: { - opacity: 1, - transition: { - duration: 0.8, - staggerChildren: 0.05 - } - } -}; - -const defaultGlitch = { - hidden: { opacity: 0 }, - visible: { - opacity: 1, - x: [0, -2, 3, -1, 0], - transition: { - duration: 0.5, - x: { - repeat: Infinity, - repeatType: "reverse", - duration: 0.2 - } - } - } -}; - /** - * Mock animation context data with working no-op implementations + * Mock animation context data: animations on, no reduced-motion preference */ export const mockAnimationData: AnimationContextType = { - inView: true, // Always in view for stories - setInView: () => {}, // No-op for stories animationEnabled: true, - entryAnimations: {}, - registerEntryAnimation: (id: string, initialState: string = 'visible') => { - // In Storybook, we'll default all animations to visible - // This ensures elements are shown immediately without animations - console.log(`[Storybook] Registered animation for ${id} with state ${initialState}`); - }, - playEntryAnimation: (id: string, delay: number = 0) => { - console.log(`[Storybook] Playing animation for ${id} with delay ${delay}`); - }, - resetEntryAnimations: () => { - console.log(`[Storybook] Reset animations`); - }, - animationStaggerDelay: 0, - getAnimationDelay: (index: number) => '0s', // No delay in Storybook - - // Add missing properties used by components - controls: { - start: () => Promise.resolve(), - stop: () => Promise.resolve(), - set: () => Promise.resolve(), - mount: () => Promise.resolve(), - unmount: () => Promise.resolve() - } as any, // Use type assertion to avoid TypeScript errors - getVariants: (duration = 0.5, delay = 0) => ({ - hidden: { opacity: 0 }, - visible: { opacity: 1, transition: { duration, delay } } - }), - fadeInVariants: defaultFadeIn, - slideUpVariants: defaultSlideUp, - scaleVariants: defaultScale, - pulseVariants: defaultPulse, - matrixVariants: defaultMatrix, - glitchVariants: defaultGlitch, - prefersReducedMotion: false, - isLowPowerDevice: false, - optimizeVariants: (variants) => variants, - enablePerformanceMonitoring: () => {}, - disablePerformanceMonitoring: () => {} + prefersReducedMotion: false }; /** diff --git a/scripts/README.md b/scripts/README.md index daf62807..f6832563 100644 --- a/scripts/README.md +++ b/scripts/README.md @@ -88,7 +88,7 @@ These have no package.json entry; run them with `node scripts/.js`. - **analyze-dependencies.js**: scans components, hooks, contexts and utils for import patterns and circular dependencies. Writes `dependency-report.html` and `dependency-report.json` to the project root. - **finalize-package-cleanup.js**: lists the package.json scripts by category. With `--clean` it rewrites package.json (after saving `package.json.bak`) to drop the one-time reorganization scripts; none of those remain, so it currently removes nothing. -- **monitor-animation-performance.js**: not a command-line script. It is a browser module that measures animation frame times; `src/context/AnimationContext.tsx` loads it through the `@scripts` alias when performance monitoring is switched on. +- **monitor-animation-performance.js**: not a command-line script. It is a browser module that measures animation frame times. Nothing imports it at the moment. ## Not working diff --git a/src/assets/css/utilities/animations.css b/src/assets/css/utilities/animations.css index f3ef6718..ee4692ff 100644 --- a/src/assets/css/utilities/animations.css +++ b/src/assets/css/utilities/animations.css @@ -2,7 +2,7 @@ * Animation Utilities * * This file has been converted to use framer-motion for animations. - * See src/context/AnimationContext.tsx and the MotionVariants export. + * See src/utils/motion.ts for the shared variants. * * IMPORTANT: The CSS classes below are kept only as fallbacks for when JS is disabled. * All new code should use framer-motion's animation system. diff --git a/src/components/layout/Background/Background.test.tsx b/src/components/layout/Background/Background.test.tsx index 8f9fa8cf..97a9f63d 100644 --- a/src/components/layout/Background/Background.test.tsx +++ b/src/components/layout/Background/Background.test.tsx @@ -7,8 +7,6 @@ import Background from './Background'; vi.mock('@context/AnimationContext', () => ({ useAnimation: () => ({ animationEnabled: true, - registerEntryAnimation: vi.fn(), - playEntryAnimation: vi.fn(), }), })); diff --git a/src/components/layout/Section/Section.tsx b/src/components/layout/Section/Section.tsx index de845efe..92dab4fd 100644 --- a/src/components/layout/Section/Section.tsx +++ b/src/components/layout/Section/Section.tsx @@ -3,7 +3,19 @@ import { motion, HTMLMotionProps, MotionProps } from 'framer-motion'; import { FaGraduationCap, FaBriefcase, FaCode, FaStar, FaHandshake, FaShieldAlt } from 'react-icons/fa'; import '@assets/css/tailwind.css'; import './Section.css'; -import { useAnimation, MotionVariants } from '@context/AnimationContext'; +import { useAnimation } from '@context/AnimationContext'; +import { slideUpVariants, fadeInVariants } from '@utils/motion'; + +// Staggers the section's children as they appear +const containerVariants = { + hidden: { opacity: 0 }, + visible: { + opacity: 1, + transition: { + staggerChildren: 0.1 + } + } +}; export interface SectionProps extends HTMLMotionProps<'section'> { /** The section content */ @@ -50,7 +62,7 @@ const Section = ({ role = 'region', ...rest }: SectionProps) => { - const { animationEnabled, slideUpVariants, fadeInVariants } = useAnimation(); + const { animationEnabled } = useAnimation(); // Base classes - removed background styling to let global background show through const sectionClasses = [ @@ -146,7 +158,7 @@ const Section = ({ const motionProps: MotionProps = animationEnabled ? { initial: "hidden", animate: "visible", - variants: MotionVariants.container, + variants: containerVariants, } : {}; // Handle animation with Framer Motion diff --git a/src/components/molecules/Timeline/Timeline.css b/src/components/molecules/Timeline/Timeline.css index b7bfdcde..36981095 100644 --- a/src/components/molecules/Timeline/Timeline.css +++ b/src/components/molecules/Timeline/Timeline.css @@ -61,33 +61,11 @@ 20%, 40%, 60%, 80% { transform: translateX(5px); } } -@keyframes borderScan { - 0%, 100% { background-position: 0% 50%; } - 50% { background-position: 100% 50%; } -} - @keyframes pulseGlow { 0%, 100% { box-shadow: 0 0 5px rgba(100, 255, 218, 0.3); } 50% { box-shadow: 0 0 20px rgba(100, 255, 218, 0.8), 0 0 30px rgba(100, 255, 218, 0.4); } } -/* Secret message overlay */ -.timeline__secret-message { - transform: translateX(-50%); /* was @apply transform -translate-x-1/2 */ - @apply fixed top-20 left-1/2 z-50 bg-gray-900 border border-theme-cyan text-theme-cyan px-6 py-3 rounded-lg font-mono text-sm font-bold; - box-shadow: 0 0 20px rgba(100, 255, 218, 0.5); - backdrop-filter: blur(10px); - background: linear-gradient(135deg, rgba(31, 41, 55, 0.95), rgba(17, 24, 39, 0.95)); -} - -/* Achievement notifications */ -.timeline__achievement { - @apply fixed right-4 z-50 bg-green-500 text-white px-4 py-2 rounded-lg font-bold text-sm; - box-shadow: 0 4px 15px rgba(34, 197, 94, 0.4); - backdrop-filter: blur(10px); - max-width: 300px; -} - /* Central timeline line with enhanced effects */ .timeline__line { transform: translateX(-50%); /* was @apply transform -translate-x-1/2 */ @@ -187,267 +165,6 @@ pointer-events: none; } -/* Enhanced experience card */ -.timeline__card { - @apply relative bg-gray-900 border border-gray-700 rounded-lg p-6 max-w-md; - background: linear-gradient(135deg, rgba(31, 41, 55, 0.95), rgba(17, 24, 39, 0.95)); - backdrop-filter: blur(10px); - transition: all 0.3s ease; - overflow: hidden; -} - -.timeline__entry--left .timeline__card { - @apply mr-auto; - margin-right: calc(50% + 2rem); -} - -.timeline__entry--right .timeline__card { - @apply ml-auto; - margin-left: calc(50% + 2rem); -} - -/* Full width override for expanded cards */ -.timeline__entry--left .timeline__card--expanded, -.timeline__entry--right .timeline__card--expanded { - @apply mx-auto; - margin-left: auto; - margin-right: auto; -} - -.timeline__card--expanded { - @apply border-theme-cyan/30; - max-width: calc(100vw - 8rem); - width: 100%; - z-index: 30; /* Higher than timeline line */ - box-shadow: - 0 10px 40px rgba(0, 0, 0, 0.3), - 0 0 20px rgba(100, 255, 218, 0.2); - background: linear-gradient(135deg, rgba(31, 41, 55, 0.98), rgba(17, 24, 39, 0.98)); -} - -.timeline__card--clicked { - border-color: rgba(239, 68, 68, 0.5); - box-shadow: 0 0 20px rgba(239, 68, 68, 0.3); -} - -/* Holographic overlay for hack modes */ -.timeline__hologram { - @apply absolute inset-0 rounded-lg pointer-events-none; - background: linear-gradient(45deg, transparent, rgba(100, 255, 218, 0.1), transparent); - background-size: 200% 200%; -} - -/* Enhanced security badge */ -.timeline__security-badge { - @apply absolute top-2 right-2 bg-theme-cyan text-gray-900 rounded-full px-3 py-1 flex items-center gap-1 text-sm font-bold z-10; - box-shadow: 0 0 15px rgba(100, 255, 218, 0.5); - transition: all 0.3s ease; -} - -.timeline__badge-icon { - @apply text-xs; -} - -.timeline__badge-text { - @apply text-xs; -} - -/* Company logo with enhanced effects */ -.timeline__logo { - @apply mb-4 flex justify-center; -} - -.timeline__logo-image { - @apply w-12 h-12 rounded-lg object-contain; - transition: all 0.3s ease; -} - -/* Card header */ -.timeline__header { - @apply mb-4; -} - -.timeline__role { - @apply text-white text-lg font-bold mb-2; - transition: color 0.3s ease; -} - -.timeline__company-info { - @apply flex flex-col gap-1; -} - -.timeline__company { - @apply text-theme-cyan font-semibold; -} - -.timeline__date { - @apply text-gray-400 text-sm; -} - -/* Improved layout for expanded cards */ -.timeline__card--expanded .timeline__header { - @apply text-center mb-6; -} - -.timeline__card--expanded .timeline__role { - @apply text-xl; -} - -.timeline__card--expanded .timeline__company-info { - @apply items-center; -} - -/* Expandable content */ -.timeline__content { - @apply border-t border-gray-700 pt-4 mt-4; - perspective: 1000px; -} - -.timeline__classification { - @apply mb-4 pb-2 border-b border-red-500/30; - transition: background-color 0.3s ease; -} - -.timeline__classification-label { - @apply bg-red-500 text-white px-2 py-1 rounded text-xs font-bold; - transition: all 0.3s ease; -} - -.timeline__description { - @apply text-gray-300 mb-4 leading-relaxed; - transition: text-shadow 0.3s ease; -} - -.timeline__bullets { - @apply list-none mb-4; -} - -/* Tailwind 3 `space-y-2` behaviour (see the space-y note in tailwind.css) */ -.timeline__bullets > :not([hidden]) ~ :not([hidden]) { - margin-top: var(--spacing-2); - margin-bottom: 0; -} - -.timeline__bullet { - @apply text-gray-300 text-sm relative pl-6; - transition: all 0.3s ease; -} - -/* Improved content layout for expanded cards */ -.timeline__card--expanded .timeline__content { - @apply pt-6 mt-6; - display: grid; - grid-template-columns: 1fr 1fr; - gap: 2rem; - align-items: start; -} - -.timeline__card--expanded .timeline__classification { - @apply col-span-2 text-center mb-6 pb-4; -} - -.timeline__card--expanded .timeline__description { - @apply text-base leading-relaxed mt-4 text-center; - /* Description is now structurally inside classification */ -} - -.timeline__card--expanded .timeline__bullets { - @apply col-span-2; - /* Bullets now span both columns and use CSS Grid */ - display: grid; - grid-template-columns: 1fr 1fr; - gap: 1rem 2rem; - align-items: start; -} - -/* Grid gap handles the spacing; the stacked-list margins would push every - bullet after the first down and misalign the two columns. */ -.timeline__card--expanded .timeline__bullets > :not([hidden]) ~ :not([hidden]) { - margin-top: 0; -} - -.timeline__card--expanded .timeline__bullet { - @apply text-base; - /* Each bullet takes one column */ - break-inside: avoid; -} - -.timeline__card--expanded .timeline__terminal { - @apply col-span-2 mt-6; -} - -.timeline__bullet::before { - content: "▸"; - @apply absolute left-0 text-theme-cyan font-bold; -} - -/* Enhanced terminal footer */ -.timeline__terminal { - @apply bg-gray-800 rounded p-3 font-mono text-sm flex items-center gap-2 mt-4; - transition: box-shadow 0.3s ease; -} - -.timeline__prompt { - @apply text-green-400; -} - -.timeline__cursor { - @apply text-white animate-pulse; -} - -.timeline__hack-text { - @apply text-red-400 font-bold; - animation: typewriter 2s steps(30) infinite; -} - -@keyframes typewriter { - 0%, 50% { opacity: 1; } - 51%, 100% { opacity: 0; } -} - -/* Enhanced border effects */ -.timeline__border-effect { - @apply absolute inset-0 rounded-lg pointer-events-none; - background: linear-gradient( - 45deg, - transparent 30%, - rgba(100, 255, 218, 0.1) 50%, - transparent 70% - ); - background-size: 200% 200%; - animation: borderScan 3s ease-in-out infinite; -} - -/* Enhanced data streams */ -.timeline__data-streams { - @apply absolute inset-0 pointer-events-none overflow-hidden rounded-lg; -} - -.timeline__data-stream { - @apply absolute w-0.5 h-4 rounded-full; - background: linear-gradient(to bottom, transparent, #64ffda, transparent); - box-shadow: 0 0 6px #64ffda; -} - -.timeline__data-stream--1 { - @apply left-4; -} - -.timeline__data-stream--2 { - @apply right-4; -} - -.timeline__data-stream--3 { - transform: translateX(-50%); /* was @apply transform -translate-x-1/2 */ - @apply left-1/2; -} - -/* Glitch overlay */ -.timeline__glitch-overlay { - @apply absolute inset-0 bg-red-500 mix-blend-multiply rounded-lg pointer-events-none; - opacity: 0.1; -} - /* Enhanced background effects */ .timeline__background-effects { @apply absolute inset-0 pointer-events-none overflow-hidden; @@ -510,12 +227,6 @@ 50% { opacity: 0.3; } } -/* Mouse trail effects */ -.timeline__mouse-trail { - pointer-events: none; - z-index: 9999; -} - /* Responsive design */ @media (max-width: 768px) { /* Tailwind 3 `space-y-12` behaviour (see the space-y note in tailwind.css) */ @@ -528,22 +239,6 @@ @apply justify-center; } - .timeline__entry--left .timeline__card, - .timeline__entry--right .timeline__card { - @apply mx-auto max-w-sm; - margin-left: auto; - margin-right: auto; - } - - .timeline__card { - @apply max-w-sm; - } - - .timeline__card--expanded { - max-width: calc(100vw - 4rem); - width: calc(100vw - 4rem); - } - .timeline__line { @apply left-8; } @@ -553,34 +248,6 @@ .timeline__connector { display: none; } - - .timeline__secret-message { - @apply max-w-xs px-4 py-2 text-xs; - } - - .timeline__achievement { - @apply text-xs px-3 py-1 max-w-64; - } - - /* Mobile layout for expanded cards */ - .timeline__card--expanded .timeline__content { - display: block; - gap: 0; - } - - .timeline__card--expanded .timeline__classification { - @apply col-span-1 mb-4; - } - - .timeline__card--expanded .timeline__bullets { - @apply col-span-1; - display: block; - gap: 0; - } - - .timeline__card--expanded .timeline__terminal { - @apply col-span-1 mt-4; - } } /* Variants with enhanced effects */ @@ -681,12 +348,7 @@ will-change: transform; } -.timeline__card { - contain: layout style paint; -} - -.timeline__data-stream, .timeline__particle, .timeline__matrix-particle { contain: strict; -} \ No newline at end of file +} diff --git a/src/components/molecules/Timeline/TimelineCard.css b/src/components/molecules/Timeline/TimelineCard.css new file mode 100644 index 00000000..6c38a65d --- /dev/null +++ b/src/components/molecules/Timeline/TimelineCard.css @@ -0,0 +1,313 @@ +@reference "../../../assets/css/tailwind.css"; + +@keyframes borderScan { + 0%, 100% { background-position: 0% 50%; } + 50% { background-position: 100% 50%; } +} + +/* Enhanced experience card */ +.timeline__card { + @apply relative bg-gray-900 border border-gray-700 rounded-lg p-6 max-w-md; + background: linear-gradient(135deg, rgba(31, 41, 55, 0.95), rgba(17, 24, 39, 0.95)); + backdrop-filter: blur(10px); + transition: all 0.3s ease; + overflow: hidden; +} + +.timeline__entry--left .timeline__card { + @apply mr-auto; + margin-right: calc(50% + 2rem); +} + +.timeline__entry--right .timeline__card { + @apply ml-auto; + margin-left: calc(50% + 2rem); +} + +/* Full width override for expanded cards */ +.timeline__entry--left .timeline__card--expanded, +.timeline__entry--right .timeline__card--expanded { + @apply mx-auto; + margin-left: auto; + margin-right: auto; +} + +.timeline__card--expanded { + @apply border-theme-cyan/30; + max-width: calc(100vw - 8rem); + width: 100%; + z-index: 30; /* Higher than timeline line */ + box-shadow: + 0 10px 40px rgba(0, 0, 0, 0.3), + 0 0 20px rgba(100, 255, 218, 0.2); + background: linear-gradient(135deg, rgba(31, 41, 55, 0.98), rgba(17, 24, 39, 0.98)); +} + +.timeline__card--clicked { + border-color: rgba(239, 68, 68, 0.5); + box-shadow: 0 0 20px rgba(239, 68, 68, 0.3); +} + +/* Holographic overlay for hack modes */ +.timeline__hologram { + @apply absolute inset-0 rounded-lg pointer-events-none; + background: linear-gradient(45deg, transparent, rgba(100, 255, 218, 0.1), transparent); + background-size: 200% 200%; +} + +/* Enhanced security badge */ +.timeline__security-badge { + @apply absolute top-2 right-2 bg-theme-cyan text-gray-900 rounded-full px-3 py-1 flex items-center gap-1 text-sm font-bold z-10; + box-shadow: 0 0 15px rgba(100, 255, 218, 0.5); + transition: all 0.3s ease; +} + +.timeline__badge-icon { + @apply text-xs; +} + +.timeline__badge-text { + @apply text-xs; +} + +/* Company logo with enhanced effects */ +.timeline__logo { + @apply mb-4 flex justify-center; +} + +.timeline__logo-image { + @apply w-12 h-12 rounded-lg object-contain; + transition: all 0.3s ease; +} + +/* Card header */ +.timeline__header { + @apply mb-4; +} + +.timeline__role { + @apply text-white text-lg font-bold mb-2; + transition: color 0.3s ease; +} + +.timeline__company-info { + @apply flex flex-col gap-1; +} + +.timeline__company { + @apply text-theme-cyan font-semibold; +} + +.timeline__date { + @apply text-gray-400 text-sm; +} + +/* Improved layout for expanded cards */ +.timeline__card--expanded .timeline__header { + @apply text-center mb-6; +} + +.timeline__card--expanded .timeline__role { + @apply text-xl; +} + +.timeline__card--expanded .timeline__company-info { + @apply items-center; +} + +/* Expandable content */ +.timeline__content { + @apply border-t border-gray-700 pt-4 mt-4; + perspective: 1000px; +} + +.timeline__classification { + @apply mb-4 pb-2 border-b border-red-500/30; + transition: background-color 0.3s ease; +} + +.timeline__classification-label { + @apply bg-red-500 text-white px-2 py-1 rounded text-xs font-bold; + transition: all 0.3s ease; +} + +.timeline__description { + @apply text-gray-300 mb-4 leading-relaxed; + transition: text-shadow 0.3s ease; +} + +.timeline__bullets { + @apply list-none mb-4; +} + +/* Tailwind 3 `space-y-2` behaviour (see the space-y note in tailwind.css) */ +.timeline__bullets > :not([hidden]) ~ :not([hidden]) { + margin-top: var(--spacing-2); + margin-bottom: 0; +} + +.timeline__bullet { + @apply text-gray-300 text-sm relative pl-6; + transition: all 0.3s ease; +} + +/* Improved content layout for expanded cards */ +.timeline__card--expanded .timeline__content { + @apply pt-6 mt-6; + display: grid; + grid-template-columns: 1fr 1fr; + gap: 2rem; + align-items: start; +} + +.timeline__card--expanded .timeline__classification { + @apply col-span-2 text-center mb-6 pb-4; +} + +.timeline__card--expanded .timeline__description { + @apply text-base leading-relaxed mt-4 text-center; + /* Description is now structurally inside classification */ +} + +.timeline__card--expanded .timeline__bullets { + @apply col-span-2; + /* Bullets now span both columns and use CSS Grid */ + display: grid; + grid-template-columns: 1fr 1fr; + gap: 1rem 2rem; + align-items: start; +} + +/* Grid gap handles the spacing; the stacked-list margins would push every + bullet after the first down and misalign the two columns. */ +.timeline__card--expanded .timeline__bullets > :not([hidden]) ~ :not([hidden]) { + margin-top: 0; +} + +.timeline__card--expanded .timeline__bullet { + @apply text-base; + /* Each bullet takes one column */ + break-inside: avoid; +} + +.timeline__card--expanded .timeline__terminal { + @apply col-span-2 mt-6; +} + +.timeline__bullet::before { + content: "▸"; + @apply absolute left-0 text-theme-cyan font-bold; +} + +/* Enhanced terminal footer */ +.timeline__terminal { + @apply bg-gray-800 rounded p-3 font-mono text-sm flex items-center gap-2 mt-4; + transition: box-shadow 0.3s ease; +} + +.timeline__prompt { + @apply text-green-400; +} + +.timeline__cursor { + @apply text-white animate-pulse; +} + +.timeline__hack-text { + @apply text-red-400 font-bold; + animation: typewriter 2s steps(30) infinite; +} + +@keyframes typewriter { + 0%, 50% { opacity: 1; } + 51%, 100% { opacity: 0; } +} + +/* Enhanced border effects */ +.timeline__border-effect { + @apply absolute inset-0 rounded-lg pointer-events-none; + background: linear-gradient( + 45deg, + transparent 30%, + rgba(100, 255, 218, 0.1) 50%, + transparent 70% + ); + background-size: 200% 200%; + animation: borderScan 3s ease-in-out infinite; +} + +/* Enhanced data streams */ +.timeline__data-streams { + @apply absolute inset-0 pointer-events-none overflow-hidden rounded-lg; +} + +.timeline__data-stream { + @apply absolute w-0.5 h-4 rounded-full; + background: linear-gradient(to bottom, transparent, #64ffda, transparent); + box-shadow: 0 0 6px #64ffda; +} + +.timeline__data-stream--1 { + @apply left-4; +} + +.timeline__data-stream--2 { + @apply right-4; +} + +.timeline__data-stream--3 { + transform: translateX(-50%); /* was @apply transform -translate-x-1/2 */ + @apply left-1/2; +} + +/* Glitch overlay */ +.timeline__glitch-overlay { + @apply absolute inset-0 bg-red-500 mix-blend-multiply rounded-lg pointer-events-none; + opacity: 0.1; +} + +@media (max-width: 768px) { + .timeline__entry--left .timeline__card, + .timeline__entry--right .timeline__card { + @apply mx-auto max-w-sm; + margin-left: auto; + margin-right: auto; + } + + .timeline__card { + @apply max-w-sm; + } + + .timeline__card--expanded { + max-width: calc(100vw - 4rem); + width: calc(100vw - 4rem); + } + + /* Mobile layout for expanded cards */ + .timeline__card--expanded .timeline__content { + display: block; + gap: 0; + } + + .timeline__card--expanded .timeline__classification { + @apply col-span-1 mb-4; + } + + .timeline__card--expanded .timeline__bullets { + @apply col-span-1; + display: block; + gap: 0; + } + + .timeline__card--expanded .timeline__terminal { + @apply col-span-1 mt-4; + } +} + +.timeline__card { + contain: layout style paint; +} + +.timeline__data-stream { + contain: strict; +} diff --git a/src/components/molecules/Timeline/TimelineCard.tsx b/src/components/molecules/Timeline/TimelineCard.tsx index 7af73170..42a94c0a 100644 --- a/src/components/molecules/Timeline/TimelineCard.tsx +++ b/src/components/molecules/Timeline/TimelineCard.tsx @@ -1,6 +1,6 @@ import React from 'react'; import { motion, AnimatePresence, Transition, TargetAndTransition } from 'framer-motion'; -import './Timeline.css'; +import './TimelineCard.css'; import type { Experience } from '@/types/portfolio'; const CYAN_GLOW = (alpha: number) => `rgba(100, 255, 218, ${alpha})`; diff --git a/src/components/molecules/Timeline/TimelineEasterEggOverlay.css b/src/components/molecules/Timeline/TimelineEasterEggOverlay.css new file mode 100644 index 00000000..5a54777b --- /dev/null +++ b/src/components/molecules/Timeline/TimelineEasterEggOverlay.css @@ -0,0 +1,34 @@ +@reference "../../../assets/css/tailwind.css"; + +/* Secret message overlay */ +.timeline__secret-message { + transform: translateX(-50%); /* was @apply transform -translate-x-1/2 */ + @apply fixed top-20 left-1/2 z-50 bg-gray-900 border border-theme-cyan text-theme-cyan px-6 py-3 rounded-lg font-mono text-sm font-bold; + box-shadow: 0 0 20px rgba(100, 255, 218, 0.5); + backdrop-filter: blur(10px); + background: linear-gradient(135deg, rgba(31, 41, 55, 0.95), rgba(17, 24, 39, 0.95)); +} + +/* Achievement notifications */ +.timeline__achievement { + @apply fixed right-4 z-50 bg-green-500 text-white px-4 py-2 rounded-lg font-bold text-sm; + box-shadow: 0 4px 15px rgba(34, 197, 94, 0.4); + backdrop-filter: blur(10px); + max-width: 300px; +} + +/* Mouse trail effects */ +.timeline__mouse-trail { + pointer-events: none; + z-index: 9999; +} + +@media (max-width: 768px) { + .timeline__secret-message { + @apply max-w-xs px-4 py-2 text-xs; + } + + .timeline__achievement { + @apply text-xs px-3 py-1 max-w-64; + } +} diff --git a/src/components/molecules/Timeline/TimelineEasterEggOverlay.tsx b/src/components/molecules/Timeline/TimelineEasterEggOverlay.tsx index 6d11078a..c4db62cd 100644 --- a/src/components/molecules/Timeline/TimelineEasterEggOverlay.tsx +++ b/src/components/molecules/Timeline/TimelineEasterEggOverlay.tsx @@ -1,6 +1,6 @@ import React, { useEffect } from 'react'; import { motion, AnimatePresence } from 'framer-motion'; -import './Timeline.css'; +import './TimelineEasterEggOverlay.css'; import type { TimelineTrailPoint } from './useTimelineEasterEggs'; /** How long an achievement toast stays before asking to be dismissed. */ diff --git a/src/components/organisms/Feedbacks/Feedbacks.tsx b/src/components/organisms/Feedbacks/Feedbacks.tsx index 7d9f26a2..5673ef92 100644 --- a/src/components/organisms/Feedbacks/Feedbacks.tsx +++ b/src/components/organisms/Feedbacks/Feedbacks.tsx @@ -4,6 +4,7 @@ import FeedbackCard from '@molecules/FeedbackCard'; import Section from '../../layout/Section'; import useFeedback from "@hooks/useFeedback"; import { useAnimation } from "@context/AnimationContext"; +import { slideUpVariants } from "@utils/motion"; /** * Feedbacks section displaying testimonials and recommendations. @@ -13,7 +14,7 @@ import { useAnimation } from "@context/AnimationContext"; */ const Feedbacks = () => { const feedbacks = useFeedback(); - const { animationEnabled, slideUpVariants } = useAnimation(); + const { animationEnabled } = useAnimation(); // Animation config for framer-motion using AnimationContext const animation: MotionProps = { diff --git a/src/components/organisms/GithubProfile/GithubProfile.test.tsx b/src/components/organisms/GithubProfile/GithubProfile.test.tsx index 53a250c4..8895b471 100644 --- a/src/components/organisms/GithubProfile/GithubProfile.test.tsx +++ b/src/components/organisms/GithubProfile/GithubProfile.test.tsx @@ -16,12 +16,6 @@ vi.mock('axios', () => { vi.mock('@context/AnimationContext', () => ({ useAnimation: () => ({ animationEnabled: false, - animationStaggerDelay: 0, - fadeInVariants: { hidden: { opacity: 0 }, visible: { opacity: 1 } }, - slideUpVariants: { - hidden: { opacity: 0, y: 20 }, - visible: { opacity: 1, y: 0 } - } }) })); diff --git a/src/components/organisms/GithubProfile/GithubProfile.tsx b/src/components/organisms/GithubProfile/GithubProfile.tsx index dfad2675..242d1866 100644 --- a/src/components/organisms/GithubProfile/GithubProfile.tsx +++ b/src/components/organisms/GithubProfile/GithubProfile.tsx @@ -6,6 +6,7 @@ import GithubProfileCard from '@molecules/GithubProfileCard'; import { motion } from "framer-motion"; import Section from '../../layout/Section'; import { useAnimation } from "@context/AnimationContext"; +import { slideUpVariants } from "@utils/motion"; import './GithubProfile.css'; // Requests are deliberately unauthenticated. Anything in the browser bundle is @@ -54,7 +55,7 @@ const GithubProfile = ({ id = 'contact' }: GithubProfileProps) => { const [prof, setProf] = useState({}); // Use animation context for animation values - const { slideUpVariants, animationEnabled } = useAnimation(); + const { animationEnabled } = useAnimation(); // Validate GitHub username const validateGithubUsername = (username: string) => { diff --git a/src/components/organisms/Greetings/Greetings.tsx b/src/components/organisms/Greetings/Greetings.tsx index df8fa57d..7432e2f1 100644 --- a/src/components/organisms/Greetings/Greetings.tsx +++ b/src/components/organisms/Greetings/Greetings.tsx @@ -7,13 +7,14 @@ import SocialLinks from '@molecules/SocialLinks'; import { profileLinks } from '@/portfolio'; import ScrollDown from '@atoms/ScrollDown'; import useCallbackHandlers from '@/hooks/useCallbackHandlers'; -import { useAnimation, MotionVariants } from '@context/AnimationContext'; +import { useAnimation } from '@context/AnimationContext'; +import { fadeInVariants, slideUpVariants } from '@utils/motion'; import './Greetings.css'; const Greetings = () => { const greetings = useGreetings(); const { handleDownload } = useCallbackHandlers(); - const { animationEnabled, fadeInVariants, slideUpVariants } = useAnimation(); + const { animationEnabled } = useAnimation(); const scrollToNextSection = () => { const nextSection = document.querySelector('#greetings-section')?.nextElementSibling; diff --git a/src/components/organisms/Proficiency/Proficiency.tsx b/src/components/organisms/Proficiency/Proficiency.tsx index 12920003..fa0c2639 100644 --- a/src/components/organisms/Proficiency/Proficiency.tsx +++ b/src/components/organisms/Proficiency/Proficiency.tsx @@ -2,6 +2,7 @@ import React, { useRef } from 'react'; import { SkillBars } from "@/portfolio"; import { motion, useInView, Variants } from "framer-motion"; import { useAnimation } from "@context/AnimationContext"; +import { slideUpVariants, STAGGER_DELAY } from "@utils/motion"; import Progress from '@atoms/Progress'; import Section from '../../layout/Section'; @@ -18,7 +19,7 @@ interface ProgressBarProps { const ProgressBar = ({ skill, index }: ProgressBarProps) => { const ref = useRef(null); const isInView = useInView(ref, { once: true, margin: "-100px 0px" }); - const { slideUpVariants, animationEnabled, animationStaggerDelay } = useAnimation(); + const { animationEnabled } = useAnimation(); // Create a custom variant based on the slideUpVariants but with x axis movement const slideInVariant: Variants = { @@ -28,7 +29,7 @@ const ProgressBar = ({ skill, index }: ProgressBarProps) => { x: 0, transition: { duration: 0.5, - delay: animationStaggerDelay * index, + delay: STAGGER_DELAY * index, ease: "easeOut" } } diff --git a/src/components/organisms/Projects/Projects.tsx b/src/components/organisms/Projects/Projects.tsx index fa1525e8..1400acad 100644 --- a/src/components/organisms/Projects/Projects.tsx +++ b/src/components/organisms/Projects/Projects.tsx @@ -7,6 +7,7 @@ import useMemoValues from "@hooks/useMemoValues"; import type { MemoValuesData } from "@hooks/useMemoValues"; import { usePortfolio } from "@context/PortfolioContext"; import { useAnimation } from "@context/AnimationContext"; +import { slideUpVariants, STAGGER_DELAY } from "@utils/motion"; import { motion, Variants } from "framer-motion"; import type { PortfolioData, Project } from '@/types/portfolio'; import './Projects.css'; @@ -47,7 +48,7 @@ const Projects = () => { const topProjects = memoValues.topProjects as unknown as Project[]; // Get animation context values - const { animationEnabled, slideUpVariants, animationStaggerDelay } = useAnimation(); + const { animationEnabled } = useAnimation(); // Get loading delay from context or use default (demonstrates skeleton loading) const loadingDelay = portfolioData?.settings?.loadingDelay || 0; @@ -89,11 +90,11 @@ const Projects = () => { visible: { opacity: 1, transition: { - staggerChildren: animationStaggerDelay, + staggerChildren: STAGGER_DELAY, delayChildren: 0.2 } } - }), [animationStaggerDelay]); + }), []); // Render loading state if projects data is not available if (isLoading) { diff --git a/src/components/organisms/Skills/Skills.tsx b/src/components/organisms/Skills/Skills.tsx index 0eddf96f..a361e071 100644 --- a/src/components/organisms/Skills/Skills.tsx +++ b/src/components/organisms/Skills/Skills.tsx @@ -9,6 +9,7 @@ import Section from '../../layout/Section'; import useSkills from "@hooks/useSkills"; import { usePortfolio } from "@context/PortfolioContext"; import { useAnimation } from '@context/AnimationContext'; +import { slideUpVariants, fadeInVariants, STAGGER_DELAY } from '@utils/motion'; import type { PortfolioData, Skill, SkillsSection } from '@/types/portfolio'; import '@assets/css/tailwind.css'; import './Skills.css'; @@ -34,12 +35,7 @@ const Skills = () => { const portfolioData: PortfolioData & SkillsSettingsConfig = usePortfolio(); // Get animation context - const { - animationEnabled, - slideUpVariants, - fadeInVariants, - animationStaggerDelay - } = useAnimation(); + const { animationEnabled } = useAnimation(); // Get loading delay from context or use default (demonstrates skeleton loading) const loadingDelay = portfolioData?.settings?.loadingDelay || 0; @@ -112,10 +108,10 @@ const Skills = () => { transition: { delay: shouldAnimate ? 0.6 : 0.3, duration: shouldAnimate ? 0.5 : 0.3, - staggerChildren: shouldAnimate ? animationStaggerDelay : animationStaggerDelay / 2 + staggerChildren: shouldAnimate ? STAGGER_DELAY : STAGGER_DELAY / 2 } } - }), [shouldAnimate, animationStaggerDelay]); + }), [shouldAnimate]); // Function to generate staggered animations for skill text items - optimized version const getSkillTextVariants = useMemo(() => (index: number | string): Variants => { @@ -137,10 +133,10 @@ const Skills = () => { visible: { opacity: 1, x: 0, - transition: { delay: 0.3 + (numIndex * animationStaggerDelay) } + transition: { delay: 0.3 + (numIndex * STAGGER_DELAY) } } }; - }, [shouldAnimate, animationStaggerDelay]); + }, [shouldAnimate]); // Group skills by security domain const groupedSkills = useMemo(() => { diff --git a/src/context/AnimationContext.tsx b/src/context/AnimationContext.tsx index f75073b2..2b84fab8 100644 --- a/src/context/AnimationContext.tsx +++ b/src/context/AnimationContext.tsx @@ -1,14 +1,7 @@ -// Use named imports to allow tree-shaking in production builds -import { useState, useCallback, useEffect, useMemo, ReactElement, useRef } from 'react'; -import type { ReactNode, Dispatch, SetStateAction } from 'react'; -import { createTypedContext } from '@utils/contextUtils'; -import { useAnimation as useFramerAnimation, Variants } from 'framer-motion'; -import useAnimationOptimization from '@hooks/useAnimationOptimization'; +import { createContext, useContext, useEffect, useMemo, useState } from 'react'; +import type { ReactElement, ReactNode } from 'react'; +import { MotionConfig } from 'framer-motion'; -// framer-motion 14 no longer exports AnimationControls -type AnimationControls = ReturnType; - -// At the top of the file, add this declaration for the global window object declare global { interface Window { __DEBUG_FLAGS?: { @@ -20,625 +13,77 @@ declare global { } } -// Animation Context Types -export interface AnimationState { - [key: string]: 'hidden' | 'visible' | string; -} - export interface AnimationContextType { - inView: boolean; - setInView: Dispatch>; + /** False when the visitor prefers reduced motion or animations are switched off for debugging */ animationEnabled: boolean; - entryAnimations: AnimationState; - registerEntryAnimation: (id: string, initialState?: string) => void; - playEntryAnimation: (id: string, delay?: number) => void; - resetEntryAnimations: () => void; - animationStaggerDelay: number; - getAnimationDelay: (index: number) => string; - // New framer-motion specific properties - controls: AnimationControls; - getVariants: (duration?: number, delay?: number) => Variants; - fadeInVariants: Variants; - slideUpVariants: Variants; - scaleVariants: Variants; - pulseVariants: Variants; - matrixVariants: Variants; - glitchVariants: Variants; - - // Animation optimization properties + /** The visitor's OS-level reduced-motion preference */ prefersReducedMotion: boolean; - isLowPowerDevice: boolean; - optimizeVariants: (variants: Variants, options?: any) => Variants; - - // Performance monitoring (dev only) - enablePerformanceMonitoring: (options?: any) => void; - disablePerformanceMonitoring: () => void; } -// Define standard variants to use across components -const defaultFadeIn: Variants = { - hidden: { opacity: 0 }, - visible: { opacity: 1, transition: { duration: 0.5 } } -}; - -const defaultSlideUp: Variants = { - hidden: { opacity: 0, y: 20 }, - visible: { opacity: 1, y: 0, transition: { duration: 0.5 } } -}; - -const defaultScale: Variants = { - hidden: { opacity: 0, scale: 0.8 }, - visible: { opacity: 1, scale: 1, transition: { duration: 0.5 } } -}; - -const defaultPulse: Variants = { - hidden: { opacity: 0.6 }, - visible: { - opacity: [0.6, 1, 0.6], - transition: { - repeat: Infinity, - duration: 2, - ease: "easeInOut" - } - } -}; - -const defaultMatrix: Variants = { - hidden: { opacity: 0 }, - visible: { - opacity: 1, - transition: { - duration: 0.8, - staggerChildren: 0.05 - } - } -}; - -const defaultGlitch: Variants = { - hidden: { opacity: 0 }, - visible: { - opacity: 1, - x: [0, -2, 3, -1, 0], - transition: { - duration: 0.5, - x: { - repeat: Infinity, - repeatType: "reverse", - duration: 0.2 - } - } - } -}; - -/** - * Default values for the animation context - */ const defaultAnimationContext: AnimationContextType = { - inView: false, - setInView: () => {}, animationEnabled: true, - animationStaggerDelay: 0.15, - entryAnimations: {}, - registerEntryAnimation: () => {}, - playEntryAnimation: () => {}, - resetEntryAnimations: () => {}, - getAnimationDelay: () => String(), - // New framer-motion defaults - controls: {} as AnimationControls, - getVariants: () => ({}), - fadeInVariants: defaultFadeIn, - slideUpVariants: defaultSlideUp, - scaleVariants: defaultScale, - pulseVariants: defaultPulse, - matrixVariants: defaultMatrix, - glitchVariants: defaultGlitch, - - // Default optimization values prefersReducedMotion: false, - isLowPowerDevice: false, - optimizeVariants: (variants) => variants, - - // Default performance monitoring functions (no-ops) - enablePerformanceMonitoring: () => {}, - disablePerformanceMonitoring: () => {} }; -/** - * Animation Context for coordinating animations across components - * Using the decoupled factory pattern - */ -const { - context: AnimationContext, - useTypedContext: useAnimation, - Provider: AnimationContextProvider -} = createTypedContext(defaultAnimationContext, 'useAnimation'); +export const AnimationContext = createContext(defaultAnimationContext); + +/** Read the animation settings. Works without a provider (animations on). */ +export const useAnimation = (): AnimationContextType => useContext(AnimationContext); export interface AnimationProviderProps { children: ReactNode; } /** - * Animation Provider component - * - * @component - * @param {AnimationProviderProps} props - Component props - * @returns {JSX.Element} Provider component + * Provides `animationEnabled` and `prefersReducedMotion`, and applies the + * visitor's reduced-motion preference to every Framer Motion component below. */ export const AnimationProvider = ({ children }: AnimationProviderProps): ReactElement => { - // Animation settings - const [inView, setInView] = useState(false); - const [animationEnabled, setAnimationEnabled] = useState(true); - const [entryAnimations, setEntryAnimations] = useState({}); - const [animationStaggerDelay, setAnimationStaggerDelay] = useState(0.15); - - // Store played animations in a ref to prevent re-renders - const playedAnimationsRef = useRef>(new Set()); - - // Initialize framer-motion animation controls - const controls = useFramerAnimation(); - - /** - * Helper to generate variants with custom timing - */ - const getVariants = useCallback((duration: number = 0.5, delay: number = 0): Variants => { - return { - hidden: { opacity: 0 }, - visible: { - opacity: 1, - transition: { - duration, - delay - } - } - }; - }, []); - - // Add animation optimization - const { - prefersReducedMotion, - isLowPowerDevice, - optimizeVariants - } = useAnimationOptimization(); - - // Types for performance monitoring - interface PerformanceMonitorOptions { - threshold?: number; - reportingInterval?: number; - debug?: boolean; - } - - // Add performance monitoring (dev only) - const enablePerformanceMonitoring = (options: Partial = {}) => { - if (import.meta.env.DEV && typeof window !== 'undefined') { - // Use dynamic import only in development - import('@scripts/monitor-animation-performance') - .then(module => { - try { - const monitor = module.default; - - // Check if browser supports required features - if (typeof window.PerformanceObserver !== 'undefined') { - monitor.start({ - threshold: 16, - reportingInterval: 3000, - debug: true, - ...options - }); - } else { - console.info('Animation performance monitoring is not fully supported in this browser. Some features will be limited.'); - monitor.start({ - threshold: 16, - reportingInterval: 3000, - debug: true, - ...options - }); - } - } catch (error) { - console.error('Error initializing animation performance monitoring:', error); - console.info('Animation performance monitoring will be disabled. This will not affect the application functionality.'); - } - }) - .catch(err => { - console.warn('Failed to load animation performance monitor:', err.message); - }); - } - }; - - const disablePerformanceMonitoring = () => { - if (import.meta.env.DEV && typeof window !== 'undefined') { - // Use dynamic import only in development - import('@scripts/monitor-animation-performance') - .then(module => { - try { - const monitor = module.default; - monitor.stop(); - } catch (error) { - console.error('Error stopping animation performance monitor:', error); - } - }) - .catch(err => { - console.warn('Failed to load animation performance monitor:', err.message); - }); - } - }; + const [prefersReducedMotion, setPrefersReducedMotion] = useState(false); + // Switch controlled by the media query and the debug event/flag + const [switchedOn, setSwitchedOn] = useState(true); - // Adjust animationEnabled to respect optimization settings - const combinedAnimationEnabled = animationEnabled && !prefersReducedMotion; - - // Enhance all variant creators to use optimizeVariants - const enhancedGetVariants = (duration = 0.5, delay = 0) => { - const variants = getVariants(duration, delay); - return optimizeVariants(variants); - }; - - // Optimize standard variants - const optimizedFadeInVariants = optimizeVariants(defaultFadeIn); - const optimizedSlideUpVariants = optimizeVariants(defaultSlideUp); - const optimizedScaleVariants = optimizeVariants(defaultScale); - const optimizedPulseVariants = optimizeVariants(defaultPulse); - const optimizedMatrixVariants = optimizeVariants(defaultMatrix); - const optimizedGlitchVariants = optimizeVariants(defaultGlitch); - - // Check if reduced motion is preferred useEffect(() => { const mediaQuery = window.matchMedia('(prefers-reduced-motion: reduce)'); - + const handleChange = (e: MediaQueryListEvent | MediaQueryList) => { - setAnimationEnabled(!e.matches); - - // Reduce stagger delay for reduced motion - if (e.matches) { - setAnimationStaggerDelay(0.05); - } else { - setAnimationStaggerDelay(0.15); - } + setPrefersReducedMotion(e.matches); + setSwitchedOn(!e.matches); }; - - // Set initial value + handleChange(mediaQuery); - - // Listen for changes mediaQuery.addEventListener('change', handleChange); - - // Add listener for debug flag changes - const handleDebugToggle = (e: CustomEvent) => { - const isEnabled = !(e.detail?.enabled === false); - setAnimationEnabled(isEnabled); + + // Debug switch: anything but `enabled: false` turns animations on + const handleDebugToggle = (e: Event) => { + const detail = e instanceof CustomEvent ? (e.detail as { enabled?: boolean } | null) : null; + const isEnabled = !(detail?.enabled === false); + setSwitchedOn(isEnabled); console.log(`[AnimationContext] Animations ${isEnabled ? 'enabled' : 'disabled'}`); }; - - window.addEventListener('debug:toggle-animations', handleDebugToggle as EventListener); - - // Check for global debug flags + window.addEventListener('debug:toggle-animations', handleDebugToggle); + + // Initial debug flag overrides the media query value if (window.__DEBUG_FLAGS && 'disableAnimations' in window.__DEBUG_FLAGS) { - setAnimationEnabled(!window.__DEBUG_FLAGS.disableAnimations); + setSwitchedOn(!window.__DEBUG_FLAGS.disableAnimations); } - + return () => { mediaQuery.removeEventListener('change', handleChange); - window.removeEventListener('debug:toggle-animations', handleDebugToggle as EventListener); + window.removeEventListener('debug:toggle-animations', handleDebugToggle); }; }, []); - /** - * Register a new animation entry - */ - const registerEntryAnimation = useCallback((id: string, initialState: string = 'hidden') => { - // Only register if not already played - if (!playedAnimationsRef.current.has(id)) { - setEntryAnimations(prev => ({ - ...prev, - [id]: initialState - })); - } - }, []); - - /** - * Play animation for specific entry - */ - const playEntryAnimation = useCallback((id: string, delay: number = 0) => { - // Skip if already played - if (playedAnimationsRef.current.has(id)) { - return; - } - - // If animations disabled, immediately set to visible - if (!animationEnabled) { - setEntryAnimations(prev => ({ - ...prev, - [id]: 'visible' - })); - playedAnimationsRef.current.add(id); - return; - } + const animationEnabled = switchedOn && !prefersReducedMotion; - // Otherwise play with delay - setTimeout(() => { - setEntryAnimations(prev => ({ - ...prev, - [id]: 'visible' - })); - playedAnimationsRef.current.add(id); - }, delay * 1000); - }, [animationEnabled]); - - /** - * Reset all animations - */ - const resetEntryAnimations = useCallback(() => { - setEntryAnimations({}); - playedAnimationsRef.current.clear(); - }, []); - - /** - * Get animation delay based on index - */ - const getAnimationDelay = useCallback((index: number): string => { - return `${index * animationStaggerDelay}s`; - }, [animationStaggerDelay]); - - // Memoize context value to prevent unnecessary re-renders - const contextValue = useMemo(() => ({ - inView, - setInView, - animationEnabled: combinedAnimationEnabled, - entryAnimations, - registerEntryAnimation, - playEntryAnimation, - resetEntryAnimations, - animationStaggerDelay, - getAnimationDelay, - controls, - getVariants: enhancedGetVariants, - fadeInVariants: optimizedFadeInVariants, - slideUpVariants: optimizedSlideUpVariants, - scaleVariants: optimizedScaleVariants, - pulseVariants: optimizedPulseVariants, - matrixVariants: optimizedMatrixVariants, - glitchVariants: optimizedGlitchVariants, - prefersReducedMotion, - isLowPowerDevice, - optimizeVariants, - enablePerformanceMonitoring, - disablePerformanceMonitoring - }), [ - inView, - combinedAnimationEnabled, - entryAnimations, - registerEntryAnimation, - playEntryAnimation, - resetEntryAnimations, - animationStaggerDelay, - getAnimationDelay, - controls, - enhancedGetVariants, - optimizedFadeInVariants, - optimizedSlideUpVariants, - optimizedScaleVariants, - optimizedPulseVariants, - optimizedMatrixVariants, - optimizedGlitchVariants, - prefersReducedMotion, - isLowPowerDevice, - optimizeVariants - ]); + const value = useMemo( + () => ({ animationEnabled, prefersReducedMotion }), + [animationEnabled, prefersReducedMotion] + ); return ( - - {children} - + + {children} + ); }; - -// Export the context and hook -export { AnimationContext, useAnimation }; - -// Export animation variants for direct import -export const MotionVariants = { - fadeIn: defaultFadeIn, - slideUp: defaultSlideUp, - scale: defaultScale, - pulse: defaultPulse, - matrix: defaultMatrix, - glitch: defaultGlitch, - - // Specialized variants - container: { - hidden: { opacity: 0 }, - visible: { - opacity: 1, - transition: { - staggerChildren: 0.1 - } - } - }, - - item: { - hidden: { opacity: 0, y: 20 }, - visible: { - opacity: 1, - y: 0, - transition: { - duration: 0.5 - } - } - }, - - // Binary stream variants by position - binaryLeft: { - hidden: { opacity: 0 }, - visible: (delay: number) => ({ - opacity: [0, 0.8, 0], - y: [-10, 0, 10], - transition: { - delay, - duration: 3, - repeat: Infinity, - repeatDelay: Math.random() * 2 - } - }) - }, - - binaryRight: { - hidden: { opacity: 0 }, - visible: (delay: number) => ({ - opacity: [0, 0.8, 0], - y: [10, 0, -10], - transition: { - delay, - duration: 3, - repeat: Infinity, - repeatDelay: Math.random() * 2 - } - }) - }, - - binaryTop: { - hidden: { opacity: 0 }, - visible: (delay: number) => ({ - opacity: [0, 0.8, 0], - x: [-10, 0, 10], - transition: { - delay, - duration: 3, - repeat: Infinity, - repeatDelay: Math.random() * 2 - } - }) - }, - - binaryBottom: { - hidden: { opacity: 0 }, - visible: (delay: number) => ({ - opacity: [0, 0.8, 0], - x: [10, 0, -10], - transition: { - delay, - duration: 3, - repeat: Infinity, - repeatDelay: Math.random() * 2 - } - }) - }, - - // Timeline-specific variants - timeline: { - entry: { - hidden: { opacity: 0, y: 20 }, - visible: { - opacity: 1, - y: 0, - transition: { - duration: 0.5, - ease: "easeOut" - } - } - }, - - connector: { - hidden: { opacity: 0, scale: 0.9 }, - visible: { - opacity: 1, - scale: 1, - transition: { - duration: 0.3, - ease: "easeOut" - } - } - }, - - line: { - hidden: { height: 0, opacity: 0 }, - visible: { - height: "100%", - opacity: 1, - transition: { - duration: 0.7, - ease: "easeInOut" - } - } - }, - - nodeLine: { - hidden: { width: 0, opacity: 0 }, - visible: { - width: "12px", - opacity: 1, - transition: { - duration: 0.3, - ease: "easeOut" - } - } - }, - - card: { - hidden: { opacity: 0, x: -10 }, - visible: { - opacity: 1, - x: 0, - transition: { - duration: 0.4, - ease: "easeOut" - } - }, - expanded: { - scale: 1.02, - boxShadow: "0 5px 15px rgba(0, 0, 0, 0.2)", - transition: { - duration: 0.3, - ease: "easeInOut" - } - } - }, - - dataFlow: { - hidden: { opacity: 0 }, - visible: { - opacity: [0, 0.8, 0], - x: [-10, 0, 10], - transition: { - duration: 2, - repeat: Infinity, - ease: "linear" - } - } - }, - - // Decryption animation - decrypt: { - hidden: { opacity: 0, width: "0%" }, - visible: { - opacity: 1, - width: "100%", - transition: { - duration: 0.7, - ease: "easeInOut" - } - } - }, - - // Type in/cursor animation - typing: { - hidden: { width: "0%" }, - visible: { - width: "100%", - transition: { - duration: 0.8, - ease: "steps(30, end)" - } - } - }, - - cursor: { - hidden: { opacity: 1 }, - visible: { - opacity: [1, 0, 1], - transition: { - duration: 0.8, - repeat: Infinity, - ease: "steps(2, start)" - } - } - } - } -}; diff --git a/src/context/__mocks__/AnimationContext.tsx b/src/context/__mocks__/AnimationContext.tsx deleted file mode 100644 index 9c8d87f7..00000000 --- a/src/context/__mocks__/AnimationContext.tsx +++ /dev/null @@ -1,148 +0,0 @@ -import React, { createContext } from 'react'; -import { vi } from 'vitest'; -import type { ReactNode } from 'react'; -import type { Variants } from 'framer-motion'; -import type { AnimationContextType } from '../AnimationContext'; - -// Define animation variants directly to avoid hoisting issues -const fadeInVariants: Variants = { - hidden: { opacity: 0 }, - visible: { opacity: 1, transition: { duration: 0.5 } } -}; - -const slideUpVariants: Variants = { - hidden: { opacity: 0, y: 20 }, - visible: { opacity: 1, y: 0, transition: { duration: 0.5 } } -}; - -const scaleVariants: Variants = { - hidden: { opacity: 0, scale: 0.8 }, - visible: { opacity: 1, scale: 1, transition: { duration: 0.5 } } -}; - -const staggerContainerVariants: Variants = { - hidden: { opacity: 0 }, - visible: { - opacity: 1, - transition: { - staggerChildren: 0.1, - delayChildren: 0.2 - } - } -}; - -const pulseVariants: Variants = { - hidden: { opacity: 0.6 }, - visible: { - opacity: [0.6, 1, 0.6], - transition: { - repeat: Infinity, - duration: 2, - ease: "easeInOut" - } - } -}; - -const matrixVariants: Variants = { - hidden: { opacity: 0 }, - visible: { - opacity: 1, - transition: { - duration: 0.8, - staggerChildren: 0.05 - } - } -}; - -const glitchVariants: Variants = { - hidden: { opacity: 0 }, - visible: { - opacity: 1, - x: [0, -2, 3, -1, 0], - transition: { - duration: 0.5, - x: { - repeat: Infinity, - repeatType: "reverse", - duration: 0.2 - } - } - } -}; - -// Create a mock context -export const AnimationContext = createContext(null); - -// Mock animation context value -const mockAnimationValue: AnimationContextType & { staggerContainerVariants: Variants } = { - inView: true, - setInView: vi.fn(), - animationEnabled: true, - entryAnimations: {}, - registerEntryAnimation: vi.fn(), - playEntryAnimation: vi.fn(), - resetEntryAnimations: vi.fn(), - animationStaggerDelay: 0.15, - getAnimationDelay: (index: number) => `${index * 0.1}s`, - // Framer-motion specific properties - // Only the control methods components call - controls: { - start: vi.fn(), - stop: vi.fn(), - set: vi.fn() - } as unknown as AnimationContextType['controls'], - getVariants: (duration = 0.5, delay = 0) => ({ - hidden: { opacity: 0 }, - visible: { - opacity: 1, - transition: { - duration, - delay - } - } - }), - fadeInVariants, - slideUpVariants, - scaleVariants, - pulseVariants, - matrixVariants, - glitchVariants, - staggerContainerVariants, - - // Animation optimization properties - prefersReducedMotion: false, - isLowPowerDevice: false, - optimizeVariants: (variants: Variants) => variants, - - // Performance monitoring (dev only) - enablePerformanceMonitoring: vi.fn(), - disablePerformanceMonitoring: vi.fn() -}; - -// Provider component for tests -export const AnimationProvider = ({ children }: { children: ReactNode }) => { - return ( -
- - {children} - -
- ); -}; - -// Custom hook to use the context -export const useAnimation = vi.fn().mockReturnValue(mockAnimationValue); - -export default { - AnimationContext, - AnimationProvider, - useAnimation, - // Export variants for direct import - fadeInVariants, - slideUpVariants, - scaleVariants, - staggerContainerVariants, - pulseVariants, - matrixVariants, - glitchVariants -}; \ No newline at end of file diff --git a/src/context/__mocks__/PortfolioContext.tsx b/src/context/__mocks__/PortfolioContext.tsx deleted file mode 100644 index c42ef2aa..00000000 --- a/src/context/__mocks__/PortfolioContext.tsx +++ /dev/null @@ -1,191 +0,0 @@ -import React, { createContext, useContext } from 'react'; -import type { ReactNode } from 'react'; -import type { Education } from '@/types/portfolio'; - -// Create a mock context with sample data -const PortfolioContext = createContext(null); - -// Sample data for tests -const mockPortfolioData = { - greetings: { - name: "Derek Mackley", - title: "Full Stack Developer", - description: "Passionate full stack developer with experience in building high-performance web applications.", - resumeLink: "https://example.com/resume" - }, - openSource: { - githubUserName: "derekmackley", - showGithubProfile: true - }, - contact: { - email: "test@example.com" - }, - socialLinks: { - github: "https://github.com/derekmackley", - linkedin: "https://www.linkedin.com/in/derekmackley", - twitter: "https://twitter.com/derekmackley" - }, - skillsSection: { - title: "Skills", - subTitle: "Professional capabilities and technologies", - display: true, - softwareSkills: [ - { - skillName: "React", - iconName: "logos:react", - category: "frontend" - }, - { - skillName: "Node.js", - iconName: "logos:nodejs", - category: "backend" - }, - { - skillName: "CSS", - fontAwesomeClassname: "fab fa-css3", - category: "frontend" - } - ], - skills: ["Skill 1", "Skill 2"], - }, - skillBars: [ - { Stack: "Frontend", progressPercentage: 90 }, - { Stack: "Backend", progressPercentage: 70 } - ], - educationSection: { - title: "Education", - subtitle: "Academic background", - display: true - }, - experienceSection: { - title: "Work Experience", - subtitle: "Professional journey", - display: true, - viewType: "timeline", - experiences: [ - { - role: "Software Engineer", - company: "Test Company 1", - companylogo: "/test-logo1.png", - date: "2022 - Present", - desc: "Leading development efforts", - descBullets: ["Led team of 5", "Deployed to production"] - }, - { - role: "Developer", - company: "Test Company 2", - companylogo: "/test-logo2.png", - date: "2020 - 2022", - desc: "Contributed to key projects", - descBullets: ["Built frontend", "Improved performance"] - } - ] - }, - projectsSection: { - title: "My Projects", - subtitle: "Things I've built", - display: true, - showTopProjectsOnly: false, - projects: [ - { - name: "Project 1", - desc: "A cool project", - image: "/project1.jpg", - github: "https://github.com/user/project1", - link: "https://project1.com", - stack: ["React", "Node.js"] - }, - { - name: "Project 2", - desc: "Another project", - image: "/project2.jpg", - github: "https://github.com/user/project2", - stack: ["Vue", "Express"] - } - ] - }, - feedbackSection: { - title: "Testimonials", - subtitle: "What others say about me", - display: true - }, - settings: { - isBlog: false, - colors: { - primary: "#3563E9", - secondary: "#5E72E4" - }, - theme: "light", - loadingDelay: 0 - } -}; - -// educationInfo is not in the sample data, so useEducation returns undefined -type MockPortfolioValue = typeof mockPortfolioData & { educationInfo?: Education[] }; - -// Provider component for tests -export const PortfolioProvider = ({ children }: { children: ReactNode }) => { - return ( - - {children} - - ); -}; - -// Custom hook to use the context -export const usePortfolio = () => { - const context = useContext(PortfolioContext); - if (context === null) { - throw new Error('usePortfolio must be used within a PortfolioProvider'); - } - return context; -}; - -// Section-specific hooks for more targeted data access -export const useGreetings = () => { - const { greetings } = usePortfolio(); - return greetings; -}; - -export const useSkills = () => { - const { skillsSection, skillBars } = usePortfolio(); - return { skillsSection, skillBars }; -}; - -export const useEducation = () => { - const { educationInfo } = usePortfolio(); - return educationInfo; -}; - -export const useExperience = () => { - const { experienceSection } = usePortfolio(); - return experienceSection; -}; - -export const useProjects = () => { - const { projectsSection } = usePortfolio(); - return projectsSection; -}; - -export const useFeedback = () => { - const { feedbackSection } = usePortfolio(); - return feedbackSection; -}; - -export const useSocialLinks = () => { - const { socialLinks } = usePortfolio(); - return socialLinks; -}; - -export default { - PortfolioContext, - PortfolioProvider, - usePortfolio, - useGreetings, - useSkills, - useEducation, - useExperience, - useProjects, - useFeedback, - useSocialLinks -}; \ No newline at end of file diff --git a/src/hooks/__mocks__/useExperience.ts b/src/hooks/__mocks__/useExperience.ts deleted file mode 100644 index 20fca3a2..00000000 --- a/src/hooks/__mocks__/useExperience.ts +++ /dev/null @@ -1,24 +0,0 @@ -// Mock implementation for useExperience hook -import { vi } from 'vitest'; -import type realUseExperience from '../useExperience'; - -const useExperience = vi.fn(() => [ - { - company: 'Test Company 1', - role: 'Senior Developer', - date: '2022 - Present', - desc: 'Leading development efforts', - companylogo: '/test-logo1.png', - descBullets: ['Led team of 5', 'Deployed to production'] - }, - { - company: 'Test Company 2', - role: 'Developer', - date: '2020 - 2022', - desc: 'Contributed to key projects', - companylogo: '/test-logo2.png', - descBullets: ['Built frontend', 'Improved performance'] - } -]); - -export default useExperience; diff --git a/src/hooks/__mocks__/useProjects.ts b/src/hooks/__mocks__/useProjects.ts deleted file mode 100644 index 86edd413..00000000 --- a/src/hooks/__mocks__/useProjects.ts +++ /dev/null @@ -1,23 +0,0 @@ -// Mock implementation for useProjects hook -import { vi } from 'vitest'; -import type realUseProjects from '../useProjects'; - -const useProjects = vi.fn(() => [ - { - name: 'Project 1', - desc: 'A cool project', - image: '/project1.jpg', - github: 'https://github.com/user/project1', - link: 'https://project1.com', - stack: ['React', 'Node.js'] - }, - { - name: 'Project 2', - desc: 'Another project', - image: '/project2.jpg', - github: 'https://github.com/user/project2', - stack: ['Vue', 'Express'] - } -]); - -export default useProjects; diff --git a/src/hooks/useAnimationOptimization.ts b/src/hooks/useAnimationOptimization.ts deleted file mode 100644 index 1701f64f..00000000 --- a/src/hooks/useAnimationOptimization.ts +++ /dev/null @@ -1,207 +0,0 @@ -import { useState, useEffect } from 'react'; -import type { Variants } from 'framer-motion'; - -/** Battery Status API; not in the standard DOM typings. */ -interface BatteryManager extends EventTarget { - charging: boolean; - level: number; -} - -export interface OptimizeVariantsOptions { - /** Disable 3D transforms on low-power devices */ - disable3DOnLowPower?: boolean; - /** Reduce animation complexity on low-end devices */ - reduceComplexity?: boolean; -} - -/** A variant after a JSON round trip: plain values plus an optional transition. */ -type PlainVariant = Record & { - transition?: { duration?: number; type?: string; ease?: string }; -}; - -/** - * Hook for optimizing animations based on device capabilities - * - * This hook returns information about device capabilities and settings - * that can help optimize animations for performance and accessibility. - * - * @returns {Object} Animation optimization settings - * @returns {boolean} disableAnimations - Whether animations should be disabled - * @returns {boolean} prefersReducedMotion - Whether user prefers reduced motion - * @returns {boolean} isLowPowerDevice - Whether device is low power - * @returns {boolean} is3DSupported - Whether 3D transforms are well supported - * @returns {boolean} isHighEndDevice - Whether device is high-end - * @returns {Function} optimizeVariants - Function to optimize animation variants - */ -const useAnimationOptimization = () => { - // Device capability states - const [prefersReducedMotion, setPrefersReducedMotion] = useState(false); - const [isLowPowerDevice, setIsLowPowerDevice] = useState(false); - const [is3DSupported, setIs3DSupported] = useState(true); - const [isHighEndDevice, setIsHighEndDevice] = useState(true); - - // Debug override from window.__DEBUG_FLAGS - const debugFlags: Partial> | undefined = typeof window !== 'undefined' ? window.__DEBUG_FLAGS : {}; - const disableAnimations = debugFlags?.disableAnimations || false; - - useEffect(() => { - // Check for prefers-reduced-motion with error handling - let motionQuery: MediaQueryList; - try { - motionQuery = window.matchMedia('(prefers-reduced-motion: reduce)'); - setPrefersReducedMotion(motionQuery.matches); - } catch (error) { - // If matchMedia is not available or fails, default to false - console.warn('matchMedia not supported, defaulting to no reduced motion preference'); - setPrefersReducedMotion(false); - return; // Exit early if matchMedia fails - } - - const handleMotionChange = (e: MediaQueryListEvent) => setPrefersReducedMotion(e.matches); - motionQuery.addEventListener('change', handleMotionChange); - - // Try to detect low power mode (iOS) - if ('getBattery' in navigator) { - (navigator as Navigator & { getBattery: () => Promise }).getBattery().then(battery => { - setIsLowPowerDevice(!battery.charging && battery.level < 0.3); - - const handleBatteryChange = () => { - setIsLowPowerDevice(!battery.charging && battery.level < 0.3); - }; - - battery.addEventListener('levelchange', handleBatteryChange); - battery.addEventListener('chargingchange', handleBatteryChange); - - return () => { - battery.removeEventListener('levelchange', handleBatteryChange); - battery.removeEventListener('chargingchange', handleBatteryChange); - }; - }).catch(() => { - console.log('Battery status API not supported'); - }); - } - - // Check for 3D transform support - const el = document.createElement('div'); - if (el.style.transform === undefined || - el.style.perspective === undefined || - el.style.backfaceVisibility === undefined) { - setIs3DSupported(false); - } - - // Detect device performance - const detectDevicePerformance = () => { - const start = performance.now(); - let result = 0; - - // Perform a heavy calculation to measure device speed - for (let i = 0; i < 1000000; i++) { - result += Math.sqrt(i); - } - - const end = performance.now(); - const duration = end - start; - - // If calculation takes longer than 100ms, consider it a low-end device - setIsHighEndDevice(duration < 100); - }; - - // Run performance detection after a short delay to not block main thread - const perfTimer = setTimeout(detectDevicePerformance, 2000); - - return () => { - motionQuery.removeEventListener('change', handleMotionChange); - clearTimeout(perfTimer); - }; - }, []); - - /** - * Optimize animation variants based on device capabilities - * - * @param {Object} variants - Animation variants - * @param {Object} options - Optimization options - * @param {boolean} options.disable3DOnLowPower - Disable 3D transforms on low-power devices - * @param {boolean} options.reduceComplexity - Reduce animation complexity on low-end devices - * @returns {Object} Optimized animation variants - */ - const optimizeVariants = (variants: Variants, options: OptimizeVariantsOptions = {}): Variants => { - const { disable3DOnLowPower = true, reduceComplexity = true } = options; - - // If animations should be disabled, return empty animations - if (disableAnimations || prefersReducedMotion) { - // Create new variants that only change opacity for a subtle effect - const reducedVariants: Variants = {}; - - for (const key in variants) { - if (key === 'visible' || key === 'show' || key === 'active') { - reducedVariants[key] = { opacity: 1, transition: { duration: 0.1 } }; - } else if (key === 'hidden' || key === 'hide' || key === 'inactive') { - reducedVariants[key] = { opacity: 0, transition: { duration: 0.1 } }; - } else { - reducedVariants[key] = { opacity: 1 }; - } - } - - return reducedVariants; - } - - // If device is low powered or low end, optimize animations - if ((isLowPowerDevice || !isHighEndDevice) && (disable3DOnLowPower || reduceComplexity)) { - // Create a copy of the variants - const optimizedVariants: Record = JSON.parse(JSON.stringify(variants)); - - // Remove or simplify expensive properties - for (const key in optimizedVariants) { - const variant = optimizedVariants[key]; - - // Handle transition property - if (variant.transition) { - // Simplify transition - faster animations, less spring physics - variant.transition.duration = variant.transition.duration - ? Math.min(variant.transition.duration, 0.3) - : 0.3; - - if (variant.transition.type === 'spring') { - variant.transition.type = 'tween'; - variant.transition.ease = 'easeOut'; - } - } - - // Remove 3D transforms if needed - if (disable3DOnLowPower && !is3DSupported) { - if (variant.rotateX !== undefined) delete variant.rotateX; - if (variant.rotateY !== undefined) delete variant.rotateY; - if (variant.rotateZ !== undefined) delete variant.rotateZ; - if (variant.z !== undefined) delete variant.z; - if (variant.perspective !== undefined) delete variant.perspective; - } - - // Simplify complex animations - if (reduceComplexity && !isHighEndDevice) { - // Convert arrays (keyframes) to single values - for (const prop in variant) { - if (Array.isArray(variant[prop]) && prop !== 'transition') { - variant[prop] = variant[prop][variant[prop].length - 1]; - } - } - } - } - - return optimizedVariants as Variants; - } - - // Return original variants if no optimization needed - return variants; - }; - - return { - disableAnimations: disableAnimations || prefersReducedMotion, - prefersReducedMotion, - isLowPowerDevice, - is3DSupported, - isHighEndDevice, - optimizeVariants - }; -}; - -export default useAnimationOptimization; \ No newline at end of file diff --git a/src/hooks/useEducation.ts b/src/hooks/useEducation.ts deleted file mode 100644 index 0df1b219..00000000 --- a/src/hooks/useEducation.ts +++ /dev/null @@ -1,29 +0,0 @@ -import { usePortfolio } from '@context/PortfolioContext'; - -/** - * Custom hook to access education data from the portfolio context. - * - * @function useEducation - * @returns {Array} Array of education objects - * - * @example - * import { useEducation } from '@hooks/useEducation'; - * - * const EducationList = () => { - * const education = useEducation(); - * - * return ( - *
- * {education.map(item => ( - *
{item.schoolName}
- * ))} - *
- * ); - * }; - */ -const useEducation = () => { - const { educationInfo } = usePortfolio(); - return educationInfo; -}; - -export default useEducation; diff --git a/src/hooks/useExperience.ts b/src/hooks/useExperience.ts deleted file mode 100644 index 9f504290..00000000 --- a/src/hooks/useExperience.ts +++ /dev/null @@ -1,130 +0,0 @@ -import { useState, useEffect, useMemo } from 'react'; -import { usePortfolio } from '@context/PortfolioContext'; -import type { Experience } from '@/types/portfolio'; - -export interface UseExperienceOptions { - /** Text to search for in company, role and description */ - filter?: string; - /** Sort method; 'recent' keeps the data order */ - sortBy?: 'recent' | 'company' | 'role'; - /** Delay in ms to simulate loading (for skeleton demo) */ - delay?: number; -} - -/** - * Validates an experience object to ensure it has all required properties - * - * @param {Object} experienceItem - Experience object to validate - * @returns {boolean} Whether the experience item is valid - */ -const isValidExperience = (experienceItem: Experience) => { - return ( - experienceItem && - typeof experienceItem === 'object' && - typeof experienceItem.company === 'string' && - typeof experienceItem.role === 'string' && - typeof experienceItem.date === 'string' && - typeof experienceItem.desc === 'string' && - typeof experienceItem.companylogo === 'string' - ); -}; - -/** - * Custom hook to access and optimize experience data from the portfolio context. - * Provides data validation, sorting, and memoization to prevent unnecessary re-renders. - * - * @function useExperience - * @param {Object} options - Hook options - * @param {string} [options.filter] - Optional filter string to search in company/role/description - * @param {string} [options.sortBy='recent'] - Optional sort method ('recent', 'company', 'role') - * @param {number} [options.delay=0] - Optional delay in ms to simulate loading (for skeleton demo) - * @returns {Array|null} Array of validated and sorted experience objects or null if loading - * - * @example - * import useExperience from '@hooks/useExperience'; - * - * const ExperienceList = () => { - * // Get all experiences sorted by most recent - * const experiences = useExperience(); - * - * // Or get filtered and sorted experiences with loading delay - * const filteredExperiences = useExperience({ - * filter: 'software', - * sortBy: 'company', - * delay: 1500 // Show skeleton for 1.5 seconds - * }); - * - * if (!experiences) { - * return ; - * } - * - * return ( - *
- * {experiences.map(job => ( - *
{job.role} at {job.company}
- * ))} - *
- * ); - * }; - */ -const useExperience = (options: UseExperienceOptions = {}): Experience[] | null => { - const { filter, sortBy = 'recent', delay = 0 } = options; - const { experience } = usePortfolio(); - const [loading, setLoading] = useState(delay > 0); - - // Effect for simulating loading time (for skeleton demo) - useEffect(() => { - let timer: ReturnType | undefined; - if (delay > 0) { - setLoading(true); - timer = setTimeout(() => { - setLoading(false); - }, delay); - } - - return () => { - if (timer) clearTimeout(timer); - }; - }, [delay]); - - // Process experience data with memoization to prevent unnecessary re-renders - const processedExperience = useMemo(() => { - // If experience is undefined or not an array, return empty array - if (!experience || !Array.isArray(experience)) { - console.warn('Experience data is missing or invalid'); - return []; - } - - // Filter out invalid experience items - let validExperience = experience.filter(isValidExperience); - - // Apply text filter if provided - if (filter && typeof filter === 'string' && filter.length > 0) { - const lowerFilter = filter.toLowerCase(); - validExperience = validExperience.filter(item => { - const companyMatch = item.company.toLowerCase().includes(lowerFilter); - const roleMatch = item.role.toLowerCase().includes(lowerFilter); - const descMatch = item.desc.toLowerCase().includes(lowerFilter); - - return companyMatch || roleMatch || descMatch; - }); - } - - // Apply sorting - switch (sortBy) { - case 'company': - return [...validExperience].sort((a, b) => a.company.localeCompare(b.company)); - case 'role': - return [...validExperience].sort((a, b) => a.role.localeCompare(b.role)); - case 'recent': - default: - // By default, assume the array is already sorted by recency - return validExperience; - } - }, [experience, filter, sortBy]); - - // Return null during loading to trigger skeleton UI - return loading ? null : processedExperience; -}; - -export default useExperience; diff --git a/src/types/global.d.ts b/src/types/global.d.ts index 756f1645..7cf9a41d 100644 --- a/src/types/global.d.ts +++ b/src/types/global.d.ts @@ -28,22 +28,12 @@ declare global { supportPassiveEvents?: boolean; /** HTML-escaping helper installed by security.applyXXSSProtection. */ encodeHTML?: (str: unknown) => string; - /** Marker installed by the CSS-variable fallback. */ - cssVars?: () => void; /** Render log shared by the debug profiler components. */ PERFORMANCE_DEBUG?: { renders: Record; recordRender: (id: string, data: ProfilerRenderRecord) => void; clear: () => void; }; - /** Console helpers installed by RenderDebugTools while it is enabled. */ - debugUtils?: { - profiler: object; - toggleMonitoring: () => void; - capturePerformance: () => void; - }; - /** Set by RenderVisualizer for other debug components to read. */ - RENDER_VISUALIZATION_ENABLED?: boolean; /** Chrome DevTools extension API; only present inside DevTools pages. */ chrome?: { devtools?: { executeScript: (options: { code: string }) => void } }; /** Chrome DevTools console utility; not available to page scripts. */ diff --git a/src/utils/__mocks__/animations.ts b/src/utils/__mocks__/animations.ts deleted file mode 100644 index 9b5eda74..00000000 --- a/src/utils/__mocks__/animations.ts +++ /dev/null @@ -1,84 +0,0 @@ -/** - * Mock for animations.ts - * - * This file provides mock implementations of animation utilities and variants - * for testing purposes. - */ - -import { vi } from 'vitest'; - -// Define animation variants -export const fadeInVariants = { - hidden: { opacity: 0 }, - visible: { opacity: 1, transition: { duration: 0.5 } } -}; - -export const slideUpVariants = { - hidden: { opacity: 0, y: 20 }, - visible: { opacity: 1, y: 0, transition: { duration: 0.5 } } -}; - -export const scaleVariants = { - hidden: { opacity: 0, scale: 0.8 }, - visible: { opacity: 1, scale: 1, transition: { duration: 0.5 } } -}; - -export const staggerContainerVariants = { - hidden: { opacity: 0 }, - visible: { - opacity: 1, - transition: { - staggerChildren: 0.1, - delayChildren: 0.2 - } - } -}; - -/** - * Animation quality settings - */ -export type AnimationQuality = 'high' | 'medium' | 'low'; - -/** - * Calculate animation delay based on index and quality settings - */ -export const getAnimationDelay = vi.fn(( - index: number, - baseDelay: number = 0.1, - staggerAmount: number = 0.05 -): number => { - return baseDelay + (index * staggerAmount); -}); - -/** - * Get optimized animation variants based on quality setting - */ -export const getOptimizedVariants = vi.fn(( - variants: any -): any => { - return variants; -}); - -/** - * Animation configuration constants - */ -export const ANIMATION_CONFIG = { - DEFAULT_DURATION: 0.5, - DEFAULT_STAGGER: 0.1, - DEFAULT_DELAY: 0.2, - REDUCED_MOTION_DURATION: 0.2, - QUALITY_SETTINGS: { - high: { - batchSize: 5, - throttleMs: 16 - }, - medium: { - batchSize: 3, - throttleMs: 32 - }, - low: { - batchSize: 2, - throttleMs: 48 - } - } -}; \ No newline at end of file diff --git a/src/utils/accessibility.tsx b/src/utils/accessibility.tsx deleted file mode 100644 index 728de99c..00000000 --- a/src/utils/accessibility.tsx +++ /dev/null @@ -1,247 +0,0 @@ -/** - * Accessibility and cross-browser compatibility utilities - */ -import React, { useEffect, useState } from 'react'; -import type { ComponentType, CSSProperties, Dispatch, SetStateAction } from 'react'; - -// Helper to handle focus trapping within modals -export const useFocusTrap = ( - isActive = false -): [Dispatch>] => { - const [containerRef, setContainerRef] = useState(null); - - useEffect(() => { - if (!isActive || !containerRef) return; - - // Get all focusable elements - const focusableElements = containerRef.querySelectorAll( - 'button, [href], input, select, textarea, [tabindex]:not([tabindex="-1"])' - ); - - if (focusableElements.length === 0) return; - - const firstElement = focusableElements[0]; - const lastElement = focusableElements[focusableElements.length - 1]; - - // Set initial focus - firstElement.focus(); - - // Handle tab key to keep focus within container - const handleKeyDown = (e: KeyboardEvent) => { - if (e.key !== 'Tab') return; - - // Shift + Tab - if (e.shiftKey) { - if (document.activeElement === firstElement) { - e.preventDefault(); - lastElement.focus(); - } - } - // Tab - else { - if (document.activeElement === lastElement) { - e.preventDefault(); - firstElement.focus(); - } - } - }; - - containerRef.addEventListener('keydown', handleKeyDown); - - return () => { - containerRef.removeEventListener('keydown', handleKeyDown); - }; - }, [isActive, containerRef]); - - return [setContainerRef]; -}; - -// Skip to main content link component -export interface SkipToContentProps { - /** id of the element the link jumps to */ - mainId?: string; -} - -export const SkipToContent = ({ mainId = 'main' }: SkipToContentProps) => { - return ( - - ); -}; - -// Detect high contrast mode -export const useHighContrastMode = () => { - const [isHighContrast, setIsHighContrast] = useState(false); - - useEffect(() => { - // Check if user has requested high contrast - const mediaQuery = window.matchMedia('(forced-colors: active)'); - setIsHighContrast(mediaQuery.matches); - - const handleChange = (e: MediaQueryListEvent) => { - setIsHighContrast(e.matches); - }; - - // Add listener for changes - if (mediaQuery.addEventListener) { - mediaQuery.addEventListener('change', handleChange); - return () => mediaQuery.removeEventListener('change', handleChange); - } else if (mediaQuery.addListener) { - // For older browsers - mediaQuery.addListener(handleChange); - return () => mediaQuery.removeListener(handleChange); - } - }, []); - - return isHighContrast; -}; - -// Detect reduced motion preference -export const useReducedMotion = () => { - const [prefersReducedMotion, setPrefersReducedMotion] = useState(false); - - useEffect(() => { - const mediaQuery = window.matchMedia('(prefers-reduced-motion: reduce)'); - setPrefersReducedMotion(mediaQuery.matches); - - const handleChange = (e: MediaQueryListEvent) => { - setPrefersReducedMotion(e.matches); - }; - - if (mediaQuery.addEventListener) { - mediaQuery.addEventListener('change', handleChange); - return () => mediaQuery.removeEventListener('change', handleChange); - } else if (mediaQuery.addListener) { - mediaQuery.addListener(handleChange); - return () => mediaQuery.removeListener(handleChange); - } - }, []); - - return prefersReducedMotion; -}; - -// Add ARIA attributes to elements -export const withAriaAttributes =

(Component: ComponentType

) => { - return React.forwardRef((props, ref) => { - const source = props as Record; - const ariaProps = Object.keys(props).reduce>((acc, key) => { - // Convert camelCase to kebab-case for aria attributes - if (key.startsWith('aria')) { - const ariaKey = key.replace(/([A-Z])/g, '-$1').toLowerCase(); - acc[ariaKey] = source[key]; - } else { - acc[key] = source[key]; - } - return acc; - }, {}); - - // The renamed props no longer match P, so the spread is cast back - return ; - }); -}; - -// Cross-browser polyfills and fixes -export const applyBrowserFixes = () => { - // Passive event listeners for better performance - try { - const options: AddEventListenerOptions = { - get passive() { - window.supportPassiveEvents = true; - return true; - } - }; - - // Window's own typing rejects a null listener; EventTarget's allows it - const target: EventTarget = window; - target.addEventListener('test', null, options); - target.removeEventListener('test', null, options); - } catch (err) { - window.supportPassiveEvents = false; - } - - // Polyfill for smooth scrolling - if (!('scrollBehavior' in document.documentElement.style)) { - import('smoothscroll-polyfill').then(smoothscroll => { - smoothscroll.polyfill(); - }); - } - - // Fix for certain iOS Safari issues - document.addEventListener('touchstart', function() {}, window.supportPassiveEvents ? { passive: true } : false); - - // Edge/IE fixes for CSS variables - try { - // Test if CSS variables are supported - const testEl = document.createElement('div'); - testEl.style.setProperty('--test', '0'); - if (testEl.style.getPropertyValue('--test') !== '0') { - // Use inline CSS variable polyfill instead of loading from CDN to avoid CSP issues - // This is a basic implementation of CSS variables for older browsers - // without requiring external CDN resources - const styleEl = document.createElement('style'); - styleEl.textContent = ` - /* Basic CSS variable fallbacks for older browsers */ - :root { - /* Core layout variables */ - --container-width: 1140px; - --spacing-unit: 8px; - - /* Colors */ - --primary: #3563E9; - --secondary: #4D5E80; - --accent: #14B8A6; - --light: #F5F9FF; - --dark: #1A1F36; - --white: #FFFFFF; - - /* Typography */ - --font-family-base: -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, "Helvetica Neue", Arial, sans-serif; - --font-size-base: 16px; - --line-height-base: 1.5; - } - - /* IE/Edge specific styles */ - @media all and (-ms-high-contrast: none), (-ms-high-contrast: active) { - /* Apply fallback values directly */ - .container { max-width: 1140px; } - .primary-color { color: #3563E9; } - .primary-bg { background-color: #3563E9; } - .secondary-color { color: #4D5E80; } - .accent-color { color: #14B8A6; } - } - `; - document.head.appendChild(styleEl); - - // Add inline polyfill helper function instead of loading external script - window.cssVars = function() { - console.log('CSS Variables polyfill applied'); - }; - } - } catch (e) { - console.warn('Error detecting CSS variable support', e); - } -}; diff --git a/src/utils/accessibilityUtils.ts b/src/utils/accessibilityUtils.ts deleted file mode 100644 index 9bcde70b..00000000 --- a/src/utils/accessibilityUtils.ts +++ /dev/null @@ -1,277 +0,0 @@ -/** - * Accessibility utility functions for enhancing component accessibility. - * These utilities help ensure WCAG compliance and better screen reader support. - */ - -import type { AriaAttributes, AriaRole, CSSProperties, KeyboardEvent } from 'react'; - -export interface AriaAttributeOptions { - /** Whether the element is disabled */ - isDisabled?: boolean; - /** Whether the element is expanded (for dropdowns, accordions) */ - isExpanded?: boolean; - /** Whether the element is selected (for tabs, options) */ - isSelected?: boolean; - /** Whether the element triggers a popup */ - hasPopup?: AriaAttributes['aria-haspopup']; - /** ID of the element this element controls */ - controls?: string; - /** ID of element that describes this element */ - describedBy?: string; - /** ID of element that labels this element */ - labelledBy?: string; - /** Whether this element represents the current page/step; `true` means "page" */ - isCurrent?: AriaAttributes['aria-current']; - /** ARIA role */ - role?: AriaRole; -} - -/** - * Generates appropriate ARIA attributes for interactive elements based on their state - * - * @param {Object} props - Properties for the interactive element - * @param {boolean} [props.isDisabled] - Whether the element is disabled - * @param {boolean} [props.isExpanded] - Whether the element is expanded (for dropdowns, accordions) - * @param {boolean} [props.isSelected] - Whether the element is selected (for tabs, options) - * @param {boolean} [props.hasPopup] - Whether the element triggers a popup - * @param {string} [props.controls] - ID of the element this element controls - * @param {string} [props.describedBy] - ID of element that describes this element - * @param {string} [props.labelledBy] - ID of element that labels this element - * @param {boolean} [props.isCurrent] - Whether this element represents the current page/step - * @returns {Object} ARIA attributes object that can be spread onto an element - * - * @example - * import { getAriaAttributes } from '@utils/accessibilityUtils'; - * - * function MyButton({ isDisabled, controls }) { - * const ariaAttrs = getAriaAttributes({ isDisabled, controls }); - * - * return ( - * - * ); - * } - */ -export function getAriaAttributes({ - isDisabled, - isExpanded, - isSelected, - hasPopup, - controls, - describedBy, - labelledBy, - isCurrent, - role -}: AriaAttributeOptions) { - const attributes: AriaAttributes & { role?: AriaRole } = {}; - - // Add attributes only if they're defined (to avoid null/undefined values) - if (isDisabled !== undefined) attributes['aria-disabled'] = isDisabled; - if (isExpanded !== undefined) attributes['aria-expanded'] = isExpanded; - if (isSelected !== undefined) attributes['aria-selected'] = isSelected; - if (hasPopup !== undefined) attributes['aria-haspopup'] = hasPopup; - if (controls) attributes['aria-controls'] = controls; - if (describedBy) attributes['aria-describedby'] = describedBy; - if (labelledBy) attributes['aria-labelledby'] = labelledBy; - if (isCurrent) attributes['aria-current'] = isCurrent === true ? 'page' : isCurrent; - if (role) attributes.role = role; - - return attributes; -} - -/** - * Creates an ID that can be used for ARIA relationships - * Uses a prefix and suffix to ensure uniqueness - * - * @param {string} prefix - Prefix for the ID - * @param {string|number} suffix - Unique suffix (e.g., item index or name) - * @returns {string} Unique ID for ARIA relationships - * - * @example - * import { createAriaId } from '@utils/accessibilityUtils'; - * - * function MyComponent({ items }) { - * return ( - *

- * {items.map((item, index) => ( - *
- * {item.content} - *
- * ))} - *
- * ); - * } - */ -export function createAriaId(prefix: string, suffix: string | number): string { - return `${prefix}-${suffix}`; -} - -/** - * Adds keyboard event handlers for improved accessibility - * Supports enter and space key handling for custom interactive elements - * - * @param {Function} onAction - Function to call when the element is activated - * @returns {Object} Object with event handlers - * - * @example - * import { getKeyboardHandlers } from '@utils/accessibilityUtils'; - * - * function CustomButton({ onClick, children }) { - * const keyboardHandlers = getKeyboardHandlers(onClick); - * - * return ( - *
- * {children} - *
- * ); - * } - */ -export function getKeyboardHandlers(onAction: (e: KeyboardEvent) => void) { - return { - onKeyDown: (e: KeyboardEvent) => { - // Trigger the action when Enter or Space is pressed - if (e.key === 'Enter' || e.key === ' ' || e.key === 'Spacebar') { - e.preventDefault(); // Prevent scroll on space - onAction(e); - } - } - }; -} - -/** - * Creates attributes for screen reader only text - * Used to add additional context for screen readers without visual impact - * - * @returns {Object} Object with style properties for screen reader only text - * - * @example - * import { srOnlyStyle } from '@utils/accessibilityUtils'; - * - * function IconButton({ icon, label }) { - * return ( - * - * ); - * } - */ -export function srOnlyStyle(): CSSProperties { - return { - position: 'absolute', - width: '1px', - height: '1px', - padding: '0', - margin: '-1px', - overflow: 'hidden', - clip: 'rect(0, 0, 0, 0)', - whiteSpace: 'nowrap', - borderWidth: '0' - }; -} - -/** - * Returns CSS styles for a skip link that allows keyboard users - * to bypass navigation and jump to main content - * - * @returns {Object} Skip link styles object - * - * @example - * import { skipLinkStyles } from '@utils/accessibilityUtils'; - * - * function App() { - * return ( - * <> - * - * Skip to main content - * - *
- *
- * Content here - *
- * - * ); - * } - */ -export function skipLinkStyles(): CSSProperties { - return { - position: 'absolute', - top: '-40px', - left: '0', - background: 'var(--color-primary)', - color: 'white', - padding: '8px 16px', - zIndex: '9999', - transition: 'top 0.2s ease', - borderRadius: '0 0 4px 0', - fontWeight: '600', - fontSize: '16px', - textDecoration: 'none', - // Focus styles have to be applied via CSS instead - // Use this class name in your CSS file: - // .skip-link:focus { top: 0; } - }; -} - -/** - * Checks if the current color contrast meets WCAG standards - * - * @param {string} foreground - Foreground color in hex format (#RRGGBB) - * @param {string} background - Background color in hex format (#RRGGBB) - * @param {string} [level='AA'] - WCAG level to check against ('A', 'AA', or 'AAA') - * @param {boolean} [isLargeText=false] - Whether the text is considered large by WCAG standards - * @returns {boolean} Whether the contrast ratio meets the specified WCAG level - */ -export function hasValidContrast( - foreground: string, - background: string, - level: 'A' | 'AA' | 'AAA' = 'AA', - isLargeText = false -): boolean { - // Convert hex to RGB - const hexToRgb = (hex: string): number[] => { - const r = parseInt(hex.slice(1, 3), 16); - const g = parseInt(hex.slice(3, 5), 16); - const b = parseInt(hex.slice(5, 7), 16); - return [r, g, b]; - }; - - // Calculate relative luminance - const calculateLuminance = (rgb: number[]) => { - const [r, g, b] = rgb.map(c => { - c = c / 255; - return c <= 0.03928 ? c / 12.92 : Math.pow((c + 0.055) / 1.055, 2.4); - }); - return 0.2126 * r + 0.7152 * g + 0.0722 * b; - }; - - // Calculate contrast ratio - const l1 = calculateLuminance(hexToRgb(foreground)); - const l2 = calculateLuminance(hexToRgb(background)); - const ratio = (Math.max(l1, l2) + 0.05) / (Math.min(l1, l2) + 0.05); - - // WCAG 2.1 contrast requirements - const requirements = { - 'A': { normal: 3, large: 3 }, - 'AA': { normal: 4.5, large: 3 }, - 'AAA': { normal: 7, large: 4.5 } - }; - - const requirement = requirements[level][isLargeText ? 'large' : 'normal']; - return ratio >= requirement; -} diff --git a/src/utils/animations.ts b/src/utils/animations.ts deleted file mode 100644 index 889edf26..00000000 --- a/src/utils/animations.ts +++ /dev/null @@ -1,171 +0,0 @@ -/** - * Animation utilities and variants for the Developer Portfolio - * - * This file contains reusable animation variants and utility functions - * for consistent animations across the application. - */ - -import { Variants } from 'framer-motion'; - -/** - * Animation quality settings - */ -export type AnimationQuality = 'high' | 'medium' | 'low'; - -/** - * Standard fade-in animation variant - */ -export const fadeInVariants: Variants = { - hidden: { - opacity: 0 - }, - visible: { - opacity: 1, - transition: { - duration: 0.6, - ease: 'easeInOut' - } - } -}; - -/** - * Slide-up animation variant with fade - */ -export const slideUpVariants: Variants = { - hidden: { - opacity: 0, - y: 20 - }, - visible: { - opacity: 1, - y: 0, - transition: { - duration: 0.5, - ease: 'easeOut' - } - } -}; - -/** - * Scale animation variant with fade - */ -export const scaleVariants: Variants = { - hidden: { - opacity: 0, - scale: 0.9 - }, - visible: { - opacity: 1, - scale: 1, - transition: { - duration: 0.4, - ease: 'easeOut' - } - } -}; - -/** - * Staggered children animation variant - */ -export const staggerContainerVariants: Variants = { - hidden: { - opacity: 0 - }, - visible: { - opacity: 1, - transition: { - staggerChildren: 0.1, - delayChildren: 0.2 - } - } -}; - -/** - * Calculate animation delay based on index and quality settings - * - * @param index Element index for staggered animations - * @param quality Animation quality setting - * @param baseDelay Base delay in seconds - * @param staggerAmount Amount of stagger between elements - * @returns Calculated delay in seconds - */ -export const getAnimationDelay = ( - index: number, - quality: AnimationQuality = 'medium', - baseDelay: number = 0.1, - staggerAmount: number = 0.05 -): number => { - // Adjust stagger based on quality - const qualityMultiplier = { - high: 1, - medium: 0.7, - low: 0.4 - }; - - const adjustedStagger = staggerAmount * qualityMultiplier[quality]; - return baseDelay + (index * adjustedStagger); -}; - -/** - * Get optimized animation variants based on quality setting - * - * @param variants Original animation variants - * @param quality Animation quality setting - * @returns Optimized variants - */ -export const getOptimizedVariants = ( - variants: Variants, - quality: AnimationQuality = 'medium' -): Variants => { - if (quality === 'low') { - // Create a deep copy to avoid modifying the original - const optimizedVariants = { ...variants }; - - // Handle the visible state transition if it exists - if (optimizedVariants.visible && typeof optimizedVariants.visible === 'object') { - const visibleState = { ...optimizedVariants.visible }; - - // Safely modify the transition if it exists - if (visibleState.transition) { - visibleState.transition = { - ...visibleState.transition, - // Safely adjust duration and stagger values - ...(typeof visibleState.transition === 'object' && { - duration: Math.max(0.2, ((visibleState.transition as any).duration || 0.3) * 0.7), - staggerChildren: Math.max(0.05, ((visibleState.transition as any).staggerChildren || 0.1) * 0.5), - }) - }; - } - - optimizedVariants.visible = visibleState; - } - - return optimizedVariants; - } - - return variants; -}; - -/** - * Animation configuration constants - */ -export const ANIMATION_CONFIG = { - DEFAULT_DURATION: 0.5, - DEFAULT_STAGGER: 0.1, - DEFAULT_DELAY: 0.2, - REDUCED_MOTION_DURATION: 0.2, - QUALITY_SETTINGS: { - high: { - batchSize: 5, - throttleMs: 16 - }, - medium: { - batchSize: 3, - throttleMs: 32 - }, - low: { - batchSize: 2, - throttleMs: 48 - } - } -}; \ No newline at end of file diff --git a/src/utils/debug/Example.tsx b/src/utils/debug/Example.tsx deleted file mode 100644 index e1079d85..00000000 --- a/src/utils/debug/Example.tsx +++ /dev/null @@ -1,170 +0,0 @@ -import React, { useState, useEffect } from 'react'; -// The index has no `withDebug` or `PerformanceDisplay`; these are the exports with the matching signatures -import { - DebugProvider, - useDebug, - createDebuggable as withDebug, - SimplePerformanceMonitor as PerformanceDisplay -} from './index'; -import PerformanceMonitor from './PerformanceMonitor'; - -/** - * Example component using the debug hook - */ -const HookedComponent = () => { - // Track this component's renders - useDebug('HookedComponent'); - - const [counter, setCounter] = useState(0); - - return ( -
-

Component with Debug Hook

-

Counter: {counter}

- -
- ); -}; - -/** - * Example component that will be wrapped with withDebug - */ -const SimpleComponent = ({ name }: { name: string }) => { - const [counter, setCounter] = useState(0); - - return ( -
-

Component with Debug HOC: {name}

-

Counter: {counter}

- -
- ); -}; - -// Wrap the component with the debug HOC -const DebuggedComponent = withDebug(SimpleComponent, 'SimpleComponent'); - -// Test component that will create some measurable performance impact -const PerformanceTest = () => { - const [counter, setCounter] = useState(0); - - // Create some CPU load - useEffect(() => { - const interval = setInterval(() => { - // Do some heavy computation - let result = 0; - for (let i = 0; i < 1000000; i++) { - result += Math.random(); - } - setCounter(prev => prev + 1); - }, 1000); - - return () => clearInterval(interval); - }, []); - - // Create some memory allocation - const array = new Array(10000).fill(0).map(() => new Object()); - - return ( -
-

Performance Test Component

-

Counter: {counter}

-

Array length: {array.length}

-
- ); -}; - -/** - * Main example showing how to use the debug utilities - */ -export const DebugExample = () => { - // State to toggle debug features - const [showPerformance, setShowPerformance] = useState(false); - - return ( - -
-

Debug Utilities Example

- -
- -
- -
- - -
- - {/* Keyboard shortcuts help */} -
-

Keyboard Shortcuts

-
    -
  • Ctrl+Shift+D: Toggle Debug Panel
  • -
  • Ctrl+Shift+P: Toggle Performance Monitor
  • -
-
- - {/* Optional performance display */} - {showPerformance && ( - - )} - - - -
-
- ); -}; - -export default DebugExample; \ No newline at end of file diff --git a/src/utils/debug/RenderDebugTools.tsx b/src/utils/debug/RenderDebugTools.tsx deleted file mode 100644 index 3f4f63e3..00000000 --- a/src/utils/debug/RenderDebugTools.tsx +++ /dev/null @@ -1,178 +0,0 @@ -import React, { lazy, Suspense, useState, useEffect } from 'react'; -import type { ComponentType, ReactNode } from 'react'; -import { RenderProfiler } from './ComponentProfiler'; -import type { PerformanceMonitorConfig } from './PerformanceMonitor'; - -export interface RenderDebugToolsProps { - /** Whether debug tools are enabled by default */ - defaultEnabled?: boolean; - /** Configuration for the performance monitor */ - performanceConfig?: Partial; - /** Child components to render */ - children?: ReactNode; -} - -export interface DebugTrackingOptions { - /** Name the renders are recorded under; defaults to the component's own name */ - name?: string; - /** Log each render to the console */ - log?: boolean; -} - -// Lazy load the tools to avoid impacting initial performance -const PerformanceMonitor = lazy(() => import('./PerformanceMonitor')); -const ComponentProfilerViewer = lazy(() => import('./ComponentProfiler')); -const RenderVisualizer = lazy(() => import('./RenderVisualizer')); - -// Default performance monitoring settings -const DEFAULT_PERFORMANCE_CONFIG: Partial = { - longTaskThreshold: 50, - fpsWarningThreshold: 30, - showComponentTimings: true, - showStackTraces: true, - logToConsole: true, - componentFilter: [] -}; - -// Utility to add or remove DOM markers for debug monitoring -const setupDebugMonitoring = (enabled: boolean) => { - if (enabled) { - document.documentElement.classList.add('debug-monitoring'); - - // Add paint flashing if Chrome DevTools API is available - if (window.chrome && window.chrome.devtools) { - try { - window.chrome.devtools.executeScript({ - code: 'void(0)' - }); - } catch { - console.log('Chrome DevTools API not available'); - } - } - - console.log('Debug monitoring enabled - Press Ctrl+Shift+D to toggle tools'); - } else { - document.documentElement.classList.remove('debug-monitoring'); - - // Remove debug paint flashing - if (window.chrome && window.chrome.devtools) { - try { - window.chrome.devtools.executeScript({ - code: 'void(0)' - }); - } catch { - console.log('Chrome DevTools API not available'); - } - } - } -}; - -/** - * RenderDebugTools Component - * - * Renders debug monitoring tools for performance profiling - * - * @param {Object} props - Component properties - * @param {boolean} props.defaultEnabled - Whether debug tools are enabled by default - * @param {Object} props.performanceConfig - Configuration for the performance monitor - * @param {React.ReactNode} props.children - Child components to render - */ -const RenderDebugTools = ({ - defaultEnabled = false, - performanceConfig = {}, - children -}: RenderDebugToolsProps) => { - const [isEnabled, setIsEnabled] = useState(defaultEnabled); - - // Merge performance configuration with defaults - const mergedPerformanceConfig = { - ...DEFAULT_PERFORMANCE_CONFIG, - ...performanceConfig - }; - - // Set up keyboard shortcut to toggle tools - useEffect(() => { - const handleKeyDown = (e: KeyboardEvent) => { - if (e.ctrlKey && e.shiftKey && e.key === 'D') { - setIsEnabled(prev => !prev); - } - }; - - window.addEventListener('keydown', handleKeyDown); - return () => window.removeEventListener('keydown', handleKeyDown); - }, []); - - // Persist enabled state - useEffect(() => { - localStorage.setItem('debug_tools_enabled', String(isEnabled)); - setupDebugMonitoring(isEnabled); - - // Log state change - console.log(`Debug tools ${isEnabled ? 'enabled' : 'disabled'}`); - - // Add utility commands to console - if (isEnabled) { - window.debugUtils = { - profiler: window.PERFORMANCE_DEBUG || {}, - toggleMonitoring: () => setIsEnabled(prev => !prev), - capturePerformance: () => { - // Capture long-tasks - const observer = new PerformanceObserver((list) => { - list.getEntries().forEach(entry => { - console.warn('Long task detected:', entry.duration, 'ms', entry); - }); - }); - observer.observe({ entryTypes: ['longtask'] }); - } - }; - - console.log('Debug utilities available in window.debugUtils'); - } else { - delete window.debugUtils; - } - }, [isEnabled]); - - if (!isEnabled) { - return children; - } - - return ( - - {/* Wrap with all debug tools when enabled */} - - - {/* Tools UI */} - - - - {/* Main app content */} - {children} - - - - ); -}; - -// Export higher-order component to easily wrap any component with debugging -export const withDebugTracking =

( - Component: ComponentType

, - options: DebugTrackingOptions = {} -) => { - const componentName = options.name || Component.displayName || Component.name; - - const DebugTrackedComponent = (props: P) => { - return ( - - - - ); - }; - - DebugTrackedComponent.displayName = `DebugTracked(${componentName})`; - return DebugTrackedComponent; -}; - -export default RenderDebugTools; \ No newline at end of file diff --git a/src/utils/debug/RenderVisualizer.tsx b/src/utils/debug/RenderVisualizer.tsx deleted file mode 100644 index 14e120c2..00000000 --- a/src/utils/debug/RenderVisualizer.tsx +++ /dev/null @@ -1,184 +0,0 @@ -import React, { useState, useEffect, useCallback, useRef } from 'react'; -import type { ComponentType, ReactNode } from 'react'; - -export interface RenderVisualizerOptions { - /** Background colour flashed on each render */ - highlightColor?: string; - /** Milliseconds the highlight takes to fade */ - fadeOutTime?: number; - /** Log each render to the console */ - log?: boolean; - /** Name shown in the badge; defaults to the component's own name */ - componentName?: string; -} - -export interface RenderVisualizerProps { - children?: ReactNode; - /** Whether visualization starts enabled; defaults to on in development */ - enabled?: boolean; -} - -/** - * HOC that adds a visual indication when a component renders - * Helps identify which components are re-rendering and how frequently - * @param {React.Component} Component - Component to wrap with visualization - * @param {Object} options - Configuration options - * @returns {React.Component} - Enhanced component with visual render indicator - */ -export const withRenderVisualizer =

( - Component: ComponentType

, - { - highlightColor = 'rgba(255, 0, 0, 0.3)', - fadeOutTime = 500, - log = false, - componentName = Component.displayName || Component.name || 'UnknownComponent' - }: RenderVisualizerOptions = {} -) => { - // Create the enhanced component - const VisualizedComponent = (props: P) => { - const [renderCount, setRenderCount] = useState(0); - const [isHighlighted, setIsHighlighted] = useState(false); - const containerRef = useRef(null); - const timeoutRef = useRef | null>(null); - - // Show highlight effect on render - useEffect(() => { - // Clear previous timeout - if (timeoutRef.current) { - clearTimeout(timeoutRef.current); - } - - // Increment render count - setRenderCount(count => count + 1); - - // Add highlight - setIsHighlighted(true); - - // Remove highlight after specified time - timeoutRef.current = setTimeout(() => { - setIsHighlighted(false); - }, fadeOutTime); - - // Log render information if enabled - if (log) { - console.log(`[RENDER] ${componentName} rendered (count: ${renderCount + 1})`); - } - - return () => { - if (timeoutRef.current) { - clearTimeout(timeoutRef.current); - } - }; - }, [props, log]); - - return ( -

- {/* Show render badge in development mode */} - {import.meta.env.DEV && ( -
- {componentName} ({renderCount}) -
- )} - - -
- ); - }; - - // Add display name - VisualizedComponent.displayName = `Visualized(${componentName})`; - - return VisualizedComponent; -}; - -/** - * Master control component for render visualization - * Allows enabling/disabling visualization globally - */ -const RenderVisualizer = ({ children, enabled = import.meta.env.DEV }: RenderVisualizerProps) => { - const [isEnabled, setIsEnabled] = useState(enabled); - - // Toggle with Ctrl+Shift+V keyboard shortcut - useEffect(() => { - const handleKeyDown = (e: KeyboardEvent) => { - if (e.ctrlKey && e.shiftKey && e.key === 'V') { - setIsEnabled(prev => !prev); - console.log(`Render visualization ${!isEnabled ? 'enabled' : 'disabled'}`); - } - }; - - window.addEventListener('keydown', handleKeyDown); - return () => window.removeEventListener('keydown', handleKeyDown); - }, [isEnabled]); - - // Inject global CSS for highlighting - useEffect(() => { - if (isEnabled) { - // Add global CSS for render visualization - const style = document.createElement('style'); - style.id = 'render-visualizer-styles'; - style.innerHTML = ` - [data-render-count] { - position: relative; - } - - [data-render-count]:hover::after { - content: attr(data-component-name) " (" attr(data-render-count) " renders)"; - position: absolute; - bottom: calc(100% + 5px); - right: 0; - background-color: rgba(0, 0, 0, 0.8); - color: white; - font-size: 12px; - padding: 4px 8px; - border-radius: 4px; - z-index: 9999; - white-space: nowrap; - pointer-events: none; - } - `; - - document.head.appendChild(style); - - return () => { - const existingStyle = document.getElementById('render-visualizer-styles'); - if (existingStyle) { - existingStyle.remove(); - } - }; - } - }, [isEnabled]); - - // Set global visualization state for other components to access - useEffect(() => { - window.RENDER_VISUALIZATION_ENABLED = isEnabled; - }, [isEnabled]); - - return children; -}; - -export default RenderVisualizer; \ No newline at end of file diff --git a/src/utils/imageOptimizerComponents.tsx b/src/utils/imageOptimizerComponents.tsx deleted file mode 100644 index 5d4bba71..00000000 --- a/src/utils/imageOptimizerComponents.tsx +++ /dev/null @@ -1,211 +0,0 @@ -/** - * Image optimization utilities - * Provides functions for lazy loading, responsive images, and blur-up techniques - */ -import { useState, useEffect } from 'react'; -import type { HTMLAttributes, ImgHTMLAttributes } from 'react'; - -// Function to create a low-quality image placeholder -export const createPlaceholder = (src: string, width = 20): Promise => { - return new Promise((resolve) => { - const img = new Image(); - img.crossOrigin = 'anonymous'; - - img.onload = () => { - // Create a small canvas to generate a low-quality image - const canvas = document.createElement('canvas'); - const ctx = canvas.getContext('2d')!; - - // Set dimensions to a very small size - canvas.width = width; - canvas.height = Math.floor(width * (img.height / img.width)); - - // Draw the image at a small size - ctx.drawImage(img, 0, 0, canvas.width, canvas.height); - - // Generate a blurry data URL - resolve(canvas.toDataURL('image/jpeg', 0.3)); - }; - - img.onerror = () => { - // Return an empty placeholder on error - resolve('data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAQAAAC1HAwCAAAAC0lEQVR42mNkYAAAAAYAAjCB0C8AAAAASUVORK5CYII='); - }; - - img.src = src; - }); -}; - -// Hook for lazy loading images with blur-up effect -export const useLazyImage = (src: string | undefined, placeholderSize = 20) => { - const [imageSrc, setImageSrc] = useState(null); - const [placeholder, setPlaceholder] = useState(null); - const [isLoaded, setIsLoaded] = useState(false); - - useEffect(() => { - if (!src) return; - - // Reset state when src changes - setIsLoaded(false); - - // Create a small placeholder while the main image loads - createPlaceholder(src, placeholderSize) - .then(placeholderDataUrl => { - setPlaceholder(placeholderDataUrl); - }); - - // Load the full image - const img = new Image(); - img.src = src; - img.onload = () => { - setImageSrc(src); - setIsLoaded(true); - }; - - return () => { - img.onload = null; - }; - }, [src, placeholderSize]); - - return { imageSrc, placeholder, isLoaded }; -}; - -// Generate srcSet for responsive images -export const generateSrcSet = (src: string | undefined, sizes: number[] = [320, 640, 960, 1280, 1920]): string => { - if (!src) return ''; - - // Parse URL to handle different file extensions - const lastDot = src.lastIndexOf('.'); - if (lastDot === -1) return src; - - const basePath = src.substring(0, lastDot); - const extension = src.substring(lastDot); - - // Generate srcSet string for different sizes - return sizes - .map(size => `${basePath}-${size}w${extension} ${size}w`) - .join(', '); -}; - -export interface ResponsiveImageProps extends ImgHTMLAttributes { - /** Load lazily with a blurred placeholder */ - lazy?: boolean; - /** Width in pixels of the generated placeholder */ - placeholderSize?: number; -} - -// Create a responsive image component -export const ResponsiveImage = ({ - src, - alt, - className, - width, - height, - sizes = '(max-width: 768px) 100vw, 50vw', - lazy = true, - placeholderSize = 20, - ...props -}: ResponsiveImageProps) => { - // If lazy loading is enabled, use the blur-up effect - const { imageSrc, placeholder, isLoaded } = lazy ? useLazyImage(src, placeholderSize) : { imageSrc: src, placeholder: null, isLoaded: false }; - - // Generate a srcSet if the browser supports it - const srcSet = generateSrcSet(src); - - return ( -
- {lazy && placeholder && ( - - )} - - {alt} -
- ); -}; - -export interface OptimizedBgImageProps extends HTMLAttributes { - /** Background image URL */ - src: string; - /** Text alternative, read from a hidden img */ - alt?: string; -} - -// Export a simple component for background images -export const OptimizedBgImage = ({ src, alt, children, className, ...props }: OptimizedBgImageProps) => { - const { imageSrc, placeholder, isLoaded } = useLazyImage(src); - - return ( -
- {/* Hidden image for screen readers */} - {alt} - {children} -
- ); -}; - -// Function to optimize image URLs with parameters for CDNs -export const optimizeImageUrl = (url: string, width: number, height?: number, quality = 80): string => { - // Example implementation for a hypothetical CDN - // Modify this based on the actual CDN you're using - if (!url) return ''; - - // If URL already contains optimization parameters, return as is - if (url.includes('?w=') || url.includes('&w=')) return url; - - // Add optimization parameters - const separator = url.includes('?') ? '&' : '?'; - let optimizedUrl = `${url}${separator}w=${width}`; - - if (height) { - optimizedUrl += `&h=${height}`; - } - - optimizedUrl += `&q=${quality}`; - - return optimizedUrl; -}; diff --git a/src/utils/performanceMonitor.ts b/src/utils/performanceMonitor.ts deleted file mode 100644 index d44f140b..00000000 --- a/src/utils/performanceMonitor.ts +++ /dev/null @@ -1,217 +0,0 @@ -/** - * Performance monitoring utilities for measuring and optimizing application performance. - * These utilities help track rendering performance, animation smoothness, and resource usage. - */ - -// External dependencies -import React from 'react'; -import type { ComponentType } from 'react'; - -// Import environment configuration -import envConfig from '@utils/envConfig'; - -// Check if performance API is available -const hasPerformanceAPI = typeof performance !== 'undefined' && - typeof performance.mark === 'function' && - typeof performance.measure === 'function'; - -// Check if we're in development mode -const isDev = envConfig.isDevelopment; - -/** - * Create a performance marker - * @param {string} markName - Name of the performance mark - */ -export const markStart = (markName: string) => { - if (hasPerformanceAPI && isDev) { - performance.mark(`${markName}-start`); - } -}; - -/** - * End a performance mark and log the result - * @param {string} markName - Name of the performance mark - * @param {boolean} shouldLog - Whether to log the result to console - * @returns {number|null} - Duration in ms, or null if performance API unavailable - */ -export const markEnd = (markName: string, shouldLog = true): number | null => { - if (!hasPerformanceAPI || !isDev) return null; - - const endMarkName = `${markName}-end`; - const startMarkName = `${markName}-start`; - const measureName = `⏱️ ${markName}`; - - performance.mark(endMarkName); - - try { - performance.measure(measureName, startMarkName, endMarkName); - const entries = performance.getEntriesByName(measureName); - const duration = entries[0]?.duration; - - if (shouldLog && duration !== undefined) { - console.info(`${measureName}: ${duration.toFixed(2)}ms`); - } - - // Clean up - performance.clearMarks(startMarkName); - performance.clearMarks(endMarkName); - performance.clearMeasures(measureName); - - return duration; - } catch (e) { - console.warn('Performance measurement error:', e); - return null; - } -}; - -/** - * Higher-order component to measure component render time - * @param {React.Component} Component - Component to measure - * @param {string} componentName - Name of the component for logging - * @returns {React.Component} - Enhanced component with performance monitoring - */ -export const withPerformanceTracking =

( - Component: ComponentType

, - componentName?: string -): ComponentType

=> { - if (!isDev) return Component; - - // Destructure all React methods we need at this level to avoid references in the returned component - const { useRef, useEffect, createElement } = React; - - return (props: P) => { - const markName = `render-${componentName || Component.displayName || Component.name || 'Component'}`; - markStart(markName); - - // Use a ref to track when the component has actually rendered to the DOM - const componentRef = useRef(undefined); - - useEffect(() => { - if (componentRef.current) { - markEnd(markName); - } - }, []); - - return createElement(Component, { - ...props, - ref: componentRef - }); - }; -}; - -/** - * Track FPS during animations - */ -export class FPSMonitor { - frames: number; - isRunning: boolean; - lastTime: number; - fps: number; - sampleInterval: number; - onFpsUpdate: ((fps: number) => void) | null; - - constructor(sampleInterval = 1000) { - this.frames = 0; - this.isRunning = false; - this.lastTime = 0; - this.fps = 0; - this.sampleInterval = sampleInterval; - this.onFpsUpdate = null; - } - - start(onFpsUpdate: ((fps: number) => void) | null = null) { - if (this.isRunning) return; - - this.isRunning = true; - this.frames = 0; - this.lastTime = performance.now(); - this.onFpsUpdate = onFpsUpdate; - - this._tick(); - } - - stop() { - this.isRunning = false; - } - - _tick() { - if (!this.isRunning) return; - - this.frames++; - const now = performance.now(); - const elapsed = now - this.lastTime; - - if (elapsed >= this.sampleInterval) { - this.fps = Math.round((this.frames * 1000) / elapsed); - this.lastTime = now; - this.frames = 0; - - if (isDev) { - console.info(`Current FPS: ${this.fps}`); - } - - if (this.onFpsUpdate) { - this.onFpsUpdate(this.fps); - } - } - - requestAnimationFrame(() => this._tick()); - } - - getFPS() { - return this.fps; - } -} - -/** - * Helper to detect slow devices where animations should be reduced - * @returns {boolean} - True if the device is likely to be slow - */ -export const isSlowDevice = () => { - // Check for hardware concurrency (CPU cores) - const hasLowCores = navigator.hardwareConcurrency <= 4; - - // Check device memory (if available) - // deviceMemory is Chromium-only and not in the DOM typings - const { deviceMemory } = navigator as Navigator & { deviceMemory?: number }; - const hasLowMemory = deviceMemory && deviceMemory <= 4; - - // Check for reduced motion preference - const prefersReducedMotion = window.matchMedia('(prefers-reduced-motion: reduce)').matches; - - // If two or more checks are true, consider it a slow device - return (hasLowCores && hasLowMemory) || prefersReducedMotion; -}; - -/** - * Enable animation based on device capability - * @returns {boolean} - Whether animations should be enabled - */ -export const shouldEnableAnimation = () => { - // If user has explicitly set a preference in localStorage, respect that - const storedPreference = localStorage.getItem('enableAnimations'); - if (storedPreference !== null) { - return storedPreference === 'true'; - } - - // Check environment configuration for default setting - // envConfig has no top-level enableAnimations, so this branch never runs - const { enableAnimations } = envConfig as typeof envConfig & { enableAnimations?: boolean }; - if (typeof enableAnimations !== 'undefined') { - return enableAnimations && !isSlowDevice(); - } - - // Otherwise, base on device capabilities - return !isSlowDevice(); -}; - -/** - * Set animation preference - * @param {boolean} enabled - Whether animations should be enabled - */ -export const setAnimationPreference = (enabled: boolean) => { - localStorage.setItem('enableAnimations', String(enabled)); -}; - -// Export singleton FPS monitor instance -export const globalFPSMonitor = new FPSMonitor(); \ No newline at end of file diff --git a/src/utils/validation.ts b/src/utils/validation.ts deleted file mode 100644 index 2fb294a8..00000000 --- a/src/utils/validation.ts +++ /dev/null @@ -1,197 +0,0 @@ -/** - * Utilities for validating data structures at runtime - */ - -export interface ValidationSchema { - required?: boolean; - /** `typeof` name, or 'array' */ - type?: string; - enum?: unknown[]; - /** Regular expression source, applied to string values */ - pattern?: string; - properties?: Record; - items?: ValidationSchema; -} - -export interface ValidationResult { - isValid: boolean; - value: T; - errors: string[]; -} - -/** - * Validates a value against a schema and returns validation result - * @template T - * @param {T} value - Value to validate - * @param {Object} schema - Validation schema - * @param {string} [name='value'] - Name of the value for error messages - * @returns {{ isValid: boolean, value: T, errors: string[] }} Validation result - */ -export const validateAgainstSchema = ( - value: T, - schema: ValidationSchema, - name = 'value' -): ValidationResult => { - const result: ValidationResult = { - isValid: true, - value, - errors: [] - }; - - // Handle null/undefined values if not allowed - if (value == null) { - if (schema.required) { - result.isValid = false; - result.errors.push(`${name} is required`); - } - return result; - } - - // Type validation - if (schema.type) { - const actualType = Array.isArray(value) ? 'array' : typeof value; - const expectedType = schema.type; - - if ( - (expectedType === 'array' && !Array.isArray(value)) || - (expectedType !== 'array' && actualType !== expectedType) - ) { - result.isValid = false; - result.errors.push(`${name} should be a ${expectedType}, received ${actualType}`); - } - } - - // Enum validation - if (schema.enum && result.isValid) { - if (!schema.enum.includes(value)) { - result.isValid = false; - result.errors.push(`${name} must be one of: ${schema.enum.join(', ')}`); - } - } - - // Pattern validation - if (schema.pattern && result.isValid && typeof value === 'string') { - const regex = new RegExp(schema.pattern); - if (!regex.test(value)) { - result.isValid = false; - result.errors.push(`${name} must match pattern: ${schema.pattern}`); - } - } - - // Property validation for objects - if (schema.properties && result.isValid && typeof value === 'object' && !Array.isArray(value)) { - Object.entries(schema.properties).forEach(([propName, propSchema]) => { - const propValue = (value as Record)[propName]; - const propResult = validateAgainstSchema(propValue, propSchema, `${name}.${propName}`); - - if (!propResult.isValid) { - result.isValid = false; - result.errors.push(...propResult.errors); - } - }); - } - - // Items validation for arrays - const itemSchema = schema.items; - if (itemSchema && result.isValid && Array.isArray(value)) { - value.forEach((item, index) => { - const itemResult = validateAgainstSchema(item, itemSchema, `${name}[${index}]`); - - if (!itemResult.isValid) { - result.isValid = false; - result.errors.push(...itemResult.errors); - } - }); - } - - return result; -}; - -/** - * Create a validation schema from PropTypes - * @param {Object} propTypes - PropTypes definitions - * @returns {Object} Validation schema - */ -export const createSchemaFromPropTypes = ( - propTypes: Record -): Record => { - const schema: Record = {}; - - Object.entries(propTypes).forEach(([propName, propType]) => { - // Extract type from PropType - const typeString = propType.toString(); - - schema[propName] = { - required: typeString.includes('isRequired'), - type: getTypeFromPropType(typeString), - // Add more schema attributes as needed - }; - }); - - return schema; -}; - -/** - * Get type string from PropType - * @param {string} propTypeString - String representation of PropType - * @returns {string} Type string - */ -function getTypeFromPropType(propTypeString: string): string { - if (propTypeString.includes('PropTypes.string')) return 'string'; - if (propTypeString.includes('PropTypes.number')) return 'number'; - if (propTypeString.includes('PropTypes.bool')) return 'boolean'; - if (propTypeString.includes('PropTypes.func')) return 'function'; - if (propTypeString.includes('PropTypes.array')) return 'array'; - if (propTypeString.includes('PropTypes.object')) return 'object'; - if (propTypeString.includes('PropTypes.node')) return 'node'; - if (propTypeString.includes('PropTypes.element')) return 'element'; - if (propTypeString.includes('PropTypes.shape')) return 'object'; - if (propTypeString.includes('PropTypes.arrayOf')) return 'array'; - return 'unknown'; -} - -/** - * Validate a component's props against PropTypes at runtime - * @param {Object} props - Component props - * @param {Object} propTypes - PropTypes definitions - * @param {string} componentName - Component name for error messages - * @returns {{ isValid: boolean, errors: string[] }} - Validation result - */ -export const validateProps = ( - props: Record, - propTypes: Record, - componentName = 'Component' -) => { - const schema = createSchemaFromPropTypes(propTypes); - const result = validateAgainstSchema(props, { - type: 'object', - properties: schema - }, componentName); - - return { - isValid: result.isValid, - errors: result.errors - }; -}; - -/** - * Logs validation errors in development mode - * @param {Array} errors - List of validation errors - * @param {string} componentName - Name of the component - */ -export const logValidationErrors = (errors: string[], componentName: string) => { - if (errors.length === 0) return; - - if (process.env.NODE_ENV === 'development') { - console.group(`Validation errors in ${componentName}:`); - errors.forEach(error => console.warn(`- ${error}`)); - console.groupEnd(); - } -}; - -export default { - validateAgainstSchema, - createSchemaFromPropTypes, - validateProps, - logValidationErrors -}; \ No newline at end of file