index.tsx 8.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253
  1. /* eslint-disable no-param-reassign */
  2. import React, { CSSProperties } from 'react';
  3. import ReactDOM from 'react-dom';
  4. import PropTypes from 'prop-types';
  5. import ToastListFoundation, {
  6. ToastListAdapter,
  7. ToastListProps,
  8. ToastListState
  9. } from '@douyinfe/semi-foundation/toast/toastListFoundation';
  10. import { cssClasses, strings } from '@douyinfe/semi-foundation/toast/constants';
  11. import BaseComponent from '../_base/baseComponent';
  12. import Toast from './toast';
  13. import '@douyinfe/semi-foundation/toast/toast.scss';
  14. import getUuid from '@douyinfe/semi-foundation/utils/uuid';
  15. import useToast from './useToast';
  16. import { ConfigProps, ToastInstance, ToastProps, ToastState } from '@douyinfe/semi-foundation/toast/toastFoundation';
  17. import CSSAnimation from '../_cssAnimation';
  18. import cls from 'classnames';
  19. export interface ToastReactProps extends ToastProps{
  20. id?: string;
  21. style?: CSSProperties;
  22. icon?: React.ReactNode;
  23. content: React.ReactNode
  24. }
  25. export type {
  26. ConfigProps,
  27. ToastListProps,
  28. ToastListState,
  29. ToastState
  30. };
  31. const createBaseToast = () => class ToastList extends BaseComponent<ToastListProps, ToastListState> {
  32. static ref: ToastList;
  33. static useToast: typeof useToast;
  34. static defaultOpts: ToastReactProps & { motion: boolean } = {
  35. motion: true,
  36. zIndex: 1010,
  37. content: '',
  38. };
  39. static propTypes = {
  40. content: PropTypes.node,
  41. duration: PropTypes.number,
  42. onClose: PropTypes.func,
  43. icon: PropTypes.node,
  44. direction: PropTypes.oneOf(strings.directions),
  45. };
  46. static defaultProps = {};
  47. static wrapperId: null | string;
  48. constructor(props: ToastListProps) {
  49. super(props);
  50. this.state = {
  51. list: [],
  52. removedItems: [],
  53. updatedItems: [],
  54. };
  55. this.foundation = new ToastListFoundation(this.adapter);
  56. }
  57. get adapter(): ToastListAdapter {
  58. return {
  59. ...super.adapter,
  60. updateToast: (list: ToastInstance[], removedItems: ToastInstance[], updatedItems: ToastInstance[]) => {
  61. this.setState({ list, removedItems, updatedItems });
  62. },
  63. };
  64. }
  65. static create(opts: ToastReactProps) {
  66. const id = opts.id ?? getUuid('toast');
  67. // this.id = id;
  68. if (!ToastList.ref) {
  69. const div = document.createElement('div');
  70. if (!this.wrapperId) {
  71. this.wrapperId = getUuid('toast-wrapper').slice(0, 26);
  72. }
  73. div.className = cssClasses.WRAPPER;
  74. div.id = this.wrapperId;
  75. div.style.zIndex = String(typeof opts.zIndex === 'number' ?
  76. opts.zIndex : ToastList.defaultOpts.zIndex);
  77. ['top', 'left', 'bottom', 'right'].map(pos => {
  78. if (pos in ToastList.defaultOpts || pos in opts) {
  79. const val = opts[pos] ? opts[pos] : ToastList.defaultOpts[pos];
  80. div.style[pos] = typeof val === 'number' ? `${val}px` : val;
  81. }
  82. });
  83. // document.body.appendChild(div);
  84. if (ToastList.defaultOpts.getPopupContainer) {
  85. const container = ToastList.defaultOpts.getPopupContainer();
  86. container.appendChild(div);
  87. } else {
  88. document.body.appendChild(div);
  89. }
  90. ReactDOM.render(React.createElement(
  91. ToastList,
  92. { ref: instance => (ToastList.ref = instance) }
  93. ),
  94. div,
  95. () => {
  96. ToastList.ref.add({ ...opts, id });
  97. });
  98. } else {
  99. const node = document.querySelector(`#${this.wrapperId}`) as HTMLElement;
  100. ['top', 'left', 'bottom', 'right'].map(pos => {
  101. if (pos in opts) {
  102. node.style[pos] = typeof opts[pos] === 'number' ? `${opts[pos]}px` : opts[pos];
  103. }
  104. });
  105. if (ToastList.ref.has(id)) {
  106. ToastList.ref.update(id, { ...opts, id });
  107. } else {
  108. ToastList.ref.add({ ...opts, id });
  109. }
  110. }
  111. return id;
  112. }
  113. static close(id: string) {
  114. if (ToastList.ref) {
  115. ToastList.ref.remove(id);
  116. }
  117. }
  118. static destroyAll() {
  119. if (ToastList.ref) {
  120. ToastList.ref.destroyAll();
  121. const wrapper = document.querySelector(`#${this.wrapperId}`);
  122. ReactDOM.unmountComponentAtNode(wrapper);
  123. wrapper && wrapper.parentNode.removeChild(wrapper);
  124. ToastList.ref = null;
  125. this.wrapperId = null;
  126. }
  127. }
  128. static getWrapperId() {
  129. return this.wrapperId;
  130. }
  131. static info(opts: Omit<ToastReactProps, 'type'> | string) {
  132. if (typeof opts === 'string') {
  133. opts = { content: opts };
  134. }
  135. return this.create({ ...ToastList.defaultOpts, ...opts, type: 'info' });
  136. }
  137. static warning(opts: Omit<ToastReactProps, 'type'> | string) {
  138. if (typeof opts === 'string') {
  139. opts = { content: opts };
  140. }
  141. return this.create({ ...ToastList.defaultOpts, ...opts, type: 'warning' });
  142. }
  143. static error(opts: Omit<ToastReactProps, 'type'> | string) {
  144. if (typeof opts === 'string') {
  145. opts = { content: opts };
  146. }
  147. return this.create({ ...ToastList.defaultOpts, ...opts, type: 'error' });
  148. }
  149. static success(opts: Omit<ToastReactProps, 'type'> | string) {
  150. if (typeof opts === 'string') {
  151. opts = { content: opts };
  152. }
  153. return this.create({ ...ToastList.defaultOpts, ...opts, type: 'success' });
  154. }
  155. static config(opts: ConfigProps) {
  156. ['top', 'left', 'bottom', 'right'].forEach(pos => {
  157. if (pos in opts) {
  158. ToastList.defaultOpts[pos] = opts[pos];
  159. }
  160. });
  161. if (typeof opts.zIndex === 'number') {
  162. ToastList.defaultOpts.zIndex = opts.zIndex;
  163. }
  164. if (typeof opts.duration === 'number') {
  165. ToastList.defaultOpts.duration = opts.duration;
  166. }
  167. if (typeof opts.getPopupContainer === 'function') {
  168. ToastList.defaultOpts.getPopupContainer = opts.getPopupContainer;
  169. }
  170. }
  171. has(id: string) {
  172. return this.foundation.hasToast(id);
  173. }
  174. add(opts: ToastInstance) {
  175. return this.foundation.addToast(opts);
  176. }
  177. update(id: string, opts: ToastInstance) {
  178. return this.foundation.updateToast(id, opts);
  179. }
  180. remove(id: string) {
  181. return this.foundation.removeToast(id);
  182. }
  183. destroyAll() {
  184. return this.foundation.destroyAll();
  185. }
  186. render() {
  187. let { list } = this.state;
  188. const { removedItems, updatedItems } = this.state;
  189. list = Array.from(new Set([...list, ...removedItems]));
  190. const updatedIds = updatedItems.map(({ id }) => id);
  191. const refFn: React.LegacyRef<Toast> = (toast) => {
  192. if (toast?.foundation?._id && updatedIds.includes(toast.foundation._id)) {
  193. toast.foundation.setState({ duration: toast.props.duration });
  194. toast.foundation.restartCloseTimer();
  195. }
  196. };
  197. return (
  198. <React.Fragment>
  199. {list.map((item, index) =>{
  200. const isRemoved = removedItems.find(removedItem=>removedItem.id===item.id) !== undefined;
  201. return <CSSAnimation key={item.id} motion={item.motion} animationState={isRemoved?"leave":"enter"} startClassName={isRemoved?`${cssClasses.PREFIX}-animation-hide`:`${cssClasses.PREFIX}-animation-show`}>
  202. {
  203. ({ animationClassName, animationEventsNeedBind, isAnimating })=>{
  204. return (isRemoved && !isAnimating) ? null : <Toast {...item} className={cls({
  205. [item.className]: Boolean(item.className),
  206. [animationClassName]: true
  207. })} {...animationEventsNeedBind} style={{ ...item.style }} close={id => this.remove(id)} ref={refFn} />;
  208. }
  209. }
  210. </CSSAnimation>;
  211. }
  212. )}
  213. </React.Fragment>
  214. );
  215. }
  216. };
  217. export class ToastFactory {
  218. static create(config?: ConfigProps): ReturnType<typeof createBaseToast> {
  219. const newToast = createBaseToast();
  220. newToast.useToast = useToast;
  221. config && newToast.config(config);
  222. return newToast;
  223. }
  224. }
  225. export default ToastFactory.create();