Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Dev #224

Merged
merged 5 commits into from
Nov 25, 2024
Merged

Dev #224

merged 5 commits into from
Nov 25, 2024

Conversation

paul-phan
Copy link
Member

@paul-phan paul-phan commented Nov 25, 2024

Summary by CodeRabbit

  • Bug Fixes

    • Improved handling of search result selections by preventing default link navigation, allowing for a smoother user experience.
  • New Features

    • Introduced a new scrolling announcement feature in the header, replacing the previous announcement bar for a more dynamic display.
    • Added a visually appealing announcement bar that reacts to user scrolling and theme settings.
  • Chores

    • Updated the theme schema to reflect changes in scrolling announcement settings and removed obsolete inputs.
    • Enhanced marquee animation performance and behavior through configuration updates.

Copy link
Contributor

coderabbitai bot commented Nov 25, 2024

Walkthrough

The changes involve modifications to multiple components related to the announcement feature in the header. The AnnouncementBar component has been removed, and a new ScrollingAnnouncement component has been introduced. The Header component now utilizes ScrollingAnnouncement instead of AnnouncementBar. Additionally, the themeSchema has been updated to reflect changes in naming and configuration for scrolling announcements. The marquee functionality has been removed, and the animation settings in the Tailwind configuration have been adjusted to enhance performance.

Changes

File Path Change Summary
app/modules/predictive-search/predictive-search-results.tsx Added event.preventDefault(); to the goToSearchResult function to suppress default navigation behavior. No other changes made to the component structure or exported entities.
app/modules/header/announcement-bar.tsx Removed the AnnouncementBar component, which managed dynamic styling based on scrolling and theme settings.
app/modules/header/index.tsx Updated imports to replace AnnouncementBar with ScrollingAnnouncement in the Header component.
app/modules/header/marquee.tsx Removed the Marquee component and its internal logic for creating a scrolling effect.
app/modules/header/scrolling-announcement.tsx Introduced the ScrollingAnnouncement component, which handles dynamic styling and scrolling announcements based on user interaction.
app/weaverse/schema.server.ts Renamed "Announcement bar" to "Scrolling announcements" and updated related input configurations in the themeSchema.
tailwind.config.js Modified animation settings for the marquee keyframe and its duration to enhance performance.

Possibly related PRs

  • Add support for animations #220: The changes in this PR involve adding a data-motion attribute to various components, which is related to the animation effects introduced in the main PR's modification of the goToSearchResult function. Both PRs focus on enhancing user interaction through visual effects.

Poem

In the search where results gleam,
A click now flows like a dream.
With a gentle pause, we take control,
Custom paths for every goal.
Hopping through data, swift and bright,
Our search results dance in delight! 🐇✨


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 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
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: 0

🧹 Outside diff range and nitpick comments (3)
app/modules/predictive-search/predictive-search-results.tsx (3)

Line range hint 14-26: Consider preserving native link behavior for non-suggestion results

The current implementation prevents default behavior for all links and then manually navigates using window.location.href. This breaks native browser features like opening links in new tabs (middle-click/right-click).

Consider conditionally preventing default behavior:

 function goToSearchResult(event: React.MouseEvent<HTMLAnchorElement>) {
-  event.preventDefault();
   let type = event.currentTarget.dataset.type;
   if (!searchInputRef.current) return;
   if (type === "SearchQuerySuggestion") {
+    event.preventDefault();
     searchInputRef.current.value = event.currentTarget.innerText;
     // dispatch event onchange for the search
     searchInputRef.current.focus();
   } else {
     searchInputRef.current.blur();
     searchInputRef.current.value = "";
-    // close the aside
-    window.location.href = event.currentTarget.href;
   }
 }

Line range hint 77-84: Remove commented-out code

Keeping commented-out code can lead to confusion and maintenance issues. If this is an alternative implementation, consider:

  1. Removing it if it's no longer needed
  2. Creating a separate component if both implementations might be needed
  3. Using a feature flag if this is meant for A/B testing

Line range hint 43-76: Consider component decomposition for better maintainability

The search results section contains complex layout logic mixed with business logic. Consider:

  1. Extracting each result section (queries, articles, products) into separate components
  2. Making the grid layout more responsive using dynamic values instead of fixed dimensions
  3. Using CSS Grid's auto-fit/auto-fill for better responsiveness

Example structure:

// SearchResultsSection.tsx
interface SearchResultsSectionProps {
  title: string;
  items: any[];
  onResultClick: (event: React.MouseEvent<HTMLAnchorElement>) => void;
}

function SearchResultsSection({ title, items, onResultClick }: SearchResultsSectionProps) {
  return (
    <div className="flex flex-col gap-4">
      <h2>{title}</h2>
      <PredictiveSearchResult
        goToSearchResult={onResultClick}
        items={items}
        type={title.toLowerCase()}
      />
    </div>
  );
}
📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL

📥 Commits

Reviewing files that changed from the base of the PR and between 5df604d and 6b69573.

📒 Files selected for processing (1)
  • app/modules/predictive-search/predictive-search-results.tsx (1 hunks)

@hta218 hta218 self-requested a review November 25, 2024 09:30
@hta218 hta218 merged commit 424b2d7 into main Nov 25, 2024
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: 4

🧹 Outside diff range and nitpick comments (3)
app/modules/header/scrolling-announcement.tsx (1)

4-4: Add documentation for the MAX_DURATION constant

Consider adding a comment explaining what MAX_DURATION represents and why it's set to 20. This will help other developers understand its purpose in controlling the animation speed.

+// Maximum duration (in seconds) for the scrolling animation at speed 1
 const MAX_DURATION = 20;
tailwind.config.js (1)

58-58: Consider adding a fallback duration

While the 15s duration is more appropriate for reading announcements, consider adding a reasonable fallback duration in case the CSS variable is not set:

-        marquee: "marquee var(--marquee-duration, 15s) linear infinite",
+        marquee: "marquee clamp(5s, var(--marquee-duration, 15s), 30s) linear infinite",

This ensures:

  • A minimum duration of 5s for short content
  • A maximum duration of 30s for very long content
  • Default of 15s when the variable is set
app/weaverse/schema.server.ts (1)

Line range hint 142-185: Consider documenting the new scrolling speed implementation

The change from seconds to a multiplier-based speed configuration represents a significant shift in the animation implementation. Consider:

  1. Adding documentation explaining how the multiplier affects scrolling speed
  2. Including examples of typical values (e.g., what speed to expect at 1x vs 20x)
  3. Documenting why the maximum was reduced from 100 to 20

This will help other developers understand and correctly utilize the new configuration.

📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL

📥 Commits

Reviewing files that changed from the base of the PR and between 6b69573 and 94ae880.

📒 Files selected for processing (6)
  • app/modules/header/announcement-bar.tsx (0 hunks)
  • app/modules/header/index.tsx (2 hunks)
  • app/modules/header/marquee.tsx (0 hunks)
  • app/modules/header/scrolling-announcement.tsx (1 hunks)
  • app/weaverse/schema.server.ts (3 hunks)
  • tailwind.config.js (2 hunks)
💤 Files with no reviewable changes (2)
  • app/modules/header/announcement-bar.tsx
  • app/modules/header/marquee.tsx
🔇 Additional comments (9)
app/modules/header/scrolling-announcement.tsx (2)

35-37: LGTM!

The conditional rendering is implemented correctly and follows React best practices.


1-65: Verify removal of old AnnouncementBar references

Since this component replaces the old AnnouncementBar, we should verify that all references to the old component have been updated.

✅ Verification successful

No remaining references to old AnnouncementBar component found

Based on the comprehensive search results:

  1. The new ScrollingAnnouncement component is properly integrated in app/modules/header/index.tsx
  2. Other files containing "announcement" references (schema.server.ts, slide.tsx, and hero-image.tsx) only contain the word in different contexts (content placeholders and configuration)
  3. No imports or usage of the old AnnouncementBar component were found in the codebase
🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Search for any remaining references to the old AnnouncementBar component
rg -l "AnnouncementBar"

# Search for any imports of the old component
ast-grep --pattern 'import { $$$AnnouncementBar$$$ } from "$_"'

Length of output: 89


Script:

#!/bin/bash
# Let's try a more comprehensive search for any references to announcement bar
# Search for files containing "announcement" case-insensitive
rg -il "announcement"

# Also search for potential kebab-case or pascal-case variations
rg -il "announcement-bar|AnnouncementBar"

# Look for any component imports with "announcement" in the name
ast-grep --pattern 'import { $$$announcement$$$ } from "$_"'

Length of output: 340


Script:

#!/bin/bash
# Let's check the content of these files to understand the context
echo "=== Checking header/index.tsx ==="
cat app/modules/header/index.tsx

echo -e "\n=== Checking schema.server.ts ==="
cat app/weaverse/schema.server.ts

echo -e "\n=== Checking sections with announcement references ==="
cat app/sections/slideshow/slide.tsx
cat app/sections/hero-image.tsx

Length of output: 32943

app/modules/header/index.tsx (3)

7-7: LGTM! Import statements are properly organized and utilized.

The new imports are correctly structured and all imported entities are used within the component.

Also applies to: 12-13


46-46: Verify ScrollingAnnouncement configuration

The component is rendered without props. Let's verify if it's properly configured through theme settings or context.

✅ Verification successful

ScrollingAnnouncement is properly configured through theme settings

The component implementation shows it correctly uses the useThemeSettings hook to access necessary configuration like topbarText, topbarHeight, topbarTextColor, and other related settings. The component handles its own configuration internally, so rendering it without props is the correct approach.

🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Check if ScrollingAnnouncement accepts any props in its implementation
ast-grep --pattern 'export function ScrollingAnnouncement($_) {
  $$$
}'

# Check for any theme configuration usage
rg -A 5 "ScrollingAnnouncement" ./app/modules/header/scrolling-announcement.tsx

Length of output: 301


Script:

#!/bin/bash
# Let's check the full implementation to understand how theme settings are used
rg -A 15 "export function ScrollingAnnouncement" ./app/modules/header/scrolling-announcement.tsx

# Check if there are any required theme settings
rg "topbarText|topbarHeight|topbarTextColor" ./app/modules/theme

Length of output: 638


Script:

#!/bin/bash
# Let's find where theme settings are defined
fd theme --type f --exec rg -l "topbarText|topbarHeight|topbarTextColor" {}

# Check the useThemeSettings hook implementation
ast-grep --pattern 'export function useThemeSettings() {
  $$$
}'

Length of output: 147


Line range hint 15-53: Consider theme customization implications

The transition from AnnouncementBar to ScrollingAnnouncement maintains clean component architecture. However, ensure that all theme customization capabilities previously available in AnnouncementBar are preserved or properly migrated to the new ScrollingAnnouncement component.

✅ Verification successful

Theme customization is properly maintained

The ScrollingAnnouncement component fully preserves theme customization capabilities through the useThemeSettings hook. It supports all necessary theme properties:

  • Text content (topbarText)
  • Height (topbarHeight)
  • Text color (topbarTextColor)
  • Background color (topbarBgColor)
  • Scrolling gap (topbarScrollingGap)
  • Scrolling speed (topbarScrollingSpeed)

The component maintains clean architecture while providing even more customization options than before, making it a proper enhancement rather than a concern.

🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Check for theme-related configurations
rg -A 5 "announcement" ./app/theme

Length of output: 86


Script:

#!/bin/bash
# Let's search for announcement-related components and configurations across the codebase
rg -l "ScrollingAnnouncement|AnnouncementBar" --type tsx --type ts

# Check the implementation of ScrollingAnnouncement
fd "ScrollingAnnouncement" --type f --exec cat {}

Length of output: 148


Script:

#!/bin/bash
# Search for announcement-related files without type restriction
rg -l "ScrollingAnnouncement|AnnouncementBar"

# Also search for any theme or customization related code near announcements
rg -B 3 -A 3 "ScrollingAnnouncement|AnnouncementBar" 

Length of output: 1554


Script:

#!/bin/bash
# Let's examine the ScrollingAnnouncement implementation and theme settings
cat app/modules/header/scrolling-announcement.tsx

# Also check for useThemeSettings implementation
rg -B 2 -A 5 "useThemeSettings"

Length of output: 16177

tailwind.config.js (1)

36-37: Great performance optimization using 3D transforms!

The switch to translate3d and translateZ(0) is a solid improvement as it:

  • Triggers hardware acceleration for smoother animations
  • Creates a new compositing layer to prevent text blur
  • Maintains better performance during animation
app/weaverse/schema.server.ts (3)

142-143: Group name change reflects new scrolling announcement implementation

The renaming from "Announcement bar" to "Scrolling announcements" aligns with the architectural changes mentioned in the AI summary, where AnnouncementBar is replaced with ScrollingAnnouncement.


Line range hint 153-161: Verify the impact of renamed configuration property

The configuration property has been renamed from scrollingGap to topbarScrollingGap. While the configuration values remain unchanged, ensure this rename is reflected in all components consuming this configuration.

✅ Verification successful

Configuration property rename is properly reflected in the codebase

The configuration property rename from scrollingGap to topbarScrollingGap has been properly implemented. The search results show:

  • No remaining references to the old scrollingGap name
  • The new topbarScrollingGap is correctly defined in schema.server.ts
  • The new name is properly consumed in scrolling-announcement.tsx component
🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Search for any remaining references to the old configuration name
rg "scrollingGap" --type ts --type tsx

# Search for usage of the new configuration name
rg "topbarScrollingGap" --type ts --type tsx

Length of output: 139


Script:

#!/bin/bash
# Search for any remaining references to the old configuration name without file type restrictions
rg "scrollingGap"

# Search for usage of the new configuration name without file type restrictions
rg "topbarScrollingGap"

Length of output: 271


177-185: Review changes to scrolling speed configuration

Several significant changes to the scrolling speed configuration:

  1. Property renamed from scrollingSpeed to topbarScrollingSpeed
  2. Range adjusted from 0-100 to 1-20
  3. Unit changed from "s" to "x"
  4. Default value reduced from 10 to 5

These changes suggest a fundamental shift in how scrolling speed is calculated. Please verify:

  1. The new range (1-20x) provides appropriate control over scrolling speed
  2. The minimum value of 1x makes sense as a lower bound
  3. Components are updated to handle the unit change from seconds to multiplier
✅ Verification successful

Review changes to scrolling speed configuration - Verified

The changes to the scrolling speed configuration are appropriate and well-implemented:

  1. The new range of 1-20x makes sense as it directly maps to the animation duration through the formula MAX_DURATION / topbarScrollingSpeed, where MAX_DURATION is 20 seconds
  2. A minimum value of 1x results in the slowest animation (20s duration), while 20x results in the fastest animation (1s duration)
  3. The unit change from "s" to "x" better reflects that the value is a multiplier of the base speed
  4. The default value of 5x results in a 4-second animation duration, which is reasonable for readable scrolling text

The implementation in the ScrollingAnnouncement component correctly applies these values to control the CSS animation duration.

🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Search for components using the scrolling speed configuration
rg "topbarScrollingSpeed|scrollingSpeed" --type tsx -A 5

# Look for any animation-related code that might be affected
ast-grep --pattern 'animation: $_ $_'

Length of output: 126


Script:

#!/bin/bash
# Search for components using the scrolling speed configuration with broader file types
rg "topbarScrollingSpeed|scrollingSpeed" -t ts -t js -t jsx -t tsx -A 5

# Look for files that might contain animation or scroll-related code
rg "animation|scroll" -t ts -t js -t jsx -t tsx -A 5

# Search for schema or configuration files that might reference these settings
fd "schema|config" -e ts -e js -e json --exec cat {}

Length of output: 30571


Script:

#!/bin/bash
# Search for scrolling-related code in the entire codebase
rg "scroll|animation" -g "!*.{json,config.js}" -A 5

# Look for any CSS/Tailwind animation configurations
rg "marquee|animation" app/styles -A 5

# Search for any React components that might use the scrolling speed
fd -e tsx -e jsx -e ts -e js . -x cat {}

Length of output: 107005


Script:

#!/bin/bash
# Search for scrolling announcement component implementation
rg -t ts -t tsx -t js "ScrollingAnnouncement" -A 10

# Look for any CSS animations related to scrolling announcements
rg -t css "marquee|scroll" -A 5 app/styles

# Search for any theme or configuration files that might use the scrolling speed
rg "topbarScrollingSpeed|scrollingSpeed" -t ts -t js -g "!*.d.ts"

Length of output: 1136


Script:

#!/bin/bash
# Get the content of the scrolling announcement component to understand the implementation
cat app/modules/header/scrolling-announcement.tsx

# Look for any constants or utility files that might define MAX_DURATION
rg "MAX_DURATION" -A 2 -B 2

Length of output: 2651

Comment on lines +28 to +33
// biome-ignore lint/correctness/useExhaustiveDependencies: <explanation>
useEffect(() => {
updateStyles();
window.addEventListener("scroll", updateStyles);
return () => window.removeEventListener("scroll", updateStyles);
}, [topbarText]);
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

Fix incomplete useEffect dependency array

The effect's dependency array is missing topbarHeight, which could lead to stale closures. Also, the lint ignore comment should explain why dependencies are being ignored.

-  // biome-ignore lint/correctness/useExhaustiveDependencies: <explanation>
+  // biome-ignore lint/correctness/useExhaustiveDependencies: topbarHeight changes would cause unnecessary re-subscriptions
   useEffect(() => {
     updateStyles();
     window.addEventListener("scroll", updateStyles);
     return () => window.removeEventListener("scroll", updateStyles);
-  }, [topbarText]);
+  }, [topbarText, topbarHeight, updateStyles]);

Committable suggestion skipped: line range outside the PR's diff.

Comment on lines +6 to +15
export function ScrollingAnnouncement() {
let themeSettings = useThemeSettings();
let {
topbarText,
topbarHeight,
topbarTextColor,
topbarBgColor,
topbarScrollingGap,
topbarScrollingSpeed,
} = themeSettings;
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 TypeScript types for theme settings

The theme settings are currently untyped, which could lead to runtime errors if the values are undefined or of unexpected types. Consider adding proper TypeScript interfaces and default values.

+interface ThemeSettings {
+  topbarText?: string;
+  topbarHeight: number;
+  topbarTextColor: string;
+  topbarBgColor: string;
+  topbarScrollingGap: number;
+  topbarScrollingSpeed: number;
+}

 export function ScrollingAnnouncement() {
-  let themeSettings = useThemeSettings();
+  let themeSettings = useThemeSettings() as ThemeSettings;
   let {
     topbarText,
     topbarHeight = 40, // Add default value
     topbarTextColor = '#000000',
     topbarBgColor = '#ffffff',
     topbarScrollingGap = 20,
     topbarScrollingSpeed = 1,
   } = themeSettings;
📝 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
export function ScrollingAnnouncement() {
let themeSettings = useThemeSettings();
let {
topbarText,
topbarHeight,
topbarTextColor,
topbarBgColor,
topbarScrollingGap,
topbarScrollingSpeed,
} = themeSettings;
interface ThemeSettings {
topbarText?: string;
topbarHeight: number;
topbarTextColor: string;
topbarBgColor: string;
topbarScrollingGap: number;
topbarScrollingSpeed: number;
}
export function ScrollingAnnouncement() {
let themeSettings = useThemeSettings() as ThemeSettings;
let {
topbarText,
topbarHeight = 40,
topbarTextColor = '#000000',
topbarBgColor = '#ffffff',
topbarScrollingGap = 20,
topbarScrollingSpeed = 1,
} = themeSettings;

Comment on lines +17 to +26
function updateStyles() {
if (topbarText) {
document.body.style.setProperty(
"--topbar-height",
`${Math.max(topbarHeight - window.scrollY, 0)}px`,
);
} else {
document.body.style.setProperty("--topbar-height", "0px");
}
}
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 scroll performance and handle SSR

The current implementation has two potential issues:

  1. Direct DOM manipulation might cause hydration mismatches during SSR
  2. Frequent style updates on scroll could impact performance

Consider these improvements:

+import { useCallback } from 'react';
+import debounce from 'lodash/debounce';

 export function ScrollingAnnouncement() {
+  const updateStyles = useCallback(
+    debounce(() => {
+      if (typeof document === 'undefined') return;
       if (topbarText) {
         document.body.style.setProperty(
           "--topbar-height",
           `${Math.max(topbarHeight - window.scrollY, 0)}px`,
         );
       } else {
         document.body.style.setProperty("--topbar-height", "0px");
       }
+    }, 16),
+    [topbarText, topbarHeight]
+  );

Committable suggestion skipped: line range outside the PR's diff.

Comment on lines +39 to +64
return (
<div
id="announcement-bar"
className="text-center z-50 relative flex items-center whitespace-nowrap"
style={
{
height: `${topbarHeight}px`,
backgroundColor: topbarBgColor,
color: topbarTextColor,
"--marquee-duration": `${MAX_DURATION / topbarScrollingSpeed}s`,
"--gap": `${topbarScrollingGap}px`,
} as React.CSSProperties
}
>
{new Array(10).fill("").map((_, idx) => {
return (
<div className="animate-marquee px-[calc(var(--gap)/2)]" key={idx}>
<div
className="flex items-center gap-[--gap] whitespace-nowrap [&_p]:flex [&_p]:gap-2 [&_p]:items-center"
dangerouslySetInnerHTML={{ __html: topbarText }}
/>
</div>
);
})}
</div>
);
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

Address security and accessibility concerns

Several issues need attention:

  1. Using dangerouslySetInnerHTML with unvalidated content poses an XSS risk
  2. The announcement bar lacks proper ARIA attributes
  3. Hard-coded array length might not work for all screen sizes

Consider these improvements:

 <div
   id="announcement-bar"
-  className="text-center z-50 relative flex items-center whitespace-nowrap"
+  className="text-center z-50 relative flex items-center whitespace-nowrap overflow-hidden"
+  role="alert"
+  aria-live="polite"
   style={/* ... */}
 >
-  {new Array(10).fill("").map((_, idx) => {
+  {new Array(Math.ceil(window.innerWidth / 300) + 2).fill("").map((_, idx) => {
     return (
       <div className="animate-marquee px-[calc(var(--gap)/2)]" key={idx}>
         <div
           className="flex items-center gap-[--gap] whitespace-nowrap [&_p]:flex [&_p]:gap-2 [&_p]:items-center"
-          dangerouslySetInnerHTML={{ __html: topbarText }}
-        />
+        >
+          {/* Replace dangerouslySetInnerHTML with a sanitized alternative */}
+          <div>{sanitizeHtml(topbarText)}</div>
+        </div>
       </div>
     );
   })}
 </div>

Also, consider adding a dependency:

+import sanitizeHtml from 'sanitize-html';

Committable suggestion skipped: line range outside the PR's diff.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

Successfully merging this pull request may close these issues.

2 participants