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

54 lines
1.3 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: '',
});
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>;
// 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;
};
// 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);
};
// 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
}