From 861bc091d48fcfdb3aa81eee518622f458167dd0 Mon Sep 17 00:00:00 2001 From: Manish Menaria Date: Tue, 17 Sep 2024 14:08:24 +0530 Subject: [PATCH] Product Collection - Add Editor UI for missing product reference (#51114) * Initial implementation of the missing product state - Changed `getProductCollectionUIStateInEditor` to a hook `useProductCollectionUIState`. - As we added logic to check if selected product reference is deleted which require making an API call. Therefore, I decided to use a hook. - While making an API call to check if product reference is deleted, I decided to show spinner in the block. - Introduced new UI state `DELETED_PRODUCT_REFERENCE` to handle the missing product state. - Updated existing `ProductPicker` component to handle the new UI state. - It's better to use existing component for the missing product state, as it already has all the required UI. * Add changefile(s) from automation for the following project(s): woocommerce-blocks * Use getEntityRecord to check if product exists and other improvements * Remove console log * Add E2E tests for deleted product reference in Product Collection block This commit introduces new E2E tests to verify the behavior of the Product Collection block when dealing with deleted product references. The changes include: 1. New test suite in register-product-collection-tester.block_theme.spec.ts 2. Modification to product-collection.page.ts to support custom product selection 3. Minor update to utils.tsx to handle trashed products These tests ensure that the Product Collection block correctly handles scenarios where referenced products are deleted, trashed, or restored, improving the overall reliability of the feature. * Simplify product creation in Product Collection block test * Refactor E2E test for delete product reference picker 1. Removing the unnecessary `test.describe` block for "Deleted product reference" 2. Eliminating the `beforeEach` hook that was creating a test product 3. Integrating the test product creation directly into the main test This change simplifies the test structure and improves readability while maintaining the same test coverage for the Product Collection block's behavior when dealing with deleted or unavailable products. * Simplify logic for product collection UI state This commit simplifies the handling of the `usesReference` prop in the Product Collection block: 1. In `edit/index.tsx`, directly pass `usesReference` to `useProductCollectionUIState` hook without conditional spreading. 2. In `utils.tsx`, update the type definition of `usesReference` in the `useProductCollectionUIState` hook to explicitly include `undefined`. * Refactor Product Collection block to improve prop passing - Introduce ProductCollectionContentProps type for better prop management - Refactor Edit component to use a renderComponent function - Update component prop types to use more specific props - Remove unnecessary props from ProductCollectionEditComponentProps - Simplify component rendering logic in Edit component - Adjust ProductPicker to receive only required props - Update imports and prop types in various files to use new types This refactoring improves code organization and reduces prop drilling by only passing necessary props to each component. It enhances maintainability and readability of the Product Collection block and related components. * Refactor Product Collection block editor UI state handling This commit simplifies the rendering logic in the Product Collection block's Edit component. It removes a redundant case for the VALID state, as both VALID and VALID_WITH_PREVIEW states now render the same ProductCollectionContent component. This change improves code maintainability and reduces duplication. * Fix: isDeletedProductReference is not set correctly * Use "page.reload" instead of "admin.page.reload" * Separate PRODUCT_REFERENCE_PICKER and DELETED_PRODUCT_REFERENCE cases This improves readability and maintainability of the switch statement. --------- Co-authored-by: github-actions --- .../product-collection/edit/ProductPicker.tsx | 43 ++--- .../product-collection/edit/editor.scss | 4 + .../blocks/product-collection/edit/index.tsx | 90 ++++++----- .../inspector-advanced-controls/index.tsx | 4 +- .../edit/inspector-controls/index.tsx | 4 +- .../edit/product-collection-content.tsx | 4 +- .../edit/toolbar-controls/index.tsx | 4 +- .../js/blocks/product-collection/types.ts | 10 +- .../js/blocks/product-collection/utils.tsx | 152 ++++++++++++------ .../product-collection.page.ts | 5 +- ...duct-collection-tester.block_theme.spec.ts | 80 +++++++++ ...ollection-handling-missing-product-context | 4 + 12 files changed, 290 insertions(+), 114 deletions(-) create mode 100644 plugins/woocommerce/changelog/51114-add-44878-product-collection-handling-missing-product-context diff --git a/plugins/woocommerce-blocks/assets/js/blocks/product-collection/edit/ProductPicker.tsx b/plugins/woocommerce-blocks/assets/js/blocks/product-collection/edit/ProductPicker.tsx index 3d80edf035c..927d3d31abc 100644 --- a/plugins/woocommerce-blocks/assets/js/blocks/product-collection/edit/ProductPicker.tsx +++ b/plugins/woocommerce-blocks/assets/js/blocks/product-collection/edit/ProductPicker.tsx @@ -21,15 +21,36 @@ import { import type { ProductCollectionEditComponentProps } from '../types'; import { getCollectionByName } from '../collections'; -const ProductPicker = ( props: ProductCollectionEditComponentProps ) => { +const ProductPicker = ( + props: ProductCollectionEditComponentProps & { + isDeletedProductReference: boolean; + } +) => { const blockProps = useBlockProps(); - const attributes = props.attributes; + const { attributes, isDeletedProductReference } = props; const collection = getCollectionByName( attributes.collection ); if ( ! collection ) { - return; + return null; } + const infoText = isDeletedProductReference + ? __( + 'Previously selected product is no longer available.', + 'woocommerce' + ) + : createInterpolateElement( + sprintf( + /* translators: %s: collection title */ + __( + '%s requires a product to be selected in order to display associated items.', + 'woocommerce' + ), + collection.title + ), + { strong: } + ); + return (
@@ -38,21 +59,7 @@ const ProductPicker = ( props: ProductCollectionEditComponentProps ) => { icon={ info } className="wc-blocks-product-collection__info-icon" /> - - { createInterpolateElement( - sprintf( - /* translators: %s: collection title */ - __( - '%s requires a product to be selected in order to display associated items.', - 'woocommerce' - ), - collection.title - ), - { - strong: , - } - ) } - + { infoText } { @@ -31,49 +33,65 @@ const Edit = ( props: ProductCollectionEditComponentProps ) => { [ clientId ] ); - const productCollectionUIStateInEditor = - getProductCollectionUIStateInEditor( { - hasInnerBlocks, + const { productCollectionUIStateInEditor, isLoading } = + useProductCollectionUIState( { location, - attributes: props.attributes, + attributes, + hasInnerBlocks, usesReference: props.usesReference, } ); - /** - * Component to render based on the UI state. - */ - let Component, - isUsingReferencePreviewMode = false; - switch ( productCollectionUIStateInEditor ) { - case ProductCollectionUIStatesInEditor.COLLECTION_PICKER: - Component = ProductCollectionPlaceholder; - break; - case ProductCollectionUIStatesInEditor.PRODUCT_REFERENCE_PICKER: - Component = ProductPicker; - break; - case ProductCollectionUIStatesInEditor.VALID: - Component = ProductCollectionContent; - break; - case ProductCollectionUIStatesInEditor.VALID_WITH_PREVIEW: - Component = ProductCollectionContent; - isUsingReferencePreviewMode = true; - break; - default: - // By default showing collection chooser. - Component = ProductCollectionPlaceholder; + // Show spinner while calculating Editor UI state. + if ( isLoading ) { + return ( + + + + ); } + const productCollectionContentProps: ProductCollectionContentProps = { + ...props, + openCollectionSelectionModal: () => setIsSelectionModalOpen( true ), + location, + isUsingReferencePreviewMode: + productCollectionUIStateInEditor === + ProductCollectionUIStatesInEditor.VALID_WITH_PREVIEW, + }; + + const renderComponent = () => { + switch ( productCollectionUIStateInEditor ) { + case ProductCollectionUIStatesInEditor.COLLECTION_PICKER: + return ; + case ProductCollectionUIStatesInEditor.PRODUCT_REFERENCE_PICKER: + return ( + + ); + case ProductCollectionUIStatesInEditor.DELETED_PRODUCT_REFERENCE: + return ( + + ); + case ProductCollectionUIStatesInEditor.VALID: + case ProductCollectionUIStatesInEditor.VALID_WITH_PREVIEW: + return ( + + ); + default: + return ; + } + }; + return ( <> - - setIsSelectionModalOpen( true ) - } - isUsingReferencePreviewMode={ isUsingReferencePreviewMode } - location={ location } - usesReference={ props.usesReference } - /> + { renderComponent() } { isSelectionModalOpen && ( + props: ProductCollectionContentProps ) { const { clientId, attributes, setAttributes } = props; const { forcePageReload } = attributes; diff --git a/plugins/woocommerce-blocks/assets/js/blocks/product-collection/edit/inspector-controls/index.tsx b/plugins/woocommerce-blocks/assets/js/blocks/product-collection/edit/inspector-controls/index.tsx index a55d9dbb84a..cf281729f24 100644 --- a/plugins/woocommerce-blocks/assets/js/blocks/product-collection/edit/inspector-controls/index.tsx +++ b/plugins/woocommerce-blocks/assets/js/blocks/product-collection/edit/inspector-controls/index.tsx @@ -27,7 +27,7 @@ import { import metadata from '../../block.json'; import { useTracksLocation } from '../../tracks-utils'; import { - ProductCollectionEditComponentProps, + ProductCollectionContentProps, ProductCollectionAttributes, CoreFilterNames, FilterName, @@ -58,7 +58,7 @@ const prepareShouldShowFilter = }; const ProductCollectionInspectorControls = ( - props: ProductCollectionEditComponentProps + props: ProductCollectionContentProps ) => { const { attributes, context, setAttributes } = props; const { query, hideControls, displayLayout } = attributes; diff --git a/plugins/woocommerce-blocks/assets/js/blocks/product-collection/edit/product-collection-content.tsx b/plugins/woocommerce-blocks/assets/js/blocks/product-collection/edit/product-collection-content.tsx index 35714946c42..4eaf299d034 100644 --- a/plugins/woocommerce-blocks/assets/js/blocks/product-collection/edit/product-collection-content.tsx +++ b/plugins/woocommerce-blocks/assets/js/blocks/product-collection/edit/product-collection-content.tsx @@ -18,7 +18,7 @@ import fastDeepEqual from 'fast-deep-equal/es6'; import type { ProductCollectionAttributes, ProductCollectionQuery, - ProductCollectionEditComponentProps, + ProductCollectionContentProps, } from '../types'; import { DEFAULT_ATTRIBUTES, INNER_BLOCKS_TEMPLATE } from '../constants'; import { @@ -68,7 +68,7 @@ const useQueryId = ( const ProductCollectionContent = ( { preview: { setPreviewState, initialPreviewState } = {}, ...props -}: ProductCollectionEditComponentProps ) => { +}: ProductCollectionContentProps ) => { const isInitialAttributesSet = useRef( false ); const { clientId, diff --git a/plugins/woocommerce-blocks/assets/js/blocks/product-collection/edit/toolbar-controls/index.tsx b/plugins/woocommerce-blocks/assets/js/blocks/product-collection/edit/toolbar-controls/index.tsx index c7252aab36e..3808dfdf120 100644 --- a/plugins/woocommerce-blocks/assets/js/blocks/product-collection/edit/toolbar-controls/index.tsx +++ b/plugins/woocommerce-blocks/assets/js/blocks/product-collection/edit/toolbar-controls/index.tsx @@ -11,10 +11,10 @@ import { setQueryAttribute } from '../../utils'; import DisplaySettingsToolbar from './display-settings-toolbar'; import DisplayLayoutToolbar from './display-layout-toolbar'; import CollectionChooserToolbar from './collection-chooser-toolbar'; -import type { ProductCollectionEditComponentProps } from '../../types'; +import type { ProductCollectionContentProps } from '../../types'; export default function ToolbarControls( - props: Omit< ProductCollectionEditComponentProps, 'preview' > + props: ProductCollectionContentProps ) { const { attributes, openCollectionSelectionModal, setAttributes } = props; const { query, displayLayout } = attributes; diff --git a/plugins/woocommerce-blocks/assets/js/blocks/product-collection/types.ts b/plugins/woocommerce-blocks/assets/js/blocks/product-collection/types.ts index 55a8ee9b460..4d37c928d7e 100644 --- a/plugins/woocommerce-blocks/assets/js/blocks/product-collection/types.ts +++ b/plugins/woocommerce-blocks/assets/js/blocks/product-collection/types.ts @@ -14,9 +14,9 @@ export enum ProductCollectionUIStatesInEditor { PRODUCT_REFERENCE_PICKER = 'product_context_picker', VALID_WITH_PREVIEW = 'uses_reference_preview_mode', VALID = 'valid', + DELETED_PRODUCT_REFERENCE = 'deleted_product_reference', // Future states // INVALID = 'invalid', - // DELETED_PRODUCT_REFERENCE = 'deleted_product_reference', } export interface ProductCollectionAttributes { @@ -110,7 +110,6 @@ export interface ProductCollectionQuery { export type ProductCollectionEditComponentProps = BlockEditProps< ProductCollectionAttributes > & { - openCollectionSelectionModal: () => void; preview?: { initialPreviewState?: PreviewState; setPreviewState?: SetPreviewState; @@ -119,8 +118,13 @@ export type ProductCollectionEditComponentProps = context: { templateSlug: string; }; - isUsingReferencePreviewMode: boolean; + }; + +export type ProductCollectionContentProps = + ProductCollectionEditComponentProps & { location: WooCommerceBlockLocation; + isUsingReferencePreviewMode: boolean; + openCollectionSelectionModal: () => void; }; export type TProductCollectionOrder = 'asc' | 'desc'; diff --git a/plugins/woocommerce-blocks/assets/js/blocks/product-collection/utils.tsx b/plugins/woocommerce-blocks/assets/js/blocks/product-collection/utils.tsx index 0565027bfe1..4e8ebc23fab 100644 --- a/plugins/woocommerce-blocks/assets/js/blocks/product-collection/utils.tsx +++ b/plugins/woocommerce-blocks/assets/js/blocks/product-collection/utils.tsx @@ -3,10 +3,16 @@ */ import { store as blockEditorStore } from '@wordpress/block-editor'; import { addFilter } from '@wordpress/hooks'; -import { select } from '@wordpress/data'; +import { select, useSelect } from '@wordpress/data'; +import { store as coreDataStore } from '@wordpress/core-data'; import { isWpVersion } from '@woocommerce/settings'; import type { BlockEditProps, Block } from '@wordpress/blocks'; -import { useEffect, useLayoutEffect, useState } from '@wordpress/element'; +import { + useEffect, + useLayoutEffect, + useState, + useMemo, +} from '@wordpress/element'; import { __ } from '@wordpress/i18n'; import type { ProductResponseItem } from '@woocommerce/types'; import { getProduct } from '@woocommerce/editor-components/utils'; @@ -193,7 +199,7 @@ export const getUsesReferencePreviewMessage = ( return ''; }; -export const getProductCollectionUIStateInEditor = ( { +export const useProductCollectionUIState = ( { location, usesReference, attributes, @@ -203,59 +209,111 @@ export const getProductCollectionUIStateInEditor = ( { usesReference?: string[] | undefined; attributes: ProductCollectionAttributes; hasInnerBlocks: boolean; -} ): ProductCollectionUIStatesInEditor => { - const isInRequiredLocation = usesReference?.includes( location.type ); - const isCollectionSelected = !! attributes.collection; +} ) => { + // Fetch product to check if it's deleted. + // `product` will be undefined if it doesn't exist. + const productId = attributes.query?.productReference; + const { product, hasResolved } = useSelect( + ( selectFunc ) => { + if ( ! productId ) { + return { product: null, hasResolved: true }; + } - /** - * Case 1: Product context picker - */ - const isProductContextRequired = usesReference?.includes( 'product' ); - const isProductContextSelected = - ( attributes.query?.productReference ?? null ) !== null; - if ( - isCollectionSelected && - isProductContextRequired && - ! isInRequiredLocation && - ! isProductContextSelected - ) { - return ProductCollectionUIStatesInEditor.PRODUCT_REFERENCE_PICKER; - } + const { getEntityRecord, hasFinishedResolution } = + selectFunc( coreDataStore ); + const selectorArgs = [ 'postType', 'product', productId ]; + return { + product: getEntityRecord( ...selectorArgs ), + hasResolved: hasFinishedResolution( + 'getEntityRecord', + selectorArgs + ), + }; + }, + [ productId ] + ); + + const productCollectionUIStateInEditor = useMemo( () => { + const isInRequiredLocation = usesReference?.includes( location.type ); + const isCollectionSelected = !! attributes.collection; - /** - * Case 2: Preview mode - based on `usesReference` value - */ - if ( isInRequiredLocation ) { /** - * Block shouldn't be in preview mode when: - * 1. Current location is archive and termId is available. - * 2. Current location is product and productId is available. - * - * Because in these cases, we have required context on the editor side. + * Case 1: Product context picker */ - const isArchiveLocationWithTermId = - location.type === LocationType.Archive && - ( location.sourceData?.termId ?? null ) !== null; - const isProductLocationWithProductId = - location.type === LocationType.Product && - ( location.sourceData?.productId ?? null ) !== null; - + const isProductContextRequired = usesReference?.includes( 'product' ); + const isProductContextSelected = + ( attributes.query?.productReference ?? null ) !== null; if ( - ! isArchiveLocationWithTermId && - ! isProductLocationWithProductId + isCollectionSelected && + isProductContextRequired && + ! isInRequiredLocation && + ! isProductContextSelected ) { - return ProductCollectionUIStatesInEditor.VALID_WITH_PREVIEW; + return ProductCollectionUIStatesInEditor.PRODUCT_REFERENCE_PICKER; } - } - /** - * Case 3: Collection chooser - */ - if ( ! hasInnerBlocks && ! isCollectionSelected ) { - return ProductCollectionUIStatesInEditor.COLLECTION_PICKER; - } + // Case 2: Deleted product reference + if ( + isCollectionSelected && + isProductContextRequired && + ! isInRequiredLocation && + isProductContextSelected + ) { + const isProductDeleted = + productId && + ( product === undefined || product?.status === 'trash' ); + if ( isProductDeleted ) { + return ProductCollectionUIStatesInEditor.DELETED_PRODUCT_REFERENCE; + } + } - return ProductCollectionUIStatesInEditor.VALID; + /** + * Case 3: Preview mode - based on `usesReference` value + */ + if ( isInRequiredLocation ) { + /** + * Block shouldn't be in preview mode when: + * 1. Current location is archive and termId is available. + * 2. Current location is product and productId is available. + * + * Because in these cases, we have required context on the editor side. + */ + const isArchiveLocationWithTermId = + location.type === LocationType.Archive && + ( location.sourceData?.termId ?? null ) !== null; + const isProductLocationWithProductId = + location.type === LocationType.Product && + ( location.sourceData?.productId ?? null ) !== null; + + if ( + ! isArchiveLocationWithTermId && + ! isProductLocationWithProductId + ) { + return ProductCollectionUIStatesInEditor.VALID_WITH_PREVIEW; + } + } + + /** + * Case 4: Collection chooser + */ + if ( ! hasInnerBlocks && ! isCollectionSelected ) { + return ProductCollectionUIStatesInEditor.COLLECTION_PICKER; + } + + return ProductCollectionUIStatesInEditor.VALID; + }, [ + location.type, + location.sourceData?.termId, + location.sourceData?.productId, + usesReference, + attributes.collection, + productId, + product, + hasInnerBlocks, + attributes.query?.productReference, + ] ); + + return { productCollectionUIStateInEditor, isLoading: ! hasResolved }; }; export const useSetPreviewState = ( { diff --git a/plugins/woocommerce-blocks/tests/e2e/tests/product-collection/product-collection.page.ts b/plugins/woocommerce-blocks/tests/e2e/tests/product-collection/product-collection.page.ts index 1a87ebeb605..3b94f037eeb 100644 --- a/plugins/woocommerce-blocks/tests/e2e/tests/product-collection/product-collection.page.ts +++ b/plugins/woocommerce-blocks/tests/e2e/tests/product-collection/product-collection.page.ts @@ -207,7 +207,8 @@ class ProductCollectionPage { } async chooseProductInEditorProductPickerIfAvailable( - pageReference: Page | FrameLocator + pageReference: Page | FrameLocator, + productName = 'Album' ) { const editorProductPicker = pageReference.locator( SELECTORS.productPicker @@ -217,7 +218,7 @@ class ProductCollectionPage { await editorProductPicker .locator( 'label' ) .filter( { - hasText: 'Album', + hasText: productName, } ) .click(); } diff --git a/plugins/woocommerce-blocks/tests/e2e/tests/product-collection/register-product-collection-tester.block_theme.spec.ts b/plugins/woocommerce-blocks/tests/e2e/tests/product-collection/register-product-collection-tester.block_theme.spec.ts index a7ea710f8a4..6fd09e4050c 100644 --- a/plugins/woocommerce-blocks/tests/e2e/tests/product-collection/register-product-collection-tester.block_theme.spec.ts +++ b/plugins/woocommerce-blocks/tests/e2e/tests/product-collection/register-product-collection-tester.block_theme.spec.ts @@ -356,4 +356,84 @@ test.describe( 'Product Collection registration', () => { await expect( previewButtonLocator ).toBeHidden(); } ); } ); + + test( 'Product picker should be shown when selected product is deleted', async ( { + pageObject, + admin, + editor, + requestUtils, + page, + } ) => { + // Add a new test product to the database + let testProductId: number | null = null; + const newProduct = await requestUtils.rest( { + method: 'POST', + path: 'wc/v3/products', + data: { + name: 'A Test Product', + price: 10, + }, + } ); + testProductId = newProduct.id; + + await admin.createNewPost(); + await pageObject.insertProductCollection(); + await pageObject.chooseCollectionInPost( + 'myCustomCollectionWithProductContext' + ); + + // Verify that product picker is shown in Editor + const editorProductPicker = editor.canvas.locator( + SELECTORS.productPicker + ); + await expect( editorProductPicker ).toBeVisible(); + + // Once a product is selected, the product picker should be hidden + await pageObject.chooseProductInEditorProductPickerIfAvailable( + editor.canvas, + 'A Test Product' + ); + await expect( editorProductPicker ).toBeHidden(); + + await editor.saveDraft(); + + // Delete the product + await requestUtils.rest( { + method: 'DELETE', + path: `wc/v3/products/${ testProductId }`, + } ); + + // Product picker should be shown in Editor + await admin.page.reload(); + const deletedProductPicker = editor.canvas.getByText( + 'Previously selected product' + ); + await expect( deletedProductPicker ).toBeVisible(); + + // Change status from "trash" to "publish" + await requestUtils.rest( { + method: 'PUT', + path: `wc/v3/products/${ testProductId }`, + data: { + status: 'publish', + }, + } ); + + // Product Picker shouldn't be shown as product is available now + await page.reload(); + await expect( editorProductPicker ).toBeHidden(); + + // Delete the product from database, instead of trashing it + await requestUtils.rest( { + method: 'DELETE', + path: `wc/v3/products/${ testProductId }`, + params: { + // Bypass trash and permanently delete the product + force: true, + }, + } ); + + // Product picker should be shown in Editor + await expect( deletedProductPicker ).toBeVisible(); + } ); } ); diff --git a/plugins/woocommerce/changelog/51114-add-44878-product-collection-handling-missing-product-context b/plugins/woocommerce/changelog/51114-add-44878-product-collection-handling-missing-product-context new file mode 100644 index 00000000000..5e5b6821ab3 --- /dev/null +++ b/plugins/woocommerce/changelog/51114-add-44878-product-collection-handling-missing-product-context @@ -0,0 +1,4 @@ +Significance: minor +Type: add + +Product Collection: Added Editor UI for missing product reference \ No newline at end of file