woocommerce/plugins/woocommerce-blocks/assets/js/blocks/product-collection/constants.ts

207 lines
4.8 KiB
TypeScript
Raw Normal View History

Product Collection: Add stock status filter (https://github.com/woocommerce/woocommerce-blocks/pull/9580) * Add columns control to product collection block editor settings - `InspectorControls` from './inspector-controls' is now imported in `edit.tsx` and used in the returned JSX of `Edit` function. - A new file `columns-control.tsx` is added under 'product-collection' block's 'inspector-controls' directory which exports a `ColumnsControl` component. This component uses `RangeControl` from '@wordpress/components' to control the number of columns in the product collection display layout when the layout type is 'flex'. - The types file (`types.ts`) for 'product-collection' block is updated. The `Attributes` interface is renamed to `ProductCollectionAttributes` and the `ProductCollectionContext` interface is removed. The `ProductCollectionAttributes` now includes 'queryContext', 'templateSlug', and 'displayLayout' properties. * Refactor: Simplify Fallback Return in ColumnsControl Component This commit simplifies the fallback return value of the ColumnsControl component. Instead of returning an empty fragment (<> </>), it now returns null when the condition isn't met. This change improves readability and aligns with best practices for conditional rendering in React. * Feature: Add 'Order By' Control to Product Collection Inspector This commit adds a new 'Order By' control to the product collection inspector. The control allows users to specify the order of products in a collection by various attributes such as title and date. To support this, a new component 'OrderByControl' has been created and included in the product collection inspector. Additionally, the types for 'order' and 'orderBy' attributes have been updated and exported for reuse. * Add more options to OrderBy type * Add orderby handling on frontend & editor The main changes include: 1. Added a new property 'isProductCollectionBlock' in the block.json to denote if a block is a product collection block. 2. In the ProductCollection PHP class, a new initialization function has been defined to hook into the WordPress lifecycle, register the block, and update the query based on this block. 3. Added methods to manage query parameters for both frontend rendering and the Editor. 4. Expanded allowed 'collection_params' for the REST API to include custom 'orderby' values. 5. Defined a function to build the query based on block attributes, filters, and global WP_Query. 6. Created utility functions to handle complex query operations such as merging queries, handling custom sort values, and merging arrays recursively. These improvements allow for more flexible and robust handling of product collections in both the front-end display and the WordPress editor. It also extends support for custom 'orderby' values in the REST API, which allows for more advanced sorting options in product collections. * Add 'on sale' filter and enhance settings management in product collection block This commit introduces several changes to the product collection block. - First, it adds a new 'on sale' filter that can be used to display only the products that are currently on sale. - It also refactors the settings management in the product collection block to use the experimental ToolsPanel component from WordPress, which provides a more flexible and intuitive way to manage block settings. - It moves the 'Columns' control into the ToolsPanel, along with the 'Order by' control. - A new utility function `setQueryAttribute` is introduced to simplify setting nested query parameters. - The structure of the `ProductCollectionAttributes` and `ProductCollectionQuery` types have been adjusted to accommodate the changes. - Finally, it makes corresponding changes in the PHP part to handle the new 'on sale' query parameter. This should enhance the flexibility and user-friendliness of the product collection block. * Add stock status filter to WooCommerce product collection block This commit introduces a stock status filter to the WooCommerce product collection block. The changes include: 1. Added the ability to filter products based on their stock status within the 'product-collection' block. A new stock status control is created within the inspector-controls of the block. 2. A new 'get_stock_status_query' function is introduced in 'ProductCollection.php' which returns a query for products depending on their stock status. Please note that the stock status filter will only appear in the experimental build for now. * Refactor Stock Status control of Product Collection block This commit refactors the Stock Status control. The changes aim to improve the code organization and make the behavior of the component more explicit. The key modifications are: 1. Moved stock status related constants and functions from `inspector-controls/utils.tsx` to `inspector-controls/constants.ts`. This is done to ensure that all constants and similar utility functions are organized in one place. 2. Updated `product-collection/index.tsx` to import `getDefaultStockStatuses` from `inspector-controls/constants` instead of `inspector-controls/utils`. 3. Updated `stock-status-control.tsx` to determine whether the stock status has value or not by comparing with the default stock statuses using `fastDeepEqual`. If the stock status control is deselected, it resets the stock status to the default statuses. These changes do not introduce any new functionalities, but improve the readability and maintainability of the code. * Fix: Default values of attributes not saving as serialized block comment This was happening because of this issue: https://github.com/WordPress/gutenberg/issues/7342 Therefore, I had to use `useEffect` to set the default values of the attributes. Here is the list of changes I made: 1. Removed default values from `block.json` for `query`, `tagName`, and `displayLayout`. 2. Moved the default values to `constants.ts` and created a new object `DEFAULT_ATTRIBUTES` to store them. 3. Relocated `constants.ts` from `inspector-controls` to the parent directory. 4. Refactored `edit.tsx` to use `DEFAULT_ATTRIBUTES` from `constants.ts` to set default attributes using `useEffect`. 5. Removed the attributes assignment from `registerBlockType` in `index.tsx`. 6. Updated `columns-control.tsx`, `index.tsx`, `order-by-control.tsx`, and `stock-status-control.tsx` to import from the relocated `constants.ts`. 7. Updated `ProductCollectionAttributes` and `ProductCollectionQuery` in `types.ts` to include `tagName` and `isProductCollectionBlock` respectively. 8. Modified `ProductCollection.php` to match the updated `orderBy` key in the query parameter. This refactor enhances the readability of the code and reduces duplication by keeping all constants and default values in one place. * Replace usage of 'statii' with 'statuses' in stock status handling This commit replaces all instances of 'statii' with the correct term 'statuses' in the context of handling stock status. This change affects three files: 1. `assets/js/blocks/product-collection/inspector-controls/stock-status-control.tsx` - The term is corrected in a comment block. 2. `assets/js/blocks/product-collection/types.ts` - Updated the name of a variable in the `ProductCollectionQuery` interface. 3. `src/BlockTypes/ProductCollection.php` - Here, the term is replaced in several locations including variable names, comments and the method `get_stock_status_query`. This commit helps improve code readability and consistency across the repository.
2023-05-26 11:44:37 +00:00
/**
* External dependencies
*/
import { getSetting } from '@woocommerce/settings';
import { objectOmit } from '@woocommerce/utils';
import {
type InnerBlockTemplate,
createBlock,
// @ts-expect-error Missing types in Gutenberg
createBlocksFromInnerBlocksTemplate,
} from '@wordpress/blocks';
Product Collection: Add stock status filter (https://github.com/woocommerce/woocommerce-blocks/pull/9580) * Add columns control to product collection block editor settings - `InspectorControls` from './inspector-controls' is now imported in `edit.tsx` and used in the returned JSX of `Edit` function. - A new file `columns-control.tsx` is added under 'product-collection' block's 'inspector-controls' directory which exports a `ColumnsControl` component. This component uses `RangeControl` from '@wordpress/components' to control the number of columns in the product collection display layout when the layout type is 'flex'. - The types file (`types.ts`) for 'product-collection' block is updated. The `Attributes` interface is renamed to `ProductCollectionAttributes` and the `ProductCollectionContext` interface is removed. The `ProductCollectionAttributes` now includes 'queryContext', 'templateSlug', and 'displayLayout' properties. * Refactor: Simplify Fallback Return in ColumnsControl Component This commit simplifies the fallback return value of the ColumnsControl component. Instead of returning an empty fragment (<> </>), it now returns null when the condition isn't met. This change improves readability and aligns with best practices for conditional rendering in React. * Feature: Add 'Order By' Control to Product Collection Inspector This commit adds a new 'Order By' control to the product collection inspector. The control allows users to specify the order of products in a collection by various attributes such as title and date. To support this, a new component 'OrderByControl' has been created and included in the product collection inspector. Additionally, the types for 'order' and 'orderBy' attributes have been updated and exported for reuse. * Add more options to OrderBy type * Add orderby handling on frontend & editor The main changes include: 1. Added a new property 'isProductCollectionBlock' in the block.json to denote if a block is a product collection block. 2. In the ProductCollection PHP class, a new initialization function has been defined to hook into the WordPress lifecycle, register the block, and update the query based on this block. 3. Added methods to manage query parameters for both frontend rendering and the Editor. 4. Expanded allowed 'collection_params' for the REST API to include custom 'orderby' values. 5. Defined a function to build the query based on block attributes, filters, and global WP_Query. 6. Created utility functions to handle complex query operations such as merging queries, handling custom sort values, and merging arrays recursively. These improvements allow for more flexible and robust handling of product collections in both the front-end display and the WordPress editor. It also extends support for custom 'orderby' values in the REST API, which allows for more advanced sorting options in product collections. * Add 'on sale' filter and enhance settings management in product collection block This commit introduces several changes to the product collection block. - First, it adds a new 'on sale' filter that can be used to display only the products that are currently on sale. - It also refactors the settings management in the product collection block to use the experimental ToolsPanel component from WordPress, which provides a more flexible and intuitive way to manage block settings. - It moves the 'Columns' control into the ToolsPanel, along with the 'Order by' control. - A new utility function `setQueryAttribute` is introduced to simplify setting nested query parameters. - The structure of the `ProductCollectionAttributes` and `ProductCollectionQuery` types have been adjusted to accommodate the changes. - Finally, it makes corresponding changes in the PHP part to handle the new 'on sale' query parameter. This should enhance the flexibility and user-friendliness of the product collection block. * Add stock status filter to WooCommerce product collection block This commit introduces a stock status filter to the WooCommerce product collection block. The changes include: 1. Added the ability to filter products based on their stock status within the 'product-collection' block. A new stock status control is created within the inspector-controls of the block. 2. A new 'get_stock_status_query' function is introduced in 'ProductCollection.php' which returns a query for products depending on their stock status. Please note that the stock status filter will only appear in the experimental build for now. * Refactor Stock Status control of Product Collection block This commit refactors the Stock Status control. The changes aim to improve the code organization and make the behavior of the component more explicit. The key modifications are: 1. Moved stock status related constants and functions from `inspector-controls/utils.tsx` to `inspector-controls/constants.ts`. This is done to ensure that all constants and similar utility functions are organized in one place. 2. Updated `product-collection/index.tsx` to import `getDefaultStockStatuses` from `inspector-controls/constants` instead of `inspector-controls/utils`. 3. Updated `stock-status-control.tsx` to determine whether the stock status has value or not by comparing with the default stock statuses using `fastDeepEqual`. If the stock status control is deselected, it resets the stock status to the default statuses. These changes do not introduce any new functionalities, but improve the readability and maintainability of the code. * Fix: Default values of attributes not saving as serialized block comment This was happening because of this issue: https://github.com/WordPress/gutenberg/issues/7342 Therefore, I had to use `useEffect` to set the default values of the attributes. Here is the list of changes I made: 1. Removed default values from `block.json` for `query`, `tagName`, and `displayLayout`. 2. Moved the default values to `constants.ts` and created a new object `DEFAULT_ATTRIBUTES` to store them. 3. Relocated `constants.ts` from `inspector-controls` to the parent directory. 4. Refactored `edit.tsx` to use `DEFAULT_ATTRIBUTES` from `constants.ts` to set default attributes using `useEffect`. 5. Removed the attributes assignment from `registerBlockType` in `index.tsx`. 6. Updated `columns-control.tsx`, `index.tsx`, `order-by-control.tsx`, and `stock-status-control.tsx` to import from the relocated `constants.ts`. 7. Updated `ProductCollectionAttributes` and `ProductCollectionQuery` in `types.ts` to include `tagName` and `isProductCollectionBlock` respectively. 8. Modified `ProductCollection.php` to match the updated `orderBy` key in the query parameter. This refactor enhances the readability of the code and reduces duplication by keeping all constants and default values in one place. * Replace usage of 'statii' with 'statuses' in stock status handling This commit replaces all instances of 'statii' with the correct term 'statuses' in the context of handling stock status. This change affects three files: 1. `assets/js/blocks/product-collection/inspector-controls/stock-status-control.tsx` - The term is corrected in a comment block. 2. `assets/js/blocks/product-collection/types.ts` - Updated the name of a variable in the `ProductCollectionQuery` interface. 3. `src/BlockTypes/ProductCollection.php` - Here, the term is replaced in several locations including variable names, comments and the method `get_stock_status_query`. This commit helps improve code readability and consistency across the repository.
2023-05-26 11:44:37 +00:00
/**
* Internal dependencies
*/
import {
ProductCollectionAttributes,
TProductCollectionOrder,
TProductCollectionOrderBy,
ProductCollectionQuery,
ProductCollectionDisplayLayout,
Transfer layout options from Toolbar to Inspector controls (https://github.com/woocommerce/woocommerce-blocks/pull/10922) In this update, the layout options for the Product Collection block are transferred from the Toolbar to the Inspector controls. Below is the breakdown of the changes: 1. **Constants Update** - `LayoutOptions` enumeration has been imported into `constants.ts`, facilitating a more structured approach to managing layout types (grid and stack). - The default display layout type has been updated from 'flex' to reference `LayoutOptions.GRID`. - The `getDefaultQuery` function now uses the `getDefaultValueOfInheritQueryFromTemplate` utility to set the default `inherit` value. (This is mainly done to fix a bug) 2. **Display Layout Control Removal** - The `display-layout-control.tsx` file has been removed, discontinuing the previous method of layout management. 3. **New Layout Options Control** - A new component `LayoutOptionsControl` has been introduced in the `layout-options-control.tsx` file, utilizing the experimental `ToggleGroupControl` and `ToggleGroupControlOption` components from the WordPress package to provide a more intuitive layout selection experience. - The `types.ts` file has been updated to define the `LayoutOptions` enum, effectively mapping 'flex' to 'GRID' and 'list' to 'STACK'. 4. **Inspector Controls Update** - In `inspector-controls/index.tsx`, the obsolete `DisplayLayoutControl` has been replaced with the new `LayoutOptionsControl`, integrating it into the `ProductCollectionInspectorControls` component. - The `BlockControls` wrapper has been removed, and layout options have been relocated to the Inspector controls, presented as a toggle group within the ToolsPanel. 5. **Inherit Query Control Modification** - The `inherit-query-control.tsx` file sees a change in the reset value for the `inherit` query attribute to employ a default value which fix one bug. These changes aim to streamline the user experience by relocating the layout options from the Toolbar to the Inspector controls, offering a centralized location for block settings. Leveraging an enum for layout options fosters code readability and maintainability. Do note that the update uses experimental components, hence it would be prudent to keep an eye on potential alterations or deprecations in upcoming WordPress releases.
2023-09-15 10:08:48 +00:00
LayoutOptions,
Product Collection: Add stock status filter (https://github.com/woocommerce/woocommerce-blocks/pull/9580) * Add columns control to product collection block editor settings - `InspectorControls` from './inspector-controls' is now imported in `edit.tsx` and used in the returned JSX of `Edit` function. - A new file `columns-control.tsx` is added under 'product-collection' block's 'inspector-controls' directory which exports a `ColumnsControl` component. This component uses `RangeControl` from '@wordpress/components' to control the number of columns in the product collection display layout when the layout type is 'flex'. - The types file (`types.ts`) for 'product-collection' block is updated. The `Attributes` interface is renamed to `ProductCollectionAttributes` and the `ProductCollectionContext` interface is removed. The `ProductCollectionAttributes` now includes 'queryContext', 'templateSlug', and 'displayLayout' properties. * Refactor: Simplify Fallback Return in ColumnsControl Component This commit simplifies the fallback return value of the ColumnsControl component. Instead of returning an empty fragment (<> </>), it now returns null when the condition isn't met. This change improves readability and aligns with best practices for conditional rendering in React. * Feature: Add 'Order By' Control to Product Collection Inspector This commit adds a new 'Order By' control to the product collection inspector. The control allows users to specify the order of products in a collection by various attributes such as title and date. To support this, a new component 'OrderByControl' has been created and included in the product collection inspector. Additionally, the types for 'order' and 'orderBy' attributes have been updated and exported for reuse. * Add more options to OrderBy type * Add orderby handling on frontend & editor The main changes include: 1. Added a new property 'isProductCollectionBlock' in the block.json to denote if a block is a product collection block. 2. In the ProductCollection PHP class, a new initialization function has been defined to hook into the WordPress lifecycle, register the block, and update the query based on this block. 3. Added methods to manage query parameters for both frontend rendering and the Editor. 4. Expanded allowed 'collection_params' for the REST API to include custom 'orderby' values. 5. Defined a function to build the query based on block attributes, filters, and global WP_Query. 6. Created utility functions to handle complex query operations such as merging queries, handling custom sort values, and merging arrays recursively. These improvements allow for more flexible and robust handling of product collections in both the front-end display and the WordPress editor. It also extends support for custom 'orderby' values in the REST API, which allows for more advanced sorting options in product collections. * Add 'on sale' filter and enhance settings management in product collection block This commit introduces several changes to the product collection block. - First, it adds a new 'on sale' filter that can be used to display only the products that are currently on sale. - It also refactors the settings management in the product collection block to use the experimental ToolsPanel component from WordPress, which provides a more flexible and intuitive way to manage block settings. - It moves the 'Columns' control into the ToolsPanel, along with the 'Order by' control. - A new utility function `setQueryAttribute` is introduced to simplify setting nested query parameters. - The structure of the `ProductCollectionAttributes` and `ProductCollectionQuery` types have been adjusted to accommodate the changes. - Finally, it makes corresponding changes in the PHP part to handle the new 'on sale' query parameter. This should enhance the flexibility and user-friendliness of the product collection block. * Add stock status filter to WooCommerce product collection block This commit introduces a stock status filter to the WooCommerce product collection block. The changes include: 1. Added the ability to filter products based on their stock status within the 'product-collection' block. A new stock status control is created within the inspector-controls of the block. 2. A new 'get_stock_status_query' function is introduced in 'ProductCollection.php' which returns a query for products depending on their stock status. Please note that the stock status filter will only appear in the experimental build for now. * Refactor Stock Status control of Product Collection block This commit refactors the Stock Status control. The changes aim to improve the code organization and make the behavior of the component more explicit. The key modifications are: 1. Moved stock status related constants and functions from `inspector-controls/utils.tsx` to `inspector-controls/constants.ts`. This is done to ensure that all constants and similar utility functions are organized in one place. 2. Updated `product-collection/index.tsx` to import `getDefaultStockStatuses` from `inspector-controls/constants` instead of `inspector-controls/utils`. 3. Updated `stock-status-control.tsx` to determine whether the stock status has value or not by comparing with the default stock statuses using `fastDeepEqual`. If the stock status control is deselected, it resets the stock status to the default statuses. These changes do not introduce any new functionalities, but improve the readability and maintainability of the code. * Fix: Default values of attributes not saving as serialized block comment This was happening because of this issue: https://github.com/WordPress/gutenberg/issues/7342 Therefore, I had to use `useEffect` to set the default values of the attributes. Here is the list of changes I made: 1. Removed default values from `block.json` for `query`, `tagName`, and `displayLayout`. 2. Moved the default values to `constants.ts` and created a new object `DEFAULT_ATTRIBUTES` to store them. 3. Relocated `constants.ts` from `inspector-controls` to the parent directory. 4. Refactored `edit.tsx` to use `DEFAULT_ATTRIBUTES` from `constants.ts` to set default attributes using `useEffect`. 5. Removed the attributes assignment from `registerBlockType` in `index.tsx`. 6. Updated `columns-control.tsx`, `index.tsx`, `order-by-control.tsx`, and `stock-status-control.tsx` to import from the relocated `constants.ts`. 7. Updated `ProductCollectionAttributes` and `ProductCollectionQuery` in `types.ts` to include `tagName` and `isProductCollectionBlock` respectively. 8. Modified `ProductCollection.php` to match the updated `orderBy` key in the query parameter. This refactor enhances the readability of the code and reduces duplication by keeping all constants and default values in one place. * Replace usage of 'statii' with 'statuses' in stock status handling This commit replaces all instances of 'statii' with the correct term 'statuses' in the context of handling stock status. This change affects three files: 1. `assets/js/blocks/product-collection/inspector-controls/stock-status-control.tsx` - The term is corrected in a comment block. 2. `assets/js/blocks/product-collection/types.ts` - Updated the name of a variable in the `ProductCollectionQuery` interface. 3. `src/BlockTypes/ProductCollection.php` - Here, the term is replaced in several locations including variable names, comments and the method `get_stock_status_query`. This commit helps improve code readability and consistency across the repository.
2023-05-26 11:44:37 +00:00
} from './types';
import { ImageSizing } from '../../atomic/blocks/product-elements/image/types';
import { VARIATION_NAME as PRODUCT_TITLE_ID } from './variations/elements/product-title';
Transfer layout options from Toolbar to Inspector controls (https://github.com/woocommerce/woocommerce-blocks/pull/10922) In this update, the layout options for the Product Collection block are transferred from the Toolbar to the Inspector controls. Below is the breakdown of the changes: 1. **Constants Update** - `LayoutOptions` enumeration has been imported into `constants.ts`, facilitating a more structured approach to managing layout types (grid and stack). - The default display layout type has been updated from 'flex' to reference `LayoutOptions.GRID`. - The `getDefaultQuery` function now uses the `getDefaultValueOfInheritQueryFromTemplate` utility to set the default `inherit` value. (This is mainly done to fix a bug) 2. **Display Layout Control Removal** - The `display-layout-control.tsx` file has been removed, discontinuing the previous method of layout management. 3. **New Layout Options Control** - A new component `LayoutOptionsControl` has been introduced in the `layout-options-control.tsx` file, utilizing the experimental `ToggleGroupControl` and `ToggleGroupControlOption` components from the WordPress package to provide a more intuitive layout selection experience. - The `types.ts` file has been updated to define the `LayoutOptions` enum, effectively mapping 'flex' to 'GRID' and 'list' to 'STACK'. 4. **Inspector Controls Update** - In `inspector-controls/index.tsx`, the obsolete `DisplayLayoutControl` has been replaced with the new `LayoutOptionsControl`, integrating it into the `ProductCollectionInspectorControls` component. - The `BlockControls` wrapper has been removed, and layout options have been relocated to the Inspector controls, presented as a toggle group within the ToolsPanel. 5. **Inherit Query Control Modification** - The `inherit-query-control.tsx` file sees a change in the reset value for the `inherit` query attribute to employ a default value which fix one bug. These changes aim to streamline the user experience by relocating the layout options from the Toolbar to the Inspector controls, offering a centralized location for block settings. Leveraging an enum for layout options fosters code readability and maintainability. Do note that the update uses experimental components, hence it would be prudent to keep an eye on potential alterations or deprecations in upcoming WordPress releases.
2023-09-15 10:08:48 +00:00
import { getDefaultValueOfInheritQueryFromTemplate } from './utils';
import blockJson from './block.json';
Product Collection: Add stock status filter (https://github.com/woocommerce/woocommerce-blocks/pull/9580) * Add columns control to product collection block editor settings - `InspectorControls` from './inspector-controls' is now imported in `edit.tsx` and used in the returned JSX of `Edit` function. - A new file `columns-control.tsx` is added under 'product-collection' block's 'inspector-controls' directory which exports a `ColumnsControl` component. This component uses `RangeControl` from '@wordpress/components' to control the number of columns in the product collection display layout when the layout type is 'flex'. - The types file (`types.ts`) for 'product-collection' block is updated. The `Attributes` interface is renamed to `ProductCollectionAttributes` and the `ProductCollectionContext` interface is removed. The `ProductCollectionAttributes` now includes 'queryContext', 'templateSlug', and 'displayLayout' properties. * Refactor: Simplify Fallback Return in ColumnsControl Component This commit simplifies the fallback return value of the ColumnsControl component. Instead of returning an empty fragment (<> </>), it now returns null when the condition isn't met. This change improves readability and aligns with best practices for conditional rendering in React. * Feature: Add 'Order By' Control to Product Collection Inspector This commit adds a new 'Order By' control to the product collection inspector. The control allows users to specify the order of products in a collection by various attributes such as title and date. To support this, a new component 'OrderByControl' has been created and included in the product collection inspector. Additionally, the types for 'order' and 'orderBy' attributes have been updated and exported for reuse. * Add more options to OrderBy type * Add orderby handling on frontend & editor The main changes include: 1. Added a new property 'isProductCollectionBlock' in the block.json to denote if a block is a product collection block. 2. In the ProductCollection PHP class, a new initialization function has been defined to hook into the WordPress lifecycle, register the block, and update the query based on this block. 3. Added methods to manage query parameters for both frontend rendering and the Editor. 4. Expanded allowed 'collection_params' for the REST API to include custom 'orderby' values. 5. Defined a function to build the query based on block attributes, filters, and global WP_Query. 6. Created utility functions to handle complex query operations such as merging queries, handling custom sort values, and merging arrays recursively. These improvements allow for more flexible and robust handling of product collections in both the front-end display and the WordPress editor. It also extends support for custom 'orderby' values in the REST API, which allows for more advanced sorting options in product collections. * Add 'on sale' filter and enhance settings management in product collection block This commit introduces several changes to the product collection block. - First, it adds a new 'on sale' filter that can be used to display only the products that are currently on sale. - It also refactors the settings management in the product collection block to use the experimental ToolsPanel component from WordPress, which provides a more flexible and intuitive way to manage block settings. - It moves the 'Columns' control into the ToolsPanel, along with the 'Order by' control. - A new utility function `setQueryAttribute` is introduced to simplify setting nested query parameters. - The structure of the `ProductCollectionAttributes` and `ProductCollectionQuery` types have been adjusted to accommodate the changes. - Finally, it makes corresponding changes in the PHP part to handle the new 'on sale' query parameter. This should enhance the flexibility and user-friendliness of the product collection block. * Add stock status filter to WooCommerce product collection block This commit introduces a stock status filter to the WooCommerce product collection block. The changes include: 1. Added the ability to filter products based on their stock status within the 'product-collection' block. A new stock status control is created within the inspector-controls of the block. 2. A new 'get_stock_status_query' function is introduced in 'ProductCollection.php' which returns a query for products depending on their stock status. Please note that the stock status filter will only appear in the experimental build for now. * Refactor Stock Status control of Product Collection block This commit refactors the Stock Status control. The changes aim to improve the code organization and make the behavior of the component more explicit. The key modifications are: 1. Moved stock status related constants and functions from `inspector-controls/utils.tsx` to `inspector-controls/constants.ts`. This is done to ensure that all constants and similar utility functions are organized in one place. 2. Updated `product-collection/index.tsx` to import `getDefaultStockStatuses` from `inspector-controls/constants` instead of `inspector-controls/utils`. 3. Updated `stock-status-control.tsx` to determine whether the stock status has value or not by comparing with the default stock statuses using `fastDeepEqual`. If the stock status control is deselected, it resets the stock status to the default statuses. These changes do not introduce any new functionalities, but improve the readability and maintainability of the code. * Fix: Default values of attributes not saving as serialized block comment This was happening because of this issue: https://github.com/WordPress/gutenberg/issues/7342 Therefore, I had to use `useEffect` to set the default values of the attributes. Here is the list of changes I made: 1. Removed default values from `block.json` for `query`, `tagName`, and `displayLayout`. 2. Moved the default values to `constants.ts` and created a new object `DEFAULT_ATTRIBUTES` to store them. 3. Relocated `constants.ts` from `inspector-controls` to the parent directory. 4. Refactored `edit.tsx` to use `DEFAULT_ATTRIBUTES` from `constants.ts` to set default attributes using `useEffect`. 5. Removed the attributes assignment from `registerBlockType` in `index.tsx`. 6. Updated `columns-control.tsx`, `index.tsx`, `order-by-control.tsx`, and `stock-status-control.tsx` to import from the relocated `constants.ts`. 7. Updated `ProductCollectionAttributes` and `ProductCollectionQuery` in `types.ts` to include `tagName` and `isProductCollectionBlock` respectively. 8. Modified `ProductCollection.php` to match the updated `orderBy` key in the query parameter. This refactor enhances the readability of the code and reduces duplication by keeping all constants and default values in one place. * Replace usage of 'statii' with 'statuses' in stock status handling This commit replaces all instances of 'statii' with the correct term 'statuses' in the context of handling stock status. This change affects three files: 1. `assets/js/blocks/product-collection/inspector-controls/stock-status-control.tsx` - The term is corrected in a comment block. 2. `assets/js/blocks/product-collection/types.ts` - Updated the name of a variable in the `ProductCollectionQuery` interface. 3. `src/BlockTypes/ProductCollection.php` - Here, the term is replaced in several locations including variable names, comments and the method `get_stock_status_query`. This commit helps improve code readability and consistency across the repository.
2023-05-26 11:44:37 +00:00
export const STOCK_STATUS_OPTIONS = getSetting< Record< string, string > >(
'stockStatusOptions',
[]
);
const GLOBAL_HIDE_OUT_OF_STOCK = getSetting< boolean >(
'hideOutOfStockItems',
false
);
export const getDefaultStockStatuses = () => {
return GLOBAL_HIDE_OUT_OF_STOCK
? Object.keys( objectOmit( STOCK_STATUS_OPTIONS, 'outofstock' ) )
: Object.keys( STOCK_STATUS_OPTIONS );
};
Product Collection: Add Taxonomy filters to sidebar settings (https://github.com/woocommerce/woocommerce-blocks/pull/9634) * Add columns control to product collection block editor settings - `InspectorControls` from './inspector-controls' is now imported in `edit.tsx` and used in the returned JSX of `Edit` function. - A new file `columns-control.tsx` is added under 'product-collection' block's 'inspector-controls' directory which exports a `ColumnsControl` component. This component uses `RangeControl` from '@wordpress/components' to control the number of columns in the product collection display layout when the layout type is 'flex'. - The types file (`types.ts`) for 'product-collection' block is updated. The `Attributes` interface is renamed to `ProductCollectionAttributes` and the `ProductCollectionContext` interface is removed. The `ProductCollectionAttributes` now includes 'queryContext', 'templateSlug', and 'displayLayout' properties. * Refactor: Simplify Fallback Return in ColumnsControl Component This commit simplifies the fallback return value of the ColumnsControl component. Instead of returning an empty fragment (<> </>), it now returns null when the condition isn't met. This change improves readability and aligns with best practices for conditional rendering in React. * Feature: Add 'Order By' Control to Product Collection Inspector This commit adds a new 'Order By' control to the product collection inspector. The control allows users to specify the order of products in a collection by various attributes such as title and date. To support this, a new component 'OrderByControl' has been created and included in the product collection inspector. Additionally, the types for 'order' and 'orderBy' attributes have been updated and exported for reuse. * Add more options to OrderBy type * Add orderby handling on frontend & editor The main changes include: 1. Added a new property 'isProductCollectionBlock' in the block.json to denote if a block is a product collection block. 2. In the ProductCollection PHP class, a new initialization function has been defined to hook into the WordPress lifecycle, register the block, and update the query based on this block. 3. Added methods to manage query parameters for both frontend rendering and the Editor. 4. Expanded allowed 'collection_params' for the REST API to include custom 'orderby' values. 5. Defined a function to build the query based on block attributes, filters, and global WP_Query. 6. Created utility functions to handle complex query operations such as merging queries, handling custom sort values, and merging arrays recursively. These improvements allow for more flexible and robust handling of product collections in both the front-end display and the WordPress editor. It also extends support for custom 'orderby' values in the REST API, which allows for more advanced sorting options in product collections. * Add 'on sale' filter and enhance settings management in product collection block This commit introduces several changes to the product collection block. - First, it adds a new 'on sale' filter that can be used to display only the products that are currently on sale. - It also refactors the settings management in the product collection block to use the experimental ToolsPanel component from WordPress, which provides a more flexible and intuitive way to manage block settings. - It moves the 'Columns' control into the ToolsPanel, along with the 'Order by' control. - A new utility function `setQueryAttribute` is introduced to simplify setting nested query parameters. - The structure of the `ProductCollectionAttributes` and `ProductCollectionQuery` types have been adjusted to accommodate the changes. - Finally, it makes corresponding changes in the PHP part to handle the new 'on sale' query parameter. This should enhance the flexibility and user-friendliness of the product collection block. * Add stock status filter to WooCommerce product collection block This commit introduces a stock status filter to the WooCommerce product collection block. The changes include: 1. Added the ability to filter products based on their stock status within the 'product-collection' block. A new stock status control is created within the inspector-controls of the block. 2. A new 'get_stock_status_query' function is introduced in 'ProductCollection.php' which returns a query for products depending on their stock status. Please note that the stock status filter will only appear in the experimental build for now. * Refactor Stock Status control of Product Collection block This commit refactors the Stock Status control. The changes aim to improve the code organization and make the behavior of the component more explicit. The key modifications are: 1. Moved stock status related constants and functions from `inspector-controls/utils.tsx` to `inspector-controls/constants.ts`. This is done to ensure that all constants and similar utility functions are organized in one place. 2. Updated `product-collection/index.tsx` to import `getDefaultStockStatuses` from `inspector-controls/constants` instead of `inspector-controls/utils`. 3. Updated `stock-status-control.tsx` to determine whether the stock status has value or not by comparing with the default stock statuses using `fastDeepEqual`. If the stock status control is deselected, it resets the stock status to the default statuses. These changes do not introduce any new functionalities, but improve the readability and maintainability of the code. * Add keyword search control to Product Collection block This commit introduces a keyword search functionality to the Product Collection block. The update is aimed to provide users with more flexibility and precision in product collection queries. Key changes: 1. Introduced a new file `keyword-control.tsx` that creates a Keyword Control component. This component includes a TextControl field that allows inputting a search keyword. The keyword search is debounced to prevent unnecessary queries during input and updates the block's attributes accordingly. 2. Modified `inspector-controls/index.tsx` to include the KeywordControl in the ToolsPanel for the block's filters. 3. Adjusted `ProductCollection.php` to include the keyword search in the product query array. With these changes, users can now search for products by keyword in the Product Collection block. * Add product attributes filter control to ProductCollection block - This commit introduces the ability to filter products by attributes in ProductCollection block. - A new `woocommerceAttributes` key was added to the `block.json` file and the `ProductCollectionQuery` type. Also, a new file `attributes-control.tsx` was created, providing the UI component for the attribute filter control in the editor. - In addition, updates were made to the `ProductCollection.php` file in the backend to support filtering products by attributes, and the tax query was updated to include attribute queries. - Lastly, the `ProductCollectionInspectorControls` was updated to include the `AttributesControl` component, thus enabling users to filter products by attributes in the block editor."` * remove unused import of getDefaultStockStatuses * Delete a duplicate file * Remove console log * Add taxonomies control to Product collection block The primary changes include: 1. `taxQuery` field in the `ProductCollectionAttributes` was changed from a string to an object in `assets/js/blocks/product-collection/types.ts` and `assets/js/blocks/product-collection/constants.ts`, accommodating the ability to query products by taxonomy terms. 2. `assets/js/blocks/product-collection/inspector-controls/utils.tsx` was moved to `assets/js/blocks/product-collection/utils.tsx` to make it available for broader use. 3. New component `TaxonomyControls` was created in `assets/js/blocks/product-collection/inspector-controls/taxonomy-controls.tsx`, which is included in `assets/js/blocks/product-collection/inspector-controls/index.tsx`. This new control allows users to filter products in the block by their taxonomy terms. 4. Updated the block's inspector controls in `assets/js/blocks/product-collection/inspector-controls/index.tsx` to use the new `TaxonomyControls` component. Please note that the TaxonomyControls component uses experimental features of WordPress's FormTokenField. As a result, a comment has been added to disable eslint warnings regarding the use of experimental APIs. * Address PR feedback & other improvements 1. Added `woocommerceAttributes` to `DEFAULT_FILTERS` in the `product-collection/constants.ts` file to fix `reset all` button issue. 2. Refactored `attributes-control.tsx` to make it more maintainable: - The constant `EDIT_ATTRIBUTES_URL` now uses `ADMIN_URL` from `@woocommerce/settings` for a more dynamic URL generation. - The interface `Props` has been renamed to `AttributesControlProps` for more explicit naming. - Removed the usage of `useState` and `useEffect` for selected attributes. Instead, `selectedAttributes` is now directly derived from `woocommerceAttributes`. - The CSS class `woocommerce-product-query-panel__external-link` was renamed to `wc-product-collection-panel__external-link` 3. Deleted the `product-collection/inspector-controls/constants.ts` file which was no longer necessary due to changes in product collection implementation. These changes contribute to codebase quality, improving readability and maintainability. * Address PR review comments This commit involves a significant refactoring of the default product query inside the 'product-collection/constants.ts' file. A new constant `DEFAULT_QUERY` has been defined and used to replace the previously hard-coded default query settings. This refactoring aids in code readability and future modifications. Changes also include adjustments in 'product-collection/inspector-controls' to enhance UI/UX. A new SCSS file 'editor.scss' has been created for custom styles related to the editor. Additions include: - Adding a class name `product-collection-inspector-toolspanel__filters` to ToolsPanel for additional styling. - The experimental property `__experimentalShowHowTo` is set to false for `FormTokenField` and `StockStatusControl`, to hide some additional information. In 'product-collection/inspector-controls/taxonomy-controls.tsx', the classname `product-collection-inspector__taxonomy-control` is added for improved CSS targeting. * Add wc-block-editor prefix to className * Add wc-block-editor- prefix with classNames * Handle duplicate taxonomy names in Taxonomy controls the taxonomy controls have been enhanced in the following ways: 1. Modified the BASE_QUERY object to include 'slug' in the '_fields' property. This will ensure that the 'slug' of the taxonomy term is fetched along with its 'id' and 'name'. 2. Added a 'slug' property to the Term type to store the 'slug' of each term. 3. Updated the useEffect hook inside the TaxonomyItem function to generate suggestions based on search results. The suggestions now include the 'slug' of a term if the term's name is not unique. This change will help users distinguish between terms with the same name but different slugs. * Remove isset() in if condition as it's unnecessary * Refactor TaxonomyItem component for better readability Following changes were made: 1. The useSelect hooks which were being used to fetch existing terms and search results have been moved into their own custom hooks named 'useExistingTerms' and 'useSearchResults' respectively. This simplifies the TaxonomyItem function's body and makes the hooks' purposes clearer. 2. The comments and props destructuring for the TaxonomyItem function have been moved up to make it easier to understand the function's purpose and the props it receives. 3. This refactor does not introduce any changes in functionality. It only changes how the code is organized and presented, which will make future development easier. * Handling for duplicate term names & other improvements This commit enhances the `TaxonomyControls` component within `product-collection` block by adding memoization and improving term uniqueness handling. Changes: 1. Imported `useMemo` from `@wordpress/element` for memoizing certain results. 2. `getTermIdByTermValue` function has been modified to use a `termIdToNameMap` (term ids as keys and term names as values). This provides a more efficient and direct mapping for term search. 3. Introduced `useTermIdToNameMap` function, which returns a `Map` where term ids are keys and term names are values. It handles duplicate term names by appending the term slug to the name, ensuring unique term names. 4. Updated the `useExistingTerms` and `useSearchResults` to include `taxonomy` in their dependency arrays for `useSelect` hook. This will force re-computation when `taxonomy` changes. 5. Changed `TaxonomyItem` from a function declaration to a const arrow function, consistent with the rest of the codebase. 6. Updated `onTermsChange` function in `TaxonomyItem` to accommodate the changes in `getTermIdByTermValue` and the introduction of `termIdToNameMap`. 7. Replaced `Set` with a standard array for storing new term IDs in `onTermsChange`. The `Set` was unnecessary as term IDs are unique by default. 8. Updated `TaxonomyItem`'s effects and rendering to work with `termIdToNameMap`, ensuring the displayed term names are unique. This update will result in more efficient term search and handling, and it will solve issues related to duplicate term names. * Restructure taxonomy controls in product collection block This commit restructures the taxonomy controls in the product collection block for improved clarity and maintainability. - The file `taxonomy-controls.tsx` has been deleted, and its functionality has been divided into two new files: `index.tsx` and `taxonomy-item.tsx`. - The `index.tsx` file contains the main TaxonomyControls component, which is responsible for displaying taxonomy-related options in the block's inspector controls. It includes a custom hook `useTaxonomies` that fetches and returns taxonomies associated with product post type. - The `taxonomy-item.tsx` file, on the other hand, contains a TaxonomyItem component that handles the rendering of individual taxonomy items. It also contains some utility functions for mapping term names and ids and fetching terms based on the search query. This refactor aims to improve code readability and separation of concerns, thus making future changes and maintenance easier. * Fix case insensitive search support for FormTokenField This change enhances the search functionality of the FormTokenField by introducing support for case insensitive search. This has been achieved by adding a lower-case version of the term name to the 'termNameToIdMap'. This is an important enhancement as it will make the search process more user-friendly and resilient to different casing inputs. Users will now be able to find the desired taxonomy term regardless of their input's case. * Refactor getTermIdByTermValue function and update newSuggestions mapping This commit does a couple of important things: 1. Reorders the definition of constants in `TaxonomyItemProps` for clarity. 2. Refactors the `getTermIdByTermValue` function. Instead of checking for an exact term name match in a convoluted manner, it now directly tries to fetch the `id` from the `searchTerm` if it is an object. If the `searchTerm` is not an object, the function tries to match it against the `termNameToIdMap` in both normal and lowercase forms. This simplification makes the function more readable and concise. 3. Updates the `newSuggestions` mapping in the `TaxonomyItem` component. It now has a fallback to `searchResult.name` if a term's name is not found in `termIdToNameMap`. This change ensures that even if the term's name is not in the map for some reason, we can still display a suggestion using the original name of the term. * Optimize term fetching and initial search state in TaxonomyItem This commit introduces a couple of improvements to the TaxonomyItem component. 1. The initial state of the 'search' state variable has been updated to 'undefined'. This change helps prevent unnecessary initial fetching of terms when the search input is empty. 2. Term fetching logic has been optimized to only enable term fetching when necessary: a) Fetching based on the search query is only enabled when 'search' is not 'undefined'. b) Fetching existing terms is only enabled when there are term IDs. 3. The block of code responsible for fetching existing terms and setting the current value has been moved upwards. This reordering of code does not change the functionality, but it groups together similar pieces of code, enhancing readability and maintainability. These optimizations make the component more efficient by reducing unnecessary requests and computations, and they improve the code organization. --------- Co-authored-by: Alexandre Lara <allexandrelara@gmail.com>
2023-06-02 10:01:29 +00:00
export const DEFAULT_QUERY: ProductCollectionQuery = {
perPage: 9,
pages: 0,
offset: 0,
postType: 'product',
order: 'asc',
orderBy: 'title',
search: '',
exclude: [],
Product Collection - Add Inherit query from template control (https://github.com/woocommerce/woocommerce-blocks/pull/9485) * Add columns control to product collection block editor settings - `InspectorControls` from './inspector-controls' is now imported in `edit.tsx` and used in the returned JSX of `Edit` function. - A new file `columns-control.tsx` is added under 'product-collection' block's 'inspector-controls' directory which exports a `ColumnsControl` component. This component uses `RangeControl` from '@wordpress/components' to control the number of columns in the product collection display layout when the layout type is 'flex'. - The types file (`types.ts`) for 'product-collection' block is updated. The `Attributes` interface is renamed to `ProductCollectionAttributes` and the `ProductCollectionContext` interface is removed. The `ProductCollectionAttributes` now includes 'queryContext', 'templateSlug', and 'displayLayout' properties. * Refactor: Simplify Fallback Return in ColumnsControl Component This commit simplifies the fallback return value of the ColumnsControl component. Instead of returning an empty fragment (<> </>), it now returns null when the condition isn't met. This change improves readability and aligns with best practices for conditional rendering in React. * Feature: Add 'Order By' Control to Product Collection Inspector This commit adds a new 'Order By' control to the product collection inspector. The control allows users to specify the order of products in a collection by various attributes such as title and date. To support this, a new component 'OrderByControl' has been created and included in the product collection inspector. Additionally, the types for 'order' and 'orderBy' attributes have been updated and exported for reuse. * Add more options to OrderBy type * Add Inherit global query control to the Product Collection * Add orderby handling on frontend & editor The main changes include: 1. Added a new property 'isProductCollectionBlock' in the block.json to denote if a block is a product collection block. 2. In the ProductCollection PHP class, a new initialization function has been defined to hook into the WordPress lifecycle, register the block, and update the query based on this block. 3. Added methods to manage query parameters for both frontend rendering and the Editor. 4. Expanded allowed 'collection_params' for the REST API to include custom 'orderby' values. 5. Defined a function to build the query based on block attributes, filters, and global WP_Query. 6. Created utility functions to handle complex query operations such as merging queries, handling custom sort values, and merging arrays recursively. These improvements allow for more flexible and robust handling of product collections in both the front-end display and the WordPress editor. It also extends support for custom 'orderby' values in the REST API, which allows for more advanced sorting options in product collections. * Fix the condition to show query controls (they shoul appear if query is NOT inherited) * Make Product Collection inheirt global query in product archive templates by default * Add 'on sale' filter and enhance settings management in product collection block This commit introduces several changes to the product collection block. - First, it adds a new 'on sale' filter that can be used to display only the products that are currently on sale. - It also refactors the settings management in the product collection block to use the experimental ToolsPanel component from WordPress, which provides a more flexible and intuitive way to manage block settings. - It moves the 'Columns' control into the ToolsPanel, along with the 'Order by' control. - A new utility function `setQueryAttribute` is introduced to simplify setting nested query parameters. - The structure of the `ProductCollectionAttributes` and `ProductCollectionQuery` types have been adjusted to accommodate the changes. - Finally, it makes corresponding changes in the PHP part to handle the new 'on sale' query parameter. This should enhance the flexibility and user-friendliness of the product collection block. * Revert "Make Product Collection inheirt global query in product archive templates by default" This reverts commit d257e8bdb014742c40ef069110f6a2a35148fb7a. * Updated 'inherit' behavior in the Product Collection block This commit updates the 'inherit' behavior in the Product Collection block and its associated controls. Changes include: - Removed the 'inherit' attribute from the block's JSON definition - Defined an array of 'archive product templates' which includes the WooCommerce product archive, taxonomy, attribute, and search results templates. - Set the initial 'inherit' value based on the current template ID when the Product Collection block is first added to the page. - Restored the query object value when toggling 'inherit' off. - Conditionally rendered the InheritQueryControl based on the current editor being the site editor. * Add stock status filter to WooCommerce product collection block This commit introduces a stock status filter to the WooCommerce product collection block. The changes include: 1. Added the ability to filter products based on their stock status within the 'product-collection' block. A new stock status control is created within the inspector-controls of the block. 2. A new 'get_stock_status_query' function is introduced in 'ProductCollection.php' which returns a query for products depending on their stock status. Please note that the stock status filter will only appear in the experimental build for now. * Refactor Stock Status control of Product Collection block This commit refactors the Stock Status control. The changes aim to improve the code organization and make the behavior of the component more explicit. The key modifications are: 1. Moved stock status related constants and functions from `inspector-controls/utils.tsx` to `inspector-controls/constants.ts`. This is done to ensure that all constants and similar utility functions are organized in one place. 2. Updated `product-collection/index.tsx` to import `getDefaultStockStatuses` from `inspector-controls/constants` instead of `inspector-controls/utils`. 3. Updated `stock-status-control.tsx` to determine whether the stock status has value or not by comparing with the default stock statuses using `fastDeepEqual`. If the stock status control is deselected, it resets the stock status to the default statuses. These changes do not introduce any new functionalities, but improve the readability and maintainability of the code. * Add keyword search control to Product Collection block This commit introduces a keyword search functionality to the Product Collection block. The update is aimed to provide users with more flexibility and precision in product collection queries. Key changes: 1. Introduced a new file `keyword-control.tsx` that creates a Keyword Control component. This component includes a TextControl field that allows inputting a search keyword. The keyword search is debounced to prevent unnecessary queries during input and updates the block's attributes accordingly. 2. Modified `inspector-controls/index.tsx` to include the KeywordControl in the ToolsPanel for the block's filters. 3. Adjusted `ProductCollection.php` to include the keyword search in the product query array. With these changes, users can now search for products by keyword in the Product Collection block. * Add product attributes filter control to ProductCollection block - This commit introduces the ability to filter products by attributes in ProductCollection block. - A new `woocommerceAttributes` key was added to the `block.json` file and the `ProductCollectionQuery` type. Also, a new file `attributes-control.tsx` was created, providing the UI component for the attribute filter control in the editor. - In addition, updates were made to the `ProductCollection.php` file in the backend to support filtering products by attributes, and the tax query was updated to include attribute queries. - Lastly, the `ProductCollectionInspectorControls` was updated to include the `AttributesControl` component, thus enabling users to filter products by attributes in the block editor."` * remove unused import of getDefaultStockStatuses * Delete a duplicate file * Remove console log * Add taxonomies control to Product collection block The primary changes include: 1. `taxQuery` field in the `ProductCollectionAttributes` was changed from a string to an object in `assets/js/blocks/product-collection/types.ts` and `assets/js/blocks/product-collection/constants.ts`, accommodating the ability to query products by taxonomy terms. 2. `assets/js/blocks/product-collection/inspector-controls/utils.tsx` was moved to `assets/js/blocks/product-collection/utils.tsx` to make it available for broader use. 3. New component `TaxonomyControls` was created in `assets/js/blocks/product-collection/inspector-controls/taxonomy-controls.tsx`, which is included in `assets/js/blocks/product-collection/inspector-controls/index.tsx`. This new control allows users to filter products in the block by their taxonomy terms. 4. Updated the block's inspector controls in `assets/js/blocks/product-collection/inspector-controls/index.tsx` to use the new `TaxonomyControls` component. Please note that the TaxonomyControls component uses experimental features of WordPress's FormTokenField. As a result, a comment has been added to disable eslint warnings regarding the use of experimental APIs. * Address PR feedback & other improvements 1. Added `woocommerceAttributes` to `DEFAULT_FILTERS` in the `product-collection/constants.ts` file to fix `reset all` button issue. 2. Refactored `attributes-control.tsx` to make it more maintainable: - The constant `EDIT_ATTRIBUTES_URL` now uses `ADMIN_URL` from `@woocommerce/settings` for a more dynamic URL generation. - The interface `Props` has been renamed to `AttributesControlProps` for more explicit naming. - Removed the usage of `useState` and `useEffect` for selected attributes. Instead, `selectedAttributes` is now directly derived from `woocommerceAttributes`. - The CSS class `woocommerce-product-query-panel__external-link` was renamed to `wc-product-collection-panel__external-link` 3. Deleted the `product-collection/inspector-controls/constants.ts` file which was no longer necessary due to changes in product collection implementation. These changes contribute to codebase quality, improving readability and maintainability. * Address PR review comments This commit involves a significant refactoring of the default product query inside the 'product-collection/constants.ts' file. A new constant `DEFAULT_QUERY` has been defined and used to replace the previously hard-coded default query settings. This refactoring aids in code readability and future modifications. Changes also include adjustments in 'product-collection/inspector-controls' to enhance UI/UX. A new SCSS file 'editor.scss' has been created for custom styles related to the editor. Additions include: - Adding a class name `product-collection-inspector-toolspanel__filters` to ToolsPanel for additional styling. - The experimental property `__experimentalShowHowTo` is set to false for `FormTokenField` and `StockStatusControl`, to hide some additional information. In 'product-collection/inspector-controls/taxonomy-controls.tsx', the classname `product-collection-inspector__taxonomy-control` is added for improved CSS targeting. * Add wc-block-editor prefix to className * Make improvements to 'inherit' functionality in Product collection block. Key changes are: 1. 'inherit' in 'ProductCollectionAttributes' within 'constants.ts' has been changed from 'false' to 'null'. This accommodates for situations when Product collection block is first added to the page. 2. Various improvements in 'index.tsx' file which include more robust null checking for the 'query' object, simplifying the way 'woocommerceAttributes' is obtained, and passing 'setQueryAttributeBind' and 'inherit' to the 'InheritQueryControl' component. 3. In 'inherit-query-control.tsx', 'InheritQueryControl' component has been refactored to use '__experimentalToolsPanelItem' from '@wordpress/components' instead of 'ToggleControl'. This adds more flexibility to the control. 4. Changes in 'ProductCollectionAttributes' and 'ProductCollectionQuery' types in 'types.ts'. The * Improve product collection query inheritance and fix URL typo This commit addresses two primary areas: 1. Fixed a typo in the URL used as a reference in the use-previous.ts file. The URL was incorrectly case-sensitive, which has been corrected. 2. The product-collection block in the JavaScript files has been refactored for better handling of query inheritance: - Changed the 'inherit' value from false to null in the DEFAULT_QUERY constant to handle initial state more accurately. - In product-collection/inspector-controls, implemented conditional rendering for Filters and Query Controls based on 'displayQueryControls'. Also, improved the 'InheritQueryControl' by using the 'usePrevious' hook to maintain the state before enabling the inheritance. - In inherit-query-control, enhanced the control to toggle the query inheritance. It now considers the 'inherit' state from the query object and keeps track of the query object state before enabling inheritance. If the inheritance is toggled off, it reverts the query to the previous state before inheritance was enabled. * Minor improvemnets * Add wc-block-editor- prefix with classNames * Handle duplicate taxonomy names in Taxonomy controls the taxonomy controls have been enhanced in the following ways: 1. Modified the BASE_QUERY object to include 'slug' in the '_fields' property. This will ensure that the 'slug' of the taxonomy term is fetched along with its 'id' and 'name'. 2. Added a 'slug' property to the Term type to store the 'slug' of each term. 3. Updated the useEffect hook inside the TaxonomyItem function to generate suggestions based on search results. The suggestions now include the 'slug' of a term if the term's name is not unique. This change will help users distinguish between terms with the same name but different slugs. * Remove isset() in if condition as it's unnecessary * Refactor TaxonomyItem component for better readability Following changes were made: 1. The useSelect hooks which were being used to fetch existing terms and search results have been moved into their own custom hooks named 'useExistingTerms' and 'useSearchResults' respectively. This simplifies the TaxonomyItem function's body and makes the hooks' purposes clearer. 2. The comments and props destructuring for the TaxonomyItem function have been moved up to make it easier to understand the function's purpose and the props it receives. 3. This refactor does not introduce any changes in functionality. It only changes how the code is organized and presented, which will make future development easier. * Handling for duplicate term names & other improvements This commit enhances the `TaxonomyControls` component within `product-collection` block by adding memoization and improving term uniqueness handling. Changes: 1. Imported `useMemo` from `@wordpress/element` for memoizing certain results. 2. `getTermIdByTermValue` function has been modified to use a `termIdToNameMap` (term ids as keys and term names as values). This provides a more efficient and direct mapping for term search. 3. Introduced `useTermIdToNameMap` function, which returns a `Map` where term ids are keys and term names are values. It handles duplicate term names by appending the term slug to the name, ensuring unique term names. 4. Updated the `useExistingTerms` and `useSearchResults` to include `taxonomy` in their dependency arrays for `useSelect` hook. This will force re-computation when `taxonomy` changes. 5. Changed `TaxonomyItem` from a function declaration to a const arrow function, consistent with the rest of the codebase. 6. Updated `onTermsChange` function in `TaxonomyItem` to accommodate the changes in `getTermIdByTermValue` and the introduction of `termIdToNameMap`. 7. Replaced `Set` with a standard array for storing new term IDs in `onTermsChange`. The `Set` was unnecessary as term IDs are unique by default. 8. Updated `TaxonomyItem`'s effects and rendering to work with `termIdToNameMap`, ensuring the displayed term names are unique. This update will result in more efficient term search and handling, and it will solve issues related to duplicate term names. * Restructure taxonomy controls in product collection block This commit restructures the taxonomy controls in the product collection block for improved clarity and maintainability. - The file `taxonomy-controls.tsx` has been deleted, and its functionality has been divided into two new files: `index.tsx` and `taxonomy-item.tsx`. - The `index.tsx` file contains the main TaxonomyControls component, which is responsible for displaying taxonomy-related options in the block's inspector controls. It includes a custom hook `useTaxonomies` that fetches and returns taxonomies associated with product post type. - The `taxonomy-item.tsx` file, on the other hand, contains a TaxonomyItem component that handles the rendering of individual taxonomy items. It also contains some utility functions for mapping term names and ids and fetching terms based on the search query. This refactor aims to improve code readability and separation of concerns, thus making future changes and maintenance easier. * Fix case insensitive search support for FormTokenField This change enhances the search functionality of the FormTokenField by introducing support for case insensitive search. This has been achieved by adding a lower-case version of the term name to the 'termNameToIdMap'. This is an important enhancement as it will make the search process more user-friendly and resilient to different casing inputs. Users will now be able to find the desired taxonomy term regardless of their input's case. * Refactor getTermIdByTermValue function and update newSuggestions mapping This commit does a couple of important things: 1. Reorders the definition of constants in `TaxonomyItemProps` for clarity. 2. Refactors the `getTermIdByTermValue` function. Instead of checking for an exact term name match in a convoluted manner, it now directly tries to fetch the `id` from the `searchTerm` if it is an object. If the `searchTerm` is not an object, the function tries to match it against the `termNameToIdMap` in both normal and lowercase forms. This simplification makes the function more readable and concise. 3. Updates the `newSuggestions` mapping in the `TaxonomyItem` component. It now has a fallback to `searchResult.name` if a term's name is not found in `termIdToNameMap`. This change ensures that even if the term's name is not in the map for some reason, we can still display a suggestion using the original name of the term. * Optimize term fetching and initial search state in TaxonomyItem This commit introduces a couple of improvements to the TaxonomyItem component. 1. The initial state of the 'search' state variable has been updated to 'undefined'. This change helps prevent unnecessary initial fetching of terms when the search input is empty. 2. Term fetching logic has been optimized to only enable term fetching when necessary: a) Fetching based on the search query is only enabled when 'search' is not 'undefined'. b) Fetching existing terms is only enabled when there are term IDs. 3. The block of code responsible for fetching existing terms and setting the current value has been moved upwards. This reordering of code does not change the functionality, but it groups together similar pieces of code, enhancing readability and maintainability. These optimizations make the component more efficient by reducing unnecessary requests and computations, and they improve the code organization. * Address PR comments and other improvements This commit makes several changes: 1. The useEffect that sets the default attributes was moved and modified. This now includes a `query` attribute that utilizes the imported function `getDefaultValueOfInheritQueryFromTemplate`. 2. An early return was added in `edit.tsx` to prevent rendering until default attributes are set. 3. In `columns-control.tsx`, the early return was removed and a label was added to the `RangeControl` component. 4. In `inherit-query-control.tsx`, logic related to `inherit` value initial setting was refactored using a `useMemo` hook with `getDefaultValueOfInheritQueryFromTemplate` function. This logic was moved to a separate utility function in `utils`. 5. The `query` attribute is no longer optional in `types.ts`. 6. A new utility function `getDefaultValueOfInheritQueryFromTemplate` was created in `utils.tsx` to encapsulate the logic of deciding the default value of `inherit` query attribute based on the current template. These changes aim to improve code clarity and maintainability. * Add with types import statement --------- Co-authored-by: Manish Menaria <the.manish.menaria@gmail.com> Co-authored-by: Alexandre Lara <allexandrelara@gmail.com>
2023-06-05 06:09:11 +00:00
inherit: null,
Product Collection: Add Taxonomy filters to sidebar settings (https://github.com/woocommerce/woocommerce-blocks/pull/9634) * Add columns control to product collection block editor settings - `InspectorControls` from './inspector-controls' is now imported in `edit.tsx` and used in the returned JSX of `Edit` function. - A new file `columns-control.tsx` is added under 'product-collection' block's 'inspector-controls' directory which exports a `ColumnsControl` component. This component uses `RangeControl` from '@wordpress/components' to control the number of columns in the product collection display layout when the layout type is 'flex'. - The types file (`types.ts`) for 'product-collection' block is updated. The `Attributes` interface is renamed to `ProductCollectionAttributes` and the `ProductCollectionContext` interface is removed. The `ProductCollectionAttributes` now includes 'queryContext', 'templateSlug', and 'displayLayout' properties. * Refactor: Simplify Fallback Return in ColumnsControl Component This commit simplifies the fallback return value of the ColumnsControl component. Instead of returning an empty fragment (<> </>), it now returns null when the condition isn't met. This change improves readability and aligns with best practices for conditional rendering in React. * Feature: Add 'Order By' Control to Product Collection Inspector This commit adds a new 'Order By' control to the product collection inspector. The control allows users to specify the order of products in a collection by various attributes such as title and date. To support this, a new component 'OrderByControl' has been created and included in the product collection inspector. Additionally, the types for 'order' and 'orderBy' attributes have been updated and exported for reuse. * Add more options to OrderBy type * Add orderby handling on frontend & editor The main changes include: 1. Added a new property 'isProductCollectionBlock' in the block.json to denote if a block is a product collection block. 2. In the ProductCollection PHP class, a new initialization function has been defined to hook into the WordPress lifecycle, register the block, and update the query based on this block. 3. Added methods to manage query parameters for both frontend rendering and the Editor. 4. Expanded allowed 'collection_params' for the REST API to include custom 'orderby' values. 5. Defined a function to build the query based on block attributes, filters, and global WP_Query. 6. Created utility functions to handle complex query operations such as merging queries, handling custom sort values, and merging arrays recursively. These improvements allow for more flexible and robust handling of product collections in both the front-end display and the WordPress editor. It also extends support for custom 'orderby' values in the REST API, which allows for more advanced sorting options in product collections. * Add 'on sale' filter and enhance settings management in product collection block This commit introduces several changes to the product collection block. - First, it adds a new 'on sale' filter that can be used to display only the products that are currently on sale. - It also refactors the settings management in the product collection block to use the experimental ToolsPanel component from WordPress, which provides a more flexible and intuitive way to manage block settings. - It moves the 'Columns' control into the ToolsPanel, along with the 'Order by' control. - A new utility function `setQueryAttribute` is introduced to simplify setting nested query parameters. - The structure of the `ProductCollectionAttributes` and `ProductCollectionQuery` types have been adjusted to accommodate the changes. - Finally, it makes corresponding changes in the PHP part to handle the new 'on sale' query parameter. This should enhance the flexibility and user-friendliness of the product collection block. * Add stock status filter to WooCommerce product collection block This commit introduces a stock status filter to the WooCommerce product collection block. The changes include: 1. Added the ability to filter products based on their stock status within the 'product-collection' block. A new stock status control is created within the inspector-controls of the block. 2. A new 'get_stock_status_query' function is introduced in 'ProductCollection.php' which returns a query for products depending on their stock status. Please note that the stock status filter will only appear in the experimental build for now. * Refactor Stock Status control of Product Collection block This commit refactors the Stock Status control. The changes aim to improve the code organization and make the behavior of the component more explicit. The key modifications are: 1. Moved stock status related constants and functions from `inspector-controls/utils.tsx` to `inspector-controls/constants.ts`. This is done to ensure that all constants and similar utility functions are organized in one place. 2. Updated `product-collection/index.tsx` to import `getDefaultStockStatuses` from `inspector-controls/constants` instead of `inspector-controls/utils`. 3. Updated `stock-status-control.tsx` to determine whether the stock status has value or not by comparing with the default stock statuses using `fastDeepEqual`. If the stock status control is deselected, it resets the stock status to the default statuses. These changes do not introduce any new functionalities, but improve the readability and maintainability of the code. * Add keyword search control to Product Collection block This commit introduces a keyword search functionality to the Product Collection block. The update is aimed to provide users with more flexibility and precision in product collection queries. Key changes: 1. Introduced a new file `keyword-control.tsx` that creates a Keyword Control component. This component includes a TextControl field that allows inputting a search keyword. The keyword search is debounced to prevent unnecessary queries during input and updates the block's attributes accordingly. 2. Modified `inspector-controls/index.tsx` to include the KeywordControl in the ToolsPanel for the block's filters. 3. Adjusted `ProductCollection.php` to include the keyword search in the product query array. With these changes, users can now search for products by keyword in the Product Collection block. * Add product attributes filter control to ProductCollection block - This commit introduces the ability to filter products by attributes in ProductCollection block. - A new `woocommerceAttributes` key was added to the `block.json` file and the `ProductCollectionQuery` type. Also, a new file `attributes-control.tsx` was created, providing the UI component for the attribute filter control in the editor. - In addition, updates were made to the `ProductCollection.php` file in the backend to support filtering products by attributes, and the tax query was updated to include attribute queries. - Lastly, the `ProductCollectionInspectorControls` was updated to include the `AttributesControl` component, thus enabling users to filter products by attributes in the block editor."` * remove unused import of getDefaultStockStatuses * Delete a duplicate file * Remove console log * Add taxonomies control to Product collection block The primary changes include: 1. `taxQuery` field in the `ProductCollectionAttributes` was changed from a string to an object in `assets/js/blocks/product-collection/types.ts` and `assets/js/blocks/product-collection/constants.ts`, accommodating the ability to query products by taxonomy terms. 2. `assets/js/blocks/product-collection/inspector-controls/utils.tsx` was moved to `assets/js/blocks/product-collection/utils.tsx` to make it available for broader use. 3. New component `TaxonomyControls` was created in `assets/js/blocks/product-collection/inspector-controls/taxonomy-controls.tsx`, which is included in `assets/js/blocks/product-collection/inspector-controls/index.tsx`. This new control allows users to filter products in the block by their taxonomy terms. 4. Updated the block's inspector controls in `assets/js/blocks/product-collection/inspector-controls/index.tsx` to use the new `TaxonomyControls` component. Please note that the TaxonomyControls component uses experimental features of WordPress's FormTokenField. As a result, a comment has been added to disable eslint warnings regarding the use of experimental APIs. * Address PR feedback & other improvements 1. Added `woocommerceAttributes` to `DEFAULT_FILTERS` in the `product-collection/constants.ts` file to fix `reset all` button issue. 2. Refactored `attributes-control.tsx` to make it more maintainable: - The constant `EDIT_ATTRIBUTES_URL` now uses `ADMIN_URL` from `@woocommerce/settings` for a more dynamic URL generation. - The interface `Props` has been renamed to `AttributesControlProps` for more explicit naming. - Removed the usage of `useState` and `useEffect` for selected attributes. Instead, `selectedAttributes` is now directly derived from `woocommerceAttributes`. - The CSS class `woocommerce-product-query-panel__external-link` was renamed to `wc-product-collection-panel__external-link` 3. Deleted the `product-collection/inspector-controls/constants.ts` file which was no longer necessary due to changes in product collection implementation. These changes contribute to codebase quality, improving readability and maintainability. * Address PR review comments This commit involves a significant refactoring of the default product query inside the 'product-collection/constants.ts' file. A new constant `DEFAULT_QUERY` has been defined and used to replace the previously hard-coded default query settings. This refactoring aids in code readability and future modifications. Changes also include adjustments in 'product-collection/inspector-controls' to enhance UI/UX. A new SCSS file 'editor.scss' has been created for custom styles related to the editor. Additions include: - Adding a class name `product-collection-inspector-toolspanel__filters` to ToolsPanel for additional styling. - The experimental property `__experimentalShowHowTo` is set to false for `FormTokenField` and `StockStatusControl`, to hide some additional information. In 'product-collection/inspector-controls/taxonomy-controls.tsx', the classname `product-collection-inspector__taxonomy-control` is added for improved CSS targeting. * Add wc-block-editor prefix to className * Add wc-block-editor- prefix with classNames * Handle duplicate taxonomy names in Taxonomy controls the taxonomy controls have been enhanced in the following ways: 1. Modified the BASE_QUERY object to include 'slug' in the '_fields' property. This will ensure that the 'slug' of the taxonomy term is fetched along with its 'id' and 'name'. 2. Added a 'slug' property to the Term type to store the 'slug' of each term. 3. Updated the useEffect hook inside the TaxonomyItem function to generate suggestions based on search results. The suggestions now include the 'slug' of a term if the term's name is not unique. This change will help users distinguish between terms with the same name but different slugs. * Remove isset() in if condition as it's unnecessary * Refactor TaxonomyItem component for better readability Following changes were made: 1. The useSelect hooks which were being used to fetch existing terms and search results have been moved into their own custom hooks named 'useExistingTerms' and 'useSearchResults' respectively. This simplifies the TaxonomyItem function's body and makes the hooks' purposes clearer. 2. The comments and props destructuring for the TaxonomyItem function have been moved up to make it easier to understand the function's purpose and the props it receives. 3. This refactor does not introduce any changes in functionality. It only changes how the code is organized and presented, which will make future development easier. * Handling for duplicate term names & other improvements This commit enhances the `TaxonomyControls` component within `product-collection` block by adding memoization and improving term uniqueness handling. Changes: 1. Imported `useMemo` from `@wordpress/element` for memoizing certain results. 2. `getTermIdByTermValue` function has been modified to use a `termIdToNameMap` (term ids as keys and term names as values). This provides a more efficient and direct mapping for term search. 3. Introduced `useTermIdToNameMap` function, which returns a `Map` where term ids are keys and term names are values. It handles duplicate term names by appending the term slug to the name, ensuring unique term names. 4. Updated the `useExistingTerms` and `useSearchResults` to include `taxonomy` in their dependency arrays for `useSelect` hook. This will force re-computation when `taxonomy` changes. 5. Changed `TaxonomyItem` from a function declaration to a const arrow function, consistent with the rest of the codebase. 6. Updated `onTermsChange` function in `TaxonomyItem` to accommodate the changes in `getTermIdByTermValue` and the introduction of `termIdToNameMap`. 7. Replaced `Set` with a standard array for storing new term IDs in `onTermsChange`. The `Set` was unnecessary as term IDs are unique by default. 8. Updated `TaxonomyItem`'s effects and rendering to work with `termIdToNameMap`, ensuring the displayed term names are unique. This update will result in more efficient term search and handling, and it will solve issues related to duplicate term names. * Restructure taxonomy controls in product collection block This commit restructures the taxonomy controls in the product collection block for improved clarity and maintainability. - The file `taxonomy-controls.tsx` has been deleted, and its functionality has been divided into two new files: `index.tsx` and `taxonomy-item.tsx`. - The `index.tsx` file contains the main TaxonomyControls component, which is responsible for displaying taxonomy-related options in the block's inspector controls. It includes a custom hook `useTaxonomies` that fetches and returns taxonomies associated with product post type. - The `taxonomy-item.tsx` file, on the other hand, contains a TaxonomyItem component that handles the rendering of individual taxonomy items. It also contains some utility functions for mapping term names and ids and fetching terms based on the search query. This refactor aims to improve code readability and separation of concerns, thus making future changes and maintenance easier. * Fix case insensitive search support for FormTokenField This change enhances the search functionality of the FormTokenField by introducing support for case insensitive search. This has been achieved by adding a lower-case version of the term name to the 'termNameToIdMap'. This is an important enhancement as it will make the search process more user-friendly and resilient to different casing inputs. Users will now be able to find the desired taxonomy term regardless of their input's case. * Refactor getTermIdByTermValue function and update newSuggestions mapping This commit does a couple of important things: 1. Reorders the definition of constants in `TaxonomyItemProps` for clarity. 2. Refactors the `getTermIdByTermValue` function. Instead of checking for an exact term name match in a convoluted manner, it now directly tries to fetch the `id` from the `searchTerm` if it is an object. If the `searchTerm` is not an object, the function tries to match it against the `termNameToIdMap` in both normal and lowercase forms. This simplification makes the function more readable and concise. 3. Updates the `newSuggestions` mapping in the `TaxonomyItem` component. It now has a fallback to `searchResult.name` if a term's name is not found in `termIdToNameMap`. This change ensures that even if the term's name is not in the map for some reason, we can still display a suggestion using the original name of the term. * Optimize term fetching and initial search state in TaxonomyItem This commit introduces a couple of improvements to the TaxonomyItem component. 1. The initial state of the 'search' state variable has been updated to 'undefined'. This change helps prevent unnecessary initial fetching of terms when the search input is empty. 2. Term fetching logic has been optimized to only enable term fetching when necessary: a) Fetching based on the search query is only enabled when 'search' is not 'undefined'. b) Fetching existing terms is only enabled when there are term IDs. 3. The block of code responsible for fetching existing terms and setting the current value has been moved upwards. This reordering of code does not change the functionality, but it groups together similar pieces of code, enhancing readability and maintainability. These optimizations make the component more efficient by reducing unnecessary requests and computations, and they improve the code organization. --------- Co-authored-by: Alexandre Lara <allexandrelara@gmail.com>
2023-06-02 10:01:29 +00:00
taxQuery: {},
isProductCollectionBlock: true,
Product Collection: Add support for filtering products by featured status (https://github.com/woocommerce/woocommerce-blocks/pull/11522) * Add support for filtering products by featured status - Added `featured` attribute to `ProductCollectionQuery` type to enable filtering by featured status. - Implemented `FeaturedProductsControl` to provide a toggle option in the inspector controls. - Integrated `FeaturedProductsControl` into `ProductCollectionInspectorControls`. - Added `get_featured_query` function in `ProductCollection` class to generate query for fetching featured products. - Updated existing functions and queries in `ProductCollection` class to support featured products filtering. * Revert changes to composer.lock * Refactor handling of 'featured' parameter This commit makes the handling of the 'featured' parameter consistent in the ProductCollection class. Previously, the 'featured' parameter was being type-casted to boolean, which was not necessary and could lead to incorrect results. Now, the 'featured' parameter is used directly without type-casting, and the check for 'featured' products in the get_featured_query method has been updated accordingly. This ensures that the 'featured' parameter is handled consistently and correctly throughout the class. * Handle undefined 'featured' index This commit adds null coalescing operator to handle the case when 'featured' index is not set in the $query array. This prevents potential PHP notices or errors that may arise when trying to access an undefined index.
2023-11-08 10:07:32 +00:00
featured: false,
Product Collection: Add Taxonomy filters to sidebar settings (https://github.com/woocommerce/woocommerce-blocks/pull/9634) * Add columns control to product collection block editor settings - `InspectorControls` from './inspector-controls' is now imported in `edit.tsx` and used in the returned JSX of `Edit` function. - A new file `columns-control.tsx` is added under 'product-collection' block's 'inspector-controls' directory which exports a `ColumnsControl` component. This component uses `RangeControl` from '@wordpress/components' to control the number of columns in the product collection display layout when the layout type is 'flex'. - The types file (`types.ts`) for 'product-collection' block is updated. The `Attributes` interface is renamed to `ProductCollectionAttributes` and the `ProductCollectionContext` interface is removed. The `ProductCollectionAttributes` now includes 'queryContext', 'templateSlug', and 'displayLayout' properties. * Refactor: Simplify Fallback Return in ColumnsControl Component This commit simplifies the fallback return value of the ColumnsControl component. Instead of returning an empty fragment (<> </>), it now returns null when the condition isn't met. This change improves readability and aligns with best practices for conditional rendering in React. * Feature: Add 'Order By' Control to Product Collection Inspector This commit adds a new 'Order By' control to the product collection inspector. The control allows users to specify the order of products in a collection by various attributes such as title and date. To support this, a new component 'OrderByControl' has been created and included in the product collection inspector. Additionally, the types for 'order' and 'orderBy' attributes have been updated and exported for reuse. * Add more options to OrderBy type * Add orderby handling on frontend & editor The main changes include: 1. Added a new property 'isProductCollectionBlock' in the block.json to denote if a block is a product collection block. 2. In the ProductCollection PHP class, a new initialization function has been defined to hook into the WordPress lifecycle, register the block, and update the query based on this block. 3. Added methods to manage query parameters for both frontend rendering and the Editor. 4. Expanded allowed 'collection_params' for the REST API to include custom 'orderby' values. 5. Defined a function to build the query based on block attributes, filters, and global WP_Query. 6. Created utility functions to handle complex query operations such as merging queries, handling custom sort values, and merging arrays recursively. These improvements allow for more flexible and robust handling of product collections in both the front-end display and the WordPress editor. It also extends support for custom 'orderby' values in the REST API, which allows for more advanced sorting options in product collections. * Add 'on sale' filter and enhance settings management in product collection block This commit introduces several changes to the product collection block. - First, it adds a new 'on sale' filter that can be used to display only the products that are currently on sale. - It also refactors the settings management in the product collection block to use the experimental ToolsPanel component from WordPress, which provides a more flexible and intuitive way to manage block settings. - It moves the 'Columns' control into the ToolsPanel, along with the 'Order by' control. - A new utility function `setQueryAttribute` is introduced to simplify setting nested query parameters. - The structure of the `ProductCollectionAttributes` and `ProductCollectionQuery` types have been adjusted to accommodate the changes. - Finally, it makes corresponding changes in the PHP part to handle the new 'on sale' query parameter. This should enhance the flexibility and user-friendliness of the product collection block. * Add stock status filter to WooCommerce product collection block This commit introduces a stock status filter to the WooCommerce product collection block. The changes include: 1. Added the ability to filter products based on their stock status within the 'product-collection' block. A new stock status control is created within the inspector-controls of the block. 2. A new 'get_stock_status_query' function is introduced in 'ProductCollection.php' which returns a query for products depending on their stock status. Please note that the stock status filter will only appear in the experimental build for now. * Refactor Stock Status control of Product Collection block This commit refactors the Stock Status control. The changes aim to improve the code organization and make the behavior of the component more explicit. The key modifications are: 1. Moved stock status related constants and functions from `inspector-controls/utils.tsx` to `inspector-controls/constants.ts`. This is done to ensure that all constants and similar utility functions are organized in one place. 2. Updated `product-collection/index.tsx` to import `getDefaultStockStatuses` from `inspector-controls/constants` instead of `inspector-controls/utils`. 3. Updated `stock-status-control.tsx` to determine whether the stock status has value or not by comparing with the default stock statuses using `fastDeepEqual`. If the stock status control is deselected, it resets the stock status to the default statuses. These changes do not introduce any new functionalities, but improve the readability and maintainability of the code. * Add keyword search control to Product Collection block This commit introduces a keyword search functionality to the Product Collection block. The update is aimed to provide users with more flexibility and precision in product collection queries. Key changes: 1. Introduced a new file `keyword-control.tsx` that creates a Keyword Control component. This component includes a TextControl field that allows inputting a search keyword. The keyword search is debounced to prevent unnecessary queries during input and updates the block's attributes accordingly. 2. Modified `inspector-controls/index.tsx` to include the KeywordControl in the ToolsPanel for the block's filters. 3. Adjusted `ProductCollection.php` to include the keyword search in the product query array. With these changes, users can now search for products by keyword in the Product Collection block. * Add product attributes filter control to ProductCollection block - This commit introduces the ability to filter products by attributes in ProductCollection block. - A new `woocommerceAttributes` key was added to the `block.json` file and the `ProductCollectionQuery` type. Also, a new file `attributes-control.tsx` was created, providing the UI component for the attribute filter control in the editor. - In addition, updates were made to the `ProductCollection.php` file in the backend to support filtering products by attributes, and the tax query was updated to include attribute queries. - Lastly, the `ProductCollectionInspectorControls` was updated to include the `AttributesControl` component, thus enabling users to filter products by attributes in the block editor."` * remove unused import of getDefaultStockStatuses * Delete a duplicate file * Remove console log * Add taxonomies control to Product collection block The primary changes include: 1. `taxQuery` field in the `ProductCollectionAttributes` was changed from a string to an object in `assets/js/blocks/product-collection/types.ts` and `assets/js/blocks/product-collection/constants.ts`, accommodating the ability to query products by taxonomy terms. 2. `assets/js/blocks/product-collection/inspector-controls/utils.tsx` was moved to `assets/js/blocks/product-collection/utils.tsx` to make it available for broader use. 3. New component `TaxonomyControls` was created in `assets/js/blocks/product-collection/inspector-controls/taxonomy-controls.tsx`, which is included in `assets/js/blocks/product-collection/inspector-controls/index.tsx`. This new control allows users to filter products in the block by their taxonomy terms. 4. Updated the block's inspector controls in `assets/js/blocks/product-collection/inspector-controls/index.tsx` to use the new `TaxonomyControls` component. Please note that the TaxonomyControls component uses experimental features of WordPress's FormTokenField. As a result, a comment has been added to disable eslint warnings regarding the use of experimental APIs. * Address PR feedback & other improvements 1. Added `woocommerceAttributes` to `DEFAULT_FILTERS` in the `product-collection/constants.ts` file to fix `reset all` button issue. 2. Refactored `attributes-control.tsx` to make it more maintainable: - The constant `EDIT_ATTRIBUTES_URL` now uses `ADMIN_URL` from `@woocommerce/settings` for a more dynamic URL generation. - The interface `Props` has been renamed to `AttributesControlProps` for more explicit naming. - Removed the usage of `useState` and `useEffect` for selected attributes. Instead, `selectedAttributes` is now directly derived from `woocommerceAttributes`. - The CSS class `woocommerce-product-query-panel__external-link` was renamed to `wc-product-collection-panel__external-link` 3. Deleted the `product-collection/inspector-controls/constants.ts` file which was no longer necessary due to changes in product collection implementation. These changes contribute to codebase quality, improving readability and maintainability. * Address PR review comments This commit involves a significant refactoring of the default product query inside the 'product-collection/constants.ts' file. A new constant `DEFAULT_QUERY` has been defined and used to replace the previously hard-coded default query settings. This refactoring aids in code readability and future modifications. Changes also include adjustments in 'product-collection/inspector-controls' to enhance UI/UX. A new SCSS file 'editor.scss' has been created for custom styles related to the editor. Additions include: - Adding a class name `product-collection-inspector-toolspanel__filters` to ToolsPanel for additional styling. - The experimental property `__experimentalShowHowTo` is set to false for `FormTokenField` and `StockStatusControl`, to hide some additional information. In 'product-collection/inspector-controls/taxonomy-controls.tsx', the classname `product-collection-inspector__taxonomy-control` is added for improved CSS targeting. * Add wc-block-editor prefix to className * Add wc-block-editor- prefix with classNames * Handle duplicate taxonomy names in Taxonomy controls the taxonomy controls have been enhanced in the following ways: 1. Modified the BASE_QUERY object to include 'slug' in the '_fields' property. This will ensure that the 'slug' of the taxonomy term is fetched along with its 'id' and 'name'. 2. Added a 'slug' property to the Term type to store the 'slug' of each term. 3. Updated the useEffect hook inside the TaxonomyItem function to generate suggestions based on search results. The suggestions now include the 'slug' of a term if the term's name is not unique. This change will help users distinguish between terms with the same name but different slugs. * Remove isset() in if condition as it's unnecessary * Refactor TaxonomyItem component for better readability Following changes were made: 1. The useSelect hooks which were being used to fetch existing terms and search results have been moved into their own custom hooks named 'useExistingTerms' and 'useSearchResults' respectively. This simplifies the TaxonomyItem function's body and makes the hooks' purposes clearer. 2. The comments and props destructuring for the TaxonomyItem function have been moved up to make it easier to understand the function's purpose and the props it receives. 3. This refactor does not introduce any changes in functionality. It only changes how the code is organized and presented, which will make future development easier. * Handling for duplicate term names & other improvements This commit enhances the `TaxonomyControls` component within `product-collection` block by adding memoization and improving term uniqueness handling. Changes: 1. Imported `useMemo` from `@wordpress/element` for memoizing certain results. 2. `getTermIdByTermValue` function has been modified to use a `termIdToNameMap` (term ids as keys and term names as values). This provides a more efficient and direct mapping for term search. 3. Introduced `useTermIdToNameMap` function, which returns a `Map` where term ids are keys and term names are values. It handles duplicate term names by appending the term slug to the name, ensuring unique term names. 4. Updated the `useExistingTerms` and `useSearchResults` to include `taxonomy` in their dependency arrays for `useSelect` hook. This will force re-computation when `taxonomy` changes. 5. Changed `TaxonomyItem` from a function declaration to a const arrow function, consistent with the rest of the codebase. 6. Updated `onTermsChange` function in `TaxonomyItem` to accommodate the changes in `getTermIdByTermValue` and the introduction of `termIdToNameMap`. 7. Replaced `Set` with a standard array for storing new term IDs in `onTermsChange`. The `Set` was unnecessary as term IDs are unique by default. 8. Updated `TaxonomyItem`'s effects and rendering to work with `termIdToNameMap`, ensuring the displayed term names are unique. This update will result in more efficient term search and handling, and it will solve issues related to duplicate term names. * Restructure taxonomy controls in product collection block This commit restructures the taxonomy controls in the product collection block for improved clarity and maintainability. - The file `taxonomy-controls.tsx` has been deleted, and its functionality has been divided into two new files: `index.tsx` and `taxonomy-item.tsx`. - The `index.tsx` file contains the main TaxonomyControls component, which is responsible for displaying taxonomy-related options in the block's inspector controls. It includes a custom hook `useTaxonomies` that fetches and returns taxonomies associated with product post type. - The `taxonomy-item.tsx` file, on the other hand, contains a TaxonomyItem component that handles the rendering of individual taxonomy items. It also contains some utility functions for mapping term names and ids and fetching terms based on the search query. This refactor aims to improve code readability and separation of concerns, thus making future changes and maintenance easier. * Fix case insensitive search support for FormTokenField This change enhances the search functionality of the FormTokenField by introducing support for case insensitive search. This has been achieved by adding a lower-case version of the term name to the 'termNameToIdMap'. This is an important enhancement as it will make the search process more user-friendly and resilient to different casing inputs. Users will now be able to find the desired taxonomy term regardless of their input's case. * Refactor getTermIdByTermValue function and update newSuggestions mapping This commit does a couple of important things: 1. Reorders the definition of constants in `TaxonomyItemProps` for clarity. 2. Refactors the `getTermIdByTermValue` function. Instead of checking for an exact term name match in a convoluted manner, it now directly tries to fetch the `id` from the `searchTerm` if it is an object. If the `searchTerm` is not an object, the function tries to match it against the `termNameToIdMap` in both normal and lowercase forms. This simplification makes the function more readable and concise. 3. Updates the `newSuggestions` mapping in the `TaxonomyItem` component. It now has a fallback to `searchResult.name` if a term's name is not found in `termIdToNameMap`. This change ensures that even if the term's name is not in the map for some reason, we can still display a suggestion using the original name of the term. * Optimize term fetching and initial search state in TaxonomyItem This commit introduces a couple of improvements to the TaxonomyItem component. 1. The initial state of the 'search' state variable has been updated to 'undefined'. This change helps prevent unnecessary initial fetching of terms when the search input is empty. 2. Term fetching logic has been optimized to only enable term fetching when necessary: a) Fetching based on the search query is only enabled when 'search' is not 'undefined'. b) Fetching existing terms is only enabled when there are term IDs. 3. The block of code responsible for fetching existing terms and setting the current value has been moved upwards. This reordering of code does not change the functionality, but it groups together similar pieces of code, enhancing readability and maintainability. These optimizations make the component more efficient by reducing unnecessary requests and computations, and they improve the code organization. --------- Co-authored-by: Alexandre Lara <allexandrelara@gmail.com>
2023-06-02 10:01:29 +00:00
woocommerceOnSale: false,
woocommerceStockStatus: getDefaultStockStatuses(),
woocommerceAttributes: [],
Product Collection: Hand picked products control in sidebar settings (https://github.com/woocommerce/woocommerce-blocks/pull/9733) * Add support for hand-picked products in Product Collection block This commit introduces the ability to manually select specific products in the Product Collection block. Changes include: - Added `woocommerceHandPickedProducts` to the `ProductCollectionQuery` and `DEFAULT_FILTERS` in `constants.ts`. - Created a new control file `hand-picked-products-control.tsx` which introduces a token field where the user can search for and select specific products. - Included `HandPickedProductsControl` in the Product Collection block's inspector controls in `index.tsx`. - Updated `ProductCollectionQuery` in `types.ts` to accommodate handpicked products. - Updated the PHP `ProductCollection` class to handle the hand-picked products query parameters. These changes allow users to hand-pick products to be displayed in the Product Collection block. This allows for greater customization of the products shown in the block. * Enhance handling of hand-picked products - A Set data structure is now used to store 'newHandPickedProducts' instead of an Array, which will help prevent duplicate entries. - Additionally, the suggestions for products to be hand-picked now excludes already selected products, enhancing the user experience by avoiding redundancy in the suggestions list. - Lastly, the function name 'displayTransform' has been changed to 'transformTokenIntoProductName' to more accurately reflect its purpose, which is to transform a token into a product name. * Update import & export of HandPickedProductsControl
2023-06-08 06:03:01 +00:00
woocommerceHandPickedProducts: [],
Product Collection - Add `Created` filter in inspector controls (https://github.com/woocommerce/woocommerce-blocks/pull/11562) * Add time frame filter to Product Collection block This commit introduces the ability to filter products within the Product Collection block by a specified time frame. The changes include: - A new 'timeFrame' property added to the DEFAULT_QUERY constant in constants.ts, initialized as null, allowing for the storage of time frame data. - Creation of a new component `CreatedControl` in created-control.tsx that provides UI elements for selecting a time frame filter. - Inclusion of `CreatedControl` in the Product Collection Inspector Controls. - Expansion of the ProductCollectionQuery interface in types.ts to include a 'timeFrame' attribute. - Addition of the 'timeFrame' parameter handling within the ProductCollection PHP class to construct and execute the date query based on the provided time frame. The addition of the time frame filter offers enhanced flexibility in presenting products and allows users to dynamically segment their product lists based on product creation dates. * Refactor: Standardize 'timeFrame' to be 'undefined' instead of 'null' This commit includes a refactoring that changes the initialization and reset values for the `timeFrame` property from `null` to `undefined`. This standardization affects the constants, type definitions, and the handling of the `timeFrame` property in both the inspector controls and the PHP backend. * Switch date query to use post_date_gmt for DST consistency This commit changes the column reference in the date query from 'post_date' to 'post_date_gmt'. This update ensures that the product collection filtering is based on Coordinated Universal Time (UTC) rather than local time, which can be affected by Daylight Saving Time (DST) shifts. The modification will lead to more consistent and reliable behavior across different time zones and during DST changes. * Capitalize toggle group labels The following adjustments have been made: - Introduced a constant `uppercaseStyle` to store the `{ textTransform: 'uppercase' }` style. - Applied `uppercaseStyle` to both the 'IN' and 'NOT IN' toggle options to ensure label text is consistently uppercase. - Updated the 'Not in' label text to uppercase ('NOT IN') to match the newly applied style. These changes ensure that the toggle labels align with the design guidelines that call for uppercase styling in control elements. * Make first letter of first work capital * Rename to Within & Before * Update i18n for Product Collection query operators This commit updates the internationalization (i18n) for the Product Collection query operators in the 'Created' control component of the WooCommerce Blocks plugin. It replaces the '__' function with '_x' for translation and provides context comments for better translation handling. This improvement enhances the localization of the query operators for better multilingual support.
2023-11-08 09:02:49 +00:00
timeFrame: undefined,
Add price range filter to Product Collection block (#42858) * Add price range filter to Product Collection block This update introduces a price range filter feature to Product Collection. Changes include: 1. Constants Update: - Added `priceRange` as undefined in `DEFAULT_QUERY` and `DEFAULT_FILTERS` in `constants.ts`. 2. Style Adjustments: - Added CSS for `.wc-block-product-price-range-control` in `editor.scss` to align the input text to the end. 3. Component Integration: - In `inspector-controls/index.tsx`, the `PriceRangeControl` component is now imported and integrated. 4. New Components: - `PriceTextField.tsx` and `PriceRangeControl/index.tsx` have been created to handle price range inputs in the Product Collection block. 5. Backend Integration: - `PriceRange` interface added in `types.ts` for type support. - In `ProductCollection.php`, a filter (`add_price_range_filter`) is added to modify the main query based on the price range, including adjustments for tax considerations. Overall, this enhancement allows users to filter products within a specific price range. The backend adjustments ensure that the filtering respects tax settings and displays accurate prices. * Fix formatting * Fix: Price range filter not working on Editor * Improve: Share logic between Frontend & Editor * Add changelog * Add changefile(s) from automation for the following project(s): woocommerce-blocks, woocommerce * Remove duplicate changelog file * Enhanced Input Control for Price Fields Key changes include: 1. **Switch to Input Control**: Replaced the NumberControl component with the more versatile InputControl. This offers better handling of currency formatting and user input. 2. **Currency Formatting Logic**: Added robust logic for formatting numbers according to the currency settings. This includes handling thousand separators, decimal places, and currency symbols. 3. **String-to-Number Conversion**: Implemented a function to convert user-entered strings back to numbers, accounting for currency symbols and separators. This ensures accurate parsing of user input for processing. 4. **Input Handling Improvements**: Modified the onChange handlers for minimum and maximum price inputs. Now, they correctly handle edge cases like undefined or zero values, maintaining consistency in the user interface and data processing. * Refactor price range query handling 1. Introduction of a new method `get_price_range_query_args()` to encapsulate the logic for handling price range queries, especially for the two edge cases: - Prices excluding tax displayed including tax. - Prices including tax displayed excluding tax. 2. Removal of direct conditionals in the `get_query_results()` method, replacing them with a call to the new `get_price_range_query_args()` method. This makes the code more modular and easier to understand. This refactor enhances readability and maintainability of the code, ensuring that special cases in price range filtering are handled more effectively. * Remove unnecessary suffix prop * Refactor PriceTextField formatting logic for currency 1. Conditional application of thousand separators: The code now checks for the existence of `currency.thousandSeparator` before applying it. This prevents potential errors when the separator is undefined. 2. Simplified decimal separator handling: Introduced a fallback for the decimal separator, defaulting to a period ('.') if not specified by the currency settings. 3. Enhanced readability and documentation: Added comments to clarify the purpose of code blocks, especially where currency symbols are added or removed, and where value normalization occurs. 4. Function renaming for clarity: Renamed `formatValueWithCurrencySymbol` to `formatCurrency`, which better reflects its purpose. * Fix onBlur issue with PriceTextField component Refactored the PriceTextField component to utilize useState for better state management. This change introduces a local state variable, 'newValue', to store the current value. The state updates occur in the handleOnChange function, ensuring that the component's state is managed efficiently. Additionally, a new function, handleOnBlur, is implemented to handle the onBlur event, updating the component's state when focus is lost. The handleEnterKeyPress function captures the 'Enter' key press, providing a more user-friendly experience by allowing users to confirm their input with the Enter key. * Fix linting error --------- Co-authored-by: github-actions <github-actions@github.com>
2023-12-21 07:15:20 +00:00
priceRange: undefined,
Product Collection: Add Taxonomy filters to sidebar settings (https://github.com/woocommerce/woocommerce-blocks/pull/9634) * Add columns control to product collection block editor settings - `InspectorControls` from './inspector-controls' is now imported in `edit.tsx` and used in the returned JSX of `Edit` function. - A new file `columns-control.tsx` is added under 'product-collection' block's 'inspector-controls' directory which exports a `ColumnsControl` component. This component uses `RangeControl` from '@wordpress/components' to control the number of columns in the product collection display layout when the layout type is 'flex'. - The types file (`types.ts`) for 'product-collection' block is updated. The `Attributes` interface is renamed to `ProductCollectionAttributes` and the `ProductCollectionContext` interface is removed. The `ProductCollectionAttributes` now includes 'queryContext', 'templateSlug', and 'displayLayout' properties. * Refactor: Simplify Fallback Return in ColumnsControl Component This commit simplifies the fallback return value of the ColumnsControl component. Instead of returning an empty fragment (<> </>), it now returns null when the condition isn't met. This change improves readability and aligns with best practices for conditional rendering in React. * Feature: Add 'Order By' Control to Product Collection Inspector This commit adds a new 'Order By' control to the product collection inspector. The control allows users to specify the order of products in a collection by various attributes such as title and date. To support this, a new component 'OrderByControl' has been created and included in the product collection inspector. Additionally, the types for 'order' and 'orderBy' attributes have been updated and exported for reuse. * Add more options to OrderBy type * Add orderby handling on frontend & editor The main changes include: 1. Added a new property 'isProductCollectionBlock' in the block.json to denote if a block is a product collection block. 2. In the ProductCollection PHP class, a new initialization function has been defined to hook into the WordPress lifecycle, register the block, and update the query based on this block. 3. Added methods to manage query parameters for both frontend rendering and the Editor. 4. Expanded allowed 'collection_params' for the REST API to include custom 'orderby' values. 5. Defined a function to build the query based on block attributes, filters, and global WP_Query. 6. Created utility functions to handle complex query operations such as merging queries, handling custom sort values, and merging arrays recursively. These improvements allow for more flexible and robust handling of product collections in both the front-end display and the WordPress editor. It also extends support for custom 'orderby' values in the REST API, which allows for more advanced sorting options in product collections. * Add 'on sale' filter and enhance settings management in product collection block This commit introduces several changes to the product collection block. - First, it adds a new 'on sale' filter that can be used to display only the products that are currently on sale. - It also refactors the settings management in the product collection block to use the experimental ToolsPanel component from WordPress, which provides a more flexible and intuitive way to manage block settings. - It moves the 'Columns' control into the ToolsPanel, along with the 'Order by' control. - A new utility function `setQueryAttribute` is introduced to simplify setting nested query parameters. - The structure of the `ProductCollectionAttributes` and `ProductCollectionQuery` types have been adjusted to accommodate the changes. - Finally, it makes corresponding changes in the PHP part to handle the new 'on sale' query parameter. This should enhance the flexibility and user-friendliness of the product collection block. * Add stock status filter to WooCommerce product collection block This commit introduces a stock status filter to the WooCommerce product collection block. The changes include: 1. Added the ability to filter products based on their stock status within the 'product-collection' block. A new stock status control is created within the inspector-controls of the block. 2. A new 'get_stock_status_query' function is introduced in 'ProductCollection.php' which returns a query for products depending on their stock status. Please note that the stock status filter will only appear in the experimental build for now. * Refactor Stock Status control of Product Collection block This commit refactors the Stock Status control. The changes aim to improve the code organization and make the behavior of the component more explicit. The key modifications are: 1. Moved stock status related constants and functions from `inspector-controls/utils.tsx` to `inspector-controls/constants.ts`. This is done to ensure that all constants and similar utility functions are organized in one place. 2. Updated `product-collection/index.tsx` to import `getDefaultStockStatuses` from `inspector-controls/constants` instead of `inspector-controls/utils`. 3. Updated `stock-status-control.tsx` to determine whether the stock status has value or not by comparing with the default stock statuses using `fastDeepEqual`. If the stock status control is deselected, it resets the stock status to the default statuses. These changes do not introduce any new functionalities, but improve the readability and maintainability of the code. * Add keyword search control to Product Collection block This commit introduces a keyword search functionality to the Product Collection block. The update is aimed to provide users with more flexibility and precision in product collection queries. Key changes: 1. Introduced a new file `keyword-control.tsx` that creates a Keyword Control component. This component includes a TextControl field that allows inputting a search keyword. The keyword search is debounced to prevent unnecessary queries during input and updates the block's attributes accordingly. 2. Modified `inspector-controls/index.tsx` to include the KeywordControl in the ToolsPanel for the block's filters. 3. Adjusted `ProductCollection.php` to include the keyword search in the product query array. With these changes, users can now search for products by keyword in the Product Collection block. * Add product attributes filter control to ProductCollection block - This commit introduces the ability to filter products by attributes in ProductCollection block. - A new `woocommerceAttributes` key was added to the `block.json` file and the `ProductCollectionQuery` type. Also, a new file `attributes-control.tsx` was created, providing the UI component for the attribute filter control in the editor. - In addition, updates were made to the `ProductCollection.php` file in the backend to support filtering products by attributes, and the tax query was updated to include attribute queries. - Lastly, the `ProductCollectionInspectorControls` was updated to include the `AttributesControl` component, thus enabling users to filter products by attributes in the block editor."` * remove unused import of getDefaultStockStatuses * Delete a duplicate file * Remove console log * Add taxonomies control to Product collection block The primary changes include: 1. `taxQuery` field in the `ProductCollectionAttributes` was changed from a string to an object in `assets/js/blocks/product-collection/types.ts` and `assets/js/blocks/product-collection/constants.ts`, accommodating the ability to query products by taxonomy terms. 2. `assets/js/blocks/product-collection/inspector-controls/utils.tsx` was moved to `assets/js/blocks/product-collection/utils.tsx` to make it available for broader use. 3. New component `TaxonomyControls` was created in `assets/js/blocks/product-collection/inspector-controls/taxonomy-controls.tsx`, which is included in `assets/js/blocks/product-collection/inspector-controls/index.tsx`. This new control allows users to filter products in the block by their taxonomy terms. 4. Updated the block's inspector controls in `assets/js/blocks/product-collection/inspector-controls/index.tsx` to use the new `TaxonomyControls` component. Please note that the TaxonomyControls component uses experimental features of WordPress's FormTokenField. As a result, a comment has been added to disable eslint warnings regarding the use of experimental APIs. * Address PR feedback & other improvements 1. Added `woocommerceAttributes` to `DEFAULT_FILTERS` in the `product-collection/constants.ts` file to fix `reset all` button issue. 2. Refactored `attributes-control.tsx` to make it more maintainable: - The constant `EDIT_ATTRIBUTES_URL` now uses `ADMIN_URL` from `@woocommerce/settings` for a more dynamic URL generation. - The interface `Props` has been renamed to `AttributesControlProps` for more explicit naming. - Removed the usage of `useState` and `useEffect` for selected attributes. Instead, `selectedAttributes` is now directly derived from `woocommerceAttributes`. - The CSS class `woocommerce-product-query-panel__external-link` was renamed to `wc-product-collection-panel__external-link` 3. Deleted the `product-collection/inspector-controls/constants.ts` file which was no longer necessary due to changes in product collection implementation. These changes contribute to codebase quality, improving readability and maintainability. * Address PR review comments This commit involves a significant refactoring of the default product query inside the 'product-collection/constants.ts' file. A new constant `DEFAULT_QUERY` has been defined and used to replace the previously hard-coded default query settings. This refactoring aids in code readability and future modifications. Changes also include adjustments in 'product-collection/inspector-controls' to enhance UI/UX. A new SCSS file 'editor.scss' has been created for custom styles related to the editor. Additions include: - Adding a class name `product-collection-inspector-toolspanel__filters` to ToolsPanel for additional styling. - The experimental property `__experimentalShowHowTo` is set to false for `FormTokenField` and `StockStatusControl`, to hide some additional information. In 'product-collection/inspector-controls/taxonomy-controls.tsx', the classname `product-collection-inspector__taxonomy-control` is added for improved CSS targeting. * Add wc-block-editor prefix to className * Add wc-block-editor- prefix with classNames * Handle duplicate taxonomy names in Taxonomy controls the taxonomy controls have been enhanced in the following ways: 1. Modified the BASE_QUERY object to include 'slug' in the '_fields' property. This will ensure that the 'slug' of the taxonomy term is fetched along with its 'id' and 'name'. 2. Added a 'slug' property to the Term type to store the 'slug' of each term. 3. Updated the useEffect hook inside the TaxonomyItem function to generate suggestions based on search results. The suggestions now include the 'slug' of a term if the term's name is not unique. This change will help users distinguish between terms with the same name but different slugs. * Remove isset() in if condition as it's unnecessary * Refactor TaxonomyItem component for better readability Following changes were made: 1. The useSelect hooks which were being used to fetch existing terms and search results have been moved into their own custom hooks named 'useExistingTerms' and 'useSearchResults' respectively. This simplifies the TaxonomyItem function's body and makes the hooks' purposes clearer. 2. The comments and props destructuring for the TaxonomyItem function have been moved up to make it easier to understand the function's purpose and the props it receives. 3. This refactor does not introduce any changes in functionality. It only changes how the code is organized and presented, which will make future development easier. * Handling for duplicate term names & other improvements This commit enhances the `TaxonomyControls` component within `product-collection` block by adding memoization and improving term uniqueness handling. Changes: 1. Imported `useMemo` from `@wordpress/element` for memoizing certain results. 2. `getTermIdByTermValue` function has been modified to use a `termIdToNameMap` (term ids as keys and term names as values). This provides a more efficient and direct mapping for term search. 3. Introduced `useTermIdToNameMap` function, which returns a `Map` where term ids are keys and term names are values. It handles duplicate term names by appending the term slug to the name, ensuring unique term names. 4. Updated the `useExistingTerms` and `useSearchResults` to include `taxonomy` in their dependency arrays for `useSelect` hook. This will force re-computation when `taxonomy` changes. 5. Changed `TaxonomyItem` from a function declaration to a const arrow function, consistent with the rest of the codebase. 6. Updated `onTermsChange` function in `TaxonomyItem` to accommodate the changes in `getTermIdByTermValue` and the introduction of `termIdToNameMap`. 7. Replaced `Set` with a standard array for storing new term IDs in `onTermsChange`. The `Set` was unnecessary as term IDs are unique by default. 8. Updated `TaxonomyItem`'s effects and rendering to work with `termIdToNameMap`, ensuring the displayed term names are unique. This update will result in more efficient term search and handling, and it will solve issues related to duplicate term names. * Restructure taxonomy controls in product collection block This commit restructures the taxonomy controls in the product collection block for improved clarity and maintainability. - The file `taxonomy-controls.tsx` has been deleted, and its functionality has been divided into two new files: `index.tsx` and `taxonomy-item.tsx`. - The `index.tsx` file contains the main TaxonomyControls component, which is responsible for displaying taxonomy-related options in the block's inspector controls. It includes a custom hook `useTaxonomies` that fetches and returns taxonomies associated with product post type. - The `taxonomy-item.tsx` file, on the other hand, contains a TaxonomyItem component that handles the rendering of individual taxonomy items. It also contains some utility functions for mapping term names and ids and fetching terms based on the search query. This refactor aims to improve code readability and separation of concerns, thus making future changes and maintenance easier. * Fix case insensitive search support for FormTokenField This change enhances the search functionality of the FormTokenField by introducing support for case insensitive search. This has been achieved by adding a lower-case version of the term name to the 'termNameToIdMap'. This is an important enhancement as it will make the search process more user-friendly and resilient to different casing inputs. Users will now be able to find the desired taxonomy term regardless of their input's case. * Refactor getTermIdByTermValue function and update newSuggestions mapping This commit does a couple of important things: 1. Reorders the definition of constants in `TaxonomyItemProps` for clarity. 2. Refactors the `getTermIdByTermValue` function. Instead of checking for an exact term name match in a convoluted manner, it now directly tries to fetch the `id` from the `searchTerm` if it is an object. If the `searchTerm` is not an object, the function tries to match it against the `termNameToIdMap` in both normal and lowercase forms. This simplification makes the function more readable and concise. 3. Updates the `newSuggestions` mapping in the `TaxonomyItem` component. It now has a fallback to `searchResult.name` if a term's name is not found in `termIdToNameMap`. This change ensures that even if the term's name is not in the map for some reason, we can still display a suggestion using the original name of the term. * Optimize term fetching and initial search state in TaxonomyItem This commit introduces a couple of improvements to the TaxonomyItem component. 1. The initial state of the 'search' state variable has been updated to 'undefined'. This change helps prevent unnecessary initial fetching of terms when the search input is empty. 2. Term fetching logic has been optimized to only enable term fetching when necessary: a) Fetching based on the search query is only enabled when 'search' is not 'undefined'. b) Fetching existing terms is only enabled when there are term IDs. 3. The block of code responsible for fetching existing terms and setting the current value has been moved upwards. This reordering of code does not change the functionality, but it groups together similar pieces of code, enhancing readability and maintainability. These optimizations make the component more efficient by reducing unnecessary requests and computations, and they improve the code organization. --------- Co-authored-by: Alexandre Lara <allexandrelara@gmail.com>
2023-06-02 10:01:29 +00:00
};
Product Collection: Implement Preview Mode (#46369) * POC: Preview Mode using HOC * Add explanation as comments POC: Implement preview mode for Product Collection block in editor - Added extensive commentary to clarify the mechanism and usage of the `handlePreviewState` function - Implemented an internal state within `ProductCollectionContent` to manage preview status and messages, serving as a foundational example of how preview mode can enrich block functionality. - Showcased the application of `handlePreviewState` by incorporating it as a prop in `BlockEdit`, illustrating the potential for extending the block's capabilities for dynamic and interactive previews. This POC demonstrates a flexible approach to managing preview states within the editor, paving the way for further development and integration based on feedback and use-case analysis. * Refactor preview state handling and collection registration This commit introduces a centralized approach for registering product collection variations and managing their preview states. It abstracts the registration logic into a dedicated function and enhances the flexibility of preview state handling across different collection types. * Rename file * Minor improvements * Don't pass previewState to handlePreviewState I don't see any good use of it in handlePreviewState. Also, We will be going to call handlePreviewState only once therefore, it will always have the same value as the initial value of the previewState. If in future, we decide to run it multiple times then we can pass the previewState as an argument to handlePreviewState. * Add comment * Use JS closure to inject handlePreviewState This commit introduces a refined approach for injecting the `handlePreviewState` function into product collection blocks, utilizing JavaScript closures to streamline the process. This method replaces the previous global registry mechanism, offering a more direct and efficient way to manage preview states. Advantages of This Approach: - Utilizing JavaScript closures for injecting `handlePreviewState` simplifies the overall architecture by directly modifying block edit components without relying on an external registry. This method enhances code clarity and reduces the cognitive load for developers. - The conditional application of `withHandlePreviewState` ensures that the preview state handling logic is only added to blocks that require it, optimizing performance and maintainability. * Refactor preview state management into custom hook This commit enhances the organization and readability of the product collection content component by abstracting the preview state management into a custom hook named `usePreviewState`. This change streamlines the component's structure and aligns with React best practices for managing state and side effects. Key Changes: - Introduced `usePreviewState`, a custom hook responsible for initializing and managing the preview state (`isPreview` and `previewMessage`) of the product collection block. This hook encapsulates the state logic and its side effects, including the conditional invocation of `handlePreviewState`. - Modified `ProductCollectionContent` to utilize `usePreviewState` for handling its preview state. This adjustment makes the component cleaner and focuses it more on presentation and behavior rather than state management details. * Replace useEffect with useLayoutEffect * Add cleanup function in handlePreviewState function Based on [this discussion](https://github.com/woocommerce/woocommerce/pull/45703#discussion_r1535323883), I added a cleanup function support for handlePreviewState. `handlePreviewState` can return a function which will be called on cleanup in `useLayoutEffect` hook. * Fetching random products in Preview mode * Allow collection to set initial preview state * Pass location & all attributes to handlePreviewState function * Handling collection specific query for preview mode - Consolidated `handlePreviewState` and `initialPreviewState` into a single `preview` prop in `register-product-collection.tsx` and `product-collection-content.tsx` to streamline prop passing and improve the component interface. - Updated the `queryContextIncludes` in `constants.ts` to include 'previewState' - Enhanced the `ProductCollection` PHP class to handle preview-specific queries more effectively, introducing a new method `get_preview_query_args` that adjusts query parameters based on the collection being previewed, thereby improving the relevance and accuracy of products displayed in preview mode. * Always set initialPreviewState on load * Refine preview state handling - Renamed `HandlePreviewStateArgs` to `SetPreviewStateArgs` in `featured.tsx` to better reflect its purpose, which is now more focused on setting rather than handling states. The implementation details within `featured.tsx` have also been refined to include async operations and cleanup functions, demonstrating a more sophisticated approach to managing state. Overall, these updates make the preview state logic more understandable and maintainable. * Rename "initialState" to "initialPreviewState" * Fix: Correct merging of newPreviewState into previewState attribute This commit addresses an issue in the product-collection-content.tsx where the newPreviewState was not properly merged into the existing previewState attribute. Previously, the spread operator was incorrectly applied, leading to potential loss of existing state attributes. By changing the order of operations and correctly spreading the existing attributes before merging the newPreviewState, we ensure that all state attributes are preserved and updated correctly. * Initial refactor POC code to productionize it * Move `useSetPreviewState` to Utils * Implement preview mode for Generic archive templates Implemented a new useLayoutEffect in `utils.tsx` to dynamically set a preview message in the editor for product collection blocks located in generic archive templates (like Products by Category, Products by Tag, or Products by Attribute). * Remove preview mode from Featured and On sale collection * Remove preview query modfication for On Sale collection * Add changefile(s) from automation for the following project(s): woocommerce-blocks, woocommerce * Fix: hide/show preview label based on value of "inherit" If user change the toggle "Sync with current query", then it should reflect for the preview label as well. - If the toggle is on, then the preview label should be shown. - If the toggle is off, then the preview label should be hidden. * Minor improvements * Add changefile(s) from automation for the following project(s): woocommerce-blocks, woocommerce * Add changefile(s) from automation for the following project(s): woocommerce-blocks, woocommerce * Refactor: Simplify SetPreviewState type definition in types.ts This commit refines the SetPreviewState type definition by eliminating the previously used intermediate interface, SetPreviewStateArgs. The change streamlines the type definition directly within the SetPreviewState type, enhancing readability and reducing redundancy. * Update import syntax for ElementType in register-product-collection.tsx This commit updates the import statement for `ElementType` from `@wordpress/element` to use the more modern and concise `import type` syntax. This change does not affect functionality but aligns with TypeScript best practices for importing types, ensuring that type imports are distinguished from regular imports. This helps in clarity and in optimizing the build process by explicitly indicating that `ElementType` is used solely for type checking and not included in the JavaScript runtime. * Refactor: Update TypeScript usage in Product Collection This commit introduces several TypeScript refinements across product-collection components: 1. **DEFAULT_ATTRIBUTES** in `constants.ts` now uses `Pick` to explicitly define its shape, ensuring only relevant attributes are included and typed accurately. 2. **ProductCollectionAdvancedInspectorControls** and **ToolbarControls** in the `edit` subdirectory now use `Omit` to exclude the 'preview' property from props, clarifying the intended prop usage and improving type safety. These changes collectively tighten the type definitions and improve the codebase's adherence to best practices in TypeScript. * Refactor: Update dependencies of useSetPreviewState hook in utils.tsx This change enhances the stability and predictability of the hook's behavior, ensuring it updates its internal state accurately when its dependencies change, thus aligning with best practices in React development. * Refactor preview button CSS and conditional rendering 1. **CSS Refactoring:** Moved the positioning styles of the `.wc-block-product-collection__preview-button` from inline styles in the JSX to the `editor.scss` file. This separation of concerns improves maintainability and readability, aligning the styling responsibilities solely within the CSS file. 2. **Conditional Rendering Logic:** Updated the rendering condition for the preview button. Now, it not only checks if `isPreview` is true but also if the block is currently selected (`props.isSelected`). This prevents the preview button from appearing when the block is not actively selected, reducing visual clutter and enhancing the user experience in the editor. * Enhance: Update preview button visibility logic in ProductCollectionContent This commit enhances the visibility logic of the preview button in the `ProductCollectionContent` component: 1. **Added `isSelectedOrInnerBlockSelected`:** Introduced a new `useSelect` hook to determine if the current block or any of its inner blocks are selected. This ensures that the preview button is visible when either the product collection block or any of its inner blocks are selected. 2. **Updated Conditional Rendering:** Adjusted the conditional rendering of the preview button to use the new `isSelectedOrInnerBlockSelected` value, providing a more intuitive user experience by ensuring the preview button remains visible when any relevant block is selected. * use __private prefix with attribute name * Add E2E tests for Preview Mode 1. **Template-Specific Tests:** Each template (tag, category, attribute) undergoes a test to ensure the preview button behaves as expected when replacing products with product collections in these contexts. 2. **Visibility Checks:** The tests verify that the preview button is visible when the block or its inner blocks are selected and hidden when the block is not selected. This helps confirm the correct implementation of the preview button visibility logic across different use cases. 3. **Interaction with Inner Blocks:** Additional checks are included to ensure the preview button's visibility toggles appropriately when interacting with inner blocks, reinforcing the dynamic nature of block selection and its effect on UI elements within the editor. * Add setPreviewState to dependencies * Add data-test-id to Preview button and update e2e locator Modifications: - Added `data-test-id="product-collection-preview-button"` to the Preview button in `product-collection-content.tsx`. - Updated the corresponding e2e test locator in `product-collection.block_theme.side_effects.spec.ts` to use the new `data-test-id` instead of the class name. By using `data-test-id`, we ensure that the e2e tests are not affected by changes in the styling or restructuring of the DOM that might alter CSS classes but do not affect functionality. * Enhance: Localize preview message in useSetPreviewState hook * Don't show shadow & outline on focus * Make preview button font same as Admin * Fix SCSS lint errors * Add missing await keyword --------- Co-authored-by: github-actions <github-actions@github.com>
2024-05-15 07:48:43 +00:00
export const DEFAULT_ATTRIBUTES: Pick<
ProductCollectionAttributes,
| 'query'
| 'tagName'
| 'displayLayout'
| 'queryContextIncludes'
| 'forcePageReload'
> = {
Product Collection: Add Taxonomy filters to sidebar settings (https://github.com/woocommerce/woocommerce-blocks/pull/9634) * Add columns control to product collection block editor settings - `InspectorControls` from './inspector-controls' is now imported in `edit.tsx` and used in the returned JSX of `Edit` function. - A new file `columns-control.tsx` is added under 'product-collection' block's 'inspector-controls' directory which exports a `ColumnsControl` component. This component uses `RangeControl` from '@wordpress/components' to control the number of columns in the product collection display layout when the layout type is 'flex'. - The types file (`types.ts`) for 'product-collection' block is updated. The `Attributes` interface is renamed to `ProductCollectionAttributes` and the `ProductCollectionContext` interface is removed. The `ProductCollectionAttributes` now includes 'queryContext', 'templateSlug', and 'displayLayout' properties. * Refactor: Simplify Fallback Return in ColumnsControl Component This commit simplifies the fallback return value of the ColumnsControl component. Instead of returning an empty fragment (<> </>), it now returns null when the condition isn't met. This change improves readability and aligns with best practices for conditional rendering in React. * Feature: Add 'Order By' Control to Product Collection Inspector This commit adds a new 'Order By' control to the product collection inspector. The control allows users to specify the order of products in a collection by various attributes such as title and date. To support this, a new component 'OrderByControl' has been created and included in the product collection inspector. Additionally, the types for 'order' and 'orderBy' attributes have been updated and exported for reuse. * Add more options to OrderBy type * Add orderby handling on frontend & editor The main changes include: 1. Added a new property 'isProductCollectionBlock' in the block.json to denote if a block is a product collection block. 2. In the ProductCollection PHP class, a new initialization function has been defined to hook into the WordPress lifecycle, register the block, and update the query based on this block. 3. Added methods to manage query parameters for both frontend rendering and the Editor. 4. Expanded allowed 'collection_params' for the REST API to include custom 'orderby' values. 5. Defined a function to build the query based on block attributes, filters, and global WP_Query. 6. Created utility functions to handle complex query operations such as merging queries, handling custom sort values, and merging arrays recursively. These improvements allow for more flexible and robust handling of product collections in both the front-end display and the WordPress editor. It also extends support for custom 'orderby' values in the REST API, which allows for more advanced sorting options in product collections. * Add 'on sale' filter and enhance settings management in product collection block This commit introduces several changes to the product collection block. - First, it adds a new 'on sale' filter that can be used to display only the products that are currently on sale. - It also refactors the settings management in the product collection block to use the experimental ToolsPanel component from WordPress, which provides a more flexible and intuitive way to manage block settings. - It moves the 'Columns' control into the ToolsPanel, along with the 'Order by' control. - A new utility function `setQueryAttribute` is introduced to simplify setting nested query parameters. - The structure of the `ProductCollectionAttributes` and `ProductCollectionQuery` types have been adjusted to accommodate the changes. - Finally, it makes corresponding changes in the PHP part to handle the new 'on sale' query parameter. This should enhance the flexibility and user-friendliness of the product collection block. * Add stock status filter to WooCommerce product collection block This commit introduces a stock status filter to the WooCommerce product collection block. The changes include: 1. Added the ability to filter products based on their stock status within the 'product-collection' block. A new stock status control is created within the inspector-controls of the block. 2. A new 'get_stock_status_query' function is introduced in 'ProductCollection.php' which returns a query for products depending on their stock status. Please note that the stock status filter will only appear in the experimental build for now. * Refactor Stock Status control of Product Collection block This commit refactors the Stock Status control. The changes aim to improve the code organization and make the behavior of the component more explicit. The key modifications are: 1. Moved stock status related constants and functions from `inspector-controls/utils.tsx` to `inspector-controls/constants.ts`. This is done to ensure that all constants and similar utility functions are organized in one place. 2. Updated `product-collection/index.tsx` to import `getDefaultStockStatuses` from `inspector-controls/constants` instead of `inspector-controls/utils`. 3. Updated `stock-status-control.tsx` to determine whether the stock status has value or not by comparing with the default stock statuses using `fastDeepEqual`. If the stock status control is deselected, it resets the stock status to the default statuses. These changes do not introduce any new functionalities, but improve the readability and maintainability of the code. * Add keyword search control to Product Collection block This commit introduces a keyword search functionality to the Product Collection block. The update is aimed to provide users with more flexibility and precision in product collection queries. Key changes: 1. Introduced a new file `keyword-control.tsx` that creates a Keyword Control component. This component includes a TextControl field that allows inputting a search keyword. The keyword search is debounced to prevent unnecessary queries during input and updates the block's attributes accordingly. 2. Modified `inspector-controls/index.tsx` to include the KeywordControl in the ToolsPanel for the block's filters. 3. Adjusted `ProductCollection.php` to include the keyword search in the product query array. With these changes, users can now search for products by keyword in the Product Collection block. * Add product attributes filter control to ProductCollection block - This commit introduces the ability to filter products by attributes in ProductCollection block. - A new `woocommerceAttributes` key was added to the `block.json` file and the `ProductCollectionQuery` type. Also, a new file `attributes-control.tsx` was created, providing the UI component for the attribute filter control in the editor. - In addition, updates were made to the `ProductCollection.php` file in the backend to support filtering products by attributes, and the tax query was updated to include attribute queries. - Lastly, the `ProductCollectionInspectorControls` was updated to include the `AttributesControl` component, thus enabling users to filter products by attributes in the block editor."` * remove unused import of getDefaultStockStatuses * Delete a duplicate file * Remove console log * Add taxonomies control to Product collection block The primary changes include: 1. `taxQuery` field in the `ProductCollectionAttributes` was changed from a string to an object in `assets/js/blocks/product-collection/types.ts` and `assets/js/blocks/product-collection/constants.ts`, accommodating the ability to query products by taxonomy terms. 2. `assets/js/blocks/product-collection/inspector-controls/utils.tsx` was moved to `assets/js/blocks/product-collection/utils.tsx` to make it available for broader use. 3. New component `TaxonomyControls` was created in `assets/js/blocks/product-collection/inspector-controls/taxonomy-controls.tsx`, which is included in `assets/js/blocks/product-collection/inspector-controls/index.tsx`. This new control allows users to filter products in the block by their taxonomy terms. 4. Updated the block's inspector controls in `assets/js/blocks/product-collection/inspector-controls/index.tsx` to use the new `TaxonomyControls` component. Please note that the TaxonomyControls component uses experimental features of WordPress's FormTokenField. As a result, a comment has been added to disable eslint warnings regarding the use of experimental APIs. * Address PR feedback & other improvements 1. Added `woocommerceAttributes` to `DEFAULT_FILTERS` in the `product-collection/constants.ts` file to fix `reset all` button issue. 2. Refactored `attributes-control.tsx` to make it more maintainable: - The constant `EDIT_ATTRIBUTES_URL` now uses `ADMIN_URL` from `@woocommerce/settings` for a more dynamic URL generation. - The interface `Props` has been renamed to `AttributesControlProps` for more explicit naming. - Removed the usage of `useState` and `useEffect` for selected attributes. Instead, `selectedAttributes` is now directly derived from `woocommerceAttributes`. - The CSS class `woocommerce-product-query-panel__external-link` was renamed to `wc-product-collection-panel__external-link` 3. Deleted the `product-collection/inspector-controls/constants.ts` file which was no longer necessary due to changes in product collection implementation. These changes contribute to codebase quality, improving readability and maintainability. * Address PR review comments This commit involves a significant refactoring of the default product query inside the 'product-collection/constants.ts' file. A new constant `DEFAULT_QUERY` has been defined and used to replace the previously hard-coded default query settings. This refactoring aids in code readability and future modifications. Changes also include adjustments in 'product-collection/inspector-controls' to enhance UI/UX. A new SCSS file 'editor.scss' has been created for custom styles related to the editor. Additions include: - Adding a class name `product-collection-inspector-toolspanel__filters` to ToolsPanel for additional styling. - The experimental property `__experimentalShowHowTo` is set to false for `FormTokenField` and `StockStatusControl`, to hide some additional information. In 'product-collection/inspector-controls/taxonomy-controls.tsx', the classname `product-collection-inspector__taxonomy-control` is added for improved CSS targeting. * Add wc-block-editor prefix to className * Add wc-block-editor- prefix with classNames * Handle duplicate taxonomy names in Taxonomy controls the taxonomy controls have been enhanced in the following ways: 1. Modified the BASE_QUERY object to include 'slug' in the '_fields' property. This will ensure that the 'slug' of the taxonomy term is fetched along with its 'id' and 'name'. 2. Added a 'slug' property to the Term type to store the 'slug' of each term. 3. Updated the useEffect hook inside the TaxonomyItem function to generate suggestions based on search results. The suggestions now include the 'slug' of a term if the term's name is not unique. This change will help users distinguish between terms with the same name but different slugs. * Remove isset() in if condition as it's unnecessary * Refactor TaxonomyItem component for better readability Following changes were made: 1. The useSelect hooks which were being used to fetch existing terms and search results have been moved into their own custom hooks named 'useExistingTerms' and 'useSearchResults' respectively. This simplifies the TaxonomyItem function's body and makes the hooks' purposes clearer. 2. The comments and props destructuring for the TaxonomyItem function have been moved up to make it easier to understand the function's purpose and the props it receives. 3. This refactor does not introduce any changes in functionality. It only changes how the code is organized and presented, which will make future development easier. * Handling for duplicate term names & other improvements This commit enhances the `TaxonomyControls` component within `product-collection` block by adding memoization and improving term uniqueness handling. Changes: 1. Imported `useMemo` from `@wordpress/element` for memoizing certain results. 2. `getTermIdByTermValue` function has been modified to use a `termIdToNameMap` (term ids as keys and term names as values). This provides a more efficient and direct mapping for term search. 3. Introduced `useTermIdToNameMap` function, which returns a `Map` where term ids are keys and term names are values. It handles duplicate term names by appending the term slug to the name, ensuring unique term names. 4. Updated the `useExistingTerms` and `useSearchResults` to include `taxonomy` in their dependency arrays for `useSelect` hook. This will force re-computation when `taxonomy` changes. 5. Changed `TaxonomyItem` from a function declaration to a const arrow function, consistent with the rest of the codebase. 6. Updated `onTermsChange` function in `TaxonomyItem` to accommodate the changes in `getTermIdByTermValue` and the introduction of `termIdToNameMap`. 7. Replaced `Set` with a standard array for storing new term IDs in `onTermsChange`. The `Set` was unnecessary as term IDs are unique by default. 8. Updated `TaxonomyItem`'s effects and rendering to work with `termIdToNameMap`, ensuring the displayed term names are unique. This update will result in more efficient term search and handling, and it will solve issues related to duplicate term names. * Restructure taxonomy controls in product collection block This commit restructures the taxonomy controls in the product collection block for improved clarity and maintainability. - The file `taxonomy-controls.tsx` has been deleted, and its functionality has been divided into two new files: `index.tsx` and `taxonomy-item.tsx`. - The `index.tsx` file contains the main TaxonomyControls component, which is responsible for displaying taxonomy-related options in the block's inspector controls. It includes a custom hook `useTaxonomies` that fetches and returns taxonomies associated with product post type. - The `taxonomy-item.tsx` file, on the other hand, contains a TaxonomyItem component that handles the rendering of individual taxonomy items. It also contains some utility functions for mapping term names and ids and fetching terms based on the search query. This refactor aims to improve code readability and separation of concerns, thus making future changes and maintenance easier. * Fix case insensitive search support for FormTokenField This change enhances the search functionality of the FormTokenField by introducing support for case insensitive search. This has been achieved by adding a lower-case version of the term name to the 'termNameToIdMap'. This is an important enhancement as it will make the search process more user-friendly and resilient to different casing inputs. Users will now be able to find the desired taxonomy term regardless of their input's case. * Refactor getTermIdByTermValue function and update newSuggestions mapping This commit does a couple of important things: 1. Reorders the definition of constants in `TaxonomyItemProps` for clarity. 2. Refactors the `getTermIdByTermValue` function. Instead of checking for an exact term name match in a convoluted manner, it now directly tries to fetch the `id` from the `searchTerm` if it is an object. If the `searchTerm` is not an object, the function tries to match it against the `termNameToIdMap` in both normal and lowercase forms. This simplification makes the function more readable and concise. 3. Updates the `newSuggestions` mapping in the `TaxonomyItem` component. It now has a fallback to `searchResult.name` if a term's name is not found in `termIdToNameMap`. This change ensures that even if the term's name is not in the map for some reason, we can still display a suggestion using the original name of the term. * Optimize term fetching and initial search state in TaxonomyItem This commit introduces a couple of improvements to the TaxonomyItem component. 1. The initial state of the 'search' state variable has been updated to 'undefined'. This change helps prevent unnecessary initial fetching of terms when the search input is empty. 2. Term fetching logic has been optimized to only enable term fetching when necessary: a) Fetching based on the search query is only enabled when 'search' is not 'undefined'. b) Fetching existing terms is only enabled when there are term IDs. 3. The block of code responsible for fetching existing terms and setting the current value has been moved upwards. This reordering of code does not change the functionality, but it groups together similar pieces of code, enhancing readability and maintainability. These optimizations make the component more efficient by reducing unnecessary requests and computations, and they improve the code organization. --------- Co-authored-by: Alexandre Lara <allexandrelara@gmail.com>
2023-06-02 10:01:29 +00:00
query: DEFAULT_QUERY,
Product Collection: Add stock status filter (https://github.com/woocommerce/woocommerce-blocks/pull/9580) * Add columns control to product collection block editor settings - `InspectorControls` from './inspector-controls' is now imported in `edit.tsx` and used in the returned JSX of `Edit` function. - A new file `columns-control.tsx` is added under 'product-collection' block's 'inspector-controls' directory which exports a `ColumnsControl` component. This component uses `RangeControl` from '@wordpress/components' to control the number of columns in the product collection display layout when the layout type is 'flex'. - The types file (`types.ts`) for 'product-collection' block is updated. The `Attributes` interface is renamed to `ProductCollectionAttributes` and the `ProductCollectionContext` interface is removed. The `ProductCollectionAttributes` now includes 'queryContext', 'templateSlug', and 'displayLayout' properties. * Refactor: Simplify Fallback Return in ColumnsControl Component This commit simplifies the fallback return value of the ColumnsControl component. Instead of returning an empty fragment (<> </>), it now returns null when the condition isn't met. This change improves readability and aligns with best practices for conditional rendering in React. * Feature: Add 'Order By' Control to Product Collection Inspector This commit adds a new 'Order By' control to the product collection inspector. The control allows users to specify the order of products in a collection by various attributes such as title and date. To support this, a new component 'OrderByControl' has been created and included in the product collection inspector. Additionally, the types for 'order' and 'orderBy' attributes have been updated and exported for reuse. * Add more options to OrderBy type * Add orderby handling on frontend & editor The main changes include: 1. Added a new property 'isProductCollectionBlock' in the block.json to denote if a block is a product collection block. 2. In the ProductCollection PHP class, a new initialization function has been defined to hook into the WordPress lifecycle, register the block, and update the query based on this block. 3. Added methods to manage query parameters for both frontend rendering and the Editor. 4. Expanded allowed 'collection_params' for the REST API to include custom 'orderby' values. 5. Defined a function to build the query based on block attributes, filters, and global WP_Query. 6. Created utility functions to handle complex query operations such as merging queries, handling custom sort values, and merging arrays recursively. These improvements allow for more flexible and robust handling of product collections in both the front-end display and the WordPress editor. It also extends support for custom 'orderby' values in the REST API, which allows for more advanced sorting options in product collections. * Add 'on sale' filter and enhance settings management in product collection block This commit introduces several changes to the product collection block. - First, it adds a new 'on sale' filter that can be used to display only the products that are currently on sale. - It also refactors the settings management in the product collection block to use the experimental ToolsPanel component from WordPress, which provides a more flexible and intuitive way to manage block settings. - It moves the 'Columns' control into the ToolsPanel, along with the 'Order by' control. - A new utility function `setQueryAttribute` is introduced to simplify setting nested query parameters. - The structure of the `ProductCollectionAttributes` and `ProductCollectionQuery` types have been adjusted to accommodate the changes. - Finally, it makes corresponding changes in the PHP part to handle the new 'on sale' query parameter. This should enhance the flexibility and user-friendliness of the product collection block. * Add stock status filter to WooCommerce product collection block This commit introduces a stock status filter to the WooCommerce product collection block. The changes include: 1. Added the ability to filter products based on their stock status within the 'product-collection' block. A new stock status control is created within the inspector-controls of the block. 2. A new 'get_stock_status_query' function is introduced in 'ProductCollection.php' which returns a query for products depending on their stock status. Please note that the stock status filter will only appear in the experimental build for now. * Refactor Stock Status control of Product Collection block This commit refactors the Stock Status control. The changes aim to improve the code organization and make the behavior of the component more explicit. The key modifications are: 1. Moved stock status related constants and functions from `inspector-controls/utils.tsx` to `inspector-controls/constants.ts`. This is done to ensure that all constants and similar utility functions are organized in one place. 2. Updated `product-collection/index.tsx` to import `getDefaultStockStatuses` from `inspector-controls/constants` instead of `inspector-controls/utils`. 3. Updated `stock-status-control.tsx` to determine whether the stock status has value or not by comparing with the default stock statuses using `fastDeepEqual`. If the stock status control is deselected, it resets the stock status to the default statuses. These changes do not introduce any new functionalities, but improve the readability and maintainability of the code. * Fix: Default values of attributes not saving as serialized block comment This was happening because of this issue: https://github.com/WordPress/gutenberg/issues/7342 Therefore, I had to use `useEffect` to set the default values of the attributes. Here is the list of changes I made: 1. Removed default values from `block.json` for `query`, `tagName`, and `displayLayout`. 2. Moved the default values to `constants.ts` and created a new object `DEFAULT_ATTRIBUTES` to store them. 3. Relocated `constants.ts` from `inspector-controls` to the parent directory. 4. Refactored `edit.tsx` to use `DEFAULT_ATTRIBUTES` from `constants.ts` to set default attributes using `useEffect`. 5. Removed the attributes assignment from `registerBlockType` in `index.tsx`. 6. Updated `columns-control.tsx`, `index.tsx`, `order-by-control.tsx`, and `stock-status-control.tsx` to import from the relocated `constants.ts`. 7. Updated `ProductCollectionAttributes` and `ProductCollectionQuery` in `types.ts` to include `tagName` and `isProductCollectionBlock` respectively. 8. Modified `ProductCollection.php` to match the updated `orderBy` key in the query parameter. This refactor enhances the readability of the code and reduces duplication by keeping all constants and default values in one place. * Replace usage of 'statii' with 'statuses' in stock status handling This commit replaces all instances of 'statii' with the correct term 'statuses' in the context of handling stock status. This change affects three files: 1. `assets/js/blocks/product-collection/inspector-controls/stock-status-control.tsx` - The term is corrected in a comment block. 2. `assets/js/blocks/product-collection/types.ts` - Updated the name of a variable in the `ProductCollectionQuery` interface. 3. `src/BlockTypes/ProductCollection.php` - Here, the term is replaced in several locations including variable names, comments and the method `get_stock_status_query`. This commit helps improve code readability and consistency across the repository.
2023-05-26 11:44:37 +00:00
tagName: 'div',
displayLayout: {
Transfer layout options from Toolbar to Inspector controls (https://github.com/woocommerce/woocommerce-blocks/pull/10922) In this update, the layout options for the Product Collection block are transferred from the Toolbar to the Inspector controls. Below is the breakdown of the changes: 1. **Constants Update** - `LayoutOptions` enumeration has been imported into `constants.ts`, facilitating a more structured approach to managing layout types (grid and stack). - The default display layout type has been updated from 'flex' to reference `LayoutOptions.GRID`. - The `getDefaultQuery` function now uses the `getDefaultValueOfInheritQueryFromTemplate` utility to set the default `inherit` value. (This is mainly done to fix a bug) 2. **Display Layout Control Removal** - The `display-layout-control.tsx` file has been removed, discontinuing the previous method of layout management. 3. **New Layout Options Control** - A new component `LayoutOptionsControl` has been introduced in the `layout-options-control.tsx` file, utilizing the experimental `ToggleGroupControl` and `ToggleGroupControlOption` components from the WordPress package to provide a more intuitive layout selection experience. - The `types.ts` file has been updated to define the `LayoutOptions` enum, effectively mapping 'flex' to 'GRID' and 'list' to 'STACK'. 4. **Inspector Controls Update** - In `inspector-controls/index.tsx`, the obsolete `DisplayLayoutControl` has been replaced with the new `LayoutOptionsControl`, integrating it into the `ProductCollectionInspectorControls` component. - The `BlockControls` wrapper has been removed, and layout options have been relocated to the Inspector controls, presented as a toggle group within the ToolsPanel. 5. **Inherit Query Control Modification** - The `inherit-query-control.tsx` file sees a change in the reset value for the `inherit` query attribute to employ a default value which fix one bug. These changes aim to streamline the user experience by relocating the layout options from the Toolbar to the Inspector controls, offering a centralized location for block settings. Leveraging an enum for layout options fosters code readability and maintainability. Do note that the update uses experimental components, hence it would be prudent to keep an eye on potential alterations or deprecations in upcoming WordPress releases.
2023-09-15 10:08:48 +00:00
type: LayoutOptions.GRID,
Product Collection: Add stock status filter (https://github.com/woocommerce/woocommerce-blocks/pull/9580) * Add columns control to product collection block editor settings - `InspectorControls` from './inspector-controls' is now imported in `edit.tsx` and used in the returned JSX of `Edit` function. - A new file `columns-control.tsx` is added under 'product-collection' block's 'inspector-controls' directory which exports a `ColumnsControl` component. This component uses `RangeControl` from '@wordpress/components' to control the number of columns in the product collection display layout when the layout type is 'flex'. - The types file (`types.ts`) for 'product-collection' block is updated. The `Attributes` interface is renamed to `ProductCollectionAttributes` and the `ProductCollectionContext` interface is removed. The `ProductCollectionAttributes` now includes 'queryContext', 'templateSlug', and 'displayLayout' properties. * Refactor: Simplify Fallback Return in ColumnsControl Component This commit simplifies the fallback return value of the ColumnsControl component. Instead of returning an empty fragment (<> </>), it now returns null when the condition isn't met. This change improves readability and aligns with best practices for conditional rendering in React. * Feature: Add 'Order By' Control to Product Collection Inspector This commit adds a new 'Order By' control to the product collection inspector. The control allows users to specify the order of products in a collection by various attributes such as title and date. To support this, a new component 'OrderByControl' has been created and included in the product collection inspector. Additionally, the types for 'order' and 'orderBy' attributes have been updated and exported for reuse. * Add more options to OrderBy type * Add orderby handling on frontend & editor The main changes include: 1. Added a new property 'isProductCollectionBlock' in the block.json to denote if a block is a product collection block. 2. In the ProductCollection PHP class, a new initialization function has been defined to hook into the WordPress lifecycle, register the block, and update the query based on this block. 3. Added methods to manage query parameters for both frontend rendering and the Editor. 4. Expanded allowed 'collection_params' for the REST API to include custom 'orderby' values. 5. Defined a function to build the query based on block attributes, filters, and global WP_Query. 6. Created utility functions to handle complex query operations such as merging queries, handling custom sort values, and merging arrays recursively. These improvements allow for more flexible and robust handling of product collections in both the front-end display and the WordPress editor. It also extends support for custom 'orderby' values in the REST API, which allows for more advanced sorting options in product collections. * Add 'on sale' filter and enhance settings management in product collection block This commit introduces several changes to the product collection block. - First, it adds a new 'on sale' filter that can be used to display only the products that are currently on sale. - It also refactors the settings management in the product collection block to use the experimental ToolsPanel component from WordPress, which provides a more flexible and intuitive way to manage block settings. - It moves the 'Columns' control into the ToolsPanel, along with the 'Order by' control. - A new utility function `setQueryAttribute` is introduced to simplify setting nested query parameters. - The structure of the `ProductCollectionAttributes` and `ProductCollectionQuery` types have been adjusted to accommodate the changes. - Finally, it makes corresponding changes in the PHP part to handle the new 'on sale' query parameter. This should enhance the flexibility and user-friendliness of the product collection block. * Add stock status filter to WooCommerce product collection block This commit introduces a stock status filter to the WooCommerce product collection block. The changes include: 1. Added the ability to filter products based on their stock status within the 'product-collection' block. A new stock status control is created within the inspector-controls of the block. 2. A new 'get_stock_status_query' function is introduced in 'ProductCollection.php' which returns a query for products depending on their stock status. Please note that the stock status filter will only appear in the experimental build for now. * Refactor Stock Status control of Product Collection block This commit refactors the Stock Status control. The changes aim to improve the code organization and make the behavior of the component more explicit. The key modifications are: 1. Moved stock status related constants and functions from `inspector-controls/utils.tsx` to `inspector-controls/constants.ts`. This is done to ensure that all constants and similar utility functions are organized in one place. 2. Updated `product-collection/index.tsx` to import `getDefaultStockStatuses` from `inspector-controls/constants` instead of `inspector-controls/utils`. 3. Updated `stock-status-control.tsx` to determine whether the stock status has value or not by comparing with the default stock statuses using `fastDeepEqual`. If the stock status control is deselected, it resets the stock status to the default statuses. These changes do not introduce any new functionalities, but improve the readability and maintainability of the code. * Fix: Default values of attributes not saving as serialized block comment This was happening because of this issue: https://github.com/WordPress/gutenberg/issues/7342 Therefore, I had to use `useEffect` to set the default values of the attributes. Here is the list of changes I made: 1. Removed default values from `block.json` for `query`, `tagName`, and `displayLayout`. 2. Moved the default values to `constants.ts` and created a new object `DEFAULT_ATTRIBUTES` to store them. 3. Relocated `constants.ts` from `inspector-controls` to the parent directory. 4. Refactored `edit.tsx` to use `DEFAULT_ATTRIBUTES` from `constants.ts` to set default attributes using `useEffect`. 5. Removed the attributes assignment from `registerBlockType` in `index.tsx`. 6. Updated `columns-control.tsx`, `index.tsx`, `order-by-control.tsx`, and `stock-status-control.tsx` to import from the relocated `constants.ts`. 7. Updated `ProductCollectionAttributes` and `ProductCollectionQuery` in `types.ts` to include `tagName` and `isProductCollectionBlock` respectively. 8. Modified `ProductCollection.php` to match the updated `orderBy` key in the query parameter. This refactor enhances the readability of the code and reduces duplication by keeping all constants and default values in one place. * Replace usage of 'statii' with 'statuses' in stock status handling This commit replaces all instances of 'statii' with the correct term 'statuses' in the context of handling stock status. This change affects three files: 1. `assets/js/blocks/product-collection/inspector-controls/stock-status-control.tsx` - The term is corrected in a comment block. 2. `assets/js/blocks/product-collection/types.ts` - Updated the name of a variable in the `ProductCollectionQuery` interface. 3. `src/BlockTypes/ProductCollection.php` - Here, the term is replaced in several locations including variable names, comments and the method `get_stock_status_query`. This commit helps improve code readability and consistency across the repository.
2023-05-26 11:44:37 +00:00
columns: 3,
shrinkColumns: true,
Product Collection: Add stock status filter (https://github.com/woocommerce/woocommerce-blocks/pull/9580) * Add columns control to product collection block editor settings - `InspectorControls` from './inspector-controls' is now imported in `edit.tsx` and used in the returned JSX of `Edit` function. - A new file `columns-control.tsx` is added under 'product-collection' block's 'inspector-controls' directory which exports a `ColumnsControl` component. This component uses `RangeControl` from '@wordpress/components' to control the number of columns in the product collection display layout when the layout type is 'flex'. - The types file (`types.ts`) for 'product-collection' block is updated. The `Attributes` interface is renamed to `ProductCollectionAttributes` and the `ProductCollectionContext` interface is removed. The `ProductCollectionAttributes` now includes 'queryContext', 'templateSlug', and 'displayLayout' properties. * Refactor: Simplify Fallback Return in ColumnsControl Component This commit simplifies the fallback return value of the ColumnsControl component. Instead of returning an empty fragment (<> </>), it now returns null when the condition isn't met. This change improves readability and aligns with best practices for conditional rendering in React. * Feature: Add 'Order By' Control to Product Collection Inspector This commit adds a new 'Order By' control to the product collection inspector. The control allows users to specify the order of products in a collection by various attributes such as title and date. To support this, a new component 'OrderByControl' has been created and included in the product collection inspector. Additionally, the types for 'order' and 'orderBy' attributes have been updated and exported for reuse. * Add more options to OrderBy type * Add orderby handling on frontend & editor The main changes include: 1. Added a new property 'isProductCollectionBlock' in the block.json to denote if a block is a product collection block. 2. In the ProductCollection PHP class, a new initialization function has been defined to hook into the WordPress lifecycle, register the block, and update the query based on this block. 3. Added methods to manage query parameters for both frontend rendering and the Editor. 4. Expanded allowed 'collection_params' for the REST API to include custom 'orderby' values. 5. Defined a function to build the query based on block attributes, filters, and global WP_Query. 6. Created utility functions to handle complex query operations such as merging queries, handling custom sort values, and merging arrays recursively. These improvements allow for more flexible and robust handling of product collections in both the front-end display and the WordPress editor. It also extends support for custom 'orderby' values in the REST API, which allows for more advanced sorting options in product collections. * Add 'on sale' filter and enhance settings management in product collection block This commit introduces several changes to the product collection block. - First, it adds a new 'on sale' filter that can be used to display only the products that are currently on sale. - It also refactors the settings management in the product collection block to use the experimental ToolsPanel component from WordPress, which provides a more flexible and intuitive way to manage block settings. - It moves the 'Columns' control into the ToolsPanel, along with the 'Order by' control. - A new utility function `setQueryAttribute` is introduced to simplify setting nested query parameters. - The structure of the `ProductCollectionAttributes` and `ProductCollectionQuery` types have been adjusted to accommodate the changes. - Finally, it makes corresponding changes in the PHP part to handle the new 'on sale' query parameter. This should enhance the flexibility and user-friendliness of the product collection block. * Add stock status filter to WooCommerce product collection block This commit introduces a stock status filter to the WooCommerce product collection block. The changes include: 1. Added the ability to filter products based on their stock status within the 'product-collection' block. A new stock status control is created within the inspector-controls of the block. 2. A new 'get_stock_status_query' function is introduced in 'ProductCollection.php' which returns a query for products depending on their stock status. Please note that the stock status filter will only appear in the experimental build for now. * Refactor Stock Status control of Product Collection block This commit refactors the Stock Status control. The changes aim to improve the code organization and make the behavior of the component more explicit. The key modifications are: 1. Moved stock status related constants and functions from `inspector-controls/utils.tsx` to `inspector-controls/constants.ts`. This is done to ensure that all constants and similar utility functions are organized in one place. 2. Updated `product-collection/index.tsx` to import `getDefaultStockStatuses` from `inspector-controls/constants` instead of `inspector-controls/utils`. 3. Updated `stock-status-control.tsx` to determine whether the stock status has value or not by comparing with the default stock statuses using `fastDeepEqual`. If the stock status control is deselected, it resets the stock status to the default statuses. These changes do not introduce any new functionalities, but improve the readability and maintainability of the code. * Fix: Default values of attributes not saving as serialized block comment This was happening because of this issue: https://github.com/WordPress/gutenberg/issues/7342 Therefore, I had to use `useEffect` to set the default values of the attributes. Here is the list of changes I made: 1. Removed default values from `block.json` for `query`, `tagName`, and `displayLayout`. 2. Moved the default values to `constants.ts` and created a new object `DEFAULT_ATTRIBUTES` to store them. 3. Relocated `constants.ts` from `inspector-controls` to the parent directory. 4. Refactored `edit.tsx` to use `DEFAULT_ATTRIBUTES` from `constants.ts` to set default attributes using `useEffect`. 5. Removed the attributes assignment from `registerBlockType` in `index.tsx`. 6. Updated `columns-control.tsx`, `index.tsx`, `order-by-control.tsx`, and `stock-status-control.tsx` to import from the relocated `constants.ts`. 7. Updated `ProductCollectionAttributes` and `ProductCollectionQuery` in `types.ts` to include `tagName` and `isProductCollectionBlock` respectively. 8. Modified `ProductCollection.php` to match the updated `orderBy` key in the query parameter. This refactor enhances the readability of the code and reduces duplication by keeping all constants and default values in one place. * Replace usage of 'statii' with 'statuses' in stock status handling This commit replaces all instances of 'statii' with the correct term 'statuses' in the context of handling stock status. This change affects three files: 1. `assets/js/blocks/product-collection/inspector-controls/stock-status-control.tsx` - The term is corrected in a comment block. 2. `assets/js/blocks/product-collection/types.ts` - Updated the name of a variable in the `ProductCollectionQuery` interface. 3. `src/BlockTypes/ProductCollection.php` - Here, the term is replaced in several locations including variable names, comments and the method `get_stock_status_query`. This commit helps improve code readability and consistency across the repository.
2023-05-26 11:44:37 +00:00
},
queryContextIncludes: [ 'collection' ],
Product Collection: Disable client side navigation if blocks incompatible with Interactivity API are detected (#45435) * Add dummy Force Page Reload control to Inspector Advanced Control * Add enhancedPagination attribute that decides if client side navigation is enabled * Consume the enhancedPagination attribute * Force client side navigation when incompatible blocks detected * Dummy util to detect incompatible blocks * Detect incompatible blocks in the Editor * Switch to WordPress Interactivity package in Product Collection * Add initial implementation of the incompatible blocks detection in frontend * Remove leftover * Revert to using internal version of interactivity API * There's no Interactivity store config available in the internal Interactivity implementation so remove it * Disable client side navigation if the incompatible block is detected * Add default attribute value * Switch from enmhancedPagination attribute to forcePageReload * Fixed some misclicked line order change * Switch from enhancedPagination to forcePageReload in PHP code * Apply the correct filter * Fix the incorrect condition to detect incompatible block * Initial implementation of orange dot to bring attention * Cleanup * Remove the orange dot indicator * Refactor checking for unsupported blocks * Add changelog * Fix PHP lint errors * Bring back empty line at the end of pnpm-lock * Bring pnpm-lock.yaml file to original state * Fix incorrect function call * Add visibility description to function * Switch private method to public * More linted fixes
2024-03-18 07:24:03 +00:00
forcePageReload: false,
Product Collection: Add stock status filter (https://github.com/woocommerce/woocommerce-blocks/pull/9580) * Add columns control to product collection block editor settings - `InspectorControls` from './inspector-controls' is now imported in `edit.tsx` and used in the returned JSX of `Edit` function. - A new file `columns-control.tsx` is added under 'product-collection' block's 'inspector-controls' directory which exports a `ColumnsControl` component. This component uses `RangeControl` from '@wordpress/components' to control the number of columns in the product collection display layout when the layout type is 'flex'. - The types file (`types.ts`) for 'product-collection' block is updated. The `Attributes` interface is renamed to `ProductCollectionAttributes` and the `ProductCollectionContext` interface is removed. The `ProductCollectionAttributes` now includes 'queryContext', 'templateSlug', and 'displayLayout' properties. * Refactor: Simplify Fallback Return in ColumnsControl Component This commit simplifies the fallback return value of the ColumnsControl component. Instead of returning an empty fragment (<> </>), it now returns null when the condition isn't met. This change improves readability and aligns with best practices for conditional rendering in React. * Feature: Add 'Order By' Control to Product Collection Inspector This commit adds a new 'Order By' control to the product collection inspector. The control allows users to specify the order of products in a collection by various attributes such as title and date. To support this, a new component 'OrderByControl' has been created and included in the product collection inspector. Additionally, the types for 'order' and 'orderBy' attributes have been updated and exported for reuse. * Add more options to OrderBy type * Add orderby handling on frontend & editor The main changes include: 1. Added a new property 'isProductCollectionBlock' in the block.json to denote if a block is a product collection block. 2. In the ProductCollection PHP class, a new initialization function has been defined to hook into the WordPress lifecycle, register the block, and update the query based on this block. 3. Added methods to manage query parameters for both frontend rendering and the Editor. 4. Expanded allowed 'collection_params' for the REST API to include custom 'orderby' values. 5. Defined a function to build the query based on block attributes, filters, and global WP_Query. 6. Created utility functions to handle complex query operations such as merging queries, handling custom sort values, and merging arrays recursively. These improvements allow for more flexible and robust handling of product collections in both the front-end display and the WordPress editor. It also extends support for custom 'orderby' values in the REST API, which allows for more advanced sorting options in product collections. * Add 'on sale' filter and enhance settings management in product collection block This commit introduces several changes to the product collection block. - First, it adds a new 'on sale' filter that can be used to display only the products that are currently on sale. - It also refactors the settings management in the product collection block to use the experimental ToolsPanel component from WordPress, which provides a more flexible and intuitive way to manage block settings. - It moves the 'Columns' control into the ToolsPanel, along with the 'Order by' control. - A new utility function `setQueryAttribute` is introduced to simplify setting nested query parameters. - The structure of the `ProductCollectionAttributes` and `ProductCollectionQuery` types have been adjusted to accommodate the changes. - Finally, it makes corresponding changes in the PHP part to handle the new 'on sale' query parameter. This should enhance the flexibility and user-friendliness of the product collection block. * Add stock status filter to WooCommerce product collection block This commit introduces a stock status filter to the WooCommerce product collection block. The changes include: 1. Added the ability to filter products based on their stock status within the 'product-collection' block. A new stock status control is created within the inspector-controls of the block. 2. A new 'get_stock_status_query' function is introduced in 'ProductCollection.php' which returns a query for products depending on their stock status. Please note that the stock status filter will only appear in the experimental build for now. * Refactor Stock Status control of Product Collection block This commit refactors the Stock Status control. The changes aim to improve the code organization and make the behavior of the component more explicit. The key modifications are: 1. Moved stock status related constants and functions from `inspector-controls/utils.tsx` to `inspector-controls/constants.ts`. This is done to ensure that all constants and similar utility functions are organized in one place. 2. Updated `product-collection/index.tsx` to import `getDefaultStockStatuses` from `inspector-controls/constants` instead of `inspector-controls/utils`. 3. Updated `stock-status-control.tsx` to determine whether the stock status has value or not by comparing with the default stock statuses using `fastDeepEqual`. If the stock status control is deselected, it resets the stock status to the default statuses. These changes do not introduce any new functionalities, but improve the readability and maintainability of the code. * Fix: Default values of attributes not saving as serialized block comment This was happening because of this issue: https://github.com/WordPress/gutenberg/issues/7342 Therefore, I had to use `useEffect` to set the default values of the attributes. Here is the list of changes I made: 1. Removed default values from `block.json` for `query`, `tagName`, and `displayLayout`. 2. Moved the default values to `constants.ts` and created a new object `DEFAULT_ATTRIBUTES` to store them. 3. Relocated `constants.ts` from `inspector-controls` to the parent directory. 4. Refactored `edit.tsx` to use `DEFAULT_ATTRIBUTES` from `constants.ts` to set default attributes using `useEffect`. 5. Removed the attributes assignment from `registerBlockType` in `index.tsx`. 6. Updated `columns-control.tsx`, `index.tsx`, `order-by-control.tsx`, and `stock-status-control.tsx` to import from the relocated `constants.ts`. 7. Updated `ProductCollectionAttributes` and `ProductCollectionQuery` in `types.ts` to include `tagName` and `isProductCollectionBlock` respectively. 8. Modified `ProductCollection.php` to match the updated `orderBy` key in the query parameter. This refactor enhances the readability of the code and reduces duplication by keeping all constants and default values in one place. * Replace usage of 'statii' with 'statuses' in stock status handling This commit replaces all instances of 'statii' with the correct term 'statuses' in the context of handling stock status. This change affects three files: 1. `assets/js/blocks/product-collection/inspector-controls/stock-status-control.tsx` - The term is corrected in a comment block. 2. `assets/js/blocks/product-collection/types.ts` - Updated the name of a variable in the `ProductCollectionQuery` interface. 3. `src/BlockTypes/ProductCollection.php` - Here, the term is replaced in several locations including variable names, comments and the method `get_stock_status_query`. This commit helps improve code readability and consistency across the repository.
2023-05-26 11:44:37 +00:00
};
export const getDefaultQuery = (
currentQuery: ProductCollectionQuery
): ProductCollectionQuery => ( {
...currentQuery,
orderBy: DEFAULT_QUERY.orderBy as TProductCollectionOrderBy,
order: DEFAULT_QUERY.order as TProductCollectionOrder,
Transfer layout options from Toolbar to Inspector controls (https://github.com/woocommerce/woocommerce-blocks/pull/10922) In this update, the layout options for the Product Collection block are transferred from the Toolbar to the Inspector controls. Below is the breakdown of the changes: 1. **Constants Update** - `LayoutOptions` enumeration has been imported into `constants.ts`, facilitating a more structured approach to managing layout types (grid and stack). - The default display layout type has been updated from 'flex' to reference `LayoutOptions.GRID`. - The `getDefaultQuery` function now uses the `getDefaultValueOfInheritQueryFromTemplate` utility to set the default `inherit` value. (This is mainly done to fix a bug) 2. **Display Layout Control Removal** - The `display-layout-control.tsx` file has been removed, discontinuing the previous method of layout management. 3. **New Layout Options Control** - A new component `LayoutOptionsControl` has been introduced in the `layout-options-control.tsx` file, utilizing the experimental `ToggleGroupControl` and `ToggleGroupControlOption` components from the WordPress package to provide a more intuitive layout selection experience. - The `types.ts` file has been updated to define the `LayoutOptions` enum, effectively mapping 'flex' to 'GRID' and 'list' to 'STACK'. 4. **Inspector Controls Update** - In `inspector-controls/index.tsx`, the obsolete `DisplayLayoutControl` has been replaced with the new `LayoutOptionsControl`, integrating it into the `ProductCollectionInspectorControls` component. - The `BlockControls` wrapper has been removed, and layout options have been relocated to the Inspector controls, presented as a toggle group within the ToolsPanel. 5. **Inherit Query Control Modification** - The `inherit-query-control.tsx` file sees a change in the reset value for the `inherit` query attribute to employ a default value which fix one bug. These changes aim to streamline the user experience by relocating the layout options from the Toolbar to the Inspector controls, offering a centralized location for block settings. Leveraging an enum for layout options fosters code readability and maintainability. Do note that the update uses experimental components, hence it would be prudent to keep an eye on potential alterations or deprecations in upcoming WordPress releases.
2023-09-15 10:08:48 +00:00
inherit: getDefaultValueOfInheritQueryFromTemplate(),
} );
export const getDefaultDisplayLayout = () =>
DEFAULT_ATTRIBUTES.displayLayout as ProductCollectionDisplayLayout;
Product Collection: Add stock status filter (https://github.com/woocommerce/woocommerce-blocks/pull/9580) * Add columns control to product collection block editor settings - `InspectorControls` from './inspector-controls' is now imported in `edit.tsx` and used in the returned JSX of `Edit` function. - A new file `columns-control.tsx` is added under 'product-collection' block's 'inspector-controls' directory which exports a `ColumnsControl` component. This component uses `RangeControl` from '@wordpress/components' to control the number of columns in the product collection display layout when the layout type is 'flex'. - The types file (`types.ts`) for 'product-collection' block is updated. The `Attributes` interface is renamed to `ProductCollectionAttributes` and the `ProductCollectionContext` interface is removed. The `ProductCollectionAttributes` now includes 'queryContext', 'templateSlug', and 'displayLayout' properties. * Refactor: Simplify Fallback Return in ColumnsControl Component This commit simplifies the fallback return value of the ColumnsControl component. Instead of returning an empty fragment (<> </>), it now returns null when the condition isn't met. This change improves readability and aligns with best practices for conditional rendering in React. * Feature: Add 'Order By' Control to Product Collection Inspector This commit adds a new 'Order By' control to the product collection inspector. The control allows users to specify the order of products in a collection by various attributes such as title and date. To support this, a new component 'OrderByControl' has been created and included in the product collection inspector. Additionally, the types for 'order' and 'orderBy' attributes have been updated and exported for reuse. * Add more options to OrderBy type * Add orderby handling on frontend & editor The main changes include: 1. Added a new property 'isProductCollectionBlock' in the block.json to denote if a block is a product collection block. 2. In the ProductCollection PHP class, a new initialization function has been defined to hook into the WordPress lifecycle, register the block, and update the query based on this block. 3. Added methods to manage query parameters for both frontend rendering and the Editor. 4. Expanded allowed 'collection_params' for the REST API to include custom 'orderby' values. 5. Defined a function to build the query based on block attributes, filters, and global WP_Query. 6. Created utility functions to handle complex query operations such as merging queries, handling custom sort values, and merging arrays recursively. These improvements allow for more flexible and robust handling of product collections in both the front-end display and the WordPress editor. It also extends support for custom 'orderby' values in the REST API, which allows for more advanced sorting options in product collections. * Add 'on sale' filter and enhance settings management in product collection block This commit introduces several changes to the product collection block. - First, it adds a new 'on sale' filter that can be used to display only the products that are currently on sale. - It also refactors the settings management in the product collection block to use the experimental ToolsPanel component from WordPress, which provides a more flexible and intuitive way to manage block settings. - It moves the 'Columns' control into the ToolsPanel, along with the 'Order by' control. - A new utility function `setQueryAttribute` is introduced to simplify setting nested query parameters. - The structure of the `ProductCollectionAttributes` and `ProductCollectionQuery` types have been adjusted to accommodate the changes. - Finally, it makes corresponding changes in the PHP part to handle the new 'on sale' query parameter. This should enhance the flexibility and user-friendliness of the product collection block. * Add stock status filter to WooCommerce product collection block This commit introduces a stock status filter to the WooCommerce product collection block. The changes include: 1. Added the ability to filter products based on their stock status within the 'product-collection' block. A new stock status control is created within the inspector-controls of the block. 2. A new 'get_stock_status_query' function is introduced in 'ProductCollection.php' which returns a query for products depending on their stock status. Please note that the stock status filter will only appear in the experimental build for now. * Refactor Stock Status control of Product Collection block This commit refactors the Stock Status control. The changes aim to improve the code organization and make the behavior of the component more explicit. The key modifications are: 1. Moved stock status related constants and functions from `inspector-controls/utils.tsx` to `inspector-controls/constants.ts`. This is done to ensure that all constants and similar utility functions are organized in one place. 2. Updated `product-collection/index.tsx` to import `getDefaultStockStatuses` from `inspector-controls/constants` instead of `inspector-controls/utils`. 3. Updated `stock-status-control.tsx` to determine whether the stock status has value or not by comparing with the default stock statuses using `fastDeepEqual`. If the stock status control is deselected, it resets the stock status to the default statuses. These changes do not introduce any new functionalities, but improve the readability and maintainability of the code. * Fix: Default values of attributes not saving as serialized block comment This was happening because of this issue: https://github.com/WordPress/gutenberg/issues/7342 Therefore, I had to use `useEffect` to set the default values of the attributes. Here is the list of changes I made: 1. Removed default values from `block.json` for `query`, `tagName`, and `displayLayout`. 2. Moved the default values to `constants.ts` and created a new object `DEFAULT_ATTRIBUTES` to store them. 3. Relocated `constants.ts` from `inspector-controls` to the parent directory. 4. Refactored `edit.tsx` to use `DEFAULT_ATTRIBUTES` from `constants.ts` to set default attributes using `useEffect`. 5. Removed the attributes assignment from `registerBlockType` in `index.tsx`. 6. Updated `columns-control.tsx`, `index.tsx`, `order-by-control.tsx`, and `stock-status-control.tsx` to import from the relocated `constants.ts`. 7. Updated `ProductCollectionAttributes` and `ProductCollectionQuery` in `types.ts` to include `tagName` and `isProductCollectionBlock` respectively. 8. Modified `ProductCollection.php` to match the updated `orderBy` key in the query parameter. This refactor enhances the readability of the code and reduces duplication by keeping all constants and default values in one place. * Replace usage of 'statii' with 'statuses' in stock status handling This commit replaces all instances of 'statii' with the correct term 'statuses' in the context of handling stock status. This change affects three files: 1. `assets/js/blocks/product-collection/inspector-controls/stock-status-control.tsx` - The term is corrected in a comment block. 2. `assets/js/blocks/product-collection/types.ts` - Updated the name of a variable in the `ProductCollectionQuery` interface. 3. `src/BlockTypes/ProductCollection.php` - Here, the term is replaced in several locations including variable names, comments and the method `get_stock_status_query`. This commit helps improve code readability and consistency across the repository.
2023-05-26 11:44:37 +00:00
export const getDefaultSettings = (
currentAttributes: ProductCollectionAttributes
): Partial< ProductCollectionAttributes > => ( {
displayLayout: getDefaultDisplayLayout(),
query: getDefaultQuery( currentAttributes.query ),
Product Collection: Add stock status filter (https://github.com/woocommerce/woocommerce-blocks/pull/9580) * Add columns control to product collection block editor settings - `InspectorControls` from './inspector-controls' is now imported in `edit.tsx` and used in the returned JSX of `Edit` function. - A new file `columns-control.tsx` is added under 'product-collection' block's 'inspector-controls' directory which exports a `ColumnsControl` component. This component uses `RangeControl` from '@wordpress/components' to control the number of columns in the product collection display layout when the layout type is 'flex'. - The types file (`types.ts`) for 'product-collection' block is updated. The `Attributes` interface is renamed to `ProductCollectionAttributes` and the `ProductCollectionContext` interface is removed. The `ProductCollectionAttributes` now includes 'queryContext', 'templateSlug', and 'displayLayout' properties. * Refactor: Simplify Fallback Return in ColumnsControl Component This commit simplifies the fallback return value of the ColumnsControl component. Instead of returning an empty fragment (<> </>), it now returns null when the condition isn't met. This change improves readability and aligns with best practices for conditional rendering in React. * Feature: Add 'Order By' Control to Product Collection Inspector This commit adds a new 'Order By' control to the product collection inspector. The control allows users to specify the order of products in a collection by various attributes such as title and date. To support this, a new component 'OrderByControl' has been created and included in the product collection inspector. Additionally, the types for 'order' and 'orderBy' attributes have been updated and exported for reuse. * Add more options to OrderBy type * Add orderby handling on frontend & editor The main changes include: 1. Added a new property 'isProductCollectionBlock' in the block.json to denote if a block is a product collection block. 2. In the ProductCollection PHP class, a new initialization function has been defined to hook into the WordPress lifecycle, register the block, and update the query based on this block. 3. Added methods to manage query parameters for both frontend rendering and the Editor. 4. Expanded allowed 'collection_params' for the REST API to include custom 'orderby' values. 5. Defined a function to build the query based on block attributes, filters, and global WP_Query. 6. Created utility functions to handle complex query operations such as merging queries, handling custom sort values, and merging arrays recursively. These improvements allow for more flexible and robust handling of product collections in both the front-end display and the WordPress editor. It also extends support for custom 'orderby' values in the REST API, which allows for more advanced sorting options in product collections. * Add 'on sale' filter and enhance settings management in product collection block This commit introduces several changes to the product collection block. - First, it adds a new 'on sale' filter that can be used to display only the products that are currently on sale. - It also refactors the settings management in the product collection block to use the experimental ToolsPanel component from WordPress, which provides a more flexible and intuitive way to manage block settings. - It moves the 'Columns' control into the ToolsPanel, along with the 'Order by' control. - A new utility function `setQueryAttribute` is introduced to simplify setting nested query parameters. - The structure of the `ProductCollectionAttributes` and `ProductCollectionQuery` types have been adjusted to accommodate the changes. - Finally, it makes corresponding changes in the PHP part to handle the new 'on sale' query parameter. This should enhance the flexibility and user-friendliness of the product collection block. * Add stock status filter to WooCommerce product collection block This commit introduces a stock status filter to the WooCommerce product collection block. The changes include: 1. Added the ability to filter products based on their stock status within the 'product-collection' block. A new stock status control is created within the inspector-controls of the block. 2. A new 'get_stock_status_query' function is introduced in 'ProductCollection.php' which returns a query for products depending on their stock status. Please note that the stock status filter will only appear in the experimental build for now. * Refactor Stock Status control of Product Collection block This commit refactors the Stock Status control. The changes aim to improve the code organization and make the behavior of the component more explicit. The key modifications are: 1. Moved stock status related constants and functions from `inspector-controls/utils.tsx` to `inspector-controls/constants.ts`. This is done to ensure that all constants and similar utility functions are organized in one place. 2. Updated `product-collection/index.tsx` to import `getDefaultStockStatuses` from `inspector-controls/constants` instead of `inspector-controls/utils`. 3. Updated `stock-status-control.tsx` to determine whether the stock status has value or not by comparing with the default stock statuses using `fastDeepEqual`. If the stock status control is deselected, it resets the stock status to the default statuses. These changes do not introduce any new functionalities, but improve the readability and maintainability of the code. * Fix: Default values of attributes not saving as serialized block comment This was happening because of this issue: https://github.com/WordPress/gutenberg/issues/7342 Therefore, I had to use `useEffect` to set the default values of the attributes. Here is the list of changes I made: 1. Removed default values from `block.json` for `query`, `tagName`, and `displayLayout`. 2. Moved the default values to `constants.ts` and created a new object `DEFAULT_ATTRIBUTES` to store them. 3. Relocated `constants.ts` from `inspector-controls` to the parent directory. 4. Refactored `edit.tsx` to use `DEFAULT_ATTRIBUTES` from `constants.ts` to set default attributes using `useEffect`. 5. Removed the attributes assignment from `registerBlockType` in `index.tsx`. 6. Updated `columns-control.tsx`, `index.tsx`, `order-by-control.tsx`, and `stock-status-control.tsx` to import from the relocated `constants.ts`. 7. Updated `ProductCollectionAttributes` and `ProductCollectionQuery` in `types.ts` to include `tagName` and `isProductCollectionBlock` respectively. 8. Modified `ProductCollection.php` to match the updated `orderBy` key in the query parameter. This refactor enhances the readability of the code and reduces duplication by keeping all constants and default values in one place. * Replace usage of 'statii' with 'statuses' in stock status handling This commit replaces all instances of 'statii' with the correct term 'statuses' in the context of handling stock status. This change affects three files: 1. `assets/js/blocks/product-collection/inspector-controls/stock-status-control.tsx` - The term is corrected in a comment block. 2. `assets/js/blocks/product-collection/types.ts` - Updated the name of a variable in the `ProductCollectionQuery` interface. 3. `src/BlockTypes/ProductCollection.php` - Here, the term is replaced in several locations including variable names, comments and the method `get_stock_status_query`. This commit helps improve code readability and consistency across the repository.
2023-05-26 11:44:37 +00:00
} );
export const DEFAULT_FILTERS: Pick<
ProductCollectionQuery,
| 'woocommerceOnSale'
| 'woocommerceStockStatus'
| 'woocommerceAttributes'
| 'woocommerceHandPickedProducts'
| 'taxQuery'
| 'featured'
| 'timeFrame'
| 'priceRange'
> = {
Product Collection: Add Taxonomy filters to sidebar settings (https://github.com/woocommerce/woocommerce-blocks/pull/9634) * Add columns control to product collection block editor settings - `InspectorControls` from './inspector-controls' is now imported in `edit.tsx` and used in the returned JSX of `Edit` function. - A new file `columns-control.tsx` is added under 'product-collection' block's 'inspector-controls' directory which exports a `ColumnsControl` component. This component uses `RangeControl` from '@wordpress/components' to control the number of columns in the product collection display layout when the layout type is 'flex'. - The types file (`types.ts`) for 'product-collection' block is updated. The `Attributes` interface is renamed to `ProductCollectionAttributes` and the `ProductCollectionContext` interface is removed. The `ProductCollectionAttributes` now includes 'queryContext', 'templateSlug', and 'displayLayout' properties. * Refactor: Simplify Fallback Return in ColumnsControl Component This commit simplifies the fallback return value of the ColumnsControl component. Instead of returning an empty fragment (<> </>), it now returns null when the condition isn't met. This change improves readability and aligns with best practices for conditional rendering in React. * Feature: Add 'Order By' Control to Product Collection Inspector This commit adds a new 'Order By' control to the product collection inspector. The control allows users to specify the order of products in a collection by various attributes such as title and date. To support this, a new component 'OrderByControl' has been created and included in the product collection inspector. Additionally, the types for 'order' and 'orderBy' attributes have been updated and exported for reuse. * Add more options to OrderBy type * Add orderby handling on frontend & editor The main changes include: 1. Added a new property 'isProductCollectionBlock' in the block.json to denote if a block is a product collection block. 2. In the ProductCollection PHP class, a new initialization function has been defined to hook into the WordPress lifecycle, register the block, and update the query based on this block. 3. Added methods to manage query parameters for both frontend rendering and the Editor. 4. Expanded allowed 'collection_params' for the REST API to include custom 'orderby' values. 5. Defined a function to build the query based on block attributes, filters, and global WP_Query. 6. Created utility functions to handle complex query operations such as merging queries, handling custom sort values, and merging arrays recursively. These improvements allow for more flexible and robust handling of product collections in both the front-end display and the WordPress editor. It also extends support for custom 'orderby' values in the REST API, which allows for more advanced sorting options in product collections. * Add 'on sale' filter and enhance settings management in product collection block This commit introduces several changes to the product collection block. - First, it adds a new 'on sale' filter that can be used to display only the products that are currently on sale. - It also refactors the settings management in the product collection block to use the experimental ToolsPanel component from WordPress, which provides a more flexible and intuitive way to manage block settings. - It moves the 'Columns' control into the ToolsPanel, along with the 'Order by' control. - A new utility function `setQueryAttribute` is introduced to simplify setting nested query parameters. - The structure of the `ProductCollectionAttributes` and `ProductCollectionQuery` types have been adjusted to accommodate the changes. - Finally, it makes corresponding changes in the PHP part to handle the new 'on sale' query parameter. This should enhance the flexibility and user-friendliness of the product collection block. * Add stock status filter to WooCommerce product collection block This commit introduces a stock status filter to the WooCommerce product collection block. The changes include: 1. Added the ability to filter products based on their stock status within the 'product-collection' block. A new stock status control is created within the inspector-controls of the block. 2. A new 'get_stock_status_query' function is introduced in 'ProductCollection.php' which returns a query for products depending on their stock status. Please note that the stock status filter will only appear in the experimental build for now. * Refactor Stock Status control of Product Collection block This commit refactors the Stock Status control. The changes aim to improve the code organization and make the behavior of the component more explicit. The key modifications are: 1. Moved stock status related constants and functions from `inspector-controls/utils.tsx` to `inspector-controls/constants.ts`. This is done to ensure that all constants and similar utility functions are organized in one place. 2. Updated `product-collection/index.tsx` to import `getDefaultStockStatuses` from `inspector-controls/constants` instead of `inspector-controls/utils`. 3. Updated `stock-status-control.tsx` to determine whether the stock status has value or not by comparing with the default stock statuses using `fastDeepEqual`. If the stock status control is deselected, it resets the stock status to the default statuses. These changes do not introduce any new functionalities, but improve the readability and maintainability of the code. * Add keyword search control to Product Collection block This commit introduces a keyword search functionality to the Product Collection block. The update is aimed to provide users with more flexibility and precision in product collection queries. Key changes: 1. Introduced a new file `keyword-control.tsx` that creates a Keyword Control component. This component includes a TextControl field that allows inputting a search keyword. The keyword search is debounced to prevent unnecessary queries during input and updates the block's attributes accordingly. 2. Modified `inspector-controls/index.tsx` to include the KeywordControl in the ToolsPanel for the block's filters. 3. Adjusted `ProductCollection.php` to include the keyword search in the product query array. With these changes, users can now search for products by keyword in the Product Collection block. * Add product attributes filter control to ProductCollection block - This commit introduces the ability to filter products by attributes in ProductCollection block. - A new `woocommerceAttributes` key was added to the `block.json` file and the `ProductCollectionQuery` type. Also, a new file `attributes-control.tsx` was created, providing the UI component for the attribute filter control in the editor. - In addition, updates were made to the `ProductCollection.php` file in the backend to support filtering products by attributes, and the tax query was updated to include attribute queries. - Lastly, the `ProductCollectionInspectorControls` was updated to include the `AttributesControl` component, thus enabling users to filter products by attributes in the block editor."` * remove unused import of getDefaultStockStatuses * Delete a duplicate file * Remove console log * Add taxonomies control to Product collection block The primary changes include: 1. `taxQuery` field in the `ProductCollectionAttributes` was changed from a string to an object in `assets/js/blocks/product-collection/types.ts` and `assets/js/blocks/product-collection/constants.ts`, accommodating the ability to query products by taxonomy terms. 2. `assets/js/blocks/product-collection/inspector-controls/utils.tsx` was moved to `assets/js/blocks/product-collection/utils.tsx` to make it available for broader use. 3. New component `TaxonomyControls` was created in `assets/js/blocks/product-collection/inspector-controls/taxonomy-controls.tsx`, which is included in `assets/js/blocks/product-collection/inspector-controls/index.tsx`. This new control allows users to filter products in the block by their taxonomy terms. 4. Updated the block's inspector controls in `assets/js/blocks/product-collection/inspector-controls/index.tsx` to use the new `TaxonomyControls` component. Please note that the TaxonomyControls component uses experimental features of WordPress's FormTokenField. As a result, a comment has been added to disable eslint warnings regarding the use of experimental APIs. * Address PR feedback & other improvements 1. Added `woocommerceAttributes` to `DEFAULT_FILTERS` in the `product-collection/constants.ts` file to fix `reset all` button issue. 2. Refactored `attributes-control.tsx` to make it more maintainable: - The constant `EDIT_ATTRIBUTES_URL` now uses `ADMIN_URL` from `@woocommerce/settings` for a more dynamic URL generation. - The interface `Props` has been renamed to `AttributesControlProps` for more explicit naming. - Removed the usage of `useState` and `useEffect` for selected attributes. Instead, `selectedAttributes` is now directly derived from `woocommerceAttributes`. - The CSS class `woocommerce-product-query-panel__external-link` was renamed to `wc-product-collection-panel__external-link` 3. Deleted the `product-collection/inspector-controls/constants.ts` file which was no longer necessary due to changes in product collection implementation. These changes contribute to codebase quality, improving readability and maintainability. * Address PR review comments This commit involves a significant refactoring of the default product query inside the 'product-collection/constants.ts' file. A new constant `DEFAULT_QUERY` has been defined and used to replace the previously hard-coded default query settings. This refactoring aids in code readability and future modifications. Changes also include adjustments in 'product-collection/inspector-controls' to enhance UI/UX. A new SCSS file 'editor.scss' has been created for custom styles related to the editor. Additions include: - Adding a class name `product-collection-inspector-toolspanel__filters` to ToolsPanel for additional styling. - The experimental property `__experimentalShowHowTo` is set to false for `FormTokenField` and `StockStatusControl`, to hide some additional information. In 'product-collection/inspector-controls/taxonomy-controls.tsx', the classname `product-collection-inspector__taxonomy-control` is added for improved CSS targeting. * Add wc-block-editor prefix to className * Add wc-block-editor- prefix with classNames * Handle duplicate taxonomy names in Taxonomy controls the taxonomy controls have been enhanced in the following ways: 1. Modified the BASE_QUERY object to include 'slug' in the '_fields' property. This will ensure that the 'slug' of the taxonomy term is fetched along with its 'id' and 'name'. 2. Added a 'slug' property to the Term type to store the 'slug' of each term. 3. Updated the useEffect hook inside the TaxonomyItem function to generate suggestions based on search results. The suggestions now include the 'slug' of a term if the term's name is not unique. This change will help users distinguish between terms with the same name but different slugs. * Remove isset() in if condition as it's unnecessary * Refactor TaxonomyItem component for better readability Following changes were made: 1. The useSelect hooks which were being used to fetch existing terms and search results have been moved into their own custom hooks named 'useExistingTerms' and 'useSearchResults' respectively. This simplifies the TaxonomyItem function's body and makes the hooks' purposes clearer. 2. The comments and props destructuring for the TaxonomyItem function have been moved up to make it easier to understand the function's purpose and the props it receives. 3. This refactor does not introduce any changes in functionality. It only changes how the code is organized and presented, which will make future development easier. * Handling for duplicate term names & other improvements This commit enhances the `TaxonomyControls` component within `product-collection` block by adding memoization and improving term uniqueness handling. Changes: 1. Imported `useMemo` from `@wordpress/element` for memoizing certain results. 2. `getTermIdByTermValue` function has been modified to use a `termIdToNameMap` (term ids as keys and term names as values). This provides a more efficient and direct mapping for term search. 3. Introduced `useTermIdToNameMap` function, which returns a `Map` where term ids are keys and term names are values. It handles duplicate term names by appending the term slug to the name, ensuring unique term names. 4. Updated the `useExistingTerms` and `useSearchResults` to include `taxonomy` in their dependency arrays for `useSelect` hook. This will force re-computation when `taxonomy` changes. 5. Changed `TaxonomyItem` from a function declaration to a const arrow function, consistent with the rest of the codebase. 6. Updated `onTermsChange` function in `TaxonomyItem` to accommodate the changes in `getTermIdByTermValue` and the introduction of `termIdToNameMap`. 7. Replaced `Set` with a standard array for storing new term IDs in `onTermsChange`. The `Set` was unnecessary as term IDs are unique by default. 8. Updated `TaxonomyItem`'s effects and rendering to work with `termIdToNameMap`, ensuring the displayed term names are unique. This update will result in more efficient term search and handling, and it will solve issues related to duplicate term names. * Restructure taxonomy controls in product collection block This commit restructures the taxonomy controls in the product collection block for improved clarity and maintainability. - The file `taxonomy-controls.tsx` has been deleted, and its functionality has been divided into two new files: `index.tsx` and `taxonomy-item.tsx`. - The `index.tsx` file contains the main TaxonomyControls component, which is responsible for displaying taxonomy-related options in the block's inspector controls. It includes a custom hook `useTaxonomies` that fetches and returns taxonomies associated with product post type. - The `taxonomy-item.tsx` file, on the other hand, contains a TaxonomyItem component that handles the rendering of individual taxonomy items. It also contains some utility functions for mapping term names and ids and fetching terms based on the search query. This refactor aims to improve code readability and separation of concerns, thus making future changes and maintenance easier. * Fix case insensitive search support for FormTokenField This change enhances the search functionality of the FormTokenField by introducing support for case insensitive search. This has been achieved by adding a lower-case version of the term name to the 'termNameToIdMap'. This is an important enhancement as it will make the search process more user-friendly and resilient to different casing inputs. Users will now be able to find the desired taxonomy term regardless of their input's case. * Refactor getTermIdByTermValue function and update newSuggestions mapping This commit does a couple of important things: 1. Reorders the definition of constants in `TaxonomyItemProps` for clarity. 2. Refactors the `getTermIdByTermValue` function. Instead of checking for an exact term name match in a convoluted manner, it now directly tries to fetch the `id` from the `searchTerm` if it is an object. If the `searchTerm` is not an object, the function tries to match it against the `termNameToIdMap` in both normal and lowercase forms. This simplification makes the function more readable and concise. 3. Updates the `newSuggestions` mapping in the `TaxonomyItem` component. It now has a fallback to `searchResult.name` if a term's name is not found in `termIdToNameMap`. This change ensures that even if the term's name is not in the map for some reason, we can still display a suggestion using the original name of the term. * Optimize term fetching and initial search state in TaxonomyItem This commit introduces a couple of improvements to the TaxonomyItem component. 1. The initial state of the 'search' state variable has been updated to 'undefined'. This change helps prevent unnecessary initial fetching of terms when the search input is empty. 2. Term fetching logic has been optimized to only enable term fetching when necessary: a) Fetching based on the search query is only enabled when 'search' is not 'undefined'. b) Fetching existing terms is only enabled when there are term IDs. 3. The block of code responsible for fetching existing terms and setting the current value has been moved upwards. This reordering of code does not change the functionality, but it groups together similar pieces of code, enhancing readability and maintainability. These optimizations make the component more efficient by reducing unnecessary requests and computations, and they improve the code organization. --------- Co-authored-by: Alexandre Lara <allexandrelara@gmail.com>
2023-06-02 10:01:29 +00:00
woocommerceOnSale: DEFAULT_QUERY.woocommerceOnSale,
woocommerceStockStatus: DEFAULT_QUERY.woocommerceStockStatus,
woocommerceAttributes: DEFAULT_QUERY.woocommerceAttributes,
woocommerceHandPickedProducts: DEFAULT_QUERY.woocommerceHandPickedProducts,
Product Collection: Add Taxonomy filters to sidebar settings (https://github.com/woocommerce/woocommerce-blocks/pull/9634) * Add columns control to product collection block editor settings - `InspectorControls` from './inspector-controls' is now imported in `edit.tsx` and used in the returned JSX of `Edit` function. - A new file `columns-control.tsx` is added under 'product-collection' block's 'inspector-controls' directory which exports a `ColumnsControl` component. This component uses `RangeControl` from '@wordpress/components' to control the number of columns in the product collection display layout when the layout type is 'flex'. - The types file (`types.ts`) for 'product-collection' block is updated. The `Attributes` interface is renamed to `ProductCollectionAttributes` and the `ProductCollectionContext` interface is removed. The `ProductCollectionAttributes` now includes 'queryContext', 'templateSlug', and 'displayLayout' properties. * Refactor: Simplify Fallback Return in ColumnsControl Component This commit simplifies the fallback return value of the ColumnsControl component. Instead of returning an empty fragment (<> </>), it now returns null when the condition isn't met. This change improves readability and aligns with best practices for conditional rendering in React. * Feature: Add 'Order By' Control to Product Collection Inspector This commit adds a new 'Order By' control to the product collection inspector. The control allows users to specify the order of products in a collection by various attributes such as title and date. To support this, a new component 'OrderByControl' has been created and included in the product collection inspector. Additionally, the types for 'order' and 'orderBy' attributes have been updated and exported for reuse. * Add more options to OrderBy type * Add orderby handling on frontend & editor The main changes include: 1. Added a new property 'isProductCollectionBlock' in the block.json to denote if a block is a product collection block. 2. In the ProductCollection PHP class, a new initialization function has been defined to hook into the WordPress lifecycle, register the block, and update the query based on this block. 3. Added methods to manage query parameters for both frontend rendering and the Editor. 4. Expanded allowed 'collection_params' for the REST API to include custom 'orderby' values. 5. Defined a function to build the query based on block attributes, filters, and global WP_Query. 6. Created utility functions to handle complex query operations such as merging queries, handling custom sort values, and merging arrays recursively. These improvements allow for more flexible and robust handling of product collections in both the front-end display and the WordPress editor. It also extends support for custom 'orderby' values in the REST API, which allows for more advanced sorting options in product collections. * Add 'on sale' filter and enhance settings management in product collection block This commit introduces several changes to the product collection block. - First, it adds a new 'on sale' filter that can be used to display only the products that are currently on sale. - It also refactors the settings management in the product collection block to use the experimental ToolsPanel component from WordPress, which provides a more flexible and intuitive way to manage block settings. - It moves the 'Columns' control into the ToolsPanel, along with the 'Order by' control. - A new utility function `setQueryAttribute` is introduced to simplify setting nested query parameters. - The structure of the `ProductCollectionAttributes` and `ProductCollectionQuery` types have been adjusted to accommodate the changes. - Finally, it makes corresponding changes in the PHP part to handle the new 'on sale' query parameter. This should enhance the flexibility and user-friendliness of the product collection block. * Add stock status filter to WooCommerce product collection block This commit introduces a stock status filter to the WooCommerce product collection block. The changes include: 1. Added the ability to filter products based on their stock status within the 'product-collection' block. A new stock status control is created within the inspector-controls of the block. 2. A new 'get_stock_status_query' function is introduced in 'ProductCollection.php' which returns a query for products depending on their stock status. Please note that the stock status filter will only appear in the experimental build for now. * Refactor Stock Status control of Product Collection block This commit refactors the Stock Status control. The changes aim to improve the code organization and make the behavior of the component more explicit. The key modifications are: 1. Moved stock status related constants and functions from `inspector-controls/utils.tsx` to `inspector-controls/constants.ts`. This is done to ensure that all constants and similar utility functions are organized in one place. 2. Updated `product-collection/index.tsx` to import `getDefaultStockStatuses` from `inspector-controls/constants` instead of `inspector-controls/utils`. 3. Updated `stock-status-control.tsx` to determine whether the stock status has value or not by comparing with the default stock statuses using `fastDeepEqual`. If the stock status control is deselected, it resets the stock status to the default statuses. These changes do not introduce any new functionalities, but improve the readability and maintainability of the code. * Add keyword search control to Product Collection block This commit introduces a keyword search functionality to the Product Collection block. The update is aimed to provide users with more flexibility and precision in product collection queries. Key changes: 1. Introduced a new file `keyword-control.tsx` that creates a Keyword Control component. This component includes a TextControl field that allows inputting a search keyword. The keyword search is debounced to prevent unnecessary queries during input and updates the block's attributes accordingly. 2. Modified `inspector-controls/index.tsx` to include the KeywordControl in the ToolsPanel for the block's filters. 3. Adjusted `ProductCollection.php` to include the keyword search in the product query array. With these changes, users can now search for products by keyword in the Product Collection block. * Add product attributes filter control to ProductCollection block - This commit introduces the ability to filter products by attributes in ProductCollection block. - A new `woocommerceAttributes` key was added to the `block.json` file and the `ProductCollectionQuery` type. Also, a new file `attributes-control.tsx` was created, providing the UI component for the attribute filter control in the editor. - In addition, updates were made to the `ProductCollection.php` file in the backend to support filtering products by attributes, and the tax query was updated to include attribute queries. - Lastly, the `ProductCollectionInspectorControls` was updated to include the `AttributesControl` component, thus enabling users to filter products by attributes in the block editor."` * remove unused import of getDefaultStockStatuses * Delete a duplicate file * Remove console log * Add taxonomies control to Product collection block The primary changes include: 1. `taxQuery` field in the `ProductCollectionAttributes` was changed from a string to an object in `assets/js/blocks/product-collection/types.ts` and `assets/js/blocks/product-collection/constants.ts`, accommodating the ability to query products by taxonomy terms. 2. `assets/js/blocks/product-collection/inspector-controls/utils.tsx` was moved to `assets/js/blocks/product-collection/utils.tsx` to make it available for broader use. 3. New component `TaxonomyControls` was created in `assets/js/blocks/product-collection/inspector-controls/taxonomy-controls.tsx`, which is included in `assets/js/blocks/product-collection/inspector-controls/index.tsx`. This new control allows users to filter products in the block by their taxonomy terms. 4. Updated the block's inspector controls in `assets/js/blocks/product-collection/inspector-controls/index.tsx` to use the new `TaxonomyControls` component. Please note that the TaxonomyControls component uses experimental features of WordPress's FormTokenField. As a result, a comment has been added to disable eslint warnings regarding the use of experimental APIs. * Address PR feedback & other improvements 1. Added `woocommerceAttributes` to `DEFAULT_FILTERS` in the `product-collection/constants.ts` file to fix `reset all` button issue. 2. Refactored `attributes-control.tsx` to make it more maintainable: - The constant `EDIT_ATTRIBUTES_URL` now uses `ADMIN_URL` from `@woocommerce/settings` for a more dynamic URL generation. - The interface `Props` has been renamed to `AttributesControlProps` for more explicit naming. - Removed the usage of `useState` and `useEffect` for selected attributes. Instead, `selectedAttributes` is now directly derived from `woocommerceAttributes`. - The CSS class `woocommerce-product-query-panel__external-link` was renamed to `wc-product-collection-panel__external-link` 3. Deleted the `product-collection/inspector-controls/constants.ts` file which was no longer necessary due to changes in product collection implementation. These changes contribute to codebase quality, improving readability and maintainability. * Address PR review comments This commit involves a significant refactoring of the default product query inside the 'product-collection/constants.ts' file. A new constant `DEFAULT_QUERY` has been defined and used to replace the previously hard-coded default query settings. This refactoring aids in code readability and future modifications. Changes also include adjustments in 'product-collection/inspector-controls' to enhance UI/UX. A new SCSS file 'editor.scss' has been created for custom styles related to the editor. Additions include: - Adding a class name `product-collection-inspector-toolspanel__filters` to ToolsPanel for additional styling. - The experimental property `__experimentalShowHowTo` is set to false for `FormTokenField` and `StockStatusControl`, to hide some additional information. In 'product-collection/inspector-controls/taxonomy-controls.tsx', the classname `product-collection-inspector__taxonomy-control` is added for improved CSS targeting. * Add wc-block-editor prefix to className * Add wc-block-editor- prefix with classNames * Handle duplicate taxonomy names in Taxonomy controls the taxonomy controls have been enhanced in the following ways: 1. Modified the BASE_QUERY object to include 'slug' in the '_fields' property. This will ensure that the 'slug' of the taxonomy term is fetched along with its 'id' and 'name'. 2. Added a 'slug' property to the Term type to store the 'slug' of each term. 3. Updated the useEffect hook inside the TaxonomyItem function to generate suggestions based on search results. The suggestions now include the 'slug' of a term if the term's name is not unique. This change will help users distinguish between terms with the same name but different slugs. * Remove isset() in if condition as it's unnecessary * Refactor TaxonomyItem component for better readability Following changes were made: 1. The useSelect hooks which were being used to fetch existing terms and search results have been moved into their own custom hooks named 'useExistingTerms' and 'useSearchResults' respectively. This simplifies the TaxonomyItem function's body and makes the hooks' purposes clearer. 2. The comments and props destructuring for the TaxonomyItem function have been moved up to make it easier to understand the function's purpose and the props it receives. 3. This refactor does not introduce any changes in functionality. It only changes how the code is organized and presented, which will make future development easier. * Handling for duplicate term names & other improvements This commit enhances the `TaxonomyControls` component within `product-collection` block by adding memoization and improving term uniqueness handling. Changes: 1. Imported `useMemo` from `@wordpress/element` for memoizing certain results. 2. `getTermIdByTermValue` function has been modified to use a `termIdToNameMap` (term ids as keys and term names as values). This provides a more efficient and direct mapping for term search. 3. Introduced `useTermIdToNameMap` function, which returns a `Map` where term ids are keys and term names are values. It handles duplicate term names by appending the term slug to the name, ensuring unique term names. 4. Updated the `useExistingTerms` and `useSearchResults` to include `taxonomy` in their dependency arrays for `useSelect` hook. This will force re-computation when `taxonomy` changes. 5. Changed `TaxonomyItem` from a function declaration to a const arrow function, consistent with the rest of the codebase. 6. Updated `onTermsChange` function in `TaxonomyItem` to accommodate the changes in `getTermIdByTermValue` and the introduction of `termIdToNameMap`. 7. Replaced `Set` with a standard array for storing new term IDs in `onTermsChange`. The `Set` was unnecessary as term IDs are unique by default. 8. Updated `TaxonomyItem`'s effects and rendering to work with `termIdToNameMap`, ensuring the displayed term names are unique. This update will result in more efficient term search and handling, and it will solve issues related to duplicate term names. * Restructure taxonomy controls in product collection block This commit restructures the taxonomy controls in the product collection block for improved clarity and maintainability. - The file `taxonomy-controls.tsx` has been deleted, and its functionality has been divided into two new files: `index.tsx` and `taxonomy-item.tsx`. - The `index.tsx` file contains the main TaxonomyControls component, which is responsible for displaying taxonomy-related options in the block's inspector controls. It includes a custom hook `useTaxonomies` that fetches and returns taxonomies associated with product post type. - The `taxonomy-item.tsx` file, on the other hand, contains a TaxonomyItem component that handles the rendering of individual taxonomy items. It also contains some utility functions for mapping term names and ids and fetching terms based on the search query. This refactor aims to improve code readability and separation of concerns, thus making future changes and maintenance easier. * Fix case insensitive search support for FormTokenField This change enhances the search functionality of the FormTokenField by introducing support for case insensitive search. This has been achieved by adding a lower-case version of the term name to the 'termNameToIdMap'. This is an important enhancement as it will make the search process more user-friendly and resilient to different casing inputs. Users will now be able to find the desired taxonomy term regardless of their input's case. * Refactor getTermIdByTermValue function and update newSuggestions mapping This commit does a couple of important things: 1. Reorders the definition of constants in `TaxonomyItemProps` for clarity. 2. Refactors the `getTermIdByTermValue` function. Instead of checking for an exact term name match in a convoluted manner, it now directly tries to fetch the `id` from the `searchTerm` if it is an object. If the `searchTerm` is not an object, the function tries to match it against the `termNameToIdMap` in both normal and lowercase forms. This simplification makes the function more readable and concise. 3. Updates the `newSuggestions` mapping in the `TaxonomyItem` component. It now has a fallback to `searchResult.name` if a term's name is not found in `termIdToNameMap`. This change ensures that even if the term's name is not in the map for some reason, we can still display a suggestion using the original name of the term. * Optimize term fetching and initial search state in TaxonomyItem This commit introduces a couple of improvements to the TaxonomyItem component. 1. The initial state of the 'search' state variable has been updated to 'undefined'. This change helps prevent unnecessary initial fetching of terms when the search input is empty. 2. Term fetching logic has been optimized to only enable term fetching when necessary: a) Fetching based on the search query is only enabled when 'search' is not 'undefined'. b) Fetching existing terms is only enabled when there are term IDs. 3. The block of code responsible for fetching existing terms and setting the current value has been moved upwards. This reordering of code does not change the functionality, but it groups together similar pieces of code, enhancing readability and maintainability. These optimizations make the component more efficient by reducing unnecessary requests and computations, and they improve the code organization. --------- Co-authored-by: Alexandre Lara <allexandrelara@gmail.com>
2023-06-02 10:01:29 +00:00
taxQuery: DEFAULT_QUERY.taxQuery,
Product Collection: Add support for filtering products by featured status (https://github.com/woocommerce/woocommerce-blocks/pull/11522) * Add support for filtering products by featured status - Added `featured` attribute to `ProductCollectionQuery` type to enable filtering by featured status. - Implemented `FeaturedProductsControl` to provide a toggle option in the inspector controls. - Integrated `FeaturedProductsControl` into `ProductCollectionInspectorControls`. - Added `get_featured_query` function in `ProductCollection` class to generate query for fetching featured products. - Updated existing functions and queries in `ProductCollection` class to support featured products filtering. * Revert changes to composer.lock * Refactor handling of 'featured' parameter This commit makes the handling of the 'featured' parameter consistent in the ProductCollection class. Previously, the 'featured' parameter was being type-casted to boolean, which was not necessary and could lead to incorrect results. Now, the 'featured' parameter is used directly without type-casting, and the check for 'featured' products in the get_featured_query method has been updated accordingly. This ensures that the 'featured' parameter is handled consistently and correctly throughout the class. * Handle undefined 'featured' index This commit adds null coalescing operator to handle the case when 'featured' index is not set in the $query array. This prevents potential PHP notices or errors that may arise when trying to access an undefined index.
2023-11-08 10:07:32 +00:00
featured: DEFAULT_QUERY.featured,
timeFrame: DEFAULT_QUERY.timeFrame,
priceRange: DEFAULT_QUERY.priceRange,
Product Collection: Add stock status filter (https://github.com/woocommerce/woocommerce-blocks/pull/9580) * Add columns control to product collection block editor settings - `InspectorControls` from './inspector-controls' is now imported in `edit.tsx` and used in the returned JSX of `Edit` function. - A new file `columns-control.tsx` is added under 'product-collection' block's 'inspector-controls' directory which exports a `ColumnsControl` component. This component uses `RangeControl` from '@wordpress/components' to control the number of columns in the product collection display layout when the layout type is 'flex'. - The types file (`types.ts`) for 'product-collection' block is updated. The `Attributes` interface is renamed to `ProductCollectionAttributes` and the `ProductCollectionContext` interface is removed. The `ProductCollectionAttributes` now includes 'queryContext', 'templateSlug', and 'displayLayout' properties. * Refactor: Simplify Fallback Return in ColumnsControl Component This commit simplifies the fallback return value of the ColumnsControl component. Instead of returning an empty fragment (<> </>), it now returns null when the condition isn't met. This change improves readability and aligns with best practices for conditional rendering in React. * Feature: Add 'Order By' Control to Product Collection Inspector This commit adds a new 'Order By' control to the product collection inspector. The control allows users to specify the order of products in a collection by various attributes such as title and date. To support this, a new component 'OrderByControl' has been created and included in the product collection inspector. Additionally, the types for 'order' and 'orderBy' attributes have been updated and exported for reuse. * Add more options to OrderBy type * Add orderby handling on frontend & editor The main changes include: 1. Added a new property 'isProductCollectionBlock' in the block.json to denote if a block is a product collection block. 2. In the ProductCollection PHP class, a new initialization function has been defined to hook into the WordPress lifecycle, register the block, and update the query based on this block. 3. Added methods to manage query parameters for both frontend rendering and the Editor. 4. Expanded allowed 'collection_params' for the REST API to include custom 'orderby' values. 5. Defined a function to build the query based on block attributes, filters, and global WP_Query. 6. Created utility functions to handle complex query operations such as merging queries, handling custom sort values, and merging arrays recursively. These improvements allow for more flexible and robust handling of product collections in both the front-end display and the WordPress editor. It also extends support for custom 'orderby' values in the REST API, which allows for more advanced sorting options in product collections. * Add 'on sale' filter and enhance settings management in product collection block This commit introduces several changes to the product collection block. - First, it adds a new 'on sale' filter that can be used to display only the products that are currently on sale. - It also refactors the settings management in the product collection block to use the experimental ToolsPanel component from WordPress, which provides a more flexible and intuitive way to manage block settings. - It moves the 'Columns' control into the ToolsPanel, along with the 'Order by' control. - A new utility function `setQueryAttribute` is introduced to simplify setting nested query parameters. - The structure of the `ProductCollectionAttributes` and `ProductCollectionQuery` types have been adjusted to accommodate the changes. - Finally, it makes corresponding changes in the PHP part to handle the new 'on sale' query parameter. This should enhance the flexibility and user-friendliness of the product collection block. * Add stock status filter to WooCommerce product collection block This commit introduces a stock status filter to the WooCommerce product collection block. The changes include: 1. Added the ability to filter products based on their stock status within the 'product-collection' block. A new stock status control is created within the inspector-controls of the block. 2. A new 'get_stock_status_query' function is introduced in 'ProductCollection.php' which returns a query for products depending on their stock status. Please note that the stock status filter will only appear in the experimental build for now. * Refactor Stock Status control of Product Collection block This commit refactors the Stock Status control. The changes aim to improve the code organization and make the behavior of the component more explicit. The key modifications are: 1. Moved stock status related constants and functions from `inspector-controls/utils.tsx` to `inspector-controls/constants.ts`. This is done to ensure that all constants and similar utility functions are organized in one place. 2. Updated `product-collection/index.tsx` to import `getDefaultStockStatuses` from `inspector-controls/constants` instead of `inspector-controls/utils`. 3. Updated `stock-status-control.tsx` to determine whether the stock status has value or not by comparing with the default stock statuses using `fastDeepEqual`. If the stock status control is deselected, it resets the stock status to the default statuses. These changes do not introduce any new functionalities, but improve the readability and maintainability of the code. * Fix: Default values of attributes not saving as serialized block comment This was happening because of this issue: https://github.com/WordPress/gutenberg/issues/7342 Therefore, I had to use `useEffect` to set the default values of the attributes. Here is the list of changes I made: 1. Removed default values from `block.json` for `query`, `tagName`, and `displayLayout`. 2. Moved the default values to `constants.ts` and created a new object `DEFAULT_ATTRIBUTES` to store them. 3. Relocated `constants.ts` from `inspector-controls` to the parent directory. 4. Refactored `edit.tsx` to use `DEFAULT_ATTRIBUTES` from `constants.ts` to set default attributes using `useEffect`. 5. Removed the attributes assignment from `registerBlockType` in `index.tsx`. 6. Updated `columns-control.tsx`, `index.tsx`, `order-by-control.tsx`, and `stock-status-control.tsx` to import from the relocated `constants.ts`. 7. Updated `ProductCollectionAttributes` and `ProductCollectionQuery` in `types.ts` to include `tagName` and `isProductCollectionBlock` respectively. 8. Modified `ProductCollection.php` to match the updated `orderBy` key in the query parameter. This refactor enhances the readability of the code and reduces duplication by keeping all constants and default values in one place. * Replace usage of 'statii' with 'statuses' in stock status handling This commit replaces all instances of 'statii' with the correct term 'statuses' in the context of handling stock status. This change affects three files: 1. `assets/js/blocks/product-collection/inspector-controls/stock-status-control.tsx` - The term is corrected in a comment block. 2. `assets/js/blocks/product-collection/types.ts` - Updated the name of a variable in the `ProductCollectionQuery` interface. 3. `src/BlockTypes/ProductCollection.php` - Here, the term is replaced in several locations including variable names, comments and the method `get_stock_status_query`. This commit helps improve code readability and consistency across the repository.
2023-05-26 11:44:37 +00:00
};
/**
* Default inner block templates for the product collection block.
* Exported for use in different collections, e.g., 'New Arrivals' collection.
*/
export const INNER_BLOCKS_PRODUCT_TEMPLATE: InnerBlockTemplate = [
'woocommerce/product-template',
{},
[
[
'woocommerce/product-image',
{
imageSizing: ImageSizing.THUMBNAIL,
},
],
[
'core/post-title',
{
textAlign: 'center',
level: 3,
fontSize: 'medium',
style: {
spacing: {
margin: {
bottom: '0.75rem',
top: '0',
},
},
},
isLink: true,
__woocommerceNamespace: PRODUCT_TITLE_ID,
},
],
[
'woocommerce/product-price',
{
textAlign: 'center',
fontSize: 'small',
},
],
[
'woocommerce/product-button',
{
textAlign: 'center',
fontSize: 'small',
},
],
],
];
export const coreQueryPaginationBlockName = 'core/query-pagination';
export const INNER_BLOCKS_PAGINATION_TEMPLATE: InnerBlockTemplate = [
coreQueryPaginationBlockName,
{
layout: {
type: 'flex',
justifyContent: 'center',
},
},
];
export const INNER_BLOCKS_NO_RESULTS_TEMPLATE: InnerBlockTemplate = [
'woocommerce/product-collection-no-results',
];
export const INNER_BLOCKS_TEMPLATE: InnerBlockTemplate[] = [
INNER_BLOCKS_PRODUCT_TEMPLATE,
INNER_BLOCKS_PAGINATION_TEMPLATE,
INNER_BLOCKS_NO_RESULTS_TEMPLATE,
];
export const getDefaultProductCollection = () =>
createBlock(
blockJson.name,
{
...DEFAULT_ATTRIBUTES,
query: {
...DEFAULT_ATTRIBUTES.query,
inherit: getDefaultValueOfInheritQueryFromTemplate(),
},
},
createBlocksFromInnerBlocksTemplate( INNER_BLOCKS_TEMPLATE )
);