Press n or j to go to the next uncovered block, b, p or k for the previous block.
| 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 | 2x 22518x 2x 8850x 8848x 8848x 2x 2412x 2412x 2412x 2412x 2x 2413x 2x 2x 2411x 3x 2411x 2409x 2x 2x 3x 8841x 2401x | import Color from 'colorjs.io';
import { MODE_EXTENSION_KEY } from '../../utils/constants.js';
/**
* Check if a value is an OKLCH color object
*
* @param {any} value
* @returns boolean
*/
const isOklchValue = (value) => {
return typeof value === 'object' && value?.colorSpace === 'oklch';
};
/**
* CSS filter to detect tokens with OKLCH values
*
* @param {Object} token
* @returns boolean
*/
export const oklchFilter = (token) => {
const hasOklchValue = isOklchValue(token.$value);
const hasOklchDarkValue = isOklchValue(token.$extensions?.[MODE_EXTENSION_KEY]?.dark?.$value);
return hasOklchValue || hasOklchDarkValue;
};
/**
* Convert OKLCH to hex using colorjs.io
*
* @param {Object} oklchValue - The OKLCH object { colorSpace: "oklch", components: [L, C, H] }
* @returns {string} The hex color value
*/
const convertOklchToHex = (oklchValue) => {
try {
const [L, C, H] = oklchValue.components;
const color = new Color('oklch', [L, C, H]);
// Convert to hex and ensure it's in gamut
return color.to('srgb').toString({ format: 'hex' });
} catch (error) {
console.warn(`Failed to convert OKLCH to hex:`, error, oklchValue);
return oklchValue;
}
};
/**
* CSS Transformer that converts OKLCH values to hex
*
* @param {Object} token
* @returns {string} The hex color value
*/
export const oklchToHexTransformer = (token) => {
if (!token) {
console.warn('Invalid token passed to oklchToHexTransformer:', token);
return '';
}
// Convert dark mode extension value if it's OKLCH
if (isOklchValue(token.$extensions?.[MODE_EXTENSION_KEY]?.dark?.$value)) {
token.$extensions[MODE_EXTENSION_KEY].dark.$value = convertOklchToHex(
token.$extensions[MODE_EXTENSION_KEY].dark.$value,
);
}
// Convert $value if it's OKLCH
if (isOklchValue(token.$value)) {
return convertOklchToHex(token.$value);
}
// Return existing $value if it's not OKLCH (but dark value was converted)
return token.$value;
};
/**
* Style Dictionary registration for the OKLCH to hex transform
* @param {StyleDictionary} StyleDictionary
*/
export const oklchToHex = (StyleDictionary) => {
StyleDictionary.registerTransform({
name: 'value/oklch-to-hex',
type: 'value',
transitive: true,
filter: (token) => oklchFilter(token),
transform: (token) => oklchToHexTransformer(token),
});
};
|