storage_cookie.js

/**
 * @module cookie
 * @description A set of utils to get, set and remove cookie data.
 *
 */

/**
 * @function get
 * @description Gets a specific cookie.
 *
 * @since 1.0.0
 *
 * @param {string} name The cookie to get.
 *
 * @return {null|string} Returns a cookie or null if none found for name.
 *
 * @example
 * import { cookieStorage } from "@gravityforms/utils";
 *
 * function Example() {
 *     console.log( cookieStorage.get( 'my-cookie' ) );
 * };
 *
 */
const get = ( name = '' ) => {
	const cookieArr = document.cookie.split( ';' );

	for ( let i = 0; i < cookieArr.length; i++ ) {
		const cookiePair = cookieArr[ i ].split( '=' );

		if ( name === cookiePair[ 0 ].trim() ) {
			return decodeURIComponent( cookiePair[ 1 ] );
		}
	}

	return null;
};

/**
 * @function set
 * @description Creates and sets a cookie.
 *
 * @since 1.0.0
 *
 * @param {string}             name                The cookie name.
 * @param {string}             value               The cookie value.
 * @param {null|number|string} daysToExpire        The number of days until cookie should expire. If not set,
 *                                                 will expire at the end of the user sessions.
 * @param {boolean}            updateExistingValue Whether or not to update the existing cookie value to include the new value.
 *                                                 Can be helpful for keeping cookie count lower for the browser.
 *
 * @return {null|string} Returns a cookie or null if none found for name.
 *
 * @example
 * import { cookieStorage } from "@gravityforms/utils";
 *
 * function Example() {
 *      const cookieValue = uniqueId( 'gform-alert' );
 * 		cookieStorage.set( this.options.cookieName, cookieValue, 1, true );
 * };
 *
 */
const set = ( name = '', value = '', daysToExpire, updateExistingValue ) => {
	let expirationDate = '';
	let cookieValue = value;

	if ( daysToExpire && ! isNaN( Number( daysToExpire ) ) ) {
		const date = new Date();
		date.setTime( date.getTime() + ( Number( daysToExpire ) * 24 * 60 * 60 * 1000 ) );
		expirationDate = ' expires=' + date.toUTCString();
	}

	if ( updateExistingValue ) {
		const currentValue = get( name );
		cookieValue = currentValue !== '' && currentValue !== null ? currentValue + ',' + value : value;
	}

	// Set cookie
	document.cookie = encodeURIComponent( name ) + '=' + encodeURIComponent( cookieValue ) + ';' + expirationDate;
};

/**
 * @function remove
 * @description Removes a cookie.
 *
 * @since 1.0.0
 *
 * @param {string} name The cookie name.
 *
 * @return {void}
 *
 * @example
 * import { cookieStorage } from "@gravityforms/utils";
 *
 * function Example() {
 * 		cookieStorage.remove( 'my-cookie' );
 * };
 *
 */
const remove = ( name ) => {
	set( name, '', -1 );
};

export { get, set, remove };