react-lgpd-consent 0.3.0 → 0.3.2

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.
@@ -1,1070 +0,0 @@
1
- // src/components/PreferencesModal.tsx
2
- import Button2 from "@mui/material/Button";
3
- import Dialog from "@mui/material/Dialog";
4
- import DialogActions from "@mui/material/DialogActions";
5
- import DialogContent from "@mui/material/DialogContent";
6
- import DialogTitle from "@mui/material/DialogTitle";
7
- import FormControlLabel from "@mui/material/FormControlLabel";
8
- import FormGroup from "@mui/material/FormGroup";
9
- import Switch from "@mui/material/Switch";
10
- import Typography3 from "@mui/material/Typography";
11
- import { useEffect as useEffect4, useState as useState2 } from "react";
12
-
13
- // src/context/CategoriesContext.tsx
14
- import * as React2 from "react";
15
-
16
- // src/utils/developerGuidance.ts
17
- import * as React from "react";
18
- var DEFAULT_PROJECT_CATEGORIES = {
19
- enabledCategories: ["analytics"]
20
- // Só analytics além de necessary
21
- };
22
- function analyzeDeveloperConfiguration(config) {
23
- const guidance = {
24
- warnings: [],
25
- suggestions: [],
26
- activeCategoriesInfo: [],
27
- usingDefaults: !config
28
- };
29
- const finalConfig = config || DEFAULT_PROJECT_CATEGORIES;
30
- if (!config) {
31
- guidance.warnings.push(
32
- 'LGPD-CONSENT: Nenhuma configura\xE7\xE3o de categorias especificada. Usando padr\xE3o: necessary + analytics. Para produ\xE7\xE3o, recomenda-se especificar explicitamente as categorias via prop "categories".'
33
- );
34
- }
35
- guidance.activeCategoriesInfo.push({
36
- id: "necessary",
37
- name: "Cookies Necess\xE1rios",
38
- description: "Essenciais para funcionamento b\xE1sico do site",
39
- essential: true,
40
- uiRequired: false
41
- // Não precisa de toggle (sempre ativo)
42
- });
43
- const enabledCategories = finalConfig.enabledCategories || [];
44
- const categoryNames = {
45
- analytics: {
46
- name: "Cookies Anal\xEDticos",
47
- description: "Medem uso e performance do site"
48
- },
49
- functional: {
50
- name: "Cookies Funcionais",
51
- description: "Melhoram experi\xEAncia e funcionalidades"
52
- },
53
- marketing: {
54
- name: "Cookies de Marketing",
55
- description: "Publicidade direcionada e campanhas"
56
- },
57
- social: {
58
- name: "Cookies de Redes Sociais",
59
- description: "Integra\xE7\xE3o com plataformas sociais"
60
- },
61
- personalization: {
62
- name: "Cookies de Personaliza\xE7\xE3o",
63
- description: "Adaptam conte\xFAdo \xE0s prefer\xEAncias do usu\xE1rio"
64
- }
65
- };
66
- enabledCategories.forEach((categoryId) => {
67
- const categoryInfo = categoryNames[categoryId];
68
- if (categoryInfo) {
69
- guidance.activeCategoriesInfo.push({
70
- id: categoryId,
71
- name: categoryInfo.name,
72
- description: categoryInfo.description,
73
- essential: false,
74
- uiRequired: true
75
- // Precisa de toggle na UI
76
- });
77
- }
78
- });
79
- const totalToggleable = guidance.activeCategoriesInfo.filter(
80
- (c) => c.uiRequired
81
- ).length;
82
- if (totalToggleable === 0) {
83
- guidance.suggestions.push(
84
- 'Apenas cookies necess\xE1rios est\xE3o configurados. Para compliance completo LGPD, considere adicionar categorias como "analytics" ou "functional" conforme uso real.'
85
- );
86
- }
87
- if (totalToggleable > 5) {
88
- guidance.warnings.push(
89
- `${totalToggleable} categorias opcionais detectadas. UI com muitas op\xE7\xF5es pode ' +
90
- 'prejudicar experi\xEAncia do usu\xE1rio. Considere agrupar categorias similares.`
91
- );
92
- }
93
- return guidance;
94
- }
95
- function logDeveloperGuidance(guidance, disableGuidanceProp) {
96
- if (disableGuidanceProp) {
97
- return;
98
- }
99
- const isProduction = (
100
- // 1. NODE_ENV de bundlers (Vite, webpack, etc.)
101
- typeof globalThis.process !== "undefined" && globalThis.process.env?.NODE_ENV === "production" || // 2. Flag customizada para desabilitar logs
102
- typeof globalThis !== "undefined" && globalThis.__LGPD_PRODUCTION__ === true || // 3. Flag de desenvolvimento desabilitada via window global (legado)
103
- typeof window !== "undefined" && window.__LGPD_DISABLE_GUIDANCE__ === true
104
- );
105
- if (isProduction) return;
106
- const PREFIX = "[\u{1F36A} LGPD-CONSENT]";
107
- if (guidance.warnings.length > 0) {
108
- console.group(`${PREFIX} \u26A0\uFE0F Avisos de Configura\xE7\xE3o`);
109
- guidance.warnings.forEach((warning) => console.warn(`${PREFIX} ${warning}`));
110
- console.groupEnd();
111
- }
112
- if (guidance.suggestions.length > 0) {
113
- console.group(`${PREFIX} \u{1F4A1} Sugest\xF5es`);
114
- guidance.suggestions.forEach(
115
- (suggestion) => console.info(`${PREFIX} ${suggestion}`)
116
- );
117
- console.groupEnd();
118
- }
119
- if (guidance.usingDefaults) {
120
- console.warn(
121
- // Changed from console.info to console.warn
122
- `${PREFIX} \u{1F4CB} Usando configura\xE7\xE3o padr\xE3o. Para personalizar, use a prop "categories" no ConsentProvider.`
123
- );
124
- }
125
- console.group(`${PREFIX} \u{1F527} Categorias Ativas (para UI customizada)`);
126
- console.table(
127
- guidance.activeCategoriesInfo.map((cat) => ({
128
- ID: cat.id,
129
- Nome: cat.name,
130
- "Toggle UI?": cat.uiRequired ? "\u2705 SIM" : "\u274C N\xC3O (sempre ativo)",
131
- "Essencial?": cat.essential ? "\u{1F512} SIM" : "\u2699\uFE0F N\xC3O"
132
- }))
133
- );
134
- console.info(
135
- `${PREFIX} \u2139\uFE0F Use estes dados para criar componentes customizados adequados.`
136
- );
137
- console.groupEnd();
138
- }
139
- function useDeveloperGuidance(config, disableGuidanceProp) {
140
- const guidance = analyzeDeveloperConfiguration(config);
141
- const stringifiedConfig = React.useMemo(
142
- () => JSON.stringify(config),
143
- [config]
144
- );
145
- React.useEffect(() => {
146
- if (disableGuidanceProp === true) {
147
- return;
148
- }
149
- logDeveloperGuidance(guidance, disableGuidanceProp);
150
- }, [guidance, stringifiedConfig, disableGuidanceProp]);
151
- return guidance;
152
- }
153
-
154
- // src/context/CategoriesContext.tsx
155
- import { jsx } from "react/jsx-runtime";
156
- var CategoriesContext = React2.createContext(
157
- null
158
- );
159
- function CategoriesProvider({
160
- children,
161
- config,
162
- // NOVO: configuração completa
163
- disableDeveloperGuidance
164
- }) {
165
- const contextValue = React2.useMemo(() => {
166
- const finalConfig = config || DEFAULT_PROJECT_CATEGORIES;
167
- const guidance = analyzeDeveloperConfiguration(config);
168
- const toggleableCategories = guidance.activeCategoriesInfo.filter(
169
- (cat) => cat.uiRequired
170
- );
171
- return {
172
- config: finalConfig,
173
- guidance,
174
- toggleableCategories,
175
- allCategories: guidance.activeCategoriesInfo
176
- };
177
- }, [config]);
178
- React2.useEffect(() => {
179
- logDeveloperGuidance(contextValue.guidance, disableDeveloperGuidance);
180
- }, [contextValue.guidance, disableDeveloperGuidance]);
181
- return /* @__PURE__ */ jsx(CategoriesContext.Provider, { value: contextValue, children });
182
- }
183
- function useCategories() {
184
- const context = React2.useContext(CategoriesContext);
185
- if (!context) {
186
- throw new Error(
187
- "useCategories deve ser usado dentro de CategoriesProvider. Certifique-se de que o ConsentProvider est\xE1 envolvendo seu componente."
188
- );
189
- }
190
- return context;
191
- }
192
- function useCategoryStatus(categoryId) {
193
- const { allCategories } = useCategories();
194
- const category = allCategories.find((cat) => cat.id === categoryId);
195
- return {
196
- isActive: !!category,
197
- isEssential: category?.essential || false,
198
- needsToggle: category?.uiRequired || false,
199
- name: category?.name,
200
- description: category?.description
201
- };
202
- }
203
-
204
- // src/context/ConsentContext.tsx
205
- import * as React4 from "react";
206
- import { ThemeProvider } from "@mui/material/styles";
207
-
208
- // src/utils/cookieUtils.ts
209
- import Cookies from "js-cookie";
210
- var DEFAULT_COOKIE_OPTS = {
211
- name: "cookieConsent",
212
- maxAgeDays: 365,
213
- sameSite: "Lax",
214
- secure: typeof window !== "undefined" ? window.location.protocol === "https:" : false,
215
- path: "/"
216
- };
217
- var COOKIE_SCHEMA_VERSION = "1.0";
218
- function readConsentCookie(name = DEFAULT_COOKIE_OPTS.name) {
219
- if (typeof document === "undefined") return null;
220
- const raw = Cookies.get(name);
221
- if (!raw) return null;
222
- try {
223
- const data = JSON.parse(raw);
224
- if (!data.version) {
225
- return migrateLegacyCookie(data);
226
- }
227
- if (data.version !== COOKIE_SCHEMA_VERSION) {
228
- console.warn(
229
- `[react-lgpd-consent] Cookie version mismatch: ${data.version} != ${COOKIE_SCHEMA_VERSION}`
230
- );
231
- return null;
232
- }
233
- return data;
234
- } catch {
235
- return null;
236
- }
237
- }
238
- function migrateLegacyCookie(legacyData) {
239
- try {
240
- const now = (/* @__PURE__ */ new Date()).toISOString();
241
- return {
242
- version: COOKIE_SCHEMA_VERSION,
243
- consented: legacyData.consented || false,
244
- preferences: legacyData.preferences || { necessary: true },
245
- consentDate: now,
246
- // Não temos o original, usar data atual
247
- lastUpdate: now,
248
- source: "banner",
249
- // Assumir origem banner
250
- isModalOpen: false
251
- // Nunca persistir estado de UI
252
- };
253
- } catch {
254
- return null;
255
- }
256
- }
257
- function writeConsentCookie(state, config, opts, source = "banner") {
258
- if (typeof document === "undefined") return;
259
- const now = (/* @__PURE__ */ new Date()).toISOString();
260
- const o = { ...DEFAULT_COOKIE_OPTS, ...opts };
261
- const cookieData = {
262
- version: COOKIE_SCHEMA_VERSION,
263
- consented: state.consented,
264
- preferences: state.preferences,
265
- consentDate: state.consentDate || now,
266
- // Preservar data original ou usar atual
267
- lastUpdate: now,
268
- source,
269
- projectConfig: config
270
- // isModalOpen NÃO é persistido (campo de UI apenas)
271
- };
272
- Cookies.set(o.name, JSON.stringify(cookieData), {
273
- expires: o.maxAgeDays,
274
- sameSite: o.sameSite,
275
- secure: o.secure,
276
- path: o.path
277
- });
278
- }
279
- function removeConsentCookie(opts) {
280
- if (typeof document === "undefined") return;
281
- const o = { ...DEFAULT_COOKIE_OPTS, ...opts };
282
- Cookies.remove(o.name, { path: o.path });
283
- }
284
-
285
- // src/utils/categoryUtils.ts
286
- function createProjectPreferences(config, defaultValue = false) {
287
- const preferences = {
288
- necessary: true
289
- // Sempre presente e true (essencial)
290
- };
291
- const enabledCategories = config?.enabledCategories || [];
292
- enabledCategories.forEach((category) => {
293
- if (category !== "necessary") {
294
- preferences[category] = defaultValue;
295
- }
296
- });
297
- return preferences;
298
- }
299
- function validateProjectPreferences(preferences, config) {
300
- const validPreferences = {
301
- necessary: true
302
- // Sempre válida
303
- };
304
- const enabledCategories = config?.enabledCategories || [];
305
- enabledCategories.forEach((category) => {
306
- if (category !== "necessary" && preferences[category] !== void 0) {
307
- validPreferences[category] = preferences[category];
308
- }
309
- });
310
- return validPreferences;
311
- }
312
-
313
- // src/utils/theme.ts
314
- import { createTheme } from "@mui/material/styles";
315
- var defaultConsentTheme = createTheme({
316
- palette: {
317
- primary: {
318
- main: "#1976d2",
319
- contrastText: "#ffffff"
320
- },
321
- secondary: {
322
- main: "#dc004e",
323
- contrastText: "#ffffff"
324
- },
325
- background: {
326
- default: "#fafafa",
327
- paper: "#ffffff"
328
- },
329
- text: {
330
- primary: "#333333",
331
- secondary: "#666666"
332
- },
333
- action: {
334
- hover: "rgba(25, 118, 210, 0.04)"
335
- }
336
- },
337
- typography: {
338
- fontFamily: '"Roboto", "Helvetica", "Arial", sans-serif',
339
- body2: {
340
- fontSize: "0.875rem",
341
- lineHeight: 1.43
342
- },
343
- button: {
344
- fontWeight: 500,
345
- textTransform: "none"
346
- }
347
- },
348
- components: {
349
- MuiButton: {
350
- styleOverrides: {
351
- root: {
352
- borderRadius: 8,
353
- paddingX: 16,
354
- paddingY: 8
355
- },
356
- contained: {
357
- boxShadow: "0 2px 4px rgba(0,0,0,0.1)",
358
- "&:hover": {
359
- boxShadow: "0 4px 8px rgba(0,0,0,0.15)"
360
- }
361
- }
362
- }
363
- },
364
- MuiPaper: {
365
- styleOverrides: {
366
- root: {
367
- borderRadius: 12
368
- }
369
- }
370
- },
371
- MuiDialog: {
372
- styleOverrides: {
373
- paper: {
374
- borderRadius: 16
375
- }
376
- }
377
- }
378
- }
379
- });
380
-
381
- // src/context/DesignContext.tsx
382
- import * as React3 from "react";
383
- import { jsx as jsx2 } from "react/jsx-runtime";
384
- var DesignContext = React3.createContext(void 0);
385
- function DesignProvider({
386
- tokens,
387
- children
388
- }) {
389
- return /* @__PURE__ */ jsx2(DesignContext.Provider, { value: tokens, children });
390
- }
391
- function useDesignTokens() {
392
- return React3.useContext(DesignContext);
393
- }
394
-
395
- // src/components/CookieBanner.tsx
396
- import Button from "@mui/material/Button";
397
- import Box from "@mui/material/Box";
398
- import Paper from "@mui/material/Paper";
399
- import Snackbar from "@mui/material/Snackbar";
400
- import Stack from "@mui/material/Stack";
401
- import Typography2 from "@mui/material/Typography";
402
- import Link2 from "@mui/material/Link";
403
-
404
- // src/components/Branding.tsx
405
- import Link from "@mui/material/Link";
406
- import Typography from "@mui/material/Typography";
407
- import { jsx as jsx3, jsxs } from "react/jsx-runtime";
408
- var brandingStyles = {
409
- banner: {
410
- fontSize: "0.65rem",
411
- textAlign: "right",
412
- mt: 1,
413
- opacity: 0.7,
414
- fontStyle: "italic",
415
- width: "100%"
416
- },
417
- modal: {
418
- fontSize: "0.65rem",
419
- textAlign: "right",
420
- px: 3,
421
- pb: 1,
422
- opacity: 0.7,
423
- fontStyle: "italic",
424
- width: "100%"
425
- }
426
- };
427
- var linkStyles = {
428
- textDecoration: "none",
429
- fontWeight: 500,
430
- "&:hover": {
431
- textDecoration: "underline"
432
- }
433
- };
434
- function Branding({ variant, hidden = false }) {
435
- if (hidden) return null;
436
- return /* @__PURE__ */ jsxs(
437
- Typography,
438
- {
439
- variant: "caption",
440
- sx: (theme) => ({
441
- ...brandingStyles[variant],
442
- color: theme.palette.text.secondary
443
- }),
444
- children: [
445
- "fornecido por",
446
- " ",
447
- /* @__PURE__ */ jsx3(
448
- Link,
449
- {
450
- href: "https://www.ledipo.eti.br",
451
- target: "_blank",
452
- rel: "noopener noreferrer",
453
- sx: (theme) => ({
454
- ...linkStyles,
455
- color: theme.palette.primary.main
456
- }),
457
- children: "L\xC9dipO.eti.br"
458
- }
459
- )
460
- ]
461
- }
462
- );
463
- }
464
-
465
- // src/components/CookieBanner.tsx
466
- import { Fragment, jsx as jsx4, jsxs as jsxs2 } from "react/jsx-runtime";
467
- function CookieBanner({
468
- policyLinkUrl,
469
- debug,
470
- blocking = true,
471
- hideBranding = false,
472
- SnackbarProps,
473
- PaperProps
474
- }) {
475
- const { consented, acceptAll, rejectAll, openPreferences } = useConsent();
476
- const texts = useConsentTexts();
477
- const isHydrated = useConsentHydration();
478
- const designTokens = useDesignTokens();
479
- const open = debug ? true : isHydrated && !consented;
480
- if (!open) return null;
481
- const bannerStyle = {
482
- p: designTokens?.spacing?.padding?.banner ?? 2,
483
- maxWidth: 720,
484
- mx: "auto",
485
- backgroundColor: designTokens?.colors?.background,
486
- color: designTokens?.colors?.text,
487
- borderRadius: designTokens?.spacing?.borderRadius?.banner,
488
- fontFamily: designTokens?.typography?.fontFamily
489
- };
490
- const bannerContent = /* @__PURE__ */ jsx4(Paper, { elevation: 3, sx: bannerStyle, ...PaperProps, children: /* @__PURE__ */ jsxs2(Stack, { spacing: 1, children: [
491
- /* @__PURE__ */ jsxs2(
492
- Typography2,
493
- {
494
- variant: "body2",
495
- sx: { fontSize: designTokens?.typography?.fontSize?.banner },
496
- children: [
497
- texts.bannerMessage,
498
- " ",
499
- policyLinkUrl && /* @__PURE__ */ jsx4(
500
- Link2,
501
- {
502
- href: policyLinkUrl,
503
- underline: "hover",
504
- target: "_blank",
505
- rel: "noopener noreferrer",
506
- sx: { color: designTokens?.colors?.primary },
507
- children: texts.policyLink ?? "Saiba mais"
508
- }
509
- )
510
- ]
511
- }
512
- ),
513
- /* @__PURE__ */ jsxs2(
514
- Stack,
515
- {
516
- direction: { xs: "column", sm: "row" },
517
- spacing: 1,
518
- justifyContent: "flex-end",
519
- children: [
520
- /* @__PURE__ */ jsx4(
521
- Button,
522
- {
523
- variant: "outlined",
524
- onClick: rejectAll,
525
- sx: { color: designTokens?.colors?.secondary },
526
- children: texts.declineAll
527
- }
528
- ),
529
- /* @__PURE__ */ jsx4(
530
- Button,
531
- {
532
- variant: "contained",
533
- onClick: acceptAll,
534
- sx: { backgroundColor: designTokens?.colors?.primary },
535
- children: texts.acceptAll
536
- }
537
- ),
538
- /* @__PURE__ */ jsx4(
539
- Button,
540
- {
541
- variant: "text",
542
- onClick: openPreferences,
543
- sx: { color: designTokens?.colors?.text },
544
- children: texts.preferences
545
- }
546
- )
547
- ]
548
- }
549
- ),
550
- !hideBranding && /* @__PURE__ */ jsx4(Branding, { variant: "banner" })
551
- ] }) });
552
- const positionStyle = {
553
- position: "fixed",
554
- zIndex: 1300,
555
- ...designTokens?.layout?.position === "top" ? { top: 0 } : { bottom: 0 },
556
- left: 0,
557
- right: 0,
558
- width: designTokens?.layout?.width?.desktop ?? "100%",
559
- p: 2
560
- };
561
- if (blocking) {
562
- return /* @__PURE__ */ jsxs2(Fragment, { children: [
563
- /* @__PURE__ */ jsx4(
564
- Box,
565
- {
566
- sx: {
567
- position: "fixed",
568
- top: 0,
569
- left: 0,
570
- right: 0,
571
- bottom: 0,
572
- backgroundColor: designTokens?.layout?.backdrop ? "rgba(0, 0, 0, 0.5)" : "transparent",
573
- zIndex: 1299
574
- }
575
- }
576
- ),
577
- /* @__PURE__ */ jsx4(Box, { sx: positionStyle, children: bannerContent })
578
- ] });
579
- }
580
- return /* @__PURE__ */ jsx4(
581
- Snackbar,
582
- {
583
- open,
584
- anchorOrigin: {
585
- vertical: designTokens?.layout?.position === "top" ? "top" : "bottom",
586
- horizontal: "center"
587
- },
588
- ...SnackbarProps,
589
- children: bannerContent
590
- }
591
- );
592
- }
593
-
594
- // src/components/FloatingPreferencesButton.tsx
595
- import CookieOutlined from "@mui/icons-material/CookieOutlined";
596
- import Fab from "@mui/material/Fab";
597
- import Tooltip from "@mui/material/Tooltip";
598
- import { useTheme } from "@mui/material/styles";
599
- import { jsx as jsx5 } from "react/jsx-runtime";
600
- function FloatingPreferencesButton({
601
- position = "bottom-right",
602
- offset = 24,
603
- icon = /* @__PURE__ */ jsx5(CookieOutlined, {}),
604
- tooltip,
605
- FabProps,
606
- hideWhenConsented = false
607
- }) {
608
- const { openPreferences, consented } = useConsent();
609
- const theme = useTheme();
610
- if (hideWhenConsented && consented) {
611
- return null;
612
- }
613
- const tooltipText = tooltip ?? "Gerenciar Prefer\xEAncias de Cookies";
614
- const getPosition = () => {
615
- const styles = {
616
- position: "fixed",
617
- zIndex: 1200
618
- };
619
- switch (position) {
620
- case "bottom-left":
621
- return { ...styles, bottom: offset, left: offset };
622
- case "bottom-right":
623
- return { ...styles, bottom: offset, right: offset };
624
- case "top-left":
625
- return { ...styles, top: offset, left: offset };
626
- case "top-right":
627
- return { ...styles, top: offset, right: offset };
628
- default:
629
- return { ...styles, bottom: offset, right: offset };
630
- }
631
- };
632
- return /* @__PURE__ */ jsx5(Tooltip, { title: tooltipText, placement: "top", children: /* @__PURE__ */ jsx5(
633
- Fab,
634
- {
635
- size: "medium",
636
- color: "primary",
637
- onClick: openPreferences,
638
- sx: {
639
- ...getPosition(),
640
- backgroundColor: theme.palette.primary.main,
641
- "&:hover": {
642
- backgroundColor: theme.palette.primary.dark
643
- }
644
- },
645
- "aria-label": tooltipText,
646
- ...FabProps,
647
- children: icon
648
- }
649
- ) });
650
- }
651
-
652
- // src/context/ConsentContext.tsx
653
- import { jsx as jsx6, jsxs as jsxs3 } from "react/jsx-runtime";
654
- var PreferencesModal = React4.lazy(
655
- () => import("./PreferencesModal-XCTM6WJN.js").then((m) => ({
656
- default: m.PreferencesModal
657
- }))
658
- );
659
- function createFullConsentState(consented, preferences, source, projectConfig, isModalOpen = false, existingState) {
660
- const now = (/* @__PURE__ */ new Date()).toISOString();
661
- return {
662
- version: "1.0",
663
- consented,
664
- preferences,
665
- consentDate: existingState?.consentDate || now,
666
- lastUpdate: now,
667
- source,
668
- projectConfig,
669
- isModalOpen
670
- };
671
- }
672
- var DEFAULT_TEXTS = {
673
- // Textos básicos
674
- bannerMessage: "Utilizamos cookies para melhorar sua experi\xEAncia.",
675
- acceptAll: "Aceitar todos",
676
- declineAll: "Recusar",
677
- preferences: "Prefer\xEAncias",
678
- policyLink: "Saiba mais",
679
- modalTitle: "Prefer\xEAncias de Cookies",
680
- modalIntro: "Ajuste as categorias de cookies. Cookies necess\xE1rios s\xE3o sempre utilizados para funcionalidades b\xE1sicas.",
681
- save: "Salvar prefer\xEAncias",
682
- necessaryAlwaysOn: "Cookies necess\xE1rios (sempre ativos)",
683
- // Textos ANPD expandidos (opcionais)
684
- controllerInfo: void 0,
685
- // Exibido se definido
686
- dataTypes: void 0,
687
- // Exibido se definido
688
- thirdPartySharing: void 0,
689
- // Exibido se definido
690
- userRights: void 0,
691
- // Exibido se definido
692
- contactInfo: void 0,
693
- // Exibido se definido
694
- retentionPeriod: void 0,
695
- // Exibido se definido
696
- lawfulBasis: void 0,
697
- // Exibido se definido
698
- transferCountries: void 0
699
- // Exibido se definido
700
- };
701
- function reducer(state, action) {
702
- switch (action.type) {
703
- case "ACCEPT_ALL": {
704
- const prefs = createProjectPreferences(action.config, true);
705
- return createFullConsentState(
706
- true,
707
- prefs,
708
- "banner",
709
- action.config,
710
- false,
711
- state
712
- );
713
- }
714
- case "REJECT_ALL": {
715
- const prefs = createProjectPreferences(action.config, false);
716
- return createFullConsentState(
717
- true,
718
- prefs,
719
- "banner",
720
- action.config,
721
- false,
722
- state
723
- );
724
- }
725
- case "SET_CATEGORY":
726
- return {
727
- ...state,
728
- preferences: {
729
- ...state.preferences,
730
- [action.category]: action.value
731
- },
732
- lastUpdate: (/* @__PURE__ */ new Date()).toISOString()
733
- };
734
- case "SET_PREFERENCES":
735
- return createFullConsentState(
736
- true,
737
- action.preferences,
738
- "modal",
739
- action.config,
740
- false,
741
- state
742
- );
743
- case "OPEN_MODAL":
744
- return { ...state, isModalOpen: true };
745
- case "CLOSE_MODAL":
746
- return createFullConsentState(
747
- true,
748
- state.preferences,
749
- "modal",
750
- action.config,
751
- false,
752
- state
753
- );
754
- case "RESET": {
755
- return createFullConsentState(
756
- false,
757
- createProjectPreferences(action.config),
758
- "programmatic",
759
- action.config,
760
- false
761
- );
762
- }
763
- case "HYDRATE": {
764
- const validatedPreferences = validateProjectPreferences(
765
- action.state.preferences,
766
- action.config
767
- );
768
- return {
769
- ...action.state,
770
- preferences: validatedPreferences,
771
- isModalOpen: false
772
- };
773
- }
774
- default:
775
- return state;
776
- }
777
- }
778
- var StateCtx = React4.createContext(null);
779
- var ActionsCtx = React4.createContext(null);
780
- var TextsCtx = React4.createContext(DEFAULT_TEXTS);
781
- var HydrationCtx = React4.createContext(false);
782
- function ConsentProvider({
783
- initialState,
784
- categories,
785
- // Nova prop para configuração de categorias
786
- texts: textsProp,
787
- theme,
788
- designTokens,
789
- scriptIntegrations,
790
- // eslint-disable-line no-unused-vars
791
- PreferencesModalComponent,
792
- preferencesModalProps = {},
793
- CookieBannerComponent,
794
- cookieBannerProps = {},
795
- FloatingPreferencesButtonComponent,
796
- floatingPreferencesButtonProps = {},
797
- disableFloatingPreferencesButton = false,
798
- hideBranding = false,
799
- onConsentGiven,
800
- onPreferencesSaved,
801
- cookie: cookieOpts,
802
- disableDeveloperGuidance,
803
- children
804
- }) {
805
- const texts = React4.useMemo(
806
- () => ({ ...DEFAULT_TEXTS, ...textsProp ?? {} }),
807
- [textsProp]
808
- );
809
- const cookie = React4.useMemo(
810
- () => ({ ...DEFAULT_COOKIE_OPTS, ...cookieOpts ?? {} }),
811
- [cookieOpts]
812
- );
813
- const appliedTheme = React4.useMemo(
814
- () => theme || defaultConsentTheme,
815
- [theme]
816
- );
817
- const finalCategoriesConfig = React4.useMemo(() => {
818
- if (categories) return categories;
819
- return DEFAULT_PROJECT_CATEGORIES;
820
- }, [categories]);
821
- useDeveloperGuidance(finalCategoriesConfig, disableDeveloperGuidance);
822
- const boot = React4.useMemo(() => {
823
- if (initialState) return { ...initialState, isModalOpen: false };
824
- return createFullConsentState(
825
- false,
826
- createProjectPreferences(finalCategoriesConfig),
827
- "banner",
828
- finalCategoriesConfig,
829
- false
830
- );
831
- }, [initialState, finalCategoriesConfig]);
832
- const [state, dispatch] = React4.useReducer(reducer, boot);
833
- const [isHydrated, setIsHydrated] = React4.useState(false);
834
- React4.useEffect(() => {
835
- if (!initialState) {
836
- const saved = readConsentCookie(cookie.name);
837
- if (saved?.consented) {
838
- dispatch({
839
- type: "HYDRATE",
840
- state: saved,
841
- config: finalCategoriesConfig
842
- });
843
- }
844
- }
845
- setIsHydrated(true);
846
- }, [cookie.name, initialState, finalCategoriesConfig]);
847
- React4.useEffect(() => {
848
- if (state.consented)
849
- writeConsentCookie(state, finalCategoriesConfig, cookie);
850
- }, [state, cookie, finalCategoriesConfig]);
851
- const prevConsented = React4.useRef(state.consented);
852
- React4.useEffect(() => {
853
- if (!prevConsented.current && state.consented && onConsentGiven) {
854
- setTimeout(() => onConsentGiven(state), 150);
855
- }
856
- prevConsented.current = state.consented;
857
- }, [state, onConsentGiven]);
858
- const api = React4.useMemo(() => {
859
- const acceptAll = () => dispatch({ type: "ACCEPT_ALL", config: finalCategoriesConfig });
860
- const rejectAll = () => dispatch({ type: "REJECT_ALL", config: finalCategoriesConfig });
861
- const setPreference = (category, value) => dispatch({ type: "SET_CATEGORY", category, value });
862
- const setPreferences = (preferences) => {
863
- dispatch({
864
- type: "SET_PREFERENCES",
865
- preferences,
866
- config: finalCategoriesConfig
867
- });
868
- if (onPreferencesSaved) {
869
- setTimeout(() => onPreferencesSaved(preferences), 150);
870
- }
871
- };
872
- const openPreferences = () => dispatch({ type: "OPEN_MODAL" });
873
- const closePreferences = () => dispatch({ type: "CLOSE_MODAL", config: finalCategoriesConfig });
874
- const resetConsent = () => {
875
- removeConsentCookie(cookie);
876
- dispatch({ type: "RESET", config: finalCategoriesConfig });
877
- };
878
- return {
879
- consented: !!state.consented,
880
- preferences: state.preferences,
881
- isModalOpen: state.isModalOpen,
882
- acceptAll,
883
- rejectAll,
884
- setPreference,
885
- setPreferences,
886
- openPreferences,
887
- closePreferences,
888
- resetConsent
889
- };
890
- }, [state, cookie, finalCategoriesConfig, onPreferencesSaved]);
891
- return /* @__PURE__ */ jsx6(ThemeProvider, { theme: appliedTheme, children: /* @__PURE__ */ jsx6(StateCtx.Provider, { value: state, children: /* @__PURE__ */ jsx6(ActionsCtx.Provider, { value: api, children: /* @__PURE__ */ jsx6(TextsCtx.Provider, { value: texts, children: /* @__PURE__ */ jsx6(HydrationCtx.Provider, { value: isHydrated, children: /* @__PURE__ */ jsx6(DesignProvider, { tokens: designTokens, children: /* @__PURE__ */ jsxs3(
892
- CategoriesProvider,
893
- {
894
- config: finalCategoriesConfig,
895
- disableDeveloperGuidance,
896
- children: [
897
- children,
898
- /* @__PURE__ */ jsx6(React4.Suspense, { fallback: null, children: PreferencesModalComponent ? /* @__PURE__ */ jsx6(
899
- PreferencesModalComponent,
900
- {
901
- preferences: api.preferences,
902
- setPreferences: api.setPreferences,
903
- closePreferences: api.closePreferences,
904
- isModalOpen: api.isModalOpen,
905
- texts,
906
- ...preferencesModalProps
907
- }
908
- ) : /* @__PURE__ */ jsx6(PreferencesModal, { hideBranding }) }),
909
- !state.consented && isHydrated && (CookieBannerComponent ? /* @__PURE__ */ jsx6(
910
- CookieBannerComponent,
911
- {
912
- consented: api.consented,
913
- acceptAll: api.acceptAll,
914
- rejectAll: api.rejectAll,
915
- openPreferences: api.openPreferences,
916
- texts,
917
- ...cookieBannerProps
918
- }
919
- ) : /* @__PURE__ */ jsx6(CookieBanner, {})),
920
- state.consented && !disableFloatingPreferencesButton && (FloatingPreferencesButtonComponent ? /* @__PURE__ */ jsx6(
921
- FloatingPreferencesButtonComponent,
922
- {
923
- openPreferences: api.openPreferences,
924
- consented: api.consented,
925
- ...floatingPreferencesButtonProps
926
- }
927
- ) : /* @__PURE__ */ jsx6(FloatingPreferencesButton, {}))
928
- ]
929
- }
930
- ) }) }) }) }) }) });
931
- }
932
- function useConsentStateInternal() {
933
- const ctx = React4.useContext(StateCtx);
934
- if (!ctx)
935
- throw new Error("useConsentState must be used within ConsentProvider");
936
- return ctx;
937
- }
938
- function useConsentActionsInternal() {
939
- const ctx = React4.useContext(ActionsCtx);
940
- if (!ctx)
941
- throw new Error("useConsentActions must be used within ConsentProvider");
942
- return ctx;
943
- }
944
- function useConsentTextsInternal() {
945
- const ctx = React4.useContext(TextsCtx);
946
- return ctx;
947
- }
948
- function useConsentHydrationInternal() {
949
- return React4.useContext(HydrationCtx);
950
- }
951
-
952
- // src/hooks/useConsent.ts
953
- function useConsent() {
954
- const state = useConsentStateInternal();
955
- const actions = useConsentActionsInternal();
956
- return {
957
- consented: state.consented,
958
- preferences: state.preferences,
959
- isModalOpen: state.isModalOpen,
960
- acceptAll: actions.acceptAll,
961
- rejectAll: actions.rejectAll,
962
- setPreference: actions.setPreference,
963
- setPreferences: actions.setPreferences,
964
- openPreferences: actions.openPreferences,
965
- closePreferences: actions.closePreferences,
966
- resetConsent: actions.resetConsent
967
- };
968
- }
969
- function useConsentTexts() {
970
- return useConsentTextsInternal();
971
- }
972
- function useConsentHydration() {
973
- return useConsentHydrationInternal();
974
- }
975
-
976
- // src/components/PreferencesModal.tsx
977
- import { jsx as jsx7, jsxs as jsxs4 } from "react/jsx-runtime";
978
- function PreferencesModal2({
979
- DialogProps: DialogProps2,
980
- hideBranding = false
981
- }) {
982
- const { preferences, setPreferences, closePreferences, isModalOpen } = useConsent();
983
- const texts = useConsentTexts();
984
- const { toggleableCategories } = useCategories();
985
- const [tempPreferences, setTempPreferences] = useState2(
986
- () => {
987
- const initialPrefs = { necessary: true };
988
- toggleableCategories.forEach((category) => {
989
- initialPrefs[category.id] = preferences[category.id] ?? false;
990
- });
991
- return initialPrefs;
992
- }
993
- );
994
- useEffect4(() => {
995
- if (isModalOpen) {
996
- const syncedPrefs = { necessary: true };
997
- toggleableCategories.forEach((category) => {
998
- syncedPrefs[category.id] = preferences[category.id] ?? false;
999
- });
1000
- setTempPreferences(syncedPrefs);
1001
- }
1002
- }, [isModalOpen, preferences, toggleableCategories]);
1003
- const open = DialogProps2?.open ?? isModalOpen ?? false;
1004
- const handleSave = () => {
1005
- setPreferences(tempPreferences);
1006
- };
1007
- const handleCancel = () => {
1008
- setTempPreferences(preferences);
1009
- closePreferences();
1010
- };
1011
- return /* @__PURE__ */ jsxs4(
1012
- Dialog,
1013
- {
1014
- "aria-labelledby": "cookie-pref-title",
1015
- open,
1016
- onClose: handleCancel,
1017
- ...DialogProps2,
1018
- children: [
1019
- /* @__PURE__ */ jsx7(DialogTitle, { id: "cookie-pref-title", children: texts.modalTitle }),
1020
- /* @__PURE__ */ jsxs4(DialogContent, { dividers: true, children: [
1021
- /* @__PURE__ */ jsx7(Typography3, { variant: "body2", sx: { mb: 2 }, children: texts.modalIntro }),
1022
- /* @__PURE__ */ jsxs4(FormGroup, { children: [
1023
- toggleableCategories.map((category) => /* @__PURE__ */ jsx7(
1024
- FormControlLabel,
1025
- {
1026
- control: /* @__PURE__ */ jsx7(
1027
- Switch,
1028
- {
1029
- checked: tempPreferences[category.id] ?? false,
1030
- onChange: (e) => setTempPreferences((prev) => ({
1031
- ...prev,
1032
- [category.id]: e.target.checked
1033
- }))
1034
- }
1035
- ),
1036
- label: `${category.name} - ${category.description}`
1037
- },
1038
- category.id
1039
- )),
1040
- /* @__PURE__ */ jsx7(
1041
- FormControlLabel,
1042
- {
1043
- control: /* @__PURE__ */ jsx7(Switch, { checked: true, disabled: true }),
1044
- label: texts.necessaryAlwaysOn
1045
- }
1046
- )
1047
- ] })
1048
- ] }),
1049
- /* @__PURE__ */ jsxs4(DialogActions, { children: [
1050
- /* @__PURE__ */ jsx7(Button2, { variant: "outlined", onClick: handleCancel, children: "Cancelar" }),
1051
- /* @__PURE__ */ jsx7(Button2, { variant: "contained", onClick: handleSave, children: texts.save })
1052
- ] }),
1053
- !hideBranding && /* @__PURE__ */ jsx7(Branding, { variant: "modal" })
1054
- ]
1055
- }
1056
- );
1057
- }
1058
-
1059
- export {
1060
- DEFAULT_PROJECT_CATEGORIES,
1061
- analyzeDeveloperConfiguration,
1062
- useCategories,
1063
- useCategoryStatus,
1064
- defaultConsentTheme,
1065
- ConsentProvider,
1066
- useConsent,
1067
- useConsentTexts,
1068
- useConsentHydration,
1069
- PreferencesModal2 as PreferencesModal
1070
- };