UNPKG

16.8 kBJavaScriptView Raw
1"use strict";
2
3Object.defineProperty(exports, "__esModule", {
4 value: true
5});
6exports.default = exports.ToasterContainer = void 0;
7
8var React = _interopRequireWildcard(require("react"));
9
10var _reactDom = _interopRequireDefault(require("react-dom"));
11
12var _overrides = require("../helpers/overrides.js");
13
14var _constants = require("./constants.js");
15
16var _styledComponents = require("./styled-components.js");
17
18var _toast = _interopRequireDefault(require("./toast.js"));
19
20function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
21
22function _getRequireWildcardCache() { if (typeof WeakMap !== "function") return null; var cache = new WeakMap(); _getRequireWildcardCache = function _getRequireWildcardCache() { return cache; }; return cache; }
23
24function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } if (obj === null || _typeof(obj) !== "object" && typeof obj !== "function") { return { default: obj }; } var cache = _getRequireWildcardCache(); if (cache && cache.has(obj)) { return cache.get(obj); } var newObj = {}; var hasPropertyDescriptor = Object.defineProperty && Object.getOwnPropertyDescriptor; for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) { var desc = hasPropertyDescriptor ? Object.getOwnPropertyDescriptor(obj, key) : null; if (desc && (desc.get || desc.set)) { Object.defineProperty(newObj, key, desc); } else { newObj[key] = obj[key]; } } } newObj.default = obj; if (cache) { cache.set(obj, newObj); } return newObj; }
25
26function _typeof(obj) { "@babel/helpers - typeof"; if (typeof Symbol === "function" && typeof Symbol.iterator === "symbol") { _typeof = function _typeof(obj) { return typeof obj; }; } else { _typeof = function _typeof(obj) { return obj && typeof Symbol === "function" && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj; }; } return _typeof(obj); }
27
28function _slicedToArray(arr, i) { return _arrayWithHoles(arr) || _iterableToArrayLimit(arr, i) || _nonIterableRest(); }
29
30function _nonIterableRest() { throw new TypeError("Invalid attempt to destructure non-iterable instance"); }
31
32function _iterableToArrayLimit(arr, i) { if (!(Symbol.iterator in Object(arr) || Object.prototype.toString.call(arr) === "[object Arguments]")) { return; } var _arr = []; var _n = true; var _d = false; var _e = undefined; try { for (var _i = arr[Symbol.iterator](), _s; !(_n = (_s = _i.next()).done); _n = true) { _arr.push(_s.value); if (i && _arr.length === i) break; } } catch (err) { _d = true; _e = err; } finally { try { if (!_n && _i["return"] != null) _i["return"](); } finally { if (_d) throw _e; } } return _arr; }
33
34function _arrayWithHoles(arr) { if (Array.isArray(arr)) return arr; }
35
36function _extends() { _extends = Object.assign || function (target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i]; for (var key in source) { if (Object.prototype.hasOwnProperty.call(source, key)) { target[key] = source[key]; } } } return target; }; return _extends.apply(this, arguments); }
37
38function _objectWithoutProperties(source, excluded) { if (source == null) return {}; var target = _objectWithoutPropertiesLoose(source, excluded); var key, i; if (Object.getOwnPropertySymbols) { var sourceSymbolKeys = Object.getOwnPropertySymbols(source); for (i = 0; i < sourceSymbolKeys.length; i++) { key = sourceSymbolKeys[i]; if (excluded.indexOf(key) >= 0) continue; if (!Object.prototype.propertyIsEnumerable.call(source, key)) continue; target[key] = source[key]; } } return target; }
39
40function _objectWithoutPropertiesLoose(source, excluded) { if (source == null) return {}; var target = {}; var sourceKeys = Object.keys(source); var key, i; for (i = 0; i < sourceKeys.length; i++) { key = sourceKeys[i]; if (excluded.indexOf(key) >= 0) continue; target[key] = source[key]; } return target; }
41
42function _toConsumableArray(arr) { return _arrayWithoutHoles(arr) || _iterableToArray(arr) || _nonIterableSpread(); }
43
44function _nonIterableSpread() { throw new TypeError("Invalid attempt to spread non-iterable instance"); }
45
46function _iterableToArray(iter) { if (Symbol.iterator in Object(iter) || Object.prototype.toString.call(iter) === "[object Arguments]") return Array.from(iter); }
47
48function _arrayWithoutHoles(arr) { if (Array.isArray(arr)) { for (var i = 0, arr2 = new Array(arr.length); i < arr.length; i++) { arr2[i] = arr[i]; } return arr2; } }
49
50function ownKeys(object, enumerableOnly) { var keys = Object.keys(object); if (Object.getOwnPropertySymbols) { var symbols = Object.getOwnPropertySymbols(object); if (enumerableOnly) symbols = symbols.filter(function (sym) { return Object.getOwnPropertyDescriptor(object, sym).enumerable; }); keys.push.apply(keys, symbols); } return keys; }
51
52function _objectSpread(target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i] != null ? arguments[i] : {}; if (i % 2) { ownKeys(Object(source), true).forEach(function (key) { _defineProperty(target, key, source[key]); }); } else if (Object.getOwnPropertyDescriptors) { Object.defineProperties(target, Object.getOwnPropertyDescriptors(source)); } else { ownKeys(Object(source)).forEach(function (key) { Object.defineProperty(target, key, Object.getOwnPropertyDescriptor(source, key)); }); } } return target; }
53
54function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }
55
56function _defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } }
57
58function _createClass(Constructor, protoProps, staticProps) { if (protoProps) _defineProperties(Constructor.prototype, protoProps); if (staticProps) _defineProperties(Constructor, staticProps); return Constructor; }
59
60function _possibleConstructorReturn(self, call) { if (call && (_typeof(call) === "object" || typeof call === "function")) { return call; } return _assertThisInitialized(self); }
61
62function _getPrototypeOf(o) { _getPrototypeOf = Object.setPrototypeOf ? Object.getPrototypeOf : function _getPrototypeOf(o) { return o.__proto__ || Object.getPrototypeOf(o); }; return _getPrototypeOf(o); }
63
64function _assertThisInitialized(self) { if (self === void 0) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return self; }
65
66function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function"); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, writable: true, configurable: true } }); if (superClass) _setPrototypeOf(subClass, superClass); }
67
68function _setPrototypeOf(o, p) { _setPrototypeOf = Object.setPrototypeOf || function _setPrototypeOf(o, p) { o.__proto__ = p; return o; }; return _setPrototypeOf(o, p); }
69
70function _defineProperty(obj, key, value) { if (key in obj) { Object.defineProperty(obj, key, { value: value, enumerable: true, configurable: true, writable: true }); } else { obj[key] = value; } return obj; }
71
72var toasterRef = null;
73
74var ToasterContainer =
75/*#__PURE__*/
76function (_React$Component) {
77 _inherits(ToasterContainer, _React$Component);
78
79 function ToasterContainer(_props) {
80 var _this;
81
82 _classCallCheck(this, ToasterContainer);
83
84 _this = _possibleConstructorReturn(this, _getPrototypeOf(ToasterContainer).call(this, _props));
85
86 _defineProperty(_assertThisInitialized(_this), "state", {
87 isMounted: false,
88 toasts: []
89 });
90
91 _defineProperty(_assertThisInitialized(_this), "dismissHandlers", {});
92
93 _defineProperty(_assertThisInitialized(_this), "toastId", 0);
94
95 _defineProperty(_assertThisInitialized(_this), "getToastProps", function (props) {
96 var _this$props = _this.props,
97 autoFocus = _this$props.autoFocus,
98 autoHideDuration = _this$props.autoHideDuration,
99 closeable = _this$props.closeable;
100 var key = props.key || "toast-".concat(_this.toastId++);
101 return _objectSpread({
102 autoFocus: autoFocus,
103 autoHideDuration: autoHideDuration,
104 closeable: closeable
105 }, props, {
106 key: key
107 });
108 });
109
110 _defineProperty(_assertThisInitialized(_this), "show", function () {
111 var props = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {};
112
113 if (_this.state.toasts.map(function (t) {
114 return t.key;
115 }).includes(props.key)) {
116 _this.update(props.key, props);
117
118 return props.key;
119 }
120
121 var toastProps = _this.getToastProps(props);
122
123 _this.setState(function (_ref) {
124 var toasts = _ref.toasts;
125 return {
126 toasts: [].concat(_toConsumableArray(toasts), [toastProps])
127 };
128 });
129
130 return toastProps.key;
131 });
132
133 _defineProperty(_assertThisInitialized(_this), "update", function (key, props) {
134 _this.setState(function (_ref2) {
135 var toasts = _ref2.toasts;
136 var updatedToasts = toasts.map(function (toast) {
137 if (toast.key === key) {
138 var updatedToastProps = _objectSpread({}, toast, {}, _this.getToastProps(_objectSpread({
139 autoHideDuration: toast.autoHideDuration
140 }, props)), {
141 key: key
142 }, _this.props.resetAutoHideTimerOnUpdate ? {
143 __updated: (parseInt(toast.__updated) || 0) + 1
144 } : {});
145
146 return updatedToastProps;
147 }
148
149 return toast;
150 });
151 return {
152 toasts: updatedToasts
153 };
154 });
155 });
156
157 _defineProperty(_assertThisInitialized(_this), "dismiss", function (key) {
158 if (_this.dismissHandlers[key]) {
159 _this.dismissHandlers[key]();
160 }
161 });
162
163 _defineProperty(_assertThisInitialized(_this), "clearAll", function () {
164 Object.keys(_this.dismissHandlers).forEach(function (key) {
165 _this.dismissHandlers[key]();
166 });
167 });
168
169 _defineProperty(_assertThisInitialized(_this), "clear", function (key) {
170 key === undefined ? _this.clearAll() : _this.dismiss(key);
171 });
172
173 _defineProperty(_assertThisInitialized(_this), "internalOnClose", function (key) {
174 delete _this.dismissHandlers[key];
175
176 _this.setState(function (_ref3) {
177 var toasts = _ref3.toasts;
178 return {
179 toasts: toasts.filter(function (t) {
180 return !(t.key === key);
181 })
182 };
183 });
184 });
185
186 _defineProperty(_assertThisInitialized(_this), "getOnCloseHandler", function (key, onClose) {
187 return function () {
188 _this.internalOnClose(key);
189
190 typeof onClose === 'function' && onClose();
191 };
192 });
193
194 _defineProperty(_assertThisInitialized(_this), "renderToast", function (toastProps) {
195 var onClose = toastProps.onClose,
196 children = toastProps.children,
197 key = toastProps.key,
198 restProps = _objectWithoutProperties(toastProps, ["onClose", "children", "key"]);
199
200 var _this$props$overrides = _this.props.overrides,
201 BodyOverride = _this$props$overrides.ToastBody,
202 CloseIconOverride = _this$props$overrides.ToastCloseIcon,
203 InnerContainerOverride = _this$props$overrides.ToastInnerContainer;
204 var globalToastOverrides = (0, _overrides.mergeOverrides)({
205 Body: _styledComponents.Body,
206 CloseIcon: _styledComponents.CloseIconSvg,
207 InnerContainer: _styledComponents.InnerContainer
208 }, // $FlowFixMe
209 {
210 Body: BodyOverride,
211 CloseIcon: CloseIconOverride,
212 InnerContainer: InnerContainerOverride
213 });
214 var toastOverrides = (0, _overrides.mergeOverrides)(globalToastOverrides, toastProps.overrides);
215 return React.createElement(_toast.default, _extends({}, restProps, {
216 overrides: toastOverrides,
217 key: key,
218 onClose: _this.getOnCloseHandler(key, onClose)
219 }), function (_ref4) {
220 var dismiss = _ref4.dismiss;
221 _this.dismissHandlers[key] = dismiss; // $FlowFixMe
222
223 return children;
224 });
225 });
226
227 _defineProperty(_assertThisInitialized(_this), "getSharedProps", function () {
228 var placement = _this.props.placement;
229 return {
230 $placement: placement
231 };
232 });
233
234 toasterRef = _assertThisInitialized(_this);
235 return _this;
236 }
237
238 _createClass(ToasterContainer, [{
239 key: "componentDidMount",
240 value: function componentDidMount() {
241 this.setState({
242 isMounted: true
243 });
244 }
245 }, {
246 key: "render",
247 value: function render() {
248 var sharedProps = this.getSharedProps();
249 var RootOverride = this.props.overrides.Root;
250
251 var _getOverrides = (0, _overrides.getOverrides)(RootOverride, _styledComponents.Root),
252 _getOverrides2 = _slicedToArray(_getOverrides, 2),
253 Root = _getOverrides2[0],
254 rootProps = _getOverrides2[1];
255
256 var toastsLength = this.state.toasts.length;
257 var toastsToRender = []; // render the toasts from the newest at the start
258 // to the oldest at the end
259 // eslint-disable-next-line for-direction
260
261 for (var _i2 = toastsLength - 1; _i2 >= 0; _i2--) {
262 toastsToRender.push(this.renderToast(this.state.toasts[_i2]));
263 }
264
265 var root = React.createElement(Root, _extends({
266 "data-baseweb": "toaster"
267 }, sharedProps, rootProps), toastsToRender);
268
269 if (this.state.isMounted) {
270 // Only render on the browser (portals aren't supported server-side)
271 if (this.props.usePortal) {
272 if (typeof document !== 'undefined') {
273 return React.createElement(React.Fragment, null, _reactDom.default.createPortal(root, // $FlowFixMe
274 document.body), this.props.children);
275 }
276 } else {
277 return React.createElement(React.Fragment, null, root, this.props.children);
278 }
279 }
280
281 return null;
282 }
283 }]);
284
285 return ToasterContainer;
286}(React.Component);
287
288exports.ToasterContainer = ToasterContainer;
289
290_defineProperty(ToasterContainer, "defaultProps", {
291 autoFocus: false,
292 autoHideDuration: 0,
293 children: null,
294 closeable: true,
295 overrides: {},
296 placement: _constants.PLACEMENT.top,
297 resetAutoHideTimerOnUpdate: true,
298 usePortal: true
299});
300
301var toaster = {
302 getRef: function getRef() {
303 return toasterRef;
304 },
305 show: function show(children) {
306 var props = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {};
307 // toasts can not be added until Toaster is mounted
308 // no SSR for the `toaster.show()`
309 var toasterInstance = this.getRef();
310
311 if (toasterInstance) {
312 return toasterInstance.show(_objectSpread({}, props, {
313 children: children
314 }));
315 } else if (process.env.NODE_ENV !== "production") {
316 throw new Error('Please make sure to add the ToasterContainer to your application before adding toasts! You can find more information here: https://baseweb.design/components/toast');
317 }
318 },
319 info: function info(children) {
320 var props = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {};
321 return this.show(children, _objectSpread({}, props, {
322 kind: _constants.KIND.info
323 }));
324 },
325 positive: function positive(children) {
326 var props = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {};
327 return this.show(children, _objectSpread({}, props, {
328 kind: _constants.KIND.positive
329 }));
330 },
331 warning: function warning(children) {
332 var props = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {};
333 return this.show(children, _objectSpread({}, props, {
334 kind: _constants.KIND.warning
335 }));
336 },
337 negative: function negative(children) {
338 var props = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {};
339 return this.show(children, _objectSpread({}, props, {
340 kind: _constants.KIND.negative
341 }));
342 },
343 update: function update(key, props) {
344 var toasterInstance = this.getRef();
345
346 if (toasterInstance) {
347 toasterInstance.update(key, props);
348 } else if (process.env.NODE_ENV !== "production") {
349 // eslint-disable-next-line no-console
350 console.error('No ToasterContainer is mounted yet.');
351 }
352 },
353 clear: function clear(key) {
354 var toasterInstance = this.getRef();
355
356 if (toasterInstance) {
357 toasterInstance.clear(key);
358 } else if (process.env.NODE_ENV !== "production") {
359 // eslint-disable-next-line no-console
360 console.error('No ToasterContainer is mounted yet.');
361 }
362 }
363};
364var _default = toaster;
365exports.default = _default;
\No newline at end of file