bigbuffet-rw/app/soapbox/reducers/alerts.ts

60 lines
1.4 KiB
TypeScript
Raw Normal View History

import { Record as ImmutableRecord, List as ImmutableList } from 'immutable';
2020-03-27 13:59:38 -07:00
import {
ALERT_SHOW,
ALERT_DISMISS,
ALERT_CLEAR,
} from '../actions/alerts';
const AlertRecord = ImmutableRecord({
key: 0,
title: '',
message: '',
severity: 'info',
actionLabel: '',
actionLink: '',
action: () => {},
2022-06-23 16:03:35 -07:00
dismissAfter: 6000 as number | false,
});
2022-03-31 16:18:39 -07:00
import type { AnyAction } from 'redux';
type PlainAlert = Record<string, any>;
type Alert = ReturnType<typeof AlertRecord>;
type State = ImmutableList<Alert>;
2022-06-23 14:05:11 -07:00
/** Get next key based on last alert. */
2022-03-31 16:18:39 -07:00
const getNextKey = (state: State): number => {
const last = state.last();
return last ? last.key + 1 : 0;
};
2022-06-23 14:05:11 -07:00
/** Import the alert. */
2022-03-31 16:18:39 -07:00
const importAlert = (state: State, alert: PlainAlert): State => {
const key = getNextKey(state);
const record = AlertRecord({ ...alert, key });
return state.push(record);
};
2022-06-23 14:05:11 -07:00
/** Delete an alert by its key. */
2022-03-31 16:18:39 -07:00
const deleteAlert = (state: State, alert: PlainAlert): State => {
return state.filterNot(item => item.key === alert.key);
};
2020-03-27 13:59:38 -07:00
2022-03-31 16:18:39 -07:00
export default function alerts(state: State = ImmutableList<Alert>(), action: AnyAction): State {
switch (action.type) {
2022-05-11 14:06:35 -07:00
case ALERT_SHOW:
return importAlert(state, action);
case ALERT_DISMISS:
return deleteAlert(state, action.alert);
case ALERT_CLEAR:
return state.clear();
default:
return state;
2020-03-27 13:59:38 -07:00
}
2021-08-03 12:22:51 -07:00
}
export {
Alert,
};