| 1 |
/** |
| 2 |
* WordPress dependencies |
| 3 |
*/ |
| 4 |
import { createReduxStore } from '@wordpress/data'; |
| 5 |
|
| 6 |
/** |
| 7 |
* Internal dependencies |
| 8 |
*/ |
| 9 |
import type { Settings } from './types'; |
| 10 |
|
| 11 |
// Define state type. |
| 12 |
interface SettingsState { |
| 13 |
[endpoint: string]: Settings; |
| 14 |
} |
| 15 |
|
| 16 |
// Define action types. |
| 17 |
interface SetSettingsAction { |
| 18 |
type: 'SET_SETTINGS'; |
| 19 |
endpoint: string; |
| 20 |
settings: Settings; |
| 21 |
} |
| 22 |
|
| 23 |
interface SetPartialSettingsAction { |
| 24 |
type: 'SET_PARTIAL_SETTINGS'; |
| 25 |
endpoint: string; |
| 26 |
partialSettings: Partial<Settings>; |
| 27 |
} |
| 28 |
|
| 29 |
// Union of all action types. |
| 30 |
type ActionTypes = SetSettingsAction | SetPartialSettingsAction; |
| 31 |
|
| 32 |
// Default state. |
| 33 |
const DEFAULT_STATE: SettingsState = {}; |
| 34 |
|
| 35 |
// Store name. |
| 36 |
export const STORE_NAME = 'wp-parsely/settings'; |
| 37 |
|
| 38 |
// Reducer. |
| 39 |
const reducer = ( state: SettingsState = DEFAULT_STATE, action: ActionTypes ): SettingsState => { |
| 40 |
switch ( action.type ) { |
| 41 |
case 'SET_SETTINGS': { |
| 42 |
return { |
| 43 |
...state, |
| 44 |
[ action.endpoint ]: action.settings, |
| 45 |
}; |
| 46 |
} |
| 47 |
case 'SET_PARTIAL_SETTINGS': { |
| 48 |
const currentSettings = state[ action.endpoint ] || {}; |
| 49 |
const updatedSettings = { ...currentSettings, ...action.partialSettings } as Settings; |
| 50 |
return { |
| 51 |
...state, |
| 52 |
[ action.endpoint ]: updatedSettings, |
| 53 |
}; |
| 54 |
} |
| 55 |
default: |
| 56 |
return state; |
| 57 |
} |
| 58 |
}; |
| 59 |
|
| 60 |
// Actions. |
| 61 |
const actions = { |
| 62 |
setSettings( endpoint: string, settings: Settings ): SetSettingsAction { |
| 63 |
return { type: 'SET_SETTINGS', endpoint, settings }; |
| 64 |
}, |
| 65 |
setPartialSettings( endpoint: string, partialSettings: Partial<Settings> ): SetPartialSettingsAction { |
| 66 |
return { type: 'SET_PARTIAL_SETTINGS', endpoint, partialSettings }; |
| 67 |
}, |
| 68 |
}; |
| 69 |
|
| 70 |
// Selectors. |
| 71 |
const selectors = { |
| 72 |
getSettings( state: SettingsState, endpoint: string ): Settings { |
| 73 |
return state[ endpoint ]; |
| 74 |
}, |
| 75 |
}; |
| 76 |
|
| 77 |
// Create and register the store. |
| 78 |
export const SettingsStore = createReduxStore( STORE_NAME, { |
| 79 |
initialState: DEFAULT_STATE, |
| 80 |
reducer, |
| 81 |
actions, |
| 82 |
selectors, |
| 83 |
} ); |
| 84 |
|