This repository has been archived by the owner on Feb 23, 2024. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 219
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
Merge branch 'trunk' into 9331-with-gutenberg-trunk-the-images-arent-…
…loaded-on-the-site-editor
- Loading branch information
Showing
4 changed files
with
16,489 additions
and
11,010 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
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -1,33 +1,37 @@ | ||
/** | ||
* External dependencies | ||
* Utility for updating nested state in the path that changed. | ||
*/ | ||
import { klona } from 'klona/json'; | ||
function updateNested< T >( // The state being updated | ||
state: T, | ||
// The path being updated | ||
path: string[], | ||
// The value to update for the path | ||
value: unknown, | ||
// The current index in the path | ||
index = 0 | ||
): T { | ||
const key = path[ index ] as keyof T; | ||
if ( index === path.length - 1 ) { | ||
return { ...state, [ key ]: value }; | ||
} | ||
|
||
const nextState = state[ key ] || {}; | ||
return { | ||
...state, | ||
[ key ]: updateNested( nextState, path, value, index + 1 ), | ||
} as T; | ||
} | ||
|
||
/** | ||
* Utility for updating state and only cloning objects in the path that changed. | ||
*/ | ||
export default function updateState< Type extends Record< string, unknown > >( | ||
export default function updateState< T >( | ||
// The state being updated | ||
state: Type, | ||
state: T, | ||
// The path being updated | ||
path: Array< keyof Type >, | ||
path: string[], | ||
// The value to update for the path | ||
value: unknown | ||
): Type { | ||
const newState = klona( state ) as Type; | ||
|
||
let current: Record< string, unknown > = newState; | ||
for ( let i = 0; i < path.length; i++ ) { | ||
const key = path[ i ] as string; | ||
|
||
if ( i === path.length - 1 ) { | ||
current[ key ] = value; | ||
} else { | ||
current[ key ] = current[ key ] || {}; | ||
} | ||
|
||
current = current[ key ] as Record< string, unknown >; | ||
} | ||
|
||
return newState; | ||
): T { | ||
return updateNested( state, path, value ); | ||
} |
Oops, something went wrong.