@shopgate/engage 7.27.3-alpha.18 → 7.27.3-alpha.19

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 (106) hide show
  1. package/components/ResponsiveContainer/breakpoints.js +2 -2
  2. package/components/View/components/Content/style.js +1 -1
  3. package/components/View/context.js +1 -1
  4. package/core/constants/index.js +7 -1
  5. package/core/contexts/ThemeResourcesContext.d.ts +10 -1
  6. package/core/contexts/ThemeResourcesContext.js +1 -1
  7. package/core/helpers/scrollContainer.js +2 -2
  8. package/core/hocs/withThemeResources.js +4 -1
  9. package/core/hooks/events/index.js +1 -1
  10. package/core/hooks/events/usePressHandler.js +38 -0
  11. package/core/hooks/useThemeResources.js +6 -5
  12. package/core/providers/ThemeResourcesProvider.js +9 -5
  13. package/locations/subscriptions.js +2 -2
  14. package/package.json +9 -7
  15. package/page/action-creators/index.js +22 -0
  16. package/page/components/Widgets/Overlay.js +51 -0
  17. package/page/components/Widgets/Tooltip.js +22 -0
  18. package/page/components/Widgets/Widget.js +15 -0
  19. package/page/components/Widgets/WidgetContext.d.ts +42 -0
  20. package/page/components/Widgets/WidgetContext.js +9 -0
  21. package/page/components/Widgets/WidgetProvider.js +8 -0
  22. package/page/components/Widgets/Widgets.js +11 -0
  23. package/page/components/Widgets/WidgetsPreviewContext.js +9 -0
  24. package/page/components/Widgets/WidgetsPreviewProvider.js +8 -0
  25. package/page/components/Widgets/constants.js +4 -0
  26. package/page/components/Widgets/events.js +23 -0
  27. package/page/components/Widgets/helpers.js +23 -0
  28. package/page/components/Widgets/hooks.js +69 -0
  29. package/page/components/Widgets/index.js +1 -0
  30. package/page/components/Widgets/types.d.ts +127 -0
  31. package/page/components/index.js +1 -1
  32. package/page/constants/actionTypes.js +1 -0
  33. package/page/constants/index.js +5 -1
  34. package/page/hooks/index.d.ts +60 -0
  35. package/page/hooks/index.js +25 -0
  36. package/page/index.js +1 -2
  37. package/page/reducers/index.js +6 -0
  38. package/page/selectors/index.js +48 -2
  39. package/page/subscriptions/index.js +4 -0
  40. package/page/widgets/HTML/HTML.js +5 -0
  41. package/page/widgets/HTML/hooks.js +12 -0
  42. package/page/widgets/HTML/index.js +1 -0
  43. package/page/widgets/Placeholder/Placeholder.js +5 -0
  44. package/page/widgets/Placeholder/hooks.js +12 -0
  45. package/page/widgets/Placeholder/index.js +1 -0
  46. package/page/widgets/ProductList/ProductList.js +5 -0
  47. package/page/widgets/ProductList/hooks.js +25 -0
  48. package/page/widgets/ProductList/index.js +1 -0
  49. package/page/widgets/ProductSlider/ProductSlider.js +4 -0
  50. package/page/widgets/ProductSlider/hooks.js +27 -0
  51. package/page/widgets/ProductSlider/index.js +1 -0
  52. package/page/widgets/index.js +1 -0
  53. package/page/widgets/widgets.json +14 -0
  54. package/product/components/ProductCard/index.js +1 -1
  55. package/product/components/ProductGrid/components/Item/components/ItemDetails/index.js +8 -0
  56. package/product/components/ProductGrid/components/Item/components/ItemDetails/spec.js +1 -0
  57. package/product/components/ProductGrid/components/Item/components/ItemDiscount/index.js +5 -0
  58. package/product/components/ProductGrid/components/Item/components/ItemFavoritesButton/index.js +5 -0
  59. package/product/components/ProductGrid/components/Item/components/ItemFavoritesButton/spec.js +1 -0
  60. package/product/components/ProductGrid/components/Item/components/ItemImage/index.js +5 -0
  61. package/product/components/ProductGrid/components/Item/components/ItemImage/spec.js +1 -0
  62. package/product/components/ProductGrid/components/Item/components/ItemName/index.js +5 -0
  63. package/product/components/ProductGrid/components/Item/components/ItemName/spec.js +1 -0
  64. package/product/components/ProductGrid/components/Item/components/ItemPrice/index.js +5 -0
  65. package/product/components/ProductGrid/components/Item/components/ItemPrice/spec.js +1 -0
  66. package/product/components/ProductGrid/components/Item/index.js +7 -0
  67. package/product/components/ProductGrid/components/Iterator/index.js +5 -0
  68. package/product/components/ProductGrid/components/Layout/index.js +5 -0
  69. package/product/components/ProductGrid/index.js +22 -0
  70. package/product/components/ProductGrid/spec.js +1 -0
  71. package/product/components/ProductGridPrice/index.js +1 -1
  72. package/product/components/ProductSlider/index.js +4 -4
  73. package/product/components/index.js +1 -1
  74. package/styles/helpers/color.js +23 -0
  75. package/styles/helpers/index.js +1 -1
  76. package/styles/helpers/setPageBackgroundColor.js +2 -2
  77. package/styles/index.d.ts +17 -0
  78. package/styles/index.js +1 -1
  79. package/styles/theme/createTheme/createBreakpoints.d.ts +114 -0
  80. package/styles/theme/createTheme/createBreakpoints.js +41 -0
  81. package/styles/theme/createTheme/createSpacing.d.ts +23 -0
  82. package/styles/theme/createTheme/createSpacing.js +14 -0
  83. package/styles/theme/createTheme/index.d.ts +19 -0
  84. package/styles/theme/createTheme/index.js +5 -0
  85. package/styles/theme/createTheme/transitions.d.ts +100 -0
  86. package/styles/theme/createTheme/transitions.js +26 -0
  87. package/styles/theme/createTheme/zIndex.d.ts +12 -0
  88. package/styles/theme/createTheme/zIndex.js +3 -0
  89. package/styles/theme/hooks/index.d.ts +4 -0
  90. package/styles/theme/hooks/index.js +1 -0
  91. package/styles/theme/hooks/useActiveBreakpoint.d.ts +18 -0
  92. package/styles/theme/hooks/useActiveBreakpoint.js +4 -0
  93. package/styles/theme/hooks/useMediaQuery.d.ts +33 -0
  94. package/styles/theme/hooks/useMediaQuery.js +20 -0
  95. package/styles/theme/hooks/useResponsiveValue.d.ts +27 -0
  96. package/styles/theme/hooks/useResponsiveValue.js +4 -0
  97. package/styles/theme/hooks/useTheme.d.ts +8 -0
  98. package/styles/theme/hooks/useTheme.js +4 -0
  99. package/styles/theme/index.d.ts +8 -0
  100. package/styles/theme/index.js +1 -0
  101. package/styles/theme/providers/ActiveBreakpointProvider.d.ts +21 -0
  102. package/styles/theme/providers/ActiveBreakpointProvider.js +13 -0
  103. package/styles/theme/providers/ThemeProvider.d.ts +18 -0
  104. package/styles/theme/providers/ThemeProvider.js +7 -0
  105. package/styles/tss/index.js +3 -0
  106. package/tracking/selectors/cookieConsent.js +2 -2
@@ -1,5 +1,5 @@
1
1
  // Ugly imports to avoid breaking tests due to circular dependencies
2
- import{isIOSTheme}from'@shopgate/engage/core/helpers/isIOSTheme';import{hasWebBridge}from'@shopgate/engage/core/helpers/bridge';var iosThemeActive=isIOSTheme();/* eslint-disable extra-rules/no-single-line-objects */var breakpoints=[{name:'xs',from:0,to:600},{name:'sm',from:600,to:960},{name:'md',from:960,to:1280},{name:'lg',from:1280,to:1920},{name:'xl',from:1920,to:Number.MAX_VALUE}];/* eslint-enable extra-rules/no-single-line-objects */ /**
2
+ import{isIOSTheme}from'@shopgate/engage/core/helpers/isIOSTheme';import{hasWebBridge}from'@shopgate/engage/core/helpers/bridge';import{IS_PAGE_PREVIEW_ACTIVE}from'@shopgate/engage/page/constants';var iosThemeActive=isIOSTheme();/* eslint-disable extra-rules/no-single-line-objects */var breakpoints=[{name:'xs',from:0,to:600},{name:'sm',from:600,to:960},{name:'md',from:960,to:1280},{name:'lg',from:1280,to:1920},{name:'xl',from:1920,to:Number.MAX_VALUE}];/* eslint-enable extra-rules/no-single-line-objects */ /**
3
3
  * Generates a media query for different breakpoints and platform.
4
4
  * @param {Object} comparators Comparators.
5
5
  * @param {string} breakpoint Breakpoint rule.
@@ -9,6 +9,6 @@ import{isIOSTheme}from'@shopgate/engage/core/helpers/isIOSTheme';import{hasWebBr
9
9
  var breakpointStart=breakpoint.search(/[a-zA-Z]/);var comparatorString=breakpoint.substring(0,breakpointStart===-1?0:breakpointStart);var breakpointString=breakpoint.substring(breakpointStart===-1?0:breakpointStart);// Get configuration.
10
10
  var comparator=comparators[comparatorString];var config=breakpoints.find(function(b){return b.name===breakpointString;});// Web / App config.
11
11
  // Handle iOS theme as app for now so that media queries in shared components only work for app
12
- var isWeb=hasWebBridge()&&!iosThemeActive;// Always mode.
12
+ var isWeb=hasWebBridge()&&!iosThemeActive&&!IS_PAGE_PREVIEW_ACTIVE;// Always mode.
13
13
  if(webAlways&&isWeb||appAlways&&!isWeb){return true;}// Return media query that never evaluates for now.
14
14
  if(appOnly&&isWeb||webOnly&&!isWeb){return false;}return comparator(config.from,config.to,window.innerWidth);};export default breakpoints;
@@ -1 +1 @@
1
- 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);}import{css}from'glamor';import{useScrollContainer}from'@shopgate/engage/core';import{responsiveMediaQuery}from'@shopgate/engage/styles';export default css(_extends({display:'flex',flexDirection:'column',width:'100vw'},useScrollContainer()?{bottom:0,top:0,overflowScrolling:'touch',position:'absolute',WebkitOverflowScrolling:'touch'}:{height:'100%',backgroundColor:'var(--page-background-color)'},_defineProperty({},responsiveMediaQuery('>xs',{webOnly:true}),{width:'var(--page-content-width)'})));
1
+ 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);}import{css}from'glamor';import{useScrollContainer}from'@shopgate/engage/core';import{responsiveMediaQuery}from'@shopgate/engage/styles';import{IS_PAGE_PREVIEW_ACTIVE}from'@shopgate/engage/page/constants';export default css(_extends({display:'flex',flexDirection:'column',width:'100vw'},useScrollContainer()?_extends({bottom:0,top:0,overflowScrolling:'touch',position:'absolute',WebkitOverflowScrolling:'touch'},IS_PAGE_PREVIEW_ACTIVE&&{scrollbarWidth:'thin',backgroundColor:'var(--page-background-color)'}):{height:'100%',backgroundColor:'var(--page-background-color)'},_defineProperty({},responsiveMediaQuery('>xs',{webOnly:true}),{width:'var(--page-content-width)'})));
@@ -1 +1 @@
1
- import React from'react';export var ViewContext=React.createContext();
1
+ import React from'react';import noop from'lodash/noop';export var ViewContext=React.createContext({top:null,bottom:null,ariaHidden:false,set:noop,setTop:noop,setBottom:noop,setContentRef:noop,getContentRef:function getContentRef(){return{current:null};},scrollTop:noop,setAriaHidden:noop});
@@ -3,4 +3,10 @@ export*from'@shopgate/pwa-core/constants/ErrorManager';export*from'@shopgate/pwa
3
3
  export*from'@shopgate/pwa-common/constants/ActionTypes';export*from'@shopgate/pwa-common/constants/Configuration';export*from'@shopgate/pwa-common/constants/Device';export*from'@shopgate/pwa-common/constants/DisplayOptions';export*from'@shopgate/pwa-common/constants/Pipelines';export*from'@shopgate/pwa-common/constants/Portals';// CLIENT CONSTANTS
4
4
  export*from'@shopgate/pwa-common/constants/client';// MENU CONSTANTS
5
5
  export*from'@shopgate/pwa-common/constants/MenuIDs';// MODAL CONSTANTS
6
- export*from'@shopgate/pwa-common/constants/ModalTypes';export{INDEX_PATH,INDEX_PATH_DEEPLINK,LOGIN_PATH};
6
+ export*from'@shopgate/pwa-common/constants/ModalTypes';export{INDEX_PATH,INDEX_PATH_DEEPLINK,LOGIN_PATH};/**
7
+ * Helper constant that can be used as a return value in Redux selectors to prevent
8
+ * unnecessary re-renders.
9
+ */export var EMPTY_OBJECT=Object.freeze({});/**
10
+ * Helper constant that can be used as a return value in Redux selectors to prevent
11
+ * unnecessary re-renders.
12
+ */export var EMPTY_ARRAY=Object.freeze([]);
@@ -43,7 +43,16 @@ export interface ThemeResourcesContextType {
43
43
  * Mapping object that contains all available widgets.
44
44
  * Key is the widget code, value is the widget component.
45
45
  */
46
- widgets: ThemeWidgetMap;
46
+ widgets: {
47
+ /**
48
+ * All available widgets for Widget API v1
49
+ */
50
+ v1: ThemeWidgetMap;
51
+ /**
52
+ * All available widgets for Widget API v2
53
+ */
54
+ v2: ThemeWidgetMap;
55
+ };
47
56
 
48
57
  /**
49
58
  * Mapping object that contains multiple components provided by the theme.
@@ -1,3 +1,3 @@
1
1
  import{createContext}from'react';/**
2
2
  * @typedef {import('./ThemeResourcesContext').ThemeResourcesContextType ThemeResourcesContextType}
3
- */ /** @type {import('react').Context<ThemeResourcesContextType>} */export default createContext({widgets:{},components:{}});
3
+ */ /** @type {import('react').Context<ThemeResourcesContextType>} */export default createContext({widgets:{v1:{},v2:{}},components:{}});
@@ -1,4 +1,4 @@
1
- import{hasWebBridge}from"./bridge";/**
1
+ import{IS_PAGE_PREVIEW_ACTIVE}from'@shopgate/engage/page/constants';import{hasWebBridge}from"./bridge";/**
2
2
  * Checks whether the app shall use a scroll container
3
3
  * @returns {boolean}
4
- */export var useScrollContainer=function useScrollContainer(){return!hasWebBridge();};
4
+ */export var useScrollContainer=function useScrollContainer(){return IS_PAGE_PREVIEW_ACTIVE||!hasWebBridge();};
@@ -12,5 +12,8 @@ function _extends(){_extends=Object.assign||function(target){for(var i=1;i<argum
12
12
  * HOC that injects the `widgets` value of the ThemeResources context as a prop called
13
13
  * `themeWidgets`.
14
14
  * @param {React.ComponentType<any>} WrappedComponent The wrapped component
15
+ * @param {Object} [options={}] Options for the HOC.
16
+ * @param {"v1"|"v2"} [options.version='v1'] The API version of the widgets to return. Can be 'v1'
17
+ * or 'v2'.
15
18
  * @returns {React.FC<any>}
16
- */export var withThemeWidgets=function withThemeWidgets(WrappedComponent){return function ThemeResourcesWrapper(props){var themeWidgets=useThemeWidgets();return React.createElement(WrappedComponent,_extends({},props,{themeWidgets:themeWidgets}));};};
19
+ */export var withThemeWidgets=function withThemeWidgets(WrappedComponent){var options=arguments.length>1&&arguments[1]!==undefined?arguments[1]:{};return function ThemeResourcesWrapper(props){var _options$version=options.version,version=_options$version===void 0?'v1':_options$version;var themeWidgets=useThemeWidgets(version);return React.createElement(WrappedComponent,_extends({},props,{themeWidgets:themeWidgets}));};};
@@ -1 +1 @@
1
- export{default as useLongPress}from"./useLongPress";export{default as useScrollDirectionChange}from"./useScrollDirectionChange";
1
+ export{default as usePressHandler}from"./usePressHandler";export{default as useLongPress}from"./useLongPress";export{default as useScrollDirectionChange}from"./useScrollDirectionChange";
@@ -0,0 +1,38 @@
1
+ import{useCallback}from'react';/**
2
+ * @typedef {Object} PressHandlers
3
+ * @property {Function} onClick - Click event handler.
4
+ * @property {Function} onKeyDown - Keydown handler for Enter/Space.
5
+ */ /**
6
+ * Improves development for accessibility by simplifying registration of multiple
7
+ * listeners (click, Enter, Space) to invoke the a callback when an element is
8
+ * interacted with.
9
+ *
10
+ * @param {Function} onPress Callback to run when the element is interacted with
11
+ * @param {Object} [options] Optional configuration
12
+ * @param {boolean} [options.triggerOnSpace=true] Whether Space triggers onActivate
13
+ * @param {boolean} [options.triggerOnEnter=false] Whether Enter triggers onActivate
14
+ * @returns {PressHandlers} handlers - Event handlers to spread onto an element
15
+ *
16
+ * @example
17
+ * ```js
18
+ * function MyPressableButton({ onActivate }) {
19
+ * // Only Enter will trigger activation; Space is disabled
20
+ * const handlers = usePressHandler(onActivate, {
21
+ * triggerOnEnter: true,
22
+ * triggerOnSpace: false,
23
+ * })
24
+ * //
25
+ * return (
26
+ * <div
27
+ * {...handlers}
28
+ * role="button"
29
+ * tabIndex={0}
30
+ * >
31
+ * Press Me (Enter only)
32
+ * </div>
33
+ * )
34
+ * }
35
+ * ```
36
+ */function usePressHandler(onPress){var options=arguments.length>1&&arguments[1]!==undefined?arguments[1]:{};var _options$triggerOnSpa=options.triggerOnSpace,triggerOnSpace=_options$triggerOnSpa===void 0?true:_options$triggerOnSpa,_options$triggerOnEnt=options.triggerOnEnter,triggerOnEnter=_options$triggerOnEnt===void 0?false:_options$triggerOnEnt;var handleKeyDown=useCallback(function(e){// Check for Enter
37
+ if(triggerOnEnter&&e.key==='Enter'){e.preventDefault();onPress(e);}// Check for Space (may be ' ' or 'Spacebar')
38
+ if(triggerOnSpace&&(e.key===' '||e.key==='Spacebar')){e.preventDefault();onPress(e);}},[onPress,triggerOnEnter,triggerOnSpace]);var handleClick=useCallback(function(e){onPress(e);},[onPress]);return{onClick:handleClick,onKeyDown:handleKeyDown};}export default usePressHandler;
@@ -2,20 +2,21 @@ import{useContext}from'react';import ThemeResourcesContext from"../contexts/Them
2
2
  * @typedef {import('../contexts/ThemeResourcesContext').ThemeResourcesContextType
3
3
  * ThemeResourcesContextType}
4
4
  */ /**
5
- * @typedef {ThemeResourcesContextType['components']} ThemeComponentsType
5
+ * @typedef {import('../contexts/ThemeResourcesContext').ThemeComponentMap ThemeComponentMap}
6
6
  */ /**
7
- * @typedef {ThemeResourcesContextType['widgets']} ThemeWidgetsType
7
+ * @typedef {import('../contexts/ThemeResourcesContext').ThemeWidgetMap ThemeWidgetMap}
8
8
  */ /**
9
9
  * Hook to access to the ThemeResourceContext. The context provides access to different groups
10
10
  * of React components provided by the active theme.
11
11
  * @returns {ThemeResourcesContextType} Value of the ThemeResourceContext
12
12
  */export function useThemeResources(){return useContext(ThemeResourcesContext);}/**
13
13
  * Hook to access the components provided by the ThemeResourceContext
14
- * @returns {ThemeComponentsType} Mapping object that contains multiple components provided by the
14
+ * @returns {ThemeComponentMap} Mapping object that contains multiple components provided by the
15
15
  * theme.
16
16
  * Key is the component name, value is the component
17
17
  */export function useThemeComponents(){var _useThemeResources=useThemeResources(),components=_useThemeResources.components;return components;}/**
18
18
  * Hook to access the widgets provided by the ThemeResourceContext
19
- * @returns {ThemeWidgetsType} Mapping object that contains all available widgets.
19
+ * @param {string} [version='v1'] The version of the widget API to use. Defaults to 'v1'.
20
+ * @returns {ThemeWidgetMap} Mapping object that contains all available widgets.
20
21
  * Key is the widget code, value is the widget component.
21
- */export function useThemeWidgets(){var _useThemeResources2=useThemeResources(),widgets=_useThemeResources2.widgets;return widgets;}
22
+ */export function useThemeWidgets(){var version=arguments.length>0&&arguments[0]!==undefined?arguments[0]:'v1';var _useThemeResources2=useThemeResources(),widgets=_useThemeResources2.widgets;return widgets[version]?widgets[version]:widgets.v1;}
@@ -1,14 +1,18 @@
1
1
  import React,{useMemo}from'react';import PropTypes from'prop-types';import{ThemeContext as LegacyThemeContext}from'@shopgate/pwa-common/context';import{ThemeResourcesContext}from"../contexts";/**
2
- * @typedef {Object<string, React.ComponentType<any>>} ComponentMap
2
+ * @typedef {import('../contexts/ThemeResourcesContext').ThemeComponentMap} ThemeComponentMap
3
+ */ /**
4
+ * @typedef {Object} Widgets
5
+ * @property {ThemeComponentMap} v1 All available widgets for Widget API v1
6
+ * @property {ThemeComponentMap} v2 All available widgets for Widget API v2
3
7
  */ /**
4
8
  * ThemeResourcesProvider component.
5
9
  * @param {Object} props The component props.
6
- * @param {ComponentMap} props.widgets Mapping object with all available widget components for the
10
+ * @param {Widgets} props.widgets Mapping object with all available widget components for the
7
11
  * theme. Key is the widget code, value is the widget component.
8
- * @param {ComponentMap} props.components Object with shared theme components. Can be used by
9
- * extensions the get unified visual presentation.
10
- * @param {ComponentMap} [props.legacyThemeAPI] Object with shared theme components. Can be used by
12
+ * @param {ThemeComponentMap} props.components Object with shared theme components. Can be used by
11
13
  * extensions the get unified visual presentation.
14
+ * @param {ThemeComponentMap} [props.legacyThemeAPI] Object with shared theme components. Can be
15
+ * used by extensions the get unified visual presentation.
12
16
  * Kept for backward compatibility with existing extensions which use the deprecated `ThemeContext`.
13
17
  * @param {React.ReactNode} props.children The component children.
14
18
  * @returns {JSX.Element}
@@ -1,4 +1,4 @@
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{getProductsResult,productIsReady$,productsReceived$,productsReceivedCached$,RECEIVE_PRODUCTS_CACHED,variantDidChange$}from'@shopgate/engage/product';import{ToastProvider,appDidStart$,routeWillEnter$,UIEvents,getCurrentRoute,hex2bin,getThemeSettings,getCurrentSearchQuery,i18n,appWillInit$,appInitialization}from'@shopgate/engage/core';import{cartReceived$,fetchCart,cartDidEnter$,getCartItems}from'@shopgate/engage/cart';import{userDidLogin$}from'@shopgate/engage/user';import{receiveFavoritesWhileVisible$}from'@shopgate/pwa-common-commerce/favorites/streams';import{getFavoritesProductsIds,isFetching}from'@shopgate/pwa-common-commerce/favorites/selectors';import{categoryDidBackEnter$}from'@shopgate/pwa-common-commerce/category/streams';import{searchDidBackEntered$}from'@shopgate/pwa-common-commerce/search/streams';import{hasNewServices}from'@shopgate/engage/core/helpers';import{cookieConsentInitialized$}from'@shopgate/engage/tracking/streams';import{getUserSearch,getStoreFinderSearch,getPreferredLocation,getIsPending,getProductAlternativeLocationParams,getProductAlternativeLocations,makeGetLocation}from"./selectors";import{fetchDefaultLocation,fetchLocations,fetchProductLocations,sendDefaultLocationCode,setPending,setUserGeolocation}from"./actions";import{setShowInventoryInLists,showInventoryInLists}from"./helpers";import fetchInventories from"./actions/fetchInventories";import{EVENT_SET_OPEN}from"./providers/FulfillmentProvider";import fetchProductInventories from"./actions/fetchProductInventories";import{submitReservationSuccess$,userSearchChanged$,storeFinderWillEnter$,preferredLocationDidUpdate$,preferredLocationDidUpdateOnPDP$,provideAlternativeLocation$,preferredLocationDidUpdateGlobalOnWishlist$,storeDetailPageWillEnter$}from"./locations.streams";import selectLocation from"./action-creators/selectLocation";import{NEARBY_LOCATIONS_RADIUS,SET_STORE_FINDER_SEARCH_RADIUS,NEARBY_LOCATIONS_LIMIT}from"./constants";import selectGlobalLocation from"./action-creators/selectGlobalLocation";var initialLocationsResolve;var initialLocationsReject;var initialLocationsPromise=new Promise(function(resolve,reject){initialLocationsResolve=resolve;initialLocationsReject=reject;});/**
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{getProductsResult,productIsReady$,productsReceived$,productsReceivedCached$,RECEIVE_PRODUCTS_CACHED,variantDidChange$}from'@shopgate/engage/product';import{ToastProvider,appDidStart$,routeWillEnter$,UIEvents,getCurrentRoute,hex2bin,getThemeSettings,getCurrentSearchQuery,i18n,appWillInit$,appInitialization}from'@shopgate/engage/core';import{cartReceived$,fetchCart,cartDidEnter$,getCartItems}from'@shopgate/engage/cart';import{userDidLogin$}from'@shopgate/engage/user';import{receiveFavoritesWhileVisible$}from'@shopgate/pwa-common-commerce/favorites/streams';import{getFavoritesProductsIds,isFetching}from'@shopgate/pwa-common-commerce/favorites/selectors';import{categoryDidBackEnter$}from'@shopgate/pwa-common-commerce/category/streams';import{searchDidBackEntered$}from'@shopgate/pwa-common-commerce/search/streams';import{hasNewServices}from'@shopgate/engage/core/helpers';import{cookieConsentInitialized$}from'@shopgate/engage/tracking/streams';import{IS_PAGE_PREVIEW_ACTIVE}from'@shopgate/engage/page/constants';import{getUserSearch,getStoreFinderSearch,getPreferredLocation,getIsPending,getProductAlternativeLocationParams,getProductAlternativeLocations,makeGetLocation}from"./selectors";import{fetchDefaultLocation,fetchLocations,fetchProductLocations,sendDefaultLocationCode,setPending,setUserGeolocation}from"./actions";import{setShowInventoryInLists,showInventoryInLists}from"./helpers";import fetchInventories from"./actions/fetchInventories";import{EVENT_SET_OPEN}from"./providers/FulfillmentProvider";import fetchProductInventories from"./actions/fetchProductInventories";import{submitReservationSuccess$,userSearchChanged$,storeFinderWillEnter$,preferredLocationDidUpdate$,preferredLocationDidUpdateOnPDP$,provideAlternativeLocation$,preferredLocationDidUpdateGlobalOnWishlist$,storeDetailPageWillEnter$}from"./locations.streams";import selectLocation from"./action-creators/selectLocation";import{NEARBY_LOCATIONS_RADIUS,SET_STORE_FINDER_SEARCH_RADIUS,NEARBY_LOCATIONS_LIMIT}from"./constants";import selectGlobalLocation from"./action-creators/selectGlobalLocation";var initialLocationsResolve;var initialLocationsReject;var initialLocationsPromise=new Promise(function(resolve,reject){initialLocationsResolve=resolve;initialLocationsReject=reject;});/**
2
2
  * Sets a location once the location has been validated.
3
3
  * @param {string} locationCode Location code
4
4
  * @param {Function} dispatch Redux dispatch function
@@ -6,7 +6,7 @@ import _regeneratorRuntime from"@babel/runtime/regenerator";function _extends(){
6
6
  */var setLocationOnceAvailable=/*#__PURE__*/function(){var _ref=_asyncToGenerator(/*#__PURE__*/_regeneratorRuntime.mark(function _callee(locationCode,dispatch){var _ref3,initialLocations;return _regeneratorRuntime.wrap(function _callee$(_context){while(1)switch(_context.prev=_context.next){case 0:_context.prev=0;_context.next=3;return initialLocationsPromise;case 3:_ref3=_context.sent;initialLocations=_ref3.locations;if(initialLocations.some(function(l){return l.code===locationCode;})){_context.next=7;break;}return _context.abrupt("return");case 7:dispatch(selectLocation({code:locationCode}));requestAnimationFrame(function(){dispatch(setPending(false));});_context.next=13;break;case 11:_context.prev=11;_context.t0=_context["catch"](0);case 13:case"end":return _context.stop();}},_callee,null,[[0,11]]);}));return function setLocationOnceAvailable(_x,_x2){return _ref.apply(this,arguments);};}();/**
7
7
  * Locations subscriptions.
8
8
  * @param {Function} subscribe The subscribe function.
9
- */function locationsSubscriber(subscribe){subscribe(appWillInit$,function(){appInitialization.set('location',/*#__PURE__*/function(){var _ref5=_asyncToGenerator(/*#__PURE__*/_regeneratorRuntime.mark(function _callee2(_ref4){var dispatch;return _regeneratorRuntime.wrap(function _callee2$(_context2){while(1)switch(_context2.prev=_context2.next){case 0:dispatch=_ref4.dispatch;if(!hasNewServices()){_context2.next=4;break;}_context2.next=4;return dispatch(fetchDefaultLocation());case 4:case"end":return _context2.stop();}},_callee2);}));return function(_x3){return _ref5.apply(this,arguments);};}());});subscribe(preferredLocationDidUpdate$,function(_ref6){var dispatch=_ref6.dispatch,getState=_ref6.getState,action=_ref6.action,events=_ref6.events;var preferredLocation=getPreferredLocation(getState());if(preferredLocation){dispatch(sendDefaultLocationCode(preferredLocation.code));}var _action$location=action.location,location=_action$location===void 0?{}:_action$location,showToast=action.showToast;if(showToast){events.emit(ToastProvider.ADD,{id:'location.changed',message:i18n.text('location.preferredLocationChanged',{storeName:location===null||location===void 0?void 0:location.name})});}});subscribe(cookieConsentInitialized$,/*#__PURE__*/function(){var _ref8=_asyncToGenerator(/*#__PURE__*/_regeneratorRuntime.mark(function _callee3(_ref7){var dispatch,getState,userSearch,_ref10,locations,preferredLocation,code,hasLocation,_ref12,preferredLocationDefault,locationToPreselect;return _regeneratorRuntime.wrap(function _callee3$(_context3){while(1)switch(_context3.prev=_context3.next){case 0:dispatch=_ref7.dispatch,getState=_ref7.getState;if(hasNewServices()){_context3.next=3;break;}return _context3.abrupt("return");case 3:// Fetch merchants locations.
9
+ */function locationsSubscriber(subscribe){subscribe(appWillInit$,function(){appInitialization.set('location',/*#__PURE__*/function(){var _ref5=_asyncToGenerator(/*#__PURE__*/_regeneratorRuntime.mark(function _callee2(_ref4){var dispatch;return _regeneratorRuntime.wrap(function _callee2$(_context2){while(1)switch(_context2.prev=_context2.next){case 0:dispatch=_ref4.dispatch;if(!(hasNewServices()&&!IS_PAGE_PREVIEW_ACTIVE)){_context2.next=4;break;}_context2.next=4;return dispatch(fetchDefaultLocation());case 4:case"end":return _context2.stop();}},_callee2);}));return function(_x3){return _ref5.apply(this,arguments);};}());});subscribe(preferredLocationDidUpdate$,function(_ref6){var dispatch=_ref6.dispatch,getState=_ref6.getState,action=_ref6.action,events=_ref6.events;var preferredLocation=getPreferredLocation(getState());if(preferredLocation){dispatch(sendDefaultLocationCode(preferredLocation.code));}var _action$location=action.location,location=_action$location===void 0?{}:_action$location,showToast=action.showToast;if(showToast){events.emit(ToastProvider.ADD,{id:'location.changed',message:i18n.text('location.preferredLocationChanged',{storeName:location===null||location===void 0?void 0:location.name})});}});subscribe(cookieConsentInitialized$,/*#__PURE__*/function(){var _ref8=_asyncToGenerator(/*#__PURE__*/_regeneratorRuntime.mark(function _callee3(_ref7){var dispatch,getState,userSearch,_ref10,locations,preferredLocation,code,hasLocation,_ref12,preferredLocationDefault,locationToPreselect;return _regeneratorRuntime.wrap(function _callee3$(_context3){while(1)switch(_context3.prev=_context3.next){case 0:dispatch=_ref7.dispatch,getState=_ref7.getState;if(hasNewServices()){_context3.next=3;break;}return _context3.abrupt("return");case 3:// Fetch merchants locations.
10
10
  userSearch=getUserSearch(getState());_context3.prev=4;_context3.next=7;return dispatch(fetchLocations(userSearch));case 7:_ref10=_context3.sent;locations=_ref10.locations;preferredLocation=getPreferredLocation(getState());if(!preferredLocation){_context3.next=16;break;}code=preferredLocation.code;// Check if the preferred location is included within the fetched locations
11
11
  hasLocation=!!locations.find(function(location){return location.code===code;});if(hasLocation){_context3.next=16;break;}_context3.next=16;return dispatch(fetchLocations({codes:[code]}));case 16:// Preset preferredLocation if configured
12
12
  _ref12=getThemeSettings('@shopgate/engage/locations')||{},preferredLocationDefault=_ref12.preferredLocationDefault;if(preferredLocationDefault){// check if there is already a preferredLocation for the user, if not set one
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@shopgate/engage",
3
- "version": "7.27.3-alpha.18",
3
+ "version": "7.27.3-alpha.19",
4
4
  "description": "Shopgate's ENGAGE library.",
5
5
  "license": "Apache-2.0",
6
6
  "author": "Shopgate <support@shopgate.com>",
@@ -15,13 +15,14 @@
15
15
  "connect"
16
16
  ],
17
17
  "dependencies": {
18
+ "@emotion/react": "^11.14.0",
18
19
  "@shopgate/native-modules": "1.0.0-beta.25",
19
- "@shopgate/pwa-common": "7.27.3-alpha.18",
20
- "@shopgate/pwa-common-commerce": "7.27.3-alpha.18",
21
- "@shopgate/pwa-core": "7.27.3-alpha.18",
22
- "@shopgate/pwa-ui-ios": "7.27.3-alpha.18",
23
- "@shopgate/pwa-ui-material": "7.27.3-alpha.18",
24
- "@shopgate/pwa-ui-shared": "7.27.3-alpha.18",
20
+ "@shopgate/pwa-common": "7.27.3-alpha.19",
21
+ "@shopgate/pwa-common-commerce": "7.27.3-alpha.19",
22
+ "@shopgate/pwa-core": "7.27.3-alpha.19",
23
+ "@shopgate/pwa-ui-ios": "7.27.3-alpha.19",
24
+ "@shopgate/pwa-ui-material": "7.27.3-alpha.19",
25
+ "@shopgate/pwa-ui-shared": "7.27.3-alpha.19",
25
26
  "@stripe/react-stripe-js": "^1.16.5",
26
27
  "@stripe/stripe-js": "^1.3.1",
27
28
  "@virtuous/conductor": "~2.5.0",
@@ -40,6 +41,7 @@
40
41
  "react-phone-number-input": "^3.2.16",
41
42
  "react-player": "1.11.0",
42
43
  "react-portal": "^3.1.0",
44
+ "tss-react": "^4.9.18",
43
45
  "validate.js": "^0.13.1"
44
46
  },
45
47
  "devDependencies": {
@@ -0,0 +1,22 @@
1
+ import{REQUEST_PAGE_CONFIG_V2,RECEIVE_PAGE_CONFIG_V2,ERROR_PAGE_CONFIG_V2}from"../constants";/**
2
+ * @typedef {'cms' | 'category'} PageType
3
+ */ /**
4
+ * Creates the dispatched REQUEST_PAGE_CONFIG_V2 action object.
5
+ * @param {Object} params The action params
6
+ * @param {PageType} params.type The type of the page.
7
+ * @param {string} [params.slug=null] The slug of the page (optional).
8
+ * @returns {Object} The dispatched action object.
9
+ */export var requestPageConfigV2=function requestPageConfigV2(_ref){var type=_ref.type,_ref$slug=_ref.slug,slug=_ref$slug===void 0?null:_ref$slug;return{type:REQUEST_PAGE_CONFIG_V2,pageType:type,pageSlug:slug};};/**
10
+ * Creates the dispatched RECEIVE_PAGE_CONFIG_V2 action object.
11
+ * @param {Object} params The action params
12
+ * @param {PageType} params.type The type of the page.
13
+ * @param {Object} params.data The page data
14
+ * @param {string} [params.slug=null] The slug of the page (optional).
15
+ * @returns {Object} The dispatched action object.
16
+ */export var receivePageConfigV2=function receivePageConfigV2(_ref2){var type=_ref2.type,data=_ref2.data,_ref2$slug=_ref2.slug,slug=_ref2$slug===void 0?null:_ref2$slug;return{type:RECEIVE_PAGE_CONFIG_V2,pageType:type,pageSlug:slug,data:data};};/**
17
+ * Creates the dispatched ERROR_PAGE_CONFIG_V2 action object.
18
+ * @param {Object} params The action params
19
+ * @param {PageType} params.type The type of the page.
20
+ * @param {string} [params.slug=null] The slug of the page (optional).
21
+ * @returns {Object} The dispatched action object.
22
+ */export var errorPageConfigV2=function errorPageConfigV2(_ref3){var type=_ref3.type,_ref3$slug=_ref3.slug,slug=_ref3$slug===void 0?null:_ref3$slug;return{type:ERROR_PAGE_CONFIG_V2,pageType:type,pageSlug:slug};};
@@ -0,0 +1,51 @@
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 React,{useState,useRef,useEffect,useCallback}from'react';import PropTypes from'prop-types';import{makeStyles,keyframes,colorToRgba}from'@shopgate/engage/styles';import{useRoute}from'@shopgate/engage/core/hooks';import{getScrollContainer}from"./helpers";import{useWidgetPreviewEvent}from"./events";import{useWidgetsPreview}from"./hooks";/**
2
+ * @typedef {Object} OverlayStyle
3
+ * @property {number} top Style for the top position of the overlay.
4
+ * @property {number} left Style for the left position of the overlay.
5
+ * @property {number} width Style for the width of the overlay.
6
+ * @property {number} height Style for the height of the overlay.
7
+ */ /**
8
+ * @typedef {Object} MarginOverlayStyles
9
+ * @property {OverlayStyle} top Style for the top margin overlay.
10
+ * @property {OverlayStyle} left Style for the left margin overlay.
11
+ * @property {OverlayStyle} bottom Style for the bottom margin overlay.
12
+ * @property {OverlayStyle} right Style for the right margin overlay.
13
+ */var useStyles=makeStyles({name:'WidgetPreviewOverlay'})(function(_,_ref){var highlightColor=_ref.highlightColor,overlayBorderColor=_ref.overlayBorderColor,marginOverlayColor=_ref.marginOverlayColor,isFlashing=_ref.isFlashing;return{root:{},mainOverlay:_extends({position:'absolute',pointerEvents:'none',zIndex:10,boxShadow:'0 0 8px 2px rgba(34, 42, 69, 0.07)',outline:"1px solid ".concat(overlayBorderColor||'#50A9AD')},isFlashing&&{animationName:keyframes({'0%':{backgroundColor:'transparent'},'50%':{backgroundColor:colorToRgba(highlightColor||'#50A9AD',0.5)},'100%':{backgroundColor:'transparent'}}),animationDuration:'0.5s',animationTimingFunction:'ease-in-out',animationFillMode:'forwards'}),marginOverlay:{position:'absolute',backgroundColor:colorToRgba(marginOverlayColor||'#50A9AD',0.1),pointerEvents:'none',zIndex:9}};});/**
14
+ * The Overlay component is used to highlight the active widget when preview mode is active.
15
+ * It also visualizes the margins of the widget and the borders to its sibling widgets.
16
+ * @param {Object} props The component props.
17
+ * @param {React.Ref<HTMLDivElement>} props.containerRef The reference to the container element that
18
+ * holds the widgets.
19
+ * @returns {JSX.Element|null}
20
+ */var Overlay=function Overlay(_ref2){var containerRef=_ref2.containerRef;var _useRoute=useRoute(),_useRoute$query=_useRoute.query,highlightColor=_useRoute$query.highlightColor,overlayBorderColor=_useRoute$query.overlayBorderColor,marginOverlayColor=_useRoute$query.marginOverlayColor;var _useWidgetsPreview=useWidgetsPreview(),activeWidget=_useWidgetsPreview.activeWidget;/**
21
+ * State to hold the style for the main overlay that highlights the active widget.
22
+ * @type {[OverlayStyle|null, React.Dispatch<React.SetStateAction<OverlayStyle|null>>]}
23
+ */var _useState=useState(null),_useState2=_slicedToArray(_useState,2),mainOverlayStyle=_useState2[0],setMainOverlayStyle=_useState2[1];/**
24
+ * State to hold the styles for the margin overlays that visualize the widget margins.
25
+ * @type {[MarginOverlayStyles|null,
26
+ * React.Dispatch<React.SetStateAction<MarginOverlayStyles|null>>]}
27
+ */var _useState3=useState(null),_useState4=_slicedToArray(_useState3,2),marginOverlays=_useState4[0],setMarginOverlays=_useState4[1];var _useState5=useState(false),_useState6=_slicedToArray(_useState5,2),isFlashing=_useState6[0],setIsFlashing=_useState6[1];var _useStyles=useStyles({highlightColor:highlightColor,overlayBorderColor:overlayBorderColor,marginOverlayColor:marginOverlayColor,isFlashing:isFlashing}),classes=_useStyles.classes;/**
28
+ * @type {import('react').MutableRefObject<ResizeObserver|null>}
29
+ */var resizeRef=useRef(null);/**
30
+ * @type {import('react').MutableRefObject<MutationObserver|null>}
31
+ */var mutationRef=useRef(null);/**
32
+ * Callback to update the overlay position, margin overlays and size based on the active widget.
33
+ */var updateOverlay=useCallback(function(){if(!containerRef.current||!activeWidget){return;}var target=containerRef.current.querySelector("#widget-code-".concat(activeWidget));if(!target){setMainOverlayStyle(null);return;}var scrollContainer=getScrollContainer();// Get the computed styles of the active widget to calculate margins
34
+ var styles=window.getComputedStyle(target);var marginLeft=parseFloat(styles.marginLeft);var marginRight=parseFloat(styles.marginRight);var marginTop=parseFloat(styles.marginTop);var marginBottom=parseFloat(styles.marginBottom);// Get bounding rectangles for the target widget and the scroll container
35
+ var elementRect=target.getBoundingClientRect();var containerRect=scrollContainer.getBoundingClientRect();var baseTop=elementRect.top-containerRect.top+scrollContainer.scrollTop;var baseLeft=elementRect.left-containerRect.left+scrollContainer.scrollLeft;var top=baseTop;var left=baseLeft-marginLeft;var width=target.offsetWidth+marginLeft+marginRight;var height=target.offsetHeight;// Keep a backdoor to re-enable overlay outline inside the widget margins
36
+ var mainOverlayBordersOnMarginEdges=true;var mainTop=baseTop-(mainOverlayBordersOnMarginEdges?marginTop:0);var mainHeight=height+(mainOverlayBordersOnMarginEdges?marginTop+marginBottom:0);setMainOverlayStyle({top:mainTop+1,left:left,width:width,height:mainHeight-2});setMarginOverlays({top:{top:top-marginTop,left:left,width:width,height:marginTop},bottom:{top:top+height,left:left,width:width,height:marginBottom},left:{top:top,left:left,width:marginLeft,height:height},right:{top:top,left:left+width-marginRight,width:marginRight,height:height}});},[activeWidget,containerRef]);// Effect to setup observers that watch for changes in the container and its children.
37
+ // Needed to update the overlay style when the layout changes.
38
+ useEffect(function(){var containerEl=containerRef.current;if(!containerEl)return undefined;// Create a ResizeObserver to watch for size changes of children
39
+ resizeRef.current=new ResizeObserver(function(){// Whenever any observed child resizes, update overlay
40
+ updateOverlay();});// Observe all existing children
41
+ Array.from(containerEl.children).forEach(function(child){if(child.nodeType===Node.ELEMENT_NODE){resizeRef.current.observe(child);}});// Create one MutationObserver on the container to watch for changes in the DOM
42
+ mutationRef.current=new MutationObserver(function(mutations){// eslint-disable-next-line no-restricted-syntax
43
+ var _iteratorNormalCompletion=true;var _didIteratorError=false;var _iteratorError=undefined;try{for(var _iterator=mutations[Symbol.iterator](),_step;!(_iteratorNormalCompletion=(_step=_iterator.next()).done);_iteratorNormalCompletion=true){var mutation=_step.value;if(mutation.type==='childList'){// Handle newly added nodes - observe them for size changes
44
+ mutation.addedNodes.forEach(function(node){if(node.nodeType===Node.ELEMENT_NODE){resizeRef.current.observe(node);}});// Handle removed nodes - remove them from observation
45
+ mutation.removedNodes.forEach(function(node){if(node.nodeType===Node.ELEMENT_NODE){resizeRef.current.unobserve(node);}});// If children were added/removed, recalculate overlay position
46
+ updateOverlay();}else if(mutation.type==='attributes'&&(mutation.attributeName==='class'||mutation.attributeName==='style')){// Update overlay if the class or style of a child changes
47
+ if(mutation.target.parentElement===containerEl){updateOverlay();}}}}catch(err){_didIteratorError=true;_iteratorError=err;}finally{try{if(!_iteratorNormalCompletion&&_iterator["return"]!=null){_iterator["return"]();}}finally{if(_didIteratorError){throw _iteratorError;}}}});// Start observing:
48
+ // - childList:true → to catch added/removed children
49
+ // - subtree:true + attributes:true → to catch any class/style changes in descendants
50
+ mutationRef.current.observe(containerEl,{childList:true,subtree:true,attributes:true,attributeFilter:['class','style']});// Cleanup on unmount or if updateOverlay changes:
51
+ return function(){if(resizeRef.current){resizeRef.current.disconnect();resizeRef.current=null;}if(mutationRef.current){mutationRef.current.disconnect();mutationRef.current=null;}};},[containerRef,updateOverlay]);useWidgetPreviewEvent('highlight-widget',function(){setIsFlashing(true);});var handleAnimationEnd=useCallback(function(){setIsFlashing(false);},[]);if(!mainOverlayStyle)return null;return React.createElement("div",{className:classes.root},React.createElement("div",{className:classes.mainOverlay,style:mainOverlayStyle,onAnimationEnd:handleAnimationEnd}),marginOverlays&&Object.entries(marginOverlays).map(function(_ref3){var _ref4=_slicedToArray(_ref3,2),key=_ref4[0],overlayStyle=_ref4[1];return React.createElement("div",{key:key,className:classes.marginOverlay,style:overlayStyle});}));};export default Overlay;
@@ -0,0 +1,22 @@
1
+ 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;}import React,{useState,useRef,useEffect}from'react';import ReactDOM from'react-dom';import PropTypes from'prop-types';import{makeStyles}from'@shopgate/engage/styles';var useStyles=makeStyles()(function(){return{wrapper:{display:'inline-block',position:'relative',cursor:'help'},tooltipBox:{position:'absolute',padding:'6px 10px',backgroundColor:'rgba(0, 0, 0, 0.87)',color:'#fff',fontSize:'0.875rem',fontWeight:400,borderRadius:'4px',whiteSpace:'normal',// allow multiline
2
+ wordBreak:'break-word',maxWidth:'200px',zIndex:1000,pointerEvents:'none',opacity:0,transform:'scale(0.9)',transition:'opacity 0.1s ease-in-out, transform 0.1s ease-in-out','&[data-visible="true"]':{opacity:1,transform:'scale(1)'}},arrowTop:{'&::before':{content:"''",position:'absolute',bottom:'-6px',left:'var(--arrow-left, 50%)',transform:'translateX(-50%)',borderWidth:'6px 6px 0 6px',borderStyle:'solid',borderColor:'rgba(0, 0, 0, 0.87) transparent transparent transparent'}},arrowBottom:{'&::before':{content:"''",position:'absolute',top:'-6px',left:'var(--arrow-left, 50%)',transform:'translateX(-50%) rotate(180deg)',borderWidth:'6px 6px 0 6px',borderStyle:'solid',borderColor:'rgba(0, 0, 0, 0.87) transparent transparent transparent'}}};});/**
3
+ * AI generated Tooltip component to display additional information on hover.
4
+ * @param {Object} props The component props.
5
+ * @param {React.ReactNode} props.children The child elements to wrap.
6
+ * @param {string} props.text The tooltip text to display.
7
+ * @returns {JSX.Element}
8
+ */function Tooltip(_ref){var children=_ref.children,text=_ref.text;var _useStyles=useStyles(),classes=_useStyles.classes,cx=_useStyles.cx;var wrapperRef=useRef(null);var _useState=useState(false),_useState2=_slicedToArray(_useState,2),visible=_useState2[0],setVisible=_useState2[1];var _useState3=useState(false),_useState4=_slicedToArray(_useState3,2),mounted=_useState4[0],setMounted=_useState4[1];var _useState5=useState(false),_useState6=_slicedToArray(_useState5,2),animate=_useState6[0],setAnimate=_useState6[1];var _useState7=useState({left:0,top:0}),_useState8=_slicedToArray(_useState7,2),coords=_useState8[0],setCoords=_useState8[1];var _useState9=useState(null),_useState10=_slicedToArray(_useState9,2),arrowLeft=_useState10[0],setArrowLeft=_useState10[1];var _useState11=useState('top'),_useState12=_slicedToArray(_useState11,2),positionState=_useState12[0],setPositionState=_useState12[1];// 'top' or 'bottom'
9
+ var tooltipId=useRef(Math.random().toString(36).slice(2,11));// Handle mounting/unmounting and trigger fade animation
10
+ useEffect(function(){var timeoutId;if(visible){setMounted(true);// allow DOM to insert before starting the fade-in
11
+ timeoutId=setTimeout(function(){return setAnimate(true);},10);}else{setAnimate(false);// after fade-out duration, unmount
12
+ timeoutId=setTimeout(function(){return setMounted(false);},200);}return function(){return clearTimeout(timeoutId);};},[visible]);// Compute position, flipping if needed, when mounted
13
+ useEffect(function(){if(!mounted||!wrapperRef.current)return;var wrapperRect=wrapperRef.current.getBoundingClientRect();var selector=".tooltip-box[data-tooltip-id=\"".concat(tooltipId.current,"\"]");var tooltipEl=document.querySelector(selector);if(!tooltipEl)return;var ttRect=tooltipEl.getBoundingClientRect();var margin=8;var vw=window.innerWidth;var vh=window.innerHeight;// 1) Try "top" placement
14
+ var left=wrapperRect.left+wrapperRect.width/2-ttRect.width/2;var top=wrapperRect.top-ttRect.height-8;// Clamp horizontal even before deciding flip, to calculate arrow offset
15
+ if(left<margin){left=margin;}else if(left+ttRect.width>vw-margin){left=vw-ttRect.width-margin;}// If top would be too high (tooltip clipped), switch to "bottom"
16
+ var finalPosition='top';if(top<margin){// try bottom
17
+ var bottomTop=wrapperRect.bottom+8;if(bottomTop+ttRect.height<=vh-margin){finalPosition='bottom';top=bottomTop;}else{// can't fit fully in bottom either; clamp top to margin
18
+ top=margin;}}// If using "top", ensure vertical clamp if it goes off bottom
19
+ if(finalPosition==='top'){if(top+ttRect.height>vh-margin){top=vh-ttRect.height-margin;}}// If using "bottom", clamp bottom if it would go off bottom
20
+ if(finalPosition==='bottom'){if(top+ttRect.height>vh-margin){top=vh-ttRect.height-margin;}}// 2) Compute arrow offset so it points to wrapper’s center X
21
+ var wrapperCenterX=wrapperRect.left+wrapperRect.width/2;var computedArrowLeft=wrapperCenterX-left;// Clamp arrow within [6px, ttRect.width - 6px]
22
+ var minArrow=6;var maxArrow=ttRect.width-6;if(computedArrowLeft<minArrow){computedArrowLeft=minArrow;}else if(computedArrowLeft>maxArrow){computedArrowLeft=maxArrow;}setPositionState(finalPosition);setCoords({left:left,top:top});setArrowLeft(computedArrowLeft);},[mounted]);if(!text){return children;}var portalStyle=_extends({left:"".concat(coords.left,"px"),top:"".concat(coords.top,"px")},arrowLeft!==null?{'--arrow-left':"".concat(arrowLeft,"px")}:{});var arrowClass=positionState==='top'?classes.arrowTop:classes.arrowBottom;return React.createElement("span",{className:classes.wrapper,ref:wrapperRef,"data-tooltip-id":tooltipId.current,onMouseEnter:function onMouseEnter(){return setVisible(true);},onMouseLeave:function onMouseLeave(){return setVisible(false);}},children,mounted&&ReactDOM.createPortal(React.createElement("div",{className:cx(classes.tooltipBox,arrowClass,'tooltip-box'),style:portalStyle,"data-visible":animate?'true':'false',"data-tooltip-id":tooltipId.current,dangerouslySetInnerHTML:{__html:text}}),document.body));}Tooltip.defaultProps={text:null};export default Tooltip;
@@ -0,0 +1,15 @@
1
+ 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 _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,{Suspense,useCallback}from'react';import PropTypes from'prop-types';import{makeStyles}from'@shopgate/engage/styles';import{VisibilityOffIcon,TimeIcon,Loading}from'@shopgate/engage/components';import{usePressHandler}from'@shopgate/engage/core/hooks';import WidgetProvider from"./WidgetProvider";import{dispatchWidgetPreviewEvent}from"./events";import{useWidgetsPreview}from"./hooks";import Tooltip from"./Tooltip";var useStyles=makeStyles()(function(theme,_ref){var marginTop=_ref.marginTop,marginLeft=_ref.marginLeft;return{root:{position:'relative'},widgetInfo:{zIndex:12,position:'absolute',top:-marginTop+(theme.spacing(0.5)+1),left:-marginLeft+theme.spacing(0.5),fontSize:24,padding:theme.spacing(0.5),display:'flex',gap:theme.spacing(1),background:'#fff',borderRadius:4,border:'1px solid rgba(0, 0, 0, 0.23)',':empty':{display:'none'}},preview:{cursor:'pointer'},visibilityIcon:{color:'#f44336'},scheduledIcon:{color:'#347DD3'},scheduledIconExpired:{color:'#f44336'}};});/**
2
+ * @typedef {import('./types').WidgetDefinition} WidgetDefinition
3
+ */ /**
4
+ * @typedef {import('./types').ScheduledStatus} ScheduledStatus
5
+ */ /**
6
+ * The Widget component.
7
+ * @param {Object} props The component props.
8
+ * @param {React.ComponentType} props.component The widget component to render.
9
+ * @param {WidgetDefinition} props.definition The widget definition data.
10
+ * @param {boolean} props.isPreview Whether the widget is in preview mode.
11
+ * @returns {JSX.Element}
12
+ */var Widget=function Widget(_ref2){var _ref3,_definition$layout,_ref4,_definition$layout2,_ref5,_definition$layout3,_ref6,_definition$layout4,_definition$layout5,_definition$layout6,_definition$layout7,_definition$layout8,_definition$meta,_definition$meta$sche,_definition$meta2,_definition$meta2$sch,_definition$meta3,_definition$meta3$sch,_definition$meta4,_definition$meta4$hid,_definition$meta5,_definition$meta5$hid;var Component=_ref2.component,definition=_ref2.definition,isPreview=_ref2.isPreview;var _useStyles=useStyles({marginTop:(_ref3=definition===null||definition===void 0?void 0:(_definition$layout=definition.layout)===null||_definition$layout===void 0?void 0:_definition$layout.marginTop)!==null&&_ref3!==void 0?_ref3:0,marginBottom:(_ref4=definition===null||definition===void 0?void 0:(_definition$layout2=definition.layout)===null||_definition$layout2===void 0?void 0:_definition$layout2.marginBottom)!==null&&_ref4!==void 0?_ref4:0,marginLeft:(_ref5=definition===null||definition===void 0?void 0:(_definition$layout3=definition.layout)===null||_definition$layout3===void 0?void 0:_definition$layout3.marginLeft)!==null&&_ref5!==void 0?_ref5:0,marginRight:(_ref6=definition===null||definition===void 0?void 0:(_definition$layout4=definition.layout)===null||_definition$layout4===void 0?void 0:_definition$layout4.marginRight)!==null&&_ref6!==void 0?_ref6:0}),classes=_useStyles.classes,cx=_useStyles.cx;var _useWidgetsPreview=useWidgetsPreview(),setActiveWidget=_useWidgetsPreview.setActiveWidget,activeWidget=_useWidgetsPreview.activeWidget;// Handle clicks on the widget container in preview mode. Take care that highlighting only happens
13
+ // when the widget is not already active, otherwise it would be confusing when users want to
14
+ // interact with widget elements.
15
+ var handleInteraction=useCallback(function(){setActiveWidget(definition.code,activeWidget!==definition.code);if(activeWidget!==definition.code){dispatchWidgetPreviewEvent('widget-clicked',definition.code);}},[activeWidget,definition.code,setActiveWidget]);var handlers=usePressHandler(handleInteraction);if(!Component){return null;}return React.createElement("section",_extends({id:"widget-code-".concat(definition.code),className:cx(classes.root,_defineProperty({},classes.preview,isPreview)),style:{marginTop:definition===null||definition===void 0?void 0:(_definition$layout5=definition.layout)===null||_definition$layout5===void 0?void 0:_definition$layout5.marginTop,marginBottom:definition===null||definition===void 0?void 0:(_definition$layout6=definition.layout)===null||_definition$layout6===void 0?void 0:_definition$layout6.marginBottom,marginLeft:definition===null||definition===void 0?void 0:(_definition$layout7=definition.layout)===null||_definition$layout7===void 0?void 0:_definition$layout7.marginLeft,marginRight:definition===null||definition===void 0?void 0:(_definition$layout8=definition.layout)===null||_definition$layout8===void 0?void 0:_definition$layout8.marginRight},"data-widget-name":definition.widgetConfigDefinitionCode},isPreview&&_extends({},handlers)),isPreview&&(definition===null||definition===void 0?void 0:definition.meta)&&React.createElement("div",{className:classes.widgetInfo},((_definition$meta=definition.meta)===null||_definition$meta===void 0?void 0:(_definition$meta$sche=_definition$meta.scheduled)===null||_definition$meta$sche===void 0?void 0:_definition$meta$sche.isScheduled)&&React.createElement(Tooltip,{text:(_definition$meta2=definition.meta)===null||_definition$meta2===void 0?void 0:(_definition$meta2$sch=_definition$meta2.scheduled)===null||_definition$meta2$sch===void 0?void 0:_definition$meta2$sch.tooltip},React.createElement(TimeIcon,{className:cx(classes.scheduledIcon,_defineProperty({},classes.scheduledIconExpired,(_definition$meta3=definition.meta)===null||_definition$meta3===void 0?void 0:(_definition$meta3$sch=_definition$meta3.scheduled)===null||_definition$meta3$sch===void 0?void 0:_definition$meta3$sch.isExpired))})),((_definition$meta4=definition.meta)===null||_definition$meta4===void 0?void 0:(_definition$meta4$hid=_definition$meta4.hidden)===null||_definition$meta4$hid===void 0?void 0:_definition$meta4$hid.isHidden)&&React.createElement(Tooltip,{text:(_definition$meta5=definition.meta)===null||_definition$meta5===void 0?void 0:(_definition$meta5$hid=_definition$meta5.hidden)===null||_definition$meta5$hid===void 0?void 0:_definition$meta5$hid.tooltip},React.createElement(VisibilityOffIcon,{className:classes.visibilityIcon}))),React.createElement(WidgetProvider,{definition:definition,isPreview:isPreview},React.createElement(Suspense,{fallback:React.createElement(Loading,null)},React.createElement(Component,null))));};export default Widget;
@@ -0,0 +1,42 @@
1
+ import { type Context } from 'react';
2
+ import {
3
+ type WidgetDefinitionLayout,
4
+ type WidgetDefinitionVisibility,
5
+ type WidgetDefinition,
6
+ } from './types'
7
+
8
+ export { WidgetDefinition } from './types';
9
+
10
+ export interface WidgetContextType<C = Record<string, any>> {
11
+ /**
12
+ * The unique code of the widget instance
13
+ */
14
+ code: string;
15
+ /**
16
+ * The name of the widget
17
+ */
18
+ name: string;
19
+ /**
20
+ * The widget configuration
21
+ */
22
+ config: C;
23
+ /**
24
+ * The widget layout settings
25
+ */
26
+ layout: WidgetDefinitionLayout;
27
+ /**
28
+ * The widget visibility settings
29
+ */
30
+ visibility: WidgetDefinitionVisibility;
31
+ /**
32
+ * Whether the widget is rendered in preview mode
33
+ */
34
+ isPreview: boolean;
35
+ }
36
+
37
+ /**
38
+ * React context for widgets.
39
+ */
40
+ declare const WidgetContext: Context<WidgetContextType>;
41
+
42
+ export default WidgetContext;
@@ -0,0 +1,9 @@
1
+ import{createContext}from'react';/**
2
+ * @typedef {import('./Widgets.jsx').WidgetDefinition} WidgetDefinition
3
+ */ /**
4
+ * @typedef {Object} WidgetContextType
5
+ * @property {WidgetDefinition['code']} code The unique widget code.
6
+ * @property {WidgetDefinition['widgetConfig']} config The widget configuration.
7
+ * @property {WidgetDefinition['layout']} layout The widget layout settings.
8
+ * @property {WidgetDefinition['visibility']} visibility The widget visibility settings.
9
+ */ /** @type {React.Context<WidgetContextType>} */export var WidgetContext=createContext({});
@@ -0,0 +1,8 @@
1
+ import React,{useMemo}from'react';import PropTypes from'prop-types';import{WidgetContext}from"./WidgetContext";/** @typedef {import('./WidgetContext').WidgetContextType} WidgetContextType */ /** @typedef {import('./WidgetContext').WidgetDefinition} WidgetDefinition */ /**
2
+ * The WidgetProvider component provides the context for a single widget.
3
+ * @param {Object} props The component props.
4
+ * @param {WidgetDefinition} props.definition The widget definition data.
5
+ * @param {boolean} props.isPreview Whether the widget is in preview mode.
6
+ * @param {React.ReactNode} props.children The child components to render.
7
+ * @returns {JSX.Element}
8
+ */var WidgetProvider=function WidgetProvider(_ref){var children=_ref.children,definition=_ref.definition,isPreview=_ref.isPreview;/** @type {WidgetContextType} */var value=useMemo(function(){var widgetConfig=definition.widgetConfig,layout=definition.layout,visibility=definition.visibility,code=definition.code,widgetConfigDefinitionCode=definition.widgetConfigDefinitionCode;return{code:code,name:widgetConfigDefinitionCode,config:widgetConfig,layout:layout,visibility:visibility,isPreview:isPreview};},[definition,isPreview]);return React.createElement(WidgetContext.Provider,{value:value},children);};export default WidgetProvider;
@@ -0,0 +1,11 @@
1
+ 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,{useMemo,useRef}from'react';import PropTypes from'prop-types';import{makeStyles}from'@shopgate/engage/styles';import{useRoute,useThemeWidgets}from'@shopgate/engage/core/hooks';import{PAGE_PREVIEW_PATTERN}from'@shopgate/engage/page/constants';import{ConditionalWrapper}from'@shopgate/engage/components';import WidgetsPreviewProvider from"./WidgetsPreviewProvider";import Widget from"./Widget";import Overlay from"./Overlay";import{usePreviewIframeCommunication}from"./hooks";/**
2
+ * @typedef {import('./types').WidgetDefinition} WidgetDefinition
3
+ */var PLACEHOLDER_COMPONENT='@shopgate/widgetsInternal/Placeholder';var useStyles=makeStyles()({preview:{'& *':{scrollbarWidth:'thin'}}});/**
4
+ * The Widgets component renders a list of widgets.
5
+ * @param {Object} props The component props.
6
+ * @param {Array<WidgetDefinition>} props.widgets The list of widgets to render.
7
+ * @returns {JSX.Element}
8
+ */var Widgets=function Widgets(_ref){var _ref$widgets=_ref.widgets,widgetsProp=_ref$widgets===void 0?[]:_ref$widgets;var _useStyles=useStyles(),classes=_useStyles.classes,cx=_useStyles.cx;var _useRoute=useRoute(),pattern=_useRoute.pattern;var widgetsRef=useRef(null);var isPreview=pattern===PAGE_PREVIEW_PATTERN;var widgetComponents=useThemeWidgets('v2');usePreviewIframeCommunication(isPreview);// Create sanitized widgets array that only includes widgets with valid components.
9
+ var widgets=useMemo(function(){if(isPreview){// All widgets are allowed in preview mode.
10
+ return widgetsProp;}// Remove widgets that do not have a valid component.
11
+ return widgetsProp.filter(function(widget){return!!widgetComponents[widget.widgetConfigDefinitionCode];});},[isPreview,widgetComponents,widgetsProp]);if(!Array.isArray(widgets)||widgets.length===0){return null;}return React.createElement(ConditionalWrapper,{condition:isPreview,wrapper:function wrapper(children){return React.createElement(WidgetsPreviewProvider,null,children,React.createElement(Overlay,{containerRef:widgetsRef}));}},React.createElement("div",{className:cx('engage__widgets',_defineProperty({},classes.preview,isPreview)),ref:widgetsRef},widgets.map(function(widget){var component=widgetComponents[widget.widgetConfigDefinitionCode]||widgetComponents[PLACEHOLDER_COMPONENT];return React.createElement(Widget,{key:widget.code,definition:widget,isPreview:isPreview,component:component});})));};Widgets.defaultProps={widgets:null};export default Widgets;
@@ -0,0 +1,9 @@
1
+ import _noop from"lodash/noop";import{createContext}from'react';/**
2
+ * @callback SetActiveWidget
3
+ * @param {string} code The code of the widget to set as active.
4
+ * @param {boolean} [highlight=false] Whether to highlight the widget after setting it as active.
5
+ */ /**
6
+ * @typedef {Object} WidgetsPreviewContextType
7
+ * @property {string} activeWidget The code of the currently active widget.
8
+ * @property {SetActiveWidget} setActiveWidget A function to set the active widget code
9
+ */ /** @type {React.Context<WidgetsPreviewContextType>} */export var WidgetsPreviewContext=createContext({activeWidget:null,setActiveWidget:_noop});
@@ -0,0 +1,8 @@
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;}import React,{useMemo,useState,useCallback}from'react';import PropTypes from'prop-types';import{useWidgetPreviewEvent,dispatchWidgetPreviewEvent}from"./events";import{WidgetsPreviewContext}from"./WidgetsPreviewContext";/**
2
+ * The WidgetsPreviewProvider component is used by the Widgets component when it's rendered
3
+ * in preview mode. It provides functionality for the Widget component that's needed when
4
+ * the widgets are rendered in the preview iframe.
5
+ * @param {Object} props The component props.
6
+ * @param {React.ReactNode} props.children The child components to render.
7
+ * @returns {JSX.Element}
8
+ */var WidgetsPreviewProvider=function WidgetsPreviewProvider(_ref){var children=_ref.children;var _useState=useState(null),_useState2=_slicedToArray(_useState,2),activeWidget=_useState2[0],setActiveWidget=_useState2[1];useWidgetPreviewEvent('set-active-widget-id',function(e){setActiveWidget(e.detail.widgetCode);});var handleSetActiveWidget=useCallback(function(code){var highlight=arguments.length>1&&arguments[1]!==undefined?arguments[1]:false;setActiveWidget(code);if(highlight){dispatchWidgetPreviewEvent('highlight-widget',code);}},[]);var value=useMemo(function(){return{activeWidget:activeWidget,setActiveWidget:handleSetActiveWidget};},[activeWidget,handleSetActiveWidget]);return React.createElement(WidgetsPreviewContext.Provider,{value:value},children);};export default WidgetsPreviewProvider;
@@ -0,0 +1,4 @@
1
+ /**
2
+ * List of allowed origins for cms page preview iFrame communication.
3
+ */export var ALLOWED_PAGE_PREVIEW_ORIGINS=['https://next.admin.shopgatedev.com','https://next.admin.shopgatepg.com','https://next.admin.shopgate.com','https://next.us.admin.shopgate.com','http://localhost:1337'];// Whether to consider vertical margins when calculating the overlay position.
4
+ export var CONSIDER_CONTAINER_MARGINS_ON_SCROLL_DEFAULT=false;
@@ -0,0 +1,23 @@
1
+ import{useEffect}from'react';/**
2
+ * @typedef {"highlight-widget"|"widget-clicked"|"set-active-widget-id"} WidgetPreviewEventName
3
+ */ /**
4
+ * @typedef {Object} WidgetPreviewEventDetail
5
+ * @property {string} widgetCode The code of the widget related to the event.
6
+ * @property {any} [payload] Optional payload data related to the event.
7
+ */ /**
8
+ * @callback WidgetPreviewEventHandler
9
+ * @param {CustomEvent<WidgetPreviewEventDetail>} event The custom event dispatched for the widget
10
+ * preview.
11
+ */ /**
12
+ * Hook to listen for widget preview events.
13
+ * These events are dispatched in the context of iFrame communication at the widget preview.
14
+ * @param {WidgetPreviewEventName} eventName Name of the listened event
15
+ * @param {WidgetPreviewEventHandler} handler A callback function to handle the event
16
+ */export var useWidgetPreviewEvent=function useWidgetPreviewEvent(eventName,handler){useEffect(function(){window.addEventListener("widget-preview-".concat(eventName),handler);return function(){window.removeEventListener("widget-preview-".concat(eventName),handler);};},[eventName,handler]);};/**
17
+ * Dispatches widget preview related events.
18
+ * Used to trigger iFrame postMessage events to the parent window or to react on incoming
19
+ * postMessage events from the parent window.
20
+ * @param {WidgetPreviewEventName} eventName Name of the event to dispatch
21
+ * @param {string} widgetCode Code of the widget to dispatch the event for
22
+ * @param {Object} [payload] Optional payload to include with the event
23
+ */export var dispatchWidgetPreviewEvent=function dispatchWidgetPreviewEvent(eventName,widgetCode){var payload=arguments.length>2&&arguments[2]!==undefined?arguments[2]:null;var event=new CustomEvent("widget-preview-".concat(eventName),{detail:{widgetCode:widgetCode,payload:payload}});window.dispatchEvent(event);};
@@ -0,0 +1,23 @@
1
+ import{PAGE_PREVIEW_PATTERN}from'@shopgate/engage/page/constants';/**
2
+ * Retrieves the scroll container for the current page. Depending on the PWA mode this can be
3
+ * a scrollable article element or the window.
4
+ * @returns {HTMLElement|null}
5
+ */export var getScrollContainer=function getScrollContainer(){return document.querySelector(".route__".concat(PAGE_PREVIEW_PATTERN.replace(/^\/+/,'')));};/**
6
+ * @typedef {Object} ScheduledParams
7
+ * @param {string} [from] The start date of the scheduling in ISO format.
8
+ * @param {string} [to] The end date of the scheduling in ISO format.
9
+ * @param {number} [timezoneOffset] The timezone offset in minutes. If not provided, the local
10
+ * timezone offset will be used.
11
+ */ /**
12
+ * @typedef {Object} ScheduledStatus
13
+ * @param {boolean} isScheduled Indicates if the widget is scheduled.
14
+ * @param {boolean} isActive Indicates if the widget is currently active within the
15
+ * scheduled time frame.
16
+ * @param {boolean} isExpired Indicates if the scheduled time frame has expired.
17
+ */ /**
18
+ * Retrieves the scheduling status of a widget based on the provided parameters.
19
+ * @param {ScheduledParams} params The parameters for the function.
20
+ * @returns {ScheduledStatus} An object containing the scheduling status.
21
+ */export function checkScheduled(){var _ref=arguments.length>0&&arguments[0]!==undefined?arguments[0]:{},from=_ref.from,to=_ref.to,timezoneOffset=_ref.timezoneOffset;var now=new Date();// Convert current time to provided or local timezone
22
+ var localOffset=timezoneOffset!==null&&timezoneOffset!==void 0?timezoneOffset:-now.getTimezoneOffset();// in minutes
23
+ var offsetMs=localOffset*60*1000;var localNow=new Date(now.getTime()+offsetMs);var fromDate=from?new Date(from):null;var toDate=to?new Date(to):null;var isActive=(!fromDate||localNow>=new Date(fromDate.getTime()+offsetMs))&&(!toDate||localNow<=new Date(toDate.getTime()+offsetMs));var isExpired=!!toDate&&localNow>new Date(toDate.getTime()+offsetMs);var isScheduled=!!fromDate||!!toDate;return{isScheduled:isScheduled,isActive:isActive,isExpired:isExpired};}