Permalink
Browse files

Added one.color files

  • Loading branch information...
0 parents commit a37d557faede3898a0e268169df3874e2fca724d @Munter Munter committed Feb 25, 2011
28 LICENSE
@@ -0,0 +1,28 @@
+Copyright (c) 2011, One.com
+All rights reserved.
+
+Redistribution and use in source and binary forms, with or without
+modification, are permitted provided that the following conditions are
+met:
+
+ * Redistributions of source code must retain the above copyright
+ notice, this list of conditions and the following disclaimer.
+ * Redistributions in binary form must reproduce the above copyright
+ notice, this list of conditions and the following disclaimer in
+ the documentation and/or other materials provided with the
+ distribution.
+ * Neither the name of the author nor the names of contributors may
+ be used to endorse or promote products derived from this
+ software without specific prior written permission.
+
+THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS
+IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED
+TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A
+PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
+HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
+SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
+LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
+DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
+THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
+(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
+OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
@@ -0,0 +1,15 @@
+jsfiles := $(shell find lib/ -type f -name "*.js")
+outputfiles := one-color-debug.js one-color.js
+
+.PHONY : all clean
+
+all: $(outputfiles)
+
+one-color-debug.js: $(jsfiles)
+ flattenOneInclude lib/one/color/_all.js --label js=lib > $@
+
+one-color.js: one-color-debug.js
+ yui-compressor --type js $< > $@
+
+clean:
+ rm -f $(outputfiles)
@@ -0,0 +1,37 @@
+one.color
+=========
+one.color is a javascript color calculation toolkit.
+Works in Node.js and in the browser.
+
+Features
+========
+* RGB, HSV, HSL and CMYK color space implementations
+* Alpha channel
+* Extensible architectre - implement your own color spaces easily
+* Chainable color manipulation
+* Seamless conversion between color spaces on demand
+* Outputs as Hex, RBG or HSV in css syntax with or without alpha channel
+
+Building
+========
+The makefile uses `AssetGraph <https://github.com/One-com/assetgraph>`_ for resolving the javascript dependencies.
+If you aren't up for a complete installation, take a look at the pre-build packages in the 'build' directory.
+
+Documentation
+=============
+The API is documented in the source code and can be built using `JSDoc <http://jsdoc.sourceforge.net/>`_.
+
+Usage Example
+=============
+one.color.(RGB|HSL|HSV|CMYK) objects are designed to be immutable; all the conversion, set, and adjust methods return new objects.
+one.color.(RGB|HSL|HSV|CMYK) objects automatically get the set and adjust methods from all other installed colorspaces, so although you can use the explicit conversion methods one.color.RGB.toHSL(), one.color.RGB.toCMYK():
+
+Example::
+ new one.color.RGB(.4, .3, .9).
+ adjustLightness(+.2). // Implicit conversion to HSL
+ setRed(-.1). // Implicit conversion back to RGB
+ toHex(); // "#00a6f2"
+
+License
+========
+one.color is licensed under a standard 3-clause BSD license -- see the LICENSE-file for details.
@@ -0,0 +1,16 @@
+(function () {
+ /** @exports stringPrototype as String.prototype*/
+ var stringPrototype = String.prototype;
+
+ /**
+ * <p>Returns this string with the char at first position in uppercase.</p>
+ * <p>Example of use:</p><pre><code>
+ "the brown Fox jumped over the lazy Dog".capitalize(); // = "The brown Fox jumped over the lazy Dog"
+ </code></pre>
+ * @return capitalized string.
+ * @memberOf String.prototype
+ */
+ stringPrototype.capitalize = function () {
+ return this.charAt(0).toUpperCase() + this.substring(1);
+ };
+}());
@@ -0,0 +1,9 @@
+/*global window*/
+
+/**
+ * @namespace one One.com global JavaScript namespace.
+ * @exports window.one as one
+ */
+window.one = window.one || {};
+
+one.include = one.exclude = function () {}; // Ignore these in development mode
@@ -0,0 +1,125 @@
+/*global one*/
+one.include('js:one/color.js');
+one.include('js:String-capitalize.js');
+
+/*jslint evil:true*/
+
+one.color.installedColorSpaces = [];
+
+one.color.installColorSpace = function (colorSpaceName, propertyDefinitions, config) {
+ var propertyNames = propertyDefinitions.map(function (propertyDefinition) {
+ return propertyDefinition.match(/[A-Z]/)[0].toLowerCase();
+ }),
+ longPropertyNames = propertyDefinitions.map(function (propertyDefinition) {
+ return propertyDefinition.toLowerCase().capitalize();
+ }),
+ Constructor = one.color[colorSpaceName] = new Function(propertyNames.join(","),
+ // Allow passing an array to the constructor:
+ "if (Object.prototype.toString.apply(" + propertyNames[0] + ") === '[object Array]') {" +
+ propertyNames.map(function (propertyName, i) {
+ return propertyName + "=" + propertyNames[0] + "[" + i + "];";
+ }).reverse().join("") +
+ "}" +
+ "if (" + propertyNames.filter(function (propertyName) {
+ return propertyName !== 'a';
+ }).map(function (propertyName) {
+ return "isNaN(" + propertyName + ")";
+ }).join("||") + "){" + "throw \"[one.color." + colorSpaceName + "]: Invalid color: (\"+" + propertyNames.join("+\",\"+") + "+\")\";}" +
+ propertyNames.map(function (propertyName) {
+ if (propertyName === 'h') {
+ return "this.h=h<0?h-Math.floor(h):h%1"; // Wrap
+ } else if (propertyName === 'a') {
+ return "this.a=(isNaN(a)||a>1)?1:(a<0?0:a);";
+ } else {
+ return "this." + propertyName + "=" + propertyName + "<0?0:(" + propertyName + ">1?1:" + propertyName + ")";
+ }
+ }).join(";") + ";"
+ ),
+ prototype = Constructor.prototype;
+
+ Constructor.propertyNames = propertyNames;
+ Constructor.longPropertyNames = longPropertyNames;
+
+ ['valueOf', 'toHex', 'toCSS', 'toCSSWithAlpha'].forEach(function (methodName) {
+ prototype[methodName] = prototype[methodName] || (colorSpaceName === 'RGB' ? prototype.toHex : new Function("return this.toRGB()." + methodName + "();"));
+ });
+
+ prototype.isColor = true;
+
+ prototype.equals = function (otherColor, epsilon) {
+ if (typeof epsilon === 'undefined') {
+ epsilon = 1e-10;
+ }
+
+ otherColor = otherColor['to' + colorSpaceName]();
+
+ for (var i = 0; i < propertyNames.length; i = i + 1) {
+ if (Math.abs(this[propertyNames[i]] - otherColor[propertyNames[i]]) > epsilon) {
+ return false;
+ }
+ }
+
+ return true;
+ };
+
+ prototype.toJSON = new Function(
+ "return ['" + colorSpaceName + "', " +
+ propertyNames.map(function (propertyName) {
+ return "this." + propertyName;
+ }, this).join(", ") +
+ "];"
+ );
+
+ if (config.fromRGB) {
+ one.color.RGB.prototype['to' + colorSpaceName] = config.fromRGB;
+ delete config.fromRGB;
+ }
+ for (var prop in config) {
+ if (config.hasOwnProperty(prop)) {
+ prototype[prop] = config[prop];
+ }
+ }
+
+ // It is pretty easy to implement the conversion to the same color space:
+ prototype['to' + colorSpaceName] = function () {
+ return this;
+ };
+ prototype.toString = new Function("return \"[one.color." + colorSpaceName + ":\"+" + propertyNames.map(function (propertyName, i) {
+ return "\" " + longPropertyNames[i] + "=\"+this." + propertyName;
+ }).join("+") + "+\"]\";");
+
+ // Generate getters and setters
+ propertyNames.forEach(function (propertyName, i) {
+ var longPropertyName = longPropertyNames[i];
+ prototype['get' + longPropertyName] = new Function("return this." + propertyName + ";");
+ prototype['set' + longPropertyName] = new Function("newValue", "return new one.color." + colorSpaceName + "(" + propertyNames.map(function (otherPropertyName, i) {
+ return propertyName === otherPropertyName ? "newValue" : "this." + otherPropertyName;
+ }).join(", ") + ");");
+ prototype['adjust' + longPropertyName] = new Function("delta", "return new one.color." + colorSpaceName + "(" + propertyNames.map(function (otherPropertyName, i) {
+ return "this." + otherPropertyName + (propertyName === otherPropertyName ? "+delta" : "");
+ }).join(", ") + ");");
+ });
+
+ function installForeignMethods(targetColorSpaceName, sourceColorSpaceName) {
+ var obj = {};
+ obj['to' + sourceColorSpaceName] = new Function("return this.toRGB().to" + sourceColorSpaceName + "();"); // Fallback
+ one.color[sourceColorSpaceName].propertyNames.forEach(function (property, i) {
+ var longPropertyName = one.color[sourceColorSpaceName].longPropertyNames[i];
+ obj['get' + longPropertyName] = new Function("return this.to" + sourceColorSpaceName + "().get" + longPropertyName + "();");
+ obj['set' + longPropertyName] = new Function("newValue", "return this.to" + sourceColorSpaceName + "().set" + longPropertyName + "(newValue);");
+ obj['adjust' + longPropertyName] = new Function("delta", "return this.to" + sourceColorSpaceName + "().adjust" + longPropertyName + "(delta);");
+ });
+ for (var prop in obj) {
+ if (obj.hasOwnProperty(prop) && one.color[targetColorSpaceName].prototype[prop] === undefined) {
+ one.color[targetColorSpaceName].prototype[prop] = obj[prop];
+ }
+ }
+ }
+
+ one.color.installedColorSpaces.forEach(function (otherColorSpaceName) {
+ installForeignMethods(colorSpaceName, otherColorSpaceName);
+ installForeignMethods(otherColorSpaceName, colorSpaceName);
+ });
+
+ one.color.installedColorSpaces.push(colorSpaceName);
+};
@@ -0,0 +1,60 @@
+/*jslint bitwise:false*/
+/*global one*/
+one.include('js:one/color.js');
+one.include('js:one/color/RGB.js');
+
+/**
+ * Parse a hex string. Please use {@link one.color#parse} instead.
+ * @param strHex The hex string, e.g. <tt>"#abc"</tt>,
+ * <tt>"123abc"<tt>....
+ * @return {one.color.RGB} Color object representing the parsed
+ * color, or false if the string couldn't be parsed.
+ * @private
+ */
+one.color.fromHex = function (strHex) {
+ if (strHex.length < 6) {
+ // Allow CSS shorthand
+ strHex = strHex.replace(/^#?([0-9a-f])([0-9a-f])([0-9a-f])$/i, '$1$1$2$2$3$3');
+ }
+ // Split strHex into red, green, and blue components
+ var hexMatch = strHex.match(/^#?([0-9a-f][0-9a-f])([0-9a-f][0-9a-f])([0-9a-f][0-9a-f])$/i);
+ if (hexMatch) {
+ return new one.color.RGB(
+ parseInt(hexMatch[1], 16) / 255,
+ parseInt(hexMatch[2], 16) / 255,
+ parseInt(hexMatch[3], 16) / 255
+ );
+ } else {
+ return false;
+ }
+};
+
+/**
+ * Parse a hex string, 24-bit integer or object representing a color.
+ * If a one.color.(RGB|HSL|HSV|CMYK) object is provided, it will be returned
+ * as-is, so in library code you can use {@link one.color.parse} to be flexible
+ * about how colors are provided to you:
+ * <pre><code>
+function foo (color) {
+color = color.parse(color);
+// Now we are sure that color is a one.color.(RGB|CMYK|HSL|HSV) object, even if it was provided as a hex string.
+}
+ * </code></pre>
+ * @param {String|Object} obj A hex string, integer value, or
+ * object to parse.
+ * @return {one.color.RGB|one.color.HSL|one.color.HSV|one.color.CMYK} Color object representing the
+ * parsed color, or false if the input couldn't be parsed.
+ */
+one.color.parse = function (obj) {
+ if (obj.charCodeAt) {
+ return one.color.fromHex(obj);
+ } else if (typeof obj === 'object' && obj.isColor) {
+ return obj;
+ } else if (Object.prototype.toString.apply(obj) === '[object Array]') {
+ return new one.color[obj[0]](obj.slice(1, obj.length));
+ } else if (!isNaN(obj)) {
+ // Strange integer representation sometimes returned by document.queryCommandValue in some browser...
+ return new one.color.RGB((obj & 0xFF) / 255, ((obj & 0xFF00) >> 8) / 255, ((obj & 0xFF0000) >> 16) / 255);
+ }
+ return false;
+};
@@ -0,0 +1,17 @@
+/*global one*/
+one.include('js:one.js');
+
+/**
+ * @namespace one.color
+ * <p>You can include <tt>one/color-registerValueType.js</tt> to be
+ * able to use the 'color' type directly in your Ext.data.Record
+ * definitions:</p>
+ * <code><pre>
+one.include('jslib:one/color-registerValueType.js');
+var MyModelObject = Ext.data.Record.create([
+ {name: 'property_name', type: 'color'}
+]);
+ * </pre></code>
+ * </p>
+ */
+one.color = one.color || {};
Oops, something went wrong.

0 comments on commit a37d557

Please sign in to comment.