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

toggle button #3814

Open
wants to merge 1 commit into
base: master
Choose a base branch
from
Open

toggle button #3814

wants to merge 1 commit into from

Conversation

Aryankadyan
Copy link

@Aryankadyan Aryankadyan commented Mar 6, 2025

Description

  • Implemented Dark Mode Toggle: Added a button to switch between light and dark themes.

  • Theme Persistence: Stores user preference in localStorage and applies it on page load.

  • Dynamic Theme Switching: Updates document.documentElement.classList to apply the dark class.

Related issue(s)

Summary by CodeRabbit

  • New Features
    • Introduced a dark mode toggle that lets users easily switch between light and dark themes.
    • Enhanced the interface with consistent theme-based styling, including dynamic visual cues that adjust based on the selected mode.

Copy link
Contributor

coderabbitai bot commented Mar 6, 2025

Walkthrough

This update introduces a dark mode feature. A new React component, DarkModeToggle, is added for toggling between light and dark themes, managing theme state via hooks, and updating local storage and the document’s CSS class. The main app component is modified to initialize the theme, conditionally style the UI, and incorporate the toggle button in its layout.

Changes

File Path Change Summary
components/.../DarkModeToggle.tsx Added a new React functional component that manages theme state, toggles between 'light' and 'dark', and updates local storage and document class.
pages/_app.tsx Integrated dark mode state logic, imported the new DarkModeToggle component, and updated the JSX to conditionally apply styling based on the theme.

Sequence Diagram(s)

sequenceDiagram
    participant U as User
    participant DMT as DarkModeToggle
    participant App as MyApp
    participant DOM as Document
    participant LS as LocalStorage

    U->>DMT: Click toggle button
    DMT->>DMT: Execute toggleTheme() to switch theme
    DMT->>LS: Update theme value in local storage
    DMT->>DOM: Update document’s CSS class based on new theme
    App->>DOM: Render UI with theme-dependent styling
Loading

Poem

Oh, how the shadows dance and play,
I toggled light for twinkling gray.
As a rabbit, I hop with glee,
With dark or light, both set free!
My code now sings, in style so bright,
A theme toggle joy that feels just right!
🐇✨

✨ Finishing Touches
  • 📝 Generate Docstrings

Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out.

❤️ 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.
  • @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.

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.

Welcome to AsyncAPI. Thanks a lot for creating your first pull request. Please check out our contributors guide useful for opening a pull request.
Keep in mind there are also other channels you can use to interact with AsyncAPI community. For more details check out this issue.

@asyncapi-bot
Copy link
Contributor

asyncapi-bot commented Mar 6, 2025

We require all PRs to follow Conventional Commits specification.
More details 👇🏼

 No release type found in pull request title "toggle button". Add a prefix to indicate what kind of release this pull request corresponds to. For reference, see https://www.conventionalcommits.org/

Available types:
 - feat: A new feature
 - fix: A bug fix
 - docs: Documentation only changes
 - style: Changes that do not affect the meaning of the code (white-space, formatting, missing semi-colons, etc)
 - refactor: A code change that neither fixes a bug nor adds a feature
 - perf: A code change that improves performance
 - test: Adding missing tests or correcting existing tests
 - build: Changes that affect the build system or external dependencies (example scopes: gulp, broccoli, npm)
 - ci: Changes to our CI configuration files and scripts (example scopes: Travis, Circle, BrowserStack, SauceLabs)
 - chore: Other changes that don't modify src or test files
 - revert: Reverts a previous commit

Copy link

netlify bot commented Mar 6, 2025

Deploy Preview for asyncapi-website ready!

Built without sensitive environment variables

Name Link
🔨 Latest commit 4e9d579
🔍 Latest deploy log https://app.netlify.com/sites/asyncapi-website/deploys/67c9847a649e2b00080f4b18
😎 Deploy Preview https://deploy-preview-3814--asyncapi-website.netlify.app
📱 Preview on mobile
Toggle QR Code...

QR Code

Use your smartphone camera to open QR code link.

To edit notification comments on pull requests, go to your Netlify site configuration.

@Aryankadyan
Copy link
Author

I have done some changes, for the Dark Mode Toggle Button. If it works in your deployment, please merge my code and if not, please give me feedback.

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 comments (1)
pages/_app.tsx (1)

1-16: 🛠️ Refactor suggestion

Sort imports according to linting rules.

The pipeline is showing an error about import sorting.

import '../styles/globals.css';

import type { AppProps } from 'next/app';
import Head from 'next/head';
import { appWithTranslation } from 'next-i18next';
-import React, { useEffect, useState } from 'react';
+import React from 'react';

import AlgoliaSearch from '@/components/AlgoliaSearch';
+import DarkModeToggle from '@/components/buttons/DarkModeToggle';
import ScrollButton from '@/components/buttons/ScrollButton';
-import DarkModeToggle from '@/components/buttons/DarkModeToggle';
import Banner from '@/components/campaigns/Banner';
import Footer from '@/components/footer/Footer';
import Layout from '@/components/layout/Layout';
import NavBar from '@/components/navigation/NavBar';
import StickyNavbar from '@/components/navigation/StickyNavbar';
import AppContext from '@/context/AppContext';
🧰 Tools
🪛 ESLint

[error] 1-16: Run autofix to sort these imports!

(simple-import-sort/imports)

🪛 GitHub Actions: PR testing - if Node project

[error] 1-1: Run autofix to sort these imports! simple-import-sort/imports

🧹 Nitpick comments (3)
components/buttons/DarkModeToggle.tsx (3)

25-25: Fix Tailwind CSS classnames order.

The pipeline is showing a warning about invalid Tailwind CSS classnames order.

-      className='p-2 rounded-full bg-gray-200 dark:bg-gray-800 text-black dark:text-white focus:outline-none'
+      className='rounded-full bg-gray-200 p-2 text-black focus:outline-none dark:bg-gray-800 dark:text-white'
🧰 Tools
🪛 GitHub Actions: PR testing - if Node project

[warning] 25-25: Invalid Tailwind CSS classnames order tailwindcss/classnames-order


1-6: Consider adding server-side rendering support.

The current implementation might cause hydration mismatches during SSR because localStorage is only available on the client. Consider using the useEffect hook to initialize the theme state during client-side rendering.

-  const [theme, setTheme] = useState<'light' | 'dark'>(
-    typeof window !== 'undefined' && localStorage.getItem('theme') === 'dark' ? 'dark' : 'light'
-  );
+  const [theme, setTheme] = useState<'light' | 'dark'>('light');
+
+  useEffect(() => {
+    const savedTheme = localStorage.getItem('theme');
+    if (savedTheme === 'dark') {
+      setTheme('dark');
+    }
+  }, []);

27-27: Consider using SVG icons for better visual consistency.

Using emoji characters for the toggle icons might look different across platforms. Consider using SVG icons for a more consistent appearance.

You could import icons from a library like heroicons:

+ import { SunIcon, MoonIcon } from '@heroicons/react/24/solid';

  // ...

- {theme === 'light' ? '🌙' : '☀️'}
+ {theme === 'light' ? <MoonIcon className="h-5 w-5" /> : <SunIcon className="h-5 w-5" />}
📜 Review details

Configuration used: .coderabbit.yaml
Review profile: CHILL
Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between d6a213a and 4e9d579.

📒 Files selected for processing (2)
  • components/buttons/DarkModeToggle.tsx (1 hunks)
  • pages/_app.tsx (1 hunks)
🧰 Additional context used
🪛 GitHub Actions: PR testing - if Node project
components/buttons/DarkModeToggle.tsx

[warning] 25-25: Invalid Tailwind CSS classnames order tailwindcss/classnames-order

pages/_app.tsx

[error] 1-1: Run autofix to sort these imports! simple-import-sort/imports


[warning] 18-18: Missing JSDoc comment. require-jsdoc


[error] 19-19: 'setTheme' is assigned a value but never used. unused-imports/no-unused-vars


[error] 19-19: 'setTheme' is assigned a value but never used. no-unused-vars


[error] 37-37: Strings must use singlequote. quotes

🪛 ESLint
pages/_app.tsx

[error] 19-19: 'setTheme' is assigned a value but never used.

(unused-imports/no-unused-vars)


[error] 19-19: 'setTheme' is assigned a value but never used.

(no-unused-vars)


[error] 37-37: Strings must use singlequote.

(quotes)

⏰ Context from checks skipped due to timeout of 180000ms (4)
  • GitHub Check: Redirect rules - asyncapi-website
  • GitHub Check: Header rules - asyncapi-website
  • GitHub Check: Pages changed - asyncapi-website
  • GitHub Check: Lighthouse CI
🔇 Additional comments (2)
components/buttons/DarkModeToggle.tsx (1)

3-30: Nice implementation of the DarkModeToggle component!

The component correctly:

  • Initializes the theme state based on localStorage
  • Uses useEffect to update the DOM and localStorage
  • Provides a clean toggle function
  • Renders a button with appropriate styling based on the current theme
🧰 Tools
🪛 GitHub Actions: PR testing - if Node project

[warning] 25-25: Invalid Tailwind CSS classnames order tailwindcss/classnames-order

pages/_app.tsx (1)

40-43: Great implementation of the toggle button placement!

Good job positioning the dark mode toggle button in the navbar. The flex layout works well for placing it alongside the navigation.

import Banner from '@/components/campaigns/Banner';
import Footer from '@/components/footer/Footer';
import Layout from '@/components/layout/Layout';
import NavBar from '@/components/navigation/NavBar';
import StickyNavbar from '@/components/navigation/StickyNavbar';
import AppContext from '@/context/AppContext';

/**
* @description The MyApp component is the root component for the application.
*/
function MyApp({ Component, pageProps, router }: AppProps) {
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 JSDoc comment to the MyApp function.

The linting rules require JSDoc comments for functions.

+/**
+ * Main application component that wraps all pages
+ * @param {AppProps} props - The app props including Component, pageProps, and router
+ * @returns {JSX.Element} The rendered application
+ */
function MyApp({ Component, pageProps, router }: AppProps) {
📝 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
function MyApp({ Component, pageProps, router }: AppProps) {
/**
* Main application component that wraps all pages
* @param {AppProps} props - The app props including Component, pageProps, and router
* @returns {JSX.Element} The rendered application
*/
function MyApp({ Component, pageProps, router }: AppProps) {
🧰 Tools
🪛 GitHub Actions: PR testing - if Node project

[warning] 18-18: Missing JSDoc comment. require-jsdoc

@@ -3,32 +3,44 @@
import type { AppProps } from 'next/app';
import Head from 'next/head';
import { appWithTranslation } from 'next-i18next';
import React from 'react';
import React, { useEffect, useState } from 'react';
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

Remove unused imports after removing duplicate theme logic.

After removing the duplicate theme state management, you should also remove the unused imports.

-import React, { useEffect, useState } from 'react';
+import React from 'react';
📝 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
import React, { useEffect, useState } from 'react';
import React from 'react';

<Head>
<script async defer src='https://buttons.github.io/buttons.js'></script>
</Head>
<AlgoliaSearch>
<div className='flex min-h-screen flex-col'>
<div className={`flex min-h-screen flex-col bg-white text-black dark:bg-black dark:text-white`}>
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

Fix string quote style.

According to your linting rules, strings should use single quotes instead of double quotes.

- <div className={`flex min-h-screen flex-col bg-white text-black dark:bg-black dark:text-white`}>
+ <div className={'flex min-h-screen flex-col bg-white text-black dark:bg-black dark:text-white'}>
📝 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
<div className={`flex min-h-screen flex-col bg-white text-black dark:bg-black dark:text-white`}>
<div className={'flex min-h-screen flex-col bg-white text-black dark:bg-black dark:text-white'}>
🧰 Tools
🪛 ESLint

[error] 37-37: Strings must use singlequote.

(quotes)

🪛 GitHub Actions: PR testing - if Node project

[error] 37-37: Strings must use singlequote. quotes

Comment on lines +19 to +29
const [theme, setTheme] = useState<'light' | 'dark'>(
typeof window !== 'undefined' && localStorage.getItem('theme') === 'dark' ? 'dark' : 'light'
);

useEffect(() => {
if (theme === 'dark') {
document.documentElement.classList.add('dark');
} else {
document.documentElement.classList.remove('dark');
}
}, [theme]);
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

Remove duplicate theme state management.

There's duplicate theme state management between _app.tsx and DarkModeToggle.tsx. Since the toggle component already handles theme state and persistence, you should remove this duplicate logic from _app.tsx.

-  const [theme, setTheme] = useState<'light' | 'dark'>(
-    typeof window !== 'undefined' && localStorage.getItem('theme') === 'dark' ? 'dark' : 'light'
-  );
-
-  useEffect(() => {
-    if (theme === 'dark') {
-      document.documentElement.classList.add('dark');
-    } else {
-      document.documentElement.classList.remove('dark');
-    }
-  }, [theme]);

This will also fix the linting errors related to the unused setTheme variable.

📝 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 [theme, setTheme] = useState<'light' | 'dark'>(
typeof window !== 'undefined' && localStorage.getItem('theme') === 'dark' ? 'dark' : 'light'
);
useEffect(() => {
if (theme === 'dark') {
document.documentElement.classList.add('dark');
} else {
document.documentElement.classList.remove('dark');
}
}, [theme]);
🧰 Tools
🪛 ESLint

[error] 19-19: 'setTheme' is assigned a value but never used.

(unused-imports/no-unused-vars)


[error] 19-19: 'setTheme' is assigned a value but never used.

(no-unused-vars)

🪛 GitHub Actions: PR testing - if Node project

[error] 19-19: 'setTheme' is assigned a value but never used. unused-imports/no-unused-vars


[error] 19-19: 'setTheme' is assigned a value but never used. no-unused-vars

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