toastFoundation.ts 2.3 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495
  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. export interface ToastState{}
  33. export interface ToastAdapter extends DefaultAdapter<ToastProps, ToastState>{
  34. notifyWrapperToRemove: (id: string) => void;
  35. notifyClose: () => void
  36. }
  37. export default class ToastFoundation extends BaseFoundation<ToastAdapter> {
  38. _timer: ReturnType<typeof setTimeout> = null;
  39. _id: string | null = null; // cache id
  40. constructor(adapter: ToastAdapter) {
  41. super({ ...ToastFoundation.defaultAdapter, ...adapter });
  42. }
  43. init() {
  44. this.startCloseTimer_();
  45. this._id = this._adapter.getProp('id');
  46. }
  47. destroy() {
  48. this.clearCloseTimer_();
  49. }
  50. startCloseTimer_() {
  51. // unit: s
  52. const duration = this._adapter.getProp('duration');
  53. if (duration && isNumber(duration)) {
  54. this._timer = setTimeout(() => {
  55. this.close(); // call parent to remove itself
  56. }, duration * 1000);
  57. }
  58. }
  59. close(e?: any) {
  60. if (e) {
  61. e.stopPropagation();
  62. }
  63. this._adapter.notifyWrapperToRemove(this._id);
  64. this._adapter.notifyClose();
  65. }
  66. clearCloseTimer_() {
  67. if (this._timer) {
  68. clearTimeout(this._timer);
  69. this._timer = null;
  70. }
  71. }
  72. restartCloseTimer() {
  73. this.clearCloseTimer_();
  74. this.startCloseTimer_();
  75. }
  76. }