woocommerce/plugins/woocommerce-blocks/assets/js/blocks/classic-shortcode/index.tsx

304 lines
7.7 KiB
TypeScript
Raw Normal View History

Refactor Cart and Checkout Page Templates (https://github.com/woocommerce/woocommerce-blocks/pull/10773) * Rename checkout template slug * Remove redirect and custom title * Classic shortcode block for checkout * Empty title * WIP placeholder * Change blockified template * Prefix cart and checkout templates with "Page: " * Template migration routine * Apply same treatment to cart template * Notices * Update placeholder text * Classic shortcodes block * Page content wrapper for templates * Update default * Do not save attributes * Update templates * Remove cart classic template * Reverted endpoints for Cart & Checkout templates. This reverts PR 9406 * Migrate page content wrapper. * Removed useless method arg. Minor tweaks. * Skip migration if the theme has a template file for this page. * Removed impossible condition. * Migrate page content wrapper. * Remove TemplateNotice in favour of DefaultNotice * Documentation links in shortcode placeholder * Hide cart and checkout page selector when using block themes * Unused var * Add tests for template changes * Revert changes to classic-template * Allow frontend redirect * Unused file * Bump version for updater * Support x template naming as well as page-x * Need to add item to cart to test checkout * Fix header test by fixing utility for adding to cart * Remove permalink tests * Click body * Wait for content to finish loading * Wait for add to cart response when adding to cart without item name * Wait for save before visiting frontend * Set content instead of inserting block * Perform test in site editor rather than page editor * Prevent notice to set the default cart/checkout page from showing on the site editor. --------- Co-authored-by: Paulo Arromba <17236129+wavvves@users.noreply.github.com> Co-authored-by: Thomas Roberts <thomas.roberts@automattic.com>
2023-09-19 09:58:18 +00:00
/**
* External dependencies
*/
import {
BlockInstance,
createBlock,
registerBlockType,
} from '@wordpress/blocks';
import type { BlockEditProps } from '@wordpress/blocks';
import { WC_BLOCKS_IMAGE_URL } from '@woocommerce/block-settings';
import {
useBlockProps,
BlockPreview,
store as blockEditorStore,
} from '@wordpress/block-editor';
import {
Button,
Placeholder,
Popover,
ExternalLink,
} from '@wordpress/components';
import { __ } from '@wordpress/i18n';
import { box, Icon } from '@wordpress/icons';
import { useDispatch, useSelect } from '@wordpress/data';
import { useState, createInterpolateElement } from '@wordpress/element';
import { store as noticesStore } from '@wordpress/notices';
import { woo } from '@woocommerce/icons';
/**
* Internal dependencies
*/
import './editor.scss';
import './style.scss';
import { TEMPLATES, TYPES } from './constants';
import { getTemplateDetailsBySlug } from './utils';
import * as blockifiedCheckout from './checkout';
import * as blockifiedCart from './cart';
import type { BlockifiedTemplateConfig } from './types';
type Attributes = {
shortcode: string;
align: string;
};
const blockifiedFallbackConfig = {
isConversionPossible: () => false,
getBlockifiedTemplate: () => [],
getDescription: () => '',
onClickCallback: () => void 0,
};
const conversionConfig: { [ key: string ]: BlockifiedTemplateConfig } = {
[ TYPES.cart ]: blockifiedCart,
[ TYPES.checkout ]: blockifiedCheckout,
fallback: blockifiedFallbackConfig,
};
const pickBlockClientIds = ( blocks: Array< BlockInstance > ) =>
blocks.reduce< Array< string > >( ( acc, block ) => {
if ( block.name === 'core/template-part' ) {
return acc;
}
return [ ...acc, block.clientId ];
}, [] );
const ConvertTemplate = ( { blockifyConfig, clientId, attributes } ) => {
const { getButtonLabel, onClickCallback, getBlockifiedTemplate } =
blockifyConfig;
const [ isPopoverOpen, setIsPopoverOpen ] = useState( false );
const { replaceBlock, selectBlock, replaceBlocks } =
useDispatch( blockEditorStore );
const { getBlocks } = useSelect( ( sel ) => {
return {
getBlocks: sel( blockEditorStore ).getBlocks,
};
}, [] );
const { createInfoNotice } = useDispatch( noticesStore );
return (
<div className="wp-block-woocommerce-classic-shortcode__placeholder-migration-button-container">
<Button
variant="primary"
onClick={ () => {
onClickCallback( {
clientId,
getBlocks,
attributes,
replaceBlock,
selectBlock,
} );
createInfoNotice(
__(
'Template transformed into blocks!',
'woo-gutenberg-products-block'
),
{
actions: [
{
label: __(
'Undo',
'woo-gutenberg-products-block'
),
onClick: () => {
const clientIds = pickBlockClientIds(
getBlocks()
);
replaceBlocks(
clientIds,
createBlock(
'core/group',
{
layout: {
inherit: true,
type: 'constrained',
},
},
[
createBlock(
'woocommerce/classic-shortcode',
{
shortcode:
attributes.shortcode,
}
),
]
)
);
},
},
],
type: 'snackbar',
}
);
} }
onMouseEnter={ () => setIsPopoverOpen( true ) }
onMouseLeave={ () => setIsPopoverOpen( false ) }
text={ getButtonLabel ? getButtonLabel() : '' }
>
{ isPopoverOpen && (
<Popover resize={ false } placement="right-end">
<div
style={ {
minWidth: '250px',
width: '250px',
maxWidth: '250px',
minHeight: '300px',
height: '300px',
maxHeight: '300px',
cursor: 'pointer',
} }
>
<BlockPreview
blocks={ getBlockifiedTemplate( attributes ) }
viewportWidth={ 1200 }
additionalStyles={ [
{
css: 'body { padding: 20px !important; height: fit-content !important; overflow:hidden}',
},
] }
/>
</div>
</Popover>
) }
</Button>
<Button
variant="secondary"
href="https://woocommerce.com/document/cart-checkout-blocks-support-status/"
target="_blank"
>
{ __( 'Learn more', 'woo-gutenberg-products-block' ) }
</Button>
</div>
);
};
const Edit = ( { clientId, attributes }: BlockEditProps< Attributes > ) => {
const blockProps = useBlockProps();
const templateDetails = getTemplateDetailsBySlug(
attributes.shortcode,
TEMPLATES
);
const templateTitle = attributes.shortcode;
const templatePlaceholder = templateDetails?.placeholder ?? 'fallback';
const templateType = templateDetails?.type ?? 'fallback';
const { isConversionPossible, getDescription, getTitle, blockifyConfig } =
conversionConfig[ templateType ];
const canConvert = isConversionPossible();
const placeholderTitle = getTitle
? getTitle()
: __( 'Classic Shortcode Placeholder', 'woo-gutenberg-products-block' );
const placeholderDescription = getDescription( templateTitle, canConvert );
const learnMoreContent = createInterpolateElement(
__(
'You can learn more about the benefits of switching to blocks, compatibility with extensions, and how to switch back to shortcodes <a>in our documentation</a>.',
'woo-gutenberg-products-block'
),
{
a: (
// Suppress the warning as this <a> will be interpolated into the string with content.
// eslint-disable-next-line jsx-a11y/anchor-has-content
<ExternalLink href="https://woocommerce.com/document/cart-checkout-blocks-support-status/" />
),
}
);
return (
<div { ...blockProps }>
<Placeholder className="wp-block-woocommerce-classic-shortcode__placeholder">
<div className="wp-block-woocommerce-classic-shortcode__placeholder-wireframe">
<img
className="wp-block-woocommerce-classic-shortcode__placeholder-image"
src={ `${ WC_BLOCKS_IMAGE_URL }template-placeholders/${ templatePlaceholder }.svg` }
alt={ templateTitle }
/>
</div>
<div className="wp-block-woocommerce-classic-shortcode__placeholder-copy">
<div className="wp-block-woocommerce-classic-shortcode__placeholder-copy__icon-container">
<span className="woo-icon">
<Icon icon={ woo } />{ ' ' }
{ __(
'WooCommerce',
'woo-gutenberg-products-block'
) }
</span>
<span>{ placeholderTitle }</span>
</div>
<p
dangerouslySetInnerHTML={ {
__html: placeholderDescription,
} }
/>
<p>{ learnMoreContent }</p>
{ canConvert && blockifyConfig && (
<ConvertTemplate
clientId={ clientId }
blockifyConfig={ blockifyConfig }
attributes={ attributes }
/>
) }
</div>
</Placeholder>
</div>
);
};
registerBlockType( 'woocommerce/classic-shortcode', {
title: __( 'Classic Shortcode', 'woo-gutenberg-products-block' ),
icon: (
<Icon icon={ box } className="wc-block-editor-components-block-icon" />
),
category: 'woocommerce',
apiVersion: 2,
keywords: [ __( 'WooCommerce', 'woo-gutenberg-products-block' ) ],
description: __(
'Renders classic WooCommerce shortcodes.',
'woo-gutenberg-products-block'
),
supports: {
align: true,
html: false,
multiple: false,
reusable: false,
Feature Branch: Blockified Order Confirmation (https://github.com/woocommerce/woocommerce-blocks/pull/10056) * Main block types for confirmation * Initial blocks * Styling and placeholders * Make blocks experimental * Update summary icon * Add name/description for status block and missing text descriptions in the block. Closes woocommerce/woocommerce-blocks#10057 * Order confirmation: Convert Order Details Templates to Blocks (https://github.com/woocommerce/woocommerce-blocks/pull/10095) * Move code from templates into the details block * Details -> Totals * Downloads block * Sample content for downloads block * Add block icon * Add conversion template (https://github.com/woocommerce/woocommerce-blocks/pull/10077) * Update inner block name * Add default title constant * Revert "Add default title constant" This reverts commit 1dd3bbfecc1be83c367b1ab064f5032ea58cb678. * Add global styles for order confirmation status block (https://github.com/woocommerce/woocommerce-blocks/pull/10164) * Implement style controls * Prevent link color spilling over onto wrapper * Add styles and remove class names * Remove __experimentalWritingMode * Add global styles for order confirmation summary block (https://github.com/woocommerce/woocommerce-blocks/pull/10179) * Styles for summary * Remove __experimentalWritingMode * Add table styles for order details (https://github.com/woocommerce/woocommerce-blocks/pull/10185) * Add table styles for order details * __experimentalFontWeight * Add link styles * Handle preview link styles * Unauthenticated views for Order Confirmation template (https://github.com/woocommerce/woocommerce-blocks/pull/10414) * Different views by permission * check user id matches when logged out * Add order confirmation wrapper block (https://github.com/woocommerce/woocommerce-blocks/pull/10286) * Add a heading wrapper block * Register the BillingWrapper Block server side * Fix exception 'render_content' error * Add the Billing Wrapper Block to the template * Fix wrong block name error * Fix php error * Conditionally render Billing Address within the Wrapper * Fix parent rendering * Clean up code (remove billing address from the template) * Update titles, descriptions, and icons of the billing Block and inner block * Fix broken block by removing the "parent" keyword * Use a user-friendly title and description for the Billing Wrapper * Update Billing Wrapper Block's title case Co-authored-by: Mike Jolley <mike.jolley@me.com> * Fix PHP failing unit test --------- Co-authored-by: Mike Jolley <mike.jolley@me.com> * Remove "thanks" for authenticated page * Introduce shipping wrapper based on billing wrapper Closes woocommerce/woocommerce-blocks#10053 * Order confirmation block: Verify email address for guest customers (https://github.com/woocommerce/woocommerce-blocks/pull/10567) * Add verify step for guest orders * Render content to pass through block content * Revert package changes * Customer orders cannot use email to verify * Add style controls for order shipping and billing address blocks (https://github.com/woocommerce/woocommerce-blocks/pull/10633) * Order confirmation block styling (https://github.com/woocommerce/woocommerce-blocks/pull/10780) * Add missing heading to order details * Summary block spacing * Update css variables * table styles * Inherit border styles for cells * Alignment and address styles * Add downloads wrapper * Style controls * Fix typo * Update Download Wrapper's Icon * Fix TS error * Disable Download Block's server side rendering in the editor This fixes the loading after each style change from the style controls * Clean up Downloads render functions * Fix client side Downloads Block's table border * Download + Total wrappers and tables styling * small screen * Remove server side render for previews --------- Co-authored-by: Saad Tarhi <saad.trh@gmail.com> * Shorten template description * Update test address data * Avoid leaking order key in permission form * Remove todo * Make email form required. * Remove edit page link * Remove empty columns from address wrapper * Remove IIFE * typo * Update description to mention billing * Adjust link scss * Fix wrapper markup and spacing controls * Add link preview in editor * Add initial E2E setup for the Order Confirmation Block (https://github.com/woocommerce/woocommerce-blocks/pull/10840) * Fix WC_DateTime check * Move form outside of block markup * Add additional information block (https://github.com/woocommerce/woocommerce-blocks/pull/10842) * Add block which contains hooks * Use skeleton for placeholder instead of illustration * Remove duplicate methods * Remove duplicate align tag * Update meta styles * Tests for order confirmation conditional blocks (https://github.com/woocommerce/woocommerce-blocks/pull/10972) * Add tests for conditional blocks * Move setup into test * Add E2E to the the Order Confirmation Block (https://github.com/woocommerce/woocommerce-blocks/pull/10863) * Add editor util functions * Update editor template E2E test * Add the "exact" property for consistency * Skip test Can't get the element in the page. More investigation needed! Skipping for now. * Fix "transformIntoBlocks" logic * Add tests for logged in user * Fix "beforeAll" config * Confirm downloads section is visible when logged in * Create "verifyOrderConfirmationDetails" util function * Add logged in test case * Add Guest user test case * Fix editor e2e testing * Apply a proper teardown * Fix failing tests after logout * Ensure we are logged in before visiting the editor * Ensure to have shipping selected * Wait for changes to be saved on the editor * Ensure shipping options is selected * Remove comment * Ensure we are logged in before going to the admin page * Mark the Order Confirmation as a side effect test * OrderConfirmation blocks are not experimental * resolve merge conflict * Revert package lock changes * Fix enqueue_assets * Fix CSS 404s * Make template tests more robust * Fix page URL for default confirmation page * Try afterEach to log back in * Skip guest/logout use cases Login out causes other tests to fail. We will implement these case when the multiple sign in roles are introduced in the codebase. * Remove tests requiring login out & add comments * Remove unused util functions * Hide confirmation blocks from post editor --------- Co-authored-by: Saad Tarhi <saad.trh@gmail.com> Co-authored-by: Paulo Arromba <17236129+wavvves@users.noreply.github.com>
2023-09-20 12:56:00 +00:00
inserter: false,
Refactor Cart and Checkout Page Templates (https://github.com/woocommerce/woocommerce-blocks/pull/10773) * Rename checkout template slug * Remove redirect and custom title * Classic shortcode block for checkout * Empty title * WIP placeholder * Change blockified template * Prefix cart and checkout templates with "Page: " * Template migration routine * Apply same treatment to cart template * Notices * Update placeholder text * Classic shortcodes block * Page content wrapper for templates * Update default * Do not save attributes * Update templates * Remove cart classic template * Reverted endpoints for Cart & Checkout templates. This reverts PR 9406 * Migrate page content wrapper. * Removed useless method arg. Minor tweaks. * Skip migration if the theme has a template file for this page. * Removed impossible condition. * Migrate page content wrapper. * Remove TemplateNotice in favour of DefaultNotice * Documentation links in shortcode placeholder * Hide cart and checkout page selector when using block themes * Unused var * Add tests for template changes * Revert changes to classic-template * Allow frontend redirect * Unused file * Bump version for updater * Support x template naming as well as page-x * Need to add item to cart to test checkout * Fix header test by fixing utility for adding to cart * Remove permalink tests * Click body * Wait for content to finish loading * Wait for add to cart response when adding to cart without item name * Wait for save before visiting frontend * Set content instead of inserting block * Perform test in site editor rather than page editor * Prevent notice to set the default cart/checkout page from showing on the site editor. --------- Co-authored-by: Paulo Arromba <17236129+wavvves@users.noreply.github.com> Co-authored-by: Thomas Roberts <thomas.roberts@automattic.com>
2023-09-19 09:58:18 +00:00
},
attributes: {
/**
* Shortcode attribute is used to determine which shortcode gets rendered.
*/
shortcode: {
type: 'string',
default: 'any',
},
align: {
type: 'string',
default: 'wide',
},
},
edit: ( {
attributes,
clientId,
setAttributes,
}: BlockEditProps< Attributes > ) => {
return (
<Edit
attributes={ attributes }
setAttributes={ setAttributes }
clientId={ clientId }
/>
);
},
save: () => null,
} );