signal-desktop/ts/state/ducks/emojis.ts

72 lines
1.5 KiB
TypeScript
Raw Normal View History

2019-05-24 23:58:27 +00:00
import { take, uniq } from 'lodash';
import { EmojiPickDataType } from '../../components/emoji/EmojiPicker';
import dataInterface from '../../sql/Client';
import { useBoundActions } from '../../util/hooks';
const { updateEmojiUsage } = dataInterface;
2019-05-24 23:58:27 +00:00
// State
export type EmojisStateType = {
readonly recents: Array<string>;
};
// Actions
type OnUseEmojiPayloadType = string;
type OnUseEmojiAction = {
2019-05-24 23:58:27 +00:00
type: 'emojis/USE_EMOJI';
payload: Promise<OnUseEmojiPayloadType>;
2019-05-24 23:58:27 +00:00
};
type OnUseEmojiFulfilledAction = {
2019-05-24 23:58:27 +00:00
type: 'emojis/USE_EMOJI_FULFILLED';
payload: OnUseEmojiPayloadType;
2019-05-24 23:58:27 +00:00
};
export type EmojisActionType = OnUseEmojiAction | OnUseEmojiFulfilledAction;
2019-05-24 23:58:27 +00:00
// Action Creators
export const actions = {
onUseEmoji,
2019-05-24 23:58:27 +00:00
};
export const useActions = () => useBoundActions(actions);
function onUseEmoji({ shortName }: EmojiPickDataType): OnUseEmojiAction {
2019-05-24 23:58:27 +00:00
return {
type: 'emojis/USE_EMOJI',
payload: doUseEmoji(shortName),
};
}
async function doUseEmoji(shortName: string): Promise<OnUseEmojiPayloadType> {
2019-05-24 23:58:27 +00:00
await updateEmojiUsage(shortName);
return shortName;
}
// Reducer
function getEmptyState(): EmojisStateType {
return {
recents: [],
};
}
export function reducer(
state: EmojisStateType = getEmptyState(),
action: EmojisActionType
): EmojisStateType {
if (action.type === 'emojis/USE_EMOJI_FULFILLED') {
const { payload } = action;
return {
...state,
recents: take(uniq([payload, ...state.recents]), 32),
};
}
return state;
}