-
Notifications
You must be signed in to change notification settings - Fork 10.7k
/
use-publish.tsx
83 lines (71 loc) · 1.92 KB
/
use-publish.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
81
82
83
/**
* External dependencies
*/
import { MouseEvent } from 'react';
import { Button } from '@wordpress/components';
import { useEntityProp } from '@wordpress/core-data';
import { isInTheFuture } from '@wordpress/date';
import { __ } from '@wordpress/i18n';
import type { Product } from '@woocommerce/data';
/**
* Internal dependencies
*/
import { useProductManager } from '../../../../hooks/use-product-manager';
import type { WPError } from '../../../../utils/get-product-error-message';
import type { PublishButtonProps } from '../../publish-button';
export function usePublish< T = Product >( {
productType = 'product',
disabled,
onClick,
onPublishSuccess,
onPublishError,
...props
}: PublishButtonProps & {
onPublishSuccess?( product: T ): void;
onPublishError?( error: WPError ): void;
} ): Button.ButtonProps {
const { isValidating, isDirty, isPublishing, publish } =
useProductManager( productType );
const [ , , prevStatus ] = useEntityProp< Product[ 'status' ] >(
'postType',
productType,
'status'
);
const [ editedDate ] = useEntityProp< string >(
'postType',
productType,
'date_created_gmt'
);
const isBusy = isPublishing || isValidating;
const isDisabled = disabled || isBusy || ! isDirty;
function handleClick( event: MouseEvent< HTMLButtonElement > ) {
if ( isDisabled ) {
event.preventDefault?.();
return;
}
if ( onClick ) {
onClick( event );
}
publish().then( onPublishSuccess ).catch( onPublishError );
}
function getButtonText() {
if (
window.wcAdminFeatures[ 'product-pre-publish-modal' ] &&
isInTheFuture( editedDate )
) {
return __( 'Schedule', 'woocommerce' );
}
if ( prevStatus === 'publish' || prevStatus === 'future' ) {
return __( 'Update', 'woocommerce' );
}
return __( 'Publish', 'woocommerce' );
}
return {
children: getButtonText(),
...props,
isBusy,
'aria-disabled': isDisabled,
variant: 'primary',
onClick: handleClick,
};
}