Skip to content

Instantly share code, notes, and snippets.

@tkh44
Last active March 13, 2017 17:16
Show Gist options
  • Select an option

  • Save tkh44/b0a779d1818ec58ea6daaddf2a0a787d to your computer and use it in GitHub Desktop.

Select an option

Save tkh44/b0a779d1818ec58ea6daaddf2a0a787d to your computer and use it in GitHub Desktop.
// eslint-disable-next-line no-unused-vars
import React from 'react'
import { render } from 'react-dom'
import crate from '../../src'
const pp = obj => JSON.stringify(obj, null, 2)
function Stateless (props) {
return (
<pre style={props.style} className={props.className}>
<details open>
<summary>Stateless Component Props</summary>
{pp(props)}
</details>
{props.children}
</pre>
)
}
const buttonCrate = crate().style({
height: '1.6em',
width: '100%',
background: 'none',
color: 'white',
fontSize: '1em',
outline: 'none'
})
const BlueButton = buttonCrate.style({ background: 'blue' }).compile('button')
const App = crate()
.prop('foo', 'bar')
.className(props => ['set-classname', ...props.colors])
.style({ border: '2px solid blue', padding: 8 })
.inspect()
.compile(Stateless)
render(
<App
name={'Kye'}
location={'Boulder'}
twitter={'tkh44'}
github={'tkh44'}
colors={['red', 'green', 'blue', 'brown', 'black', 'purple', 'yellow', 'pink']}
>
<h1>App</h1>
<BlueButton>I'm blue</BlueButton>
</App>,
document.querySelector('#demo')
import { Component as ReactComponent, Children, createElement as h } from 'react'
import classnames from 'classnames'
const isFn = test => typeof test === 'function'
const id = Component => Component
class Crate {
constructor (hoc = id) {
this.hoc = hoc
return this
}
map (fn) {
return new Crate(fn(this.hoc))
}
fold (fn) {
return fn(this.hoc)
}
compile (Component) {
return this.fold(hoc => hoc(Component))
}
// Set prop by key
prop (key, value) {
return this.map(hoc => Wrapped => hoc(props => {
const nextProps = { ...props, [key]: isFn(value) ? value(props) : value }
return h(Wrapped, nextProps)
}))
}
// Set className prop
// accepts anything that `classnames`
// https://www.npmjs.com/package/classnames
className (value) {
return this.prop('className', props => {
return classnames(props.className, isFn(value) ? value(props) : value)
})
}
// Set style
style (s) {
return this.prop('style', props => ({
...props.style,
...(isFn(s) ? s(props) : s)
}))
}
// Inspect your props at a certain point
inspect () {
return this.map(hoc => Wrapped => hoc(props => {
console.log('=== inspect ===')
console.log('props', props)
console.log('this.hoc', this.hoc)
console.log('===============')
return h(Wrapped, props)
}))
}
}
export default function crate (...args) {
return new Crate(...args)
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment