Skip to content

Commit

Permalink
feat: implement jsx()
Browse files Browse the repository at this point in the history
  • Loading branch information
streamich committed Mar 13, 2018
1 parent 3816612 commit 7721f0b
Show file tree
Hide file tree
Showing 2 changed files with 53 additions and 3 deletions.
2 changes: 1 addition & 1 deletion lib/hash.js
Original file line number Diff line number Diff line change
Expand Up @@ -11,5 +11,5 @@ exports.hash = function(styles) {
hash = (hash * 33) ^ str.charCodeAt(--i);
}

return '_' + (hash >>> 0).toString(36);
return '_' + (hash >>> 0);
};
54 changes: 52 additions & 2 deletions lib/index.js
Original file line number Diff line number Diff line change
Expand Up @@ -27,7 +27,7 @@ exports.create = function (h) {
};
}

function put (selector, decls) {
var put = function (selector, decls) {
var selectors = selector.split(',');
var str = '';
var prop, value;
Expand All @@ -48,7 +48,21 @@ exports.create = function (h) {
str = '.' + selector + '{' + str + '}';
putRaw(str);
}
}
};

var cache = {};

var fromCache = function (styles) {
if (!styles) return '';

var key = hash(styles);

if (!cache[key]) {
cache[key] = renderer.rule(styles, key);
}

return cache[key];
};

renderer.rule = function(styles, block) {
if (!block) {
Expand Down Expand Up @@ -90,6 +104,9 @@ exports.create = function (h) {
var className;
var isElement = typeof fn === 'string';

if (!block && !isElement)
block = fn.displayName || fn.name;

var Component = function(props) {
if (!className) {
className = renderer.rule(styles, block);
Expand Down Expand Up @@ -131,5 +148,38 @@ exports.create = function (h) {
return Component;
};

renderer.jsx = function (fn, styles, block) {
var className;
var isElement = typeof fn === 'string';

if (!block && !isElement)
block = fn.displayName || fn.name;

var Component = function (props) {
if (!className) {
className = renderer.rule(styles, block);
}

var copy = props;

if (process.env.NODE_ENV !== 'production') {
copy = Object.assign({}, props);
}

var dynamicClassName = fromCache(props.css);
delete copy.css;

copy.className = (props.className + '') + className + dynamicClassName;

return isElement ? h(fn, copy) : fn(copy);
};

if (block && (process.env.NODE_EVN !== 'production')) {
Component.displayName = 'jsx(' + block + ')';
}

return Component;
};

return renderer;
};

0 comments on commit 7721f0b

Please sign in to comment.