Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion README.md
Original file line number Diff line number Diff line change
Expand Up @@ -180,6 +180,7 @@ A collection of standalone javascript utility functions.
|--------|-----------|
|[captureMouse](https://github.com/georapbox/js-utils/tree/master/packages/dom/captureMouse)|Captures the mouse position on a specific HTML element.|
|[captureTouch](https://github.com/georapbox/js-utils/tree/master/packages/dom/captureTouch)|Captures the touch position on a specific HTML element.|
|[cookie](https://github.com/georapbox/js-utils/tree/master/packages/dom/cookie)|Create, read and delete cookies.|
|[preloadImages](https://github.com/georapbox/js-utils/tree/master/packages/dom/preloadImages)|Asynchronously load images to browser so that can be cached.|
|[isEventSupported](https://github.com/georapbox/js-utils/tree/master/packages/dom/isEventSupported)|Checks if an event is supported in a browser environment.|
|[scroll](https://github.com/georapbox/js-utils/tree/master/packages/dom/scroll)|Easing based scrolling to a specified y point inside page.|
Expand All @@ -198,7 +199,6 @@ A collection of standalone javascript utility functions.

|Name|Description|
|--------|-----------|
|[cookie](https://github.com/georapbox/js-utils/tree/master/packages/misc/cookie)|Create, read and delete cookies.|
|[hexToRGB](https://github.com/georapbox/js-utils/tree/master/packages/misc/hexToRGB)|Converts a color value (number or hexadecimal string) to RGB(A) format.|
|[parseColor](https://github.com/georapbox/js-utils/tree/master/packages/misc/parseColor)|Converts a color number value to a hexadecimal formatted string, or a hexadecimal formatted string to a number.|

Expand Down
89 changes: 89 additions & 0 deletions packages/dom/cookie/README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,89 @@
<a name="module_cookie"></a>

## cookie
**Category**: DOM

* [cookie](#module_cookie)
* [~set(name, value, [options], [options[&#x27;max-age&#x27;]])](#module_cookie..set) ⇒ <code>void</code>
* [~get([name])](#module_cookie..get) ⇒ <code>String</code>
* [~remove(name)](#module_cookie..remove) ⇒ <code>void</code>

<a name="module_cookie..set"></a>

### cookie~set(name, value, [options], [options[&#x27;max-age&#x27;]]) ⇒ <code>void</code>
Creates a new cookie.

**Kind**: inner method of [<code>cookie</code>](#module_cookie)
**Throws**:

- <code>TypeError</code> If `name` is not string.
- <code>TypeError</code> If `value` is not string.


| Param | Type | Default | Description |
| --- | --- | --- | --- |
| name | <code>String</code> | | The name of the cookie to create. |
| value | <code>String</code> | | The value of the cookie to create. |
| [options] | <code>Object</code> | | |
| [options.path] | <code>String</code> | <code>&quot;/&quot;</code> | The path where cookie is visible. If not specified, defaults to the current path of the current document location. |
| [options.domain] | <code>String</code> | | The domain where cookie is visible. If not specified, this defaults to the host portion of the current document location. If a domain is specified, subdomains are always included. |
| [options.expires] | <code>String</code> | | A date in GMTString format that tells when cookie expires. If not specified it will expire at the end of session. If date is in the past, then the cookie is deleted. Use `Date.prototype.toUTCString()` to properly format it. |
| [options['max-age']] | <code>Number</code> | | Max age in seconds from the time the cookie is set; alternative to `expires`. If not specified it will expire at the end of session. If zero or negative, then the cookie is deleted. |
| [options.secure] | <code>String</code> | | Cookie to only be transmitted over secure protocol as https. |
| [options.samesite] | <code>String</code> | | SameSite prevents the browser from sending this cookie along with cross-site requests. Possible values are "lax", "strict" or "none". |

**Example**
```js
cookie.set('foo', 'bar', {
path: '/',
domain: 'example.com',
'max-age': 3600, // value in seconds; expires after one hour from the current time
secure: true,
samesite: 'strict'
});
// -> undefined
```
<a name="module_cookie..get"></a>

### cookie~get([name]) ⇒ <code>String</code>
Get a cookie by its name.

**Kind**: inner method of [<code>cookie</code>](#module_cookie)
**Returns**: <code>String</code> - Returns the value of the cookie if exists; otherwise an empty string.
**Throws**:

- <code>TypeError</code> If `name` is not string.


| Param | Type | Description |
| --- | --- | --- |
| [name] | <code>String</code> | The name of the cookie to get. |

**Example**
```js
cookie.get('foo');
// -> 'bar'

cookie.get('cookie-that-does-not-exist');
// -> ''
```
<a name="module_cookie..remove"></a>

### cookie~remove(name) ⇒ <code>void</code>
Deletes a cookie by its name.

**Kind**: inner method of [<code>cookie</code>](#module_cookie)
**Throws**:

- <code>TypeError</code> If `name` is not string.


| Param | Type | Description |
| --- | --- | --- |
| name | <code>String</code> | The name of the cookie to delete. |

**Example**
```js
cookie.remove('foo');
// -> undefined
```
118 changes: 118 additions & 0 deletions packages/dom/cookie/cookie.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,118 @@
/**
* @module cookie
* @category DOM
*/
module.exports = (function () {
/**
* Creates a new cookie.
*
* @function set
* @param {String} name The name of the cookie to create.
* @param {String} value The value of the cookie to create.
* @param {Object} [options]
* @param {String} [options.path="/"] The path where cookie is visible. If not specified, defaults to the current path of the current document location.
* @param {String} [options.domain] The domain where cookie is visible. If not specified, this defaults to the host portion of the current document location. If a domain is specified, subdomains are always included.
* @param {String} [options.expires] A date in GMTString format that tells when cookie expires. If not specified it will expire at the end of session. If date is in the past, then the cookie is deleted. Use `Date.prototype.toUTCString()` to properly format it.
* @param {Number} [options['max-age']] Max age in seconds from the time the cookie is set; alternative to `expires`. If not specified it will expire at the end of session. If zero or negative, then the cookie is deleted.
* @param {String} [options.secure] Cookie to only be transmitted over secure protocol as https.
* @param {String} [options.samesite] SameSite prevents the browser from sending this cookie along with cross-site requests. Possible values are "lax", "strict" or "none".
* @throws {TypeError} If `name` is not string.
* @throws {TypeError} If `value` is not string.
* @returns {void}
* @example
*
* cookie.set('foo', 'bar', {
* path: '/',
* domain: 'example.com',
* 'max-age': 3600, // value in seconds; expires after one hour from the current time
* secure: true,
* samesite: 'strict'
* });
* // -> undefined
*/
function setCookie(name, value, options) {
var cookie, optionKey, optionValue;

if (typeof name !== 'string' || typeof value !== 'string') {
throw new TypeError('Expected a string for first and second argument');
}

if (!options || typeof options !== 'object') {
options = {};
}

options.path = options.path || '/';

cookie = encodeURIComponent(name) + '=' + encodeURIComponent(value);

for (optionKey in options) {
if (Object.prototype.hasOwnProperty.call(options, optionKey)) {
optionValue = options[optionKey];
cookie += '; ' + optionKey;

if (optionValue !== true) {
cookie += '=' + optionValue;
}
}
}

document.cookie = cookie;
}

/**
* Get a cookie by its name.
*
* @function get
* @param {String} [name] The name of the cookie to get.
* @throws {TypeError} If `name` is not string.
* @returns {String} Returns the value of the cookie if exists; otherwise an empty string.
* @example
*
* cookie.get('foo');
* // -> 'bar'
*
* cookie.get('cookie-that-does-not-exist');
* // -> ''
*/
function getCookie(name) {
var matches;

if (typeof name !== 'string') {
throw new TypeError('Expected a string for first argument');
}

matches = document.cookie.match(
new RegExp('(?:^|; )' + name.replace(/([.$?*|{}()[\]\\/+^])/g, '\\$1') + '=([^;]*)')
);

return matches ? decodeURIComponent(matches[1]) : '';
}

/**
* Deletes a cookie by its name.
*
* @function remove
* @param {String} name The name of the cookie to delete.
* @throws {TypeError} If `name` is not string.
* @returns {void}
* @example
*
* cookie.remove('foo');
* // -> undefined
*/
function removeCookie(name) {
if (typeof name !== 'string') {
throw new TypeError('Expected a string for first argument');
}

setCookie(name, '', {
'max-age': -1
});
}

return {
set: setCookie,
get: getCookie,
remove: removeCookie
};
}());
63 changes: 63 additions & 0 deletions packages/dom/cookie/test.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,63 @@
var cookie = require('./cookie');

describe('misc/cookie', function () {
it('should create, read and delete cookies', function () {
cookie.set('cookie-1', 'value-1');
expect(cookie.get('cookie-1')).toBe('value-1');

cookie.set('cookie-2', 'val ue-2');
expect(cookie.get('cookie-2')).toBe('val ue-2');

cookie.set('cookie-3', 'val;ue-3');
expect(cookie.get('cookie-3')).toBe('val;ue-3');

cookie.set('cookie-4', 'val,ue-4');
expect(cookie.get('cookie-4')).toBe('val,ue-4');

cookie.set('cookie-5', 'val\tue-5');
expect(cookie.get('cookie-5')).toBe('val\tue-5');

cookie.set('cookie-6', 'val\nue-6');
expect(cookie.get('cookie-6')).toBe('val\nue-6');

expect(document.cookie).toBe('cookie-1=value-1; cookie-2=val%20ue-2; cookie-3=val%3Bue-3; cookie-4=val%2Cue-4; cookie-5=val%09ue-5; cookie-6=val%0Aue-6');

expect(decodeURIComponent(document.cookie)).toBe('cookie-1=value-1; cookie-2=val ue-2; cookie-3=val;ue-3; cookie-4=val,ue-4; cookie-5=val\tue-5; cookie-6=val\nue-6');

cookie.remove('cookie-1');
expect(cookie.get('cookie-1')).toBe('');

cookie.remove('cookie-2');
expect(cookie.get('cookie-2')).toBe('');

cookie.remove('cookie-3');
expect(cookie.get('cookie-3')).toBe('');

cookie.remove('cookie-4');
expect(cookie.get('cookie-4')).toBe('');

cookie.remove('cookie-5');
expect(cookie.get('cookie-5')).toBe('');

cookie.remove('cookie-6');
expect(cookie.get('cookie-6')).toBe('');

expect(document.cookie).toBe('');

expect(function () {
return cookie.set(null, 'value');
}).toThrow('Expected a string for first and second argument');

expect(function () {
return cookie.set('name', null);
}).toThrow('Expected a string for first and second argument');

expect(function () {
return cookie.get(null);
}).toThrow('Expected a string for first argument');

expect(function () {
return cookie.remove(null);
}).toThrow('Expected a string for first argument');
});
});
94 changes: 0 additions & 94 deletions packages/misc/cookie/README.md

This file was deleted.

Loading