UNPKG

@uigstudio/uig-nextjs-helper

Version:

``` npm install @uig/uig-nextjs-helper ``` or ``` yarn add -D @uig/uig-nextjs-helper ```

201 lines (168 loc) 5.99 kB
import { jsx, jsxs } from 'react/jsx-runtime'; import { Fragment, useRef, useEffect, useState } from 'react'; import { useTranslation } from 'next-i18next'; function _extends() { _extends = Object.assign ? Object.assign.bind() : 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); } const initialApiError = { statusCode: 500, error: 'Error', message: 'Unknown error' }; const parseApiError = error => { var _error$message; switch (typeof error) { case 'string': return _extends({}, initialApiError, { message: error }); case 'object': return _extends({}, initialApiError, (error == null ? void 0 : error.message) || error, { message: (error == null ? void 0 : (_error$message = error.message) == null ? void 0 : _error$message.message) || (error == null ? void 0 : error.message) }, (error == null ? void 0 : error.statusCode) && { statusCode: error.statusCode }); default: return initialApiError; } }; const PREVIEW_ID_PREFIX = 'preview_'; const HOMEPAGE_SLUG = 'homepage'; // export const BLOG_PREFIX = 'blog'; const objectEntries = obj => { // Object.entries typings error // @ts-ignore return Object.entries(obj); }; const objectHas = (obj, key) => Object.prototype.hasOwnProperty.call(obj, key); const createUrl = (baseUrl, path) => { if (/https?:/.test(path)) { return path; } return [(baseUrl || process.env.NEXT_PUBLIC_API || '').replace(/\/$/, ''), path.replace(/^\//, '')].join('/'); }; const resolveUrl = (baseUrl, path, queryParams = {}, bindParams = {}) => { const url = new URL(createUrl(baseUrl, bindUrlParams(path, bindParams))); if (queryParams) { Object.entries(queryParams).forEach(([name, value]) => { if (value !== undefined && value !== null) { url.searchParams.append(name, value.toString()); } }); } return url.href; }; const bindUrlParams = (route, params) => { return route.replace(/:(\w+)/g, (_, key) => { var _params$key; return objectHas(params, key) ? ((_params$key = params[key]) == null ? void 0 : _params$key.toString()) || '' : ''; }); }; const slugToData = (ctx, items, defaultSlug, blockList) => { var _ctx$params, _ctx$params2, _ctx$params3; let slug = `${(_ctx$params = ctx.params) == null ? void 0 : _ctx$params.slug}`; if (!((_ctx$params2 = ctx.params) != null && _ctx$params2.slug) && !defaultSlug || (blockList || []).includes(slug)) { return undefined; } if (!((_ctx$params3 = ctx.params) != null && _ctx$params3.slug) && defaultSlug) { slug = `${defaultSlug}`; } if (slug.startsWith(PREVIEW_ID_PREFIX)) { const [, id] = slug.split('_'); return { slug: '', id: Number(id) }; } return items.find(p => p.slug === slug); }; const absoluteUrl = (...parts) => { return [`${process.env.NEXT_PUBLIC_URL}`, ...parts].filter(p => !!p).map(p => p.replace(/^\//, '').replace(/\/$/, '')).join('/'); }; const queryPage = ctx => { const page = queryParam(ctx, 'page', '1'); return /\d+/.test(page) ? Number(page) : 1; }; const queryParam = (ctx, key, defaultValue) => { var _ctx$query, _ctx$query2; return (_ctx$query = ctx.query) != null && _ctx$query[key] ? `${(_ctx$query2 = ctx.query) == null ? void 0 : _ctx$query2[key]}` : defaultValue; }; const imageProps = image => { var _image$data; // @ts-ignore const attributes = (image == null ? void 0 : (_image$data = image.data) == null ? void 0 : _image$data.attributes) || (image == null ? void 0 : image.attributes); const src = (attributes == null ? void 0 : attributes.url) || ''; return { src: src.startsWith('http') ? src : createUrl(process.env.NEXT_PUBLIC_MEDIA_URL, src), alt: (attributes == null ? void 0 : attributes.alternativeText) || '' }; }; function safeJsonParse(string, returnRaw) { try { return JSON.parse(string); } catch (err) { return returnRaw ? string : {}; } } const formatNumber = value => Number(`${value}`).toLocaleString('en', { useGrouping: true }); const formatPrice = value => `$${formatNumber(value)}`; const minMax = (min, value, max) => Math.max(min, Math.min(value, max)); function linkTarget(target = '_self') { return target[0] === '_' ? target : `_${target}`; } function linkRel(target) { if (linkTarget(target) === '_blank') { return { rel: 'nofollow noopener noreferrer' }; } return {}; } function slugToUrl(seo, prefix) { const slug = [prefix, HOMEPAGE_SLUG === seo.slug ? '' : seo.slug].filter(e => !!e).join('/'); return `/${slug}`; } const nlToBr = text => { return jsx(Fragment, { children: text.split('\n').map((item, idx) => { return jsxs(Fragment, { children: [Boolean(idx) && jsx("br", {}), item] }, idx); }) }); }; function useCurrentRef(value) { const valueRef = useRef(value); useEffect(() => { valueRef.current = value; }, [value]); return valueRef; } function useRefState(initValue) { const valueRef = useRef(initValue); const [value, setValue] = useState(initValue); return [value, valueRef, val => { valueRef.current = val; setValue(val); }]; } const useScopeTranslation = (namespace, ...scopes) => { const { t } = useTranslation(namespace); const finalScope = scopes && scopes.length ? `${scopes.join('.')}.` : ''; return (key, option) => t(`${finalScope}${key}`, option); }; export { HOMEPAGE_SLUG, PREVIEW_ID_PREFIX, absoluteUrl, bindUrlParams, createUrl, formatNumber, formatPrice, imageProps, linkRel, linkTarget, minMax, nlToBr, objectEntries, objectHas, parseApiError, queryPage, queryParam, resolveUrl, safeJsonParse, slugToData, slugToUrl, useCurrentRef, useRefState, useScopeTranslation };