Skip to content

Commit

Permalink
DataViews Fields API: default getValueFromId supports nested objects (W…
Browse files Browse the repository at this point in the history
…ordPress#66890)

Co-authored-by: oandregal <[email protected]>
Co-authored-by: youknowriad <[email protected]>
Co-authored-by: ntsekouras <[email protected]>
Co-authored-by: cbravobernal <[email protected]>
  • Loading branch information
5 people authored and karthick-murugan committed Nov 13, 2024
1 parent 7eade84 commit 258164d
Show file tree
Hide file tree
Showing 2 changed files with 62 additions and 2 deletions.
19 changes: 17 additions & 2 deletions packages/dataviews/src/normalize-fields.ts
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,22 @@ import type {
import { getControl } from './dataform-controls';
import DataFormCombinedEdit from './components/dataform-combined-edit';

const getValueFromId =
( id: string ) =>
( { item }: { item: any } ) => {
const path = id.split( '.' );
let value = item;
for ( const segment of path ) {
if ( value.hasOwnProperty( segment ) ) {
value = value[ segment ];
} else {
value = undefined;
}
}

return value;
};

/**
* Apply default values and normalize the fields config.
*
Expand All @@ -23,8 +39,7 @@ export function normalizeFields< Item >(
return fields.map( ( field ) => {
const fieldTypeDefinition = getFieldTypeDefinition( field.type );

const getValue =
field.getValue || ( ( { item } ) => ( item as any )[ field.id ] );
const getValue = field.getValue || getValueFromId( field.id );

const sort =
field.sort ??
Expand Down
45 changes: 45 additions & 0 deletions packages/dataviews/src/test/normalize-fields.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,45 @@
/**
* Internal dependencies
*/
import { normalizeFields } from '../normalize-fields';
import type { Field } from '../types';

describe( 'normalizeFields: default getValue', () => {
describe( 'getValue from ID', () => {
it( 'user', () => {
const item = { user: 'value' };
const fields: Field< {} >[] = [
{
id: 'user',
},
];
const normalizedFields = normalizeFields( fields );
const result = normalizedFields[ 0 ].getValue( { item } );
expect( result ).toBe( 'value' );
} );

it( 'user.name', () => {
const item = { user: { name: 'value' } };
const fields: Field< {} >[] = [
{
id: 'user.name',
},
];
const normalizedFields = normalizeFields( fields );
const result = normalizedFields[ 0 ].getValue( { item } );
expect( result ).toBe( 'value' );
} );

it( 'user.name.first', () => {
const item = { user: { name: { first: 'value' } } };
const fields: Field< {} >[] = [
{
id: 'user.name.first',
},
];
const normalizedFields = normalizeFields( fields );
const result = normalizedFields[ 0 ].getValue( { item } );
expect( result ).toBe( 'value' );
} );
} );
} );

0 comments on commit 258164d

Please sign in to comment.