Data Flow and State Management
Relevant source files
The following files were used as context for generating this wiki page:
The consent-manager library provides a modular architecture for managing user consent for cookies. The data flow and state management are centralized within the ConsentManager class, which acts as the single source of truth. This core module maintains the current consent status, persists it to a browser cookie, and communicates state changes to other modules, such as GrantsInterface (UI components) and DOMConnector (DOM manipulation), through an event-based system.
The overall architecture is designed to be flexible, allowing developers to use only the components they need. The state is initialized from a cookie or default configuration, updated through user interactions or direct API calls, and then propagated to subscribed modules to reflect the changes in the UI and application behavior.
Core Architecture
The system is composed of a central state manager (ConsentManager) and optional consumer modules (GrantsInterface, DOMConnector) that react to state changes.
This diagram illustrates the relationship between the main classes. ConsentManager is the central hub, with GrantsInterface and DOMConnector acting as clients that both listen for and trigger state updates.
State Management in ConsentManager
The ConsentManager class is the heart of the library, responsible for all state-related operations.
Initialization and Configuration
Upon instantiation, ConsentManager merges the user-provided configuration with default values and immediately attempts to parse an existing consent cookie to establish the initial state.
Sources: src/modules/ConsentManager.ts:81-84
The configuration object defines the behavior of the manager.
| Property | Type | Description | Default |
|---|---|---|---|
version | string | The version of the configuration. A mismatch with the cookie's version invalidates the stored consent. | '1' |
cookieName | string | The name of the cookie used for storage. | 'consent-manager' |
expires | number | Date | 'session' | The cookie's expiration time in days, as a Date object, or 'session'. | 365 |
categories | object[] | An array defining the consent categories. Each object has id, label, description, required, and optional default properties. | [] |
Sources: src/modules/ConsentManager.ts:58-77
The initialization flow is as follows:
Sources: src/modules/ConsentManager.ts:86-118
State Representation
The state is primarily represented by two public properties:
grants: An object where keys are category IDs and values are booleans indicating if consent is granted.isCustomized: A boolean flag that isfalseby default and becomestrueonce the user makes a choice, either by interacting with the UI or through asetGrantcall.
Sources: src/modules/ConsentManager.ts:79-80, src/modules/ConsentManager.test.ts:20, src/modules/ConsentManager.test.ts:39
State Persistence
State is persisted in a browser cookie using the js-cookie library.
Sources: package.json:47
Cookie Structure
The data is stored as a JSON string with a specific structure. The validateCookie function ensures that only cookies matching this structure are considered valid.
The writeCookie method is called internally whenever setGrant successfully changes the state. It serializes the version and grants properties and saves them to the cookie.
Sources: src/modules/ConsentManager.ts:120-127
State Modification
The setGrant(id, status) method is the sole entry point for modifying the consent state.
- It can update a single category by its
idor all non-required categories ifidis'*'. - It prevents changes to categories marked as
required: true. - After updating a grant, it sets
isCustomizedtotrue, writes the new state to the cookie, and dispatches events.
Sources: src/modules/ConsentManager.ts:129-155, src/modules/ConsentManager.test.ts:42-52
This diagram shows the logic within the setGrant method.
Event System
ConsentManager uses a simple event emitter pattern to communicate state changes. This decouples the state logic from the UI and other modules.
The available events are:
update: Fired when any category is granted or revoked.grant: Fired only when a category is granted (status: true).revoke: Fired only when a category is revoked (status: false).
Modules can subscribe and unsubscribe to these events using on(eventName, callback) and off(eventName, callback).
Sources: src/modules/ConsentManager.ts:157-185, src/modules/ConsentManager.test.ts:98-106
State Consumption and Data Flow
Other modules consume the state from ConsentManager by listening to events and directly accessing its public properties.
GrantsInterface (UI Module)
The GrantsInterface module is responsible for rendering UI components like the consent banner and modal.
- Initialization: On creation, it checks
client.isCustomized. IffalseandautoShowistrue, it callsshowBanner(). - Event Handling: It listens for the
updateevent on theConsentManagerinstance. When an update occurs andisCustomizedbecomestrue, it automatically hides the banner. - State Modification: UI elements like "Accept All" and "Reject" buttons call
client.setGrant('*', true/false)to update the state. Toggles in the consent table callsetGrantfor individual categories. - State Reading: The
generateConsentTablemethod readsclient.config.categoriesto build the table rows andclient.grantsto set the initial state of the checkboxes.
Sources: src/modules/GrantsInterface.ts:40-44, src/modules/GrantsInterface.ts:101-105, src/modules/GrantsInterface.ts:71-74, src/modules/GrantsInterface.ts:114-121
The sequence diagram below shows a typical user interaction flow.
DOMConnector (DOM Manipulation)
The DOMConnector module links the consent state directly to the DOM.
- Initialization: In its constructor, it performs an initial
updateDOM()call and subscribes to theupdateevent from theConsentManagerclient. - State Reaction: The
updateDOMmethod is called on initialization and for everyupdateevent. It queries the DOM for all elements with thedata-consent-managerattribute. - Logic: For each element,
isElementGrantedchecks if any of the categories listed indata-cm-categoriesare enabled inclient.grants. Based on this and the presence ofdata-cm-inverted, it either sets the attribute defined bydata-cm-attributeto the value fromdata-cm-valueor removes it.
Sources: src/modules/DOMConnector.ts:4-7, src/modules/DOMConnector.ts:30-47
| Attribute | Description |
|---|---|
data-consent-manager | Marks the element for processing by DOMConnector. |
data-cm-categories | A comma-separated list of category IDs that enable the element. |
data-cm-attribute | The HTML attribute to be set on the element when enabled. |
data-cm-value | The value for the specified attribute. |
data-cm-inverted | (Optional) Inverts the logic, applying the attribute when consent is not granted. |
Sources: README.md:144-153, src/modules/DOMConnector.ts:9-28
Module Bundling and Exposure
The core modules are exported for use in different environments. src/index.ts prepares the modules for standard ES Module and CommonJS usage, while src/bundle.ts attaches the classes to the global window object for direct use in browsers via a <script> tag.
Sources: src/index.ts, src/bundle.ts