Update color parsing and formatting (#5442)

* Replace `culori` with simple color parser

* Use space-separated color syntax

* Update default color values to use space-separated syntax

* Update separator regex

* Fix tests

* add tests for the new `color` util

Also slightly modified the `color` util itself to take `transparent`
into account and also format every value as a string for consistency.

Co-authored-by: Robin Malfait <malfait.robin@gmail.com>
This commit is contained in:
Brad Cornes 2021-09-09 15:15:53 +01:00 • committed by GitHub
parent 12fa78b9ca
commit 4919cbfbb8
No known key found for this signature in database
GPG key ID: 4AEE18F83AFDEB23
25 changed files with 409 additions and 302 deletions

View file

@ -1302,7 +1302,7 @@ export let backgroundImage = createUtilityPlugin(
)
export let gradientColorStops = (() => {
function transparentTo(value) {
return withAlphaValue(value, 0, 'rgba(255, 255, 255, 0)')
return withAlphaValue(value, 0, 'rgb(255 255 255 / 0)')
}
return function ({ matchUtilities, theme }) {
@ -1738,7 +1738,7 @@ export let ringWidth = ({ matchUtilities, addBase, addUtilities, theme }) => {
let ringColorDefault = withAlphaValue(
theme('ringColor.DEFAULT'),
ringOpacityDefault,
`rgba(147, 197, 253, ${ringOpacityDefault})`
`rgb(147 197 253 / ${ringOpacityDefault})`
)
addBase({

56
src/util/color.js Normal file
View file

@ -0,0 +1,56 @@
import namedColors from 'color-name'
let HEX = /^#([a-f\d]{2})([a-f\d]{2})([a-f\d]{2})([a-f\d]{2})?$/i
let SHORT_HEX = /^#([a-f\d])([a-f\d])([a-f\d])([a-f\d])?$/i
let VALUE = `(?:\\d+|\\d*\\.\\d+)%?`
let SEP = `(?:\\s*,\\s*|\\s+)`
let ALPHA_SEP = `\\s*[,/]\\s*`
let RGB_HSL = new RegExp(
`^(rgb|hsl)a?\\(\\s*(${VALUE})${SEP}(${VALUE})${SEP}(${VALUE})(?:${ALPHA_SEP}(${VALUE}))?\\s*\\)$`
)
export function parseColor(value) {
if (typeof value !== 'string') {
return null
}
value = value.trim()
if (value === 'transparent') {
return { mode: 'rgb', color: ['0', '0', '0'], alpha: '0' }
}
if (value in namedColors) {
return { mode: 'rgb', color: namedColors[value].map((v) => v.toString()) }
}
let hex = value
.replace(SHORT_HEX, (_, r, g, b, a) => ['#', r, r, g, g, b, b, a ? a + a : ''].join(''))
.match(HEX)
if (hex !== null) {
return {
mode: 'rgb',
color: [parseInt(hex[1], 16), parseInt(hex[2], 16), parseInt(hex[3], 16)].map((v) =>
v.toString()
),
alpha: hex[4] ? (parseInt(hex[4], 16) / 255).toString() : undefined,
}
}
let match = value.match(RGB_HSL)
if (match !== null) {
return {
mode: match[1],
color: [match[2], match[3], match[4]].map((v) => v.toString()),
alpha: match[5]?.toString?.(),
}
}
return null
}
export function formatColor({ mode, color, alpha }) {
let hasAlpha = alpha !== undefined
return `${mode}(${color.join(' ')}${hasAlpha ? ` / ${alpha}` : ''})`
}

View file

@ -1,9 +1,9 @@
import selectorParser from 'postcss-selector-parser'
import postcss from 'postcss'
import * as culori from 'culori'
import escapeCommas from './escapeCommas'
import { withAlphaValue } from './withAlphaVariable'
import isKeyframeRule from './isKeyframeRule'
import { parseColor } from './color'
export function applyPseudoToMarker(selector, marker, state, join) {
let states = [state]
@ -221,10 +221,6 @@ function splitAlpha(modifier) {
return [modifier.slice(0, slashIdx), modifier.slice(slashIdx + 1)]
}
function isColor(value) {
return culori.parse(value) !== undefined
}
export function asColor(modifier, lookup = {}, tailwindConfig = {}) {
if (lookup[modifier] !== undefined) {
return lookup[modifier]
@ -245,7 +241,7 @@ export function asColor(modifier, lookup = {}, tailwindConfig = {}) {
}
return asValue(modifier, lookup, {
validate: isColor,
validate: (value) => parseColor(value) !== null,
})
}

View file

@ -1,41 +1,17 @@
import * as culori from 'culori'
function isValidColor(color) {
return culori.parse(color) !== undefined
}
import { parseColor, formatColor } from './color'
export function withAlphaValue(color, alphaValue, defaultValue) {
if (typeof color === 'function') {
return color({ opacityValue: alphaValue })
}
if (isValidColor(color)) {
// Parse color
const parsed = culori.parse(color)
let parsed = parseColor(color)
// Apply alpha value
parsed.alpha = alphaValue
// Format string
let value
if (parsed.mode === 'hsl') {
value = culori.formatHsl(parsed)
} else {
value = culori.formatRgb(parsed)
}
// Correctly apply CSS variable alpha value
if (typeof alphaValue === 'string' && alphaValue.startsWith('var(') && value.endsWith('NaN)')) {
value = value.replace('NaN)', `${alphaValue})`)
}
// Color could not be formatted correctly
if (!value.includes('NaN')) {
return value
}
if (parsed === null) {
return defaultValue
}
return defaultValue
return formatColor({ ...parsed, alpha: alphaValue })
}
export default function withAlphaVariable({ color, property, variable }) {
@ -46,29 +22,23 @@ export default function withAlphaVariable({ color, property, variable }) {
}
}
if (isValidColor(color)) {
const parsed = culori.parse(color)
if ('alpha' in parsed) {
// Has an alpha value, return color as-is
return {
[property]: color,
}
}
const formatFn = parsed.mode === 'hsl' ? 'formatHsl' : 'formatRgb'
const value = culori[formatFn]({
...parsed,
alpha: NaN, // intentionally set to `NaN` for replacing
}).replace('NaN)', `var(${variable}))`)
const parsed = parseColor(color)
if (parsed === null) {
return {
[variable]: '1',
[property]: value,
[property]: color,
}
}
if (parsed.alpha !== undefined) {
// Has an alpha value, return color as-is
return {
[property]: color,
}
}
return {
[property]: color,
[variable]: '1',
[property]: formatColor({ ...parsed, alpha: `var(${variable})` }),
}
}