Skip to content

Commit

Permalink
Feat: Allow overriding consent description intro #CCM-63
Browse files Browse the repository at this point in the history
  • Loading branch information
OndraM committed Mar 7, 2022
1 parent 4f28840 commit 1f6c31a
Show file tree
Hide file tree
Showing 15 changed files with 89 additions and 42 deletions.
22 changes: 11 additions & 11 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -241,7 +241,7 @@ initLmcCookieConsentManager( // when loaded as a module, these options are passe
// custom code
},
translationOverrides: { // overrides of the default translation for specified languages
cs: { consentTitle: 'Vlastní nadpis' },
cs: { consentTitle: 'Vlastní nadpis', descriptionIntro: 'Vlastní úvodní text popisu souhlasu' },
en: { consentTitle: 'Custom title' },
},
config: {
Expand All @@ -255,16 +255,16 @@ initLmcCookieConsentManager( // when loaded as a module, these options are passe
## Configuration options
| Option | Type | Default value | Description |
|--------------------------|--------------------------------------|---------------------------------|----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------|
| `autodetectLang` | boolean | `true` | Autodetect language based on the value of `<html lang="...">`. If autodetect fails or if unsupported language is detected, fallback to `defaultLang`.<br>When disabled, force language to `defaultLang`. |
| `defaultLang` | string | `'cs'` | Default language. One of `cs`, `de`, `en`, `hu`, `pl`, `ru`, `sk`, `uk`. This language will be used when autodetect is disabled or when it fails. |
| `companyNames` | array | `['LMC']` | Array of strings with company names. Adjust only when the consent needs to be given to multiple companies. [See example][examples-configuration]. |
| `consentCollectorApiUrl` | ?string | `'https://ccm.lmc.cz/(...)'` | URL of the API where user consent information is sent. Null to disable sending data to the API. |
| `config` | Object | `{}` | Override default config of the underlying library. For all parameters see [original library][cookie consent options]. |
| `displayMode` | DisplayMode (string) | `DisplayMode.FORCE` (`force`) | `force` (default) to show consent in a centered modal box and to block page until user action. `soft` to show consent banner on the bottom of the page and do not block the page before user action. |
| `on*` callbacks | function | `(cookieConsent) => {}` | See below for configurable callbacks. |
| `translationOverrides` | Record<string, TranslationOverride> | `{}` | Override default translation for specified languages. Currently only `consentTitle` could be overridden. <br>For example: `{ en: { consentTitle: 'Custom consent modal title' } }` |
| Option | Type | Default value | Description |
|--------------------------|-------------------------------------|-------------------------------|----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------|
| `autodetectLang` | boolean | `true` | Autodetect language based on the value of `<html lang="...">`. If autodetect fails or if unsupported language is detected, fallback to `defaultLang`.<br>When disabled, force language to `defaultLang`. |
| `defaultLang` | string | `'cs'` | Default language. One of `cs`, `de`, `en`, `hu`, `pl`, `ru`, `sk`, `uk`. This language will be used when autodetect is disabled or when it fails. |
| `companyNames` | array | `['LMC']` | Array of strings with company names. Adjust only when the consent needs to be given to multiple companies. [See example][examples-configuration]. |
| `consentCollectorApiUrl` | ?string | `'https://ccm.lmc.cz/(...)'` | URL of the API where user consent information is sent. Null to disable sending data to the API. |
| `config` | Object | `{}` | Override default config of the underlying library. For all parameters see [original library][cookie consent options]. |
| `displayMode` | DisplayMode (string) | `DisplayMode.FORCE` (`force`) | `force` (default) to show consent in a centered modal box and to block page until user action. `soft` to show consent banner on the bottom of the page and do not block the page before user action. |
| `on*` callbacks | function | `(cookieConsent) => {}` | See below for configurable callbacks. |
| `translationOverrides` | Record<string, TranslationOverride> | `{}` | Override default translation for specified languages. `consentTitle` and/or `descriptionIntro` could be overridden.<br>[See example][examples-configuration] |
### Supported languages
Expand Down
5 changes: 3 additions & 2 deletions examples/configuration.html
Original file line number Diff line number Diff line change
Expand Up @@ -157,8 +157,9 @@ <h2 class="mt-md-3 mb-3">Use cookieConsent instance</h2>
},
translationOverrides: {
sk: {
consentTitle: 'Prispôsobený titulok'
}
consentTitle: 'Prispôsobený titulok',
descriptionIntro: 'Prispôsobený úvodný text.',
},
}
}
);
Expand Down
16 changes: 8 additions & 8 deletions src/LmcCookieConsentManager.ts
Original file line number Diff line number Diff line change
Expand Up @@ -80,14 +80,14 @@ const LmcCookieConsentManager: CookieConsentManager = (serviceName, args) => {
const cookieConsent = window.initCookieConsent();

const languages = {
cs: configCs({ companyNames, consentTitle: translationOverrides.cs?.consentTitle }),
de: configDe({ companyNames, consentTitle: translationOverrides.de?.consentTitle }),
en: configEn({ companyNames, consentTitle: translationOverrides.en?.consentTitle }),
hu: configHu({ companyNames, consentTitle: translationOverrides.hu?.consentTitle }),
pl: configPl({ companyNames, consentTitle: translationOverrides.pl?.consentTitle }),
ru: configRu({ companyNames, consentTitle: translationOverrides.ru?.consentTitle }),
sk: configSk({ companyNames, consentTitle: translationOverrides.sk?.consentTitle }),
uk: configUk({ companyNames, consentTitle: translationOverrides.uk?.consentTitle }),
cs: configCs({ companyNames, ...translationOverrides.cs }),
de: configDe({ companyNames, ...translationOverrides.de }),
en: configEn({ companyNames, ...translationOverrides.en }),
hu: configHu({ companyNames, ...translationOverrides.hu }),
pl: configPl({ companyNames, ...translationOverrides.pl }),
ru: configRu({ companyNames, ...translationOverrides.ru }),
sk: configSk({ companyNames, ...translationOverrides.sk }),
uk: configUk({ companyNames, ...translationOverrides.uk }),
};

const onFirstAcceptHandler = (
Expand Down
16 changes: 15 additions & 1 deletion src/__tests__/utils.test.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
import { addSeparators, pluralize } from '../utils';
import { addSeparators, assembleDescriptionIntro, pluralize } from '../utils';

describe('utils', () => {
describe('addSeparators', () => {
Expand Down Expand Up @@ -30,4 +30,18 @@ describe('utils', () => {
expect(pluralize(2, 'test', 'tests')).toBe('tests');
});
});

describe('assembleDescriptionIntro', () => {
it('should use default value as description when no override was provided', () => {
expect(assembleDescriptionIntro('Default value')).toBe('<p>Default value</p>');
});

it('should use override value as description when provided', () => {
expect(assembleDescriptionIntro('Default value', 'Override value')).toBe('<p>Override value</p>');
});

it('should return empty string when empty override value given', () => {
expect(assembleDescriptionIntro('Default value', '')).toBe('');
});
});
});
7 changes: 5 additions & 2 deletions src/languages/cs.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
import { addSeparators, pluralize } from '../utils';
import { addSeparators, assembleDescriptionIntro, pluralize } from '../utils';
import { CookieConsentCategory, ExtraMessages } from '../types';
import { VanillaCookieConsent } from '../types/vanilla-cookieconsent';

Expand All @@ -20,7 +20,10 @@ export const config = (extraMessages: ExtraMessages): VanillaCookieConsent.Langu
consent_modal: {
title: lang.consentTitle ?? 'Díky Cookies budou naše stránky ještě lepší',
description: `
<p>Když lépe pochopíme, co vás zajímá, budeme vám zobrazovat přesnější obsah na míru.</p>
${assembleDescriptionIntro(
'Když lépe pochopíme, co vás zajímá, budeme vám zobrazovat přesnější obsah na míru.',
lang.descriptionIntro,
)}
<p>
Kliknutím na tlačítko „Přijmout všechny“ dáte
${pluralize(lang.companyNames.length, lang.company, lang.companies)}
Expand Down
7 changes: 5 additions & 2 deletions src/languages/de.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
import { addSeparators } from '../utils';
import { addSeparators, assembleDescriptionIntro } from '../utils';
import { ExtraMessages, CookieConsentCategory } from '../types';
import { VanillaCookieConsent } from '../types/vanilla-cookieconsent';

Expand All @@ -18,7 +18,10 @@ export const config = (extraMessages: ExtraMessages): VanillaCookieConsent.Langu
consent_modal: {
title: lang.consentTitle ?? 'Diese Website verwendet Cookies',
description: `
<p>Wenn wir genau wissen, wofür Sie sich interessieren, können wir Ihnen maßgeschneiderte Inhalte anbieten.</p>
${assembleDescriptionIntro(
'Wenn wir genau wissen, wofür Sie sich interessieren, können wir Ihnen maßgeschneiderte Inhalte anbieten.',
lang.descriptionIntro,
)}
<p>
Indem Sie auf „Alles akzeptieren“ klicken, stimmen Sie der Verwendung von Cookies und anderen Identifikatoren auf Ihrem Gerät durch
${addSeparators(lang.companyNames, extra.and)}
Expand Down
7 changes: 5 additions & 2 deletions src/languages/en.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
import { addSeparators } from '../utils';
import { addSeparators, assembleDescriptionIntro } from '../utils';
import { ExtraMessages, CookieConsentCategory } from '../types';
import { VanillaCookieConsent } from '../types/vanilla-cookieconsent';

Expand All @@ -17,7 +17,10 @@ export const config = (extraMessages: ExtraMessages): VanillaCookieConsent.Langu
consent_modal: {
title: lang.consentTitle ?? 'Cookies make our site even better',
description: `
<p>By better understanding what you're interested in, we'll show you more relevant content.</p>
${assembleDescriptionIntro(
"By better understanding what you're interested in, we'll show you more relevant content.",
lang.descriptionIntro,
)}
<p>
By clicking the "Accept all" button, you give
${addSeparators(lang.companyNames, extra.and)}
Expand Down
7 changes: 5 additions & 2 deletions src/languages/hu.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
import { addSeparators } from '../utils';
import { addSeparators, assembleDescriptionIntro } from '../utils';
import { ExtraMessages, CookieConsentCategory } from '../types';
import { VanillaCookieConsent } from '../types/vanilla-cookieconsent';

Expand All @@ -18,7 +18,10 @@ export const config = (extraMessages: ExtraMessages): VanillaCookieConsent.Langu
consent_modal: {
title: lang.consentTitle ?? 'Az oldalak süti fájlokat használnak',
description: `
<p>Ha jobban megértjük, mi érdekli Önt, akkor pontosabban személyre szabott tartalmat tudunk Önnek megjeleníteni.</p>
${assembleDescriptionIntro(
'Ha jobban megértjük, mi érdekli Önt, akkor pontosabban személyre szabott tartalmat tudunk Önnek megjeleníteni.',
lang.descriptionIntro,
)}
<p>
A „Mindent elfogadok” gombra kattintva a hozzájárulását adja ahhoz, hogy az
${addSeparators(lang.companyNames, extra.and)}
Expand Down
7 changes: 5 additions & 2 deletions src/languages/pl.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
import { addSeparators, pluralize } from '../utils';
import { addSeparators, assembleDescriptionIntro, pluralize } from '../utils';
import { ExtraMessages, CookieConsentCategory } from '../types';
import { VanillaCookieConsent } from '../types/vanilla-cookieconsent';

Expand All @@ -20,7 +20,10 @@ export const config = (extraMessages: ExtraMessages): VanillaCookieConsent.Langu
consent_modal: {
title: lang.consentTitle ?? 'Dzięki plikom Cookies nasza strona będzie jeszcze lepsza',
description: `
<p>Gdy lepiej zrozumiemy, co Cię interesuje, pokażemy dokładniejsze treści dopasowane do Twoich preferencji.</p>
${assembleDescriptionIntro(
'Gdy lepiej zrozumiemy, co Cię interesuje, pokażemy dokładniejsze treści dopasowane do Twoich preferencji.',
lang.descriptionIntro,
)}
<p>
Kliknij w przycisk „Akceptuj wszystkie”, aby wyrazić zgodę na wykorzystanie plików cookie przez
${pluralize(lang.companyNames.length, lang.company, lang.companies)}
Expand Down
7 changes: 5 additions & 2 deletions src/languages/ru.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
import { addSeparators, pluralize } from '../utils';
import { addSeparators, assembleDescriptionIntro, pluralize } from '../utils';
import { ExtraMessages, CookieConsentCategory } from '../types';
import { VanillaCookieConsent } from '../types/vanilla-cookieconsent';

Expand All @@ -20,7 +20,10 @@ export const config = (extraMessages: ExtraMessages): VanillaCookieConsent.Langu
consent_modal: {
title: lang.consentTitle ?? 'Этот сайт использует файлы cookie',
description: `
<p>Когда мы лучше поймем, что вас интересует, мы покажем вам лучший контент.</p>
${assembleDescriptionIntro(
'Когда мы лучше поймем, что вас интересует, мы покажем вам лучший контент.',
lang.descriptionIntro,
)}
<p>
Нажав «Принять все», Вы даете свое согласие
${pluralize(lang.companyNames.length, lang.company, lang.companies)}
Expand Down
7 changes: 5 additions & 2 deletions src/languages/sk.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
import { addSeparators, pluralize } from '../utils';
import { addSeparators, assembleDescriptionIntro, pluralize } from '../utils';
import { ExtraMessages, CookieConsentCategory } from '../types';
import { VanillaCookieConsent } from '../types/vanilla-cookieconsent';

Expand All @@ -20,7 +20,10 @@ export const config = (extraMessages: ExtraMessages): VanillaCookieConsent.Langu
consent_modal: {
title: lang.consentTitle ?? 'Vďaka Cookies budú naše stránky ešte lepšie',
description: `
<p>Presnejší obsah na mieru vám budeme zobrazovať, keď lepšie pochopíme, čo vás zaujíma.</p>
${assembleDescriptionIntro(
'Presnejší obsah na mieru vám budeme zobrazovať, keď lepšie pochopíme, čo vás zaujíma.',
lang.descriptionIntro,
)}
<p>
Kliknutím na tlačidlo „Prijať všetky“, čím dáte
${pluralize(lang.companyNames.length, lang.company, lang.companies)}
Expand Down
7 changes: 5 additions & 2 deletions src/languages/uk.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
import { addSeparators, pluralize } from '../utils';
import { addSeparators, assembleDescriptionIntro, pluralize } from '../utils';
import { ExtraMessages, CookieConsentCategory } from '../types';
import { VanillaCookieConsent } from '../types/vanilla-cookieconsent';

Expand All @@ -20,7 +20,10 @@ export const config = (extraMessages: ExtraMessages): VanillaCookieConsent.Langu
consent_modal: {
title: lang.consentTitle ?? 'Цей сайт використовує файли cookie',
description: `
<p>Якщо ми краще зрозуміємо, що вас цікавить, ми покажемо вам точніший контент.</p>
${assembleDescriptionIntro(
'Якщо ми краще зрозуміємо, що вас цікавить, ми покажемо вам точніший контент.',
lang.descriptionIntro,
)}
<p>
Натиснувши «Прийняти все», Ви даєте свою згоду
${pluralize(lang.companyNames.length, lang.company, lang.companies)}
Expand Down
9 changes: 5 additions & 4 deletions src/types/CookieConsentManager.ts
Original file line number Diff line number Diff line change
Expand Up @@ -19,6 +19,11 @@ export const enum DisplayMode {
SOFT = 'soft',
}

export type TranslationOverride = {
consentTitle: string;
descriptionIntro: string;
};

export type CookieConsentManagerOptions = {
defaultLang: string;
autodetectLang: boolean;
Expand All @@ -32,10 +37,6 @@ export type CookieConsentManagerOptions = {
config: VanillaCookieConsent.Options;
};

export type TranslationOverride = {
consentTitle: string;
};

export type CookieConsentManager = (
serviceName: string,
args?: Partial<CookieConsentManagerOptions>,
Expand Down
1 change: 1 addition & 0 deletions src/types/Messages.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
export interface ExtraMessages {
companyNames: string[];
consentTitle?: string;
descriptionIntro?: string;
}
6 changes: 6 additions & 0 deletions src/utils.ts
Original file line number Diff line number Diff line change
Expand Up @@ -12,3 +12,9 @@ export const addSeparators = (strings: string[], and: string = ''): string =>
});

export const pluralize = (count: number, singular: string, plural: string): string => (count === 1 ? singular : plural);

export const assembleDescriptionIntro = (defaultValue: string, overrideValue?: string): string => {
const descriptionIntro = overrideValue ?? defaultValue;

return descriptionIntro !== '' ? `<p>${descriptionIntro}</p>` : '';
};

0 comments on commit 1f6c31a

Please sign in to comment.