-
Notifications
You must be signed in to change notification settings - Fork 3
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
ignore-colors-that-contain-custom-properties
Converter should not try to convert colors with custom properties as it converts custom properties.
- Loading branch information
Showing
2 changed files
with
61 additions
and
32 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -1,17 +1,48 @@ | ||
const Color = require("colorjs.io").default; | ||
const colorsRegex = new RegExp(/(^#[0-9a-f]{3,8}$|(hsla?|rgba?)\([^)]+\))/gi); | ||
const pc = require("picocolors"); | ||
|
||
module.exports = () => ({ | ||
postcssPlugin: "postcss-convert-to-oklch", | ||
Declaration(decl) { | ||
const colors = decl.value.match(colorsRegex); | ||
if (colors) { | ||
for (const color of colors) { | ||
const oklch = new Color(color).to("oklch").toString(); | ||
decl.value = decl.value.replace(color, oklch); | ||
} | ||
} | ||
}, | ||
postcssPlugin: "postcss-convert-to-oklch", | ||
Declaration(decl) { | ||
const originalColors = decl.value.match(colorsRegex); | ||
if (!originalColors) return; | ||
|
||
const colorsToConvert = originalColors.filter( | ||
(originalColor) => !originalColor.includes("var(--"), | ||
); | ||
|
||
const convertedAndOriginalColors = colorsToConvert.map( | ||
(originalColor) => { | ||
try { | ||
const converted = getConvertedColor(originalColor); | ||
return { converted, original: originalColor }; | ||
} catch (e) { | ||
console.error( | ||
pc.bgRed( | ||
`Error during color ${originalColor} conversion: ${e}. It will not be converted.`, | ||
), | ||
); | ||
} | ||
}, | ||
); | ||
|
||
convertedAndOriginalColors.forEach(({ converted, original }) => { | ||
try { | ||
decl.value = decl.value.replace(original, converted); | ||
} catch (e) { | ||
console.error( | ||
pc.bgRed( | ||
`Error during replacing ${original} with ${converted}: ${e}`, | ||
), | ||
); | ||
} | ||
}); | ||
}, | ||
}); | ||
|
||
function getConvertedColor(color) { | ||
return new Color(color).to("oklch").toString(); | ||
} | ||
|
||
module.exports.postcss = true; |