2021-03-09 10:50:51 +00:00
|
|
|
/**
|
|
|
|
* Internal dependencies
|
|
|
|
*/
|
|
|
|
import {
|
|
|
|
ACTION,
|
|
|
|
ActionType,
|
|
|
|
ActionCallbackType,
|
|
|
|
EventObserversType,
|
|
|
|
} from './types';
|
|
|
|
|
2023-04-28 10:29:45 +00:00
|
|
|
export function generateUniqueId() {
|
|
|
|
return Math.floor( Math.random() * Date.now() ).toString();
|
|
|
|
}
|
|
|
|
|
2021-03-09 10:50:51 +00:00
|
|
|
export const actions = {
|
|
|
|
addEventCallback: (
|
|
|
|
eventType: string,
|
|
|
|
callback: ActionCallbackType,
|
|
|
|
priority = 10
|
|
|
|
): ActionType => {
|
|
|
|
return {
|
2023-04-28 10:29:45 +00:00
|
|
|
id: generateUniqueId(),
|
2021-03-09 10:50:51 +00:00
|
|
|
type: ACTION.ADD_EVENT_CALLBACK,
|
|
|
|
eventType,
|
|
|
|
callback,
|
|
|
|
priority,
|
|
|
|
};
|
|
|
|
},
|
|
|
|
removeEventCallback: ( eventType: string, id: string ): ActionType => {
|
|
|
|
return {
|
|
|
|
id,
|
|
|
|
type: ACTION.REMOVE_EVENT_CALLBACK,
|
|
|
|
eventType,
|
|
|
|
};
|
|
|
|
},
|
|
|
|
};
|
|
|
|
|
|
|
|
const initialState = {} as EventObserversType;
|
|
|
|
|
|
|
|
/**
|
|
|
|
* Handles actions for emitters
|
|
|
|
*/
|
|
|
|
export const reducer = (
|
|
|
|
state = initialState,
|
|
|
|
{ type, eventType, id, callback, priority }: ActionType
|
|
|
|
): typeof initialState => {
|
|
|
|
const newEvents = state.hasOwnProperty( eventType )
|
|
|
|
? new Map( state[ eventType ] )
|
|
|
|
: new Map();
|
|
|
|
switch ( type ) {
|
|
|
|
case ACTION.ADD_EVENT_CALLBACK:
|
|
|
|
newEvents.set( id, { priority, callback } );
|
|
|
|
return {
|
|
|
|
...state,
|
|
|
|
[ eventType ]: newEvents,
|
|
|
|
};
|
|
|
|
case ACTION.REMOVE_EVENT_CALLBACK:
|
|
|
|
newEvents.delete( id );
|
|
|
|
return {
|
|
|
|
...state,
|
|
|
|
[ eventType ]: newEvents,
|
|
|
|
};
|
|
|
|
}
|
|
|
|
};
|