Skip to content

CDB-113 Feat/dark mode#19

Closed
mariana-lins wants to merge 2 commits intodevelopfrom
feat/dark-mode
Closed

CDB-113 Feat/dark mode#19
mariana-lins wants to merge 2 commits intodevelopfrom
feat/dark-mode

Conversation

@mariana-lins
Copy link
Contributor

Dark Mode - Implementação Independente

Tipo de Pull Request:

  • Nova Funcionalidade (Feature)

Referência da Task

Jira/Ticket: CDB-113

Descrição das Alterações - Changelog

  • Implementado sistema de modo escuro completamente independente
  • Criado botão toggle minimalista no navbar com ícones Bootstrap Icons (lua/sol)
  • Adicionado suporte a detecção automática de preferência do sistema operacional
  • Implementada persistência da escolha do usuário via localStorage
  • Aplicados estilos dark mode usando apenas cores da paleta oficial do sistema
  • Ajustados todos os componentes (navbar, footer, cards, tabelas, inputs, etc.) para contraste adequado

Instruções de Teste

Passos para testar:

  1. Faça git pull e npm install (não há novas dependências, apenas garantia)
  2. Execute npm run dev
  3. Abra a aplicação no navegador
  4. Localize o ícone de lua 🌙 no navbar (lado direito, após "Guia de Uso")
  5. Clique no ícone para alternar entre modo claro e escuro
  6. Navegue pelas páginas: Home, Banco de Dados, Extrair Documento, Tabelas
  7. Verifique contraste de textos, cards, inputs e ícones

Resultado esperado:

  • Alternância suave entre temas light/dark
  • Ícone muda de lua (modo claro) para sol (modo escuro)
  • Todos os elementos mantêm contraste adequado e legibilidade
  • Preferência salva ao recarregar a página
  • Modo claro funciona exatamente como antes (zero impacto)

Reviewers Recomendados

  1. @[TECH_LEAD] - Motivo: Validação da arquitetura independente e não-invasiva
  2. @[FRONTEND_TEAM] - Motivo: Garantir que não há conflitos com features em desenvolvimento

Observações

Arquivos Criados:

  • src/styles/dark-mode.css - Estilos do modo escuro
  • src/scripts/darkModeToggle.js - Lógica de gerenciamento do tema

Arquivos Modificados (apenas imports):

  • src/index.css - Adicionada 1 linha de import
  • src/main.jsx - Adicionada 1 linha de import

Características Técnicas:

  • Totalmente independente: Não modifica nenhum componente ou lógica existente
  • CSS com seletores [data-theme="dark"]: Só aplica quando ativo
  • Vanilla JavaScript: Script não depende de React, funciona de forma isolada
  • Zero conflitos: Usa !important para sobrescrever sem modificar estilos originais
  • Fácil remoção: Basta deletar 2 arquivos e 2 linhas de import

Funcionalidades Implementadas:

  • ✅ Detecção automática de preferência do sistema (prefers-color-scheme)
  • ✅ Persistência no localStorage
  • ✅ Toggle minimalista com ícones Bootstrap Icons
  • ✅ Transições suaves entre temas
  • ✅ 100% das cores da paleta oficial do sistema

Compatibilidade:

  • Esta feature NÃO interfere com nenhuma outra branch ou desenvolvimento em andamento
  • O modo claro permanece como padrão e funciona exatamente como antes
  • Outros desenvolvedores podem trabalhar normalmente em suas features

Copy link

Copilot AI left a comment

Choose a reason for hiding this comment

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

Pull request overview

This PR implements a standalone dark mode feature for the application, providing users with the ability to toggle between light and dark themes. The implementation is designed to be non-invasive, using CSS data attributes and vanilla JavaScript to avoid interference with existing React components.

Key Changes:

  • Created independent dark mode CSS styling system using [data-theme="dark"] selectors
  • Implemented vanilla JavaScript toggle mechanism with localStorage persistence and OS preference detection
  • Added minimalist moon/sun icon toggle button in the navbar using Bootstrap Icons

Reviewed changes

Copilot reviewed 4 out of 4 changed files in this pull request and generated 7 comments.

File Description
src/styles/dark-mode.css Comprehensive dark mode styles for all UI components using CSS data attribute selectors
src/scripts/darkModeToggle.js Vanilla JavaScript implementation for theme toggling, persistence, and button management
src/main.jsx Added import for dark mode toggle script
src/index.css Added import for dark mode CSS stylesheet

💡 Add Copilot custom instructions for smarter, more guided reviews. Learn how to get started.

Comment on lines +254 to +262
[data-theme="dark"] b {
background: var(--black-500) !important;
color: var(--base-white) !important;
}

[data-theme="dark"] abbr {
background: var(--black-500) !important;
color: var(--base-white) !important;
}
Copy link

Copilot AI Nov 23, 2025

Choose a reason for hiding this comment

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

Applying dark mode styles to all <b> and <abbr> elements globally may have unintended side effects. These are semantic HTML elements that might be used in various contexts throughout the application. Consider using more specific selectors (e.g., scoping to specific components or adding a class) to avoid affecting elements that shouldn't have this styling.

Suggested change
[data-theme="dark"] b {
background: var(--black-500) !important;
color: var(--base-white) !important;
}
[data-theme="dark"] abbr {
background: var(--black-500) !important;
color: var(--base-white) !important;
}
[data-theme="dark"] .homepage-highlight {
background: var(--black-500) !important;
color: var(--base-white) !important;
}

Copilot uses AI. Check for mistakes.
Comment on lines +7 to +16
/* Variáveis auxiliares (não utilizadas atualmente, podem ser removidas) */
[data-theme="dark"] {
--bg-main: var(--base-black);
--bg-card: var(--black-700);
--bg-hover: var(--black-500);
--txt-primary: var(--base-white);
--txt-secondary: var(--white-500);
--txt-tertiary: var(--white-700);
}

Copy link

Copilot AI Nov 23, 2025

Choose a reason for hiding this comment

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

The comment on line 7 states these CSS variables are "não utilizadas atualmente, podem ser removidas" (not currently used, can be removed). These unused CSS custom properties add unnecessary code. Consider removing them to keep the codebase clean and maintainable.

Suggested change
/* Variáveis auxiliares (não utilizadas atualmente, podem ser removidas) */
[data-theme="dark"] {
--bg-main: var(--base-black);
--bg-card: var(--black-700);
--bg-hover: var(--black-500);
--txt-primary: var(--base-white);
--txt-secondary: var(--white-500);
--txt-tertiary: var(--white-700);
}

Copilot uses AI. Check for mistakes.
Comment on lines +279 to +281
[data-theme="dark"] * {
transition: background-color 0.3s ease, color 0.3s ease, border-color 0.3s ease;
}
Copy link

Copilot AI Nov 23, 2025

Choose a reason for hiding this comment

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

Applying a transition to all elements with the universal selector (*) can cause significant performance issues, especially on pages with many DOM elements. Each property change will trigger transitions on every element, which can lead to janky animations and increased CPU usage. Consider applying transitions only to specific elements that need them, or at minimum scope this to only the properties that actually change (background-color, color, border-color) on specific selectors rather than using the universal selector.

Suggested change
[data-theme="dark"] * {
transition: background-color 0.3s ease, color 0.3s ease, border-color 0.3s ease;
}
[data-theme="dark"] body,
[data-theme="dark"] div#root {
transition: background-color 0.3s ease, color 0.3s ease;
}
[data-theme="dark"] b,
[data-theme="dark"] abbr {
transition: background-color 0.3s ease, color 0.3s ease;
}
[data-theme="dark"] button[class*="outlined"],
[data-theme="dark"] a[class*="outlined"] {
transition: border-color 0.3s ease, color 0.3s ease, background-color 0.3s ease;
}
[data-theme="dark"] button[class*="outlined"]:hover,
[data-theme="dark"] a[class*="outlined"]:hover {
transition: background-color 0.3s ease, border-color 0.3s ease, color 0.3s ease;
}

Copilot uses AI. Check for mistakes.
updateToggleButton(initialTheme);
} else if (attempts < 20) {
// Tenta novamente após 100ms
setTimeout(() => tryCreateButton(attempts + 1), 100);
Copy link

Copilot AI Nov 23, 2025

Choose a reason for hiding this comment

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

The tryCreateButton function will attempt to find the navbar up to 20 times with 100ms intervals (total 2 seconds). However, if the navbar structure changes or the selector .navbar-nav:last-child doesn't match the actual DOM structure, this will silently fail after all attempts. Consider adding a console warning or error after all attempts are exhausted to help with debugging, or verify that this selector accurately matches your navbar structure.

Suggested change
setTimeout(() => tryCreateButton(attempts + 1), 100);
setTimeout(() => tryCreateButton(attempts + 1), 100);
} else {
console.warn(
"[DarkModeToggle] Failed to find navbar with selector '.navbar-nav:last-child' after 20 attempts. " +
"Button not created. Please check if the selector matches your DOM structure."
);

Copilot uses AI. Check for mistakes.
Comment on lines +140 to +145
// Expõe funções globalmente (opcional, para debug)
window.darkMode = {
toggle: toggleTheme,
set: applyTheme,
get: () => document.documentElement.getAttribute('data-theme')
};
Copy link

Copilot AI Nov 23, 2025

Choose a reason for hiding this comment

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

[nitpick] The window.darkMode object is exposed globally for debugging purposes, but this could lead to unintended side effects if other code modifies these functions or if there are naming conflicts. Consider either removing this exposure in production code, or namespacing it more specifically (e.g., window.__DESCRIPTUM_DARK_MODE__) to avoid potential conflicts.

Copilot uses AI. Check for mistakes.
Comment on lines +68 to +71
const button = document.createElement('button');
button.id = 'dark-mode-toggle';
button.setAttribute('aria-label', 'Alternar modo escuro');
button.innerHTML = '<i class="bi bi-moon-stars-fill"></i>';
Copy link

Copilot AI Nov 23, 2025

Choose a reason for hiding this comment

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

The button has an aria-label attribute but it's static ("Alternar modo escuro"). Consider using aria-pressed attribute to indicate the current state of the toggle button for better accessibility. The button should have aria-pressed="false" in light mode and aria-pressed="true" in dark mode to communicate the toggle state to screen readers.

Copilot uses AI. Check for mistakes.
Comment on lines +88 to +90
const title = theme === 'light' ? 'Ativar modo escuro' : 'Ativar modo claro';
button.innerHTML = icon;
button.setAttribute('title', title);
Copy link

Copilot AI Nov 23, 2025

Choose a reason for hiding this comment

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

The updateToggleButton function updates the title attribute but should also update the aria-label to match the current state. Additionally, consider adding aria-pressed attribute here to indicate whether dark mode is currently active (true) or inactive (false) for better accessibility support.

Suggested change
const title = theme === 'light' ? 'Ativar modo escuro' : 'Ativar modo claro';
button.innerHTML = icon;
button.setAttribute('title', title);
const title = theme === 'light' ? 'Ativar modo escuro' : 'Ativar modo claro';
const ariaLabel = title; // Use the same string for aria-label
const ariaPressed = theme === 'dark' ? 'true' : 'false';
button.innerHTML = icon;
button.setAttribute('title', title);
button.setAttribute('aria-label', ariaLabel);
button.setAttribute('aria-pressed', ariaPressed);

Copilot uses AI. Check for mistakes.
@mariana-lins
Copy link
Contributor Author

Este PR foi integrado ao PR #20 (feat/user-guide-page) durante o desenvolvimento.

As funcionalidades de dark mode implementadas aqui foram:

  • ✅ Incorporadas e melhoradas com correções do code review
  • ✅ Refatoradas para seguir padrões do projeto (CSS variables, error handling, acessibilidade)
  • ✅ Testadas e validadas na branch feat/user-guide-page

Os commits relevantes são:

  • 47ae36e - feat: implementação tema escuro
  • c60b031 - feat: correção dark mode styles para navbar, cards, e buttons

Ação: Fechando este PR em favor do #20 que contém todo o código atualizado.

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