index.tsx 8.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264
  1. import React, { CSSProperties } from 'react';
  2. import ReactDOM from 'react-dom';
  3. import cls from 'classnames';
  4. import PropTypes from 'prop-types';
  5. import ConfigContext from '../configProvider/context';
  6. import NotificationListFoundation, {
  7. ConfigProps, NotificationListAdapter,
  8. NotificationListProps,
  9. NotificationListState
  10. } from '@douyinfe/semi-foundation/notification/notificationListFoundation';
  11. import { cssClasses, strings } from '@douyinfe/semi-foundation/notification/constants';
  12. import Notice from './notice';
  13. import BaseComponent from '../_base/baseComponent';
  14. import '@douyinfe/semi-foundation/notification/notification.scss';
  15. import NoticeTransition from './NoticeTransition';
  16. import getUuid from '@douyinfe/semi-foundation/utils/uuid';
  17. import useNotification from './useNotification';
  18. import { NoticeInstance, NoticePosition, NoticeProps, NoticeState } from '@douyinfe/semi-foundation/notification/notificationFoundation';
  19. // TODO: Automatic folding + unfolding function when there are more than N
  20. export { NoticeTransitionProps } from './NoticeTransition';
  21. export interface NoticeReactProps extends NoticeProps{
  22. style?: CSSProperties;
  23. }
  24. export {
  25. NoticeState,
  26. NotificationListProps,
  27. NotificationListState
  28. };
  29. export type NoticesInPosition = { top: NoticeInstance[];
  30. topLeft: NoticeInstance[];
  31. topRight: NoticeInstance[];
  32. bottom: NoticeInstance[];
  33. bottomLeft: NoticeInstance[];
  34. bottomRight: NoticeInstance[];
  35. };
  36. let ref: NotificationList = null;
  37. const defaultConfig = {
  38. duration: 3,
  39. position: 'topRight' as NoticePosition,
  40. motion: true,
  41. content: '',
  42. title: '',
  43. zIndex: 1010,
  44. };
  45. class NotificationList extends BaseComponent<NotificationListProps, NotificationListState> {
  46. static contextType = ConfigContext;
  47. static propTypes = {
  48. style: PropTypes.object,
  49. className: PropTypes.string,
  50. direction: PropTypes.oneOf(strings.directions),
  51. };
  52. static defaultProps = {};
  53. static useNotification: typeof useNotification;
  54. private static wrapperId: string;
  55. private noticeStorage: NoticeInstance[];
  56. private removeItemStorage: NoticeInstance[];
  57. constructor(props: NotificationListProps) {
  58. super(props);
  59. this.state = {
  60. notices: [],
  61. removedItems: [],
  62. };
  63. this.noticeStorage = [];
  64. this.removeItemStorage = [];
  65. this.foundation = new NotificationListFoundation(this.adapter);
  66. }
  67. get adapter(): NotificationListAdapter {
  68. return {
  69. ...super.adapter,
  70. updateNotices: (notices: NoticeInstance[], removedItems: NoticeInstance[] = []) => {
  71. this.noticeStorage = [...notices];
  72. this.removeItemStorage = [...removedItems];
  73. // setState is async sometimes and react often merges state, so use "this" , make sure other code always get right data.
  74. this.setState({ notices, removedItems });
  75. },
  76. getNotices: () => this.noticeStorage,
  77. };
  78. }
  79. static addNotice(notice: NoticeProps) {
  80. const id = getUuid('notification');
  81. if (!ref) {
  82. const { getPopupContainer } = notice;
  83. const div = document.createElement('div');
  84. if (!this.wrapperId) {
  85. this.wrapperId = getUuid('notification-wrapper').slice(0, 32);
  86. }
  87. div.className = cssClasses.WRAPPER;
  88. div.id = this.wrapperId;
  89. div.style.zIndex = String(typeof notice.zIndex === 'number' ? notice.zIndex : defaultConfig.zIndex);
  90. if (getPopupContainer) {
  91. const container = getPopupContainer();
  92. container.appendChild(div);
  93. } else {
  94. document.body.appendChild(div);
  95. }
  96. ReactDOM.render(React.createElement(NotificationList, { ref: instance => (ref = instance) }), div, () => {
  97. ref.add({ ...notice, id });
  98. });
  99. } else {
  100. ref.add({ ...notice, id });
  101. }
  102. return id;
  103. }
  104. static removeNotice(id: string) {
  105. if (ref) {
  106. ref.remove(id);
  107. }
  108. return id;
  109. }
  110. static info(opts: NoticeProps) {
  111. return this.addNotice({ ...defaultConfig, ...opts, type: 'info' });
  112. }
  113. static success(opts: NoticeProps) {
  114. return this.addNotice({ ...defaultConfig, ...opts, type: 'success' });
  115. }
  116. static error(opts: NoticeProps) {
  117. return this.addNotice({ ...defaultConfig, ...opts, type: 'error' });
  118. }
  119. static warning(opts: NoticeProps) {
  120. return this.addNotice({ ...defaultConfig, ...opts, type: 'warning' });
  121. }
  122. static open(opts: NoticeProps) {
  123. return this.addNotice({ ...defaultConfig, ...opts, type: 'default' });
  124. }
  125. static close(id: string) {
  126. return this.removeNotice(id);
  127. }
  128. static destroyAll() {
  129. if (ref) {
  130. ref.destroyAll();
  131. const wrapper = document.querySelector(`#${this.wrapperId}`);
  132. ReactDOM.unmountComponentAtNode(wrapper);
  133. wrapper && wrapper.parentNode.removeChild(wrapper);
  134. ref = null;
  135. this.wrapperId = null;
  136. }
  137. }
  138. static config(opts: ConfigProps) {
  139. ['top', 'left', 'bottom', 'right'].map(pos => {
  140. if (pos in opts) {
  141. defaultConfig[pos] = opts[pos];
  142. }
  143. });
  144. if (typeof opts.zIndex === 'number') {
  145. defaultConfig.zIndex = opts.zIndex;
  146. }
  147. if (typeof opts.duration === 'number') {
  148. defaultConfig.duration = opts.duration;
  149. }
  150. if (typeof opts.position === 'string') {
  151. defaultConfig.position = opts.position as NoticePosition;
  152. }
  153. }
  154. add = (noticeOpts: NoticeProps) => this.foundation.addNotice(noticeOpts);
  155. remove = (id: string) => {
  156. this.foundation.removeNotice(id);
  157. };
  158. destroyAll = () => this.foundation.destroyAll();
  159. renderNoticeInPosition = (
  160. notices: NoticeInstance[],
  161. position: NoticePosition,
  162. removedItems: NoticeInstance[] = []
  163. ) => {
  164. const className = cls(cssClasses.LIST);
  165. // TODO notifyOnClose
  166. if (notices.length) {
  167. const style = this.setPosInStyle(notices[0]);
  168. return (
  169. // @ts-ignore
  170. <div placement={position} key={position} className={className} style={style}>
  171. {notices.map((notice, index) =>
  172. (notice.motion ? (
  173. <NoticeTransition key={notice.id || index} position={position} motion={notice.motion}>
  174. {removedItems.find(item => item.id === notice.id) ?
  175. null :
  176. transitionStyle => (
  177. <Notice
  178. {...notice}
  179. style={{ ...transitionStyle, ...notice.style }}
  180. key={notice.id}
  181. close={this.remove}
  182. />
  183. )}
  184. </NoticeTransition>
  185. ) : (
  186. <Notice {...notice} style={{ ...notice.style }} key={notice.id} close={this.remove} />
  187. ))
  188. )}
  189. </div>
  190. );
  191. }
  192. return null;
  193. };
  194. setPosInStyle(noticeInstance: NoticeInstance) {
  195. const style = {};
  196. ['top', 'left', 'bottom', 'right'].forEach(pos => {
  197. if (pos in noticeInstance) {
  198. const val = noticeInstance[pos];
  199. style[pos] = typeof val === 'number' ? `${val}px` : val;
  200. }
  201. });
  202. return style;
  203. }
  204. render() {
  205. let { notices } = this.state;
  206. const { removedItems } = this.state;
  207. notices = Array.from(new Set([...notices, ...removedItems]));
  208. const noticesInPosition: NoticesInPosition = {
  209. top: [],
  210. topLeft: [],
  211. topRight: [],
  212. bottom: [],
  213. bottomLeft: [],
  214. bottomRight: [],
  215. };
  216. notices.forEach(notice => {
  217. const direction = notice.direction || this.context.direction;
  218. const defaultPosition = direction === 'rtl' ? 'topLeft' : 'topRight';
  219. const position = notice.position || defaultPosition;
  220. noticesInPosition[position].push(notice);
  221. });
  222. const noticesList = Object.entries(noticesInPosition).map(obj => {
  223. const pos = obj[0];
  224. const noticesInPos = obj[1];
  225. return this.renderNoticeInPosition(noticesInPos, pos as NoticePosition, removedItems);
  226. });
  227. return <React.Fragment>{noticesList}</React.Fragment>;
  228. }
  229. }
  230. NotificationList.useNotification = useNotification;
  231. export default NotificationList;