toastFoundation.ts 2.3 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798
  1. import BaseFoundation, { DefaultAdapter } from '../base/foundation';
  2. import { isNumber, noop } from 'lodash';
  3. export type ToastType = 'success' | 'warning' | 'error' | 'info' | 'default';
  4. export type ToastTheme = 'light' | 'normal';
  5. export type Directions = 'ltr' | 'rtl';
  6. export interface ConfigProps {
  7. top?: number | string;
  8. bottom?: number | string;
  9. left?: number | string;
  10. right?: number | string;
  11. duration?: number;
  12. zIndex?: number;
  13. getPopupContainer?: () => HTMLElement | null
  14. }
  15. export interface ToastProps extends ConfigProps {
  16. onClose?: () => void;
  17. content: any;
  18. type?: ToastType;
  19. textMaxWidth?: string | number;
  20. style?: Record<string, any>;
  21. className?: string;
  22. showClose?: boolean;
  23. icon?: any;
  24. theme?: ToastTheme;
  25. direction?: Directions;
  26. close?: (id: string) => void
  27. }
  28. export interface ToastInstance extends ToastProps{
  29. id?: string;
  30. motion?: boolean
  31. }
  32. // eslint-disable-next-line @typescript-eslint/no-empty-interface
  33. export interface ToastState{
  34. }
  35. export interface ToastAdapter extends DefaultAdapter<ToastProps, ToastState>{
  36. notifyWrapperToRemove: (id: string) => void;
  37. notifyClose: () => void
  38. }
  39. export default class ToastFoundation extends BaseFoundation<ToastAdapter> {
  40. _timer: ReturnType<typeof setTimeout> = null;
  41. _id: string | null = null; // cache id
  42. constructor(adapter: ToastAdapter) {
  43. super({ ...ToastFoundation.defaultAdapter, ...adapter });
  44. }
  45. init() {
  46. this.startCloseTimer_();
  47. this._id = this._adapter.getProp('id');
  48. }
  49. destroy() {
  50. this.clearCloseTimer_();
  51. }
  52. startCloseTimer_() {
  53. // unit: s
  54. const duration = this._adapter.getProp('duration');
  55. if (duration && isNumber(duration)) {
  56. this._timer = setTimeout(() => {
  57. this.close(); // call parent to remove itself
  58. }, duration * 1000);
  59. }
  60. }
  61. close(e?: any) {
  62. if (e) {
  63. e.stopPropagation();
  64. }
  65. this._adapter.notifyWrapperToRemove(this._id);
  66. this._adapter.notifyClose();
  67. }
  68. clearCloseTimer_() {
  69. if (this._timer) {
  70. clearTimeout(this._timer);
  71. this._timer = null;
  72. }
  73. }
  74. restartCloseTimer() {
  75. this.clearCloseTimer_();
  76. this.startCloseTimer_();
  77. }
  78. }