@ht-sdks/consent-manager 0.0.1

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.
Files changed (110) hide show
  1. package/LICENSE +45 -0
  2. package/README.md +851 -0
  3. package/commonjs/__tests__/consent-manager-builder/analytics.test.js +250 -0
  4. package/commonjs/__tests__/consent-manager-builder/fetch-destinations.test.js +155 -0
  5. package/commonjs/__tests__/consent-manager-builder/index.todo.js +327 -0
  6. package/commonjs/__tests__/consent-manager-builder/preferences.test.js +129 -0
  7. package/commonjs/__tests__/index.test.js +57 -0
  8. package/commonjs/consent-manager/banner.js +89 -0
  9. package/commonjs/consent-manager/buttons.js +18 -0
  10. package/commonjs/consent-manager/cancel-dialog.js +76 -0
  11. package/commonjs/consent-manager/categories.js +29 -0
  12. package/commonjs/consent-manager/container.js +169 -0
  13. package/commonjs/consent-manager/dialog.js +129 -0
  14. package/commonjs/consent-manager/font-styles.js +10 -0
  15. package/commonjs/consent-manager/index.js +244 -0
  16. package/commonjs/consent-manager/preference-dialog.js +178 -0
  17. package/commonjs/consent-manager-builder/analytics.js +76 -0
  18. package/commonjs/consent-manager-builder/fetch-destinations.js +104 -0
  19. package/commonjs/consent-manager-builder/index.js +330 -0
  20. package/commonjs/consent-manager-builder/preferences.js +82 -0
  21. package/commonjs/index.js +39 -0
  22. package/commonjs/standalone.js +86 -0
  23. package/commonjs/types.js +3 -0
  24. package/esm/__tests__/consent-manager-builder/analytics.test.js +245 -0
  25. package/esm/__tests__/consent-manager-builder/fetch-destinations.test.js +150 -0
  26. package/esm/__tests__/consent-manager-builder/index.todo.js +322 -0
  27. package/esm/__tests__/consent-manager-builder/preferences.test.js +124 -0
  28. package/esm/__tests__/index.test.js +55 -0
  29. package/esm/consent-manager/banner.js +65 -0
  30. package/esm/consent-manager/buttons.js +12 -0
  31. package/esm/consent-manager/cancel-dialog.js +52 -0
  32. package/esm/consent-manager/categories.js +26 -0
  33. package/esm/consent-manager/container.js +162 -0
  34. package/esm/consent-manager/dialog.js +105 -0
  35. package/esm/consent-manager/font-styles.js +8 -0
  36. package/esm/consent-manager/index.js +220 -0
  37. package/esm/consent-manager/preference-dialog.js +154 -0
  38. package/esm/consent-manager-builder/analytics.js +73 -0
  39. package/esm/consent-manager-builder/fetch-destinations.js +98 -0
  40. package/esm/consent-manager-builder/index.js +325 -0
  41. package/esm/consent-manager-builder/preferences.js +73 -0
  42. package/esm/index.js +28 -0
  43. package/esm/standalone.js +58 -0
  44. package/esm/types.js +1 -0
  45. package/package.json +168 -0
  46. package/src/__tests__/consent-manager-builder/analytics.test.ts +279 -0
  47. package/src/__tests__/consent-manager-builder/fetch-destinations.test.ts +89 -0
  48. package/src/__tests__/consent-manager-builder/index.todo.js +386 -0
  49. package/src/__tests__/consent-manager-builder/preferences.test.ts +156 -0
  50. package/src/__tests__/index.test.ts +68 -0
  51. package/src/consent-manager/banner.tsx +227 -0
  52. package/src/consent-manager/buttons.tsx +78 -0
  53. package/src/consent-manager/cancel-dialog.tsx +68 -0
  54. package/src/consent-manager/categories.ts +27 -0
  55. package/src/consent-manager/container.tsx +282 -0
  56. package/src/consent-manager/dialog.tsx +236 -0
  57. package/src/consent-manager/font-styles.tsx +14 -0
  58. package/src/consent-manager/index.tsx +327 -0
  59. package/src/consent-manager/preference-dialog.tsx +371 -0
  60. package/src/consent-manager-builder/analytics.ts +104 -0
  61. package/src/consent-manager-builder/fetch-destinations.ts +50 -0
  62. package/src/consent-manager-builder/index.tsx +426 -0
  63. package/src/consent-manager-builder/preferences.ts +100 -0
  64. package/src/index.ts +42 -0
  65. package/src/standalone.tsx +57 -0
  66. package/src/styled.d.ts +7 -0
  67. package/src/types.ts +151 -0
  68. package/standalone/consent-manager.js +23 -0
  69. package/standalone/consent-manager.js.map +1 -0
  70. package/types/__tests__/consent-manager-builder/analytics.test.d.ts +1 -0
  71. package/types/__tests__/consent-manager-builder/fetch-destinations.test.d.ts +1 -0
  72. package/types/__tests__/consent-manager-builder/index.todo.d.ts +1 -0
  73. package/types/__tests__/consent-manager-builder/preferences.test.d.ts +1 -0
  74. package/types/__tests__/index.test.d.ts +1 -0
  75. package/types/consent-manager/banner.d.ts +21 -0
  76. package/types/consent-manager/buttons.d.ts +13 -0
  77. package/types/consent-manager/cancel-dialog.d.ts +19 -0
  78. package/types/consent-manager/categories.d.ts +3 -0
  79. package/types/consent-manager/container.d.ts +35 -0
  80. package/types/consent-manager/dialog.d.ts +29 -0
  81. package/types/consent-manager/font-styles.d.ts +2 -0
  82. package/types/consent-manager/index.d.ts +35 -0
  83. package/types/consent-manager/preference-dialog.d.ts +32 -0
  84. package/types/consent-manager-builder/analytics.d.ts +14 -0
  85. package/types/consent-manager-builder/fetch-destinations.d.ts +2 -0
  86. package/types/consent-manager-builder/index.d.ts +126 -0
  87. package/types/consent-manager-builder/preferences.d.ts +26 -0
  88. package/types/index.d.ts +7 -0
  89. package/types/src/__tests__/consent-manager-builder/analytics.test.d.ts +1 -0
  90. package/types/src/__tests__/consent-manager-builder/fetch-destinations.test.d.ts +1 -0
  91. package/types/src/__tests__/consent-manager-builder/preferences.test.d.ts +1 -0
  92. package/types/src/__tests__/index.test.d.ts +1 -0
  93. package/types/src/consent-manager/banner.d.ts +21 -0
  94. package/types/src/consent-manager/buttons.d.ts +13 -0
  95. package/types/src/consent-manager/cancel-dialog.d.ts +19 -0
  96. package/types/src/consent-manager/categories.d.ts +3 -0
  97. package/types/src/consent-manager/container.d.ts +35 -0
  98. package/types/src/consent-manager/dialog.d.ts +29 -0
  99. package/types/src/consent-manager/font-styles.d.ts +2 -0
  100. package/types/src/consent-manager/index.d.ts +35 -0
  101. package/types/src/consent-manager/preference-dialog.d.ts +32 -0
  102. package/types/src/consent-manager-builder/analytics.d.ts +14 -0
  103. package/types/src/consent-manager-builder/fetch-destinations.d.ts +2 -0
  104. package/types/src/consent-manager-builder/index.d.ts +126 -0
  105. package/types/src/consent-manager-builder/preferences.d.ts +26 -0
  106. package/types/src/index.d.ts +7 -0
  107. package/types/src/standalone.d.ts +5 -0
  108. package/types/src/types.d.ts +131 -0
  109. package/types/standalone.d.ts +5 -0
  110. package/types/types.d.ts +131 -0
package/README.md ADDED
@@ -0,0 +1,851 @@
1
+ # Hightouch Consent Manager ![CI](https://github.com/ht-sdks/consent-manager/actions/workflows/ci.yml/badge.svg)
2
+
3
+ Drop-in consent management plugin for `@ht-sdks/events-sdk-js-browser`
4
+
5
+ > [!NOTE]
6
+ > You must install `@ht-sdks/events-sdk-js-browser` via [**snippet**](https://github.com/ht-sdks/events-sdk-js-mono/tree/master/packages/browser#installation-via-cdn) in order for Consent Manager to work. It will not work if you use an NPM import.
7
+
8
+ At its core, the Consent Manager empowers your visitors to control and customize their tracking preferences on a website. They can opt out entirely of being tracked, or selectively opt out of tools in which they don’t want their information stored.
9
+
10
+ _Hightouch works to ensure Consent Manager works with most of our product pipeline. We cannot ensure it works in your specific implementation or website. Please contact our team for implementation support._
11
+
12
+ ### Features
13
+
14
+ - Give users the ability to opt-in or opt-out to tracking.
15
+ - Fine grained control of tools or categories used for tracking.
16
+ - 30s setup with a drop in script tag.
17
+ - Or fully customizable UI/UX through React components.
18
+ - EU traffic detection through [@segment/in-eu][ineu].
19
+ - Ability for visitors to reconsent and change preferences.
20
+ - Automatically updates to reflect the destinations you have enabled in Hightouch.
21
+ - Consent Manager will add consent metadata to the context of all track calls:
22
+
23
+ ### How it works
24
+
25
+ 1. The consent manager delays loading the events SDK until user consent is given, and will not load the SDK at all if the user opts out of everything. The user's tracking preferences are saved to a cookie and sent as an `identify` trait and a `Consent Updated` track event (if they haven't opted out of everything), ensuring consent data is propagated to your destinations.
26
+
27
+ 2. **All** events will include the latest consent metadata inside the `context.consent` object:
28
+
29
+ ```json
30
+ {
31
+ "event": "Created Account",
32
+ "context": {
33
+ "consent": {
34
+ "defaultDestinationBehavior": "disable",
35
+ "destinationPreferences": {},
36
+ "categoryPreferences": {
37
+ "marketingAndAnalytics": false,
38
+ "advertising": true,
39
+ "functional": false
40
+ }
41
+ }
42
+ }
43
+ }
44
+ ```
45
+
46
+ 3. Whenever a user updates their consent preferences, the following events will be emitted
47
+ - `identify` with updated preferences in `traits`
48
+ ```json
49
+ {
50
+ "type": "identify",
51
+ "traits": {
52
+ "destinationTrackingPreferences": {},
53
+ "categoryTrackingPreferences": {
54
+ "marketingAndAnalytics": true,
55
+ "advertising": true,
56
+ "functional": true
57
+ }
58
+ }
59
+ }
60
+ ```
61
+ - `track` named `Consent Updated` with updated preferences
62
+ ```json
63
+ {
64
+ "type": "track",
65
+ "event": "Consent Updated",
66
+ "properties": {
67
+ "destinationTrackingPreferences": {},
68
+ "categoryTrackingPreferences": {
69
+ "marketingAndAnalytics": true,
70
+ "advertising": true,
71
+ "functional": true
72
+ }
73
+ }
74
+ }
75
+ ```
76
+
77
+ ## Install
78
+
79
+ The Hightouch Consent Manager can be used in several ways, depending on how custom you want your visitor's experience to be.
80
+
81
+ > [!IMPORTANT]
82
+ > Ensure you're using the latest version of the [Hightouch Events Browser SDK snippet](https://github.com/ht-sdks/events-sdk-js-mono/tree/master/packages/browser#installation-via-cdn) and **remove** the `e.load("WRITE_KEY")` call from the snippet so consent manager can manage the loading process.
83
+
84
+ ### Standalone Script
85
+
86
+ The standalone script is a prebuilt bundle that uses the [ConsentManager][] React component with [Preact][] (a lightweight React alternative). It's best if you want to get up and running quickly or you don't have a preexisting React setup.
87
+
88
+ Include the consent manager script tag after the Browser SDK snippet and add your own custom copy. The standalone script is configured via a global callback function.
89
+
90
+ ```html
91
+ <!-- Consent Manager element -->
92
+ <div id="consent-manager"></div>
93
+
94
+ <!-- Browser SDK snippet -->
95
+ <script type="text/javascript">
96
+ !function(){var e=window.htevents=window.htevents||[];if(!e.initialize)if(e.invoked)window.console&&console.error&&console.error("Hightouch snippet included twice.");else{e.invoked=!0,e.methods=["trackSubmit","trackClick","trackLink","trackForm","pageview","identify","reset","group","track","ready","alias","debug","page","once","off","on","addSourceMiddleware","addIntegrationMiddleware","setAnonymousId","addDestinationMiddleware"],e.factory=function(t){return function(){var n=Array.prototype.slice.call(arguments);return n.unshift(t),e.push(n),e}};for(var t=0;t<e.methods.length;t++){var n=e.methods[t];e[n]=e.factory(n)}e.load=function(t,n){var o=document.createElement("script");o.type="text/javascript",o.async=!0,o.src="https://cdn.hightouch-events.com/browser/release/v1-latest/events.min.js";var r=document.getElementsByTagName("script")[0];r.parentNode.insertBefore(o,r),e._loadOptions=n,e._writeKey=t},e.SNIPPET_VERSION="0.0.1",
97
+ e.page()}}();
98
+ </script>
99
+
100
+ <!-- Consent Manager configuration -->
101
+ <script>
102
+ window.consentManagerConfig = function(exports) {
103
+ return {
104
+ container: '#consent-manager',
105
+ writeKey: 'WRITE_KEY',
106
+ shouldRequireConsent: exports.inEU // optional: require consent only for EU users
107
+ }
108
+ }
109
+ </script>
110
+
111
+ <!-- Consent Manager JS -->
112
+ <script
113
+ src="https://unpkg.com/@ht-sdks/consent-manager@0.0.1/standalone/consent-manager.js"
114
+ defer
115
+ ></script>
116
+ ```
117
+
118
+ #### Options
119
+
120
+ All of the [ConsentManager][] options are supported with the addition of these options:
121
+
122
+ ##### container
123
+
124
+ **Type**: `string`
125
+
126
+ [CSS selector][] to the DOM element that will host the consent banner. It should be an empty DOM element (usually a `<div>`) because the consent manager will replace any existing DOM elements inside it. The element must also exist on the page before the script is executed.
127
+
128
+ You can also control the positioning of the consent banner by applying styles to the container element (optional). E.g:
129
+
130
+ ```css
131
+ #target-container {
132
+ position: fixed;
133
+ left: 0;
134
+ right: 0;
135
+ bottom: 0;
136
+ z-index: 100;
137
+ }
138
+ ```
139
+
140
+ ```html
141
+ <div id="target-container"></div>
142
+ ```
143
+
144
+ #### Globals
145
+
146
+ The following global variables are also exposed:
147
+
148
+ - `consentManager.version` - Version of the consent manager.
149
+ - `consentManager.openConsentManager()` - Opens the consent manager preferences dialog.
150
+ - `consentManager.doNotTrack()` - Utility function that returns the user's Do Not Track preference (normalises the cross browser API differences). Returns `true`, `false` or `null` (no preference specified).
151
+ - `consentManager.inEU()` - The [@segment/in-eu][ineu] `inEU()` function.
152
+ - `consentManager.preferences` - Returns an instance of `PreferencesManager` with the following helper functions:
153
+ - `loadPreferences` - returns the cookie value for consent preferences
154
+ - `savePreferences` - allows for managing the consent cookie programatically (useful if you want to re-hydrate consent from your own database or prefill consent options)
155
+ - `onPreferencesSaved(callback)` - allows for subscribing to changes in preferences.
156
+
157
+ #### Callback Function
158
+
159
+ All the options are supported. The callback function also receives these exports:
160
+
161
+ - `React` - Reference to the [Preact][] library (the API is React compatible). Useful for if you need to use virtual DOM in your content.
162
+ - `version` - Version of the consent manager.
163
+ - `openConsentManager()` - Opens the consent manager preferences dialog.
164
+ - `doNotTrack()` - Utility function that returns the user's Do Not Track preference (normalises the cross browser API differences). Returns `true`, `false` or `null` (no preference specified).
165
+ - `inEU()` - The [@segment/in-eu][ineu] `inEU()` function.
166
+ - `consentManager.preferences` - Returns an instance of `PreferencesManager` with the following helper functions:
167
+ - `loadPreferences` - returns the cookie value for consent preferences
168
+ - `savePreferences` - allows for managing the consent cookie programatically (useful if you want to re-hydrate consent from your own database or prefill consent options)
169
+ - `onPreferencesSaved(callback)` - allows for subscribing to changes in preferences.
170
+
171
+ ```html
172
+ <script>
173
+ window.consentManagerConfig = function(exports) {
174
+ var React = exports.React
175
+
176
+ // optional: customize the banner for your brand
177
+ var bannerContent = React.createElement(
178
+ 'span',
179
+ null,
180
+ 'We use cookies (and other similar technologies) to collect data to improve your experience on our site. By using our website, you՚re agreeing to the collection of data as described in our',
181
+ ' ',
182
+ React.createElement(
183
+ 'a',
184
+ { href: '/docs/legal/website-data-collection-policy/', target: '_blank' },
185
+ 'Website Data Collection Policy'
186
+ ),
187
+ '.'
188
+ )
189
+
190
+ return {
191
+ container: '#target-container',
192
+ writeKey: 'WRITE_KEY',
193
+ bannerContent: bannerContent
194
+ }
195
+ }
196
+ </script>
197
+
198
+ <script
199
+ src="https://unpkg.com/@ht-sdks/consent-manager@0.0.1/standalone/consent-manager.js"
200
+ defer
201
+ ></script>
202
+ ```
203
+
204
+ ### ConsentManager
205
+
206
+ The `ConsentManager` React component is a prebuilt consent manager UI that uses the `ConsentManagerBuilder` component under the hood. To use it, just mount the component where you want the consent banner to appear and pass in your own custom copy.
207
+
208
+ _Note: Consent Manager is React-based so is not currently compatible with other frameworks such as Vue.js or Angular. In case you want to use it in another framework that is not React, you should use the Standalone implementation._
209
+
210
+ #### Install
211
+
212
+ Using npm:
213
+
214
+ ```
215
+ npm install @ht-sdks/consent-manager
216
+ ```
217
+
218
+ Using yarn:
219
+
220
+ ```
221
+ yarn add @ht-sdks/consent-manager
222
+ ```
223
+
224
+ #### Example
225
+
226
+ ```jsx
227
+ import React from 'react'
228
+ import { ConsentManager, openConsentManager } from '@ht-sdks/consent-manager'
229
+ import inEU from '@segment/in-eu'
230
+
231
+ export default function() {
232
+ return (
233
+ <div>
234
+ <ConsentManager
235
+ writeKey="WRITE_KEY"
236
+ shouldRequireConsent={inEU} // optional: require consent only from EU users
237
+ />
238
+
239
+ <button type="button" onClick={openConsentManager}>
240
+ Website Data Collection Preferences
241
+ </button>
242
+ </div>
243
+ )
244
+ }
245
+ ```
246
+
247
+ #### Example in Next.js
248
+
249
+ In Next.js we do not have an HTML file to inject the Browser SDK snippet. Here we will use the Script component to inject the snippet provided by Hightouch. Again, note that the `e.load(WRITE_KEY)` call was removed from the snippet since `ConsentManager` will invoke that for us.
250
+
251
+ ```jsx
252
+ import React from 'react'
253
+ import Script from 'next/script'
254
+ import { ConsentManager, openConsentManager } from '@ht-sdks/consent-manager'
255
+
256
+ export default function Home() {
257
+ return (
258
+ <div>
259
+ <Script
260
+ id="events-sdk-js-browser"
261
+ dangerouslySetInnerHTML={{
262
+ __html: `
263
+ !function(){var e=window.htevents=window.htevents||[];if(!e.initialize)if(e.invoked)window.console&&console.error&&console.error("Hightouch snippet included twice.");else{e.invoked=!0,e.methods=["trackSubmit","trackClick","trackLink","trackForm","pageview","identify","reset","group","track","ready","alias","debug","page","once","off","on","addSourceMiddleware","addIntegrationMiddleware","setAnonymousId","addDestinationMiddleware"],e.factory=function(t){return function(){var n=Array.prototype.slice.call(arguments);return n.unshift(t),e.push(n),e}};for(var t=0;t<e.methods.length;t++){var n=e.methods[t];e[n]=e.factory(n)}e.load=function(t,n){var o=document.createElement("script");o.type="text/javascript",o.async=!0,o.src="https://cdn.hightouch-events.com/browser/release/v1-latest/events.min.js";var r=document.getElementsByTagName("script")[0];r.parentNode.insertBefore(o,r),e._loadOptions=n,e._writeKey=t},e.SNIPPET_VERSION="0.0.1",
264
+ e.page()}}();
265
+ `
266
+ }}
267
+ />
268
+
269
+ <main>
270
+ <ConsentManager writeKey="WRITE_KEY" />
271
+
272
+ <button type="button" onClick={openConsentManager}>
273
+ Website Data Collection Preferences
274
+ </button>
275
+ </main>
276
+ </div>
277
+ )
278
+ }
279
+ ```
280
+
281
+ #### ConsentManager Props
282
+
283
+ This section lists the configurable props you can change when
284
+ loading the out of the box Consent Manager. In [this demo](https://codepen.io/samuelkahr/pen/eYYrobB), these are all the props you can pass into the returned preferences object.
285
+
286
+ <!-- TOC depthFrom:5 depthTo:5 withLinks:1 updateOnSave:1 orderedList:0 -->
287
+
288
+ - [writeKey](#writekey)
289
+ - [shouldRequireConsent](#shouldrequireconsent)
290
+ - [initialPreferences](#initialpreferences)
291
+ - [closeBehavior](#closebehavior)
292
+ - [implyConsentOnInteraction](#implyconsentoninteraction)
293
+ - [defaultDestinationBehavior](#defaultdestinationbehavior)
294
+ - [cookieDomain](#cookiedomain)
295
+ - [bannerContent](#bannercontent)
296
+ - [bannerSubContent](#bannersubcontent)
297
+ - [bannerTextColor](#bannertextcolor)
298
+ - [bannerBackgroundColor](#bannerbackgroundcolor)
299
+ - [bannerActionsBlock](#banneractionsblock)
300
+ - [bannerHideCloseButton](#bannerhideclosebutton)
301
+ - [bannerAsModal](#bannerasmodal)
302
+ - [preferencesDialogTitle](#preferencesdialogtitle)
303
+ - [preferencesDialogContent](#preferencesdialogcontent)
304
+ - [cancelDialogTitle](#canceldialogtitle)
305
+ - [cancelDialogContent](#canceldialogcontent)
306
+ - [customCategories](#customcategories)
307
+ - [preferencesDialogTemplate](#preferencesdialogtemplate)
308
+
309
+ <!-- /TOC -->
310
+
311
+ ##### writeKey
312
+
313
+ **Type**: `string`
314
+ **Default**: none
315
+
316
+ The write key events.js should be loaded with.
317
+
318
+ ##### shouldRequireConsent
319
+
320
+ **Type**: `function`
321
+ **Default**: `() => true`
322
+
323
+ Callback function that determines if consent is required before tracking begins. Set to `true` to show the consent banner, otherwise return `false` to not show consent banner and start tracking immediately.
324
+
325
+ The function can return a `Promise` that resolves to a boolean.
326
+
327
+ ##### initialPreferences
328
+
329
+ **Type**: object
330
+ **Default**: {}
331
+
332
+ Object that opts into users into tracking for the different tracking categories. For example `{‘Functional’:true}`
333
+
334
+ ##### closeBehavior
335
+
336
+ **Type**: `string` or `function`
337
+ **Default**: `dismiss`
338
+
339
+ This option sets the default behavior for the x (close) button on the Consent Manager banner. Available options:
340
+
341
+ - “dismiss” - dismisses the banner, but doesn't save or change any preferences. Events Browser SDK won’t load until consent is given.
342
+ - “accept”- assume consent across every category.
343
+ - ”deny” - denies consent across every category.
344
+
345
+ `closeBehavior` can also be customized - i.e. don't load some categories, but load everything else. For example, if you wanted to load everything _except_ advertising, you could pass the following as `closeBehavior`:
346
+
347
+ ```js
348
+ closeBehavior={
349
+ (categories) => ({
350
+ ...categories,
351
+ advertising: false
352
+ })
353
+ }
354
+ ```
355
+
356
+ ##### implyConsentOnInteraction
357
+
358
+ **Type**: `boolean`
359
+ **Default**: `false`
360
+
361
+ Determines whether or not consent should be implied if the user interacts with the website by clicking anywhere outside the Consent Manager banner.
362
+
363
+ ##### defaultDestinationBehavior
364
+
365
+ **Type**: `string`
366
+ **Default**: `disable`
367
+
368
+ Determines what the Consent Manager does if the user has already made consent selections and it detects new destination tools. (This is determined by checking if the user already has a cookie set on their browser.)
369
+
370
+ This is relevant when you've added a connected a new destination to any of the sources managed by Consent Manager.
371
+
372
+ Options:
373
+
374
+ - `disable` (default) - When you add new destinations, they are set to “disabled” unless a user updates their consent selections by default.
375
+ - `enable` - When you add new destinations, they are set to “enabled” unless a user updates their consent selections.
376
+ - `imply` - When you add new destinations, they are enabled or disabled based on the category to which they belong and the user's previous consent to that category.
377
+ For example, if a user already consented to the `marketingAndAnalytics` category, and you add a new destination which is in the `Analytics` category, that destination will be enabled until the user updates their consent selections.
378
+ - `ask` - When you add new destinations, the Consent Manager automatically opens the preferences dialog on initialization, and asks the user for their consent again.
379
+
380
+ ##### cookieDomain
381
+
382
+ **Type**: `string`
383
+ **Default**: the top most domain and all sub domains
384
+
385
+ The domain the `ht-cm-preferences` cookie should be scoped to.
386
+
387
+ ##### bannerContent
388
+
389
+ **Type**: `PropTypes.node`
390
+
391
+ The content of the [consent banner](https://share.getcloudapp.com/Apurj6zv).
392
+
393
+ ##### bannerSubContent
394
+
395
+ **Type**: `string`
396
+
397
+ The [call to action](https://share.getcloudapp.com/z8uXxpkZ) under the primary text in the Consent Manager banner.
398
+
399
+ ##### bannerActionsBlock
400
+
401
+ Type: `function(object) | boolean`
402
+
403
+ The flag or function to render the actions block. If `true` value is passed - will render the default buttons block with `Accept all` and `Deny all` (required for the GDPR compliance). if the function is passed - will render the passed function into a actions block placeholder.
404
+
405
+ Function props:
406
+
407
+ - `acceptAll: () => void` - accept all cookies and close the banner
408
+ - `denyAll: () => void` - deny all cookies and close the banner
409
+ - `changePreferences: () => void` - open the dialog
410
+
411
+ ##### bannerTextColor
412
+
413
+ **Type**: `string`
414
+ **Default**: `#fff`
415
+
416
+ The color of the consent banner text.
417
+
418
+ ##### bannerBackgroundColor
419
+
420
+ Type: `string`<br>
421
+ Default: `#1f4160`
422
+
423
+ The color of the consent banner background.
424
+
425
+ ##### bannerHideCloseButton
426
+
427
+ Type: `boolean`<br>
428
+ Default: `false`
429
+
430
+ Hide the close button of the consent banner.
431
+
432
+ ##### bannerAsModal
433
+
434
+ Type: `boolean`<br>
435
+ Default: `false`
436
+
437
+ Show the consent banner as a modal, blocking the interaction while it is not accepted/rejected.
438
+
439
+ ##### preferencesDialogTitle
440
+
441
+ **Type**: `PropTypes.node`
442
+ **Default**: `Website Data Collection Preferences`
443
+
444
+ The [title of the preferences dialog](https://share.getcloudapp.com/jkuKlrAw).
445
+
446
+ ##### preferencesDialogContent
447
+
448
+ **Type**: `PropTypes.node`
449
+
450
+ The top [descriptive content](https://share.getcloudapp.com/z8uXxJAQ) of the preferences dialog.
451
+
452
+ ##### cancelDialogTitle
453
+
454
+ **Type**: `PropTypes.node`
455
+ **Default**: `Are you sure you want to cancel?`
456
+
457
+ [The title](https://share.getcloudapp.com/v1urD6R6) of the cancel dialog.
458
+
459
+ ##### cancelDialogContent
460
+
461
+ **Type**: `PropTypes.node`
462
+
463
+ The text displayed in the cancel dialog box.
464
+
465
+ ##### customCategories
466
+
467
+ **Type**: `PropTypes.object`
468
+ **Default**: `undefined`
469
+
470
+ An object that represents custom consent categories, and which tools are included in these categories. For example, for CCPA compliance, you could create a custom “Do Not Sell” category and list relevant destinations to it.
471
+
472
+ _Note: Calling the `customCategories` object will overwrite the prebuilt categories (Analytics, Functional, Targeting and Advertising) provided by Consent Manager. Those categories will need to be redeclared inside `customCategories`. You can find examples [here](https://gist.github.com/samuelkahr/343350ad0a466ded566f0d0c8167e800) and [here](https://codepen.io/samuelkahr/pen/JjdNqzr)._
473
+
474
+ ```javascript
475
+ const customCategories = {
476
+ 'New Category': {
477
+ purpose: 'A new consent category to capture more granular consent groupings',
478
+ integrations: ['Google Adwords (Classic)', 'Amplitude', 'Slack']
479
+ }
480
+ }
481
+ ```
482
+
483
+ ##### preferencesDialogTemplate
484
+
485
+ **Type**: `PropTypes.object`
486
+ **Default**:
487
+
488
+ ```javascript
489
+ {
490
+ headings: {
491
+ allowValue: 'Allow',
492
+ categoryValue: 'Category',
493
+ purposeValue: 'Purpose',
494
+ toolsValue: 'Tools'
495
+ },
496
+ checkboxes: {
497
+ noValue: 'No',
498
+ yesValue: 'Yes'
499
+ },
500
+ actionButtons: {
501
+ cancelValue: 'Cancel',
502
+ saveValue: 'Save'
503
+ },
504
+ cancelDialogButtons: {
505
+ cancelValue: 'Yes, Cancel',
506
+ backValue: 'Go Back'
507
+ },
508
+ categories: [
509
+ {
510
+ key: 'functional',
511
+ name: 'Functional',
512
+ description:
513
+ 'To monitor the performance of our site and to enhance your browsing experience.',
514
+ example: 'For example, these tools enable you to communicate with us via live chat.'
515
+ },
516
+ {
517
+ key: 'marketing',
518
+ name: 'Marketing and Analytics',
519
+ description:
520
+ 'To understand user behavior in order to provide you with a more relevant browsing experience or personalize the content on our site.',
521
+ example:
522
+ 'For example, we collect information about which pages you visit to help us present more relevant information.'
523
+ },
524
+ {
525
+ key: 'advertising',
526
+ name: 'Advertising',
527
+ description:
528
+ 'To personalize and measure the effectiveness of advertising on our site and other websites.',
529
+ example:
530
+ 'For example, we may serve you a personalized ad based on the pages you visit on our site.'
531
+ },
532
+ {
533
+ key: 'essential',
534
+ name: 'Essential',
535
+ description: 'We use browser cookies that are necessary for the site to work as intended.',
536
+ example:
537
+ 'For example, we store your website data collection preferences so we can honor them if you return to our site. You can disable these cookies in your browser settings but if you do the site may not work as intended.'
538
+ }
539
+ ]
540
+ }
541
+ ```
542
+
543
+ An object that represents the text fields of the preferences dialog and allows customizing them.
544
+ We recommend copying the default object and changing the fields as necessary.
545
+
546
+ _Note: All fields are optional. If they are not included in the template (object) the default fields will be used._
547
+
548
+ _Note: For categories, you need to provide the key in order to map all the values properly._
549
+
550
+ ### ConsentManagerBuilder
551
+
552
+ The `ConsentManagerBuilder` React component is a low level render props component for building your own consent manager UI. It abstracts away all the logic for fetching destinations, checking/saving consent and loading the Events Browser SDK.
553
+
554
+ _Note: ConsentManagerBuilder is React-based so is not currently compatible with other frameworks such as Vue.js or Angular. In case you want to use it in another framework that is not React, you should use the Standalone implementation._
555
+
556
+ #### Example
557
+
558
+ For a more detailed/advanced example, checkout the [ConsentManager implementation][].
559
+
560
+ ```jsx
561
+ import React from 'react'
562
+ import { ConsentManagerBuilder } from '@ht-sdks/consent-manager'
563
+
564
+ export default function() {
565
+ return (
566
+ <ConsentManagerBuilder writeKey="WRITE_KEY">
567
+ {({ destinations, preferences, setPreferences, saveConsent }) => (
568
+ <div>
569
+ <h2>Tracking tools</h2>
570
+ <ul>
571
+ {destinations.map(destination => (
572
+ <li key={destination.id}>
573
+ <label>
574
+ <input
575
+ type="checkbox"
576
+ checked={Boolean(preferences[destination.id])}
577
+ onChange={() =>
578
+ setPreferences({
579
+ [destination.id]: !preferences[destination.id]
580
+ })
581
+ }
582
+ />
583
+ {destination.name}
584
+ </label>
585
+ </li>
586
+ ))}
587
+ </ul>
588
+
589
+ <button type="button" onClick={() => saveConsent()}>
590
+ Save
591
+ </button>
592
+ <button type="button" onClick={() => saveConsent(true)}>
593
+ Allow all
594
+ </button>
595
+ <button type="button" onClick={() => saveConsent(false)}>
596
+ Deny all
597
+ </button>
598
+ </div>
599
+ )}
600
+ </ConsentManagerBuilder>
601
+ )
602
+ }
603
+ ```
604
+
605
+ #### ConsentManagerBuilder Props
606
+
607
+ - [children](#children)
608
+ - [writeKey](#writekey-1)
609
+ - [shouldRequireConsent](#shouldrequireconsent-1)
610
+ - [initialPreferences](#initialpreferences-1)
611
+ - [defaultDestinationBehavior](#defaultdestinationbehavior-1)
612
+ - [mapCustomPreferences](#mapcustompreferences)
613
+ - [cookieDomain](#cookiedomain-1)
614
+ - [shouldReload](#shouldReload-1)
615
+ - [devMode](#devMode-1)
616
+ - [useDefaultCategories](#useDefaultCategories-1)
617
+
618
+ ##### children
619
+
620
+ **Type**: `function`
621
+
622
+ The render props function that returns your UI.
623
+
624
+ ##### writeKey
625
+
626
+ **Type**: `string`
627
+
628
+ The write key the Events Browser SDK should be loaded with.
629
+
630
+ ##### shouldRequireConsent
631
+
632
+ **Type**: `function`
633
+ **Default**: `() => true`
634
+
635
+ Callback function that determines if consent is required before tracking can begin. Return `true` to show the consent banner and wait for consent (if no consent has been given yet). Return `false` to not show the consent banner and start tracking immediately (unless the user has opted out). The function can return a `Promise` that resolves to a boolean.
636
+
637
+ ##### initialPreferences
638
+
639
+ **Type**: `object`
640
+ **Default**: `{}`
641
+
642
+ The initial value of the preferences. By default it should be an object map of `{destinationId: true|false|'N/A'}`. If you're using [mapCustomPreferences][] it should be an object map of your custom preferences' default values.
643
+
644
+ ##### defaultDestinationBehavior
645
+
646
+ **Type**: `string`
647
+ **Default**: `disable`
648
+
649
+ Determines what the Consent Manager does if the user has already made consent selections and it detects new destination tools. (This is determined by checking if the user already has a cookie set on their browser.)
650
+
651
+ This is relevant when you've added a connected a new destination to any of the sources managed by Consent Manager.
652
+
653
+ Options:
654
+
655
+ - `disable` (default) - When you add new destinations, they are set to “disabled” unless a user updates their consent selections by default.
656
+ - `enable` - When you add new destinations, they are set to “enabled” unless a user updates their consent selections.
657
+ - `imply` - When you add new destinations, they are enabled or disabled based on the category to which they belong and the user's previous consent to that category.
658
+ For example, if a user already consented to the `marketingAndAnalytics` category, and you add a new destination which is in the `Analytics` category, that destination will be enabled until the user updates their consent selections.
659
+ - `ask` - When you add new destinations, the Consent Manager automatically opens the preferences dialog on initialization, and asks the user for their consent again.
660
+
661
+ ##### mapCustomPreferences
662
+
663
+ **Type**: `function`
664
+ **Default**: `undefined`
665
+
666
+ Callback function allows you to use a custom preferences format (e.g: categories) instead of the default destination based one. The function gets called during the consent saving process and gets passed `(destinations, preferences)`. The function should return `{destinationPreferences, customPreferences}` where `destinationPreferences` is your custom preferences mapped to the destinations format (`{destiantionId: true|false}`) and `customPreferences` is your custom preferences if you changed them in the callback (optional).
667
+
668
+ ##### cookieDomain
669
+
670
+ **Type**: `string`
671
+ **Default**: the [top most domain][top-domain] and all sub domains
672
+
673
+ The domain the `ht-cm-preferences` cookie should be scoped to.
674
+
675
+ ##### shouldReload
676
+
677
+ **Type**: `boolean`
678
+ **Default**: `true`
679
+
680
+ Reload the page if the trackers have already been initialized so that the user's new preferences can take effect.
681
+
682
+ ##### devMode
683
+
684
+ **Type**: `boolean`
685
+ **Default**: `false`
686
+
687
+ Disable calling `htevents.load` for local testing.
688
+
689
+ ##### useDefaultCategories
690
+
691
+ **Type**: `boolean`
692
+ **Default**: `false`
693
+
694
+ Use default categories set by Consent Manager instead of destinations.
695
+
696
+ #### ConsentManagerBuilder Render Props
697
+
698
+ - [destinations](#destinations)
699
+ - [newDestinations](#newdestinations)
700
+ - [preferences](#preferences)
701
+ - [destinationPreferences](#destinationpreferences)
702
+ - [havePreferencesChanged](#havepreferenceschanged)
703
+ - [isConsentRequired](#isconsentrequired)
704
+ - [workspaceAddedNewDestinations](#workspaceaddednewdestinations)
705
+ - [setPreferences](#setpreferences)
706
+ - [resetPreferences](#resetpreferences)
707
+ - [saveConsent](#saveconsent)
708
+ - [onError](#onError)
709
+
710
+ ##### destinations
711
+
712
+ **Type**: `array<object>`
713
+ **Default**: `[]`
714
+
715
+ Destinations enabled for the provided write keys. Each destination contains these properties:
716
+
717
+ ```
718
+ {
719
+ id,
720
+ name,
721
+ description,
722
+ website,
723
+ category
724
+ }
725
+ ```
726
+
727
+ ##### newDestinations
728
+
729
+ **Type**: `array<object>`
730
+ **Default**: `[]`
731
+
732
+ New destinations that have been enabled since the user last gave consent.
733
+
734
+ ##### preferences
735
+
736
+ **Type**: `object`
737
+ **Default**: `{}`
738
+
739
+ The current preferences in state. By default if should be in the format of `{destinationId: true|false}`, but if you're using [mapCustomPreferences][] the object map can be in any format you want. _Note: this isn't the saved preferences._
740
+
741
+ ##### destinationPreferences
742
+
743
+ **Type**: `object`
744
+ **Default**: `{}`
745
+
746
+ The current _destination specific_ preferences, i.e. `{Amplitude: true}`.
747
+
748
+ ##### havePreferencesChanged
749
+
750
+ **Type**: `boolean`
751
+ **Default**: `false`
752
+
753
+ A boolean value representing whether or not the user has changed their preferences since opening the preferences modal. Will be set to `true` if the user interacts with the preferences modal by selecting "Yes" or "No" on any of the consent categories.
754
+
755
+ This is used to not reload the page if no preferences have changed, as to not create a disruptive user experience.
756
+
757
+ ##### isConsentRequired
758
+
759
+ **Type**: `boolean`
760
+ **Default**: `true`
761
+
762
+ The result of [shouldRequireConsent][].
763
+
764
+ ##### workspaceAddedNewDestinations
765
+
766
+ **Type**: `boolean`
767
+ **Default**: `false`
768
+
769
+ A boolean value representing whether or not there have been new destinations connected to the source(s) managed by Consent Manager, compared to the destinations set on the existing cookie.
770
+
771
+ ##### setPreferences
772
+
773
+ **Type**: `function(object|boolean)`
774
+
775
+ Sets a preference to a new value in state. By default it takes an object map in the format of `{destinationId: true|false}`, but if you're using [mapCustomPreferences][] the object map can be in any format you want. It behaves like `setState()` in that you can set one or more preferences at a time and they get merged with what's currently in state. You can also pass a boolean to set all destination preferences to `true` or `false` (you shouldn't do this if you're using [mapCustomPreferences][]).
776
+
777
+ ##### resetPreferences
778
+
779
+ **Type**: `function`
780
+
781
+ Resets the [preferences][] state to the value saved in the cookie. Useful for resetting the state when the preferences dialog is closed without saving for example.
782
+
783
+ ##### saveConsent
784
+
785
+ **Type**: `function(object|boolean)`
786
+
787
+ Saves the preferences currently in state to a cookie called `ht-cm-preferences`, triggers an `identify` event with `destinationTrackingPreferences` and `categoryTrackingPreferences` traits, triggers a `track` event called `Consent Updated`, and then reloads the Browser SDK using the new preferences. It can also be passed preferences like [setPreferences][] to do a final update before saving.
788
+
789
+ ##### onError
790
+
791
+ **Type**: `function(object)`
792
+
793
+ Allows you to manually handle if there is an error when initializing - e.g. if there is an ad blocker that prevented fetching the destinations. This will prevent an uncaught error e.g. `Failed to fetch`.
794
+
795
+ ### Utility functions
796
+
797
+ - `openConsentManager()` - Opens the [ConsentManager][] preferences dialog.
798
+ - `doNotTrack()` - Returns the user's Do Not Track preference (normalises the cross browser API differences). Returns `true`, `false` or `null` (no preference specified).
799
+
800
+ ### Setting Custom Anonymous ID
801
+
802
+ Hightouch Events Browser SDK generates a universally unique ID (UUID) for the viewer during the library’s initialization phase, and sets this as anonymousId for each new visitor to your site. This happens before the SDK loads any device-mode destinations, and so before these destination-libraries can generate their own user IDs.
803
+
804
+ Example
805
+
806
+ ```javascript
807
+ htjs_anonymous_id=%2239ee7ea5-b6d8-4174-b612-04e1ef3fa952
808
+ ```
809
+
810
+ You can override the default-generated anonymousID from the Hightouch snippet.
811
+
812
+ ```javascript
813
+ htevents.setAnonymousId('YOUR_CUSTOM_ID')
814
+ ```
815
+
816
+ _Note: Keep in mind that setting the anonymousId does not overwrite the anonymous tracking IDs for any destinations you’re using._
817
+
818
+ _There are other ways to override the anonymousID, you can find more information [here][]._
819
+
820
+ ## Styles
821
+
822
+ [GUIDESTYLES.md](GUIDESTYLES.md) contains the list of all components you can use this id to change de styles on Consent Manager.
823
+
824
+ ## Development
825
+
826
+ To run our storybook locally, simply do:
827
+
828
+ ```
829
+ $ npm run dev
830
+ ```
831
+
832
+ and the storybook should be opened in your browser. We recommend adding a new story for new features, and testing against existing stories when making bug fixes.
833
+
834
+ ## License
835
+
836
+ consent-manager is released under the MIT license.
837
+
838
+ Copyright © 2024 Hightouch
839
+
840
+ [preact]: https://preactjs.com
841
+ [currentscript]: https://caniuse.com/#feat=document-currentscript
842
+ [ineu]: https://github.com/segmentio/in-eu
843
+ [consentmanager]: #consentmanager
844
+ [consentmanagerbuilder]: #consentmanagerbuilder
845
+ [top-domain]: https://github.com/segmentio/top-domain
846
+ [mapcustompreferences]: #mapcustompreferences
847
+ [shouldrequireconsent]: #shouldrequireconsent-1
848
+ [preferences]: #preferences
849
+ [setpreferences]: #setpreferences
850
+ [consentmanager implementation]: src/consent-manager
851
+ [css selector]: https://developer.mozilla.org/en-US/docs/Web/API/Document/querySelector