woocommerce/plugins/woocommerce-blocks/assets/js/blocks/product-template/utils.tsx

352 lines
8.9 KiB
TypeScript
Raw Normal View History

Product Collection: Make attributes available in rest_product_query hook (#44150) * Make attributes available in rest_product_query hook This commit introduces the 'includeInQueryContext' attribute to the 'woocommerce/product-collection' block and updates the 'woocommerce/product-template' block to consume this new attribute. Key Changes: 1. `woocommerce/product-collection` Block: - A new attribute 'includeInQueryContext' is added in `block.json`. This attribute is designed to hold a list of attribute names relevant for the query context. - The 'includeInQueryContext' attribute is included in the `providesContext` field to ensure its availability to child blocks. - In `constants.ts`, default values for 'includeInQueryContext' are defined, specifying 'collection' and 'id' as initial attributes. - The `types.ts` file is updated with a comment explaining the purpose of 'includeInQueryContext'. 2. `woocommerce/product-template` Block: - Modified `block.json` to utilize the 'includeInQueryContext' context provided by the parent `woocommerce/product-collection` block. - The `edit.tsx` file is updated to handle the new context. It uses a newly added utility function `useProductCollectionBlockAttributes` from `utils.tsx` to access parent block attributes. - The `utils.tsx` file is introduced, containing the `useProductCollectionBlockAttributes` hook. This hook is responsible for finding the parent 'woocommerce/product-collection' block and returning its attributes. - Within `edit.tsx`, logic is added to create a query context object based on the attributes specified in 'includeInQueryContext', enhancing the block's ability to dynamically adapt to changes. * Remove commented code * Rename query context attribute and optimize parent block detection This commit introduces two significant changes aimed at improving code readability and efficiency. 1. **Renaming of Query Context Attribute:** - The attribute `includeInQueryContext` has been renamed to `queryContextIncludes` across various files, including block JSON configurations and TypeScript definitions. This change makes the attribute's purpose more intuitive, indicating it specifies which attributes to include in the query context. 2. **Optimized Parent Block Detection:** - Replaced the use of `getBlockParents` with `getBlockParentsByBlockName` in utility functions to find the closest Product Collection block. This optimization allows for a more direct and efficient way to identify the relevant parent block by specifying the block name, reducing unnecessary iterations and improving code performance. * Streamline query context construction in product template Key Changes: - **Introduction of `useProductCollectionQueryContext` Hook:** This new hook takes the `clientId` and `queryContextIncludes` as inputs and returns a query context object. It encapsulates the logic for fetching parent product collection block attributes and constructing the query context accordingly. This abstraction simplifies the edit component's logic, focusing on the essentials and improving code readability. - **Optimization of Parent Block Detection:** The hook uses `getBlockParentsByBlockName` to accurately and efficiently find the closest parent `Product Collection` block, minimizing the overhead previously associated with traversing the block hierarchy. * Always include `collection` and `id` in query context * Minor refactor * Enhance query context handling for more maintainable code - Introduced `DEFAULT_QUERY_CONTEXT_ATTRIBUTES` in `edit.tsx` to maintain a clear list of default query context attributes. - Modified `ProductTemplateEdit` to automatically include these default attributes in `queryContextIncludes`, ensuring they are always part of the query context without manual initialization. - Simplified `useProductCollectionQueryContext` in `utils.tsx` by removing static initialization of 'collection' and 'id', relying instead on the dynamic addition of necessary attributes from `queryContextIncludes`. This refactor enhances the maintainability and clarity of the code, ensuring a solid foundation for future enhancements and features. * Add E2E tests for Product Collection query context - Added a new test suite 'Query Context in Editor' to validate the correctness of query context parameters when the Product Collection block is used. This suite ensures that: - For the 'Product Catalog', only the ID is sent in the query context, confirming that collection-specific parameters are excluded when not relevant. - For collections such as 'On Sale', the collection name is correctly passed in the query context, validating that the block dynamically adjusts query parameters based on its settings. - Introduced a new utility method `setupAndFetchQueryContextURL` in `product-collection.page.ts`. This method automates the setup of a post with the Product Collection block and fetches the URL with query context parameters, facilitating the validation of query context handling. * Add changefile(s) from automation for the following project(s): woocommerce-blocks * Fix edge case when `queryContextIncludes` is not defined - Initializing `queryContextIncludes` with a default empty array directly in the destructuring assignment of the component's props. This approach ensures that `queryContextIncludes` is always an array, simplifying downstream logic. - Creating a new constant `queryContextIncludesWithDefaults` to hold the combination of `queryContextIncludes` and `DEFAULT_QUERY_CONTEXT_ATTRIBUTES`. This step avoids directly mutating the `queryContextIncludes` prop, aligning with best practices for functional purity and making the code easier to understand and debug. - Updating the `useProductCollectionQueryContext` hook call to use `queryContextIncludesWithDefaults`. This ensures that the default query context attributes are consistently included without altering the original prop. These adjustments not only enhance the code's maintainability but also ensure more predictable behavior by avoiding side effects related to parameter mutation. --------- Co-authored-by: github-actions <github-actions@github.com>
2024-02-12 08:45:24 +00:00
/**
* External dependencies
*/
Getting the Product Collection location/context (#43997) * Early implementation of getting the Product Collection location/context * Solve the problem of async fetch in the hook * Improve typing * Import core data store instead of hardcoding store name * Recognise Product Category and Product Tag * Remove attr property from archive location data * Unify states naming * Add TODO entry * Display the info about the location of Product Collection * Improve the typing * Recognise if Product Collection is nested in Single Product block * Improve cases descriptions and add some defaults to potentially undefined values * Change the taxonomies sourceData * Recognise Mini Cart as Cart context * Recognise attribute as archive contect but no taxonomy * Refactor the function into single useEffect and clean it up * Fix typo * Remove unnecessary import * Stop rendering the output in Editor (it was for demo purposes) * Pass location data to Product Template query in Editor * Replace templateSlugs literal strings with object reference * Rename parseResponse function to more specific name getIdFromResponse * Add dpeendency array to useEffect * Refactor templates detection * Use full taxonomy names instead of shortcuts * Write down scenarios to test * Working scenario * Change the verification way for more robust * Add more robust methods to include Single Product block * Add test Product Collection in Single Product block in a Single Product Template * Imprvoe the order of veryfing the requests * Fix linter issues. Although that makes code less readable * Improve the useGetLocation typing so it's more generic * Rework the E2E tests regarding location of Product Collection and limit their number * Bring back necessary eslint-disable * Remove unused imports * Uncomment line required for other tests * Add changelog * Rename constant from BLOCK_NAME to BLOCK_SLUG as it's a slug * Add a BLOCK_NAME constant and replace the literal block name usages in E2E tests * Fix post merge issues * Fix test after merge * Adjust the tests to kick off waiting for request before action that triggers them
2024-02-12 19:59:40 +00:00
import { resolveSelect, useSelect } from '@wordpress/data';
import { useState, useEffect, useMemo } from '@wordpress/element';
import { store as coreStore } from '@wordpress/core-data';
import { store as blockEditorStore } from '@wordpress/block-editor';
type LocationType = 'product' | 'archive' | 'cart' | 'order' | 'generic';
type Context< T > = T & {
templateSlug?: string;
postId?: number;
};
type SetEntityId = (
kind: 'postType' | 'taxonomy',
name: 'product' | 'product_cat' | 'product_tag',
slug: string,
stateSetter: ( entityId: number | null ) => void
) => void;
const templateSlugs = {
singleProduct: 'single-product',
productCategory: 'taxonomy-product_cat',
productTag: 'taxonomy-product_tag',
productAttribute: 'taxonomy-product_attribute',
orderConfirmation: 'order-confirmation',
cart: 'page-cart',
checkout: 'page-checkout',
};
const getIdFromResponse = ( resp?: Record< 'id', number >[] ): number | null =>
resp && resp.length && resp[ 0 ]?.id ? resp[ 0 ].id : null;
const setEntityId: SetEntityId = async ( kind, name, slug, stateSetter ) => {
const response = ( await resolveSelect( coreStore ).getEntityRecords(
kind,
name,
{
_fields: [ 'id' ],
slug,
}
) ) as Record< 'id', number >[];
const entityId = getIdFromResponse( response );
stateSetter( entityId );
};
const prepareGetEntitySlug =
( templateSlug: string ) =>
( entitySlug: string ): string =>
templateSlug.replace( `${ entitySlug }-`, '' );
const prepareIsInSpecificTemplate =
( templateSlug: string ) =>
( entitySlug: string ): boolean =>
templateSlug.includes( entitySlug ) && templateSlug !== entitySlug;
const prepareIsInGenericTemplate =
( templateSlug: string ) =>
( entitySlug: string ): boolean =>
templateSlug === entitySlug;
const createLocationObject = ( type: LocationType, sourceData = {} ) => ( {
type,
sourceData,
} );
type ContextProperties = {
templateSlug: string;
postId?: string;
};
export const useGetLocation = < T, >(
context: Context< T & ContextProperties >,
clientId: string
) => {
const templateSlug = context.templateSlug || '';
const postId = context.postId || null;
const getEntitySlug = prepareGetEntitySlug( templateSlug );
const isInSpecificTemplate = prepareIsInSpecificTemplate( templateSlug );
// Detect Specific Templates
const isInSpecificProductTemplate = isInSpecificTemplate(
templateSlugs.singleProduct
);
const isInSpecificCategoryTemplate = isInSpecificTemplate(
templateSlugs.productCategory
);
const isInSpecificTagTemplate = isInSpecificTemplate(
templateSlugs.productTag
);
const [ productId, setProductId ] = useState< number | null >( null );
const [ categoryId, setCategoryId ] = useState< number | null >( null );
const [ tagId, setTagId ] = useState< number | null >( null );
useEffect( () => {
if ( isInSpecificProductTemplate ) {
const slug = getEntitySlug( templateSlugs.singleProduct );
setEntityId( 'postType', 'product', slug, setProductId );
}
if ( isInSpecificCategoryTemplate ) {
const slug = getEntitySlug( templateSlugs.productCategory );
setEntityId( 'taxonomy', 'product_cat', slug, setCategoryId );
}
if ( isInSpecificTagTemplate ) {
const slug = getEntitySlug( templateSlugs.productTag );
setEntityId( 'taxonomy', 'product_tag', slug, setTagId );
}
}, [
isInSpecificProductTemplate,
isInSpecificCategoryTemplate,
isInSpecificTagTemplate,
getEntitySlug,
] );
const { isInSingleProductBlock, isInSomeCartCheckoutBlock } = useSelect(
( select ) => {
// eslint-disable-next-line @typescript-eslint/ban-ts-comment
// @ts-ignore No types for this selector exist yet
const { getBlockParentsByBlockName } = select( blockEditorStore );
const isInBlocks = ( parentBlockNames: string[] ) =>
getBlockParentsByBlockName( clientId, parentBlockNames )
.length > 0;
return {
isInSingleProductBlock: isInBlocks( [
'woocommerce/single-product',
] ),
isInSomeCartCheckoutBlock: isInBlocks( [
'woocommerce/cart',
'woocommerce/checkout',
'woocommerce/mini-cart-contents',
] ),
};
},
Getting the Product Collection location/context (#43997) * Early implementation of getting the Product Collection location/context * Solve the problem of async fetch in the hook * Improve typing * Import core data store instead of hardcoding store name * Recognise Product Category and Product Tag * Remove attr property from archive location data * Unify states naming * Add TODO entry * Display the info about the location of Product Collection * Improve the typing * Recognise if Product Collection is nested in Single Product block * Improve cases descriptions and add some defaults to potentially undefined values * Change the taxonomies sourceData * Recognise Mini Cart as Cart context * Recognise attribute as archive contect but no taxonomy * Refactor the function into single useEffect and clean it up * Fix typo * Remove unnecessary import * Stop rendering the output in Editor (it was for demo purposes) * Pass location data to Product Template query in Editor * Replace templateSlugs literal strings with object reference * Rename parseResponse function to more specific name getIdFromResponse * Add dpeendency array to useEffect * Refactor templates detection * Use full taxonomy names instead of shortcuts * Write down scenarios to test * Working scenario * Change the verification way for more robust * Add more robust methods to include Single Product block * Add test Product Collection in Single Product block in a Single Product Template * Imprvoe the order of veryfing the requests * Fix linter issues. Although that makes code less readable * Improve the useGetLocation typing so it's more generic * Rework the E2E tests regarding location of Product Collection and limit their number * Bring back necessary eslint-disable * Remove unused imports * Uncomment line required for other tests * Add changelog * Rename constant from BLOCK_NAME to BLOCK_SLUG as it's a slug * Add a BLOCK_NAME constant and replace the literal block name usages in E2E tests * Fix post merge issues * Fix test after merge * Adjust the tests to kick off waiting for request before action that triggers them
2024-02-12 19:59:40 +00:00
[ clientId ]
);
/**
* Case 1.1: BLOCK LEVEL: SPECIFIC PRODUCT
Getting the Product Collection location/context (#43997) * Early implementation of getting the Product Collection location/context * Solve the problem of async fetch in the hook * Improve typing * Import core data store instead of hardcoding store name * Recognise Product Category and Product Tag * Remove attr property from archive location data * Unify states naming * Add TODO entry * Display the info about the location of Product Collection * Improve the typing * Recognise if Product Collection is nested in Single Product block * Improve cases descriptions and add some defaults to potentially undefined values * Change the taxonomies sourceData * Recognise Mini Cart as Cart context * Recognise attribute as archive contect but no taxonomy * Refactor the function into single useEffect and clean it up * Fix typo * Remove unnecessary import * Stop rendering the output in Editor (it was for demo purposes) * Pass location data to Product Template query in Editor * Replace templateSlugs literal strings with object reference * Rename parseResponse function to more specific name getIdFromResponse * Add dpeendency array to useEffect * Refactor templates detection * Use full taxonomy names instead of shortcuts * Write down scenarios to test * Working scenario * Change the verification way for more robust * Add more robust methods to include Single Product block * Add test Product Collection in Single Product block in a Single Product Template * Imprvoe the order of veryfing the requests * Fix linter issues. Although that makes code less readable * Improve the useGetLocation typing so it's more generic * Rework the E2E tests regarding location of Product Collection and limit their number * Bring back necessary eslint-disable * Remove unused imports * Uncomment line required for other tests * Add changelog * Rename constant from BLOCK_NAME to BLOCK_SLUG as it's a slug * Add a BLOCK_NAME constant and replace the literal block name usages in E2E tests * Fix post merge issues * Fix test after merge * Adjust the tests to kick off waiting for request before action that triggers them
2024-02-12 19:59:40 +00:00
* Single Product block - take product ID from context
*/
if ( isInSingleProductBlock ) {
return createLocationObject( 'product', { productId: postId } );
}
/**
* Case 1.2: BLOCK LEVEL: GENERIC CART
* Cart, Checkout or Mini Cart blocks - block scope is more important than template
*/
if ( isInSomeCartCheckoutBlock ) {
return createLocationObject( 'cart' );
}
/**
* Case 2.1: TEMPLATES: SPECIFIC PRODUCT
Getting the Product Collection location/context (#43997) * Early implementation of getting the Product Collection location/context * Solve the problem of async fetch in the hook * Improve typing * Import core data store instead of hardcoding store name * Recognise Product Category and Product Tag * Remove attr property from archive location data * Unify states naming * Add TODO entry * Display the info about the location of Product Collection * Improve the typing * Recognise if Product Collection is nested in Single Product block * Improve cases descriptions and add some defaults to potentially undefined values * Change the taxonomies sourceData * Recognise Mini Cart as Cart context * Recognise attribute as archive contect but no taxonomy * Refactor the function into single useEffect and clean it up * Fix typo * Remove unnecessary import * Stop rendering the output in Editor (it was for demo purposes) * Pass location data to Product Template query in Editor * Replace templateSlugs literal strings with object reference * Rename parseResponse function to more specific name getIdFromResponse * Add dpeendency array to useEffect * Refactor templates detection * Use full taxonomy names instead of shortcuts * Write down scenarios to test * Working scenario * Change the verification way for more robust * Add more robust methods to include Single Product block * Add test Product Collection in Single Product block in a Single Product Template * Imprvoe the order of veryfing the requests * Fix linter issues. Although that makes code less readable * Improve the useGetLocation typing so it's more generic * Rework the E2E tests regarding location of Product Collection and limit their number * Bring back necessary eslint-disable * Remove unused imports * Uncomment line required for other tests * Add changelog * Rename constant from BLOCK_NAME to BLOCK_SLUG as it's a slug * Add a BLOCK_NAME constant and replace the literal block name usages in E2E tests * Fix post merge issues * Fix test after merge * Adjust the tests to kick off waiting for request before action that triggers them
2024-02-12 19:59:40 +00:00
* Specific Single Product template - take product ID from taxononmy
*/
if ( isInSpecificProductTemplate ) {
return createLocationObject( 'product', { productId } );
}
const isInGenericTemplate = prepareIsInGenericTemplate( templateSlug );
/**
* Case 2.2: TEMPLATES: GENERIC PRODUCT
Getting the Product Collection location/context (#43997) * Early implementation of getting the Product Collection location/context * Solve the problem of async fetch in the hook * Improve typing * Import core data store instead of hardcoding store name * Recognise Product Category and Product Tag * Remove attr property from archive location data * Unify states naming * Add TODO entry * Display the info about the location of Product Collection * Improve the typing * Recognise if Product Collection is nested in Single Product block * Improve cases descriptions and add some defaults to potentially undefined values * Change the taxonomies sourceData * Recognise Mini Cart as Cart context * Recognise attribute as archive contect but no taxonomy * Refactor the function into single useEffect and clean it up * Fix typo * Remove unnecessary import * Stop rendering the output in Editor (it was for demo purposes) * Pass location data to Product Template query in Editor * Replace templateSlugs literal strings with object reference * Rename parseResponse function to more specific name getIdFromResponse * Add dpeendency array to useEffect * Refactor templates detection * Use full taxonomy names instead of shortcuts * Write down scenarios to test * Working scenario * Change the verification way for more robust * Add more robust methods to include Single Product block * Add test Product Collection in Single Product block in a Single Product Template * Imprvoe the order of veryfing the requests * Fix linter issues. Although that makes code less readable * Improve the useGetLocation typing so it's more generic * Rework the E2E tests regarding location of Product Collection and limit their number * Bring back necessary eslint-disable * Remove unused imports * Uncomment line required for other tests * Add changelog * Rename constant from BLOCK_NAME to BLOCK_SLUG as it's a slug * Add a BLOCK_NAME constant and replace the literal block name usages in E2E tests * Fix post merge issues * Fix test after merge * Adjust the tests to kick off waiting for request before action that triggers them
2024-02-12 19:59:40 +00:00
* Generic Single Product template
*/
const isInSingleProductTemplate = isInGenericTemplate(
templateSlugs.singleProduct
);
if ( isInSingleProductTemplate ) {
return createLocationObject( 'product', { productId: null } );
}
/**
* Case 2.3: TEMPLATES: SPECIFIC TAXONOMY
Getting the Product Collection location/context (#43997) * Early implementation of getting the Product Collection location/context * Solve the problem of async fetch in the hook * Improve typing * Import core data store instead of hardcoding store name * Recognise Product Category and Product Tag * Remove attr property from archive location data * Unify states naming * Add TODO entry * Display the info about the location of Product Collection * Improve the typing * Recognise if Product Collection is nested in Single Product block * Improve cases descriptions and add some defaults to potentially undefined values * Change the taxonomies sourceData * Recognise Mini Cart as Cart context * Recognise attribute as archive contect but no taxonomy * Refactor the function into single useEffect and clean it up * Fix typo * Remove unnecessary import * Stop rendering the output in Editor (it was for demo purposes) * Pass location data to Product Template query in Editor * Replace templateSlugs literal strings with object reference * Rename parseResponse function to more specific name getIdFromResponse * Add dpeendency array to useEffect * Refactor templates detection * Use full taxonomy names instead of shortcuts * Write down scenarios to test * Working scenario * Change the verification way for more robust * Add more robust methods to include Single Product block * Add test Product Collection in Single Product block in a Single Product Template * Imprvoe the order of veryfing the requests * Fix linter issues. Although that makes code less readable * Improve the useGetLocation typing so it's more generic * Rework the E2E tests regarding location of Product Collection and limit their number * Bring back necessary eslint-disable * Remove unused imports * Uncomment line required for other tests * Add changelog * Rename constant from BLOCK_NAME to BLOCK_SLUG as it's a slug * Add a BLOCK_NAME constant and replace the literal block name usages in E2E tests * Fix post merge issues * Fix test after merge * Adjust the tests to kick off waiting for request before action that triggers them
2024-02-12 19:59:40 +00:00
* Specific Category template - take category ID from
*/
if ( isInSpecificCategoryTemplate ) {
return createLocationObject( 'archive', {
taxonomy: 'product_cat',
termId: categoryId,
} );
}
/**
* Case 2.4: TEMPLATES: SPECIFIC TAXONOMY
Getting the Product Collection location/context (#43997) * Early implementation of getting the Product Collection location/context * Solve the problem of async fetch in the hook * Improve typing * Import core data store instead of hardcoding store name * Recognise Product Category and Product Tag * Remove attr property from archive location data * Unify states naming * Add TODO entry * Display the info about the location of Product Collection * Improve the typing * Recognise if Product Collection is nested in Single Product block * Improve cases descriptions and add some defaults to potentially undefined values * Change the taxonomies sourceData * Recognise Mini Cart as Cart context * Recognise attribute as archive contect but no taxonomy * Refactor the function into single useEffect and clean it up * Fix typo * Remove unnecessary import * Stop rendering the output in Editor (it was for demo purposes) * Pass location data to Product Template query in Editor * Replace templateSlugs literal strings with object reference * Rename parseResponse function to more specific name getIdFromResponse * Add dpeendency array to useEffect * Refactor templates detection * Use full taxonomy names instead of shortcuts * Write down scenarios to test * Working scenario * Change the verification way for more robust * Add more robust methods to include Single Product block * Add test Product Collection in Single Product block in a Single Product Template * Imprvoe the order of veryfing the requests * Fix linter issues. Although that makes code less readable * Improve the useGetLocation typing so it's more generic * Rework the E2E tests regarding location of Product Collection and limit their number * Bring back necessary eslint-disable * Remove unused imports * Uncomment line required for other tests * Add changelog * Rename constant from BLOCK_NAME to BLOCK_SLUG as it's a slug * Add a BLOCK_NAME constant and replace the literal block name usages in E2E tests * Fix post merge issues * Fix test after merge * Adjust the tests to kick off waiting for request before action that triggers them
2024-02-12 19:59:40 +00:00
* Specific Tag template
*/
if ( isInSpecificTagTemplate ) {
return createLocationObject( 'archive', {
taxonomy: 'product_tag',
termId: tagId,
} );
}
/**
* Case 2.5: TEMPLATES: GENERIC TAXONOMY
Getting the Product Collection location/context (#43997) * Early implementation of getting the Product Collection location/context * Solve the problem of async fetch in the hook * Improve typing * Import core data store instead of hardcoding store name * Recognise Product Category and Product Tag * Remove attr property from archive location data * Unify states naming * Add TODO entry * Display the info about the location of Product Collection * Improve the typing * Recognise if Product Collection is nested in Single Product block * Improve cases descriptions and add some defaults to potentially undefined values * Change the taxonomies sourceData * Recognise Mini Cart as Cart context * Recognise attribute as archive contect but no taxonomy * Refactor the function into single useEffect and clean it up * Fix typo * Remove unnecessary import * Stop rendering the output in Editor (it was for demo purposes) * Pass location data to Product Template query in Editor * Replace templateSlugs literal strings with object reference * Rename parseResponse function to more specific name getIdFromResponse * Add dpeendency array to useEffect * Refactor templates detection * Use full taxonomy names instead of shortcuts * Write down scenarios to test * Working scenario * Change the verification way for more robust * Add more robust methods to include Single Product block * Add test Product Collection in Single Product block in a Single Product Template * Imprvoe the order of veryfing the requests * Fix linter issues. Although that makes code less readable * Improve the useGetLocation typing so it's more generic * Rework the E2E tests regarding location of Product Collection and limit their number * Bring back necessary eslint-disable * Remove unused imports * Uncomment line required for other tests * Add changelog * Rename constant from BLOCK_NAME to BLOCK_SLUG as it's a slug * Add a BLOCK_NAME constant and replace the literal block name usages in E2E tests * Fix post merge issues * Fix test after merge * Adjust the tests to kick off waiting for request before action that triggers them
2024-02-12 19:59:40 +00:00
* Generic Taxonomy template
*/
const isInProductsByCategoryTemplate = isInGenericTemplate(
templateSlugs.productCategory
);
if ( isInProductsByCategoryTemplate ) {
return createLocationObject( 'archive', {
taxonomy: 'product_cat',
termId: null,
} );
}
const isInProductsByTagTemplate = isInGenericTemplate(
templateSlugs.productTag
);
if ( isInProductsByTagTemplate ) {
return createLocationObject( 'archive', {
taxonomy: 'product_tag',
termId: null,
} );
}
const isInProductsByAttributeTemplate = isInGenericTemplate(
templateSlugs.productAttribute
);
if ( isInProductsByAttributeTemplate ) {
return createLocationObject( 'archive', {
taxonomy: null,
termId: null,
} );
}
/**
* Case 2.6: TEMPLATES: GENERIC CART
* Cart/Checkout templates
Getting the Product Collection location/context (#43997) * Early implementation of getting the Product Collection location/context * Solve the problem of async fetch in the hook * Improve typing * Import core data store instead of hardcoding store name * Recognise Product Category and Product Tag * Remove attr property from archive location data * Unify states naming * Add TODO entry * Display the info about the location of Product Collection * Improve the typing * Recognise if Product Collection is nested in Single Product block * Improve cases descriptions and add some defaults to potentially undefined values * Change the taxonomies sourceData * Recognise Mini Cart as Cart context * Recognise attribute as archive contect but no taxonomy * Refactor the function into single useEffect and clean it up * Fix typo * Remove unnecessary import * Stop rendering the output in Editor (it was for demo purposes) * Pass location data to Product Template query in Editor * Replace templateSlugs literal strings with object reference * Rename parseResponse function to more specific name getIdFromResponse * Add dpeendency array to useEffect * Refactor templates detection * Use full taxonomy names instead of shortcuts * Write down scenarios to test * Working scenario * Change the verification way for more robust * Add more robust methods to include Single Product block * Add test Product Collection in Single Product block in a Single Product Template * Imprvoe the order of veryfing the requests * Fix linter issues. Although that makes code less readable * Improve the useGetLocation typing so it's more generic * Rework the E2E tests regarding location of Product Collection and limit their number * Bring back necessary eslint-disable * Remove unused imports * Uncomment line required for other tests * Add changelog * Rename constant from BLOCK_NAME to BLOCK_SLUG as it's a slug * Add a BLOCK_NAME constant and replace the literal block name usages in E2E tests * Fix post merge issues * Fix test after merge * Adjust the tests to kick off waiting for request before action that triggers them
2024-02-12 19:59:40 +00:00
*/
const isInCartCheckoutTemplate =
Getting the Product Collection location/context (#43997) * Early implementation of getting the Product Collection location/context * Solve the problem of async fetch in the hook * Improve typing * Import core data store instead of hardcoding store name * Recognise Product Category and Product Tag * Remove attr property from archive location data * Unify states naming * Add TODO entry * Display the info about the location of Product Collection * Improve the typing * Recognise if Product Collection is nested in Single Product block * Improve cases descriptions and add some defaults to potentially undefined values * Change the taxonomies sourceData * Recognise Mini Cart as Cart context * Recognise attribute as archive contect but no taxonomy * Refactor the function into single useEffect and clean it up * Fix typo * Remove unnecessary import * Stop rendering the output in Editor (it was for demo purposes) * Pass location data to Product Template query in Editor * Replace templateSlugs literal strings with object reference * Rename parseResponse function to more specific name getIdFromResponse * Add dpeendency array to useEffect * Refactor templates detection * Use full taxonomy names instead of shortcuts * Write down scenarios to test * Working scenario * Change the verification way for more robust * Add more robust methods to include Single Product block * Add test Product Collection in Single Product block in a Single Product Template * Imprvoe the order of veryfing the requests * Fix linter issues. Although that makes code less readable * Improve the useGetLocation typing so it's more generic * Rework the E2E tests regarding location of Product Collection and limit their number * Bring back necessary eslint-disable * Remove unused imports * Uncomment line required for other tests * Add changelog * Rename constant from BLOCK_NAME to BLOCK_SLUG as it's a slug * Add a BLOCK_NAME constant and replace the literal block name usages in E2E tests * Fix post merge issues * Fix test after merge * Adjust the tests to kick off waiting for request before action that triggers them
2024-02-12 19:59:40 +00:00
templateSlug === templateSlugs.cart ||
templateSlug === templateSlugs.checkout;
Getting the Product Collection location/context (#43997) * Early implementation of getting the Product Collection location/context * Solve the problem of async fetch in the hook * Improve typing * Import core data store instead of hardcoding store name * Recognise Product Category and Product Tag * Remove attr property from archive location data * Unify states naming * Add TODO entry * Display the info about the location of Product Collection * Improve the typing * Recognise if Product Collection is nested in Single Product block * Improve cases descriptions and add some defaults to potentially undefined values * Change the taxonomies sourceData * Recognise Mini Cart as Cart context * Recognise attribute as archive contect but no taxonomy * Refactor the function into single useEffect and clean it up * Fix typo * Remove unnecessary import * Stop rendering the output in Editor (it was for demo purposes) * Pass location data to Product Template query in Editor * Replace templateSlugs literal strings with object reference * Rename parseResponse function to more specific name getIdFromResponse * Add dpeendency array to useEffect * Refactor templates detection * Use full taxonomy names instead of shortcuts * Write down scenarios to test * Working scenario * Change the verification way for more robust * Add more robust methods to include Single Product block * Add test Product Collection in Single Product block in a Single Product Template * Imprvoe the order of veryfing the requests * Fix linter issues. Although that makes code less readable * Improve the useGetLocation typing so it's more generic * Rework the E2E tests regarding location of Product Collection and limit their number * Bring back necessary eslint-disable * Remove unused imports * Uncomment line required for other tests * Add changelog * Rename constant from BLOCK_NAME to BLOCK_SLUG as it's a slug * Add a BLOCK_NAME constant and replace the literal block name usages in E2E tests * Fix post merge issues * Fix test after merge * Adjust the tests to kick off waiting for request before action that triggers them
2024-02-12 19:59:40 +00:00
if ( isInCartCheckoutTemplate ) {
Getting the Product Collection location/context (#43997) * Early implementation of getting the Product Collection location/context * Solve the problem of async fetch in the hook * Improve typing * Import core data store instead of hardcoding store name * Recognise Product Category and Product Tag * Remove attr property from archive location data * Unify states naming * Add TODO entry * Display the info about the location of Product Collection * Improve the typing * Recognise if Product Collection is nested in Single Product block * Improve cases descriptions and add some defaults to potentially undefined values * Change the taxonomies sourceData * Recognise Mini Cart as Cart context * Recognise attribute as archive contect but no taxonomy * Refactor the function into single useEffect and clean it up * Fix typo * Remove unnecessary import * Stop rendering the output in Editor (it was for demo purposes) * Pass location data to Product Template query in Editor * Replace templateSlugs literal strings with object reference * Rename parseResponse function to more specific name getIdFromResponse * Add dpeendency array to useEffect * Refactor templates detection * Use full taxonomy names instead of shortcuts * Write down scenarios to test * Working scenario * Change the verification way for more robust * Add more robust methods to include Single Product block * Add test Product Collection in Single Product block in a Single Product Template * Imprvoe the order of veryfing the requests * Fix linter issues. Although that makes code less readable * Improve the useGetLocation typing so it's more generic * Rework the E2E tests regarding location of Product Collection and limit their number * Bring back necessary eslint-disable * Remove unused imports * Uncomment line required for other tests * Add changelog * Rename constant from BLOCK_NAME to BLOCK_SLUG as it's a slug * Add a BLOCK_NAME constant and replace the literal block name usages in E2E tests * Fix post merge issues * Fix test after merge * Adjust the tests to kick off waiting for request before action that triggers them
2024-02-12 19:59:40 +00:00
return createLocationObject( 'cart' );
}
/**
* Case 2.7: TEMPLATES: GENERIC ORDER
Getting the Product Collection location/context (#43997) * Early implementation of getting the Product Collection location/context * Solve the problem of async fetch in the hook * Improve typing * Import core data store instead of hardcoding store name * Recognise Product Category and Product Tag * Remove attr property from archive location data * Unify states naming * Add TODO entry * Display the info about the location of Product Collection * Improve the typing * Recognise if Product Collection is nested in Single Product block * Improve cases descriptions and add some defaults to potentially undefined values * Change the taxonomies sourceData * Recognise Mini Cart as Cart context * Recognise attribute as archive contect but no taxonomy * Refactor the function into single useEffect and clean it up * Fix typo * Remove unnecessary import * Stop rendering the output in Editor (it was for demo purposes) * Pass location data to Product Template query in Editor * Replace templateSlugs literal strings with object reference * Rename parseResponse function to more specific name getIdFromResponse * Add dpeendency array to useEffect * Refactor templates detection * Use full taxonomy names instead of shortcuts * Write down scenarios to test * Working scenario * Change the verification way for more robust * Add more robust methods to include Single Product block * Add test Product Collection in Single Product block in a Single Product Template * Imprvoe the order of veryfing the requests * Fix linter issues. Although that makes code less readable * Improve the useGetLocation typing so it's more generic * Rework the E2E tests regarding location of Product Collection and limit their number * Bring back necessary eslint-disable * Remove unused imports * Uncomment line required for other tests * Add changelog * Rename constant from BLOCK_NAME to BLOCK_SLUG as it's a slug * Add a BLOCK_NAME constant and replace the literal block name usages in E2E tests * Fix post merge issues * Fix test after merge * Adjust the tests to kick off waiting for request before action that triggers them
2024-02-12 19:59:40 +00:00
* Order Confirmation template
*/
const isInOrderTemplate = isInGenericTemplate(
templateSlugs.orderConfirmation
);
if ( isInOrderTemplate ) {
return createLocationObject( 'order' );
}
/**
* Case 3: GENERIC
Getting the Product Collection location/context (#43997) * Early implementation of getting the Product Collection location/context * Solve the problem of async fetch in the hook * Improve typing * Import core data store instead of hardcoding store name * Recognise Product Category and Product Tag * Remove attr property from archive location data * Unify states naming * Add TODO entry * Display the info about the location of Product Collection * Improve the typing * Recognise if Product Collection is nested in Single Product block * Improve cases descriptions and add some defaults to potentially undefined values * Change the taxonomies sourceData * Recognise Mini Cart as Cart context * Recognise attribute as archive contect but no taxonomy * Refactor the function into single useEffect and clean it up * Fix typo * Remove unnecessary import * Stop rendering the output in Editor (it was for demo purposes) * Pass location data to Product Template query in Editor * Replace templateSlugs literal strings with object reference * Rename parseResponse function to more specific name getIdFromResponse * Add dpeendency array to useEffect * Refactor templates detection * Use full taxonomy names instead of shortcuts * Write down scenarios to test * Working scenario * Change the verification way for more robust * Add more robust methods to include Single Product block * Add test Product Collection in Single Product block in a Single Product Template * Imprvoe the order of veryfing the requests * Fix linter issues. Although that makes code less readable * Improve the useGetLocation typing so it's more generic * Rework the E2E tests regarding location of Product Collection and limit their number * Bring back necessary eslint-disable * Remove unused imports * Uncomment line required for other tests * Add changelog * Rename constant from BLOCK_NAME to BLOCK_SLUG as it's a slug * Add a BLOCK_NAME constant and replace the literal block name usages in E2E tests * Fix post merge issues * Fix test after merge * Adjust the tests to kick off waiting for request before action that triggers them
2024-02-12 19:59:40 +00:00
* All other cases
*/
return createLocationObject( 'generic' );
};
Product Collection: Make attributes available in rest_product_query hook (#44150) * Make attributes available in rest_product_query hook This commit introduces the 'includeInQueryContext' attribute to the 'woocommerce/product-collection' block and updates the 'woocommerce/product-template' block to consume this new attribute. Key Changes: 1. `woocommerce/product-collection` Block: - A new attribute 'includeInQueryContext' is added in `block.json`. This attribute is designed to hold a list of attribute names relevant for the query context. - The 'includeInQueryContext' attribute is included in the `providesContext` field to ensure its availability to child blocks. - In `constants.ts`, default values for 'includeInQueryContext' are defined, specifying 'collection' and 'id' as initial attributes. - The `types.ts` file is updated with a comment explaining the purpose of 'includeInQueryContext'. 2. `woocommerce/product-template` Block: - Modified `block.json` to utilize the 'includeInQueryContext' context provided by the parent `woocommerce/product-collection` block. - The `edit.tsx` file is updated to handle the new context. It uses a newly added utility function `useProductCollectionBlockAttributes` from `utils.tsx` to access parent block attributes. - The `utils.tsx` file is introduced, containing the `useProductCollectionBlockAttributes` hook. This hook is responsible for finding the parent 'woocommerce/product-collection' block and returning its attributes. - Within `edit.tsx`, logic is added to create a query context object based on the attributes specified in 'includeInQueryContext', enhancing the block's ability to dynamically adapt to changes. * Remove commented code * Rename query context attribute and optimize parent block detection This commit introduces two significant changes aimed at improving code readability and efficiency. 1. **Renaming of Query Context Attribute:** - The attribute `includeInQueryContext` has been renamed to `queryContextIncludes` across various files, including block JSON configurations and TypeScript definitions. This change makes the attribute's purpose more intuitive, indicating it specifies which attributes to include in the query context. 2. **Optimized Parent Block Detection:** - Replaced the use of `getBlockParents` with `getBlockParentsByBlockName` in utility functions to find the closest Product Collection block. This optimization allows for a more direct and efficient way to identify the relevant parent block by specifying the block name, reducing unnecessary iterations and improving code performance. * Streamline query context construction in product template Key Changes: - **Introduction of `useProductCollectionQueryContext` Hook:** This new hook takes the `clientId` and `queryContextIncludes` as inputs and returns a query context object. It encapsulates the logic for fetching parent product collection block attributes and constructing the query context accordingly. This abstraction simplifies the edit component's logic, focusing on the essentials and improving code readability. - **Optimization of Parent Block Detection:** The hook uses `getBlockParentsByBlockName` to accurately and efficiently find the closest parent `Product Collection` block, minimizing the overhead previously associated with traversing the block hierarchy. * Always include `collection` and `id` in query context * Minor refactor * Enhance query context handling for more maintainable code - Introduced `DEFAULT_QUERY_CONTEXT_ATTRIBUTES` in `edit.tsx` to maintain a clear list of default query context attributes. - Modified `ProductTemplateEdit` to automatically include these default attributes in `queryContextIncludes`, ensuring they are always part of the query context without manual initialization. - Simplified `useProductCollectionQueryContext` in `utils.tsx` by removing static initialization of 'collection' and 'id', relying instead on the dynamic addition of necessary attributes from `queryContextIncludes`. This refactor enhances the maintainability and clarity of the code, ensuring a solid foundation for future enhancements and features. * Add E2E tests for Product Collection query context - Added a new test suite 'Query Context in Editor' to validate the correctness of query context parameters when the Product Collection block is used. This suite ensures that: - For the 'Product Catalog', only the ID is sent in the query context, confirming that collection-specific parameters are excluded when not relevant. - For collections such as 'On Sale', the collection name is correctly passed in the query context, validating that the block dynamically adjusts query parameters based on its settings. - Introduced a new utility method `setupAndFetchQueryContextURL` in `product-collection.page.ts`. This method automates the setup of a post with the Product Collection block and fetches the URL with query context parameters, facilitating the validation of query context handling. * Add changefile(s) from automation for the following project(s): woocommerce-blocks * Fix edge case when `queryContextIncludes` is not defined - Initializing `queryContextIncludes` with a default empty array directly in the destructuring assignment of the component's props. This approach ensures that `queryContextIncludes` is always an array, simplifying downstream logic. - Creating a new constant `queryContextIncludesWithDefaults` to hold the combination of `queryContextIncludes` and `DEFAULT_QUERY_CONTEXT_ATTRIBUTES`. This step avoids directly mutating the `queryContextIncludes` prop, aligning with best practices for functional purity and making the code easier to understand and debug. - Updating the `useProductCollectionQueryContext` hook call to use `queryContextIncludesWithDefaults`. This ensures that the default query context attributes are consistently included without altering the original prop. These adjustments not only enhance the code's maintainability but also ensure more predictable behavior by avoiding side effects related to parameter mutation. --------- Co-authored-by: github-actions <github-actions@github.com>
2024-02-12 08:45:24 +00:00
/**
* In Product Collection block, queryContextIncludes attribute contains
* list of attribute names that should be included in the query context.
*
* This hook returns the query context object based on the attribute names
* provided in the queryContextIncludes array.
*
* Example:
* {
* clientID = 'd2c7e34f-70d6-417c-b582-f554a3a575f3',
* queryContextIncludes = [ 'collection' ]
* }
*
* The hook will return the following query context object:
* {
* collection: 'woocommerce/product-collection/featured'
* }
*
* @param args Arguments for the hook.
* @param args.clientId Client ID of the inner block.
* @param args.queryContextIncludes Array of attribute names to be included in the query context.
*
* @return Query context object.
*/
export const useProductCollectionQueryContext = ( {
clientId,
queryContextIncludes,
}: {
clientId: string;
queryContextIncludes: string[];
} ) => {
const productCollectionBlockAttributes = useSelect(
( select ) => {
const { getBlockParentsByBlockName, getBlockAttributes } =
select( 'core/block-editor' );
const parentBlocksClientIds = getBlockParentsByBlockName(
clientId,
'woocommerce/product-collection',
true
);
if ( parentBlocksClientIds?.length ) {
const closestParentClientId = parentBlocksClientIds[ 0 ];
return getBlockAttributes( closestParentClientId );
}
return null;
},
[ clientId ]
);
return useMemo( () => {
// If the product collection block is not found, return null.
if ( ! productCollectionBlockAttributes ) {
return null;
}
const queryContext: {
[ key: string ]: unknown;
} = {};
if ( queryContextIncludes?.length ) {
queryContextIncludes.forEach( ( attribute: string ) => {
if ( productCollectionBlockAttributes?.[ attribute ] ) {
queryContext[ attribute ] =
productCollectionBlockAttributes[ attribute ];
}
} );
}
return queryContext;
}, [ queryContextIncludes, productCollectionBlockAttributes ] );
};