Skip to content

Commit

Permalink
feat: add virtual CSS addon
Browse files Browse the repository at this point in the history
  • Loading branch information
streamich committed Mar 21, 2018
1 parent 0db425f commit 3220b02
Show file tree
Hide file tree
Showing 2 changed files with 56 additions and 4 deletions.
51 changes: 51 additions & 0 deletions addon/virtual-hydrate.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,51 @@
'use strict';

exports.addon = function (renderer) {
if (process.env.NODE_ENV !== 'production') {
require('./__dev__/warnOnMissingDependencies')('styled', renderer, ['putRaw']);
}

if (process.env.NODE_ENV !== 'production') {
// Check we have a style sheet to hydrate.
if (!renderer.sh) {
console.warn(
'"virtual-hydrate" addon expected a style sheet in "sh" property, ' +
'but could not find one. Will not re-hydrate.'
);
}

if ((typeof renderer.atomic !== 'function') || (typeof renderer.virtual !== 'function') || (typeof renderer.memo !== 'object')) {
console.error(
'"virtual-hydrate" requires "virtual" addon bot be installed, but it was not found.'
);
}
}

if (!renderer.sh) return;

var rules = renderer.sh.sheet.cssRules || renderer.sh.sheet.rules;
var length = rules.length;
var cache = {};

for (var i = 0; i < length; i++) {
var rule = rules[i];

var atrule = '_';
var selector = rule.selectorText;
var prop = rule.style[0];
var value = rule.style[prop];

if (!cache[atrule]) {
cache[atrule] = {};
}

if (!cache[atrule][selector]) {
// TO BO IMPLEMENTED... (maybe)
// The thing is, it is not possible to hydrate arbitrary selectors.
// - .a .b .c:hover { ... }
// - & .b .c:hover { ... }
// - .a & .c:hover { ... }
// - .a .b &:hover { ... }
}
}
};
9 changes: 5 additions & 4 deletions addon/virtual.js
Original file line number Diff line number Diff line change
Expand Up @@ -4,9 +4,9 @@ var createMemoizer = function (pfx) {
var offset = 10;
var msb = 35;
var power = 1;
var cache = {};

var self = {
cache: {},
length: 0,

next: function () {
Expand All @@ -22,7 +22,7 @@ var createMemoizer = function (pfx) {
},

get: function () {
var curr = cache;
var curr = self.cache;
var lastIndex = arguments.length - 1;
var lastStep = arguments[lastIndex];

Expand All @@ -36,7 +36,7 @@ var createMemoizer = function (pfx) {
if (!curr[lastStep]) curr[lastStep] = pfx + self.next().toString(36);

return curr[lastStep];
},
}
};

return self;
Expand All @@ -47,9 +47,10 @@ exports.addon = function (renderer) {
require('./__dev__/warnOnMissingDependencies')('styled', renderer, ['putRaw']);
}

var memo = createMemoizer(renderer.pfx);
renderer.memo = createMemoizer(renderer.pfx);

renderer.atomic = function (selectorTemplate, rawDecl, atrule) {
var memo = renderer.memo;
var memoLength = memo.length;
var className = memo.get(atrule, selectorTemplate, rawDecl);

Expand Down

0 comments on commit 3220b02

Please sign in to comment.