-
Notifications
You must be signed in to change notification settings - Fork 10.7k
/
edit.tsx
80 lines (69 loc) · 2.14 KB
/
edit.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
69
70
71
72
73
74
75
76
77
78
79
80
/**
* External dependencies
*/
import { useWooBlockProps } from '@woocommerce/block-templates';
import { recordEvent } from '@woocommerce/tracks';
import { Spinner, ToggleControl } from '@wordpress/components';
import { createElement, useMemo } from '@wordpress/element';
import {
// @ts-expect-error no exported member.
useInnerBlocksProps,
} from '@wordpress/block-editor';
/**
* Internal dependencies
*/
import { TRACKS_SOURCE } from '../../../constants';
import { useMetaboxHiddenProduct } from '../../../hooks/use-metabox-hidden-product';
import { ProductEditorBlockEditProps } from '../../../types';
import { CustomFieldsToggleBlockAttributes } from './types';
const METABOX_HIDDEN_VALUE = 'postcustom';
export function Edit( {
attributes,
}: ProductEditorBlockEditProps< CustomFieldsToggleBlockAttributes > ) {
const { label, _templateBlockId } = attributes;
const blockProps = useWooBlockProps( attributes );
const innerBlockProps = useInnerBlocksProps(
{
className:
'wp-block-woocommerce-product-custom-fields-toggle-field__inner-blocks',
},
{ templateLock: 'all' }
);
const { isLoading, metaboxhiddenProduct, saveMetaboxhiddenProduct } =
useMetaboxHiddenProduct();
const isChecked = useMemo( () => {
return (
metaboxhiddenProduct &&
! metaboxhiddenProduct.some(
( value ) => value === METABOX_HIDDEN_VALUE
)
);
}, [ metaboxhiddenProduct ] );
async function handleChange( checked: boolean ) {
const values = checked
? metaboxhiddenProduct.filter(
( value ) => value !== METABOX_HIDDEN_VALUE
)
: [ ...metaboxhiddenProduct, METABOX_HIDDEN_VALUE ];
recordEvent( 'product_custom_fields_toggle_click', {
block_id: _templateBlockId,
source: TRACKS_SOURCE,
metaboxhidden_product: values,
} );
await saveMetaboxhiddenProduct( values );
}
return (
<div { ...blockProps }>
<div className="wp-block-woocommerce-product-custom-fields-toggle-field__content">
<ToggleControl
label={ label }
checked={ isChecked }
disabled={ isLoading }
onChange={ handleChange }
/>
{ isLoading && <Spinner /> }
</div>
{ isChecked && <div { ...innerBlockProps } /> }
</div>
);
}