154 Commits

Author SHA1 Message Date
Ron Braha
413abc7fd8 add missing "hideOnDecline" prop to index.d.ts (#145) 2021-12-28 12:07:49 +01:00
2a1e52b24a Fix the TypeScript definition of some properties ( (#144)
Co-authored-by: Souchet Céline <4921914+csouchet@users.noreply.github.com>
2021-12-20 17:49:36 +01:00
775ec9db96 release 7.1.0 2021-12-19 13:30:47 +01:00
eaaf6f8797 Added custom attribute props for content and container 2021-12-19 13:30:42 +01:00
8c86599f24 release 7.0.1 2021-12-11 11:13:55 +01:00
719bb2f496 Switch Library Type from CommonJs2 =&gt; UMD ( (#135)
Co-authored-by: Peter Krieg <pkrieg2@gmail.com>
2021-12-08 17:37:44 +01:00
9a0c974b2a release 6.4.1 2021-09-23 19:16:15 +02:00
c2f92ec130 added visible prop, and other missing items, to typings 2021-09-23 19:16:02 +02:00
7136086602 release 6.4.0 2021-09-17 18:25:41 +02:00
Situ
c3ba87e62f Update cookie value (#125)
* Chore: resetCookieConsentValue function

* Chore: VISIBLE_OPTIONS enum & render update in order to use it

* Readme review
2021-09-17 18:22:12 +02:00
239001cb19 readme update ... 2021-08-11 11:19:29 +02:00
e024961eae release code now escapes variables properly :) 2021-08-11 11:18:44 +02:00
a19649bbcf release $npm_package_version 2021-08-11 11:16:03 +02:00
696200262e Added the (optional) scrolling effect back in as it is declared legal in some countries now. 2021-08-11 11:14:18 +02:00
e52811b3a8 release $npm_package_version 2021-05-24 18:27:42 +02:00
dependabot[bot]
814202780b Bump lodash from 4.17.20 to 4.17.21 (#114)
Bumps [lodash](https://github.com/lodash/lodash) from 4.17.20 to 4.17.21.
- [Release notes](https://github.com/lodash/lodash/releases)
- [Commits](https://github.com/lodash/lodash/compare/4.17.20...4.17.21)

Signed-off-by: dependabot[bot] <support@github.com>

Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com>
2021-05-12 09:08:43 +02:00
dependabot[bot]
d01995e3b4 Bump ssri from 8.0.0 to 8.0.1 (#111)
Bumps [ssri](https://github.com/npm/ssri) from 8.0.0 to 8.0.1.
- [Release notes](https://github.com/npm/ssri/releases)
- [Changelog](https://github.com/npm/ssri/blob/latest/CHANGELOG.md)
- [Commits](https://github.com/npm/ssri/compare/v8.0.0...v8.0.1)

Signed-off-by: dependabot[bot] <support@github.com>

Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com>
2021-04-12 13:15:52 +02:00
56de263dce release $npm_package_version 2021-02-19 10:43:49 +01:00
Gabrijel Škoro
0228e7f32c Added support for IE11 (#107) 2021-02-19 10:40:58 +01:00
50216eec3c release $npm_package_version 2021-01-27 16:35:17 +01:00
3e9e988e96 Fixed the return type of getCookieConsentValue in the dts file. 2021-01-27 16:34:57 +01:00
1c6f335500 release $npm_package_version 2020-12-08 18:02:10 +01:00
eb45e7a652 release $npm_package_version 2020-12-06 19:08:02 +01:00
26306f7490 Added the exported function getCookieConsentValue to get the cookie value from custom code 2020-12-06 19:07:50 +01:00
7d8f52018d Merge branch 'master' of github.com:Mastermindzh/react-cookie-consent into master 2020-11-29 10:28:40 +01:00
a494066785 Updated the Changelog and added a check in the package.json to ensure no more releases skip the CHANGELOG updates. fixes #99 2020-11-29 10:28:32 +01:00
Tom
7f15b25e89 fixed anchor (#98) 2020-11-20 09:52:12 +01:00
0f4893af4b release $PACKAGE_VERSION 2020-11-08 11:44:10 +01:00
Evan Kennedy
1ad4474d93 Support React 17 (#96) 2020-11-08 11:43:24 +01:00
Stephan Bakkelund Valois
6a5aac9cd7 Fixed typos - changed headlines to capitalized first letter. (#94)
Co-authored-by: Ubuntu <ubuntu@ip-172-31-14-150.eu-north-1.compute.internal>
2020-11-06 16:54:27 +01:00
c656e311e6 release 6.0.0 2020-11-02 19:43:03 +01:00
Gerard Brull
86226dfbe3 Upgrade deps (#93) 2020-11-02 19:17:06 +01:00
Gerard Brull
d0c619542d Remove scroll on accept (#89) 2020-11-02 19:16:58 +01:00
f6243bd987 added the contributing guidelines and added package-lock.json (Thanks to @poteirard) 2020-11-01 09:16:36 +01:00
d99d88f5b8 readme update 2020-10-14 09:03:22 +02:00
f51e2a0555 release $PACKAGE_VERSION 2020-10-13 22:16:59 +02:00
5e4e8406e6 added aria label capabilities for both buttons 2020-10-13 22:13:09 +02:00
b1913d223e release $PACKAGE_VERSION 2020-10-04 09:52:10 +02:00
cb93ae6387 set default SameSite attribute to "lax" 2020-10-04 09:51:53 +02:00
35e45c3125 Create stale.yml 2020-08-16 16:30:08 +02:00
a7fe76056e auto tagging 2020-07-23 13:02:26 +02:00
3471a72b1e version bump and build 2020-07-23 12:50:54 +02:00
777ceb8e1a 5.1.3 2020-07-23 12:50:52 +02:00
72443a758a added link to github release and releasing will now create a git tag 2020-07-23 12:50:49 +02:00
Benedikt Bauer
5910a110ce Add ButtonWrapperClass from v4 to type definition (#80) 2020-07-23 12:44:16 +02:00
a56e806ee2 Update README.md
Added an explanation of the legacy cookie to the readme.
2020-07-06 10:12:54 +02:00
13c6909b1a align changelog with version 2020-06-28 12:00:32 +02:00
97bb1e5be0 version bump and build 2020-06-28 11:58:17 +02:00
Bram Devries
4fa6476406 Set cookie value before handling side-effects (#76) 2020-06-28 11:26:06 +02:00
8561858333 adding some pretty badges :) 2020-06-18 18:27:49 +02:00
d502d28739 version bump and build 2020-06-18 18:14:31 +02:00
47f0e98fe4 Removed the React.Fragment and introduced a more general div. By moving the declaration in code our html code is a bit nicer as well. Fixes #74 2020-06-18 18:14:17 +02:00
6dbd794b6e version bump and build 2020-06-17 10:29:15 +02:00
Sean Teague
76ec5ba9e6 Overlay develop feature (#71)
Thanks again @Steague
2020-06-17 10:25:21 +02:00
9169c132fe updated contributor info, added a TOC and installed lint-staged 2020-06-16 21:14:22 +02:00
75ff4a09e6 added husky, prettier and changed editorconfig 2020-06-16 21:09:25 +02:00
d51ea89620 version bump and build 2020-05-26 17:16:12 +02:00
e7c2b5b39a bugfix issue#68 2020-05-26 17:16:01 +02:00
22bb46981d version bump and build 2020-05-23 22:40:09 +02:00
e2fb5f3990 Merge pull request #68 from mding5692/hot-fix/samesite-support 2020-05-23 22:38:21 +02:00
a64cbc28f9 minor bugfixes for PR https://github.com/Mastermindzh/react-cookie-consent/pull/68
- extracted code which handles setting/getting cookies.
- added correct implementation of the legacy cookie fix according to the provided url
- added cookieSecurity attribute with default value based on runtime environment
- updated README
- ran builds
2020-05-23 22:36:28 +02:00
mding5692
d7bfb5bfbd Fixes typo with component config 2020-05-19 12:06:00 -04:00
mding5692
3cf103ae3a Fixes typo with js cookie samesite props 2020-05-19 12:04:54 -04:00
mding5692
a45da474b4 Adds fallback for older incompatible browsers with samesite=none 2020-05-18 13:43:39 -04:00
mding5692
ee7ac9ed86 Adds config for samesite support 2020-05-17 12:09:53 -04:00
b3bd42adae version bump and build 2020-05-11 08:35:04 +02:00
900d724ea5 made CookieConsent the default containerClass 2020-05-11 08:34:50 +02:00
d1a1c39ef6 buttonWrapper added, npm updates done, changelog added and formatting 2020-05-10 11:32:06 +02:00
62d607d813 Merge pull request #66 from iliyanyotov/typings-styled-components
Changed ButtonComponent proptype definitions to ElementType. See https://reactjs.org/docs/typechecking-with-proptypes.html for details.
2020-05-10 10:59:30 +02:00
Iliyan Yotov
c1659cef53 Adjust the typing and the prop-type definitions related to the ButtonComponent property 2020-05-08 00:32:48 +03:00
4a37243ec2 Updated link to inici gatsby theme
According to #62
2020-04-05 10:38:53 +02:00
6328f74e78 version bump and build 2019-12-20 08:14:32 +01:00
12341c9126 Fix #56 - add acceptedByScrolling to onAccept (#57)
Fix #56 - add acceptedByScrolling to onAccept
2019-12-20 08:11:56 +01:00
Matt Knight
7cc1fc3905 Fix #56 - add acceptedByScrolling to onAccept
Checking the {acceptedByScrolling} boolean property will allow you to
determine whether the acceptance was triggered by the user scrolling
(if acceptedByScrolling=true) or explicitly clicking the Accept button
(if acceptedByScrolling=false).
2019-12-19 15:39:17 -07:00
9980d42af6 version bump and build 2019-08-22 14:20:03 +02:00
7b5e6dc66f Merge pull request #52 from agustin107/master
Add @types/js-cookie
2019-08-22 14:18:50 +02:00
Agustin N. R. Ramirez
11b55f2f8a Add @types/js-cookie 2019-08-22 09:05:31 -03:00
7e0cb2059b version bump and build 2019-08-19 19:10:34 +02:00
959412c96b fixed typings, my bad! 2019-08-19 19:10:23 +02:00
51e0c9949c Develop (#47)
Develop
2019-08-12 18:41:55 +02:00
844b69363e Merge branch 'master' of github.com:Mastermindzh/react-cookie-consent into develop 2019-08-12 18:41:01 +02:00
8d74d5531f version bump and build 2019-08-12 18:38:59 +02:00
1c3a54bd89 no longer setting position when location is passed.
added property "setDeclineCookie" to indicate whether a cookie has to be set on decline.

fixes #45
fixes #46
2019-08-12 18:38:25 +02:00
c174baaba6 Merge pull request #44 from dcsaszar/readme
README: Add Scrivito Example App to projects
2019-08-05 08:27:46 +02:00
David Császár
3c1d11b509 Add Scrivito Example App to projects 2019-08-02 15:38:42 +02:00
f3c5bfcd83 version bump and build 2019-06-27 14:26:23 +02:00
68a8301cd5 Merge pull request #42 from a-game/fix/acceptOnScroll-forced-in-debug
Fix: Debug mode overriding acceptOnScroll property
2019-06-27 14:24:53 +02:00
Ahmad Game
f7a98c925d When running in debug mode, the scroll liteneris always added regardless of weather the acceptOnScroll was set to true or false 2019-06-27 11:30:43 +02:00
98b401dc72 Fix name of imported variable (#41)
Fix name of imported variable
2019-05-06 15:07:19 +02:00
Karl Horky
cfbd647c38 Fix name of imported variable 2019-05-06 11:24:34 +02:00
5a807f884b version bump and build 2019-05-03 12:07:12 +02:00
8aef083015 Merge pull request #40 from csoLs/master
Add flipButtons to ts definition
2019-05-03 11:53:35 +02:00
csoLs
34ac530629 Add flipButtons to ts definition 2019-05-03 10:47:55 +02:00
ce0d7e2b0c spelling.. :) 2019-04-13 22:25:17 +02:00
bd54a23369 version bump and build 2019-04-13 22:17:21 +02:00
b1ba269ed3 added buttonFlipping 2019-04-13 22:17:03 +02:00
13701e0a1d changed default colours 2019-04-13 22:09:16 +02:00
3926fff424 prettified the code 2019-04-13 21:30:58 +02:00
c82911c903 Merge pull request #38 from fannaroh/master
Decline button added and bug fix for acceptOnScroll handler
2019-04-13 21:29:31 +02:00
Fannar Orn Hermannsson
351b0e1233 Decline button added and bug fix for onAccept being triggered on scroll to accept when a cookie was already created 2019-04-05 22:25:15 +00:00
e7a48a8694 added another project which uses the cookiebar 2019-03-16 20:40:27 +01:00
f355409b87 version bump and build 2019-03-05 15:16:03 +01:00
Varmint
abe9a06399 Provide feedback the button is clickable (#37) 2019-03-05 15:11:18 +01:00
67af0cf9f4 version bump and build 2019-02-26 14:02:14 +01:00
9baff03191 Revert "reverted PascalCase to camelCase, thanks again for the contribution @charlyx !"
This reverts commit 969da3c809.
2019-02-26 14:01:17 +01:00
49f275b3cd version bump and build 2019-02-26 13:27:39 +01:00
969da3c809 reverted PascalCase to camelCase, thanks again for the contribution @charlyx ! 2019-02-26 13:27:13 +01:00
Charles-Henri GUERIN
ee24754fc8 Add prop ButtonComponent (#36)
*  Add prop buttonComponent

Allow users to use their own button component

* 🐛 Make it work as expected

* 📝 Add ButtonComponent to the Props table

* ✏️ Capitalize ButtonComponent in index.d.ts
2019-02-26 13:23:17 +01:00
0a5e4ea440 added the disableButtonStyles property 2019-02-04 20:38:46 +01:00
e8d4dcab3e version bump and build 2019-01-06 11:09:01 +01:00
a4c30e6a5d added the object-assign babel transformation 2019-01-06 11:08:43 +01:00
4cc521c977 version bump and build 2018-12-05 08:34:50 +01:00
666678eade Merge pull request #31 from amytych/patch-1
Fix misplaced dependencies
2018-12-05 08:32:27 +01:00
Arek Mytych
f587c141b0 Add React to devDependencies as well 2018-12-05 07:32:30 +01:00
Arek Mytych
720063d47b Fix misplaced dependencies
Move `react` to `peerDependencies` and  `copy-webpack-plugin` to `devDependencies`

Closes #30
2018-12-04 17:19:42 +01:00
73271cafe1 added comicrelief to the storybook :) 2018-11-28 09:09:36 +01:00
06d41df333 version bump and build 2018-11-28 09:05:35 +01:00
1822d9ad83 prettified the typescript definition file (using prettier) 2018-11-28 09:03:48 +01:00
04c553fded Merge pull request #29 from Saturate/master
Add TypeScript Definition
2018-11-28 09:01:50 +01:00
Allan Kimmer Jensen
ef192c0e86 Fix issue pointed out in PR
Last commit went a little too fast it seems, this fixes:

- Spelling error
- Indentation
- Code Syntax (No interface prefix)
2018-11-27 19:50:32 +01:00
Allan Kimmer Jensen
673f4fe28f Add TypeScript Definition
Add a TypeScript Definition, and "build" it with webpack to the build folder.

This will add correct typings, if you use TypeScript with React.

#27
2018-11-27 17:40:11 +01:00
48995d9a3c Update README.md 2018-11-02 08:32:57 +01:00
cd634efa9e version bump and build 2018-10-19 14:25:16 +02:00
55267ebfce Merge pull request #26 from delaneymethod/feature/button-id
Added new buttonId prop
2018-10-19 14:22:35 +02:00
Sean Delaney
f1fdab3bb5 Added new buttonId prop
Signed-off-by: Sean Delaney <hello@delaneymethod.com>
2018-10-19 10:38:51 +01:00
e6120e4f24 version bump and build 2018-09-27 16:24:36 +02:00
Jo Wo
c5a2632ea3 Adding a cookieValue prop (#24)
The PR will:
* Add a new prop, `cookieValue`, to component and the README. This prop let's you defined the value of the cookie, instead of always defining the hardcoded value of `true`. This is useful when integrating cookies with other cookie consent banners which need to check the same cookie value. For example we use another consent banner along side this one (on a different sub-domain) which checks that the consent cookie is set to `allowed`. 
* Tidying up the props table spacing in the README file
* Remove a few trailing white-spaces after component names and prop definition.
2018-09-27 16:22:13 +02:00
b3d5470d8c version bump and build 2018-07-29 22:03:48 +02:00
df6bd5464f added extra cookie options as requested in #23 2018-07-29 22:02:34 +02:00
27833943f0 version bump and build 2018-07-28 13:24:44 +02:00
38b8d752bb version bump and build 2018-07-13 22:51:24 +02:00
3f6c47ae6d Added the ability to accept on scroll. Fixes #21 2018-07-13 22:50:43 +02:00
ace3cf2886 version bump and build 2018-06-25 22:36:26 +02:00
Dimitris Fasoulas
97133f2c80 Auto hide (#19) 2018-06-25 22:35:16 +02:00
c5a4268624 version bump and build 2018-06-21 18:43:34 +02:00
Dimitris Fasoulas
2d1501457b Allow location none, to disable automatic location styling. Closes gi… (#17)
Fixes #16 

Allows location property to receive string `none` which will disable automatic placement of the component.
2018-06-21 18:33:53 +02:00
d601613b5a implemented issue #15 2018-06-07 11:32:43 +02:00
f8ef6ca218 correcting semver (added a feature in 1.1.13 ...oops) 2018-06-07 10:28:43 +02:00
8df1e362c8 version bump and build 2018-06-07 10:23:28 +02:00
55f62ee575 added an expires prop, idea inspired by aleplusplus (https://github.com/Mastermindzh/react-cookie-consent/pull/14) 2018-06-07 10:09:05 +02:00
869e0b1d13 version bump and build 2018-06-03 18:04:56 +02:00
0fe4c4c567 version bump and build 2018-06-03 17:54:41 +02:00
Karl Anders
cbbbd0422a Remove outdated PNGs (#12) 2018-06-03 17:44:18 +02:00
Karl Anders
36a8fae2b9 Moving to componentdidmount
ComponentWillMount is bound to be deprecated (hence UNSAFE) in the new React version so switching to componentDidMount is a solid plan.
2018-06-03 17:44:04 +02:00
ecdf88a7e9 new build + editorconfig 2018-06-03 11:54:58 +02:00
Karl Anders
66d6aaa57d Default visibility should be false (#11)
* Default visibility should be false
* .prettierrc
2018-06-03 11:47:22 +02:00
Karl Anders
dd350edfbd Correcting the lines (#10)
Thanks again Karland!
2018-06-01 09:32:51 +02:00
26cde73055 default debug prop and new build 2018-05-31 20:00:26 +02:00
Karl Anders
456d5b4fa0 Improve debugging (#9)
* Improve debugging
2018-05-31 19:51:48 +02:00
8bf481fe59 v 1.1.0 2018-05-30 14:25:35 +02:00
431419c3b4 button style fix 2018-05-30 14:22:24 +02:00
1ea07ba29f styling fix by Karland, small readme changes and a version update 2018-05-30 14:10:47 +02:00
Karl Anders
30214d5411 Improve styling with flexbox (#8)
* Improve styling
2018-05-30 14:06:00 +02:00
413ef0c595 moved the example app to its own branch and added a gh-pages 2018-05-26 20:51:39 +02:00
34 changed files with 14968 additions and 11144 deletions

View File

@@ -1,7 +1,8 @@
{
"presets": ["env"],
"presets": ["@babel/preset-env"],
"plugins": [
"transform-object-rest-spread",
"transform-react-jsx"
"@babel/plugin-proposal-object-rest-spread",
"@babel/plugin-transform-react-jsx",
"@babel/plugin-transform-object-assign"
]
}

23
.editorconfig Normal file
View File

@@ -0,0 +1,23 @@
root = true
[*]
end_of_line = lf
charset = utf-8
trim_trailing_whitespace = true
insert_final_newline = true
indent_style = space
indent_size = 2
[Makefile]
indent_style = tab
indent_size = 8
[{deps,tools,build}/**]
indent_style = ignore
indent_size = ignore
end_of_line = ignore
trim_trailing_whitespace = ignore
charset = ignore
[{test/fixtures,deps,build,tools/eslint,tools/gyp,tools/icu,tools/msvs}/**]
insert_final_newline = false

3
.gitignore vendored
View File

@@ -1,2 +1,3 @@
node_modules
package-lock.json
build/index.js.LICENSE.txt
example/*

157
CHANGELOG.md Normal file
View File

@@ -0,0 +1,157 @@
# Changelog
All notable changes to this project will be documented in this file.
The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.0.0/),
and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0.html).
## [[7.2.0]](https://github.com/Mastermindzh/react-cookie-consent/releases/tag/7.2.0)
- Added `onOverlayClick` which allows you to react to a click on the overlay
- Added `acceptOnOverlayClick` which accepts the cookies when the overlay is clicked and runs `onOverlayClick`
## [[7.1.1]](https://github.com/Mastermindzh/react-cookie-consent/releases/tag/7.1.1)
- `customContentAttributes` and `customContainerAttributes` are now optional in the typing file as they should be
## [[7.1.0](https://github.com/Mastermindzh/react-cookie-consent/releases/tag/7.1.0)]
- Added custom attribute props for content and container
## [[7.0.1](https://github.com/Mastermindzh/react-cookie-consent/releases/tag/7.0.1)]
- Configured webpack to remove self from build artefact. Should now work in Nextjs and Gatsby (only tested those..)
## [[7.0.0](https://github.com/Mastermindzh/react-cookie-consent/releases/tag/7.0.0)]
- Switched from CommonJS to UMD module
## [[6.4.1](https://github.com/Mastermindzh/react-cookie-consent/releases/tag/6.4.1))]
- Added missing typing
## [[6.4.0](https://github.com/Mastermindzh/react-cookie-consent/releases/tag/6.4.0))]
- Added visible prop
## [[6.3.0](https://github.com/Mastermindzh/react-cookie-consent/releases/tag/6.2.3))]
- Added the (optional) scrolling effect back in as it is declared legal in some countries now.
## [6.2.4]
- version bumps :)
## [[6.2.3](https://github.com/Mastermindzh/react-cookie-consent/releases/tag/6.2.3)]
- Added support for IE11, the webpack generated runtime-code should not use arrow functions
## [[6.2.2](https://github.com/Mastermindzh/react-cookie-consent/releases/tag/6.2.2)]
- Fixed the return type of getCookieConsentValue in the dts file.
## [[6.2.1](https://github.com/Mastermindzh/react-cookie-consent/releases/tag/6.2.1)]
Added the `getCookieConsentValue` to the dts file.
## [[6.2.0](https://github.com/Mastermindzh/react-cookie-consent/releases/tag/6.2.0)]
Added the exported function `getCookieConsentValue` to get the cookie value from custom code
## [[6.1.0](https://github.com/Mastermindzh/react-cookie-consent/releases/tag/6.1.0)]
Added support for React 17
## [[6.0.0](https://github.com/Mastermindzh/react-cookie-consent/releases/tag/6.0.0)]
### removed
Accepting by scrolling is no longer allowed and has thus been removed from the package.
For details see [issue 88](https://github.com/Mastermindzh/react-cookie-consent/issues/88)
## [[5.2.0](https://github.com/Mastermindzh/react-cookie-consent/releases/tag/5.2.0)]
### added
Added aria labels for both the decline and accept button
## [[5.1.4](https://github.com/Mastermindzh/react-cookie-consent/releases/tag/5.1.4)]
### changed
- set default SameSite attribute to "lax" because browsers are already implementing the cookie policy changes.
## [[5.1.3](https://github.com/Mastermindzh/react-cookie-consent/releases/tag/5.1.3)]
### changed
- Fix missing buttonWrapperClasses prop in type definition
## [5.1.2]
### changed
- Set cookie value before handling side-effects.
- The overlay is now conditional. Meaning that the component behaves exactly as it did prior to 5.1.0 when you do not use the overlay
## [5.1.0]
A new feature! This time it's an "overlay" on the entire website to block access whilst the cookiebar is displayed.
This is all opt-in of course and the README covers it nicely (just add overlay to the props and see what happens).
We got an update picture, with a cute cat... unfortunately the cat won't be included by default:
![overlay example image](https://github.com/Mastermindzh/react-cookie-consent/blob/master/images/overlay.png?raw=true)
## [5.0.1]
- Fixed [Issue
69](https://github.com/Mastermindzh/react-cookie-consent/issues/69) by
removing location from the proptypes to avoid build-time issues
## [5.0.0]
### added
- CookieSecurity prop - allows securing the cookie
- sameSite prop - allows you to set sameSite properties so browser won't warn
about non-secure cookies :)
## [4.1.0]
### changed
- Added CookieConsent back in as the default for the containerClasses property.
## [4.0.0]
I decided to update react-cookie-consent to version 4 because this version has a
buttonWrapper which will break appearance. I consider appearance a major feature.
### Added
- Changelog :D
- A wrapper around the buttons so they always stay together. (still possible to
change with css using buttonWrapperClasses)
### Changed
- Default ids for the buttons (rcc stands for react-cookie-consent,
cookie-consent is blocked by some adblockers nowadays so I abbreviated it)
### Updated
#### dependencies
- js-cookie updated from `2.2.0` to `2.2.1`
#### peer dependencies
- react updated from `16.4.0` to `16.13.1`
#### development dependencies
- @types/js-cookie updated from `2.2.2` to `2.2.6`
- babel-cli updated from `6.24.1` to `6.26.0`
- babel-preset-env updated from `1.5.1` to `1.7.0`
- react updated from `16.8.6` to `16.13.1`

152
CONTRIBUTING.md Normal file
View File

@@ -0,0 +1,152 @@
# Contributing
When contributing to this repository, please first discuss the change you wish to make via issue,
email, or any other method with the owners of this repository before making a changes in order to avoid wasting your time.
## scope
Please keep the scope of a PR down to a single change.
You can make multiple prs to change multiple things though.
## builds
Don't modify anything in the build/ directory please.
This will be done on release.
## Pull Request Process
1. Code away :D
2. Update the README.md with details of changes to the interface, this includes new environment
variables, exposed ports, useful file locations and container parameters.
_Please don't change the format of the variable table in the README_
3. Add the section "[next]" to the CHANGELOG.md and describe what you changed and why.
4. Create the PR. yay.
## Contributor Covenant Code of Conduct
### Our Pledge
We as members, contributors, and leaders pledge to make participation in our
community a harassment-free experience for everyone, regardless of age, body
size, visible or invisible disability, ethnicity, sex characteristics, gender
identity and expression, level of experience, education, socio-economic status,
nationality, personal appearance, race, religion, or sexual identity
and orientation.
We pledge to act and interact in ways that contribute to an open, welcoming,
diverse, inclusive, and healthy community.
### Our Standards
Examples of behavior that contributes to a positive environment for our
community include:
- Demonstrating empathy and kindness toward other people
- Being respectful of differing opinions, viewpoints, and experiences
- Giving and gracefully accepting constructive feedback
- Accepting responsibility and apologizing to those affected by our mistakes,
and learning from the experience
- Focusing on what is best not just for us as individuals, but for the
overall community
Examples of unacceptable behavior include:
- The use of sexualized language or imagery, and sexual attention or
advances of any kind
- Trolling, insulting or derogatory comments, and personal or political attacks
- Public or private harassment
- Publishing others' private information, such as a physical or email
address, without their explicit permission
- Other conduct which could reasonably be considered inappropriate in a
professional setting
### Enforcement Responsibilities
Community leaders are responsible for clarifying and enforcing our standards of
acceptable behavior and will take appropriate and fair corrective action in
response to any behavior that they deem inappropriate, threatening, offensive,
or harmful.
Community leaders have the right and responsibility to remove, edit, or reject
comments, commits, code, wiki edits, issues, and other contributions that are
not aligned to this Code of Conduct, and will communicate reasons for moderation
decisions when appropriate.
### Scope
This Code of Conduct applies within all community spaces, and also applies when
an individual is officially representing the community in public spaces.
Examples of representing our community include using an official e-mail address,
posting via an official social media account, or acting as an appointed
representative at an online or offline event.
### Enforcement
Instances of abusive, harassing, or otherwise unacceptable behavior may be
reported to the community leaders responsible for enforcement at
[info@rickvanlieshout.com](mailto:info@rickvanlieshout.com).
All complaints will be reviewed and investigated fairly.
All community leaders are obligated to respect the privacy and security of the
reporter of any incident.
### Enforcement Guidelines
Community leaders will follow these Community Impact Guidelines in determining
the consequences for any action they deem in violation of this Code of Conduct:
#### 1. Correction
**Community Impact**: Use of inappropriate language or other behavior deemed
unprofessional or unwelcome in the community.
**Consequence**: A private, written warning from community leaders, providing
clarity around the nature of the violation and an explanation of why the
behavior was inappropriate. A public apology may be requested.
#### 2. Warning
**Community Impact**: A violation through a single incident or series
of actions.
**Consequence**: A warning with consequences for continued behavior. No
interaction with the people involved, including unsolicited interaction with
those enforcing the Code of Conduct, for a specified period of time. This
includes avoiding interactions in community spaces as well as external channels
like social media. Violating these terms may lead to a temporary or
permanent ban.
#### 3. Temporary Ban
**Community Impact**: A serious violation of community standards, including
sustained inappropriate behavior.
**Consequence**: A temporary ban from any sort of interaction or public
communication with the community for a specified period of time. No public or
private interaction with the people involved, including unsolicited interaction
with those enforcing the Code of Conduct, is allowed during this period.
Violating these terms may lead to a permanent ban.
#### 4. Permanent Ban
**Community Impact**: Demonstrating a pattern of violation of community
standards, including sustained inappropriate behavior, harassment of an
individual, or aggression toward or disparagement of classes of individuals.
**Consequence**: A permanent ban from any sort of public interaction within
the community.
### Attribution
This Code of Conduct is adapted from the [Contributor Covenant][homepage],
version 2.0, available at
https://www.contributor-covenant.org/version/2/0/code_of_conduct.html.
Community Impact Guidelines were inspired by [Mozilla's code of conduct
enforcement ladder](https://github.com/mozilla/diversity).
[homepage]: https://www.contributor-covenant.org
For answers to common questions about this code of conduct, see the FAQ at
https://www.contributor-covenant.org/faq. Translations are available at
https://www.contributor-covenant.org/translations.

325
README.md
View File

@@ -4,20 +4,50 @@ A small, simple and customizable cookie consent bar for use in React application
[![NPM](https://nodei.co/npm/react-cookie-consent.png)](https://npmjs.org/package/react-cookie-consent)
Demo: https://mastermindzh.github.io/react-cookie-consent/
Example branch: https://github.com/Mastermindzh/react-cookie-consent/tree/example
![Downloads](https://img.shields.io/npm/dm/react-cookie-consent) ![Dependent repos (via libraries.io)](https://img.shields.io/librariesio/dependent-repos/npm/react-cookie-consent) ![GitHub contributors](https://img.shields.io/github/contributors/mastermindzh/react-cookie-consent) ![Minified size](https://img.shields.io/bundlephobia/min/react-cookie-consent) ![npm type definitions](https://img.shields.io/npm/types/react-cookie-consent) ![license-mit](https://img.shields.io/badge/license-MIT-green)
## Default look
![default look](https://raw.githubusercontent.com/Mastermindzh/react-cookie-consent/master/images/default.png)
## Table of contents
<!-- toc -->
- [Installation](#installation)
- [Using it](#using-it)
- [getting the cookies value in your own code](#getting-the-cookies-value-in-your-own-code)
- [Props](#props)
- [Debugging it](#debugging-it)
- [Why are there two cookies? One of which named "Legacy"](#why-are-there-two-cookies-one-of-which-named-legacy)
- [Styling it](#styling-it)
- [Examples](#examples)
- [Changing the bar background to red](#changing-the-bar-background-to-red)
- [Changing the button font-weight to bold](#changing-the-button-font-weight-to-bold)
- [Using predefined CSS classes](#using-predefined-css-classes)
- [Accept on scroll](#accept-on-scroll)
- [Flipping the buttons](#flipping-the-buttons)
- [Extra cookie options](#extra-cookie-options)
- [Rainbows!](#rainbows)
- [Overlay](#overlay)
- [Contributor information](#contributor-information)
- [Projects using react-cookie-consent](#projects-using-react-cookie-consent)
<!-- tocstop -->
## Installation
```
```shell
npm install react-cookie-consent
```
or use yarn:
```
```shell
yarn add react-cookie-consent
```
@@ -28,86 +58,244 @@ You can import the cookie bar like this:
```js
import CookieConsent from "react-cookie-consent";
```
If you want to set/remove cookies yourself you can optionally import Cookie (straight from js-cookie) like this:
If you want to set/remove cookies yourself you can optionally import `Cookies` (straight from js-cookie) like this:
```js
import CookieConsent, { Cookies } from "react-cookie-consent";
```
Then you can use the component anywhere in your React app like so:
```js
<CookieConsent>
This website uses cookies to enhance the user experience.
</CookieConsent>
```jsx
<CookieConsent>This website uses cookies to enhance the user experience.</CookieConsent>
```
You can optionally set some props like this (next chapter will show all props):
```js
<CookieConsent
location="bottom"
buttonText="Sure man!!"
cookieName="myAwesomeCookieName2"
style={{ background: "#2B373B" }}
buttonStyle={{ color: "#4e503b", fontSize: "13px" }}
location="bottom"
buttonText="Sure man!!"
cookieName="myAwesomeCookieName2"
style={{ background: "#2B373B" }}
buttonStyle={{ color: "#4e503b", fontSize: "13px" }}
expires={150}
>
This website uses cookies to enhance the user experience.{" "}
<span style={{ fontSize: "10px" }}>
This bit of text is smaller :O
</span>
This website uses cookies to enhance the user experience.{" "}
<span style={{ fontSize: "10px" }}>This bit of text is smaller :O</span>
</CookieConsent>
```
One of the props (onAccept) is a function, this function will be called after the user has clicked the accept button. You can provide a function like so:
One of the props (onAccept) is a function, this function will be called after the user has clicked the accept button. It is called with an object containing a boolean property `acceptedByScrolling` to indicate if the acceptance was triggered by the user scrolling You can provide a function like so:
```js
<CookieConsent
onAccept={() => {alert("yay!")}}
>
</CookieConsent>
onAccept={(acceptedByScrolling) => {
if (acceptedByScrolling) {
// triggered if user scrolls past threshold
alert("Accept was triggered by user scrolling");
} else {
alert("Accept was triggered by clicking the Accept button");
}
}}
></CookieConsent>
```
If the decline button is enabled then the (onDecline) prop function can be used, this function will be called after the user has clicked the decline button. You can enable the button and provide a function like so:
```js
<CookieConsent
enableDeclineButton
onDecline={() => {
alert("nay!");
}}
></CookieConsent>
```
### getting the cookies value in your own code
react-cookie-consent exports a function called `getCookieConsentValue`. You can use it in your own code like so:
```js
import CookieConsent, { Cookies, getCookieConsentValue } from "react-cookie-consent";
console.log(getCookieConsentValue());
```
### reset the cookies value in your own code
react-cookie-consent exports a function called `resetCookieConsentValue`. You can use it in order to remove cookie in client-site:
```js
import CookieConsent, { Cookies, resetCookieConsentValue } from "react-cookie-consent";
console.log(resetCookieConsentValue());
```
That option would be interesting if you want to allow user to change their consent. If you want to show again the consent bar, you must force "visible" prop to show again the bar.
## Props
| Prop | Type | Default value | Description |
|---------------|:--------------------------------:|---------------|-------------------------------------------------------------------------------------------------------|
| location | String, either "top" or "bottom" | bottom | Syntactic sugar to easily enable you to place the bar at the top or the bottom of the browser window. |
| children | String or React component | | Content to appear inside the bar |
| disableStyles | boolean | false | If enabled the component will have no default style. (you can still supply style through props) |
| buttonText | String or React component | I understand | Text to appear on the button |
| cookieName | string | CookieConsent | Name of the cookie used to track whether the user has agreed. |
| onAccept | function | () => {} | Function to be called after the accept button has been clicked. |
| style | Object | ![barstyle](https://github.com/Mastermindzh/react-cookie-consent/blob/master/images/barStyle.png?raw=true) | React styling object for the bar. |
| buttonStyle | Object | ![buttonStyle](https://github.com/Mastermindzh/react-cookie-consent/blob/master/images/buttonStyle.png?raw=true) | React styling object for the button. |
| Prop | Type | Default value | Description |
| ------------------------- | :-----------------------------------------: | ------------------------------------ | --------------------------------------------------------------------------------------------------------------------------------------- |
| location | string, "top", "bottom" or "none" | "bottom" | Syntactic sugar to easily enable you to place the bar at the top or the bottom of the browser window. Use "none" to disable. |
| visible | string, "show", "hidden" or "byCookieValue" | "byCookieValue" | Force the consent bar visibility. If "byCookieValue", visibility are defined by cookie consent existence. |
| children | string or React component | | Content to appear inside the bar |
| disableStyles | boolean | false | If enabled the component will have no default style. (you can still supply style through props) |
| hideOnAccept | boolean | true | If disabled the component will not hide it self after the accept button has been clicked. You will need to hide yourself (see onAccept) |
| buttonText | string or React component | "I understand" | Text to appear on the button |
| declineButtonText | string or React component | "I decline" | Text to appear on the decline button |
| cookieName | string | "CookieConsent" | Name of the cookie used to track whether the user has agreed. |
| cookieValue | string or boolean or number | true | Value to be saved under the cookieName. |
| declineCookieValue | string or boolean or number | false | Value to be saved under the cookieName when declined. |
| setDeclineCookie | boolean | true | Whether to set a cookie when the user clicks "decline" |
| onAccept | function | `() => {}` | Function to be called after the accept button has been clicked. |
| onDecline | function | `() => {}` | Function to be called after the decline button has been clicked. |
| debug | boolean | undefined | Bar will be drawn regardless of cookie for debugging purposes. |
| expires | number | 365 | Number of days before the cookie expires. |
| extraCookieOptions | object | `{}` | Extra info (apart from expiry date) to add to the cookie |
| overlay | boolean | false | Whether to show a page obscuring overlay or not. |
| containerClasses | string | "" | CSS classes to apply to the surrounding container |
| buttonClasses | string | "" | CSS classes to apply to the button |
| buttonWrapperClasses | string | "" | CSS classes to apply to the div wrapping the buttons |
| declineButtonClasses | string | "" | CSS classes to apply to the decline button |
| buttonId | string | "" | Id to apply to the button |
| declineButtonId | string | "" | Id to apply to the decline button |
| contentClasses | string | "" | CSS classes to apply to the content |
| overlayClasses | string | "" | CSS classes to apply to the surrounding overlay |
| style | object | [look at source][style] | React styling object for the bar. |
| buttonStyle | object | [look at source][buttonstyle] | React styling object for the button. |
| declineButtonStyle | object | [look at source][declinebuttonstyle] | React styling object for the decline button. |
| contentStyle | object | [look at source][contentstyle] | React styling object for the content. |
| overlayStyle | object | [look at source][overlaystyle] | React styling object for the overlay. |
| disableButtonStyles | boolean | false | If enabled the button will have no default style. (you can still supply style through props) |
| enableDeclineButton | boolean | false | If enabled the decline button will be rendered |
| flipButtons | boolean | false | If enabled the accept and decline buttons will be flipped |
| ButtonComponent | React component | button | React Component to render as a button. |
| sameSite | string, "strict", "lax" or "none" | none | Cookies sameSite attribute value |
| cookieSecurity | boolean ¡ | undefined | Cookie security level. Defaults to true unless running on http. |
| ariaAcceptLabel | string | Accept cookies | Aria label to set on the accept button |
| ariaDeclineLabel | string | Decline cookies | Aria label to set on the decline button |
| acceptOnScroll | boolean | false | Defines whether "accept" should be fired after the user scrolls a certain distance (see acceptOnScrollPercentage) |
| acceptOnScrollPercentage | number | 25 | Percentage of the page height the user has to scroll to trigger the accept function if acceptOnScroll is enabled |
| customContentAttributes | object | `{}` | Allows you to set custom (data) attributes on the content div |
| customContainerAttributes | object | `{}` | Allows you to set custom (data) attributes on the container div |
| onOverlayClick | function | `() => {}` | allows you to react to a click on the overlay |
| acceptOnOverlayClick | boolean | false | Determines whether the cookies should be accepted after clicking on the overlay |
## Debugging it
Because the cookie consent bar will be hidden once accepted, you will have to set the prop `debug={true}` to evaluate styling changes:
```js
<CookieConsent debug={true}></CookieConsent>
```
**Note:** Don't forget to remove the `debug`-property for production.
## Why are there two cookies? One of which named "Legacy"
The short story is that some browsers don't support the SameSite=None attribute.
The modern browsers force you to have SameSite set to something other than none.
So react-cookie-consent fixes this like so:
- set the fallback cookie (e.g -legacy) first, this will always succeed (on all browsers)
- set the correct cookie second (this will work on modern browsers, fail on older ones)
This happens on lines [186-192](https://github.com/Mastermindzh/react-cookie-consent/blob/master/src/index.js#L186-L192)
When checking the cookie it'll do it in reverse. If the regular cookie exists, it'll use that. If no regular cookie exists it'll check whether the legacy cookie exists. If both are non-existent no consent was given.
The long story can be found here: [pull-request#68](https://github.com/Mastermindzh/react-cookie-consent/pull/68)
## Styling it
You can provide styling for both the bar and the button.
You can do this using the `style` and `buttonStyle` prop, both of these will append / replace the default style of the component.
You can provide styling for the bar, the button and the content. Note that the bar has a `display: flex` property as default and is parent to its children "content" and "button".
The styling behaves kind of responsive. The minimum content width has been chosen to be "300px" as a default value. If the button does not fit into the same line it is wrapped around into the next line.
You can style each component by using the `style`, `buttonStyle` and `contentStyle` prop. These will append / replace the default styles of the components.
Alternatively you can provide CSS classnames as `containerClasses`, `buttonClasses` and `contentClasses` to apply predefined CSS classes.
You can use `disableStyles={true}` to disable any built-in styling.
### Examples
#### changing the bar background to red
#### Changing the bar background to red
```js
<CookieConsent style={{ background: "red" }}></CookieConsent>
```
#### Changing the button font-weight to bold
```js
<CookieConsent buttonStyle={{ fontWeight: "bold" }}></CookieConsent>
```
#### Using predefined CSS classes
You can pass predefined CSS classes to the components using the `containerClasses`, `buttonClasses` and `contentClasses` props. The example below uses bootstrap classes:
```js
<CookieConsent
style={{ background: "red" }}
disableStyles={true}
location={OPTIONS.BOTTOM}
buttonClasses="btn btn-primary"
containerClasses="alert alert-warning col-lg-12"
contentClasses="text-capitalize"
>
This website uses cookies to enhance the user experience.{" "}
<span style={{ fontSize: "10px" }}>This bit of text is smaller :O</span>
</CookieConsent>
```
#### changing the button font-weight to bold
Which results in:
![bootstrap styling](https://github.com/Mastermindzh/react-cookie-consent/blob/master/images/css_classes.png?raw=true)
#### Accept on scroll
You can make the cookiebar disappear after scrolling a certain percentage using acceptOnScroll and acceptOnScrollPercentage.
It is legal in some use-cases, [Italy](https://www.garanteprivacy.it/web/guest/home/docweb/-/docweb-display/docweb/9679893) being one of them. Consult your legislation on whether this is allowed.
```js
<CookieConsent
buttonStyle={{ fontWeight: "bold" }}
acceptOnScroll={true}
acceptOnScrollPercentage={50}
onAccept={(byScroll) => {
alert(`consent given. \n\n By scrolling? ${byScroll}`);
}}
>
Hello scroller :)
</CookieConsent>
```
#### rainbows!
#### Flipping the buttons
If you enable the decline button you can pass along the "flipButtons" property to turn the buttons around:
```js
<CookieConsent enableDeclineButton flipButtons>
Flipped buttons
</CookieConsent>
```
Which results in:
![flipped buttons](./images/flipped.png)
#### Extra cookie options
You can add more cookie options using the extraCookieOptions parameter like so:
```js
<CookieConsent extraCookieOptions={{ domain: "myexample.com" }}>cookie bar</CookieConsent>
```
#### Rainbows!
![rainbows!](https://github.com/Mastermindzh/react-cookie-consent/blob/master/images/rainbow.png?raw=true)
@@ -115,28 +303,57 @@ If you're crazy enough you can even make a rainbow colored bar:
```js
<CookieConsent
buttonText="OMG DOUBLE RAINBOW"
cookieName="myAwesomeCookieName2"
style={{ background: "linear-gradient(to right, orange , yellow, green, cyan, blue, violet)", textShadow: "2px 2px black" }}
buttonStyle={{background: "linear-gradient(to left, orange , yellow, green, cyan, blue, violet)", color:"white", fontWeight: "bolder", textShadow: "2px 2px black"}}
buttonText="OMG DOUBLE RAINBOW"
cookieName="myAwesomeCookieName2"
style={{
background: "linear-gradient(to right, orange , yellow, green, cyan, blue, violet)",
textShadow: "2px 2px black",
}}
buttonStyle={{
background: "linear-gradient(to left, orange , yellow, green, cyan, blue, violet)",
color: "white",
fontWeight: "bolder",
textShadow: "2px 2px black",
}}
>
This website uses cookies to enhance the user experience.{" "}
<span style={{ fontSize: "10px" }}>
This bit of text is smaller :O
</span>
This website uses cookies to enhance the user experience.{" "}
<span style={{ fontSize: "10px" }}>This bit of text is smaller :O</span>
</CookieConsent>
```
## Debugging it
#### Overlay
Because the cookie consent bar will be hidden once accepted, you will have to remove the cookie if you want to evaluate changes:
![overlay](https://github.com/Mastermindzh/react-cookie-consent/blob/master/images/overlay.png?raw=true)
You can also generate a page-obfuscating overlay that will prevent actions other than interacting with the cookie consent button(s).
```js
import CookieConsent, { Cookies } from "react-cookie-consent";
{Cookies.remove("myAwesomeCookieName2")}
<CookieConsent
cookieName="myAwesomeCookieName2"
>
<CookieConsent location="bottom" cookieName="myAwesomeCookieName3" expires={999} overlay>
This website uses cookies to enhance the user experience.
</CookieConsent>
```
<!-- links -->
[style]: https://github.com/Mastermindzh/react-cookie-consent/blob/master/src/index.js#L18-L29
[buttonstyle]: https://github.com/Mastermindzh/react-cookie-consent/blob/master/src/index.js#L30-L40
[declinebuttonstyle]: https://github.com/Mastermindzh/react-cookie-consent/blob/master/src/index.js#L41-L51
[contentstyle]: https://github.com/Mastermindzh/react-cookie-consent/blob/master/src/index.js#L52-L55
[overlaystyle]: https://github.com/Mastermindzh/react-cookie-consent/blob/master/src/index.js#L62-L69
## Contributor information
When making a PR please think about the following things:
- Update the ChangeLog (or include what you did in the PR and I'll add it, up to you)
- No need to build or update the package.json. I will do both on release.
- Please don't change code convention / style
## Projects using react-cookie-consent
The list below features the projects which use react-cookie-consent (that I know off):
- [bs-react-cookie-consent](https://github.com/ctbucha/bs-react-cookie-consent)
- [comicrelief's storybook](https://github.com/comicrelief/storybook)
- [inici Gatsby theme](https://github.com/kuworking/gatsby-theme-kuworking-core)
- [Scrivito Example App](https://github.com/Scrivito/scrivito_example_app_js)

74
build/index.d.ts vendored Normal file
View File

@@ -0,0 +1,74 @@
import * as React from "react";
import Cookies from "js-cookie";
export interface CookieConsentProps {
location?: "top" | "bottom" | "none";
sameSite?: "strict" | "lax" | "none";
visible?: "hidden" | "show" | "byCookieValue";
cookieSecurity?: boolean;
style?: object;
buttonStyle?: object;
declineButtonStyle?: object;
contentStyle?: object;
children?: React.ReactNode;
disableStyles?: boolean;
hideOnAccept?: boolean;
onAccept?: (acceptedByScrolling?: boolean) => void;
onDecline?: Function;
buttonText?: Function | React.ReactNode;
declineButtonText?: Function | React.ReactNode;
cookieName?: string;
cookieValue?: string | boolean | number;
declineCookieValue?: string | boolean | number;
setDeclineCookie?: boolean;
debug?: boolean;
expires?: number;
containerClasses?: string;
contentClasses?: string;
buttonWrapperClasses?: string;
buttonClasses?: string;
declineButtonClasses?: string;
buttonId?: string;
declineButtonId?: string;
extraCookieOptions?: object;
disableButtonStyles?: boolean;
enableDeclineButton?: boolean;
flipButtons?: boolean;
ButtonComponent?: React.ElementType;
overlay?: boolean;
overlayClasses?: string;
overlayStyle?: object;
onOverlayClick?: () => void;
acceptOnOverlayClick?: boolean;
ariaAcceptLabel?: string;
ariaDeclineLabel?: string;
acceptOnScroll?: boolean;
acceptOnScrollPercentage?: number;
customContentAttributes?: object;
customContainerAttributes?: object;
}
export default class CookieConsent extends React.Component<CookieConsentProps, {}> {}
/**
* Returns the value of the consent cookie
* Retrieves the regular value first and if not found the legacy one according
* to: https://web.dev/samesite-cookie-recipes/#handling-incompatible-clients
* @param {*} name optional name of the cookie
*/
export function getCookieConsentValue(name?: string): string;
/**
* Reset the consent cookie
* Remove the cookie on browser in order to allow user to change their consent
* @param {*} name optional name of the cookie
*/
export function resetCookieConsentValue(name?: string);
/**
* Get the legacy cookie name by the regular cookie name
* @param {string} name of cookie to get
*/
export function getLegacyCookieName(name: string);
export { Cookies };

File diff suppressed because it is too large Load Diff

1
example Submodule

Submodule example added at bff8dd76c5

21
example/.gitignore vendored
View File

@@ -1,21 +0,0 @@
# See https://help.github.com/ignore-files/ for more about ignoring files.
# dependencies
/node_modules
# testing
/coverage
# production
/build
# misc
.DS_Store
.env.local
.env.development.local
.env.test.local
.env.production.local
npm-debug.log*
yarn-debug.log*
yarn-error.log*

File diff suppressed because it is too large Load Diff

View File

@@ -1,17 +0,0 @@
{
"name": "example",
"version": "0.1.0",
"private": true,
"dependencies": {
"react": "^16.2.0",
"react-cookie-consent": "^1.0.5",
"react-dom": "^16.2.0",
"react-scripts": "1.1.0"
},
"scripts": {
"start": "react-scripts start",
"build": "react-scripts build",
"test": "react-scripts test --env=jsdom",
"eject": "react-scripts eject"
}
}

Binary file not shown.

Before

Width:  |  Height:  |  Size: 3.8 KiB

After

Width:  |  Height:  |  Size: 3.8 KiB

View File

@@ -1,40 +0,0 @@
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">
<meta name="theme-color" content="#000000">
<!--
manifest.json provides metadata used when your web app is added to the
homescreen on Android. See https://developers.google.com/web/fundamentals/engage-and-retain/web-app-manifest/
-->
<link rel="manifest" href="%PUBLIC_URL%/manifest.json">
<link rel="shortcut icon" href="%PUBLIC_URL%/favicon.ico">
<!--
Notice the use of %PUBLIC_URL% in the tags above.
It will be replaced with the URL of the `public` folder during the build.
Only files inside the `public` folder can be referenced from the HTML.
Unlike "/favicon.ico" or "favicon.ico", "%PUBLIC_URL%/favicon.ico" will
work correctly both with client-side routing and a non-root public URL.
Learn how to configure a non-root public URL by running `npm run build`.
-->
<title>React App</title>
</head>
<body>
<noscript>
You need to enable JavaScript to run this app.
</noscript>
<div id="root"></div>
<!--
This HTML file is a template.
If you open it directly in the browser, you will see an empty page.
You can add webfonts, meta tags, or analytics to this file.
The build step will place the bundled scripts into the <body> tag.
To begin the development, run `npm start` or `yarn start`.
To create a production bundle, use `npm run build` or `yarn build`.
-->
</body>
</html>

View File

@@ -1,15 +0,0 @@
{
"short_name": "React App",
"name": "Create React App Sample",
"icons": [
{
"src": "favicon.ico",
"sizes": "64x64 32x32 24x24 16x16",
"type": "image/x-icon"
}
],
"start_url": "./index.html",
"display": "standalone",
"theme_color": "#000000",
"background_color": "#ffffff"
}

View File

@@ -1,28 +0,0 @@
.App {
text-align: center;
}
.App-logo {
animation: App-logo-spin infinite 20s linear;
height: 80px;
}
.App-header {
background-color: #222;
height: 150px;
padding: 20px;
color: white;
}
.App-title {
font-size: 1.5em;
}
.App-intro {
font-size: large;
}
@keyframes App-logo-spin {
from { transform: rotate(0deg); }
to { transform: rotate(360deg); }
}

View File

@@ -1,34 +0,0 @@
import React, { Component } from 'react';
import logo from './logo.svg';
import './App.css';
import CookieConsent, { Cookies } from "react-cookie-consent";
class App extends Component {
render() {
Cookies.set("test", "nice")
return (
<div className="App">
<header className="App-header">
<img src={logo} className="App-logo" alt="logo" />
<h1 className="App-title">Welcome to React</h1>
</header>
<p className="App-intro">
To get started, edit <code>src/App.js</code> and save to reload.
</p>
<CookieConsent
onAccept={() => {alert("yay!")}}
>
This website uses cookies to enhance the user experience.{" "}
<span style={{ fontSize: "10px" }}>
This bit of text is smaller :O
</span>
</CookieConsent>
</div>
);
}
}
export default App;

View File

@@ -1,9 +0,0 @@
import React from 'react';
import ReactDOM from 'react-dom';
import App from './App';
it('renders without crashing', () => {
const div = document.createElement('div');
ReactDOM.render(<App />, div);
ReactDOM.unmountComponentAtNode(div);
});

View File

@@ -1,5 +0,0 @@
body {
margin: 0;
padding: 0;
font-family: sans-serif;
}

View File

@@ -1,8 +0,0 @@
import React from 'react';
import ReactDOM from 'react-dom';
import './index.css';
import App from './App';
import registerServiceWorker from './registerServiceWorker';
ReactDOM.render(<App />, document.getElementById('root'));
registerServiceWorker();

View File

@@ -1,7 +0,0 @@
<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 841.9 595.3">
<g fill="#61DAFB">
<path d="M666.3 296.5c0-32.5-40.7-63.3-103.1-82.4 14.4-63.6 8-114.2-20.2-130.4-6.5-3.8-14.1-5.6-22.4-5.6v22.3c4.6 0 8.3.9 11.4 2.6 13.6 7.8 19.5 37.5 14.9 75.7-1.1 9.4-2.9 19.3-5.1 29.4-19.6-4.8-41-8.5-63.5-10.9-13.5-18.5-27.5-35.3-41.6-50 32.6-30.3 63.2-46.9 84-46.9V78c-27.5 0-63.5 19.6-99.9 53.6-36.4-33.8-72.4-53.2-99.9-53.2v22.3c20.7 0 51.4 16.5 84 46.6-14 14.7-28 31.4-41.3 49.9-22.6 2.4-44 6.1-63.6 11-2.3-10-4-19.7-5.2-29-4.7-38.2 1.1-67.9 14.6-75.8 3-1.8 6.9-2.6 11.5-2.6V78.5c-8.4 0-16 1.8-22.6 5.6-28.1 16.2-34.4 66.7-19.9 130.1-62.2 19.2-102.7 49.9-102.7 82.3 0 32.5 40.7 63.3 103.1 82.4-14.4 63.6-8 114.2 20.2 130.4 6.5 3.8 14.1 5.6 22.5 5.6 27.5 0 63.5-19.6 99.9-53.6 36.4 33.8 72.4 53.2 99.9 53.2 8.4 0 16-1.8 22.6-5.6 28.1-16.2 34.4-66.7 19.9-130.1 62-19.1 102.5-49.9 102.5-82.3zm-130.2-66.7c-3.7 12.9-8.3 26.2-13.5 39.5-4.1-8-8.4-16-13.1-24-4.6-8-9.5-15.8-14.4-23.4 14.2 2.1 27.9 4.7 41 7.9zm-45.8 106.5c-7.8 13.5-15.8 26.3-24.1 38.2-14.9 1.3-30 2-45.2 2-15.1 0-30.2-.7-45-1.9-8.3-11.9-16.4-24.6-24.2-38-7.6-13.1-14.5-26.4-20.8-39.8 6.2-13.4 13.2-26.8 20.7-39.9 7.8-13.5 15.8-26.3 24.1-38.2 14.9-1.3 30-2 45.2-2 15.1 0 30.2.7 45 1.9 8.3 11.9 16.4 24.6 24.2 38 7.6 13.1 14.5 26.4 20.8 39.8-6.3 13.4-13.2 26.8-20.7 39.9zm32.3-13c5.4 13.4 10 26.8 13.8 39.8-13.1 3.2-26.9 5.9-41.2 8 4.9-7.7 9.8-15.6 14.4-23.7 4.6-8 8.9-16.1 13-24.1zM421.2 430c-9.3-9.6-18.6-20.3-27.8-32 9 .4 18.2.7 27.5.7 9.4 0 18.7-.2 27.8-.7-9 11.7-18.3 22.4-27.5 32zm-74.4-58.9c-14.2-2.1-27.9-4.7-41-7.9 3.7-12.9 8.3-26.2 13.5-39.5 4.1 8 8.4 16 13.1 24 4.7 8 9.5 15.8 14.4 23.4zM420.7 163c9.3 9.6 18.6 20.3 27.8 32-9-.4-18.2-.7-27.5-.7-9.4 0-18.7.2-27.8.7 9-11.7 18.3-22.4 27.5-32zm-74 58.9c-4.9 7.7-9.8 15.6-14.4 23.7-4.6 8-8.9 16-13 24-5.4-13.4-10-26.8-13.8-39.8 13.1-3.1 26.9-5.8 41.2-7.9zm-90.5 125.2c-35.4-15.1-58.3-34.9-58.3-50.6 0-15.7 22.9-35.6 58.3-50.6 8.6-3.7 18-7 27.7-10.1 5.7 19.6 13.2 40 22.5 60.9-9.2 20.8-16.6 41.1-22.2 60.6-9.9-3.1-19.3-6.5-28-10.2zM310 490c-13.6-7.8-19.5-37.5-14.9-75.7 1.1-9.4 2.9-19.3 5.1-29.4 19.6 4.8 41 8.5 63.5 10.9 13.5 18.5 27.5 35.3 41.6 50-32.6 30.3-63.2 46.9-84 46.9-4.5-.1-8.3-1-11.3-2.7zm237.2-76.2c4.7 38.2-1.1 67.9-14.6 75.8-3 1.8-6.9 2.6-11.5 2.6-20.7 0-51.4-16.5-84-46.6 14-14.7 28-31.4 41.3-49.9 22.6-2.4 44-6.1 63.6-11 2.3 10.1 4.1 19.8 5.2 29.1zm38.5-66.7c-8.6 3.7-18 7-27.7 10.1-5.7-19.6-13.2-40-22.5-60.9 9.2-20.8 16.6-41.1 22.2-60.6 9.9 3.1 19.3 6.5 28.1 10.2 35.4 15.1 58.3 34.9 58.3 50.6-.1 15.7-23 35.6-58.4 50.6zM320.8 78.4z"/>
<circle cx="420.9" cy="296.5" r="45.7"/>
<path d="M520.5 78.1z"/>
</g>
</svg>

Before

Width:  |  Height:  |  Size: 2.6 KiB

After

Width:  |  Height:  |  Size: 2.6 KiB

View File

@@ -1,117 +0,0 @@
// In production, we register a service worker to serve assets from local cache.
// This lets the app load faster on subsequent visits in production, and gives
// it offline capabilities. However, it also means that developers (and users)
// will only see deployed updates on the "N+1" visit to a page, since previously
// cached resources are updated in the background.
// To learn more about the benefits of this model, read https://goo.gl/KwvDNy.
// This link also includes instructions on opting out of this behavior.
const isLocalhost = Boolean(
window.location.hostname === 'localhost' ||
// [::1] is the IPv6 localhost address.
window.location.hostname === '[::1]' ||
// 127.0.0.1/8 is considered localhost for IPv4.
window.location.hostname.match(
/^127(?:\.(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)){3}$/
)
);
export default function register() {
if (process.env.NODE_ENV === 'production' && 'serviceWorker' in navigator) {
// The URL constructor is available in all browsers that support SW.
const publicUrl = new URL(process.env.PUBLIC_URL, window.location);
if (publicUrl.origin !== window.location.origin) {
// Our service worker won't work if PUBLIC_URL is on a different origin
// from what our page is served on. This might happen if a CDN is used to
// serve assets; see https://github.com/facebookincubator/create-react-app/issues/2374
return;
}
window.addEventListener('load', () => {
const swUrl = `${process.env.PUBLIC_URL}/service-worker.js`;
if (isLocalhost) {
// This is running on localhost. Lets check if a service worker still exists or not.
checkValidServiceWorker(swUrl);
// Add some additional logging to localhost, pointing developers to the
// service worker/PWA documentation.
navigator.serviceWorker.ready.then(() => {
console.log(
'This web app is being served cache-first by a service ' +
'worker. To learn more, visit https://goo.gl/SC7cgQ'
);
});
} else {
// Is not local host. Just register service worker
registerValidSW(swUrl);
}
});
}
}
function registerValidSW(swUrl) {
navigator.serviceWorker
.register(swUrl)
.then(registration => {
registration.onupdatefound = () => {
const installingWorker = registration.installing;
installingWorker.onstatechange = () => {
if (installingWorker.state === 'installed') {
if (navigator.serviceWorker.controller) {
// At this point, the old content will have been purged and
// the fresh content will have been added to the cache.
// It's the perfect time to display a "New content is
// available; please refresh." message in your web app.
console.log('New content is available; please refresh.');
} else {
// At this point, everything has been precached.
// It's the perfect time to display a
// "Content is cached for offline use." message.
console.log('Content is cached for offline use.');
}
}
};
};
})
.catch(error => {
console.error('Error during service worker registration:', error);
});
}
function checkValidServiceWorker(swUrl) {
// Check if the service worker can be found. If it can't reload the page.
fetch(swUrl)
.then(response => {
// Ensure service worker exists, and that we really are getting a JS file.
if (
response.status === 404 ||
response.headers.get('content-type').indexOf('javascript') === -1
) {
// No service worker found. Probably a different app. Reload the page.
navigator.serviceWorker.ready.then(registration => {
registration.unregister().then(() => {
window.location.reload();
});
});
} else {
// Service worker found. Proceed as normal.
registerValidSW(swUrl);
}
})
.catch(() => {
console.log(
'No internet connection found. App is running in offline mode.'
);
});
}
export function unregister() {
if ('serviceWorker' in navigator) {
navigator.serviceWorker.ready.then(registration => {
registration.unregister();
});
}
}

File diff suppressed because it is too large Load Diff

Binary file not shown.

Before

Width:  |  Height:  |  Size: 15 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 14 KiB

BIN
images/css_classes.png Normal file

Binary file not shown.

After

Width:  |  Height:  |  Size: 28 KiB

BIN
images/flipped.png Normal file

Binary file not shown.

After

Width:  |  Height:  |  Size: 3.3 KiB

BIN
images/overlay.png Normal file

Binary file not shown.

After

Width:  |  Height:  |  Size: 25 KiB

12921
package-lock.json generated Normal file

File diff suppressed because it is too large Load Diff

View File

@@ -4,15 +4,28 @@
"name": "Rick van Lieshout",
"email": "info@rickvanlieshout.com"
},
"version": "1.0.8",
"version": "7.2.0",
"description": "A small, simple and customizable cookie consent bar for use in React applications.",
"main": "build/index.js",
"types": "build/index.d.ts",
"dependencies": {
"js-cookie": "^2.2.0",
"react": "^15.5.4"
"js-cookie": "^2.2.1",
"prop-types": "^15.7.2"
},
"peerDependencies": {
"react": "^16.13.1 || ^17.0.0"
},
"scripts": {
"build": "webpack"
"build": "webpack",
"prettier": "prettier 'src/**/*.{js*,ts*,htm*,md,scss}' --write",
"patch": "npm --no-git-tag-version version patch",
"minor": "npm --no-git-tag-version version minor",
"major": "npm --no-git-tag-version version major",
"preversion": "grep \"\\[$npm_package_version\\]\" CHANGELOG.md > /dev/null || ( echo 'You need to add an entry in CHANGELOG.md for this version.' && false )",
"release": "npm run build && git add -A && git tag $npm_package_version && git commit -m \"release $npm_package_version\" && git push && git push --tags && npm publish",
"release-patch": "npm run patch && npm run release",
"release-minor": "npm run minor && npm run release",
"release-major": "npm run major && npm run release"
},
"repository": {
"type": "git",
@@ -30,14 +43,32 @@
},
"homepage": "https://github.com/Mastermindzh/react-cookie-consent#readme",
"devDependencies": {
"babel-cli": "^6.24.1",
"babel-core": "^6.24.1",
"babel-loader": "^7.0.0",
"babel-plugin-transform-object-rest-spread": "^6.23.0",
"babel-plugin-transform-react-jsx": "^6.24.1",
"babel-preset-env": "^1.5.1",
"babel-preset-es2015": "^6.24.1",
"babel-preset-stage-1": "^6.24.1",
"webpack": "^2.6.1"
"@babel/cli": "^7.12.1",
"@babel/core": "^7.12.3",
"@babel/plugin-proposal-object-rest-spread": "^7.12.1",
"@babel/plugin-transform-object-assign": "^7.12.1",
"@babel/plugin-transform-react-jsx": "^7.12.1",
"@babel/preset-env": "^7.12.1",
"@mastermindzh/prettier-config": "^1.0.0",
"@types/js-cookie": "^2.2.6",
"babel-loader": "^8.1.0",
"copy-webpack-plugin": "^6.2.1",
"husky": "^4.3.0",
"lint-staged": "^10.5.1",
"prettier": "^2.1.2",
"react": "^16.13.1",
"webpack": "^5.3.2",
"webpack-cli": "^4.1.0"
},
"prettier": "@mastermindzh/prettier-config",
"husky": {
"hooks": {
"pre-commit": "lint-staged --allow-empty"
}
},
"lint-staged": {
"*.{js*,ts*,htm*,md,scss}": [
"prettier --write"
]
}
}

75
src/index.d.ts vendored Normal file
View File

@@ -0,0 +1,75 @@
import * as React from "react";
import Cookies from "js-cookie";
export interface CookieConsentProps {
location?: "top" | "bottom" | "none";
sameSite?: "strict" | "lax" | "none";
visible?: "hidden" | "show" | "byCookieValue";
cookieSecurity?: boolean;
style?: object;
buttonStyle?: object;
declineButtonStyle?: object;
contentStyle?: object;
children?: React.ReactNode;
disableStyles?: boolean;
hideOnAccept?: boolean;
hideOnDecline?: boolean;
onAccept?: (acceptedByScrolling?: boolean) => void;
onDecline?: Function;
buttonText?: Function | React.ReactNode;
declineButtonText?: Function | React.ReactNode;
cookieName?: string;
cookieValue?: string | boolean | number;
declineCookieValue?: string | boolean | number;
setDeclineCookie?: boolean;
debug?: boolean;
expires?: number;
containerClasses?: string;
contentClasses?: string;
buttonWrapperClasses?: string;
buttonClasses?: string;
declineButtonClasses?: string;
buttonId?: string;
declineButtonId?: string;
extraCookieOptions?: object;
disableButtonStyles?: boolean;
enableDeclineButton?: boolean;
flipButtons?: boolean;
ButtonComponent?: React.ElementType;
overlay?: boolean;
overlayClasses?: string;
overlayStyle?: object;
onOverlayClick?: () => void;
acceptOnOverlayClick?: boolean;
ariaAcceptLabel?: string;
ariaDeclineLabel?: string;
acceptOnScroll?: boolean;
acceptOnScrollPercentage?: number;
customContentAttributes?: object;
customContainerAttributes?: object;
}
export default class CookieConsent extends React.Component<CookieConsentProps, {}> {}
/**
* Returns the value of the consent cookie
* Retrieves the regular value first and if not found the legacy one according
* to: https://web.dev/samesite-cookie-recipes/#handling-incompatible-clients
* @param {*} name optional name of the cookie
*/
export function getCookieConsentValue(name?: string): string;
/**
* Reset the consent cookie
* Remove the cookie on browser in order to allow user to change their consent
* @param {*} name optional name of the cookie
*/
export function resetCookieConsentValue(name?: string);
/**
* Get the legacy cookie name by the regular cookie name
* @param {string} name of cookie to get
*/
export function getLegacyCookieName(name: string);
export { Cookies };

View File

@@ -4,88 +4,326 @@ import Cookies from "js-cookie";
export const OPTIONS = {
TOP: "top",
BOTTOM: "bottom"
BOTTOM: "bottom",
NONE: "none",
};
export const SAME_SITE_OPTIONS = {
STRICT: "strict",
LAX: "lax",
NONE: "none",
};
export const VISIBLE_OPTIONS = {
HIDDEN: "hidden",
SHOW: "show",
BY_COOKIE_VALUE: "byCookieValue",
};
/**
* Returns the value of the consent cookie
* Retrieves the regular value first and if not found the legacy one according
* to: https://web.dev/samesite-cookie-recipes/#handling-incompatible-clients
* @param {*} name optional name of the cookie
*/
export const getCookieConsentValue = (name = defaultCookieConsentName) => {
let cookieValue = Cookies.get(name);
// if the cookieValue is undefined check for the legacy cookie
if (cookieValue === undefined) {
cookieValue = Cookies.get(getLegacyCookieName(name));
}
return cookieValue;
};
/**
* Reset the consent cookie
* Remove the cookie on browser in order to allow user to change their consent
* @param {*} name optional name of the cookie
*/
export const resetCookieConsentValue = (name = defaultCookieConsentName) => {
Cookies.remove(name);
};
/**
* Get the legacy cookie name by the regular cookie name
* @param {string} name of cookie to get
*/
const getLegacyCookieName = (name) => {
return `${name}-legacy`;
};
/**
* Default name of the cookie which is set by CookieConsent
*/
const defaultCookieConsentName = "CookieConsent";
/**
* A function to wrap elements with a "wrapper" on a condition
* @param {object} wrappingOptions
* condition == boolean condition, when to wrap
* wrapper == style to wrap. e.g <div>{children}</div>
* children == react passes whatever is between tags as children. Don't supply this yourself.
*/
const ConditionalWrapper = ({ condition, wrapper, children }) => {
return condition ? wrapper(children) : children;
};
class CookieConsent extends Component {
constructor(props) {
super(props);
this.accept.bind(this);
this.state = {
visible: true,
visible: false,
style: {
position: "fixed",
width: "100%",
padding: "15px",
alignItems: "baseline",
background: "#353535",
color: "white",
display: "flex",
flexWrap: "wrap",
justifyContent: "space-between",
left: "0",
position: "fixed",
width: "100%",
zIndex: "999",
lineHeight: "30px",
textAlign: "left"
},
buttonStyle: {
position: "absolute",
right: "50px",
border: "0",
background: "#ffd42d",
boxShadow: "none",
border: "0",
borderRadius: "0px",
padding: "5px",
color: "black"
}
boxShadow: "none",
color: "black",
cursor: "pointer",
flex: "0 0 auto",
padding: "5px 10px",
margin: "15px",
},
declineButtonStyle: {
background: "#c12a2a",
border: "0",
borderRadius: "0px",
boxShadow: "none",
color: "#e5e5e5",
cursor: "pointer",
flex: "0 0 auto",
padding: "5px 10px",
margin: "15px",
},
contentStyle: {
flex: "1 0 300px",
margin: "15px",
},
overlayStyle: {
position: "fixed",
left: 0,
top: 0,
width: "100%",
height: "100%",
zIndex: "999",
backgroundColor: "rgba(0,0,0,0.3)",
},
};
}
componentWillMount(){
const { cookieName } = this.props;
componentDidMount() {
const { debug } = this.props;
if (Cookies.get(cookieName) != undefined ) {
// if cookie undefined or debug
if (this.getCookieValue() === undefined || debug) {
this.setState({ visible: true });
// if acceptOnScroll is set to true and (cookie is undefined or debug is set to true), add a listener.
if (this.props.acceptOnScroll) {
window.addEventListener("scroll", this.handleScroll, { passive: true });
}
}
}
componentWillUnmount() {
// remove listener if still set
this.removeScrollListener();
}
/**
* Set a persistent accept cookie
*/
accept(acceptedByScrolling = false) {
const { cookieName, cookieValue, hideOnAccept, onAccept } = this.props;
this.setCookie(cookieName, cookieValue);
onAccept(acceptedByScrolling ?? false);
if (hideOnAccept) {
this.setState({ visible: false });
this.removeScrollListener();
}
}
/**
* Handle a click on the overlay
*/
overlayClick() {
const { acceptOnOverlayClick, onOverlayClick } = this.props;
if (acceptOnOverlayClick) {
this.accept();
}
onOverlayClick();
}
/**
* Set a persistent decline cookie
*/
decline() {
const { cookieName, declineCookieValue, hideOnDecline, onDecline, setDeclineCookie } =
this.props;
if (setDeclineCookie) {
this.setCookie(cookieName, declineCookieValue);
}
onDecline();
if (hideOnDecline) {
this.setState({ visible: false });
}
}
/**
* Set a persistent cookie
* Function to set the consent cookie based on the provided variables
* Sets two cookies to handle incompatible browsers, more details:
* https://web.dev/samesite-cookie-recipes/#handling-incompatible-clients
*/
accept() {
const { cookieName } = this.props;
setCookie(cookieName, cookieValue) {
const { extraCookieOptions, expires, sameSite } = this.props;
let { cookieSecurity } = this.props;
Cookies.set(cookieName, true);
this.setState({ visible: false });
if (cookieSecurity === undefined) {
cookieSecurity = location ? location.protocol === "https:" : true;
}
let cookieOptions = { expires, ...extraCookieOptions, sameSite, secure: cookieSecurity };
// Fallback for older browsers where can not set SameSite=None, SEE: https://web.dev/samesite-cookie-recipes/#handling-incompatible-clients
if (sameSite === SAME_SITE_OPTIONS.NONE) {
Cookies.set(getLegacyCookieName(cookieName), cookieValue, cookieOptions);
}
// set the regular cookie
Cookies.set(cookieName, cookieValue, cookieOptions);
}
render() {
/**
* Returns the value of the consent cookie
* Retrieves the regular value first and if not found the legacy one according
* to: https://web.dev/samesite-cookie-recipes/#handling-incompatible-clients
*/
getCookieValue() {
const { cookieName } = this.props;
return getCookieConsentValue(cookieName);
}
/**
* checks whether scroll has exceeded set amount and fire accept if so.
*/
handleScroll = () => {
const { acceptOnScrollPercentage } = this.props;
// (top / height) - height * 100
let rootNode = document.documentElement,
body = document.body,
top = "scrollTop",
height = "scrollHeight";
let percentage =
((rootNode[top] || body[top]) /
((rootNode[height] || body[height]) - rootNode.clientHeight)) *
100;
if (percentage > acceptOnScrollPercentage) {
this.accept(true);
}
};
removeScrollListener = () => {
const { acceptOnScroll } = this.props;
if (acceptOnScroll) {
window.removeEventListener("scroll", this.handleScroll);
}
};
render() {
// If the bar shouldn't be visible don't render anything.
if (!this.state.visible) {
return null;
switch (this.props.visible) {
case VISIBLE_OPTIONS.HIDDEN:
return null;
case VISIBLE_OPTIONS.BY_COOKIE_VALUE:
if (!this.state.visible) {
return null;
}
break;
default:
break;
}
const {
location,
style,
buttonStyle,
declineButtonStyle,
contentStyle,
disableStyles,
onAccept,
buttonText
buttonText,
declineButtonText,
containerClasses,
contentClasses,
buttonClasses,
buttonWrapperClasses,
declineButtonClasses,
buttonId,
declineButtonId,
disableButtonStyles,
enableDeclineButton,
flipButtons,
ButtonComponent,
overlay,
overlayClasses,
overlayStyle,
ariaAcceptLabel,
ariaDeclineLabel,
customContainerAttributes,
customContentAttributes,
} = this.props;
let myStyle = {},
myButtonStyle = {};
let myStyle = {};
let myButtonStyle = {};
let myDeclineButtonStyle = {};
let myContentStyle = {};
let myOverlayStyle = {};
if (disableStyles) {
// if styles are disabled use the provided styles (or non)
// if styles are disabled use the provided styles (or none)
myStyle = Object.assign({}, style);
myButtonStyle = Object.assign({}, buttonStyle);
myDeclineButtonStyle = Object.assign({}, declineButtonStyle);
myContentStyle = Object.assign({}, contentStyle);
myOverlayStyle = Object.assign({}, overlayStyle);
} else {
// if styles aren't disabled merge them with the styles that are provided (or use default styles)
myStyle = Object.assign({}, { ...this.state.style, ...style });
myButtonStyle = Object.assign(
{},
{ ...this.state.buttonStyle, ...buttonStyle }
);
myContentStyle = Object.assign({}, { ...this.state.contentStyle, ...contentStyle });
myOverlayStyle = Object.assign({}, { ...this.state.overlayStyle, ...overlayStyle });
// switch to disable JUST the button styles
if (disableButtonStyles) {
myButtonStyle = Object.assign({}, buttonStyle);
myDeclineButtonStyle = Object.assign({}, declineButtonStyle);
} else {
myButtonStyle = Object.assign({}, { ...this.state.buttonStyle, ...buttonStyle });
myDeclineButtonStyle = Object.assign(
{},
{ ...this.state.declineButtonStyle, ...declineButtonStyle }
);
}
}
// syntactic sugar to enable user to easily select top / bottom
@@ -99,40 +337,163 @@ class CookieConsent extends Component {
break;
}
return (
<div className="cookieConsent" style={myStyle}>
{this.props.children}
<button
style={myButtonStyle}
const buttonsToRender = [];
// add decline button
enableDeclineButton &&
buttonsToRender.push(
<ButtonComponent
key="declineButton"
style={myDeclineButtonStyle}
className={declineButtonClasses}
id={declineButtonId}
aria-label={ariaDeclineLabel}
onClick={() => {
this.accept();
onAccept();
this.decline();
}}
>
{buttonText}
</button>
</div>
{declineButtonText}
</ButtonComponent>
);
// add accept button
buttonsToRender.push(
<ButtonComponent
key="acceptButton"
style={myButtonStyle}
className={buttonClasses}
id={buttonId}
aria-label={ariaAcceptLabel}
onClick={() => {
this.accept();
}}
>
{buttonText}
</ButtonComponent>
);
if (flipButtons) {
buttonsToRender.reverse();
}
return (
<ConditionalWrapper
condition={overlay}
wrapper={(children) => (
<div
style={myOverlayStyle}
className={overlayClasses}
onClick={() => {
this.overlayClick();
}}
>
{children}
</div>
)}
>
<div className={`${containerClasses}`} style={myStyle} {...customContainerAttributes}>
<div style={myContentStyle} className={contentClasses} {...customContentAttributes}>
{this.props.children}
</div>
<div className={`${buttonWrapperClasses}`}>
{buttonsToRender.map((button) => {
return button;
})}
</div>
</div>
</ConditionalWrapper>
);
}
}
CookieConsent.propTypes = {
location: PropTypes.oneOf(["top", "bottom"]),
location: PropTypes.oneOf(Object.keys(OPTIONS).map((key) => OPTIONS[key])),
visible: PropTypes.oneOf(Object.keys(VISIBLE_OPTIONS).map((key) => VISIBLE_OPTIONS[key])),
sameSite: PropTypes.oneOf(Object.keys(SAME_SITE_OPTIONS).map((key) => SAME_SITE_OPTIONS[key])),
style: PropTypes.object,
buttonStyle: PropTypes.object,
declineButtonStyle: PropTypes.object,
contentStyle: PropTypes.object,
children: PropTypes.any, // eslint-disable-line react/forbid-prop-types
disableStyles: PropTypes.bool,
hideOnAccept: PropTypes.bool,
hideOnDecline: PropTypes.bool,
onAccept: PropTypes.func,
buttonText: PropTypes.oneOfType([PropTypes.string,PropTypes.func,PropTypes.element]),
cookieName: PropTypes.string
onDecline: PropTypes.func,
buttonText: PropTypes.oneOfType([PropTypes.string, PropTypes.func, PropTypes.element]),
declineButtonText: PropTypes.oneOfType([PropTypes.string, PropTypes.func, PropTypes.element]),
cookieName: PropTypes.string,
cookieValue: PropTypes.oneOfType([PropTypes.string, PropTypes.bool, PropTypes.number]),
declineCookieValue: PropTypes.oneOfType([PropTypes.string, PropTypes.bool, PropTypes.number]),
setDeclineCookie: PropTypes.bool,
debug: PropTypes.bool,
expires: PropTypes.number,
containerClasses: PropTypes.string,
contentClasses: PropTypes.string,
buttonClasses: PropTypes.string,
buttonWrapperClasses: PropTypes.string,
declineButtonClasses: PropTypes.string,
buttonId: PropTypes.string,
declineButtonId: PropTypes.string,
extraCookieOptions: PropTypes.object,
disableButtonStyles: PropTypes.bool,
enableDeclineButton: PropTypes.bool,
flipButtons: PropTypes.bool,
ButtonComponent: PropTypes.elementType,
cookieSecurity: PropTypes.bool,
overlay: PropTypes.bool,
overlayClasses: PropTypes.string,
overlayStyle: PropTypes.object,
onOverlayClick: PropTypes.func,
acceptOnOverlayClick: PropTypes.bool,
ariaAcceptLabel: PropTypes.string,
ariaDeclineLabel: PropTypes.string,
acceptOnScroll: PropTypes.bool,
acceptOnScrollPercentage: PropTypes.number,
customContentAttributes: PropTypes.object,
customContainerAttributes: PropTypes.object,
};
CookieConsent.defaultProps = {
disableStyles: false,
hideOnAccept: true,
hideOnDecline: true,
location: OPTIONS.BOTTOM,
visible: VISIBLE_OPTIONS.BY_COOKIE_VALUE,
onAccept: () => {},
cookieName: "CookieConsent",
buttonText: "I understand"
onDecline: () => {},
cookieName: defaultCookieConsentName,
cookieValue: true,
declineCookieValue: false,
setDeclineCookie: true,
buttonText: "I understand",
declineButtonText: "I decline",
debug: false,
expires: 365,
containerClasses: "CookieConsent",
contentClasses: "",
buttonClasses: "",
buttonWrapperClasses: "",
declineButtonClasses: "",
buttonId: "rcc-confirm-button",
declineButtonId: "rcc-decline-button",
extraCookieOptions: {},
disableButtonStyles: false,
enableDeclineButton: false,
flipButtons: false,
sameSite: SAME_SITE_OPTIONS.LAX,
ButtonComponent: ({ children, ...props }) => <button {...props}>{children}</button>,
overlay: false,
overlayClasses: "",
onOverlayClick: () => {},
acceptOnOverlayClick: false,
ariaAcceptLabel: "Accept cookies",
ariaDeclineLabel: "Decline cookies",
acceptOnScroll: false,
acceptOnScrollPercentage: 25,
customContentAttributes: {},
customContainerAttributes: {},
};
export default CookieConsent;
export {Cookies};
export { Cookies };

17
stale.yml Normal file
View File

@@ -0,0 +1,17 @@
# Number of days of inactivity before an issue becomes stale
daysUntilStale: 30
# Number of days of inactivity before a stale issue is closed
daysUntilClose: 2
# Issues with these labels will never be considered stale
exemptLabels:
- good first issue
- security
# Label to use when marking an issue as stale
staleLabel: stale
# Comment to post when marking an issue as stale. Set to `false` to disable
markComment: >
This issue has been automatically marked as stale because it has not had
recent activity. It will be closed if no further activity occurs. Thank you
for your contributions.
# Comment to post when closing a stale issue. Set to `false` to disable
closeComment: false

View File

@@ -1,27 +1,37 @@
var path = require('path');
var path = require("path");
var CopyWebpackPlugin = require("copy-webpack-plugin");
module.exports = {
entry: './src/index.js',
entry: "./src/index.js",
output: {
path: path.resolve(__dirname, 'build'),
filename: 'index.js',
libraryTarget: 'commonjs2' // THIS IS THE MOST IMPORTANT LINE! :mindblow: I wasted more than 2 days until realize this was the line most important in all this guide.
path: path.resolve(__dirname, "build"),
filename: "index.js",
library: {
name: "ReactCookieConsent",
type: "umd",
},
environment: {
arrowFunction: false, // the generated runtime-code should not use arrow functions
},
globalObject: `typeof self !== 'undefined' ? self : this`,
},
module: {
rules: [
{
test: /\.js$/,
include: path.resolve(__dirname, 'src'),
exclude: /(node_modules|bower_components|build)/,
include: path.resolve(__dirname, "src"),
exclude: /(node_modules|build)/,
use: {
loader: 'babel-loader',
loader: "babel-loader",
options: {
presets: ['env']
}
}
}
]
presets: ["@babel/preset-env"],
},
},
},
],
},
externals: {
'react': 'commonjs react' // this line is just to use the React dependency of our parent-testing-project instead of using our own React.
}
react: "commonjs react", // this line is just to use the React dependency of our parent-testing-project instead of using our own React.
},
plugins: [new CopyWebpackPlugin({ patterns: [{ from: "src/index.d.ts", to: "index.d.ts" }] })],
};