Skip to content

Commit

Permalink
Merge pull request #16 from commercelayer/improve-large-page-data
Browse files Browse the repository at this point in the history
Improve large page data
  • Loading branch information
marcomontalbano authored Feb 9, 2023
2 parents 0ae58cc + 1b20096 commit 8dbbf70
Show file tree
Hide file tree
Showing 11 changed files with 1,494 additions and 1,512 deletions.
2,899 changes: 1,421 additions & 1,478 deletions package-lock.json

Large diffs are not rendered by default.

2 changes: 1 addition & 1 deletion packages/setup/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -13,6 +13,6 @@
"license": "MIT",
"dependencies": {
"@commercelayer/js-auth": "^2.3.0",
"@commercelayer/sdk": "^4.21.0"
"@commercelayer/sdk": "^4.24.1"
}
}
4 changes: 2 additions & 2 deletions packages/types/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -8,10 +8,10 @@
"dist"
],
"dependencies": {
"zod": "^3.20.2"
"zod": "^3.20.6"
},
"devDependencies": {
"typescript": "^4.9.4"
"typescript": "^4.9.5"
},
"scripts": {
"ts:check": "tsc --noEmit",
Expand Down
26 changes: 13 additions & 13 deletions packages/website/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -24,21 +24,21 @@
"dependencies": {
"@commercelayer/demo-store-types": "^2.0.0",
"@commercelayer/js-auth": "^2.3.0",
"@commercelayer/react-components": "4.1.0",
"@commercelayer/sdk": "^4.21.0",
"@commercelayer/react-components": "4.2.2",
"@commercelayer/sdk": "^4.24.1",
"@svgr/webpack": "^6.5.1",
"@types/lodash": "^4.14.191",
"fuse.js": "^6.6.2",
"iframe-resizer-react": "^1.1.0",
"immer": "^9.0.18",
"immer": "^9.0.19",
"lodash": "^4.17.21",
"next": "^13.1.3",
"next": "^13.1.6",
"next-localization": "^0.12.0",
"next-pwa": "^5.6.0",
"react": "^18",
"react-dom": "^18",
"react-remark": "^2.1.0",
"swiper": "^8.4.6",
"swiper": "^9.0.3",
"use-immer": "^0.8.1"
},
"devDependencies": {
Expand All @@ -48,16 +48,16 @@
"@types/react": "^18",
"autoprefixer": "^10.4.13",
"dotenv-cli": "^7.0.0",
"eslint": "8.32.0",
"eslint-config-next": "13.1.3",
"jest": "^29.3.1",
"jest-environment-jsdom": "^29.3.1",
"next-sitemap": "^3.1.45",
"eslint": "8.33.0",
"eslint-config-next": "13.1.6",
"jest": "^29.4.2",
"jest-environment-jsdom": "^29.4.2",
"next-sitemap": "^3.1.52",
"postcss": "^8.4.21",
"sass": "^1.57.1",
"tailwindcss": "^3.2.4",
"sass": "^1.58.0",
"tailwindcss": "^3.2.6",
"ts-jest": "^29.0.5",
"typescript": "4.9.4"
"typescript": "4.9.5"
},
"engines": {
"node": "^16.13.0 || ^18.0.0"
Expand Down
3 changes: 2 additions & 1 deletion packages/website/src/components/Auth.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@ import { NEXT_PUBLIC_BASE_PATH } from '#utils/envs'
import { getPersistKey } from '#utils/order'
import { AuthReturnType, ClientCredentials, getSalesChannelToken } from '@commercelayer/js-auth'
import { CommerceLayer, LineItemsContainer, OrderContainer, OrderStorage } from '@commercelayer/react-components'
import type { DefaultChildrenType } from '@commercelayer/react-components/lib/esm/typings/globals'
import { useRouter } from 'next/router'
import { useEffect, useState } from 'react'

Expand Down Expand Up @@ -52,7 +53,7 @@ const hasExpired = (time: number | undefined): boolean => time === undefined ||
const isValid = (auth: Auth | null): auth is Auth => !hasExpired(auth?.expires)

type Props = {
children ?: React.ReactNode
children: DefaultChildrenType
locale: ShoppableLocale
}

Expand Down
31 changes: 20 additions & 11 deletions packages/website/src/contexts/CatalogContext.tsx
Original file line number Diff line number Diff line change
@@ -1,12 +1,13 @@
import facetsConfig from '#config/facets.config'
import { getRawDataProducts } from '#data/products'
import { getLocale } from '#i18n/locale'
import type { FacetResult, Primitives } from '#utils/facets'
import { getFacets } from '#utils/facets'
import { addProductVariants, spreadProductVariants, LocalizedProductWithVariant } from '#utils/products'
import { addProductVariants, getProductWithVariants, LocalizedProductWithVariant, spreadProductVariants } from '#utils/products'
import CommerceLayer, { CommerceLayerClient } from '@commercelayer/sdk'
import facetsConfig from '#config/facets.config'
import type Fuse from 'fuse.js'
import { uniq } from 'lodash'
import chunk from 'lodash/chunk'
import uniq from 'lodash/uniq'
import uniqBy from 'lodash/uniqBy'
import { useRouter } from 'next/router'
import { createContext, useContext, useEffect, useMemo, useState } from 'react'
Expand Down Expand Up @@ -38,7 +39,7 @@ export const useCatalogContext = () => useContext(CatalogContext)
export const CatalogProvider: React.FC<Props> = ({ children, products: initialProducts }) => {
const router = useRouter()

const flattenProducts = useMemo(() => spreadProductVariants(initialProducts), [initialProducts])
const [flattenProducts, setFlattenProducts] = useState(initialProducts)

const { products: productsWithTaxonomies } = useCatalog(flattenProducts)
const { products: productsWithAvailabilities } = useCommerceLayerAvailability(productsWithTaxonomies)
Expand Down Expand Up @@ -87,6 +88,14 @@ export const CatalogProvider: React.FC<Props> = ({ children, products: initialPr
[selectedFacets, router]
)

useEffect(function enrichProductsWithVariants() {
(async () => {
const rawDataProducts = await getRawDataProducts()
const products = initialProducts.map(ref => getProductWithVariants(ref.sku, ref._locale, rawDataProducts))
setFlattenProducts(products)
})()
}, [initialProducts])

useEffect(function manageOnRouterChange() {
if (typeof router.query.facets === 'string') {
try {
Expand Down Expand Up @@ -120,11 +129,10 @@ export const CatalogProvider: React.FC<Props> = ({ children, products: initialPr
getFacets(spreadProductVariants(resultFromFreeTextSearch))
)

setProducts(
// TODO: this could be a configuration .. group by variantCode vs productCode
uniqBy(result, 'variantCode')
// uniqBy(result, 'productCode')
)
// TODO: this could be a configuration
const uniqByKey = 'variantCode' // 'productCode'

setProducts(isFiltering ? uniqBy(result, uniqByKey) : result)
}
}

Expand All @@ -133,7 +141,7 @@ export const CatalogProvider: React.FC<Props> = ({ children, products: initialPr
return () => {
isMounted = false
}
}, [query, selectedFacets, productList])
}, [query, selectedFacets, productList, isFiltering])

return (
<CatalogContext.Provider value={{ products, availableFacets, selectedFacets, selectFacet, currencyCode }}>
Expand Down Expand Up @@ -169,7 +177,8 @@ function useCatalog(initialProducts: LocalizedProductWithVariant[]) {
const productDataset = await buildProductDataset(rawDataCatalog, locale.code, initialProducts)

if (isMounted) {
setProducts(Object.values(productDataset))
const productsWithTaxonomies = Object.values(productDataset)
setProducts(productsWithTaxonomies.map(product => addProductVariants(product, productsWithTaxonomies)))
setLatestInitialProducts(initialProducts)
}
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -113,7 +113,7 @@ exports[`CustomPage component 1`] = `
data-testid="carousel-page-component"
>
<div
class="swiper swiper-initialized swiper-horizontal swiper-pointer-events carousel"
class="swiper swiper-initialized swiper-horizontal carousel"
>
<div
class="swiper-wrapper"
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -103,7 +103,7 @@ exports[`product detail page 1`] = `
class=" basis-1/2"
>
<div
class="swiper swiper-initialized swiper-horizontal swiper-pointer-events carousel"
class="swiper swiper-initialized swiper-horizontal carousel"
>
<div
class="swiper-wrapper"
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,7 @@ import { getLocale, getLocaleCodes } from '#i18n/locale'
import { serverSideTranslations } from '#i18n/serverSideTranslations'
import { withLocalePaths } from '#i18n/withLocalePaths'
import { findTaxonBySlug, flattenReferencesFromTaxon, getNavigation, getRootNavigationLinks, getSlugs } from '#utils/catalog'
import { getProductWithVariants } from '#utils/products'
import { getProduct, LocalizedProductWithVariant } from '#utils/products'
import type { GetServerSideProps, GetStaticPaths, GetStaticProps } from 'next'
import type { Props } from './SearchPageComponent'

Expand Down Expand Up @@ -42,9 +42,20 @@ export const getStaticProps: GetStaticProps<Props, Query> = async ({ params }) =
const references = flattenReferencesFromTaxon(taxon.result)

const rawDataProducts = await getRawDataProducts()
const products = references.map(ref => getProductWithVariants(ref, locale.code, rawDataProducts))

return {
const products: LocalizedProductWithVariant[] = references.map(ref => {
const product = getProduct(ref, locale.code, rawDataProducts)

return {
...product,
images: product.images.slice(0, 1),
variants: [],
details: [],
variant: []
}
})

const result = {
props: {
navigation: getRootNavigationLinks(catalog),
subNavigation: getNavigation(taxon),
Expand All @@ -54,6 +65,8 @@ export const getStaticProps: GetStaticProps<Props, Query> = async ({ params }) =
...(await serverSideTranslations(localeCode))
}
}

return result
}

export const getServerSideProps: GetServerSideProps<Props, Query> = async ({ res, params }) => {
Expand Down
16 changes: 16 additions & 0 deletions packages/website/src/utils/data.ts
Original file line number Diff line number Diff line change
Expand Up @@ -42,3 +42,19 @@ export async function fetchLocaleData(filename: string): Promise<unknown> {

return data
}

function formatBytes(bytes: number, decimals = 2) {
if (!+bytes) return '0 Bytes'

const k = 1024
const dm = decimals < 0 ? 0 : decimals
const sizes = ['Bytes', 'KB', 'MB', 'GB', 'TB', 'PB', 'EB', 'ZB', 'YB']

const i = Math.floor(Math.log(bytes) / Math.log(k))

return `${parseFloat((bytes / Math.pow(k, i)).toFixed(dm))} ${sizes[i]}`
}

export function getSize(input?: string | object) {
return formatBytes((new TextEncoder().encode(typeof input === 'object' ? JSON.stringify(input) : input)).length)
}
2 changes: 1 addition & 1 deletion packages/website/src/utils/products.ts
Original file line number Diff line number Diff line change
Expand Up @@ -65,7 +65,7 @@ function resolveProductLocale(product: RawDataProduct | LocalizedProduct | Local
}
}

function getProduct(sku: string, locale: string, productList: (LocalizedProduct | RawDataProduct)[]): LocalizedProduct {
export function getProduct(sku: string, locale: string, productList: (LocalizedProduct | RawDataProduct)[]): LocalizedProduct {
const product = productList.find(product => product.sku === sku)

if (!product) {
Expand Down

0 comments on commit 8dbbf70

Please sign in to comment.