2020-03-10 13:39:21 +00:00
|
|
|
/**
|
|
|
|
* External dependencies
|
|
|
|
*/
|
2020-04-02 09:27:54 +00:00
|
|
|
import { uniqueId } from 'lodash';
|
2020-03-10 13:39:21 +00:00
|
|
|
|
|
|
|
export const TYPES = {
|
|
|
|
ADD_EVENT_CALLBACK: 'add_event_callback',
|
|
|
|
REMOVE_EVENT_CALLBACK: 'remove_event_callback',
|
|
|
|
};
|
|
|
|
|
|
|
|
export const actions = {
|
2020-04-03 11:50:54 +00:00
|
|
|
addEventCallback: ( eventType, callback, priority = 10 ) => {
|
2020-03-10 13:39:21 +00:00
|
|
|
return {
|
|
|
|
id: uniqueId(),
|
|
|
|
type: TYPES.ADD_EVENT_CALLBACK,
|
|
|
|
eventType,
|
|
|
|
callback,
|
2020-04-03 11:50:54 +00:00
|
|
|
priority,
|
2020-03-10 13:39:21 +00:00
|
|
|
};
|
|
|
|
},
|
|
|
|
removeEventCallback: ( eventType, id ) => {
|
|
|
|
return {
|
|
|
|
id,
|
|
|
|
type: TYPES.REMOVE_EVENT_CALLBACK,
|
|
|
|
eventType,
|
|
|
|
};
|
|
|
|
},
|
|
|
|
};
|
|
|
|
|
|
|
|
/**
|
|
|
|
* Handles actions for emmitters
|
|
|
|
*
|
|
|
|
* @param {Object} state Current state.
|
|
|
|
* @param {Object} action Incoming action object
|
|
|
|
*/
|
2020-04-03 11:50:54 +00:00
|
|
|
export const reducer = (
|
|
|
|
state = {},
|
|
|
|
{ type, eventType, id, callback, priority }
|
|
|
|
) => {
|
2020-04-02 09:27:54 +00:00
|
|
|
const newEvents = new Map( state[ eventType ] );
|
2020-03-10 13:39:21 +00:00
|
|
|
switch ( type ) {
|
|
|
|
case TYPES.ADD_EVENT_CALLBACK:
|
2020-04-03 11:50:54 +00:00
|
|
|
newEvents.set( id, { priority, callback } );
|
2020-03-10 13:39:21 +00:00
|
|
|
return {
|
|
|
|
...state,
|
2020-04-02 09:27:54 +00:00
|
|
|
[ eventType ]: newEvents,
|
2020-03-10 13:39:21 +00:00
|
|
|
};
|
|
|
|
case TYPES.REMOVE_EVENT_CALLBACK:
|
2020-04-02 09:27:54 +00:00
|
|
|
newEvents.delete( id );
|
2020-03-10 13:39:21 +00:00
|
|
|
return {
|
|
|
|
...state,
|
2020-04-02 09:27:54 +00:00
|
|
|
[ eventType ]: newEvents,
|
2020-03-10 13:39:21 +00:00
|
|
|
};
|
|
|
|
}
|
|
|
|
return state;
|
|
|
|
};
|