Back

0% Statements 0/87
0% Branches 0/1
0% Functions 0/1
0% Lines 0/87

Press n or j to go to the next uncovered block, b, p or k for the previous block.

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                                                                                                                                                                               
import { combineReducers, registerStore } from '@wordpress/data';
import { apiFetch as apiFetchControls, controls } from '@wordpress/data-controls';

const shouldShowFirstPostPublishedModalReducer = ( state = false, action ) => {
	switch ( action.type ) {
		case 'WPCOM_SET_SHOULD_SHOW_FIRST_POST_PUBLISHED_MODAL':
			return action.value;
		default:
			return state;
	}
};

const fourForFourEligibleReducer = ( state = false, action ) => {
	switch ( action.type ) {
		case 'WPCOM_SET_FOUR_FOR_FOUR_ELIGIBLE':
			return action.value;
		default:
			return state;
	}
};

const reducer = combineReducers( {
	shouldShowFirstPostPublishedModal: shouldShowFirstPostPublishedModalReducer,
	fourForFourEligible: fourForFourEligibleReducer,
} );

export const actions = {
	*fetchShouldShowFirstPostPublishedModal() {
		const response = yield apiFetchControls( {
			path: '/wpcom/v2/block-editor/should-show-first-post-published-modal',
		} );

		return {
			type: 'WPCOM_SET_SHOULD_SHOW_FIRST_POST_PUBLISHED_MODAL',
			value: response.should_show_first_post_published_modal,
		};
	},
	setFourForFourEligible: value => ( {
		type: 'WPCOM_SET_FOUR_FOR_FOUR_ELIGIBLE',
		value,
	} ),
	// Resolves to whether the decision was saved. An opt-in must be saved before
	// the writer leaves for the Reader, where only opted-in writers can complete.
	*setFourForFourStatus( status ) {
		if ( status === 'opted_out' ) {
			yield { type: 'WPCOM_SET_FOUR_FOR_FOUR_ELIGIBLE', value: false };
		}
		try {
			yield apiFetchControls( {
				path: '/wpcom/v2/block-editor/four-for-four',
				method: 'POST',
				data: { status },
			} );
		} catch {
			return false;
		}
		return true;
	},
};

export const resolvers = {
	*isFourForFourEligible() {
		const response = yield apiFetchControls( { path: '/wpcom/v2/block-editor/four-for-four' } );
		return actions.setFourForFourEligible( !! response.eligible );
	},
};

export const selectors = {
	getShouldShowFirstPostPublishedModal: state => state.shouldShowFirstPostPublishedModal,
	isFourForFourEligible: state => state.fourForFourEligible,
};

/**
 * Register the wpcom-welcome-guide store
 *
 * @return {object} The registered store.
 */
export function register() {
	return registerStore( 'automattic/wpcom-welcome-guide', {
		reducer,
		actions,
		selectors,
		resolvers,
		controls,
		persist: true,
	} );
}