react-lgpd-consent 0.1.12 → 0.1.13

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/README.md CHANGED
@@ -1,487 +0,0 @@
1
- # react-lgpd-consent 🍪
2
-
3
- [![NPM Version](https://img.shields.io/npm/v/react-lgpd-consent?style=for-the-badge&color=blue)](https://www.npmjs.com/package/react-lgpd-consent)
4
- [![License](https://img.shields.io/npm/l/react-lgpd-consent?style=for-the-badge)](https://github.com/lucianoedipo/react-lgpd-consent/blob/main/LICENSE)
5
- [![TypeScrip```
6
-
7
- ## 🎛️ Botão Flutuante de Preferências
8
-
9
- Para facilitar o acesso às configurações após consentimento inicial:
10
-
11
- ```tsx
12
- import { FloatingPreferencesButton } from 'react-lgpd-consent'
13
-
14
- function App() {
15
- return (
16
- <ConsentProvider>
17
- <MeuApp />
18
- <CookieBanner />
19
-
20
- {/* Botão flutuante opcional */}
21
- <FloatingPreferencesButton
22
- position="bottom-right"
23
- hideWhenConsented={false}
24
- tooltip="Configurar Cookies"
25
- />
26
- </ConsentProvider>
27
- )
28
- }
29
- ```
30
-
31
- ### Posições Disponíveis
32
-
33
- - `bottom-left` | `bottom-right` (padrão)
34
- - `top-left` | `top-right`
35
-
36
- ## 🔧 API Completahttps://img.shields.io/badge/TypeScript-Ready-blue?style=for-the-badge&logo=typescript)](https://www.typescriptlang.org/)
37
-
38
- [![React](https://img.shields.io/badge/React-18%2B-61DAFB?style=for-the-badge&logo=react)](https://reactjs.org/)
39
- [![Material-UI](https://img.shields.io/badge/MUI-Ready-007FFF?style=for-the-badge&logo=mui)](https://mui.com/)
40
-
41
- > **Biblioteca completa de consentimento de cookies para React e Next.js em conformidade com a LGPD**
42
-
43
- Solução moderna, acessível e personalizável para gerenciar consentimento de cookies em aplicações React, com suporte completo a SSR, Material-UI e TypeScript.
44
-
45
- ## ✨ Características Principais
46
-
47
- - 🇧🇷 **Conformidade LGPD**: Respeita totalmente a legislação brasileira de proteção de dados
48
- - ⚡ **SSR/Next.js Ready**: Suporte nativo a Server-Side Rendering sem flash de conteúdo
49
- - 🎨 **Material-UI Integration**: Componentes prontos e customizáveis com MUI
50
- - ♿ **Acessibilidade**: Navegação por teclado e leitores de tela nativamente suportados
51
- - 🌐 **Internacionalização**: Textos totalmente customizáveis (padrão pt-BR)
52
- - 🚀 **TypeScript**: API completamente tipada para melhor DX
53
- - 📦 **Zero Config**: Funciona out-of-the-box com configurações sensatas
54
- - 🎯 **Granular Control**: Controle individual de categorias (analytics, marketing, etc.)
55
- - 🚫 **Banner Bloqueante**: Modo opcional para exigir interação antes de continuar
56
- - 🎨 **Sistema de Temas**: Temas customizáveis para integração visual perfeita
57
- - ⚡ **Carregamento Condicional**: Scripts só executam após consentimento explícito
58
- - 🔌 **Modal Automático**: Modal de preferências incluído automaticamente com lazy loading
59
- - 🎛️ **Botão Flutuante**: Componente opcional para acesso fácil às preferências
60
-
61
- ## 🚀 Instalação
62
-
63
- ```bash
64
- npm install react-lgpd-consent
65
- # ou
66
- yarn add react-lgpd-consent
67
- # ou
68
- pnpm add react-lgpd-consent
69
- ```
70
-
71
- ### Dependências
72
-
73
- ```bash
74
- npm install @mui/material js-cookie
75
- ```
76
-
77
- ## � Exemplo Completo
78
-
79
- ```tsx
80
- import {
81
- ConsentProvider,
82
- CookieBanner,
83
- FloatingPreferencesButton,
84
- } from 'react-lgpd-consent'
85
-
86
- function App() {
87
- return (
88
- <ConsentProvider>
89
- <div>
90
- <h1>Meu Site</h1>
91
- <p>Conteúdo do site...</p>
92
-
93
- {/* Banner de cookies - Modal incluído automaticamente! */}
94
- <CookieBanner policyLinkUrl="/privacy-policy" blocking={true} />
95
-
96
- {/* Botão flutuante opcional para acesso às preferências */}
97
- <FloatingPreferencesButton position="bottom-right" />
98
- </div>
99
- </ConsentProvider>
100
- )
101
- }
102
- ```
103
-
104
- ## �📖 Uso Básico
105
-
106
- ### 1. Setup do Provider
107
-
108
- ```tsx
109
- import { ConsentProvider } from 'react-lgpd-consent'
110
-
111
- function App() {
112
- return (
113
- <ConsentProvider>
114
- <YourApp />
115
- </ConsentProvider>
116
- )
117
- }
118
- ```
119
-
120
- ### 2. Banner de Consentimento
121
-
122
- ```tsx
123
- import { CookieBanner } from 'react-lgpd-consent'
124
-
125
- function Layout() {
126
- return (
127
- <>
128
- <YourContent />
129
- <CookieBanner
130
- policyLinkUrl="/politica-privacidade"
131
- blocking={true} // Padrão: bloqueia até decisão
132
- />
133
- {/* Modal de preferências incluído automaticamente! */}
134
- </>
135
- )
136
- }
137
- ```
138
-
139
- ### 3. Uso do Hook
140
-
141
- ```tsx
142
- import { useConsent } from 'react-lgpd-consent'
143
-
144
- function MyComponent() {
145
- const { consented, preferences, acceptAll, openPreferences } = useConsent()
146
-
147
- return (
148
- <div>
149
- <p>Consentimento: {consented ? 'Dado' : 'Pendente'}</p>
150
- <button onClick={acceptAll}>Aceitar Todos</button>
151
- <button onClick={openPreferences}>Gerenciar Preferências</button>
152
- </div>
153
- )
154
- }
155
- ```
156
-
157
- > ✅ **O modal de preferências é incluído automaticamente pelo ConsentProvider!** Não é mais necessário renderizá-lo manualmente.
158
-
159
- ````
160
-
161
- ### 4. Carregamento Condicional de Scripts
162
-
163
- ```tsx
164
- import { ConsentGate, loadScript } from 'react-lgpd-consent'
165
-
166
- function Analytics() {
167
- return (
168
- <ConsentGate category="analytics">
169
- <GoogleAnalytics />
170
- </ConsentGate>
171
- )
172
- }
173
-
174
- // Ou carregando scripts que aguardam consentimento
175
- function MyComponent() {
176
- const { preferences, consented } = useConsent()
177
-
178
- useEffect(() => {
179
- if (consented && preferences.analytics) {
180
- loadConditionalScript(
181
- 'ga',
182
- 'https://www.googletagmanager.com/gtag/js?id=GA_ID',
183
- () => preferences.analytics, // Condição que aguarda
184
- )
185
- }
186
- }, [preferences, consented])
187
- }
188
- ````
189
-
190
- ## 🎨 Customização
191
-
192
- ### Banner Bloqueante vs Não-bloqueante
193
-
194
- ```tsx
195
- // Banner bloqueante (padrão) - impede interação até decisão
196
- <CookieBanner blocking={true} />
197
-
198
- // Banner não-intrusivo - permite navegação
199
- <CookieBanner blocking={false} />
200
- ```
201
-
202
- ### Tema Personalizado
203
-
204
- ```tsx
205
- import { ConsentProvider, defaultConsentTheme } from 'react-lgpd-consent'
206
- import { createTheme } from '@mui/material/styles'
207
-
208
- const meuTema = createTheme({
209
- ...defaultConsentTheme,
210
- palette: {
211
- ...defaultConsentTheme.palette,
212
- primary: {
213
- main: '#1976d2', // Sua cor principal
214
- },
215
- },
216
- })
217
-
218
- <ConsentProvider theme={meuTema}>
219
- <App />
220
- </ConsentProvider>
221
- ```
222
-
223
- ### Textos Personalizados
224
-
225
- ```tsx
226
- <ConsentProvider
227
- texts={{
228
- bannerMessage: "Utilizamos cookies para melhorar sua experiência.",
229
- acceptAll: "Aceitar Todos",
230
- declineAll: "Recusar Opcionais",
231
- preferences: "Configurar"
232
- }}
233
- >
234
- ```
235
-
236
- ### Configuração do Cookie
237
-
238
- ```tsx
239
- <ConsentProvider
240
- cookie={{
241
- name: 'meuSiteConsent',
242
- maxAgeDays: 180,
243
- sameSite: 'Strict'
244
- }}
245
- >
246
- ```
247
-
248
- ### Callbacks
249
-
250
- ```tsx
251
- <ConsentProvider
252
- onConsentGiven={(state) => {
253
- console.log('Consentimento dado:', state)
254
- // Inicializar analytics, etc.
255
- }}
256
- onPreferencesSaved={(prefs) => {
257
- console.log('Preferências salvas:', prefs)
258
- }}
259
- >
260
- ```
261
-
262
- ## � Banner Bloqueante
263
-
264
- Para cenários onde é necessário bloquear o acesso até obter consentimento explícito:
265
-
266
- ```tsx
267
- <CookieBanner blocking />
268
- ```
269
-
270
- Com `blocking={true}`, o banner:
271
-
272
- - Cria um overlay escuro sobre todo o conteúdo
273
- - Impede interação com o resto da página
274
- - É útil para casos críticos onde consentimento é obrigatório
275
-
276
- ## 🎨 Sistema de Temas
277
-
278
- ### Tema Personalizado
279
-
280
- ```tsx
281
- import { createTheme } from '@mui/material/styles'
282
-
283
- const meuTema = createTheme({
284
- palette: {
285
- primary: { main: '#2196f3' },
286
- secondary: { main: '#f50057' },
287
- },
288
- })
289
-
290
- <ConsentProvider theme={meuTema}>
291
- <App />
292
- </ConsentProvider>
293
- ```
294
-
295
- ### Tema Padrão
296
-
297
- O tema padrão do react-lgpd-consent está disponível para customização:
298
-
299
- ```tsx
300
- import { defaultConsentTheme } from 'react-lgpd-consent'
301
-
302
- const temaCustomizado = createTheme({
303
- ...defaultConsentTheme,
304
- palette: {
305
- ...defaultConsentTheme.palette,
306
- primary: { main: '#your-color' },
307
- },
308
- })
309
- ```
310
-
311
- ## ⚡ Carregamento Inteligente de Scripts
312
-
313
- ### Função loadScript
314
-
315
- Scripts aguardam automaticamente o **consentimento finalizado** (banner fechado ou preferências salvas):
316
-
317
- ```tsx
318
- import { loadScript } from 'react-lgpd-consent'
319
-
320
- // Carrega script apenas após consentimento para analytics
321
- await loadScript(
322
- 'gtag',
323
- 'https://www.googletagmanager.com/gtag/js?id=GA_ID',
324
- 'analytics', // Categoria obrigatória
325
- )
326
-
327
- // Script geral (sempre carrega após consentimento)
328
- await loadScript('custom-script', 'https://example.com/script.js')
329
- ```
330
-
331
- ### Comportamento Inteligente
332
-
333
- - **Aguarda decisão final**: Não executa durante mudanças no modal de preferências
334
- - **Só executa após salvar**: Scripts só rodam quando o usuário finaliza as preferências
335
- - **Baseado em categoria**: Respeita as permissões por categoria
336
-
337
- ## 🎨 Personalização Total
338
-
339
- ### Modal de Preferências Customizado
340
-
341
- Substitua completamente o modal padrão com seu próprio componente:
342
-
343
- ```tsx
344
- import { ConsentProvider, useConsent } from 'react-lgpd-consent'
345
- import MeuModalCustomizado from './MeuModalCustomizado'
346
-
347
- function App() {
348
- return (
349
- <ConsentProvider
350
- PreferencesModalComponent={MeuModalCustomizado}
351
- preferencesModalProps={{ variant: 'custom' }}
352
- >
353
- <MeuApp />
354
- </ConsentProvider>
355
- )
356
- }
357
-
358
- // Seu componente customizado
359
- function MeuModalCustomizado({ variant }) {
360
- const { isModalOpen, closePreferences, setPreference } = useConsent()
361
-
362
- return (
363
- <MyCustomDialog open={isModalOpen} onClose={closePreferences}>
364
- {/* Seu design personalizado aqui */}
365
- </MyCustomDialog>
366
- )
367
- }
368
- ```
369
-
370
- ### Desabilitar Modal Automático
371
-
372
- Para controle total, desabilite o modal automático:
373
-
374
- ```tsx
375
- <ConsentProvider disableAutomaticModal>
376
- <MeuApp />
377
- {/* Renderize seus componentes customizados onde quiser */}
378
- <MeuModalTotalmenteCustomizado />
379
- </ConsentProvider>
380
- ```
381
-
382
- ## �🔧 API Completa
383
-
384
- ### Components
385
-
386
- | Componente | Descrição | Props Principais |
387
- | --------------------------- | ------------------------------------------------ | ---------------------------------------------------------------------------------------- |
388
- | `ConsentProvider` | Provider principal do contexto | `initialState`, `texts`, `theme`, `hideBranding`, `PreferencesModalComponent`, callbacks |
389
- | `CookieBanner` | Banner de consentimento | `policyLinkUrl`, `blocking`, `hideBranding`, `debug`, pass-through MUI props |
390
- | `PreferencesModal` | Modal de preferências (incluído automaticamente) | `DialogProps`, `hideBranding` - **Opcional** |
391
- | `FloatingPreferencesButton` | Botão flutuante para abrir preferências | `position`, `hideWhenConsented`, `tooltip`, `icon`, `FabProps` |
392
- | `ConsentGate` | Renderização condicional por categoria | `category`, `children` |
393
-
394
- ### Hook `useConsent()`
395
-
396
- ```typescript
397
- interface ConsentContextValue {
398
- consented: boolean // usuário já consentiu?
399
- preferences: ConsentPreferences // preferências atuais
400
- isModalOpen: boolean // estado do modal de preferências
401
- acceptAll(): void // aceitar todas as categorias
402
- rejectAll(): void // recusar opcionais
403
- setPreference(cat: Category, value: boolean): void // definir categoria específica
404
- openPreferences(): void // abrir modal de preferências
405
- closePreferences(): void // fechar modal
406
- resetConsent(): void // resetar tudo
407
- }
408
- ```
409
-
410
- ### Hook `useConsentTexts()`
411
-
412
- ```typescript
413
- // Acesso aos textos contextuais
414
- const texts = useConsentTexts()
415
- console.log(texts.banner.title) // "Política de Cookies"
416
- ```
417
-
418
- ### Utilitários
419
-
420
- - `loadScript(id, src, category?, attrs?)` - Carrega scripts com consentimento inteligente
421
- - `defaultConsentTheme` - Tema padrão do Material-UI
422
- - Tipos TypeScript completos exportados## 🌐 SSR / Next.js
423
-
424
- Para evitar flash de conteúdo em SSR:
425
-
426
- ```tsx
427
- // pages/_app.tsx (Next.js)
428
- function MyApp({ Component, pageProps }) {
429
- return (
430
- <ConsentProvider
431
- initialState={{
432
- consented: false,
433
- preferences: { analytics: false, marketing: false },
434
- }}
435
- >
436
- <Component {...pageProps} />
437
- </ConsentProvider>
438
- )
439
- }
440
- ```
441
-
442
- ## ♿ Acessibilidade
443
-
444
- A biblioteca segue as melhores práticas de acessibilidade:
445
-
446
- - ✅ Navegação por teclado (Tab, Enter, Escape)
447
- - ✅ Leitores de tela (`aria-labelledby`, `aria-describedby`)
448
- - ✅ Foco gerenciado automaticamente
449
- - ✅ Contrastes adequados
450
- - ✅ Estrutura semântica correta
451
-
452
- ## 📚 Exemplos
453
-
454
- Confira exemplos completos no repositório:
455
-
456
- - [Básico com React](./examples/basic)
457
- - [Next.js com SSR](./examples/nextjs)
458
- - [Customização avançada](./examples/advanced)
459
- - [Integração com analytics](./examples/analytics)
460
-
461
- ## 🤝 Contribuição
462
-
463
- Contribuições são bem-vindas! Por favor:
464
-
465
- 1. Faça fork do projeto
466
- 2. Crie uma branch para sua feature (`git checkout -b feature/AmazingFeature`)
467
- 3. Commit suas mudanças (`git commit -m 'Add some AmazingFeature'`)
468
- 4. Push para a branch (`git push origin feature/AmazingFeature`)
469
- 5. Abra um Pull Request
470
-
471
- ## 📄 Licença
472
-
473
- Este projeto está licenciado sob a Licença MIT - veja o arquivo [LICENSE](LICENSE) para detalhes.
474
-
475
- ## 🙋‍♀️ Suporte
476
-
477
- - 📖 [Documentação](./docs)
478
- - 🐛 [Issues](https://github.com/lucianoedipo/react-lgpd-consent/issues)
479
- - 💬 [Discussões](https://github.com/lucianoedipo/react-lgpd-consent/discussions)
480
-
481
- ---
482
-
483
- <div align="center">
484
-
485
- **Feito com ❤️ para a comunidade React brasileira**
486
-
487
- </div>
@@ -1,6 +1,6 @@
1
1
  import {
2
2
  PreferencesModal
3
- } from "./chunk-V54LZT2Q.js";
3
+ } from "./chunk-XIHO7M77.js";
4
4
  export {
5
5
  PreferencesModal
6
6
  };
@@ -120,7 +120,7 @@ var defaultConsentTheme = createTheme({
120
120
  // src/context/ConsentContext.tsx
121
121
  import { jsx, jsxs } from "react/jsx-runtime";
122
122
  var PreferencesModal = React.lazy(
123
- () => import("./PreferencesModal-IFKCHTF2.js").then((m) => ({
123
+ () => import("./PreferencesModal-2V2W3262.js").then((m) => ({
124
124
  default: m.PreferencesModal
125
125
  }))
126
126
  );
@@ -225,7 +225,7 @@ function ConsentProvider({
225
225
  const [state, dispatch] = React.useReducer(reducer, boot);
226
226
  const [isHydrated, setIsHydrated] = React.useState(false);
227
227
  React.useEffect(() => {
228
- if (typeof window !== "undefined" && !initialState) {
228
+ if (!initialState) {
229
229
  const saved = readConsentCookie(cookie.name);
230
230
  if (saved?.consented) {
231
231
  console.log("\u{1F680} Immediate hydration: Cookie found", saved);
package/dist/index.cjs CHANGED
@@ -400,7 +400,7 @@ function ConsentProvider({
400
400
  const [state, dispatch] = React.useReducer(reducer, boot);
401
401
  const [isHydrated, setIsHydrated] = React.useState(false);
402
402
  React.useEffect(() => {
403
- if (typeof window !== "undefined" && !initialState) {
403
+ if (!initialState) {
404
404
  const saved = readConsentCookie(cookie.name);
405
405
  if (saved?.consented) {
406
406
  console.log("\u{1F680} Immediate hydration: Cookie found", saved);
package/dist/index.js CHANGED
@@ -6,7 +6,7 @@ import {
6
6
  useConsent,
7
7
  useConsentHydration,
8
8
  useConsentTexts
9
- } from "./chunk-V54LZT2Q.js";
9
+ } from "./chunk-XIHO7M77.js";
10
10
 
11
11
  // src/components/CookieBanner.tsx
12
12
  import Button from "@mui/material/Button";
package/package.json CHANGED
@@ -1,17 +1,17 @@
1
1
  {
2
2
  "name": "react-lgpd-consent",
3
- "version": "0.1.12",
4
- "description": "Biblioteca de consentimento de cookies (LGPD) para React e Next.js, com contexto, banner e modal personalizáveis usando MUI.",
3
+ "version": "0.1.13",
4
+ "description": "Biblioteca de consentimento de cookies (LGPD) para React client-side, com contexto, banner e modal personalizáveis usando MUI.",
5
5
  "keywords": [
6
6
  "lgpd",
7
7
  "cookie",
8
8
  "consent",
9
9
  "react",
10
- "nextjs",
10
+ "client-side",
11
+ "spa",
11
12
  "material-ui",
12
13
  "mui",
13
14
  "typescript",
14
- "ssr",
15
15
  "js-cookie",
16
16
  "consentimento",
17
17
  "privacidade",