tinycolor2
Advanced tools
Comparing version 0.9.9 to 0.9.16
{ | ||
"version": "0.9.9", | ||
"name" : "tinycolor2", | ||
"description" : "Fast Color Parsing and Manipulation", | ||
"url" : "http://bgrins.github.com/TinyColor", | ||
"version": "0.9.16", | ||
"name": "tinycolor2", | ||
"description": "Fast Color Parsing and Manipulation", | ||
"url": "http://bgrins.github.com/TinyColor", | ||
"repository": { | ||
@@ -10,8 +10,22 @@ "type": "git", | ||
}, | ||
"keywords" : ["color", "parser", "tinycolor"], | ||
"author" : "Brian Grinstead <briangrinstead@gmail.com> (http://briangrinstead.com)", | ||
"contributors" : [], | ||
"main" : "./tinycolor.js", | ||
"directories" : { }, | ||
"engines" : { "node": "*" } | ||
} | ||
"keywords": [ | ||
"color", | ||
"parser", | ||
"tinycolor" | ||
], | ||
"author": "Brian Grinstead <briangrinstead@gmail.com> (http://briangrinstead.com)", | ||
"contributors": [], | ||
"main": "./tinycolor.js", | ||
"directories": {}, | ||
"engines": { | ||
"node": "*" | ||
}, | ||
"devDependencies": { | ||
"grunt": "~0.4.1", | ||
"grunt-contrib-jshint": "~0.1.1", | ||
"grunt-contrib-qunit": "~0.2.2", | ||
"grunt-contrib-concat": "~0.1.3", | ||
"grunt-contrib-uglify": "~0.2.0", | ||
"grunt-docco": "~0.2.0" | ||
} | ||
} |
162
README.md
# TinyColor | ||
## JavaScript color parsing | ||
### Features | ||
* Color Types Supported | ||
* Hex | ||
* Hex, 8-digit (ARGB) Hex | ||
tinycolor("#000"); | ||
tinycolor("000"); | ||
tinycolor("#f0f0f6"); | ||
tinycolor("f0f0f6"); | ||
```js | ||
tinycolor("#000"); | ||
tinycolor("000"); | ||
tinycolor("#f0f0f6"); | ||
tinycolor("f0f0f6"); | ||
tinycolor("#88f0f0f6"); | ||
tinycolor("88f0f0f6"); | ||
``` | ||
* RGB, RGBA | ||
tinycolor("rgb (255, 0, 0)"); | ||
tinycolor("rgb 255 0 0"); | ||
tinycolor("rgba (255, 0, 0, .5)"); | ||
tinycolor({ r: 255, g: 0, b: 0 }); | ||
```js | ||
tinycolor("rgb (255, 0, 0)"); | ||
tinycolor("rgb 255 0 0"); | ||
tinycolor("rgba (255, 0, 0, .5)"); | ||
tinycolor({ r: 255, g: 0, b: 0 }); | ||
``` | ||
* HSL, HSLA | ||
tinycolor("hsl(0, 100%, 50%)"); | ||
tinycolor("hsla(0, 100%, 50%, .5)"); | ||
tinycolor("hsl(0, 100%, 50%)"); | ||
tinycolor("hsl 0 1.0 0.5"); | ||
tinycolor({ h: 0, s: 1, l: .5 }"); | ||
```js | ||
tinycolor("hsl(0, 100%, 50%)"); | ||
tinycolor("hsla(0, 100%, 50%, .5)"); | ||
tinycolor("hsl(0, 100%, 50%)"); | ||
tinycolor("hsl 0 1.0 0.5"); | ||
tinycolor({ h: 0, s: 1, l: .5 }); | ||
``` | ||
* HSV, HSVA | ||
tinycolor("hsv(0, 100%, 100%)"); | ||
tinycolor("hsva(0, 100%, 100%, .5)"); | ||
tinycolor("hsv (0 100% 100%)"); | ||
tinycolor("hsv 0 1 1"); | ||
tinycolor({ h: 0, s: 100, v: 100 }"); | ||
```js | ||
tinycolor("hsv(0, 100%, 100%)"); | ||
tinycolor("hsva(0, 100%, 100%, .5)"); | ||
tinycolor("hsv (0 100% 100%)"); | ||
tinycolor("hsv 0 1 1"); | ||
tinycolor({ h: 0, s: 100, v: 100 }); | ||
``` | ||
* Named | ||
tinycolor("RED"); | ||
tinycolor("blanchedalmond"); | ||
tinycolor("darkblue"); | ||
```js | ||
tinycolor("RED"); | ||
tinycolor("blanchedalmond"); | ||
tinycolor("darkblue"); | ||
``` | ||
* File Size: | ||
@@ -41,52 +60,75 @@ | ||
The uncompressed size is: | ||
### Usage | ||
var t = tinycolor("red"); | ||
t.toHex() // "ff0000" | ||
t.toHexString() // "#ff0000" | ||
t.toRgb() // {"r":255,"g":0,"b":0} or {"r":255,"g":0,"b":0,"a":0.5} | ||
t.toRgbString() // "rgb(255, 0, 0)" or "rgba(255, 0, 0, 0.5)" | ||
t.toHsv() // {"h":0,"s":1,"v":1} | ||
t.toHsvString() // "hsv(0, 100%, 100%)" | ||
t.toHsl() // {"h":0,"s":1,"l":0.5} | ||
t.toHslString() // "hsl(0, 100%, 50%)" | ||
t.toName() // "red" | ||
```js | ||
var t = tinycolor("red"); | ||
t.toHex() // "ff0000" | ||
t.toHexString() // "#ff0000" | ||
t.toHex8() // "ffff0000" | ||
t.toHex8String() // "#ffff0000" | ||
t.toRgb() // {"r":255,"g":0,"b":0} or {"r":255,"g":0,"b":0,"a":0.5} | ||
t.toRgbString() // "rgb(255, 0, 0)" or "rgba(255, 0, 0, 0.5)" | ||
t.toPercentageRgb() // {"r":100,"g":0,"b":0} or {"r":100,"g":0,"b":0,"a":0.5} | ||
t.toPercentageRgbString() // "rgb(100%, 0%, 0%)" or "rgba(100%, 0%, 0%, 0.5)" | ||
t.toHsv() // {"h":0,"s":1,"v":1} | ||
t.toHsvString() // "hsv(0, 100%, 100%)" | ||
t.toHsl() // {"h":0,"s":1,"l":0.5} | ||
t.toHslString() // "hsl(0, 100%, 50%)" | ||
t.toName() // "red" | ||
``` | ||
`tinycolor` may also be included as a [node](http://nodejs.org/) module like so: | ||
var tinycolor = require("./tinycolor"); | ||
``` | ||
npm install tinycolor2 | ||
``` | ||
Then it can be used: | ||
```js | ||
var tinycolor = require("./tinycolor"); | ||
``` | ||
### Accepted String Input | ||
The string parsing is very permissive. It is meant to make typing a color as input as easy as possible. All commas, percentages, parenthesis are optional, and most input allow either 0-1, 0%-100%, or 0-n (where n is either 100, 255, or 360 depending on the value). | ||
The string parsing is very permissive. It is meant to make typing a color as input as easy as possible. All commas, percentages, parenthesis are optional, and most input allow either 0-1, 0%-100%, or 0-n (where n is either 100, 255, or 360 depending on the value). | ||
HSL and HSV both require either 0%-100% or 0-1. RGB requires either 0-255 or 0%-100%. If you call tinycolor.fromRatio, any input can also accept 0-1 | ||
Here are some examples of string input: | ||
red | ||
#fff | ||
fff | ||
#ffffff | ||
ffffff | ||
rgb(255, 0, 0) | ||
rgb 255 0 0 | ||
hsl(0, 100, 50) | ||
hsl(0, 100%, 50%) | ||
hsl 0 100 50 | ||
hsl 0 100% 50% | ||
hsv(0, 100%, 100%) | ||
hsv(0, 100, 100) | ||
hsv 0 100% 100% | ||
hsv 0 100 100 | ||
``` | ||
red | ||
#fff | ||
fff | ||
#ffffff | ||
ffffff | ||
#ffffffff | ||
ffffffff | ||
rgb(255, 0, 0) | ||
rgb 255 0 0 | ||
hsl(0, 100, 50) | ||
hsl(0, 100%, 50%) | ||
hsl 0 100 50 | ||
hsl 0 100% 50% | ||
hsv(0, 100%, 100%) | ||
hsv(0, 100, 100) | ||
hsv 0 100% 100% | ||
hsv 0 100 100 | ||
``` | ||
### Accepted Object Input | ||
If you are calling this from code, you may want to use object input. Here are examples of the different types of accepted object inputs: | ||
{ r: 255, g: 0, b: 0 } | ||
{ r: 255, g: 0, b: 0, a: .5 } | ||
{ r: 1, g: 0, b: 0 } | ||
{ h: 0, s: 100, l: 50 } | ||
{ h: 0, s: 100, v: 100 } | ||
etc... | ||
```js | ||
{ r: 255, g: 0, b: 0 } | ||
{ r: 255, g: 0, b: 0, a: .5 } | ||
{ r: 1, g: 0, b: 0 } | ||
{ h: 0, s: 100, l: 50 } | ||
{ h: 0, s: 100, v: 100 } | ||
// etc... | ||
``` | ||
See index.html in the project for a demo. | ||
See [index.html](https://github.com/bgrins/TinyColor/blob/master/index.html) in the project for a demo. |
2288
test/qunit.js
/** | ||
* QUnit - A JavaScript Unit Testing Framework | ||
* QUnit v1.11.0 - A JavaScript Unit Testing Framework | ||
* | ||
* http://docs.jquery.com/QUnit | ||
* http://qunitjs.com | ||
* | ||
* Copyright (c) 2011 John Resig, Jörn Zaefferer | ||
* Dual licensed under the MIT (MIT-LICENSE.txt) | ||
* or GPL (GPL-LICENSE.txt) licenses. | ||
* Pulled Live from Git Wed Jun 29 17:45:01 UTC 2011 | ||
* Last Commit: b061e22c54f548fa2a768f14af5876c81ace5d09 | ||
* Copyright 2012 jQuery Foundation and other contributors | ||
* Released under the MIT license. | ||
* http://jquery.org/license | ||
*/ | ||
(function(window) { | ||
(function( window ) { | ||
var defined = { | ||
setTimeout: typeof window.setTimeout !== "undefined", | ||
sessionStorage: (function() { | ||
try { | ||
return !!sessionStorage.getItem; | ||
} catch(e){ | ||
return false; | ||
var QUnit, | ||
assert, | ||
config, | ||
onErrorFnPrev, | ||
testId = 0, | ||
fileName = (sourceFromStacktrace( 0 ) || "" ).replace(/(:\d+)+\)?/, "").replace(/.+\//, ""), | ||
toString = Object.prototype.toString, | ||
hasOwn = Object.prototype.hasOwnProperty, | ||
// Keep a local reference to Date (GH-283) | ||
Date = window.Date, | ||
defined = { | ||
setTimeout: typeof window.setTimeout !== "undefined", | ||
sessionStorage: (function() { | ||
var x = "qunit-test-string"; | ||
try { | ||
sessionStorage.setItem( x, x ); | ||
sessionStorage.removeItem( x ); | ||
return true; | ||
} catch( e ) { | ||
return false; | ||
} | ||
}()) | ||
}, | ||
/** | ||
* Provides a normalized error string, correcting an issue | ||
* with IE 7 (and prior) where Error.prototype.toString is | ||
* not properly implemented | ||
* | ||
* Based on http://es5.github.com/#x15.11.4.4 | ||
* | ||
* @param {String|Error} error | ||
* @return {String} error message | ||
*/ | ||
errorString = function( error ) { | ||
var name, message, | ||
errorString = error.toString(); | ||
if ( errorString.substring( 0, 7 ) === "[object" ) { | ||
name = error.name ? error.name.toString() : "Error"; | ||
message = error.message ? error.message.toString() : ""; | ||
if ( name && message ) { | ||
return name + ": " + message; | ||
} else if ( name ) { | ||
return name; | ||
} else if ( message ) { | ||
return message; | ||
} else { | ||
return "Error"; | ||
} | ||
} else { | ||
return errorString; | ||
} | ||
})() | ||
}; | ||
}, | ||
/** | ||
* Makes a clone of an object using only Array or Object as base, | ||
* and copies over the own enumerable properties. | ||
* | ||
* @param {Object} obj | ||
* @return {Object} New object with only the own properties (recursively). | ||
*/ | ||
objectValues = function( obj ) { | ||
// Grunt 0.3.x uses an older version of jshint that still has jshint/jshint#392. | ||
/*jshint newcap: false */ | ||
var key, val, | ||
vals = QUnit.is( "array", obj ) ? [] : {}; | ||
for ( key in obj ) { | ||
if ( hasOwn.call( obj, key ) ) { | ||
val = obj[key]; | ||
vals[key] = val === Object(val) ? objectValues(val) : val; | ||
} | ||
} | ||
return vals; | ||
}; | ||
var testId = 0; | ||
function Test( settings ) { | ||
extend( this, settings ); | ||
this.assertions = []; | ||
this.testNumber = ++Test.count; | ||
} | ||
var Test = function(name, testName, expected, testEnvironmentArg, async, callback) { | ||
this.name = name; | ||
this.testName = testName; | ||
this.expected = expected; | ||
this.testEnvironmentArg = testEnvironmentArg; | ||
this.async = async; | ||
this.callback = callback; | ||
this.assertions = []; | ||
}; | ||
Test.count = 0; | ||
Test.prototype = { | ||
init: function() { | ||
var tests = id("qunit-tests"); | ||
if (tests) { | ||
var b = document.createElement("strong"); | ||
b.innerHTML = "Running " + this.name; | ||
var li = document.createElement("li"); | ||
li.appendChild( b ); | ||
li.className = "running"; | ||
li.id = this.id = "test-output" + testId++; | ||
var a, b, li, | ||
tests = id( "qunit-tests" ); | ||
if ( tests ) { | ||
b = document.createElement( "strong" ); | ||
b.innerHTML = this.nameHtml; | ||
// `a` initialized at top of scope | ||
a = document.createElement( "a" ); | ||
a.innerHTML = "Rerun"; | ||
a.href = QUnit.url({ testNumber: this.testNumber }); | ||
li = document.createElement( "li" ); | ||
li.appendChild( b ); | ||
li.appendChild( a ); | ||
li.className = "running"; | ||
li.id = this.id = "qunit-test-output" + testId++; | ||
tests.appendChild( li ); | ||
@@ -51,5 +118,5 @@ } | ||
setup: function() { | ||
if (this.module != config.previousModule) { | ||
if ( this.module !== config.previousModule ) { | ||
if ( config.previousModule ) { | ||
QUnit.moduleDone( { | ||
runLoggingCallbacks( "moduleDone", QUnit, { | ||
name: config.previousModule, | ||
@@ -59,23 +126,27 @@ failed: config.moduleStats.bad, | ||
total: config.moduleStats.all | ||
} ); | ||
}); | ||
} | ||
config.previousModule = this.module; | ||
config.moduleStats = { all: 0, bad: 0 }; | ||
QUnit.moduleStart( { | ||
runLoggingCallbacks( "moduleStart", QUnit, { | ||
name: this.module | ||
} ); | ||
}); | ||
} else if ( config.autorun ) { | ||
runLoggingCallbacks( "moduleStart", QUnit, { | ||
name: this.module | ||
}); | ||
} | ||
config.current = this; | ||
this.testEnvironment = extend({ | ||
setup: function() {}, | ||
teardown: function() {} | ||
}, this.moduleTestEnvironment); | ||
if (this.testEnvironmentArg) { | ||
extend(this.testEnvironment, this.testEnvironmentArg); | ||
} | ||
}, this.moduleTestEnvironment ); | ||
QUnit.testStart( { | ||
name: this.testName | ||
} ); | ||
this.started = +new Date(); | ||
runLoggingCallbacks( "testStart", QUnit, { | ||
name: this.testName, | ||
module: this.module | ||
}); | ||
@@ -86,13 +157,24 @@ // allow utility functions to access the current test environment | ||
if ( !config.pollution ) { | ||
saveGlobal(); | ||
} | ||
if ( config.notrycatch ) { | ||
this.testEnvironment.setup.call( this.testEnvironment ); | ||
return; | ||
} | ||
try { | ||
if ( !config.pollution ) { | ||
saveGlobal(); | ||
} | ||
this.testEnvironment.setup.call(this.testEnvironment); | ||
} catch(e) { | ||
QUnit.ok( false, "Setup failed on " + this.testName + ": " + e.message ); | ||
this.testEnvironment.setup.call( this.testEnvironment ); | ||
} catch( e ) { | ||
QUnit.pushFailure( "Setup failed on " + this.testName + ": " + ( e.message || e ), extractStacktrace( e, 1 ) ); | ||
} | ||
}, | ||
run: function() { | ||
config.current = this; | ||
var running = id( "qunit-testresult" ); | ||
if ( running ) { | ||
running.innerHTML = "Running: <br/>" + this.nameHtml; | ||
} | ||
if ( this.async ) { | ||
@@ -102,11 +184,17 @@ QUnit.stop(); | ||
this.callbackStarted = +new Date(); | ||
if ( config.notrycatch ) { | ||
this.callback.call(this.testEnvironment); | ||
this.callback.call( this.testEnvironment, QUnit.assert ); | ||
this.callbackRuntime = +new Date() - this.callbackStarted; | ||
return; | ||
} | ||
try { | ||
this.callback.call(this.testEnvironment); | ||
} catch(e) { | ||
fail("Test " + this.testName + " died, exception and test follows", e, this.callback); | ||
QUnit.ok( false, "Died on test #" + (this.assertions.length + 1) + ": " + e.message + " - " + QUnit.jsDump.parse(e) ); | ||
this.callback.call( this.testEnvironment, QUnit.assert ); | ||
this.callbackRuntime = +new Date() - this.callbackStarted; | ||
} catch( e ) { | ||
this.callbackRuntime = +new Date() - this.callbackStarted; | ||
QUnit.pushFailure( "Died on test #" + (this.assertions.length + 1) + " " + this.stack + ": " + ( e.message || e ), extractStacktrace( e, 0 ) ); | ||
// else next test will carry the responsibility | ||
@@ -117,3 +205,3 @@ saveGlobal(); | ||
if ( config.blocking ) { | ||
start(); | ||
QUnit.start(); | ||
} | ||
@@ -123,17 +211,35 @@ } | ||
teardown: function() { | ||
try { | ||
this.testEnvironment.teardown.call(this.testEnvironment); | ||
checkPollution(); | ||
} catch(e) { | ||
QUnit.ok( false, "Teardown failed on " + this.testName + ": " + e.message ); | ||
config.current = this; | ||
if ( config.notrycatch ) { | ||
if ( typeof this.callbackRuntime === "undefined" ) { | ||
this.callbackRuntime = +new Date() - this.callbackStarted; | ||
} | ||
this.testEnvironment.teardown.call( this.testEnvironment ); | ||
return; | ||
} else { | ||
try { | ||
this.testEnvironment.teardown.call( this.testEnvironment ); | ||
} catch( e ) { | ||
QUnit.pushFailure( "Teardown failed on " + this.testName + ": " + ( e.message || e ), extractStacktrace( e, 1 ) ); | ||
} | ||
} | ||
checkPollution(); | ||
}, | ||
finish: function() { | ||
if ( this.expected && this.expected != this.assertions.length ) { | ||
QUnit.ok( false, "Expected " + this.expected + " assertions, but " + this.assertions.length + " were run" ); | ||
config.current = this; | ||
if ( config.requireExpects && this.expected === null ) { | ||
QUnit.pushFailure( "Expected number of assertions to be defined, but expect() was not called.", this.stack ); | ||
} else if ( this.expected !== null && this.expected !== this.assertions.length ) { | ||
QUnit.pushFailure( "Expected " + this.expected + " assertions, but " + this.assertions.length + " were run", this.stack ); | ||
} else if ( this.expected === null && !this.assertions.length ) { | ||
QUnit.pushFailure( "Expected at least one assertion, but none were run - call expect(0) to accept zero assertions.", this.stack ); | ||
} | ||
var good = 0, bad = 0, | ||
tests = id("qunit-tests"); | ||
var i, assertion, a, b, time, li, ol, | ||
test = this, | ||
good = 0, | ||
bad = 0, | ||
tests = id( "qunit-tests" ); | ||
this.runtime = +new Date() - this.started; | ||
config.stats.all += this.assertions.length; | ||
@@ -143,10 +249,11 @@ config.moduleStats.all += this.assertions.length; | ||
if ( tests ) { | ||
var ol = document.createElement("ol"); | ||
ol = document.createElement( "ol" ); | ||
ol.className = "qunit-assert-list"; | ||
for ( var i = 0; i < this.assertions.length; i++ ) { | ||
var assertion = this.assertions[i]; | ||
for ( i = 0; i < this.assertions.length; i++ ) { | ||
assertion = this.assertions[i]; | ||
var li = document.createElement("li"); | ||
li = document.createElement( "li" ); | ||
li.className = assertion.result ? "pass" : "fail"; | ||
li.innerHTML = assertion.message || (assertion.result ? "okay" : "failed"); | ||
li.innerHTML = assertion.message || ( assertion.result ? "okay" : "failed" ); | ||
ol.appendChild( li ); | ||
@@ -165,45 +272,50 @@ | ||
if ( QUnit.config.reorder && defined.sessionStorage ) { | ||
if (bad) { | ||
sessionStorage.setItem("qunit-" + this.module + "-" + this.testName, bad); | ||
if ( bad ) { | ||
sessionStorage.setItem( "qunit-test-" + this.module + "-" + this.testName, bad ); | ||
} else { | ||
sessionStorage.removeItem("qunit-" + this.module + "-" + this.testName); | ||
sessionStorage.removeItem( "qunit-test-" + this.module + "-" + this.testName ); | ||
} | ||
} | ||
if (bad == 0) { | ||
ol.style.display = "none"; | ||
if ( bad === 0 ) { | ||
addClass( ol, "qunit-collapsed" ); | ||
} | ||
var b = document.createElement("strong"); | ||
b.innerHTML = this.name + " <b class='counts'>(<b class='failed'>" + bad + "</b>, <b class='passed'>" + good + "</b>, " + this.assertions.length + ")</b>"; | ||
// `b` initialized at top of scope | ||
b = document.createElement( "strong" ); | ||
b.innerHTML = this.nameHtml + " <b class='counts'>(<b class='failed'>" + bad + "</b>, <b class='passed'>" + good + "</b>, " + this.assertions.length + ")</b>"; | ||
var a = document.createElement("a"); | ||
a.innerHTML = "Rerun"; | ||
a.href = QUnit.url({ filter: getText([b]).replace(/\([^)]+\)$/, "").replace(/(^\s*|\s*$)/g, "") }); | ||
addEvent(b, "click", function() { | ||
var next = b.nextSibling.nextSibling, | ||
display = next.style.display; | ||
next.style.display = display === "none" ? "block" : "none"; | ||
var next = b.parentNode.lastChild, | ||
collapsed = hasClass( next, "qunit-collapsed" ); | ||
( collapsed ? removeClass : addClass )( next, "qunit-collapsed" ); | ||
}); | ||
addEvent(b, "dblclick", function(e) { | ||
addEvent(b, "dblclick", function( e ) { | ||
var target = e && e.target ? e.target : window.event.srcElement; | ||
if ( target.nodeName.toLowerCase() == "span" || target.nodeName.toLowerCase() == "b" ) { | ||
if ( target.nodeName.toLowerCase() === "span" || target.nodeName.toLowerCase() === "b" ) { | ||
target = target.parentNode; | ||
} | ||
if ( window.location && target.nodeName.toLowerCase() === "strong" ) { | ||
window.location = QUnit.url({ filter: getText([target]).replace(/\([^)]+\)$/, "").replace(/(^\s*|\s*$)/g, "") }); | ||
window.location = QUnit.url({ testNumber: test.testNumber }); | ||
} | ||
}); | ||
var li = id(this.id); | ||
// `time` initialized at top of scope | ||
time = document.createElement( "span" ); | ||
time.className = "runtime"; | ||
time.innerHTML = this.runtime + " ms"; | ||
// `li` initialized at top of scope | ||
li = id( this.id ); | ||
li.className = bad ? "fail" : "pass"; | ||
li.removeChild( li.firstChild ); | ||
a = li.firstChild; | ||
li.appendChild( b ); | ||
li.appendChild( a ); | ||
li.appendChild( time ); | ||
li.appendChild( ol ); | ||
} else { | ||
for ( var i = 0; i < this.assertions.length; i++ ) { | ||
for ( i = 0; i < this.assertions.length; i++ ) { | ||
if ( !this.assertions[i].result ) { | ||
@@ -217,18 +329,20 @@ bad++; | ||
try { | ||
QUnit.reset(); | ||
} catch(e) { | ||
fail("reset() failed, following Test " + this.testName + ", exception and reset fn follows", e, QUnit.reset); | ||
} | ||
QUnit.testDone( { | ||
runLoggingCallbacks( "testDone", QUnit, { | ||
name: this.testName, | ||
module: this.module, | ||
failed: bad, | ||
passed: this.assertions.length - bad, | ||
total: this.assertions.length | ||
} ); | ||
total: this.assertions.length, | ||
duration: this.runtime | ||
}); | ||
QUnit.reset(); | ||
config.current = undefined; | ||
}, | ||
queue: function() { | ||
var test = this; | ||
var bad, | ||
test = this; | ||
synchronize(function() { | ||
@@ -252,32 +366,39 @@ test.init(); | ||
} | ||
// `bad` initialized at top of scope | ||
// defer when previous test run passed, if storage is available | ||
var bad = QUnit.config.reorder && defined.sessionStorage && +sessionStorage.getItem("qunit-" + this.module + "-" + this.testName); | ||
if (bad) { | ||
bad = QUnit.config.reorder && defined.sessionStorage && | ||
+sessionStorage.getItem( "qunit-test-" + this.module + "-" + this.testName ); | ||
if ( bad ) { | ||
run(); | ||
} else { | ||
synchronize(run); | ||
}; | ||
synchronize( run, true ); | ||
} | ||
} | ||
}; | ||
var QUnit = { | ||
// Root QUnit object. | ||
// `QUnit` initialized at top of scope | ||
QUnit = { | ||
// call on start of module test to prepend name to all tests | ||
module: function(name, testEnvironment) { | ||
module: function( name, testEnvironment ) { | ||
config.currentModule = name; | ||
config.currentModuleTestEnviroment = testEnvironment; | ||
config.currentModuleTestEnvironment = testEnvironment; | ||
config.modules[name] = true; | ||
}, | ||
asyncTest: function(testName, expected, callback) { | ||
asyncTest: function( testName, expected, callback ) { | ||
if ( arguments.length === 2 ) { | ||
callback = expected; | ||
expected = 0; | ||
expected = null; | ||
} | ||
QUnit.test(testName, expected, callback, true); | ||
QUnit.test( testName, expected, callback, true ); | ||
}, | ||
test: function(testName, expected, callback, async) { | ||
var name = '<span class="test-name">' + testName + '</span>', testEnvironmentArg; | ||
test: function( testName, expected, callback, async ) { | ||
var test, | ||
nameHtml = "<span class='test-name'>" + escapeText( testName ) + "</span>"; | ||
@@ -288,43 +409,133 @@ if ( arguments.length === 2 ) { | ||
} | ||
// is 2nd argument a testEnvironment? | ||
if ( expected && typeof expected === 'object') { | ||
testEnvironmentArg = expected; | ||
expected = null; | ||
} | ||
if ( config.currentModule ) { | ||
name = '<span class="module-name">' + config.currentModule + "</span>: " + name; | ||
nameHtml = "<span class='module-name'>" + escapeText( config.currentModule ) + "</span>: " + nameHtml; | ||
} | ||
if ( !validTest(config.currentModule + ": " + testName) ) { | ||
test = new Test({ | ||
nameHtml: nameHtml, | ||
testName: testName, | ||
expected: expected, | ||
async: async, | ||
callback: callback, | ||
module: config.currentModule, | ||
moduleTestEnvironment: config.currentModuleTestEnvironment, | ||
stack: sourceFromStacktrace( 2 ) | ||
}); | ||
if ( !validTest( test ) ) { | ||
return; | ||
} | ||
var test = new Test(name, testName, expected, testEnvironmentArg, async, callback); | ||
test.module = config.currentModule; | ||
test.moduleTestEnvironment = config.currentModuleTestEnviroment; | ||
test.queue(); | ||
}, | ||
/** | ||
* Specify the number of expected assertions to gurantee that failed test (no assertions are run at all) don't slip through. | ||
*/ | ||
expect: function(asserts) { | ||
config.current.expected = asserts; | ||
// Specify the number of expected assertions to gurantee that failed test (no assertions are run at all) don't slip through. | ||
expect: function( asserts ) { | ||
if (arguments.length === 1) { | ||
config.current.expected = asserts; | ||
} else { | ||
return config.current.expected; | ||
} | ||
}, | ||
start: function( count ) { | ||
// QUnit hasn't been initialized yet. | ||
// Note: RequireJS (et al) may delay onLoad | ||
if ( config.semaphore === undefined ) { | ||
QUnit.begin(function() { | ||
// This is triggered at the top of QUnit.load, push start() to the event loop, to allow QUnit.load to finish first | ||
setTimeout(function() { | ||
QUnit.start( count ); | ||
}); | ||
}); | ||
return; | ||
} | ||
config.semaphore -= count || 1; | ||
// don't start until equal number of stop-calls | ||
if ( config.semaphore > 0 ) { | ||
return; | ||
} | ||
// ignore if start is called more often then stop | ||
if ( config.semaphore < 0 ) { | ||
config.semaphore = 0; | ||
QUnit.pushFailure( "Called start() while already started (QUnit.config.semaphore was 0 already)", null, sourceFromStacktrace(2) ); | ||
return; | ||
} | ||
// A slight delay, to avoid any current callbacks | ||
if ( defined.setTimeout ) { | ||
window.setTimeout(function() { | ||
if ( config.semaphore > 0 ) { | ||
return; | ||
} | ||
if ( config.timeout ) { | ||
clearTimeout( config.timeout ); | ||
} | ||
config.blocking = false; | ||
process( true ); | ||
}, 13); | ||
} else { | ||
config.blocking = false; | ||
process( true ); | ||
} | ||
}, | ||
stop: function( count ) { | ||
config.semaphore += count || 1; | ||
config.blocking = true; | ||
if ( config.testTimeout && defined.setTimeout ) { | ||
clearTimeout( config.timeout ); | ||
config.timeout = window.setTimeout(function() { | ||
QUnit.ok( false, "Test timed out" ); | ||
config.semaphore = 1; | ||
QUnit.start(); | ||
}, config.testTimeout ); | ||
} | ||
} | ||
}; | ||
// `assert` initialized at top of scope | ||
// Asssert helpers | ||
// All of these must either call QUnit.push() or manually do: | ||
// - runLoggingCallbacks( "log", .. ); | ||
// - config.current.assertions.push({ .. }); | ||
// We attach it to the QUnit object *after* we expose the public API, | ||
// otherwise `assert` will become a global variable in browsers (#341). | ||
assert = { | ||
/** | ||
* Asserts true. | ||
* Asserts rough true-ish result. | ||
* @name ok | ||
* @function | ||
* @example ok( "asdfasdf".length > 5, "There must be at least 5 chars" ); | ||
*/ | ||
ok: function(a, msg) { | ||
a = !!a; | ||
var details = { | ||
result: a, | ||
message: msg | ||
}; | ||
msg = escapeHtml(msg); | ||
QUnit.log(details); | ||
ok: function( result, msg ) { | ||
if ( !config.current ) { | ||
throw new Error( "ok() assertion outside test context, was " + sourceFromStacktrace(2) ); | ||
} | ||
result = !!result; | ||
var source, | ||
details = { | ||
module: config.current.module, | ||
name: config.current.testName, | ||
result: result, | ||
message: msg | ||
}; | ||
msg = escapeText( msg || (result ? "okay" : "failed" ) ); | ||
msg = "<span class='test-message'>" + msg + "</span>"; | ||
if ( !result ) { | ||
source = sourceFromStacktrace( 2 ); | ||
if ( source ) { | ||
details.source = source; | ||
msg += "<table><tr class='test-source'><th>Source: </th><td><pre>" + escapeText( source ) + "</pre></td></tr></table>"; | ||
} | ||
} | ||
runLoggingCallbacks( "log", QUnit, details ); | ||
config.current.assertions.push({ | ||
result: a, | ||
result: result, | ||
message: msg | ||
@@ -335,41 +546,81 @@ }); | ||
/** | ||
* Checks that the first two arguments are equal, with an optional message. | ||
* Assert that the first two arguments are equal, with an optional message. | ||
* Prints out both actual and expected values. | ||
* | ||
* Prefered to ok( actual == expected, message ) | ||
* | ||
* @example equal( format("Received {0} bytes.", 2), "Received 2 bytes." ); | ||
* | ||
* @param Object actual | ||
* @param Object expected | ||
* @param String message (optional) | ||
* @name equal | ||
* @function | ||
* @example equal( format( "Received {0} bytes.", 2), "Received 2 bytes.", "format() replaces {0} with next argument" ); | ||
*/ | ||
equal: function(actual, expected, message) { | ||
QUnit.push(expected == actual, actual, expected, message); | ||
equal: function( actual, expected, message ) { | ||
/*jshint eqeqeq:false */ | ||
QUnit.push( expected == actual, actual, expected, message ); | ||
}, | ||
notEqual: function(actual, expected, message) { | ||
QUnit.push(expected != actual, actual, expected, message); | ||
/** | ||
* @name notEqual | ||
* @function | ||
*/ | ||
notEqual: function( actual, expected, message ) { | ||
/*jshint eqeqeq:false */ | ||
QUnit.push( expected != actual, actual, expected, message ); | ||
}, | ||
deepEqual: function(actual, expected, message) { | ||
QUnit.push(QUnit.equiv(actual, expected), actual, expected, message); | ||
/** | ||
* @name propEqual | ||
* @function | ||
*/ | ||
propEqual: function( actual, expected, message ) { | ||
actual = objectValues(actual); | ||
expected = objectValues(expected); | ||
QUnit.push( QUnit.equiv(actual, expected), actual, expected, message ); | ||
}, | ||
notDeepEqual: function(actual, expected, message) { | ||
QUnit.push(!QUnit.equiv(actual, expected), actual, expected, message); | ||
/** | ||
* @name notPropEqual | ||
* @function | ||
*/ | ||
notPropEqual: function( actual, expected, message ) { | ||
actual = objectValues(actual); | ||
expected = objectValues(expected); | ||
QUnit.push( !QUnit.equiv(actual, expected), actual, expected, message ); | ||
}, | ||
strictEqual: function(actual, expected, message) { | ||
QUnit.push(expected === actual, actual, expected, message); | ||
/** | ||
* @name deepEqual | ||
* @function | ||
*/ | ||
deepEqual: function( actual, expected, message ) { | ||
QUnit.push( QUnit.equiv(actual, expected), actual, expected, message ); | ||
}, | ||
notStrictEqual: function(actual, expected, message) { | ||
QUnit.push(expected !== actual, actual, expected, message); | ||
/** | ||
* @name notDeepEqual | ||
* @function | ||
*/ | ||
notDeepEqual: function( actual, expected, message ) { | ||
QUnit.push( !QUnit.equiv(actual, expected), actual, expected, message ); | ||
}, | ||
raises: function(block, expected, message) { | ||
var actual, ok = false; | ||
/** | ||
* @name strictEqual | ||
* @function | ||
*/ | ||
strictEqual: function( actual, expected, message ) { | ||
QUnit.push( expected === actual, actual, expected, message ); | ||
}, | ||
if (typeof expected === 'string') { | ||
/** | ||
* @name notStrictEqual | ||
* @function | ||
*/ | ||
notStrictEqual: function( actual, expected, message ) { | ||
QUnit.push( expected !== actual, actual, expected, message ); | ||
}, | ||
"throws": function( block, expected, message ) { | ||
var actual, | ||
expectedOutput = expected, | ||
ok = false; | ||
// 'expected' is optional | ||
if ( typeof expected === "string" ) { | ||
message = expected; | ||
@@ -379,73 +630,73 @@ expected = null; | ||
config.current.ignoreGlobalErrors = true; | ||
try { | ||
block(); | ||
block.call( config.current.testEnvironment ); | ||
} catch (e) { | ||
actual = e; | ||
} | ||
config.current.ignoreGlobalErrors = false; | ||
if (actual) { | ||
if ( actual ) { | ||
// we don't want to validate thrown error | ||
if (!expected) { | ||
if ( !expected ) { | ||
ok = true; | ||
expectedOutput = null; | ||
// expected is a regexp | ||
} else if (QUnit.objectType(expected) === "regexp") { | ||
ok = expected.test(actual); | ||
} else if ( QUnit.objectType( expected ) === "regexp" ) { | ||
ok = expected.test( errorString( actual ) ); | ||
// expected is a constructor | ||
} else if (actual instanceof expected) { | ||
} else if ( actual instanceof expected ) { | ||
ok = true; | ||
// expected is a validation function which returns true is validation passed | ||
} else if (expected.call({}, actual) === true) { | ||
} else if ( expected.call( {}, actual ) === true ) { | ||
expectedOutput = null; | ||
ok = true; | ||
} | ||
} | ||
QUnit.ok(ok, message); | ||
}, | ||
start: function() { | ||
config.semaphore--; | ||
if (config.semaphore > 0) { | ||
// don't start until equal number of stop-calls | ||
return; | ||
} | ||
if (config.semaphore < 0) { | ||
// ignore if start is called more often then stop | ||
config.semaphore = 0; | ||
} | ||
// A slight delay, to avoid any current callbacks | ||
if ( defined.setTimeout ) { | ||
window.setTimeout(function() { | ||
if ( config.timeout ) { | ||
clearTimeout(config.timeout); | ||
} | ||
config.blocking = false; | ||
process(); | ||
}, 13); | ||
QUnit.push( ok, actual, expectedOutput, message ); | ||
} else { | ||
config.blocking = false; | ||
process(); | ||
QUnit.pushFailure( message, null, 'No exception was thrown.' ); | ||
} | ||
}, | ||
} | ||
}; | ||
stop: function(timeout) { | ||
config.semaphore++; | ||
config.blocking = true; | ||
/** | ||
* @deprecate since 1.8.0 | ||
* Kept assertion helpers in root for backwards compatibility. | ||
*/ | ||
extend( QUnit, assert ); | ||
if ( timeout && defined.setTimeout ) { | ||
clearTimeout(config.timeout); | ||
config.timeout = window.setTimeout(function() { | ||
QUnit.ok( false, "Test timed out" ); | ||
QUnit.start(); | ||
}, timeout); | ||
} | ||
} | ||
/** | ||
* @deprecated since 1.9.0 | ||
* Kept root "raises()" for backwards compatibility. | ||
* (Note that we don't introduce assert.raises). | ||
*/ | ||
QUnit.raises = assert[ "throws" ]; | ||
/** | ||
* @deprecated since 1.0.0, replaced with error pushes since 1.3.0 | ||
* Kept to avoid TypeErrors for undefined methods. | ||
*/ | ||
QUnit.equals = function() { | ||
QUnit.push( false, false, false, "QUnit.equals has been deprecated since 2009 (e88049a0), use QUnit.equal instead" ); | ||
}; | ||
QUnit.same = function() { | ||
QUnit.push( false, false, false, "QUnit.same has been deprecated since 2009 (e88049a0), use QUnit.deepEqual instead" ); | ||
}; | ||
// Backwards compatibility, deprecated | ||
QUnit.equals = QUnit.equal; | ||
QUnit.same = QUnit.deepEqual; | ||
// We want access to the constructor's prototype | ||
(function() { | ||
function F() {} | ||
F.prototype = QUnit; | ||
QUnit = new F(); | ||
// Make F QUnit's constructor so that we can add to the prototype later | ||
QUnit.constructor = F; | ||
}()); | ||
// Maintain internal state | ||
var config = { | ||
/** | ||
* Config object: Maintain internal state | ||
* Later exposed as QUnit.config | ||
* `config` initialized at top of scope | ||
*/ | ||
config = { | ||
// The queue of tests to run | ||
@@ -457,2 +708,6 @@ queue: [], | ||
// when enabled, show only failing tests | ||
// gets persisted through sessionStorage and can be changed in UI via checkbox | ||
hidepassed: false, | ||
// by default, run previously failed tests first | ||
@@ -462,9 +717,49 @@ // very useful in combination with "Hide passed tests" checked | ||
noglobals: false, | ||
notrycatch: false | ||
// by default, modify document.title when suite is done | ||
altertitle: true, | ||
// when enabled, all tests must call expect() | ||
requireExpects: false, | ||
// add checkboxes that are persisted in the query-string | ||
// when enabled, the id is set to `true` as a `QUnit.config` property | ||
urlConfig: [ | ||
{ | ||
id: "noglobals", | ||
label: "Check for Globals", | ||
tooltip: "Enabling this will test if any test introduces new properties on the `window` object. Stored as query-strings." | ||
}, | ||
{ | ||
id: "notrycatch", | ||
label: "No try-catch", | ||
tooltip: "Enabling this will run tests outside of a try-catch block. Makes debugging exceptions in IE reasonable. Stored as query-strings." | ||
} | ||
], | ||
// Set of all modules. | ||
modules: {}, | ||
// logging callback queues | ||
begin: [], | ||
done: [], | ||
log: [], | ||
testStart: [], | ||
testDone: [], | ||
moduleStart: [], | ||
moduleDone: [] | ||
}; | ||
// Load paramaters | ||
// Export global variables, unless an 'exports' object exists, | ||
// in that case we assume we're in CommonJS (dealt with on the bottom of the script) | ||
if ( typeof exports === "undefined" ) { | ||
extend( window, QUnit ); | ||
// Expose QUnit object | ||
window.QUnit = QUnit; | ||
} | ||
// Initialize more QUnit.config and QUnit.urlParams | ||
(function() { | ||
var location = window.location || { search: "", protocol: "file:" }, | ||
var i, | ||
location = window.location || { search: "", protocol: "file:" }, | ||
params = location.search.slice( 1 ).split( "&" ), | ||
@@ -476,3 +771,3 @@ length = params.length, | ||
if ( params[ 0 ] ) { | ||
for ( var i = 0; i < length; i++ ) { | ||
for ( i = 0; i < length; i++ ) { | ||
current = params[ i ].split( "=" ); | ||
@@ -483,5 +778,2 @@ current[ 0 ] = decodeURIComponent( current[ 0 ] ); | ||
urlParams[ current[ 0 ] ] = current[ 1 ]; | ||
if ( current[ 0 ] in config ) { | ||
config[ current[ 0 ] ] = current[ 1 ]; | ||
} | ||
} | ||
@@ -491,20 +783,20 @@ } | ||
QUnit.urlParams = urlParams; | ||
// String search anywhere in moduleName+testName | ||
config.filter = urlParams.filter; | ||
// Exact match of the module name | ||
config.module = urlParams.module; | ||
config.testNumber = parseInt( urlParams.testNumber, 10 ) || null; | ||
// Figure out if we're running the tests from a server or not | ||
QUnit.isLocal = !!(location.protocol === 'file:'); | ||
})(); | ||
QUnit.isLocal = location.protocol === "file:"; | ||
}()); | ||
// Expose the API as global variables, unless an 'exports' | ||
// object exists, in that case we assume we're in CommonJS | ||
if ( typeof exports === "undefined" || typeof require === "undefined" ) { | ||
extend(window, QUnit); | ||
window.QUnit = QUnit; | ||
} else { | ||
extend(exports, QUnit); | ||
exports.QUnit = QUnit; | ||
} | ||
// Extend QUnit object, | ||
// these after set here because they should not be exposed as global functions | ||
extend( QUnit, { | ||
assert: assert, | ||
// define these after exposing globals to keep them in these QUnit namespace only | ||
extend(QUnit, { | ||
config: config, | ||
@@ -514,6 +806,6 @@ | ||
init: function() { | ||
extend(config, { | ||
extend( config, { | ||
stats: { all: 0, bad: 0 }, | ||
moduleStats: { all: 0, bad: 0 }, | ||
started: +new Date, | ||
started: +new Date(), | ||
updateRate: 1000, | ||
@@ -525,9 +817,21 @@ blocking: false, | ||
queue: [], | ||
semaphore: 0 | ||
semaphore: 1 | ||
}); | ||
var tests = id( "qunit-tests" ), | ||
banner = id( "qunit-banner" ), | ||
result = id( "qunit-testresult" ); | ||
var tests, banner, result, | ||
qunit = id( "qunit" ); | ||
if ( qunit ) { | ||
qunit.innerHTML = | ||
"<h1 id='qunit-header'>" + escapeText( document.title ) + "</h1>" + | ||
"<h2 id='qunit-banner'></h2>" + | ||
"<div id='qunit-testrunner-toolbar'></div>" + | ||
"<h2 id='qunit-userAgent'></h2>" + | ||
"<ol id='qunit-tests'></ol>"; | ||
} | ||
tests = id( "qunit-tests" ); | ||
banner = id( "qunit-banner" ); | ||
result = id( "qunit-testresult" ); | ||
if ( tests ) { | ||
@@ -550,39 +854,25 @@ tests.innerHTML = ""; | ||
tests.parentNode.insertBefore( result, tests ); | ||
result.innerHTML = 'Running...<br/> '; | ||
result.innerHTML = "Running...<br/> "; | ||
} | ||
}, | ||
/** | ||
* Resets the test setup. Useful for tests that modify the DOM. | ||
* | ||
* If jQuery is available, uses jQuery's html(), otherwise just innerHTML. | ||
*/ | ||
// Resets the test setup. Useful for tests that modify the DOM. | ||
reset: function() { | ||
if ( window.jQuery ) { | ||
jQuery( "#qunit-fixture" ).html( config.fixture ); | ||
} else { | ||
var main = id( 'qunit-fixture' ); | ||
if ( main ) { | ||
main.innerHTML = config.fixture; | ||
} | ||
var fixture = id( "qunit-fixture" ); | ||
if ( fixture ) { | ||
fixture.innerHTML = config.fixture; | ||
} | ||
}, | ||
/** | ||
* Trigger an event on an element. | ||
* | ||
* @example triggerEvent( document.body, "click" ); | ||
* | ||
* @param DOMElement elem | ||
* @param String type | ||
*/ | ||
// Trigger an event on an element. | ||
// @example triggerEvent( document.body, "click" ); | ||
triggerEvent: function( elem, type, event ) { | ||
if ( document.createEvent ) { | ||
event = document.createEvent("MouseEvents"); | ||
event = document.createEvent( "MouseEvents" ); | ||
event.initMouseEvent(type, true, true, elem.ownerDocument.defaultView, | ||
0, 0, 0, 0, 0, false, false, false, false, 0, null); | ||
elem.dispatchEvent( event ); | ||
} else if ( elem.fireEvent ) { | ||
elem.fireEvent("on"+type); | ||
elem.fireEvent( "on" + type ); | ||
} | ||
@@ -593,35 +883,33 @@ }, | ||
is: function( type, obj ) { | ||
return QUnit.objectType( obj ) == type; | ||
return QUnit.objectType( obj ) === type; | ||
}, | ||
objectType: function( obj ) { | ||
if (typeof obj === "undefined") { | ||
if ( typeof obj === "undefined" ) { | ||
return "undefined"; | ||
// consider: typeof null === object | ||
} | ||
if (obj === null) { | ||
if ( obj === null ) { | ||
return "null"; | ||
} | ||
var type = Object.prototype.toString.call( obj ) | ||
.match(/^\[object\s(.*)\]$/)[1] || ''; | ||
var match = toString.call( obj ).match(/^\[object\s(.*)\]$/), | ||
type = match && match[1] || ""; | ||
switch (type) { | ||
case 'Number': | ||
if (isNaN(obj)) { | ||
return "nan"; | ||
} else { | ||
return "number"; | ||
} | ||
case 'String': | ||
case 'Boolean': | ||
case 'Array': | ||
case 'Date': | ||
case 'RegExp': | ||
case 'Function': | ||
return type.toLowerCase(); | ||
switch ( type ) { | ||
case "Number": | ||
if ( isNaN(obj) ) { | ||
return "nan"; | ||
} | ||
return "number"; | ||
case "String": | ||
case "Boolean": | ||
case "Array": | ||
case "Date": | ||
case "RegExp": | ||
case "Function": | ||
return type.toLowerCase(); | ||
} | ||
if (typeof obj === "object") { | ||
return "object"; | ||
if ( typeof obj === "object" ) { | ||
return "object"; | ||
} | ||
@@ -631,29 +919,42 @@ return undefined; | ||
push: function(result, actual, expected, message) { | ||
var details = { | ||
result: result, | ||
message: message, | ||
actual: actual, | ||
expected: expected | ||
}; | ||
push: function( result, actual, expected, message ) { | ||
if ( !config.current ) { | ||
throw new Error( "assertion outside test context, was " + sourceFromStacktrace() ); | ||
} | ||
message = escapeHtml(message) || (result ? "okay" : "failed"); | ||
message = '<span class="test-message">' + message + "</span>"; | ||
expected = escapeHtml(QUnit.jsDump.parse(expected)); | ||
actual = escapeHtml(QUnit.jsDump.parse(actual)); | ||
var output = message + '<table><tr class="test-expected"><th>Expected: </th><td><pre>' + expected + '</pre></td></tr>'; | ||
if (actual != expected) { | ||
output += '<tr class="test-actual"><th>Result: </th><td><pre>' + actual + '</pre></td></tr>'; | ||
output += '<tr class="test-diff"><th>Diff: </th><td><pre>' + QUnit.diff(expected, actual) +'</pre></td></tr>'; | ||
} | ||
if (!result) { | ||
var source = sourceFromStacktrace(); | ||
if (source) { | ||
var output, source, | ||
details = { | ||
module: config.current.module, | ||
name: config.current.testName, | ||
result: result, | ||
message: message, | ||
actual: actual, | ||
expected: expected | ||
}; | ||
message = escapeText( message ) || ( result ? "okay" : "failed" ); | ||
message = "<span class='test-message'>" + message + "</span>"; | ||
output = message; | ||
if ( !result ) { | ||
expected = escapeText( QUnit.jsDump.parse(expected) ); | ||
actual = escapeText( QUnit.jsDump.parse(actual) ); | ||
output += "<table><tr class='test-expected'><th>Expected: </th><td><pre>" + expected + "</pre></td></tr>"; | ||
if ( actual !== expected ) { | ||
output += "<tr class='test-actual'><th>Result: </th><td><pre>" + actual + "</pre></td></tr>"; | ||
output += "<tr class='test-diff'><th>Diff: </th><td><pre>" + QUnit.diff( expected, actual ) + "</pre></td></tr>"; | ||
} | ||
source = sourceFromStacktrace(); | ||
if ( source ) { | ||
details.source = source; | ||
output += '<tr class="test-source"><th>Source: </th><td><pre>' + escapeHtml(source) + '</pre></td></tr>'; | ||
output += "<tr class='test-source'><th>Source: </th><td><pre>" + escapeText( source ) + "</pre></td></tr>"; | ||
} | ||
output += "</table>"; | ||
} | ||
output += "</table>"; | ||
QUnit.log(details); | ||
runLoggingCallbacks( "log", QUnit, details ); | ||
@@ -666,28 +967,92 @@ config.current.assertions.push({ | ||
pushFailure: function( message, source, actual ) { | ||
if ( !config.current ) { | ||
throw new Error( "pushFailure() assertion outside test context, was " + sourceFromStacktrace(2) ); | ||
} | ||
var output, | ||
details = { | ||
module: config.current.module, | ||
name: config.current.testName, | ||
result: false, | ||
message: message | ||
}; | ||
message = escapeText( message ) || "error"; | ||
message = "<span class='test-message'>" + message + "</span>"; | ||
output = message; | ||
output += "<table>"; | ||
if ( actual ) { | ||
output += "<tr class='test-actual'><th>Result: </th><td><pre>" + escapeText( actual ) + "</pre></td></tr>"; | ||
} | ||
if ( source ) { | ||
details.source = source; | ||
output += "<tr class='test-source'><th>Source: </th><td><pre>" + escapeText( source ) + "</pre></td></tr>"; | ||
} | ||
output += "</table>"; | ||
runLoggingCallbacks( "log", QUnit, details ); | ||
config.current.assertions.push({ | ||
result: false, | ||
message: output | ||
}); | ||
}, | ||
url: function( params ) { | ||
params = extend( extend( {}, QUnit.urlParams ), params ); | ||
var querystring = "?", | ||
key; | ||
var key, | ||
querystring = "?"; | ||
for ( key in params ) { | ||
if ( !hasOwn.call( params, key ) ) { | ||
continue; | ||
} | ||
querystring += encodeURIComponent( key ) + "=" + | ||
encodeURIComponent( params[ key ] ) + "&"; | ||
} | ||
return window.location.pathname + querystring.slice( 0, -1 ); | ||
return window.location.protocol + "//" + window.location.host + | ||
window.location.pathname + querystring.slice( 0, -1 ); | ||
}, | ||
extend: extend, | ||
id: id, | ||
addEvent: addEvent | ||
// load, equiv, jsDump, diff: Attached later | ||
}); | ||
/** | ||
* @deprecated: Created for backwards compatibility with test runner that set the hook function | ||
* into QUnit.{hook}, instead of invoking it and passing the hook function. | ||
* QUnit.constructor is set to the empty F() above so that we can add to it's prototype here. | ||
* Doing this allows us to tell if the following methods have been overwritten on the actual | ||
* QUnit object. | ||
*/ | ||
extend( QUnit.constructor.prototype, { | ||
// Logging callbacks; all receive a single argument with the listed properties | ||
// run test/logs.html for any related changes | ||
begin: function() {}, | ||
begin: registerLoggingCallback( "begin" ), | ||
// done: { failed, passed, total, runtime } | ||
done: function() {}, | ||
done: registerLoggingCallback( "done" ), | ||
// log: { result, actual, expected, message } | ||
log: function() {}, | ||
log: registerLoggingCallback( "log" ), | ||
// testStart: { name } | ||
testStart: function() {}, | ||
// testDone: { name, failed, passed, total } | ||
testDone: function() {}, | ||
testStart: registerLoggingCallback( "testStart" ), | ||
// testDone: { name, failed, passed, total, duration } | ||
testDone: registerLoggingCallback( "testDone" ), | ||
// moduleStart: { name } | ||
moduleStart: function() {}, | ||
moduleStart: registerLoggingCallback( "moduleStart" ), | ||
// moduleDone: { name, failed, passed, total } | ||
moduleDone: function() {} | ||
moduleDone: registerLoggingCallback( "moduleDone" ) | ||
}); | ||
@@ -699,7 +1064,13 @@ | ||
addEvent(window, "load", function() { | ||
QUnit.begin({}); | ||
QUnit.load = function() { | ||
runLoggingCallbacks( "begin", QUnit, {} ); | ||
// Initialize the config, saving the execution queue | ||
var oldconfig = extend({}, config); | ||
var banner, filter, i, label, len, main, ol, toolbar, userAgent, val, | ||
urlConfigCheckboxesContainer, urlConfigCheckboxes, moduleFilter, | ||
numModules = 0, | ||
moduleFilterHtml = "", | ||
urlConfigHtml = "", | ||
oldconfig = extend( {}, config ); | ||
QUnit.init(); | ||
@@ -710,42 +1081,79 @@ extend(config, oldconfig); | ||
var userAgent = id("qunit-userAgent"); | ||
len = config.urlConfig.length; | ||
for ( i = 0; i < len; i++ ) { | ||
val = config.urlConfig[i]; | ||
if ( typeof val === "string" ) { | ||
val = { | ||
id: val, | ||
label: val, | ||
tooltip: "[no tooltip available]" | ||
}; | ||
} | ||
config[ val.id ] = QUnit.urlParams[ val.id ]; | ||
urlConfigHtml += "<input id='qunit-urlconfig-" + escapeText( val.id ) + | ||
"' name='" + escapeText( val.id ) + | ||
"' type='checkbox'" + ( config[ val.id ] ? " checked='checked'" : "" ) + | ||
" title='" + escapeText( val.tooltip ) + | ||
"'><label for='qunit-urlconfig-" + escapeText( val.id ) + | ||
"' title='" + escapeText( val.tooltip ) + "'>" + val.label + "</label>"; | ||
} | ||
moduleFilterHtml += "<label for='qunit-modulefilter'>Module: </label><select id='qunit-modulefilter' name='modulefilter'><option value='' " + | ||
( config.module === undefined ? "selected='selected'" : "" ) + | ||
">< All Modules ></option>"; | ||
for ( i in config.modules ) { | ||
if ( config.modules.hasOwnProperty( i ) ) { | ||
numModules += 1; | ||
moduleFilterHtml += "<option value='" + escapeText( encodeURIComponent(i) ) + "' " + | ||
( config.module === i ? "selected='selected'" : "" ) + | ||
">" + escapeText(i) + "</option>"; | ||
} | ||
} | ||
moduleFilterHtml += "</select>"; | ||
// `userAgent` initialized at top of scope | ||
userAgent = id( "qunit-userAgent" ); | ||
if ( userAgent ) { | ||
userAgent.innerHTML = navigator.userAgent; | ||
} | ||
var banner = id("qunit-header"); | ||
// `banner` initialized at top of scope | ||
banner = id( "qunit-header" ); | ||
if ( banner ) { | ||
banner.innerHTML = '<a href="' + QUnit.url({ filter: undefined }) + '"> ' + banner.innerHTML + '</a> ' + | ||
'<label><input name="noglobals" type="checkbox"' + ( config.noglobals ? ' checked="checked"' : '' ) + '>noglobals</label>' + | ||
'<label><input name="notrycatch" type="checkbox"' + ( config.notrycatch ? ' checked="checked"' : '' ) + '>notrycatch</label>'; | ||
addEvent( banner, "change", function( event ) { | ||
var params = {}; | ||
params[ event.target.name ] = event.target.checked ? true : undefined; | ||
window.location = QUnit.url( params ); | ||
}); | ||
banner.innerHTML = "<a href='" + QUnit.url({ filter: undefined, module: undefined, testNumber: undefined }) + "'>" + banner.innerHTML + "</a> "; | ||
} | ||
var toolbar = id("qunit-testrunner-toolbar"); | ||
// `toolbar` initialized at top of scope | ||
toolbar = id( "qunit-testrunner-toolbar" ); | ||
if ( toolbar ) { | ||
var filter = document.createElement("input"); | ||
// `filter` initialized at top of scope | ||
filter = document.createElement( "input" ); | ||
filter.type = "checkbox"; | ||
filter.id = "qunit-filter-pass"; | ||
addEvent( filter, "click", function() { | ||
var ol = document.getElementById("qunit-tests"); | ||
var tmp, | ||
ol = document.getElementById( "qunit-tests" ); | ||
if ( filter.checked ) { | ||
ol.className = ol.className + " hidepass"; | ||
} else { | ||
var tmp = " " + ol.className.replace( /[\n\t\r]/g, " " ) + " "; | ||
ol.className = tmp.replace(/ hidepass /, " "); | ||
tmp = " " + ol.className.replace( /[\n\t\r]/g, " " ) + " "; | ||
ol.className = tmp.replace( / hidepass /, " " ); | ||
} | ||
if ( defined.sessionStorage ) { | ||
if (filter.checked) { | ||
sessionStorage.setItem("qunit-filter-passed-tests", "true"); | ||
sessionStorage.setItem( "qunit-filter-passed-tests", "true" ); | ||
} else { | ||
sessionStorage.removeItem("qunit-filter-passed-tests"); | ||
sessionStorage.removeItem( "qunit-filter-passed-tests" ); | ||
} | ||
} | ||
}); | ||
if ( defined.sessionStorage && sessionStorage.getItem("qunit-filter-passed-tests") ) { | ||
if ( config.hidepassed || defined.sessionStorage && sessionStorage.getItem( "qunit-filter-passed-tests" ) ) { | ||
filter.checked = true; | ||
var ol = document.getElementById("qunit-tests"); | ||
// `ol` initialized at top of scope | ||
ol = document.getElementById( "qunit-tests" ); | ||
ol.className = ol.className + " hidepass"; | ||
@@ -755,9 +1163,40 @@ } | ||
var label = document.createElement("label"); | ||
label.setAttribute("for", "qunit-filter-pass"); | ||
// `label` initialized at top of scope | ||
label = document.createElement( "label" ); | ||
label.setAttribute( "for", "qunit-filter-pass" ); | ||
label.setAttribute( "title", "Only show tests and assertons that fail. Stored in sessionStorage." ); | ||
label.innerHTML = "Hide passed tests"; | ||
toolbar.appendChild( label ); | ||
urlConfigCheckboxesContainer = document.createElement("span"); | ||
urlConfigCheckboxesContainer.innerHTML = urlConfigHtml; | ||
urlConfigCheckboxes = urlConfigCheckboxesContainer.getElementsByTagName("input"); | ||
// For oldIE support: | ||
// * Add handlers to the individual elements instead of the container | ||
// * Use "click" instead of "change" | ||
// * Fallback from event.target to event.srcElement | ||
addEvents( urlConfigCheckboxes, "click", function( event ) { | ||
var params = {}, | ||
target = event.target || event.srcElement; | ||
params[ target.name ] = target.checked ? true : undefined; | ||
window.location = QUnit.url( params ); | ||
}); | ||
toolbar.appendChild( urlConfigCheckboxesContainer ); | ||
if (numModules > 1) { | ||
moduleFilter = document.createElement( 'span' ); | ||
moduleFilter.setAttribute( 'id', 'qunit-modulefilter-container' ); | ||
moduleFilter.innerHTML = moduleFilterHtml; | ||
addEvent( moduleFilter.lastChild, "change", function() { | ||
var selectBox = moduleFilter.getElementsByTagName("select")[0], | ||
selectedModule = decodeURIComponent(selectBox.options[selectBox.selectedIndex].value); | ||
window.location = QUnit.url( { module: ( selectedModule === "" ) ? undefined : selectedModule } ); | ||
}); | ||
toolbar.appendChild(moduleFilter); | ||
} | ||
} | ||
var main = id('qunit-fixture'); | ||
// `main` initialized at top of scope | ||
main = id( "qunit-fixture" ); | ||
if ( main ) { | ||
@@ -767,7 +1206,41 @@ config.fixture = main.innerHTML; | ||
if (config.autostart) { | ||
if ( config.autostart ) { | ||
QUnit.start(); | ||
} | ||
}); | ||
}; | ||
addEvent( window, "load", QUnit.load ); | ||
// `onErrorFnPrev` initialized at top of scope | ||
// Preserve other handlers | ||
onErrorFnPrev = window.onerror; | ||
// Cover uncaught exceptions | ||
// Returning true will surpress the default browser handler, | ||
// returning false will let it run. | ||
window.onerror = function ( error, filePath, linerNr ) { | ||
var ret = false; | ||
if ( onErrorFnPrev ) { | ||
ret = onErrorFnPrev( error, filePath, linerNr ); | ||
} | ||
// Treat return value as window.onerror itself does, | ||
// Only do our handling if not surpressed. | ||
if ( ret !== true ) { | ||
if ( QUnit.config.current ) { | ||
if ( QUnit.config.current.ignoreGlobalErrors ) { | ||
return true; | ||
} | ||
QUnit.pushFailure( error, filePath + ":" + linerNr ); | ||
} else { | ||
QUnit.test( "global failure", extend( function() { | ||
QUnit.pushFailure( error, filePath + ":" + linerNr ); | ||
}, { validTest: validTest } ) ); | ||
} | ||
return false; | ||
} | ||
return ret; | ||
}; | ||
function done() { | ||
@@ -778,3 +1251,3 @@ config.autorun = true; | ||
if ( config.currentModule ) { | ||
QUnit.moduleDone( { | ||
runLoggingCallbacks( "moduleDone", QUnit, { | ||
name: config.currentModule, | ||
@@ -784,24 +1257,25 @@ failed: config.moduleStats.bad, | ||
total: config.moduleStats.all | ||
} ); | ||
}); | ||
} | ||
var banner = id("qunit-banner"), | ||
tests = id("qunit-tests"), | ||
runtime = +new Date - config.started, | ||
var i, key, | ||
banner = id( "qunit-banner" ), | ||
tests = id( "qunit-tests" ), | ||
runtime = +new Date() - config.started, | ||
passed = config.stats.all - config.stats.bad, | ||
html = [ | ||
'Tests completed in ', | ||
"Tests completed in ", | ||
runtime, | ||
' milliseconds.<br/>', | ||
'<span class="passed">', | ||
" milliseconds.<br/>", | ||
"<span class='passed'>", | ||
passed, | ||
'</span> tests of <span class="total">', | ||
"</span> assertions of <span class='total'>", | ||
config.stats.all, | ||
'</span> passed, <span class="failed">', | ||
"</span> passed, <span class='failed'>", | ||
config.stats.bad, | ||
'</span> failed.' | ||
].join(''); | ||
"</span> failed." | ||
].join( "" ); | ||
if ( banner ) { | ||
banner.className = (config.stats.bad ? "qunit-fail" : "qunit-pass"); | ||
banner.className = ( config.stats.bad ? "qunit-fail" : "qunit-pass" ); | ||
} | ||
@@ -813,9 +1287,28 @@ | ||
if ( typeof document !== "undefined" && document.title ) { | ||
if ( config.altertitle && typeof document !== "undefined" && document.title ) { | ||
// show ✖ for good, ✔ for bad suite result in title | ||
// use escape sequences in case file gets loaded with non-utf-8-charset | ||
document.title = (config.stats.bad ? "\u2716" : "\u2714") + " " + document.title; | ||
document.title = [ | ||
( config.stats.bad ? "\u2716" : "\u2714" ), | ||
document.title.replace( /^[\u2714\u2716] /i, "" ) | ||
].join( " " ); | ||
} | ||
QUnit.done( { | ||
// clear own sessionStorage items if all tests passed | ||
if ( config.reorder && defined.sessionStorage && config.stats.bad === 0 ) { | ||
// `key` & `i` initialized at top of scope | ||
for ( i = 0; i < sessionStorage.length; i++ ) { | ||
key = sessionStorage.key( i++ ); | ||
if ( key.indexOf( "qunit-test-" ) === 0 ) { | ||
sessionStorage.removeItem( key ); | ||
} | ||
} | ||
} | ||
// scroll back to top to show results | ||
if ( window.scrollTo ) { | ||
window.scrollTo(0, 0); | ||
} | ||
runLoggingCallbacks( "done", QUnit, { | ||
failed: config.stats.bad, | ||
@@ -825,9 +1318,26 @@ passed: passed, | ||
runtime: runtime | ||
} ); | ||
}); | ||
} | ||
function validTest( name ) { | ||
var filter = config.filter, | ||
run = false; | ||
/** @return Boolean: true if this test should be ran */ | ||
function validTest( test ) { | ||
var include, | ||
filter = config.filter && config.filter.toLowerCase(), | ||
module = config.module && config.module.toLowerCase(), | ||
fullName = (test.module + ": " + test.testName).toLowerCase(); | ||
// Internally-generated tests are always valid | ||
if ( test.callback && test.callback.validTest === validTest ) { | ||
delete test.callback.validTest; | ||
return true; | ||
} | ||
if ( config.testNumber ) { | ||
return test.testNumber === config.testNumber; | ||
} | ||
if ( module && ( !test.module || test.module.toLowerCase() !== module ) ) { | ||
return false; | ||
} | ||
if ( !filter ) { | ||
@@ -837,47 +1347,86 @@ return true; | ||
var not = filter.charAt( 0 ) === "!"; | ||
if ( not ) { | ||
include = filter.charAt( 0 ) !== "!"; | ||
if ( !include ) { | ||
filter = filter.slice( 1 ); | ||
} | ||
if ( name.indexOf( filter ) !== -1 ) { | ||
return !not; | ||
// If the filter matches, we need to honour include | ||
if ( fullName.indexOf( filter ) !== -1 ) { | ||
return include; | ||
} | ||
if ( not ) { | ||
run = true; | ||
// Otherwise, do the opposite | ||
return !include; | ||
} | ||
// so far supports only Firefox, Chrome and Opera (buggy), Safari (for real exceptions) | ||
// Later Safari and IE10 are supposed to support error.stack as well | ||
// See also https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/Error/Stack | ||
function extractStacktrace( e, offset ) { | ||
offset = offset === undefined ? 3 : offset; | ||
var stack, include, i; | ||
if ( e.stacktrace ) { | ||
// Opera | ||
return e.stacktrace.split( "\n" )[ offset + 3 ]; | ||
} else if ( e.stack ) { | ||
// Firefox, Chrome | ||
stack = e.stack.split( "\n" ); | ||
if (/^error$/i.test( stack[0] ) ) { | ||
stack.shift(); | ||
} | ||
if ( fileName ) { | ||
include = []; | ||
for ( i = offset; i < stack.length; i++ ) { | ||
if ( stack[ i ].indexOf( fileName ) !== -1 ) { | ||
break; | ||
} | ||
include.push( stack[ i ] ); | ||
} | ||
if ( include.length ) { | ||
return include.join( "\n" ); | ||
} | ||
} | ||
return stack[ offset ]; | ||
} else if ( e.sourceURL ) { | ||
// Safari, PhantomJS | ||
// hopefully one day Safari provides actual stacktraces | ||
// exclude useless self-reference for generated Error objects | ||
if ( /qunit.js$/.test( e.sourceURL ) ) { | ||
return; | ||
} | ||
// for actual exceptions, this is useful | ||
return e.sourceURL + ":" + e.line; | ||
} | ||
return run; | ||
} | ||
// so far supports only Firefox, Chrome and Opera (buggy) | ||
// could be extended in the future to use something like https://github.com/csnover/TraceKit | ||
function sourceFromStacktrace() { | ||
function sourceFromStacktrace( offset ) { | ||
try { | ||
throw new Error(); | ||
} catch ( e ) { | ||
if (e.stacktrace) { | ||
// Opera | ||
return e.stacktrace.split("\n")[6]; | ||
} else if (e.stack) { | ||
// Firefox, Chrome | ||
return e.stack.split("\n")[4]; | ||
} | ||
return extractStacktrace( e, offset ); | ||
} | ||
} | ||
function escapeHtml(s) { | ||
if (!s) { | ||
/** | ||
* Escape text for attribute or text content. | ||
*/ | ||
function escapeText( s ) { | ||
if ( !s ) { | ||
return ""; | ||
} | ||
s = s + ""; | ||
return s.replace(/[\&"<>\\]/g, function(s) { | ||
switch(s) { | ||
case "&": return "&"; | ||
case "\\": return "\\\\"; | ||
case '"': return '\"'; | ||
case "<": return "<"; | ||
case ">": return ">"; | ||
default: return s; | ||
// Both single quotes and double quotes (for attributes) | ||
return s.replace( /['"<>&]/g, function( s ) { | ||
switch( s ) { | ||
case '\'': | ||
return '''; | ||
case '"': | ||
return '"'; | ||
case '<': | ||
return '<'; | ||
case '>': | ||
return '>'; | ||
case '&': | ||
return '&'; | ||
} | ||
@@ -887,24 +1436,29 @@ }); | ||
function synchronize( callback ) { | ||
function synchronize( callback, last ) { | ||
config.queue.push( callback ); | ||
if ( config.autorun && !config.blocking ) { | ||
process(); | ||
process( last ); | ||
} | ||
} | ||
function process() { | ||
var start = (new Date()).getTime(); | ||
function process( last ) { | ||
function next() { | ||
process( last ); | ||
} | ||
var start = new Date().getTime(); | ||
config.depth = config.depth ? config.depth + 1 : 1; | ||
while ( config.queue.length && !config.blocking ) { | ||
if ( config.updateRate <= 0 || (((new Date()).getTime() - start) < config.updateRate) ) { | ||
if ( !defined.setTimeout || config.updateRate <= 0 || ( ( new Date().getTime() - start ) < config.updateRate ) ) { | ||
config.queue.shift()(); | ||
} else { | ||
window.setTimeout( process, 13 ); | ||
window.setTimeout( next, 13 ); | ||
break; | ||
} | ||
} | ||
if (!config.blocking && !config.queue.length) { | ||
done(); | ||
} | ||
config.depth--; | ||
if ( last && !config.blocking && !config.queue.length && config.depth === 0 ) { | ||
done(); | ||
} | ||
} | ||
@@ -917,2 +1471,6 @@ | ||
for ( var key in window ) { | ||
// in Opera sometimes DOM element ids show up here, ignore them | ||
if ( !hasOwn.call( window, key ) || /^qunit-test-output/.test( key ) ) { | ||
continue; | ||
} | ||
config.pollution.push( key ); | ||
@@ -923,14 +1481,17 @@ } | ||
function checkPollution( name ) { | ||
var old = config.pollution; | ||
function checkPollution() { | ||
var newGlobals, | ||
deletedGlobals, | ||
old = config.pollution; | ||
saveGlobal(); | ||
var newGlobals = diff( config.pollution, old ); | ||
newGlobals = diff( config.pollution, old ); | ||
if ( newGlobals.length > 0 ) { | ||
ok( false, "Introduced global variable(s): " + newGlobals.join(", ") ); | ||
QUnit.pushFailure( "Introduced global variable(s): " + newGlobals.join(", ") ); | ||
} | ||
var deletedGlobals = diff( old, config.pollution ); | ||
deletedGlobals = diff( old, config.pollution ); | ||
if ( deletedGlobals.length > 0 ) { | ||
ok( false, "Deleted global variable(s): " + deletedGlobals.join(", ") ); | ||
QUnit.pushFailure( "Deleted global variable(s): " + deletedGlobals.join(", ") ); | ||
} | ||
@@ -941,7 +1502,9 @@ } | ||
function diff( a, b ) { | ||
var result = a.slice(); | ||
for ( var i = 0; i < result.length; i++ ) { | ||
for ( var j = 0; j < b.length; j++ ) { | ||
var i, j, | ||
result = a.slice(); | ||
for ( i = 0; i < result.length; i++ ) { | ||
for ( j = 0; j < b.length; j++ ) { | ||
if ( result[i] === b[j] ) { | ||
result.splice(i, 1); | ||
result.splice( i, 1 ); | ||
i--; | ||
@@ -955,19 +1518,10 @@ break; | ||
function fail(message, exception, callback) { | ||
if ( typeof console !== "undefined" && console.error && console.warn ) { | ||
console.error(message); | ||
console.error(exception); | ||
console.warn(callback.toString()); | ||
function extend( a, b ) { | ||
for ( var prop in b ) { | ||
if ( b[ prop ] === undefined ) { | ||
delete a[ prop ]; | ||
} else if ( window.opera && opera.postError ) { | ||
opera.postError(message, exception, callback.toString); | ||
} | ||
} | ||
function extend(a, b) { | ||
for ( var prop in b ) { | ||
if ( b[prop] === undefined ) { | ||
delete a[prop]; | ||
} else { | ||
a[prop] = b[prop]; | ||
// Avoid "Member not found" error in IE8 caused by setting window.constructor | ||
} else if ( prop !== "constructor" || a !== window ) { | ||
a[ prop ] = b[ prop ]; | ||
} | ||
@@ -979,187 +1533,264 @@ } | ||
function addEvent(elem, type, fn) { | ||
/** | ||
* @param {HTMLElement} elem | ||
* @param {string} type | ||
* @param {Function} fn | ||
*/ | ||
function addEvent( elem, type, fn ) { | ||
// Standards-based browsers | ||
if ( elem.addEventListener ) { | ||
elem.addEventListener( type, fn, false ); | ||
} else if ( elem.attachEvent ) { | ||
// IE | ||
} else { | ||
elem.attachEvent( "on" + type, fn ); | ||
} else { | ||
fn(); | ||
} | ||
} | ||
function id(name) { | ||
return !!(typeof document !== "undefined" && document && document.getElementById) && | ||
/** | ||
* @param {Array|NodeList} elems | ||
* @param {string} type | ||
* @param {Function} fn | ||
*/ | ||
function addEvents( elems, type, fn ) { | ||
var i = elems.length; | ||
while ( i-- ) { | ||
addEvent( elems[i], type, fn ); | ||
} | ||
} | ||
function hasClass( elem, name ) { | ||
return (" " + elem.className + " ").indexOf(" " + name + " ") > -1; | ||
} | ||
function addClass( elem, name ) { | ||
if ( !hasClass( elem, name ) ) { | ||
elem.className += (elem.className ? " " : "") + name; | ||
} | ||
} | ||
function removeClass( elem, name ) { | ||
var set = " " + elem.className + " "; | ||
// Class name may appear multiple times | ||
while ( set.indexOf(" " + name + " ") > -1 ) { | ||
set = set.replace(" " + name + " " , " "); | ||
} | ||
// If possible, trim it for prettiness, but not neccecarily | ||
elem.className = window.jQuery ? jQuery.trim( set ) : ( set.trim ? set.trim() : set ); | ||
} | ||
function id( name ) { | ||
return !!( typeof document !== "undefined" && document && document.getElementById ) && | ||
document.getElementById( name ); | ||
} | ||
function registerLoggingCallback( key ) { | ||
return function( callback ) { | ||
config[key].push( callback ); | ||
}; | ||
} | ||
// Supports deprecated method of completely overwriting logging callbacks | ||
function runLoggingCallbacks( key, scope, args ) { | ||
var i, callbacks; | ||
if ( QUnit.hasOwnProperty( key ) ) { | ||
QUnit[ key ].call(scope, args ); | ||
} else { | ||
callbacks = config[ key ]; | ||
for ( i = 0; i < callbacks.length; i++ ) { | ||
callbacks[ i ].call( scope, args ); | ||
} | ||
} | ||
} | ||
// Test for equality any JavaScript type. | ||
// Discussions and reference: http://philrathe.com/articles/equiv | ||
// Test suites: http://philrathe.com/tests/equiv | ||
// Author: Philippe Rathé <prathe@gmail.com> | ||
QUnit.equiv = function () { | ||
QUnit.equiv = (function() { | ||
var innerEquiv; // the real equiv function | ||
var callers = []; // stack to decide between skip/abort functions | ||
var parents = []; // stack to avoiding loops from circular referencing | ||
// Call the o related callback with the given arguments. | ||
function bindCallbacks( o, callbacks, args ) { | ||
var prop = QUnit.objectType( o ); | ||
if ( prop ) { | ||
if ( QUnit.objectType( callbacks[ prop ] ) === "function" ) { | ||
return callbacks[ prop ].apply( callbacks, args ); | ||
} else { | ||
return callbacks[ prop ]; // or undefined | ||
} | ||
} | ||
} | ||
// Call the o related callback with the given arguments. | ||
function bindCallbacks(o, callbacks, args) { | ||
var prop = QUnit.objectType(o); | ||
if (prop) { | ||
if (QUnit.objectType(callbacks[prop]) === "function") { | ||
return callbacks[prop].apply(callbacks, args); | ||
} else { | ||
return callbacks[prop]; // or undefined | ||
} | ||
} | ||
} | ||
// the real equiv function | ||
var innerEquiv, | ||
// stack to decide between skip/abort functions | ||
callers = [], | ||
// stack to avoiding loops from circular referencing | ||
parents = [], | ||
var callbacks = function () { | ||
getProto = Object.getPrototypeOf || function ( obj ) { | ||
return obj.__proto__; | ||
}, | ||
callbacks = (function () { | ||
// for string, boolean, number and null | ||
function useStrictEquality(b, a) { | ||
if (b instanceof a.constructor || a instanceof b.constructor) { | ||
// to catch short annotaion VS 'new' annotation of a declaration | ||
// e.g. var i = 1; | ||
// var j = new Number(1); | ||
return a == b; | ||
} else { | ||
return a === b; | ||
} | ||
} | ||
// for string, boolean, number and null | ||
function useStrictEquality( b, a ) { | ||
/*jshint eqeqeq:false */ | ||
if ( b instanceof a.constructor || a instanceof b.constructor ) { | ||
// to catch short annotaion VS 'new' annotation of a | ||
// declaration | ||
// e.g. var i = 1; | ||
// var j = new Number(1); | ||
return a == b; | ||
} else { | ||
return a === b; | ||
} | ||
} | ||
return { | ||
"string": useStrictEquality, | ||
"boolean": useStrictEquality, | ||
"number": useStrictEquality, | ||
"null": useStrictEquality, | ||
"undefined": useStrictEquality, | ||
return { | ||
"string": useStrictEquality, | ||
"boolean": useStrictEquality, | ||
"number": useStrictEquality, | ||
"null": useStrictEquality, | ||
"undefined": useStrictEquality, | ||
"nan": function (b) { | ||
return isNaN(b); | ||
}, | ||
"nan": function( b ) { | ||
return isNaN( b ); | ||
}, | ||
"date": function (b, a) { | ||
return QUnit.objectType(b) === "date" && a.valueOf() === b.valueOf(); | ||
}, | ||
"date": function( b, a ) { | ||
return QUnit.objectType( b ) === "date" && a.valueOf() === b.valueOf(); | ||
}, | ||
"regexp": function (b, a) { | ||
return QUnit.objectType(b) === "regexp" && | ||
a.source === b.source && // the regex itself | ||
a.global === b.global && // and its modifers (gmi) ... | ||
a.ignoreCase === b.ignoreCase && | ||
a.multiline === b.multiline; | ||
}, | ||
"regexp": function( b, a ) { | ||
return QUnit.objectType( b ) === "regexp" && | ||
// the regex itself | ||
a.source === b.source && | ||
// and its modifers | ||
a.global === b.global && | ||
// (gmi) ... | ||
a.ignoreCase === b.ignoreCase && | ||
a.multiline === b.multiline && | ||
a.sticky === b.sticky; | ||
}, | ||
// - skip when the property is a method of an instance (OOP) | ||
// - abort otherwise, | ||
// initial === would have catch identical references anyway | ||
"function": function () { | ||
var caller = callers[callers.length - 1]; | ||
return caller !== Object && | ||
typeof caller !== "undefined"; | ||
}, | ||
// - skip when the property is a method of an instance (OOP) | ||
// - abort otherwise, | ||
// initial === would have catch identical references anyway | ||
"function": function() { | ||
var caller = callers[callers.length - 1]; | ||
return caller !== Object && typeof caller !== "undefined"; | ||
}, | ||
"array": function (b, a) { | ||
var i, j, loop; | ||
var len; | ||
"array": function( b, a ) { | ||
var i, j, len, loop; | ||
// b could be an object literal here | ||
if ( ! (QUnit.objectType(b) === "array")) { | ||
return false; | ||
} | ||
// b could be an object literal here | ||
if ( QUnit.objectType( b ) !== "array" ) { | ||
return false; | ||
} | ||
len = a.length; | ||
if (len !== b.length) { // safe and faster | ||
return false; | ||
} | ||
len = a.length; | ||
if ( len !== b.length ) { | ||
// safe and faster | ||
return false; | ||
} | ||
//track reference to avoid circular references | ||
parents.push(a); | ||
for (i = 0; i < len; i++) { | ||
loop = false; | ||
for(j=0;j<parents.length;j++){ | ||
if(parents[j] === a[i]){ | ||
loop = true;//dont rewalk array | ||
} | ||
} | ||
if (!loop && ! innerEquiv(a[i], b[i])) { | ||
parents.pop(); | ||
return false; | ||
} | ||
} | ||
parents.pop(); | ||
return true; | ||
}, | ||
// track reference to avoid circular references | ||
parents.push( a ); | ||
for ( i = 0; i < len; i++ ) { | ||
loop = false; | ||
for ( j = 0; j < parents.length; j++ ) { | ||
if ( parents[j] === a[i] ) { | ||
loop = true;// dont rewalk array | ||
} | ||
} | ||
if ( !loop && !innerEquiv(a[i], b[i]) ) { | ||
parents.pop(); | ||
return false; | ||
} | ||
} | ||
parents.pop(); | ||
return true; | ||
}, | ||
"object": function (b, a) { | ||
var i, j, loop; | ||
var eq = true; // unless we can proove it | ||
var aProperties = [], bProperties = []; // collection of strings | ||
"object": function( b, a ) { | ||
var i, j, loop, | ||
// Default to true | ||
eq = true, | ||
aProperties = [], | ||
bProperties = []; | ||
// comparing constructors is more strict than using instanceof | ||
if ( a.constructor !== b.constructor) { | ||
return false; | ||
} | ||
// comparing constructors is more strict than using | ||
// instanceof | ||
if ( a.constructor !== b.constructor ) { | ||
// Allow objects with no prototype to be equivalent to | ||
// objects with Object as their constructor. | ||
if ( !(( getProto(a) === null && getProto(b) === Object.prototype ) || | ||
( getProto(b) === null && getProto(a) === Object.prototype ) ) ) { | ||
return false; | ||
} | ||
} | ||
// stack constructor before traversing properties | ||
callers.push(a.constructor); | ||
//track reference to avoid circular references | ||
parents.push(a); | ||
// stack constructor before traversing properties | ||
callers.push( a.constructor ); | ||
// track reference to avoid circular references | ||
parents.push( a ); | ||
for (i in a) { // be strict: don't ensures hasOwnProperty and go deep | ||
loop = false; | ||
for(j=0;j<parents.length;j++){ | ||
if(parents[j] === a[i]) | ||
loop = true; //don't go down the same path twice | ||
} | ||
aProperties.push(i); // collect a's properties | ||
for ( i in a ) { // be strict: don't ensures hasOwnProperty | ||
// and go deep | ||
loop = false; | ||
for ( j = 0; j < parents.length; j++ ) { | ||
if ( parents[j] === a[i] ) { | ||
// don't go down the same path twice | ||
loop = true; | ||
} | ||
} | ||
aProperties.push(i); // collect a's properties | ||
if (!loop && ! innerEquiv(a[i], b[i])) { | ||
eq = false; | ||
break; | ||
} | ||
} | ||
if (!loop && !innerEquiv( a[i], b[i] ) ) { | ||
eq = false; | ||
break; | ||
} | ||
} | ||
callers.pop(); // unstack, we are done | ||
parents.pop(); | ||
callers.pop(); // unstack, we are done | ||
parents.pop(); | ||
for (i in b) { | ||
bProperties.push(i); // collect b's properties | ||
} | ||
for ( i in b ) { | ||
bProperties.push( i ); // collect b's properties | ||
} | ||
// Ensures identical properties name | ||
return eq && innerEquiv(aProperties.sort(), bProperties.sort()); | ||
} | ||
}; | ||
}(); | ||
// Ensures identical properties name | ||
return eq && innerEquiv( aProperties.sort(), bProperties.sort() ); | ||
} | ||
}; | ||
}()); | ||
innerEquiv = function () { // can take multiple arguments | ||
var args = Array.prototype.slice.apply(arguments); | ||
if (args.length < 2) { | ||
return true; // end transition | ||
} | ||
innerEquiv = function() { // can take multiple arguments | ||
var args = [].slice.apply( arguments ); | ||
if ( args.length < 2 ) { | ||
return true; // end transition | ||
} | ||
return (function (a, b) { | ||
if (a === b) { | ||
return true; // catch the most you can | ||
} else if (a === null || b === null || typeof a === "undefined" || typeof b === "undefined" || QUnit.objectType(a) !== QUnit.objectType(b)) { | ||
return false; // don't lose time with error prone cases | ||
} else { | ||
return bindCallbacks(a, callbacks, [b, a]); | ||
} | ||
return (function( a, b ) { | ||
if ( a === b ) { | ||
return true; // catch the most you can | ||
} else if ( a === null || b === null || typeof a === "undefined" || | ||
typeof b === "undefined" || | ||
QUnit.objectType(a) !== QUnit.objectType(b) ) { | ||
return false; // don't lose time with error prone cases | ||
} else { | ||
return bindCallbacks(a, callbacks, [ b, a ]); | ||
} | ||
// apply transition with (1..n) arguments | ||
})(args[0], args[1]) && arguments.callee.apply(this, args.splice(1, args.length -1)); | ||
}; | ||
// apply transition with (1..n) arguments | ||
}( args[0], args[1] ) && arguments.callee.apply( this, args.splice(1, args.length - 1 )) ); | ||
}; | ||
return innerEquiv; | ||
return innerEquiv; | ||
}()); | ||
}(); | ||
/** | ||
* jsDump | ||
* Copyright (c) 2008 Ariel Flesler - aflesler(at)gmail(dot)com | http://flesler.blogspot.com | ||
* Licensed under BSD (http://www.opensource.org/licenses/bsd-license.php) | ||
* Date: 5/15/2008 | ||
* jsDump Copyright (c) 2008 Ariel Flesler - aflesler(at)gmail(dot)com | | ||
* http://flesler.blogspot.com Licensed under BSD | ||
* (http://www.opensource.org/licenses/bsd-license.php) Date: 5/15/2008 | ||
* | ||
* @projectDescription Advanced and extensible data dumping for Javascript. | ||
@@ -1172,7 +1803,7 @@ * @version 1.0.0 | ||
function quote( str ) { | ||
return '"' + str.toString().replace(/"/g, '\\"') + '"'; | ||
}; | ||
return '"' + str.toString().replace( /"/g, '\\"' ) + '"'; | ||
} | ||
function literal( o ) { | ||
return o + ''; | ||
}; | ||
return o + ""; | ||
} | ||
function join( pre, arr, post ) { | ||
@@ -1182,172 +1813,225 @@ var s = jsDump.separator(), | ||
inner = jsDump.indent(1); | ||
if ( arr.join ) | ||
arr = arr.join( ',' + s + inner ); | ||
if ( !arr ) | ||
if ( arr.join ) { | ||
arr = arr.join( "," + s + inner ); | ||
} | ||
if ( !arr ) { | ||
return pre + post; | ||
} | ||
return [ pre, inner + arr, base + post ].join(s); | ||
}; | ||
function array( arr ) { | ||
var i = arr.length, ret = Array(i); | ||
} | ||
function array( arr, stack ) { | ||
var i = arr.length, ret = new Array(i); | ||
this.up(); | ||
while ( i-- ) | ||
ret[i] = this.parse( arr[i] ); | ||
while ( i-- ) { | ||
ret[i] = this.parse( arr[i] , undefined , stack); | ||
} | ||
this.down(); | ||
return join( '[', ret, ']' ); | ||
}; | ||
return join( "[", ret, "]" ); | ||
} | ||
var reName = /^function (\w+)/; | ||
var reName = /^function (\w+)/, | ||
jsDump = { | ||
// type is used mostly internally, you can fix a (custom)type in advance | ||
parse: function( obj, type, stack ) { | ||
stack = stack || [ ]; | ||
var inStack, res, | ||
parser = this.parsers[ type || this.typeOf(obj) ]; | ||
var jsDump = { | ||
parse:function( obj, type ) { //type is used mostly internally, you can fix a (custom)type in advance | ||
var parser = this.parsers[ type || this.typeOf(obj) ]; | ||
type = typeof parser; | ||
type = typeof parser; | ||
inStack = inArray( obj, stack ); | ||
return type == 'function' ? parser.call( this, obj ) : | ||
type == 'string' ? parser : | ||
this.parsers.error; | ||
}, | ||
typeOf:function( obj ) { | ||
var type; | ||
if ( obj === null ) { | ||
type = "null"; | ||
} else if (typeof obj === "undefined") { | ||
type = "undefined"; | ||
} else if (QUnit.is("RegExp", obj)) { | ||
type = "regexp"; | ||
} else if (QUnit.is("Date", obj)) { | ||
type = "date"; | ||
} else if (QUnit.is("Function", obj)) { | ||
type = "function"; | ||
} else if (typeof obj.setInterval !== undefined && typeof obj.document !== "undefined" && typeof obj.nodeType === "undefined") { | ||
type = "window"; | ||
} else if (obj.nodeType === 9) { | ||
type = "document"; | ||
} else if (obj.nodeType) { | ||
type = "node"; | ||
} else if (typeof obj === "object" && typeof obj.length === "number" && obj.length >= 0) { | ||
type = "array"; | ||
} else { | ||
type = typeof obj; | ||
} | ||
return type; | ||
}, | ||
separator:function() { | ||
return this.multiline ? this.HTML ? '<br />' : '\n' : this.HTML ? ' ' : ' '; | ||
}, | ||
indent:function( extra ) {// extra can be a number, shortcut for increasing-calling-decreasing | ||
if ( !this.multiline ) | ||
return ''; | ||
var chr = this.indentChar; | ||
if ( this.HTML ) | ||
chr = chr.replace(/\t/g,' ').replace(/ /g,' '); | ||
return Array( this._depth_ + (extra||0) ).join(chr); | ||
}, | ||
up:function( a ) { | ||
this._depth_ += a || 1; | ||
}, | ||
down:function( a ) { | ||
this._depth_ -= a || 1; | ||
}, | ||
setParser:function( name, parser ) { | ||
this.parsers[name] = parser; | ||
}, | ||
// The next 3 are exposed so you can use them | ||
quote:quote, | ||
literal:literal, | ||
join:join, | ||
// | ||
_depth_: 1, | ||
// This is the list of parsers, to modify them, use jsDump.setParser | ||
parsers:{ | ||
window: '[Window]', | ||
document: '[Document]', | ||
error:'[ERROR]', //when no parser is found, shouldn't happen | ||
unknown: '[Unknown]', | ||
'null':'null', | ||
'undefined':'undefined', | ||
'function':function( fn ) { | ||
var ret = 'function', | ||
name = 'name' in fn ? fn.name : (reName.exec(fn)||[])[1];//functions never have name in IE | ||
if ( name ) | ||
ret += ' ' + name; | ||
ret += '('; | ||
ret = [ ret, QUnit.jsDump.parse( fn, 'functionArgs' ), '){'].join(''); | ||
return join( ret, QUnit.jsDump.parse(fn,'functionCode'), '}' ); | ||
if ( inStack !== -1 ) { | ||
return "recursion(" + (inStack - stack.length) + ")"; | ||
} | ||
if ( type === "function" ) { | ||
stack.push( obj ); | ||
res = parser.call( this, obj, stack ); | ||
stack.pop(); | ||
return res; | ||
} | ||
return ( type === "string" ) ? parser : this.parsers.error; | ||
}, | ||
array: array, | ||
nodelist: array, | ||
arguments: array, | ||
object:function( map ) { | ||
var ret = [ ]; | ||
QUnit.jsDump.up(); | ||
for ( var key in map ) | ||
ret.push( QUnit.jsDump.parse(key,'key') + ': ' + QUnit.jsDump.parse(map[key]) ); | ||
QUnit.jsDump.down(); | ||
return join( '{', ret, '}' ); | ||
typeOf: function( obj ) { | ||
var type; | ||
if ( obj === null ) { | ||
type = "null"; | ||
} else if ( typeof obj === "undefined" ) { | ||
type = "undefined"; | ||
} else if ( QUnit.is( "regexp", obj) ) { | ||
type = "regexp"; | ||
} else if ( QUnit.is( "date", obj) ) { | ||
type = "date"; | ||
} else if ( QUnit.is( "function", obj) ) { | ||
type = "function"; | ||
} else if ( typeof obj.setInterval !== undefined && typeof obj.document !== "undefined" && typeof obj.nodeType === "undefined" ) { | ||
type = "window"; | ||
} else if ( obj.nodeType === 9 ) { | ||
type = "document"; | ||
} else if ( obj.nodeType ) { | ||
type = "node"; | ||
} else if ( | ||
// native arrays | ||
toString.call( obj ) === "[object Array]" || | ||
// NodeList objects | ||
( typeof obj.length === "number" && typeof obj.item !== "undefined" && ( obj.length ? obj.item(0) === obj[0] : ( obj.item( 0 ) === null && typeof obj[0] === "undefined" ) ) ) | ||
) { | ||
type = "array"; | ||
} else if ( obj.constructor === Error.prototype.constructor ) { | ||
type = "error"; | ||
} else { | ||
type = typeof obj; | ||
} | ||
return type; | ||
}, | ||
node:function( node ) { | ||
var open = QUnit.jsDump.HTML ? '<' : '<', | ||
close = QUnit.jsDump.HTML ? '>' : '>'; | ||
var tag = node.nodeName.toLowerCase(), | ||
ret = open + tag; | ||
for ( var a in QUnit.jsDump.DOMAttrs ) { | ||
var val = node[QUnit.jsDump.DOMAttrs[a]]; | ||
if ( val ) | ||
ret += ' ' + a + '=' + QUnit.jsDump.parse( val, 'attribute' ); | ||
separator: function() { | ||
return this.multiline ? this.HTML ? "<br />" : "\n" : this.HTML ? " " : " "; | ||
}, | ||
// extra can be a number, shortcut for increasing-calling-decreasing | ||
indent: function( extra ) { | ||
if ( !this.multiline ) { | ||
return ""; | ||
} | ||
return ret + close + open + '/' + tag + close; | ||
var chr = this.indentChar; | ||
if ( this.HTML ) { | ||
chr = chr.replace( /\t/g, " " ).replace( / /g, " " ); | ||
} | ||
return new Array( this._depth_ + (extra||0) ).join(chr); | ||
}, | ||
functionArgs:function( fn ) {//function calls it internally, it's the arguments part of the function | ||
var l = fn.length; | ||
if ( !l ) return ''; | ||
up: function( a ) { | ||
this._depth_ += a || 1; | ||
}, | ||
down: function( a ) { | ||
this._depth_ -= a || 1; | ||
}, | ||
setParser: function( name, parser ) { | ||
this.parsers[name] = parser; | ||
}, | ||
// The next 3 are exposed so you can use them | ||
quote: quote, | ||
literal: literal, | ||
join: join, | ||
// | ||
_depth_: 1, | ||
// This is the list of parsers, to modify them, use jsDump.setParser | ||
parsers: { | ||
window: "[Window]", | ||
document: "[Document]", | ||
error: function(error) { | ||
return "Error(\"" + error.message + "\")"; | ||
}, | ||
unknown: "[Unknown]", | ||
"null": "null", | ||
"undefined": "undefined", | ||
"function": function( fn ) { | ||
var ret = "function", | ||
// functions never have name in IE | ||
name = "name" in fn ? fn.name : (reName.exec(fn) || [])[1]; | ||
var args = Array(l); | ||
while ( l-- ) | ||
args[l] = String.fromCharCode(97+l);//97 is 'a' | ||
return ' ' + args.join(', ') + ' '; | ||
if ( name ) { | ||
ret += " " + name; | ||
} | ||
ret += "( "; | ||
ret = [ ret, QUnit.jsDump.parse( fn, "functionArgs" ), "){" ].join( "" ); | ||
return join( ret, QUnit.jsDump.parse(fn,"functionCode" ), "}" ); | ||
}, | ||
array: array, | ||
nodelist: array, | ||
"arguments": array, | ||
object: function( map, stack ) { | ||
var ret = [ ], keys, key, val, i; | ||
QUnit.jsDump.up(); | ||
keys = []; | ||
for ( key in map ) { | ||
keys.push( key ); | ||
} | ||
keys.sort(); | ||
for ( i = 0; i < keys.length; i++ ) { | ||
key = keys[ i ]; | ||
val = map[ key ]; | ||
ret.push( QUnit.jsDump.parse( key, "key" ) + ": " + QUnit.jsDump.parse( val, undefined, stack ) ); | ||
} | ||
QUnit.jsDump.down(); | ||
return join( "{", ret, "}" ); | ||
}, | ||
node: function( node ) { | ||
var len, i, val, | ||
open = QUnit.jsDump.HTML ? "<" : "<", | ||
close = QUnit.jsDump.HTML ? ">" : ">", | ||
tag = node.nodeName.toLowerCase(), | ||
ret = open + tag, | ||
attrs = node.attributes; | ||
if ( attrs ) { | ||
for ( i = 0, len = attrs.length; i < len; i++ ) { | ||
val = attrs[i].nodeValue; | ||
// IE6 includes all attributes in .attributes, even ones not explicitly set. | ||
// Those have values like undefined, null, 0, false, "" or "inherit". | ||
if ( val && val !== "inherit" ) { | ||
ret += " " + attrs[i].nodeName + "=" + QUnit.jsDump.parse( val, "attribute" ); | ||
} | ||
} | ||
} | ||
ret += close; | ||
// Show content of TextNode or CDATASection | ||
if ( node.nodeType === 3 || node.nodeType === 4 ) { | ||
ret += node.nodeValue; | ||
} | ||
return ret + open + "/" + tag + close; | ||
}, | ||
// function calls it internally, it's the arguments part of the function | ||
functionArgs: function( fn ) { | ||
var args, | ||
l = fn.length; | ||
if ( !l ) { | ||
return ""; | ||
} | ||
args = new Array(l); | ||
while ( l-- ) { | ||
// 97 is 'a' | ||
args[l] = String.fromCharCode(97+l); | ||
} | ||
return " " + args.join( ", " ) + " "; | ||
}, | ||
// object calls it internally, the key part of an item in a map | ||
key: quote, | ||
// function calls it internally, it's the content of the function | ||
functionCode: "[code]", | ||
// node calls it internally, it's an html attribute value | ||
attribute: quote, | ||
string: quote, | ||
date: quote, | ||
regexp: literal, | ||
number: literal, | ||
"boolean": literal | ||
}, | ||
key:quote, //object calls it internally, the key part of an item in a map | ||
functionCode:'[code]', //function calls it internally, it's the content of the function | ||
attribute:quote, //node calls it internally, it's an html attribute value | ||
string:quote, | ||
date:quote, | ||
regexp:literal, //regex | ||
number:literal, | ||
'boolean':literal | ||
}, | ||
DOMAttrs:{//attributes to dump from nodes, name=>realName | ||
id:'id', | ||
name:'name', | ||
'class':'className' | ||
}, | ||
HTML:false,//if true, entities are escaped ( <, >, \t, space and \n ) | ||
indentChar:' ',//indentation unit | ||
multiline:true //if true, items in a collection, are separated by a \n, else just a space. | ||
}; | ||
// if true, entities are escaped ( <, >, \t, space and \n ) | ||
HTML: false, | ||
// indentation unit | ||
indentChar: " ", | ||
// if true, items in a collection, are separated by a \n, else just a space. | ||
multiline: true | ||
}; | ||
return jsDump; | ||
})(); | ||
}()); | ||
// from Sizzle.js | ||
function getText( elems ) { | ||
var ret = "", elem; | ||
// from jquery.js | ||
function inArray( elem, array ) { | ||
if ( array.indexOf ) { | ||
return array.indexOf( elem ); | ||
} | ||
for ( var i = 0; elems[i]; i++ ) { | ||
elem = elems[i]; | ||
// Get the text from text nodes and CDATA nodes | ||
if ( elem.nodeType === 3 || elem.nodeType === 4 ) { | ||
ret += elem.nodeValue; | ||
// Traverse everything else, except comment nodes | ||
} else if ( elem.nodeType !== 8 ) { | ||
ret += getText( elem.childNodes ); | ||
for ( var i = 0, length = array.length; i < length; i++ ) { | ||
if ( array[ i ] === elem ) { | ||
return i; | ||
} | ||
} | ||
return ret; | ||
}; | ||
return -1; | ||
} | ||
@@ -1366,35 +2050,42 @@ /* | ||
* | ||
* QUnit.diff("the quick brown fox jumped over", "the quick fox jumps over") == "the quick <del>brown </del> fox <del>jumped </del><ins>jumps </ins> over" | ||
* QUnit.diff( "the quick brown fox jumped over", "the quick fox jumps over" ) == "the quick <del>brown </del> fox <del>jumped </del><ins>jumps </ins> over" | ||
*/ | ||
QUnit.diff = (function() { | ||
function diff(o, n){ | ||
var ns = new Object(); | ||
var os = new Object(); | ||
/*jshint eqeqeq:false, eqnull:true */ | ||
function diff( o, n ) { | ||
var i, | ||
ns = {}, | ||
os = {}; | ||
for (var i = 0; i < n.length; i++) { | ||
if (ns[n[i]] == null) | ||
ns[n[i]] = { | ||
rows: new Array(), | ||
for ( i = 0; i < n.length; i++ ) { | ||
if ( !hasOwn.call( ns, n[i] ) ) { | ||
ns[ n[i] ] = { | ||
rows: [], | ||
o: null | ||
}; | ||
ns[n[i]].rows.push(i); | ||
} | ||
ns[ n[i] ].rows.push( i ); | ||
} | ||
for (var i = 0; i < o.length; i++) { | ||
if (os[o[i]] == null) | ||
os[o[i]] = { | ||
rows: new Array(), | ||
for ( i = 0; i < o.length; i++ ) { | ||
if ( !hasOwn.call( os, o[i] ) ) { | ||
os[ o[i] ] = { | ||
rows: [], | ||
n: null | ||
}; | ||
os[o[i]].rows.push(i); | ||
} | ||
os[ o[i] ].rows.push( i ); | ||
} | ||
for (var i in ns) { | ||
if (ns[i].rows.length == 1 && typeof(os[i]) != "undefined" && os[i].rows.length == 1) { | ||
n[ns[i].rows[0]] = { | ||
text: n[ns[i].rows[0]], | ||
for ( i in ns ) { | ||
if ( !hasOwn.call( ns, i ) ) { | ||
continue; | ||
} | ||
if ( ns[i].rows.length === 1 && hasOwn.call( os, i ) && os[i].rows.length === 1 ) { | ||
n[ ns[i].rows[0] ] = { | ||
text: n[ ns[i].rows[0] ], | ||
row: os[i].rows[0] | ||
}; | ||
o[os[i].rows[0]] = { | ||
text: o[os[i].rows[0]], | ||
o[ os[i].rows[0] ] = { | ||
text: o[ os[i].rows[0] ], | ||
row: ns[i].rows[0] | ||
@@ -1405,11 +2096,12 @@ }; | ||
for (var i = 0; i < n.length - 1; i++) { | ||
if (n[i].text != null && n[i + 1].text == null && n[i].row + 1 < o.length && o[n[i].row + 1].text == null && | ||
n[i + 1] == o[n[i].row + 1]) { | ||
n[i + 1] = { | ||
text: n[i + 1], | ||
for ( i = 0; i < n.length - 1; i++ ) { | ||
if ( n[i].text != null && n[ i + 1 ].text == null && n[i].row + 1 < o.length && o[ n[i].row + 1 ].text == null && | ||
n[ i + 1 ] == o[ n[i].row + 1 ] ) { | ||
n[ i + 1 ] = { | ||
text: n[ i + 1 ], | ||
row: n[i].row + 1 | ||
}; | ||
o[n[i].row + 1] = { | ||
text: o[n[i].row + 1], | ||
o[ n[i].row + 1 ] = { | ||
text: o[ n[i].row + 1 ], | ||
row: i + 1 | ||
@@ -1420,11 +2112,12 @@ }; | ||
for (var i = n.length - 1; i > 0; i--) { | ||
if (n[i].text != null && n[i - 1].text == null && n[i].row > 0 && o[n[i].row - 1].text == null && | ||
n[i - 1] == o[n[i].row - 1]) { | ||
n[i - 1] = { | ||
text: n[i - 1], | ||
for ( i = n.length - 1; i > 0; i-- ) { | ||
if ( n[i].text != null && n[ i - 1 ].text == null && n[i].row > 0 && o[ n[i].row - 1 ].text == null && | ||
n[ i - 1 ] == o[ n[i].row - 1 ]) { | ||
n[ i - 1 ] = { | ||
text: n[ i - 1 ], | ||
row: n[i].row - 1 | ||
}; | ||
o[n[i].row - 1] = { | ||
text: o[n[i].row - 1], | ||
o[ n[i].row - 1 ] = { | ||
text: o[ n[i].row - 1 ], | ||
row: i - 1 | ||
@@ -1441,45 +2134,48 @@ }; | ||
return function(o, n){ | ||
o = o.replace(/\s+$/, ''); | ||
n = n.replace(/\s+$/, ''); | ||
var out = diff(o == "" ? [] : o.split(/\s+/), n == "" ? [] : n.split(/\s+/)); | ||
return function( o, n ) { | ||
o = o.replace( /\s+$/, "" ); | ||
n = n.replace( /\s+$/, "" ); | ||
var str = ""; | ||
var i, pre, | ||
str = "", | ||
out = diff( o === "" ? [] : o.split(/\s+/), n === "" ? [] : n.split(/\s+/) ), | ||
oSpace = o.match(/\s+/g), | ||
nSpace = n.match(/\s+/g); | ||
var oSpace = o.match(/\s+/g); | ||
if (oSpace == null) { | ||
oSpace = [" "]; | ||
if ( oSpace == null ) { | ||
oSpace = [ " " ]; | ||
} | ||
else { | ||
oSpace.push(" "); | ||
oSpace.push( " " ); | ||
} | ||
var nSpace = n.match(/\s+/g); | ||
if (nSpace == null) { | ||
nSpace = [" "]; | ||
if ( nSpace == null ) { | ||
nSpace = [ " " ]; | ||
} | ||
else { | ||
nSpace.push(" "); | ||
nSpace.push( " " ); | ||
} | ||
if (out.n.length == 0) { | ||
for (var i = 0; i < out.o.length; i++) { | ||
str += '<del>' + out.o[i] + oSpace[i] + "</del>"; | ||
if ( out.n.length === 0 ) { | ||
for ( i = 0; i < out.o.length; i++ ) { | ||
str += "<del>" + out.o[i] + oSpace[i] + "</del>"; | ||
} | ||
} | ||
else { | ||
if (out.n[0].text == null) { | ||
for (n = 0; n < out.o.length && out.o[n].text == null; n++) { | ||
str += '<del>' + out.o[n] + oSpace[n] + "</del>"; | ||
if ( out.n[0].text == null ) { | ||
for ( n = 0; n < out.o.length && out.o[n].text == null; n++ ) { | ||
str += "<del>" + out.o[n] + oSpace[n] + "</del>"; | ||
} | ||
} | ||
for (var i = 0; i < out.n.length; i++) { | ||
for ( i = 0; i < out.n.length; i++ ) { | ||
if (out.n[i].text == null) { | ||
str += '<ins>' + out.n[i] + nSpace[i] + "</ins>"; | ||
str += "<ins>" + out.n[i] + nSpace[i] + "</ins>"; | ||
} | ||
else { | ||
var pre = ""; | ||
// `pre` initialized at top of scope | ||
pre = ""; | ||
for (n = out.n[i].row + 1; n < out.o.length && out.o[n].text == null; n++) { | ||
pre += '<del>' + out.o[n] + oSpace[n] + "</del>"; | ||
for ( n = out.n[i].row + 1; n < out.o.length && out.o[n].text == null; n++ ) { | ||
pre += "<del>" + out.o[n] + oSpace[n] + "</del>"; | ||
} | ||
@@ -1493,4 +2189,10 @@ str += " " + out.n[i].text + nSpace[i] + pre; | ||
}; | ||
})(); | ||
}()); | ||
})(this); | ||
// for CommonJS enviroments, export everything | ||
if ( typeof exports !== "undefined" ) { | ||
extend( exports, QUnit ); | ||
} | ||
// get at whatever the global object is, like window in browsers | ||
}( (function() {return this;}.call()) )); |
271
test/test.js
@@ -5,2 +5,5 @@ | ||
ok ( typeof tinycolor("red") == "object", "tinycolor is able to be instantiated." ); | ||
equal ( tinycolor("red", { format: "hex" }).toString(), "#ff0000", "tinycolor options are being parsed" ); | ||
equal ( tinycolor.fromRatio({r: 1, g: 0, b: 0 }, { format: "hex" }).toString(), "#ff0000", "tinycolor options are being parsed" ); | ||
}); | ||
@@ -10,21 +13,18 @@ | ||
var conversions = [ | ||
{"hex":"#FFFFFF","rgb":{"r":"100.0%","g":"100.0%","b":"100.0%"},"hsv":{"h":"0","s":"0.000","v":"1.000"},"hsl":{"h":"0","s":"0.000","l":"1.000"}}, | ||
{"hex":"#808080","rgb":{"r":"050.0%","g":"050.0%","b":"050.0%"},"hsv":{"h":"0","s":"0.000","v":"0.500"},"hsl":{"h":"0","s":"0.000","l":"0.500"}}, | ||
{"hex":"#000000","rgb":{"r":"000.0%","g":"000.0%","b":"000.0%"},"hsv":{"h":"0","s":"0.000","v":"0.000"},"hsl":{"h":"0","s":"0.000","l":"0.000"}}, | ||
{"hex":"#FF0000","rgb":{"r":"100.0%","g":"000.0%","b":"000.0%"},"hsv":{"h":"0.0","s":"1.000","v":"1.000"},"hsl":{"h":"0.0","s":"1.000","l":"0.500"}}, | ||
{"hex":"#BFBF00","rgb":{"r":"075.0%","g":"075.0%","b":"000.0%"},"hsv":{"h":"60.0","s":"1.000","v":"0.750"},"hsl":{"h":"60.0","s":"1.000","l":"0.375"}}, | ||
{"hex":"#008000","rgb":{"r":"000.0%","g":"050.0%","b":"000.0%"},"hsv":{"h":"120.0","s":"1.000","v":"0.500"},"hsl":{"h":"120.0","s":"1.000","l":"0.250"}}, | ||
{"hex":"#80FFFF","rgb":{"r":"050.0%","g":"100.0%","b":"100.0%"},"hsv":{"h":"180.0","s":"0.500","v":"1.000"},"hsl":{"h":"180.0","s":"1.000","l":"0.750"}}, | ||
{"hex":"#8080FF","rgb":{"r":"050.0%","g":"050.0%","b":"100.0%"},"hsv":{"h":"240.0","s":"0.500","v":"1.000"},"hsl":{"h":"240.0","s":"1.000","l":"0.750"}}, | ||
{"hex":"#BF40BF","rgb":{"r":"075.0%","g":"025.0%","b":"075.0%"},"hsv":{"h":"300.0","s":"0.667","v":"0.750"},"hsl":{"h":"300.0","s":"0.500","l":"0.500"}}, | ||
{"hex":"#A0A424","rgb":{"r":"062.8%","g":"064.3%","b":"014.2%"},"hsv":{"h":"61.8","s":"0.779","v":"0.643"},"hsl":{"h":"61.8","s":"0.638","l":"0.393"}}, | ||
//{"hex":"#411BEA","rgb":{"r":"025.5%","g":"010.4%","b":"091.8%"},"hsv":{"h":"251.1","s":"0.887","v":"0.918"},"hsl":{"h":"251.1","s":"0.832","l":"0.511"}}, | ||
{"hex":"#1EAC41","rgb":{"r":"011.6%","g":"067.5%","b":"025.5%"},"hsv":{"h":"134.9","s":"0.828","v":"0.675"},"hsl":{"h":"134.9","s":"0.707","l":"0.396"}}, | ||
//{"hex":"#F0C80E","rgb":{"r":"094.1%","g":"078.5%","b":"005.3%"},"hsv":{"h":"49.5","s":"0.944","v":"0.941"},"hsl":{"h":"49.5","s":"0.893","l":"0.497"}}, | ||
{"hex":"#B430E5","rgb":{"r":"070.4%","g":"018.7%","b":"089.7%"},"hsv":{"h":"283.7","s":"0.792","v":"0.897"},"hsl":{"h":"283.7","s":"0.775","l":"0.542"}}, | ||
//{"hex":"#ED7651","rgb":{"r":"093.1%","g":"046.3%","b":"031.6%"},"hsv":{"h":"14.3","s":"0.661","v":"0.931"},"hsl":{"h":"14.3","s":"0.817","l":"0.624"}}, | ||
{"hex":"#FEF888","rgb":{"r":"099.8%","g":"097.4%","b":"053.2%"},"hsv":{"h":"56.9","s":"0.467","v":"0.998"},"hsl":{"h":"56.9","s":"0.991","l":"0.765"}}, | ||
{"hex":"#19CB97","rgb":{"r":"009.9%","g":"079.5%","b":"059.1%"},"hsv":{"h":"162.4","s":"0.875","v":"0.795"},"hsl":{"h":"162.4","s":"0.779","l":"0.447"}}, | ||
{"hex":"#362698","rgb":{"r":"021.1%","g":"014.9%","b":"059.7%"},"hsv":{"h":"248.3","s":"0.750","v":"0.597"},"hsl":{"h":"248.3","s":"0.601","l":"0.373"}}, | ||
{"hex":"#7E7EB8","rgb":{"r":"049.5%","g":"049.3%","b":"072.1%"},"hsv":{"h":"240.5","s":"0.316","v":"0.721"},"hsl":{"h":"240.5","s":"0.290","l":"0.607"}} | ||
{"hex":"#FFFFFF","hex8":"#FFFFFFFF","rgb":{"r":"100.0%","g":"100.0%","b":"100.0%"},"hsv":{"h":"0","s":"0.000","v":"1.000"},"hsl":{"h":"0","s":"0.000","l":"1.000"}}, | ||
{"hex":"#808080","hex8":"#FF808080","rgb":{"r":"050.0%","g":"050.0%","b":"050.0%"},"hsv":{"h":"0","s":"0.000","v":"0.500"},"hsl":{"h":"0","s":"0.000","l":"0.500"}}, | ||
{"hex":"#000000","hex8":"#FF000000","rgb":{"r":"000.0%","g":"000.0%","b":"000.0%"},"hsv":{"h":"0","s":"0.000","v":"0.000"},"hsl":{"h":"0","s":"0.000","l":"0.000"}}, | ||
{"hex":"#FF0000","hex8":"#FFFF0000","rgb":{"r":"100.0%","g":"000.0%","b":"000.0%"},"hsv":{"h":"0.0","s":"1.000","v":"1.000"},"hsl":{"h":"0.0","s":"1.000","l":"0.500"}}, | ||
{"hex":"#BFBF00","hex8":"#FFBFBF00","rgb":{"r":"075.0%","g":"075.0%","b":"000.0%"},"hsv":{"h":"60.0","s":"1.000","v":"0.750"},"hsl":{"h":"60.0","s":"1.000","l":"0.375"}}, | ||
{"hex":"#008000","hex8":"#FF008000","rgb":{"r":"000.0%","g":"050.0%","b":"000.0%"},"hsv":{"h":"120.0","s":"1.000","v":"0.500"},"hsl":{"h":"120.0","s":"1.000","l":"0.250"}}, | ||
{"hex":"#80FFFF","hex8":"#FF80FFFF","rgb":{"r":"050.0%","g":"100.0%","b":"100.0%"},"hsv":{"h":"180.0","s":"0.500","v":"1.000"},"hsl":{"h":"180.0","s":"1.000","l":"0.750"}}, | ||
{"hex":"#8080FF","hex8":"#FF8080FF","rgb":{"r":"050.0%","g":"050.0%","b":"100.0%"},"hsv":{"h":"240.0","s":"0.500","v":"1.000"},"hsl":{"h":"240.0","s":"1.000","l":"0.750"}}, | ||
{"hex":"#BF40BF","hex8":"#FFBF40BF","rgb":{"r":"075.0%","g":"025.0%","b":"075.0%"},"hsv":{"h":"300.0","s":"0.667","v":"0.750"},"hsl":{"h":"300.0","s":"0.500","l":"0.500"}}, | ||
{"hex":"#A0A424","hex8":"#FFA0A424","rgb":{"r":"062.8%","g":"064.3%","b":"014.2%"},"hsv":{"h":"61.8","s":"0.779","v":"0.643"},"hsl":{"h":"61.8","s":"0.638","l":"0.393"}}, | ||
{"hex":"#1EAC41","hex8":"#FF1EAC41","rgb":{"r":"011.6%","g":"067.5%","b":"025.5%"},"hsv":{"h":"134.9","s":"0.828","v":"0.675"},"hsl":{"h":"134.9","s":"0.707","l":"0.396"}}, | ||
{"hex":"#B430E5","hex8":"#FFB430E5","rgb":{"r":"070.4%","g":"018.7%","b":"089.7%"},"hsv":{"h":"283.7","s":"0.792","v":"0.897"},"hsl":{"h":"283.7","s":"0.775","l":"0.542"}}, | ||
{"hex":"#FEF888","hex8":"#FFFEF888","rgb":{"r":"099.8%","g":"097.4%","b":"053.2%"},"hsv":{"h":"56.9","s":"0.467","v":"0.998"},"hsl":{"h":"56.9","s":"0.991","l":"0.765"}}, | ||
{"hex":"#19CB97","hex8":"#FF19CB97","rgb":{"r":"009.9%","g":"079.5%","b":"059.1%"},"hsv":{"h":"162.4","s":"0.875","v":"0.795"},"hsl":{"h":"162.4","s":"0.779","l":"0.447"}}, | ||
{"hex":"#362698","hex8":"#FF362698","rgb":{"r":"021.1%","g":"014.9%","b":"059.7%"},"hsv":{"h":"248.3","s":"0.750","v":"0.597"},"hsl":{"h":"248.3","s":"0.601","l":"0.373"}}, | ||
{"hex":"#7E7EB8","hex8":"#FF7E7EB8","rgb":{"r":"049.5%","g":"049.3%","b":"072.1%"},"hsv":{"h":"240.5","s":"0.316","v":"0.721"},"hsl":{"h":"240.5","s":"0.290","l":"0.607"}} | ||
]; | ||
@@ -39,18 +39,20 @@ | ||
var tiny = tinycolor(c.hex); | ||
ok (true, | ||
"Testing " + c.hex + ": " + tiny.toRgbString() + " " + tiny.toHsvString() + " " + tiny.toHslString() + " " + tiny.toHexString() + | ||
ok (true, | ||
"Testing " + c.hex + ": " + tiny.toRgbString() + " " + tiny.toPercentageRgbString() + " " + tiny.toHsvString() + " " + tiny.toHslString() + " " + tiny.toHexString() + | ||
"Original: " + JSON.stringify(c.rgb) + " " + JSON.stringify(c.hsv) + " " + JSON.stringify(c.hsl) | ||
); | ||
ok (tinycolor.equals(c.rgb, c.hex), "RGB equals hex " + c.hex); | ||
ok (tinycolor.equals(c.rgb, c.hex8), "RGB equals hex " + c.hex); | ||
ok (tinycolor.equals(c.rgb, c.hsl), "RGB equals HSL " + c.hex); | ||
ok (tinycolor.equals(c.rgb, c.hsv), "RGB equals HSV " + c.hex); | ||
ok (tinycolor.equals(c.rgb, c.rgb), "RGB equals RGB " + c.hex); | ||
ok (tinycolor.equals(c.hex, c.hex), "hex equals hex " + c.hex); | ||
ok (tinycolor.equals(c.hex, c.hex8), "hex equals hex8 " + c.hex); | ||
ok (tinycolor.equals(c.hex, c.hsl), "hex equals HSL " + c.hex); | ||
ok (tinycolor.equals(c.hex, c.hsv), "hex equals HSV " + c.hex); | ||
ok (tinycolor.equals(c.hsl, c.hsv), "HSL equals HSV " + c.hex); | ||
} | ||
@@ -61,3 +63,7 @@ }); | ||
test("With Ratio", function() { | ||
equal (tinycolor.fromRatio({r: 1, g: 1, b: 1}).toHexString(), "#fff", "white"); | ||
equal (tinycolor.fromRatio({r: 1, g: 1, b: 1}).toHexString(), "#ffffff", "white"); | ||
equal ( tinycolor.fromRatio({r: 1, g: 0, b: 0, a: .5 }).toRgbString(), "rgba(255, 0, 0, 0.5)", "alpha works when ratio is parsed" ); | ||
equal ( tinycolor.fromRatio({r: 1, g: 0, b: 0, a: 1 }).toRgbString(), "rgb(255, 0, 0)", "alpha = 1 works when ratio is parsed" ); | ||
equal ( tinycolor.fromRatio({r: 1, g: 0, b: 0, a: 10 }).toRgbString(), "rgb(255, 0, 0)", "alpha > 1 works when ratio is parsed" ); | ||
equal ( tinycolor.fromRatio({r: 1, g: 0, b: 0, a: -1 }).toRgbString(), "rgb(255, 0, 0)", "alpha < 1 works when ratio is parsed" ); | ||
}); | ||
@@ -73,6 +79,6 @@ | ||
equal (tinycolor("rgb 255 0 0").toHexString(), "#f00", "spaced input"); | ||
equal (tinycolor("rgb(255, 0, 0)").toHexString(), "#f00", "parenthesized input"); | ||
equal (tinycolor("rgb (255, 0, 0)").toHexString(), "#f00", "parenthesized spaced input"); | ||
equal (tinycolor({ r: 255, g: 0, b: 0 }).toHexString(), "#f00", "object input"); | ||
equal (tinycolor("rgb 255 0 0").toHexString(), "#ff0000", "spaced input"); | ||
equal (tinycolor("rgb(255, 0, 0)").toHexString(), "#ff0000", "parenthesized input"); | ||
equal (tinycolor("rgb (255, 0, 0)").toHexString(), "#ff0000", "parenthesized spaced input"); | ||
equal (tinycolor({ r: 255, g: 0, b: 0 }).toHexString(), "#ff0000", "object input"); | ||
deepEqual (tinycolor({ r: 255, g: 0, b: 0 }).toRgb(), { r: 255, g: 0, b: 0, a: 1 }, "object input and compare"); | ||
@@ -86,14 +92,40 @@ | ||
ok (!tinycolor.equals({r:199, g: 100, b: 0 }, "rgba 200 100 0 1")); | ||
ok (!tinycolor.equals({r:199, g: 100, b: 0 }, "rgb(200, 100, 0)")); | ||
ok (!tinycolor.equals({r:199, g: 100, b: 0 }, "rgb 200 100 0")); | ||
ok (!tinycolor.equals({r:199, g: 100, b: 0 }, "rgb 200 100 0")); | ||
ok (tinycolor.equals(tinycolor({r:200, g: 100, b: 0 }), "rgb(200, 100, 0)")); | ||
ok (tinycolor.equals(tinycolor({r:200, g: 100, b: 0 }), "rgb 200 100 0")); | ||
ok (tinycolor.equals(tinycolor({r:200, g: 100, b: 0 }), "rgb 200 100 0")); | ||
}); | ||
test("Percentage RGB Text Parsing", function() { | ||
equal (tinycolor("rgb 100% 0% 0%").toHexString(), "#ff0000", "spaced input"); | ||
equal (tinycolor("rgb(100%, 0%, 0%)").toHexString(), "#ff0000", "parenthesized input"); | ||
equal (tinycolor("rgb (100%, 0%, 0%)").toHexString(), "#ff0000", "parenthesized spaced input"); | ||
equal (tinycolor({ r: "100%", g: "0%", b: "0%" }).toHexString(), "#ff0000", "object input"); | ||
deepEqual (tinycolor({ r: "100%", g: "0%", b: "0%" }).toRgb(), { r: 255, g: 0, b: 0, a: 1 }, "object input and compare"); | ||
ok (tinycolor.equals({r:"90%", g: "45%", b: "0%" }, "rgb(90%, 45%, 0%)")); | ||
ok (tinycolor.equals({r:"90%", g: "45%", b: "0%" }, "rgb 90% 45% 0%")); | ||
ok (tinycolor.equals({r:"90%", g: "45%", b: "0%" }, "rgb 90% 45% 0%")); | ||
ok (tinycolor.equals({r:"90%", g: "45%", b: "0%", a: .4 }, "rgba 90% 45% 0% .4")); | ||
ok (!tinycolor.equals({r:"89%", g: "45%", b: "0%" }, "rgba 90% 45% 0% 1")); | ||
ok (!tinycolor.equals({r:"89%", g: "45%", b: "0%" }, "rgb(90%, 45%, 0%)")); | ||
ok (!tinycolor.equals({r:"89%", g: "45%", b: "0%" }, "rgb 90% 45% 0%")); | ||
ok (!tinycolor.equals({r:"89%", g: "45%", b: "0%" }, "rgb 90% 45% 0%")); | ||
ok (tinycolor.equals(tinycolor({r:"90%", g: "45%", b: "0%" }), "rgb(90%, 45%, 0%)")); | ||
ok (tinycolor.equals(tinycolor({r:"90%", g: "45%", b: "0%" }), "rgb 90% 45% 0%")); | ||
ok (tinycolor.equals(tinycolor({r:"90%", g: "45%", b: "0%" }), "rgb 90% 45% 0%")); | ||
}); | ||
test("HSL parsing", function() { | ||
@@ -111,4 +143,12 @@ equal( tinycolor({ h: 251, s: 100, l: .38 }).toHexString(), "#2400c2", "to hex" ); | ||
test("Hex Parsing", function() { | ||
//equal (tinycolor(rgb).toHexString().toLowerCase(), c.hex.toLowerCase()); | ||
equal (tinycolor("rgb 255 0 0").toHexString(), "#ff0000"); | ||
equal (tinycolor("rgb 255 0 0").toHexString(true), "#f00"); | ||
equal (tinycolor("rgba 255 0 0 0.5").toHex8String(), "#80ff0000"); | ||
equal (tinycolor("rgb 255 0 0").toHex(), "ff0000"); | ||
equal (tinycolor("rgb 255 0 0").toHex(true), "f00"); | ||
equal (tinycolor("rgba 255 0 0 0.5").toHex8(), "80ff0000"); | ||
}); | ||
@@ -123,6 +163,12 @@ | ||
test("Invalid Parsing", function() { | ||
equal( tinycolor("this is not a color").toHexString(), "#000000"); | ||
}); | ||
test("Named colors", function() { | ||
equal (tinycolor("aliceblue").toHex(), "f0f8ff"); | ||
equal (tinycolor("antiquewhite").toHex(), "faebd7"); | ||
equal (tinycolor("aqua").toHex(), "0ff"); | ||
equal (tinycolor("aqua").toHex(), "00ffff"); | ||
equal (tinycolor("aquamarine").toHex(), "7fffd4"); | ||
@@ -132,5 +178,5 @@ equal (tinycolor("azure").toHex(), "f0ffff"); | ||
equal (tinycolor("bisque").toHex(), "ffe4c4"); | ||
equal (tinycolor("black").toHex(), "000"); | ||
equal (tinycolor("black").toHex(), "000000"); | ||
equal (tinycolor("blanchedalmond").toHex(), "ffebcd"); | ||
equal (tinycolor("blue").toHex(), "00f"); | ||
equal (tinycolor("blue").toHex(), "0000ff"); | ||
equal (tinycolor("blueviolet").toHex(), "8a2be2"); | ||
@@ -146,3 +192,3 @@ equal (tinycolor("brown").toHex(), "a52a2a"); | ||
equal (tinycolor("crimson").toHex(), "dc143c"); | ||
equal (tinycolor("cyan").toHex(), "0ff"); | ||
equal (tinycolor("cyan").toHex(), "00ffff"); | ||
equal (tinycolor("darkblue").toHex(), "00008b"); | ||
@@ -172,3 +218,3 @@ equal (tinycolor("darkcyan").toHex(), "008b8b"); | ||
equal (tinycolor("forestgreen").toHex(), "228b22"); | ||
equal (tinycolor("fuchsia").toHex(), "f0f"); | ||
equal (tinycolor("fuchsia").toHex(), "ff00ff"); | ||
equal (tinycolor("gainsboro").toHex(), "dcdcdc"); | ||
@@ -202,9 +248,9 @@ equal (tinycolor("ghostwhite").toHex(), "f8f8ff"); | ||
equal (tinycolor("lightskyblue").toHex(), "87cefa"); | ||
equal (tinycolor("lightslategray").toHex(), "789"); | ||
equal (tinycolor("lightslategray").toHex(), "778899"); | ||
equal (tinycolor("lightsteelblue").toHex(), "b0c4de"); | ||
equal (tinycolor("lightyellow").toHex(), "ffffe0"); | ||
equal (tinycolor("lime").toHex(), "0f0"); | ||
equal (tinycolor("lime").toHex(), "00ff00"); | ||
equal (tinycolor("limegreen").toHex(), "32cd32"); | ||
equal (tinycolor("linen").toHex(), "faf0e6"); | ||
equal (tinycolor("magenta").toHex(), "f0f"); | ||
equal (tinycolor("magenta").toHex(), "ff00ff"); | ||
equal (tinycolor("maroon").toHex(), "800000"); | ||
@@ -243,3 +289,3 @@ equal (tinycolor("mediumaquamarine").toHex(), "66cdaa"); | ||
equal (tinycolor("purple").toHex(), "800080"); | ||
equal (tinycolor("red").toHex(), "f00"); | ||
equal (tinycolor("red").toHex(), "ff0000"); | ||
equal (tinycolor("rosybrown").toHex(), "bc8f8f"); | ||
@@ -267,12 +313,67 @@ equal (tinycolor("royalblue").toHex(), "4169e1"); | ||
equal (tinycolor("wheat").toHex(), "f5deb3"); | ||
equal (tinycolor("white").toHex(), "fff"); | ||
equal (tinycolor("white").toHex(), "ffffff"); | ||
equal (tinycolor("whitesmoke").toHex(), "f5f5f5"); | ||
equal (tinycolor("yellow").toHex(), "ff0"); | ||
equal (tinycolor("yellow").toHex(), "ffff00"); | ||
equal (tinycolor("yellowgreen").toHex(), "9acd32"); | ||
equal (tinycolor("#f00").toName(), "red"); | ||
equal (tinycolor("#fa0a0a").toName(), false); | ||
}); | ||
module("Alpha handling"); | ||
test("Invalid alpha should normalize to 1", function() { | ||
equal(tinycolor({r:255,g:20,b:10,a: -1}).toRgbString(), "rgb(255, 20, 10)", "Negative value"); | ||
equal(tinycolor({r:255,g:20,b:10,a: -0}).toRgbString(), "rgba(255, 20, 10, 0)", "Negative 0"); | ||
equal(tinycolor({r:255,g:20,b:10,a: 0}).toRgbString(), "rgba(255, 20, 10, 0)", "0"); | ||
equal(tinycolor({r:255,g:20,b:10,a: .5}).toRgbString(), "rgba(255, 20, 10, 0.5)", ".5"); | ||
equal(tinycolor({r:255,g:20,b:10,a: 1}).toRgbString(), "rgb(255, 20, 10)", "1"); | ||
equal(tinycolor({r:255,g:20,b:10,a: 100}).toRgbString(), "rgb(255, 20, 10)", "Greater than 1"); | ||
equal(tinycolor({r:255,g:20,b:10,a: "asdfasd"}).toRgbString(), "rgb(255, 20, 10)", "Non Numeric"); | ||
module("Initialization from output"); | ||
equal(tinycolor("#fff").toRgbString(), "rgb(255, 255, 255)", "Hex should be 1"); | ||
equal(tinycolor("rgba 255 0 0 100").toRgbString(), "rgb(255, 0, 0)", "Greater than 1 in string parsing"); | ||
var redNamed = tinycolor.fromRatio({ r: 255, g: 0, b: 0, a: .5}, {format: "name"}); | ||
var transparentNamed = tinycolor.fromRatio({ r: 255, g: 0, b: 0, a: 0 }, {format: "name"}); | ||
var redHex = tinycolor.fromRatio({ r: 255, g: 0, b: 0, a: .5}, {format: "hex"}); | ||
equal(redNamed.toString(), "rgba(255, 0, 0, 0.5)", "Names should default to rgba if alpha is < 1"); | ||
equal(redHex.toString(), "rgba(255, 0, 0, 0.5)", "Hex should default to rgba if alpha is < 1"); | ||
equal(redNamed.toString("hex"), "#ff0000", "Names should not be returned as rgba if format is specified"); | ||
equal(redNamed.toString("hex6"), "#ff0000", "Names should not be returned as rgba if format is specified"); | ||
equal(redNamed.toString("hex3"), "#f00", "Names should not be returned as rgba if format is specified"); | ||
equal(redNamed.toString("name"), "red", "Names should not be returned as rgba if format is specified"); | ||
equal(redHex.toString(), "rgba(255, 0, 0, 0.5)", "Hex should default to rgba if alpha is < 1"); | ||
equal(transparentNamed.toString(), "transparent", "Named color should equal transparent if alpha == 0"); | ||
var hexSetter = tinycolor("rgba(255, 0, 0, 1)"); | ||
equal(hexSetter.alpha, 1, "Alpha should start as 1"); | ||
hexSetter.setAlpha(.9); | ||
equal(hexSetter.getAlpha(), .9, "setAlpha should change alpha value"); | ||
hexSetter.setAlpha(.5); | ||
equal(hexSetter.getAlpha(), .5, "setAlpha should change alpha value"); | ||
hexSetter.setAlpha(0); | ||
equal(hexSetter.getAlpha(), 0, "setAlpha should change alpha value"); | ||
hexSetter.setAlpha(-1); | ||
equal(hexSetter.getAlpha(), 1, "setAlpha with value < 0 should be bound to 1"); | ||
hexSetter.setAlpha(2); | ||
equal(hexSetter.getAlpha(), 1, "setAlpha with value > 1 should be bound to 1"); | ||
hexSetter.setAlpha(); | ||
equal(hexSetter.getAlpha(), 1, "setAlpha with invalid value should be bound to 1"); | ||
hexSetter.setAlpha(null); | ||
equal(hexSetter.getAlpha(), 1, "setAlpha with invalid value should be bound to 1"); | ||
hexSetter.setAlpha("test"); | ||
equal(hexSetter.getAlpha(), 1, "setAlpha with invalid value should be bound to 1"); | ||
}); | ||
test("Alpha = 0 should act differently on toName()", function() { | ||
equal(tinycolor({r:255,g:20,b:10,a: 0}).toName(), "transparent", "0"); | ||
equal(tinycolor("transparent").toString(), "transparent", "toString when passed"); | ||
equal(tinycolor("transparent").toHex(), "000000", "toHex"); | ||
}); | ||
module("Initialization from tinycolor output"); | ||
test("HSL Object", function() { | ||
var random = tinycolor.random(); | ||
var random = tinycolor.random(); | ||
equal (random.toHexString(), tinycolor(random.toHsl()).toHexString(), "HSL Object"); | ||
@@ -296,8 +397,28 @@ }); | ||
var random = tinycolor.random(); | ||
equal (random.toHexString(), tinycolor(random.toRgb()).toHexString(), "HSL"); | ||
equal (random.toHexString(), tinycolor(random.toRgb()).toHexString(), "RGB Object"); | ||
}); | ||
test("RGB String", function() { | ||
var random = tinycolor.random(); | ||
equal (random.toHexString(), tinycolor(random.toRgbString()).toHexString(), "HSL"); | ||
equal (random.toHexString(), tinycolor(random.toRgbString()).toHexString(), "RGB String"); | ||
}); | ||
test("PRGB Object", function() { | ||
var random = tinycolor.random(); | ||
var input = random.toRgb(); | ||
var output = tinycolor(random.toPercentageRgb()).toRgb(); | ||
var maxDiff = 2; | ||
equal(Math.abs(input.r - output.r) <= maxDiff, true, "Red value difference <= " + maxDiff); | ||
equal(Math.abs(input.g - output.g) <= maxDiff, true, "Green value difference <= " + maxDiff); | ||
equal(Math.abs(input.b - output.b) <= maxDiff, true, "Blue value difference <= " + maxDiff); | ||
}); | ||
test("PRGB String", function() { | ||
var random = tinycolor.random(); | ||
var input = random.toRgb(); | ||
var output = tinycolor(random.toPercentageRgbString()).toRgb(); | ||
var maxDiff = 2; | ||
equal(Math.abs(input.r - output.r) <= maxDiff, true, "Red value difference <= " + maxDiff); | ||
equal(Math.abs(input.g - output.g) <= maxDiff, true, "Green value difference <= " + maxDiff); | ||
equal(Math.abs(input.b - output.b) <= maxDiff, true, "Blue value difference <= " + maxDiff); | ||
}); | ||
test("Object", function() { | ||
@@ -313,2 +434,4 @@ var random = tinycolor.random(); | ||
ok (tinycolor.equals("#ff0000", "#ff0000"), "Same hex"); | ||
ok (tinycolor.equals("#ff0000", "rgb(255, 0, 0)"), "Same alphas"); | ||
ok (!tinycolor.equals("#ff0000", "rgba(255, 0, 0, .1)"), "Different alphas"); | ||
ok (tinycolor.equals("ff0000", "#ff0000"), "Same hex"); | ||
@@ -319,6 +442,54 @@ ok (tinycolor.equals("#f00", "#ff0000"), "Same hex"); | ||
ok (!tinycolor.equals("#ff0000", "#00ff00"), "Different hex"); | ||
ok (tinycolor.equals("#ff8000", "rgb(100%, 50%, 0%)"), "Percentage bounds checking"); | ||
}); | ||
test("Readability", function () { | ||
ok (tinycolor.readable("#000000", "#ffffff"), "white/black is readable"); | ||
ok (!tinycolor.readable("#FF0088", "#8822AA"), "pink on pink is not readable"); | ||
equal (tinycolor.mostReadable("#000", ["#111", "#222"]).toHexString(), "#222222", "pick most readable color"); | ||
equal (tinycolor.mostReadable("#f00", ["#d00", "#0d0"]).toHexString(), "#00dd00", "pick most readable color"); | ||
}); | ||
test("Filters", function () { | ||
equal (tinycolor("red").toFilter(), "progid:DXImageTransform.Microsoft.gradient(startColorstr=#ffff0000,endColorstr=#ffff0000)"); | ||
equal (tinycolor("red").toFilter("blue"), "progid:DXImageTransform.Microsoft.gradient(startColorstr=#ffff0000,endColorstr=#ff0000ff)"); | ||
equal(tinycolor("transparent").toFilter(), "progid:DXImageTransform.Microsoft.gradient(startColorstr=#00000000,endColorstr=#00000000)"); | ||
equal(tinycolor("transparent").toFilter("red"), "progid:DXImageTransform.Microsoft.gradient(startColorstr=#00000000,endColorstr=#ffff0000)"); | ||
equal (tinycolor("#ddf0f0f0").toFilter(), "progid:DXImageTransform.Microsoft.gradient(startColorstr=#ddf0f0f0,endColorstr=#ddf0f0f0)"); | ||
equal (tinycolor("rgba(0, 0, 255, .5").toFilter(), "progid:DXImageTransform.Microsoft.gradient(startColorstr=#800000ff,endColorstr=#800000ff)"); | ||
}); | ||
/* Originally generated with: | ||
var results = []; | ||
for (var i = 0; i <= 100; i++) results.push( tinycolor.saturate("red", i).toHex() ) | ||
console.log(JSON.stringify(results)) | ||
*/ | ||
var DESATURATIONS = ["ff0000","fe0101","fc0303","fb0404","fa0505","f90606","f70808","f60909","f50a0a","f40b0b","f20d0d","f10e0e","f00f0f","ee1111","ed1212","ec1313","eb1414","e91616","e81717","e71818","e61919","e41b1b","e31c1c","e21d1d","e01f1f","df2020","de2121","dd2222","db2424","da2525","d92626","d72828","d62929","d52a2a","d42b2b","d22d2d","d12e2e","d02f2f","cf3030","cd3232","cc3333","cb3434","c93636","c83737","c73838","c63939","c43b3b","c33c3c","c23d3d","c13e3e","bf4040","be4141","bd4242","bb4444","ba4545","b94646","b84747","b64949","b54a4a","b44b4b","b34d4d","b14e4e","b04f4f","af5050","ad5252","ac5353","ab5454","aa5555","a85757","a75858","a65959","a45b5b","a35c5c","a25d5d","a15e5e","9f6060","9e6161","9d6262","9c6363","9a6565","996666","986767","966969","956a6a","946b6b","936c6c","916e6e","906f6f","8f7070","8e7171","8c7373","8b7474","8a7575","887777","877878","867979","857a7a","837c7c","827d7d","817e7e","808080"]; | ||
var SATURATIONS = ["ff0000","ff0000","ff0000","ff0000","ff0000","ff0000","ff0000","ff0000","ff0000","ff0000","ff0000","ff0000","ff0000","ff0000","ff0000","ff0000","ff0000","ff0000","ff0000","ff0000","ff0000","ff0000","ff0000","ff0000","ff0000","ff0000","ff0000","ff0000","ff0000","ff0000","ff0000","ff0000","ff0000","ff0000","ff0000","ff0000","ff0000","ff0000","ff0000","ff0000","ff0000","ff0000","ff0000","ff0000","ff0000","ff0000","ff0000","ff0000","ff0000","ff0000","ff0000","ff0000","ff0000","ff0000","ff0000","ff0000","ff0000","ff0000","ff0000","ff0000","ff0000","ff0000","ff0000","ff0000","ff0000","ff0000","ff0000","ff0000","ff0000","ff0000","ff0000","ff0000","ff0000","ff0000","ff0000","ff0000","ff0000","ff0000","ff0000","ff0000","ff0000","ff0000","ff0000","ff0000","ff0000","ff0000","ff0000","ff0000","ff0000","ff0000","ff0000","ff0000","ff0000","ff0000","ff0000","ff0000","ff0000","ff0000","ff0000","ff0000","ff0000"]; | ||
var LIGHTENS = ["ff0000","ff0505","ff0a0a","ff0f0f","ff1414","ff1a1a","ff1f1f","ff2424","ff2929","ff2e2e","ff3333","ff3838","ff3d3d","ff4242","ff4747","ff4d4d","ff5252","ff5757","ff5c5c","ff6161","ff6666","ff6b6b","ff7070","ff7575","ff7a7a","ff8080","ff8585","ff8a8a","ff8f8f","ff9494","ff9999","ff9e9e","ffa3a3","ffa8a8","ffadad","ffb3b3","ffb8b8","ffbdbd","ffc2c2","ffc7c7","ffcccc","ffd1d1","ffd6d6","ffdbdb","ffe0e0","ffe5e5","ffebeb","fff0f0","fff5f5","fffafa","ffffff","ffffff","ffffff","ffffff","ffffff","ffffff","ffffff","ffffff","ffffff","ffffff","ffffff","ffffff","ffffff","ffffff","ffffff","ffffff","ffffff","ffffff","ffffff","ffffff","ffffff","ffffff","ffffff","ffffff","ffffff","ffffff","ffffff","ffffff","ffffff","ffffff","ffffff","ffffff","ffffff","ffffff","ffffff","ffffff","ffffff","ffffff","ffffff","ffffff","ffffff","ffffff","ffffff","ffffff","ffffff","ffffff","ffffff","ffffff","ffffff","ffffff","ffffff"]; | ||
var DARKENS = ["ff0000","fa0000","f50000","f00000","eb0000","e60000","e00000","db0000","d60000","d10000","cc0000","c70000","c20000","bd0000","b80000","b30000","ad0000","a80000","a30000","9e0000","990000","940000","8f0000","8a0000","850000","800000","7a0000","750000","700000","6b0000","660000","610000","5c0000","570000","520000","4d0000","470000","420000","3d0000","380000","330000","2e0000","290000","240000","1f0000","190000","140000","0f0000","0a0000","050000","000000","000000","000000","000000","000000","000000","000000","000000","000000","000000","000000","000000","000000","000000","000000","000000","000000","000000","000000","000000","000000","000000","000000","000000","000000","000000","000000","000000","000000","000000","000000","000000","000000","000000","000000","000000","000000","000000","000000","000000","000000","000000","000000","000000","000000","000000","000000","000000","000000","000000","000000"]; | ||
test("Combinations", function () { | ||
for (var i = 0; i <= 100; i++) { | ||
equal(tinycolor.desaturate("red", i).toHex(), DESATURATIONS[i], "Desaturation " + i + " works"); | ||
} | ||
for (var i = 0; i <= 100; i++) { | ||
equal(tinycolor.saturate("red", i).toHex(), SATURATIONS[i], "Saturation " + i + " works"); | ||
} | ||
for (var i = 0; i <= 100; i++) { | ||
equal(tinycolor.lighten("red", i).toHex(), LIGHTENS[i], "Lighten " + i + " works"); | ||
} | ||
for (var i = 0; i <= 100; i++) { | ||
equal(tinycolor.darken("red", i).toHex(), DARKENS[i], "Darken " + i + " works"); | ||
} | ||
equal(tinycolor.greyscale("red").toHex(), "808080", "Greyscale works") | ||
equal(tinycolor.complement("red").toHex(), "00ffff", "Complement works"); | ||
}); | ||
/* Too slow: 1677731 possibilities | ||
@@ -325,0 +496,0 @@ asyncTest("Ajax load", function() { |
468
tinycolor.js
@@ -1,6 +0,8 @@ | ||
// TinyColor.js - <https://github.com/bgrins/TinyColor> - 2011 Brian Grinstead - v0.5 | ||
// TinyColor v0.9.16 | ||
// https://github.com/bgrins/TinyColor | ||
// 2013-08-10, Brian Grinstead, MIT License | ||
(function(root) { | ||
(function() { | ||
var trimLeft = /^[\s,#]+/, | ||
var trimLeft = /^[\s,#]+/, | ||
trimRight = /\s+$/, | ||
@@ -13,6 +15,8 @@ tinyCounter = 0, | ||
mathRandom = math.random; | ||
// parseFloat redeclaration caused errors in Node | ||
function tinycolor (color, opts) { | ||
color = (color) ? color : ''; | ||
opts = opts || { }; | ||
// If input is already a tinycolor, return itself | ||
@@ -22,3 +26,3 @@ if (typeof color == "object" && color.hasOwnProperty("_tc_id")) { | ||
} | ||
var rgb = inputToRGB(color); | ||
@@ -28,9 +32,9 @@ var r = rgb.r, | ||
b = rgb.b, | ||
a = parseFloat(rgb.a), | ||
a = rgb.a, | ||
roundA = mathRound(100*a) / 100, | ||
format = rgb.format; | ||
// Don't let the range of [0,255] come back in [0,1]. | ||
format = opts.format || rgb.format; | ||
// Don't let the range of [0,255] come back in [0,1]. | ||
// Potentially lose a little bit of precision here, but will fix issues where | ||
// .5 gets interpreted as half of the total, instead of half of 1 | ||
// .5 gets interpreted as half of the total, instead of half of 1 | ||
// If it was supposed to be 128, this was already taken care of by `inputToRgb` | ||
@@ -40,3 +44,3 @@ if (r < 1) { r = mathRound(r); } | ||
if (b < 1) { b = mathRound(b); } | ||
return { | ||
@@ -47,2 +51,9 @@ ok: rgb.ok, | ||
alpha: a, | ||
getAlpha: function() { | ||
return a; | ||
}, | ||
setAlpha: function(value) { | ||
a = boundAlpha(value); | ||
roundA = mathRound(100*a) / 100; | ||
}, | ||
toHsv: function() { | ||
@@ -55,4 +66,4 @@ var hsv = rgbToHsv(r, g, b); | ||
var h = mathRound(hsv.h * 360), s = mathRound(hsv.s * 100), v = mathRound(hsv.v * 100); | ||
return (a == 1) ? | ||
"hsv(" + h + ", " + s + "%, " + v + "%)" : | ||
return (a == 1) ? | ||
"hsv(" + h + ", " + s + "%, " + v + "%)" : | ||
"hsva(" + h + ", " + s + "%, " + v + "%, "+ roundA + ")"; | ||
@@ -67,12 +78,18 @@ }, | ||
var h = mathRound(hsl.h * 360), s = mathRound(hsl.s * 100), l = mathRound(hsl.l * 100); | ||
return (a == 1) ? | ||
"hsl(" + h + ", " + s + "%, " + l + "%)" : | ||
return (a == 1) ? | ||
"hsl(" + h + ", " + s + "%, " + l + "%)" : | ||
"hsla(" + h + ", " + s + "%, " + l + "%, "+ roundA + ")"; | ||
}, | ||
toHex: function() { | ||
return rgbToHex(r, g, b); | ||
toHex: function(allow3Char) { | ||
return rgbToHex(r, g, b, allow3Char); | ||
}, | ||
toHexString: function() { | ||
return '#' + rgbToHex(r, g, b); | ||
toHexString: function(allow3Char) { | ||
return '#' + this.toHex(allow3Char); | ||
}, | ||
toHex8: function() { | ||
return rgbaToHex(r, g, b, a); | ||
}, | ||
toHex8String: function() { | ||
return '#' + this.toHex8(); | ||
}, | ||
toRgb: function() { | ||
@@ -82,24 +99,56 @@ return { r: mathRound(r), g: mathRound(g), b: mathRound(b), a: a }; | ||
toRgbString: function() { | ||
return (a == 1) ? | ||
return (a == 1) ? | ||
"rgb(" + mathRound(r) + ", " + mathRound(g) + ", " + mathRound(b) + ")" : | ||
"rgba(" + mathRound(r) + ", " + mathRound(g) + ", " + mathRound(b) + ", " + roundA + ")"; | ||
}, | ||
toPercentageRgb: function() { | ||
return { r: mathRound(bound01(r, 255) * 100) + "%", g: mathRound(bound01(g, 255) * 100) + "%", b: mathRound(bound01(b, 255) * 100) + "%", a: a }; | ||
}, | ||
toPercentageRgbString: function() { | ||
return (a == 1) ? | ||
"rgb(" + mathRound(bound01(r, 255) * 100) + "%, " + mathRound(bound01(g, 255) * 100) + "%, " + mathRound(bound01(b, 255) * 100) + "%)" : | ||
"rgba(" + mathRound(bound01(r, 255) * 100) + "%, " + mathRound(bound01(g, 255) * 100) + "%, " + mathRound(bound01(b, 255) * 100) + "%, " + roundA + ")"; | ||
}, | ||
toName: function() { | ||
return hexNames[rgbToHex(r, g, b)] || false; | ||
if (a === 0) { | ||
return "transparent"; | ||
} | ||
return hexNames[rgbToHex(r, g, b, true)] || false; | ||
}, | ||
toFilter: function() { | ||
var hex = rgbToHex(r, g, b); | ||
var alphaHex = Math.round(parseFloat(a) * 255).toString(16); | ||
return "progid:DXImageTransform.Microsoft.gradient(startColorstr=#" + | ||
alphaHex + hex + ",endColorstr=#" + alphaHex + hex + ")"; | ||
toFilter: function(secondColor) { | ||
var hex8String = '#' + rgbaToHex(r, g, b, a); | ||
var secondHex8String = hex8String; | ||
var gradientType = opts && opts.gradientType ? "GradientType = 1, " : ""; | ||
if (secondColor) { | ||
var s = tinycolor(secondColor); | ||
secondHex8String = s.toHex8String(); | ||
} | ||
return "progid:DXImageTransform.Microsoft.gradient("+gradientType+"startColorstr="+hex8String+",endColorstr="+secondHex8String+")"; | ||
}, | ||
toString: function(format) { | ||
var formatSet = !!format; | ||
format = format || this.format; | ||
var formattedString = false; | ||
var hasAlphaAndFormatNotSet = !formatSet && a < 1 && a > 0; | ||
var formatWithAlpha = hasAlphaAndFormatNotSet && (format === "hex" || format === "hex6" || format === "hex3" || format === "name"); | ||
if (format === "rgb") { | ||
formattedString = this.toRgbString(); | ||
} | ||
if (format === "hex") { | ||
if (format === "prgb") { | ||
formattedString = this.toPercentageRgbString(); | ||
} | ||
if (format === "hex" || format === "hex6") { | ||
formattedString = this.toHexString(); | ||
} | ||
if (format === "hex3") { | ||
formattedString = this.toHexString(true); | ||
} | ||
if (format === "hex8") { | ||
formattedString = this.toHex8String(); | ||
} | ||
if (format === "name") { | ||
@@ -114,3 +163,7 @@ formattedString = this.toName(); | ||
} | ||
if (formatWithAlpha) { | ||
return this.toRgbString(); | ||
} | ||
return formattedString || this.toHexString(); | ||
@@ -123,7 +176,14 @@ } | ||
// String input requires "1.0" as input, so 1 will be treated as 1 | ||
tinycolor.fromRatio = function(color) { | ||
tinycolor.fromRatio = function(color, opts) { | ||
if (typeof color == "object") { | ||
var newColor = {}; | ||
var newColor = {}; | ||
for (var i in color) { | ||
newColor[i] = convertToPercentage(color[i]); | ||
if (color.hasOwnProperty(i)) { | ||
if (i === "a") { | ||
newColor[i] = color[i]; | ||
} | ||
else { | ||
newColor[i] = convertToPercentage(color[i]); | ||
} | ||
} | ||
} | ||
@@ -133,4 +193,4 @@ color = newColor; | ||
return tinycolor(color); | ||
} | ||
return tinycolor(color, opts); | ||
}; | ||
@@ -143,6 +203,7 @@ // Given a string or object, convert that input to RGB | ||
// "#ff0000" or "ff0000" | ||
// "#ff000000" or "ff000000" | ||
// "rgb 255 0 0" or "rgb (255, 0, 0)" | ||
// "rgb 1.0 0 0" or "rgb (1, 0, 0)" | ||
// "rgba (255, 0, 0, 1)" or "rgba 255, 0, 0, 1" | ||
// "rgba (1.0, 0, 0, 1)" or "rgba 1.0, 0, 0, 1" | ||
// "rgba (1.0, 0, 0, 1)" or "rgba 1.0, 0, 0, 1" | ||
// "hsl(0, 100%, 50%)" or "hsl 0 100% 50%" | ||
@@ -154,11 +215,11 @@ // "hsla(0, 100%, 50%, 1)" or "hsla 0 100% 50%, 1" | ||
var rgb = { r: 255, g: 255, b: 255 }; | ||
var rgb = { r: 0, g: 0, b: 0 }; | ||
var a = 1; | ||
var ok = false; | ||
var format = false; | ||
if (typeof color == "string") { | ||
color = stringInputToObject(color); | ||
} | ||
if (typeof color == "object") { | ||
@@ -168,3 +229,3 @@ if (color.hasOwnProperty("r") && color.hasOwnProperty("g") && color.hasOwnProperty("b")) { | ||
ok = true; | ||
format = "rgb"; | ||
format = String(color.r).substr(-1) === "%" ? "prgb" : "rgb"; | ||
} | ||
@@ -181,7 +242,7 @@ else if (color.hasOwnProperty("h") && color.hasOwnProperty("s") && color.hasOwnProperty("v")) { | ||
color.l = convertToPercentage(color.l); | ||
var rgb = hslToRgb(color.h, color.s, color.l); | ||
rgb = hslToRgb(color.h, color.s, color.l); | ||
ok = true; | ||
format = "hsl"; | ||
} | ||
if (color.hasOwnProperty("a")) { | ||
@@ -191,3 +252,5 @@ a = color.a; | ||
} | ||
a = boundAlpha(a); | ||
return { | ||
@@ -204,17 +267,16 @@ ok: ok, | ||
// Conversion Functions | ||
// -------------------- | ||
// `rgbToHsl`, `rgbToHsv`, `hslToRgb`, `hsvToRgb` modified from: | ||
// `rgbToHsl`, `rgbToHsv`, `hslToRgb`, `hsvToRgb` modified from: | ||
// <http://mjijackson.com/2008/02/rgb-to-hsl-and-rgb-to-hsv-color-model-conversion-algorithms-in-javascript> | ||
// `rgbToRgb` | ||
// `rgbToRgb` | ||
// Handle bounds / percentage checking to conform to CSS color spec | ||
// <http://www.w3.org/TR/css3-color/> | ||
// *Assumes:* r, g, b in [0, 255] or [0, 1] | ||
// <http://www.w3.org/TR/css3-color/> | ||
// *Assumes:* r, g, b in [0, 255] or [0, 1] | ||
// *Returns:* { r, g, b } in [0, 255] | ||
function rgbToRgb(r, g, b){ | ||
return { | ||
r: bound01(r, 255) * 255, | ||
function rgbToRgb(r, g, b){ | ||
return { | ||
r: bound01(r, 255) * 255, | ||
g: bound01(g, 255) * 255, | ||
@@ -225,12 +287,12 @@ b: bound01(b, 255) * 255 | ||
// `rgbToHsl` | ||
// Converts an RGB color value to HSL. | ||
// *Assumes:* r, g, and b are contained in [0, 255] or [0, 1] | ||
// *Returns:* { h, s, l } in [0,1] | ||
// `rgbToHsl` | ||
// Converts an RGB color value to HSL. | ||
// *Assumes:* r, g, and b are contained in [0, 255] or [0, 1] | ||
// *Returns:* { h, s, l } in [0,1] | ||
function rgbToHsl(r, g, b) { | ||
r = bound01(r, 255); | ||
g = bound01(g, 255); | ||
b = bound01(b, 255); | ||
var max = mathMax(r, g, b), min = mathMin(r, g, b); | ||
@@ -250,3 +312,3 @@ var h, s, l = (max + min) / 2; | ||
} | ||
h /= 6; | ||
@@ -258,6 +320,6 @@ } | ||
// `hslToRgb` | ||
// Converts an HSL color value to RGB. | ||
// *Assumes:* h is contained in [0, 1] or [0, 360] and s and l are contained [0, 1] or [0, 100] | ||
// *Returns:* { r, g, b } in the set [0, 255] | ||
// `hslToRgb` | ||
// Converts an HSL color value to RGB. | ||
// *Assumes:* h is contained in [0, 1] or [0, 360] and s and l are contained [0, 1] or [0, 100] | ||
// *Returns:* { r, g, b } in the set [0, 255] | ||
function hslToRgb(h, s, l) { | ||
@@ -269,3 +331,3 @@ var r, g, b; | ||
l = bound01(l, 100); | ||
function hue2rgb(p, q, t) { | ||
@@ -279,4 +341,4 @@ if(t < 0) t += 1; | ||
} | ||
if(s == 0) { | ||
if(s === 0) { | ||
r = g = b = l; // achromatic | ||
@@ -295,6 +357,6 @@ } | ||
// `rgbToHsv` | ||
// Converts an RGB color value to HSV | ||
// *Assumes:* r, g, and b are contained in the set [0, 255] or [0, 1] | ||
// *Returns:* { h, s, v } in [0,1] | ||
// `rgbToHsv` | ||
// Converts an RGB color value to HSV | ||
// *Assumes:* r, g, and b are contained in the set [0, 255] or [0, 1] | ||
// *Returns:* { h, s, v } in [0,1] | ||
function rgbToHsv(r, g, b) { | ||
@@ -305,3 +367,3 @@ | ||
b = bound01(b, 255); | ||
var max = mathMax(r, g, b), min = mathMin(r, g, b); | ||
@@ -311,3 +373,3 @@ var h, s, v = max; | ||
var d = max - min; | ||
s = max == 0 ? 0 : d / max; | ||
s = max === 0 ? 0 : d / max; | ||
@@ -328,9 +390,8 @@ if(max == min) { | ||
// `hsvToRgb` | ||
// Converts an HSV color value to RGB. | ||
// `hsvToRgb` | ||
// Converts an HSV color value to RGB. | ||
// *Assumes:* h is contained in [0, 1] or [0, 360] and s and v are contained in [0, 1] or [0, 100] | ||
// *Returns:* { r, g, b } in the set [0, 255] | ||
function hsvToRgb(h, s, v) { | ||
var r, g, b; | ||
h = bound01(h, 360) * 6; | ||
@@ -349,35 +410,46 @@ s = bound01(s, 100); | ||
b = [p, p, t, v, v, q][mod]; | ||
return { r: r * 255, g: g * 255, b: b * 255 }; | ||
} | ||
// `rgbToHex` | ||
// Converts an RGB color to hex | ||
// Assumes r, g, and b are contained in the set [0, 255] | ||
// Returns a 3 or 6 character hex | ||
function rgbToHex(r, g, b) { | ||
function pad(c) { | ||
return c.length == 1 ? '0' + c : '' + c; | ||
} | ||
var hex = [ | ||
pad(mathRound(r).toString(16)), | ||
pad(mathRound(g).toString(16)), | ||
pad(mathRound(b).toString(16)) | ||
// `rgbToHex` | ||
// Converts an RGB color to hex | ||
// Assumes r, g, and b are contained in the set [0, 255] | ||
// Returns a 3 or 6 character hex | ||
function rgbToHex(r, g, b, allow3Char) { | ||
var hex = [ | ||
pad2(mathRound(r).toString(16)), | ||
pad2(mathRound(g).toString(16)), | ||
pad2(mathRound(b).toString(16)) | ||
]; | ||
// Return a 3 character hex if possible | ||
if (hex[0][0] == hex[0][1] && hex[1][0] == hex[1][1] && hex[2][0] == hex[2][1]) { | ||
return hex[0][0] + hex[1][0] + hex[2][0]; | ||
if (allow3Char && hex[0].charAt(0) == hex[0].charAt(1) && hex[1].charAt(0) == hex[1].charAt(1) && hex[2].charAt(0) == hex[2].charAt(1)) { | ||
return hex[0].charAt(0) + hex[1].charAt(0) + hex[2].charAt(0); | ||
} | ||
return hex.join(""); | ||
} | ||
// `rgbaToHex` | ||
// Converts an RGBA color plus alpha transparency to hex | ||
// Assumes r, g, b and a are contained in the set [0, 255] | ||
// Returns an 8 character hex | ||
function rgbaToHex(r, g, b, a) { | ||
// `equals` | ||
var hex = [ | ||
pad2(convertDecimalToHex(a)), | ||
pad2(mathRound(r).toString(16)), | ||
pad2(mathRound(g).toString(16)), | ||
pad2(mathRound(b).toString(16)) | ||
]; | ||
return hex.join(""); | ||
} | ||
// `equals` | ||
// Can be called with any tinycolor input | ||
tinycolor.equals = function(color1, color2) { | ||
if (!color1 || !color2) { | ||
return false; | ||
} | ||
return tinycolor(color1).toHex() == tinycolor(color2).toHex(); | ||
tinycolor.equals = function (color1, color2) { | ||
if (!color1 || !color2) { return false; } | ||
return tinycolor(color1).toRgbString() == tinycolor(color2).toRgbString(); | ||
}; | ||
@@ -395,9 +467,9 @@ tinycolor.random = function() { | ||
// ---------------------- | ||
// Thanks to less.js for some of the basics here | ||
// Thanks to less.js for some of the basics here | ||
// <https://github.com/cloudhead/less.js/blob/master/lib/less/functions.js> | ||
tinycolor.desaturate = function (color, amount) { | ||
amount = (amount === 0) ? 0 : (amount || 10); | ||
var hsl = tinycolor(color).toHsl(); | ||
hsl.s -= ((amount || 10) / 100); | ||
hsl.s -= amount / 100; | ||
hsl.s = clamp01(hsl.s); | ||
@@ -407,4 +479,5 @@ return tinycolor(hsl); | ||
tinycolor.saturate = function (color, amount) { | ||
amount = (amount === 0) ? 0 : (amount || 10); | ||
var hsl = tinycolor(color).toHsl(); | ||
hsl.s += ((amount || 10) / 100); | ||
hsl.s += amount / 100; | ||
hsl.s = clamp01(hsl.s); | ||
@@ -417,4 +490,5 @@ return tinycolor(hsl); | ||
tinycolor.lighten = function(color, amount) { | ||
amount = (amount === 0) ? 0 : (amount || 10); | ||
var hsl = tinycolor(color).toHsl(); | ||
hsl.l += ((amount || 10) / 100); | ||
hsl.l += amount / 100; | ||
hsl.l = clamp01(hsl.l); | ||
@@ -424,4 +498,5 @@ return tinycolor(hsl); | ||
tinycolor.darken = function (color, amount) { | ||
amount = (amount === 0) ? 0 : (amount || 10); | ||
var hsl = tinycolor(color).toHsl(); | ||
hsl.l -= ((amount || 10) / 100); | ||
hsl.l -= amount / 100; | ||
hsl.l = clamp01(hsl.l); | ||
@@ -473,5 +548,5 @@ return tinycolor(hsl); | ||
slices = slices || 30; | ||
var hsl = tinycolor(color).toHsl(); | ||
var part = 360 / slices | ||
var part = 360 / slices; | ||
var ret = [tinycolor(color)]; | ||
@@ -491,3 +566,3 @@ | ||
var modification = 1 / results; | ||
while (results--) { | ||
@@ -497,16 +572,74 @@ ret.push(tinycolor({ h: h, s: s, v: v})); | ||
} | ||
return ret; | ||
}; | ||
// Readability Functions | ||
// --------------------- | ||
// <http://www.w3.org/TR/AERT#color-contrast> | ||
// `readability` | ||
// Analyze the 2 colors and returns an object with the following properties: | ||
// `brightness`: difference in brightness between the two colors | ||
// `color`: difference in color/hue between the two colors | ||
tinycolor.readability = function(color1, color2) { | ||
var a = tinycolor(color1).toRgb(); | ||
var b = tinycolor(color2).toRgb(); | ||
var brightnessA = (a.r * 299 + a.g * 587 + a.b * 114) / 1000; | ||
var brightnessB = (b.r * 299 + b.g * 587 + b.b * 114) / 1000; | ||
var colorDiff = ( | ||
Math.max(a.r, b.r) - Math.min(a.r, b.r) + | ||
Math.max(a.g, b.g) - Math.min(a.g, b.g) + | ||
Math.max(a.b, b.b) - Math.min(a.b, b.b) | ||
); | ||
return { | ||
brightness: Math.abs(brightnessA - brightnessB), | ||
color: colorDiff | ||
}; | ||
}; | ||
// `readable` | ||
// http://www.w3.org/TR/AERT#color-contrast | ||
// Ensure that foreground and background color combinations provide sufficient contrast. | ||
// *Example* | ||
// tinycolor.readable("#000", "#111") => false | ||
tinycolor.readable = function(color1, color2) { | ||
var a = tinycolor(color1).toRgb(), b = tinycolor(color2).toRgb(); | ||
return ( | ||
(b.r - a.r) * (b.r - a.r) + | ||
(b.g - a.g) * (b.g - a.g) + | ||
(b.b - a.b) * (b.b - a.b) | ||
) > 0x28A4; | ||
var readability = tinycolor.readability(color1, color2); | ||
return readability.brightness > 125 && readability.color > 500; | ||
}; | ||
// `mostReadable` | ||
// Given a base color and a list of possible foreground or background | ||
// colors for that base, returns the most readable color. | ||
// *Example* | ||
// tinycolor.mostReadable("#123", ["#fff", "#000"]) => "#000" | ||
tinycolor.mostReadable = function(baseColor, colorList) { | ||
var bestColor = null; | ||
var bestScore = 0; | ||
var bestIsReadable = false; | ||
for (var i=0; i < colorList.length; i++) { | ||
// We normalize both around the "acceptable" breaking point, | ||
// but rank brightness constrast higher than hue. | ||
var readability = tinycolor.readability(baseColor, colorList[i]); | ||
var readable = readability.brightness > 125 && readability.color > 500; | ||
var score = 3 * (readability.brightness / 125) + (readability.color / 500); | ||
if ((readable && ! bestIsReadable) || | ||
(readable && bestIsReadable && score > bestScore) || | ||
((! readable) && (! bestIsReadable) && score > bestScore)) { | ||
bestIsReadable = readable; | ||
bestScore = score; | ||
bestColor = tinycolor(colorList[i]); | ||
} | ||
} | ||
return bestColor; | ||
}; | ||
// Big List of Colors | ||
// --------- | ||
// ------------------ | ||
// <http://www.w3.org/TR/css3-color/#svg-color> | ||
@@ -682,14 +815,25 @@ var names = tinycolor.names = { | ||
// Return a valid alpha value [0,1] with all invalid values being set to 1 | ||
function boundAlpha(a) { | ||
a = parseFloat(a); | ||
if (isNaN(a) || a < 0 || a > 1) { | ||
a = 1; | ||
} | ||
return a; | ||
} | ||
// Take input from [0, n] and return it as [0, 1] | ||
function bound01(n, max) { | ||
if (isOnePointZero(n)) { n = "100%"; } | ||
var processPercent = isPercentage(n); | ||
n = mathMin(max, mathMax(0, parseFloat(n))); | ||
// Automatically convert percentage into number | ||
if (processPercent) { | ||
n = parseInt(n * max) / 100; | ||
n = parseInt(n * max, 10) / 100; | ||
} | ||
// Handle floating point rounding errors | ||
@@ -699,3 +843,3 @@ if ((math.abs(n - max) < 0.000001)) { | ||
} | ||
// Convert into [0, 1] range if it isn't already | ||
@@ -710,4 +854,4 @@ return (n % max) / parseFloat(max); | ||
// Parse an integer into hex | ||
function parseHex(val) { | ||
// Parse a base-16 hex value into a base-10 integer | ||
function parseIntFromHex(val) { | ||
return parseInt(val, 16); | ||
@@ -727,2 +871,7 @@ } | ||
// Force a hex value to have 2 characters | ||
function pad2(c) { | ||
return c.length == 1 ? '0' + c : '' + c; | ||
} | ||
// Replace a decimal with it's percentage value | ||
@@ -733,23 +882,32 @@ function convertToPercentage(n) { | ||
} | ||
return n; | ||
} | ||
// Converts a decimal to a hex value | ||
function convertDecimalToHex(d) { | ||
return Math.round(parseFloat(d) * 255).toString(16); | ||
} | ||
// Converts a hex value to a decimal | ||
function convertHexToDecimal(h) { | ||
return (parseIntFromHex(h) / 255); | ||
} | ||
var matchers = (function() { | ||
// <http://www.w3.org/TR/css3-values/#integers> | ||
var CSS_INTEGER = "[-\\+]?\\d+%?"; | ||
var CSS_INTEGER = "[-\\+]?\\d+%?"; | ||
// <http://www.w3.org/TR/css3-values/#number-value> | ||
var CSS_NUMBER = "[-\\+]?\\d*\\.\\d+%?"; | ||
var CSS_NUMBER = "[-\\+]?\\d*\\.\\d+%?"; | ||
// Allow positive/negative integer/number. Don't capture the either/or, just the entire outcome. | ||
var CSS_UNIT = "(?:" + CSS_NUMBER + ")|(?:" + CSS_INTEGER + ")"; | ||
// Actual matching. | ||
// Parentheses and commas are optional, but not required. | ||
var CSS_UNIT = "(?:" + CSS_NUMBER + ")|(?:" + CSS_INTEGER + ")"; | ||
// Actual matching. | ||
// Parentheses and commas are optional, but not required. | ||
// Whitespace can take the place of commas or opening paren | ||
var PERMISSIVE_MATCH3 = "[\\s|\\(]+(" + CSS_UNIT + ")[,|\\s]+(" + CSS_UNIT + ")[,|\\s]+(" + CSS_UNIT + ")\\s*\\)?"; | ||
var PERMISSIVE_MATCH4 = "[\\s|\\(]+(" + CSS_UNIT + ")[,|\\s]+(" + CSS_UNIT + ")[,|\\s]+(" + CSS_UNIT + ")[,|\\s]+(" + CSS_UNIT + ")\\s*\\)?"; | ||
return { | ||
@@ -762,7 +920,8 @@ rgb: new RegExp("rgb" + PERMISSIVE_MATCH3), | ||
hex3: /^([0-9a-fA-F]{1})([0-9a-fA-F]{1})([0-9a-fA-F]{1})$/, | ||
hex6: /^([0-9a-fA-F]{2})([0-9a-fA-F]{2})([0-9a-fA-F]{2})$/ | ||
hex6: /^([0-9a-fA-F]{2})([0-9a-fA-F]{2})([0-9a-fA-F]{2})$/, | ||
hex8: /^([0-9a-fA-F]{2})([0-9a-fA-F]{2})([0-9a-fA-F]{2})([0-9a-fA-F]{2})$/ | ||
}; | ||
})(); | ||
// `stringInputToObject` | ||
// `stringInputToObject` | ||
// Permissive string parsing. Take in a number of formats, and output an object | ||
@@ -778,9 +937,9 @@ // based on detected format. Returns `{ r, g, b }` or `{ h, s, l }` or `{ h, s, v}` | ||
} | ||
else if (color == 'transparent') { | ||
return { r: 0, g: 0, b: 0, a: 0 }; | ||
else if (color == 'transparent') { | ||
return { r: 0, g: 0, b: 0, a: 0, format: "name" }; | ||
} | ||
// Try to match string input using regular expressions. | ||
// Keep most of the number bounding out of this function - don't worry about [0,1] or [0,100] or [0,360] | ||
// Just return an object and let the conversion functions handle that. | ||
// Try to match string input using regular expressions. | ||
// Keep most of the number bounding out of this function - don't worry about [0,1] or [0,100] or [0,360] | ||
// Just return an object and let the conversion functions handle that. | ||
// This way the result will be the same whether the tinycolor is initialized with string or object. | ||
@@ -803,7 +962,16 @@ var match; | ||
} | ||
if ((match = matchers.hex8.exec(color))) { | ||
return { | ||
a: convertHexToDecimal(match[1]), | ||
r: parseIntFromHex(match[2]), | ||
g: parseIntFromHex(match[3]), | ||
b: parseIntFromHex(match[4]), | ||
format: named ? "name" : "hex8" | ||
}; | ||
} | ||
if ((match = matchers.hex6.exec(color))) { | ||
return { | ||
r: parseHex(match[1]), | ||
g: parseHex(match[2]), | ||
b: parseHex(match[3]), | ||
r: parseIntFromHex(match[1]), | ||
g: parseIntFromHex(match[2]), | ||
b: parseIntFromHex(match[3]), | ||
format: named ? "name" : "hex" | ||
@@ -814,9 +982,9 @@ }; | ||
return { | ||
r: parseHex(match[1] + '' + match[1]), | ||
g: parseHex(match[2] + '' + match[2]), | ||
b: parseHex(match[3] + '' + match[3]), | ||
r: parseIntFromHex(match[1] + '' + match[1]), | ||
g: parseIntFromHex(match[2] + '' + match[2]), | ||
b: parseIntFromHex(match[3] + '' + match[3]), | ||
format: named ? "name" : "hex" | ||
}; | ||
} | ||
return false; | ||
@@ -829,7 +997,11 @@ } | ||
} | ||
// AMD/requirejs: Define the module | ||
else if (typeof define !== "undefined") { | ||
define(function () {return tinycolor;}); | ||
} | ||
// Browser: Expose to window | ||
else { | ||
root.tinycolor = tinycolor; | ||
window.tinycolor = tinycolor; | ||
} | ||
})(this); | ||
})(); |
Sorry, the diff of this file is not supported yet
Sorry, the diff of this file is not supported yet
Sorry, the diff of this file is not supported yet
Sorry, the diff of this file is not supported yet
Sorry, the diff of this file is not supported yet
Sorry, the diff of this file is not supported yet
Sorry, the diff of this file is not supported yet
Sorry, the diff of this file is not supported yet
License Policy Violation
LicenseThis package is not allowed per your license policy. Review the package's license to ensure compliance.
Found 1 instance in 1 package
New author
Supply chain riskA new npm collaborator published a version of the package for the first time. New collaborators are usually benign additions to a project, but do indicate a change to the security surface area of a package.
Found 1 instance in 1 package
License Policy Violation
LicenseThis package is not allowed per your license policy. Review the package's license to ensure compliance.
Found 1 instance in 1 package
Non-existent author
Supply chain riskThe package was published by an npm account that no longer exists.
Found 1 instance in 1 package
12626952
23
19011
134
0
6
1