Created
November 24, 2022 06:40
-
-
Save ultrox/14cb91841f2558b770a476b44307eed6 to your computer and use it in GitHub Desktop.
recompose-light.js
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import { createFactory, Component } from 'react' | |
export const withContext = (childContextTypes, getChildContext) => BaseComponent => { | |
const factory = createFactory(BaseComponent) | |
class WithContext extends Component { | |
getChildContext = () => getChildContext(this.props) | |
render() { | |
return factory(this.props) | |
} | |
} | |
WithContext.childContextTypes = childContextTypes | |
if (devOrTestEnv()) { | |
return setDisplayName(wrapDisplayName(BaseComponent, 'withContext'))( | |
WithContext | |
) | |
} | |
return WithContext | |
} | |
export function withProps(input) { | |
const hoc = mapProps(props => ({ | |
...props, | |
...(typeof input === 'function' ? input(props) : input), | |
})) | |
if (devOrTestEnv()) { | |
return BaseComponent => | |
setDisplayName(wrapDisplayName(BaseComponent, 'withProps'))( | |
hoc(BaseComponent) | |
) | |
} | |
return hoc | |
} | |
export const defaultProps = props => BaseComponent => { | |
const factory = createFactory(BaseComponent) | |
const DefaultProps = ownerProps => factory(ownerProps) | |
DefaultProps.defaultProps = props | |
if (devOrTestEnv()) { | |
return setDisplayName(wrapDisplayName(BaseComponent, 'defaultProps'))( | |
DefaultProps | |
) | |
} | |
return DefaultProps | |
} | |
// Helpers | |
const mapProps = propsMapper => BaseComponent => { | |
const factory = createFactory(BaseComponent) | |
const MapProps = props => factory(propsMapper(props)) | |
if (devOrTestEnv()) { | |
return setDisplayName(wrapDisplayName(BaseComponent, 'mapProps'))(MapProps) | |
} | |
return MapProps | |
} | |
function setDisplayName(displayName) { | |
const setStatic = (key, value) => BaseComponent => { | |
/* eslint-disable no-param-reassign */ | |
BaseComponent[key] = value | |
/* eslint-enable no-param-reassign */ | |
return BaseComponent | |
} | |
return setStatic('displayName', displayName) | |
} | |
const getDisplayName = Component => { | |
if (typeof Component === 'string') { | |
return Component; | |
} | |
if (!Component) { | |
return undefined; | |
} | |
return Component.displayName || Component.name || 'Component'; | |
} | |
function wrapDisplayName(BaseComponent, hocName){ | |
return `${hocName}(${getDisplayName(BaseComponent)})`; | |
} | |
function devOrTestEnv() { | |
return process.env.NODE_ENV !== 'production' | |
} | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment