summaryrefslogtreecommitdiff
blob: 7649fd45f19559a89bd2d1533778fbc9a46c837d (plain)
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
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
/**
 * External dependencies
 */
import apiFetch from '@wordpress/api-fetch';
import classNames from 'classnames';
import { __ } from '@wordpress/i18n';
import { __experimentalGetSettings } from '@wordpress/date';
import { BlockIcon } from '@wordpress/editor';
import { Component } from '@wordpress/element';
import { Placeholder } from '@wordpress/components';

/**
 * Internal dependencies
 */
import DayEdit from './components/day-edit';
import DayPreview from './components/day-preview';
import { icon } from '.';

const defaultLocalization = {
	days: {
		Sun: __( 'Sunday', 'jetpack' ),
		Mon: __( 'Monday', 'jetpack' ),
		Tue: __( 'Tuesday', 'jetpack' ),
		Wed: __( 'Wednesday', 'jetpack' ),
		Thu: __( 'Thursday', 'jetpack' ),
		Fri: __( 'Friday', 'jetpack' ),
		Sat: __( 'Saturday', 'jetpack' ),
	},
	startOfWeek: 0,
};

class BusinessHours extends Component {
	state = {
		localization: defaultLocalization,
		hasFetched: false,
	};

	componentDidMount() {
		this.apiFetch();
	}

	apiFetch() {
		this.setState( { data: defaultLocalization }, () => {
			apiFetch( { path: '/wpcom/v2/business-hours/localized-week' } ).then(
				data => {
					this.setState( { localization: data, hasFetched: true } );
				},
				() => {
					this.setState( { localization: defaultLocalization, hasFetched: true } );
				}
			);
		} );
	}

	render() {
		const { attributes, className, isSelected } = this.props;
		const { days } = attributes;
		const { localization, hasFetched } = this.state;
		const { startOfWeek } = localization;
		const localizedWeek = days.concat( days.slice( 0, startOfWeek ) ).slice( startOfWeek );

		if ( ! hasFetched ) {
			return (
				<Placeholder
					icon={ <BlockIcon icon={ icon } /> }
					label={ __( 'Loading business hours', 'jetpack' ) }
				/>
			);
		}

		if ( ! isSelected ) {
			const settings = __experimentalGetSettings();
			const {
				formats: { time },
			} = settings;
			return (
				<dl className={ classNames( className, 'jetpack-business-hours' ) }>
					{ localizedWeek.map( ( day, key ) => {
						return (
							<DayPreview
								key={ key }
								day={ day }
								localization={ localization }
								timeFormat={ time }
							/>
						);
					} ) }
				</dl>
			);
		}

		return (
			<div className={ classNames( className, 'is-edit' ) }>
				{ localizedWeek.map( ( day, key ) => {
					return (
						<DayEdit key={ key } day={ day } localization={ localization } { ...this.props } />
					);
				} ) }
			</div>
		);
	}
}

export default BusinessHours;