Skip to content

Commit

Permalink
feat(values): add fromValue decorator
Browse files Browse the repository at this point in the history
Fixes #23
  • Loading branch information
davidbonnet committed Jan 8, 2019
1 parent 8c9bee8 commit d9b37d7
Show file tree
Hide file tree
Showing 2 changed files with 38 additions and 0 deletions.
8 changes: 8 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -89,6 +89,14 @@ Injects prop `cycle(payload)` that cycles the `value` prop through the values of
Sets the `editing` prop and enables its toggling through the `onToggleEditing()` prop.

### `fromValue(path)`

> ⬆️ `{ name, onChange? }`
> ⬇️ `{ onChange(value) }`
Adapts `onChange` for components that call it by providing the `value` as a first argument. If the `path` is not `nil`, extracts the value from `get(value, path)`.

## Tools

### `logProps(propNames, title?)`
Expand Down
30 changes: 30 additions & 0 deletions src/values.js
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@ import {
withPropsOnChange,
withProps,
} from 'recompose'
import { memoize, get } from 'lodash'

import {
hasProp,
Expand Down Expand Up @@ -141,3 +142,32 @@ export const toggledEditing = branch(
})),
),
)

function onChangeFromPath(path) {
switch (path) {
case undefined:
case null:
return ({ onChange, name }) => value => onChange(value, name)
default:
return ({ onChange, name }) => value => onChange(get(value, path), name)
}
}

export const fromValue = memoize(path => {
/*
Adapts `onChange` for components that call it by providing the `value` as a first argument. If the `path` is not `nil`, extracts the value from `get(value, path)`.
Example:
function Trigger({ onChange }) {
return <button onClick={() => onChange(true)}>Enable</button>
}
// `AdaptedTrigger` calls `onChange` with `onChange(true, name)`
const AdaptedTrigger = fromValue(Trigger)
*/
return branch(
hasProp('onChange'),
withHandlers({ onChange: onChangeFromPath(path) }),
)
})

1 comment on commit d9b37d7

@gtnx
Copy link

@gtnx gtnx commented on d9b37d7 Jan 8, 2019

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Please sign in to comment.