@shopgate/pwa-common 7.27.4 → 7.27.5-alpha.2
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
|
@@ -30,7 +30,7 @@ if(nextProps.enablePromiseBasedLoading){_this3.handleLoadingPromise(true,nextPro
|
|
|
30
30
|
* @param {Object} nextProps The next component props.
|
|
31
31
|
* @param {Object} nextState The next component state.
|
|
32
32
|
* @returns {boolean}
|
|
33
|
-
*/},{key:"shouldComponentUpdate",value:function shouldComponentUpdate(nextProps,nextState){return!isEqual(this.props.containerRef,nextProps.containerRef)||!isEqual(this.props.items,nextProps.items)||!isEqual(this.state,nextState);}/**
|
|
33
|
+
*/},{key:"shouldComponentUpdate",value:function shouldComponentUpdate(nextProps,nextState){return!isEqual(this.props.containerRef,nextProps.containerRef)||!isEqual(this.props.columns,nextProps.columns)||!isEqual(this.props.items,nextProps.items)||!isEqual(this.state,nextState);}/**
|
|
34
34
|
* Reset the loading flag.
|
|
35
35
|
*/},{key:"componentDidUpdate",value:function componentDidUpdate(){// When promise based implementation is active, `isLoading` is reset when response comes in.
|
|
36
36
|
// In the legacy implementation this happens after the fetched items reached the component and
|
|
@@ -1,6 +1,13 @@
|
|
|
1
|
-
var _excluded=["maxIndicators","indicators","controls","aria-hidden","disabled","autoPlay","interval","classNames","className","onSlideChange","additionalModules","children","paginationType"];function _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;}function _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);}function _typeof(obj){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);}function _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;}function _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;}import React,{useMemo,useCallback,useEffect,useRef}from'react';import PropTypes from'prop-types';import cls from'classnames';import{A11y,Autoplay,FreeMode,Navigation,Pagination,Zoom}from'swiper/modules';import'swiper/swiper.min.css';import'swiper/modules/a11y.min.css';import'swiper/modules/pagination.min.css';import'swiper/modules/navigation.min.css';import'swiper/modules/zoom.min.css';import{useReduceMotion}from'@shopgate/engage/a11y/hooks';import SwiperItem from"./components/SwiperItem";import OriginalSwiper from"./components/OriginalSwiper";import{container,innerContainer,zoomFix,buttonNext,buttonPrev}from"./styles";/**
|
|
1
|
+
var _excluded=["maxIndicators","indicators","controls","aria-hidden","disabled","autoPlay","interval","classNames","className","onSlideChange","onBreakpoint","additionalModules","loop","children","paginationType"];function _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;}function _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);}function _typeof(obj){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);}function _slicedToArray(arr,i){return _arrayWithHoles(arr)||_iterableToArrayLimit(arr,i)||_nonIterableRest();}function _nonIterableRest(){throw new TypeError("Invalid attempt to destructure non-iterable instance");}function _iterableToArrayLimit(arr,i){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;}function _arrayWithHoles(arr){if(Array.isArray(arr))return arr;}function _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;}function _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;}import React,{useMemo,useCallback,useEffect,useRef,useState}from'react';import PropTypes from'prop-types';import cls from'classnames';import{A11y,Autoplay,FreeMode,Navigation,Pagination,Zoom}from'swiper/modules';import'swiper/swiper.min.css';import'swiper/modules/a11y.min.css';import'swiper/modules/pagination.min.css';import'swiper/modules/navigation.min.css';import'swiper/modules/zoom.min.css';import{useReduceMotion}from'@shopgate/engage/a11y/hooks';import SwiperItem from"./components/SwiperItem";import OriginalSwiper from"./components/OriginalSwiper";import{container,innerContainer,zoomFix,buttonNext,buttonPrev}from"./styles";/**
|
|
2
2
|
* @typedef {import('swiper/react').SwiperProps} SwiperCmpProps
|
|
3
3
|
*/ /**
|
|
4
|
+
* @typedef {import('swiper/react').SwiperClass} SwiperClass
|
|
5
|
+
*/ /**
|
|
6
|
+
* Performs steps that are required when the loop prop of the Swiper is updated.
|
|
7
|
+
* @param {SwiperClass} swiper Swiper instance
|
|
8
|
+
* @param {boolean} loop Whether the loop mode should be enabled or not.
|
|
9
|
+
*/var handleLoopPropUpdate=function handleLoopPropUpdate(swiper,loop){var realIndex=(swiper===null||swiper===void 0?void 0:swiper.realIndex)||0;// eslint-disable-next-line no-param-reassign
|
|
10
|
+
swiper.params.loop=loop;if(loop){swiper.loopDestroy();swiper.loopCreate(realIndex);swiper.updateSlides();}else{swiper.loopDestroy();}};/**
|
|
4
11
|
* The basic Swiper component. It acts as a wrapper for the Swiper JS library component.
|
|
5
12
|
*
|
|
6
13
|
* This component wraps the [Swiper](https://swiperjs.com/) library's main component.
|
|
@@ -8,7 +15,20 @@ var _excluded=["maxIndicators","indicators","controls","aria-hidden","disabled",
|
|
|
8
15
|
*
|
|
9
16
|
* @param {SwiperCmpProps} props The component props.
|
|
10
17
|
* @returns {JSX.Element}
|
|
11
|
-
*/var Swiper=function Swiper(_ref){var maxIndicators=_ref.maxIndicators,indicators=_ref.indicators,controls=_ref.controls,ariaHidden=_ref['aria-hidden'],disabled=_ref.disabled,autoPlay=_ref.autoPlay,interval=_ref.interval,classNames=_ref.classNames,className=_ref.className,onSlideChange=_ref.onSlideChange,additionalModules=_ref.additionalModules,children=_ref.children,paginationTypeProp=_ref.paginationType,swiperProps=_objectWithoutProperties(_ref,_excluded);var useFraction=maxIndicators&&maxIndicators<children.length;var paginationType=useFraction?'fraction':'bullets';var showPagination=indicators&&children.length>1;var hasControls=typeof controls==='boolean'&&controls===true;var reduceMotion=useReduceMotion()
|
|
18
|
+
*/var Swiper=function Swiper(_ref){var _internalProps$autopl,_swiperProps$autoplay;var maxIndicators=_ref.maxIndicators,indicators=_ref.indicators,controls=_ref.controls,ariaHidden=_ref['aria-hidden'],disabled=_ref.disabled,autoPlay=_ref.autoPlay,interval=_ref.interval,classNames=_ref.classNames,className=_ref.className,onSlideChange=_ref.onSlideChange,onBreakpoint=_ref.onBreakpoint,additionalModules=_ref.additionalModules,loopProp=_ref.loop,children=_ref.children,paginationTypeProp=_ref.paginationType,swiperProps=_objectWithoutProperties(_ref,_excluded);var useFraction=maxIndicators&&maxIndicators<children.length;var paginationType=useFraction?'fraction':'bullets';var showPagination=indicators&&children.length>1;var hasControls=typeof controls==='boolean'&&controls===true;var reduceMotion=useReduceMotion();/** @type {React.RefObject<{ swiper: SwiperClass}>} */var swiperRef=useRef(null);var _useState=useState((swiperProps===null||swiperProps===void 0?void 0:swiperProps.slidesPerView)||1),_useState2=_slicedToArray(_useState,2),currentSlidesPerView=_useState2[0],setCurrentSlidesPerView=_useState2[1];var navigation=useMemo(function(){var nav;if(hasControls){nav={// Important to use dot notation (swiper uses it as selector internally)
|
|
12
19
|
nextEl:".swiper-button-next.".concat(buttonNext),prevEl:".swiper-button-prev.".concat(buttonPrev)};}if(_typeof(controls)==='object'){nav=controls;}return nav;},[controls,hasControls]);var handleSlideChange=useCallback(function(swiper){if(typeof onSlideChange==='function'){onSlideChange(swiper.realIndex,swiper);}},[onSlideChange]);/**
|
|
13
20
|
* @type {SwiperCmpProps}
|
|
14
|
-
*/var internalProps=useMemo(function(){return _extends({modules:[A11y,Autoplay,FreeMode,Navigation,Pagination,Zoom].concat(Array.isArray(additionalModules)?additionalModules:[]),className:cls(innerContainer,classNames.container,_defineProperty({},zoomFix,swiperProps===null||swiperProps===void 0?void 0:swiperProps.zoom)),autoplay:autoPlay?{delay:interval}:false,navigation:navigation},showPagination&&{pagination:{el:undefined,type:paginationTypeProp||paginationType,bulletClass:classNames.bulletClass||'swiper-pagination-bullet',bulletActiveClass:classNames.bulletActiveClass||'swiper-pagination-bullet-active',dynamicBullets:true,clickable:true,enabled:indicators&&children.length>1}},{allowSlidePrev:!disabled,allowSlideNext:!disabled,onSlideChange:handleSlideChange});},[additionalModules,classNames.container,classNames.bulletClass,classNames.bulletActiveClass,swiperProps,autoPlay,interval,navigation,showPagination,paginationTypeProp,paginationType,indicators,children.length,disabled,handleSlideChange]);useEffect(function(){var _swiperRef$
|
|
21
|
+
*/var internalProps=useMemo(function(){return _extends({modules:[A11y,Autoplay,FreeMode,Navigation,Pagination,Zoom].concat(Array.isArray(additionalModules)?additionalModules:[]),className:cls(innerContainer,classNames.container,_defineProperty({},zoomFix,swiperProps===null||swiperProps===void 0?void 0:swiperProps.zoom)),autoplay:autoPlay?{delay:interval}:false,navigation:navigation},showPagination&&{pagination:{el:undefined,type:paginationTypeProp||paginationType,bulletClass:classNames.bulletClass||'swiper-pagination-bullet',bulletActiveClass:classNames.bulletActiveClass||'swiper-pagination-bullet-active',dynamicBullets:true,clickable:true,enabled:indicators&&children.length>1}},{allowSlidePrev:!disabled,allowSlideNext:!disabled,onSlideChange:handleSlideChange});},[additionalModules,classNames.container,classNames.bulletClass,classNames.bulletActiveClass,swiperProps,autoPlay,interval,navigation,showPagination,paginationTypeProp,paginationType,indicators,children.length,disabled,handleSlideChange]);useEffect(function(){var _swiperRef$current2,_swiperRef$current2$s;if(!internalProps.autoplay&&!swiperProps.autoplay){var _swiperRef$current,_swiperRef$current$sw;if((_swiperRef$current=swiperRef.current)===null||_swiperRef$current===void 0?void 0:(_swiperRef$current$sw=_swiperRef$current.swiper)===null||_swiperRef$current$sw===void 0?void 0:_swiperRef$current$sw.autoplay){// When autoplay is disabled, ensure that the slider is really stopped. That tackles UI
|
|
22
|
+
// issues when e.g. autoplay and loop mode where disabled during one slide interval.
|
|
23
|
+
swiperRef.current.swiper.autoplay.stop();}return;}if((_swiperRef$current2=swiperRef.current)===null||_swiperRef$current2===void 0?void 0:(_swiperRef$current2$s=_swiperRef$current2.swiper)===null||_swiperRef$current2$s===void 0?void 0:_swiperRef$current2$s.autoplay){if(reduceMotion){swiperRef.current.swiper.autoplay.stop();}else{swiperRef.current.swiper.autoplay.start();}}},[internalProps.autoplay,reduceMotion,swiperProps.autoplay]);// The currently configured delay for autoplay.
|
|
24
|
+
var delay=((_internalProps$autopl=internalProps.autoplay)===null||_internalProps$autopl===void 0?void 0:_internalProps$autopl.delay)||((_swiperProps$autoplay=swiperProps.autoplay)===null||_swiperProps$autoplay===void 0?void 0:_swiperProps$autoplay.delay);// Whether the loop mode should be enabled.
|
|
25
|
+
var shouldLoop=loopProp&&(children===null||children===void 0?void 0:children.length)>currentSlidesPerView+1;useEffect(function(){if(!swiperRef.current)return;// Perform required steps when loop prop changes on runtime.
|
|
26
|
+
handleLoopPropUpdate(swiperRef.current.swiper,shouldLoop);},[shouldLoop]);/**
|
|
27
|
+
* Handles the breakpoint change event.
|
|
28
|
+
* The Swiper has some issues when props are changed on runtime followed by a breakpoint change.
|
|
29
|
+
* This function is supposed to ensure the the Swiper behaves as expected in that case.
|
|
30
|
+
*/var handleOnBreakpoint=useCallback(/**
|
|
31
|
+
* @param {SwiperClass} swiper Swiper instance
|
|
32
|
+
* @param {Object} breakpoint Current breakpoint object
|
|
33
|
+
*/function(swiper,breakpoint){var _swiper$autoplay;var slidesPerView=breakpoint.slidesPerView;if(!slidesPerView){slidesPerView=1;}var wasRunning=(swiper===null||swiper===void 0?void 0:(_swiper$autoplay=swiper.autoplay)===null||_swiper$autoplay===void 0?void 0:_swiper$autoplay.running)||false;if(wasRunning){swiper.autoplay.stop();}var loopUpdate=loopProp&&swiper.slides.length>slidesPerView+1;handleLoopPropUpdate(swiper,loopUpdate);if(typeof delay==='number'&&swiper.params.autoplay){// eslint-disable-next-line no-param-reassign
|
|
34
|
+
swiper.params.autoplay.delay=delay;}if(wasRunning){swiper.autoplay.start();}setCurrentSlidesPerView(slidesPerView);if(typeof onBreakpoint==='function'){onBreakpoint(swiper,breakpoint);}},[delay,loopProp,onBreakpoint]);return React.createElement("div",{className:cls(container,className,'common__swiper'),"aria-hidden":ariaHidden},React.createElement(OriginalSwiper,_extends({"aria-live":"off",a11y:{enabled:false}},internalProps,swiperProps,{loop:shouldLoop,onBreakpoint:handleOnBreakpoint,ref:swiperRef}),children,hasControls&&React.createElement(React.Fragment,null,React.createElement("div",{className:"swiper-button-next ".concat(buttonNext)}),React.createElement("div",{className:"swiper-button-prev ".concat(buttonPrev)}))));};Swiper.Item=SwiperItem;Swiper.defaultProps={'aria-hidden':false,additionalModules:null,autoPlay:false,className:null,classNames:{},controls:false,indicators:false,interval:3000,loop:false,maxIndicators:null,disabled:false,onSlideChange:null,onBreakpoint:null,paginationType:null};export default Swiper;
|
|
@@ -5,7 +5,7 @@ import React from'react';import{mount}from'enzyme';import{ThemeResourcesProvider
|
|
|
5
5
|
* A mock WidgetGrid component.
|
|
6
6
|
* @param {Array} children Array of children.
|
|
7
7
|
* @returns {JSX}
|
|
8
|
-
*/var WidgetGrid=function WidgetGrid(_ref2){var children=_ref2.children;return React.createElement("div",{className:"widget-grid"},children);};/* eslint-enable react/prop-types */var components={'@shopgate/commerce-widgets/image':Image,'@shopgate/commerce-widgets/widget-grid':WidgetGrid};/**
|
|
8
|
+
*/var WidgetGrid=function WidgetGrid(_ref2){var children=_ref2.children;return React.createElement("div",{className:"widget-grid"},children);};/* eslint-enable react/prop-types */var components={v1:{'@shopgate/commerce-widgets/image':Image,'@shopgate/commerce-widgets/widget-grid':WidgetGrid}};/**
|
|
9
9
|
* @param {Object[]} widgets Widgets to be rendered.
|
|
10
10
|
* @returns {JSX.Element}
|
|
11
11
|
*/var createWrapper=function createWrapper(widgets){return mount(React.createElement(ThemeResourcesProvider,{widgets:components,components:{}},React.createElement(Widgets,{widgets:widgets})));};describe('<Widgets />',function(){it('should render a grid if height is defined',function(){var widgets=[{col:0,row:0,width:12,height:3,settings:{id:83535,image:'https://data.shopgate.com/shop_widget_images/23836/92204c0f264ac30d6836994c2fb64eb1.min.jpeg'},type:'@shopgate/commerce-widgets/image'}];var wrapper=createWrapper(widgets);expect(wrapper.find('WidgetGrid').exists()).toBe(true);});it('should not wrap a widget which is not a grid and has no height',function(){var widgets=[{col:0,row:0,width:12,settings:{id:83535,image:'https://data.shopgate.com/shop_widget_images/23836/92204c0f264ac30d6836994c2fb64eb1.min.jpeg'},type:'@shopgate/commerce-widgets/image'}];var wrapper=createWrapper(widgets);expect(wrapper).toMatchSnapshot();expect(wrapper.find('WidgetGrid').exists()).toBe(false);});it('should render a grid if the widget is of type grid',function(){var widgets=[{type:'@shopgate/commerce-widgets/widget-grid',settings:{widgets:[{col:0,row:0,width:12,height:5,settings:{id:'84961',alt:'',image:'https://data.shopgate.com/shop_widget_images/23836/aedc545959f55e3f73851eca0ed40a75.min.jpeg',link:'/category/'},type:'@shopgate/commerce-widgets/image'}]}}];var wrapper=createWrapper(widgets);expect(wrapper).toMatchSnapshot();expect(wrapper.find('WidgetGrid').exists()).toBe(true);});it('should render only one widget when the second one is not published and third one is invalid',function(){var widgets=[{col:0,row:0,width:12,settings:{id:835351,image:'https://data.shopgate.com/shop_widget_images/23836/92204c0f264ac30d6836994c2fb64eb1.min.jpeg'},type:'@shopgate/commerce-widgets/image'},{col:0,row:0,width:12,settings:{id:835352,image:'https://data.shopgate.com/shop_widget_images/23836/92204c0f264ac30d6836994c2fb64eb1.min.jpeg'},type:'@shopgate/commerce-widgets/imagefoo'},{col:0,row:0,width:12,settings:{published:false,id:835353,image:'https://data.shopgate.com/shop_widget_images/23836/92204c0f264ac30d6836994c2fb64eb1.min.jpeg'},type:'@shopgate/commerce-widgets/image'}];var wrapper=createWrapper(widgets);expect(wrapper).toMatchSnapshot();expect(wrapper.find('img').length).toBe(1);});it('should schedule a re-render when widget is scheduled',function(){var minutesToNextFullHour=60-new Date().getMinutes();var msToNextFullHour=minutesToNextFullHour*60000;var scheduledFromMs=Date.now()+msToNextFullHour-1;var scheduledToMs=Date.now()+minutesToNextFullHour+1000;/* eslint-disable camelcase */var widgets=[{col:0,row:0,width:12,settings:{id:835351,image:'https://data.shopgate.com/shop_widget_images/23836/92204c0f264ac30d6836994c2fb64eb1.min.jpeg',published:true,plan:true,planDate:{valid_from:new Date(scheduledFromMs).toISOString(),valid_to:new Date(scheduledToMs).toISOString()}},type:'@shopgate/commerce-widgets/image'}];/* eslint-enable camelcase */var wrapper=createWrapper(widgets);var instance=wrapper.find('Widgets').instance();instance.forceUpdate=jest.fn();expect(wrapper.find(Image).exists()).toBe(false);jest.advanceTimersByTime(msToNextFullHour);expect(instance.forceUpdate).toHaveBeenCalledTimes(1);// In real life next timeout should be in 60 minutes.
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@shopgate/pwa-common",
|
|
3
|
-
"version": "7.27.
|
|
3
|
+
"version": "7.27.5-alpha.2",
|
|
4
4
|
"description": "Common library for the Shopgate Connect PWA.",
|
|
5
5
|
"license": "Apache-2.0",
|
|
6
6
|
"author": "Shopgate <support@shopgate.com>",
|
|
@@ -17,7 +17,7 @@
|
|
|
17
17
|
"dependencies": {
|
|
18
18
|
"@redux-devtools/extension": "^3.3.0",
|
|
19
19
|
"@sentry/browser": "6.0.1",
|
|
20
|
-
"@shopgate/pwa-benchmark": "7.27.
|
|
20
|
+
"@shopgate/pwa-benchmark": "7.27.5-alpha.2",
|
|
21
21
|
"@virtuous/conductor": "~2.5.0",
|
|
22
22
|
"@virtuous/react-conductor": "~2.5.0",
|
|
23
23
|
"@virtuous/redux-persister": "1.1.0-beta.7",
|
|
@@ -43,7 +43,7 @@
|
|
|
43
43
|
"url-search-params": "^0.10.0"
|
|
44
44
|
},
|
|
45
45
|
"devDependencies": {
|
|
46
|
-
"@shopgate/pwa-core": "7.27.
|
|
46
|
+
"@shopgate/pwa-core": "7.27.5-alpha.2",
|
|
47
47
|
"@types/react-portal": "^3.0.9",
|
|
48
48
|
"lodash": "^4.17.4",
|
|
49
49
|
"prop-types": "~15.8.1",
|
package/subscriptions/router.js
CHANGED
|
@@ -1,29 +1,29 @@
|
|
|
1
|
-
import _regeneratorRuntime from"@babel/runtime/regenerator";function _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);}function asyncGeneratorStep(gen,resolve,reject,_next,_throw,key,arg){try{var info=gen[key](arg);var value=info.value;}catch(error){reject(error);return;}if(info.done){resolve(value);}else{Promise.resolve(value).then(_next,_throw);}}function _asyncToGenerator(fn){return function(){var self=this,args=arguments;return new Promise(function(resolve,reject){var gen=fn.apply(self,args);function _next(value){asyncGeneratorStep(gen,resolve,reject,_next,_throw,"next",value);}function _throw(err){asyncGeneratorStep(gen,resolve,reject,_next,_throw,"throw",err);}_next(undefined);});};}import queryString from'query-string';import{router,ACTION_POP,ACTION_PUSH,ACTION_REPLACE,ACTION_RESET}from'@virtuous/conductor';import Route from'@virtuous/conductor/Route';import{HISTORY_RESET_TO}from'@shopgate/pwa-common/constants/ActionTypes';import{logger}from'@shopgate/pwa-core';import{getCurrentRoute,getRouterStackIndex}from"../selectors/router";import{LoadingProvider}from"../providers";import{redirects}from"../collections";import{navigate}from"../action-creators";import{historyRedirect,historyPush,windowOpenOverride}from"../actions/router";import*as handler from"./helpers/handleLinks";import{navigate$,userDidLogin$,appWillStart$,windowOpenOverride$}from"../streams";import{isUserLoggedIn}from"../selectors/user";import{getIsConnected}from"../selectors/client";import{INDEX_PATH}from"../constants/RoutePaths";import appConfig from"../helpers/config";import authRoutes from"../collections/AuthRoutes";import ToastProvider from"../providers/toast";/**
|
|
1
|
+
import _regeneratorRuntime from"@babel/runtime/regenerator";function _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);}function asyncGeneratorStep(gen,resolve,reject,_next,_throw,key,arg){try{var info=gen[key](arg);var value=info.value;}catch(error){reject(error);return;}if(info.done){resolve(value);}else{Promise.resolve(value).then(_next,_throw);}}function _asyncToGenerator(fn){return function(){var self=this,args=arguments;return new Promise(function(resolve,reject){var gen=fn.apply(self,args);function _next(value){asyncGeneratorStep(gen,resolve,reject,_next,_throw,"next",value);}function _throw(err){asyncGeneratorStep(gen,resolve,reject,_next,_throw,"throw",err);}_next(undefined);});};}import queryString from'query-string';import{router,ACTION_POP,ACTION_PUSH,ACTION_REPLACE,ACTION_RESET}from'@virtuous/conductor';import Route from'@virtuous/conductor/Route';import{HISTORY_RESET_TO}from'@shopgate/pwa-common/constants/ActionTypes';import{logger}from'@shopgate/pwa-core';import{IS_PAGE_PREVIEW_ACTIVE}from'@shopgate/engage/page/constants';import{getCurrentRoute,getRouterStackIndex}from"../selectors/router";import{LoadingProvider}from"../providers";import{redirects}from"../collections";import{navigate}from"../action-creators";import{historyRedirect,historyPush,windowOpenOverride}from"../actions/router";import*as handler from"./helpers/handleLinks";import{navigate$,userDidLogin$,appWillStart$,windowOpenOverride$}from"../streams";import{isUserLoggedIn}from"../selectors/user";import{getIsConnected}from"../selectors/client";import{INDEX_PATH}from"../constants/RoutePaths";import appConfig from"../helpers/config";import authRoutes from"../collections/AuthRoutes";import ToastProvider from"../providers/toast";/**
|
|
2
2
|
* Router subscriptions.
|
|
3
3
|
* @param {Function} subscribe The subscribe function.
|
|
4
|
-
*/export default function routerSubscriptions(subscribe){subscribe(navigate$,/*#__PURE__*/function(){var _ref=_asyncToGenerator(/*#__PURE__*/_regeneratorRuntime.mark(function _callee(params){var action,dispatch,getState,events,showConnectivityError,_action$params,silent,steps,resetToPathname,historyAction,routeState,location,state,historyLength,historyEmpty,_ref2,currentPathname,protector,_ref3,redirect,matcher,pathParams,queryParams,_getCurrentRoute2,pathname,pattern,_ref5,transform,route,parsedLocation,parsedRedirect,stringifiedQuery,finalRedirect,parsed,_ref7,_pathname,search;return _regeneratorRuntime.wrap(function _callee$(_context){while(1)switch(_context.prev=_context.next){case 0:action=params.action,dispatch=params.dispatch,getState=params.getState,events=params.events;/**
|
|
4
|
+
*/export default function routerSubscriptions(subscribe){subscribe(navigate$,/*#__PURE__*/function(){var _ref=_asyncToGenerator(/*#__PURE__*/_regeneratorRuntime.mark(function _callee(params){var action,dispatch,getState,events,showConnectivityError,_action$params,silent,steps,resetToPathname,historyAction,routeState,location,state,historyLength,historyEmpty,_ref2,currentPathname,protector,_ref3,redirect,matcher,pathParams,queryParams,_getCurrentRoute2,pathname,pattern,_ref5,transform,route,parsedLocation,parsedRedirect,stringifiedQuery,finalRedirect,parsed,_ref7,_pathname,search;return _regeneratorRuntime.wrap(function _callee$(_context){while(1)switch(_context.prev=_context.next){case 0:if(!IS_PAGE_PREVIEW_ACTIVE){_context.next=2;break;}return _context.abrupt("return");case 2:action=params.action,dispatch=params.dispatch,getState=params.getState,events=params.events;/**
|
|
5
5
|
* Triggers a connectivity error toast message
|
|
6
|
-
*/showConnectivityError=function showConnectivityError(){events.emit(ToastProvider.ADD,{id:'navigate.error',message:'error.general'});};_action$params=action.params,silent=_action$params.silent,steps=_action$params.steps,resetToPathname=_action$params.pathname,historyAction=_action$params.action,routeState=_action$params.state;location=action.params.pathname;state=getState();historyLength=getRouterStackIndex(state)+1;historyEmpty=historyLength===1;_ref2=getCurrentRoute(state)||{},currentPathname=_ref2.pathname;if(!(historyEmpty&&[ACTION_POP,ACTION_RESET,HISTORY_RESET_TO].includes(historyAction))){_context.next=
|
|
6
|
+
*/showConnectivityError=function showConnectivityError(){events.emit(ToastProvider.ADD,{id:'navigate.error',message:'error.general'});};_action$params=action.params,silent=_action$params.silent,steps=_action$params.steps,resetToPathname=_action$params.pathname,historyAction=_action$params.action,routeState=_action$params.state;location=action.params.pathname;state=getState();historyLength=getRouterStackIndex(state)+1;historyEmpty=historyLength===1;_ref2=getCurrentRoute(state)||{},currentPathname=_ref2.pathname;if(!(historyEmpty&&[ACTION_POP,ACTION_RESET,HISTORY_RESET_TO].includes(historyAction))){_context.next=15;break;}if(!(currentPathname&¤tPathname===INDEX_PATH)){_context.next=13;break;}return _context.abrupt("return");case 13:/**
|
|
7
7
|
* Replace the current route with the index, when a history action is supposed to be
|
|
8
8
|
* dispatched which reduces the router stack, but the route which triggered the action
|
|
9
9
|
* is the only one within the stack.
|
|
10
|
-
*/router.replace({pathname:INDEX_PATH});return _context.abrupt("return");case
|
|
10
|
+
*/router.replace({pathname:INDEX_PATH});return _context.abrupt("return");case 15:_context.t0=historyAction;_context.next=_context.t0===ACTION_POP?18:_context.t0===ACTION_RESET?20:_context.t0===HISTORY_RESET_TO?22:27;break;case 18:router.pop(_extends({},typeof steps==='number'&&{steps:steps}));return _context.abrupt("return");case 20:/**
|
|
11
11
|
* We don't use the native reset function here, since it contains a bug that causes
|
|
12
12
|
* a history pop right after the reset. That can cause side effects when the previous
|
|
13
13
|
* route briefly renders - same for HISTORY_RESET_TO
|
|
14
|
-
*/router.pop({steps:steps||historyLength-1});return _context.abrupt("return");case
|
|
14
|
+
*/router.pop({steps:steps||historyLength-1});return _context.abrupt("return");case 22:_context.next=24;return router.pop({steps:historyLength-1,state:routeState,emitBefore:false,emitAfter:false});case 24:_context.next=26;return router.replace({pathname:resetToPathname,state:routeState});case 26:return _context.abrupt("return");case 27:return _context.abrupt("break",28);case 28:// Remove trailing slashes from internal links, since they might break the routing mechanism.
|
|
15
15
|
// External links are treated as valid, since we don't know about the requirements at the
|
|
16
16
|
// 3rd party server (e.g. google maps links might require trailing slashes).
|
|
17
17
|
if(location&&!handler.isExternalLink(location)){location=handler.sanitizeLink(location);}// Stop further processing if the location is empty.
|
|
18
|
-
if(location){_context.next=
|
|
18
|
+
if(location){_context.next=31;break;}return _context.abrupt("return");case 31:if(!(historyAction===ACTION_PUSH&&location===currentPathname)){_context.next=33;break;}return _context.abrupt("return");case 33:if(getIsConnected(state)){_context.next=36;break;}showConnectivityError();return _context.abrupt("return");case 36:if(isUserLoggedIn(state)){_context.next=41;break;}// Determine whether or not this location is protected.
|
|
19
19
|
protector=authRoutes.getProtector(location);// If protected then navigate to the protector instead.
|
|
20
|
-
if(!protector){_context.next=
|
|
21
|
-
_ref3=redirects.getRedirectExtended(location)||{},redirect=_ref3.handler,matcher=_ref3.matcher,pathParams=_ref3.pathParams,queryParams=_ref3.queryParams;/* eslint-enable prefer-const */if(!redirect){_context.next=
|
|
22
|
-
pathname:location}),route:route,redirectMeta:{location:location,matcher:matcher,pathParams:pathParams,queryParams:queryParams}})}));case
|
|
23
|
-
parsedLocation=queryString.parseUrl(location);parsedRedirect=queryString.parseUrl(redirect);stringifiedQuery=queryString.stringify(_extends({},parsedLocation.query,{},parsedRedirect.query));finalRedirect=stringifiedQuery?"".concat(parsedRedirect.url,"?").concat(stringifiedQuery):parsedRedirect.url;location=finalRedirect;case
|
|
24
|
-
showConnectivityError();return _context.abrupt("return");case
|
|
20
|
+
if(!protector){_context.next=41;break;}dispatch(navigate({action:historyAction,pathname:protector,state:{redirect:{location:location,state:routeState}}}));return _context.abrupt("return");case 41:/* eslint-disable prefer-const */ // Check for a redirect and change location if one is found.
|
|
21
|
+
_ref3=redirects.getRedirectExtended(location)||{},redirect=_ref3.handler,matcher=_ref3.matcher,pathParams=_ref3.pathParams,queryParams=_ref3.queryParams;/* eslint-enable prefer-const */if(!redirect){_context.next=67;break;}if(!(typeof redirect==='function'||redirect instanceof Promise)){_context.next=62;break;}_getCurrentRoute2=getCurrentRoute(state),pathname=_getCurrentRoute2.pathname;LoadingProvider.setLoading(pathname);pattern=router.findPattern(location.split('?')[0]);_ref5=router.patterns[pattern]||{},transform=_ref5.transform;route=new Route({pathname:location,pattern:pattern,routeState:routeState,transform:transform});_context.prev=49;_context.next=52;return redirect(_extends({},params,{action:_extends({},params.action,{params:_extends({},params.action.params,{// Merge the sanitized location into the redirect handler payload.
|
|
22
|
+
pathname:location}),route:route,redirectMeta:{location:location,matcher:matcher,pathParams:pathParams,queryParams:queryParams}})}));case 52:redirect=_context.sent;_context.next=59;break;case 55:_context.prev=55;_context.t1=_context["catch"](49);redirect=null;logger.error(_context.t1);case 59:LoadingProvider.unsetLoading(pathname);if(redirect){_context.next=62;break;}return _context.abrupt("return");case 62:// Add query parameters from the original location to the redirect
|
|
23
|
+
parsedLocation=queryString.parseUrl(location);parsedRedirect=queryString.parseUrl(redirect);stringifiedQuery=queryString.stringify(_extends({},parsedLocation.query,{},parsedRedirect.query));finalRedirect=stringifiedQuery?"".concat(parsedRedirect.url,"?").concat(stringifiedQuery):parsedRedirect.url;location=finalRedirect;case 67:parsed=queryString.parseUrl(location);if(parsed.url){_context.next=71;break;}// The URL is not valid - show a toast message
|
|
24
|
+
showConnectivityError();return _context.abrupt("return");case 71:// Override the location if is Shop link is found.
|
|
25
25
|
if(handler.isShopLink(location)){_ref7=new URL(location),_pathname=_ref7.pathname,search=_ref7.search;location="".concat(_pathname).concat(search);}// If there is one of the known protocols in the url.
|
|
26
|
-
if(!(location&&handler.hasKnownProtocols(location))){_context.next=
|
|
26
|
+
if(!(location&&handler.hasKnownProtocols(location))){_context.next=75;break;}if(handler.isExternalLink(location)){handler.openExternalLink(location,historyAction,state,routeState);}else if(handler.isNativeLink(location)){handler.openNativeLink(location);}return _context.abrupt("return");case 75:if(!(location&&handler.isLegacyPage(location))){_context.next=78;break;}handler.openLegacy(location,historyAction,state);return _context.abrupt("return");case 78:if(!(location&&handler.isLegacyLink(location))){_context.next=81;break;}handler.openLegacyLink(location,historyAction,state);return _context.abrupt("return");case 81:_context.t2=historyAction;_context.next=_context.t2===ACTION_PUSH?84:_context.t2===ACTION_REPLACE?86:88;break;case 84:router.push({pathname:location,state:routeState,emitBefore:silent,emitAfter:silent});return _context.abrupt("break",89);case 86:router.replace({pathname:location,state:routeState,emitBefore:silent,emitAfter:silent});return _context.abrupt("break",89);case 88:return _context.abrupt("break",89);case 89:case"end":return _context.stop();}},_callee,null,[[49,55]]);}));return function(_x){return _ref.apply(this,arguments);};}());/**
|
|
27
27
|
* Added a 100ms delay here to allow the Redux action to complete.
|
|
28
28
|
* Without it the store would show that the user is still not
|
|
29
29
|
* logged in during the upcoming navigate() action.
|