1// Copyright 2013 The Chromium Authors. All rights reserved. 2// Use of this source code is governed by a BSD-style license that can be 3// found in the LICENSE file. 4 5 6/** 7 * @fileoverview Helpers for validating parameters to chrome-search:// iframes. 8 */ 9 10 11/** 12 * Converts an RGB color number to a hex color string if valid. 13 * @param {number} color A 6-digit hex RGB color code as a number. 14 * @return {?string} A CSS representation of the color or null if invalid. 15 */ 16function convertToHexColor(color) { 17 // Color must be a number, finite, with no fractional part, in the correct 18 // range for an RGB hex color. 19 if (isFinite(color) && Math.floor(color) == color && 20 color >= 0 && color <= 0xffffff) { 21 var hexColor = color.toString(16); 22 // Pads with initial zeros and # (e.g. for 'ff' yields '#0000ff'). 23 return '#000000'.substr(0, 7 - hexColor.length) + hexColor; 24 } 25 return null; 26} 27 28 29/** 30 * Validates a RGBA color component. It must be a number between 0 and 255. 31 * @param {number} component An RGBA component. 32 * @return {boolean} True if the component is valid. 33 */ 34function isValidRBGAComponent(component) { 35 return isFinite(component) && component >= 0 && component <= 255; 36} 37 38 39/** 40 * Converts an Array of color components into RGBA format "rgba(R,G,B,A)". 41 * @param {Array.<number>} rgbaColor Array of rgba color components. 42 * @return {?string} CSS color in RGBA format or null if invalid. 43 */ 44function convertArrayToRGBAColor(rgbaColor) { 45 // Array must contain 4 valid components. 46 if (rgbaColor instanceof Array && rgbaColor.length === 4 && 47 isValidRBGAComponent(rgbaColor[0]) && 48 isValidRBGAComponent(rgbaColor[1]) && 49 isValidRBGAComponent(rgbaColor[2]) && 50 isValidRBGAComponent(rgbaColor[3])) { 51 return 'rgba(' + 52 rgbaColor[0] + ',' + 53 rgbaColor[1] + ',' + 54 rgbaColor[2] + ',' + 55 rgbaColor[3] / 255 + ')'; 56 } 57 return null; 58} 59