diff --git a/css.js b/css.js index 68d0826..9b8a37a 100644 --- a/css.js +++ b/css.js @@ -13,15 +13,37 @@ var path = require("path") .replace(/: +/g, ":") .replace(/([ :,])0\.([0-9])/g, "$1.$2") , clear = s => s.replace(/("|')((?:\\\1|[^\1])*?)\1|[^"']+/g, clearFn).replace(/url\(("|')([^'"()\s]+)\1\)/g, "url($2)") +, toRgb = { + rgb(r, g, b) { + var f = n => ((n | 0) + 256).toString(16).slice(1) + return f(r) + f(g) + f(b) + }, + hsl(h, s, l) { + l /= 100 + s /= 100 / (l < 0.5 ? l : 1 - l) + function f(n) { + n = (n + h / 30) % 12 + return (0 | 256.5 + (255 * (l - s * (n < 2 || n > 10 ? -1 : n < 4 ? n - 3 : n > 8 ? 9 - n : 1)))).toString(16).slice(1) + } + return f(0) + f(8) + f(4) + } +} +, colorRe = /\b(rgb|hsl)\s*\(\s*(\w+)\s+(\w+)%?\s+(\w+)%?\s*\)/g +, colorFn = (_, name, a, b, c) => "#" + toRgb[name](a, b, c).replace(/(\w)\1(\w)\2(\w)\3/, "$1$2$3") , styleHandler = { get(style, prop) { if (prop === "cssText") { + var min = style.parentRule && style.parentRule.parentStyleSheet.min for (var out = [], i = style.length; i--; ) { - out[i] = style[i] + ":" + (style.__[i] || style[style[i]]) + out[i] = joinProp(style[i], style.__[i] || style[style[i]]) } return out.join(";") } return style[prop] || "" + function joinProp(name, value) { + if (min && min.color) value = value.replace(colorRe, colorFn) + return name + ":" + value + } }, set(style, prop, val) { if (prop === "cssText") { diff --git a/test/css.js b/test/css.js index 46222f4..ab7a228 100644 --- a/test/css.js +++ b/test/css.js @@ -50,6 +50,22 @@ describe("css.js {0}", describe.env === "browser" ? [["mock", exports], ["native assert.end() }) + test("color {i} '{1}'", [ + [ {}, ".a{color:rgb(255 0 153)}.b{color:rgb( 0 1 2 )}", ".a{color:rgb(255 0 153)}\n.b{color:rgb( 0 1 2 )}"], + [ { color: true }, ".a{color:rgb(255 0 153)}.b{color:rgb( 0 1 2 )}", ".a{color:#f09}\n.b{color:#000102}"], + [ { color: true }, ".a{color:hsl(0 0% 0%)}", ".a{color:#000}"], + [ { color: true }, ".a{color:hsl(0 0% 100%)}", ".a{color:#fff}"], + [ { color: true }, ".a{color:hsl(0 100% 100%)}", ".a{color:#fff}"], + [ { color: true }, ".a{color:hsl(30 10% 90%)}", ".a{color:#e8e6e3}"], + [ { color: true }, ".a{color:hsl(60 20% 80%)}", ".a{color:#d6d6c2}"], + [ { color: true }, ".a{color:hsl(90 30% 70%)}", ".a{color:#b3c99c}"], + [ { color: true }, ".a{color:hsl(120 40% 60%)}", ".a{color:#70c270}"], + ], (min, text, expected, assert) => { + const sheet = new CSSStyleSheet({ min }) + sheet.replaceSync(text) + assert.equal(sheet.toString(), expected).end() + }) + test("parse '{0}'", [ [" ", ""], [" html {} body{ } ", ""],