import settings from 'settings'; import { LocaleUrlStrategy } from '../localization'; import { CDNOptions, ClientRequestOptions, SetCookieOptions } from '../types'; import getRootHostname from './get-root-hostname'; export * from './get-currency'; export * from './menu-generator'; export * from './generate-commerce-search-params'; export * from './get-currency-label'; export function getCookie(name: string) { if (typeof document === 'undefined') { return null; } const value = `; ${document.cookie}`; const parts = value.split(`; ${name}=`); if (parts.length === 2) { return parts.pop().split(';').shift(); } } export function setCookie( name: string, value: string, options: SetCookieOptions = {} ) { const cookieParts = [`${name}=${value}`]; if (options.expires) { const date = new Date(); date.setTime(date.getTime() + options.expires * 24 * 60 * 60 * 1000); cookieParts.push(`expires=${date.toUTCString()}`); } cookieParts.push(`path=${options.path ?? '/'}`); if (options.secure) { cookieParts.push('secure'); } if (options.sameSite) { cookieParts.push(`sameSite=${options.sameSite}`); } const domain = options.domain ?? (settings.localization.localeUrlStrategy === LocaleUrlStrategy.Subdomain ? getRootHostname(document.location.href) : null); if (domain) { cookieParts.push(`domain=${domain}`); } document.cookie = cookieParts.join('; '); } export function removeCookie(name: string) { const date = 'Thu, 01 Jan 1970 00:00:00 UTC'; document.cookie = `${name}=; expires=${date}; path=/;`; } /** * @deprecated Use setCurrency method in useLocalization hook instead. */ export function setCurrency(currency: string) { if (getCookie('pz-currency') !== currency) { setCookie('pz-reset-basket', 'true'); } setCookie('pz-currency', currency); } export function getTranslateFn(path: string, translations: any) { const get = (parts_: Array, tObj: any) => { const currentPart = parts_[0]; if (parts_.length === 1) { return tObj?.[currentPart] ?? path; } return get(parts_.slice(1), tObj?.[currentPart]); }; return get(path.split('.'), translations); } export function buildClientRequestUrl( path: string, options?: ClientRequestOptions & { cache?: boolean } ) { let url = `/api/client${path}`; let hasQuery = url.includes('?'); if (options) { const { cache, ...otherOptions } = options; if (Object.keys(otherOptions).length > 0) { if (hasQuery) { url += '&'; } else { url += '?'; hasQuery = true; } url += `options=${encodeURIComponent(JSON.stringify(otherOptions))}`; } if (cache === false) { if (hasQuery) { url += '&'; } else { url += '?'; } url += `t=${Date.now()}`; } } return url; } export function capitalize(str: string) { return str.charAt(0).toUpperCase() + str.slice(1); } export function asTypedObject() { return function (et: { [K in keyof T]: E }) { return et; }; } function splitUrlByFileExtension(path: string) { const lastDotIndex = path.lastIndexOf('.'); return [path.slice(0, lastDotIndex), path.slice(lastDotIndex)] as const; } export function buildCDNUrl(url: string, config?: CDNOptions) { const [root, fileExtension] = splitUrlByFileExtension(url); const rootWithoutOptions = root.replace( /_size\d+(x\d+)?|_quality\d*|_crop\w*|_upscale\d*/g, '' ); const noOptionFileExtension = url?.split('.').pop()?.toLowerCase() ?? ''; if (noOptionFileExtension === 'svg' || noOptionFileExtension === 'gif') { return url; } let options = ''; if (config) { const { width, height, quality, crop, upscale } = config; if (width && height) { options += `_size${width}x${height}`; } else if (height) { options += `_sizex${height}`; } else if (width) { options += `_size${width}`; } if (quality) { options += `_quality${quality}`; } if (crop) { options += `_crop${capitalize(crop)}`; } if (upscale) { options += `_upscale${upscale.toString()}`; } } return `${rootWithoutOptions}${options}${fileExtension}`; } export const urlLocaleMatcherRegex = new RegExp( `^/(${settings.localization.locales .filter((l) => ![LocaleUrlStrategy.ShowAllLocales, LocaleUrlStrategy.Subdomain].includes( settings.localization.localeUrlStrategy ) ? l.value !== settings.localization.defaultLocaleValue : l ) .map((l) => l.value) .join('|')})(?=/|$)` ); export const getPosError = () => { const error = JSON.parse(getCookie('pz-pos-error') ?? '{}'); // delete 'pz-pos-error' cookie when refreshing or closing page window.addEventListener('beforeunload', () => { removeCookie('pz-pos-error'); }); return error; }; export const urlSchemes = [ 'http', 'tel:', 'mailto:', 'sms:', 'whatsapp:', 'skype:', 'ftp:', 'file:', '//', '#', 'viber:', 'tg:', 'slack:', 'data:', 'market:', 'intent:', 'webcal:', 'geo:', 'maps:', 'news:', 'facetime:', 'facetime-audio:', 'spotify:', 'steam:', 'ms-settings:', 'zoommtg:', 'zoomus:', 'blob:', 'wss:', 'sftp:', 'magnet:' ] as const;