Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- import { breakpoints, sessionStorageSpace } from '../constants';
- import { LinkField } from '@sitecore-jss/sitecore-jss-react/types/components/Link';
- import _ from 'lodash';
- import { IImageSize } from '../interfaces/ImageSize';
- import { LINK_TYPE } from '../links/constants';
- import WebFont from 'webfontloader';
- import { setConfiguration } from 'react-grid-system';
- const getLabelWithoutUniqueNumberId = (label: string): string => {
- return label.split('-')[0];
- };
- const replaceAll = (text: string, mapObject: any): string => {
- const regularExpression = new RegExp(Object.keys(mapObject).join('|'), 'gi');
- return text.replace(regularExpression, (matched): string => {
- return mapObject[matched.toLowerCase()];
- });
- };
- const getFormattedId = (prefixes: string[], id: string): string => {
- const replaceMap: any = {};
- prefixes.forEach(prefix => (replaceMap[prefix] = ''));
- const formattedId = replaceAll(id, replaceMap);
- return getLabelWithoutUniqueNumberId(formattedId);
- };
- const isIdFromSelection = (selectors: string[], id: string): boolean => {
- return selectors.some(selectorItem => `${id}`.includes(selectorItem));
- };
- const getIdAttribute = (event: any, attribute: string): string => {
- return `${_.get(event, 'target', {}).getAttribute(attribute)}`;
- };
- const goTop = (): void => {
- window.scrollTo({ top: 0, behavior: 'smooth' });
- };
- const getOffset = className => _.get(document.getElementsByClassName(className), '[0].offsetHeight') || 0;
- const getFormattedIdFromUrl = (url: string): string => url.replace(/[\./ ,:-]+/g, '-');
- const makeAnchorFromTitle = (title: string): string => {
- const anchor = title.replace(/\W+/g, '-').toLowerCase();
- return anchor;
- };
- const srcsetRender = (imageSizes: IImageSize[]) => {
- // tslint:disable-next-line
- const srcSet: {}[] = [];
- let sizes: string = '';
- imageSizes.map(size => {
- srcSet.push({ w: size.size });
- sizes += `(max-width: ${size.breakpoint}px) ${size.size}px, `;
- });
- sizes += `100vw`;
- return {
- srcSet,
- sizes,
- };
- };
- const getLink = (href: string, isExternal: boolean): LinkField => {
- return {
- value: {
- href,
- linktype: getLinkType(isExternal),
- },
- };
- };
- const getSimpleLink = (url: string): LinkField => {
- return {
- value: {
- href: url,
- linktype: LINK_TYPE.internal,
- },
- };
- };
- const getLinkType = (isExternal: boolean): string => (isExternal ? LINK_TYPE.external : LINK_TYPE.internal);
- const slash = '/';
- const getPathSegments = () => {
- if (typeof window !== 'undefined') {
- const url = new URL(window.location.href);
- const pathSegments = url.pathname.split(slash).filter(segment => !!segment);
- return pathSegments;
- }
- return [];
- };
- const deeply = (mapper: any) => {
- return (obj: any, fn: any) => {
- return mapper(
- _.mapValues(obj, v => {
- return _.isPlainObject(v)
- ? deeply(mapper)(v, fn)
- : _.isArray(v)
- ? v.map(x => {
- return deeply(mapper)(x, fn);
- })
- : v;
- }),
- fn
- );
- };
- };
- const getRouteName = (pathname: string): string => {
- const path = pathname.split('/');
- return path[path.length - 1];
- };
- const fireEvent = (el: any, etype: string): void => {
- if (el.fireEvent) {
- el.fireEvent(`on${etype}`);
- } else {
- const evObj = document.createEvent('Events');
- evObj.initEvent(etype, true, false);
- el.dispatchEvent(evObj);
- }
- };
- const getIsNotDesktop = () => {
- if (typeof window === 'undefined') { return; }
- const ua = navigator.userAgent;
- const isMobile = /Android|webOS|iPhone|iPad|iPod|BlackBerry|IEMobile|Opera Mini/i.test(ua);
- const isBelowLastBreakPoint = document.documentElement.clientWidth <= breakpoints.md;
- return isBelowLastBreakPoint || isMobile;
- };
- const loadWebFonts = (isDisconnectedMode: boolean, activeCallback: () => {}): void => {
- // font loader initialization
- WebFont.load({
- custom: {
- families: ['Suisse Intl', 'Suisse Intl Bold'],
- urls: [isDisconnectedMode ? '/assets/fonts/_suisseIntl.css' : '/dist/aosr/assets/fonts/_suisseIntl.css'],
- },
- active: activeCallback()
- });
- };
- const setGridConfiguration = () => {
- const { xs, sm, md, lg, gutter } = breakpoints;
- setConfiguration({
- breakpoints: [xs, sm, md, lg],
- gutterWidth: gutter,
- });
- };
- const isIE = () => {
- if (typeof document !== 'undefined') {
- return !!(document as any).documentMode;
- }
- return false;
- };
- const getTextFromFullContent = (fullContent: string): string => {
- /* const text = fullContent.replace(/<[^>]+>/g, '');
- 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
- return decodedText; */
- const contentDocument = new DOMParser().parseFromString(fullContent, 'text/html').documentElement;
- const firstParagraph = _.get(contentDocument, 'childNodes[1].childNodes[0]');
- return firstParagraph ? firstParagraph.textContent : '';
- };
- const saveToSessionStorage = (data: object) => {
- const currentData = JSON.parse(`${sessionStorage.getItem(sessionStorageSpace)}`);
- // const updatedData = {...currentData, ...data};
- const updatedData = _.merge({}, currentData, data);
- sessionStorage.setItem(sessionStorageSpace, JSON.stringify(updatedData));
- };
- const loadFromSessionStorage = (path: string): any => {
- const currentData = JSON.parse(`${sessionStorage.getItem(sessionStorageSpace)}`);
- return _.get(currentData, path);
- };
- const removeFromSessionStorage = (key: string, filter: string): void => {
- const currentData = JSON.parse(`${sessionStorage.getItem(sessionStorageSpace)}`);
- let updatedData = currentData;
- if (currentData[key].hasOwnProperty(filter)) {
- updatedData = _.omit(currentData, `${key}.${filter}`);
- }
- sessionStorage.setItem(sessionStorageSpace, JSON.stringify(updatedData));
- };
- const getUid = (props: any): string => {
- return `uid-${_.get(props, 'rendering.uid')}`;
- };
- export {
- replaceAll,
- getLabelWithoutUniqueNumberId,
- getFormattedId,
- isIdFromSelection,
- getIdAttribute,
- goTop,
- getFormattedIdFromUrl,
- makeAnchorFromTitle,
- srcsetRender,
- getLink,
- getSimpleLink,
- getPathSegments,
- deeply,
- getRouteName,
- fireEvent,
- getIsNotDesktop,
- loadWebFonts,
- setGridConfiguration,
- slash,
- isIE,
- getTextFromFullContent,
- getOffset,
- saveToSessionStorage,
- loadFromSessionStorage,
- removeFromSessionStorage,
- getUid
- };
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement