UNPKG

@shopgate/pwa-common

Version:

Common library for the Shopgate Connect PWA.

120 lines (116 loc) 3.07 kB
import _createClass from "@babel/runtime/helpers/createClass"; import _inheritsLoose from "@babel/runtime/helpers/inheritsLoose"; import React, { Component } from 'react'; import PropTypes from 'prop-types'; import { UIEvents } from '@shopgate/pwa-core'; import { themeConfig } from '@shopgate/pwa-common/helpers/config'; import ToastContext from "./context"; import { jsx as _jsx } from "react/jsx-runtime"; const { variables: { toast: { duration = 5000 } = {} } = {} } = themeConfig; /** * The ToastProvider component */ let ToastProvider = /*#__PURE__*/function (_Component) { /** * @param {Object} props The component props. */ function ToastProvider(props) { var _this; _this = _Component.call(this, props) || this; /** * Adds a new, unique, toast to the list. * @param {Object} toast The toast object to add. */ _this.addToast = toast => { if (!toast.message) { return; } const { toasts } = _this.state; // Check if the toast id already is present. const found = toasts.find(({ id }) => toast.id === id); // If found, update the toast with the new data. if (found) { found.action = toast.action; found.actionLabel = toast.actionLabel; found.message = toast.message; found.messageParams = toast.messageParams; found.duration = toast.duration || duration; } else { toasts.push({ id: toast.id, action: toast.action, actionLabel: toast.actionLabel, message: toast.message, messageParams: toast.messageParams, duration: toast.duration || duration }); } _this.setState({ toasts }); }; /** * Removes the first toast from the list. */ _this.removeToast = () => { const { toasts } = _this.state; toasts.shift(); _this.setState({ toasts }); }; _this.flushToasts = () => { if (_this.state.toasts.length) { _this.setState({ toasts: [] }); } }; _this.state = { toasts: [] }; UIEvents.addListener(_this.constructor.ADD, _this.addToast); UIEvents.addListener(_this.constructor.FLUSH, _this.flushToasts); return _this; } /** * Returns the context value to be passed to consumers. * @returns {Object} */ _inheritsLoose(ToastProvider, _Component); var _proto = ToastProvider.prototype; /** * @returns {JSX} */ _proto.render = function render() { return /*#__PURE__*/_jsx(ToastContext.Provider, { value: this.provided, children: this.props.children }); }; return _createClass(ToastProvider, [{ key: "provided", get: function () { return { addToast: this.addToast, removeToast: this.removeToast, toasts: this.state.toasts }; } }]); }(Component); ToastProvider.ADD = 'toast_add'; ToastProvider.FLUSH = 'toast_flush'; export default ToastProvider;