notificationFoundation.ts 2.4 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798
  1. import BaseFoundation, { DefaultAdapter } from '../base/foundation';
  2. import { isNumber } from 'lodash';
  3. import { strings } from '../notification/constants';
  4. export type NoticePosition = 'top' | 'bottom' | 'topLeft' | 'topRight' | 'bottomLeft' | 'bottomRight';
  5. export type NoticeType = 'warning' | 'success' | 'info' | 'error' | 'default';
  6. export type NoticeTheme = 'light' | 'normal';
  7. export interface NoticeProps {
  8. duration?: number;
  9. id?: string | number;
  10. title?: any;
  11. content?: any;
  12. position?: NoticePosition;
  13. type?: NoticeType;
  14. onClick?: (e: any) => void;
  15. onClose?: () => void;
  16. onCloseClick?: (id: string | number) => void;
  17. showClose?: boolean;
  18. close?: (id: string | number) => void;
  19. zIndex?: number;
  20. icon?: any;
  21. getPopupContainer?: () => HTMLElement;
  22. theme?: NoticeTheme;
  23. onHookClose?: () => void;
  24. direction?: typeof strings.directions[number];
  25. className?: string;
  26. style?: any
  27. }
  28. export interface NoticeState{
  29. visible: boolean
  30. }
  31. export interface NoticeInstance extends NoticeProps{
  32. motion?: boolean
  33. }
  34. export interface NoticeAdapter extends DefaultAdapter<NoticeProps, NoticeState>{
  35. notifyWrapperToRemove: (id: string) => void;
  36. notifyClose: () => void
  37. }
  38. export default class NotificationFoundation extends BaseFoundation<NoticeAdapter> {
  39. _timer: ReturnType<typeof setTimeout> | null = null;
  40. _id: string | null = null; // cache id
  41. constructor(adapter: NoticeAdapter) {
  42. super({ ...NotificationFoundation.defaultAdapter, ...adapter });
  43. }
  44. init() {
  45. this._startCloseTimer();
  46. this._id = this.getProp('id');
  47. }
  48. destroy() {
  49. this._clearCloseTimer();
  50. }
  51. _startCloseTimer() {
  52. // unit: s
  53. const duration = this.getProp('duration');
  54. if (duration && isNumber(duration)) {
  55. this._timer = setTimeout(() => {
  56. this.close(); // call parent to remove itself
  57. }, duration * 1000);
  58. }
  59. }
  60. close(e?: any) {
  61. if (e) {
  62. e.stopPropagation();
  63. }
  64. this._adapter.notifyWrapperToRemove(this._id);
  65. this._adapter.notifyClose();
  66. }
  67. _clearCloseTimer() {
  68. if (this._timer) {
  69. clearTimeout(this._timer);
  70. this._timer = null;
  71. }
  72. }
  73. restartCloseTimer() {
  74. this._clearCloseTimer();
  75. this._startCloseTimer();
  76. }
  77. }