Update Bower JS libs

Signed-off-by: Olivier Paroz (oparoz) <github@oparoz.com>
This commit is contained in:
Olivier Paroz (oparoz) 2017-03-12 10:12:43 +01:00
parent 979e31e034
commit 5c1d9b6086
No known key found for this signature in database
GPG Key ID: 165E66587C7FE8B1
7 changed files with 1110 additions and 709 deletions

View File

@ -1,11 +1,11 @@
{
"name": "gallery",
"homepage": "https://github.com/owncloud/gallery",
"homepage": "https://github.com/nextcloud/gallery",
"authors": [
"Olivier Paroz <galleryapps@oparoz.com>",
"Robin Appelman <robin@icewind.nl>"
],
"description": "Media gallery for ownCloud and Nextcloud which includes previews for all media types supported by your installation.",
"description": "Media gallery for Nextcloud which includes previews for all media types supported by your Nextcloud installation.",
"license": "AGPL",
"private": true,
"ignore": [
@ -18,7 +18,7 @@
"dependencies": {
"eventsource-polyfill": "~0.*",
"github-markdown-css": "~2.*",
"dompurify": "~0.7.0",
"commonmark": "~0.22.0"
"dompurify": "~0.8.*",
"commonmark": "~0.27.*"
}
}

File diff suppressed because one or more lines are too long

File diff suppressed because one or more lines are too long

View File

@ -1,4 +1,4 @@
# DOMPurify [![Bower version](https://badge.fury.io/bo/dompurify.svg)](http://badge.fury.io/bo/dompurify) · [![npm version](https://badge.fury.io/js/dompurify.svg)](http://badge.fury.io/js/dompurify) · [![Build Status](https://travis-ci.org/cure53/DOMPurify.svg?branch=master)](https://travis-ci.org/cure53/DOMPurify)
# DOMPurify [![Bower version](https://badge.fury.io/bo/dompurify.svg)](http://badge.fury.io/bo/dompurify) · [![npm version](https://badge.fury.io/js/dompurify.svg)](http://badge.fury.io/js/dompurify) · [![Build Status](https://travis-ci.org/cure53/DOMPurify.svg)](https://travis-ci.org/cure53/DOMPurify)
[![NPM](https://nodei.co/npm/dompurify.png)](https://nodei.co/npm/dompurify/)
@ -6,7 +6,9 @@ DOMPurify is a DOM-only, super-fast, uber-tolerant XSS sanitizer for HTML, MathM
It's also very simple to use and get started with.
DOMPurify is written in JavaScript and works in all modern browsers (Safari, Opera (15+), Internet Explorer (10+), Edge, Firefox and Chrome - as well as almost anything else using Blink or WebKit). It doesn't break on IE6 or other legacy browsers. It simply does nothing there. Our automated tests cover [9 different browsers](https://github.com/cure53/DOMPurify/blob/master/test/karma.conf.js#L125) right now.
DOMPurify is written in JavaScript and works in all modern browsers (Safari, Opera (15+), Internet Explorer (10+), Edge, Firefox and Chrome - as well as almost anything else using Blink or WebKit). It doesn't break on IE6 or other legacy browsers. It either uses [a fall-back](#what-about-older-browsers-like-msie8) or simply does nothing.
Our automated tests cover [12 different browsers](https://github.com/cure53/DOMPurify/blob/master/test/karma.conf.js#L153) right now. We also cover Node.js v4.0.0, v5.0.0 and v6.0.0, running DOMPurify on [jsdom](https://github.com/tmpvar/jsdom).
DOMPurify is written by security people who have vast background in web attacks and XSS. Fear not. For more details please also read about our [Security Goals & Threat Model](https://github.com/cure53/DOMPurify/wiki/Security-Goals-&-Threat-Model)
@ -38,6 +40,8 @@ var clean = DOMPurify.sanitize(dirty);
The resulting HTML can be written into a DOM element using `innerHTML` or the DOM using `document.write()`. That is fully up to you. But keep in mind, if you use the sanitized HTML with jQuery's very insecure `elm.html()` method, then the `SAFE_FOR_JQUERY` flag has to be set to make sure it's safe! Other than that, all is fine.
After sanitizing your markup, you can also have a look at the property `DOMPurify.removed` and find out, what elements and attributes were thrown out.
If you're using an [AMD](https://github.com/amdjs/amdjs-api/wiki/AMD) module loader like [Require.js](http://requirejs.org/), you can load this script asynchronously as well:
```javascript
@ -46,17 +50,28 @@ require(['dompurify'], function(DOMPurify) {
});
```
You can also grab the files straight from npm (requires either [io.js](https://iojs.org) or [Browserify](http://browserify.org/), **Node.js 0.x is not supported**):
DOMPurify also works server-side with node.js as well as client-side via [Browserify](http://browserify.org/) or similar translators. Node.js 0.x is not supported; either [io.js](https://iojs.org) or Node.js 4.x or newer is required.
```bash
npm install dompurify
```
```javascript
var DOMPurify = require('dompurify');
var clean = DOMPurify.sanitize(dirty);
const createDOMPurify = require('dompurify');
const jsdom = require('jsdom');
const window = jsdom.jsdom('', {
features: {
FetchExternalResources: false, // disables resource loading over HTTP / filesystem
ProcessExternalResources: false // do not execute JS within script blocks
}
}).defaultView;
const DOMPurify = createDOMPurify(window);
const clean = DOMPurify.sanitize(dirty);
```
Strictly speaking, DOMPurify creates a document without a browsing context and you can replace it with `const window = jsdom.jsdom().defaultView;`, however, the longer case protects against accidental bugs in jsdom or DOMPurify.
## Is there a demo?
Of course there is a demo! [Play with DOMPurify](https://cure53.de/purify)
@ -82,6 +97,11 @@ DOMPurify.sanitize('<UL><li><A HREF=//google.com>click</UL>'); // becomes <ul><l
DOMPurify currently supports HTML5, SVG and MathML. DOMPurify per default allows CSS, HTML custom data attributes. DOMPurify also supports the Shadow DOM - and sanitizes DOM templates recursively. DOMPurify also allows you to sanitize HTML for being used with the jQuery `$()` and `elm.html()` methods but requires the `SAFE_FOR_JQUERY` flag for that - see below.
## What about older browsers like MSIE8?
DOMPurify offers a fall-back behavior for older MSIE browsers. It uses the MSIE-only `toStaticHTML` feature to sanitize. Note however that in this fall-back mode, pretty much none of the configuration flags shown below have any effect. You need to handle that yourself.
If not even `toStaticHTML` is supported, DOMPurify does nothing at all. It simply returns exactly the string that you fed it.
## Can I configure it?
@ -115,6 +135,10 @@ var clean = DOMPurify.sanitize(dirty, {ADD_ATTR: ['my-attr']});
// prohibit HTML5 data attributes (default is true)
var clean = DOMPurify.sanitize(dirty, {ALLOW_DATA_ATTR: false});
// allow external protocol handlers in URL attributes (default is false)
// by default only http, https, ftp, ftps, tel and mailto are allowed.
var clean = DOMPurify.sanitize(dirty, {ALLOW_UNKNOWN_PROTOCOLS: true});
// return a DOM HTMLBodyElement instead of an HTML string (default is false)
var clean = DOMPurify.sanitize(dirty, {RETURN_DOM: true});
@ -137,7 +161,7 @@ var clean = DOMPurify.sanitize(dirty, {SANITIZE_DOM: false});
// discard an element's content when the element is removed (default is true)
var clean = DOMPurify.sanitize(dirty, {KEEP_CONTENT: false});
```
There is even [more examples here](https://github.com/cure53/DOMPurify/tree/master/demos#what-it-this), showing how you can run, customize and configure DOMPurify to fit your needs.
There is even [more examples here](https://github.com/cure53/DOMPurify/tree/master/demos#what-is-this), showing how you can run, customize and configure DOMPurify to fit your needs.
## Hooks
@ -168,7 +192,9 @@ DOMPurify.addHook('beforeSanitizeElements', function(currentNode, data, config)
We are currently using Travis CI in combination with BrowserStack. This gives us the possibility to confirm for each and every commit that all is going according to plan in all supported browsers. Check out the build logs here: https://travis-ci.org/cure53/DOMPurify
You can further run local tests by executing `npm run-script local-test` or, in case you have a BrowserStack account with automation available, run the tests using `npm run-script ci-test`.
You can further run local tests by executing `npm test`. The tests work fine with Node.js v0.6.2 and jsdom@8.5.0.
All relevant commits will be signed with the key `0x24BB6BF4` for additional security (since 8th of April 2016).
## Security Mailing List
@ -176,15 +202,18 @@ We maintain a mailing list that notifies whenever a security-critical release of
[https://lists.ruhr-uni-bochum.de/mailman/listinfo/dompurify-security](https://lists.ruhr-uni-bochum.de/mailman/listinfo/dompurify-security)
## What's on the road-map?
We recently implemented a Hook-API allowing developers to create their own DOMPurify plugins and customize its functionality without changing the core. Thus, we are looking forward for plugins and extensions - pull requests are welcome! Oh, and we will increase the amount of browsers and HTML-mappings in our automates tests to make sure nothing slips through.
Feature releases will not be announced to this list.
## Who contributed?
Several people need to be listed here! [@garethheyes](https://twitter.com/garethheyes) for invaluable help, [@shafigullin](https://twitter.com/shafigullin) for breaking the library multiple times and thereby strengthening it, [@mmrupp](https://twitter.com/mmrupp) and [@irsdl](https://twitter.com/irsdl) for doing the same.
Several people need to be listed here!
Big thanks also go to [@asutherland](https://twitter.com/asutherland), [@mathias](https://twitter.com/mathias), [@cgvwzq](https://twitter.com/cgvwzq), [@robbertatwork](https://twitter.com/robbertatwork), [@giutro](https://twitter.com/giutro) and [@fhemberger](https://twitter.com/fhemberger)! Further, thanks [@neilj](https://twitter.com/neilj) for his code review and countless small optimizations, fixes and beautifications. Big thanks also go to [@tdeekens](https://twitter.com/tdeekens) for doing all the hard work and getting us on track with Travis CI and BrowserStack.
[@garethheyes](https://twitter.com/garethheyes) and [@filedescriptor](https://twitter.com/filedescriptor) for invaluable help, [@shafigullin](https://twitter.com/shafigullin) for breaking the library multiple times and thereby strengthening it, [@mmrupp](https://twitter.com/mmrupp) and [@irsdl](https://twitter.com/irsdl) for doing the same.
Big thanks also go to [@asutherland](https://twitter.com/asutherland), [@mathias](https://twitter.com/mathias), [@cgvwzq](https://twitter.com/cgvwzq), [@robbertatwork](https://twitter.com/robbertatwork), [@giutro](https://twitter.com/giutro) and [@fhemberger](https://twitter.com/fhemberger)!
Further, thanks [@neilj](https://twitter.com/neilj) and [@0xsobky](https://twitter.com/0xsobky) for their code reviews and countless small optimizations, fixes and beautifications.
Big thanks also go to [@tdeekens](https://twitter.com/tdeekens) for doing all the hard work and getting us on track with Travis CI and BrowserStack. And thanks to [@Joris-van-der-Wel](https://github.com/Joris-van-der-Wel) for setting up DOMPurify for jsdom and creating the additional test suite.
And last but not least, thanks to [BrowserStack](https://browserstack.com) for supporting this project with their services for free and delivering excellent, dedicated and very professional support on top of that.

View File

@ -21,7 +21,13 @@
* Version label, exposed for easier checks
* if DOMPurify is up to date or not
*/
DOMPurify.version = '0.7.3';
DOMPurify.version = '0.8.5';
/**
* Array of elements that DOMPurify removed during sanitation.
* Empty if nothing was removed.
*/
DOMPurify.removed = [];
if (!window || !window.document || window.document.nodeType !== 9) {
// not running in a browser, provide a factory function
@ -34,6 +40,7 @@
var originalDocument = document;
var DocumentFragment = window.DocumentFragment;
var HTMLTemplateElement = window.HTMLTemplateElement;
var Node = window.Node;
var NodeFilter = window.NodeFilter;
var NamedNodeMap = window.NamedNodeMap || window.MozNamedAttrMap;
var Text = window.Text;
@ -47,7 +54,10 @@
// document, so we use that as our parent document to ensure nothing
// is inherited.
if (typeof HTMLTemplateElement === 'function') {
document = document.createElement('template').content.ownerDocument;
var template = document.createElement('template');
if (template.content && template.content.ownerDocument) {
document = template.content.ownerDocument;
}
}
var implementation = document.implementation;
var createNodeIterator = document.createNodeIterator;
@ -68,6 +78,9 @@
var _addToSet = function(set, array) {
var l = array.length;
while (l--) {
if (typeof array[l] === 'string') {
array[l] = array[l].toLowerCase();
}
set[array[l]] = true;
}
return set;
@ -112,7 +125,7 @@
// SVG
'svg','altglyph','altglyphdef','altglyphitem','animatecolor',
'animatemotion','animatetransform','circle','clippath','defs','desc',
'ellipse','font','g','glyph','glyphref','hkern','image','line',
'ellipse','filter','font','g','glyph','glyphref','hkern','image','line',
'lineargradient','marker','mask','metadata','mpath','path','pattern',
'polygon','polyline','radialgradient','rect','stop','switch','symbol',
'text','textpath','title','tref','tspan','view','vkern',
@ -121,7 +134,7 @@
'feBlend','feColorMatrix','feComponentTransfer','feComposite',
'feConvolveMatrix','feDiffuseLighting','feDisplacementMap',
'feFlood','feFuncA','feFuncB','feFuncG','feFuncR','feGaussianBlur',
'feImage','feMerge','feMergeNode','feMorphology','feOffset',
'feMerge','feMergeNode','feMorphology','feOffset',
'feSpecularLighting','feTile','feTurbulence',
//MathML
@ -169,9 +182,9 @@
'opacity','order','orient','orientation','origin','overflow','paint-order',
'path','pathlength','patterncontentunits','patterntransform','patternunits',
'points','preservealpha','r','rx','ry','radius','refx','refy','repeatcount',
'repeatdur','restart','rotate','scale','seed','shape-rendering','specularconstant',
'specularexponent','spreadmethod','stddeviation','stitchtiles','stop-color',
'stop-opacity','stroke-dasharray','stroke-dashoffset','stroke-linecap',
'repeatdur','restart','result','rotate','scale','seed','shape-rendering',
'specularconstant','specularexponent','spreadmethod','stddeviation','stitchtiles',
'stop-color','stop-opacity','stroke-dasharray','stroke-dashoffset','stroke-linecap',
'stroke-linejoin','stroke-miterlimit','stroke-opacity','stroke','stroke-width',
'surfacescale','targetx','targety','transform','text-anchor','text-decoration',
'text-rendering','textlength','u1','u2','unicode','values','viewbox',
@ -203,6 +216,9 @@
/* Decide if custom data attributes are okay */
var ALLOW_DATA_ATTR = true;
/* Decide if unknown protocols are okay */
var ALLOW_UNKNOWN_PROTOCOLS = false;
/* Output should be safe for jQuery's $() factory? */
var SAFE_FOR_JQUERY = false;
@ -211,6 +227,10 @@
*/
var SAFE_FOR_TEMPLATES = false;
/* Specify template detection regex for SAFE_FOR_TEMPLATES mode */
var MUSTACHE_EXPR = /\{\{[\s\S]*|[\s\S]*\}\}/gm;
var ERB_EXPR = /<%[\s\S]*|[\s\S]*%>/gm;
/* Decide if document with <html>... should be returned */
var WHOLE_DOCUMENT = false;
@ -239,6 +259,17 @@
'audio', 'head', 'math', 'script', 'style', 'svg', 'video'
]);
/* Tags that are safe for data: URIs */
var DATA_URI_TAGS = _addToSet({}, [
'audio', 'video', 'img', 'source'
]);
/* Attributes safe for values like "javascript:" */
var URI_SAFE_ATTRIBUTES = _addToSet({}, [
'alt','class','for','id','label','name','pattern','placeholder',
'summary','title','value','style','xmlns'
]);
/* Keep a reference to config to pass to hooks */
var CONFIG = null;
@ -268,6 +299,7 @@
FORBID_ATTR = 'FORBID_ATTR' in cfg ?
_addToSet({}, cfg.FORBID_ATTR) : {};
ALLOW_DATA_ATTR = cfg.ALLOW_DATA_ATTR !== false; // Default true
ALLOW_UNKNOWN_PROTOCOLS = cfg.ALLOW_UNKNOWN_PROTOCOLS || false; // Default false
SAFE_FOR_JQUERY = cfg.SAFE_FOR_JQUERY || false; // Default false
SAFE_FOR_TEMPLATES = cfg.SAFE_FOR_TEMPLATES || false; // Default false
WHOLE_DOCUMENT = cfg.WHOLE_DOCUMENT || false; // Default false
@ -277,6 +309,10 @@
SANITIZE_DOM = cfg.SANITIZE_DOM !== false; // Default true
KEEP_CONTENT = cfg.KEEP_CONTENT !== false; // Default true
if (SAFE_FOR_TEMPLATES) {
ALLOW_DATA_ATTR = false;
}
if (RETURN_DOM_FRAGMENT) {
RETURN_DOM = true;
}
@ -294,6 +330,9 @@
}
_addToSet(ALLOWED_ATTR, cfg.ADD_ATTR);
}
if (cfg.ADD_URI_SAFE_ATTR) {
_addToSet(URI_SAFE_ATTRIBUTES, cfg.ADD_URI_SAFE_ATTR);
}
/* Add #text in case KEEP_CONTENT is set to true */
if (KEEP_CONTENT) { ALLOWED_TAGS['#text'] = true; }
@ -311,6 +350,7 @@
* @param a DOM node
*/
var _forceRemove = function(node) {
DOMPurify.removed.push({element: node});
try {
node.parentNode.removeChild(node);
} catch (e) {
@ -318,6 +358,20 @@
}
};
/**
* _removeAttribute
*
* @param an Attribute name
* @param a DOM node
*/
var _removeAttribute = function(name, node) {
DOMPurify.removed.push({
attribute: node.getAttributeNode(name),
from: node
});
node.removeAttribute(name);
};
/**
* _initDocument
*
@ -332,8 +386,9 @@
} catch (e) {}
/* Some browsers throw, some browsers return null for the code above
DOMParser with text/html support is only in very recent browsers. */
if (!doc){
DOMParser with text/html support is only in very recent browsers.
See #159 why the check here is extra-thorough */
if (!doc || !doc.documentElement) {
doc = implementation.createHTMLDocument('');
body = doc.body;
body.parentNode.removeChild(body.parentNode.firstElementChild);
@ -341,13 +396,12 @@
}
/* Work on whole document or just its body */
if (typeof doc.getElementsByTagName === 'function'){
if (typeof doc.getElementsByTagName === 'function') {
return doc.getElementsByTagName(
WHOLE_DOCUMENT ? 'html' : 'body')[0];
} else {
return getElementsByTagName.call(doc,
WHOLE_DOCUMENT ? 'html' : 'body')[0];
}
return getElementsByTagName.call(doc,
WHOLE_DOCUMENT ? 'html' : 'body')[0];
};
/**
@ -389,8 +443,19 @@
return false;
};
var MUSTACHE_EXPR = /\{\{.*|.*\}\}/gm;
var ERB_EXPR = /<%.*|.*%>/gm;
/**
* _isNode
*
* @param object to check whether it's a DOM node
* @return true is object is a DOM node
*/
var _isNode = function(obj) {
return (
typeof Node === "object" ? obj instanceof Node : obj
&& typeof obj === "object" && typeof obj.nodeType === "number"
&& typeof obj.nodeName==="string"
);
};
/**
* _sanitizeElements
@ -403,6 +468,7 @@
* @return true if node was killed, false if left alive
*/
var _sanitizeElements = function(currentNode) {
var tagName, content;
/* Execute a hook if present */
_executeHook('beforeSanitizeElements', currentNode, null);
@ -413,11 +479,12 @@
}
/* Now let's check the element's type and name */
var tagName = currentNode.nodeName.toLowerCase();
tagName = currentNode.nodeName.toLowerCase();
/* Execute a hook if present */
_executeHook('uponSanitizeElement', currentNode, {
tagName: tagName
tagName: tagName,
allowedTags: ALLOWED_TAGS
});
/* Remove element if anything forbids its presence */
@ -435,17 +502,22 @@
/* Convert markup to cover jQuery behavior */
if (SAFE_FOR_JQUERY && !currentNode.firstElementChild &&
(!currentNode.content || !currentNode.content.firstElementChild)) {
(!currentNode.content || !currentNode.content.firstElementChild) &&
/</g.test(currentNode.textContent)) {
DOMPurify.removed.push({element: currentNode.cloneNode()});
currentNode.innerHTML = currentNode.textContent.replace(/</g, '&lt;');
}
/* Sanitize element content to be template-safe */
if (SAFE_FOR_TEMPLATES && currentNode.nodeType === 3) {
/* Get the element's text content */
var content = currentNode.textContent;
content = currentNode.textContent;
content = content.replace(MUSTACHE_EXPR, ' ');
content = content.replace(ERB_EXPR, ' ');
currentNode.textContent = content;
if (currentNode.textContent !== content) {
DOMPurify.removed.push({element: currentNode.cloneNode()});
currentNode.textContent = content;
}
}
/* Execute a hook if present */
@ -454,7 +526,8 @@
return false;
};
var DATA_ATTR = /^data-[\w.\u00B7-\uFFFF-]/;
var DATA_ATTR = /^data-[\-\w.\u00B7-\uFFFF]/;
var IS_ALLOWED_URI = /^(?:(?:(?:f|ht)tps?|mailto|tel):|[^a-z]|[a-z+.\-]+(?:[^a-z+.\-:]|$))/i;
var IS_SCRIPT_OR_DATA = /^(?:\w+script|data):/i;
/* This needs to be extensive thanks to Webkit/Blink's behavior */
var ATTR_WHITESPACE = /[\x00-\x20\xA0\u1680\u180E\u2000-\u2029\u205f\u3000]/g;
@ -471,27 +544,28 @@
* @return void
*/
var _sanitizeAttributes = function(currentNode) {
var attr, name, value, lcName, idAttr, attributes, hookEvent, l;
/* Execute a hook if present */
_executeHook('beforeSanitizeAttributes', currentNode, null);
var attributes = currentNode.attributes;
attributes = currentNode.attributes;
/* Check if we have attributes; if not we might have a text node */
if (!attributes) { return; }
var hookEvent = {
hookEvent = {
attrName: '',
attrValue: '',
keepAttr: true
keepAttr: true,
allowedAttributes: ALLOWED_ATTR
};
var l = attributes.length;
var attr, name, value, lcName, idAttr;
l = attributes.length;
/* Go backwards over all attributes; safely remove bad ones */
while (l--) {
attr = attributes[l];
name = attr.name;
value = attr.value;
value = attr.value.trim();
lcName = name.toLowerCase();
/* Execute a hook if present */
@ -509,8 +583,8 @@
currentNode.nodeName === 'IMG' && attributes.id) {
idAttr = attributes.id;
attributes = Array.prototype.slice.apply(attributes);
currentNode.removeAttribute('id');
currentNode.removeAttribute(name);
_removeAttribute('id', currentNode);
_removeAttribute(name, currentNode);
if (attributes.indexOf(idAttr) > l) {
currentNode.setAttribute('id', idAttr.value);
}
@ -521,7 +595,7 @@
if (name === 'id') {
currentNode.setAttribute(name, '');
}
currentNode.removeAttribute(name);
_removeAttribute(name, currentNode);
}
/* Did the hooks approve of the attribute? */
@ -536,33 +610,61 @@
continue;
}
if (
/* Check the name is permitted */
(
(ALLOWED_ATTR[lcName] && !FORBID_ATTR[lcName]) ||
/* Allow potentially valid data-* attributes
* At least one character after "-" (https://html.spec.whatwg.org/multipage/dom.html#embedding-custom-non-visible-data-with-the-data-*-attributes)
* XML-compatible (https://html.spec.whatwg.org/multipage/infrastructure.html#xml-compatible and http://www.w3.org/TR/xml/#d0e804) */
(!SAFE_FOR_TEMPLATES && ALLOW_DATA_ATTR && DATA_ATTR.test(lcName))
) &&
/* Get rid of script and data URIs */
(
!IS_SCRIPT_OR_DATA.test(value.replace(ATTR_WHITESPACE,'')) ||
/* Keep image data URIs alive if src is allowed */
(lcName === 'src' && value.indexOf('data:') === 0 &&
currentNode.nodeName === 'IMG')
)
) {
/* Handle invalid data-* attribute set by try-catching it */
try {
/* Sanitize attribute content to be template-safe */
if (SAFE_FOR_TEMPLATES) {
value = value.replace(MUSTACHE_EXPR, ' ');
value = value.replace(ERB_EXPR, ' ');
}
currentNode.setAttribute(name, value);
} catch (e) {}
/* Sanitize attribute content to be template-safe */
if (SAFE_FOR_TEMPLATES) {
value = value.replace(MUSTACHE_EXPR, ' ');
value = value.replace(ERB_EXPR, ' ');
}
/* Allow valid data-* attributes: At least one character after "-"
(https://html.spec.whatwg.org/multipage/dom.html#embedding-custom-non-visible-data-with-the-data-*-attributes)
XML-compatible (https://html.spec.whatwg.org/multipage/infrastructure.html#xml-compatible and http://www.w3.org/TR/xml/#d0e804)
We don't need to check the value; it's always URI safe. */
if (ALLOW_DATA_ATTR && DATA_ATTR.test(lcName)) {
// This attribute is safe
}
/* Otherwise, check the name is permitted */
else if (!ALLOWED_ATTR[lcName] || FORBID_ATTR[lcName]) {
continue;
}
/* Check value is safe. First, is attr inert? If so, is safe */
else if (URI_SAFE_ATTRIBUTES[lcName]) {
// This attribute is safe
}
/* Check no script, data or unknown possibly unsafe URI
unless we know URI values are safe for that attribute */
else if (IS_ALLOWED_URI.test(value.replace(ATTR_WHITESPACE,''))) {
// This attribute is safe
}
/* Keep image data URIs alive if src is allowed */
else if (
lcName === 'src' &&
value.indexOf('data:') === 0 &&
DATA_URI_TAGS[currentNode.nodeName.toLowerCase()]) {
// This attribute is safe
}
/* Allow unknown protocols: This provides support for links that
are handled by protocol handlers which may be unknown ahead of
time, e.g. fb:, spotify: */
else if (
ALLOW_UNKNOWN_PROTOCOLS &&
!IS_SCRIPT_OR_DATA.test(value.replace(ATTR_WHITESPACE,''))) {
// This attribute is safe
}
/* Check for binary attributes */
else if (!value) {
// binary attributes are safe at this point
}
/* Anything else, presume unsafe, do not add it back */
else {
continue;
}
/* Handle invalid data-* attribute set by try-catching it */
try {
currentNode.setAttribute(name, value);
DOMPurify.removed.pop();
} catch (e) {}
}
/* Execute a hook if present */
@ -623,27 +725,36 @@
* sanitize
* Public method providing core sanitation functionality
*
* @param {String} dirty string
* @param {String|Node} dirty string or DOM node
* @param {Object} configuration object
*/
DOMPurify.sanitize = function(dirty, cfg) {
var body, importedNode, currentNode, oldNode, nodeIterator, returnNode;
/* Make sure we have a string to sanitize.
DO NOT return early, as this will return the wrong type if
the user has requested a DOM object rather than a string */
if (!dirty) {
dirty = '';
dirty = '<!-->';
}
/* Stringify, in case dirty is an array or other object */
if (typeof dirty !== 'string') {
dirty = dirty.toString();
/* Stringify, in case dirty is an object */
if (typeof dirty !== 'string' && !_isNode(dirty)) {
if (typeof dirty.toString !== 'function') {
throw new TypeError('toString is not a function');
} else {
dirty = dirty.toString();
}
}
/* Check we can run. Otherwise fall back or ignore */
if (!DOMPurify.isSupported) {
if (typeof window.toStaticHTML === 'object'
if (typeof window.toStaticHTML === 'object'
|| typeof window.toStaticHTML === 'function') {
return window.toStaticHTML(dirty);
if (typeof dirty === 'string') {
return window.toStaticHTML(dirty);
} else if (_isNode(dirty)) {
return window.toStaticHTML(dirty.outerHTML);
}
}
return dirty;
}
@ -651,23 +762,37 @@
/* Assign config vars */
_parseConfig(cfg);
/* Exit directly if we have nothing to do */
if (!RETURN_DOM && !WHOLE_DOCUMENT && dirty.indexOf('<') === -1) {
return dirty;
}
/* Clean up removed elements */
DOMPurify.removed = [];
/* Initialize the document to work on */
var body = _initDocument(dirty);
if (dirty instanceof Node) {
/* If dirty is a DOM element, append to an empty document to avoid
elements being stripped by the parser */
body = _initDocument('<!-->');
importedNode = body.ownerDocument.importNode(dirty, true);
if (importedNode.nodeType === 1 && importedNode.nodeName === 'BODY') {
/* Node is already a body, use as is */
body = importedNode;
} else {
body.appendChild( importedNode );
}
} else {
/* Exit directly if we have nothing to do */
if (!RETURN_DOM && !WHOLE_DOCUMENT && dirty.indexOf('<') === -1) {
return dirty;
}
/* Check we have a DOM node from the data */
if (!body) {
return RETURN_DOM ? null : '';
/* Initialize the document to work on */
body = _initDocument(dirty);
/* Check we have a DOM node from the data */
if (!body) {
return RETURN_DOM ? null : '';
}
}
/* Get node iterator */
var currentNode;
var oldNode;
var nodeIterator = _createIterator(body);
nodeIterator = _createIterator(body);
/* Now start iterating over the created document */
while ( (currentNode = nodeIterator.nextNode()) ) {
@ -694,7 +819,6 @@
}
/* Return sanitized string or DOM */
var returnNode;
if (RETURN_DOM) {
if (RETURN_DOM_FRAGMENT) {
@ -769,7 +893,7 @@
* @return void
*/
DOMPurify.removeAllHooks = function() {
hooks = [];
hooks = {};
};
return DOMPurify;

View File

@ -1,43 +1,150 @@
jQuery Touch Events
====================
# jQuery Touch Events
This is a series of plugins that create additional events that can be used in combination with jQuery when developing for mobile devices. The events are also compatible with desktop browsers to ensure ultimate compatibility for your projects. In time, we will update the Repository to include some very basic demonstrations to get you started with using the events, but for now, we've put together a list of the events that are provided, and what they do.
As explained, the events are each triggered by native touch events, or alternatively by click events. The plugin automatically detects whether the user's device is touch compatible, and will use the correct native events whenever required. It is hoped that these events will help to aid single-environment development with jQuery for mobile web app development.
Version History:
---------------
## Table of Contents:
1. [Version History](#1-version-history)
2. [Installation](#2-installation)
3. [Usage](#3-usage)
4. [Events](#4-the-events)
5. [Callback Data](#5-callback-data)
6. [Defining Thresholds](#6-defining-thresholds)
7. [Utility Functions](#7-utility-functions)
8. [Demo](#8-demo)
9. [Requirements](#9-requirements)
10. [License](#10-license)
## 1. Version History:
After almost 2 years in public beta, I am pleased to announce that the library is now officially launched as **version 1.0.0**. I'll be updating the version history over time with digests of fixes, features and improvements:
+ **2015-07-18 - Version 1.0.0**
+ The library officially entered 1.0.0 after minor bug fixes and final adjustments.
+ **Version 1.0.8** (2017-02-01)
+ Fixes a bug where certain instances of Chrome on touch devices did not correctly fire events.
+ Added license info to minified script.
+ **2015-08-21 - Version 1.0.1**
+ **Version 1.0.7** (2017-02-01)
+ Added threshold support for `taphold`
+ **Version 1.0.6** (2016-11-16)
+ Added slop factor for `singletap`
+ Fixed a bug where `offset()` was sometimes called on `null` (instead of `window`).
+ **Version 1.0.5** (2015-11-13)
+ Fixed a major bug where the reported `offset` position of events was incorrect when inside of a parent element.
+ **Version 1.0.4** (2015-11-12)
+ Regressed from `MSPointerEvent` for compatibility with IE11 and Edge
+ Removed multi-name event for `tap`.
+ **Version 1.0.3** (2015-11-10)
+ Numerous minor bug fixes
+ Fixes a bug where the offset position returned by events relative to the **current target**, not the bound target.
+ **Version 1.0.2** (2015-08-26)
+ Numerous bug fixes
+ Added support for `MSPointerEvent`
+ **Version 1.0.1** (2015-08-21)
+ Added Bower package for easy install
+ Fixed a bug where Internet Explorer under Windows Mobile did not trigger certain events.
Utility Functions:
-----------------
In addition to the numerous additional events that are provided, the library also includes a number of utility functions that can be used to further leverage the power of native events within your website or application. These utility functions can be used for unifying basic events, such as `tapstart` or `mousedown`.
+ **Version 1.0.0** (2015-07-18)
+ The library officially entered 1.0.0 after minor bug fixes and final adjustments.
The following utility functions are provided (each function is registered to the jQuery namespace, and should be called with `$.funcName()` (or `jQuery.funcName()` for compatibility):
## 2. Installation:
+ `isTouchCapable()`:
Returns `true` or `false` depending upon whether touch events are supported.
+ `getStartEvent()`:
Returns `touchstart` for touch-enabled devices, or `mousedown` for standard environments.
+ `getEndEvent()`:
Returns `touchend` for touch-enabled devices, or `mouseup` for standard environments.
+ `getMoveEvent()`:
Returns `touchmove` for touch-enabled devices, or `mousemove` for standard environments.
+ `getTapEvent()`:
Returns `tap` for touch-enabled devices, or `click` for standard environments.
+ `getScrollEvent()`:
Returns `touchmove` for touch-enabled devices, or `scroll` for standard environments. **Caution should be exercised when using this function, since some mobile browsers will correctly bind to `scroll` as well as `touchmove`.**
Events Provided:
---------------
jQuery Touch Events, as the name suggests, require only the jQuery library (version 1.7+) to run. You should download the latest release from the `src` folder, and include the Javascript file within your project, **after** jQuery has been included. It is recommended to also wrap your code inside the `DOMReady` callback function of jQuery (`$(function() { })`, for example).
**Manual installation:**
Once you have downloaded the JS files from the master branch, you should include them using the following code:
```
<script type="text/javascript" src="path/to/jquery.mobile-events.min.js"></script>
```
The awesome guys over at cdnjs have kindly added the library to their CDN so you can include it as follows directly into your application:
```
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery-touch-events/1.0.5/jquery.mobile-events.js"></script>
```
Alternatively, you can also install jQuery-touch-events using Bower as follows:
```
$ bower install jquery-touch-events
```
jQuery Touch Events can also be installed using NPM as follows:
```
$ npm install git+https://github.com/benmajor/jQuery-Touch-Events.git
```
### 3. Usage:
All of the events outlined above have been written using jQuery's ``event.special`` object, and so can be used in conjunction with jQuery's event handling functions, as well as shortcut wrappers. As a result, all of the events that are supported by this library may be handled using any of jQuery's own event-specific methods, such as `bind()`, `on()`, `live()` (for legacy) and `one()`.
The following code snippets showcase some basic usage with jQuery:
**Binding a ``tap`` event to an element:**
```
$('#myElement').bind('tap', function(e) {
console.log('User tapped #myElement');
});
```
**Using with ``.on()`` and ``.live()``:**
```
$('#myElement').live('tap', function(e) {
console.log('User tapped #myElement');
});
```
```
$('#myElement').on('tap', function(e) {
console.log('User tapped #myElement');
});
```
**Triggering the event:**
```
$('#myElement').trigger('tap');
```
**Removing the event with ``.off()``, ``.die()`` and ``.unbind()``:**
```
$('#myElement').off('tap', handler);
```
```
$('#myElement').die('tap', handler);
```
```
$('#myElement').unbind('tap', handler);
```
**Using method wrapper:**
```
$('#myElement').tap(function(e) {
console.log('User tapped #myElement');
});
```
**Method chaining:**
Chaining has also been preserved, so you can easily use these events in conjunction with other jQuery functions, or attach multiple events in a single, chained LOC:
```
$('#myElement').singletap(function() {
console.log('singletap');
}).doubletap(function() {
console.log('doubletap');
});
```
## 4. The Events:
+ **`tapstart`**
Fired as soon as the user begins touching an element (or clicking, for desktop environments).
@ -46,7 +153,7 @@ Fired after the user releases their finger from the target element (or releases
+ **`tapmove`**
Fired as soon as the user begins moving their finger on an element (or moving their mouse, for desktop environments).
+ **`tap`**
This event is fired whenever the user taps and releases their finger on the target element. Caution should be observed when using this event in conjunction without tap events, especially ``doubletap``. This event will be fired twice when ``doubletap`` is used, so it is recommended to use ``singletap`` in this case.
This event is fired whenever the user taps and releases their finger on the target element. Caution should be observed when using this event in conjunction with tap events, especially ``doubletap``. This event will be fired twice when ``doubletap`` is used, so it is recommended to use ``singletap`` in this case.
+ **`singletap`**
Unlike ``tap`` this event is only triggered once we are certain the user has only tapped the target element a single time. This will not be triggered by ``doubletap`` or ``taphold``, unlike ``tap``. Since we need to run some tests to make sure the user isn't double tapping or holding a tap on the target element, this event is fired with a short delay (currently of 500 milliseconds).
+ **`doubletap`**
@ -72,17 +179,19 @@ Triggered as soon as scrolling is stopped on the target element.
+ **`orientationchange`**
This event is triggered when the orientation of the device is changed. Please note that it uses throttling for non-mobile devices, or devices which do not support the native ``orientationchange`` event. In the latter instance, a detection of the viewport size change occurs.
Callback Data:
--------------
## 5. Callback Data:
Each event now features a second argument that can be passed to the specified callback function. This argument includes some basic data relating specifically to the event, and can be accessed as a standard JavaScript object. To hook into this parameter, you should use the following code:
`$(element).swipeend(function(e, touch) { });`
```
$(element).swipeend(function(e, touch) { });
```
Given the example above, `touch` will now contain some basic data that can be accessed through `touch.`. The first argument will represent the last *native* event that occurred (the names used for these two arguments is irrelevant).
Each event provides different callback data. The following shows the numerous data that are passed back to the callback function inside the second parameter:
##`tapstart`, `tapend`, `tapmove`, `tap`, `singletap`:
### `tapstart`, `tapend`, `tapmove`, `tap`, `singletap`:
`offset` - object containing the X and Y positions of the event relative to the element to which is was bound. Accessed through `offset.x` and `offset.y` respectively.
@ -92,7 +201,7 @@ Each event provides different callback data. The following shows the numerous da
`time` - JavaScript timestamp the event occurred (milliseconds since the Unix Epoch)
##`taphold`:
### `taphold`:
`duration`: the time in milliseconds that the user tapped for.
@ -110,7 +219,7 @@ Each event provides different callback data. The following shows the numerous da
`target` - the jQuery object from which the event was triggered.
##`doubletap`:
### `doubletap`:
`firstTap` - Object containing the same data as a `tap` event, but for the first tap to occur.
@ -118,7 +227,7 @@ Each event provides different callback data. The following shows the numerous da
`interval` - the time in milliseconds between the two tap.
##`swipe`, `swipeup`, `swiperight`, `swipedown`, `swipeleft`, `swipeend`:
### `swipe`, `swipeup`, `swiperight`, `swipedown`, `swipeleft`, `swipeend`:
`direction` - string representing the swipe direction (either `up`, `right`, `down` or `left`).
@ -128,48 +237,12 @@ Each event provides different callback data. The following shows the numerous da
`yAmount` - number of pixels the swipe occupied on the Y-axis (returned regardless of direction).
`startEvent` - Object containing the same data as a `tap` event, but captured when swiping begins.
`startEvnt` - Object containing the same data as a `tap` event, but captured when swiping begins.
`endEvent` - Object containing the same data as a `tap` event, but captured when swiping is complete.
Demo:
-----
I have put together a simple demo application that shows the numerous events in action. The console on the left hand side is used to show information about the events that have been called. You can examine the code easily by viewing the page's source to lear more about how this works. Please click on the below to check out the demo:
## 6. Defining Thresholds:
http://ben-major.co.uk/jquery-mobile-events/
Please be aware that this demonstration uses Google's hosted jQuery file, and also pulls the latest version of the events library from GitHub. It is a great place to check the status of the library. Since this demo uses the vanilla code, it is a good idea to check the library functionality here for your own reference. If you're running into problems with the library, please check this demonstration using your device in the first instance. You can scan in the QR below to go directly to the web page:
![Demonstration QR Code](http://qrfree.kaywa.com/?l=1&s=8&d=http%3A%2F%2Fben-major.co.uk%2Fjquery-mobile-events%2F)
Usage:
------
All of the events outlined above have been written using jQuery's ``event.special`` object, and so can be used in conjunction with jQuery's event handling functions, as well as shortcut wrappers.
**Binding a ``tap`` event to an element:**
``$('#myElement').bind('tap', function(e) { console.log('User tapped #myElement'); });``
**Using with ``.on()`` and ``.live()``:**
``$('#myElement').live('tap', function(e) { console.log('User tapped #myElement'); });``
``$('#myElement').on('tap', function(e) { console.log('User tapped #myElement'); });``
**Triggering the event:**
``$('#myElement').trigger('tap');``
**Removing the event with ``.off()``, ``.die()`` and ``.unbind()``:**
``$('#myElement').off('tap', hander);``
``$('#myElement').die('tap', hander);``
``$('#myElement').unbind('tap', hander);``
**Using method wrapper:**
``$('#myElement').tap(function(e) { console.log('User tapped #myElement'); });``
**Method chaining:**
Chaining has also been preserved, so you can easily use these events in conjuction with other jQuery functions, or attach multiple events in a single, chained LOC:
``$('#myElement').singletap(function() { console.log('singletap'); }).doubletap(function() { console.log('doubletap'); });``
Defining Thresholds:
--------------------
You can also define custom thresholds to be used for ``swipe`` events (``swipeup``, ``swiperight``, ``swipedown`` and ``swipeleft``) to prevent interference with scrolling and other events. To do so, simply assign a `data-xthreshold` or `date-ythreshold` to the target element as follows:
``<div id="mySwiper" data-xthreshold="500"></div>``
@ -180,12 +253,47 @@ The value you define is the difference in pixels that the user must move before
``data-ythreshold`` defines the vertical threshold.
Requirements:
-------------
**Update as of 1.0.7:**
Following requests from users and contributors, as of 1.0.7 it is now possible to also define the `doubletap` threshold via jQuery's `data-` attributes as follows:
``data-threshold`` defines the amount of time (in milliseconds) after which the `doubletap` event is fired on the target element.
## 7. Utility Functions:
In addition to the numerous additional events that are provided, the library also includes a number of utility functions that can be used to further leverage the power of native events within your website or application. These utility functions can be used for unifying basic events, such as `tapstart` or `mousedown`.
The following utility functions are provided (each function is registered to the jQuery namespace, and should be called with `$.funcName()` (or `jQuery.funcName()` for compatibility):
+ `isTouchCapable()`:
Returns `true` or `false` depending upon whether touch events are supported.
+ `getStartEvent()`:
Returns `touchstart` for touch-enabled devices, or `mousedown` for standard environments.
+ `getEndEvent()`:
Returns `touchend` for touch-enabled devices, or `mouseup` for standard environments.
+ `getMoveEvent()`:
Returns `touchmove` for touch-enabled devices, or `mousemove` for standard environments.
+ `getTapEvent()`:
Returns `tap` for touch-enabled devices, or `click` for standard environments.
+ `getScrollEvent()`:
Returns `touchmove` for touch-enabled devices, or `scroll` for standard environments. **Caution should be exercised when using this function, since some mobile browsers will correctly bind to `scroll` as well as `touchmove`.**
## 8. Demo:
I have put together a simple demo application that shows the numerous events in action. The console on the left hand side is used to show information about the events that have been called. You can examine the code easily by viewing the page's source to lear more about how this works. Please click on the below to check out the demo:
http://lincweb.co.uk/labs/jquery-touch-events/demo/
Please be aware that this demonstration uses Google's hosted jQuery file, and also pulls the latest version of the events library from GitHub. It is a great place to check the status of the library. Since this demo uses the vanilla code, it is a good idea to check the library functionality here for your own reference. If you're running into problems with the library, please check this demonstration using your device in the first instance. You can scan in the QR below to go directly to the web page:
![Demonstration QR Code](http://qrfree.kaywa.com/?l=1&s=8&d=http://lincweb.co.uk/labs/jquery-touch-events/demo/)
## 9. Requirements:
The library works with jQuery 1.7.0+. All major browsers have been tested without problem. The library is not compatible with jQuery < 1.7.
License:
--------
## 10. License:
Licensed under the MIT License:
Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:

View File

@ -552,13 +552,17 @@
'y': (settings.touch_capable) ? origEvent.touches[0].pageY - origEvent.touches[0].target.offsetTop : e.offsetY
},
'time': Date.now(),
'target': e.target
'target': e.target,
'identifier': origEvent.touches && origEvent.touches[0].identifier
};
}
// Store coordinates as finger is swiping
function touchMove(e) {
if (e.originalEvent.changedTouches && e.originalEvent.changedTouches && e.originalEvent.changedTouches[0].identifier !== startEvnt.identifier) {
return;
}
$this = $(e.currentTarget);
$this.data('callee2', arguments.callee);
finalCoord.x = (e.originalEvent.targetTouches) ? e.originalEvent.targetTouches[0].pageX : e.pageX;
@ -624,6 +628,9 @@
}
function touchEnd(e) {
if (e.originalEvent.changedTouches && e.originalEvent.changedTouches[0].identifier !== startEvnt.identifier) {
return;
}
$this = $(e.currentTarget);
var swipedir = "";
$this.data('callee3', arguments.callee);