toastFoundation.ts 2.4 KB

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