@spaced-out/ui-design-system
Version:
Sense UI components library
68 lines (55 loc) • 1.62 kB
Flow
// @flow strict
import type {
callbackFuncTypes,
contentTypes,
ToastOptions,
} from '../../types/toast';
import {uuid} from '../../utils/helpers';
const DEFAULT_AUTOCLOSE_TIME = 8000; // default auto close time for with autoClose = true (be default true) but timeout not passed.
export const POSITIONS = {
TOP_CENTER: 'topCenter',
TOP_LEFT: 'topLeft',
TOP_RIGHT: 'topRight',
BOTTOM_LEFT: 'bottomLeft',
BOTTOM_RIGHT: 'bottomRight',
BOTTOM_CENTER: 'bottomCenter',
};
export const ACTIONS = {
ADD: 'ADD',
REMOVE: 'REMOVE',
};
const defaultOptions: ToastOptions = {
autoClose: true,
timeout: DEFAULT_AUTOCLOSE_TIME,
position: POSITIONS.BOTTOM_LEFT,
};
export const toastManager: {
add(content: contentTypes, options?: ToastOptions): string,
remove(id: string): boolean,
subscribe(callback: callbackFuncTypes): void,
...
} = (() => {
let callbackFn: callbackFuncTypes;
const manager = {
subscribe(callback: callbackFuncTypes): void {
callbackFn = callback;
},
add(content: contentTypes, options?: ToastOptions): string {
const mergedOptions = {...defaultOptions, ...options};
const toastId = uuid();
callbackFn &&
callbackFn(ACTIONS.ADD, content, {...mergedOptions, id: toastId});
return toastId;
},
remove(id: string) {
callbackFn(ACTIONS.REMOVE, null, {id});
return true;
},
};
return manager;
})();
export const toastApi = {
show: (content: contentTypes, options?: ToastOptions): string =>
toastManager.add(content, options),
remove: (id: string): boolean => toastManager.remove(id),
};