Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

cmmc @ 1.0.12: minor fixes and improvements #39

Merged
merged 1 commit into from
Mar 3, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
8 changes: 4 additions & 4 deletions packages/commerce/components/select-item-in-category-view.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -31,15 +31,15 @@ const SelectItemInCategoryView: React.FC<React.HTMLAttributes<HTMLDivElement> &
...props
}) => {

const waiting = (): boolean => (isLoading || !category)
const waiting = (): boolean => (isLoading) // keep for convenience for now

const CategoryImage: React.FC<{ className?: string }> = ({ className = '' }) => {

if (waiting()) {
// deliberately not Skeleton to have a better overall pulse effect.
return <div className={cn(
'bg-level-1 rounded-xl aspect-square ' +
' min-h-[100px] sm:min-h-[200px] lg:aspect-auto lg:h-[300px] lg:w-[200px] 2xl:w-auto 2xl:aspect-square',
'bg-level-1 rounded-xl aspect-square w-full min-h-1 ', // +
//' min-h-[100px] sm:min-h-[200px] lg:aspect-auto 2xl:w-auto 2xl:aspect-square',
className)} />
}

Expand All @@ -49,7 +49,7 @@ const SelectItemInCategoryView: React.FC<React.HTMLAttributes<HTMLDivElement> &
aria-label='Placeholder'
role='img'
aria-roledescription='placeholder'
className={cn('h-60 flex items-center justify-center', className)}
className={cn('w-full flex items-center justify-center aspect-square' , className)}
>
<Icons.barcode className='h-9 w-9 text-muted' aria-hidden='true' />
</div>
Expand Down
2 changes: 1 addition & 1 deletion packages/commerce/package.json
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
{
"name": "@hanzo/commerce",
"version": "1.0.11",
"version": "1.0.12",
"description": "Library with shopping cart components.",
"publishConfig": {
"registry": "https://registry.npmjs.org/",
Expand Down
2 changes: 1 addition & 1 deletion packages/commerce/service/commerce-service.ts
Original file line number Diff line number Diff line change
Expand Up @@ -30,7 +30,7 @@ interface CommerceService extends ObsLineItemRef {
* "current" is unrelated to what is "specified",
* ie, facets' values
* */
setCurrentItem(sku: string | undefined): void
setCurrentItem(sku: string | undefined): boolean // was valid sku and was set.
/**
* For convenience, so widgets can share state.
* "current" is unrelated to what is "specified",
Expand Down
65 changes: 36 additions & 29 deletions packages/commerce/service/impl/standalone/service.ts
Original file line number Diff line number Diff line change
Expand Up @@ -31,7 +31,7 @@ class StandaloneCommerceService

private _options : StandaloneServiceOptions

private _currentItemSku: string | undefined = undefined
private _currentItem: LineItem | undefined = undefined

constructor(
categories: Category[],
Expand All @@ -50,20 +50,20 @@ class StandaloneCommerceService
makeObservable<
StandaloneCommerceService,
'_selectedFacets' |
'_currentItemSku'
'_currentItem'
>(this, {
_selectedFacets : observable.deep,
_currentItemSku: observable,
_currentItem: observable,
})

makeObservable(this, {
cartItems: computed,
cartTotal: computed,
specifiedItems: computed,
specifiedCategories: computed,
setCurrentItem: action,
currentItem: computed,
item: computed,
specifiedCategories: computed,
facetsValue: computed
/* NOT setFacets. It implements it's action mechanism */
})
Expand All @@ -85,39 +85,46 @@ class StandaloneCommerceService
)
}

setCurrentItem(sku: string | undefined): void {
this._currentItemSku = sku
setCurrentItem(skuToFind: string | undefined): boolean {

if (skuToFind === undefined || skuToFind.length === 0) {
this._currentItem = undefined
return true
}

this._currentItem = ((): LineItem | undefined => {
const categoriesTried: string[] = []
if (this.specifiedCategories && this.specifiedCategories.length > 0) {

for (let category of this.specifiedCategories) {
categoriesTried.push(category.id)
const foundItem =
(category.products as LineItem[]).find((item) => (item.sku === skuToFind))
if (foundItem) {
return foundItem
}
}
}

let foundItem: LineItem | undefined = undefined
this._categoryMap.forEach((category, categoryId) => {
if (foundItem) return
if (categoriesTried.includes(categoryId)) return
foundItem = (category.products as LineItem[]).find((item) => (item.sku === skuToFind))
})
})();

return !!this._currentItem
}


/* ObsLineItemRef */
get item(): LineItem | undefined {
return this.currentItem
}

get currentItem(): LineItem | undefined {
if (!this._currentItemSku) return undefined

const categoriesTried: string[] = []
if (this.specifiedCategories && this.specifiedCategories.length > 0) {

for (let category of this.specifiedCategories) {
categoriesTried.push(category.id)
const foundItem =
(category.products as LineItem[]).find((item) => (item.sku === this._currentItemSku))
if (foundItem) {
return foundItem
}
}
}

let foundItem: LineItem | undefined = undefined
this._categoryMap.forEach((category, categoryId) => {
if (foundItem) return
if (categoriesTried.includes(categoryId)) return
foundItem = (category.products as LineItem[]).find((item) => (item.sku === this._currentItemSku))
})

return foundItem
return this._currentItem
}

setFacets(sel: FacetsValue): Category[] {
Expand Down
78 changes: 46 additions & 32 deletions packages/commerce/util/use-sku-and-facet-params.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
import {
useEffect,
useRef,
useState,
} from 'react'
import { autorun, toJS, type IReactionDisposer } from 'mobx'

Expand All @@ -13,6 +14,8 @@ import {
import type { Category, FacetsValue, StringMutator } from '../types'
import { useCommerce } from '../service'

const PLEASE_SELECT_FACETS = 'Please select an option from each group above.'

interface GetMutator {
(level: 1 | 2): StringMutator
}
Expand All @@ -24,11 +27,9 @@ const useSkuAndFacetParams = (
const cmmc = useCommerce()

const encRef = useRef<{
category: Category | undefined
usingSkuMode: boolean
autoRunDisposer: IReactionDisposer | undefined
}>({
category: undefined,
usingSkuMode: false,
autoRunDisposer: undefined,
})
Expand All @@ -40,12 +41,15 @@ const useSkuAndFacetParams = (
parseAsString.withDefault('').withOptions({ clearOnDefault: true })
)

const [skuParam, setSkuParam] = useQueryState('sku')
const [skuParam, setSkuParam] = useQueryState('sku',
parseAsString.withDefault('').withOptions({ clearOnDefault: true })
)

const [addParam, setAddParam] = useQueryState('add',
parseAsBoolean.withDefault(false).withOptions({ clearOnDefault: true })
)

let message = ''
const [message, setMessage] = useState<string | undefined>(undefined)

const directMutator: GetMutator = (level: 1 | 2): StringMutator => {

Expand Down Expand Up @@ -83,70 +87,80 @@ const useSkuAndFacetParams = (

const setCurrentCategoryFromSku = (sku: string) => {
const toks: string[] = sku.split('-')
const categories = cmmc.setFacets({
cmmc.setFacets({
1: [toks[1]],
2: [toks[2]]
})
encRef.current.category = categories[0]
}

if (skuParam) {
cmmc.setCurrentItem(skuParam)
if (addParam && cmmc.currentItem!.quantity === 0) {
cmmc.currentItem!.increment()
setAddParam(false)
// true if a valid sku
if (cmmc.setCurrentItem(skuParam)) {
if (addParam && cmmc.currentItem!.quantity === 0) {
cmmc.currentItem!.increment()
setAddParam(false)
}
// Marks that we've been here so no need to
// create an autorun() instance twice.
if (!encRef.current.usingSkuMode) {
setCurrentCategoryFromSku(skuParam)
encRef.current.autoRunDisposer = autorun(() => {
if (cmmc.currentItem && cmmc.currentItem.sku !== skuParam) {
setSkuParam(cmmc.currentItem.sku)
}
})
}
setMessage(undefined)
encRef.current.usingSkuMode = true
}
// Marks that we've been here so no need to
// create an autorun() instance twice.
if (!encRef.current.usingSkuMode) {
setCurrentCategoryFromSku(skuParam)
encRef.current.autoRunDisposer = autorun(() => {
if (cmmc.currentItem && cmmc.currentItem.sku !== skuParam) {
setSkuParam(cmmc.currentItem.sku)
}
})
else {
setSkuParam('')
// if sent here w an invalid sku,
// it will effectively put us in facet params mode
setMessage('Invalid sku. ' + PLEASE_SELECT_FACETS)
}
encRef.current.usingSkuMode = true
}
else if (encRef.current.category) {
//const catMutators = [{val: level1, set: setLevel1} , {val: level2, set: setLevel2}]
cmmc.setCurrentItem(encRef.current.category.products[0].sku)
}

setLoading && setLoading(false)
}, [skuParam, encRef.current.category])
}, [skuParam])

// supposed to be when component unmounts
/*
useEffect(() => (() => {
if (encRef.current.autoRunDisposer) {
//encRef.current.autoRunDisposer() // no idea why this seems to be called prematurely and so many times <shrug>
}
}), [])
*/


// Level Params Mode
useEffect(() => {

if (encRef.current.usingSkuMode) return

const facets: FacetsValue = { }
if (level1) { facets[1] = [level1] }
if (level2) { facets[2] = [level2] }
//console.log(`LEV1: ${level1}, LEV2: ${level2}`)
if (level1 && level2) {
const categories = cmmc.setFacets(facets)
if (categories.length > 1) {
console.error("CAT", categories.map((c) => (c.title)))
throw new Error ( "CategoryContents: More than one specified Category should never be possible with this UI!")
if (categories && categories.length > 0) {
cmmc.setCurrentItem(categories?.[0].products[0].sku)
setMessage(undefined)
}
else {
cmmc.setCurrentItem(undefined)
setMessage('Unrecognized facets. ' + PLEASE_SELECT_FACETS)
}
encRef.current.category = categories[0]
}
else {
message = 'Please select an option from each group above.'
setMessage(PLEASE_SELECT_FACETS)
}
setLoading && setLoading(false)
}, [level1 , level2])

return {
category: encRef.current.category,
message,
getMutator: encRef.current.usingSkuMode ?
directMutator : paramsMutator
Expand Down
Loading