Skip to content
This repository has been archived by the owner on Feb 23, 2024. It is now read-only.

Add Stock Status setting to Product Query Block #7397

Merged
merged 9 commits into from
Oct 27, 2022
27 changes: 26 additions & 1 deletion assets/js/blocks/product-query/constants.ts
Original file line number Diff line number Diff line change
@@ -1,22 +1,44 @@
/**
* External dependencies
*/
import { getSetting } from '@woocommerce/settings';
import type { InnerBlockTemplate } from '@wordpress/blocks';

/**
* Internal dependencies
*/
import { QueryBlockAttributes } from './types';

/**
* Returns an object without a key.
*/
function objectOmit< T, K extends keyof T >( obj: T, key: K ) {
const { [ key ]: omit, ...rest } = obj;

return rest;
}

export const QUERY_LOOP_ID = 'core/query';

export const DEFAULT_CORE_ALLOWED_CONTROLS = [ 'order', 'taxQuery', 'search' ];

export const ALL_PRODUCT_QUERY_CONTROLS = [ 'onSale' ];
export const ALL_PRODUCT_QUERY_CONTROLS = [ 'onSale', 'stockStatus' ];

export const DEFAULT_ALLOWED_CONTROLS = [
...DEFAULT_CORE_ALLOWED_CONTROLS,
...ALL_PRODUCT_QUERY_CONTROLS,
];

export const STOCK_STATUS_OPTIONS = getSetting< Record< string, string > >(
'stockStatusOptions',
[]
);

const GLOBAL_HIDE_OUT_OF_STOCK = getSetting< boolean >(
'hideOutOfStockItems',
false
);

export const QUERY_DEFAULT_ATTRIBUTES: QueryBlockAttributes = {
allowedControls: DEFAULT_ALLOWED_CONTROLS,
displayLayout: {
Expand All @@ -35,6 +57,9 @@ export const QUERY_DEFAULT_ATTRIBUTES: QueryBlockAttributes = {
exclude: [],
sticky: '',
inherit: false,
__woocommerceStockStatus: GLOBAL_HIDE_OUT_OF_STOCK
? Object.keys( objectOmit( STOCK_STATUS_OPTIONS, 'outofstock' ) )
: Object.keys( STOCK_STATUS_OPTIONS ),
},
};

Expand Down
3 changes: 2 additions & 1 deletion assets/js/blocks/product-query/index.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,7 @@ import { addFilter } from '@wordpress/hooks';
/**
* Internal dependencies
*/
import { QUERY_LOOP_ID } from './constants';
import './inspector-controls';
import './variations/product-query';
import './variations/products-on-sale';
Expand All @@ -15,7 +16,7 @@ function registerProductQueryVariationAttributes(
props: Block,
blockName: string
) {
if ( blockName === 'core/query' ) {
if ( blockName === QUERY_LOOP_ID ) {
// Gracefully handle if settings.attributes is undefined.
// eslint-disable-next-line @typescript-eslint/ban-ts-comment
// @ts-ignore -- We need this because `attributes` is marked as `readonly`
Expand Down
177 changes: 151 additions & 26 deletions assets/js/blocks/product-query/inspector-controls.tsx
Original file line number Diff line number Diff line change
@@ -1,61 +1,186 @@
/**
* External dependencies
*/
import { ElementType } from 'react';
import { __ } from '@wordpress/i18n';
import { InspectorControls } from '@wordpress/block-editor';
import { PanelBody, ToggleControl } from '@wordpress/components';
import { useSelect } from '@wordpress/data';
import { addFilter } from '@wordpress/hooks';
import { EditorBlock } from '@woocommerce/types';
import { ElementType } from 'react';
import {
FormTokenField,
ToggleControl,
// eslint-disable-next-line @wordpress/no-unsafe-wp-apis
__experimentalToolsPanel as ToolsPanel,
// eslint-disable-next-line @wordpress/no-unsafe-wp-apis
__experimentalToolsPanelItem as ToolsPanelItem,
} from '@wordpress/components';

/**
* Internal dependencies
*/
import { ProductQueryBlock } from './types';
import {
ProductQueryArguments,
ProductQueryBlock,
QueryBlockAttributes,
} from './types';
import {
isWooQueryBlockVariation,
setCustomQueryAttribute,
useAllowedControls,
} from './utils';
import {
ALL_PRODUCT_QUERY_CONTROLS,
QUERY_LOOP_ID,
STOCK_STATUS_OPTIONS,
} from './constants';

const NAMESPACED_CONTROLS = ALL_PRODUCT_QUERY_CONTROLS.map(
( id ) =>
`__woocommerce${ id[ 0 ].toUpperCase() }${ id.slice(
1
) }` as keyof ProductQueryArguments
);

function useDefaultWooQueryParamsForVariation(
variationName: string | undefined
): Partial< ProductQueryArguments > {
const variationAttributes: QueryBlockAttributes = useSelect(
( select ) =>
select( 'core/blocks' )
.getBlockVariations( QUERY_LOOP_ID )
.find(
( variation: ProductQueryBlock ) =>
variation.name === variationName
)?.attributes
);

return variationAttributes
? Object.assign(
{},
...NAMESPACED_CONTROLS.map( ( key ) => ( {
[ key ]: variationAttributes.query[ key ],
} ) )
)
: {};
}

/**
* Gets the id of a specific stock status from its text label
*
* In theory, we could use a `saveTransform` function on the
* `FormFieldToken` component to do the conversion. However, plugins
* can add custom stock statii which don't conform to our naming
* conventions.
*/
function getStockStatusIdByLabel( statusLabel: FormTokenField.Value ) {
const label =
typeof statusLabel === 'string' ? statusLabel : statusLabel.value;

return Object.entries( STOCK_STATUS_OPTIONS ).find(
( [ , value ] ) => value === label
)?.[ 0 ];
}

export const INSPECTOR_CONTROLS = {
onSale: ( props: ProductQueryBlock ) => (
<ToggleControl
label={ __(
'Show only products on sale',
'woo-gutenberg-products-block'
) }
checked={ props.attributes.query.__woocommerceOnSale || false }
onChange={ ( __woocommerceOnSale ) => {
setCustomQueryAttribute( props, { __woocommerceOnSale } );
} }
/>
),
onSale: ( props: ProductQueryBlock ) => {
const { query } = props.attributes;

return (
<ToolsPanelItem
label={ __( 'Sale status', 'woo-gutenberg-products-block' ) }
hasValue={ () => query.__woocommerceOnSale }
>
<ToggleControl
label={ __(
'Show only products on sale',
'woo-gutenberg-products-block'
) }
checked={ query.__woocommerceOnSale || false }
onChange={ ( __woocommerceOnSale ) => {
setCustomQueryAttribute( props, {
__woocommerceOnSale,
} );
} }
/>
</ToolsPanelItem>
);
},
stockStatus: ( props: ProductQueryBlock ) => {
const { query } = props.attributes;

return (
<ToolsPanelItem
label={ __( 'Stock status', 'woo-gutenberg-products-block' ) }
hasValue={ () => query.__woocommerceStockStatus }
>
<FormTokenField
label={ __(
'Stock status',
'woo-gutenberg-products-block'
) }
onChange={ ( statusLabels ) => {
const __woocommerceStockStatus = statusLabels
.map( getStockStatusIdByLabel )
.filter( Boolean ) as string[];

setCustomQueryAttribute( props, {
__woocommerceStockStatus,
} );
} }
suggestions={ Object.values( STOCK_STATUS_OPTIONS ) }
validateInput={ ( value: string ) =>
Object.values( STOCK_STATUS_OPTIONS ).includes( value )
}
value={
query?.__woocommerceStockStatus?.map(
( key ) => STOCK_STATUS_OPTIONS[ key ]
) || []
}
__experimentalExpandOnFocus={ true }
/>
</ToolsPanelItem>
);
},
};

export const withProductQueryControls =
< T extends EditorBlock< T > >( BlockEdit: ElementType ) =>
( props: ProductQueryBlock ) => {
const allowedControls = useAllowedControls( props.attributes );

const availableControls = Object.entries( INSPECTOR_CONTROLS ).filter(
( [ key ] ) => allowedControls?.includes( key )
const defaultWooQueryParams = useDefaultWooQueryParamsForVariation(
props.attributes.namespace
);
return isWooQueryBlockVariation( props ) &&
availableControls.length > 0 ? (

return isWooQueryBlockVariation( props ) ? (
<>
<BlockEdit { ...props } />
<InspectorControls>
<PanelBody>
{ availableControls.map( ( [ key, Control ] ) => (
<Control key={ key } { ...props } />
) ) }
</PanelBody>
<ToolsPanel
class="woocommerce-product-query-toolspanel"
label={ __(
'Product filters',
'woo-gutenberg-products-block'
) }
resetAll={ () => {
setCustomQueryAttribute(
props,
defaultWooQueryParams
);
} }
>
{ Object.entries( INSPECTOR_CONTROLS ).map(
( [ key, Control ] ) =>
allowedControls?.includes( key ) ? (
<Control { ...props } />
) : null
) }
</ToolsPanel>
</InspectorControls>
</>
) : (
<BlockEdit { ...props } />
);
};

addFilter( 'editor.BlockEdit', 'core/query', withProductQueryControls );
addFilter( 'editor.BlockEdit', QUERY_LOOP_ID, withProductQueryControls );
39 changes: 22 additions & 17 deletions assets/js/blocks/product-query/types.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,11 @@
*/
import type { EditorBlock } from '@woocommerce/types';

// The interface below disables the forbidden underscores
// naming convention because we are namespacing our
// custom attributes inside a core block. Prefixing with underscores
// will help signify our intentions.
/* eslint-disable @typescript-eslint/naming-convention */
export interface ProductQueryArguments {
/**
* Display only products on sale.
Expand All @@ -27,27 +32,27 @@ export interface ProductQueryArguments {
* )
* ```
*/
// Disabling naming convention because we are namespacing our
// custom attributes inside a core block. Prefixing with underscores
// will help signify our intentions.
// eslint-disable-next-line @typescript-eslint/naming-convention
__woocommerceOnSale?: boolean;
}

export type ProductQueryBlock = EditorBlock< QueryBlockAttributes >;

export interface ProductQueryAttributes {
/**
* An array of controls to disable in the inspector.
* Filter products by their stock status.
*
* @example `[ 'stockStatus' ]` will not render the dropdown for stock status.
*/
disabledInspectorControls?: string[];
/**
* Query attributes that define which products will be fetched.
* Will generate the following `meta_query`:
*
* ```
* array(
* 'key' => '_stock_status',
* 'value' => (array) $stock_statii,
* 'compare' => 'IN',
* ),
* ```
*/
query?: ProductQueryArguments;
__woocommerceStockStatus?: string[];
}
/* eslint-enable */

export type ProductQueryBlock = EditorBlock< QueryBlockAttributes >;

export type ProductQueryBlockQuery = QueryBlockQuery & ProductQueryArguments;

export interface QueryBlockAttributes {
allowedControls?: string[];
Expand All @@ -56,7 +61,7 @@ export interface QueryBlockAttributes {
columns?: number;
};
namespace?: string;
query: QueryBlockQuery & ProductQueryArguments;
query: ProductQueryBlockQuery;
}

export interface QueryBlockQuery {
Expand Down
5 changes: 3 additions & 2 deletions assets/js/blocks/product-query/utils.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,7 @@ import { store as WP_BLOCKS_STORE } from '@wordpress/blocks';
/**
* Internal dependencies
*/
import { QUERY_LOOP_ID } from './constants';
import {
ProductQueryArguments,
ProductQueryBlock,
Expand All @@ -29,7 +30,7 @@ export function ArrayXOR< T extends Array< unknown > >( a: T, b: T ) {
*/
export function isWooQueryBlockVariation( block: ProductQueryBlock ) {
return (
block.name === 'core/query' &&
block.name === QUERY_LOOP_ID &&
Object.values( QueryVariation ).includes(
block.attributes.namespace as QueryVariation
)
Expand Down Expand Up @@ -71,7 +72,7 @@ export function useAllowedControls(
return useSelect(
( select ) =>
select( WP_BLOCKS_STORE ).getActiveBlockVariation(
'core/query',
QUERY_LOOP_ID,
attributes
)?.allowedControls,

Expand Down
3 changes: 2 additions & 1 deletion assets/js/blocks/product-query/variations/product-query.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -14,12 +14,13 @@ import {
DEFAULT_ALLOWED_CONTROLS,
INNER_BLOCKS_TEMPLATE,
QUERY_DEFAULT_ATTRIBUTES,
QUERY_LOOP_ID,
} from '../constants';

const VARIATION_NAME = 'woocommerce/product-query';

if ( isExperimentalBuild() ) {
registerBlockVariation( 'core/query', {
registerBlockVariation( QUERY_LOOP_ID, {
name: VARIATION_NAME,
title: __( 'Product Query', 'woo-gutenberg-products-block' ),
isActive: ( blockAttributes ) =>
Expand Down
Loading