-
Notifications
You must be signed in to change notification settings - Fork 4.2k
/
index.tsx
68 lines (61 loc) · 1.63 KB
/
index.tsx
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
/**
* WordPress dependencies
*/
import { useMemo } from '@wordpress/element';
/**
* Internal dependencies
*/
import type { DataFormProps } from '../../types';
import { DataFormProvider } from '../dataform-context';
import { normalizeFields } from '../../normalize-fields';
import { DataFormLayout } from '../../dataforms-layouts/data-form-layout';
/**
* Loops through the list of data items and returns an object with the intersecting ( same ) key and values.
*
* @param data list of items.
*/
function getIntersectingValues< Item extends object >( data: Item[] ): Item {
const intersectingValues = {} as Item;
const keys = Object.keys( data[ 0 ] ) as Array< keyof Item >;
for ( const key of keys ) {
const [ firstRecord, ...remainingRecords ] = data;
const intersects = remainingRecords.every( ( item ) => {
return item[ key ] === firstRecord[ key ];
} );
if ( intersects ) {
intersectingValues[ key ] = firstRecord[ key ];
}
}
return intersectingValues;
}
export default function DataForm< Item extends object >( {
data,
form,
fields,
onChange,
}: DataFormProps< Item > ) {
const normalizedFields = useMemo(
() => normalizeFields( fields ),
[ fields ]
);
const flattenedData = useMemo( () => {
if ( Array.isArray( data ) ) {
return getIntersectingValues< Item >( data );
}
return data;
}, [ data ] );
if ( ! form.fields ) {
return null;
}
const isBulkEditing = Array.isArray( data );
return (
<DataFormProvider fields={ normalizedFields }>
<DataFormLayout
data={ flattenedData }
form={ form }
onChange={ onChange }
isBulkEditing={ isBulkEditing }
/>
</DataFormProvider>
);
}