-
Notifications
You must be signed in to change notification settings - Fork 3
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
Merge pull request #10 from evanrs/next
Add cursors, coerce namespace and keys to property paths
- Loading branch information
Showing
3 changed files
with
119 additions
and
31 deletions.
There are no files selected for viewing
This file contains 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
This file contains 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
This file contains 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
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -1,19 +1,51 @@ | ||
import result from 'lodash/result'; | ||
import concat from 'lodash/concat'; | ||
import get from 'lodash/get'; | ||
import merge from 'lodash/merge'; | ||
import set from 'lodash/set'; | ||
import toPath from 'lodash/toPath'; | ||
import clone from 'lodash/clone'; | ||
|
||
|
||
export const BIND = 'BIND_NAMESPACE_NEXT'; | ||
|
||
|
||
export function namespaceReducer (state={}, action={}) { | ||
|
||
if (action.type === BIND) { | ||
let { payload: { namespace, key, value } } = action | ||
|
||
let prev = result(state, namespace, {}); | ||
let touched = result(prev, '@@touched', {}); | ||
let next = { | ||
...prev, [key]: value, ['@@touched']: { ...touched, [key]: true } }; | ||
namespace = toPath(namespace); | ||
key = toPath(key); | ||
|
||
let changedPath = concat(namespace, key); | ||
let touchedPath = concat(namespace, '@@touched', key); | ||
let versionPath = concat(namespace, '@@version'); | ||
|
||
if (value !== get(state, changedPath)) { | ||
let version = get(state, versionPath, 0) + 1; | ||
let fragment = set({}, namespace, get(state, namespace)); | ||
|
||
clonePath(fragment, changedPath); | ||
clonePath(fragment, touchedPath); | ||
|
||
set(fragment, versionPath, version); | ||
set(fragment, changedPath, value); | ||
set(fragment, touchedPath, true); | ||
|
||
state = { ...state, [namespace]: next }; | ||
state = merge(clone(state), fragment) | ||
} | ||
} | ||
|
||
|
||
return state; | ||
} | ||
|
||
|
||
function clonePath (target, path) { | ||
path.forEach((key, idx, col) => { | ||
key = col.slice(0, idx); | ||
set(target, key, clone(get(target, key))) | ||
}) | ||
|
||
return target; | ||
} |