index.tsx 8.9 KB

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