| 1 |
/* eslint-disable react-hooks/rules-of-hooks */ |
| 2 |
|
| 3 |
( function ( wp, wc ) { |
| 4 |
'use strict'; |
| 5 |
|
| 6 |
if ( ! wp || ! wc ) { |
| 7 |
return; |
| 8 |
} |
| 9 |
|
| 10 |
const el = wp.element.createElement; |
| 11 |
const { withInstanceId } = wp.compose; |
| 12 |
const { useDispatch, useSelect } = wp.data; |
| 13 |
const { useEffect, useState } = wp.element; |
| 14 |
const { __ } = wp.i18n; |
| 15 |
const { getSetting } = wc.wcSettings; |
| 16 |
const { VALIDATION_STORE_KEY } = wc.wcBlocksData; |
| 17 |
const { CheckboxControl, registerCheckoutBlock } = wc.blocksCheckout; |
| 18 |
|
| 19 |
registerCheckoutBlock( { |
| 20 |
metadata: { |
| 21 |
name: 'mypreview/woo-additional-terms', |
| 22 |
parent: [ 'woocommerce/checkout-fields-block' ], |
| 23 |
}, |
| 24 |
component: withInstanceId( ( { instanceId, checkoutExtensionData } ) => { |
| 25 |
const { content, notice } = getSetting( '_woo_additional_terms_data', '' ); |
| 26 |
|
| 27 |
if ( ! notice ) { |
| 28 |
return null; |
| 29 |
} |
| 30 |
|
| 31 |
const validationErrorId = `_woo_additional_terms_data_${ instanceId }`; |
| 32 |
const { setExtensionData } = checkoutExtensionData; |
| 33 |
const [ checked, setChecked ] = useState( false ); |
| 34 |
const { setValidationErrors, clearValidationError } = useDispatch( VALIDATION_STORE_KEY ); |
| 35 |
const error = useSelect( ( select ) => |
| 36 |
select( VALIDATION_STORE_KEY ).getValidationError( validationErrorId ) |
| 37 |
); |
| 38 |
const hasError = !! ( error?.message && ! error?.hidden ); |
| 39 |
|
| 40 |
useEffect( () => { |
| 41 |
setExtensionData( '_woo_additional_terms', 'wat_checkbox', checked ); |
| 42 |
|
| 43 |
if ( checked ) { |
| 44 |
clearValidationError( validationErrorId ); |
| 45 |
} else { |
| 46 |
setValidationErrors( { |
| 47 |
[ validationErrorId ]: { |
| 48 |
message: __( |
| 49 |
'Please read and accept the additional terms and conditions to proceed with your order.', |
| 50 |
'woo-additional-terms' |
| 51 |
), |
| 52 |
hidden: true, |
| 53 |
}, |
| 54 |
} ); |
| 55 |
} |
| 56 |
|
| 57 |
return () => { |
| 58 |
clearValidationError( validationErrorId ); |
| 59 |
}; |
| 60 |
}, [ setExtensionData, checked, validationErrorId, clearValidationError, setValidationErrors ] ); |
| 61 |
|
| 62 |
return el( |
| 63 |
'div', |
| 64 |
{ |
| 65 |
className: 'woocommerce-terms-and-conditions-wrapper woo-additional-terms', |
| 66 |
}, |
| 67 |
el( 'div', { |
| 68 |
dangerouslySetInnerHTML: { |
| 69 |
__html: content, |
| 70 |
}, |
| 71 |
} ), |
| 72 |
el( |
| 73 |
CheckboxControl, |
| 74 |
{ |
| 75 |
checked, |
| 76 |
hasError, |
| 77 |
id: '_woo_additional_terms', |
| 78 |
name: '_woo_additional_terms', |
| 79 |
onChange: () => setChecked( ( value ) => ! value ), |
| 80 |
}, |
| 81 |
el( 'span', { |
| 82 |
dangerouslySetInnerHTML: { |
| 83 |
__html: notice, |
| 84 |
}, |
| 85 |
} ) |
| 86 |
) |
| 87 |
); |
| 88 |
} ), |
| 89 |
} ); |
| 90 |
} )( window.wp, window.wc ); |
| 91 |
|