Skip to content

Commit

Permalink
feat: implement basic ref() interface
Browse files Browse the repository at this point in the history
  • Loading branch information
streamich committed Mar 27, 2018
1 parent d8b6a1e commit 46de4fd
Show file tree
Hide file tree
Showing 2 changed files with 57 additions and 3 deletions.
27 changes: 26 additions & 1 deletion .storybook/ref.stories.js
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
import {createElement as h} from 'react';
import {createElement as h, Component} from 'react';
import {storiesOf} from '@storybook/react';
const {action} = require('@storybook/addon-actions');
const {linkTo} = require('@storybook/addon-links');
Expand All @@ -11,7 +11,32 @@ addonRef(nano);

const css = nano.createRef();

class RefExample extends Component {
constructor(props) {
super(props);
this.state = {
color: 'red',
};
}

render () {
var data = nano.ref({'&': {color: this.state.color}, '&:hover': {color: 'blue'}});

return h('div', {},
h('div', data, 'Hello world'),

h('br'),

h('button', {onClick: () => this.setState({color: 'red'})}, 'red'),
h('button', {onClick: () => this.setState({color: 'blue'})}, 'blue'),
);
}
}

storiesOf('Addons/ref', module)
.add('Default', () =>
h('div', css({'&': {color: 'red'}, '&:hover': {color: 'blue'}}), 'Hello world')
)
.add('ref()', () =>
h(RefExample)
)
33 changes: 31 additions & 2 deletions addon/ref.js
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,9 @@

var addonPipe = require('./pipe').addon;

// eslint-disable-next-line no-undef
var sNano = typeof Symbol === 'object' ? Symbol('nano-css') : '@@nano-css';

exports.addon = function (renderer) {
if (!renderer.pipe) {
addonPipe(renderer);
Expand All @@ -14,15 +17,13 @@ exports.addon = function (renderer) {
renderer.createRef = function () {
var pipe = renderer.pipe();
var el = null;

var ref = function (element) {
if (el) el = element;
else {
el = null;
pipe.remove();
}
};

var obj = {ref: ref};

obj[pipe.attr] = '';
Expand All @@ -32,4 +33,32 @@ exports.addon = function (renderer) {
return obj;
};
};

renderer.ref = function (css, originalRef) {
if (process.env.NODE_ENV !== 'production') {
if (originalRef && typeof originalRef !== 'function') {
console.error(
'nano-css "ref" function expects argument to be a ref function, "' + (typeof originalRef) + '" provided.'
);
}
}

var obj = {
ref: function (el) {
if (originalRef) originalRef(el);
if (!el) return;

var pipe = el[sNano];

if (!pipe) {
el[sNano] = pipe = renderer.pipe();
el.setAttribute(pipe.attr, '');
}

pipe.css(css);
}
};

return obj;
};
};

0 comments on commit 46de4fd

Please sign in to comment.