-
Notifications
You must be signed in to change notification settings - Fork 4.2k
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
Move overlapping logic to useFieldValue hook
Showing
3 changed files
with
42 additions
and
37 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
38 changes: 38 additions & 0 deletions
38
packages/dataviews/src/dataforms-layouts/use-field-value.ts
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 |
---|---|---|
@@ -0,0 +1,38 @@ | ||
/** | ||
* WordPress dependencies | ||
*/ | ||
import { useContext, useMemo } from '@wordpress/element'; | ||
|
||
/** | ||
* Internal dependencies | ||
*/ | ||
import DataFormContext from '../components/dataform-context'; | ||
import { MIXED_VALUE } from '../constants'; | ||
|
||
export default function useFieldValue< Item >( | ||
data: Item | Item[], | ||
fieldId: string | ||
) { | ||
const { fields } = useContext( DataFormContext ); | ||
return useMemo( () => { | ||
const fieldDefinition = fields.find( | ||
( fieldDef ) => fieldDef.id === fieldId | ||
); | ||
if ( ! fieldDefinition ) { | ||
return undefined; | ||
} | ||
if ( Array.isArray( data ) ) { | ||
const [ firstRecord, ...remainingRecords ] = data; | ||
const firstValue = fieldDefinition.getValue( { | ||
item: firstRecord, | ||
} ); | ||
const intersects = remainingRecords.every( ( item ) => { | ||
return fieldDefinition.getValue( { item } ) === firstValue; | ||
} ); | ||
return intersects ? firstValue : MIXED_VALUE; | ||
} | ||
return fieldDefinition.getValue( { | ||
item: data, | ||
} ); | ||
}, [ data, fields, fieldId ] ); | ||
} |