UNPKG

@poupe/material-color-utilities

Version:

Algorithms and utilities that power the Material Design 3 (M3) color system, including choosing theme colors from images and creating tones of colors; all in a new color space.

77 lines 2.58 kB
/** * @license * Copyright 2021 Google LLC * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ import * as colorUtils from './color_utils.js'; /** * Utility methods for hexadecimal representations of colors. */ /** * @param argb ARGB representation of a color. * @return Hex string representing color, ex. #ff0000 for red. */ export function hexFromArgb(argb) { const r = colorUtils.redFromArgb(argb); const g = colorUtils.greenFromArgb(argb); const b = colorUtils.blueFromArgb(argb); const outParts = [r.toString(16), g.toString(16), b.toString(16)]; // Pad single-digit output values for (const [i, part] of outParts.entries()) { if (part.length === 1) { outParts[i] = '0' + part; } } return '#' + outParts.join(''); } /** * @param hex String representing color as hex code. Accepts strings with or * without leading #, and string representing the color using 3, 6, or 8 * hex characters. * @return ARGB representation of color. */ export function argbFromHex(hex) { hex = hex.replace('#', ''); const isThree = hex.length === 3; const isSix = hex.length === 6; const isEight = hex.length === 8; if (!isThree && !isSix && !isEight) { throw new Error('unexpected hex ' + hex); } let r = 0; let g = 0; let b = 0; if (isThree) { r = parseIntHex(hex.slice(0, 1).repeat(2)); g = parseIntHex(hex.slice(1, 2).repeat(2)); b = parseIntHex(hex.slice(2, 3).repeat(2)); } else if (isSix) { r = parseIntHex(hex.slice(0, 2)); g = parseIntHex(hex.slice(2, 4)); b = parseIntHex(hex.slice(4, 6)); } else if (isEight) { r = parseIntHex(hex.slice(2, 4)); g = parseIntHex(hex.slice(4, 6)); b = parseIntHex(hex.slice(6, 8)); } return (((255 << 24) | ((r & 0x0ff) << 16) | ((g & 0x0ff) << 8) | (b & 0x0ff)) >>> 0); } function parseIntHex(value) { // tslint:disable-next-line:ban return parseInt(value, 16); } //# sourceMappingURL=string_utils.js.map