Skip to content

✨ feat(header): Add Header component with responsive navigation and… #1

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

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

Conversation

dev-fagundes01
Copy link

@dev-fagundes01 dev-fagundes01 commented Apr 21, 2025

… logo

Summary by CodeRabbit

  • Novos Recursos
    • Adicionado um cabeçalho responsivo com navegação e botão de menu para dispositivos móveis.
  • Estilo
    • Implementado novo sistema de estilos globais utilizando styled-components.
    • Atualizados os estilos do cabeçalho e navegação para melhor adaptação em diferentes tamanhos de tela.
  • Refatoração
    • Substituída a importação de CSS global por um componente de estilos globais aplicados em tempo de execução.

Copy link

coderabbitai bot commented Apr 21, 2025

Walkthrough

As alterações introduzem um novo componente de cabeçalho (Header) responsivo, com navegação, à aplicação React. O arquivo de estilos globais foi migrado de CSS tradicional para um componente de estilos globais via styled-components. O componente App agora inclui o Header e ajusta o espaçamento do conteúdo principal. Foram criados novos estilos para o Header e suas subpartes, além de um arquivo de barrel para facilitar as importações. O controle de exibição do menu de navegação é gerenciado por estado interno no Header.

Changes

Arquivo(s) Resumo das alterações
src/App.tsx Incluído o componente Header acima do conteúdo principal; ajustado o espaçamento do <main>.
src/components/header/header.tsx, src/components/header/header.styles.ts Adição do componente Header com navegação responsiva e seus estilos via styled-components.
src/components/header/index.ts Criado arquivo barrel para reexportação do Header.
src/main.tsx Substituída importação de CSS global por GlobalStyles via styled-components; incluído <GlobalStyles /> na árvore React.
src/styles/globalStyles.ts Adicionado componente de estilos globais com reset de CSS e fonte padrão usando styled-components.

Sequence Diagram(s)

sequenceDiagram
    participant Usuário
    participant App
    participant Header
    participant MenuButton
    participant Nav

    Usuário->>App: Acessa aplicação
    App->>Header: Renderiza Header
    Header->>MenuButton: Exibe botão de menu (mobile)
    Usuário->>MenuButton: Clica para abrir/fechar menu
    MenuButton->>Header: Altera estado isMenuOpen
    Header->>Nav: Exibe ou oculta navegação conforme isMenuOpen
Loading

Poem

🐇
Um Header saltou no jardim do app,
Com menu que abre e fecha num estalo rápido.
Os estilos agora dançam no ar,
Com styled-components a brilhar!
O CSS global virou componente,
E a navegação ficou elegante e contente.
Saltando feliz, o código ficou mais atraente!

Tip

⚡💬 Agentic Chat (Pro Plan, General Availability)
  • We're introducing multi-step agentic chat in review comments and issue comments, within and outside of PR's. This feature enhances review and issue discussions with the CodeRabbit agentic chat by enabling advanced interactions, including the ability to create pull requests directly from comments and add commits to existing pull requests.
✨ 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.

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

@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: 5

🧹 Nitpick comments (8)
src/components/header/header.styles.ts (5)

1-14: Bom trabalho com o container do header fixo!

O container está bem estruturado com posicionamento fixo e flexbox para layout. A escolha do space-around para justificar o conteúdo é adequada.

Sugestões:

  • Considere adicionar um background-color e box-shadow para melhorar a visibilidade do header
  • Adicione um z-index alto para garantir que o header fique acima de outros elementos
  • O uso de unidades relativas como rem é excelente, mas para maior consistência, considere usar variáveis para padronizar os valores
export const HeaderContainer = styled.header`
  position: fixed;
  top: 0;
  left: 0;
  right: 0;
  display: flex;
  justify-content: space-around;  
  align-items: center;
  gap: 3rem;
  padding: 2rem 0rem;
+ background-color: #fff;
+ box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
+ z-index: 100;
`;

15-31: Boa implementação do componente de navegação responsivo!

A navegação está bem implementada com alterações de layout baseadas no tamanho da tela. O uso da prop isOpen para controlar a exibição do menu em dispositivos móveis é uma boa prática.

Sugestões:

  • Adicione uma transição suave para o menu móvel aparecer e desaparecer
  • Considere adicionar um background-color ao menu móvel para melhorar a legibilidade
  • Pode ser interessante adicionar uma sobreposição semi-transparente (overlay) quando o menu móvel estiver aberto
export const Nav = styled.nav<{ isOpen: boolean }>`
  @media (max-width: 768px) {
    position: absolute;
    top: 100%;
    left: 0;
    right: 0;
    padding: 1rem;
    display: ${({ isOpen }) => (isOpen ? "flex" : "none")};
    flex-direction: column;
    z-index: 10;
+   background-color: #fff;
+   box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
+   transition: all 0.3s ease;
  }

  @media (min-width: 769px) {
    display: flex;
    align-items: center;
  }
`;

33-43: Boa estruturação da lista de links de navegação!

A implementação dos links como uma lista não ordenada é uma boa prática de acessibilidade e semântica.

Observação:

  • Existem algumas linhas em branco extras no código (linhas 38-39)

Sugestão:

  • Remova as linhas em branco extras para manter a consistência do código
export const NavLinks = styled.ul`
  display: flex;
  align-items: center;
  list-style: none;

-
-
  @media (max-width: 768px) {
    flex-direction: column;
    width: 100%;
  }
`;

53-62: Boa estilização dos links de navegação!

Os links estão bem estilizados, com cores adequadas e efeito de transição no hover.

Sugestão:

  • Considere adicionar um efeito visual mais notável no hover (como sublinhado ou mudança de opacidade) para melhorar o feedback visual
  • Verifique se a cor #1165BA tem contraste suficiente com o fundo para acessibilidade WCAG
export const NavLink = styled.a`
  text-decoration: none;
  color: #1165BA;
  font-weight: bold;
  transition: color 0.3s ease;

  &:hover {
    color: #0070f3;
+   text-decoration: underline;
  }
`;

64-75: Boa implementação do botão de menu para dispositivos móveis!

O botão de menu está bem estruturado, ficando visível apenas em dispositivos móveis.

Sugestão:

  • Adicione padding ao botão para aumentar a área de toque em dispositivos móveis (recomendado pelo menos 44x44px para acessibilidade)
  • Considere adicionar um efeito de hover/active para feedback visual
export const MenuButton = styled.button`
  display: none;
  background: none;
  border: none;
  cursor: pointer;
+ padding: 8px;
+ 
+ &:hover, &:active {
+   opacity: 0.8;
+ }

  @media (max-width: 768px) {
    display: flex;
    align-items: center;
    justify-content: center;
  }
`;
src/components/header/header.tsx (3)

6-19: Componentes de ícones implementados de forma eficiente.

Os componentes MenuIcon e CloseIcon utilizam SVG inline, o que é uma boa prática para ícones que não precisam ser reutilizados em muitos lugares. O uso de currentColor permite que os ícones herdem a cor do elemento pai.

No entanto, estes componentes poderiam ser movidos para um arquivo separado se forem utilizados em outros lugares da aplicação.


30-30: Estilize a logo com componentes estilizados em vez de estilos inline.

A imagem do logo utiliza estilos inline que poderiam ser melhor implementados através de um componente estilizado para manter a consistência com o restante do código.

- <img src={LogoSrc} style={{height: 24.67, width: 164}} alt="SouJunior Logo" />
+ <Logo src={LogoSrc} alt="SouJunior Logo" />

E adicione ao arquivo header.styles.ts:

export const Logo = styled.img`
  height: 24.67px;
  width: 164px;
`;

21-55: Adicione suporte para eventos de teclado no menu de navegação.

A navegação atual não possui suporte para eventos de teclado, como a tecla Escape para fechar o menu, o que é importante para acessibilidade.

export const Header = () => {
  const [isMenuOpen, setIsMenuOpen] = useState(false)

  const toggleMenu = () => {
    setIsMenuOpen(!isMenuOpen)
  }
+
+ const handleKeyDown = (event: React.KeyboardEvent) => {
+   if (event.key === 'Escape' && isMenuOpen) {
+     setIsMenuOpen(false)
+   }
+ }
+
+ // Para garantir que o componente escuta eventos de teclado
+ React.useEffect(() => {
+   if (isMenuOpen) {
+     document.addEventListener('keydown', handleKeyDown as unknown as EventListener)
+   }
+   return () => {
+     document.removeEventListener('keydown', handleKeyDown as unknown as EventListener)
+   }
+ }, [isMenuOpen])

  return (
    <HeaderContainer>
      // ... resto do código
📜 Review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between a392e52 and 98e81e8.

📒 Files selected for processing (6)
  • src/App.tsx (1 hunks)
  • src/components/header/header.styles.ts (1 hunks)
  • src/components/header/header.tsx (1 hunks)
  • src/components/header/index.ts (1 hunks)
  • src/main.tsx (1 hunks)
  • src/styles/globalStyles.ts (1 hunks)
🧰 Additional context used
🧬 Code Graph Analysis (1)
src/components/header/header.tsx (2)
src/components/header/header.styles.ts (6)
  • HeaderContainer (3-13)
  • MenuButton (64-75)
  • Nav (15-31)
  • NavLinks (33-43)
  • NavItem (45-51)
  • NavLink (53-62)
src/components/cta-button/cta-button.tsx (1)
  • CtaButton (5-10)
🔇 Additional comments (7)
src/styles/globalStyles.ts (1)

1-10: Boas práticas na implementação dos estilos globais!

O uso do createGlobalStyle do styled-components é uma excelente escolha para definir estilos globais. A implementação contém os resets básicos importantes como margin, padding e box-sizing, além de definir uma fonte padrão para toda a aplicação.

Sugestões para aprimoramento:

  • Considere adicionar outras configurações úteis como outline: none para elementos focados, se alinhado com o design do projeto
  • Pense em definir algumas variáveis de cores e espaçamentos também nos estilos globais para manter consistência
src/components/header/header.styles.ts (1)

45-51: Bom uso de margens diferenciadas para os itens de navegação!

A estruturação dos itens de navegação com margens diferentes para desktop e mobile está bem implementada.

src/components/header/index.ts (1)

1-1: Boa prática usando barrel file!

O uso de um arquivo de barrel para re-exportar o componente é uma boa prática que facilita as importações em outros arquivos.

src/App.tsx (2)

1-1: Importação do componente Header adicionada corretamente.

A importação do novo componente Header utiliza um caminho de alias (@components/header), o que é uma boa prática para manter as importações limpas e mais fáceis de manter.


6-12: Integração do Header implementada adequadamente.

A estrutura do JSX foi modificada para incluir o componente Header antes do conteúdo principal. O uso do Fragment (<>...</>) é apropriado para evitar nós desnecessários no DOM.

O ajuste de marginTop: "60px" no elemento main é essencial para prevenir que o conteúdo fique oculto sob o cabeçalho fixo, considerando que o Header está posicionado como fixed conforme visto nos estilos.

src/components/header/header.tsx (2)

1-5: Importações estruturadas corretamente.

As importações estão bem organizadas, separando as dependências do React, os componentes estilizados, os assets e outros componentes.


21-27: Estado do menu implementado corretamente.

O uso do hook useState para controlar o estado do menu está correto e a função toggleMenu é implementada de forma adequada.

@@ -1,10 +1,11 @@
import { StrictMode } from "react";
import { createRoot } from "react-dom/client";
import "./index.css";
import GlobalStyles from "./styles/globalStyles.js";
Copy link

Choose a reason for hiding this comment

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

⚠️ Potential issue

Atenção à extensão do arquivo importado!

O import está referenciando um arquivo com extensão .js, mas o arquivo criado tem extensão .ts. Isso pode causar problemas dependendo da configuração do projeto.

- import GlobalStyles from "./styles/globalStyles.js";
+ import GlobalStyles from "./styles/globalStyles";
📝 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 GlobalStyles from "./styles/globalStyles.js";
-import GlobalStyles from "./styles/globalStyles.js";
+import GlobalStyles from "./styles/globalStyles";

Comment on lines 8 to +9
<App />
<GlobalStyles />
Copy link

Choose a reason for hiding this comment

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

🛠️ Refactor suggestion

Posicionamento incorreto do GlobalStyles!

Quando trabalhamos com createGlobalStyle do styled-components, é importante que o componente seja renderizado antes do componente App para garantir que os estilos já estejam aplicados quando o App for renderizado.

<StrictMode>
+   <GlobalStyles />
    <App />
-   <GlobalStyles />
</StrictMode>
📝 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
<App />
<GlobalStyles />
<StrictMode>
<GlobalStyles />
<App />
</StrictMode>

Comment on lines +28 to +33
return (
<HeaderContainer>
<img src={LogoSrc} style={{height: 24.67, width: 164}} alt="SouJunior Logo" />

<MenuButton onClick={toggleMenu}>{isMenuOpen ? <CloseIcon /> : <MenuIcon />}</MenuButton>

Copy link

Choose a reason for hiding this comment

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

🛠️ Refactor suggestion

Melhore a acessibilidade do botão de menu.

O botão de menu não possui atributos de acessibilidade necessários para usuários de leitores de tela.

- <MenuButton onClick={toggleMenu}>{isMenuOpen ? <CloseIcon /> : <MenuIcon />}</MenuButton>
+ <MenuButton 
+   onClick={toggleMenu} 
+   aria-label={isMenuOpen ? "Fechar menu" : "Abrir menu"} 
+   aria-expanded={isMenuOpen}
+ >
+   {isMenuOpen ? <CloseIcon /> : <MenuIcon />}
+ </MenuButton>
📝 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
return (
<HeaderContainer>
<img src={LogoSrc} style={{height: 24.67, width: 164}} alt="SouJunior Logo" />
<MenuButton onClick={toggleMenu}>{isMenuOpen ? <CloseIcon /> : <MenuIcon />}</MenuButton>
return (
<HeaderContainer>
<img src={LogoSrc} style={{height: 24.67, width: 164}} alt="SouJunior Logo" />
<MenuButton
onClick={toggleMenu}
aria-label={isMenuOpen ? "Fechar menu" : "Abrir menu"}
aria-expanded={isMenuOpen}
>
{isMenuOpen ? <CloseIcon /> : <MenuIcon />}
</MenuButton>

<NavLink href="/blog">Depoimentos</NavLink>
</NavItem>
<NavItem>
<NavLink href="/contato"><CtaButton label='Faça Parte'/></NavLink>
Copy link

Choose a reason for hiding this comment

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

💡 Verification agent

🧩 Analysis chain

Verifique a integração do CtaButton dentro do NavLink.

O componente CtaButton está sendo usado dentro de um NavLink, o que pode causar problemas de acessibilidade e estilo se o NavLink aplicar estilos que afetem o botão.


🏁 Script executed:

#!/bin/bash
# Verificar como o CtaButton é estilizado e se há conflitos potenciais
cat src/components/cta-button/cta-button.styles.ts

Length of output: 556


Evitar aninhamento de <button> dentro de um link

Analisar esse trecho em src/components/header/header.tsx (linha 49):

- <NavLink href="/contato"><CtaButton label="Faça Parte" /></NavLink>
+ <CtaButton as="a" href="/contato" label="Faça Parte" />
  • O <NavLink> renderiza uma <a> e o CtaButton é um <button>. Aninhar controles interativos impacta a acessibilidade.
  • Recomendo remover o wrapper <NavLink> e usar o polimorfismo do styled‑components (as="a" ou as={NavLink}) para que o próprio CtaButton seja um link sem perder estilos.
  • Verifique se o CtaButton passa corretamente o href e preserva o estilo desejado.
📝 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
<NavLink href="/contato"><CtaButton label='Faça Parte'/></NavLink>
<CtaButton as="a" href="/contato" label="Faça Parte" />

Comment on lines +34 to +52
<Nav isOpen={isMenuOpen}>
<NavLinks>
<NavItem>
<NavLink href="/">Home</NavLink>
</NavItem>
<NavItem>
<NavLink href="/sobre">Sobre Nós</NavLink>
</NavItem>
<NavItem>
<NavLink href="/projetos">Iniciativas</NavLink>
</NavItem>
<NavItem>
<NavLink href="/blog">Depoimentos</NavLink>
</NavItem>
<NavItem>
<NavLink href="/contato"><CtaButton label='Faça Parte'/></NavLink>
</NavItem>
</NavLinks>
</Nav>
Copy link

Choose a reason for hiding this comment

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

🛠️ Refactor suggestion

Implemente o fechamento do menu ao clicar em um link.

Atualmente, o menu móvel permanece aberto mesmo após o usuário clicar em um link, o que não é uma boa experiência de usuário em dispositivos móveis.

Considere adicionar uma função para fechar o menu quando um link é clicado:

export const Header = () => {
  const [isMenuOpen, setIsMenuOpen] = useState(false)

  const toggleMenu = () => {
    setIsMenuOpen(!isMenuOpen)
  }
+
+ const closeMenu = () => {
+   setIsMenuOpen(false)
+ }

  return (
    // ...
    <Nav isOpen={isMenuOpen}>
      <NavLinks>
        <NavItem>
-         <NavLink href="/">Home</NavLink>
+         <NavLink href="/" onClick={closeMenu}>Home</NavLink>
        </NavItem>
        // aplicar o onClick={closeMenu} para todos os links
📝 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
<Nav isOpen={isMenuOpen}>
<NavLinks>
<NavItem>
<NavLink href="/">Home</NavLink>
</NavItem>
<NavItem>
<NavLink href="/sobre">Sobre Nós</NavLink>
</NavItem>
<NavItem>
<NavLink href="/projetos">Iniciativas</NavLink>
</NavItem>
<NavItem>
<NavLink href="/blog">Depoimentos</NavLink>
</NavItem>
<NavItem>
<NavLink href="/contato"><CtaButton label='Faça Parte'/></NavLink>
</NavItem>
</NavLinks>
</Nav>
export const Header = () => {
const [isMenuOpen, setIsMenuOpen] = useState(false)
const toggleMenu = () => {
setIsMenuOpen(!isMenuOpen)
}
const closeMenu = () => {
setIsMenuOpen(false)
}
return (
// ...
<Nav isOpen={isMenuOpen}>
<NavLinks>
<NavItem>
<NavLink href="/" onClick={closeMenu}>Home</NavLink>
</NavItem>
<NavItem>
<NavLink href="/sobre" onClick={closeMenu}>Sobre Nós</NavLink>
</NavItem>
<NavItem>
<NavLink href="/projetos" onClick={closeMenu}>Iniciativas</NavLink>
</NavItem>
<NavItem>
<NavLink href="/blog" onClick={closeMenu}>Depoimentos</NavLink>
</NavItem>
<NavItem>
<NavLink href="/contato" onClick={closeMenu}>
<CtaButton label='Faça Parte'/>
</NavLink>
</NavItem>
</NavLinks>
</Nav>
// ...
)
}

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.

1 participant