Skip to content

Commit

Permalink
DataForm: provide a better default for render when field has elements (
Browse files Browse the repository at this point in the history
…#64338)

Co-authored-by: oandregal <oandregal@git.wordpress.org>
Co-authored-by: youknowriad <youknowriad@git.wordpress.org>
  • Loading branch information
3 people authored Aug 7, 2024
1 parent dc54a90 commit 50419e5
Showing 1 changed file with 17 additions and 3 deletions.
20 changes: 17 additions & 3 deletions packages/dataviews/src/normalize-fields.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@
* Internal dependencies
*/
import getFieldTypeDefinition from './field-types';
import type { Field, NormalizedField, ItemRecord } from './types';
import type { Field, NormalizedField } from './types';

/**
* Apply default values and normalize the fields config.
Expand All @@ -18,7 +18,7 @@ export function normalizeFields< Item >(

const getValue =
field.getValue ||
( ( { item }: { item: ItemRecord } ) => item[ field.id ] );
( ( { item }: { item: Item } ) => item[ field.id as keyof Item ] );

const sort =
field.sort ??
Expand All @@ -41,11 +41,25 @@ export function normalizeFields< Item >(

const Edit = field.Edit || fieldTypeDefinition.Edit;

const renderFromElements = ( { item }: { item: Item } ) => {
const value = getValue( { item } );
const label = field?.elements?.find( ( element ) => {
// Intentionally using == here to allow for type coercion.
// eslint-disable-next-line eqeqeq
return element.value == value;
} )?.label;

return label || value;
};

const render =
field.render || ( field.elements ? renderFromElements : getValue );

return {
...field,
label: field.label || field.id,
getValue,
render: field.render || getValue,
render,
sort,
isValid,
Edit,
Expand Down

0 comments on commit 50419e5

Please sign in to comment.