Compare commits

..

No commits in common. "main" and "ldcweb-cookies" have entirely different histories.

64 changed files with 10440 additions and 8067 deletions

View file

@ -3,22 +3,16 @@ root = true
[*]
charset = utf-8
end_of_line = lf
indent_size = 4
indent_style = space
insert_final_newline = true
indent_style = space
indent_size = 4
trim_trailing_whitespace = true
[*.md]
trim_trailing_whitespace = false
[*.{yml,yaml}]
indent_size = 2
[docker-compose.yml]
indent_size = 4
[*.vue]
indent_size = 2
[*.scss]
[*.{yml,yaml}]
indent_size = 2

1
.gitignore vendored
View file

@ -1,2 +1 @@
node_modules
dist

View file

@ -1,10 +0,0 @@
node_modules
.editorconfig
.babelrc
.gitattributes
.gitlab-ci.yml
.stylelintrc.json
jsconfig.json
rollup.config.js
tsconfig.json
webpack.config.cjs

View file

@ -4,13 +4,8 @@
"stylelint-config-sass-guidelines",
"stylelint-config-idiomatic-order"
],
"plugins": [
"stylelint-scss"
],
"files": [
"**/*.css",
"**/*.scss"
],
"plugins": ["stylelint-scss"],
"files": ["**/*.css", "**/*.scss"],
"ignoreFiles": [
"**/vendor/*.css",
"**/vendor/**/*.css",
@ -23,14 +18,12 @@
],
"customSyntax": "postcss-scss",
"rules": {
"declaration-property-value-no-unknown": true,
"selector-max-id": null,
"color-no-invalid-hex": true,
"order/properties-alphabetical-order": null,
"max-nesting-depth": 5,
"selector-max-compound-selectors": 5,
"declaration-colon-newline-after": null,
"value-list-comma-newline-after": null,
"scss/double-slash-comment-empty-line-before": [
"always",
{

View file

@ -1,124 +0,0 @@
## [6.0.3](///compare/6.0.2...6.0.3) (2024-07-03)
### Bug Fixes
* :bug: Cn Cookie expiration Date was renewd on page load instead of choice modifications 090e8e0
## [6.0.2](///compare/6.0.0...6.0.2) (2024-07-03)
### Bug Fixes
* :bug: Cookie CN was set in past date 63cd8d2
* :bug: FF attribute samesite 51384e9
## [6.0.0](///compare/5.0.7...6.0.0) (2024-06-17)
### Features
* Add cookie references to prevent weird cookie config from a project 17a5f3b
* Finally delete associated cookies correctly de42a12
### Bug Fixes
* acceptAllCookies and denyAllCookies methods error fix 02a573c
* CookieMotice.getCnCookieValues parsing wrongly 1c175c5
* CookieNotice configHasChanged wrong evaluation fix f601075
* denyAllWaitingCookies regression 23502f7
* DocumentCookie.set applying wrongly CnCookiePolicies e395df6
* DocumentCookies.getCookies would not trim elements 722b084
* fix and refactor CookieNotice constructor 4065147
* Move type on type.ts file and CookeNotice class on a dedicaced file 30bb793
## [5.0.7](///compare/5.0.6...5.0.7) (2024-06-06)
## [5.0.6](///compare/5.0.4...5.0.6) (2024-06-06)
### Bug Fixes
* stylelint positioning error f9054ec
## [5.0.4](///compare/5.0.3...5.0.4) (2024-06-04)
### Reverts
* Revert "feat: Cookies are indetermined by default (visually only)" 794ff14
## 5.0.3
- fix: 🐛 Click on toggle with trigger twice the toggle action
- refactor: ♻️ REmove unUsed bannerDetailsAreExapanded
## 5.0.2
- fix: 🐛 Cookie Modal list 'toggleCookie' was using wrong HTMLElement
## 5.0.1
- fix: 🐛 acceptCookie and denyCookie were trying to change domElements from cookie list event if not present
## 5.0.0
- fix: 🐛 Prevent modifying tabindexes inside cookie modal
- fix: 🐛 Cookie modal was overflowing on landscape mobile
- feat: fin de sélection le bouton actuel "Retour" modifié par le bouton "VALIDER ET FERMER"
- feat: ✨ Toggle switch instead of buttons
- feat: Cookies are indetermined by default (visually only)
## 4.1.1
- Fixed Scss button colors inverted variables
## 4.1.0
- Added possibility to activate a specific cookie (or deactivate) (example in Agis)
- Changed lang text for recaptcha
## 4.0.1
- Removed `font-weight: bolder` property on the accept button.
## 4.0.0
- Bump to major version in order to prevent breaking projects,
the bump cannot be done only using npm update, therefore the
developper has to change template and other fils in any specific project.
- Bump Npm dependencies to latest in order fix audit issues and so on.
- Add missing translations
## 3.1.3
- Update and add new sass variables to counter global font-size in project
## 3.1.2
- Add exemple for Wordpress
- Add notice for Wordress in readme.md
- Fix animation on open/close modal
## 3.1.1
- Accessibility corrections (Template examples are part of this)
- Correction to keyboard event for modifying cookies (keydown instead of keyup)
## 3.1.0
- Cookies lifespan will now be 6 month by default.
- The cookie date creation will be stored in the cookie it self, and deletion will be called by the lib if they are too old.
## 3.0.9
- Changed Now cookie button will ber smaller on mobile
- Changed Cookie button will now be more discrete
## 3.0.8
- Fix examples
- Fixed package json export files
## 3.0.7
- Fixed typing issue
- Release with browser compiled version
## 3.0.3
- Banner picture as autowith and contain.
- Build command fixed
## 3.0.2 Initial release as UMD + ESM

View file

@ -2,44 +2,32 @@
<div style="text-align: center;">
<!-- Link for icons : https://github.com/Ileriayo/markdown-badges -->
![Laravel](https://img.shields.io/badge/laravel-%23FF2D20.svg?style=for-the-badge&logo=laravel&logoColor=white)
![HTML5](https://img.shields.io/badge/html5-%23E34F26.svg?style=for-the-badge&logo=html5&logoColor=white)
![SASS](https://img.shields.io/badge/SASS-hotpink.svg?style=for-the-badge&logo=SASS&logoColor=white)
![TypeScript](https://img.shields.io/badge/typescript-%23007ACC.svg?style=for-the-badge&logo=typescript&logoColor=white)
![WordPress](https://img.shields.io/badge/WordPress-%23117AC9.svg?style=for-the-badge&logo=WordPress&logoColor=white)
![PHP](https://img.shields.io/badge/php-%23777BB4.svg?style=for-the-badge&logo=php&logoColor=white)
![CSS3](https://img.shields.io/badge/css3-%231572B6.svg?style=for-the-badge&logo=css3&logoColor=white)
![JavaScript](https://img.shields.io/badge/javascript-%23323330.svg?style=for-the-badge&logo=javascript&logoColor=%23F7DF1E)
</div>
## Exemples :
Voir dans le dossier `examples` pour **Laravel** et **Wordpress**.
Voir dans la dossier `exemples`.
Ici pour l'instant seulement un exemple pour **Laravel**.
## Étape 1 : implémentation
### Ajouter le package avec npm
- https://lab.s-web.fr/ldc-web/general/documentation/-/wikis/NPM-Private-package-registry
- https://docs.gitlab.com/ee/user/packages/npm_registry/
- https://lab.s-web.fr/ldc-web/projets/laravel-base-project/-/snippets/8
- `npm i @ldc-web/cookie-notice --save-dev`
[Lien doc Gitlab](https://docs.gitlab.com/ee/user/packages/npm_registry/)
## Browser
- Pour inclure directement dans le navigateur, les fichiers compilés sont dans `dist/browser`.
### Laravel
- Ajouter dans le projet, les fichiers au bon endroit :
- [`cn-cookies.blade.php`](./examples/laravel/cn-cookies.blade.php) dans le dossier `resources/view/vendor/`
- [`standard.blade.php`](./examples/laravel/templates/standard.blade.php) dans le dossier `resources/view/vendor/cookie-notice-templates`
- Inclure dans le layout général `@include('vendor.cn-cookies')`.
**Cela doit être avant le stack('scripts')**
- **!! Ne pas oublier de modifier les configurations dans le blade `vendor.cn-cookies`**.
- [`cn-cookies.blade.php`](./examples/cn-cookies.blade.php) dans le dossier `resources/view/vendor/`
- [`standard.blade.php`](./examples/templates/standard.blade.php) dans le dossier `resources/view/vendor/cookie-notice-templates`
- Inclure dans le layout general `@include('vendor.cn-cookies')`
- Ensuite inclure les éléments **style** et **script**
- **SCSS**
- SCSS
@import "~@ldc-web/cookie-notice";
// ou
@ -48,44 +36,12 @@ Voir dans le dossier `examples` pour **Laravel** et **Wordpress**.
@import "~@ldc-web/cookie-notice/src/scss/themes/standard";
- **TS/JS**
// Dans fo.ts
import type CookieNotice from "@ldc-web/cookie-notice";
window.CookieNotice = CookieNotice;
// Dans index.d.ts
...
@import "@ldc-web/cookie-notice"
import CookieNotice from "@ldc-web/cookie-notice";
declare global {
...
interface Window {
CookieNotice: typeof CookieNotice;
...
}
}
window.WebCookieNotice = CookieNotice;
### Wordpress
- Ajouter dans le projet, les fichiers au bon endroit :
- [`cn-cookies.php`](./examples/wordpress/cn-cookies.php) dans le dossier `resources/view/vendor/`
- [`standard.php`](./examples/wordpress/templates/standard.php) dans le dossier `resources/view/vendor/cookie-notice-templates`
- Inclure dans le footer général `<?php include('resources/views/vendor/cn-cookies.php'); ?>`.
- **!! Ne pas oublier de modifier les configurations dans le fichier `resources/views/vendor/cn-cookies`**.
- Ensuite inclure les éléments **style** et **script**
- **SCSS**
@import '../../node_modules/@ldc-web/cookie-notice';
## OU ##
- **CSS**
inclure directement le fichier compilé `cookie-cn.css` présent dans `dist/browser` dans le fichier css du projet
- **JS**
ajouter directement le fichier compilé `cookie-cn.js` présent dans `dist/browser` dans le fichier js du projet
**TODO: Add instructions for wordpress**
## Étape 2 : customisation
- Couleurs : Pour l'instant les variables **SASS** sont personalisables. Elle se trouvent ici [`node_modules/@ldc-web/cookie-notice/src/scss/variables.scss`](./src/scss/variables.scss)

8
changelog.md Normal file
View file

@ -0,0 +1,8 @@
# Changelog
## 3.0.3
*FIXED*
- Banner picture as autowith and contain.
- Build command fixed
## 3.0.2 Initial release as UMD + ESM

View file

@ -1,438 +0,0 @@
@charset "UTF-8";
:root {
--cs-primary-color: var();
}
/* Distance par rapport à la gauche de la fenêtre */
/* Distance par rapport à la droite de la fenêtre */
/* Distance par rapport au bas de la fenêtre */
/* Position gauche de base des cookies */
/* Position droite de base des cookies */
#cn-wrapper {
/* Buttons styles start */
/* Button styles end */
}
#cn-wrapper * {
box-sizing: border-box;
}
#cn-wrapper *::before {
display: none;
}
#cn-wrapper button {
display: inline-block;
padding: 0.2rem 0.5rem;
border: 0;
margin: 0;
appearance: none;
background: #d6d6d6;
color: #000;
cursor: pointer;
font-family: "Barlow", sans-serif;
font-size: 1rem;
line-height: 1;
text-align: center;
text-decoration: none;
transition: background 250ms ease-in-out, transform 150ms ease;
}
#cn-wrapper button:hover,
#cn-wrapper button:focus {
background: #bdbdbd;
/* prettier-ignore */
color: #000;
}
#cn-wrapper button:focus {
outline: 1px solid;
/* prettier-ignore */
outline-color: #000;
outline-offset: -4px;
}
#cn-wrapper button:active {
transform: scale(0.99);
}
/* FENETRE D'ACCUEIL */
/* Title settings */
/* Text settings */
/* Button settings */
/* Title settings */
/* Text settings */
/* Switch Buttons */
/* Cookies list settings */
/* Size */
#cn-wrapper .cn-nav #cn-settings-banner, #cn-wrapper .cn-nav #cn-accept-banner, #cn-wrapper .cn-nav #cn-deny-banner, #cn-wrapper #cn-banner .cn-modal-top-line #cn-close-modal {
display: flex;
height: 3rem;
flex-direction: column;
align-items: center;
justify-content: center;
padding: 0;
background-color: #d6d6d6;
color: #000;
font-family: "Barlow", sans-serif;
font-size: 16px;
}
#cn-wrapper .cn-nav #cn-settings-banner:hover, #cn-wrapper .cn-nav #cn-accept-banner:hover, #cn-wrapper .cn-nav #cn-deny-banner:hover, #cn-wrapper #cn-banner .cn-modal-top-line #cn-close-modal:hover, #cn-wrapper .cn-nav #cn-settings-banner:focus, #cn-wrapper .cn-nav #cn-accept-banner:focus, #cn-wrapper .cn-nav #cn-deny-banner:focus, #cn-wrapper #cn-banner .cn-modal-top-line #cn-close-modal:focus {
background-color: #bdbdbd;
/* prettier-ignore */
color: #000;
}
#cn-wrapper .cn-nav #cn-settings-banner:focus, #cn-wrapper .cn-nav #cn-accept-banner:focus, #cn-wrapper .cn-nav #cn-deny-banner:focus, #cn-wrapper #cn-banner .cn-modal-top-line #cn-close-modal:focus {
/* prettier-ignore */
outline-color: #000;
}
.cn-modal-bg {
position: fixed;
z-index: 1030;
top: 0;
left: 0;
width: 100vw;
height: 100dvh;
background-color: rgba(0, 0, 0, 0.6);
cursor: pointer;
opacity: 0;
transition: 0.3s;
visibility: hidden;
}
.cn-modal-bg-active {
cursor: default;
}
.cn-open .cn-modal-bg {
opacity: 1;
visibility: visible;
}
.cn-disabled {
pointer-events: none;
}
#cn-wrapper {
position: fixed;
z-index: 1050;
top: 0;
left: 0;
width: 100vw;
height: 100dvh;
pointer-events: none;
}
#cn-wrapper #cn-cookie-btn {
position: fixed;
right: auto;
bottom: 0.5rem;
left: 0.5rem;
width: 2.4rem;
height: 2.4rem;
padding: 0.3rem;
border-radius: 100%;
background-color: #fff;
box-shadow: 0 0.1rem 1rem rgba(0, 0, 0, 0.35);
cursor: pointer;
pointer-events: auto;
}
@media (min-width: 535px) {
#cn-wrapper #cn-cookie-btn {
right: auto;
bottom: -1.5rem;
left: -1.5rem;
width: 3rem;
height: 3rem;
padding: 0.5rem;
transition: all 1s 6s;
}
#cn-wrapper #cn-cookie-btn:hover, #cn-wrapper #cn-cookie-btn:focus {
right: auto;
bottom: 0.5rem;
left: 0.5rem;
transition: all 1s;
}
}
#cn-wrapper #cn-cookie-btn:focus {
outline-color: #d1842a;
outline-offset: 0.1rem;
outline-width: 0.2rem;
}
#cn-wrapper #cn-cookie-btn-icon path {
fill: #dc9c52;
}
#cn-wrapper #cn-cookie-btn-icon circle {
fill: #dc9c52;
}
#cn-wrapper #cn-banner {
position: absolute;
z-index: 1050;
top: 0;
bottom: 0;
left: 0;
display: flex;
width: 100vw;
max-height: 100dvh;
flex-direction: column;
align-items: center;
justify-content: space-between;
padding: 0;
border-radius: 0;
margin: auto;
margin-bottom: 0;
background-color: #fff;
box-shadow: 0 0.1rem 1rem rgba(0, 0, 0, 0.35);
line-height: initial;
opacity: 0;
pointer-events: none;
transition: 0.3s;
user-select: none;
visibility: hidden;
}
#cn-wrapper #cn-banner .cn-modal-top-line {
align-self: end;
}
#cn-wrapper #cn-banner .cn-modal-top-line #cn-close-modal {
width: 4rem;
height: 3rem;
border-bottom-left-radius: 0.5rem;
}
@media (min-width: 535px) {
#cn-wrapper #cn-banner .cn-modal-top-line #cn-close-modal {
border-top-right-radius: 0.5rem;
}
}
#cn-wrapper #cn-banner > * {
pointer-events: all;
}
@media (min-width: 535px) {
#cn-wrapper #cn-banner {
right: auto;
bottom: calc(0.5rem + 60px);
left: 0;
width: 30rem;
max-height: 26rem;
border-radius: 0.5rem;
}
#cn-wrapper #cn-banner.cn-modal-page {
max-height: 38rem;
}
}
#cn-wrapper #cn-li-template {
display: none;
}
#cn-wrapper .d-none {
display: none !important;
}
#cn-wrapper .cn-content {
flex-basis: 100%;
flex-grow: 1;
padding: 0.8rem;
overflow-y: auto;
}
@media (min-width: 535px) {
#cn-wrapper .cn-content {
flex-grow: 0;
}
}
#cn-wrapper .cn-content .cn-switch {
position: relative;
display: inline-block;
overflow: hidden;
width: 4.2rem;
height: 2.4rem;
box-sizing: content-box;
cursor: pointer;
}
#cn-wrapper .cn-content .cn-switch:focus, #cn-wrapper .cn-content .cn-switch:focus-visible {
border-width: 0.1rem;
border-style: solid;
border-color: #dc9c52;
}
#cn-wrapper .cn-content .cn-switch input {
display: none;
}
#cn-wrapper .cn-content .cn-switch input + span {
position: absolute;
border-radius: 2rem;
background: #b7b7b7;
inset: 0;
}
#cn-wrapper .cn-content .cn-switch input + span::before {
position: absolute;
top: 50%;
left: 0.21rem;
display: inline-block;
width: 1.8rem;
height: 1.8rem;
border-radius: 50%;
background: #fff;
content: "";
transform: translateY(-50%);
transition: all 0.5s;
}
#cn-wrapper .cn-content .cn-switch input:indeterminate + span {
background: #b7b7b7;
}
#cn-wrapper .cn-content .cn-switch input:indeterminate + span::before {
left: 1.08rem;
}
#cn-wrapper .cn-content .cn-switch input:checked + span {
background: #dc9c52;
}
#cn-wrapper .cn-content .cn-switch input:checked + span::before {
left: 2.16rem;
}
#cn-wrapper .cn-content .cn-banner-content {
display: flex;
min-height: 100%;
flex-direction: column;
color: #707070;
font-family: "Barlow", sans-serif;
font-size: 16px;
}
@media (min-width: 535px) {
#cn-wrapper .cn-content .cn-banner-content {
flex-flow: row wrap;
align-items: center;
}
#cn-wrapper .cn-content .cn-banner-content .cn-banner-img {
width: 33%;
}
#cn-wrapper .cn-content .cn-banner-content .cn-banner-text {
width: 66%;
}
}
#cn-wrapper .cn-content .cn-banner-content .cn-banner-img {
text-align: center;
}
#cn-wrapper .cn-content .cn-banner-content .cn-banner-img img {
width: 90%;
object-fit: contain;
}
#cn-wrapper .cn-content .cn-banner-content .cn-banner-text .cn-banner-title {
color: #dc9c52;
font-family: "Satisfy", sans-serif;
font-size: 28px;
font-weight: bold;
line-height: inherit;
text-align: left;
}
#cn-wrapper .cn-content .cn-banner-content .cn-banner-text .cn-banner-para-p {
margin: 6px 0;
text-align: justify;
}
#cn-wrapper .cn-content .cn-modal-container {
position: relative;
display: flex;
overflow: auto;
flex-direction: column;
align-items: center;
/* stylelint-disable-next-line no-descending-specificity */
}
#cn-wrapper .cn-content .cn-modal-container ul {
display: flex;
flex-direction: column;
padding: 0;
margin: 0;
list-style: none;
}
#cn-wrapper .cn-content .cn-modal-container .cn-cookie-wrapper {
display: flex;
flex-direction: row;
align-items: center;
justify-content: space-between;
padding: 20px;
border: 1px solid #e4e4e4;
border-radius: 20px;
margin: 10px 0;
}
#cn-wrapper .cn-content .cn-modal-container span {
color: #dc9c52;
font-family: "Barlow", sans-serif;
font-size: 16px;
}
#cn-wrapper .cn-content .cn-modal-container a {
font-family: "Barlow", sans-serif;
font-size: 16px;
}
#cn-wrapper .cn-content .cn-modal-container label {
color: #dc9c52;
font-family: "Barlow", sans-serif;
font-size: 16px;
}
#cn-wrapper .cn-content .cn-modal-container .cn-cookie-name {
color: #dc9c52;
}
#cn-wrapper .cn-content .cn-modal-container .cn-cookie-infos {
display: flex;
width: 100%;
flex: 1;
flex-direction: column;
}
#cn-wrapper .cn-content .cn-modal-container .cn-cookie-infos span:first-of-type {
font-size: calc(16px * 1.25);
font-weight: bold;
}
#cn-wrapper .cn-content .cn-modal-container .cn-cookie-infos .cn-cookie-description {
color: #707070;
}
#cn-wrapper .cn-content .cn-modal-container .cn-cookie-infos a {
width: fit-content;
}
#cn-wrapper .cn-nav {
display: flex;
overflow: hidden;
width: 100%;
height: 6rem;
flex-shrink: 0;
flex-wrap: wrap;
align-items: center;
border-top: 1px solid #6d6d6d;
}
#cn-wrapper .cn-nav #cn-deny-banner {
width: 50%;
}
#cn-wrapper .cn-nav #cn-accept-banner {
width: 50%;
border-right: 1px solid #6d6d6d;
border-left: 1px solid #6d6d6d;
}
#cn-wrapper .cn-nav #cn-settings-banner {
width: 100%;
border-top: 1px solid #6d6d6d;
}
@media (min-width: 535px) {
#cn-wrapper .cn-nav {
height: 3rem;
flex-wrap: initial;
border-bottom-left-radius: 0.5rem;
border-bottom-right-radius: 0.5rem;
}
#cn-wrapper .cn-nav #cn-deny-banner {
width: 33.33%;
}
#cn-wrapper .cn-nav #cn-accept-banner {
width: 33.33%;
}
#cn-wrapper .cn-nav #cn-settings-banner {
width: 33.33%;
border-top: initial;
}
}
.cn-open {
overflow: hidden !important;
}
.cn-open #cn-wrapper #cn-banner {
opacity: 1;
visibility: visible;
}
@media (min-width: 535px) {
.cn-open #cn-wrapper #cn-banner {
right: auto;
left: 0.5rem;
}
}
@media (min-width: 535px) {
.cn-open #cn-wrapper #cn-cookie-btn {
right: auto;
bottom: 0.5rem;
left: 0.5rem;
transition: all 1s;
}
}

File diff suppressed because one or more lines are too long

View file

@ -1,128 +0,0 @@
import { CookieOptions as CnCookieConfig } from "../type";
export default class CookieNotice {
private config;
/** The CN cookie status */
private cookieName;
/** Cookie life time */
private cookieTimeLife;
/** The index on which store the expiration date */
private cookieExpirationName;
/** Cookie policies for each functionality */
private cookiePolicies;
/** Prevent user from closing modal */
private restrictCloseModal;
/** Cookie expiration date as specified in the cookie itself */
private cookieExpirationDate;
private domElList;
/**
* @param config Holding all cookie configs
*/
constructor(config: Record<string, CnCookieConfig>);
/** Accept a all cookies */
acceptAllCookies(): void;
/** Accept a specific cookie */
acceptCookie(cookieName: string): void;
/** Deny a all cookies */
denyAllCookies(): void;
/** Deny a specific cookie */
denyCookie(cookieName: string): void;
/** Deny all waiting cookies */
denyAllWaitingCookies(): void;
/**
* Get a specific cookie config
* @throws {Error} If the cookie `cookieName` is not found in config.
*/
getCookieConfig(cookieName: string): CnCookieConfig;
/** Check if the config has expired */
private configHasExpired;
/** Check if the actual cookie config matches the CN config */
private configHasChanged;
/**
* Invert cookie status
*
* @param cookieStatus
* @returns Inverted cookie status, `wait` will give `false`.
* @throw {Error} If the cookie status is not handled.
*/
private invertCookieStatus;
/** Get a new expiration date */
private getNewExpirationDate;
private getCnCookieInfo;
/**
* Get a cookie status
*
* @param cookieName
* @throws {Error} If the cookie value could not be found.
*/
private getCnCookieStatus;
/** Trigger cookie status actions and persist status */
private setCnCookieStatus;
/** Save cookie content on web browser */
private persistCnCookieList;
/** Bump CN expiration date */
private refreshCnCookieExpirationDate;
/** Read CN cookie values */
private getCnCookieValues;
/** Reset Cookie status list */
private resetCnCookie;
/** Change the status of a cookie */
private persistCnCookie;
/**
* Add event on a specific element
*
* @param element
* @param evnt
* @param funct
* @returns
*/
private addEvent;
/**
* Add event on a specific element and prevent default
*
* @param element
* @param evnt
* @param funct
*/
private addEventPrevent;
/**
* Add event on a specific element
*
* @param element A HTMLElement on which the should should be bound.
* @param funct A closure for the event hanling.
*/
private addEventKbdValidate;
private setCookieSwitchButton;
/** Update restrict for closing cookie modal */
private updateRestrictCloseModal;
/** Show or hide Cookie modal */
private toggleCookieModal;
/** Open the cookies modal to the banner page */
private openCookieModalToBannerPage;
/** Open the cookies modal to the cookies page */
private openCookieModalToCookiePage;
/** Hide the cookies modal */
private closeCookieModal;
/** Setup tab indexes on visible elements */
private setTabIndex;
/** Undo setup tab indexes on visible elements */
private unsetTabIndex;
/** Reset the modal view state */
private resetCookieModal;
/** Set the cookies list in the modal */
private setupCookieModalList;
private switchToModalPageOrClose;
/** Toggle Cookie modal pages */
private toggleCookieModalPages;
/** Toggle customize btn */
private toggleCustomizeBtn;
/** Get the actual page: banner or modal (with cookie choices) */
private isOnBannerPage;
/** Setup Events */
private setupEvents;
/** Get dom element */
private getDomEl;
/** Init a Dom cookie switch */
private initDomCookieSwitch;
/** Init Dom elements selector */
private initDomElements;
}

View file

@ -1,13 +0,0 @@
import { CnCookiePolicies } from "../type";
export declare abstract class DocumentCookie {
static has(cookieName: string): boolean;
static get(cookieName: string): string | undefined;
static set(cookieName: string, value: string, date?: Date | null, cookiePolicies?: CnCookiePolicies | null): void;
static getAllStartingWith(cookieNameStartingPart: string): Map<string, string>;
/**
* Set an older expire parameter to a specific cookie
*/
static markForDeletion(cookieName: string): void;
/** Fetch browser cookies except(http-only ones) the cannot be handled using js */
private static getCookies;
}

View file

@ -1,14 +0,0 @@
import { CnCookiePolicies } from "./type";
declare const defaults: {
/** The CN cookie status */
cookieName: string;
/** Cookie life time */
cookieTimeLife: number;
/** The index on which store the expiration date */
cookieExpirationName: "_expiration";
/** Cookie policies for each functionality */
cookiePolicies: CnCookiePolicies;
/** Prevent user from closing modal */
restrictCloseModal: boolean;
};
export default defaults;

View file

@ -1,2 +0,0 @@
declare const _default: Map<string, string[]>;
export default _default;

View file

@ -1,12 +0,0 @@
/** A cookie status as written in the cn cookie */
export declare enum CookieStatus {
true = "true",
false = "false",
wait = "wait"
}
/** A cookie Policy same site */
export declare enum CookiePolicySameSite {
lax = "lax",
strict = "strict",
none = "none"
}

View file

@ -1,7 +0,0 @@
import CookieNotice from "../classes/CookieNotice";
import "./../../scss/themes/standard.scss";
declare global {
interface Window {
CookieNotice: typeof CookieNotice;
}
}

View file

@ -1,2 +0,0 @@
import CookieNotice from "./classes/CookieNotice";
export default CookieNotice;

View file

@ -1,49 +0,0 @@
import type { CookiePolicySameSite, CookieStatus } from "./enums";
export type CookieStatusList = Record<string, CookieStatus>;
export type CookieOptions = {
/** The cookie name as an index that can be referred to */
name: string;
/** A string description of the cookie */
description: string;
/** A link of the cookie policy */
link: string;
/** A link label for the (learn more about link) */
labelLink: string;
/**
* The cookies indexes that are concerned
* they should really match.
* Some references
* @link https://github.com/AmauriC/tarteaucitron.js/blob/5a2252baa117b75c1143af635ed4f52c5b0afb5b/tarteaucitron.services.js#L4700
* @link https://developers.google.com/recaptcha/docs/faq?hl=fr
* @link https://cookiedatabase.org/service/vimeo/
* @link https://vimeo.com/cookie_policy
* @link https://policies.google.com/technologies/cookies?hl=en
*/
cookies: string[];
/**
* Fonction qui sert à initialiser la fonctionnalité
* conduisant à la génération du cookie
* @return void
*/
script: () => void;
/**
* Fonction qui sert à informer l'utilisateur
* sur chaque élèment que le cookie
* associé à la fonctionnalité
* est désactivé et propose un lien sur
* cookie notice pour l'activer
* @return void
*/
fallback: () => void | null;
};
export type CnCookiePolicies = {
sameSite: CookiePolicySameSite;
secure: boolean;
};
export type CnCookieValues = Map<string, CookieStatus>;
export type CnCookieInfo = {
name: string;
values: CnCookieValues;
date: Date;
cookiePolicies: CnCookiePolicies;
};

594
dist/esm/index.js vendored Normal file
View file

@ -0,0 +1,594 @@
export default class CookieNotice {
constructor(config) {
this.browserCookieName = "cn-init";
this.cookiePolicies = {
sameSite: CookiePolicySameSite.lax,
secure: "",
};
// * Setup Config
this.config = config;
// * Inject DOM modal BG
const modalBg = document.createElement("div");
modalBg.classList.add("cn-modal-bg");
document.body.append(modalBg);
this.modalBg = modalBg;
// * Setup Dom Elements
const cookieContainer = document.querySelector("div#cn-wrapper"), cookieShowModalBtn = document.querySelector("button#cn-cookie-btn"), cookieCloseModalBtn = document.querySelector("button#cn-close-modal"), cookieLinkShowCustomizeModalPageList = document.querySelectorAll("a.cn-cookie-link"), bannerContainer = document.querySelector("div#cn-banner"), bannerContent = document.querySelector("div.cn-banner-content"), bannerDetails = document.querySelector("div.cn-banner-details"), bannerParaP = document.querySelector("div.cn-banner-para-p"), detailsTextOpen = document.querySelector("p.cn-banner-para-p-open"), detailsTextClose = document.querySelector("p.cn-banner-para-p-close"), bannerDetailsCollapseBtn = document.querySelector("button.cn-banner-btn-details-p"), bannerDetailsContainer = document.querySelector("div.cn-banner-btn-details"), modalContainer = document.querySelector("div.cn-modal-container"), acceptAllBtn = document.querySelector("button#cn-accept-banner"), denyAllBtn = document.querySelector("button#cn-deny-banner"), customizeBtn = document.querySelector("button#cn-settings-banner"), cookiesUnorderedList = document.querySelector("ul#cn-modal-list"), modalWrapper = document.querySelector("div.cn-modal-wrapper"), template = document.querySelector("div#cn-li-template");
if (!cookieContainer) {
throw new Error("Cannot find div#cn-wrapper");
}
if (!cookieShowModalBtn) {
throw new Error("Cannot find 'button#cn-cookie-btn' element");
}
if (!cookieCloseModalBtn) {
throw new Error("Cannot find 'button#cn-close-modal' element");
}
if (!bannerContainer) {
throw new Error("Cannot find 'div#cn-banner' element");
}
if (!bannerContent) {
throw new Error("Cannot find 'div.cn-banner-content' element");
}
if (!bannerDetails) {
throw new Error("Cannot find 'div.cn-banner-details' element");
}
if (!bannerParaP) {
throw new Error("Cannot find 'div.cn-banner-para-p' element");
}
if (!detailsTextOpen) {
throw new Error("Cannot find 'p.cn-banner-para-p-open' element");
}
if (!detailsTextClose) {
throw new Error("Cannot find 'p.cn-banner-para-p-close' element");
}
if (!bannerDetailsCollapseBtn) {
throw new Error("Cannot find 'button.cn-banner-btn-details-p' element");
}
if (!bannerDetailsContainer) {
throw new Error("Cannot find '.cn-banner-btn-details' element");
}
if (!modalContainer) {
throw new Error("Cannot find 'div.cn-modal-container' element");
}
if (!acceptAllBtn) {
throw new Error("Cannot find 'button#cn-accept-banner' element");
}
if (!denyAllBtn) {
throw new Error("Cannot find 'button#cn-deny-banner' element");
}
if (!customizeBtn) {
throw new Error("Cannot find 'button.cn-settings-banner' element");
}
if (!cookiesUnorderedList) {
throw new Error("Cannot find 'ul#cn-modal-list' element");
}
if (!modalWrapper) {
throw new Error("Cannot find 'div.cn-modal-wrapper' element");
}
if (!template) {
throw new Error("Cannot find 'div#cn-li-template' element");
}
this.cookieShowModalBtn = cookieShowModalBtn;
this.cookieCloseModalBtn = cookieCloseModalBtn;
this.cookieLinkShowCustomizeModalList =
cookieLinkShowCustomizeModalPageList;
this.cookieContainer = cookieContainer;
this.bannerDetailsContainer = bannerDetailsContainer;
this.bannerContainer = bannerContainer;
this.bannerContent = bannerContent;
this.cookiesUnorderedList = cookiesUnorderedList;
this.modalWrapper = modalWrapper;
this.bannerParaP = bannerParaP;
this.detailsTextOpen = detailsTextOpen;
this.detailsTextClose = detailsTextClose;
this.bannerDetails = bannerDetails;
this.bannerDetailsCollapseBtn = bannerDetailsCollapseBtn;
this.modalContainer = modalContainer;
this.acceptAllBtn = acceptAllBtn;
this.denyAllBtn = denyAllBtn;
this.customizeBtn = customizeBtn;
this.bannerDetailsAreExpanded = false;
this.template = template;
const memoryTemplate = this.template.cloneNode(true);
this.template.remove();
this.template = memoryTemplate;
// * Setup Events
this.addEventPrevent(this.modalBg, "click", this.closeCookieModal);
this.addEventPrevent(this.cookieCloseModalBtn, "click", this.closeCookieModal);
this.addEventPrevent(this.acceptAllBtn, "click", this.acceptAllCookies);
this.addEventPrevent(this.denyAllBtn, "click", this.denyAllCookies);
this.addEventPrevent(this.customizeBtn, "click", this.toggleCookieModalPages);
this.addEventPrevent(this.bannerDetailsCollapseBtn, "click", this.toggleBannerDetails);
this.addEventPrevent(this.cookieShowModalBtn, "click", this.toggleCookieModal);
this.cookieLinkShowCustomizeModalList.forEach((cookieLink) => {
this.addEventPrevent(cookieLink, "click", this.openCookieModalToCookiePage);
});
// * Setup CN Cookie
if (!this.cookiesMatchesConfig()) {
// * Setup Browser Cookie if none.
this.resetBrowserCookie();
this.openCookieModalToBannerPage();
}
// * Cookie should have been created from here.
const cookies = this.getCookieStatusList();
Object.entries(cookies).forEach(([cookieName, cookieStatus]) => {
if (cookieStatus === CookieStatus.wait) {
// * Open modal if any cookie config is not set.
this.openCookieModalToBannerPage();
return;
}
if (!this.config[cookieName]) {
// * Ignore missing config
return;
}
if (cookieStatus === CookieStatus.true) {
// * Exec script part for accepted cookie.
this.config[cookieName].script();
return;
}
if (this.config[cookieName].fallback != null) {
// * Exec fallback part for accepted cookie if provided.
this.config[cookieName].fallback();
}
});
}
// COOKIES
/**
* Check if the actual cookie matches the config
*/
cookiesMatchesConfig() {
const cookies = this.getCookieStatusList();
return Object.keys(cookies).length === Object.keys(this.config).length;
}
/**
* Accept a specific cookie
*/
acceptAllCookies() {
Object.entries(this.config).forEach(([cookieName, cookieOption]) => this.setCookieStatus(cookieName, CookieStatus.true, cookieOption));
for (const acceptLabel of this.cookieContainer.querySelectorAll(".accept > label")) {
acceptLabel.classList.add("active");
}
for (const denyLabel of this.cookieContainer.querySelectorAll(".deny > label")) {
denyLabel.classList.remove("active");
}
this.closeCookieModal();
}
/**
* Deny a specific cookie
*/
denyAllCookies() {
Object.entries(this.config).forEach(([cookieName, cookieOption]) => this.setCookieStatus(cookieName, CookieStatus.false, cookieOption));
for (const acceptLabel of this.cookieContainer.querySelectorAll(".accept > label")) {
acceptLabel.classList.remove("active");
}
for (const denyLabel of this.cookieContainer.querySelectorAll(".deny > label")) {
denyLabel.classList.add("active");
}
this.closeCookieModal();
}
/**
* Fetch the cookie status list
*
* @returns the cookie status list
*/
getCookieStatusList() {
const cookies = this.getBrowserCookieValue(), statusList = {};
if (cookies === undefined) {
return statusList;
}
/** specificCookieString contains youtube=true like */
cookies.split(",").forEach((specificCookieString) => {
const values = specificCookieString.split("=");
statusList[values[0]] = values[1];
});
return statusList;
}
/**
* Check has cookie status
*
* @param key
* @param value
*/
containsCookieStatus(key) {
const statusList = this.getCookieStatusList();
return (Object.keys(statusList).find((cookieName) => cookieName === key) !==
undefined);
}
/**
* Set the cookie value
*
* @param cookieName
* @param status
* @param cookieOption
*/
setCookieStatus(cookieName, status, cookieOption) {
if (status === CookieStatus.true) {
this.addCookieStatus(cookieName, cookieOption);
return;
}
if (status === CookieStatus.false) {
this.removeCookieStatus(cookieName, cookieOption);
return;
}
this.setBrowserCookieStatus(cookieName, CookieStatus.wait);
}
/**
* Add a specific cookie and
* change his status to true
*
* @param cookieName
* @param cookieOption
*/
addCookieStatus(cookieName, cookieOption) {
if (cookieOption.script) {
cookieOption.script();
}
this.setBrowserCookieStatus(cookieName, CookieStatus.true);
}
/**
* Remove a specific cookie and
* change his status to false
*
* @param cookieName
* @param cookieOption
*/
removeCookieStatus(cookieName, cookieOption) {
const cookieNameElement = document.getElementById(cookieName);
if (cookieNameElement) {
cookieNameElement.remove();
}
if (cookieOption.fallback) {
cookieOption.fallback();
}
this.setBrowserCookieStatus(cookieName, CookieStatus.false);
}
/**
* Change the status of a cookie
*
* @param cookieName
* @param status
*/
setBrowserCookieStatus(cookieName, status) {
const statusList = this.getCookieStatusList();
// * Force refresh
this.deleteBrowserCookie();
statusList[cookieName] = status;
this.saveBrowserCookie(statusList);
}
/**
* Has CN cokie setup ?
* @returns true if the cookie is setup
*/
hasBrowserCookie() {
return Boolean(this.getBrowserCookieValue());
}
/**
* Get the Ldcweb cookie
*
* @returns A string like analytics=true,youtube=true or undefined
*/
getBrowserCookieValue() {
const matches = document.cookie.match(new RegExp("(?:^|; )" +
this.browserCookieName.replace(/([.$?*|{}()[\]\\/+^])/g, "\\$1") +
"=([^;]*)"));
return matches ? decodeURIComponent(matches[1]) : undefined;
}
/**
* Save cookie content on web browser
*
* @param list
*/
saveBrowserCookie(statusList) {
const date = new Date(), newDate = new Date(date.setMonth(date.getMonth() + 13)), content = Object.entries(statusList)
.map(([cookieName, cookieStatus]) => {
return `${cookieName}=${cookieStatus}`;
})
.join(",");
document.cookie = `${this.browserCookieName}=${content};path=/${location.hostname ? `;domain=${location.hostname}` : ""};expires=${newDate.toUTCString()};${this.getCookiePoliciesAsString()}`;
}
/**
* Set an older expire parameter to a specific cookie
*/
deleteBrowserCookie() {
if (this.hasBrowserCookie()) {
// * Suppression du cookie et de sa version precedé d'un point
document.cookie = `${this.browserCookieName}=;path=/${location.hostname ? `;domain=.${location.hostname}` : ""};expires=Thu, 01 Jan 1970 00:00:01 GMT;${this.getCookiePoliciesAsString()}`;
document.cookie = `${this.browserCookieName}=;path=/${location.hostname ? `;domain=${location.hostname}` : ""};expires=Thu, 01 Jan 1970 00:00:01 GMT;${this.getCookiePoliciesAsString()}`;
}
}
getCookiePoliciesAsString() {
return Object.entries(this.cookiePolicies)
.map(([policyName, policyValue]) => `${policyName}=${policyValue}`)
.join(";");
}
/**
* Reset Ldc Web CN cookie
*/
resetBrowserCookie() {
// * Create Cookie as It does not exists.
const newCookieList = {};
Object.entries(this.config).forEach(([cookieName]) => (newCookieList[cookieName] = CookieStatus.wait));
this.saveBrowserCookie(newCookieList);
}
// LISTENERS
/**
* Add event on a specific element
*
* @param element
* @param evnt
* @param funct
* @returns
*/
addEvent(element, evnt, funct) {
return element.addEventListener(evnt, funct.bind(this), false);
}
/**
* Add event on a specific element and prevent default
*
* @param element
* @param evnt
* @param funct
* @returns
*/
addEventPrevent(element, evnt, funct) {
return element.addEventListener(evnt, (e) => {
e.preventDefault();
funct.call(this, e);
}, false);
}
/**
* Add event on a specific element
*
* @param element
* @param evnt
* @param funct
* @returns
*/
addEventKbdValidate(element, funct) {
return this.addEvent(element, "keyup", (e) => {
const kbdEvt = e;
if (kbdEvt.key == " " ||
kbdEvt.code == "Space" ||
kbdEvt.keyCode == 32 ||
kbdEvt.key == "Enter" ||
kbdEvt.code == "Enter" ||
kbdEvt.keyCode == 13) {
funct.call(this, kbdEvt);
}
});
}
// COOKIE MODAL
/**
* Show or hide Cookie modal
* @returns
*/
toggleCookieModal() {
if (!document.body.classList.contains("cn-open")) {
this.openCookieModalToBannerPage();
return;
}
this.closeCookieModal();
}
/**
* Open the cookies modal to the banner page
*/
openCookieModalToBannerPage() {
this.openCookieModalToCookiePage();
this.toggleCookieModalPages();
}
/**
* Open the cookies modal to the cookies page
*/
openCookieModalToCookiePage() {
document.body.classList.add("cn-open");
this.resetCookieModal();
this.bannerContent.classList.add("d-none");
this.bannerDetails.classList.add("d-none");
this.bannerDetailsContainer.classList.add("d-none");
this.modalContainer.classList.remove("d-none");
// Scroll to the top of the cookies list
this.modalWrapper.scrollTop = 0;
this.setupCookieModalList();
this.setTabIndex();
}
/**
* Hide the cookies modal
*/
closeCookieModal() {
document.body.classList.remove("cn-open");
this.bannerContent.classList.toggle("d-none");
this.bannerDetails.classList.toggle("d-none");
this.bannerDetailsContainer.classList.toggle("d-none");
this.modalContainer.classList.toggle("d-none");
this.unsetTabIndex();
this.setupCookieModalList();
}
/**
* Setup tab indexes on visible elements
*/
setTabIndex() {
// * Prevent focus html tag
document.documentElement.setAttribute("tabindex", "-1");
setTimeout(() => {
const focusableSelector = "a[href], button, [role=\"button\"], input, embed, object, iframe, textarea, select, details, [tabindex]:not([tabindex=\"-1\"])";
// * Only focusable elements
[...document.body.querySelectorAll(focusableSelector)]
.filter((el) => !el.hasAttribute("disabled") &&
!el.getAttribute("aria-hidden"))
.forEach((el) => {
el.setAttribute("tabindex", "-1");
el.classList.add("cn-disabled");
});
[...this.cookieContainer.querySelectorAll(focusableSelector)]
.filter((el) => !el.hasAttribute("disabled") &&
!el.getAttribute("aria-hidden") &&
// * Only visible elements
!!(el.offsetWidth ||
el.offsetHeight ||
el.getClientRects().length))
.forEach((el) => {
el.setAttribute("tabindex", "0");
el.classList.remove("cn-disabled");
});
this.cookieShowModalBtn.setAttribute("tabindex", "-1");
}, 500);
}
/**
* Undo setup tab indexes on visible elements
*/
unsetTabIndex() {
document.documentElement.setAttribute("tabindex", "0");
setTimeout(() => {
document.body.querySelectorAll(".cn-disabled").forEach((el) => {
el.setAttribute("tabindex", "0");
el.classList.remove("cn-disabled");
});
this.cookieShowModalBtn.setAttribute("tabindex", "0");
}, 500);
}
/**
* Reset the modal view state
*/
resetCookieModal() {
this.bannerContent.classList.remove("d-none");
this.bannerDetails.classList.remove("d-none");
this.bannerDetailsContainer.classList.remove("d-none");
this.modalContainer.classList.add("d-none");
if (!this.customizeBtn.dataset.openModal) {
throw new Error("Cannot find attribut data-open-modal");
}
this.customizeBtn.innerHTML = this.customizeBtn.dataset.openModal;
}
/**
* Set the cookies list in the modal
*/
setupCookieModalList() {
this.cookiesUnorderedList.innerHTML = "";
Object.entries(this.config).forEach(([cookieName, cookieConfig]) => {
const cookie = document.createElement("li");
const childItem = this.template.children.item(0);
if (childItem === null) {
throw new Error("Cannot find child item");
}
cookie.append(childItem.cloneNode(true));
const name = cookie.querySelector("span.cn-cookie-name");
const description = cookie.querySelector("span.cn-cookie-description");
const link = cookie.querySelector(".cn-cookie-link");
const acceptInput = cookie.querySelector(".accept > input");
const denyInput = cookie.querySelector(".deny > input");
const acceptLabel = cookie.querySelector(".accept > label");
const denyLabel = cookie.querySelector(".deny > label");
name.textContent = cookieConfig.name;
description.textContent = cookieConfig.description;
link.textContent = cookieConfig.labelLink;
link.setAttribute("href", cookieConfig.link);
acceptInput.id = cookieName + "1";
acceptInput.name = cookieName;
acceptInput.dataset.name = cookieName;
acceptLabel.htmlFor = cookieName + "1";
denyInput.id = cookieName + "2";
denyInput.name = cookieName;
denyInput.dataset.name = cookieName;
denyLabel.htmlFor = cookieName + "2";
const acceptFn = () => {
acceptLabel.classList.add("active");
denyLabel.classList.remove("active");
this.setCookieStatus(cookieName, CookieStatus.true, cookieConfig);
}, denyFn = () => {
acceptLabel.classList.remove("active");
denyLabel.classList.add("active");
this.setCookieStatus(cookieName, CookieStatus.false, cookieConfig);
};
this.addEvent(acceptInput, "click", acceptFn);
this.addEventKbdValidate(acceptLabel, acceptFn);
this.addEvent(denyInput, "click", denyFn);
this.addEventKbdValidate(denyLabel, denyFn);
this.cookiesUnorderedList.append(cookie);
if (!this.hasBrowserCookie()) {
// * Ldcweb cookie is not set.
return;
}
// * Setup list status state
Object.entries(this.getCookieStatusList()).forEach(([ckName, cookieStatus]) => {
if (ckName === cookieName) {
acceptLabel.classList.remove("active");
denyLabel.classList.remove("active");
switch (cookieStatus) {
case CookieStatus.true:
acceptLabel.classList.add("active");
break;
case CookieStatus.false:
denyLabel.classList.add("active");
break;
}
}
});
});
}
/**
* Toggle show hide banner details
*/
toggleBannerDetails() {
this.bannerDetails.classList.toggle("cn-details-open");
if (!this.bannerDetailsCollapseBtn.dataset.open ||
!this.bannerDetailsCollapseBtn.dataset.close) {
throw new Error("Cannot find attribute data-open or data-close");
}
if (this.bannerDetailsAreExpanded) {
this.bannerDetailsCollapseBtn.innerHTML =
this.bannerDetailsCollapseBtn.dataset.close;
this.detailsTextOpen.classList.add("d-none");
this.detailsTextClose.classList.remove("d-none");
this.bannerDetails.style.height = "0px";
this.bannerDetailsAreExpanded = false;
}
else {
this.bannerDetailsCollapseBtn.innerHTML =
this.bannerDetailsCollapseBtn.dataset.open;
this.detailsTextOpen.classList.remove("d-none");
this.detailsTextClose.classList.add("d-none");
this.bannerDetails.style.height =
this.bannerDetails.children[0].clientHeight + "px";
this.bannerDetailsAreExpanded = true;
}
}
/**
* Toggle Cookie modal pages
*/
toggleCookieModalPages() {
this.bannerContent.classList.toggle("d-none");
this.bannerDetails.classList.toggle("d-none");
this.bannerDetailsContainer.classList.toggle("d-none");
this.modalContainer.classList.toggle("d-none");
this.setTabIndex();
this.setupCookieModalList();
this.togglePersonalizeBtn();
}
/**
* Toggle customize btn
*/
togglePersonalizeBtn() {
const customizeBtnBannerDataset = this.customizeBtn.dataset;
this.modalWrapper.scrollTop = 0;
if (this.bannerContent.classList.contains("d-none")) {
this.customizeBtn.innerHTML =
customizeBtnBannerDataset.openModal;
}
else {
this.customizeBtn.innerHTML =
customizeBtnBannerDataset.closeModal;
}
}
}
var CookieStatus;
(function (CookieStatus) {
CookieStatus["true"] = "true";
CookieStatus["false"] = "false";
CookieStatus["wait"] = "wait";
})(CookieStatus || (CookieStatus = {}));
var CookiePolicySameSite;
(function (CookiePolicySameSite) {
CookiePolicySameSite["lax"] = "lax";
CookiePolicySameSite["strict"] = "strict";
CookiePolicySameSite["none"] = "none";
})(CookiePolicySameSite || (CookiePolicySameSite = {}));

View file

@ -1,558 +0,0 @@
import defaults from "../cookie-defaults";
import cookieReferences from "../cookie-references";
import { CookieStatus } from "./../enums";
import { DocumentCookie } from "./DocumentCookie";
export default class CookieNotice {
// * -- END DOM ELEMENTS
/**
* @param config Holding all cookie configs
*/
constructor(config) {
this.config = config;
/** The CN cookie status */
this.cookieName = defaults.cookieName;
/** Cookie life time */
this.cookieTimeLife = defaults.cookieTimeLife;
/** The index on which store the expiration date */
this.cookieExpirationName = defaults.cookieExpirationName;
/** Cookie policies for each functionality */
this.cookiePolicies = defaults.cookiePolicies;
/** Prevent user from closing modal */
this.restrictCloseModal = defaults.restrictCloseModal;
/** Cookie expiration date as specified in the cookie itself */
this.cookieExpirationDate = new Date();
// * -- DOM ELEMENTS
this.domElList = {};
// * Merge cookie config with references
[...Object.keys(this.config)].forEach(cookieName => {
this.config[cookieName].cookies = [...new Set([
...this.config[cookieName].cookies,
...(cookieReferences.get(cookieName) ?? [])
])];
});
// * Setup cookie expiration date
this.cookieExpirationDate = this.getCnCookieInfo().date;
this.initDomElements();
this.setupEvents();
// * Setup CN Cookie
if (this.configHasChanged() || this.configHasExpired()) {
// * Setup Browser Cookie if none.
this.resetCnCookie();
this.openCookieModalToBannerPage();
}
this.updateRestrictCloseModal();
// * Cookie should have been created from here.
this.getCnCookieInfo().values.forEach((cookieStatus, cookieName) => {
if (cookieStatus === CookieStatus.wait) {
this.openCookieModalToBannerPage();
return;
}
this.setCnCookieStatus(cookieName, cookieStatus);
this.setCookieSwitchButton(cookieName, cookieStatus);
});
}
// * --- PUBLIC ---
/** Accept a all cookies */
acceptAllCookies() {
[...this.getCnCookieInfo().values.keys()]
.forEach(cookieName => this.acceptCookie(cookieName));
}
/** Accept a specific cookie */
acceptCookie(cookieName) {
this.setCnCookieStatus(cookieName, CookieStatus.true);
this.setCookieSwitchButton(cookieName, CookieStatus.true);
this.refreshCnCookieExpirationDate();
}
/** Deny a all cookies */
denyAllCookies() {
[...this.getCnCookieInfo().values.keys()]
.forEach(cookieName => this.denyCookie(cookieName));
}
/** Deny a specific cookie */
denyCookie(cookieName) {
this.setCnCookieStatus(cookieName, CookieStatus.false);
this.setCookieSwitchButton(cookieName, CookieStatus.false);
this.refreshCnCookieExpirationDate();
}
/** Deny all waiting cookies */
denyAllWaitingCookies() {
this.getCnCookieInfo().values.forEach((cookieStatus, cookieName) => {
if (cookieStatus === CookieStatus.wait) {
this.persistCnCookie(cookieName, CookieStatus.false);
return;
}
});
this.updateRestrictCloseModal();
}
/**
* Get a specific cookie config
* @throws {Error} If the cookie `cookieName` is not found in config.
*/
getCookieConfig(cookieName) {
const cookieOptions = Object.entries(this.config).find((entry) => entry[0] === cookieName)?.[1];
if (cookieOptions === undefined) {
throw new Error(`Cookie options ${cookieName} not found in list`);
}
return cookieOptions;
}
// * --- PRIVATE ---
// * - Utilities
/** Check if the config has expired */
configHasExpired() {
return this.cookieExpirationDate.getTime() < (new Date()).getTime();
}
/** Check if the actual cookie config matches the CN config */
configHasChanged() {
const cookies = this.getCnCookieInfo().values;
return cookies.size !== Object.keys(this.config).length ||
[...cookies.keys()].join(".") !== Object.keys(this.config).join(".");
}
/**
* Invert cookie status
*
* @param cookieStatus
* @returns Inverted cookie status, `wait` will give `false`.
* @throw {Error} If the cookie status is not handled.
*/
invertCookieStatus(cookieStatus) {
switch (cookieStatus) {
case CookieStatus.true:
case CookieStatus.wait:
return CookieStatus.false;
case CookieStatus.false:
return CookieStatus.true;
default:
throw new Error(`Un handled cookie status ${cookieStatus}`);
}
}
/** Get a new expiration date */
getNewExpirationDate() {
const expDate = new Date();
return new Date(expDate.setMonth(expDate.getMonth() + this.cookieTimeLife));
}
// * - CN Browser Cookie Manipulation
getCnCookieInfo() {
const cookies = this.getCnCookieValues();
const expirationDate = (cookies.get(this.cookieExpirationName) ?? this.getNewExpirationDate());
cookies.delete(this.cookieExpirationName);
return {
name: this.cookieName,
values: cookies,
date: expirationDate,
cookiePolicies: this.cookiePolicies
};
}
/**
* Get a cookie status
*
* @param cookieName
* @throws {Error} If the cookie value could not be found.
*/
getCnCookieStatus(cookieName) {
const statusList = this.getCnCookieInfo().values;
const cookieStatus = statusList.get(cookieName);
if (cookieStatus === undefined) {
throw new Error(`Cookie options ${cookieName} not found in list`);
}
return cookieStatus;
}
/** Trigger cookie status actions and persist status */
setCnCookieStatus(cookieName, status) {
const cookieConfig = this.getCookieConfig(cookieName);
this.persistCnCookie(cookieName, status);
if (status === CookieStatus.true) {
cookieConfig.script();
return;
}
if (status === CookieStatus.false) {
if (cookieConfig.fallback) {
cookieConfig.fallback();
}
return;
}
this.persistCnCookie(cookieName, CookieStatus.wait);
}
/** Save cookie content on web browser */
persistCnCookieList(statusMap) {
const content = Array.from(statusMap.entries()).map(([cookieName, cookieStatus]) => {
if (cookieStatus === CookieStatus.false) {
// * Need to remove all associated cookies
this.getCookieConfig(cookieName).cookies.forEach((cookieToRemove) => {
[...DocumentCookie.getAllStartingWith(cookieToRemove.replace(/\*+$/, ""))
.keys()].forEach(cookieName => DocumentCookie.markForDeletion(cookieName));
});
}
return `${cookieName}=${cookieStatus}`;
});
// * Append expiration date
content.push(`${this.cookieExpirationName}=${this.cookieExpirationDate.getTime()}`);
DocumentCookie.set(this.cookieName, content.join(","), this.cookieExpirationDate, this.cookiePolicies);
}
/** Bump CN expiration date */
refreshCnCookieExpirationDate() {
const content = Array.from(this.getCnCookieInfo().values.entries())
.map(([cookieName, cookieStatus]) => `${cookieName}=${cookieStatus}`);
// * Update expiration date
this.cookieExpirationDate = this.getNewExpirationDate();
// * Append expiration date
content.push(`${this.cookieExpirationName}=${this.cookieExpirationDate.getTime()}`);
DocumentCookie.set(this.cookieName, content.join(","), this.cookieExpirationDate, this.cookiePolicies);
}
/** Read CN cookie values */
getCnCookieValues() {
const cookies = (DocumentCookie.get(this.cookieName) ?? "").split(",").filter(e => e)
.map((cookieKeyValue) => cookieKeyValue.split(/=|(?:->)/s)), out = new Map();
cookies.forEach(keyValue => {
const key = keyValue[0], value = keyValue[1];
// * Exp Date
if (key === this.cookieExpirationName) {
let expDate = this.getNewExpirationDate();
try {
const epochExpiration = Number.parseInt(value);
if (!isNaN(epochExpiration)) {
expDate = new Date(epochExpiration);
}
}
finally {
out.set(keyValue[0], expDate);
}
return;
}
// * CookieStatus values
out.set(keyValue[0], keyValue[1]);
});
return out;
}
/** Reset Cookie status list */
resetCnCookie() {
const newCookieList = new Map();
Object.entries(this.config).forEach(([cookieName]) => newCookieList.set(cookieName, CookieStatus.wait));
this.persistCnCookieList(newCookieList);
}
/** Change the status of a cookie */
persistCnCookie(cookieName, status) {
const statusMap = this.getCnCookieInfo().values;
// * Force refresh
DocumentCookie.markForDeletion(this.cookieName);
statusMap.set(cookieName, status);
this.persistCnCookieList(statusMap);
this.updateRestrictCloseModal();
}
// * --- LISTENERS ---
/**
* Add event on a specific element
*
* @param element
* @param evnt
* @param funct
* @returns
*/
addEvent(element, evnt, funct) {
element.addEventListener(evnt, funct.bind(this), false);
}
/**
* Add event on a specific element and prevent default
*
* @param element
* @param evnt
* @param funct
*/
addEventPrevent(element, evnt, funct) {
element.addEventListener(evnt, (e) => {
e.preventDefault();
funct.call(this, e);
}, false);
}
/**
* Add event on a specific element
*
* @param element A HTMLElement on which the should should be bound.
* @param funct A closure for the event hanling.
*/
addEventKbdValidate(element, funct) {
this.addEvent(element, "keydown", (e) => {
const kbdEvt = e;
if (kbdEvt.key == " " ||
kbdEvt.code == "Space" ||
kbdEvt.keyCode == 32 ||
kbdEvt.key == "Enter" ||
kbdEvt.code == "Enter" ||
kbdEvt.keyCode == 13) {
funct.call(this, kbdEvt);
e.preventDefault();
}
});
}
// * --- COOKIE MODAL ---
setCookieSwitchButton(cookieName, status) {
const cnSwitch = document.getElementById(`${cookieName}-switch`);
const cnSwitchInput = cnSwitch?.querySelector("input");
if (!cnSwitch || !cnSwitchInput) {
return;
}
cnSwitchInput.indeterminate = status === CookieStatus.wait;
cnSwitchInput.checked = status === CookieStatus.true;
cnSwitch.ariaChecked = status === CookieStatus.wait ? CookieStatus.false : status;
}
/** Update restrict for closing cookie modal */
updateRestrictCloseModal() {
const cookieCloseModalBtn = this.getDomEl("cookieCloseModalBtn"), modalBg = this.getDomEl("modalBg");
this.restrictCloseModal = (Array.from(this.getCnCookieInfo().values.values()).includes(CookieStatus.wait)) ? true : false;
(this.restrictCloseModal) ? cookieCloseModalBtn.classList.add("d-none") : cookieCloseModalBtn.classList.remove("d-none");
(this.restrictCloseModal) ? modalBg.classList.add("cn-modal-bg-active") : modalBg.classList.remove("cn-modal-bg-active");
}
/** Show or hide Cookie modal */
toggleCookieModal() {
if (!document.body.classList.contains("cn-open")) {
this.openCookieModalToBannerPage();
return;
}
this.closeCookieModal();
}
/** Open the cookies modal to the banner page */
openCookieModalToBannerPage() {
this.openCookieModalToCookiePage();
this.toggleCookieModalPages();
}
/** Open the cookies modal to the cookies page */
openCookieModalToCookiePage() {
document.body.classList.add("cn-open");
this.resetCookieModal();
this.getDomEl("bannerContent").classList.add("d-none");
this.getDomEl("modalContainer").classList.remove("d-none");
this.getDomEl("bannerContainer").classList.add("cn-modal-page");
// Scroll to the top of the cookies list
this.getDomEl("modalContainer").scrollTop = 0;
this.setupCookieModalList();
this.setTabIndex();
}
/** Hide the cookies modal */
closeCookieModal() {
this.updateRestrictCloseModal();
if (!this.restrictCloseModal) {
document.body.classList.remove("cn-open");
if (!this.isOnBannerPage()) {
// * Make toggle page to banner on closing
this.getDomEl("bannerContent").classList.toggle("d-none");
this.getDomEl("modalContainer").classList.toggle("d-none");
this.getDomEl("bannerContainer").classList.remove("cn-modal-page");
}
this.unsetTabIndex();
this.setupCookieModalList();
}
else {
throw new Error("You need to accept or refuse all cookies");
}
}
/** Setup tab indexes on visible elements */
setTabIndex() {
// * Prevent focus html tag
document.documentElement.setAttribute("tabindex", "-1");
setTimeout(() => {
const focusableSelector = "a[href], button, [role=\"button\"], input, embed, object, iframe, textarea, select, details, [tabindex]:not([tabindex=\"-1\"])";
const cookieContainer = this.getDomEl("cookieContainer");
// * Only focusable elements
[...document.body.querySelectorAll(focusableSelector)]
.filter((el) => !el.hasAttribute("disabled") &&
!el.getAttribute("aria-hidden") &&
!cookieContainer.contains(el))
.forEach((el) => {
el.setAttribute("tabindex", "-1");
el.classList.add("cn-disabled");
});
[...cookieContainer.querySelectorAll(focusableSelector)]
.filter((el) => !el.hasAttribute("disabled") &&
!el.getAttribute("aria-hidden") &&
// * Only visible elements
!!(el.offsetWidth ||
el.offsetHeight ||
el.getClientRects().length) &&
!cookieContainer.contains(el))
.forEach((el) => {
el.setAttribute("tabindex", "0");
el.classList.remove("cn-disabled");
});
this.getDomEl("cookieShowModalBtn").setAttribute("tabindex", "-1");
}, 500);
}
/** Undo setup tab indexes on visible elements */
unsetTabIndex() {
document.documentElement.setAttribute("tabindex", "0");
setTimeout(() => {
document.body.querySelectorAll(".cn-disabled").forEach((el) => {
el.setAttribute("tabindex", "0");
el.classList.remove("cn-disabled");
});
this.getDomEl("cookieShowModalBtn").setAttribute("tabindex", "0");
}, 500);
}
/** Reset the modal view state */
resetCookieModal() {
const customizeBtn = this.getDomEl("customizeBtn");
this.getDomEl("bannerContent").classList.remove("d-none");
this.getDomEl("modalContainer").classList.add("d-none");
this.getDomEl("bannerContainer").classList.remove("cn-modal-page");
if (!customizeBtn.dataset.openModal) {
throw new Error("Cannot find attribut data-open-modal");
}
customizeBtn.innerHTML = customizeBtn.dataset.openModal;
}
/** Set the cookies list in the modal */
setupCookieModalList() {
this.getDomEl("cookiesUnorderedList").innerHTML = "";
Object.entries(this.config).forEach(([cookieName, cookieConfig]) => {
this.initDomCookieSwitch(cookieName, cookieConfig);
if (!DocumentCookie.has(this.cookieName)) {
// * Ldcweb cookie is not set.
return;
}
let cookieStatus = CookieStatus.wait;
try {
cookieStatus = this.getCnCookieStatus(cookieName);
}
finally {
// * Setup list status state
this.setCookieSwitchButton(cookieName, cookieStatus);
}
});
}
switchToModalPageOrClose() {
// * Modification du comportement du bouton, même si ca n'a pas de sens.
// https://lab.s-web.fr/ldc-web/projets/ldc-web-cookie-notice/-/issues/9`
if (this.isOnBannerPage()) {
this.toggleCookieModalPages();
return;
}
// * Pas de permutation en arrière
this.closeCookieModal();
}
/** Toggle Cookie modal pages */
toggleCookieModalPages() {
this.getDomEl("bannerContent").classList.toggle("d-none");
this.getDomEl("modalContainer").classList.toggle("d-none");
this.getDomEl("bannerContainer").classList.toggle("cn-modal-page");
if (!this.isOnBannerPage()) {
this.getDomEl("bannerContainer").classList.add("cn-modal-page");
this.denyAllWaitingCookies();
}
this.setTabIndex();
this.setupCookieModalList();
this.toggleCustomizeBtn();
}
/** Toggle customize btn */
toggleCustomizeBtn() {
const customizeBtn = this.getDomEl("customizeBtn"), customizeBtnBannerDataset = this.getDomEl("customizeBtn").dataset;
this.getDomEl("modalContainer").scrollTop = 0;
if (this.getDomEl("bannerContent").classList.contains("d-none")) {
customizeBtn.innerHTML =
customizeBtnBannerDataset.openModal;
customizeBtn.title = customizeBtnBannerDataset.openModal;
}
else {
customizeBtn.innerHTML =
customizeBtnBannerDataset.closeModal;
customizeBtn.title = customizeBtnBannerDataset.closeModal;
}
}
/** Get the actual page: banner or modal (with cookie choices) */
isOnBannerPage() {
return this.getDomEl("modalContainer").classList.contains("d-none");
}
/** Setup Events */
setupEvents() {
this.addEventPrevent(this.getDomEl("modalBg"), "click", this.closeCookieModal);
this.addEventPrevent(this.getDomEl("cookieCloseModalBtn"), "click", this.closeCookieModal);
this.addEventPrevent(this.getDomEl("acceptAllBtn"), "click", () => { this.acceptAllCookies(); this.closeCookieModal(); });
this.addEventPrevent(this.getDomEl("denyAllBtn"), "click", () => { this.denyAllCookies(); this.closeCookieModal(); });
this.addEventPrevent(this.getDomEl("customizeBtn"), "click", this.switchToModalPageOrClose);
this.addEventPrevent(this.getDomEl("cookieShowModalBtn"), "click", this.toggleCookieModal);
this.getDomEl("cookieLinkShowCustomizeModalList").forEach((cookieLink) => {
this.addEventPrevent(cookieLink, "click", this.openCookieModalToCookiePage);
this.addEventKbdValidate(cookieLink, this.openCookieModalToCookiePage);
});
}
/** Get dom element */
getDomEl(item) {
// Exclude null|undefined as elements are verified in initDomElements
return this.domElList[item];
}
/** Init a Dom cookie switch */
initDomCookieSwitch(cookieName, cookieConfig) {
const cookie = document.createElement("li");
const childItem = this.getDomEl("template").children.item(0);
if (childItem === null) {
throw new Error("Cannot find child item");
}
cookie.append(childItem.cloneNode(true));
const name = cookie.querySelector("span.cn-cookie-name");
const description = cookie.querySelector("span.cn-cookie-description");
const link = cookie.querySelector(".cn-cookie-link");
const cnSwitch = cookie.querySelector(".cn-switch");
const cnSwitchInput = cookie.querySelector(".cn-switch > input");
// * Undertermined state
cnSwitchInput.indeterminate = true;
cnSwitchInput.checked = false;
// * Assign cookie aside content
name.textContent = cookieConfig.name;
description.id = `${cookieName}-desc`;
description.textContent = cookieConfig.description;
link.textContent = cookieConfig.labelLink;
link.setAttribute("href", cookieConfig.link);
// * Assign cookie controls
cnSwitch.id = `${cookieName}-switch`;
cnSwitch.name = cookieName;
cnSwitch.dataset.name = cookieName;
cnSwitch.setAttribute("aria-labelledby", `${cookieName}-desc`);
cnSwitch.setAttribute("aria-describedby", `${cookieName}-desc`);
const toggleCookie = (cookieName) => {
let cookieStatus = CookieStatus.wait;
try {
cookieStatus = this.getCnCookieStatus(cookieName);
}
finally {
this.setCnCookieStatus(cookieName, this.invertCookieStatus(cookieStatus));
this.refreshCnCookieExpirationDate();
}
};
this.addEvent(cnSwitchInput, "click", () => toggleCookie(cookieName));
this.addEventKbdValidate(cnSwitch, () => cnSwitchInput.click());
this.getDomEl("cookiesUnorderedList").append(cookie);
}
/** Init Dom elements selector */
initDomElements() {
// * Inject DOM modal BG
const modalBg = document.createElement("div");
modalBg.classList.add("cn-modal-bg");
document.body.append(modalBg);
this.domElList.modalBg = modalBg;
// * Setup Dom Elements
this.domElList.cookieLinkShowCustomizeModalList = document.querySelectorAll(".cn-cookie-link");
const selectorList = {
"div#cn-wrapper": "cookieContainer",
"button#cn-cookie-btn": "cookieShowModalBtn",
"button#cn-close-modal": "cookieCloseModalBtn",
"div#cn-banner": "bannerContainer",
"div.cn-banner-content": "bannerContent",
"div.cn-modal-container": "modalContainer",
"button#cn-accept-banner": "acceptAllBtn",
"button#cn-deny-banner": "denyAllBtn",
"button#cn-settings-banner": "customizeBtn",
"ul#cn-modal-list": "cookiesUnorderedList",
"div#cn-li-template": "template",
};
Object.entries(selectorList).forEach(entry => {
const selector = entry[0], domElItemKey = entry[1];
let itemEntry = this.domElList[domElItemKey];
const domEl = document.querySelector(selector);
itemEntry = domEl;
if (!itemEntry) {
throw new Error(`Cannot find dom element ${selector}`);
}
this.domElList = { ...this.domElList, [domElItemKey]: itemEntry };
});
// * Clone and remove original template node
const memoryTemplate = this.domElList.template.cloneNode(true);
this.domElList.template.remove();
this.domElList.template = memoryTemplate;
}
}

View file

@ -1,51 +0,0 @@
export class DocumentCookie {
static has(cookieName) {
return this.getCookies().has(cookieName);
}
static get(cookieName) {
return this.getCookies().get(cookieName);
}
static set(cookieName, value, date = null, cookiePolicies = null) {
let cookieValue = `${cookieName}=${value};path=/${location.hostname ? `;domain=${location.hostname}` : ""}`;
if (date) {
cookieValue += `;expires=${date.toUTCString()}`;
}
if (cookiePolicies) {
cookieValue += `;sameSite=${cookiePolicies.sameSite}${cookiePolicies.secure ? ";secure" : ""}`;
}
document.cookie = cookieValue;
}
static getAllStartingWith(cookieNameStartingPart) {
const cookies = this.getCookies();
for (const cookieName of cookies.keys()) {
if (!cookieName.startsWith(cookieNameStartingPart)) {
cookies.delete(cookieName);
}
}
return cookies;
}
/**
* Set an older expire parameter to a specific cookie
*/
static markForDeletion(cookieName) {
if (!DocumentCookie.has(cookieName)) {
console.debug(`No document cookie named ${cookieName}`);
}
// * Suppression du cookie et de sa version precedé d'un point
document.cookie = `${cookieName}=;path=/;expires=Thu, 01 Jan 1970 00:00:01 GMT;sameSite=Lax`;
document.cookie = `${cookieName}=;path=/${location.hostname ? `;domain=.${location.hostname}` : ""};expires=Thu, 01 Jan 1970 00:00:01 GMT;sameSite=Lax`;
document.cookie = `${cookieName}=;path=/${location.hostname ? `;domain=${location.hostname}` : ""};expires=Thu, 01 Jan 1970 00:00:01 GMT;sameSite=Lax`;
}
/** Fetch browser cookies except(http-only ones) the cannot be handled using js */
static getCookies() {
const out = new Map();
document.cookie.split(";").filter(e => e).forEach(c => {
const cookieKeyValue = c.split(/=(.*)/s).filter(e => e);
out.set(cookieKeyValue[0].trim(), cookieKeyValue[1].trim());
});
return out;
}
}
// eslint-disable-next-line @typescript-eslint/ban-ts-comment
// @ts-ignore
window.DocumentCookie = DocumentCookie;

View file

@ -1,12 +0,0 @@
import { CookiePolicySameSite } from "./enums";
const defaults = {
cookieName: "cn-init",
cookieTimeLife: 6,
cookieExpirationName: "_expiration",
cookiePolicies: {
sameSite: CookiePolicySameSite.lax,
secure: false
},
restrictCloseModal: true
};
export default defaults;

View file

@ -1,28 +0,0 @@
export default new Map([
["youtube", [
// * https://cookiedatabase.org/service/youtube/
// * https://tarteaucitron.io/fr/service/youtube/
"NID", "ENID", "_Secure-ENID", "VISITOR_INFO1_LIVE", "YEC", "__Secure-YEC", "YSC",
"GEUP", "PREF", "pm_sess", "CGIC", "SOCS", "GPS", "yt-player-bandwidth", "yt-player-headers-readable"
]],
["recaptcha", [
// * https://developers.google.com/recaptcha/docs/faq?hl=fr
// * https://cookiedatabase.org/?s=recaptcha&lang=en
"NID", "_grecaptcha", "__Secure-3PAPISID", "__Secure-3PSID", "__Secure-3PSIDCC",
"_GRECAPTCHA", "rc::c", "rc::b", "rc::a", "itsec-recaptcha-opt-in-*"
]],
["vimeo", [
// * https://help.vimeo.com/hc/fr/articles/17670845188113-Comment-puis-je-int%C3%A9grer-des-vid%C3%A9os-tout-en-%C3%A9tant-conforme-au-GDPR
// * Cookie Database https://cookiedatabase.org/service/vimeo/
// Ne semble plus placer de cookies
"vuid", "__utmt_player"
]],
["matomo", [
// * PK* as in doc https://fr.matomo.org/faq/faq_146/
"_pk*",
// * Matomo
"_pk_ref", "_pk_cvar", "_pk_id", "_pk_ses", "_pk_hsr", "piwik_ignore", "_pk_uid",
// * Matomo Cloud
"_pk_ref", "_pk_cvar", "_pk_id", "_pk_ses", "_pk_hsr", "mtm_consent", "matomo_ignore", "matomo_sessid"
]],
]);

14
dist/esm/ts/enums.js vendored
View file

@ -1,14 +0,0 @@
/** A cookie status as written in the cn cookie */
export var CookieStatus;
(function (CookieStatus) {
CookieStatus["true"] = "true";
CookieStatus["false"] = "false";
CookieStatus["wait"] = "wait";
})(CookieStatus || (CookieStatus = {}));
/** A cookie Policy same site */
export var CookiePolicySameSite;
(function (CookiePolicySameSite) {
CookiePolicySameSite["lax"] = "lax";
CookiePolicySameSite["strict"] = "strict";
CookiePolicySameSite["none"] = "none";
})(CookiePolicySameSite || (CookiePolicySameSite = {}));

View file

@ -1,3 +0,0 @@
import CookieNotice from "../classes/CookieNotice";
import "./../../scss/themes/standard.scss";
window.CookieNotice = CookieNotice;

View file

@ -1,2 +0,0 @@
import CookieNotice from "./classes/CookieNotice";
export default CookieNotice;

1
dist/esm/ts/type.js vendored
View file

@ -1 +0,0 @@
export {};

219
dist/typings/index.d.ts vendored Normal file
View file

@ -0,0 +1,219 @@
export default class CookieNotice {
browserCookieName: string;
cookiePolicies: CookiePolicy;
config: Record<string, CookieOptions>;
modalBg: HTMLDivElement;
cookieContainer: HTMLDivElement;
bannerContainer: HTMLDivElement;
modalContainer: HTMLDivElement;
cookieShowModalBtn: HTMLButtonElement;
cookieCloseModalBtn: HTMLButtonElement;
bannerDetailsCollapseBtn: HTMLButtonElement;
bannerParaP: HTMLDivElement;
detailsTextOpen: HTMLParagraphElement;
detailsTextClose: HTMLParagraphElement;
bannerContent: HTMLDivElement;
bannerDetails: HTMLDivElement;
bannerDetailsContainer: HTMLDivElement;
acceptAllBtn: HTMLButtonElement;
denyAllBtn: HTMLButtonElement;
customizeBtn: HTMLButtonElement;
cookiesUnorderedList: HTMLUListElement;
cookieLinkShowCustomizeModalList: NodeListOf<HTMLAnchorElement>;
modalWrapper: HTMLDivElement;
template: HTMLDivElement;
bannerDetailsAreExpanded: boolean;
constructor(config: Record<string, CookieOptions>);
/**
* Check if the actual cookie matches the config
*/
cookiesMatchesConfig(): boolean;
/**
* Accept a specific cookie
*/
acceptAllCookies(): void;
/**
* Deny a specific cookie
*/
denyAllCookies(): void;
/**
* Fetch the cookie status list
*
* @returns the cookie status list
*/
getCookieStatusList(): CookieStatusList;
/**
* Check has cookie status
*
* @param key
* @param value
*/
containsCookieStatus(key: string): boolean;
/**
* Set the cookie value
*
* @param cookieName
* @param status
* @param cookieOption
*/
setCookieStatus(cookieName: string, status: CookieStatus, cookieOption: CookieOptions): void;
/**
* Add a specific cookie and
* change his status to true
*
* @param cookieName
* @param cookieOption
*/
addCookieStatus(cookieName: string, cookieOption: CookieOptions): void;
/**
* Remove a specific cookie and
* change his status to false
*
* @param cookieName
* @param cookieOption
*/
removeCookieStatus(cookieName: string, cookieOption: CookieOptions): void;
/**
* Change the status of a cookie
*
* @param cookieName
* @param status
*/
setBrowserCookieStatus(cookieName: string, status: CookieStatus): void;
/**
* Has CN cokie setup ?
* @returns true if the cookie is setup
*/
hasBrowserCookie(): boolean;
/**
* Get the Ldcweb cookie
*
* @returns A string like analytics=true,youtube=true or undefined
*/
getBrowserCookieValue(): string | undefined;
/**
* Save cookie content on web browser
*
* @param list
*/
saveBrowserCookie(statusList: CookieStatusList): void;
/**
* Set an older expire parameter to a specific cookie
*/
deleteBrowserCookie(): void;
getCookiePoliciesAsString(): string;
/**
* Reset Ldc Web CN cookie
*/
resetBrowserCookie(): void;
/**
* Add event on a specific element
*
* @param element
* @param evnt
* @param funct
* @returns
*/
addEvent(element: HTMLElement, evnt: string, funct: (e: Event) => void): void;
/**
* Add event on a specific element and prevent default
*
* @param element
* @param evnt
* @param funct
* @returns
*/
addEventPrevent(element: HTMLElement, evnt: string, funct: (e: Event) => void): void;
/**
* Add event on a specific element
*
* @param element
* @param evnt
* @param funct
* @returns
*/
addEventKbdValidate(element: HTMLElement, funct: (e: Event) => void): void;
/**
* Show or hide Cookie modal
* @returns
*/
toggleCookieModal(): void;
/**
* Open the cookies modal to the banner page
*/
openCookieModalToBannerPage(): void;
/**
* Open the cookies modal to the cookies page
*/
openCookieModalToCookiePage(): void;
/**
* Hide the cookies modal
*/
closeCookieModal(): void;
/**
* Setup tab indexes on visible elements
*/
setTabIndex(): void;
/**
* Undo setup tab indexes on visible elements
*/
unsetTabIndex(): void;
/**
* Reset the modal view state
*/
resetCookieModal(): void;
/**
* Set the cookies list in the modal
*/
setupCookieModalList(): void;
/**
* Toggle show hide banner details
*/
toggleBannerDetails(): void;
/**
* Toggle Cookie modal pages
*/
toggleCookieModalPages(): void;
/**
* Toggle customize btn
*/
togglePersonalizeBtn(): void;
}
declare enum CookieStatus {
true = "true",
false = "false",
wait = "wait"
}
type CookieStatusList = Record<string, keyof typeof CookieStatus>;
type CookiePolicy = {
sameSite: CookiePolicySameSite;
secure: string;
};
declare enum CookiePolicySameSite {
lax = "lax",
strict = "strict",
none = "none"
}
export type CookieOptions = {
name: string;
description: string;
link: string;
labelLink: string;
cookies: string[];
/**
* Fonction qui sert à initialiser la fonctionnalité
* conduisant à la génération du cookie
* @return void
*/
script: () => void;
/**
* Fonction qui sert à informer l'utilisateur
* sur chaque élèment que le cookie
* associé à la fonctionnalité
* est désactivé et propose un lien sur
* cookie notice pour l'activer
* @return void
*/
fallback: () => void | null;
};
export {};

View file

@ -1,128 +0,0 @@
import { CookieOptions as CnCookieConfig } from "../type";
export default class CookieNotice {
private config;
/** The CN cookie status */
private cookieName;
/** Cookie life time */
private cookieTimeLife;
/** The index on which store the expiration date */
private cookieExpirationName;
/** Cookie policies for each functionality */
private cookiePolicies;
/** Prevent user from closing modal */
private restrictCloseModal;
/** Cookie expiration date as specified in the cookie itself */
private cookieExpirationDate;
private domElList;
/**
* @param config Holding all cookie configs
*/
constructor(config: Record<string, CnCookieConfig>);
/** Accept a all cookies */
acceptAllCookies(): void;
/** Accept a specific cookie */
acceptCookie(cookieName: string): void;
/** Deny a all cookies */
denyAllCookies(): void;
/** Deny a specific cookie */
denyCookie(cookieName: string): void;
/** Deny all waiting cookies */
denyAllWaitingCookies(): void;
/**
* Get a specific cookie config
* @throws {Error} If the cookie `cookieName` is not found in config.
*/
getCookieConfig(cookieName: string): CnCookieConfig;
/** Check if the config has expired */
private configHasExpired;
/** Check if the actual cookie config matches the CN config */
private configHasChanged;
/**
* Invert cookie status
*
* @param cookieStatus
* @returns Inverted cookie status, `wait` will give `false`.
* @throw {Error} If the cookie status is not handled.
*/
private invertCookieStatus;
/** Get a new expiration date */
private getNewExpirationDate;
private getCnCookieInfo;
/**
* Get a cookie status
*
* @param cookieName
* @throws {Error} If the cookie value could not be found.
*/
private getCnCookieStatus;
/** Trigger cookie status actions and persist status */
private setCnCookieStatus;
/** Save cookie content on web browser */
private persistCnCookieList;
/** Bump CN expiration date */
private refreshCnCookieExpirationDate;
/** Read CN cookie values */
private getCnCookieValues;
/** Reset Cookie status list */
private resetCnCookie;
/** Change the status of a cookie */
private persistCnCookie;
/**
* Add event on a specific element
*
* @param element
* @param evnt
* @param funct
* @returns
*/
private addEvent;
/**
* Add event on a specific element and prevent default
*
* @param element
* @param evnt
* @param funct
*/
private addEventPrevent;
/**
* Add event on a specific element
*
* @param element A HTMLElement on which the should should be bound.
* @param funct A closure for the event hanling.
*/
private addEventKbdValidate;
private setCookieSwitchButton;
/** Update restrict for closing cookie modal */
private updateRestrictCloseModal;
/** Show or hide Cookie modal */
private toggleCookieModal;
/** Open the cookies modal to the banner page */
private openCookieModalToBannerPage;
/** Open the cookies modal to the cookies page */
private openCookieModalToCookiePage;
/** Hide the cookies modal */
private closeCookieModal;
/** Setup tab indexes on visible elements */
private setTabIndex;
/** Undo setup tab indexes on visible elements */
private unsetTabIndex;
/** Reset the modal view state */
private resetCookieModal;
/** Set the cookies list in the modal */
private setupCookieModalList;
private switchToModalPageOrClose;
/** Toggle Cookie modal pages */
private toggleCookieModalPages;
/** Toggle customize btn */
private toggleCustomizeBtn;
/** Get the actual page: banner or modal (with cookie choices) */
private isOnBannerPage;
/** Setup Events */
private setupEvents;
/** Get dom element */
private getDomEl;
/** Init a Dom cookie switch */
private initDomCookieSwitch;
/** Init Dom elements selector */
private initDomElements;
}

View file

@ -1,13 +0,0 @@
import { CnCookiePolicies } from "../type";
export declare abstract class DocumentCookie {
static has(cookieName: string): boolean;
static get(cookieName: string): string | undefined;
static set(cookieName: string, value: string, date?: Date | null, cookiePolicies?: CnCookiePolicies | null): void;
static getAllStartingWith(cookieNameStartingPart: string): Map<string, string>;
/**
* Set an older expire parameter to a specific cookie
*/
static markForDeletion(cookieName: string): void;
/** Fetch browser cookies except(http-only ones) the cannot be handled using js */
private static getCookies;
}

View file

@ -1,14 +0,0 @@
import { CnCookiePolicies } from "./type";
declare const defaults: {
/** The CN cookie status */
cookieName: string;
/** Cookie life time */
cookieTimeLife: number;
/** The index on which store the expiration date */
cookieExpirationName: "_expiration";
/** Cookie policies for each functionality */
cookiePolicies: CnCookiePolicies;
/** Prevent user from closing modal */
restrictCloseModal: boolean;
};
export default defaults;

View file

@ -1,2 +0,0 @@
declare const _default: Map<string, string[]>;
export default _default;

View file

@ -1,12 +0,0 @@
/** A cookie status as written in the cn cookie */
export declare enum CookieStatus {
true = "true",
false = "false",
wait = "wait"
}
/** A cookie Policy same site */
export declare enum CookiePolicySameSite {
lax = "lax",
strict = "strict",
none = "none"
}

View file

@ -1,7 +0,0 @@
import CookieNotice from "../classes/CookieNotice";
import "./../../scss/themes/standard.scss";
declare global {
interface Window {
CookieNotice: typeof CookieNotice;
}
}

View file

@ -1,2 +0,0 @@
import CookieNotice from "./classes/CookieNotice";
export default CookieNotice;

View file

@ -1,49 +0,0 @@
import type { CookiePolicySameSite, CookieStatus } from "./enums";
export type CookieStatusList = Record<string, CookieStatus>;
export type CookieOptions = {
/** The cookie name as an index that can be referred to */
name: string;
/** A string description of the cookie */
description: string;
/** A link of the cookie policy */
link: string;
/** A link label for the (learn more about link) */
labelLink: string;
/**
* The cookies indexes that are concerned
* they should really match.
* Some references
* @link https://github.com/AmauriC/tarteaucitron.js/blob/5a2252baa117b75c1143af635ed4f52c5b0afb5b/tarteaucitron.services.js#L4700
* @link https://developers.google.com/recaptcha/docs/faq?hl=fr
* @link https://cookiedatabase.org/service/vimeo/
* @link https://vimeo.com/cookie_policy
* @link https://policies.google.com/technologies/cookies?hl=en
*/
cookies: string[];
/**
* Fonction qui sert à initialiser la fonctionnalité
* conduisant à la génération du cookie
* @return void
*/
script: () => void;
/**
* Fonction qui sert à informer l'utilisateur
* sur chaque élèment que le cookie
* associé à la fonctionnalité
* est désactivé et propose un lien sur
* cookie notice pour l'activer
* @return void
*/
fallback: () => void | null;
};
export type CnCookiePolicies = {
sameSite: CookiePolicySameSite;
secure: boolean;
};
export type CnCookieValues = Map<string, CookieStatus>;
export type CnCookieInfo = {
name: string;
values: CnCookieValues;
date: Date;
cookiePolicies: CnCookiePolicies;
};

View file

@ -24,7 +24,7 @@
border: 0;
margin: 0;
appearance: none;
background: #d6d6d6;
background: #b9b9b9;
color: #000;
cursor: pointer;
font-family: "Barlow", sans-serif;
@ -36,13 +36,11 @@
}
#cn-wrapper button:hover,
#cn-wrapper button:focus {
background: #bdbdbd;
/* prettier-ignore */
background: #a0a0a0;
color: #000;
}
#cn-wrapper button:focus {
outline: 1px solid;
/* prettier-ignore */
outline-color: #000;
outline-offset: -4px;
}
@ -50,57 +48,51 @@
transform: scale(0.99);
}
/** 3.0.0 */
/* FENETRE D'ACCUEIL */
/* Title settings */
/* Text settings */
/* Button settings */
/* Title settings */
/* Text settings */
/* Switch Buttons */
/* Accept/Deny btn settings */
/* Cookies list settings */
/* Size */
#cn-wrapper .cn-nav #cn-settings-banner, #cn-wrapper .cn-nav #cn-accept-banner, #cn-wrapper .cn-nav #cn-deny-banner, #cn-wrapper #cn-banner .cn-modal-top-line #cn-close-modal {
#cn-wrapper .cn-nav #cn-settings-banner, #cn-wrapper .cn-nav #cn-accept-banner, #cn-wrapper .cn-nav #cn-deny-banner, #cn-wrapper .cn-content .cn-modal-container .accept label,
#cn-wrapper .cn-content .cn-modal-container .deny label, #cn-wrapper .cn-content .cn-banner-content .cn-banner-btn-details-p {
display: flex;
height: 3rem;
flex-direction: column;
align-items: center;
justify-content: center;
padding: 0;
background-color: #d6d6d6;
color: #000;
background-color: #000;
color: #b9b9b9;
font-family: "Barlow", sans-serif;
font-size: 16px;
font-size: 1rem;
}
#cn-wrapper .cn-nav #cn-settings-banner:hover, #cn-wrapper .cn-nav #cn-accept-banner:hover, #cn-wrapper .cn-nav #cn-deny-banner:hover, #cn-wrapper #cn-banner .cn-modal-top-line #cn-close-modal:hover, #cn-wrapper .cn-nav #cn-settings-banner:focus, #cn-wrapper .cn-nav #cn-accept-banner:focus, #cn-wrapper .cn-nav #cn-deny-banner:focus, #cn-wrapper #cn-banner .cn-modal-top-line #cn-close-modal:focus {
background-color: #bdbdbd;
/* prettier-ignore */
#cn-wrapper .cn-nav #cn-settings-banner:hover, #cn-wrapper .cn-nav #cn-accept-banner:hover, #cn-wrapper .cn-nav #cn-deny-banner:hover, #cn-wrapper .cn-content .cn-modal-container .accept label:hover,
#cn-wrapper .cn-content .cn-modal-container .deny label:hover, #cn-wrapper .cn-content .cn-banner-content .cn-banner-btn-details-p:hover, #cn-wrapper .cn-nav #cn-settings-banner:focus, #cn-wrapper .cn-nav #cn-accept-banner:focus, #cn-wrapper .cn-nav #cn-deny-banner:focus, #cn-wrapper .cn-content .cn-modal-container .accept label:focus,
#cn-wrapper .cn-content .cn-modal-container .deny label:focus, #cn-wrapper .cn-content .cn-banner-content .cn-banner-btn-details-p:focus {
background-color: #a0a0a0;
color: #000;
}
#cn-wrapper .cn-nav #cn-settings-banner:focus, #cn-wrapper .cn-nav #cn-accept-banner:focus, #cn-wrapper .cn-nav #cn-deny-banner:focus, #cn-wrapper #cn-banner .cn-modal-top-line #cn-close-modal:focus {
/* prettier-ignore */
#cn-wrapper .cn-nav #cn-settings-banner:focus, #cn-wrapper .cn-nav #cn-accept-banner:focus, #cn-wrapper .cn-nav #cn-deny-banner:focus, #cn-wrapper .cn-content .cn-modal-container .accept label:focus,
#cn-wrapper .cn-content .cn-modal-container .deny label:focus, #cn-wrapper .cn-content .cn-banner-content .cn-banner-btn-details-p:focus {
outline-color: #000;
}
.cn-modal-bg {
position: fixed;
z-index: 1030;
top: 0;
left: 0;
width: 100vw;
height: 100dvh;
background-color: rgba(0, 0, 0, 0.6);
cursor: pointer;
opacity: 0;
transition: 0.3s;
visibility: hidden;
}
.cn-modal-bg-active {
cursor: default;
display: none;
}
.cn-open .cn-modal-bg {
opacity: 1;
visibility: visible;
position: fixed;
z-index: 1030;
top: 0;
display: block;
width: 100vw;
height: 100vh;
background-color: rgba(0, 0, 0, 0.6);
}
.cn-disabled {
@ -108,49 +100,23 @@
}
#cn-wrapper {
position: fixed;
z-index: 1050;
top: 0;
left: 0;
width: 100vw;
height: 100dvh;
pointer-events: none;
}
#cn-wrapper #cn-cookie-btn {
position: fixed;
right: auto;
bottom: 0.5rem;
left: 0.5rem;
width: 2.4rem;
height: 2.4rem;
padding: 0.3rem;
bottom: 1rem;
left: 1rem;
width: 3rem;
height: 3rem;
padding: 0.5rem;
border-radius: 100%;
background-color: #fff;
box-shadow: 0 0.1rem 1rem rgba(0, 0, 0, 0.35);
cursor: pointer;
pointer-events: auto;
}
@media (min-width: 535px) {
#cn-wrapper #cn-cookie-btn {
right: auto;
bottom: -1.5rem;
left: -1.5rem;
width: 3rem;
height: 3rem;
padding: 0.5rem;
transition: all 1s 6s;
}
#cn-wrapper #cn-cookie-btn:hover, #cn-wrapper #cn-cookie-btn:focus {
right: auto;
bottom: 0.5rem;
left: 0.5rem;
transition: all 1s;
}
}
#cn-wrapper #cn-cookie-btn:focus {
outline-color: #d1842a;
outline-offset: 0.1rem;
outline-width: 0.2rem;
}
#cn-wrapper #cn-cookie-btn-icon path {
fill: #dc9c52;
@ -159,17 +125,18 @@
fill: #dc9c52;
}
#cn-wrapper #cn-banner {
position: absolute;
position: fixed;
z-index: 1050;
top: 0;
bottom: 0;
left: 0;
display: flex;
width: 100vw;
max-height: 100dvh;
height: 100vh;
max-height: 100vh;
flex-direction: column;
align-items: center;
justify-content: space-between;
justify-content: flex-end;
padding: 0;
border-radius: 0;
margin: auto;
@ -193,6 +160,8 @@
}
@media (min-width: 535px) {
#cn-wrapper #cn-banner .cn-modal-top-line #cn-close-modal {
width: 3rem;
height: 2rem;
border-top-right-radius: 0.5rem;
}
}
@ -202,15 +171,13 @@
@media (min-width: 535px) {
#cn-wrapper #cn-banner {
right: auto;
bottom: calc(0.5rem + 60px);
bottom: calc(1rem + 60px);
left: 0;
width: 30rem;
height: auto;
max-height: 26rem;
border-radius: 0.5rem;
}
#cn-wrapper #cn-banner.cn-modal-page {
max-height: 38rem;
}
}
#cn-wrapper #cn-li-template {
display: none;
@ -219,71 +186,17 @@
display: none !important;
}
#cn-wrapper .cn-content {
flex-basis: 100%;
flex-grow: 1;
padding: 0.8rem;
overflow-y: auto;
}
@media (min-width: 535px) {
#cn-wrapper .cn-content {
flex-grow: 0;
}
}
#cn-wrapper .cn-content .cn-switch {
position: relative;
display: inline-block;
overflow: hidden;
width: 4.2rem;
height: 2.4rem;
box-sizing: content-box;
cursor: pointer;
}
#cn-wrapper .cn-content .cn-switch:focus, #cn-wrapper .cn-content .cn-switch:focus-visible {
border-width: 0.1rem;
border-style: solid;
border-color: #dc9c52;
}
#cn-wrapper .cn-content .cn-switch input {
display: none;
}
#cn-wrapper .cn-content .cn-switch input + span {
position: absolute;
border-radius: 2rem;
background: #b7b7b7;
inset: 0;
}
#cn-wrapper .cn-content .cn-switch input + span::before {
position: absolute;
top: 50%;
left: 0.21rem;
display: inline-block;
width: 1.8rem;
height: 1.8rem;
border-radius: 50%;
background: #fff;
content: "";
transform: translateY(-50%);
transition: all 0.5s;
}
#cn-wrapper .cn-content .cn-switch input:indeterminate + span {
background: #b7b7b7;
}
#cn-wrapper .cn-content .cn-switch input:indeterminate + span::before {
left: 1.08rem;
}
#cn-wrapper .cn-content .cn-switch input:checked + span {
background: #dc9c52;
}
#cn-wrapper .cn-content .cn-switch input:checked + span::before {
left: 2.16rem;
}
#cn-wrapper .cn-content .cn-banner-content {
display: flex;
min-height: 100%;
flex-direction: column;
color: #707070;
color: #b9b9b9;
font-family: "Barlow", sans-serif;
font-size: 16px;
font-size: 14px;
}
@media (min-width: 535px) {
#cn-wrapper .cn-content .cn-banner-content {
@ -304,10 +217,13 @@
width: 90%;
object-fit: contain;
}
#cn-wrapper .cn-content .cn-banner-content .cn-banner-text {
flex: 2;
}
#cn-wrapper .cn-content .cn-banner-content .cn-banner-text .cn-banner-title {
color: #dc9c52;
font-family: "Satisfy", sans-serif;
font-size: 28px;
font-size: 25px;
font-weight: bold;
line-height: inherit;
text-align: left;
@ -316,24 +232,69 @@
margin: 6px 0;
text-align: justify;
}
#cn-wrapper .cn-content .cn-modal-container {
#cn-wrapper .cn-content .cn-banner-content .cn-banner-details {
display: flex;
overflow: hidden;
height: 0;
flex-direction: row;
align-items: flex-start;
justify-content: center;
text-align: justify;
transition: 0.3s;
}
#cn-wrapper .cn-content .cn-banner-content .cn-banner-btn-details {
width: 100%;
margin: 1rem 0;
}
#cn-wrapper .cn-content .cn-banner-content .cn-banner-btn-details-p {
display: inline-block;
width: 100%;
margin: 0 auto;
cursor: pointer;
font-size: 14px;
text-align: center;
}
#cn-wrapper .cn-content .cn-modal-container .cn-modal-title {
color: #dc9c52;
font-family: "Satisfy", sans-serif;
font-size: 25px;
font-weight: bold;
text-align: center;
}
#cn-wrapper .cn-content .cn-modal-container .cn-modal-subtitle {
margin-bottom: 6px;
color: #b9b9b9;
color: #dc9c52;
font-family: "Barlow", sans-serif;
font-size: 14px;
text-align: center;
}
#cn-wrapper .cn-content .cn-modal-container .cn-modal-description {
display: flex;
flex-direction: column;
align-items: center;
color: #b9b9b9;
font-family: "Barlow", sans-serif;
font-size: 14px;
font-weight: normal;
line-height: initial;
}
#cn-wrapper .cn-content .cn-modal-container .cn-modal-wrapper {
position: relative;
display: flex;
overflow: auto;
flex-direction: column;
align-items: center;
/* stylelint-disable-next-line no-descending-specificity */
}
#cn-wrapper .cn-content .cn-modal-container ul {
#cn-wrapper .cn-content .cn-modal-container .cn-modal-wrapper ul {
display: flex;
flex-direction: column;
padding: 0;
margin: 0;
padding: 0 20px;
list-style: none;
}
#cn-wrapper .cn-content .cn-modal-container .cn-cookie-wrapper {
#cn-wrapper .cn-content .cn-modal-container .cn-modal-wrapper .cn-cookie-wrapper {
display: flex;
flex-direction: row;
flex-direction: column;
align-items: center;
justify-content: space-between;
padding: 20px;
@ -341,19 +302,20 @@
border-radius: 20px;
margin: 10px 0;
}
#cn-wrapper .cn-content .cn-modal-container span {
#cn-wrapper .cn-content .cn-modal-container .cn-modal-wrapper span {
color: #dc9c52;
font-family: "Barlow", sans-serif;
font-size: 16px;
font-size: 14px;
}
#cn-wrapper .cn-content .cn-modal-container a {
font-family: "Barlow", sans-serif;
font-size: 16px;
}
#cn-wrapper .cn-content .cn-modal-container label {
#cn-wrapper .cn-content .cn-modal-container .cn-modal-wrapper a {
color: #dc9c52;
font-family: "Barlow", sans-serif;
font-size: 16px;
font-size: 14px;
}
#cn-wrapper .cn-content .cn-modal-container .cn-modal-wrapper label {
color: #dc9c52;
font-family: "Barlow", sans-serif;
font-size: 14px;
}
#cn-wrapper .cn-content .cn-modal-container .cn-cookie-name {
color: #dc9c52;
@ -365,15 +327,62 @@
flex-direction: column;
}
#cn-wrapper .cn-content .cn-modal-container .cn-cookie-infos span:first-of-type {
font-size: calc(16px * 1.25);
font-size: 17.5px;
font-weight: bold;
}
#cn-wrapper .cn-content .cn-modal-container .cn-cookie-infos .cn-cookie-description {
color: #707070;
color: #b9b9b9;
}
#cn-wrapper .cn-content .cn-modal-container .cn-cookie-infos a {
width: fit-content;
}
#cn-wrapper .cn-content .cn-modal-container .cn-cookie-buttons {
display: flex;
width: 200px;
justify-content: space-around;
margin-top: 6px;
}
#cn-wrapper .cn-content .cn-modal-container .cn-cookie-buttons input {
display: none;
}
#cn-wrapper .cn-content .cn-modal-container .cn-cookie-buttons label {
display: block;
width: 100px;
padding: 6px 20px;
color: #fff;
cursor: pointer;
transition: color 0.3s;
}
#cn-wrapper .cn-content .cn-modal-container .cn-cookie-buttons div {
display: table;
margin: 0.5em;
text-align: center;
}
#cn-wrapper .cn-content .cn-modal-container .accept label,
#cn-wrapper .cn-content .cn-modal-container .deny label {
height: inherit;
background: #808080;
}
#cn-wrapper .cn-content .cn-modal-container .accept label:hover,
#cn-wrapper .cn-content .cn-modal-container .accept label:focus {
background-color: #278327;
}
#cn-wrapper .cn-content .cn-modal-container .accept .active {
background-color: #3a3;
}
#cn-wrapper .cn-content .cn-modal-container .deny label:hover,
#cn-wrapper .cn-content .cn-modal-container .deny label:focus {
background-color: #832727;
}
#cn-wrapper .cn-content .cn-modal-container .deny .active {
background-color: #a33;
}
#cn-wrapper .cn-content .cn-modal-container .accept input:checked ~ label {
background-color: #3a3;
}
#cn-wrapper .cn-content .cn-modal-container .deny input:checked ~ label {
background-color: #a33;
}
#cn-wrapper .cn-nav {
display: flex;
overflow: hidden;
@ -382,19 +391,20 @@
flex-shrink: 0;
flex-wrap: wrap;
align-items: center;
border-top: 1px solid #6d6d6d;
border-top: 1px solid #808080;
}
#cn-wrapper .cn-nav #cn-deny-banner {
width: 50%;
}
#cn-wrapper .cn-nav #cn-accept-banner {
width: 50%;
border-right: 1px solid #6d6d6d;
border-left: 1px solid #6d6d6d;
border-right: 1px solid #808080;
border-left: 1px solid #808080;
font-weight: bolder;
}
#cn-wrapper .cn-nav #cn-settings-banner {
width: 100%;
border-top: 1px solid #6d6d6d;
border-top: 1px solid #808080;
}
@media (min-width: 535px) {
#cn-wrapper .cn-nav {
@ -414,6 +424,12 @@
border-top: initial;
}
}
@media (min-width: 535px) {
#cn-wrapper {
width: 100%;
height: 100%;
}
}
.cn-open {
overflow: hidden !important;
@ -425,14 +441,6 @@
@media (min-width: 535px) {
.cn-open #cn-wrapper #cn-banner {
right: auto;
left: 0.5rem;
}
}
@media (min-width: 535px) {
.cn-open #cn-wrapper #cn-cookie-btn {
right: auto;
bottom: 0.5rem;
left: 0.5rem;
transition: all 1s;
left: 1rem;
}
}

1321
dist/umd/main.js vendored

File diff suppressed because it is too large Load diff

File diff suppressed because one or more lines are too long

View file

@ -0,0 +1,214 @@
@php
$site_name = Str::ucfirst(config('app.name'));
$logo_picture_url = asset('picture string path');
$logo_alt_text = "Logo {$site_name}";
$confidentiality_page_url = route('page.confidentiality');
$strings = (object)[
'button_customize_cookies' => __('Personnaliser les cookies'),
'button_forbid' => __('Interdire'),
'button_allow' => __('Autoriser'),
'button_forbid_all' => Str::upper(__('Tout refuser')),
'button_allow_all' => Str::upper(__('Tout accepter')),
'button_customize' => Str::upper(__('Personnaliser')),
'button_back' => Str::upper(__('Retour')),
'banner_title' => __('Le site internet :site_name utilise des cookies !', ['site_name' => $site_name]),
'banner_text_open' => __("Ce site web stocke les cookies sur votre ordinateur. :site_name utilise ces informations
afin d’améliorer et de personnaliser votre expérience de navigation, ainsi que pour l’analyse et les indicateurs concernant nos
visiteurs à la fois sur ce site web et sur d’autres supports.\n Vous pouvez cliquer sur « Accepter » si vous consentez à l’utilisation
de ces cookies.", ['site_name' => $site_name]),
'banner_text' => __('Nous utilisons des cookies pour nous assurer du bon fonctionnement de notre site et à des fins analytiques.
En poursuivant votre navigation sur ce site ou en fermant ce bandeau, vous consentez à l’utilisationde ces cookies.'),
'banner_details' => __('Si vous refusez l’utilisation des cookies, vos informations ne seront pas suivies lors de votre visite sur ce site.
Un cookie sera utilisé dans votre navigateur afin de se souvenir de ne pas suivre vos préférences.
Certaines fonctionnalités ne seront pas accessibles.
Vous pouvez changer d’avis et modifier votre consentement à tout moment en revenant sur ce site.'),
'banner_details_link' => __('Pour en savoir plus sur les cookies que nous utilisons, consultez notre charte de confidentialité.'),
'banner_details_link_title' => __('Charte de confidentialité'),
'banner_more_details' => __('Plus de détails...'),
'banner_less_details' => __('Moins de détails...'),
'Panel_title' => __('Panneau de gestion des cookies'),
'Panel_subtitle' => __('Le respect de votre vie privée est notre priorité'),
'Panel_details' => __('Les fonctionnalités de ce site s’appuient sur des services proposés par des tiers.
Si vous acceptez, ces tiers déposeront des cookies qui vous permettront de visualiser sur le site du contenu hébergé par ces tiers.
Via ces cookies, ces tiers collecteront et utiliseront vos données de navigation pour des finalités qui leur sont propres, conformément
à leur politique de confidentialité (lien ci-dessous).
Cette page vous permet de donner ou de retirer votre consentement, soit globalement soit service par service.'),
];
$cookies = [];
// YOUTUBE
$cookies['youtube'] = [
'name' => 'VIDEOS - Youtube',
'description' => __('Les cookies déposés via les services de partage de vidéo ont pour finalité de permettre à l’utilisateur de visionner directement sur le site le contenu multimédia.'),
'link' => 'https://policies.google.com/technologies/cookies?hl=fr&utm_source=ucb',
'labelLink' => __('En savoir +'),
'cookies' => ['NID', 'VISITOR_INFO1_LIVE', 'YSC']
];
$cookies['youtube']['script'] = <<<SCRIPT
function () {
let youtubeVids = document.getElementsByClassName('cn-youtube');
for (let item of youtubeVids) {
let id = item.dataset.id;
let e = document.createElement('iframe');
e.src = "https://www.youtube.com/embed/" + id;
e.width = "640";
e.height = "360";
e.frameBorder = "0";
e.allow = "accelerometer; autoplay; clipboard-write; encrypted-media; gyroscope; picture-in-picture";
e.allowFullscreen = true;
item.innerHTML = "";
item.appendChild(e);
}
}
SCRIPT;
$cookies['youtube']['fallback'] = <<<FALLBACK
function () {
let youtubeVids = document.getElementsByClassName('cn-youtube');
for (let item of youtubeVids) {
let a = document.createElement('a');
a.innerText = 'Autoriser';
a.classList.add('cn-cookie-link');
a.classList.add('btn-autorize');
a.onclick = function () {
CookieNotice.openModal();
};
let e = document.createElement('p');
e.innerHTML = 'Youtube est désactivé. ';
item.innerHTML = "";
e.appendChild(a);
item.appendChild(e);
}
}
FALLBACK;
// VIMEO
$cookies['vimeo'] = [
'name' => 'VIDEOS - Vimeo',
'description' => __('Les cookies déposés via les services de partage de vidéo ont pour finalité de permettre à l’utilisateur de visionner directement sur le site le contenu multimédia.'),
'link' => 'https://vimeo.com/cookie_policy',
'labelLink' => __('En savoir +'),
'cookies' => ['NID', 'VISITOR_INFO1_LIVE', 'YSC']
];
$cookies['vimeo']['script'] = <<<SCRIPT
function () {
let vimeoVids = document.getElementsByClassName('cn-vimeo');
for (let item of vimeoVids) {
let id = item.dataset.id;
let e = document.createElement('iframe');
e.src = "https://player.vimeo.com/video/" + id;
e.width = "640";
e.height = "360";
e.frameBorder = "0";
e.allow = "autoplay; fullscreen; picture-in-picture";
e.allowFullscreen = true;
item.innerHTML = "";
item.appendChild(e);
}
}
SCRIPT;
$cookies['vimeo']['fallback'] = <<<FALLBACK
function () {
let vimeoVids = document.getElementsByClassName('cn-vimeo');
for (let item of vimeoVids) {
let a = document.createElement('a');
a.innerText = 'Autoriser';
a.classList.add('cn-cookie-link');
a.classList.add('btn-autorize');
a.onclick = function () {
CookieNotice.openModal();
};
let e = document.createElement('p');
e.innerHTML = 'Vimeo est désactivé. ';
item.innerHTML = "";
e.appendChild(a);
item.appendChild(e);
}
}
FALLBACK;
// RECAPTCHA
$cookies['recaptcha'] = [
'name' => 'API - reCAPTACHA',
'description' => __('Les cookies qui sont déposés via le recaptcha sur les formulaires ont pour finalité d\'empêcher que ceux-ci ne soient soumis par des robots.'),
'link' => 'https://policies.google.com/privacy',
'labelLink' => __('En savoir +'),
'cookies' => ['NID', '__Secure-3PAPISID', '__Secure-3PSID', '__Secure-3PSIDCC']
];
$cookies['recaptcha']['script'] = <<<SCRIPT
function () {
if (window.__CN_Recaptcha) {
window.__CN_Recaptcha();
}
}
SCRIPT;
// ANALYCTICS
$cookies['analytics'] = [
'name' => __('MESURES D’AUDIENCE') . ' - Google Analytics',
'description' => __('Les cookies qui sont déposés via le recaptcha sur les formulaires ont pour finalité d’empêcher que ceux-ci ne soient soumis par des robots.'),
'link' => 'https://policies.google.com/privacy',
'labelLink' => __('En savoir +'),
'cookies' => [
'_ga',
'_gat_gtag_' . str_replace("-", "_", config("ldcweb-cookies.analyticsKey")),
'_gid'
]
];
$cookies['analytics']['script'] = <<<SCRIPT
function () {
(function (d, t) {
var g = d.createElement(t),
s = d.getElementsByTagName(t)[0];
g.src = 'https://www.googletagmanager.com/gtag/js?id={{ config("ldcweb-cookies.analyticsKey") }}';
g.id = 'analytics';
s.parentNode.insertBefore(g, s)
}(document, 'script'));
window.dataLayer = window.dataLayer || [];
function gtag() {
dataLayer.push(arguments);
}
gtag('js', new Date());
gtag('config', '{{ config("ldcweb-cookies.analyticsKey") }}');
}
SCRIPT;
@endphp
{{-- INCLUDE TEMPLATE --}}
@include('vendor.cookie-notice-templates/standard', compact(
'site_name', 'logo_picture_url', 'logo_alt_text',
'confidentiality_page_url', 'strings'
))
@push('scripts')
<script nonce="{{ $nonce ?? '' }}">
window.WebCookieNotice = {};
@foreach($cookies as $index_name => $cookie)
window.WebCookieNotice['{{ $index_name }}'] = {};
window.WebCookieNotice['{{ $index_name }}'].tmp = {};
// SCRIPT
window.WebCookieNotice['{{ $index_name }}'].tmp.script = {!! strip_tags($cookie['script']) !!};
@php unset($cookie['script']); @endphp
// FALLBACK
@if(isset($cookie['fallback']))
window.WebCookieNotice['{{ $index_name }}'].tmp.fallback = {!! strip_tags($cookie['fallback']) !!};
@php unset($cookie['fallback']); @endphp
@endif
window.WebCookieNotice['{{ $index_name }}'].conf = @json($cookie);
window.WebCookieNotice['{{ $index_name }}'].conf.script = window.WebCookieNotice['{{ $index_name }}'].tmp.script;
window.WebCookieNotice['{{ $index_name }}'].conf.fallback = window.WebCookieNotice['{{ $index_name }}'].tmp.fallback;
window.WebCookieNotice['{{ $index_name }}'] = window.WebCookieNotice['{{ $index_name }}'].conf;
@endforeach
window.WebCookieNotice = new WebCookieNotice(window.WebCookieNotice);
</script>
@endpush

View file

@ -1,302 +0,0 @@
{{-- blade-formatter-disable --}}
@php
$site_name = Str::ucfirst(config('app.name'));
$logo_picture_url = asset('picture string path');
$logo_title_text = __('Logo du site :name', ['name' => $site_name]);
$logo_alt_text = __('Logo :name', ['name' => $site_name]);
$strings = (object)[
'modal_title' => __('cookie-notice.modal_title'),
'button_customize_cookies' => __('cookie-notice.button_customize_cookies'),
'button_close_cookies' => __('cookie-notice.button_close_cookies'),
'button_title_open_new_tab' => __('cookie-notice.button_title_open_new_tab'),
'button_toggle_cookie' => __('cookie-notice.button_toggle_cookie'),
'button_forbid_all' => Str::upper(__('cookie-notice.button_forbid_all')),
'button_allow_all' => Str::upper(__('cookie-notice.button_allow_all')),
'button_customize' => Str::upper(__('cookie-notice.button_customize')),
'button_forbid_all_title' => __('cookie-notice.button_forbid_all_title'),
'button_allow_all_title' => __('cookie-notice.button_allow_all_title'),
'button_validate_and_close' => Str::upper(__('cookie-notice.button_validate_and_close')),
'banner_title' => __('cookie-notice.banner_title', ['site_name' => $site_name]),
'banner_text' => __('cookie-notice.banner_text'),
'panel_content' => __('cookie-notice.panel_content'),
'picture_cookie_title' => __('cookie-notice.picture_cookie_title'),
'navigation_title' => __('cookie-notice.navigation_title'),
];
$cookieInline = function ($cookieName, $text, $subtext = '') {
return <<<SCRIPT
(() => {
const cookieActivate = document.createElement("span");
cookieActivate.classList.add("cn-cookie-activate");
cookieActivate.dataset.cookieName = '{$cookieName}';
const childSpan = document.createElement("span");
const childSpanSpan = document.createElement("span");
const childSpanSmall = document.createElement("span");
childSpanSpan.textContent = '{$text}';
childSpanSmall.textContent = '{$subtext}';
childSpan.appendChild(childSpanSpan);
childSpan.appendChild(childSpanSmall);
const childBtn = document.createElement("button");
childBtn.classList.add('btn','btn-secondary');
childBtn.textContent = 'Autoriser';
cookieActivate.appendChild(childSpan);
cookieActivate.appendChild(childBtn);
return cookieActivate;
})
SCRIPT;
};
$cookies = [];
// YOUTUBE
$cookies['youtube'] = [
'name' => 'VIDEOS - Youtube',
'description' => __('Les cookies déposés via les services de partage de vidéo ont pour finalité de permettre à l’utilisateur de visionner directement sur le site le contenu multimédia.'),
'link' => 'https://policies.google.com/technologies/cookies?hl=fr&utm_source=ucb',
'labelLink' => __('En savoir +'),
'cookies' => ['NID', 'VISITOR_INFO1_LIVE', 'YSC']
];
$cookies['youtube']['script'] = <<<SCRIPT
function () {
let youtubeVids = document.getElementsByClassName('cn-youtube');
for (let item of youtubeVids) {
let id = item.dataset.id;
let e = document.createElement('iframe');
e.src = "https://www.youtube.com/embed/" + id;
e.width = "640";
e.height = "360";
e.frameBorder = "0";
e.allow = "accelerometer; autoplay; clipboard-write; encrypted-media; gyroscope; picture-in-picture";
e.allowFullscreen = true;
item.innerHTML = "";
item.appendChild(e);
}
}
SCRIPT;
$cookies['youtube']['fallback'] = <<<FALLBACK
function () {
let youtubeVids = document.getElementsByClassName('cn-youtube');
for (let item of youtubeVids) {
let a = document.createElement('a');
a.innerText = 'Autoriser';
a.classList.add('cn-cookie-link');
a.setAttribute('role', 'button');
a.onclick = function () {
WebCookieNotice.openCookieModalToCookiePage();
};
let e = document.createElement('p');
e.innerHTML = 'Youtube est désactivé. ';
item.innerHTML = "";
e.appendChild(a);
item.appendChild(e);
}
}
FALLBACK;
// VIMEO
$cookies['vimeo'] = [
'name' => 'VIDEOS - Vimeo',
'description' => __('Les cookies déposés via les services de partage de vidéo ont pour finalité de permettre à l’utilisateur de visionner directement sur le site le contenu multimédia.'),
'link' => 'https://vimeo.com/cookie_policy',
'labelLink' => __('En savoir +'),
'cookies' => ['NID', 'VISITOR_INFO1_LIVE', 'YSC']
];
$cookies['vimeo']['script'] = <<<SCRIPT
function () {
let vimeoVids = document.getElementsByClassName('cn-vimeo');
for (let item of vimeoVids) {
let id = item.dataset.id;
let e = document.createElement('iframe');
e.src = "https://player.vimeo.com/video/" + id;
e.width = "640";
e.height = "360";
e.frameBorder = "0";
e.allow = "autoplay; fullscreen; picture-in-picture";
e.allowFullscreen = true;
item.innerHTML = "";
item.appendChild(e);
}
}
SCRIPT;
$cookies['vimeo']['fallback'] = <<<FALLBACK
function () {
let vimeoVids = document.getElementsByClassName('cn-vimeo');
for (let item of vimeoVids) {
let a = document.createElement('a');
a.innerText = 'Autoriser';
a.classList.add('cn-cookie-link');
a.setAttribute('role', 'button');
a.onclick = function () {
WebCookieNotice.openCookieModalToCookiePage();
};
let e = document.createElement('p');
e.innerHTML = 'Vimeo est désactivé. ';
item.innerHTML = "";
e.appendChild(a);
item.appendChild(e);
}
}
FALLBACK;
// RECAPTCHA
$cookies['recaptcha'] = [
'name' => __('cookie-notice.custom.recaptcha.title'),
'description' => __('cookie-notice.custom.recaptcha.description'),
'link' => 'https://policies.google.com/privacy',
'labelLink' => __('En savoir +'),
'cookies' => ['NID', '__Secure-3PAPISID', '__Secure-3PSID', '__Secure-3PSIDCC']
];
$cookies['recaptcha']['script'] = <<<SCRIPT
function () {
if (window.__CN_Recaptcha) {
window.__CN_Recaptcha();
}
[...document.getElementsByClassName('cn-cookie-activate')].forEach(function(el) {
if (el.dataset.cookieName === 'recaptcha') {
el.classList.add('d-none');
document.getElementById('contact-form').inert = false;
}
});
}
SCRIPT;
$cookies['recaptcha']['fallback'] = <<<FALLBACK
function () {
if (window.__CN_Recaptcha_Reset) {
window.__CN_Recaptcha_Reset();
}
[...document.getElementsByClassName('cn-cookie-activate')].forEach(function(el) {
if (el.dataset.cookieName === 'recaptcha') {
el.classList.remove('d-none');
document.getElementById('contact-form').inert = true;
}
});
}
FALLBACK;
// ANALYCTICS
$analyticKey = config('services.google.analytics.id');
$cookies['analytics'] = [
'name' => __('cookie-notice.custom.analytics.title'),
'description' => __('cookie-notice.custom.analytics.description'),
'link' => 'https://policies.google.com/privacy',
'labelLink' => __('En savoir +'),
'cookies' => [
'_ga',
'_gat_gtag_' . str_replace("-", "_", $analyticKey),
'_gid'
]
];
$cookies['analytics']['script'] = <<<SCRIPT
function () {
(function (d, t) {
var g = d.createElement(t),
s = d.getElementsByTagName(t)[0];
g.src = 'https://www.googletagmanager.com/gtag/js?id={$analyticKey}';
g.id = 'analytics';
s.parentNode.insertBefore(g, s)
}(document, 'script'));
window.dataLayer = window.dataLayer || [];
function gtag() {
dataLayer.push(arguments);
}
gtag('js', new Date());
gtag('config', '{$analyticKey}');
}
SCRIPT;
// MATOMO
$cookies['matomo'] = [
'name' => __('cookie-notice.custom.matomo.title'),
'description' => __('cookie-notice.custom.matomo.description'),
'link' => 'https://fr.matomo.org/gdpr-analytics/',
'labelLink' => __('En savoir +'),
'cookies' => ['_pk']
];
$cookies['matomo']['script'] = <<<SCRIPT
function () {
var _paq = window._paq = window._paq || [];
/* tracker methods like "setCustomDimension" should be called before "trackPageView" */
_paq.push(['trackPageView']);
_paq.push(['enableLinkTracking']);
(function() {
var u="//yl.s-web.fr/";
_paq.push(['setTrackerUrl', u+'rainbow']);
_paq.push(['setSiteId', '
SCRIPT;
$cookies['matomo']['script'] .= config("services.matomo.site_id");
$cookies['matomo']['script'] .= <<<SCRIPT
']);
var d=document, g=d.createElement('script'), s=d.getElementsByTagName('script')[0];
g.async=true; g.src=u+'unicorn'; s.parentNode.insertBefore(g,s);
})();
}
SCRIPT;
@endphp
{{-- INCLUDE TEMPLATE --}}
@include('vendor.cookie-notice-templates.standard', compact(
'site_name', 'logo_picture_url', 'logo_alt_text',
'logo_title_text', 'strings'
))
@push('scripts')
<script nonce="{{ $nonce ?? '' }}">
document.addEventListener('DOMContentLoaded', function () {
window.WebCookieNotice = {};
@foreach($cookies as $index_name => $cookie)
window.WebCookieNotice['{{ $index_name }}'] = {};
window.WebCookieNotice['{{ $index_name }}'].tmp = {};
// SCRIPT
window.WebCookieNotice['{{ $index_name }}'].tmp.script = {!! strip_tags($cookie['script']) !!};
@php unset($cookie['script']); @endphp
// FALLBACK
@if(isset($cookie['fallback']))
window.WebCookieNotice['{{ $index_name }}'].tmp.fallback = {!! strip_tags($cookie['fallback']) !!};
@php unset($cookie['fallback']); @endphp
@endif
window.WebCookieNotice['{{ $index_name }}'].conf = @json($cookie);
window.WebCookieNotice['{{ $index_name }}'].conf.script = window.WebCookieNotice['{{ $index_name }}'].tmp.script;
window.WebCookieNotice['{{ $index_name }}'].conf.fallback = window.WebCookieNotice['{{ $index_name }}'].tmp.fallback;
window.WebCookieNotice['{{ $index_name }}'] = window.WebCookieNotice['{{ $index_name }}'].conf;
@endforeach
window.WebCookieNotice = new window.CookieNotice(window.WebCookieNotice);
function handle(e) {
e.preventDefault();
const cookieEl = e.target.parentElement;
window.WebCookieNotice.acceptCookie(cookieEl.dataset.cookieName);
cookieEl.classList.add("d-none");
}
if (!window.WebCookieNotice) {
console.debug("Missing WebCookieNotice on window");
return;
}
window.listenInlineCnButtons = () => {
const cookieInlineActivation = document.getElementsByClassName("cn-cookie-activate");
[...cookieInlineActivation].forEach((cookieEl) => {
const cookieBtnActivation = cookieEl.querySelector("button");
if (!cookieBtnActivation) {
throw new Error("Invalid template cookie button");
}
cookieBtnActivation.removeEventListener("click", handle);
cookieBtnActivation.addEventListener("click", handle);
});
};
window.listenInlineCnButtons();
});
</script>
@endpush

View file

@ -1,44 +0,0 @@
<?php
return [
'button_customize_cookies' => 'Cookie-Einstellungen',
'button_close_cookies' => 'Cookies-Fenster schließen',
'button_toggle_cookie' => 'Akzeptieren oder ablehnen',
'button_forbid_all' => 'Alle ablehnen',
'button_allow_all' => 'Alle akzeptieren',
'button_forbid_all_title' => 'Lehnen Sie alle Cookies ab und schließen Sie das Cookie-Panel',
'button_allow_all_title' => 'Akzeptieren Sie alle Cookies und schließen Sie das Cookie-Panel',
'button_customize' => 'Einstellungen',
'button_validate_and_close' => 'Bestätigen und schließen',
'button_title_open_new_tab' => 'Link in neuem Tab öffnen',
'banner_title' => 'Die Website :site_name nutzt Cookies!',
'banner_text' => 'Wir verwenden Cookies, um sicherzustellen, dass unsere Website ordnungsgemäß funktioniert, und zu analytischen Zwecken.
Sie können Ihre Meinung jederzeit ändern, indem Sie auf das Symbol auf jeder Seite unserer Website klicken.
Wenn Sie diese Dienste von Drittanbietern zulassen, stimmen Sie dem Ablegen und Lesen von Cookies und der Verwendung von Tracking-Technologien zu, die für das Funktionieren dieser Dienste erforderlich sind.',
'panel_content' => 'Inhalt des Cookie-Verwaltungspanels',
'picture_cookie_title' => 'Bild eines schönen großen Kekses',
'navigation_title' => 'Navigation im Cookie-Panel',
'custom' => [
'analytics' => [
'title' => 'Google Analytics',
'description' => 'Dienste zur Zielgruppenmessung ermöglichen die Erstellung von Besucherstatistiken, die zur Verbesserung der Website nützlich sind.',
],
'youtube' => [
'name' => 'Youtube',
'description' => 'Über Video-Sharing-Dienste platzierte Cookies sollen es dem Benutzer ermöglichen, Multimedia-Inhalte direkt auf der Website anzusehen.',
'labelLink' => 'Erfahren Sie mehr',
'warning' => 'Sie müssen Cookies akzeptieren, um dieses Video anzusehen',
],
'matomo' => [
'title' => 'Matomo',
'description' => 'Mithilfe von Publikumsmessungsdiensten werden Verkehrsstatistiken erstellt, die zur Verbesserung der Website nützlich sind.',
'labelLink' => 'Erfahren Sie mehr',
],
'recaptcha' => [
'title' => 'reCAPTCHA',
'description' => 'Der Zweck der über das Recaptcha auf Formularen platzierten Cookies besteht darin, zu verhindern, dass diese von Robotern übermittelt werden.',
'labelLink' => 'Erfahren Sie mehr',
'warning' => 'Sie müssen reCAPTCHA Cookies akzeptieren, um das Formular senden zu können',
]
]
];

View file

@ -1,45 +0,0 @@
<?php
return [
'button_customize_cookies' => 'Customize cookies',
'button_close_cookies' => 'Close cookie window',
'button_toggle_cookie' => 'Accept or refuse',
'button_forbid_all' => 'Refuse all',
'button_allow_all' => 'Accept all',
'button_forbid_all_title' => 'Refuse all cookies and close the cookies panel',
'button_allow_all_title' => 'Accept all cookies and close the cookies panel',
'button_customize' => 'Customize',
'button_validate_and_close' => 'Confirm and close',
'button_title_open_new_tab' => 'Open link in new tab',
'banner_title' => 'The :site_name website uses cookies!',
'banner_text' => 'We use cookies to ensure the proper functioning of our site and for analytical purposes.
You can change your mind at any time by clicking on the icon on any page of our site.
By authorizing these third-party services, you agree to the deposit and reading of cookies and the use of tracking technologies necessary for their proper operation.',
'modal_title' => 'Cookie management window',
'panel_content' => 'Cookie management panel content',
'picture_cookie_title' => 'Image of a nice big cookie',
'navigation_title' => 'Cookies panel navigation',
'custom' => [
'analytics' => [
'title' => 'Google Analytics',
'description' => 'Audience measurement services make it possible to generate attendance statistics useful for improving the site.',
],
'youtube' => [
'title' => 'Youtube',
'description' => 'Cookies placed via video sharing services are intended to allow the user to view multimedia content directly on the site.',
'labelLink' => 'Learn more',
'warning' => 'You must accept cookies to view this video',
],
'matomo' => [
'title' => 'Matomo',
'description' => 'Audience measurement services are used to generate traffic statistics, which are useful for improving the site.',
'labelLink' => 'Learn more',
],
'recaptcha' => [
'title' => 'reCAPTCHA',
'description' => 'The purpose of the cookies placed on forms via the recaptcha is to prevent them from being submitted by robots.',
'labelLink' => 'Learn more',
'warning' => 'You must accept reCAPTCHA cookies to send the form',
]
]
];

View file

@ -1,45 +0,0 @@
<?php
return [
'button_customize_cookies' => 'Personnaliser les cookies',
'button_close_cookies' => 'Fermer la fenêtre des cookies',
'button_toggle_cookie' => 'Autoriser ou refuser',
'button_forbid_all' => 'Tout refuser',
'button_allow_all' => 'Tout accepter',
'button_forbid_all_title' => 'Refuser tous les cookies et fermer le panneau des cookies',
'button_allow_all_title' => 'Accepter tous les cookies et fermer le panneau des cookies',
'button_customize' => 'Personnaliser',
'button_validate_and_close' => 'Valider et fermer',
'button_title_open_new_tab' => 'Ouvrir le lien dans un nouvel onglet',
'banner_title' => 'Le site internet :site_name utilise des cookies' . html_entity_decode('&nbsp;') . '!',
'banner_text' => 'Nous utilisons des cookies pour nous assurer du bon fonctionnement de notre site et à des fins analytiques.
Vous pouvez changer d’avis à tout moment en cliquant sur l’icône présente sur chaque page de notre site.
En autorisant ces services tiers, vous acceptez le dépôt et la lecture de cookies et l’utilisation de technologies de suivi nécessaires à leur bon fonctionnement.',
'modal_title' => 'Fenêtre de gestion de cookies',
'panel_content' => 'Contenu du panneau des cookies',
'picture_cookie_title' => 'Image d’un bon gros cookie',
'navigation_title' => 'Navigation du panneau des cookies',
'custom' => [
'analytics' => [
'title' => 'Google Analytics',
'description' => 'Les services de mesure d’audience permettent de générer des statistiques de fréquentation utiles à l’amélioration du site.',
],
'youtube' => [
'name' => 'Youtube',
'description' => 'Les cookies placés via les services de partage de vidéos sont destinés à permettre à l’utilisateur de visionner des contenus multimédias directement sur le site.',
'labelLink' => 'En apprendre plus',
'warning' => 'Vous devez accepter les cookies pour visionner cette vidéo',
],
'matomo' => [
'title' => 'Matomo',
'description' => 'Les services de mesure d’audience permettent de générer des statistiques de fréquentation utiles à l’amélioration du site.',
'labelLink' => 'En apprendre plus',
],
'recaptcha' => [
'title' => 'reCAPTCHA',
'description' => 'Les cookies qui sont déposés via le recaptcha sur les formulaires ont pour finalité d’empêcher que ceux-ci ne soient soumis par des robots.',
'labelLink' => 'En apprendre plus',
'warning' => 'Vous devez accepter les cookies reCAPTCHA pour envoyer le formulaire',
]
]
];

View file

@ -1,70 +0,0 @@
<div id="cn-wrapper" title="{{ $strings->modal_title }}" role="alertdialog" tabindex="-1">
<button id="cn-cookie-btn" title="{{ $strings->button_customize_cookies }}">
{{-- COOKIE SVG --}}
<svg viewBox="0 0 28 28" xmlns="http://www.w3.org/2000/svg">
<title>{{ $strings->picture_cookie_title }}</title>
<path fill-rule="evenodd" clip-rule="evenodd" d="M14.0001 2.93383C14.0001 4.16622 14.6159 5.25477 15.5567 5.90849C15.3526 6.46423 15.2412 7.06473 15.2412 7.69126C15.2412 10.5472 17.5564 12.8624 20.4123 12.8624C21.0807 12.8624 21.7195 12.7356 22.3059 12.5047C22.9456 13.527 24.0817 14.2069 25.3766 14.2069C26.1872 14.2069 26.9357 13.9404 27.539 13.4903C27.5453 13.6594 27.5484 13.8294 27.5484 14C27.5484 21.4826 21.4826 27.5484 14 27.5484C6.51748 27.5484 0.45166 21.4826 0.45166 14C0.45166 6.51748 6.51748 0.45166 14 0.45166C14.3209 0.45166 14.6391 0.462811 14.9543 0.484747C14.3618 1.12929 14.0001 1.98931 14.0001 2.93383ZM21.2176 2.53212C21.2195 2.54914 21.2213 2.56619 21.2229 2.58328C21.2569 2.58864 21.2909 2.59433 21.3247 2.60035C21.2891 2.57745 21.2534 2.5547 21.2176 2.53212ZM25.5171 6.86104C25.523 6.89745 25.5285 6.93399 25.5336 6.97066C25.5512 6.97141 25.5687 6.97228 25.5861 6.97328C25.5633 6.93574 25.5403 6.89833 25.5171 6.86104ZM12.5247 2.09283C12.4748 2.38291 12.4487 2.68118 12.4487 2.98553C12.4487 4.33316 12.9591 5.56158 13.7972 6.48802C13.7266 6.87842 13.6898 7.28054 13.6898 7.69126C13.6898 11.404 16.6996 14.4137 20.4123 14.4137C20.8725 14.4137 21.3219 14.3675 21.7562 14.2794C22.689 15.1941 23.9669 15.7582 25.3766 15.7582C25.5439 15.7582 25.7094 15.7503 25.8726 15.7347C25.0321 21.5385 20.0368 25.9971 14.0001 25.9971C7.37431 25.9971 2.00305 20.6258 2.00305 14.0001C2.00305 7.87378 6.59498 2.82 12.5247 2.09283Z" fill="#FF4E4E" />
<circle cx="7.58784" cy="12.8624" r="1.96503" fill="#FF4E4E" />
<circle cx="8.82887" cy="19.2745" r="1.3445" fill="#FF4E4E" />
<circle cx="13.6897" cy="14.5171" r="1.03423" fill="#FF4E4E" />
<circle cx="11.4144" cy="7.48439" r="0.930805" fill="#FF4E4E" />
<circle cx="17.5164" cy="20.3089" r="1.86161" fill="#FF4E4E" />
<circle cx="21.3432" cy="6.7604" r="0.930805" fill="#FF4E4E" />
<circle cx="22.1706" cy="1.89958" r="1.44792" fill="#FF4E4E" />
<circle cx="26.8245" cy="8.31185" r="0.72396" fill="#FF4E4E" />
</svg>
</button>
{{-- BANNER --}}
<div id="cn-banner" tabindex="-1">
<div class="cn-modal-top-line">
<button id="cn-close-modal" title="{{ $strings->button_close_cookies }}">X</button>
</div>
{{-- CONTENT VIEW --}}
<div class="cn-content" title="{{ $strings->panel_content }}" tabindex="0">
{{-- 1ST PAGE BANNER --}}
<div class="cn-banner-content">
<div class="cn-banner-img">
<img src="{{ $logo_picture_url }}" title="{{ $logo_title_text }}" alt="{{ $logo_alt_text }}">
</div>
<div class="cn-banner-text">
<div class="cn-banner-title">
<span>{!! nl2br(e($strings->banner_title)) !!}</span>
</div>
<div class="cn-banner-para-p">
<p>{!! nl2br(e($strings->banner_text)) !!}</p>
<a href="{{ route('charte') }}">{{ __('Privacy_policy') }}</a>
</div>
</div>
</div>
{{-- 2ND PAGE CUSTOMIZE PANEL --}}
<div class="cn-modal-container d-none">
{{-- COOKIES LIST --}}
<ul id="cn-modal-list"></ul>
</div>
</div>
{{-- NAV BAR --}}
<div class="cn-nav" title="{{ $strings->navigation_title }}" role="navigation">
<button class="cn-banner-btn cn-deny" id="cn-deny-banner" title="{{ $strings->button_forbid_all_title }}">{{ $strings->button_forbid_all }}</button>
<button class="cn-banner-btn cn-accept" id="cn-accept-banner" title="{{ $strings->button_allow_all_title }}">{{ $strings->button_allow_all }}</button>
<button class="cn-banner-btn cn-custom" id="cn-settings-banner" data-open-modal="{{ $strings->button_validate_and_close }}" data-close-modal="{{ $strings->button_customize }}">{{ $strings->button_customize }}</button>
</div>
{{-- COOKIE LIST LI TEMPLATE --}}
<div id="cn-li-template">
<div class="cn-cookie-wrapper">
<div class="cn-cookie-infos">
<span class="cn-cookie-name">#name</span>
<span class="cn-cookie-description">#description</span>
<a class="cn-cookie-link" title="{{ $strings->button_title_open_new_tab }}" target="blank">#link</a>
</div>
<div class="cn-cookie-buttons">
<label class="cn-switch" role="checkbox" aria-label="{{ $strings->button_toggle_cookie }}" title="{{ $strings->button_toggle_cookie }}" aria-checked="undefined"
tabindex="0">
<input type="checkbox" tabindex="-1" />
<span></span>
</label>
</div>
</div>
</div>
</div>
</div>

View file

@ -0,0 +1,92 @@
<div id="cn-wrapper" tabindex="-1" role="dialog">
<button id="cn-cookie-btn" title="{{ $strings->button_customize_cookies }}">
{{-- COOKIE SVG --}}
<svg viewBox="0 0 28 28" xmlns="http://www.w3.org/2000/svg">
<path fill-rule="evenodd" clip-rule="evenodd"
d="M14.0001 2.93383C14.0001 4.16622 14.6159 5.25477 15.5567 5.90849C15.3526 6.46423 15.2412 7.06473 15.2412 7.69126C15.2412 10.5472 17.5564 12.8624 20.4123 12.8624C21.0807 12.8624 21.7195 12.7356 22.3059 12.5047C22.9456 13.527 24.0817 14.2069 25.3766 14.2069C26.1872 14.2069 26.9357 13.9404 27.539 13.4903C27.5453 13.6594 27.5484 13.8294 27.5484 14C27.5484 21.4826 21.4826 27.5484 14 27.5484C6.51748 27.5484 0.45166 21.4826 0.45166 14C0.45166 6.51748 6.51748 0.45166 14 0.45166C14.3209 0.45166 14.6391 0.462811 14.9543 0.484747C14.3618 1.12929 14.0001 1.98931 14.0001 2.93383ZM21.2176 2.53212C21.2195 2.54914 21.2213 2.56619 21.2229 2.58328C21.2569 2.58864 21.2909 2.59433 21.3247 2.60035C21.2891 2.57745 21.2534 2.5547 21.2176 2.53212ZM25.5171 6.86104C25.523 6.89745 25.5285 6.93399 25.5336 6.97066C25.5512 6.97141 25.5687 6.97228 25.5861 6.97328C25.5633 6.93574 25.5403 6.89833 25.5171 6.86104ZM12.5247 2.09283C12.4748 2.38291 12.4487 2.68118 12.4487 2.98553C12.4487 4.33316 12.9591 5.56158 13.7972 6.48802C13.7266 6.87842 13.6898 7.28054 13.6898 7.69126C13.6898 11.404 16.6996 14.4137 20.4123 14.4137C20.8725 14.4137 21.3219 14.3675 21.7562 14.2794C22.689 15.1941 23.9669 15.7582 25.3766 15.7582C25.5439 15.7582 25.7094 15.7503 25.8726 15.7347C25.0321 21.5385 20.0368 25.9971 14.0001 25.9971C7.37431 25.9971 2.00305 20.6258 2.00305 14.0001C2.00305 7.87378 6.59498 2.82 12.5247 2.09283Z"
fill="#FF4E4E" />
<circle cx="7.58784" cy="12.8624" r="1.96503" fill="#FF4E4E" />
<circle cx="8.82887" cy="19.2745" r="1.3445" fill="#FF4E4E" />
<circle cx="13.6897" cy="14.5171" r="1.03423" fill="#FF4E4E" />
<circle cx="11.4144" cy="7.48439" r="0.930805" fill="#FF4E4E" />
<circle cx="17.5164" cy="20.3089" r="1.86161" fill="#FF4E4E" />
<circle cx="21.3432" cy="6.7604" r="0.930805" fill="#FF4E4E" />
<circle cx="22.1706" cy="1.89958" r="1.44792" fill="#FF4E4E" />
<circle cx="26.8245" cy="8.31185" r="0.72396" fill="#FF4E4E" />
</svg>
</button>
{{-- BANNER --}}
<div id="cn-banner" tabindex="-1">
<div class="cn-modal-top-line">
<button id="cn-close-modal">X</button>
</div>
{{-- CONTENT VIEW --}}
<div class="cn-content">
{{-- 1ST PAGE BANNER --}}
<div class="cn-banner-content">
<div class="cn-banner-img">
<img src="{{ $logo_picture_url }}" alt="{{ $logo_alt_text }}">
</div>
<div class="cn-banner-text">
<div class="cn-banner-title">
<span>{!! nl2br(e($strings->banner_title)) !!}</span>
</div>
<div class="cn-banner-para-p">
<p class="cn-banner-para-p-close">{!! nl2br(e($strings->banner_text)) !!}</p>
<p class="cn-banner-para-p-open d-none">{!! nl2br(e($strings->banner_text_open)) !!}</p>
</div>
</div>
<div class="cn-banner-details">
<p>
{!! nl2br(e($strings->banner_details)) !!}<br>
<a href="{{ $confidentiality_page_url }}" title="{{ $strings->banner_details_link_title }}">{{ $strings->banner_details_link }}</a>
</p>
</div>
<div class="cn-banner-btn-details">
<button class="cn-banner-btn-details-p" data-open="{{ $strings->banner_less_details }}" data-close="{{ $strings->banner_more_details }}">{!!
nl2br(e($strings->banner_more_details))
!!}</button>
</div>
</div>
{{-- 2ND PAGE CUSTOMIZE PANEL --}}
<div class="cn-modal-container d-none">
<p class="cn-modal-title" aria-level="h2">{{ $strings->Panel_title }}</p>
<p class="cn-modal-subtitle">{!! nl2br(e($strings->Panel_subtitle)) !!}</p>
<p class="cn-modal-description">{!! nl2br(e($strings->Panel_details)) !!}</p>
<div class="cn-modal-wrapper">
{{-- COOKIES LIST --}}
<ul id="cn-modal-list"></ul>
</div>
</div>
</div>
{{-- NAV BAR --}}
<div class="cn-nav">
<button id="cn-deny-banner" class="cn-banner-btn cn-deny">{{ $strings->button_forbid_all }}</button>
<button id="cn-accept-banner" class="cn-banner-btn cn-accept">{{ $strings->button_allow_all }}</button>
<button id="cn-settings-banner" class="cn-banner-btn cn-custom" data-open-modal="{{ $strings->button_back }}" data-close-modal="{{ $strings->button_customize }}">{{
$strings->button_customize
}}</button>
</div>
{{-- COOKIE LIST LI TEMPLATE --}}
<div id="cn-li-template">
<div class="cn-cookie-wrapper">
<div class="cn-cookie-infos">
<span class="cn-cookie-name">#name</span>
<span class="cn-cookie-description">#description</span>
<a class="cn-cookie-link">#link</a>
</div>
<div class="cn-cookie-buttons">
<div class="deny">
<input type="radio" id="" name="" data-name="" data-status="false">
<label for="" role="button" tabindex="0">{{ $strings->button_forbid }}</label>
</div>
<div class="accept">
<input type="radio" id="" name="" data-name="" data-status="true">
<label for="" role="button" tabindex="0">{{ $strings->button_allow }}</label>
</div>
</div>
</div>
</div>
</div>
</div>

View file

@ -1,237 +0,0 @@
<?php
$site_name = get_bloginfo('name');
$logo_picture_url = get_stylesheet_directory_uri() . '/assets/images/logo-mr.png';
$logo_alt_text = "Logo " . $site_name;
$logo_title_text = "Logo " . $site_name;
$strings = (object)[
'modal_title' => 'Fenêtre de gestion de cookies',
'button_customize_cookies' => 'Personnaliser les cookies',
'button_close_cookies' => 'Fermer la fenêtre des cookies',
'button_title_open_new_tab' => 'Ouvrir le lien dans un nouvel onglet',
'button_toggle_cookie' => 'Autoriser ou refuser',
'button_forbid_all' => strtoupper('Tout refuser'),
'button_allow_all' => strtoupper('Tout accepter'),
'button_customize' => strtoupper('Personnaliser'),
'button_forbid_all_title' => 'Refuser tous les cookies et fermer le panneau des cookies',
'button_allow_all_title' => 'Accepter tous les cookies et fermer le panneau des cookies',
'button_validate_and_close' => strtoupper('Autoriser ou refuser'),
'banner_title' => 'Le site internet ' . $site_name . ' utilise des cookies' . html_entity_decode('&nbsp;') . '!',
'banner_text' => 'Nous utilisons des cookies pour nous assurer du bon fonctionnement de notre site et à des fins analytiques.
Vous pouvez changer d\'avis à tout moment en cliquant sur l\'icône présente sur chaque page de notre site.
En autorisant ces services tiers, vous acceptez le dépôt et la lecture de cookies et l\'utilisation de technologies de suivi nécessaires à leur bon fonctionnement.',
'panel_content' => 'Contenu du panneau des cookies',
'picture_cookie_title' => 'Image d\'un bon gros cookie',
'navigation_title' => 'Navigation du panneau des cookie'
];
$cookies = [];
// YOUTUBE
$cookies['youtube'] = [
'name' => 'VIDEOS - Youtube',
'description' => 'Les cookies déposés via les services de partage de vidéo ont pour finalité de permettre à
l’utilisateur de visionner directement sur le site le contenu multimédia.',
'link' => 'https://policies.google.com/technologies/cookies?hl=fr&utm_source=ucb',
'labelLink' => 'En savoir +',
'cookies' => ['NID', 'VISITOR_INFO1_LIVE', 'YSC']
];
$cookies['youtube']['script'] = <<<SCRIPT
function () {
let youtubeVids = document.getElementsByClassName('cn-youtube');
for (let item of youtubeVids) {
let id = item.dataset.id;
let e = document.createElement('iframe');
e.src = "https://www.youtube.com/embed/" + id;
e.width = "640";
e.height = "360";
e.frameBorder = "0";
e.allow = "accelerometer; autoplay; clipboard-write; encrypted-media; gyroscope; picture-in-picture";
e.allowFullscreen = true;
item.innerHTML = "";
item.appendChild(e);
}
}
SCRIPT;
$cookies['youtube']['fallback'] = <<<FALLBACK
function () {
let youtubeVids = document.getElementsByClassName('cn-youtube');
for (let item of youtubeVids) {
let a = document.createElement('a');
a.innerText = 'Autoriser';
a.classList.add('cn-cookie-link');
a.setAttribute('role', 'button');
a.onclick = function () {
WebCookieNotice.openCookieModalToCookiePage();
};
let e = document.createElement('p');
e.innerHTML = 'Youtube est désactivé. ';
item.innerHTML = "";
e.appendChild(a);
item.appendChild(e);
}
}
FALLBACK;
// VIMEO
$cookies['vimeo'] = [
'name' => 'VIDEOS - Vimeo',
'description' => 'Les cookies déposés via les services de partage de vidéo ont pour finalité de permettre à
l’utilisateur de visionner directement sur le site le contenu multimédia.',
'link' => 'https://vimeo.com/cookie_policy',
'labelLink' => 'En savoir +',
'cookies' => ['NID', 'VISITOR_INFO1_LIVE', 'YSC']
];
$cookies['vimeo']['script'] = <<<SCRIPT
function () {
let vimeoVids = document.getElementsByClassName('cn-vimeo');
for (let item of vimeoVids) {
let id = item.dataset.id;
let e = document.createElement('iframe');
e.src = "https://player.vimeo.com/video/" + id;
e.width = "640";
e.height = "360";
e.frameBorder = "0";
e.allow = "autoplay; fullscreen; picture-in-picture";
e.allowFullscreen = true;
item.innerHTML = "";
item.appendChild(e);
}
}
SCRIPT;
$cookies['vimeo']['fallback'] = <<<FALLBACK
function () {
let vimeoVids = document.getElementsByClassName('cn-vimeo');
for (let item of vimeoVids) {
let a = document.createElement('a');
a.innerText = 'Autoriser';
a.classList.add('cn-cookie-link');
a.setAttribute('role', 'button');
a.onclick = function () {
WebCookieNotice.openCookieModalToCookiePage();
};
let e = document.createElement('p');
e.innerHTML = 'Vimeo est désactivé. ';
item.innerHTML = "";
e.appendChild(a);
item.appendChild(e);
}
}
FALLBACK;
// RECAPTCHA
$cookies['recaptcha'] = [
'name' => 'API - reCAPTCHA',
'description' => 'Les cookies qui sont déposés via le recaptcha sur les formulaires ont pour
finalité d\'empêcher que ceux-ci ne soient soumis par des robots.',
'link' => 'https://policies.google.com/privacy',
'labelLink' => 'En savoir +',
'cookies' => ['NID', '__Secure-3PAPISID', '__Secure-3PSID', '__Secure-3PSIDCC']
];
$cookies['recaptcha']['script'] = <<<SCRIPT
function () {
if (window.__CN_Recaptcha) {
window.__CN_Recaptcha();
}
}
SCRIPT;
// ANALYCTICS
$cookies['analytics'] = [
'name' => 'MESURES D’AUDIENCE' . ' - Google Analytics',
'description' => 'Les cookies qui sont déposés via le recaptcha sur les formulaires ont pour finalité
d’empêcher que ceux-ci ne soient soumis par des robots.',
'link' => 'https://policies.google.com/privacy',
'labelLink' => 'En savoir +',
'cookies' => [
'_ga',
'_gat_gtag_G_GVRHBCHE09',
'_gid'
]
];
$cookies['analytics']['script'] = <<<SCRIPT
function () {
(function (d, t) {
var g = d.createElement(t),
s = d.getElementsByTagName(t)[0];
g.src = 'https://www.googletagmanager.com/gtag/js?id=G-GVRHBCHE09';
g.id = 'analytics';
s.parentNode.insertBefore(g, s)
}(document, 'script'));
window.dataLayer = window.dataLayer || [];
function gtag() {
dataLayer.push(arguments);
}
gtag('js', new Date());
gtag('config', 'G-GVRHBCHE09');
}
SCRIPT;
// MATOMO
$cookies['matomo'] = [
'name' => 'Matomo',
'description' => 'Les services de mesure d\'audience permettent de générer des statistiques de fréquentation utiles à l\'amélioration du site.',
'link' => 'https://fr.matomo.org/gdpr-analytics/',
'labelLink' => 'En savoir +',
'cookies' => ['_pk']
];
$cookies['matomo']['script'] = <<<SCRIPT
function () {
var _paq = window._paq = window._paq || [];
/* tracker methods like "setCustomDimension" should be called before "trackPageView" */
_paq.push(['trackPageView']);
_paq.push(['enableLinkTracking']);
(function() {
var u="//yl.s-web.fr/";
_paq.push(['setTrackerUrl', u+'rainbow']);
_paq.push(['setSiteId', '
SCRIPT;
$cookies['matomo']['script'] .= MATOMO_SITE_ID;
$cookies['matomo']['script'] .= <<<SCRIPT
']);
var d=document, g=d.createElement('script'), s=d.getElementsByTagName('script')[0];
g.async=true; g.src=u+'unicorn'; s.parentNode.insertBefore(g,s);
})();
}
SCRIPT;
?>
<?php include('cookie-notice-templates/standard.php'); ?>
<script nonce="{{ $nonce ?? '' }}">
document.addEventListener('DOMContentLoaded', function() {
window.WebCookieNotice = {};
<?php foreach ($cookies as $index_name => $cookie) { ?>
window.WebCookieNotice['<?= $index_name; ?>'] = {};
window.WebCookieNotice['<?= $index_name; ?>'].tmp = {};
// SCRIPT
window.WebCookieNotice['<?= $index_name; ?>'].tmp.script =
<?= strip_tags($cookie['script']); ?>;
<?php unset($cookie['script']); ?>
// FALLBACK
<?php if (isset($cookie['fallback'])) { ?>
window.WebCookieNotice['<?= $index_name; ?>'].tmp.fallback =
<?= strip_tags($cookie['fallback']); ?>;
<?php unset($cookie['fallback']); ?>
<?php } ?>
window.WebCookieNotice['<?= $index_name; ?>'].conf = <?= json_encode($cookie); ?>;
window.WebCookieNotice['<?= $index_name; ?>'].conf.script =
window.WebCookieNotice['<?= $index_name; ?>'].tmp.script;
window.WebCookieNotice['<?= $index_name; ?>'].conf.fallback =
window.WebCookieNotice['<?= $index_name; ?>'].tmp.fallback;
window.WebCookieNotice['<?= $index_name; ?>'] =
window.WebCookieNotice['<?= $index_name; ?>'].conf;
<?php } ?>
window.WebCookieNotice = new CookieNotice(window.WebCookieNotice);
});
</script>

View file

@ -1,68 +0,0 @@
<div id="cn-wrapper" title="<?= $strings->modal_title; ?>" role="alertdialog" tabindex="-1">
<button id="cn-cookie-btn" title="<?= $strings->button_customize_cookies; ?>">
<!-- COOKIE SVG -->
<svg viewBox="0 0 28 28" xmlns="http://www.w3.org/2000/svg">
<title><?= $strings->picture_cookie_title; ?></title>
<path fill-rule="evenodd" clip-rule="evenodd" d="M14.0001 2.93383C14.0001 4.16622 14.6159 5.25477 15.5567 5.90849C15.3526 6.46423 15.2412 7.06473 15.2412 7.69126C15.2412 10.5472 17.5564 12.8624 20.4123 12.8624C21.0807 12.8624 21.7195 12.7356 22.3059 12.5047C22.9456 13.527 24.0817 14.2069 25.3766 14.2069C26.1872 14.2069 26.9357 13.9404 27.539 13.4903C27.5453 13.6594 27.5484 13.8294 27.5484 14C27.5484 21.4826 21.4826 27.5484 14 27.5484C6.51748 27.5484 0.45166 21.4826 0.45166 14C0.45166 6.51748 6.51748 0.45166 14 0.45166C14.3209 0.45166 14.6391 0.462811 14.9543 0.484747C14.3618 1.12929 14.0001 1.98931 14.0001 2.93383ZM21.2176 2.53212C21.2195 2.54914 21.2213 2.56619 21.2229 2.58328C21.2569 2.58864 21.2909 2.59433 21.3247 2.60035C21.2891 2.57745 21.2534 2.5547 21.2176 2.53212ZM25.5171 6.86104C25.523 6.89745 25.5285 6.93399 25.5336 6.97066C25.5512 6.97141 25.5687 6.97228 25.5861 6.97328C25.5633 6.93574 25.5403 6.89833 25.5171 6.86104ZM12.5247 2.09283C12.4748 2.38291 12.4487 2.68118 12.4487 2.98553C12.4487 4.33316 12.9591 5.56158 13.7972 6.48802C13.7266 6.87842 13.6898 7.28054 13.6898 7.69126C13.6898 11.404 16.6996 14.4137 20.4123 14.4137C20.8725 14.4137 21.3219 14.3675 21.7562 14.2794C22.689 15.1941 23.9669 15.7582 25.3766 15.7582C25.5439 15.7582 25.7094 15.7503 25.8726 15.7347C25.0321 21.5385 20.0368 25.9971 14.0001 25.9971C7.37431 25.9971 2.00305 20.6258 2.00305 14.0001C2.00305 7.87378 6.59498 2.82 12.5247 2.09283Z" fill="#FF4E4E" />
<circle cx="7.58784" cy="12.8624" r="1.96503" fill="#FF4E4E" />
<circle cx="8.82887" cy="19.2745" r="1.3445" fill="#FF4E4E" />
<circle cx="13.6897" cy="14.5171" r="1.03423" fill="#FF4E4E" />
<circle cx="11.4144" cy="7.48439" r="0.930805" fill="#FF4E4E" />
<circle cx="17.5164" cy="20.3089" r="1.86161" fill="#FF4E4E" />
<circle cx="21.3432" cy="6.7604" r="0.930805" fill="#FF4E4E" />
<circle cx="22.1706" cy="1.89958" r="1.44792" fill="#FF4E4E" />
<circle cx="26.8245" cy="8.31185" r="0.72396" fill="#FF4E4E" />
</svg>
</button>
<!-- BANNER -->
<div id="cn-banner" tabindex="-1">
<div class="cn-modal-top-line">
<button id="cn-close-modal" title="<?= $strings->button_close_cookies; ?>">X</button>
</div>
<!-- CONTENT VIEW -->
<div class="cn-content" title="<?= $strings->panel_content; ?>" tabindex="0">
<!-- 1ST PAGE BANNER -->
<div class="cn-banner-content">
<div class="cn-banner-img">
<img src="<?= $logo_picture_url; ?>" title="<?= $logo_title_text; ?>" alt="<?= $logo_alt_text; ?>">
</div>
<div class="cn-banner-text">
<div class="cn-banner-title">
<span><?= nl2br($strings->banner_title); ?></span>
</div>
<div class="cn-banner-para-p">
<p><?= nl2br($strings->banner_text); ?></p>
</div>
</div>
</div>
<!-- 2ND PAGE CUSTOMIZE PANEL -->
<div class="cn-modal-container d-none">
<!-- COOKIES LIST -->
<ul id="cn-modal-list"></ul>
</div>
</div>
<!-- NAV BAR -->
<div class="cn-nav" title="<?= $strings->navigation_title; ?>" role="navigation">
<button class="cn-banner-btn cn-deny" id="cn-deny-banner" title="<?= $strings->button_forbid_all_title; ?>"><?= $strings->button_forbid_all; ?></button>
<button class="cn-banner-btn cn-accept" id="cn-accept-banner" title="<?= $strings->button_allow_all_title; ?>"><?= $strings->button_allow_all; ?></button>
<button class="cn-banner-btn cn-custom" id="cn-settings-banner" data-open-modal="<?= $strings->button_validate_and_close; ?>" data-close-modal="<?= $strings->button_customize; ?>"><?= $strings->button_customize; ?></button>
</div>
<!-- COOKIE LIST LI TEMPLATE -->
<div id="cn-li-template">
<div class="cn-cookie-wrapper">
<div class="cn-cookie-infos">
<span class="cn-cookie-name">#name</span>
<span class="cn-cookie-description">#description</span>
<a class="cn-cookie-link" title="<?= $strings->button_title_open_new_tab; ?>" target="blank">#link</a>
</div>
<div class="cn-cookie-buttons">
<label class="cn-switch" role="checkbox" aria-label="<?= $strings->button_toggle_cookie ?>" title="<?= $strings->button_toggle_cookie ?>" aria-checked="undefined" tabindex="0">
<input type="checkbox" tabindex="-1" />
<span></span>
</label>
</div>
</div>
</div>
</div>
</div>

10202
package-lock.json generated

File diff suppressed because it is too large Load diff

View file

@ -1,12 +1,12 @@
{
"name": "@ldc-web/cookie-notice",
"version": "6.1.1",
"version": "3.0.3",
"description": "Web cookie notice for websites usage",
"main": "./dist/umd/main.js",
"module": "./dist/esm/ts/index.js",
"types": "./dist/typings/ts/index.d.ts",
"module": "./dist/esm/index.js",
"types": "./dist/typings/index.d.ts",
"sass": "./src/scss/themes/standard.scss",
"style": "./dist/umd/css/standard.css",
"style": "./dist/css/cookie-notice-standard.css",
"browserslist": "last 3 version, not dead, >0.3%",
"directories": {
"example": "examples"
@ -31,29 +31,19 @@
"scripts": {
"test": "echo \"Error: no test specified\" && exit 1",
"prod": "npm run build",
"build": "npm run prebuild && rm -rf ./dist/umd && webpack --progress && npm run buildbrowser",
"buildbrowser": "rm -rf ./dist/browser && node ./node_modules/.bin/rollup --bundleConfigAsCjs -c rollup.config.js",
"prebuild": "npm run stylelint && npm run eslint && rm -rf ./dist/typings && rm -rf ./dist/esm && tsc -p ./tsconfig.json",
"buildPackage": "git checkout main && git reset && git merge --no-ff --no-commit -m \"chore: 📦 Npm run build\" develop && npm run build && git add -f \"dist/\" && git commit --no-edit && echo 'DONE !!';",
"eslint": "node ./node_modules/.bin/eslint --max-warnings 0 -c .eslintrc.json ./src",
"eslint-fix": "node ./node_modules/.bin/eslint --fix --max-warnings 0 -c .eslintrc.json ./src",
"eslint-ci": "node ./node_modules/.bin/eslint --max-warnings 0 -c .eslintrc.json ./src -f junit",
"stylelint": "node ./node_modules/.bin/stylelint --config './.stylelintrc.json' --max-warnings 0 '**/*.scss'",
"stylelint-fix": "node ./node_modules/.bin/stylelint --config './.stylelintrc.json' --fix --max-warnings 0 '**/*.scss'",
"stylelint-ci": "node ./node_modules/.bin/stylelint --config './.stylelintrc.json' --max-warnings 0 '**/*.scss' -f json"
"build": "rm -rf ./dist/{esm,typings} && webpack --progress",
"prebuild": "npm run stylelint && npm run eslint && tsc -p ./tsconfig.json",
"eslint": "node ./node_modules/.bin/eslint -c .eslintrc.json ./src",
"eslint-ci": "node ./node_modules/.bin/eslint -c .eslintrc.json ./src -f junit",
"stylelint": "npx stylelint '**/*.scss'",
"stylelint-ci": "npx stylelint '**/*.scss' -f json"
},
"devDependencies": {
"@babel/core": "^7.22.11",
"@babel/preset-env": "^7.23.6",
"@babel/preset-typescript": "^7.23.3",
"@babel/types": "^7.21.2",
"@rollup/plugin-babel": "^6.0.3",
"@rollup/plugin-terser": "^0.4.3",
"@rollup/plugin-typescript": "^11.1.1",
"@typescript-eslint/parser": "^7.3.1",
"@vue/eslint-config-typescript": "^12.0.0",
"@babel/preset-env": "^7.21.4",
"@babel/preset-typescript": "^7.21.4",
"@typescript-eslint/parser": "^5.58.0",
"@vue/eslint-config-typescript": "^11.0.2",
"babel-loader": "^9.1.2",
"core-js": "^3.30.2",
"eslint": "^8.38.0",
"eslint-config-typescript": "^3.0.0",
"eslint-plugin-vue": "^9.10.0",
@ -61,20 +51,19 @@
"postcss": "^8.4.21",
"postcss-scss": "^4.0.6",
"prettier": "^2.8.7",
"rollup": "^3.23.0",
"rollup-plugin-scss": "^3.0.0",
"sass": "^1.58.3",
"sass-loader": "^13.3.1",
"stylelint": "^15.11.0",
"stylelint-config-idiomatic-order": "github:ream88/stylelint-config-idiomatic-order",
"sass": "^1.61.0",
"sass-loader": "^13.2.2",
"stylelint": "^15.4.0",
"stylelint-config-idiomatic-order": "^9.0.0",
"stylelint-config-sass-guidelines": "^10.0.0",
"stylelint-config-standard-scss": "^11.1.0",
"stylelint-scss": "^5.3.2",
"stylelint-config-standard-scss": "^8.0.0",
"stylelint-webpack-plugin": "^4.1.1",
"tslib": "^2.6.2",
"typescript": ">=3.3.1 <5.2.0",
"typescript-eslint": "^7.3.1",
"typescript": "^5.0.4",
"typescript-eslint": "^0.0.1-alpha.0",
"webpack": "^5.78.0",
"webpack-cli": "^5.0.1"
},
"dependencies": {
"core-js": "^3.30.0"
}
}

20
rollup.config.js vendored
View file

@ -1,20 +0,0 @@
import typescript from "@rollup/plugin-typescript";
import { babel } from "@rollup/plugin-babel";
import terser from "@rollup/plugin-terser";
import scss from "rollup-plugin-scss";
export default {
input: "./src/ts/export/global.ts",
output: {
file: "./dist/browser/cookie-cn.js",
format: "iife",
name: "CookieNotice",
strict: false
},
plugins: [
scss({ fileName: "cookie-cn.css" }),
typescript(),
babel({ babelHelpers: "runtime" }),
terser()
]
};

858
src/index.ts Normal file
View file

@ -0,0 +1,858 @@
export default class CookieNotice {
browserCookieName = "cn-init";
cookiePolicies: CookiePolicy = {
sameSite: CookiePolicySameSite.lax,
secure: "",
};
config: Record<string, CookieOptions>;
modalBg: HTMLDivElement;
cookieContainer: HTMLDivElement;
bannerContainer: HTMLDivElement;
modalContainer: HTMLDivElement;
cookieShowModalBtn: HTMLButtonElement;
cookieCloseModalBtn: HTMLButtonElement;
bannerDetailsCollapseBtn: HTMLButtonElement;
bannerParaP: HTMLDivElement;
detailsTextOpen: HTMLParagraphElement;
detailsTextClose: HTMLParagraphElement;
bannerContent: HTMLDivElement;
bannerDetails: HTMLDivElement;
bannerDetailsContainer: HTMLDivElement;
acceptAllBtn: HTMLButtonElement;
denyAllBtn: HTMLButtonElement;
customizeBtn: HTMLButtonElement;
cookiesUnorderedList: HTMLUListElement;
cookieLinkShowCustomizeModalList: NodeListOf<HTMLAnchorElement>;
modalWrapper: HTMLDivElement;
template: HTMLDivElement;
bannerDetailsAreExpanded: boolean;
constructor(config: Record<string, CookieOptions>) {
// * Setup Config
this.config = config;
// * Inject DOM modal BG
const modalBg = document.createElement("div");
modalBg.classList.add("cn-modal-bg");
document.body.append(modalBg);
this.modalBg = modalBg;
// * Setup Dom Elements
const cookieContainer = document.querySelector(
"div#cn-wrapper"
) as HTMLDivElement | null,
cookieShowModalBtn = document.querySelector(
"button#cn-cookie-btn"
) as HTMLButtonElement | null,
cookieCloseModalBtn = document.querySelector(
"button#cn-close-modal"
) as HTMLButtonElement | null,
cookieLinkShowCustomizeModalPageList = document.querySelectorAll(
"a.cn-cookie-link"
) as NodeListOf<HTMLAnchorElement>,
bannerContainer = document.querySelector(
"div#cn-banner"
) as HTMLDivElement | null,
bannerContent = document.querySelector(
"div.cn-banner-content"
) as HTMLDivElement | null,
bannerDetails = document.querySelector(
"div.cn-banner-details"
) as HTMLDivElement | null,
bannerParaP = document.querySelector(
"div.cn-banner-para-p"
) as HTMLDivElement | null,
detailsTextOpen = document.querySelector(
"p.cn-banner-para-p-open"
) as HTMLParagraphElement | null,
detailsTextClose = document.querySelector(
"p.cn-banner-para-p-close"
) as HTMLParagraphElement | null,
bannerDetailsCollapseBtn = document.querySelector(
"button.cn-banner-btn-details-p"
) as HTMLButtonElement | null,
bannerDetailsContainer = document.querySelector(
"div.cn-banner-btn-details"
) as HTMLDivElement | null,
modalContainer = document.querySelector(
"div.cn-modal-container"
) as HTMLDivElement | null,
acceptAllBtn = document.querySelector(
"button#cn-accept-banner"
) as HTMLButtonElement | null,
denyAllBtn = document.querySelector(
"button#cn-deny-banner"
) as HTMLButtonElement | null,
customizeBtn = document.querySelector(
"button#cn-settings-banner"
) as HTMLButtonElement | null,
cookiesUnorderedList = document.querySelector(
"ul#cn-modal-list"
) as HTMLUListElement | null,
modalWrapper = document.querySelector(
"div.cn-modal-wrapper"
) as HTMLDivElement,
template = document.querySelector(
"div#cn-li-template"
) as HTMLDivElement | null;
if (!cookieContainer) {
throw new Error("Cannot find div#cn-wrapper");
}
if (!cookieShowModalBtn) {
throw new Error("Cannot find 'button#cn-cookie-btn' element");
}
if (!cookieCloseModalBtn) {
throw new Error("Cannot find 'button#cn-close-modal' element");
}
if (!bannerContainer) {
throw new Error("Cannot find 'div#cn-banner' element");
}
if (!bannerContent) {
throw new Error("Cannot find 'div.cn-banner-content' element");
}
if (!bannerDetails) {
throw new Error("Cannot find 'div.cn-banner-details' element");
}
if (!bannerParaP) {
throw new Error("Cannot find 'div.cn-banner-para-p' element");
}
if (!detailsTextOpen) {
throw new Error("Cannot find 'p.cn-banner-para-p-open' element");
}
if (!detailsTextClose) {
throw new Error("Cannot find 'p.cn-banner-para-p-close' element");
}
if (!bannerDetailsCollapseBtn) {
throw new Error(
"Cannot find 'button.cn-banner-btn-details-p' element"
);
}
if (!bannerDetailsContainer) {
throw new Error("Cannot find '.cn-banner-btn-details' element");
}
if (!modalContainer) {
throw new Error("Cannot find 'div.cn-modal-container' element");
}
if (!acceptAllBtn) {
throw new Error("Cannot find 'button#cn-accept-banner' element");
}
if (!denyAllBtn) {
throw new Error("Cannot find 'button#cn-deny-banner' element");
}
if (!customizeBtn) {
throw new Error("Cannot find 'button.cn-settings-banner' element");
}
if (!cookiesUnorderedList) {
throw new Error("Cannot find 'ul#cn-modal-list' element");
}
if (!modalWrapper) {
throw new Error("Cannot find 'div.cn-modal-wrapper' element");
}
if (!template) {
throw new Error("Cannot find 'div#cn-li-template' element");
}
this.cookieShowModalBtn = cookieShowModalBtn;
this.cookieCloseModalBtn = cookieCloseModalBtn;
this.cookieLinkShowCustomizeModalList =
cookieLinkShowCustomizeModalPageList;
this.cookieContainer = cookieContainer;
this.bannerDetailsContainer = bannerDetailsContainer;
this.bannerContainer = bannerContainer;
this.bannerContent = bannerContent;
this.cookiesUnorderedList = cookiesUnorderedList;
this.modalWrapper = modalWrapper;
this.bannerParaP = bannerParaP;
this.detailsTextOpen = detailsTextOpen;
this.detailsTextClose = detailsTextClose;
this.bannerDetails = bannerDetails;
this.bannerDetailsCollapseBtn = bannerDetailsCollapseBtn;
this.modalContainer = modalContainer;
this.acceptAllBtn = acceptAllBtn;
this.denyAllBtn = denyAllBtn;
this.customizeBtn = customizeBtn;
this.bannerDetailsAreExpanded = false;
this.template = template;
const memoryTemplate = this.template.cloneNode(true) as HTMLDivElement;
this.template.remove();
this.template = memoryTemplate;
// * Setup Events
this.addEventPrevent(this.modalBg, "click", this.closeCookieModal);
this.addEventPrevent(
this.cookieCloseModalBtn,
"click",
this.closeCookieModal
);
this.addEventPrevent(this.acceptAllBtn, "click", this.acceptAllCookies);
this.addEventPrevent(this.denyAllBtn, "click", this.denyAllCookies);
this.addEventPrevent(
this.customizeBtn,
"click",
this.toggleCookieModalPages
);
this.addEventPrevent(
this.bannerDetailsCollapseBtn,
"click",
this.toggleBannerDetails
);
this.addEventPrevent(
this.cookieShowModalBtn,
"click",
this.toggleCookieModal
);
this.cookieLinkShowCustomizeModalList.forEach((cookieLink) => {
this.addEventPrevent(
cookieLink,
"click",
this.openCookieModalToCookiePage
);
});
// * Setup CN Cookie
if (!this.cookiesMatchesConfig()) {
// * Setup Browser Cookie if none.
this.resetBrowserCookie();
this.openCookieModalToBannerPage();
}
// * Cookie should have been created from here.
const cookies = this.getCookieStatusList();
Object.entries(cookies).forEach(([cookieName, cookieStatus]) => {
if (cookieStatus === CookieStatus.wait) {
// * Open modal if any cookie config is not set.
this.openCookieModalToBannerPage();
return;
}
if (!this.config[cookieName]) {
// * Ignore missing config
return;
}
if (cookieStatus === CookieStatus.true) {
// * Exec script part for accepted cookie.
this.config[cookieName].script();
return;
}
if (this.config[cookieName].fallback != null) {
// * Exec fallback part for accepted cookie if provided.
this.config[cookieName].fallback();
}
});
}
// COOKIES
/**
* Check if the actual cookie matches the config
*/
cookiesMatchesConfig(): boolean {
const cookies = this.getCookieStatusList();
return Object.keys(cookies).length === Object.keys(this.config).length;
}
/**
* Accept a specific cookie
*/
acceptAllCookies() {
Object.entries(this.config).forEach(([cookieName, cookieOption]) =>
this.setCookieStatus(cookieName, CookieStatus.true, cookieOption)
);
for (const acceptLabel of this.cookieContainer.querySelectorAll(
".accept > label"
)) {
acceptLabel.classList.add("active");
}
for (const denyLabel of this.cookieContainer.querySelectorAll(
".deny > label"
)) {
denyLabel.classList.remove("active");
}
this.closeCookieModal();
}
/**
* Deny a specific cookie
*/
denyAllCookies() {
Object.entries(this.config).forEach(([cookieName, cookieOption]) =>
this.setCookieStatus(cookieName, CookieStatus.false, cookieOption)
);
for (const acceptLabel of this.cookieContainer.querySelectorAll(
".accept > label"
)) {
acceptLabel.classList.remove("active");
}
for (const denyLabel of this.cookieContainer.querySelectorAll(
".deny > label"
)) {
denyLabel.classList.add("active");
}
this.closeCookieModal();
}
/**
* Fetch the cookie status list
*
* @returns the cookie status list
*/
getCookieStatusList(): CookieStatusList {
const cookies = this.getBrowserCookieValue(),
statusList: CookieStatusList = {};
if (cookies === undefined) {
return statusList;
}
/** specificCookieString contains youtube=true like */
cookies.split(",").forEach((specificCookieString) => {
const values = specificCookieString.split("=");
statusList[values[0]] = values[1] as CookieStatus;
});
return statusList;
}
/**
* Check has cookie status
*
* @param key
* @param value
*/
containsCookieStatus(key: string): boolean {
const statusList: CookieStatusList = this.getCookieStatusList();
return (
Object.keys(statusList).find((cookieName) => cookieName === key) !==
undefined
);
}
/**
* Set the cookie value
*
* @param cookieName
* @param status
* @param cookieOption
*/
setCookieStatus(
cookieName: string,
status: CookieStatus,
cookieOption: CookieOptions
) {
if (status === CookieStatus.true) {
this.addCookieStatus(cookieName, cookieOption);
return;
}
if (status === CookieStatus.false) {
this.removeCookieStatus(cookieName, cookieOption);
return;
}
this.setBrowserCookieStatus(cookieName, CookieStatus.wait);
}
/**
* Add a specific cookie and
* change his status to true
*
* @param cookieName
* @param cookieOption
*/
addCookieStatus(cookieName: string, cookieOption: CookieOptions) {
if (cookieOption.script) {
cookieOption.script();
}
this.setBrowserCookieStatus(cookieName, CookieStatus.true);
}
/**
* Remove a specific cookie and
* change his status to false
*
* @param cookieName
* @param cookieOption
*/
removeCookieStatus(cookieName: string, cookieOption: CookieOptions) {
const cookieNameElement = document.getElementById(cookieName);
if (cookieNameElement) {
cookieNameElement.remove();
}
if (cookieOption.fallback) {
cookieOption.fallback();
}
this.setBrowserCookieStatus(cookieName, CookieStatus.false);
}
/**
* Change the status of a cookie
*
* @param cookieName
* @param status
*/
setBrowserCookieStatus(cookieName: string, status: CookieStatus) {
const statusList: CookieStatusList = this.getCookieStatusList();
// * Force refresh
this.deleteBrowserCookie();
statusList[cookieName] = status;
this.saveBrowserCookie(statusList);
}
/**
* Has CN cokie setup ?
* @returns true if the cookie is setup
*/
hasBrowserCookie(): boolean {
return Boolean(this.getBrowserCookieValue());
}
/**
* Get the Ldcweb cookie
*
* @returns A string like analytics=true,youtube=true or undefined
*/
getBrowserCookieValue() {
const matches = document.cookie.match(
new RegExp(
"(?:^|; )" +
this.browserCookieName.replace(
/([.$?*|{}()[\]\\/+^])/g,
"\\$1"
) +
"=([^;]*)"
)
);
return matches ? decodeURIComponent(matches[1]) : undefined;
}
/**
* Save cookie content on web browser
*
* @param list
*/
saveBrowserCookie(statusList: CookieStatusList) {
const date = new Date(),
newDate = new Date(date.setMonth(date.getMonth() + 13)),
content = Object.entries(statusList)
.map(([cookieName, cookieStatus]) => {
return `${cookieName}=${cookieStatus}`;
})
.join(",");
document.cookie = `${this.browserCookieName}=${content};path=/${
location.hostname ? `;domain=${location.hostname}` : ""
};expires=${newDate.toUTCString()};${this.getCookiePoliciesAsString()}`;
}
/**
* Set an older expire parameter to a specific cookie
*/
deleteBrowserCookie() {
if (this.hasBrowserCookie()) {
// * Suppression du cookie et de sa version precedé d'un point
document.cookie = `${this.browserCookieName}=;path=/${
location.hostname ? `;domain=.${location.hostname}` : ""
};expires=Thu, 01 Jan 1970 00:00:01 GMT;${this.getCookiePoliciesAsString()}`;
document.cookie = `${this.browserCookieName}=;path=/${
location.hostname ? `;domain=${location.hostname}` : ""
};expires=Thu, 01 Jan 1970 00:00:01 GMT;${this.getCookiePoliciesAsString()}`;
}
}
getCookiePoliciesAsString(): string {
return Object.entries(this.cookiePolicies)
.map(([policyName, policyValue]) => `${policyName}=${policyValue}`)
.join(";");
}
/**
* Reset Ldc Web CN cookie
*/
resetBrowserCookie() {
// * Create Cookie as It does not exists.
const newCookieList: CookieStatusList = {};
Object.entries(this.config).forEach(
([cookieName]) => (newCookieList[cookieName] = CookieStatus.wait)
);
this.saveBrowserCookie(newCookieList);
}
// LISTENERS
/**
* Add event on a specific element
*
* @param element
* @param evnt
* @param funct
* @returns
*/
addEvent(element: HTMLElement, evnt: string, funct: (e: Event) => void) {
return element.addEventListener(evnt, funct.bind(this), false);
}
/**
* Add event on a specific element and prevent default
*
* @param element
* @param evnt
* @param funct
* @returns
*/
addEventPrevent(
element: HTMLElement,
evnt: string,
funct: (e: Event) => void
) {
return element.addEventListener(
evnt,
(e) => {
e.preventDefault();
funct.call(this, e);
},
false
);
}
/**
* Add event on a specific element
*
* @param element
* @param evnt
* @param funct
* @returns
*/
addEventKbdValidate(element: HTMLElement, funct: (e: Event) => void) {
return this.addEvent(element, "keyup", (e: Event) => {
const kbdEvt = e as KeyboardEvent;
if (
kbdEvt.key == " " ||
kbdEvt.code == "Space" ||
kbdEvt.keyCode == 32 ||
kbdEvt.key == "Enter" ||
kbdEvt.code == "Enter" ||
kbdEvt.keyCode == 13
) {
funct.call(this, kbdEvt);
}
});
}
// COOKIE MODAL
/**
* Show or hide Cookie modal
* @returns
*/
toggleCookieModal() {
if (!document.body.classList.contains("cn-open")) {
this.openCookieModalToBannerPage();
return;
}
this.closeCookieModal();
}
/**
* Open the cookies modal to the banner page
*/
openCookieModalToBannerPage() {
this.openCookieModalToCookiePage();
this.toggleCookieModalPages();
}
/**
* Open the cookies modal to the cookies page
*/
openCookieModalToCookiePage() {
document.body.classList.add("cn-open");
this.resetCookieModal();
this.bannerContent.classList.add("d-none");
this.bannerDetails.classList.add("d-none");
this.bannerDetailsContainer.classList.add("d-none");
this.modalContainer.classList.remove("d-none");
// Scroll to the top of the cookies list
this.modalWrapper.scrollTop = 0;
this.setupCookieModalList();
this.setTabIndex();
}
/**
* Hide the cookies modal
*/
closeCookieModal() {
document.body.classList.remove("cn-open");
this.bannerContent.classList.toggle("d-none");
this.bannerDetails.classList.toggle("d-none");
this.bannerDetailsContainer.classList.toggle("d-none");
this.modalContainer.classList.toggle("d-none");
this.unsetTabIndex();
this.setupCookieModalList();
}
/**
* Setup tab indexes on visible elements
*/
setTabIndex() {
// * Prevent focus html tag
document.documentElement.setAttribute("tabindex", "-1");
setTimeout(() => {
const focusableSelector =
"a[href], button, [role=\"button\"], input, embed, object, iframe, textarea, select, details, [tabindex]:not([tabindex=\"-1\"])";
// * Only focusable elements
[...document.body.querySelectorAll(focusableSelector)]
.filter(
(el) =>
!el.hasAttribute("disabled") &&
!el.getAttribute("aria-hidden")
)
.forEach((el) => {
(el as HTMLElement).setAttribute("tabindex", "-1");
(el as HTMLElement).classList.add("cn-disabled");
});
[...this.cookieContainer.querySelectorAll(focusableSelector)]
.filter(
(el) =>
!el.hasAttribute("disabled") &&
!el.getAttribute("aria-hidden") &&
// * Only visible elements
!!(
(el as HTMLElement).offsetWidth ||
(el as HTMLElement).offsetHeight ||
el.getClientRects().length
)
)
.forEach((el) => {
(el as HTMLElement).setAttribute("tabindex", "0");
(el as HTMLElement).classList.remove("cn-disabled");
});
this.cookieShowModalBtn.setAttribute("tabindex", "-1");
}, 500);
}
/**
* Undo setup tab indexes on visible elements
*/
unsetTabIndex() {
document.documentElement.setAttribute("tabindex", "0");
setTimeout(() => {
document.body.querySelectorAll(".cn-disabled").forEach((el) => {
(el as HTMLElement).setAttribute("tabindex", "0");
(el as HTMLElement).classList.remove("cn-disabled");
});
this.cookieShowModalBtn.setAttribute("tabindex", "0");
}, 500);
}
/**
* Reset the modal view state
*/
resetCookieModal() {
this.bannerContent.classList.remove("d-none");
this.bannerDetails.classList.remove("d-none");
this.bannerDetailsContainer.classList.remove("d-none");
this.modalContainer.classList.add("d-none");
if (!this.customizeBtn.dataset.openModal) {
throw new Error("Cannot find attribut data-open-modal");
}
this.customizeBtn.innerHTML = this.customizeBtn.dataset.openModal;
}
/**
* Set the cookies list in the modal
*/
setupCookieModalList() {
this.cookiesUnorderedList.innerHTML = "";
Object.entries(this.config).forEach(([cookieName, cookieConfig]) => {
const cookie = document.createElement("li");
const childItem = this.template.children.item(
0
) as HTMLDivElement | null;
if (childItem === null) {
throw new Error("Cannot find child item");
}
cookie.append(childItem.cloneNode(true));
const name = cookie.querySelector(
"span.cn-cookie-name"
) as HTMLSpanElement;
const description = cookie.querySelector(
"span.cn-cookie-description"
) as HTMLSpanElement;
const link = cookie.querySelector(
".cn-cookie-link"
) as HTMLButtonElement;
const acceptInput = cookie.querySelector(
".accept > input"
) as HTMLInputElement;
const denyInput = cookie.querySelector(
".deny > input"
) as HTMLInputElement;
const acceptLabel = cookie.querySelector(
".accept > label"
) as HTMLLabelElement;
const denyLabel = cookie.querySelector(
".deny > label"
) as HTMLLabelElement;
name.textContent = cookieConfig.name;
description.textContent = cookieConfig.description;
link.textContent = cookieConfig.labelLink;
link.setAttribute("href", cookieConfig.link);
acceptInput.id = cookieName + "1";
acceptInput.name = cookieName;
acceptInput.dataset.name = cookieName;
acceptLabel.htmlFor = cookieName + "1";
denyInput.id = cookieName + "2";
denyInput.name = cookieName;
denyInput.dataset.name = cookieName;
denyLabel.htmlFor = cookieName + "2";
const acceptFn = () => {
acceptLabel.classList.add("active");
denyLabel.classList.remove("active");
this.setCookieStatus(
cookieName,
CookieStatus.true,
cookieConfig
);
},
denyFn = () => {
acceptLabel.classList.remove("active");
denyLabel.classList.add("active");
this.setCookieStatus(
cookieName,
CookieStatus.false,
cookieConfig
);
};
this.addEvent(acceptInput, "click", acceptFn);
this.addEventKbdValidate(acceptLabel, acceptFn);
this.addEvent(denyInput, "click", denyFn);
this.addEventKbdValidate(denyLabel, denyFn);
this.cookiesUnorderedList.append(cookie);
if (!this.hasBrowserCookie()) {
// * Ldcweb cookie is not set.
return;
}
// * Setup list status state
Object.entries(this.getCookieStatusList()).forEach(
([ckName, cookieStatus]) => {
if (ckName === cookieName) {
acceptLabel.classList.remove("active");
denyLabel.classList.remove("active");
switch (cookieStatus) {
case CookieStatus.true:
acceptLabel.classList.add("active");
break;
case CookieStatus.false:
denyLabel.classList.add("active");
break;
}
}
}
);
});
}
/**
* Toggle show hide banner details
*/
toggleBannerDetails() {
this.bannerDetails.classList.toggle("cn-details-open");
if (
!this.bannerDetailsCollapseBtn.dataset.open ||
!this.bannerDetailsCollapseBtn.dataset.close
) {
throw new Error("Cannot find attribute data-open or data-close");
}
if (this.bannerDetailsAreExpanded) {
this.bannerDetailsCollapseBtn.innerHTML =
this.bannerDetailsCollapseBtn.dataset.close;
this.detailsTextOpen.classList.add("d-none");
this.detailsTextClose.classList.remove("d-none");
this.bannerDetails.style.height = "0px";
this.bannerDetailsAreExpanded = false;
} else {
this.bannerDetailsCollapseBtn.innerHTML =
this.bannerDetailsCollapseBtn.dataset.open;
this.detailsTextOpen.classList.remove("d-none");
this.detailsTextClose.classList.add("d-none");
this.bannerDetails.style.height =
this.bannerDetails.children[0].clientHeight + "px";
this.bannerDetailsAreExpanded = true;
}
}
/**
* Toggle Cookie modal pages
*/
toggleCookieModalPages() {
this.bannerContent.classList.toggle("d-none");
this.bannerDetails.classList.toggle("d-none");
this.bannerDetailsContainer.classList.toggle("d-none");
this.modalContainer.classList.toggle("d-none");
this.setTabIndex();
this.setupCookieModalList();
this.togglePersonalizeBtn();
}
/**
* Toggle customize btn
*/
togglePersonalizeBtn() {
const customizeBtnBannerDataset = this.customizeBtn.dataset;
this.modalWrapper.scrollTop = 0;
if (this.bannerContent.classList.contains("d-none")) {
this.customizeBtn.innerHTML =
customizeBtnBannerDataset.openModal as string;
} else {
this.customizeBtn.innerHTML =
customizeBtnBannerDataset.closeModal as string;
}
}
}
enum CookieStatus {
true = "true",
false = "false",
wait = "wait",
}
type CookieStatusList = Record<string, keyof typeof CookieStatus>;
type CookiePolicy = {
sameSite: CookiePolicySameSite;
secure: string;
};
enum CookiePolicySameSite {
lax = "lax",
strict = "strict",
none = "none",
}
export type CookieOptions = {
name: string;
description: string;
link: string;
labelLink: string;
cookies: string[];
/**
* Fonction qui sert à initialiser la fonctionnalité
* conduisant à la génération du cookie
* @return void
*/
script: () => void;
/**
* Fonction qui sert à informer l'utilisateur
* sur chaque élèment que le cookie
* associé à la fonctionnalité
* est désactivé et propose un lien sur
* cookie notice pour l'activer
* @return void
*/
fallback: () => void | null;
};

90
src/scss/reset.scss vendored
View file

@ -1,57 +1,59 @@
@use 'sass:color';
@use './variables';
@use "sass:color";
%reset-styles {
$darker-bg-color: color.adjust($color: variables.$cn-button-bg-color, $lightness: -10%,);
$darker-bg-color: color.adjust(
$color: $cn-button-bg-color,
$lightness: -10%,
);
* {
box-sizing: border-box;
* {
box-sizing: border-box;
&::before {
display: none;
&::before {
display: none;
}
}
}
// RESET BTNS
// RESET BTNS
/* Buttons styles start */
/* Buttons styles start */
button {
display: inline-block;
padding: 0.2rem 0.5rem;
border: 0;
margin: 0;
appearance: none;
background: variables.$cn-button-bg-color;
color: #{text(variables.$cn-button-bg-color)};
cursor: pointer;
font-family: variables.$cn-button-font-family;
font-size: variables.$cn-button-font-size;
line-height: variables.$cn-button-line-height;
text-align: center;
text-decoration: none;
transition: background 250ms ease-in-out, transform 150ms ease;
}
button {
display: inline-block;
padding: 0.2rem 0.5rem;
border: 0;
margin: 0;
appearance: none;
background: $cn-button-bg-color;
color: text($cn-button-bg-color);
cursor: pointer;
font-family: $cn-button-font-family;
font-size: $cn-button-font-size;
line-height: $cn-button-line-height;
text-align: center;
text-decoration: none;
transition: background 250ms ease-in-out, transform 150ms ease;
}
button:hover,
button:focus {
background: color.adjust($color: variables.$cn-button-bg-color, $lightness: -10%);
button:hover,
button:focus {
background: color.adjust($color: $cn-button-bg-color, $lightness: -10%);
color: text(
color.adjust($color: $cn-button-bg-color, $lightness: -10%)
);
}
/* prettier-ignore */
color: text(color.adjust($color: variables.$cn-button-bg-color, $lightness: -10%));
}
button:focus {
outline: 1px solid;
outline-color: text(
color.adjust($color: $cn-button-bg-color, $lightness: -10%)
);
outline-offset: -4px;
}
button:focus {
outline: 1px solid;
button:active {
transform: scale(0.99);
}
/* prettier-ignore */
outline-color: text(color.adjust($color: variables.$cn-button-bg-color, $lightness: -10%));
outline-offset: -4px;
}
button:active {
transform: scale(0.99);
}
/* Button styles end */
/* Button styles end */
}

View file

@ -1,519 +1,543 @@
@use 'sass:color';
@use 'sass:math';
@use './../variables';
@use './../mixins';
@use './../reset';
@use "sass:color";
@import "./../variables";
@import "./../mixins";
@import "./../reset";
/** 3.0.0 */
/* FENETRE D'ACCUEIL */
$ck-bg-color: variables.$ck-background-color;
$ck-bg-color: $ck-background-color;
/* Title settings */
$ck-w1-bgcolor-title: variables.$ck-background-color;
$ck-w1-font-family-title: variables.$ck-title-font;
$ck-w1-line-height-title: variables.$ck-title-line-height;
$ck-w1-font-size-title: variables.$ck-title-size;
$ck-w1-color-title: variables.$ck-secondary-color;
$ck-w1-bgcolor-title: $ck-background-color;
$ck-w1-font-family-title: $ck-title-font;
$ck-w1-line-height-title: $ck-title-line-height;
$ck-w1-font-size-title: $ck-title-size;
$ck-w1-color-title: $ck-secondary-color;
/* Text settings */
$ck-w1-font-family-txt: variables.$ck-text-font;
$ck-w1-font-size-txt: variables.$ck-text-size;
$ck-w1-color-txt: variables.$ck-primary-color;
$ck-w1-color-href-hover: variables.$ck-secondary-color;
$ck-w1-font-family-txt: $ck-text-font;
$ck-w1-font-size-txt: $ck-text-size;
$ck-w1-color-txt: $ck-primary-color;
$ck-w1-color-href-hover: $ck-secondary-color;
/* Button settings */
$ck-w1-color-btn-hover: variables.$ck-secondary-color;
$ck-w1-font-family-btn-txt: variables.$ck-text-font;
$ck-w1-font-size-btn-txt: variables.$ck-text-size;
$ck-w1-color-btn-txt-hover: text(variables.$ck-secondary-color);
$ck-w1-color-btn-hover: $ck-secondary-color;
$ck-w1-font-family-btn-txt: $ck-text-font;
$ck-w1-font-size-btn-txt: $ck-text-size;
$ck-w1-color-btn-txt-hover: text($ck-secondary-color);
/* Title settings */
$ck-w2-font-family-title: variables.$ck-title-font;
$ck-w2-font-size-title: variables.$ck-title-size;
$ck-w2-color-title: variables.$ck-secondary-color;
$ck-w2-font-family-title: $ck-title-font;
$ck-w2-font-size-title: $ck-title-size;
$ck-w2-color-title: $ck-secondary-color;
/* Text settings */
$ck-w2-font-family-txt: variables.$ck-text-font;
$ck-w2-font-size-txt: variables.$ck-text-size;
$ck-w2-color-txt: variables.$ck-primary-color;
$ck-w2-font-family-txt: $ck-text-font;
$ck-w2-font-size-txt: $ck-text-size;
$ck-w2-color-txt: $ck-primary-color;
/* Switch Buttons */
$cn-w2-swth-height: variables.$cn-switch-height;
$cn-w2-swth-width: variables.$cn-switch-width;
$cn-w2-swth-toggle-height: variables.$cn-switch-toggle-height;
$cn-w2-swth-toggle-width: variables.$cn-switch-toggle-width;
$cn-w2-swth-toggle-color: variables.$cn-switch-toggle-color;
$cn-w2-swth-indetermined-color: variables.$cn-switch-indetermined-color;
$cn-w2-swth-unchecked-color: variables.$cn-switch-unchecked-color;
$cn-w2-swth-checked-color: variables.$cn-switch-checked-color;
$cn-w2-swth-focus-color: variables.$cn-switch-focus-color;
/* Accept/Deny btn settings */
$ck-color-accept: $ck-borders-color;
$ck-color-deny: $ck-borders-color;
$ck-color-accept-hover: $ck-accept-color;
$ck-color-deny-hover: $ck-deny-color;
$ck-color-txt: #fff;
/* Cookies list settings */
$ck-bgcolor-list: variables.$ck-list-background-color;
$ck-font-family-list: variables.$ck-text-font;
$ck-font-size-list: variables.$ck-text-size;
$ck-color-list: variables.$ck-secondary-color;
$ck-color-title: variables.$ck-secondary-color;
$ck-bgcolor-list: $ck-list-background-color;
$ck-font-family-list: $ck-text-font;
$ck-font-size-list: $ck-text-size;
$ck-color-list: $ck-secondary-color;
$ck-color-title: $ck-secondary-color;
$breakpoint-mobile: 535px;
/* Size */
$cn-w-max-height-desktop: variables.$cn-cookie-modal-max-height-desktop;
$cn-w-modal-width: variables.$cn-cookie-modal-width;
%nav-button {
display: flex;
height: variables.$cn-button-height;
flex-direction: column;
align-items: center;
justify-content: center;
padding: 0;
background-color: variables.$cn-button-bg-color;
color: #{text(variables.$cn-button-bg-color)};
font-family: variables.$ck-text-font;
font-size: $ck-w1-font-size-btn-txt;
display: flex;
height: 3rem;
flex-direction: column;
align-items: center;
justify-content: center;
padding: 0;
background-color: text($cn-button-bg-color);
color: $cn-button-bg-color;
font-family: $ck-text-font;
font-size: 1rem;
&:hover,
&:focus {
background-color: color.adjust($color: variables.$cn-button-bg-color, $lightness: -10%);
&:hover,
&:focus {
background-color: color.adjust(
$color: $cn-button-bg-color,
$lightness: -10%
);
color: text(
color.adjust($color: $cn-button-bg-color, $lightness: -10%)
);
}
/* prettier-ignore */
color: text(color.adjust($color: variables.$cn-button-bg-color, $lightness: -10%));
}
&:focus {
/* prettier-ignore */
outline-color: text(color.adjust($color: variables.$cn-button-bg-color, $lightness: -10%));
}
&:focus {
outline-color: text(
color.adjust($color: $cn-button-bg-color, $lightness: -10%)
);
}
}
// * Prevent click on clickable element using cookie notice
.cn-modal-bg {
position: fixed;
z-index: 1030;
top: 0;
left: 0;
width: 100vw;
height: 100dvh;
background-color: rgb(0 0 0 / 60%);
cursor: pointer;
opacity: 0;
transition: 0.3s;
visibility: hidden;
&-active {
cursor: default;
}
display: none;
}
.cn-open .cn-modal-bg {
opacity: 1;
visibility: visible;
position: fixed;
z-index: 1030;
top: 0;
display: block;
width: 100vw;
height: 100vh;
background-color: rgb(0 0 0 / 60%);
}
.cn-disabled {
pointer-events: none;
pointer-events: none;
}
#cn-wrapper {
@extend %reset-styles;
@extend %reset-styles;
// Display over BS elements
z-index: $cn-cookie-button-z-index;
position: fixed;
// * Display over BS elements
z-index: variables.$cn-cookie-button-z-index;
top: 0;
left: 0;
width: 100vw;
height: 100dvh;
pointer-events: none;
// BIG COOKIE BTN
#cn-cookie-btn {
position: fixed;
right: $cn-cookie-button-position-right;
bottom: $cn-cookie-button-position-bottom;
left: $cn-cookie-button-position-left;
width: 3rem;
height: 3rem;
padding: 0.5rem;
border-radius: 100%;
background-color: $ck-btn-background-color;
box-shadow: $ck-shadow-color;
cursor: pointer;
// * BIG COOKIE BTN
#cn-cookie-btn {
position: fixed;
right: variables.$cn-cookie-button-position-right;
bottom: variables.$cn-cookie-button-position-bottom;
left: variables.$cn-cookie-button-position-left;
width: variables.$cn-cookie-button-width;
height: variables.$cn-cookie-button-height;
padding: variables.$cn-cookie-button-padding;
border-radius: 100%;
background-color: variables.$ck-btn-background-color;
box-shadow: variables.$ck-shadow-color;
cursor: pointer;
pointer-events: auto;
&:focus {
outline-color: color.adjust(
$color: $ck-secondary-color,
$lightness: -10%
);
}
@media (min-width: $breakpoint-mobile) {
right: variables.$cn-cookie-button-position-right-h;
bottom: variables.$cn-cookie-button-position-bottom-h;
left: variables.$cn-cookie-button-position-left-h;
width: variables.$cn-cookie-button-width-h;
height: variables.$cn-cookie-button-height-h;
padding: variables.$cn-cookie-button-padding-h;
transition: variables.$cn-cookie-button-transition-show;
&-icon {
path {
fill: $ck-secondary-color;
}
&:hover,
&:focus {
right: variables.$cn-cookie-button-position-right;
bottom: variables.$cn-cookie-button-position-bottom;
left: variables.$cn-cookie-button-position-left;
transition: variables.$cn-cookie-button-transition-hide;
}
circle {
fill: $ck-secondary-color;
}
}
}
&:focus {
outline-color: color.adjust($color: variables.$ck-secondary-color, $lightness: -10%);
outline-offset: variables.$cn-base-font-size * 0.1;
outline-width: variables.$cn-base-font-size * 0.2;
}
// COOKIE BANNER MODAL
#cn-banner {
position: fixed;
z-index: $cn-cookie-button-z-index;
top: 0;
bottom: 0;
left: 0;
display: flex;
width: 100vw;
height: 100vh;
max-height: 100vh;
flex-direction: column;
align-items: center;
justify-content: flex-end;
padding: 0;
border-radius: 0;
margin: auto;
margin-bottom: 0;
background-color: $ck-bg-color;
box-shadow: $ck-shadow-color;
line-height: initial;
opacity: 0;
// * prevent body scroll (for mobile)
pointer-events: none;
transition: 0.3s;
user-select: none;
visibility: hidden;
&-icon {
path {
fill: variables.$ck-secondary-color;
}
.cn-modal-top-line {
align-self: end;
circle {
fill: variables.$ck-secondary-color;
}
}
}
#cn-close-modal {
width: 4rem;
height: 3rem;
border-bottom-left-radius: 0.5rem;
// * COOKIE BANNER MODAL
#cn-banner {
position: absolute;
z-index: variables.$cn-cookie-button-z-index;
top: 0;
bottom: 0;
left: 0;
display: flex;
width: 100vw;
max-height: variables.$cn-cookie-modal-max-height-mobile;
flex-direction: column;
align-items: center;
justify-content: space-between;
padding: 0;
border-radius: 0;
margin: auto;
margin-bottom: 0;
background-color: $ck-bg-color;
box-shadow: variables.$ck-shadow-color;
line-height: initial;
opacity: 0;
// * prevent body scroll (for mobile)
pointer-events: none;
transition: 0.3s;
user-select: none;
visibility: hidden;
@media (min-width: $breakpoint-mobile) {
width: 3rem;
height: 2rem;
border-top-right-radius: 0.5rem;
}
}
}
.cn-modal-top-line {
align-self: end;
#cn-close-modal {
@extend %nav-button;
width: variables.$cn-base-font-size * 4;
height: variables.$cn-base-font-size * 3;
border-bottom-left-radius: variables.$cn-base-font-size * 0.5;
// * allow child body scroll
> * {
pointer-events: all;
}
@media (min-width: $breakpoint-mobile) {
border-top-right-radius: variables.$cn-base-font-size * 0.5;
right: $cn-cookie-animation-right;
bottom: calc($cn-cookie-button-position-bottom + 60px);
left: $cn-cookie-animation-left;
width: 30rem;
height: auto;
max-height: 26rem;
border-radius: 0.5rem;
}
}
}
// * allow child body scroll
>* {
pointer-events: all;
}
@media (min-width: $breakpoint-mobile) {
right: variables.$cn-cookie-animation-right;
bottom: calc(#{variables.$cn-cookie-button-position-bottom} + 60px);
left: variables.$cn-cookie-animation-left;
width: $cn-w-modal-width;
max-height: #{math.max($cn-w-max-height-desktop - (variables.$cn-base-font-size * 12), (variables.$cn-base-font-size * 26))};
border-radius: variables.$cn-base-font-size * 0.5;
&.cn-modal-page {
max-height: $cn-w-max-height-desktop;
}
}
}
#cn-li-template {
display: none;
}
.d-none {
display: none !important;
}
// * CONTENT WRAPPER
.cn-content {
flex-basis: 100%;
flex-grow: 1;
padding: variables.$cn-base-font-size * 0.8;
overflow-y: auto;
@media (min-width: $breakpoint-mobile) {
flex-grow: 0;
}
// * Switch on 2nd Page MODAL
.cn-switch {
position: relative;
display: inline-block;
overflow: hidden;
width: $cn-w2-swth-width;
height: $cn-w2-swth-height;
box-sizing: content-box;
cursor: pointer;
&:focus,
&:focus-visible {
border-width: variables.$cn-base-font-size * 0.1;
border-style: solid;
border-color: $cn-w2-swth-focus-color;
}
input {
#cn-li-template {
display: none;
}
input + span {
position: absolute;
border-radius: variables.$cn-base-font-size * 2;
background: $cn-w2-swth-unchecked-color;
inset: 0;
&::before {
position: absolute;
top: 50%;
left: $cn-w2-swth-width * 0.05;
display: inline-block;
width: $cn-w2-swth-toggle-width;
height: $cn-w2-swth-toggle-height;
border-radius: 50%;
background: $cn-w2-swth-toggle-color;
content: '';
transform: translateY(-50%);
transition: all 0.5s;
}
}
input:indeterminate + span {
background: $cn-w2-swth-indetermined-color;
&::before {
left: #{math.div((($cn-w2-swth-width - $cn-w2-swth-toggle-width) * 0.9), 2)};
}
}
input:checked + span {
background: $cn-w2-swth-checked-color;
&::before {
left: #{($cn-w2-swth-width - $cn-w2-swth-toggle-width) * 0.9};
}
}
}
// * 1rst Page BANNER
.cn-banner-content {
display: flex;
min-height: 100%;
flex-direction: column;
color: $ck-w1-color-txt;
font-family: $ck-w1-font-family-txt;
font-size: $ck-w1-font-size-txt;
@media (min-width: $breakpoint-mobile) {
flex-flow: row wrap;
align-items: center;
.cn-banner-img {
width: 33%;
}
.cn-banner-text {
width: 66%;
}
}
// LOGO
.cn-banner-img {
text-align: center;
img {
width: 90%;
object-fit: contain;
}
}
.cn-banner-text {
// TITLE
.cn-banner-title {
color: $ck-w1-color-title;
font-family: $ck-w1-font-family-title;
font-size: $ck-w1-font-size-title;
font-weight: bold;
line-height: $ck-w1-line-height-title;
text-align: left;
}
.cn-banner-para-p {
margin: 6px 0;
text-align: justify;
}
}
.d-none {
display: none !important;
}
// * 2nd Page MODAL
.cn-modal-container {
position: relative;
display: flex;
overflow: auto;
flex-direction: column;
align-items: center;
// CONTENT WRAPPER
.cn-content {
flex-grow: 1;
padding: 0.8rem;
overflow-y: auto;
ul {
// 1rst Page BANNER
.cn-banner-content {
display: flex;
min-height: 100%;
flex-direction: column;
color: $ck-w1-color-txt;
font-family: $ck-w1-font-family-txt;
font-size: $ck-w1-font-size-txt;
@media (min-width: $breakpoint-mobile) {
flex-flow: row wrap;
align-items: center;
.cn-banner-img {
width: 33%;
}
.cn-banner-text {
width: 66%;
}
}
// LOGO
.cn-banner-img {
text-align: center;
img {
width: 90%;
object-fit: contain;
}
}
.cn-banner-text {
flex: 2;
// TITLE
.cn-banner-title {
color: $ck-w1-color-title;
font-family: $ck-w1-font-family-title;
font-size: $ck-w1-font-size-title;
font-weight: bold;
line-height: $ck-w1-line-height-title;
text-align: left;
}
.cn-banner-para-p {
margin: 6px 0;
text-align: justify;
}
}
.cn-banner-details {
display: flex;
overflow: hidden;
height: 0;
flex-direction: row;
align-items: flex-start;
justify-content: center;
text-align: justify;
transition: 0.3s;
}
.cn-banner-btn-details {
width: 100%;
margin: 1rem 0;
}
.cn-banner-btn-details-p {
@extend %nav-button;
display: inline-block;
width: 100%;
margin: 0 auto;
cursor: pointer;
font-size: 14px;
text-align: center;
}
}
// 2nd Page MODAL
.cn-modal-container {
.cn-modal-title {
color: $ck-w2-color-title;
font-family: $ck-w2-font-family-title;
font-size: $ck-w2-font-size-title;
font-weight: bold;
text-align: center;
}
.cn-modal-subtitle {
margin-bottom: 6px;
color: $ck-w2-color-txt;
color: $ck-w2-color-title;
font-family: $ck-w2-font-family-txt;
font-size: $ck-w2-font-size-txt;
text-align: center;
}
.cn-modal-description {
display: flex;
flex-direction: column;
align-items: center;
color: $ck-w2-color-txt;
font-family: $ck-w2-font-family-txt;
font-size: $ck-w2-font-size-txt;
font-weight: normal;
line-height: initial;
}
.cn-modal-wrapper {
position: relative;
display: flex;
overflow: auto;
flex-direction: column;
align-items: center;
ul {
display: flex;
flex-direction: column;
padding: 0 20px;
list-style: none;
}
.cn-cookie-wrapper {
display: flex;
flex-direction: column;
align-items: center;
justify-content: space-between;
padding: 20px;
border: 1px solid $ck-bgcolor-list;
border-radius: 20px;
margin: 10px 0;
}
span {
color: $ck-color-list;
font-family: $ck-font-family-list;
font-size: $ck-font-size-list;
}
a {
color: $ck-color-list;
font-family: $ck-font-family-list;
font-size: $ck-font-size-list;
}
label {
color: $ck-color-list;
font-family: $ck-font-family-list;
font-size: $ck-font-size-list;
}
}
.cn-cookie {
&-name {
color: $ck-color-title;
}
&-infos {
display: flex;
width: 100%;
flex: 1;
flex-direction: column;
span:first-of-type {
font-size: calc($ck-font-size-list * 1.25);
font-weight: bold;
}
.cn-cookie-description {
color: $ck-w2-color-txt;
}
a {
width: fit-content;
}
}
&-buttons {
display: flex;
width: 200px;
justify-content: space-around;
margin-top: 6px;
input {
display: none;
}
label {
display: block;
width: 100px;
padding: 6px 20px;
color: $ck-color-txt;
cursor: pointer;
transition: color 0.3s;
}
div {
display: table;
margin: 0.5em;
text-align: center;
}
}
}
.accept,
.deny {
label {
@extend %nav-button;
height: inherit;
background: $ck-color-accept;
}
}
.accept {
label:hover,
label:focus {
background-color: color.adjust(
$color: $ck-color-accept-hover,
$lightness: -10%
);
}
.active {
background-color: $ck-color-accept-hover;
}
}
.deny {
label:hover,
label:focus {
background-color: color.adjust(
$color: $ck-color-deny-hover,
$lightness: -10%
);
}
.active {
background-color: $ck-color-deny-hover;
}
}
// stylelint-disable-next-line selector-max-compound-selectors
.accept input:checked ~ label {
background-color: $ck-color-accept-hover;
}
// stylelint-disable-next-line selector-max-compound-selectors
.deny input:checked ~ label {
background-color: $ck-color-deny-hover;
}
}
}
// NAV BAR
.cn-nav {
display: flex;
flex-direction: column;
padding: 0;
margin: 0;
list-style: none;
}
.cn-cookie-wrapper {
display: flex;
flex-direction: row;
overflow: hidden;
width: 100%;
height: 3rem * 2;
flex-shrink: 0;
flex-wrap: wrap;
align-items: center;
justify-content: space-between;
padding: 20px;
border: 1px solid #{$ck-bgcolor-list};
border-radius: 20px;
margin: 10px 0;
}
border-top: 1px solid $ck-borders-color;
/* stylelint-disable-next-line no-descending-specificity */
span {
color: $ck-color-list;
font-family: $ck-font-family-list;
font-size: $ck-font-size-list;
}
#cn-deny-banner {
@extend %nav-button;
a {
font-family: $ck-font-family-list;
font-size: $ck-font-size-list;
}
label {
color: $ck-color-list;
font-family: $ck-font-family-list;
font-size: $ck-font-size-list;
}
.cn-cookie {
&-name {
color: $ck-color-title;
width: 50%;
}
&-infos {
display: flex;
width: 100%;
flex: 1;
flex-direction: column;
#cn-accept-banner {
@extend %nav-button;
span:first-of-type {
font-size: calc(#{$ck-font-size-list} * 1.25);
font-weight: bold;
}
.cn-cookie-description {
color: $ck-w2-color-txt;
}
a {
width: fit-content;
}
width: 50%;
border-right: 1px solid $ck-borders-color;
border-left: 1px solid $ck-borders-color;
font-weight: bolder;
}
}
}
}
// * NAV BAR
.cn-nav {
display: flex;
overflow: hidden;
width: 100%;
height: variables.$cn-button-height * 2;
flex-shrink: 0;
flex-wrap: wrap;
align-items: center;
border-top: 1px solid #{variables.$ck-borders-color};
#cn-settings-banner {
@extend %nav-button;
#cn-deny-banner {
@extend %nav-button;
width: 100%;
border-top: 1px solid $ck-borders-color;
}
width: 50%;
}
@media (min-width: $breakpoint-mobile) {
height: 3rem;
flex-wrap: initial;
border-bottom-left-radius: 0.5rem;
border-bottom-right-radius: 0.5rem;
#cn-accept-banner {
@extend %nav-button;
#cn-deny-banner {
width: 33.33%;
}
width: 50%;
border-right: 1px solid #{variables.$ck-borders-color};
border-left: 1px solid #{variables.$ck-borders-color};
}
#cn-accept-banner {
width: 33.33%;
}
#cn-settings-banner {
@extend %nav-button;
width: 100%;
border-top: 1px solid #{variables.$ck-borders-color};
#cn-settings-banner {
width: 33.33%;
border-top: initial;
}
}
}
@media (min-width: $breakpoint-mobile) {
height: variables.$cn-button-height;
flex-wrap: initial;
border-bottom-left-radius: variables.$cn-base-font-size * 0.5;
border-bottom-right-radius: variables.$cn-base-font-size * 0.5;
#cn-deny-banner {
width: 33.33%;
}
#cn-accept-banner {
width: 33.33%;
}
#cn-settings-banner {
width: 33.33%;
border-top: initial;
}
width: 100%;
height: 100%;
}
}
}
// * SHOW CN BANNER MODAL
// SHOW CN BANNER MODAL
.cn-open {
overflow: hidden !important;
overflow: hidden !important;
#cn-wrapper #cn-banner {
opacity: 1;
visibility: visible;
#cn-wrapper #cn-banner {
opacity: 1;
visibility: visible;
@media (min-width: $breakpoint-mobile) {
right: variables.$cn-cookie-button-position-right;
left: variables.$cn-cookie-button-position-left;
@media (min-width: $breakpoint-mobile) {
right: $cn-cookie-button-position-right;
left: $cn-cookie-button-position-left;
}
}
}
#cn-wrapper #cn-cookie-btn {
@media (min-width: $breakpoint-mobile) {
right: variables.$cn-cookie-button-position-right;
bottom: variables.$cn-cookie-button-position-bottom;
left: variables.$cn-cookie-button-position-left;
transition: variables.$cn-cookie-button-transition-hide;
}
}
}

View file

@ -1,77 +1,33 @@
:root {
--cs-primary-color: var();
--cs-primary-color: var();
}
$cn-base-font-size: 1rem !default;
$ck-primary-color: #707070 !default;
$ck-primary-color: #b9b9b9 !default;
$ck-secondary-color: #dc9c52 !default;
$ck-background-color: #fff !default;
$ck-list-background-color: #e4e4e4 !default;
$ck-borders-color: #6d6d6d !default;
$ck-borders-color: #808080 !default;
$ck-shadow-color: 0 0.1rem 1rem rgb(0 0 0 / 35%) !default;
$ck-title-font: 'Satisfy', sans-serif !default;
$ck-title-font: "Satisfy", sans-serif !default;
$ck-title-line-height: inherit !default;
$ck-title-size: 28px !default;
$ck-text-font: 'Barlow', sans-serif !default;
$ck-text-size: 16px !default;
$ck-title-size: 25px !default;
$ck-text-font: "Barlow", sans-serif !default;
$ck-text-size: 14px !default;
$ck-btn-background-color: #fff !default;
$ck-accept-color: #3a3 !default;
$ck-deny-color: #a33 !default;
// CN Wrapper z-index
$cn-cookie-button-z-index: 1050 !default;
// Cookie Button dimension
$cn-cookie-button-width: $cn-base-font-size * 2.4 !default;
$cn-cookie-button-height: $cn-base-font-size * 2.4 !default;
$cn-cookie-button-padding: $cn-base-font-size * 0.3 !default;
// Cookie Button dimension (above mobile)
$cn-cookie-button-width-h: $cn-base-font-size * 3 !default;
$cn-cookie-button-height-h: $cn-base-font-size * 3 !default;
$cn-cookie-button-padding-h: $cn-base-font-size * 0.5 !default;
// Cookie Button position
/* Distance par rapport à la gauche de la fenêtre */
$cn-cookie-button-position-left: $cn-base-font-size * 0.5;
/* Distance par rapport à la droite de la fenêtre */
$cn-cookie-button-position-right: auto;
/* Distance par rapport au bas de la fenêtre */
$cn-cookie-button-position-bottom: 0.5rem;
/* Position gauche de base des cookies */
$cn-cookie-animation-left: 0;
/* Position droite de base des cookies */
$cn-cookie-animation-right: auto;
// Cookie Button position hide btn vars
$cn-cookie-button-position-right-h: auto;
$cn-cookie-button-position-bottom-h: #{calc($cn-cookie-button-position-bottom - ($cn-base-font-size * 2))};
$cn-cookie-button-position-left-h: #{calc($cn-cookie-button-position-left - ($cn-base-font-size * 2))};
$cn-cookie-button-transition-show: all 1s 6s, border-radius 0s, background-color 0s, box-shadow 0s, padding 0s;
$cn-cookie-button-transition-hide: all 1s;
$cn-cookie-button-position-left: 1rem; /* Distance par rapport à la gauche de la fenêtre */
$cn-cookie-button-position-right: auto; /* Distance par rapport à la droite de la fenêtre */
$cn-cookie-button-position-bottom: 1rem; /* Distance par rapport au bas de la fenêtre */
$cn-cookie-animation-left: 0; /* Position gauche de base des cookies */
$cn-cookie-animation-right: auto; /* Position droite de base des cookies */
// Buttons
$cn-button-bg-color: #d6d6d6 !default;
$cn-button-bg-color: $ck-primary-color !default;
$cn-button-font-family: $ck-text-font !default;
$cn-button-font-size: $cn-base-font-size * 1 !default;
$cn-button-font-size: 1rem !default;
$cn-button-line-height: 1 !default;
$cn-button-height: $cn-base-font-size * 3 !default;
// Switch Buttons
$cn-switch-height: $cn-base-font-size * 2.4 !default;
$cn-switch-width: $cn-base-font-size * 4.2 !default;
$cn-switch-toggle-height: $cn-base-font-size * 1.8 !default;
$cn-switch-toggle-width: $cn-base-font-size * 1.8 !default;
$cn-switch-toggle-color: #fff !default;
$cn-switch-indetermined-color: #b7b7b7 !default;
$cn-switch-unchecked-color: #b7b7b7 !default;
$cn-switch-checked-color: $ck-secondary-color !default;
$cn-switch-focus-color: $cn-switch-checked-color !default;
// Dimensions modal
$cn-cookie-modal-max-height-mobile: 100dvh !default;
$cn-cookie-modal-max-height-desktop: $cn-base-font-size * 38 !default;
$cn-cookie-modal-width: $cn-base-font-size * 30 !default;

View file

@ -1,715 +0,0 @@
import defaults from "../cookie-defaults";
import cookieReferences from "../cookie-references";
import { CookieOptions as CnCookieConfig, CnCookieInfo, CnCookiePolicies, CnCookieValues } from "../type";
import { CookieStatus } from "./../enums";
import { DocumentCookie } from "./DocumentCookie";
export default class CookieNotice {
/** The CN cookie status */
private cookieName = defaults.cookieName;
/** Cookie life time */
private cookieTimeLife = defaults.cookieTimeLife;
/** The index on which store the expiration date */
private cookieExpirationName = defaults.cookieExpirationName;
/** Cookie policies for each functionality */
private cookiePolicies: CnCookiePolicies = defaults.cookiePolicies;
/** Prevent user from closing modal */
private restrictCloseModal: boolean = defaults.restrictCloseModal;
/** Cookie expiration date as specified in the cookie itself */
private cookieExpirationDate: Date = new Date();
// * -- DOM ELEMENTS
private domElList: {
/** Modal transparent background => div.cn-modal-bg */
modalBg?: HTMLDivElement|null,
/** Modal window container for the cookie panel and button => div#cn-wrapper */
cookieContainer?: HTMLDivElement|null|null,
/** Modal container (wrapping pages) => div#cn-banner */
bannerContainer?: HTMLDivElement|null,
/** Modal banner (1rst page) container => div.cn-banner-content */
bannerContent?: HTMLDivElement|null,
/** Modal cookie list (2nd page) container => div.cn-modal-container */
modalContainer?: HTMLDivElement | null,
/** The big cookie button => button#cn-cookie-btn */
cookieShowModalBtn?: HTMLButtonElement | null,
/** Modal container close button => button#cn-close-modal */
cookieCloseModalBtn?: HTMLButtonElement | null,
/** Modal container accept all cookies button => button#cn-accept-banner */
acceptAllBtn?: HTMLButtonElement|null,
/** Modal container deny all cookies button => button#cn-deny-banner */
denyAllBtn?: HTMLButtonElement | null,
/** Modal container switch page / (validate and) close button => button#cn-settings-banner */
customizeBtn?: HTMLButtonElement | null,
/** Modal unordered cookie list => ul#cn-modal-list */
cookiesUnorderedList?: HTMLUListElement | null,
/** List of all links that will open cookie notice */
cookieLinkShowCustomizeModalList?: NodeListOf<HTMLElement> | null,
/** Cookie template for unordered cookie list */
template?: HTMLDivElement|null
} = {};
// * -- END DOM ELEMENTS
/**
* @param config Holding all cookie configs
*/
constructor(private config: Record<string, CnCookieConfig>) {
// * Merge cookie config with references
[...Object.keys(this.config)].forEach(cookieName => {
this.config[cookieName].cookies = [...new Set([
...this.config[cookieName].cookies,
...(cookieReferences.get(cookieName) ?? [])
])];
});
// * Setup cookie expiration date
this.cookieExpirationDate = this.getCnCookieInfo().date;
this.initDomElements();
this.setupEvents();
// * Setup CN Cookie
if (this.configHasChanged() || this.configHasExpired()) {
// * Setup Browser Cookie if none.
this.resetCnCookie();
this.openCookieModalToBannerPage();
}
this.updateRestrictCloseModal();
// * Cookie should have been created from here.
this.getCnCookieInfo().values.forEach((cookieStatus, cookieName) => {
if (cookieStatus === CookieStatus.wait) {
this.openCookieModalToBannerPage();
return;
}
this.setCnCookieStatus(cookieName, cookieStatus);
this.setCookieSwitchButton(cookieName, cookieStatus);
});
}
// * --- PUBLIC ---
/** Accept a all cookies */
public acceptAllCookies(): void {
[...this.getCnCookieInfo().values.keys()]
.forEach(cookieName => this.acceptCookie(cookieName));
}
/** Accept a specific cookie */
public acceptCookie(cookieName: string): void {
this.setCnCookieStatus(cookieName, CookieStatus.true);
this.setCookieSwitchButton(cookieName, CookieStatus.true);
this.refreshCnCookieExpirationDate();
}
/** Deny a all cookies */
public denyAllCookies(): void {
[...this.getCnCookieInfo().values.keys()]
.forEach(cookieName => this.denyCookie(cookieName));
}
/** Deny a specific cookie */
public denyCookie(cookieName: string): void {
this.setCnCookieStatus(cookieName, CookieStatus.false);
this.setCookieSwitchButton(cookieName, CookieStatus.false);
this.refreshCnCookieExpirationDate();
}
/** Deny all waiting cookies */
public denyAllWaitingCookies(): void {
this.getCnCookieInfo().values.forEach((cookieStatus, cookieName) => {
if (cookieStatus === CookieStatus.wait) {
this.persistCnCookie(cookieName, CookieStatus.false);
return;
}
});
this.updateRestrictCloseModal();
}
/**
* Get a specific cookie config
* @throws {Error} If the cookie `cookieName` is not found in config.
*/
public getCookieConfig(cookieName: string): CnCookieConfig {
const cookieOptions = Object.entries(this.config).find((entry) => entry[0] === cookieName)?.[1];
if (cookieOptions === undefined) {
throw new Error(`Cookie options ${cookieName} not found in list`);
}
return cookieOptions;
}
// * --- PRIVATE ---
// * - Utilities
/** Check if the config has expired */
private configHasExpired(): boolean {
return this.cookieExpirationDate.getTime() < (new Date()).getTime();
}
/** Check if the actual cookie config matches the CN config */
private configHasChanged(): boolean {
const cookies = this.getCnCookieInfo().values;
return cookies.size !== Object.keys(this.config).length ||
[...cookies.keys()].join(".") !== Object.keys(this.config).join(".");
}
/**
* Invert cookie status
*
* @param cookieStatus
* @returns Inverted cookie status, `wait` will give `false`.
* @throw {Error} If the cookie status is not handled.
*/
private invertCookieStatus(cookieStatus: CookieStatus): CookieStatus {
switch (cookieStatus) {
case CookieStatus.true:
case CookieStatus.wait:
return CookieStatus.false;
case CookieStatus.false:
return CookieStatus.true;
default:
throw new Error(`Un handled cookie status ${cookieStatus}`);
}
}
/** Get a new expiration date */
private getNewExpirationDate(): Date {
const expDate = new Date();
return new Date(expDate.setMonth(expDate.getMonth() + this.cookieTimeLife));
}
// * - CN Browser Cookie Manipulation
private getCnCookieInfo(): CnCookieInfo {
const cookies = this.getCnCookieValues();
const expirationDate = (cookies.get(this.cookieExpirationName) ?? this.getNewExpirationDate()) as Date;
cookies.delete(this.cookieExpirationName);
return {
name: this.cookieName,
values: cookies as CnCookieValues,
date: expirationDate,
cookiePolicies: this.cookiePolicies
};
}
/**
* Get a cookie status
*
* @param cookieName
* @throws {Error} If the cookie value could not be found.
*/
private getCnCookieStatus(cookieName: string): CookieStatus {
const statusList = this.getCnCookieInfo().values;
const cookieStatus = statusList.get(cookieName);
if (cookieStatus === undefined) {
throw new Error(`Cookie options ${cookieName} not found in list`);
}
return cookieStatus;
}
/** Trigger cookie status actions and persist status */
private setCnCookieStatus(
cookieName: string,
status: CookieStatus
): void {
const cookieConfig = this.getCookieConfig(cookieName);
this.persistCnCookie(cookieName, status);
if (status === CookieStatus.true) {
cookieConfig.script();
return;
}
if (status === CookieStatus.false) {
if (cookieConfig.fallback) {
cookieConfig.fallback();
}
return;
}
this.persistCnCookie(cookieName, CookieStatus.wait);
}
/** Save cookie content on web browser */
private persistCnCookieList(statusMap: CnCookieValues): void {
const content = Array.from(statusMap.entries()).map(([cookieName, cookieStatus]) => {
if (cookieStatus === CookieStatus.false) {
// * Need to remove all associated cookies
this.getCookieConfig(cookieName).cookies.forEach((cookieToRemove) => {
[...DocumentCookie.getAllStartingWith(cookieToRemove.replace(/\*+$/, ""))
.keys()].forEach(cookieName => DocumentCookie.markForDeletion(cookieName));
});
}
return `${cookieName}=${cookieStatus}`;
});
// * Append expiration date
content.push(`${this.cookieExpirationName}=${this.cookieExpirationDate.getTime()}`);
DocumentCookie.set(
this.cookieName,
content.join(","),
this.cookieExpirationDate,
this.cookiePolicies
);
}
/** Bump CN expiration date */
private refreshCnCookieExpirationDate(): void {
const content = Array.from(this.getCnCookieInfo().values.entries())
.map(([cookieName, cookieStatus]) => `${cookieName}=${cookieStatus}`);
// * Update expiration date
this.cookieExpirationDate = this.getNewExpirationDate();
// * Append expiration date
content.push(`${this.cookieExpirationName}=${this.cookieExpirationDate.getTime()}`);
DocumentCookie.set(
this.cookieName,
content.join(","),
this.cookieExpirationDate,
this.cookiePolicies
);
}
/** Read CN cookie values */
private getCnCookieValues(): Map<string, CookieStatus|Date> {
const cookies = (DocumentCookie.get(this.cookieName) ?? "").split(",").filter(e => e)
.map((cookieKeyValue) => cookieKeyValue.split(/=|(?:->)/s)),
out = new Map<string, CookieStatus|Date>();
cookies.forEach(keyValue => {
const key = keyValue[0], value = keyValue[1];
// * Exp Date
if (key === this.cookieExpirationName) {
let expDate = this.getNewExpirationDate();
try {
const epochExpiration = Number.parseInt(value);
if (!isNaN(epochExpiration)) {
expDate = new Date(epochExpiration);
}
} finally {
out.set(keyValue[0], expDate);
}
return;
}
// * CookieStatus values
out.set(keyValue[0], keyValue[1] as CookieStatus);
});
return out;
}
/** Reset Cookie status list */
private resetCnCookie(): void {
const newCookieList: CnCookieValues = new Map<string, CookieStatus>();
Object.entries(this.config).forEach(([cookieName]) => newCookieList.set(cookieName, CookieStatus.wait));
this.persistCnCookieList(newCookieList);
}
/** Change the status of a cookie */
private persistCnCookie(cookieName: string, status: CookieStatus): void {
const statusMap = this.getCnCookieInfo().values;
// * Force refresh
DocumentCookie.markForDeletion(this.cookieName);
statusMap.set(cookieName, status);
this.persistCnCookieList(statusMap);
this.updateRestrictCloseModal();
}
// * --- LISTENERS ---
/**
* Add event on a specific element
*
* @param element
* @param evnt
* @param funct
* @returns
*/
private addEvent(element: HTMLElement, evnt: string, funct: (e: Event) => void): void {
element.addEventListener(evnt, funct.bind(this), false);
}
/**
* Add event on a specific element and prevent default
*
* @param element
* @param evnt
* @param funct
*/
private addEventPrevent(
element: HTMLElement,
evnt: string,
funct: (e: Event) => void
): void {
element.addEventListener(
evnt,
(e) => {
e.preventDefault();
funct.call(this, e);
},
false
);
}
/**
* Add event on a specific element
*
* @param element A HTMLElement on which the should should be bound.
* @param funct A closure for the event hanling.
*/
private addEventKbdValidate(element: HTMLElement, funct: (e: Event) => void): void {
this.addEvent(element, "keydown", (e: Event) => {
const kbdEvt = e as KeyboardEvent;
if (
kbdEvt.key == " " ||
kbdEvt.code == "Space" ||
kbdEvt.keyCode == 32 ||
kbdEvt.key == "Enter" ||
kbdEvt.code == "Enter" ||
kbdEvt.keyCode == 13
) {
funct.call(this, kbdEvt);
e.preventDefault();
}
});
}
// * --- COOKIE MODAL ---
private setCookieSwitchButton(cookieName: string, status: CookieStatus): void {
const cnSwitch = document.getElementById(`${cookieName}-switch`) as HTMLInputElement | null;
const cnSwitchInput = cnSwitch?.querySelector("input") as HTMLInputElement | null;
if (!cnSwitch || !cnSwitchInput) {
return;
}
cnSwitchInput.indeterminate = status === CookieStatus.wait;
cnSwitchInput.checked = status === CookieStatus.true;
cnSwitch.ariaChecked = status === CookieStatus.wait ? CookieStatus.false : status;
}
/** Update restrict for closing cookie modal */
private updateRestrictCloseModal(): void {
const cookieCloseModalBtn = this.getDomEl("cookieCloseModalBtn"),
modalBg = this.getDomEl("modalBg");
this.restrictCloseModal = (Array.from(this.getCnCookieInfo().values.values()).includes(CookieStatus.wait)) ? true : false;
(this.restrictCloseModal) ? cookieCloseModalBtn.classList.add("d-none") : cookieCloseModalBtn.classList.remove("d-none");
(this.restrictCloseModal) ? modalBg.classList.add("cn-modal-bg-active") : modalBg.classList.remove("cn-modal-bg-active");
}
/** Show or hide Cookie modal */
private toggleCookieModal(): void {
if (!document.body.classList.contains("cn-open")) {
this.openCookieModalToBannerPage();
return;
}
this.closeCookieModal();
}
/** Open the cookies modal to the banner page */
private openCookieModalToBannerPage() {
this.openCookieModalToCookiePage();
this.toggleCookieModalPages();
}
/** Open the cookies modal to the cookies page */
private openCookieModalToCookiePage() {
document.body.classList.add("cn-open");
this.resetCookieModal();
this.getDomEl("bannerContent").classList.add("d-none");
this.getDomEl("modalContainer").classList.remove("d-none");
this.getDomEl("bannerContainer").classList.add("cn-modal-page");
// Scroll to the top of the cookies list
this.getDomEl("modalContainer").scrollTop = 0;
this.setupCookieModalList();
this.setTabIndex();
}
/** Hide the cookies modal */
private closeCookieModal() {
this.updateRestrictCloseModal();
if (!this.restrictCloseModal) {
document.body.classList.remove("cn-open");
if (!this.isOnBannerPage()) {
// * Make toggle page to banner on closing
this.getDomEl("bannerContent").classList.toggle("d-none");
this.getDomEl("modalContainer").classList.toggle("d-none");
this.getDomEl("bannerContainer").classList.remove("cn-modal-page");
}
this.unsetTabIndex();
this.setupCookieModalList();
} else {
throw new Error("You need to accept or refuse all cookies");
}
}
/** Setup tab indexes on visible elements */
private setTabIndex() {
// * Prevent focus html tag
document.documentElement.setAttribute("tabindex", "-1");
setTimeout(() => {
const focusableSelector =
"a[href], button, [role=\"button\"], input, embed, object, iframe, textarea, select, details, [tabindex]:not([tabindex=\"-1\"])";
const cookieContainer = this.getDomEl("cookieContainer");
// * Only focusable elements
[...document.body.querySelectorAll(focusableSelector)]
.filter(
(el) =>
!el.hasAttribute("disabled") &&
!el.getAttribute("aria-hidden") &&
!cookieContainer.contains(el)
)
.forEach((el) => {
(el as HTMLElement).setAttribute("tabindex", "-1");
(el as HTMLElement).classList.add("cn-disabled");
});
[...cookieContainer.querySelectorAll(focusableSelector)]
.filter(
(el) =>
!el.hasAttribute("disabled") &&
!el.getAttribute("aria-hidden") &&
// * Only visible elements
!!(
(el as HTMLElement).offsetWidth ||
(el as HTMLElement).offsetHeight ||
el.getClientRects().length
) &&
!cookieContainer.contains(el)
)
.forEach((el) => {
(el as HTMLElement).setAttribute("tabindex", "0");
(el as HTMLElement).classList.remove("cn-disabled");
});
this.getDomEl("cookieShowModalBtn").setAttribute("tabindex", "-1");
}, 500);
}
/** Undo setup tab indexes on visible elements */
private unsetTabIndex() {
document.documentElement.setAttribute("tabindex", "0");
setTimeout(() => {
document.body.querySelectorAll(".cn-disabled").forEach((el) => {
(el as HTMLElement).setAttribute("tabindex", "0");
(el as HTMLElement).classList.remove("cn-disabled");
});
this.getDomEl("cookieShowModalBtn").setAttribute("tabindex", "0");
}, 500);
}
/** Reset the modal view state */
private resetCookieModal() {
const customizeBtn = this.getDomEl("customizeBtn");
this.getDomEl("bannerContent").classList.remove("d-none");
this.getDomEl("modalContainer").classList.add("d-none");
this.getDomEl("bannerContainer").classList.remove("cn-modal-page");
if (!customizeBtn.dataset.openModal) {
throw new Error("Cannot find attribut data-open-modal");
}
customizeBtn.innerHTML = customizeBtn.dataset.openModal;
}
/** Set the cookies list in the modal */
private setupCookieModalList() {
this.getDomEl("cookiesUnorderedList").innerHTML = "";
Object.entries(this.config).forEach(([cookieName, cookieConfig]) => {
this.initDomCookieSwitch(cookieName, cookieConfig);
if (!DocumentCookie.has(this.cookieName)) {
// * Ldcweb cookie is not set.
return;
}
let cookieStatus = CookieStatus.wait;
try {
cookieStatus = this.getCnCookieStatus(cookieName);
} finally {
// * Setup list status state
this.setCookieSwitchButton(cookieName, cookieStatus);
}
});
}
private switchToModalPageOrClose(): void {
// * Modification du comportement du bouton, même si ca n'a pas de sens.
// https://lab.s-web.fr/ldc-web/projets/ldc-web-cookie-notice/-/issues/9`
if (this.isOnBannerPage()) {
this.toggleCookieModalPages();
return;
}
// * Pas de permutation en arrière
this.closeCookieModal();
}
/** Toggle Cookie modal pages */
private toggleCookieModalPages(): void {
this.getDomEl("bannerContent").classList.toggle("d-none");
this.getDomEl("modalContainer").classList.toggle("d-none");
this.getDomEl("bannerContainer").classList.toggle("cn-modal-page");
if (!this.isOnBannerPage()) {
this.getDomEl("bannerContainer").classList.add("cn-modal-page");
this.denyAllWaitingCookies();
}
this.setTabIndex();
this.setupCookieModalList();
this.toggleCustomizeBtn();
}
/** Toggle customize btn */
private toggleCustomizeBtn(): void {
const customizeBtn = this.getDomEl("customizeBtn"),
customizeBtnBannerDataset = this.getDomEl("customizeBtn").dataset;
this.getDomEl("modalContainer").scrollTop = 0;
if (this.getDomEl("bannerContent").classList.contains("d-none")) {
customizeBtn.innerHTML =
customizeBtnBannerDataset.openModal as string;
customizeBtn.title = customizeBtnBannerDataset.openModal as string;
} else {
customizeBtn.innerHTML =
customizeBtnBannerDataset.closeModal as string;
customizeBtn.title = customizeBtnBannerDataset.closeModal as string;
}
}
/** Get the actual page: banner or modal (with cookie choices) */
private isOnBannerPage(): boolean {
return this.getDomEl("modalContainer").classList.contains("d-none");
}
/** Setup Events */
private setupEvents(): void {
this.addEventPrevent(this.getDomEl("modalBg"), "click", this.closeCookieModal);
this.addEventPrevent(this.getDomEl("cookieCloseModalBtn"), "click", this.closeCookieModal );
this.addEventPrevent(this.getDomEl("acceptAllBtn"), "click", () => { this.acceptAllCookies(); this.closeCookieModal(); });
this.addEventPrevent(this.getDomEl("denyAllBtn"), "click", () => { this.denyAllCookies(); this.closeCookieModal(); });
this.addEventPrevent(this.getDomEl("customizeBtn"), "click", this.switchToModalPageOrClose );
this.addEventPrevent(this.getDomEl("cookieShowModalBtn"), "click", this.toggleCookieModal );
this.getDomEl("cookieLinkShowCustomizeModalList").forEach((cookieLink) => {
this.addEventPrevent(
cookieLink,
"click",
this.openCookieModalToCookiePage
);
this.addEventKbdValidate(cookieLink, this.openCookieModalToCookiePage);
});
}
/** Get dom element */
private getDomEl<K extends keyof typeof this.domElList,T extends Exclude<typeof this.domElList[K], null | undefined>>
(item: K): T {
// Exclude null|undefined as elements are verified in initDomElements
return this.domElList[item] as T;
}
/** Init a Dom cookie switch */
private initDomCookieSwitch(cookieName: string, cookieConfig: CnCookieConfig): void {
const cookie = document.createElement("li");
const childItem = this.getDomEl("template").children.item(
0
) as HTMLDivElement | null;
if (childItem === null) {
throw new Error("Cannot find child item");
}
cookie.append(childItem.cloneNode(true));
const name = cookie.querySelector(
"span.cn-cookie-name"
) as HTMLSpanElement;
const description = cookie.querySelector(
"span.cn-cookie-description"
) as HTMLSpanElement;
const link = cookie.querySelector(
".cn-cookie-link"
) as HTMLElement;
const cnSwitch = cookie.querySelector(
".cn-switch"
) as HTMLInputElement;
const cnSwitchInput = cookie.querySelector(
".cn-switch > input"
) as HTMLInputElement;
// * Undertermined state
cnSwitchInput.indeterminate = true;
cnSwitchInput.checked = false;
// * Assign cookie aside content
name.textContent = cookieConfig.name;
description.id = `${cookieName}-desc`;
description.textContent = cookieConfig.description;
link.textContent = cookieConfig.labelLink;
link.setAttribute("href", cookieConfig.link);
// * Assign cookie controls
cnSwitch.id = `${cookieName}-switch`;
cnSwitch.name = cookieName;
cnSwitch.dataset.name = cookieName;
cnSwitch.setAttribute("aria-labelledby", `${cookieName}-desc`);
cnSwitch.setAttribute("aria-describedby", `${cookieName}-desc`);
const toggleCookie = (cookieName: string) => {
let cookieStatus = CookieStatus.wait;
try {
cookieStatus = this.getCnCookieStatus(cookieName);
} finally {
this.setCnCookieStatus(
cookieName,
this.invertCookieStatus(cookieStatus)
);
this.refreshCnCookieExpirationDate();
}
};
this.addEvent(cnSwitchInput, "click", () => toggleCookie(cookieName));
this.addEventKbdValidate(cnSwitch, () => cnSwitchInput.click());
this.getDomEl("cookiesUnorderedList").append(cookie);
}
/** Init Dom elements selector */
private initDomElements(): void {
// * Inject DOM modal BG
const modalBg = document.createElement("div");
modalBg.classList.add("cn-modal-bg");
document.body.append(modalBg);
this.domElList.modalBg = modalBg;
// * Setup Dom Elements
this.domElList.cookieLinkShowCustomizeModalList = document.querySelectorAll(
".cn-cookie-link"
) as NodeListOf<HTMLElement>;
const selectorList = {
"div#cn-wrapper": "cookieContainer",
"button#cn-cookie-btn": "cookieShowModalBtn",
"button#cn-close-modal": "cookieCloseModalBtn",
"div#cn-banner": "bannerContainer",
"div.cn-banner-content": "bannerContent",
"div.cn-modal-container": "modalContainer",
"button#cn-accept-banner": "acceptAllBtn",
"button#cn-deny-banner": "denyAllBtn",
"button#cn-settings-banner": "customizeBtn",
"ul#cn-modal-list": "cookiesUnorderedList",
"div#cn-li-template": "template",
};
Object.entries(selectorList).forEach(entry => {
const selector = entry[0],
domElItemKey = entry[1] as keyof typeof this.domElList;
let itemEntry = this.domElList[domElItemKey];
const domEl = document.querySelector(selector) as Exclude<typeof this.domElList[keyof typeof this.domElList], undefined>;
itemEntry = domEl as typeof itemEntry;
if (!itemEntry) {
throw new Error(`Cannot find dom element ${selector}`);
}
this.domElList = {...this.domElList, [domElItemKey]: itemEntry};
});
// * Clone and remove original template node
const memoryTemplate = this.domElList.template!.cloneNode(true) as HTMLDivElement;
this.domElList.template!.remove();
this.domElList.template = memoryTemplate;
}
}

View file

@ -1,70 +0,0 @@
import { CnCookiePolicies } from "../type";
export abstract class DocumentCookie {
public static has(cookieName: string): boolean {
return this.getCookies().has(cookieName);
}
public static get(cookieName: string): string|undefined {
return this.getCookies().get(cookieName);
}
public static set(
cookieName: string,
value: string,
date: Date | null = null,
cookiePolicies: CnCookiePolicies | null = null
): void {
let cookieValue = `${cookieName}=${value};path=/${
location.hostname ? `;domain=${location.hostname}` : ""
}`;
if (date) {
cookieValue += `;expires=${date.toUTCString()}`;
}
if (cookiePolicies) {
cookieValue += `;sameSite=${cookiePolicies.sameSite}${cookiePolicies.secure ? ";secure" : ""}`;
}
document.cookie = cookieValue;
}
public static getAllStartingWith(cookieNameStartingPart: string): Map<string, string> {
const cookies = this.getCookies();
for (const cookieName of cookies.keys()) {
if (!cookieName.startsWith(cookieNameStartingPart)) {
cookies.delete(cookieName);
}
}
return cookies;
}
/**
* Set an older expire parameter to a specific cookie
*/
public static markForDeletion(cookieName: string): void {
if (!DocumentCookie.has(cookieName)) {
console.debug(`No document cookie named ${cookieName}`);
}
// * Suppression du cookie et de sa version precedé d'un point
document.cookie = `${cookieName}=;path=/;expires=Thu, 01 Jan 1970 00:00:01 GMT;sameSite=Lax`;
document.cookie = `${cookieName}=;path=/${
location.hostname ? `;domain=.${location.hostname}` : ""
};expires=Thu, 01 Jan 1970 00:00:01 GMT;sameSite=Lax`;
document.cookie = `${cookieName}=;path=/${
location.hostname ? `;domain=${location.hostname}` : ""
};expires=Thu, 01 Jan 1970 00:00:01 GMT;sameSite=Lax`;
}
/** Fetch browser cookies except(http-only ones) the cannot be handled using js */
private static getCookies(): Map<string, string> {
const out = new Map<string, string>();
document.cookie.split(";").filter(e => e).forEach(c => {
const cookieKeyValue = c.split(/=(.*)/s).filter(e => e);
out.set(cookieKeyValue[0].trim(), cookieKeyValue[1].trim());
});
return out;
}
}
// eslint-disable-next-line @typescript-eslint/ban-ts-comment
// @ts-ignore
window.DocumentCookie = DocumentCookie;

View file

@ -1,26 +0,0 @@
import { CookiePolicySameSite } from "./enums";
import { CnCookiePolicies } from "./type";
const defaults: {
/** The CN cookie status */
cookieName: string;
/** Cookie life time */
cookieTimeLife: number;
/** The index on which store the expiration date */
cookieExpirationName: "_expiration";
/** Cookie policies for each functionality */
cookiePolicies: CnCookiePolicies;
/** Prevent user from closing modal */
restrictCloseModal: boolean;
} = {
cookieName: "cn-init",
cookieTimeLife: 6,
cookieExpirationName: "_expiration",
cookiePolicies: {
sameSite: CookiePolicySameSite.lax,
secure: false
},
restrictCloseModal: true
};
export default defaults;

View file

@ -1,28 +0,0 @@
export default new Map<string, string[]>([
["youtube", [
// * https://cookiedatabase.org/service/youtube/
// * https://tarteaucitron.io/fr/service/youtube/
"NID", "ENID", "_Secure-ENID", "VISITOR_INFO1_LIVE", "YEC", "__Secure-YEC", "YSC",
"GEUP", "PREF", "pm_sess", "CGIC", "SOCS", "GPS", "yt-player-bandwidth", "yt-player-headers-readable"
]],
["recaptcha", [
// * https://developers.google.com/recaptcha/docs/faq?hl=fr
// * https://cookiedatabase.org/?s=recaptcha&lang=en
"NID", "_grecaptcha", "__Secure-3PAPISID", "__Secure-3PSID", "__Secure-3PSIDCC",
"_GRECAPTCHA", "rc::c", "rc::b", "rc::a", "itsec-recaptcha-opt-in-*"
]],
["vimeo", [
// * https://help.vimeo.com/hc/fr/articles/17670845188113-Comment-puis-je-int%C3%A9grer-des-vid%C3%A9os-tout-en-%C3%A9tant-conforme-au-GDPR
// * Cookie Database https://cookiedatabase.org/service/vimeo/
// Ne semble plus placer de cookies
"vuid", "__utmt_player"
]],
["matomo", [
// * PK* as in doc https://fr.matomo.org/faq/faq_146/
"_pk*",
// * Matomo
"_pk_ref", "_pk_cvar", "_pk_id", "_pk_ses", "_pk_hsr", "piwik_ignore", "_pk_uid",
// * Matomo Cloud
"_pk_ref", "_pk_cvar", "_pk_id", "_pk_ses", "_pk_hsr", "mtm_consent", "matomo_ignore", "matomo_sessid"
]],
]);

View file

@ -1,13 +0,0 @@
/** A cookie status as written in the cn cookie */
export enum CookieStatus {
true = "true",
false = "false",
wait = "wait",
}
/** A cookie Policy same site */
export enum CookiePolicySameSite {
lax = "lax",
strict = "strict",
none = "none",
}

View file

@ -1,10 +0,0 @@
import CookieNotice from "../classes/CookieNotice";
import "./../../scss/themes/standard.scss";
declare global {
interface Window {
CookieNotice: typeof CookieNotice;
}
}
window.CookieNotice = CookieNotice;

View file

@ -1,3 +0,0 @@
import CookieNotice from "./classes/CookieNotice";
export default CookieNotice;

View file

@ -1,58 +0,0 @@
import type { CookiePolicySameSite, CookieStatus } from "./enums";
// * Cookie Notice types
export type CookieStatusList = Record<string, CookieStatus>;
export type CookieOptions = {
/** The cookie name as an index that can be referred to */
name: string;
/** A string description of the cookie */
description: string;
/** A link of the cookie policy */
link: string;
/** A link label for the (learn more about link) */
labelLink: string;
/**
* The cookies indexes that are concerned
* they should really match.
* Some references
* @link https://github.com/AmauriC/tarteaucitron.js/blob/5a2252baa117b75c1143af635ed4f52c5b0afb5b/tarteaucitron.services.js#L4700
* @link https://developers.google.com/recaptcha/docs/faq?hl=fr
* @link https://cookiedatabase.org/service/vimeo/
* @link https://vimeo.com/cookie_policy
* @link https://policies.google.com/technologies/cookies?hl=en
*/
cookies: string[];
/**
* Fonction qui sert à initialiser la fonctionnalité
* conduisant à la génération du cookie
* @return void
*/
script: () => void;
/**
* Fonction qui sert à informer l'utilisateur
* sur chaque élèment que le cookie
* associé à la fonctionnalité
* est désactivé et propose un lien sur
* cookie notice pour l'activer
* @return void
*/
fallback: () => void | null;
};
// * Values stored in Browser cookie
export type CnCookiePolicies = {
sameSite: CookiePolicySameSite;
secure: boolean;
};
export type CnCookieValues = Map<string, CookieStatus>;
export type CnCookieInfo = {
name: string,
values: CnCookieValues,
date: Date,
cookiePolicies: CnCookiePolicies
}

View file

@ -4,9 +4,9 @@
"declaration": true /* Generates corresponding'.d.ts' files. */,
"declarationDir": "dist/typings" /* build '.d.ts' files to ./dist/typeings */,
"outDir": "dist/esm/" /* build to ./dist/esm/ */,
"target": "es2020" /* Build to es2020 */,
"lib": ["es2018", "es2021", "es2022", "dom", "dom.iterable"] /* Using ES2022 features and DOM APIs */,
"module": "es2020" /* using es2020 modules */,
"target": "es2015" /* Build to ES2022 */,
"lib": ["es2015", "es2021", "es2022", "dom", "dom.iterable"] /* Using ES2022 features and DOM APIs */,
"module": "es2015" /* using es2020 modules */,
"rootDir": "src",
"strict": true,
"jsx": "preserve",
@ -16,7 +16,7 @@
"node_modules/@types"
]
},
"files": ["src/ts/index.ts"],
"files": ["./src/index.ts"],
"include": [
"src/**/*.js",
"src/**/*.ts",

View file

@ -5,7 +5,7 @@ module.exports = (env, argv) => {
devtool: "source-map",
mode: argv.mode === "production" ? "production" : "development",
entry: [
path.resolve(__dirname, "./src/ts/index.ts"),
path.resolve(__dirname, "./dist/esm/index.js"),
path.resolve(__dirname, "./src/scss/themes/standard.scss")
],
output: {