@shopgate/pwa-common 7.30.0-alpha.6 → 7.30.0-alpha.8

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.
Files changed (306) hide show
  1. package/App.js +48 -6
  2. package/action-creators/app/index.js +75 -12
  3. package/action-creators/app/spec.js +96 -1
  4. package/action-creators/client/index.js +27 -5
  5. package/action-creators/client/spec.js +44 -1
  6. package/action-creators/error/index.js +15 -3
  7. package/action-creators/index.js +9 -1
  8. package/action-creators/menu/index.js +23 -4
  9. package/action-creators/menu/spec.js +37 -1
  10. package/action-creators/modal/index.js +15 -3
  11. package/action-creators/modal/spec.js +26 -1
  12. package/action-creators/page/index.js +24 -4
  13. package/action-creators/page/spec.js +38 -1
  14. package/action-creators/router/index.js +48 -7
  15. package/action-creators/url/index.js +24 -4
  16. package/action-creators/url/spec.js +45 -1
  17. package/action-creators/user/index.js +90 -13
  18. package/action-creators/user/spec.js +186 -2
  19. package/actions/app/handleDeepLink.js +11 -2
  20. package/actions/app/handleLink.js +62 -6
  21. package/actions/app/handlePushNotification.js +32 -4
  22. package/actions/app/handleUniversalLink.js +11 -2
  23. package/actions/app/registerLinkEvents.js +24 -3
  24. package/actions/client/fetchClientInformation.js +26 -2
  25. package/actions/menu/fetchMenu.js +23 -2
  26. package/actions/modal/closeModal.js +18 -2
  27. package/actions/modal/promiseMap.js +3 -1
  28. package/actions/modal/showModal.js +54 -8
  29. package/actions/page/fetchPageConfig.js +69 -2
  30. package/actions/page/getPageConfig.js +6 -2
  31. package/actions/page/index.js +1 -1
  32. package/actions/router/historyPop.js +12 -2
  33. package/actions/router/historyPopToRoute.js +27 -2
  34. package/actions/router/historyPush.js +12 -2
  35. package/actions/router/historyRedirect.js +21 -2
  36. package/actions/router/historyReplace.js +20 -3
  37. package/actions/router/historyReset.js +11 -2
  38. package/actions/router/historyResetTo.js +12 -2
  39. package/actions/router/index.js +17 -1
  40. package/actions/router/routeDidPop.js +11 -2
  41. package/actions/router/routeDidPush.js +13 -2
  42. package/actions/router/routeDidReplace.js +11 -2
  43. package/actions/router/routeDidReset.js +11 -2
  44. package/actions/router/routeDidUpdate.js +10 -2
  45. package/actions/router/routeWillPop.js +11 -2
  46. package/actions/router/routeWillPush.js +13 -2
  47. package/actions/router/routeWillReplace.js +11 -2
  48. package/actions/router/routeWillReset.js +11 -2
  49. package/actions/router/windowOpenOverride.js +10 -2
  50. package/actions/user/fetchRegisterUrl.js +36 -2
  51. package/actions/user/fetchUser.js +29 -3
  52. package/actions/user/getUser.js +6 -2
  53. package/actions/user/index.js +1 -1
  54. package/actions/user/login.js +76 -9
  55. package/actions/user/logout.js +30 -2
  56. package/collections/AuthRoutes.js +73 -14
  57. package/collections/Configuration.js +54 -7
  58. package/collections/EmbeddedMedia.js +84 -11
  59. package/collections/PersistedReducers.js +41 -6
  60. package/collections/Redirects.js +103 -17
  61. package/collections/index.js +5 -1
  62. package/collections/media-providers/MediaProvider.js +151 -26
  63. package/collections/media-providers/Vimeo.js +113 -19
  64. package/collections/media-providers/YouTube.js +74 -14
  65. package/collections/media-providers/index.js +3 -1
  66. package/collections/media-providers/style.js +52 -2
  67. package/components/Backdrop/index.js +95 -6
  68. package/components/Backdrop/spec.js +23 -1
  69. package/components/Backdrop/style.js +11 -2
  70. package/components/Button/index.js +47 -5
  71. package/components/Button/spec.js +36 -1
  72. package/components/Button/style.js +6 -1
  73. package/components/Checkbox/index.js +126 -32
  74. package/components/Checkbox/spec.js +94 -3
  75. package/components/Consume/helpers/buildParams.js +13 -2
  76. package/components/Consume/index.js +14 -2
  77. package/components/CountdownTimer/index.js +115 -17
  78. package/components/CountdownTimer/spec.js +126 -12
  79. package/components/Drawer/index.js +131 -16
  80. package/components/Drawer/spec.js +76 -1
  81. package/components/Drawer/style.js +37 -1
  82. package/components/Dropdown/index.js +65 -6
  83. package/components/Dropdown/style.js +4 -1
  84. package/components/Dropdown/transitions.js +34 -1
  85. package/components/Ellipsis/index.js +16 -2
  86. package/components/Ellipsis/spec.js +13 -1
  87. package/components/EmbeddedMedia/index.js +56 -6
  88. package/components/EmbeddedMedia/spec.js +52 -3
  89. package/components/ErrorBoundary/connector.js +9 -2
  90. package/components/ErrorBoundary/index.js +43 -7
  91. package/components/Grid/components/Item/index.js +40 -4
  92. package/components/Grid/components/Item/spec.js +23 -1
  93. package/components/Grid/components/Item/style.js +17 -3
  94. package/components/Grid/index.js +36 -4
  95. package/components/Grid/spec.js +23 -1
  96. package/components/Grid/style.js +11 -2
  97. package/components/HtmlSanitizer/connector.js +24 -3
  98. package/components/HtmlSanitizer/index.js +104 -12
  99. package/components/HtmlSanitizer/spec.js +207 -6
  100. package/components/I18n/components/FormatDate/index.js +26 -2
  101. package/components/I18n/components/FormatDate/spec.js +46 -1
  102. package/components/I18n/components/FormatNumber/index.js +34 -2
  103. package/components/I18n/components/FormatNumber/spec.js +41 -2
  104. package/components/I18n/components/FormatPrice/index.js +32 -2
  105. package/components/I18n/components/FormatPrice/spec.js +46 -1
  106. package/components/I18n/components/FormatTime/index.js +26 -2
  107. package/components/I18n/components/FormatTime/spec.js +43 -2
  108. package/components/I18n/components/I18nProvider/index.js +52 -9
  109. package/components/I18n/components/I18nProvider/spec.js +39 -1
  110. package/components/I18n/components/Placeholder/index.js +8 -2
  111. package/components/I18n/components/Placeholder/spec.js +30 -1
  112. package/components/I18n/components/Translate/index.js +68 -7
  113. package/components/I18n/components/Translate/spec.js +30 -1
  114. package/components/I18n/index.js +16 -1
  115. package/components/Icon/index.js +25 -2
  116. package/components/Icon/style.js +6 -1
  117. package/components/Image/Image.js +176 -19
  118. package/components/Image/ImageInner.js +48 -2
  119. package/components/Image/index.js +1 -1
  120. package/components/Image/style.js +29 -2
  121. package/components/InfiniteContainer/index.js +381 -49
  122. package/components/InfiniteContainer/spec.js +199 -10
  123. package/components/Input/components/DateInput.js +262 -6
  124. package/components/Input/components/MultiLineInput.js +98 -12
  125. package/components/Input/components/SimpleInput.js +207 -31
  126. package/components/Input/index.js +32 -3
  127. package/components/Input/spec.js +122 -1
  128. package/components/KeyboardConsumer/index.js +48 -7
  129. package/components/Link/connector.js +7 -1
  130. package/components/Link/index.js +96 -11
  131. package/components/Link/spec.js +56 -1
  132. package/components/Link/style.js +10 -1
  133. package/components/List/components/Item/index.js +35 -3
  134. package/components/List/components/Item/style.js +16 -1
  135. package/components/List/index.js +20 -2
  136. package/components/List/spec.js +31 -1
  137. package/components/Loading/index.js +6 -2
  138. package/components/Modal/index.js +38 -3
  139. package/components/Modal/style.js +36 -1
  140. package/components/ModalContainer/connector.js +17 -3
  141. package/components/ModalContainer/index.js +36 -3
  142. package/components/ModalContainer/spec.js +105 -5
  143. package/components/Picker/components/Button/index.js +34 -2
  144. package/components/Picker/components/Button/style.js +19 -1
  145. package/components/Picker/components/List/index.js +33 -2
  146. package/components/Picker/components/List/style.js +17 -1
  147. package/components/Picker/components/Modal/index.js +60 -7
  148. package/components/Picker/components/Modal/style.js +78 -1
  149. package/components/Picker/index.js +167 -21
  150. package/components/Picker/spec.js +83 -2
  151. package/components/Portal/index.js +130 -19
  152. package/components/ProductCharacteristics/connector.js +33 -4
  153. package/components/ProductCharacteristics/context.js +2 -1
  154. package/components/ProductCharacteristics/helpers/index.js +135 -21
  155. package/components/ProductCharacteristics/index.js +266 -31
  156. package/components/RangeSlider/components/Handle/index.js +25 -2
  157. package/components/RangeSlider/components/Handle/style.js +14 -1
  158. package/components/RangeSlider/helper.js +43 -8
  159. package/components/RangeSlider/index.js +228 -38
  160. package/components/RangeSlider/style.js +14 -1
  161. package/components/Route/RouteNotFound.js +46 -3
  162. package/components/Route/index.js +78 -10
  163. package/components/Router/connector.js +9 -2
  164. package/components/Router/index.js +237 -31
  165. package/components/ScannerContainer/connector.js +9 -2
  166. package/components/ScannerContainer/index.js +42 -6
  167. package/components/Select/components/Item/index.js +20 -4
  168. package/components/Select/components/Item/style.js +4 -1
  169. package/components/Select/index.js +149 -28
  170. package/components/Select/spec.js +86 -2
  171. package/components/Select/style.js +17 -1
  172. package/components/SelectBox/components/Item/index.js +47 -5
  173. package/components/SelectBox/components/Item/style.js +7 -1
  174. package/components/SelectBox/index.js +173 -17
  175. package/components/SelectBox/spec.js +59 -3
  176. package/components/SelectBox/style.js +18 -1
  177. package/components/Slider/index.js +6 -2
  178. package/components/SurroundPortals/index.js +26 -2
  179. package/components/Swiper/components/SwiperItem/index.js +28 -4
  180. package/components/Swiper/components/SwiperItem/spec.js +17 -1
  181. package/components/Swiper/components/SwiperItem/styles.js +5 -1
  182. package/components/Swiper/index.js +210 -18
  183. package/components/Swiper/styles.js +75 -7
  184. package/components/Toaster/index.js +10 -2
  185. package/components/Transition/index.js +89 -13
  186. package/components/Widgets/components/Widget/index.js +52 -4
  187. package/components/Widgets/components/Widget/spec.js +68 -3
  188. package/components/Widgets/components/Widget/style.js +21 -3
  189. package/components/Widgets/components/WidgetGrid/index.js +52 -7
  190. package/components/Widgets/components/WidgetGrid/spec.js +46 -2
  191. package/components/Widgets/components/WidgetGrid/style.js +8 -1
  192. package/components/Widgets/helpers/shouldShowWidget.js +44 -7
  193. package/components/Widgets/index.js +127 -15
  194. package/components/Widgets/spec.js +213 -6
  195. package/components/index.js +9 -1
  196. package/constants/ActionTypes.js +97 -19
  197. package/constants/Configuration.js +12 -2
  198. package/constants/Device.js +29 -2
  199. package/constants/DisplayOptions.js +8 -1
  200. package/constants/MenuIDs.js +2 -1
  201. package/constants/ModalTypes.js +1 -1
  202. package/constants/PageIDs.js +1 -1
  203. package/constants/Pipelines.js +7 -1
  204. package/constants/Portals.js +136 -3
  205. package/constants/Registration.js +3 -1
  206. package/constants/RoutePaths.js +13 -2
  207. package/constants/Tracking.js +3 -1
  208. package/constants/client.js +6 -1
  209. package/constants/ui.js +2 -1
  210. package/constants/user.js +6 -2
  211. package/context/index.js +33 -3
  212. package/helpers/config/index.js +139 -21
  213. package/helpers/config/mock.js +200 -8
  214. package/helpers/config/theme.js +50 -4
  215. package/helpers/data/index.js +204 -29
  216. package/helpers/data/spec.js +187 -7
  217. package/helpers/date/index.js +58 -6
  218. package/helpers/date/spec.js +92 -1
  219. package/helpers/dom/index.js +48 -11
  220. package/helpers/environment/index.js +14 -2
  221. package/helpers/html/decodeHTML.js +7 -1
  222. package/helpers/html/handleDOM.js +172 -21
  223. package/helpers/html/parseHTML.js +67 -12
  224. package/helpers/i18n/getDateFormatter.js +23 -4
  225. package/helpers/i18n/getNumberFormatter.js +32 -4
  226. package/helpers/i18n/getPriceFormatter.js +38 -4
  227. package/helpers/i18n/getTimeFormatter.js +23 -4
  228. package/helpers/i18n/getTranslator.js +62 -8
  229. package/helpers/i18n/index.js +5 -1
  230. package/helpers/i18n/mergeTranslations.js +36 -9
  231. package/helpers/i18n/messageCache.js +3 -1
  232. package/helpers/legacy/index.js +47 -9
  233. package/helpers/modal/withShowModal.js +13 -2
  234. package/helpers/portals/portalCollection.js +28 -6
  235. package/helpers/portals/routePortals.js +12 -1
  236. package/helpers/redux/compareObjects.js +7 -2
  237. package/helpers/redux/generateResultHash.js +36 -3
  238. package/helpers/redux/generateSortedHash.js +7 -2
  239. package/helpers/redux/hasExpired.js +10 -2
  240. package/helpers/redux/index.js +7 -1
  241. package/helpers/redux/mutable.js +143 -24
  242. package/helpers/redux/shouldFetchData.js +46 -10
  243. package/helpers/redux/shouldFetchFilters.js +17 -4
  244. package/helpers/router/index.js +49 -5
  245. package/helpers/style/index.js +43 -4
  246. package/helpers/style/spec.js +108 -2
  247. package/helpers/tracking/index.js +52 -9
  248. package/helpers/validation/index.js +39 -12
  249. package/helpers/validation/spec.js +10 -1
  250. package/package.json +3 -3
  251. package/providers/index.js +4 -1
  252. package/providers/loading/context.js +2 -1
  253. package/providers/loading/index.js +137 -22
  254. package/providers/toast/context.js +2 -1
  255. package/providers/toast/index.js +105 -11
  256. package/reducers/client/connectivity.js +22 -2
  257. package/reducers/client/index.js +7 -1
  258. package/reducers/client/info.js +27 -2
  259. package/reducers/index.js +23 -4
  260. package/reducers/menu/index.js +5 -1
  261. package/reducers/menu/menusById.js +41 -2
  262. package/reducers/modal/index.js +14 -2
  263. package/reducers/page/index.js +68 -5
  264. package/reducers/router/index.js +48 -2
  265. package/reducers/url/index.js +42 -3
  266. package/reducers/user/data.js +27 -2
  267. package/reducers/user/index.js +7 -1
  268. package/reducers/user/login.js +65 -2
  269. package/selectors/client.js +138 -21
  270. package/selectors/history.js +49 -11
  271. package/selectors/menu.js +34 -6
  272. package/selectors/modal.js +15 -4
  273. package/selectors/page.js +25 -4
  274. package/selectors/router.js +154 -30
  275. package/selectors/url.js +25 -4
  276. package/selectors/user.js +90 -13
  277. package/store/index.js +60 -6
  278. package/store/middelwares/logger.js +7 -1
  279. package/store/middelwares/streams.js +19 -2
  280. package/streams/app.js +60 -8
  281. package/streams/client.js +8 -2
  282. package/streams/error.js +14 -3
  283. package/streams/index.js +6 -1
  284. package/streams/interval.js +6 -2
  285. package/streams/main.js +27 -2
  286. package/streams/router.js +45 -8
  287. package/streams/user.js +89 -15
  288. package/streams/view.js +97 -25
  289. package/styles/reset/form.js +57 -5
  290. package/styles/reset/index.js +6 -1
  291. package/styles/reset/media.js +22 -1
  292. package/styles/reset/root.js +33 -1
  293. package/styles/reset/table.js +10 -1
  294. package/styles/reset/typography.js +26 -1
  295. package/subscriptions/app.js +148 -17
  296. package/subscriptions/error.js +292 -13
  297. package/subscriptions/helpers/buildRegisterUrl.js +25 -6
  298. package/subscriptions/helpers/clearUpInAppBrowser.js +14 -3
  299. package/subscriptions/helpers/handleLinks.js +267 -25
  300. package/subscriptions/helpers/pipeline.js +12 -1
  301. package/subscriptions/history.js +34 -6
  302. package/subscriptions/index.js +25 -4
  303. package/subscriptions/menu.js +22 -5
  304. package/subscriptions/mock.js +39 -7
  305. package/subscriptions/router.js +336 -23
  306. package/subscriptions/user.js +93 -3
@@ -1,14 +1,203 @@
1
- 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 _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);}import range from'lodash/range';import React from'react';import{shallow,mount}from'enzyme';import{ITEMS_PER_LOAD}from"../../constants/DisplayOptions";import InfiniteContainer from"./index";global.console.error=jest.fn();var context={state:{}};describe('<InfiniteContainer />',function(){var renderedElement;var renderedInstance;var mockLoader;var mockIterator;var mockItems;var mockData=range(100).map(function(id){return{id:id,title:"Item ".concat(id)};});/**
1
+ import range from 'lodash/range';
2
+ import React from 'react';
3
+ import { shallow, mount } from 'enzyme';
4
+ import { ITEMS_PER_LOAD } from "../../constants/DisplayOptions";
5
+ import InfiniteContainer from "./index";
6
+ global.console.error = jest.fn();
7
+ const context = {
8
+ state: {}
9
+ };
10
+ describe('<InfiniteContainer />', () => {
11
+ let renderedElement;
12
+ let renderedInstance;
13
+ let mockLoader;
14
+ let mockIterator;
15
+ let mockItems;
16
+ const mockData = range(100).map(id => ({
17
+ id,
18
+ title: `Item ${id}`
19
+ }));
20
+
21
+ /**
2
22
  * The view component
3
23
  * @param {Object} props The component props.
4
- */var renderComponent=function renderComponent(props){renderedElement=shallow(React.createElement(InfiniteContainer,props),{context:context});renderedInstance=renderedElement.instance();};/**
24
+ */
25
+ const renderComponent = props => {
26
+ renderedElement = shallow(/*#__PURE__*/React.createElement(InfiniteContainer, props), {
27
+ context
28
+ });
29
+ renderedInstance = renderedElement.instance();
30
+ };
31
+
32
+ /**
5
33
  * Mocks the mapStateToProps connector.
6
34
  * @param {number} amount The new product amount.
7
- */var receiveItemsByProp=function receiveItemsByProp(amount){mockItems=mockData.slice(0,amount);var nextProps=_extends({},renderedInstance.props,{items:mockItems,totalItems:mockData.length});renderedElement.setProps(nextProps);};beforeEach(function(){mockLoader=jest.fn();mockIterator=jest.fn(function(data){return React.createElement("li",{key:data.id},data.title);});});describe('Given the component was mounted to the DOM',function(){beforeEach(function(){renderComponent({items:[],loader:mockLoader,iterator:mockIterator,totalItems:null});renderedInstance.componentDidMount();});it('should match snapshot',function(){expect(renderedElement).toMatchSnapshot();});it('should call the loader function',function(){var _renderedInstance$sta=_slicedToArray(renderedInstance.state.offset,1),offset=_renderedInstance$sta[0];expect(mockLoader).toBeCalledWith(offset);});describe('Given the loader requested new items',function(){var mockItemsLength=10;beforeEach(function(){receiveItemsByProp(mockItemsLength);});it('should call the iterator function according to the number of loaded items',function(){expect(mockIterator).toBeCalled();expect(mockIterator.mock.calls.length).toBe(mockItemsLength);});it('should render the loaded items',function(){expect(renderedElement.find('li').length).toBe(mockItemsLength);});});describe('Given the component was mounted within a scroll container',function(){var mockItemsLength=11;beforeEach(function(){// Receive items from initial mounting before proceeding...
8
- receiveItemsByProp(mockItemsLength);// Reset any previous calls (e.g. from componentDidMount())
9
- mockLoader.mock.calls=[];renderedInstance.componentDidUpdate();});it('should call the loader function if scrolled to the bottom',function(){renderedInstance.domScrollContainer={scrollTop:900,scrollHeight:1000,clientHeight:100};renderedInstance.handleLoading();expect(mockLoader).toBeCalled();});it('should not call the loader function if the scroll position did not change',function(){renderedInstance.domScrollContainer={scrollTop:0,scrollHeight:1000,clientHeight:100};renderedInstance.handleLoading();expect(mockLoader.mock.calls.length).toBe(0);});});describe('Given all items have been received',function(){var mockItemsLength=mockData.length;beforeEach(function(){receiveItemsByProp(mockItemsLength);});it('should expect no more items to be received',function(){expect(renderedInstance.needsToReceiveItems()).toBe(false);});it('should keep state.awaitingItems as true if not all items are rendered',function(){expect(renderedInstance.allItemsAreRendered()).toBe(false);expect(renderedInstance.state.awaitingItems).toBe(true);expect(renderedElement.find('li').length).toBeLessThan(mockItemsLength);});it('should set state.awaitingItems to false if all items are rendered',function(){renderedElement.setState({offset:[0,mockItemsLength]});renderedInstance.handleLoading();expect(renderedInstance.allItemsAreRendered()).toBe(true);expect(renderedInstance.state.awaitingItems).toBe(false);expect(renderedElement.find('li').length).toBe(mockItemsLength);});});});describe('Given that the initialLimit is used in the correct ways',function(){describe('Given that the initialLimit is used',function(){it('should render with the initialLimit',function(){renderComponent({items:mockData,loader:mockLoader,iterator:mockIterator,totalItems:mockData.length});// Check if the iniLimit was used
10
- expect(renderedElement.find('li').length).toBe(renderedInstance.props.initialLimit);// Reset the limit from props.initialLimit back to props.limit
11
- renderedInstance.componentDidMount();renderedInstance.handleLoading();// Re-render with the new limit
12
- renderedElement.update();// Check if the correct limit was used for the second render
13
- var newLimit=renderedInstance.props.initialLimit+renderedInstance.props.limit;expect(renderedElement.find('li').length).toBe(newLimit);});});describe('Given that the initialLimit is NOT used',function(){it('should render without the initialLimit',function(){renderComponent({items:[],loader:mockLoader,iterator:mockIterator,totalItems:null});renderedInstance.componentDidMount();receiveItemsByProp(ITEMS_PER_LOAD);// Check if the iniLimit wasn't used
14
- expect(renderedElement).toMatchSnapshot();expect(renderedElement.find('li').length).toBe(renderedInstance.props.limit);});});});describe('Given that the requestHash changes',function(){it('should reset the component',function(){var props={items:mockData,loader:mockLoader,iterator:mockIterator,totalItems:mockData.length,requestHash:'default'};var wrapper=mount(React.createElement(InfiniteContainer,props));var instance=wrapper.instance();instance.componentDidMount();instance.domScrollContainer=document.createElement('div');wrapper.setState({awaitingItems:false,offset:[10,10]});wrapper.setProps({requestHash:'price_desc'});expect(wrapper.state()).toEqual({offset:[0,32],awaitingItems:true,itemCount:0});});});});
35
+ */
36
+ const receiveItemsByProp = amount => {
37
+ mockItems = mockData.slice(0, amount);
38
+ const nextProps = {
39
+ ...renderedInstance.props,
40
+ items: mockItems,
41
+ totalItems: mockData.length
42
+ };
43
+ renderedElement.setProps(nextProps);
44
+ };
45
+ beforeEach(() => {
46
+ mockLoader = jest.fn();
47
+ mockIterator = jest.fn(data => /*#__PURE__*/React.createElement("li", {
48
+ key: data.id
49
+ }, data.title));
50
+ });
51
+ describe('Given the component was mounted to the DOM', () => {
52
+ beforeEach(() => {
53
+ renderComponent({
54
+ items: [],
55
+ loader: mockLoader,
56
+ iterator: mockIterator,
57
+ totalItems: null
58
+ });
59
+ renderedInstance.componentDidMount();
60
+ });
61
+ it('should match snapshot', () => {
62
+ expect(renderedElement).toMatchSnapshot();
63
+ });
64
+ it('should call the loader function', () => {
65
+ const [offset] = renderedInstance.state.offset;
66
+ expect(mockLoader).toBeCalledWith(offset);
67
+ });
68
+ describe('Given the loader requested new items', () => {
69
+ const mockItemsLength = 10;
70
+ beforeEach(() => {
71
+ receiveItemsByProp(mockItemsLength);
72
+ });
73
+ it('should call the iterator function according to the number of loaded items', () => {
74
+ expect(mockIterator).toBeCalled();
75
+ expect(mockIterator.mock.calls.length).toBe(mockItemsLength);
76
+ });
77
+ it('should render the loaded items', () => {
78
+ expect(renderedElement.find('li').length).toBe(mockItemsLength);
79
+ });
80
+ });
81
+ describe('Given the component was mounted within a scroll container', () => {
82
+ const mockItemsLength = 11;
83
+ beforeEach(() => {
84
+ // Receive items from initial mounting before proceeding...
85
+ receiveItemsByProp(mockItemsLength);
86
+
87
+ // Reset any previous calls (e.g. from componentDidMount())
88
+ mockLoader.mock.calls = [];
89
+ renderedInstance.componentDidUpdate();
90
+ });
91
+ it('should call the loader function if scrolled to the bottom', () => {
92
+ renderedInstance.domScrollContainer = {
93
+ scrollTop: 900,
94
+ scrollHeight: 1000,
95
+ clientHeight: 100
96
+ };
97
+ renderedInstance.handleLoading();
98
+ expect(mockLoader).toBeCalled();
99
+ });
100
+ it('should not call the loader function if the scroll position did not change', () => {
101
+ renderedInstance.domScrollContainer = {
102
+ scrollTop: 0,
103
+ scrollHeight: 1000,
104
+ clientHeight: 100
105
+ };
106
+ renderedInstance.handleLoading();
107
+ expect(mockLoader.mock.calls.length).toBe(0);
108
+ });
109
+ });
110
+ describe('Given all items have been received', () => {
111
+ const mockItemsLength = mockData.length;
112
+ beforeEach(() => {
113
+ receiveItemsByProp(mockItemsLength);
114
+ });
115
+ it('should expect no more items to be received', () => {
116
+ expect(renderedInstance.needsToReceiveItems()).toBe(false);
117
+ });
118
+ it('should keep state.awaitingItems as true if not all items are rendered', () => {
119
+ expect(renderedInstance.allItemsAreRendered()).toBe(false);
120
+ expect(renderedInstance.state.awaitingItems).toBe(true);
121
+ expect(renderedElement.find('li').length).toBeLessThan(mockItemsLength);
122
+ });
123
+ it('should set state.awaitingItems to false if all items are rendered', () => {
124
+ renderedElement.setState({
125
+ offset: [0, mockItemsLength]
126
+ });
127
+ renderedInstance.handleLoading();
128
+ expect(renderedInstance.allItemsAreRendered()).toBe(true);
129
+ expect(renderedInstance.state.awaitingItems).toBe(false);
130
+ expect(renderedElement.find('li').length).toBe(mockItemsLength);
131
+ });
132
+ });
133
+ });
134
+ describe('Given that the initialLimit is used in the correct ways', () => {
135
+ describe('Given that the initialLimit is used', () => {
136
+ it('should render with the initialLimit', () => {
137
+ renderComponent({
138
+ items: mockData,
139
+ loader: mockLoader,
140
+ iterator: mockIterator,
141
+ totalItems: mockData.length
142
+ });
143
+
144
+ // Check if the iniLimit was used
145
+ expect(renderedElement.find('li').length).toBe(renderedInstance.props.initialLimit);
146
+
147
+ // Reset the limit from props.initialLimit back to props.limit
148
+ renderedInstance.componentDidMount();
149
+ renderedInstance.handleLoading();
150
+
151
+ // Re-render with the new limit
152
+ renderedElement.update();
153
+
154
+ // Check if the correct limit was used for the second render
155
+ const newLimit = renderedInstance.props.initialLimit + renderedInstance.props.limit;
156
+ expect(renderedElement.find('li').length).toBe(newLimit);
157
+ });
158
+ });
159
+ describe('Given that the initialLimit is NOT used', () => {
160
+ it('should render without the initialLimit', () => {
161
+ renderComponent({
162
+ items: [],
163
+ loader: mockLoader,
164
+ iterator: mockIterator,
165
+ totalItems: null
166
+ });
167
+ renderedInstance.componentDidMount();
168
+ receiveItemsByProp(ITEMS_PER_LOAD);
169
+
170
+ // Check if the iniLimit wasn't used
171
+ expect(renderedElement).toMatchSnapshot();
172
+ expect(renderedElement.find('li').length).toBe(renderedInstance.props.limit);
173
+ });
174
+ });
175
+ });
176
+ describe('Given that the requestHash changes', () => {
177
+ it('should reset the component', () => {
178
+ const props = {
179
+ items: mockData,
180
+ loader: mockLoader,
181
+ iterator: mockIterator,
182
+ totalItems: mockData.length,
183
+ requestHash: 'default'
184
+ };
185
+ const wrapper = mount(/*#__PURE__*/React.createElement(InfiniteContainer, props));
186
+ const instance = wrapper.instance();
187
+ instance.componentDidMount();
188
+ instance.domScrollContainer = document.createElement('div');
189
+ wrapper.setState({
190
+ awaitingItems: false,
191
+ offset: [10, 10]
192
+ });
193
+ wrapper.setProps({
194
+ requestHash: 'price_desc'
195
+ });
196
+ expect(wrapper.state()).toEqual({
197
+ offset: [0, 32],
198
+ awaitingItems: true,
199
+ itemCount: 0
200
+ });
201
+ });
202
+ });
203
+ });
@@ -1,17 +1,273 @@
1
- var _excluded=["onFocusChange","onChange","type","value"];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 _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,{useCallback,useState,useEffect,useRef}from'react';import PropTypes from'prop-types';import DayPicker from'react-day-picker';import MomentLocaleUtils from'react-day-picker/moment';import'react-day-picker/lib/style.css';import{css}from'glamor';import classNames from'classnames';import moment from'moment';import CalendarIcon from'@shopgate/pwa-ui-shared/icons/CalendarIcon';import appConfig,{themeConfig}from'@shopgate/pwa-common/helpers/config';import Backdrop from'@shopgate/pwa-common/components/Backdrop';import{i18n}from'@shopgate/engage/core/helpers';import SimpleInput from"./SimpleInput";var variables=themeConfig.variables;var locale=appConfig.language.substring(0,2);/**
1
+ import _extends from "@babel/runtime/helpers/extends";
2
+ import React, { useCallback, useState, useEffect, useRef } from 'react';
3
+ import PropTypes from 'prop-types';
4
+ import DayPicker from 'react-day-picker';
5
+ import MomentLocaleUtils from 'react-day-picker/moment';
6
+ import 'react-day-picker/lib/style.css';
7
+ import { css } from 'glamor';
8
+ import classNames from 'classnames';
9
+ import moment from 'moment';
10
+ import CalendarIcon from '@shopgate/pwa-ui-shared/icons/CalendarIcon';
11
+ import appConfig, { themeConfig } from '@shopgate/pwa-common/helpers/config';
12
+ import Backdrop from '@shopgate/pwa-common/components/Backdrop';
13
+ import { i18n } from '@shopgate/engage/core/helpers';
14
+ import SimpleInput from "./SimpleInput";
15
+ const {
16
+ variables
17
+ } = themeConfig;
18
+ const locale = appConfig.language.substring(0, 2);
19
+
20
+ /**
2
21
  * @param {Object|string} date The input date
3
22
  * @returns {string}
4
- */var getDateFromISO=function getDateFromISO(date){var result=moment(date);if(!result.isValid()){return null;}return result.toDate();};/**
23
+ */
24
+ const getDateFromISO = date => {
25
+ const result = moment(date);
26
+ if (!result.isValid()) {
27
+ return null;
28
+ }
29
+ return result.toDate();
30
+ };
31
+
32
+ /**
5
33
  * @param {Object|string} date The input date
6
34
  * @param {boolean} validate Should the date be validated
7
35
  * @returns {string}
8
- */var getISOFormattedDate=function getISOFormattedDate(date){var validate=arguments.length>1&&arguments[1]!==undefined?arguments[1]:true;var result=moment(date,'L',locale);if(validate&&!result.isValid()){return'';}return result.format(moment.HTML5_FMT.DATE);};/**
36
+ */
37
+ const getISOFormattedDate = (date, validate = true) => {
38
+ const result = moment(date, 'L', locale);
39
+ if (validate && !result.isValid()) {
40
+ return '';
41
+ }
42
+ return result.format(moment.HTML5_FMT.DATE);
43
+ };
44
+
45
+ /**
9
46
  * @param {Object|string} date The input date
10
47
  * @returns {string}
11
- */var getLocaleFormattedDate=function getLocaleFormattedDate(date){var result=moment(date);if(!result.isValid()){return'';}return result.format('L');};var styles={selectBox:css({WebkitAppearance:'none',border:'1px solid var(--color-text-low-emphasis)',padding:'2px 16px 2px 6px',marginRight:7,backgroundImage:'url(data:image/svg+xml;utf8;base64,PD94bWwgdmVyc2lvbj0iMS4wIiBlbmNvZGluZz0iaXNvLTg4NTktMSI/Pg0KPHN2ZyB4bWxucz0iaHR0cDovL3d3dy53My5vcmcvMjAwMC9zdmciIHhtbG5zOnhsaW5rPSJodHRwOi8vd3d3LnczLm9yZy8xOTk5L3hsaW5rIiB2ZXJzaW9uPSIxLjEiIHg9IjBweCIgeT0iMHB4IiB2aWV3Qm94PSIwIDAgNDA1LjQ1NiA0MDUuNDU2IiBzdHlsZT0iZW5hYmxlLWJhY2tncm91bmQ6bmV3IDAgMCA0MDUuNDU2IDQwNS40NTY7IiB4bWw6c3BhY2U9InByZXNlcnZlIiB3aWR0aD0iMTZweCIgaGVpZ2h0PSIxNnB4Ij4NCjxnPg0KCTxwYXRoIGQ9Ik03NC4xMzQsNjQuMTQ3Yy00Ljk4NSwwLjA3OC05LjkxMSwyLjE2My0xMy40MzgsNS42ODhsLTU1LDU1QzIuMDk2LDEyOC40MzIsMCwxMzMuNDkyLDAsMTM4LjU4MyAgIHMyLjA5NiwxMC4xNTEsNS42OTcsMTMuNzVsMTgzLjI4MSwxODMuMjgxYzMuNTk5LDMuNjAxLDguNjU5LDUuNjk3LDEzLjc1LDUuNjk3czEwLjE1MS0yLjA5NiwxMy43NS01LjY5N2wxODMuMjgxLTE4My4yODEgICBjMy42MDEtMy41OTksNS42OTctOC42NTksNS42OTctMTMuNzVzLTIuMDk2LTEwLjE1MS01LjY5Ny0xMy43NWwtNTUtNTVjLTMuNTk4LTMuNTkxLTguNjUxLTUuNjgxLTEzLjczNC01LjY4MSAgIGMtNS4wODMsMC0xMC4xMzYsMi4wOS0xMy43MzQsNS42ODFMMjAyLjcyOCwxODQuMzk3TDg4LjE2Niw2OS44MzNDODQuNDk5LDY2LjE2OSw3OS4zMTgsNjQuMDcsNzQuMTM0LDY0LjE0N0w3NC4xMzQsNjQuMTQ3eiIgZmlsbD0iIzk2OTY5NiIvPg0KPC9nPg0KPC9zdmc+DQo=)',backgroundPosition:'right 4px top 50%',backgroundRepeat:'no-repeat',backgroundSize:10,borderRadius:0,outline:0,cursor:'pointer'}).toString(),iconWrapper:css({position:'absolute',right:variables.gap.small,top:'50%',cursor:'pointer',color:'var(--color-text-high-emphasis)'}).toString(),pickerWrapper:css({position:'relative',zIndex:12}).toString(),picker:css({left:'inherit !important',right:5,' .DayPicker-Day':{padding:'3px !important'},' .DayPicker-Day--selected':{backgroundColor:'var(--color-primary) !important'},' .DayPicker-Footer':{textAlign:'center'},' .DayPicker-TodayButton':{color:'var(--color-primary) !important'},' .DayPicker-TodayButton:hover':{backgroundColor:'var(--color-primary) !important',color:'#fff !important'},' .DayPicker-Caption':{padding:'0 !important'},' .DayPicker-NavButton':{right:'.5em !important'}}).toString(),pickerTop:css({bottom:30}).toString(),hidden:css({display:'none'}).toString()};var currentYear=new Date().getFullYear();var fromMonth=new Date(currentYear-100,11);var toMonth=new Date(currentYear+10,11);/**
48
+ */
49
+ const getLocaleFormattedDate = date => {
50
+ const result = moment(date);
51
+ if (!result.isValid()) {
52
+ return '';
53
+ }
54
+ return result.format('L');
55
+ };
56
+ const styles = {
57
+ selectBox: css({
58
+ WebkitAppearance: 'none',
59
+ border: '1px solid var(--color-text-low-emphasis)',
60
+ padding: '2px 16px 2px 6px',
61
+ marginRight: 7,
62
+ backgroundImage: 'url(data:image/svg+xml;utf8;base64,PD94bWwgdmVyc2lvbj0iMS4wIiBlbmNvZGluZz0iaXNvLTg4NTktMSI/Pg0KPHN2ZyB4bWxucz0iaHR0cDovL3d3dy53My5vcmcvMjAwMC9zdmciIHhtbG5zOnhsaW5rPSJodHRwOi8vd3d3LnczLm9yZy8xOTk5L3hsaW5rIiB2ZXJzaW9uPSIxLjEiIHg9IjBweCIgeT0iMHB4IiB2aWV3Qm94PSIwIDAgNDA1LjQ1NiA0MDUuNDU2IiBzdHlsZT0iZW5hYmxlLWJhY2tncm91bmQ6bmV3IDAgMCA0MDUuNDU2IDQwNS40NTY7IiB4bWw6c3BhY2U9InByZXNlcnZlIiB3aWR0aD0iMTZweCIgaGVpZ2h0PSIxNnB4Ij4NCjxnPg0KCTxwYXRoIGQ9Ik03NC4xMzQsNjQuMTQ3Yy00Ljk4NSwwLjA3OC05LjkxMSwyLjE2My0xMy40MzgsNS42ODhsLTU1LDU1QzIuMDk2LDEyOC40MzIsMCwxMzMuNDkyLDAsMTM4LjU4MyAgIHMyLjA5NiwxMC4xNTEsNS42OTcsMTMuNzVsMTgzLjI4MSwxODMuMjgxYzMuNTk5LDMuNjAxLDguNjU5LDUuNjk3LDEzLjc1LDUuNjk3czEwLjE1MS0yLjA5NiwxMy43NS01LjY5N2wxODMuMjgxLTE4My4yODEgICBjMy42MDEtMy41OTksNS42OTctOC42NTksNS42OTctMTMuNzVzLTIuMDk2LTEwLjE1MS01LjY5Ny0xMy43NWwtNTUtNTVjLTMuNTk4LTMuNTkxLTguNjUxLTUuNjgxLTEzLjczNC01LjY4MSAgIGMtNS4wODMsMC0xMC4xMzYsMi4wOS0xMy43MzQsNS42ODFMMjAyLjcyOCwxODQuMzk3TDg4LjE2Niw2OS44MzNDODQuNDk5LDY2LjE2OSw3OS4zMTgsNjQuMDcsNzQuMTM0LDY0LjE0N0w3NC4xMzQsNjQuMTQ3eiIgZmlsbD0iIzk2OTY5NiIvPg0KPC9nPg0KPC9zdmc+DQo=)',
63
+ backgroundPosition: 'right 4px top 50%',
64
+ backgroundRepeat: 'no-repeat',
65
+ backgroundSize: 10,
66
+ borderRadius: 0,
67
+ outline: 0,
68
+ cursor: 'pointer'
69
+ }).toString(),
70
+ iconWrapper: css({
71
+ position: 'absolute',
72
+ right: variables.gap.small,
73
+ top: '50%',
74
+ cursor: 'pointer',
75
+ color: 'var(--color-text-high-emphasis)'
76
+ }).toString(),
77
+ pickerWrapper: css({
78
+ position: 'relative',
79
+ zIndex: 12
80
+ }).toString(),
81
+ picker: css({
82
+ left: 'inherit !important',
83
+ right: 5,
84
+ ' .DayPicker-Day': {
85
+ padding: '3px !important'
86
+ },
87
+ ' .DayPicker-Day--selected': {
88
+ backgroundColor: 'var(--color-primary) !important'
89
+ },
90
+ ' .DayPicker-Footer': {
91
+ textAlign: 'center'
92
+ },
93
+ ' .DayPicker-TodayButton': {
94
+ color: 'var(--color-primary) !important'
95
+ },
96
+ ' .DayPicker-TodayButton:hover': {
97
+ backgroundColor: 'var(--color-primary) !important',
98
+ color: '#fff !important'
99
+ },
100
+ ' .DayPicker-Caption': {
101
+ padding: '0 !important'
102
+ },
103
+ ' .DayPicker-NavButton': {
104
+ right: '.5em !important'
105
+ }
106
+ }).toString(),
107
+ pickerTop: css({
108
+ bottom: 30
109
+ }).toString(),
110
+ hidden: css({
111
+ display: 'none'
112
+ }).toString()
113
+ };
114
+ const currentYear = new Date().getFullYear();
115
+ const fromMonth = new Date(currentYear - 100, 11);
116
+ const toMonth = new Date(currentYear + 10, 11);
117
+
118
+ /**
12
119
  * @param {Object} props The components props
13
120
  * @returns {JSX}
14
- */var Caption=function Caption(_ref){var date=_ref.date,localeUtils=_ref.localeUtils,onChange=_ref.onChange;var months=localeUtils.getMonths(locale);var years=[];for(var i=fromMonth.getFullYear();i<=toMonth.getFullYear();i+=1){years.push(i);}var handleChange=function handleChange(e){var _e$target$form=e.target.form,year=_e$target$form.year,month=_e$target$form.month;onChange(new Date(year.value,month.value));};return React.createElement("div",{className:"DayPicker-Caption"},React.createElement("select",{name:"month",onChange:handleChange,value:date.getMonth(),className:styles.selectBox},months.map(function(month,i){return React.createElement("option",{key:month,value:i},month);})),React.createElement("select",{name:"year",onChange:handleChange,value:date.getFullYear(),className:styles.selectBox},years.map(function(year){return React.createElement("option",{key:year,value:year},year);})));};/**
121
+ */
122
+ const Caption = ({
123
+ date,
124
+ localeUtils,
125
+ onChange
126
+ }) => {
127
+ const months = localeUtils.getMonths(locale);
128
+ const years = [];
129
+ for (let i = fromMonth.getFullYear(); i <= toMonth.getFullYear(); i += 1) {
130
+ years.push(i);
131
+ }
132
+ const handleChange = function handleChange(e) {
133
+ const {
134
+ year,
135
+ month
136
+ } = e.target.form;
137
+ onChange(new Date(year.value, month.value));
138
+ };
139
+ return /*#__PURE__*/React.createElement("div", {
140
+ className: "DayPicker-Caption"
141
+ }, /*#__PURE__*/React.createElement("select", {
142
+ name: "month",
143
+ onChange: handleChange,
144
+ value: date.getMonth(),
145
+ className: styles.selectBox
146
+ }, months.map((month, i) => /*#__PURE__*/React.createElement("option", {
147
+ key: month,
148
+ value: i
149
+ }, month))), /*#__PURE__*/React.createElement("select", {
150
+ name: "year",
151
+ onChange: handleChange,
152
+ value: date.getFullYear(),
153
+ className: styles.selectBox
154
+ }, years.map(year => /*#__PURE__*/React.createElement("option", {
155
+ key: year,
156
+ value: year
157
+ }, year))));
158
+ };
159
+ /**
15
160
  * @param {Object} props The components props
16
161
  * @returns {JSX}
17
- */var DateInput=function DateInput(_ref2){var onFocusChange=_ref2.onFocusChange,onChange=_ref2.onChange,type=_ref2.type,value=_ref2.value,rest=_objectWithoutProperties(_ref2,_excluded);var wrapperRef=useRef(null);var _useState=useState(getLocaleFormattedDate(value)),_useState2=_slicedToArray(_useState,2),inputValue=_useState2[0],setInputValue=_useState2[1];var _useState3=useState(getDateFromISO(value)),_useState4=_slicedToArray(_useState3,2),pickerValue=_useState4[0],setPickerValue=_useState4[1];var _useState5=useState(false),_useState6=_slicedToArray(_useState5,2),isFocused=_useState6[0],setIsFocused=_useState6[1];var _useState7=useState(false),_useState8=_slicedToArray(_useState7,2),pickerVisible=_useState8[0],setPickerVisible=_useState8[1];useEffect(function(){var updated=getLocaleFormattedDate(value);if(updated){setInputValue(updated);setPickerValue(getDateFromISO(value));}},[value]);var needsPositionTop=useCallback(function(){var element=wrapperRef.current;if(!element){return false;}var _element$getBoundingC=element.getBoundingClientRect(),top=_element$getBoundingC.top,height=_element$getBoundingC.height;var distToBottom=document.body.offsetHeight-(top+height);return distToBottom<=300;},[wrapperRef]);var handleInputValueChange=useCallback(function(val){setInputValue(val);},[]);var handleFocusChange=useCallback(function(focused,e){if(!focused){setPickerValue(getDateFromISO(getISOFormattedDate(inputValue)));onChange(inputValue.length!==0?getISOFormattedDate(inputValue,false):null);}setIsFocused(focused);onFocusChange(focused,e);},[inputValue,onChange,onFocusChange]);var handlePickerChange=useCallback(function(date){setPickerVisible(false);setPickerValue(date);setInputValue(getLocaleFormattedDate(date));onChange(getISOFormattedDate(date));},[onChange]);var handleMonthChange=useCallback(function(date){setPickerValue(date);},[]);var handleIconClick=useCallback(function(){setPickerVisible(!pickerVisible);},[pickerVisible]);var handleBackdropClick=useCallback(function(){setPickerVisible(false);},[]);return React.createElement(React.Fragment,null,React.createElement("div",{ref:wrapperRef},React.createElement(SimpleInput,_extends({},rest,{attributes:{placeholder:isFocused?i18n.text('formats.date.pattern'):null},value:inputValue,type:"text",onFocusChange:handleFocusChange,onChange:handleInputValueChange})),React.createElement("div",{className:styles.iconWrapper,onClick:handleIconClick,role:"button",tabIndex:"0",onKeyDown:handleIconClick},React.createElement(CalendarIcon,null))),React.createElement("div",{className:classNames(styles.pickerWrapper,_defineProperty({},styles.hidden,!pickerVisible))},React.createElement(DayPicker,{className:classNames('DayPickerInput-Overlay',styles.picker,_defineProperty({},styles.pickerTop,needsPositionTop())),onDayClick:handlePickerChange,selectedDays:pickerValue,localeUtils:MomentLocaleUtils,locale:locale,todayButton:i18n.text('locations.your_current_timeslot.today'),onTodayButtonClick:handlePickerChange,month:pickerValue,showOutsideDays:true,captionElement:function captionElement(_ref3){var date=_ref3.date,localeUtils=_ref3.localeUtils;return React.createElement(Caption,{date:date,localeUtils:localeUtils,onChange:handleMonthChange});}})),pickerVisible&&React.createElement(Backdrop,{isVisible:true,level:11,opacity:0,onClick:handleBackdropClick}));};DateInput.defaultProps={onFocusChange:function onFocusChange(){},onChange:function onChange(){},type:null,value:null};export default DateInput;
162
+ */
163
+ const DateInput = ({
164
+ onFocusChange,
165
+ onChange,
166
+ type,
167
+ value,
168
+ ...rest
169
+ }) => {
170
+ const wrapperRef = useRef(null);
171
+ const [inputValue, setInputValue] = useState(getLocaleFormattedDate(value));
172
+ const [pickerValue, setPickerValue] = useState(getDateFromISO(value));
173
+ const [isFocused, setIsFocused] = useState(false);
174
+ const [pickerVisible, setPickerVisible] = useState(false);
175
+ useEffect(() => {
176
+ const updated = getLocaleFormattedDate(value);
177
+ if (updated) {
178
+ setInputValue(updated);
179
+ setPickerValue(getDateFromISO(value));
180
+ }
181
+ }, [value]);
182
+ const needsPositionTop = useCallback(() => {
183
+ const element = wrapperRef.current;
184
+ if (!element) {
185
+ return false;
186
+ }
187
+ const {
188
+ top,
189
+ height
190
+ } = element.getBoundingClientRect();
191
+ const distToBottom = document.body.offsetHeight - (top + height);
192
+ return distToBottom <= 300;
193
+ }, [wrapperRef]);
194
+ const handleInputValueChange = useCallback(val => {
195
+ setInputValue(val);
196
+ }, []);
197
+ const handleFocusChange = useCallback((focused, e) => {
198
+ if (!focused) {
199
+ setPickerValue(getDateFromISO(getISOFormattedDate(inputValue)));
200
+ onChange(inputValue.length !== 0 ? getISOFormattedDate(inputValue, false) : null);
201
+ }
202
+ setIsFocused(focused);
203
+ onFocusChange(focused, e);
204
+ }, [inputValue, onChange, onFocusChange]);
205
+ const handlePickerChange = useCallback(date => {
206
+ setPickerVisible(false);
207
+ setPickerValue(date);
208
+ setInputValue(getLocaleFormattedDate(date));
209
+ onChange(getISOFormattedDate(date));
210
+ }, [onChange]);
211
+ const handleMonthChange = useCallback(date => {
212
+ setPickerValue(date);
213
+ }, []);
214
+ const handleIconClick = useCallback(() => {
215
+ setPickerVisible(!pickerVisible);
216
+ }, [pickerVisible]);
217
+ const handleBackdropClick = useCallback(() => {
218
+ setPickerVisible(false);
219
+ }, []);
220
+ return /*#__PURE__*/React.createElement(React.Fragment, null, /*#__PURE__*/React.createElement("div", {
221
+ ref: wrapperRef
222
+ }, /*#__PURE__*/React.createElement(SimpleInput, _extends({}, rest, {
223
+ attributes: {
224
+ placeholder: isFocused ? i18n.text('formats.date.pattern') : null
225
+ },
226
+ value: inputValue,
227
+ type: "text",
228
+ onFocusChange: handleFocusChange,
229
+ onChange: handleInputValueChange
230
+ })), /*#__PURE__*/React.createElement("div", {
231
+ className: styles.iconWrapper,
232
+ onClick: handleIconClick,
233
+ role: "button",
234
+ tabIndex: "0",
235
+ onKeyDown: handleIconClick
236
+ }, /*#__PURE__*/React.createElement(CalendarIcon, null))), /*#__PURE__*/React.createElement("div", {
237
+ className: classNames(styles.pickerWrapper, {
238
+ [styles.hidden]: !pickerVisible
239
+ })
240
+ }, /*#__PURE__*/React.createElement(DayPicker, {
241
+ className: classNames('DayPickerInput-Overlay', styles.picker, {
242
+ [styles.pickerTop]: needsPositionTop()
243
+ }),
244
+ onDayClick: handlePickerChange,
245
+ selectedDays: pickerValue,
246
+ localeUtils: MomentLocaleUtils,
247
+ locale: locale,
248
+ todayButton: i18n.text('locations.your_current_timeslot.today'),
249
+ onTodayButtonClick: handlePickerChange,
250
+ month: pickerValue,
251
+ showOutsideDays: true,
252
+ captionElement: ({
253
+ date,
254
+ localeUtils
255
+ }) => /*#__PURE__*/React.createElement(Caption, {
256
+ date: date,
257
+ localeUtils: localeUtils,
258
+ onChange: handleMonthChange
259
+ })
260
+ })), pickerVisible && /*#__PURE__*/React.createElement(Backdrop, {
261
+ isVisible: true,
262
+ level: 11,
263
+ opacity: 0,
264
+ onClick: handleBackdropClick
265
+ }));
266
+ };
267
+ DateInput.defaultProps = {
268
+ onFocusChange: () => {},
269
+ onChange: () => {},
270
+ type: null,
271
+ value: null
272
+ };
273
+ export default DateInput;
@@ -1,26 +1,112 @@
1
- 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 _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 _classCallCheck(instance,Constructor){if(!(instance instanceof Constructor)){throw new TypeError("Cannot call a class as a function");}}function _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);}}function _createClass(Constructor,protoProps,staticProps){if(protoProps)_defineProperties(Constructor.prototype,protoProps);if(staticProps)_defineProperties(Constructor,staticProps);return Constructor;}function _callSuper(_this,derived,args){function isNativeReflectConstruct(){if(typeof Reflect==="undefined"||!Reflect.construct)return false;if(Reflect.construct.sham)return false;if(typeof Proxy==="function")return true;try{return!Boolean.prototype.valueOf.call(Reflect.construct(Boolean,[],function(){}));}catch(e){return false;}}derived=_getPrototypeOf(derived);return _possibleConstructorReturn(_this,isNativeReflectConstruct()?Reflect.construct(derived,args||[],_getPrototypeOf(_this).constructor):derived.apply(_this,args));}function _possibleConstructorReturn(self,call){if(call&&(_typeof(call)==="object"||typeof call==="function")){return call;}return _assertThisInitialized(self);}function _assertThisInitialized(self){if(self===void 0){throw new ReferenceError("this hasn't been initialised - super() hasn't been called");}return self;}function _get(target,property,receiver){if(typeof Reflect!=="undefined"&&Reflect.get){_get=Reflect.get;}else{_get=function _get(target,property,receiver){var base=_superPropBase(target,property);if(!base)return;var desc=Object.getOwnPropertyDescriptor(base,property);if(desc.get){return desc.get.call(receiver);}return desc.value;};}return _get(target,property,receiver||target);}function _superPropBase(object,property){while(!Object.prototype.hasOwnProperty.call(object,property)){object=_getPrototypeOf(object);if(object===null)break;}return object;}function _getPrototypeOf(o){_getPrototypeOf=Object.setPrototypeOf?Object.getPrototypeOf:function _getPrototypeOf(o){return o.__proto__||Object.getPrototypeOf(o);};return _getPrototypeOf(o);}function _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);}function _setPrototypeOf(o,p){_setPrototypeOf=Object.setPrototypeOf||function _setPrototypeOf(o,p){o.__proto__=p;return o;};return _setPrototypeOf(o,p);}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;}import React from'react';import classNames from'classnames';import{logger}from'@shopgate/pwa-core';import SimpleInput from"./SimpleInput";/**
1
+ import _extends from "@babel/runtime/helpers/extends";
2
+ import React from 'react';
3
+ import classNames from 'classnames';
4
+ import { logger } from '@shopgate/pwa-core';
5
+ import SimpleInput from "./SimpleInput";
6
+
7
+ /**
2
8
  * A component that takes care of rendering and validation of input fields.
3
9
  * This component has no styling and should not be used directly.
4
10
  * You may want to use an appropriate form field component from the template instead.
5
- */var MultiLineInput=/*#__PURE__*/function(_SimpleInput){/**
11
+ */
12
+ class MultiLineInput extends SimpleInput {
13
+ /**
6
14
  * Creates a new input component.
7
15
  * @param {Object} props The component properties.
8
- */function MultiLineInput(props){var _this2;_classCallCheck(this,MultiLineInput);_this2=_callSuper(this,MultiLineInput,[props]);/**
9
- * Sets an initial height of the multiline HTMLElement.
10
- */_defineProperty(_this2,"setBaseHeight",function(){if(_this2.baseHeight!==null){return;}_this2.baseHeight=_this2.ref.clientHeight;});_this2.baseHeight=null;// First render must be empty.
11
- var sanitizedValue=_this2.props.onSanitize('');_this2.state={value:sanitizedValue,isValid:_this2.props.onValidate(sanitizedValue,true),isFocused:false};return _this2;}/**
16
+ */
17
+ constructor(props) {
18
+ super(props);
19
+ /**
20
+ * Sets an initial height of the multiline HTMLElement.
21
+ */
22
+ this.setBaseHeight = () => {
23
+ if (this.baseHeight !== null) {
24
+ return;
25
+ }
26
+ this.baseHeight = this.ref.clientHeight;
27
+ };
28
+ this.baseHeight = null;
29
+ // First render must be empty.
30
+ const sanitizedValue = this.props.onSanitize('');
31
+ this.state = {
32
+ value: sanitizedValue,
33
+ isValid: this.props.onValidate(sanitizedValue, true),
34
+ isFocused: false
35
+ };
36
+ }
37
+
38
+ /**
12
39
  * Additional function to make avoid .setState use in componentDidMount
13
40
  * usage violation.
14
- */_inherits(MultiLineInput,_SimpleInput);return _createClass(MultiLineInput,[{key:"doComponentDidMount",value:function doComponentDidMount(){var sanitizedValue=this.props.onSanitize(this.props.value||'');this.props.onChange(sanitizedValue);this.setState({value:sanitizedValue,isValid:this.props.onValidate(sanitizedValue,true),isFocused:false});}/**
41
+ */
42
+ doComponentDidMount() {
43
+ const sanitizedValue = this.props.onSanitize(this.props.value || '');
44
+ this.props.onChange(sanitizedValue);
45
+ this.setState({
46
+ value: sanitizedValue,
47
+ isValid: this.props.onValidate(sanitizedValue, true),
48
+ isFocused: false
49
+ });
50
+ }
51
+
52
+ /**
15
53
  * Set real value and trigger second render.
16
54
  * Initially trigger onChange() to set the initial value.
17
- */},{key:"componentDidMount",value:function componentDidMount(){// No super, would have to sanitize anyway.
18
- this.doComponentDidMount();}/**
55
+ */
56
+ componentDidMount() {
57
+ // No super, would have to sanitize anyway.
58
+ this.doComponentDidMount();
59
+ }
60
+
61
+ /**
19
62
  * Adjusts the element height.
20
- */},{key:"componentDidUpdate",value:function componentDidUpdate(){if(!(this.ref instanceof HTMLElement)){logger.error('Ref is not an HTMLElement');return;}this.ref.style.height="".concat(this.baseHeight,"px");this.ref.style.height="".concat(this.ref.scrollHeight,"px");}},{key:"handleRef",value:/**
63
+ */
64
+ componentDidUpdate() {
65
+ if (!(this.ref instanceof HTMLElement)) {
66
+ logger.error('Ref is not an HTMLElement');
67
+ return;
68
+ }
69
+ this.ref.style.height = `${this.baseHeight}px`;
70
+ this.ref.style.height = `${this.ref.scrollHeight}px`;
71
+ }
72
+ /**
21
73
  * Handles reference passing to callback and assignation.
22
74
  * @param {HTMLElement} ref The element
23
- */function handleRef(ref){_get(_getPrototypeOf(MultiLineInput.prototype),"handleRef",this).call(this,ref);this.setBaseHeight();}/**
75
+ */
76
+ handleRef(ref) {
77
+ super.handleRef(ref);
78
+ this.setBaseHeight();
79
+ }
80
+
81
+ /**
24
82
  * Renders the component.
25
83
  * @returns {JSX}
26
- */},{key:"render",value:function render(){var _this3=this;var _this$props=this.props,className=_this$props.className,password=_this$props.password,attributes=_this$props.attributes,disabled=_this$props.disabled,required=_this$props.required;var type=password?'password':this.props.type;var value=this.state.value;return React.createElement("textarea",_extends({id:this.props.id,name:this.props.name,ref:function ref(_ref){return _this3.handleRef(_ref);},className:classNames(className,'multiLineInput','common__multi-line-input'),type:type,value:value,onChange:this.handleChange,onFocus:this.handleFocus,onBlur:this.handleBlur,required:required,disabled:disabled},attributes));}}]);}(SimpleInput);export default MultiLineInput;
84
+ */
85
+ render() {
86
+ const {
87
+ className,
88
+ password,
89
+ attributes,
90
+ disabled,
91
+ required
92
+ } = this.props;
93
+ const type = password ? 'password' : this.props.type;
94
+ const {
95
+ value
96
+ } = this.state;
97
+ return /*#__PURE__*/React.createElement("textarea", _extends({
98
+ id: this.props.id,
99
+ name: this.props.name,
100
+ ref: ref => this.handleRef(ref),
101
+ className: classNames(className, 'multiLineInput', 'common__multi-line-input'),
102
+ type: type,
103
+ value: value,
104
+ onChange: this.handleChange,
105
+ onFocus: this.handleFocus,
106
+ onBlur: this.handleBlur,
107
+ required: required,
108
+ disabled: disabled
109
+ }, attributes));
110
+ }
111
+ }
112
+ export default MultiLineInput;