@vllnt/analytics 0.2.0-canary.13db137 → 0.2.0-canary.33c37cf

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/src/react.tsx ADDED
@@ -0,0 +1,239 @@
1
+ "use client";
2
+
3
+ import {
4
+ createContext,
5
+ type ReactNode,
6
+ useCallback,
7
+ useContext,
8
+ useEffect,
9
+ useMemo,
10
+ useState,
11
+ } from "react";
12
+
13
+ import {
14
+ disableAnalytics,
15
+ enableAnalytics,
16
+ initAnalytics,
17
+ setMaxQueuedEvents,
18
+ } from "./analytics";
19
+ import {
20
+ clearConsent,
21
+ CONSENT_VERSION,
22
+ createAcceptAllConsent,
23
+ createDeclineAnalyticsConsent,
24
+ loadConsent,
25
+ needsRePrompt,
26
+ saveConsent,
27
+ updateConsentCategory,
28
+ } from "./consent";
29
+ import type {
30
+ AnalyticsConfig,
31
+ ConsentCategory,
32
+ ConsentState,
33
+ UseConsentOptions,
34
+ UseConsentReturn,
35
+ } from "./types";
36
+
37
+ // Context for analytics configuration
38
+ type AnalyticsContextValue = {
39
+ acceptAll: () => void;
40
+ config: AnalyticsConfig;
41
+ consent: ConsentState | null;
42
+ declineAnalytics: () => void;
43
+ hasResponded: boolean;
44
+ isLoading: boolean;
45
+ resetConsent: () => void;
46
+ updateConsent: (category: ConsentCategory, value: boolean) => void;
47
+ };
48
+
49
+ const AnalyticsContext = createContext<AnalyticsContextValue | null>(null);
50
+
51
+ /**
52
+ * Analytics provider component
53
+ */
54
+ export function AnalyticsProvider({
55
+ children,
56
+ config,
57
+ consentVersion = CONSENT_VERSION,
58
+ }: {
59
+ children: ReactNode;
60
+ config: AnalyticsConfig;
61
+ consentVersion?: number;
62
+ }) {
63
+ const [consent, setConsent] = useState<ConsentState | null>(() => {
64
+ // Runs once, during the first render: the limit is set before any child
65
+ // effect can queue an event and before the consent decision.
66
+ setMaxQueuedEvents(config.maxQueuedEvents);
67
+ const stored = loadConsent();
68
+ if (!stored) return null;
69
+ if (needsRePrompt(stored, consentVersion)) {
70
+ clearConsent();
71
+ return null;
72
+ }
73
+ return stored;
74
+ });
75
+
76
+ const [hasResponded, setHasResponded] = useState(() => consent !== null);
77
+
78
+ // Start analytics when consent allows it; block it (and drop queued
79
+ // events) when the stored choice is a decline.
80
+ useEffect(() => {
81
+ if (!consent) return;
82
+ if (consent.analytics) {
83
+ initAnalytics(config);
84
+ } else {
85
+ disableAnalytics();
86
+ }
87
+ }, [consent, config]);
88
+
89
+ const acceptAll = useCallback(() => {
90
+ const newConsent = { ...createAcceptAllConsent(), version: consentVersion };
91
+ saveConsent(newConsent);
92
+ setConsent(newConsent);
93
+ setHasResponded(true);
94
+ enableAnalytics(config);
95
+ }, [config, consentVersion]);
96
+
97
+ const declineAnalytics = useCallback(() => {
98
+ const newConsent = {
99
+ ...createDeclineAnalyticsConsent(),
100
+ version: consentVersion,
101
+ };
102
+ saveConsent(newConsent);
103
+ setConsent(newConsent);
104
+ setHasResponded(true);
105
+ disableAnalytics();
106
+ }, [consentVersion]);
107
+
108
+ const updateConsentHandler = useCallback(
109
+ (category: ConsentCategory, value: boolean) => {
110
+ if (!consent) return;
111
+
112
+ const newConsent = updateConsentCategory(consent, category, value);
113
+ saveConsent(newConsent);
114
+ setConsent(newConsent);
115
+
116
+ // Update analytics state
117
+ if (category === "analytics") {
118
+ if (value) {
119
+ enableAnalytics(config);
120
+ } else {
121
+ disableAnalytics();
122
+ }
123
+ }
124
+ },
125
+ [consent, config],
126
+ );
127
+
128
+ const resetConsentHandler = useCallback(() => {
129
+ clearConsent();
130
+ setConsent(null);
131
+ setHasResponded(false);
132
+ disableAnalytics();
133
+ }, []);
134
+
135
+ const value = useMemo<AnalyticsContextValue>(
136
+ () => ({
137
+ acceptAll,
138
+ config,
139
+ consent,
140
+ declineAnalytics,
141
+ hasResponded,
142
+ isLoading: false,
143
+ resetConsent: resetConsentHandler,
144
+ updateConsent: updateConsentHandler,
145
+ }),
146
+ [
147
+ config,
148
+ consent,
149
+ hasResponded,
150
+ acceptAll,
151
+ declineAnalytics,
152
+ updateConsentHandler,
153
+ resetConsentHandler,
154
+ ],
155
+ );
156
+
157
+ return (
158
+ <AnalyticsContext.Provider value={value}>
159
+ {children}
160
+ </AnalyticsContext.Provider>
161
+ );
162
+ }
163
+
164
+ /**
165
+ * Hook to access analytics context
166
+ */
167
+ export function useAnalytics() {
168
+ const context = useContext(AnalyticsContext);
169
+ if (!context) {
170
+ throw new Error("useAnalytics must be used within an AnalyticsProvider");
171
+ }
172
+ return context;
173
+ }
174
+
175
+ /**
176
+ * Hook to manage consent state
177
+ */
178
+ export function useConsent(options: UseConsentOptions = {}): UseConsentReturn {
179
+ const { consentVersion = CONSENT_VERSION } = options;
180
+
181
+ const [consent, setConsent] = useState<ConsentState | null>(() => {
182
+ const stored = loadConsent();
183
+ if (!stored) return null;
184
+ if (needsRePrompt(stored, consentVersion)) {
185
+ clearConsent();
186
+ return null;
187
+ }
188
+ return stored;
189
+ });
190
+
191
+ const [hasResponded, setHasResponded] = useState(() => consent !== null);
192
+
193
+ const acceptAll = useCallback(() => {
194
+ const newConsent = { ...createAcceptAllConsent(), version: consentVersion };
195
+ saveConsent(newConsent);
196
+ setConsent(newConsent);
197
+ setHasResponded(true);
198
+ }, [consentVersion]);
199
+
200
+ const declineAnalytics = useCallback(() => {
201
+ const newConsent = {
202
+ ...createDeclineAnalyticsConsent(),
203
+ version: consentVersion,
204
+ };
205
+ saveConsent(newConsent);
206
+ setConsent(newConsent);
207
+ setHasResponded(true);
208
+ }, [consentVersion]);
209
+
210
+ const updateConsentHandler = useCallback(
211
+ (category: ConsentCategory, value: boolean) => {
212
+ if (!consent) return;
213
+
214
+ const newConsent = updateConsentCategory(consent, category, value);
215
+ saveConsent(newConsent);
216
+ setConsent(newConsent);
217
+ },
218
+ [consent],
219
+ );
220
+
221
+ const resetConsentHandler = useCallback(() => {
222
+ clearConsent();
223
+ setConsent(null);
224
+ setHasResponded(false);
225
+ }, []);
226
+
227
+ return {
228
+ acceptAll,
229
+ consent,
230
+ declineAnalytics,
231
+ hasResponded,
232
+ isLoading: false,
233
+ resetConsent: resetConsentHandler,
234
+ updateConsent: updateConsentHandler,
235
+ };
236
+ }
237
+
238
+ // Re-export core analytics functions for convenience
239
+ export { initAnalytics } from "./analytics";
package/src/types.ts ADDED
@@ -0,0 +1,110 @@
1
+ /**
2
+ * Analytics consent state stored in localStorage
3
+ */
4
+ export type ConsentState = {
5
+ /** Whether analytics tracking is allowed */
6
+ analytics: boolean;
7
+ /** Whether functional cookies are allowed (always true for site operation) */
8
+ functional: boolean;
9
+ /** ISO timestamp when consent was given */
10
+ timestamp: string;
11
+ /** Version of consent prompt (bump to re-prompt users) */
12
+ version: number;
13
+ };
14
+
15
+ /**
16
+ * Consent categories that can be toggled
17
+ */
18
+ export type ConsentCategory = "analytics" | "functional";
19
+
20
+ /**
21
+ * Tutorial-specific event names
22
+ */
23
+ export type TutorialEventName =
24
+ | "tutorial_complete"
25
+ | "tutorial_navigation"
26
+ | "tutorial_section_complete"
27
+ | "tutorial_section_view"
28
+ | "tutorial_start"
29
+ | "tutorial_time_spent";
30
+
31
+ /**
32
+ * Tutorial event properties
33
+ */
34
+ export type TutorialEventProperties = {
35
+ /** Completion percentage (0-100) */
36
+ completion_percent?: number;
37
+ /** User's locale */
38
+ locale: string;
39
+ /** Navigation method used */
40
+ navigation_type?: "keyboard" | "next" | "prev" | "toc";
41
+ /** Section identifier */
42
+ section_id?: string;
43
+ /** Section position (0-indexed) */
44
+ section_index?: number;
45
+ /** Time spent in seconds */
46
+ time_spent_seconds?: number;
47
+ /** Total number of sections */
48
+ total_sections?: number;
49
+ /** Unique tutorial identifier (contentId) */
50
+ tutorial_id: string;
51
+ /** Human-readable tutorial title */
52
+ tutorial_title: string;
53
+ };
54
+
55
+ /**
56
+ * Generic analytics event
57
+ */
58
+ export type AnalyticsEvent = {
59
+ name: string;
60
+ properties?: Record<string, unknown>;
61
+ timestamp?: string;
62
+ };
63
+
64
+ /**
65
+ * Analytics instance configuration
66
+ */
67
+ export type AnalyticsConfig = {
68
+ /** Application name for analytics */
69
+ app: string;
70
+ /** Enable debug mode */
71
+ debug?: boolean;
72
+ /**
73
+ * How many `track` and `trackPage` calls are queued before `initAnalytics`
74
+ * runs; later calls are dropped. `0` queues nothing. Defaults to
75
+ * `DEFAULT_MAX_QUEUED_EVENTS` (100); any value that is not a non-negative
76
+ * safe integer means the default. `AnalyticsProvider` applies it on mount;
77
+ * without the provider, the default applies until `initAnalytics` runs.
78
+ */
79
+ maxQueuedEvents?: number;
80
+ /** Application version */
81
+ version?: number;
82
+ };
83
+
84
+ /**
85
+ * Hook options for useConsent
86
+ */
87
+ export type UseConsentOptions = {
88
+ /** Current consent version (bump to re-prompt) */
89
+ consentVersion?: number;
90
+ };
91
+
92
+ /**
93
+ * Return type for useConsent hook
94
+ */
95
+ export type UseConsentReturn = {
96
+ /** Accept all tracking */
97
+ acceptAll: () => void;
98
+ /** Current consent state (null if not yet determined) */
99
+ consent: ConsentState | null;
100
+ /** Decline analytics tracking (functional always on) */
101
+ declineAnalytics: () => void;
102
+ /** Whether consent has been given (any response) */
103
+ hasResponded: boolean;
104
+ /** Whether currently loading from storage */
105
+ isLoading: boolean;
106
+ /** Reset consent (will re-show banner) */
107
+ resetConsent: () => void;
108
+ /** Update specific consent category */
109
+ updateConsent: (category: ConsentCategory, value: boolean) => void;
110
+ };