Skip to content

Commit

Permalink
add css scoper
Browse files Browse the repository at this point in the history
  • Loading branch information
kbrsh committed Jul 18, 2018
1 parent d6201ef commit eaeb873
Show file tree
Hide file tree
Showing 2 changed files with 53 additions and 1 deletion.
33 changes: 32 additions & 1 deletion packages/moon-mvl/index.js
Original file line number Diff line number Diff line change
@@ -1,9 +1,40 @@
const fs = require("fs");
const path = require("path");
const Moon = require("moon");
const slash = require("./slash/slash");

const cssRE = /([@#.="':\w\s\-\[\]()]+)(\s*,|(?:{[\s\n]*(?:[\w\n]+:[\w\s\n(),]+;[\s\n]*)*}))/g;

const addClass(element, name) => {
const attributes = element.attributes;
let value = name;
let expression = false;
let dynamic = false;

for (let i = 0; i < attributes.length; i++) {
const attribute = attributes[i];
if (attribute.key === "class") {
if (attribute.expression) {
value = `(${attribute.value}) + " ${name}"`;
expression = attribute.expression;
dynamic = attribute.dynamic;
} else {
value = `${attribute.value} ${name}`;
}

attributes.splice(i, 1);
break;
}
}

attributes.push({
key: "class",
value: value,
expression: expression,
dynamic: dynamic
});
};

module.exports = (file, contents) => {
let js = "import Moon from \"moon\";";
let css;
Expand All @@ -26,7 +57,7 @@ module.exports = (file, contents) => {
const cssPath = path.join(directoryName, fileName + ".css");
if (fs.existsSync(cssPath)) {
const scope = `moon-${name}-${slash(name)}`;
view = Moon.parse(contents);
view = Moon.generate(addClass(Moon.parse(contents), scope), null);
css = fs.readFileSync(css).toString().replace(cssRE, (match, selector, rule) => {
return selector.replace(trailingWhitespaceRE, "") + "." + scope;
});
Expand Down
21 changes: 21 additions & 0 deletions packages/moon-mvl/slash/slash.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,21 @@
/**
* Slash
* Fast, efficient hash
* Copyright 2017-2018 Kabir Shah
* Released under the MIT License
*/

const prime = 0xA017132D;

const slash = (key) => {
let result = 0;

for (let i = 0; i < key.length; i++) {
const current = key.charCodeAt(i);
result = ((result ^ current) * prime) >>> 0;
result = (result >> 8) | (result << 24);
result = result >>> 0;
}

return result.toString(36);
};

0 comments on commit eaeb873

Please sign in to comment.