Skip to content

Conversation

@SrisharanVS
Copy link
Contributor

@SrisharanVS SrisharanVS commented Dec 13, 2024

Related Issue

Fixes #416

Description

Added a cursor trail

Screenshots

Summary by CodeRabbit

  • New Features

    • Introduced new cursor functionality with visual trails for enhanced user interaction.
    • Added components for cursor trail management and handling mouse movement.
  • Bug Fixes

    • Improved cursor state management through Redux integration.
  • Documentation

    • Updated type definitions for better clarity and type safety in the Redux store.

@vercel
Copy link

vercel bot commented Dec 13, 2024

Someone is attempting to deploy a commit to the Sanchit Bajaj's projects Team on Vercel.

A member of the Team first needs to authorize it.

@coderabbitai
Copy link
Contributor

coderabbitai bot commented Dec 13, 2024

Warning

There were issues while running some tools. Please review the errors and either fix the tool’s configuration or disable the tool if it’s a critical failure.

🔧 eslint

If the error stems from missing dependencies, add them to the package.json file. For unrecoverable errors (e.g., due to private dependencies), disable the tool in the CodeRabbit configuration.

src/app/layout.tsx

Oops! Something went wrong! :(

ESLint: 8.47.0

Error: Failed to load parser '@typescript-eslint/parser' declared in '.eslintrc.json » eslint-config-next/core-web-vitals » /node_modules/eslint-config-next/index.js#overrides[0]': Cannot find module 'typescript'
Require stack:

  • /node_modules/@typescript-eslint/typescript-estree/dist/convert.js
  • /node_modules/@typescript-eslint/typescript-estree/dist/ast-converter.js
  • /node_modules/@typescript-eslint/typescript-estree/dist/parser.js
  • /node_modules/@typescript-eslint/typescript-estree/dist/index.js
  • /node_modules/@typescript-eslint/parser/dist/parser.js
  • /node_modules/@typescript-eslint/parser/dist/index.js
  • /node_modules/@eslint/eslintrc/dist/eslintrc.cjs
    at Module._resolveFilename (node:internal/modules/cjs/loader:1248:15)
    at mod._resolveFilename (/node_modules/eslint-config-next/index.js:49:26)
    at Module._load (node:internal/modules/cjs/loader:1074:27)
    at TracingChannel.traceSync (node:diagnostics_channel:315:14)
    at wrapModuleLoad (node:internal/modules/cjs/loader:217:24)
    at Module.require (node:internal/modules/cjs/loader:1339:12)
    at require (node:internal/modules/helpers:135:16)
    at Object. (/node_modules/@typescript-eslint/typescript-estree/dist/convert.js:36:25)
    at Module._compile (node:internal/modules/cjs/loader:1546:14)
    at Module._extensions..js (node:internal/modules/cjs/loader:1691:10)

Walkthrough

The changes introduce a new cursor trail effect to the application by replacing the AnimatedCursor component with CursorTrail and CursorTrailHandler. The new components are integrated into the Redux store, managing cursor positions and visual trails. A new Redux slice is created to handle cursor state, including position and trail management. The Redux store is updated to include this new slice, enhancing the application's cursor interaction capabilities.

Changes

File Change Summary
src/app/layout.tsx Removed AnimatedCursor, added CursorTrail and CursorTrailHandler components.
src/components/core/cursor/cursorTrail.tsx Introduced CursorTrail component for visual cursor trails, utilizing Redux for state management.
src/components/core/cursor/cursorTrailHandler.tsx Introduced CursorTrailHandler to manage mouse movement and update cursor position in Redux.
src/redux/reducers/cursorReducer.ts Added a new Redux slice for cursor state, including interfaces and reducers for position and trail.
src/redux/store.ts Integrated cursorReducer into the Redux store and added type exports for RootState and AppDispatch.

Assessment against linked issues

Objective Addressed Explanation
Add Cursor Trail Effect Matched to Website Design Theme (#416)

Thank you for using CodeRabbit. We offer it for free to the OSS community and would appreciate your support in helping us grow. If you find it useful, would you consider giving us a shout-out on your favorite social media?

❤️ Share
🪧 Tips

Chat

There are 3 ways to chat with CodeRabbit:

  • Review comments: Directly reply to a review comment made by CodeRabbit. Example:
    • I pushed a fix in commit <commit_id>, please review it.
    • Generate unit testing code for this file.
    • Open a follow-up GitHub issue for this discussion.
  • Files and specific lines of code (under the "Files changed" tab): Tag @coderabbitai in a new review comment at the desired location with your query. Examples:
    • @coderabbitai generate unit testing code for this file.
    • @coderabbitai modularize this function.
  • PR comments: Tag @coderabbitai in a new PR comment to ask questions about the PR branch. For the best results, please provide a very specific query, as very limited context is provided in this mode. Examples:
    • @coderabbitai gather interesting stats about this repository and render them as a table. Additionally, render a pie chart showing the language distribution in the codebase.
    • @coderabbitai read src/utils.ts and generate unit testing code.
    • @coderabbitai read the files in the src/scheduler package and generate a class diagram using mermaid and a README in the markdown format.
    • @coderabbitai help me debug CodeRabbit configuration file.

Note: Be mindful of the bot's finite context window. It's strongly recommended to break down tasks such as reading entire modules into smaller chunks. For a focused discussion, use review comments to chat about specific files and their changes, instead of using the PR comments.

CodeRabbit Commands (Invoked using PR comments)

  • @coderabbitai pause to pause the reviews on a PR.
  • @coderabbitai resume to resume the paused reviews.
  • @coderabbitai review to trigger an incremental review. This is useful when automatic reviews are disabled for the repository.
  • @coderabbitai full review to do a full review from scratch and review all the files again.
  • @coderabbitai summary to regenerate the summary of the PR.
  • @coderabbitai generate docstrings to generate docstrings for this PR. (Experiment)
  • @coderabbitai resolve resolve all the CodeRabbit review comments.
  • @coderabbitai configuration to show the current CodeRabbit configuration for the repository.
  • @coderabbitai help to get help.

Other keywords and placeholders

  • Add @coderabbitai ignore anywhere in the PR description to prevent this PR from being reviewed.
  • Add @coderabbitai summary to generate the high-level summary at a specific location in the PR description.
  • Add @coderabbitai anywhere in the PR title to generate the title automatically.

CodeRabbit Configuration File (.coderabbit.yaml)

  • You can programmatically configure CodeRabbit by adding a .coderabbit.yaml file to the root of your repository.
  • Please see the configuration documentation for more information.
  • If your editor has YAML language server enabled, you can add the path at the top of this file to enable auto-completion and validation: # yaml-language-server: $schema=https://coderabbit.ai/integrations/schema.v2.json

Documentation and Community

  • Visit our Documentation for detailed information on how to use CodeRabbit.
  • Join our Discord Community to get help, request features, and share feedback.
  • Follow us on X/Twitter for updates and announcements.

Copy link

@github-actions github-actions bot left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Great job, @SrisharanVS! 🎉 Thank you for submitting your pull request. Your contribution is valuable and we appreciate your efforts to improve our project. Keep being the part of the community!

'We will promptly review your changes and offer feedback. Keep up the excellent work!
Kindly remember to check our Contributing Guidelines'

Copy link
Contributor

@coderabbitai coderabbitai bot left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 7

🧹 Outside diff range and nitpick comments (4)
src/redux/reducers/cursorReducer.ts (1)

15-19: Consider configurable initial trail length

The initial state looks good, but consider making the trail length configurable through environment variables or constants.

+const DEFAULT_TRAIL_LENGTH = 20;
+
 const initialState: CursorState = {
     position: {x:0, y:0},
     trailPositions: [],
-    trailLength:20,
+    trailLength: DEFAULT_TRAIL_LENGTH,
 }
src/components/core/cursor/cursorTrailHandler.tsx (2)

8-24: Consider adding passive event listener

For better scroll performance, especially on mobile devices, consider using passive event listeners.

-    window.addEventListener("mousemove", handleMouseMove);
+    window.addEventListener("mousemove", handleMouseMove, { passive: true });

1-26: Add error boundary protection

Consider wrapping the component with an error boundary to gracefully handle any potential errors in the mouse tracking logic.

Would you like me to provide an example implementation of an error boundary component?

src/app/layout.tsx (1)

70-70: Consider improving component readability and accessibility

While the functionality is correct, the current formatting makes it difficult to read and maintain.

Consider restructuring for better readability:

-          <ReduxProvider><CursorTrail /><CursorTrailHandler />{children}</ReduxProvider>
+          <ReduxProvider>
+            <CursorTrailHandler />
+            <CursorTrail />
+            {children}
+          </ReduxProvider>
📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL
Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between da0905a and 7d4a914.

⛔ Files ignored due to path filters (2)
  • package.json is excluded by !**/*.json
  • yarn.lock is excluded by !**/yarn.lock, !**/*.lock, !**/*.lock
📒 Files selected for processing (5)
  • src/app/layout.tsx (3 hunks)
  • src/components/core/cursor/cursorTrail.tsx (1 hunks)
  • src/components/core/cursor/cursorTrailHandler.tsx (1 hunks)
  • src/redux/reducers/cursorReducer.ts (1 hunks)
  • src/redux/store.ts (1 hunks)
🔇 Additional comments (5)
src/redux/reducers/cursorReducer.ts (1)

4-13: LGTM: Well-defined interfaces

The interfaces are well-structured and properly typed for the cursor state management.

src/redux/store.ts (2)

6-6: LGTM: Clean Redux store integration

The cursor reducer is properly integrated into the store configuration.

Also applies to: 13-13


17-18: LGTM: Proper type exports

The type exports follow Redux Toolkit best practices for TypeScript integration.

src/app/layout.tsx (1)

7-8: LGTM: Clean import additions

The new cursor trail component imports are properly organized.

src/components/core/cursor/cursorTrail.tsx (1)

1-80: Verify browser compatibility and add error handling

The implementation needs verification across different browsers and proper error handling.

Let's check for potential browser compatibility issues:

Comment on lines +33 to +36
setTrailLength(state, action:PayloadAction<number>)
{
state.trailLength = action.payload;
},
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

⚠️ Potential issue

Add validation for trail length

The setTrailLength reducer should validate the input to prevent negative or zero values.

 setTrailLength(state, action:PayloadAction<number>) {
+    if (action.payload <= 0) {
+        throw new Error('Trail length must be greater than 0');
+    }
     state.trailLength = action.payload;
 }
📝 Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
setTrailLength(state, action:PayloadAction<number>)
{
state.trailLength = action.payload;
},
setTrailLength(state, action:PayloadAction<number>)
{
if (action.payload <= 0) {
throw new Error('Trail length must be greater than 0');
}
state.trailLength = action.payload;
},

@@ -0,0 +1,41 @@
import { createSlice, PayloadAction } from "@reduxjs/toolkit";
import PageLoader from "next/dist/client/page-loader";
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

⚠️ Potential issue

Remove unused import

The PageLoader import is not used in this file.

-import PageLoader from "next/dist/client/page-loader";

Comment on lines +25 to +32
updateCursorPosition(state, action: PayloadAction<Position>) {
state.position = action.payload;
state.trailPositions.push(action.payload);
if(state.trailPositions.length > state.trailLength)
{
state.trailPositions.shift();
}
},
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🛠️ Refactor suggestion

Add performance optimization for trail updates

The current implementation might cause unnecessary re-renders by mutating the array on every mouse move.

Consider these optimizations:

  1. Throttle updates using a debounce/throttle mechanism
  2. Use array size check before push
 updateCursorPosition(state, action: PayloadAction<Position>) {
     state.position = action.payload;
-    state.trailPositions.push(action.payload);
-    if(state.trailPositions.length > state.trailLength)
-    {
+    if (state.trailPositions.length >= state.trailLength) {
         state.trailPositions.shift();
     }
+    state.trailPositions.push(action.payload);
 }
📝 Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
updateCursorPosition(state, action: PayloadAction<Position>) {
state.position = action.payload;
state.trailPositions.push(action.payload);
if(state.trailPositions.length > state.trailLength)
{
state.trailPositions.shift();
}
},
updateCursorPosition(state, action: PayloadAction<Position>) {
state.position = action.payload;
if (state.trailPositions.length >= state.trailLength) {
state.trailPositions.shift();
}
state.trailPositions.push(action.payload);
},

Comment on lines +11 to +21
useEffect(() => {
const handleMouseMove = (event: MouseEvent) => {
dispatch(updateCursorPosition({ x: event.clientX, y: event.clientY }));
};

window.addEventListener("mousemove", handleMouseMove);

return () => {
window.removeEventListener("mousemove", handleMouseMove);
};
}, [dispatch]);
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🛠️ Refactor suggestion

Optimize mouse move event handling

The current implementation dispatches an action on every mouse move, which could impact performance.

Consider throttling the mouse move handler:

+import { throttle } from 'lodash';
+
 const CursorTrailHandler = () => {
   const dispatch = useDispatch<AppDispatch>();
 
   useEffect(() => {
-    const handleMouseMove = (event: MouseEvent) => {
+    const handleMouseMove = throttle((event: MouseEvent) => {
       dispatch(updateCursorPosition({ x: event.clientX, y: event.clientY }));
-    };
+    }, 16); // ~60fps
 
     window.addEventListener("mousemove", handleMouseMove);
 
     return () => {
+      handleMouseMove.cancel();
       window.removeEventListener("mousemove", handleMouseMove);
     };
   }, [dispatch]);
📝 Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
useEffect(() => {
const handleMouseMove = (event: MouseEvent) => {
dispatch(updateCursorPosition({ x: event.clientX, y: event.clientY }));
};
window.addEventListener("mousemove", handleMouseMove);
return () => {
window.removeEventListener("mousemove", handleMouseMove);
};
}, [dispatch]);
import { throttle } from 'lodash';
useEffect(() => {
const handleMouseMove = throttle((event: MouseEvent) => {
dispatch(updateCursorPosition({ x: event.clientX, y: event.clientY }));
}, 16); // ~60fps
window.addEventListener("mousemove", handleMouseMove);
return () => {
handleMouseMove.cancel();
window.removeEventListener("mousemove", handleMouseMove);
};
}, [dispatch]);

Comment on lines +53 to +77
return (
<>
{Array(10)
.fill(0)
.map((_, index) => (
<div
key={index}
ref={(el) => {
if (el) trailRef.current[index] = el;
}}
style={{
position: "fixed",
left: `0px`, // Initial position
top: `0px`,
width: `${15 - index}px`, // Increase size here
height: `${15 - index}px`, // Increase size here
backgroundColor: `rgba(255, 0, 0, ${0.5 - index * 0.05})`, // Fade with index
borderRadius: "50%",
pointerEvents: "none",
transform: "translate(-50%, -50%)",
}}
/>
))}
</>
);
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🛠️ Refactor suggestion

Enhance accessibility and performance

The trail implementation could benefit from accessibility improvements and performance optimizations.

  1. Add ARIA attributes
  2. Use CSS transforms for better performance
  3. Consider reducing DOM elements for better performance
  4. Add media query support for reduced motion
+ const TRAIL_LENGTH = 10;
+ const BASE_SIZE = 15;
+ const BASE_OPACITY = 0.5;

return (
+   <div aria-hidden="true" className="cursor-trail-container">
-   <>
-     {Array(10)
+     {Array(TRAIL_LENGTH)
        .fill(0)
        .map((_, index) => (
          <div
            key={index}
            ref={(el) => {
              if (el) trailRef.current[index] = el;
            }}
            style={{
              position: "fixed",
              left: `0px`,
              top: `0px`,
-             width: `${15 - index}px`,
-             height: `${15 - index}px`,
-             backgroundColor: `rgba(255, 0, 0, ${0.5 - index * 0.05})`,
+             width: `${BASE_SIZE - index}px`,
+             height: `${BASE_SIZE - index}px`,
+             backgroundColor: `rgba(255, 0, 0, ${BASE_OPACITY - index * 0.05})`,
              borderRadius: "50%",
              pointerEvents: "none",
-             transform: "translate(-50%, -50%)",
+             transform: "translate(-50%, -50%) translateZ(0)",
+             willChange: "transform",
            }}
          />
        ))}
-   </>
+   </div>

Also, add this CSS to your global styles:

@media (prefers-reduced-motion: reduce) {
  .cursor-trail-container {
    display: none;
  }
}

Comment on lines +8 to +11
const trailPositions = useSelector((state: RootState) => state.cursor.trailPositions);
const restPosition = useSelector((state: RootState) => state.cursor.position); // Last cursor position
const trailRef = useRef<HTMLDivElement[]>([]); // Refs for trail elements
const animationFrameRef = useRef<number | null>(null);
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🛠️ Refactor suggestion

Consider memoizing selector and adding type safety

The Redux selectors could benefit from memoization to prevent unnecessary re-renders, and the refs could use explicit typing.

Consider these improvements:

+ import { createSelector } from '@reduxjs/toolkit';
+ import { RefObject } from 'react';

+ const selectTrailPositions = createSelector(
+   (state: RootState) => state.cursor.trailPositions,
+   (trailPositions) => trailPositions
+ );

+ const selectRestPosition = createSelector(
+   (state: RootState) => state.cursor.position,
+   (position) => position
+ );

const CursorTrail = () => {
-  const trailPositions = useSelector((state: RootState) => state.cursor.trailPositions);
-  const restPosition = useSelector((state: RootState) => state.cursor.position);
-  const trailRef = useRef<HTMLDivElement[]>([]);
+  const trailPositions = useSelector(selectTrailPositions);
+  const restPosition = useSelector(selectRestPosition);
+  const trailRef = useRef<Array<HTMLDivElement | null>>([]);
📝 Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
const trailPositions = useSelector((state: RootState) => state.cursor.trailPositions);
const restPosition = useSelector((state: RootState) => state.cursor.position); // Last cursor position
const trailRef = useRef<HTMLDivElement[]>([]); // Refs for trail elements
const animationFrameRef = useRef<number | null>(null);
import { createSelector } from '@reduxjs/toolkit';
import { RefObject } from 'react';
const selectTrailPositions = createSelector(
(state: RootState) => state.cursor.trailPositions,
(trailPositions) => trailPositions
);
const selectRestPosition = createSelector(
(state: RootState) => state.cursor.position,
(position) => position
);
const CursorTrail = () => {
const trailPositions = useSelector(selectTrailPositions);
const restPosition = useSelector(selectRestPosition);
const trailRef = useRef<Array<HTMLDivElement | null>>([]);
const animationFrameRef = useRef<number | null>(null);

Comment on lines +13 to +51
useEffect(() => {
const lerp = (start: number, end: number, factor: number) => {
return start + (end - start) * factor;
};

const animateTrail = () => {
if (trailRef.current) {
trailRef.current.forEach((el, index) => {
if (el) {
// Current element position
const currentX = parseFloat(el.style.left || "0");
const currentY = parseFloat(el.style.top || "0");

// Target position: Interpolate toward trail position or rest position
const targetX = index < trailPositions.length ? trailPositions[index].x : restPosition.x;
const targetY = index < trailPositions.length ? trailPositions[index].y : restPosition.y;

// Smoothly move toward the target position
const newX = lerp(currentX, targetX, 0.2); // Adjust 0.2 for faster catch-up
const newY = lerp(currentY, targetY, 0.2);

// Update element position
el.style.left = `${newX}px`;
el.style.top = `${newY}px`;
}
});
}

animationFrameRef.current = requestAnimationFrame(animateTrail);
};

animationFrameRef.current = requestAnimationFrame(animateTrail);

return () => {
if (animationFrameRef.current) {
cancelAnimationFrame(animationFrameRef.current);
}
};
}, [trailPositions, restPosition]);
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🛠️ Refactor suggestion

Optimize animation performance and add cleanup

The animation logic could benefit from performance optimizations and better cleanup handling.

  1. Debounce animation frame updates
  2. Add error boundaries
  3. Improve cleanup handling
  useEffect(() => {
+   let isActive = true;
    const lerp = (start: number, end: number, factor: number) => {
      return start + (end - start) * factor;
    };

    const animateTrail = () => {
+     if (!isActive) return;
      if (trailRef.current) {
        trailRef.current.forEach((el, index) => {
          if (el) {
+           try {
              // Current element position
              const currentX = parseFloat(el.style.left || "0");
              const currentY = parseFloat(el.style.top || "0");

              // Target position
              const targetX = index < trailPositions.length ? trailPositions[index].x : restPosition.x;
              const targetY = index < trailPositions.length ? trailPositions[index].y : restPosition.y;

+             // Skip update if change is minimal
+             if (Math.abs(currentX - targetX) < 0.1 && Math.abs(currentY - targetY) < 0.1) {
+               return;
+             }

              // Update position
              const newX = lerp(currentX, targetX, 0.2);
              const newY = lerp(currentY, targetY, 0.2);
              el.style.left = `${newX}px`;
              el.style.top = `${newY}px`;
+           } catch (error) {
+             console.error('Error updating trail position:', error);
+           }
          }
        });
      }

      animationFrameRef.current = requestAnimationFrame(animateTrail);
    };

    animationFrameRef.current = requestAnimationFrame(animateTrail);

    return () => {
+     isActive = false;
      if (animationFrameRef.current) {
        cancelAnimationFrame(animationFrameRef.current);
+       animationFrameRef.current = null;
      }
    };
  }, [trailPositions, restPosition]);
📝 Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
useEffect(() => {
const lerp = (start: number, end: number, factor: number) => {
return start + (end - start) * factor;
};
const animateTrail = () => {
if (trailRef.current) {
trailRef.current.forEach((el, index) => {
if (el) {
// Current element position
const currentX = parseFloat(el.style.left || "0");
const currentY = parseFloat(el.style.top || "0");
// Target position: Interpolate toward trail position or rest position
const targetX = index < trailPositions.length ? trailPositions[index].x : restPosition.x;
const targetY = index < trailPositions.length ? trailPositions[index].y : restPosition.y;
// Smoothly move toward the target position
const newX = lerp(currentX, targetX, 0.2); // Adjust 0.2 for faster catch-up
const newY = lerp(currentY, targetY, 0.2);
// Update element position
el.style.left = `${newX}px`;
el.style.top = `${newY}px`;
}
});
}
animationFrameRef.current = requestAnimationFrame(animateTrail);
};
animationFrameRef.current = requestAnimationFrame(animateTrail);
return () => {
if (animationFrameRef.current) {
cancelAnimationFrame(animationFrameRef.current);
}
};
}, [trailPositions, restPosition]);
useEffect(() => {
let isActive = true;
const lerp = (start: number, end: number, factor: number) => {
return start + (end - start) * factor;
};
const animateTrail = () => {
if (!isActive) return;
if (trailRef.current) {
trailRef.current.forEach((el, index) => {
if (el) {
try {
// Current element position
const currentX = parseFloat(el.style.left || "0");
const currentY = parseFloat(el.style.top || "0");
// Target position
const targetX = index < trailPositions.length ? trailPositions[index].x : restPosition.x;
const targetY = index < trailPositions.length ? trailPositions[index].y : restPosition.y;
// Skip update if change is minimal
if (Math.abs(currentX - targetX) < 0.1 && Math.abs(currentY - targetY) < 0.1) {
return;
}
// Update position
const newX = lerp(currentX, targetX, 0.2);
const newY = lerp(currentY, targetY, 0.2);
el.style.left = `${newX}px`;
el.style.top = `${newY}px`;
} catch (error) {
console.error('Error updating trail position:', error);
}
}
});
}
animationFrameRef.current = requestAnimationFrame(animateTrail);
};
animationFrameRef.current = requestAnimationFrame(animateTrail);
return () => {
isActive = false;
if (animationFrameRef.current) {
cancelAnimationFrame(animationFrameRef.current);
animationFrameRef.current = null;
}
};
}, [trailPositions, restPosition]);

@Sanchitbajaj02 Sanchitbajaj02 added 🏆 good first issue Good for newcomers ⭐ enhancement Feature enhancement ✨ goal: improve interface EASY Difficulty Level: Easy level1 10 points and removed wait for reviewers gssoc GSSOC'24 Required Label labels Dec 16, 2024
@Sanchitbajaj02 Sanchitbajaj02 merged commit 24d06d2 into Sanchitbajaj02:master Dec 16, 2024
13 of 14 checks passed
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

EASY Difficulty Level: Easy ⭐ enhancement Feature enhancement ✨ goal: improve interface 🏆 good first issue Good for newcomers level1 10 points

Projects

None yet

Development

Successfully merging this pull request may close these issues.

Add Cursor Trail Effect Matched to Website Design Theme

2 participants