|
| 1 | +import React from 'react'; |
| 2 | + |
| 3 | +const defaultMount = (nameFn) => (props) => `${nameFn(props)} mounts`; |
| 4 | +const defaultUnmount = (nameFn) => (props) => `${nameFn(props)} unmounts`; |
| 5 | +const defaultUpdate = (nameFn) => (props, nextProps) => { |
| 6 | + const changed = Object.keys(nextProps).filter((key) => props[key] !== nextProps[key]).join(', '); |
| 7 | + return `${nameFn(nextProps)} updates ${changed}`; |
| 8 | +}; |
| 9 | +const logIfExists = (string) => { |
| 10 | + if (string) { |
| 11 | + console.log(string); |
| 12 | + } |
| 13 | +}; |
| 14 | + |
| 15 | +/** |
| 16 | + * [HoC] Debug component. Logs debug information about component lifecycle: componentDidMount, componentWillUnmount, componentWillUpdate. |
| 17 | + * |
| 18 | + * @param {?object} $0 Configuration (optional) |
| 19 | + * @param {?string|function} $0.name Name of the component. May be a string or function from props. If undefined, displayName is used. |
| 20 | + * @param {?function} $0.mount Generates componentDidMount message. Receives props as argument. |
| 21 | + * @param {?function} $0.unmount Generates componentWillUnmount message. Receives props as argument. |
| 22 | + * @param {?function} $0.update Generates componentWillUpdate message. Receives props and nextProps as arguments. |
| 23 | + * @return {component => component} Configured debug component wrapper. |
| 24 | + */ |
| 25 | +const debug = ({name, mount, unmount, update} = {}) => (Component) => { |
| 26 | + const finalName = name || Component.displayName || Component.name || 'Component'; |
| 27 | + const nameFn = typeof finalName === 'function' ? finalName : () => finalName; |
| 28 | + const onMount = mount || defaultMount(nameFn); |
| 29 | + const onUnmount = unmount || defaultUnmount(nameFn); |
| 30 | + const onUpdate = update || defaultUpdate(nameFn); |
| 31 | + |
| 32 | + return class extends React.Component { |
| 33 | + componentDidMount() { |
| 34 | + logIfExists(onMount(this.props)); |
| 35 | + } |
| 36 | + |
| 37 | + componentWillUpdate(nextProps) { |
| 38 | + logIfExists(onUpdate(this.props, nextProps)); |
| 39 | + } |
| 40 | + |
| 41 | + componentWillUnmount() { |
| 42 | + logIfExists(onUnmount(this.props)); |
| 43 | + } |
| 44 | + |
| 45 | + render() { |
| 46 | + return <Component {...this.props} />; |
| 47 | + } |
| 48 | + }; |
| 49 | +}; |
| 50 | +export default debug; |
0 commit comments