Hangar/frontend/store/snackbar.ts

56 lines
1.6 KiB
TypeScript
Raw Normal View History

2021-02-06 03:50:18 +08:00
import { ActionTree, MutationTree } from 'vuex';
2021-03-20 09:19:51 +08:00
import { TranslateResult } from 'vue-i18n';
2021-02-06 03:50:18 +08:00
import { RootState } from '~/store/index';
export const state = () => ({
enabled: false,
color: null as string | null,
2021-03-20 09:19:51 +08:00
messages: [] as TranslateResult[],
2021-02-06 03:50:18 +08:00
timeout: 3000 as number,
});
export type SnackbarState = ReturnType<typeof state>;
2021-02-09 02:26:18 +08:00
export interface NotifPayload {
2021-02-06 03:50:18 +08:00
color?: string;
timeout?: number;
2021-03-20 09:19:51 +08:00
message: TranslateResult;
2021-02-06 03:50:18 +08:00
}
function timeout(ms: number) {
return new Promise((resolve) => setTimeout(resolve, ms));
}
export const actions: ActionTree<SnackbarState, RootState> = {
2021-02-09 02:26:18 +08:00
SHOW_NOTIF: async ({ commit, state }, payload: NotifPayload) => {
2021-02-06 03:50:18 +08:00
commit('SET_COLOR', payload.color);
commit('ADD_MESSAGE', payload.message);
if (!state.enabled) {
commit('SET_TIMEOUT', payload.timeout);
} else {
commit('SET_TIMEOUT', state.timeout + (payload.timeout || 3000));
}
commit('SHOW_SNACKBAR', true);
await timeout(payload.timeout || 3000);
},
};
export const mutations: MutationTree<SnackbarState> = {
SET_COLOR: (state: SnackbarState, color: string | null) => {
state.color = color || 'error';
},
SET_TIMEOUT: (state: SnackbarState, timeout: number | null) => {
state.timeout = timeout || 3000;
},
2021-03-20 09:19:51 +08:00
ADD_MESSAGE: (state: SnackbarState, message: TranslateResult) => {
2021-02-06 03:50:18 +08:00
state.messages.push(message);
},
SHOW_SNACKBAR: (state: SnackbarState, show: boolean) => {
state.enabled = show;
},
CLEAR_MESSAGES: (state: SnackbarState) => {
state.messages = [];
state.timeout = 1000;
},
};