notificationFoundation.ts 2.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899
  1. import BaseFoundation, { DefaultAdapter } from '../base/foundation';
  2. import { isNumber } from 'lodash-es';
  3. import { strings } from '../notification/constants';
  4. import { Motion } from '../utils/type';
  5. export type NoticePosition = 'top' | 'bottom' | 'topLeft' | 'topRight' | 'bottomLeft' | 'bottomRight';
  6. export type NoticeType = 'warning' | 'success' | 'info' | 'error' | 'default';
  7. export type NoticeTheme = 'light' | 'normal';
  8. export interface NoticeProps {
  9. duration?: number;
  10. id?: string | number;
  11. title?: any;
  12. content?: any;
  13. position?: NoticePosition;
  14. type?: NoticeType;
  15. onClick?: (e: any) => void;
  16. onClose?: () => void;
  17. onCloseClick?: (id: string | number) => void;
  18. showClose?: boolean;
  19. close?: (id: string | number) => void;
  20. zIndex?: number;
  21. icon?: any;
  22. getPopupContainer?: () => HTMLElement;
  23. theme?: NoticeTheme;
  24. onHookClose?: () => void;
  25. direction?: typeof strings.directions[number];
  26. className?: string;
  27. style?: any;
  28. }
  29. export interface NoticeState{
  30. visible: boolean;
  31. }
  32. export interface NoticeInstance extends NoticeProps{
  33. motion?: Motion;
  34. }
  35. export interface NoticeAdapter extends DefaultAdapter<NoticeProps, NoticeState>{
  36. notifyWrapperToRemove: (id: string) => void;
  37. notifyClose: () => void;
  38. }
  39. export default class NotificationFoundation extends BaseFoundation<NoticeAdapter> {
  40. _timer: ReturnType<typeof setTimeout> | null = null;
  41. _id: string | null = null; // cache id
  42. constructor(adapter: NoticeAdapter) {
  43. super({ ...NotificationFoundation.defaultAdapter, ...adapter });
  44. }
  45. init() {
  46. this._startCloseTimer();
  47. this._id = this.getProp('id');
  48. }
  49. destroy() {
  50. this._clearCloseTimer();
  51. }
  52. _startCloseTimer() {
  53. // unit: s
  54. const duration = this.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. }