Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

HDS-2495 cookie hds event namings #1417

Merged
merged 1 commit into from
Nov 14, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
6 changes: 3 additions & 3 deletions packages/hds-js/standalone/example.html
Original file line number Diff line number Diff line change
Expand Up @@ -6,8 +6,8 @@
<title>Esimerkki keksibannerista</title>
<script>
/* Example listener for cookie consent change events */
window.addEventListener('cookie-consent-changed', function (event) {
console.log('Got cookie-consent-changed event with accepted groups:', event.detail.acceptedGroups);
window.addEventListener('hds-cookie-consent-changed', function (event) {
console.log('Got hds-cookie-consent-changed event with accepted groups:', event.detail.acceptedGroups);
});

const test = window.addEventListener('hds-cookie-consent-unapproved-cookie-found', function (event) {
Expand Down Expand Up @@ -830,7 +830,7 @@
//targetSelector: 'body', // Defaults to 'body'
//spacerParentSelector: 'body', // Defaults to 'body'
//pageContentSelector: 'body', // Defaults to 'body'
//submitEvent: 'cookie-consent-changed', // If this string is set, triggers a window level event with that string and detail.acceptedGroups before closing banner. If not set, reloads page instead
//submitEvent: true, // If this is set to true, triggers a window level event 'hds-cookie-consent-changed' and detail.acceptedGroups before closing banner. If not set, reloads page instead
settingsPageSelector: '#hds-cookie-consent-full-page', // If this string is set and matching element is found on page, instead of banner, show a full page cookie settings replacing the matched element.
};
hds.CookieConsentCore.create(siteSettingsObj, options);
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,7 @@ import siteSettings from '../../cookieConsentCore/example/minimal_sitesettings.j
const mockCore = mockCookieConsentCore();

jest.mock('../../cookieConsentCore/cookieConsentCore', () => ({
...(jest.requireActual('../../cookieConsentCore/cookieConsentCore') as Record<string, unknown>),
CookieConsentCore: {
create: (...args: Parameters<typeof CookieConsentCore.create>) => mockCore.create(...args),
},
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,7 @@ import { CookieConsentContextProvider } from '../../contexts/CookieConsentContex
const mockCore = mockCookieConsentCore();

jest.mock('../../../cookieConsentCore/cookieConsentCore', () => ({
...(jest.requireActual('../../../cookieConsentCore/cookieConsentCore') as Record<string, unknown>),
CookieConsentCore: {
create: (...args: Parameters<typeof CookieConsentCore.create>) => mockCore.create(...args),
},
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,7 @@ import useForceRender from '../../../../hooks/useForceRender';
const mockCore = mockCookieConsentCore();

jest.mock('../../../cookieConsentCore/cookieConsentCore', () => ({
...(jest.requireActual('../../../cookieConsentCore/cookieConsentCore') as Record<string, unknown>),
CookieConsentCore: {
create: (...args: Parameters<typeof CookieConsentCore.create>) => mockCore.create(...args),
},
Expand Down Expand Up @@ -222,7 +223,7 @@ describe('useCookieConsent', () => {
expect(result.getAllByTestId(mockCore.getBannerTestId())).toHaveLength(1);
});
it('"onChange" is triggered when an event is dispatched', async () => {
const result = renderTests({ options: { submitEvent: 'my-event' } });
const result = renderTests({ options: { submitEvent: true } });
const { getConsents, waitForReady, createPromiseForOnChangeUpdate } = result;
await waitForReady();
const updatedConsentData = ['group3', 'group4'];
Expand Down
Original file line number Diff line number Diff line change
@@ -1,21 +1,20 @@
import React, { useState } from 'react';
import { act, fireEvent, render, RenderResult, waitFor } from '@testing-library/react';

import { monitorEvent, useCookieConsentEvents } from '../useCookieConsentEvents';
import { CookieConsentCore, cookieEventType } from '../../../cookieConsentCore/cookieConsentCore';
import { useCookieConsentEvents } from '../useCookieConsentEvents';
// eslint-disable-next-line jest/no-mocks-import
import { mockCookieConsentCore } from '../../../cookieConsentCore/__mocks__/mockCookieConsentCore';
import { CookieConsentCore } from '../../../cookieConsentCore/cookieConsentCore';
import useForceRender from '../../../../hooks/useForceRender';
import { getLastMockCallArgs } from '../../../../utils/testHelpers';

const mockCore = mockCookieConsentCore();

jest.mock('../../../cookieConsentCore/cookieConsentCore', () => ({
...(jest.requireActual('../../../cookieConsentCore/cookieConsentCore') as Record<string, unknown>),
CookieConsentCore: {
create: (...args: Parameters<typeof CookieConsentCore.create>) => mockCore.create(...args),
},
}));

describe('useCookieConsentEventsEvents', () => {
const testIds = {
disposeButton: 'dispose',
Expand All @@ -24,22 +23,18 @@ describe('useCookieConsentEventsEvents', () => {
listener: 'listener',
isMounted: 'is-mounted',
};

const getCallCount = (tracker: jest.Mock) => {
return tracker.mock.calls.length;
};

const onChange = jest.fn();
const onMonitorEvent = jest.fn();
const onReady = jest.fn();
let renderCount: number = 0;
let submitEvent: string | undefined;
const ListenerComponent = () => {
const disposer = useCookieConsentEvents({
onChange,
onMonitorEvent,
onReady,
submitEvent,
});
return (
<div data-testid={testIds.listener}>
Expand Down Expand Up @@ -92,35 +87,25 @@ describe('useCookieConsentEventsEvents', () => {
onMonitorEvent.mockReset();
onReady.mockReset();
renderCount = 0;
submitEvent = undefined;
});
const triggerAllEvents = () => {
mockCore.triggerReadyEvent();
mockCore.triggerChangeEvent([]);
mockCore.triggerMonitorEvent('', '', []);
};

const renderTests = (newSubmitEvent?: string) => {
if (newSubmitEvent) {
submitEvent = newSubmitEvent;
}
const renderTests = () => {
let result: RenderResult;
act(() => {
result = render(<HookComponent />);
});

const getRenderCount = () => {
return parseInt(result.getByTestId(testIds.renderAgainButton).innerHTML, 10);
};
const getIsMounted = () => {
return parseInt(result.getByTestId(testIds.isMounted).innerHTML, 10) === 1;
};

// eslint-disable-next-line @typescript-eslint/no-shadow
const renderAgain = async (newSubmitEvent?: string) => {
if (newSubmitEvent) {
submitEvent = newSubmitEvent;
}
const renderAgain = async () => {
const lastRender = getRenderCount();
fireEvent.click(result.getByTestId(testIds.renderAgainButton));
await waitFor(() => {
Expand All @@ -138,7 +123,6 @@ describe('useCookieConsentEventsEvents', () => {
fireEvent.click(result.getByTestId(testIds.disposeButton));
// await renderAgain();
};

return {
// @ts-ignore
...result,
Expand All @@ -148,7 +132,6 @@ describe('useCookieConsentEventsEvents', () => {
dispose,
};
};

it('listeners are not called on init', async () => {
renderTests();
expect(getCallCount(onChange)).toBe(0);
Expand All @@ -161,21 +144,17 @@ describe('useCookieConsentEventsEvents', () => {
expect(getCallCount(onChange)).toBe(0);
expect(getCallCount(onMonitorEvent)).toBe(0);
expect(getCallCount(onReady)).toBe(1);

const consentData = ['group3', 'group4'];

mockCore.triggerChangeEvent(consentData);
expect(getCallCount(onChange)).toBe(1);
expect(getLastMockCallArgs(onChange)[0].acceptedGroups).toEqual(consentData);
expect(getCallCount(onMonitorEvent)).toBe(0);
expect(getCallCount(onReady)).toBe(1);

mockCore.triggerChangeEvent([]);
expect(getCallCount(onChange)).toBe(2);
expect(getLastMockCallArgs(onChange)[0].acceptedGroups).toEqual([]);
expect(getCallCount(onMonitorEvent)).toBe(0);
expect(getCallCount(onReady)).toBe(1);

const storageKeys = 'storageKeys';
const storageType = 'storageType';
const acceptedGroups = ['acceptedGroups'];
Expand All @@ -186,13 +165,12 @@ describe('useCookieConsentEventsEvents', () => {
storageKeys,
storageType,
acceptedGroups,
type: monitorEvent,
type: cookieEventType.MONITOR,
});
expect(getCallCount(onReady)).toBe(1);
});
it('listeners are not called after unmount', async () => {
const { toggleMount, renderAgain } = renderTests();

triggerAllEvents();
triggerAllEvents();
expect(getCallCount(onChange)).toBe(2);
Expand All @@ -212,7 +190,6 @@ describe('useCookieConsentEventsEvents', () => {
});
it('listeners are not called after disposer is called. Remounting sets listeners back', async () => {
const { dispose, toggleMount, renderAgain } = renderTests();

dispose();
triggerAllEvents();
expect(getCallCount(onChange)).toBe(0);
Expand All @@ -234,24 +211,4 @@ describe('useCookieConsentEventsEvents', () => {
expect(getCallCount(onMonitorEvent)).toBe(1);
expect(getCallCount(onReady)).toBe(1);
});
it('changing the submit event changes event listeners', async () => {
const { renderAgain } = renderTests();
const newSubmitEvent = 'new-event-type';
triggerAllEvents();
expect(getCallCount(onChange)).toBe(1);
expect(getCallCount(onMonitorEvent)).toBe(1);
expect(getCallCount(onReady)).toBe(1);
await renderAgain(newSubmitEvent);
triggerAllEvents();
expect(getCallCount(onChange)).toBe(1);
expect(getCallCount(onMonitorEvent)).toBe(2);
expect(getCallCount(onReady)).toBe(2);

mockCore.triggerChangeEvent([], newSubmitEvent);
expect(getCallCount(onChange)).toBe(2);

await renderAgain();
mockCore.triggerChangeEvent([], newSubmitEvent);
expect(getCallCount(onChange)).toBe(3);
});
});
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,7 @@ import { defaultSettingsPageId } from '../useCookieConsent';
const mockCore = mockCookieConsentCore();

jest.mock('../../../cookieConsentCore/cookieConsentCore', () => ({
...(jest.requireActual('../../../cookieConsentCore/cookieConsentCore') as Record<string, unknown>),
CookieConsentCore: {
create: (...args: Parameters<typeof CookieConsentCore.create>) => mockCore.create(...args),
},
Expand Down Expand Up @@ -178,6 +179,7 @@ describe('useCookieSettingsPage', () => {
act(() => {
mockCore.triggerChangeEvent(updatedConsentData);
});

await waitFor(() => {
expect(getConsents()).toEqual(updatedConsentData.map((group) => ({ group, consented: true })));
});
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@ import { useCallback, useEffect, useRef } from 'react';

import { CookieConsentCore } from '../../cookieConsentCore/cookieConsentCore';
import useForceRender from '../../../hooks/useForceRender';
import { CookieConsentChangeEvent, defaultSubmitEvent, useCookieConsentEvents } from './useCookieConsentEvents';
import { CookieConsentChangeEvent, useCookieConsentEvents } from './useCookieConsentEvents';
import { Options } from '../../cookieConsentCore/types';
import { isSsrEnvironment } from '../../../utils/isSsrEnvironment';

Expand Down Expand Up @@ -54,17 +54,16 @@ export function useCookieConsent(props: CookieConsentReactProps): CookieConsentR
}
return window && window.hds && window.hds.cookieConsent;
};
const submitEventName = passedOptions.submitEvent || defaultSubmitEvent;
const instanceRef = useRef<CookieCore | null>(null);
const readyRef = useRef<boolean>(false);
const forceRender = useForceRender();
//
const mergedOptions: CreateProps['options'] = {
language,
submitEvent: submitEventName,
...passedOptions,
// this must always be true
// these must always be true
disableAutoRender: true,
submitEvent: true,
};

const onChangeListener = useCallback(
Expand All @@ -91,7 +90,6 @@ export function useCookieConsent(props: CookieConsentReactProps): CookieConsentR
onChange: onChangeListener,
onMonitorEvent,
onReady,
submitEvent: mergedOptions.submitEvent,
});

const getAllConsentStatuses = () => {
Expand Down
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
import { MutableRefObject, useEffect, useMemo, useRef } from 'react';

import { isSsrEnvironment } from '../../../utils/isSsrEnvironment';
import { cookieEventType } from '../../cookieConsentCore/cookieConsentCore';

export type CookieConsentChangeEvent = {
type: string;
Expand All @@ -12,17 +13,11 @@ export type CookieConsentEventsProps = {
onChange: (changeProps: CookieConsentChangeEvent) => void;
onReady: () => void;
onMonitorEvent: (changeProps: CookieConsentChangeEvent) => void;
submitEvent?: string;
};
export type CookieConsentEventsReturnType = () => void;

export const defaultSubmitEvent = 'cookie-consent-changed';
export const monitorEvent = 'hds-cookie-consent-unapproved-item-found';
export const readyEvent = 'hds_cookieConsent_ready';

export function useCookieConsentEvents(props: CookieConsentEventsProps): CookieConsentEventsReturnType {
const { onChange, onReady, onMonitorEvent } = props;
const submitEvent = props.submitEvent || defaultSubmitEvent;
const listenerDisposer: MutableRefObject<(() => void) | null> = useRef(null);
mrTuomoK marked this conversation as resolved.
Show resolved Hide resolved

useMemo(() => {
Expand All @@ -45,7 +40,7 @@ export function useCookieConsentEvents(props: CookieConsentEventsProps): CookieC
type,
acceptedGroups: detail.consentedGroups || detail.acceptedGroups || [],
};
if (type === monitorEvent && detail.type && detail.keys) {
if (type === cookieEventType.MONITOR && detail.type && detail.keys) {
changeProps.storageType = detail.type;
changeProps.storageKeys = detail.keys;
}
Expand All @@ -64,21 +59,21 @@ export function useCookieConsentEvents(props: CookieConsentEventsProps): CookieC
onReady();
};

window.addEventListener(submitEvent, cookieListener);
window.addEventListener(monitorEvent, monitorListener);
window.addEventListener(readyEvent, readyListener);
window.addEventListener(cookieEventType.CHANGE, cookieListener);
window.addEventListener(cookieEventType.MONITOR, monitorListener);
window.addEventListener(cookieEventType.READY, readyListener);

const disposer = () => {
window.removeEventListener(submitEvent, cookieListener);
window.removeEventListener(monitorEvent, monitorListener);
window.removeEventListener(readyEvent, readyListener);
window.removeEventListener(cookieEventType.CHANGE, cookieListener);
window.removeEventListener(cookieEventType.MONITOR, monitorListener);
window.removeEventListener(cookieEventType.READY, readyListener);
listenerDisposer.current = null;
};

listenerDisposer.current = disposer;

return disposer;
}, [submitEvent, onChange, onMonitorEvent, onReady]);
}, [onChange, onMonitorEvent, onReady]);

useEffect(() => {
return () => {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -17,8 +17,8 @@ type Options = {
targetSelector?: string;
spacerParentSelector?: string;
pageContentSelector?: string;
submitEvent?: boolean | string;
settingsPageSelector?: string;
submitEvent?: boolean;
};

jest.mock('hds-core/lib/components/cookie-consent/cookieConsent', () => ({
Expand Down Expand Up @@ -79,10 +79,11 @@ describe('cookieConsentCore', () => {
// targetSelector: 'body', // Defaults to 'body'
// spacerParentSelector: 'body', // Defaults to 'body'
// pageContentSelector: 'body', // Defaults to 'body'
// submitEvent: 'cookie-consent-changed', // If this string is set, triggers a window level event with that string and detail.acceptedGroups before closing banner. If not set, reloads page instead
// submitEvent: false, // If this is set to true, triggers a window level event 'hds-cookie-consent-changed' containing detail.acceptedGroups before closing banner. If not set, reloads page instead
submitEvent: true,
settingsPageSelector: '#hds-cookie-consent-full-page', // If this string is set and matching element is found on page, instead of banner, show a full page cookie settings replacing the matched element.
};
const optionsEvent = { ...options, submitEvent: 'cookie-consent-changed' };
const optionsEvent = { ...options };

const STORAGE_TYPE = {
cookie: 1,
Expand Down
Loading
Loading