Advertisement
Guest User

Untitled

a guest
Oct 17th, 2019
136
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. import { breakpoints, sessionStorageSpace } from '../constants';
  2. import { LinkField } from '@sitecore-jss/sitecore-jss-react/types/components/Link';
  3. import _ from 'lodash';
  4. import { IImageSize } from '../interfaces/ImageSize';
  5. import { LINK_TYPE } from '../links/constants';
  6. import WebFont from 'webfontloader';
  7. import { setConfiguration } from 'react-grid-system';
  8.  
  9. const getLabelWithoutUniqueNumberId = (label: string): string => {
  10.   return label.split('-')[0];
  11. };
  12.  
  13. const replaceAll = (text: string, mapObject: any): string => {
  14.   const regularExpression = new RegExp(Object.keys(mapObject).join('|'), 'gi');
  15.  
  16.   return text.replace(regularExpression, (matched): string => {
  17.     return mapObject[matched.toLowerCase()];
  18.   });
  19. };
  20.  
  21. const getFormattedId = (prefixes: string[], id: string): string => {
  22.   const replaceMap: any = {};
  23.   prefixes.forEach(prefix => (replaceMap[prefix] = ''));
  24.   const formattedId = replaceAll(id, replaceMap);
  25.  
  26.   return getLabelWithoutUniqueNumberId(formattedId);
  27. };
  28.  
  29. const isIdFromSelection = (selectors: string[], id: string): boolean => {
  30.   return selectors.some(selectorItem => `${id}`.includes(selectorItem));
  31. };
  32.  
  33. const getIdAttribute = (event: any, attribute: string): string => {
  34.   return `${_.get(event, 'target', {}).getAttribute(attribute)}`;
  35. };
  36.  
  37. const goTop = (): void => {
  38.   window.scrollTo({ top: 0, behavior: 'smooth' });
  39. };
  40.  
  41. const getOffset = className => _.get(document.getElementsByClassName(className), '[0].offsetHeight') || 0;
  42.  
  43. const getFormattedIdFromUrl = (url: string): string => url.replace(/[\./ ,:-]+/g, '-');
  44.  
  45. const makeAnchorFromTitle = (title: string): string => {
  46.   const anchor = title.replace(/\W+/g, '-').toLowerCase();
  47.  
  48.   return anchor;
  49. };
  50.  
  51. const srcsetRender = (imageSizes: IImageSize[]) => {
  52.   // tslint:disable-next-line
  53.   const srcSet: {}[] = [];
  54.   let sizes: string = '';
  55.  
  56.   imageSizes.map(size => {
  57.     srcSet.push({ w: size.size });
  58.     sizes += `(max-width: ${size.breakpoint}px) ${size.size}px, `;
  59.   });
  60.  
  61.   sizes += `100vw`;
  62.  
  63.   return {
  64.     srcSet,
  65.     sizes,
  66.   };
  67. };
  68.  
  69. const getLink = (href: string, isExternal: boolean): LinkField => {
  70.   return {
  71.     value: {
  72.       href,
  73.       linktype: getLinkType(isExternal),
  74.     },
  75.   };
  76. };
  77.  
  78. const getSimpleLink = (url: string): LinkField => {
  79.   return {
  80.     value: {
  81.       href: url,
  82.       linktype: LINK_TYPE.internal,
  83.     },
  84.   };
  85. };
  86.  
  87. const getLinkType = (isExternal: boolean): string => (isExternal ? LINK_TYPE.external : LINK_TYPE.internal);
  88.  
  89. const slash = '/';
  90.  
  91. const getPathSegments = () => {
  92.   if (typeof window !== 'undefined') {
  93.     const url = new URL(window.location.href);
  94.     const pathSegments = url.pathname.split(slash).filter(segment => !!segment);
  95.  
  96.     return pathSegments;
  97.   }
  98.  
  99.   return [];
  100. };
  101.  
  102. const deeply = (mapper: any) => {
  103.   return (obj: any, fn: any) => {
  104.     return mapper(
  105.       _.mapValues(obj, v => {
  106.         return _.isPlainObject(v)
  107.           ? deeply(mapper)(v, fn)
  108.           : _.isArray(v)
  109.           ? v.map(x => {
  110.               return deeply(mapper)(x, fn);
  111.             })
  112.           : v;
  113.       }),
  114.       fn
  115.     );
  116.   };
  117. };
  118.  
  119. const getRouteName = (pathname: string): string => {
  120.   const path = pathname.split('/');
  121.   return path[path.length - 1];
  122. };
  123.  
  124. const fireEvent = (el: any, etype: string): void => {
  125.   if (el.fireEvent) {
  126.     el.fireEvent(`on${etype}`);
  127.   } else {
  128.     const evObj = document.createEvent('Events');
  129.     evObj.initEvent(etype, true, false);
  130.     el.dispatchEvent(evObj);
  131.   }
  132. };
  133.  
  134. const getIsNotDesktop = () => {
  135.   if (typeof window === 'undefined') { return; }
  136.   const ua = navigator.userAgent;
  137.   const isMobile = /Android|webOS|iPhone|iPad|iPod|BlackBerry|IEMobile|Opera Mini/i.test(ua);
  138.   const isBelowLastBreakPoint = document.documentElement.clientWidth <= breakpoints.md;
  139.  
  140.   return isBelowLastBreakPoint || isMobile;
  141. };
  142.  
  143. const loadWebFonts = (isDisconnectedMode: boolean, activeCallback: () => {}): void => {
  144. // font loader initialization
  145.   WebFont.load({
  146.     custom: {
  147.       families: ['Suisse Intl', 'Suisse Intl Bold'],
  148.       urls: [isDisconnectedMode ? '/assets/fonts/_suisseIntl.css' : '/dist/aosr/assets/fonts/_suisseIntl.css'],
  149.     },
  150.     active: activeCallback()
  151.   });
  152. };
  153.  
  154. const setGridConfiguration = () => {
  155.   const { xs, sm, md, lg, gutter } = breakpoints;
  156.  
  157.   setConfiguration({
  158.     breakpoints: [xs, sm, md, lg],
  159.     gutterWidth: gutter,
  160.   });
  161. };
  162.  
  163. const isIE = () => {
  164.   if (typeof document !== 'undefined') {
  165.     return !!(document as any).documentMode;
  166.   }
  167.   return false;
  168. };
  169.  
  170. const getTextFromFullContent = (fullContent: string): string => {
  171.   /* const text = fullContent.replace(/<[^>]+>/g, '');
  172.   const decodedText = text.replace(/&#(\d+);/g, (match, dec) => String.fromCharCode(dec)); // https://ourcodeworld.com/articles/read/188/encode-and-decode-html-entities-using-pure-javascript
  173.  
  174.   return decodedText; */
  175.   const contentDocument = new DOMParser().parseFromString(fullContent, 'text/html').documentElement;
  176.   const firstParagraph = _.get(contentDocument, 'childNodes[1].childNodes[0]');
  177.   return firstParagraph ? firstParagraph.textContent : '';
  178. };
  179.  
  180. const saveToSessionStorage = (data: object) => {
  181.   const currentData = JSON.parse(`${sessionStorage.getItem(sessionStorageSpace)}`);
  182.   // const updatedData = {...currentData, ...data};
  183.   const updatedData = _.merge({}, currentData, data);
  184.   sessionStorage.setItem(sessionStorageSpace, JSON.stringify(updatedData));
  185. };
  186.  
  187. const loadFromSessionStorage = (path: string): any => {
  188.   const currentData = JSON.parse(`${sessionStorage.getItem(sessionStorageSpace)}`);
  189.   return _.get(currentData, path);
  190. };
  191.  
  192. const removeFromSessionStorage = (key: string, filter: string): void => {
  193.   const currentData = JSON.parse(`${sessionStorage.getItem(sessionStorageSpace)}`);
  194.   let updatedData = currentData;
  195.  
  196.   if (currentData[key].hasOwnProperty(filter)) {
  197.     updatedData = _.omit(currentData, `${key}.${filter}`);
  198.   }
  199.   sessionStorage.setItem(sessionStorageSpace, JSON.stringify(updatedData));
  200. };
  201.  
  202. const getUid = (props: any): string => {
  203.   return `uid-${_.get(props, 'rendering.uid')}`;
  204. };
  205.  
  206. export {
  207.   replaceAll,
  208.   getLabelWithoutUniqueNumberId,
  209.   getFormattedId,
  210.   isIdFromSelection,
  211.   getIdAttribute,
  212.   goTop,
  213.   getFormattedIdFromUrl,
  214.   makeAnchorFromTitle,
  215.   srcsetRender,
  216.   getLink,
  217.   getSimpleLink,
  218.   getPathSegments,
  219.   deeply,
  220.   getRouteName,
  221.   fireEvent,
  222.   getIsNotDesktop,
  223.   loadWebFonts,
  224.   setGridConfiguration,
  225.   slash,
  226.   isIE,
  227.   getTextFromFullContent,
  228.   getOffset,
  229.   saveToSessionStorage,
  230.   loadFromSessionStorage,
  231.   removeFromSessionStorage,
  232.   getUid
  233. };
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement