react-lgpd-consent 0.3.3 → 0.3.5

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/CHANGELOG.md CHANGED
@@ -4,6 +4,71 @@ Todas as mudanças notáveis neste projeto serão documentadas neste arquivo.
4
4
 
5
5
  O formato é baseado em [Keep a Changelog](https://keepachangelog.com/pt-BR/1.0.0/), e este projeto segue [Semantic Versioning](https://semver.org/lang/pt-BR/).
6
6
 
7
+ ## [Unreleased]
8
+
9
+ ### ✨ Novas funcionalidades e melhorias
10
+
11
+ - Storybook
12
+ - Adicionado e aprimorado suporte ao Storybook com controles (`args`/`argTypes`) para componentes-chave (`FloatingPreferencesButton`, `PreferencesModal`) e suporte a tema escuro nas histórias.
13
+ - Isolamento entre stories via reset de estado (remoção/limpeza de cookie entre stories) e ajustes em `.storybook/preview.tsx` para compatibilidade com Vite/ESM.
14
+
15
+ - ConsentProvider
16
+ - `blockingStrategy` (opt-in) adicionado para permitir overlays de bloqueio controlados pelo provider.
17
+ - Melhor encaminhamento de props: `floatingPreferencesButtonProps` agora são repassadas corretamente quando o `FloatingPreferencesButton` é instanciado automaticamente.
18
+
19
+ - Testes e qualidade
20
+ - Suíte de testes ampliada: novos testes para `DesignContext`, `useConsent`, `CategoriesContext`, `ConsentScriptLoader`, `cookieUtils`, `scriptLoader`, `scriptIntegrations`, `SafeThemeProvider`, `logger`, `ConsentGate`, `PreferencesModal` e `FloatingPreferencesButton`.
21
+ - Configuração inicial de mutation testing com Stryker.
22
+ - Setup de testes atualizado para suprimir logs do `developerGuidance` durante execução normal e permitir testes dedicados que verifiquem esses logs.
23
+
24
+ - Integração e DX
25
+ - Quickstart PT/EN e melhorias no `README` para facilitar adoção e contribuições.
26
+ - Notas de troubleshooting e documentação adicional sobre Storybook e integração de componentes.
27
+
28
+ ### 🐛 Correções importantes
29
+
30
+ - `FloatingPreferencesButton` — props forward
31
+ - Sintoma: props (`tooltip`, `hideWhenConsented`, etc.) não eram aplicadas quando o botão era renderizado automaticamente pelo `ConsentProvider`.
32
+ - Solução: `ConsentProvider` agora encaminha `floatingPreferencesButtonProps` corretamente para o componente padrão. Stories atualizadas.
33
+
34
+ - Storybook fixes
35
+ - Removidos arquivos `preview.ts` que continham JSX; migrado para `preview.tsx` e ajustadas exports para evitar erros com o bundler (esbuild/vite).
36
+
37
+ ### 🧪 Testes e estabilidade
38
+
39
+ - Cobertura e robustez
40
+ - Adicionados testes que validam uso de hooks fora do `ConsentProvider` (erros esperados), hidratação a partir de cookie, callbacks (`onConsentGiven`, `onPreferencesSaved`) e fluxos de UI (abrir/fechar modal, accept/reject).
41
+ - Ajustes no `jest.setup` e um `jest.console-setup.ts` para garantir suprimir logs antes da coleta de módulos, mantendo testes determinísticos.
42
+
43
+ ### 📚 Documentação
44
+
45
+ - Quickstart & README
46
+ - Novo Quickstart em PT/EN e simplificações no `README` com foco em `QUICKSTART`.
47
+ - Documentação de uso do Storybook e troubleshooting adicionada em `docs`.
48
+
49
+ ### 🛠️ Correção crítica: Herança de ThemeProvider (v0.3.5)
50
+
51
+ - **Corrigido:** A biblioteca não deve criar ou impor um `ThemeProvider` global por si só. Agora o `ConsentProvider` herda o theme do app consumidor quando um `ThemeProvider` do MUI estiver presente. O Provider só envolverá com `ThemeProvider` se a prop `theme` for explicitamente fornecida.
52
+ - **Motivação:** Evitar conflitos de contexto MUI/Emotion, regressões visuais e problemas em SSR causados por criação de tema no escopo de módulo.
53
+ - **Export:** `createDefaultConsentTheme()` foi adicionada como fábrica para quem precisar de um fallback explícito. Há também um getter compat (deprecated) `defaultConsentTheme()` que retorna uma nova instância quando chamada.
54
+ - **Compatibilidade:** Uso padrão continua igual — se seu app fornece um `ThemeProvider` e você passa o mesmo theme para `ConsentProvider` (ou não passa `theme`), tudo continuará funcionando normalmente.
55
+
56
+ Referência: issues/PR relacionadas e notas de release serão adicionadas no branch de release.
57
+
58
+ ### ♻️ Dependências e manutenção
59
+
60
+ - Dev-deps e chores
61
+ - Atualizações de dependências de desenvolvimento (ex.: `jest`, `@types/jest`, `typedoc`, `jest-environment-jsdom`) e ajustes na `package.json` (engine `npm` atualizado, scripts e chores relacionados ao Storybook).
62
+ - Limpeza de arquivos redundantes e ajustes de ESLint/preview para Storybook.
63
+
64
+ ### Commits representativos
65
+
66
+ - Testes e supressão de logs: `fce823a`, `333ce0a`, `a1eea7e`
67
+ - Storybook / docs: `8f8c388`, `6e09058`, `329682c`, `9b1d977`, `adf0d49`
68
+ - Provider features: `967d278` (blockingStrategy)
69
+ - Quickstart / README: `db03ae3`
70
+ - Dependências / chores: `27339e7`, `3b7fdba`, `11c3602`
71
+
7
72
  ## [0.3.1] - 2025-08-13 - CORREÇÕES DE PRODUÇÃO E MELHORIAS DE COMPATIBILIDADE
8
73
 
9
74
  ### 🛡️ **Corrigido - Critical Production Fixes**
@@ -294,7 +359,7 @@ A v0.2.1 introduz um **sistema inteligente de orientações** que guia desenvolv
294
359
 
295
360
  ### 📋 **Documentação**
296
361
 
297
- - **📋 CONFORMIDADE-LGPD.md**: Guia completo de implementação conforme ANPD
362
+ - **📋 CONFORMIDADE.md**: Guia completo de implementação conforme ANPD
298
363
  - **🔄 Migração**: Instruções detalhadas v0.2.0 → v0.2.1
299
364
  - **🏛️ Exemplos**: Casos de uso governamentais e corporativos
300
365
 
@@ -458,8 +523,6 @@ A v0.2.1 introduz um **sistema inteligente de orientações** que guia desenvolv
458
523
 
459
524
  ---
460
525
 
461
- ## [Unreleased]
462
-
463
526
  ### 🔮 Futuro (v0.4.0+)
464
527
 
465
528
  - [ ] Modal detalhado com lista de cookies
package/LICENSE CHANGED
@@ -1,21 +1,21 @@
1
- MIT License
2
-
3
- Copyright (c) 2025 @lucianoedipo
4
-
5
- Permission is hereby granted, free of charge, to any person obtaining a copy
6
- of this software and associated documentation files (the "Software"), to deal
7
- in the Software without restriction, including without limitation the rights
8
- to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
- copies of the Software, and to permit persons to whom the Software is
10
- furnished to do so, subject to the following conditions:
11
-
12
- The above copyright notice and this permission notice shall be included in all
13
- copies or substantial portions of the Software.
14
-
15
- THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
- IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
- FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
- AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
- LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
- OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
- SOFTWARE.
1
+ MIT License
2
+
3
+ Copyright (c) 2025 @lucianoedipo
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
@@ -0,0 +1,245 @@
1
+ # 🚀 Quickstart
2
+
3
+ This quickstart gives everything you need to integrate `react-lgpd-consent` into a React project fast.
4
+
5
+ ## 📦 Installation
6
+
7
+ ```bash
8
+ npm install react-lgpd-consent
9
+ # or
10
+ yarn add react-lgpd-consent
11
+ ```
12
+
13
+ ### Peer dependencies
14
+
15
+ ```bash
16
+ npm install @mui/material @mui/icons-material @emotion/react @emotion/styled
17
+ ```
18
+
19
+ ## 🎯 Basic Usage (30 seconds)
20
+
21
+ ```tsx
22
+ import React from 'react'
23
+ import { ConsentProvider } from 'react-lgpd-consent'
24
+
25
+ function App() {
26
+ return (
27
+ <ConsentProvider
28
+ categories={{
29
+ enabledCategories: ['analytics', 'marketing'],
30
+ }}
31
+ >
32
+ <main>
33
+ <h1>My Application</h1>
34
+ </main>
35
+ </ConsentProvider>
36
+ )
37
+ }
38
+
39
+ export default App
40
+ ```
41
+
42
+ ## 🧭 Storybook — quick note
43
+
44
+ This repository ships an interactive Storybook playground used for manual testing and visual exploration of components. Quick commands:
45
+
46
+ - Run locally (development):
47
+
48
+ ```bash
49
+ npm run storybook
50
+ ```
51
+
52
+ - Build static Storybook (for publishing to GitHub Pages):
53
+
54
+ ```bash
55
+ npm run build-storybook
56
+ ```
57
+
58
+ Notes:
59
+ - The Storybook preview (`.storybook/preview.tsx`) applies a clean environment between stories (it removes the consent cookie and performs defensive DOM cleanup). Check that file when creating stories that rely on a clean initial state.
60
+
61
+
62
+ ## 📋 ConsentProvider props (summary)
63
+
64
+ This is a condensed reference of the most commonly-used props. For a full typed table, see the TypeScript API docs.
65
+
66
+ - `categories` (required) — Project categories configuration (e.g. enabledCategories: ["analytics"]).
67
+ - `texts` — Partial object to override UI texts.
68
+ - `theme` — Material-UI theme for consent components.
69
+ - `designTokens` — Advanced visual tokens (colors, spacing, backdrop).
70
+ - `blocking` (boolean) — If true, provider will block interaction until user acts.
71
+ - `blockingStrategy` (`"auto" | "provider" | "component"`) — How overlay is managed.
72
+ - `hideBranding` (boolean) — Hide library branding.
73
+ - `onConsentGiven` — Callback when user gives consent for the first time.
74
+ - `onPreferencesSaved` — Callback when preferences are saved.
75
+ - `CookieBannerComponent`, `PreferencesModalComponent`, `FloatingPreferencesButtonComponent` — Replace UI components.
76
+ - `cookie` — Customize cookie name, maxAge, domain, secure, sameSite.
77
+
78
+ ## 🎨 Custom components (TypeScript)
79
+
80
+ ### Custom Cookie Banner
81
+
82
+ ```tsx
83
+ import React from 'react'
84
+ import { ConsentProvider, type CustomCookieBannerProps } from 'react-lgpd-consent'
85
+
86
+ const MyBanner: React.FC<CustomCookieBannerProps> = ({
87
+ consented,
88
+ acceptAll,
89
+ rejectAll,
90
+ openPreferences,
91
+ texts,
92
+ blocking,
93
+ }) => {
94
+ return (
95
+ <div style={{ position: 'fixed', bottom: 0, left: 0, right: 0, background: '#222', color: 'white', padding: '1rem' }}>
96
+ <p>{texts.bannerMessage}</p>
97
+ <div style={{ display: 'flex', gap: '1rem', marginTop: '1rem' }}>
98
+ <button onClick={acceptAll}>{texts.acceptAll}</button>
99
+ <button onClick={rejectAll}>{texts.declineAll}</button>
100
+ <button onClick={openPreferences}>{texts.preferences}</button>
101
+ </div>
102
+ </div>
103
+ )
104
+ }
105
+
106
+ function App() {
107
+ return (
108
+ <ConsentProvider categories={{ enabledCategories: ['analytics'] }} CookieBannerComponent={MyBanner} blocking>
109
+ <main>My App</main>
110
+ </ConsentProvider>
111
+ )
112
+ }
113
+ ```
114
+
115
+ ### Custom Preferences Modal
116
+
117
+ ```tsx
118
+ import React from 'react'
119
+ import { ConsentProvider, type CustomPreferencesModalProps } from 'react-lgpd-consent'
120
+
121
+ const MyModal: React.FC<CustomPreferencesModalProps> = ({ preferences, setPreferences, closePreferences, isModalOpen, texts }) => {
122
+ if (!isModalOpen) return null
123
+
124
+ return (
125
+ <div style={{ position: 'fixed', inset: '20% 25%', background: 'white', borderRadius: 8, padding: '1.5rem', zIndex: 2000 }}>
126
+ <h2>{texts.modalTitle}</h2>
127
+ <p>{texts.modalIntro}</p>
128
+
129
+ {Object.entries(preferences).map(([category, enabled]) => (
130
+ <label key={category} style={{ display: 'block', margin: '0.5rem 0' }}>
131
+ <input
132
+ type="checkbox"
133
+ checked={enabled}
134
+ onChange={(e) => setPreferences({ ...preferences, [category]: e.target.checked })}
135
+ disabled={category === 'necessary'}
136
+ />{' '}
137
+ {category === 'necessary' ? texts.necessaryAlwaysOn : `Cookies ${category}`}
138
+ </label>
139
+ ))}
140
+
141
+ <div style={{ display: 'flex', gap: '1rem', justifyContent: 'flex-end', marginTop: '1rem' }}>
142
+ <button onClick={closePreferences}>Cancel</button>
143
+ <button onClick={closePreferences}>{texts.save}</button>
144
+ </div>
145
+ </div>
146
+ )
147
+ }
148
+
149
+ function App() {
150
+ return (
151
+ <ConsentProvider categories={{ enabledCategories: ['analytics', 'marketing'] }} PreferencesModalComponent={MyModal}>
152
+ <main>My App</main>
153
+ </ConsentProvider>
154
+ )
155
+ }
156
+ ```
157
+
158
+ ## 🎮 Programmatic control
159
+
160
+ ### React hook: `useOpenPreferencesModal`
161
+
162
+ ```tsx
163
+ import React from 'react'
164
+ import { useOpenPreferencesModal, useConsent } from 'react-lgpd-consent'
165
+
166
+ function MyComponent() {
167
+ const openPreferences = useOpenPreferencesModal()
168
+ const { preferences, acceptAll, rejectAll } = useConsent()
169
+
170
+ return (
171
+ <div>
172
+ <h3>Analytics: {preferences.analytics ? 'enabled' : 'disabled'}</h3>
173
+ <button onClick={openPreferences}>⚙️ Manage preferences</button>
174
+ <button onClick={acceptAll}>✅ Accept all</button>
175
+ <button onClick={rejectAll}>❌ Reject all</button>
176
+ </div>
177
+ )
178
+ }
179
+ ```
180
+
181
+ ### Global: `window.openPreferencesModal` (for plain JS)
182
+
183
+ ```html
184
+ <button onclick="window.openPreferencesModal?.()">Configure cookies</button>
185
+
186
+ <script>
187
+ if (typeof window.openPreferencesModal === 'function') {
188
+ console.log('Consent system available')
189
+ }
190
+ </script>
191
+ ```
192
+
193
+ ## 🐛 Debug system
194
+
195
+ ```tsx
196
+ import { setDebugLogging, LogLevel } from 'react-lgpd-consent'
197
+
198
+ // enable verbose debug locally
199
+ setDebugLogging(true, LogLevel.DEBUG)
200
+
201
+ // quieter in staging
202
+ setDebugLogging(true, LogLevel.INFO)
203
+
204
+ // errors only
205
+ setDebugLogging(true, LogLevel.ERROR)
206
+
207
+ // disable
208
+ setDebugLogging(false)
209
+ ```
210
+
211
+ Use the `useConsent` hook to inspect runtime state (preferences, consented) and optionally render a small debug panel in dev mode.
212
+
213
+ ## 🎨 Material-UI Theme integration
214
+
215
+ Wrap your app with MUI `ThemeProvider` and optionally pass a `theme` prop to `ConsentProvider` to style consent components.
216
+
217
+ ## 🔧 Advanced
218
+
219
+ - `designTokens` for low-level visual control (colors, spacing, backdrop)
220
+ - `cookie` to customize name, maxAge, domain, secure, sameSite
221
+ - `blocking` + `blockingStrategy` to control overlay behavior
222
+
223
+ ## 🚀 Common use cases
224
+
225
+ - E-commerce: analytics + marketing integrations
226
+ - Blog: only analytics
227
+ - Enterprise: strict blocking and auditing via `onPreferencesSaved`
228
+
229
+ ## 🆘 Troubleshooting
230
+
231
+ - "ConsentProvider must be used within ConsentProvider": ensure hooks are called inside provider tree.
232
+ - Banner not showing: clear consent cookie, check z-index and config.
233
+ - TypeScript types: set `moduleResolution` or `skipLibCheck` in `tsconfig` if needed.
234
+
235
+ ## 📚 Next steps
236
+
237
+ - API docs: `API.md`
238
+ - LGPD compliance guide: `CONFORMIDADE.md`
239
+ - Integrations: `INTEGRACOES.md`
240
+ - Example app: `example/`
241
+
242
+
243
+ ---
244
+
245
+ Tip: enable debug logs during development with `setDebugLogging(true, LogLevel.DEBUG)` to see runtime behavior.