All files / Toasts ToastProvider.js

34.24% Statements 25/73
21.21% Branches 7/33
7.69% Functions 2/26
39.06% Lines 25/64

Press n or j to go to the next uncovered block, b, p or k for the previous block.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237              21x       21x 21x   21x                 21x                   97x       97x               97x             97x                                         97x                           97x               97x                                                             141x 141x 141x 141x   141x 141x           141x                                                                                                                                             21x       21x             21x 18x   18x           18x              
import React, { Component, useContext } from 'react';
import { createPortal } from 'react-dom';
import { Transition, TransitionGroup } from 'react-transition-group';
 
import { ToastController } from './ToastController';
import { ToastContainer } from './ToastContainer';
import { DefaultToast } from './ToastElement';
const defaultComponents = { Toast: DefaultToast, ToastContainer };
 
import { generateUEID, NOOP } from './utils';
 
const ToastContext = React.createContext();
const { Consumer, Provider } = ToastContext;
 
const canUseDOM = !!(
    typeof window !== 'undefined' &&
    window.document &&
    window.document.createElement
);
 
// Provider
// ===========================
export class ToastProvider extends Component {
    static defaultProps = {
        autoDismiss: false,
        autoDismissTimeout: 5000,
        components: defaultComponents,
        newestOnTop: false,
        placement: 'top-right',
        transitionDuration: 220,
        containerClasses: '',
    };
 
    state = { toasts: [] };
 
    // Internal Helpers
    // =================
    has = (id) => {
        if (!this.state.toasts.length) {
            return false;
        }
 
        return Boolean(this.state.toasts.filter(t => t.id === id).length);
    };
 
    onDismiss = (id, cb = NOOP) => () => {
        cb(id);
        this.remove(id);
    };
 
    // Public API
    // ================
    add = (title, content, options = {}, cb = NOOP) => {
        const id = options.id ? options.id : generateUEID();
        const callback = () => cb(id);
 
        // Bail if a toast exists with this ID
        if (this.has(id)) {
            return;
        }
 
        // Update the toast stack
        this.setState(state => {
            const newToast = { title, content, id, ...options };
            const toasts = this.props.newestOnTop ? [newToast, ...state.toasts] : [...state.toasts, newToast];
 
            return { toasts };
        }, callback);
 
        // Consumer may want to do something with the generated ID (and not use the callback)
        return id;
    };
 
    remove = (id, cb = NOOP) => {
        const callback = () => cb(id);
 
        // Bail if NO toasts exists with this ID
        if (!this.has(id)) {
            return;
        }
 
        this.setState(state => {
            const toasts = state.toasts.filter(t => t.id !== id);
            return { toasts };
        }, callback);
    };
 
    removeAll = () => {
        if (!this.state.toasts.length) {
            return;
        }
 
        this.state.toasts.forEach(t => this.remove(t.id));
    };
 
    update = (id, options = {}, cb = NOOP) => {
        const callback = () => cb(id);
 
        // Bail if NO toasts exists with ID
        if (!this.has(id)) {
            return;
        }
 
        // Update the toast stack
        this.setState(state => {
            const old = state.toasts;
            const i = old.findIndex(t => t.id === id);
            const updateToast = { ...old[i], ...options };
            const toasts = [...old.slice(0, i), updateToast, ...old.slice(i + 1)];
 
            return { toasts };
        }, callback);
    };
 
    render() {
        const {
            autoDismiss: inheritedAutoDismiss,
            autoDismissTimeout,
            children,
            components,
            placement,
            portalTargetSelector,
            transitionDuration,
            containerClasses,
            theme,
            color,
        } = this.props;
        const { Toast, ToastContainer } = { ...defaultComponents, ...components };
        const { add, remove, removeAll, update } = this;
        const toasts = Object.freeze(this.state.toasts);
 
        const hasToasts = Boolean(toasts.length);
        const portalTarget = canUseDOM
            ? portalTargetSelector
                ? document.querySelector(portalTargetSelector)
                : document.body
            : null;
 
        return (
            <Provider value={{ add, remove, removeAll, update, toasts }}>
                {children}
                {portalTarget ? (
                    createPortal(
                        <ToastContainer className={containerClasses} placement={placement} hasToasts={hasToasts}>
                            <TransitionGroup component={null}>
                                {toasts.map(
                                    ({
                                        appearance,
                                        autoDismiss,
                                        title,
                                        content,
                                        id,
                                        onDismiss,
                                        action,
                                        actionLabel,
                                        secondaryAction,
                                        secondaryActionLabel,
                                        ...unknownConsumerProps
                                    }) => (
                                        <Transition
                                            appear
                                            key={id}
                                            mountOnEnter
                                            timeout={transitionDuration}
                                            unmountOnExit
                                        >
                                            {
                                                transitionState => (
                                                    <ToastController
                                                        appearance={appearance}
                                                        autoDismiss={
                                                            autoDismiss !== undefined
                                                                ? autoDismiss
                                                                : inheritedAutoDismiss
                                                        }
                                                        autoDismissTimeout={autoDismissTimeout}
                                                        component={Toast}
                                                        key={id}
                                                        onDismiss={this.onDismiss(id, onDismiss)}
                                                        placement={placement}
                                                        transitionDuration={transitionDuration}
                                                        transitionState={transitionState}
                                                        title={title}
                                                        content={content}
                                                        action={action}
                                                        actionLabel={actionLabel}
                                                        secondaryAction={secondaryAction}
                                                        secondaryActionLabel={secondaryActionLabel}
                                                        theme={theme}
                                                        color={color}
                                                        {...unknownConsumerProps}
                                                    />
                                                )
                                            }
                                        </Transition>
                                    )
                                )}
                            </TransitionGroup>
                        </ToastContainer>,
                        portalTarget
                    )
                ) : (
                    <ToastContainer placement={placement} hasToasts={hasToasts} />
                )}
            </Provider>
        )
    }
}
 
export const ToastConsumer = ({ children }) => (
    <Consumer>{context => children(context)}</Consumer>
);
 
export const withToastManager = (Comp) =>
    React.forwardRef((props, ref) => (
        <ToastConsumer>
            {context => <Comp toastManager={context} {...props} ref={ref} />}
        </ToastConsumer>
    ));
 
export const useToasts = () => {
    const ctx = useContext(ToastContext);
 
    Iif (!ctx) {
        throw Error(
            'The `useToasts` hook must be called from a descendent of the `ToastProvider`.'
        );
    }
 
    return {
        addToast: ctx.add,
        removeToast: ctx.remove,
        removeAllToasts: ctx.removeAll,
        updateToast: ctx.update,
        toastStack: ctx.toasts
    };
};