Skip to content
Browse files

set the color as background on color hint

  • Loading branch information...
1 parent 1796dee commit dacdf095abef41acdf990616d24b4cceede2a501 @marianoguerra committed Aug 28, 2012
Showing with 90 additions and 1 deletion.
  1. +15 −0 js/demos.js
  2. +75 −1 src/addons/color/color.js
View
15 js/demos.js
@@ -174,6 +174,21 @@
}
],
[
+ "color hint with default (addon)",
+ "",
+ {
+ "order": ["color"],
+ "properties": {
+ "color": {
+ "type": "string",
+ "title": "Color",
+ "je:hint": "color",
+ "default": "cc0000"
+ }
+ }
+ }
+ ],
+ [
"date hint (addon)",
"",
{
View
76 src/addons/color/color.js
@@ -22,13 +22,87 @@
formatHints.string = formatHints.string || {};
+ function normalizeRGB(c) {
+ var
+ red, green, blue,
+ rnum, gnum, bnum;
+
+ // remove the # if it's there
+ c = (c.charAt(0) === "#") ? c.slice(1) : c;
+
+ if (c.length === 3) {
+ c = c[0] + c[0] + c[1] + c[1] + c[2] + c[2];
+ } else if (c.length !== 6) {
+ return {
+ str: c,
+ hex: {},
+ num: {},
+ ok: false
+ };
+ }
+
+ red = c[0] + c[1];
+ green = c[2] + c[3];
+ blue = c[4] + c[5];
+
+ rnum = parseInt(red, 16);
+ gnum = parseInt(green, 16);
+ bnum = parseInt(blue, 16);
+
+ return {
+ str: c,
+ hex: {
+ red: red,
+ green: green,
+ blue: blue
+ },
+ num: {
+ red: rnum,
+ green: gnum,
+ blue: bnum
+ },
+ // check if some of the numbers is NaN
+ ok: rnum === rnum && gnum === gnum && bnum === bnum
+ };
+ }
+
+ function contrastTextColor(red, green, blue) {
+ var brightness;
+
+ brightness = (red * 299) + (green * 587) + (blue * 114);
+ brightness = brightness / 255000;
+
+ // values range from 0 to 1
+ // anything greater than 0.5 should be bright enough for dark text
+ if (brightness >= 0.5) {
+ return "#333";
+ } else {
+ return "#f5f5f5";
+ }
+ }
+
formatHints.string.color = function (name, type, id, opts, required, priv, util) {
util.events.rendered.handleOnce(function () {
+ var content, color, contrastColor, input = $("#" + id);
- $("#" + id).click(function (event) {
+ input.click(function (event) {
mColorPicker.size = 3;
mColorPicker(event);
});
+
+ content = $.trim(input.val());
+ if (content !== "") {
+ color = normalizeRGB(content);
+
+ if (color.ok) {
+ contrastColor = contrastTextColor(color.num.red,
+ color.num.green,
+ color.num.blue);
+
+ input.css({"background-color": "#" + color.str, "color": contrastColor});
+ }
+ }
+
});
return JsonEdit.defaults.formatters.default_(name, type, id, opts, required, util);

0 comments on commit dacdf09

Please sign in to comment.
Something went wrong with that request. Please try again.