index.tsx 9.2 KB

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