🚚 Rename Redux store (settings-tab → settings)

This commit is contained in:
Philipp Stracker 2025-01-21 15:52:55 +01:00
parent 664e81d5c3
commit e2f88cdef8
No known key found for this signature in database
10 changed files with 1 additions and 1 deletions

View file

@ -0,0 +1,40 @@
/**
* Settings action types
*
* Defines the constants used for dispatching actions in the settings store.
* Each constant represents a unique action type that can be handled by reducers.
*
* @file
*/
export default {
/**
* Represents setting transient (temporary) state data.
* These values are not persisted and will reset on page reload.
*/
SET_TRANSIENT: 'ppcp/settings/SET_TRANSIENT',
/**
* Represents setting persistent state data.
* These values are meant to be saved to the server and persist between page loads.
*/
SET_PERSISTENT: 'ppcp/settings/SET_PERSISTENT',
/**
* Resets the store state to its initial values.
* Used when needing to clear all settings data.
*/
RESET: 'ppcp/settings/RESET',
/**
* Initializes the store with data, typically used during store initialization
* to set up the initial state with data from the server.
*/
HYDRATE: 'ppcp/settings/HYDRATE',
/**
* Triggers the persistence of store data to the server.
* Used when changes need to be saved to the backend.
*/
DO_PERSIST_DATA: 'ppcp/settings/DO_PERSIST_DATA',
};

View file

@ -0,0 +1,71 @@
/**
* Action Creators: Define functions to create action objects.
*
* These functions update state or trigger side effects (e.g., async operations).
* Actions are categorized as Transient, Persistent, or Side effect.
*
* @file
*/
import { select } from '@wordpress/data';
import ACTION_TYPES from './action-types';
import { STORE_NAME } from './constants';
/**
* @typedef {Object} Action An action object that is handled by a reducer or control.
* @property {string} type - The action type.
* @property {Object?} payload - Optional payload for the action.
*/
/**
* Special. Resets all values in the store to initial defaults.
*
* @return {Action} The action.
*/
export const reset = () => ( {
type: ACTION_TYPES.RESET,
} );
/**
* Persistent. Sets the full store details during app initialization.
*
* @param {Object} payload Initial store data
* @return {Action} The action.
*/
export const hydrate = ( payload ) => ( {
type: ACTION_TYPES.HYDRATE,
payload,
} );
/**
* Transient. Marks the store as "ready", i.e., fully initialized.
*
* @param {boolean} isReady Whether the store is ready
* @return {Action} The action.
*/
export const setIsReady = ( isReady ) => ( {
type: ACTION_TYPES.SET_TRANSIENT,
payload: { isReady },
} );
/**
* Persistent. Updates the settings data in the store.
*
* @param {Object} settings The settings object to store
* @return {Action} The action.
*/
export const setSettings = ( settings ) => ( {
type: ACTION_TYPES.SET_PERSISTENT,
payload: settings,
} );
/**
* Side effect. Triggers the persistence of store data to the server.
* Yields an action with the current persistent data to be saved.
*
* @return {Action} The action.
*/
export const persist = function* () {
const data = yield select( STORE_NAME ).persistentData();
yield { type: ACTION_TYPES.DO_PERSIST_DATA, data };
};

View file

@ -0,0 +1,28 @@
/**
* Name of the Redux store module.
*
* Used by: Reducer, Selector, Index
*
* @type {string}
*/
export const STORE_NAME = 'wc/paypal/settings';
/**
* REST path to hydrate data of this module by loading data from the WP DB.
*
* Used by: Resolvers
* See: SettingsRestEndpoint.php
*
* @type {string}
*/
export const REST_HYDRATE_PATH = '/wc/v3/wc_paypal/settings';
/**
* REST path to persist data of this module to the WP DB.
*
* Used by: Controls
* See: SettingsRestEndpoint.php
*
* @type {string}
*/
export const REST_PERSIST_PATH = '/wc/v3/wc_paypal/settings';

View file

@ -0,0 +1,34 @@
/**
* Controls: Implement side effects, typically asynchronous operations.
*
* Controls use ACTION_TYPES keys as identifiers.
* They are triggered by corresponding actions and handle external interactions.
*
* @file
*/
import apiFetch from '@wordpress/api-fetch';
import { REST_PERSIST_PATH } from './constants';
import ACTION_TYPES from './action-types';
/**
* Control handlers for settings store actions.
* Each handler maps to an ACTION_TYPE and performs the corresponding async operation.
*/
export const controls = {
/**
* Persists settings data to the server via REST API.
* Triggered by the DO_PERSIST_DATA action to save settings changes.
*
* @param {Object} action The action object
* @param {Object} action.data The settings data to persist
* @return {Promise<Object>} The API response
*/
async [ ACTION_TYPES.DO_PERSIST_DATA ]( { data } ) {
return await apiFetch( {
path: REST_PERSIST_PATH,
method: 'POST',
data,
} );
},
};

View file

@ -0,0 +1,43 @@
/**
* Hooks: Provide the main API for components to interact with the store.
*
* These encapsulate store interactions, offering a consistent interface.
* Hooks simplify data access and manipulation for components.
*
* @file
*/
import { useDispatch } from '@wordpress/data';
import { STORE_NAME } from './constants';
import { createHooksForStore } from '../utils';
const useHooks = () => {
const { useTransient, usePersistent } = createHooksForStore( STORE_NAME );
const { persist } = useDispatch( STORE_NAME );
// Read-only flags and derived state.
const [ isReady ] = useTransient( 'isReady' );
// Persistent accessors.
const [ settings, setSettings ] = usePersistent( 'settings' );
return {
persist,
isReady,
settings,
setSettings,
};
};
export const useStore = () => {
const { persist, isReady } = useHooks();
return { persist, isReady };
};
export const useSettings = () => {
const { settings, setSettings } = useHooks();
return {
settings,
setSettings,
};
};

View file

@ -0,0 +1,40 @@
/**
* Store Configuration: Defines and registers the settings data store.
*
* Creates a Redux-style store with WordPress data layer integration.
* Combines reducers, actions, selectors and controls into a unified store.
*
* @file
*/
import { createReduxStore, register } from '@wordpress/data';
import { controls as wpControls } from '@wordpress/data-controls';
import { STORE_NAME } from './constants';
import reducer from './reducer';
import * as selectors from './selectors';
import * as actions from './actions';
import * as hooks from './hooks';
import { resolvers } from './resolvers';
import { controls } from './controls';
/**
* Initializes and registers the settings store with WordPress data layer.
* Combines custom controls with WordPress data controls.
*
* @return {boolean} True if initialization succeeded, false otherwise.
*/
export const initStore = () => {
const store = createReduxStore( STORE_NAME, {
reducer,
controls: { ...wpControls, ...controls },
actions,
selectors,
resolvers,
} );
register( store );
return Boolean( wp.data.select( STORE_NAME ) );
};
export { hooks, selectors, STORE_NAME };

View file

@ -0,0 +1,107 @@
/**
* Reducer: Defines store structure and state updates for this module.
*
* Manages both transient (temporary) and persistent (saved) state.
* The initial state must define all properties, as dynamic additions are not supported.
*
* @file
*/
import { createReducer, createReducerSetters } from '../utils';
import ACTION_TYPES from './action-types';
// Store structure.
/**
* Transient: Values that are _not_ saved to the DB (like app lifecycle-flags).
* These reset on page reload.
*/
const defaultTransient = Object.freeze( {
isReady: false,
} );
/**
* Persistent: Values that are loaded from and saved to the DB.
* These represent the core PayPal payment settings configuration.
*/
const defaultPersistent = Object.freeze( {
invoicePrefix: '', // Prefix for PayPal invoice IDs
authorizeOnly: false, // Whether to only authorize payments initially
captureVirtualOnlyOrders: false, // Auto-capture virtual-only orders
savePaypalAndVenmo: false, // Enable PayPal & Venmo vaulting
saveCreditCardAndDebitCard: false, // Enable card vaulting
payNowExperience: false, // Enable Pay Now experience
sandboxAccountCredentials: false, // Use sandbox credentials
sandboxMode: null, // Sandbox mode configuration
sandboxEnabled: false, // Whether sandbox mode is active
sandboxClientId: '', // Sandbox API client ID
sandboxSecretKey: '', // Sandbox API secret key
sandboxConnected: false, // Sandbox connection status
logging: false, // Enable debug logging
subtotalMismatchFallback: null, // Handling for subtotal mismatches
brandName: '', // Merchant brand name for PayPal
softDescriptor: '', // Payment descriptor on statements
paypalLandingPage: null, // PayPal checkout landing page
buttonLanguage: '', // Language for PayPal buttons
} );
// Reducer logic.
const [ changeTransient, changePersistent ] = createReducerSetters(
defaultTransient,
defaultPersistent
);
/**
* Reducer implementation mapping actions to state updates.
*/
const reducer = createReducer( defaultTransient, defaultPersistent, {
/**
* Updates temporary state values
*
* @param {Object} state Current state
* @param {Object} payload Update payload
* @return {Object} Updated state
*/
[ ACTION_TYPES.SET_TRANSIENT ]: ( state, payload ) => {
return changeTransient( state, payload );
},
/**
* Updates persistent configuration values
*
* @param {Object} state Current state
* @param {Object} payload Update payload
* @return {Object} Updated state
*/
[ ACTION_TYPES.SET_PERSISTENT ]: ( state, payload ) =>
changePersistent( state, payload ),
/**
* Resets state to defaults while maintaining initialization status
*
* @param {Object} state Current state
* @return {Object} Reset state
*/
[ ACTION_TYPES.RESET ]: ( state ) => {
const cleanState = changeTransient(
changePersistent( state, defaultPersistent ),
defaultTransient
);
cleanState.isReady = true; // Keep initialization flag
return cleanState;
},
/**
* Initializes persistent state with data from the server
*
* @param {Object} state Current state
* @param {Object} payload Hydration payload containing server data
* @param {Object} payload.data The settings data to hydrate
* @return {Object} Hydrated state
*/
[ ACTION_TYPES.HYDRATE ]: ( state, payload ) =>
changePersistent( state, payload.data ),
} );
export default reducer;

View file

@ -0,0 +1,57 @@
/**
* Resolvers: Handle asynchronous data fetching for the store.
*
* These functions update store state with data from external sources.
* Each resolver corresponds to a specific selector (selector with same name must exist).
* Resolvers are called automatically when selectors request unavailable data.
*
* @file
*/
import { dispatch } from '@wordpress/data';
import { __ } from '@wordpress/i18n';
import { apiFetch } from '@wordpress/data-controls';
import { STORE_NAME, REST_HYDRATE_PATH } from './constants';
export const resolvers = {
/**
* Retrieve PayPal settings from the site's REST API.
* Hydrates the store with the retrieved data and marks it as ready.
*
* @generator
* @yield {Object} API fetch and dispatch actions
*/
*persistentData() {
try {
// Fetch settings data from REST API
const result = yield apiFetch( {
path: REST_HYDRATE_PATH,
method: 'GET',
headers: {
'Content-Type': 'application/json',
Accept: 'application/json',
},
} );
// Update store with retrieved data
yield dispatch( STORE_NAME ).hydrate( result );
// Mark store as ready for use
yield dispatch( STORE_NAME ).setIsReady( true );
} catch ( e ) {
// Log detailed error information for debugging
console.error( 'Full error details:', {
error: e,
path: REST_HYDRATE_PATH,
store: STORE_NAME,
} );
// Display user-friendly error notice
yield dispatch( 'core/notices' ).createErrorNotice(
__(
'Error retrieving PayPal settings details.',
'woocommerce-paypal-payments'
)
);
}
},
};

View file

@ -0,0 +1,46 @@
/**
* Selectors: Extract specific pieces of state from the store.
*
* These functions provide a consistent interface for accessing store data.
* They allow components to retrieve data without knowing the store structure.
*
* @file
*/
/**
* Empty frozen object used as fallback when state is undefined.
*
* @constant
* @type {Object}
*/
const EMPTY_OBJ = Object.freeze( {} );
/**
* Base selector that ensures a valid state object.
*
* @param {Object|undefined} state The current state
* @return {Object} The state or empty object if undefined
*/
export const getState = ( state ) => state || EMPTY_OBJ;
/**
* Retrieves persistent (saved) data from the store.
*
* @param {Object} state The current state
* @return {Object} The persistent data or empty object if undefined
*/
export const persistentData = ( state ) => {
return getState( state ).data || EMPTY_OBJ;
};
/**
* Retrieves transient (temporary) data from the store.
* Excludes persistent data stored in the 'data' property.
*
* @param {Object} state The current state
* @return {Object} The transient state or empty object if undefined
*/
export const transientData = ( state ) => {
const { data, ...transientState } = getState( state );
return transientState || EMPTY_OBJ;
};