diff --git a/docs/reference-guides/block-api/block-bindings.md b/docs/reference-guides/block-api/block-bindings.md index fe8ec74eea9319..5d150baf7ff3b0 100644 --- a/docs/reference-guides/block-api/block-bindings.md +++ b/docs/reference-guides/block-api/block-bindings.md @@ -374,6 +374,7 @@ The function to register a custom source is `registerBlockBindingsSource( args ) - `name`: `string` with the unique and machine-readable name. - `label`: `string` with the human readable name of the custom source. In case it was defined already on the server, the server label will be overridden by this one, in that case, it is not recommended to be defined here. (optional) - `usesContext`: `array` with the block context that the custom source may need. In case it was defined already on the server, it should not be defined here. (optional) + - `supportsCopy`: `boolean` that opts the source in to resolving values for copied blocks. Defaults to `false`, so existing sources preserve the saved block attributes when copied. (optional) - `getValues`: `function` that retrieves the values from the source. (optional) - `setValues`: `function` that allows updating the values connected to the source. (optional) - `canUserEditValue`: `function` to determine if the user can edit the value. The user won't be able to edit by default. (optional) @@ -390,7 +391,8 @@ registerBlockBindingsSource( { name: 'wpmovies/visualization-date', label: __( 'Visualization Date', 'custom-bindings' ), // We can skip the label, as it was already defined in the server in the previous example. usesContext: [ 'postType' ], // We can skip postId, as it was already defined in the server in the previous example. - getValues( { select, context } ) { + supportsCopy: true, + getValues( { select, context, isForCopy } ) { let wpMoviesVisualizationDate; const { getEditedEntityRecord } = select( coreDataStore ); if ( context?.postType && context?.postId ) { @@ -398,13 +400,19 @@ registerBlockBindingsSource( { 'postType', context?.postType, context?.postId - ).meta?.wp_movies_visualization_date; + )?.meta?.wp_movies_visualization_date; } - if ( wpMoviesVisualizationDate ) { + if ( + wpMoviesVisualizationDate || + ( isForCopy && wpMoviesVisualizationDate === '' ) + ) { return { content: wpMoviesVisualizationDate, }; } + if ( isForCopy ) { + return {}; + } return { content: new Date().toLocaleDateString( 'en-US' ), @@ -430,16 +438,19 @@ registerBlockBindingsSource( { #### getValues -The `getValues` function retrieves the value from the source on block loading. It receives an `object` as an argument with the following properties: +The `getValues` function retrieves values from the source when rendering a block. Sources with `supportsCopy: true` also receive copy requests to resolve bound attributes for the clipboard. It receives an `object` as an argument with the following properties: - `bindings` returns the bindings object of the specific source. It must have the attributes as a key, and the value can be a `string` or an `object` with arguments. - `clientId` returns a `string` with the current block client ID. - `context` returns an `object` of the current block context, defined in the `usesContext` property. [More about block context.](https://developer.wordpress.org/block-editor/reference-guides/block-api/block-context/). +- `isForCopy` is an optional `boolean` set to `true` when resolving clipboard values. It is omitted for display requests. - `select` returns an `object` of a given store's selectors. [More info in their docs.](https://developer.wordpress.org/block-editor/reference-guides/packages/packages-data/#select). The function must return an `object` with this structure: `{ 'block attribute' : value }` +Set `supportsCopy: true` only when the source handles copy requests. For copy requests, return the actual source values. Omit an attribute, or return `undefined` for it, when its value is unavailable and the editor displays a placeholder instead. This preserves the attribute's saved fallback in the copied block. Return genuine values even when they are empty, read-only, or equal to a field's key or label. In the example above, an empty stored date remains empty when copied, while missing or `null` meta omits the copied value; the display still falls back to today's date. + #### setValues The `setValues` function updates all the values of the source of the block bound. It receives an `object` as an argument with the following properties: diff --git a/packages/block-editor/CHANGELOG.md b/packages/block-editor/CHANGELOG.md index 0886eb592ee4ff..aa102b8bb422d0 100644 --- a/packages/block-editor/CHANGELOG.md +++ b/packages/block-editor/CHANGELOG.md @@ -22,6 +22,7 @@ - Writing flow: Bring back the editor header and block toolbar that iOS slides off screen when the on-screen keyboard opens, once the canvas stops scrolling ([#87316](https://github.com/WordPress/gutenberg/pull/87316)). - Block states: Undo a text gradient set in Global Styles, for the block type or an applied block style variation, when a state or breakpoint sets a box clip or text color. A breakpoint pseudo-state now also undoes one set by the default pseudo-state ([#86245](https://github.com/WordPress/gutenberg/pull/86245)). - List View: Arrow Left moves to the parent row when the parent is outside the render window ([#87266](https://github.com/WordPress/gutenberg/pull/87266)). +- Clipboard: Include resolved content from opted-in binding sources when copying blocks, preserve saved fallbacks and bindings, and consistently wrap copied List Items ([#84428](https://github.com/WordPress/gutenberg/pull/84428)). ### Internal diff --git a/packages/block-editor/src/components/block-breadcrumb/test/index.browser.test.tsx b/packages/block-editor/src/components/block-breadcrumb/test/index.browser.test.tsx index 8101b96d9835be..55e013a2867efe 100644 --- a/packages/block-editor/src/components/block-breadcrumb/test/index.browser.test.tsx +++ b/packages/block-editor/src/components/block-breadcrumb/test/index.browser.test.tsx @@ -65,7 +65,13 @@ it( 'clears selection and focuses the editor canvas from the document button', a const refsMap = observableMap< string, Element | null >(); await render( - +
{ @@ -54,6 +62,9 @@ const EditWithGeneratedProps = ( props: BlockEditPublicProps ) => { bindableAttributes, blockBindingsSources: registeredSources = NO_SOURCES, } = useContext( PrivateBlockContext ); + const { attributesForCopy } = useContext( BlockRefs ); + const { [ isPreviewModeKey ]: isPreviewMode } = useBlockEditContext(); + const instanceToken = useRef( {} ).current; const { blockBindings, context, hasPatternOverrides } = useMemo( () => { return { @@ -88,12 +99,8 @@ const EditWithGeneratedProps = ( props: BlockEditPublicProps ) => { registeredSources, ] ); - const computedAttributes = useSelect( - ( select ) => { - if ( ! blockBindings ) { - return attributes; - } - + const getBoundAttributes = useCallback( + ( select: typeof registry.select, isForCopy = false ) => { const attributesFromSources: Record< string, unknown > = {}; const blockBindingsBySource = new Map< Omit< BlockBindingsSource, 'name' >, @@ -101,13 +108,14 @@ const EditWithGeneratedProps = ( props: BlockEditPublicProps ) => { >(); for ( const [ attributeName, binding ] of Object.entries( - blockBindings + blockBindings ?? {} ) ) { const { source: sourceName, args: sourceArgs } = binding; // An absent source looks up nothing. const source = registeredSources[ sourceName as string ]; if ( ! source || + ( isForCopy && source.supportsCopy !== true ) || ! bindableAttributes?.includes( attributeName ) ) { continue; @@ -126,6 +134,9 @@ const EditWithGeneratedProps = ( props: BlockEditPublicProps ) => { // Get values in batch if the source supports it. let values: Record< string, unknown > = {}; if ( ! source.getValues ) { + if ( isForCopy ) { + continue; + } Object.keys( bindings ).forEach( ( attr ) => { // Default to the source label when `getValues` doesn't exist. values[ attr ] = source.label; @@ -136,11 +147,15 @@ const EditWithGeneratedProps = ( props: BlockEditPublicProps ) => { context, clientId, bindings, + ...( isForCopy ? { isForCopy: true } : {} ), } ); } for ( const [ attributeName, value ] of Object.entries( values ) ) { + if ( isForCopy && value === undefined ) { + continue; + } if ( attributeName === 'url' && // Sources return URLs as strings. @@ -155,20 +170,84 @@ const EditWithGeneratedProps = ( props: BlockEditPublicProps ) => { } } - return { - ...attributes, - ...attributesFromSources, - }; + return attributesFromSources; }, [ - attributes, bindableAttributes, blockBindings, clientId, context, registeredSources, + registry, ] ); + const computedAttributes = useSelect( + ( select ) => + blockBindings + ? { ...attributes, ...getBoundAttributes( select ) } + : attributes, + [ attributes, blockBindings, getBoundAttributes ] + ); + const getAttributesForCopy = useCallback( + () => getBoundAttributes( registry.select, true ), + [ getBoundAttributes, registry ] + ); + + const boundAttributeNames = useMemo( + () => + Object.entries( blockBindings ?? {} ) + .filter( ( [ attributeName, binding ] ) => { + const source = + registeredSources[ binding?.source as string ]; + return ( + bindableAttributes?.includes( attributeName ) && + source?.supportsCopy === true && + source.getValues + ); + } ) + .map( ( [ attributeName ] ) => attributeName ), + [ bindableAttributes, blockBindings, registeredSources ] + ); + useLayoutEffect( () => { + if ( + ! clientId || + ! attributesForCopy || + ! boundAttributeNames.length || + isPreviewMode || + blockContext.query !== undefined || + blockContext.queryId !== undefined || + blockContext.termQuery !== undefined + ) { + return; + } + const instances = attributesForCopy.get( clientId ) ?? new Map(); + instances.set( instanceToken, { + attributes, + boundAttributeNames, + getAttributesForCopy, + } ); + attributesForCopy.set( clientId, instances ); + return () => { + instances.delete( instanceToken ); + if ( + ! instances.size && + attributesForCopy.get( clientId ) === instances + ) { + attributesForCopy.delete( clientId ); + } + }; + }, [ + attributes, + attributesForCopy, + blockContext.query, + blockContext.queryId, + blockContext.termQuery, + boundAttributeNames, + clientId, + getAttributesForCopy, + instanceToken, + isPreviewMode, + ] ); const setBoundAttributes = useCallback( ( nextAttributes: Record< string, unknown > ) => { diff --git a/packages/block-editor/src/components/block-edit/test/bound-block-copy.jsdom.test.ts b/packages/block-editor/src/components/block-edit/test/bound-block-copy.jsdom.test.ts new file mode 100644 index 00000000000000..b01ce47d96e57b --- /dev/null +++ b/packages/block-editor/src/components/block-edit/test/bound-block-copy.jsdom.test.ts @@ -0,0 +1,454 @@ +import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'; +import { act, fireEvent, render, screen } from '@testing-library/react'; +import { createElement, Fragment } from '@wordpress/element'; +import { createRegistry, RegistryProvider, useSelect } from '@wordpress/data'; +import { + createBlock, + getBlockTypes, + parse, + registerBlockBindingsSource, + registerBlockType, + store as blocksStore, + unregisterBlockBindingsSource, + unregisterBlockType, +} from '@wordpress/blocks'; +import type { BlockBindingsSource } from '@wordpress/blocks'; +import { store as noticesStore } from '@wordpress/notices'; +import Edit from '../edit'; +import { BlockContextProvider } from '../../block-context'; +import { PrivateBlockContext } from '../../block-list/private-block-context'; +import { BlockRefsProvider } from '../../provider/block-refs-provider'; +import useCanvasClipboard from '../../writing-flow/use-clipboard-handler'; +import useListClipboard from '../../list-view/use-clipboard-handler'; +import { store as blockEditorStore } from '../../../store'; +import { unlock } from '../../../lock-unlock'; +import type { BlockAttributes } from '../../../store/types'; + +describe( 'copying a rendered bound block', () => { + const blockName = 'testing/bound-paragraph'; + const sourceName = 'testing/clipboard-source'; + const bindings = { content: { source: sourceName } }; + let source: BlockBindingsSource; + + beforeEach( () => { + source = { + name: sourceName, + label: 'Clipboard source', + getValues: ( { + select, + }: { + select: ReturnType< typeof createRegistry >[ 'select' ]; + } ) => ( { + content: + select( blockEditorStore ).getSettings().clipboardTestValue, + } ), + setValues: vi.fn(), + supportsCopy: true, + }; + registerBlockBindingsSource( source ); + registerBlockType< { + content: string; + metadata?: BlockAttributes[ 'metadata' ]; + } >( blockName, { + apiVersion: 3, + title: 'Bound paragraph', + category: 'text', + merge: ( attributes, attributesToMerge ) => ( { + content: attributes.content + attributesToMerge.content, + } ), + attributes: { + metadata: { type: 'object' }, + content: { + type: 'string', + source: 'html', + selector: 'p', + default: '', + }, + }, + edit: ( { attributes, clientId } ) => + createElement( 'p', { + id: `block-${ clientId }`, + 'data-block': clientId, + className: 'block-editor-block-list__block', + role: 'textbox', + 'aria-label': 'Bound paragraph', + contentEditable: true, + suppressContentEditableWarning: true, + tabIndex: 0, + dangerouslySetInnerHTML: { __html: attributes.content }, + } ), + save: ( { attributes } ) => + createElement( 'p', { + dangerouslySetInnerHTML: { __html: attributes.content }, + } ), + } ); + } ); + + afterEach( () => { + document.getSelection()!.removeAllRanges(); + act( () => { + unregisterBlockBindingsSource( sourceName ); + if ( source.name !== sourceName ) { + unregisterBlockBindingsSource( source.name ); + } + unregisterBlockType( blockName ); + } ); + } ); + + function BoundBlock( { clientId }: { clientId: string } ) { + const { attributes, blockBindingsSources } = useSelect( + ( select ) => ( { + attributes: + select( blockEditorStore ).getBlockAttributes( clientId ), + blockBindingsSources: unlock( + select( blocksStore ) + ).getAllBlockBindingsSources(), + } ), + [ clientId ] + ); + return createElement( + PrivateBlockContext.Provider, + { + value: { + bindableAttributes: [ 'content' ], + blockBindingsSources, + }, + }, + createElement( Edit, { + name: blockName, + clientId, + attributes: attributes!, + } ) + ); + } + + function Canvas( { clientId }: { clientId: string } ) { + const clipboardRef = useCanvasClipboard(); + return createElement( + 'div', + { ref: clipboardRef }, + createElement( BoundBlock, { clientId } ) + ); + } + + function ListView( { clientId }: { clientId: string } ) { + const clipboardRef = useListClipboard( { selectBlock: () => {} } ); + return createElement( + Fragment, + null, + createElement( BoundBlock, { clientId } ), + createElement( + 'div', + { ref: clipboardRef }, + createElement( + 'div', + { role: 'row', 'data-block': clientId, tabIndex: 0 }, + 'Bound paragraph' + ) + ) + ); + } + + function copyFrom( element: HTMLElement ) { + const clipboard = new Map< string, string >(); + const event = new Event( 'copy', { bubbles: true, cancelable: true } ); + Object.defineProperty( event, 'clipboardData', { + value: { + setData: ( type: string, content: string ) => + clipboard.set( type, content ), + getData: ( type: string ) => clipboard.get( type ) ?? '', + }, + } ); + element.focus(); + fireEvent( element, event ); + expect( event.defaultPrevented ).toBe( true ); + return { + plainText: clipboard.get( 'text/plain' ), + html: clipboard.get( 'text/html' )!, + }; + } + + it( 'keeps the saved fallback when a binding only has a server-side placeholder', () => { + source = { + name: 'testing/server-only-source', + label: 'Server Source', + }; + registerBlockBindingsSource( source ); + const registry = createRegistry(); + registry.register( blocksStore ); + registry.register( blockEditorStore ); + registry.register( noticesStore ); + registry.dispatch( blocksStore ).addBlockTypes( getBlockTypes() ); + unlock( registry.dispatch( blocksStore ) ).addBlockBindingsSource( + source + ); + const actions = registry.dispatch( blockEditorStore ); + const serverBindings = { content: { source: source.name } }; + const boundBlock = createBlock( blockName, { + content: 'paragraph default content', + metadata: { bindings: serverBindings }, + } ); + const normalBlock = createBlock( blockName, { + content: 'Normal paragraph', + } ); + actions.resetBlocks( [ boundBlock, normalBlock ] ); + actions.multiSelect( boundBlock.clientId, normalBlock.clientId ); + render( + createElement( + RegistryProvider, + { value: registry }, + createElement( + BlockRefsProvider, + null, + createElement( Canvas, { clientId: boundBlock.clientId } ) + ) + ) + ); + + const paragraph = screen.getByRole( 'textbox', { + name: 'Bound paragraph', + } ); + expect( paragraph ).toHaveTextContent( 'Server Source' ); + const copied = copyFrom( paragraph ); + expect( copied.plainText ).toBe( + 'paragraph default content\n\nNormal paragraph' + ); + expect( parse( copied.html )[ 0 ] ).toMatchObject( { + isValid: true, + attributes: { + content: 'paragraph default content', + metadata: { bindings: serverBindings }, + }, + } ); + expect( boundBlock.attributes.content ).toBe( + 'paragraph default content' + ); + } ); + + it.each( [ + [ 'omitted', {}, 'fallback content' ], + [ 'undefined', { content: undefined }, 'fallback content' ], + [ + 'a genuine field key', + { content: 'unaccessible_field' }, + 'unaccessible_field', + ], + [ 'a genuine label', { content: 'Field label' }, 'Field label' ], + [ 'an empty string', { content: '' }, '' ], + ] )( + 'copies %s from the mounted source only when copying', + ( _, copyValues, expectedContent ) => { + unregisterBlockBindingsSource( sourceName ); + const getValues = vi.fn( + ( { + isForCopy, + select, + }: { + isForCopy?: boolean; + select: ReturnType< typeof createRegistry >[ 'select' ]; + } ) => + isForCopy + ? select( blockEditorStore ).getSettings() + .clipboardCopyValues + : { content: 'unaccessible_field' } + ); + source = { + ...source, + usesContext: [ 'postId', 'postType' ], + getValues, + canUserEditValue: () => false, + getFieldsList: () => [], + }; + registerBlockBindingsSource( source ); + const registry = createRegistry(); + registry.register( blocksStore ); + registry.register( blockEditorStore ); + registry.register( noticesStore ); + registry.dispatch( blocksStore ).addBlockTypes( getBlockTypes() ); + unlock( registry.dispatch( blocksStore ) ).addBlockBindingsSource( + source + ); + const actions = registry.dispatch( blockEditorStore ); + const boundBindings = { + content: { + source: sourceName, + args: { key: 'unaccessible_field' }, + }, + }; + const boundBlock = createBlock( blockName, { + content: 'fallback content', + metadata: { bindings: boundBindings }, + } ); + const normalBlock = createBlock( blockName, { + content: 'Normal paragraph', + } ); + actions.resetBlocks( [ boundBlock, normalBlock ] ); + actions.multiSelect( boundBlock.clientId, normalBlock.clientId ); + actions.updateSettings( { + clipboardCopyValues: { content: 'Old value' }, + } ); + render( + createElement( + RegistryProvider, + { value: registry }, + createElement( + BlockRefsProvider, + null, + createElement( BlockContextProvider, { + value: { postId: 41, postType: 'post' }, + children: createElement( Canvas, { + clientId: boundBlock.clientId, + } ), + } ) + ) + ) + ); + const paragraph = screen.getByRole( 'textbox', { + name: 'Bound paragraph', + } ); + expect( paragraph ).toHaveTextContent( 'unaccessible_field' ); + expect( getValues ).toHaveBeenCalled(); + expect( + getValues.mock.calls.some( + ( [ options ] ) => options.isForCopy + ) + ).toBe( false ); + act( () => { + actions.updateSettings( { clipboardCopyValues: copyValues } ); + } ); + expect( + getValues.mock.calls.some( + ( [ options ] ) => options.isForCopy + ) + ).toBe( false ); + + const copied = copyFrom( paragraph ); + expect( parse( copied.html )[ 0 ] ).toMatchObject( { + isValid: true, + attributes: { + content: expectedContent, + metadata: { bindings: boundBindings }, + }, + } ); + const copyCalls = getValues.mock.calls.filter( + ( [ options ] ) => options.isForCopy + ); + expect( copyCalls ).toHaveLength( 1 ); + expect( copyCalls[ 0 ][ 0 ] ).toEqual( + expect.objectContaining( { + isForCopy: true, + clientId: boundBlock.clientId, + context: { postId: 41, postType: 'post' }, + bindings: { + content: { args: { key: 'unaccessible_field' } }, + }, + } ) + ); + expect( + registry + .select( blockEditorStore ) + .getBlockAttributes( boundBlock.clientId ) + ).toMatchObject( { + content: 'fallback content', + metadata: { bindings: boundBindings }, + } ); + expect( source.setValues ).not.toHaveBeenCalled(); + } + ); + + it.each( [ 'canvas', 'list view', 'canvas with RichText endpoints' ] )( + 'copies current resolved content from the %s without changing the source', + async ( mode ) => { + const registry = createRegistry(); + registry.register( blocksStore ); + registry.register( blockEditorStore ); + registry.register( noticesStore ); + registry.dispatch( blocksStore ).addBlockTypes( getBlockTypes() ); + unlock( registry.dispatch( blocksStore ) ).addBlockBindingsSource( + source + ); + const actions = registry.dispatch( blockEditorStore ); + const boundBlock = createBlock( blockName, { + content: '', + metadata: { bindings }, + } ); + const normalBlock = createBlock( blockName, { + content: 'Normal paragraph', + } ); + actions.resetBlocks( [ boundBlock, normalBlock ] ); + actions.updateSettings( { + clipboardTestValue: 'Bound text', + } ); + if ( mode === 'canvas with RichText endpoints' ) { + actions.selectionChange( { + start: { + clientId: boundBlock.clientId, + attributeKey: 'content', + offset: 0, + }, + end: { + clientId: normalBlock.clientId, + attributeKey: 'content', + offset: ( normalBlock.attributes.content as string ) + .length, + }, + } ); + } else { + actions.multiSelect( + boundBlock.clientId, + normalBlock.clientId + ); + } + const Fixture = mode === 'list view' ? ListView : Canvas; + render( + createElement( + RegistryProvider, + { value: registry }, + createElement( + BlockRefsProvider, + null, + createElement( BlockContextProvider, { + value: { postId: 41, postType: 'post' }, + children: createElement( Fixture, { + clientId: boundBlock.clientId, + } ), + } ) + ) + ) + ); + const copyTarget = + mode === 'list view' + ? screen.getByRole( 'row' ) + : screen.getByRole( 'textbox', { + name: 'Bound paragraph', + } ); + const copied = copyFrom( copyTarget ); + expect( copied.plainText ).toBe( 'Bound text\n\nNormal paragraph' ); + const pasted = parse( copied.html ); + expect( pasted.map( ( block ) => block.isValid ) ).toEqual( [ + true, + true, + ] ); + expect( pasted[ 0 ].attributes ).toMatchObject( { + content: 'Bound text', + metadata: { bindings }, + } ); + expect( pasted[ 1 ].attributes.content ).toBe( 'Normal paragraph' ); + + await act( async () => { + await actions.updateSettings( { + clipboardTestValue: 'Updated value', + } ); + } ); + expect( copyFrom( copyTarget ).plainText ).toBe( + 'Updated value\n\nNormal paragraph' + ); + expect( + registry + .select( blockEditorStore ) + .getBlockAttributes( boundBlock.clientId ) + ).toMatchObject( { content: '', metadata: { bindings } } ); + expect( source.setValues ).not.toHaveBeenCalled(); + } + ); +} ); diff --git a/packages/block-editor/src/components/block-edit/test/edit.jsdom.test.tsx b/packages/block-editor/src/components/block-edit/test/edit.jsdom.test.tsx index 36c69bb06b21f5..fb4ea927c5b302 100644 --- a/packages/block-editor/src/components/block-edit/test/edit.jsdom.test.tsx +++ b/packages/block-editor/src/components/block-edit/test/edit.jsdom.test.tsx @@ -1,19 +1,43 @@ -import { afterEach, describe, expect, it } from 'vitest'; -import { render, screen } from '@testing-library/react'; +import { afterEach, describe, expect, it, vi } from 'vitest'; +import { act, render, screen } from '@testing-library/react'; import { + getBlockBindingsSource, + createBlock, + registerBlockBindingsSource, registerBlockType, + unregisterBlockBindingsSource, unregisterBlockType, getBlockTypes, + store as blocksStore, } from '@wordpress/blocks'; +import { useSelect } from '@wordpress/data'; +import { StrictMode, useContext } from '@wordpress/element'; +import type { ComponentProps } from 'react'; import Edit from '../edit'; import { BlockContextProvider } from '../../block-context'; +import { PrivateBlockContext } from '../../block-list/private-block-context'; +import { + BlockRefs, + getBoundAttributesForCopy, +} from '../../provider/block-refs-provider'; +import { BlockEditContextProvider, isPreviewModeKey } from '../context'; +import { unlock } from '../../../lock-unlock'; +import { getBoundPartialBlockForCopy } from '../../writing-flow/utils'; const noop = () => null; describe( 'Edit', () => { afterEach( () => { - getBlockTypes().forEach( ( block ) => { - unregisterBlockType( block.name ); + act( () => { + if ( getBlockBindingsSource( 'testing/copy' ) ) { + unregisterBlockBindingsSource( 'testing/copy' ); + } + if ( getBlockBindingsSource( 'testing/legacy' ) ) { + unregisterBlockBindingsSource( 'testing/legacy' ); + } + getBlockTypes().forEach( ( block ) => { + unregisterBlockType( block.name ); + } ); } ); } ); @@ -23,6 +47,392 @@ describe( 'Edit', () => { expect( container ).toBeEmptyDOMElement(); } ); + describe( 'bound attributes for copying', () => { + const bindings = { content: { source: 'testing/copy' } }; + + function registerBoundBlock( + getValues: ( options?: { + isForCopy?: boolean; + } ) => Record< string, unknown > = () => ( { + content: 'Resolved text', + } ), + copySupport: { supportsCopy?: boolean } = { supportsCopy: true } + ) { + registerBlockBindingsSource( { + name: 'testing/copy', + label: 'Copy test', + getValues, + ...copySupport, + } ); + registerBlockType( 'core/test-block', { + attributes: {}, + apiVersion: 3, + category: 'text', + title: 'Copy test', + edit: ( { attributes } ) => ( +

+ { ( attributes.content ?? attributes.text ) as string } +

+ ), + save: noop, + } ); + } + + function BoundEdit( { + attributesForCopy, + attributes, + clientId = 'bound-block', + bindableAttributes = [ 'content' ], + isPreviewMode = false, + blockContext = {}, + }: { + attributesForCopy?: ComponentProps< + typeof BlockRefs.Provider + >[ 'value' ][ 'attributesForCopy' ]; + attributes: ComponentProps< typeof Edit >[ 'attributes' ]; + clientId?: string | null; + bindableAttributes?: string[]; + isPreviewMode?: boolean; + blockContext?: Record< string, unknown >; + } ) { + const blockRefs = useContext( BlockRefs ); + const blockBindingsSources = useSelect( + ( select ) => + unlock( + select( blocksStore ) + ).getAllBlockBindingsSources(), + [] + ); + return ( + + + + + + + + + + ); + } + + it( 'registers the resolved value without changing the stored attributes', () => { + registerBoundBlock(); + const attributesForCopy = new Map(); + const attributes = { content: '', metadata: { bindings } }; + const block = { clientId: 'bound-block', attributes }; + const { unmount } = render( + + ); + + expect( screen.getByText( 'Resolved text' ) ).toBeVisible(); + expect( + getBoundAttributesForCopy( block, attributesForCopy ) + ).toEqual( { content: 'Resolved text' } ); + expect( attributes.content ).toBe( '' ); + expect( attributes.metadata.bindings ).toBe( bindings ); + unmount(); + expect( attributesForCopy.size ).toBe( 0 ); + } ); + + it.each( [ {}, { supportsCopy: false } ] )( + 'keeps an unaware source display value out of copied attributes (%j)', + ( copySupport ) => { + const getValues = vi.fn( () => ( { + content: 'Display placeholder', + } ) ); + registerBoundBlock( getValues, copySupport ); + const attributesForCopy = new Map(); + const attributes = { + content: 'Saved fallback', + metadata: { bindings }, + }; + render( + + ); + expect( + screen.getByText( 'Display placeholder' ) + ).toBeVisible(); + const callsBeforeCopy = getValues.mock.calls.length; + expect( + getBoundAttributesForCopy( + { clientId: 'bound-block', attributes }, + attributesForCopy + ) + ).toBeUndefined(); + expect( getValues ).toHaveBeenCalledTimes( callsBeforeCopy ); + expect( attributesForCopy.size ).toBe( 0 ); + expect( attributes.content ).toBe( 'Saved fallback' ); + } + ); + + it( 'resolves only opted-in attributes when a block also has an unaware source', () => { + const getValues = vi.fn( + ( { isForCopy }: { isForCopy?: boolean } = {} ) => ( { + content: isForCopy ? 'Copy value' : 'Display value', + } ) + ); + const legacyGetValues = vi.fn( () => ( { + text: 'Legacy placeholder', + } ) ); + registerBoundBlock( getValues ); + registerBlockBindingsSource( { + name: 'testing/legacy', + label: 'Legacy source', + getValues: legacyGetValues, + } ); + const attributesForCopy = new Map(); + const attributes = { + content: 'Saved content', + text: 'Saved text', + metadata: { + bindings: { + ...bindings, + text: { source: 'testing/legacy' }, + }, + }, + }; + render( + + ); + const legacyCallsBeforeCopy = legacyGetValues.mock.calls.length; + expect( + getValues.mock.calls.some( + ( [ options ] ) => options?.isForCopy + ) + ).toBe( false ); + expect( + getBoundAttributesForCopy( + { clientId: 'bound-block', attributes }, + attributesForCopy + ) + ).toEqual( { content: 'Copy value' } ); + expect( legacyGetValues ).toHaveBeenCalledTimes( + legacyCallsBeforeCopy + ); + expect( attributes.text ).toBe( 'Saved text' ); + } ); + + it( 'refreshes the snapshot when the block attributes change', () => { + registerBoundBlock(); + const attributesForCopy = new Map(); + const originalAttributes = { content: '', metadata: { bindings } }; + const nextAttributes = { ...originalAttributes, anchor: 'updated' }; + const { rerender } = render( + + ); + rerender( + + ); + + expect( + getBoundAttributesForCopy( + { clientId: 'bound-block', attributes: originalAttributes }, + attributesForCopy + ) + ).toBeUndefined(); + expect( + getBoundAttributesForCopy( + { clientId: 'bound-block', attributes: nextAttributes }, + attributesForCopy + ) + ).toEqual( { content: 'Resolved text' } ); + } ); + + it( 'ignores ambiguous instances and removes only the unmounted instance', () => { + registerBoundBlock(); + const attributesForCopy = new Map(); + const attributes = { content: '', metadata: { bindings } }; + const block = { clientId: 'bound-block', attributes }; + const { unmount: unmountFirst } = render( + + ); + const { unmount: unmountSecond } = render( + + ); + + expect( attributesForCopy.get( block.clientId ).size ).toBe( 2 ); + expect( + getBoundAttributesForCopy( block, attributesForCopy ) + ).toBeUndefined(); + unmountFirst(); + expect( + getBoundAttributesForCopy( block, attributesForCopy ) + ).toEqual( { content: 'Resolved text' } ); + unmountSecond(); + expect( attributesForCopy.size ).toBe( 0 ); + } ); + + it( 'registers a single instance under StrictMode', () => { + registerBoundBlock(); + const attributesForCopy = new Map(); + const attributes = { content: '', metadata: { bindings } }; + const { unmount } = render( + + + + ); + + expect( attributesForCopy.get( 'bound-block' ).size ).toBe( 1 ); + unmount(); + expect( attributesForCopy.size ).toBe( 0 ); + } ); + + it.each( [ + { isPreviewMode: true }, + { clientId: null }, + { clientId: '' }, + { attributesForCopy: undefined }, + { bindableAttributes: [] }, + { blockContext: { queryId: 0 } }, + { blockContext: { query: {} } }, + { blockContext: { termQuery: {} } }, + ] )( + 'does not register an ineligible edit instance (%j)', + ( props ) => { + registerBoundBlock(); + const attributesForCopy = new Map(); + const attributes = { content: '', metadata: { bindings } }; + render( + + ); + + expect( attributesForCopy.size ).toBe( 0 ); + } + ); + + it( 'does not register bindings to an unknown source', () => { + registerBoundBlock(); + const attributesForCopy = new Map(); + const attributes = { + content: '', + metadata: { + bindings: { content: { source: 'testing/unknown' } }, + }, + }; + render( + + ); + + expect( attributesForCopy.size ).toBe( 0 ); + } ); + + it.each( [ undefined, 'https://example.com/saved' ] )( + 'keeps resolved Button text when its bound URL fallback is %s', + ( url ) => { + registerBoundBlock( () => ( { text: 'Visible label' } ) ); + const attributesForCopy = new Map(); + const attributes = { + ...( url ? { url } : {} ), + metadata: { + bindings: { + text: { source: 'testing/copy' }, + url: { source: 'testing/copy' }, + }, + }, + }; + render( + + ); + + expect( screen.getByText( 'Visible label' ) ).toBeVisible(); + expect( + getBoundAttributesForCopy( + { clientId: 'bound-block', attributes }, + attributesForCopy + ) + ).toEqual( { + text: 'Visible label', + } ); + const block = { + ...createBlock( 'core/test-block' ), + clientId: 'bound-block', + attributes, + }; + expect( + getBoundPartialBlockForCopy( + block, + block, + attributesForCopy, + {} + ).attributes + ).toEqual( { ...attributes, text: 'Visible label' } ); + expect( attributes ).not.toHaveProperty( 'text' ); + } + ); + + it( 'omits attributes when none of the bound values is available', () => { + registerBoundBlock( () => ( {} ) ); + const attributesForCopy = new Map(); + const attributes = { metadata: { bindings } }; + render( + + ); + + expect( + getBoundAttributesForCopy( + { clientId: 'bound-block', attributes }, + attributesForCopy + ) + ).toBeUndefined(); + } ); + } ); + it( 'should use edit implementation of block', () => { const edit = () =>
; diff --git a/packages/block-editor/src/components/block-settings-menu/block-settings-dropdown.tsx b/packages/block-editor/src/components/block-settings-menu/block-settings-dropdown.tsx index 7b5e015d03dbd3..1f7c766ae7f416 100644 --- a/packages/block-editor/src/components/block-settings-menu/block-settings-dropdown.tsx +++ b/packages/block-editor/src/components/block-settings-menu/block-settings-dropdown.tsx @@ -4,12 +4,12 @@ import { store as blocksStore, } from '@wordpress/blocks'; import { DropdownMenu, MenuGroup, MenuItem } from '@wordpress/components'; -import { useDispatch, useSelect } from '@wordpress/data'; +import { useDispatch, useRegistry, useSelect } from '@wordpress/data'; import { chevronDown, chevronUp, moreVertical } from '@wordpress/icons'; -import { Children, cloneElement } from '@wordpress/element'; +import { Children, cloneElement, useContext } from '@wordpress/element'; import { __ } from '@wordpress/i18n'; import { store as keyboardShortcutsStore } from '@wordpress/keyboard-shortcuts'; -import { pipe, useCopyToClipboard } from '@wordpress/compose'; +import { pipe } from '@wordpress/compose'; import type { ComponentProps } from 'react'; import type { Block } from '@wordpress/blocks'; import BlockActions from '../block-actions'; @@ -21,6 +21,9 @@ import BlockParentSelectorMenuItem from './block-parent-selector-menu-item'; import { store as blockEditorStore } from '../../store'; import { unlock } from '../../lock-unlock'; import { useNotifyCopy } from '../../utils/use-notify-copy'; +import { BlockRefs } from '../provider/block-refs-provider'; +import { getClipboardBlocksContent } from '../writing-flow/utils'; +import useBlockCopyToClipboard from './use-block-copy-to-clipboard'; import type { BlockSettingsDropdownProps, CopyMenuItemProps } from './types'; const POPOVER_PROPS: ComponentProps< typeof DropdownMenu >[ 'popoverProps' ] = { @@ -28,7 +31,7 @@ const POPOVER_PROPS: ComponentProps< typeof DropdownMenu >[ 'popoverProps' ] = { placement: 'bottom-start', }; -function CopyMenuItem( { +export function CopyMenuItem( { clientIds, onCopy, label, @@ -38,10 +41,21 @@ function CopyMenuItem( { }: CopyMenuItemProps ) { const { getBlocksByClientId } = useSelect( blockEditorStore ); const { removeBlocks } = useDispatch( blockEditorStore ); + const registry = useRegistry(); + const { attributesForCopy } = useContext( BlockRefs ); const notifyCopy = useNotifyCopy(); - const ref = useCopyToClipboard( - // The copied blocks exist. - () => serialize( getBlocksByClientId( clientIds ) as Block[] ), + const ref = useBlockCopyToClipboard( + () => { + const blocks = getBlocksByClientId( clientIds ) as Block[]; + return eventType === 'copyStyles' + ? { html: serialize( blocks ), hasBoundAttributes: false } + : getClipboardBlocksContent( + blocks, + registry, + attributesForCopy, + { addWrapper: true } + ); + }, () => { switch ( eventType ) { case 'copy': diff --git a/packages/block-editor/src/components/block-settings-menu/test/copy-menu-item.jsdom.test.ts b/packages/block-editor/src/components/block-settings-menu/test/copy-menu-item.jsdom.test.ts new file mode 100644 index 00000000000000..65cf08e208044c --- /dev/null +++ b/packages/block-editor/src/components/block-settings-menu/test/copy-menu-item.jsdom.test.ts @@ -0,0 +1,456 @@ +import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'; +import type { Mock } from 'vitest'; +import type { ComponentProps, ContextType } from 'react'; +import { fireEvent, render, screen, waitFor } from '@testing-library/react'; +import { + createBlock, + getBlockType, + parse, + registerBlockType, + serialize, + unregisterBlockType, + __unstableGetInnerBlocksProps as getInnerBlocksProps, +} from '@wordpress/blocks'; +import type { Block } from '@wordpress/blocks'; +import { observableMap } from '@wordpress/compose'; +import type { useDispatch, useRegistry, useSelect } from '@wordpress/data'; +import { createElement } from '@wordpress/element'; +import { CopyMenuItem } from '../block-settings-dropdown'; +import { BlockRefs } from '../../provider/block-refs-provider'; +import { + getPasteBlocks, + requiresWrapperOnCopy, +} from '../../writing-flow/utils'; +import type { BlockAttributes } from '../../../store/types'; + +const { + getBlocksByClientId, + removeBlocks, + notifyCopy, + getBlockRootClientId, + getBlockName, + getBlockAttributes, +} = vi.hoisted( () => ( { + getBlocksByClientId: vi.fn(), + removeBlocks: vi.fn(), + notifyCopy: vi.fn(), + getBlockRootClientId: vi.fn(), + getBlockName: vi.fn(), + getBlockAttributes: vi.fn(), +} ) ); + +vi.mock( import( '@wordpress/data' ), async ( importOriginal ) => ( { + ...( await importOriginal() ), + useSelect: ( () => ( { getBlocksByClientId } ) ) as typeof useSelect, + useDispatch: ( () => ( { + removeBlocks, + } ) ) as unknown as typeof useDispatch, + useRegistry: ( () => ( { + select: () => ( { + getBlockType, + getBlockRootClientId, + getBlockName, + getBlockAttributes, + } ), + } ) ) as unknown as typeof useRegistry, +} ) ); + +vi.mock( import( '../../../utils/use-notify-copy' ), () => ( { + useNotifyCopy: () => notifyCopy, +} ) ); + +describe( 'CopyMenuItem', () => { + const save = vi.fn( + ( { attributes }: { attributes: { content: string } } ) => + createElement( 'p', null, attributes.content ) + ); + let clipboardDescriptor: PropertyDescriptor | undefined; + let execCommandDescriptor: PropertyDescriptor | undefined; + let clipboard: { + write: Mock< + ( + items: { representations: Record< string, Blob > }[] + ) => Promise< void > + >; + writeText: Mock< ( text: string ) => Promise< void > >; + }; + let block: Block< BlockAttributes >; + let attributesForCopy: NonNullable< + ContextType< typeof BlockRefs >[ 'attributesForCopy' ] + >; + + beforeEach( () => { + vi.clearAllMocks(); + removeBlocks.mockReset(); + registerBlockType< { + content: string; + metadata?: BlockAttributes[ 'metadata' ]; + } >( 'core/copy-menu-test', { + apiVersion: 3, + title: 'Copy test', + category: 'text', + attributes: { + content: { type: 'string', source: 'html', selector: 'p' }, + metadata: { type: 'object' }, + }, + transforms: { + from: [ + { + type: 'raw', + selector: 'p', + schema: ( { phrasingContentSchema } ) => ( { + p: { children: phrasingContentSchema }, + } ), + }, + ], + }, + save, + } ); + block = createBlock( 'core/copy-menu-test', { + content: '', + metadata: { bindings: { content: { source: 'testing/copy' } } }, + } ); + getBlocksByClientId.mockReturnValue( [ block ] ); + attributesForCopy = new Map( [ + [ + block.clientId, + new Map( [ + [ + {}, + { + attributes: block.attributes, + getAttributesForCopy: () => ( { + ...block.attributes, + content: 'Bound text', + } ), + boundAttributeNames: [ 'content' ], + }, + ], + ] ), + ], + ] ); + clipboardDescriptor = Object.getOwnPropertyDescriptor( + navigator, + 'clipboard' + ); + execCommandDescriptor = Object.getOwnPropertyDescriptor( + document, + 'execCommand' + ); + clipboard = { + write: vi + .fn< + ( + items: { representations: Record< string, Blob > }[] + ) => Promise< void > + >() + .mockResolvedValue( undefined ), + writeText: vi + .fn< ( text: string ) => Promise< void > >() + .mockResolvedValue( undefined ), + }; + Object.defineProperty( navigator, 'clipboard', { + configurable: true, + value: clipboard, + } ); + Object.defineProperty( document, 'execCommand', { + configurable: true, + value: vi.fn().mockReturnValue( false ), + } ); + vi.stubGlobal( + 'ClipboardItem', + class { + representations: Record< string, Blob | PromiseLike< Blob > >; + + constructor( + representations: Record< + string, + Blob | PromiseLike< Blob > + > + ) { + this.representations = representations; + } + } + ); + } ); + + afterEach( () => { + unregisterBlockType( 'core/copy-menu-test' ); + for ( const name of [ 'core/list', 'core/list-item' ] ) { + if ( getBlockType( name ) ) { + unregisterBlockType( name ); + } + } + if ( clipboardDescriptor ) { + Object.defineProperty( + navigator, + 'clipboard', + clipboardDescriptor + ); + } else { + Reflect.deleteProperty( navigator, 'clipboard' ); + } + if ( execCommandDescriptor ) { + Object.defineProperty( + document, + 'execCommand', + execCommandDescriptor + ); + } else { + Reflect.deleteProperty( document, 'execCommand' ); + } + vi.unstubAllGlobals(); + } ); + + function renderMenuItem( + props: Partial< ComponentProps< typeof CopyMenuItem > > = {} + ) { + const onCopy = vi.fn(); + render( + createElement( + BlockRefs.Provider, + { + value: { + refsMap: observableMap< string, Element | null >(), + eventHandlers: new Map(), + attributesForCopy, + }, + }, + createElement( CopyMenuItem, { + clientIds: [ block.clientId ], + onCopy, + label: undefined, + shortcut: undefined, + ...props, + } ) + ) + ); + fireEvent.click( screen.getByRole( 'menuitem' ) ); + return { onCopy }; + } + + it( 'copies resolved content without changing the block and marks copy success', async () => { + const { onCopy } = renderMenuItem(); + + await waitFor( () => + expect( notifyCopy ).toHaveBeenCalledWith( 'copy', [ + block.clientId, + ] ) + ); + expect( clipboard.writeText ).toHaveBeenCalledTimes( 1 ); + expect( clipboard.write ).not.toHaveBeenCalled(); + expect( onCopy ).toHaveBeenCalledTimes( 1 ); + expect( removeBlocks ).not.toHaveBeenCalled(); + expect( block.attributes.content ).toBe( '' ); + expect( block.attributes.metadata!.bindings!.content.source ).toBe( + 'testing/copy' + ); + } ); + + it( 'removes cut blocks only after the clipboard write succeeds', async () => { + let finishWrite!: () => void; + clipboard.writeText.mockReturnValue( + new Promise< void >( ( resolve ) => { + finishWrite = resolve; + } ) + ); + const { onCopy } = renderMenuItem( { + eventType: 'cut', + __experimentalUpdateSelection: true, + } ); + + expect( removeBlocks ).not.toHaveBeenCalled(); + finishWrite(); + await waitFor( () => + expect( removeBlocks ).toHaveBeenCalledWith( + [ block.clientId ], + true + ) + ); + expect( notifyCopy ).toHaveBeenCalledWith( 'cut', [ block.clientId ] ); + expect( onCopy ).not.toHaveBeenCalled(); + } ); + + it( 'keeps cut blocks and omits notifications if copying fails', async () => { + clipboard.writeText.mockRejectedValue( + new Error( 'Clipboard denied' ) + ); + const { onCopy } = renderMenuItem( { eventType: 'cut' } ); + + await waitFor( () => + expect( document.execCommand ).toHaveBeenCalled() + ); + expect( removeBlocks ).not.toHaveBeenCalled(); + expect( notifyCopy ).not.toHaveBeenCalled(); + expect( onCopy ).not.toHaveBeenCalled(); + } ); + + it( 'preserves the binding when Cut uses the asynchronous clipboard fallback', async () => { + const copied = new Map< string, string >(); + clipboard.write.mockImplementation( async ( items ) => { + for ( const [ type, blob ] of Object.entries( + items[ 0 ].representations + ) ) { + const text = blob.text + ? await blob.text() + : await new Promise< string >( ( resolve ) => { + const reader = new FileReader(); + reader.onload = () => + resolve( reader.result as string ); + reader.readAsText( blob ); + } ); + // Model an HTML clipboard write that sanitizes block comments. + copied.set( + type, + type === 'text/html' + ? text.replace( //g, '' ) + : text + ); + } + } ); + clipboard.writeText.mockImplementation( async ( text ) => { + copied.set( 'text/plain', text ); + } ); + removeBlocks.mockImplementation( () => { + getBlocksByClientId.mockReturnValue( [] ); + attributesForCopy.clear(); + } ); + renderMenuItem( { eventType: 'cut' } ); + await waitFor( () => + expect( removeBlocks ).toHaveBeenCalledTimes( 1 ) + ); + expect( document.execCommand ).toHaveBeenCalled(); + + const pasted = getPasteBlocks( { + clipboardData: { + getData: ( type: string ) => copied.get( type ) ?? '', + files: [], + items: [], + } as unknown as DataTransfer, + } ); + expect( console ).toHaveLogged(); + expect( pasted ).toMatchObject( [ + { + isValid: true, + attributes: { + content: 'Bound text', + metadata: block.attributes.metadata, + }, + }, + ] ); + } ); + + it( 'keeps copy styles on the original serialization path', async () => { + const { onCopy } = renderMenuItem( { eventType: 'copyStyles' } ); + + await waitFor( () => + expect( notifyCopy ).toHaveBeenCalledWith( 'copyStyles', [ + block.clientId, + ] ) + ); + expect( clipboard.writeText ).toHaveBeenCalledWith( + serialize( [ block ] ) + ); + expect( clipboard.write ).not.toHaveBeenCalled(); + expect( onCopy ).toHaveBeenCalledTimes( 1 ); + } ); + + it( 'keeps unbound blocks on the original serialization path', async () => { + attributesForCopy.clear(); + const markup = serialize( [ block ] ); + save.mockClear(); + const { onCopy } = renderMenuItem(); + + await waitFor( () => expect( onCopy ).toHaveBeenCalledTimes( 1 ) ); + expect( save ).toHaveBeenCalledTimes( 1 ); + expect( clipboard.writeText ).toHaveBeenCalledWith( markup ); + expect( clipboard.write ).not.toHaveBeenCalled(); + } ); + + it.each( [ 'unbound', 'unresolved', 'resolved' ] )( + 'copies a List Item with its ordered List wrapper when its binding is %s', + async ( state ) => { + const wrapperSettings = { [ requiresWrapperOnCopy ]: true }; + registerBlockType< { + content: string; + metadata?: BlockAttributes[ 'metadata' ]; + } >( 'core/list-item', { + apiVersion: 3, + title: 'List Item', + category: 'text', + attributes: { + content: { type: 'string', source: 'html', selector: 'li' }, + metadata: { type: 'object' }, + }, + ...wrapperSettings, + save: ( { attributes } ) => + createElement( 'li', null, attributes.content ), + } ); + registerBlockType< { ordered: boolean } >( 'core/list', { + apiVersion: 3, + title: 'List', + category: 'text', + attributes: { ordered: { type: 'boolean' } }, + save: ( { attributes } ) => + createElement( + attributes.ordered ? 'ol' : 'ul', + getInnerBlocksProps() + ), + } ); + block = createBlock( 'core/list-item', { + content: 'Saved item', + ...( state === 'unbound' + ? {} + : { + metadata: { + bindings: { + content: { source: 'testing/copy' }, + }, + }, + } ), + } ); + getBlocksByClientId.mockReturnValue( [ block ] ); + getBlockRootClientId.mockReturnValue( 'parent-list' ); + getBlockName.mockReturnValue( 'core/list' ); + getBlockAttributes.mockReturnValue( { ordered: true } ); + attributesForCopy.clear(); + if ( state !== 'unbound' ) { + attributesForCopy.set( + block.clientId, + new Map( [ + [ + {}, + { + attributes: block.attributes, + boundAttributeNames: [ 'content' ], + getAttributesForCopy: () => + state === 'resolved' + ? { content: 'Resolved item' } + : {}, + }, + ], + ] ) + ); + } + const { onCopy } = renderMenuItem(); + await waitFor( () => expect( onCopy ).toHaveBeenCalledTimes( 1 ) ); + const pasted = parse( clipboard.writeText.mock.calls[ 0 ][ 0 ] ); + expect( pasted ).toHaveLength( 1 ); + expect( pasted[ 0 ] ).toMatchObject( { + name: 'core/list', + isValid: true, + attributes: { ordered: true }, + } ); + expect( pasted[ 0 ].innerBlocks ).toHaveLength( 1 ); + expect( pasted[ 0 ].innerBlocks[ 0 ] ).toMatchObject( { + name: 'core/list-item', + isValid: true, + attributes: { + content: + state === 'resolved' ? 'Resolved item' : 'Saved item', + }, + } ); + expect( block.attributes.content ).toBe( 'Saved item' ); + } + ); +} ); diff --git a/packages/block-editor/src/components/block-settings-menu/test/use-block-copy-to-clipboard.jsdom.test.ts b/packages/block-editor/src/components/block-settings-menu/test/use-block-copy-to-clipboard.jsdom.test.ts new file mode 100644 index 00000000000000..4c8714ad743371 --- /dev/null +++ b/packages/block-editor/src/components/block-settings-menu/test/use-block-copy-to-clipboard.jsdom.test.ts @@ -0,0 +1,345 @@ +import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'; +import type { Mock } from 'vitest'; +import { + createEvent, + fireEvent, + render, + screen, + waitFor, +} from '@testing-library/react'; +import { createElement } from '@wordpress/element'; +import useBlockCopyToClipboard, { + writeBlocksToClipboard, +} from '../use-block-copy-to-clipboard'; + +const content = { + html: '

Bound text

', + plainText: 'Bound text', + hasBoundAttributes: true, +}; + +function CopyButton( { + getContent = () => content, + onSuccess, +}: { + getContent?: Parameters< typeof useBlockCopyToClipboard >[ 0 ]; + onSuccess?: Parameters< typeof useBlockCopyToClipboard >[ 1 ]; +} ) { + const ref = useBlockCopyToClipboard( getContent, onSuccess ); + return createElement( 'button', { ref }, 'Copy' ); +} + +describe( 'block clipboard writes', () => { + let clipboardDescriptor: PropertyDescriptor | undefined; + let execCommandDescriptor: PropertyDescriptor | undefined; + let clipboard: { + write: Mock< + ( + items: { representations: Record< string, Blob > }[] + ) => Promise< void > + >; + writeText: Mock< ( text: string ) => Promise< void > >; + }; + + beforeEach( () => { + clipboardDescriptor = Object.getOwnPropertyDescriptor( + navigator, + 'clipboard' + ); + execCommandDescriptor = Object.getOwnPropertyDescriptor( + document, + 'execCommand' + ); + clipboard = { + write: vi.fn().mockResolvedValue( undefined ), + writeText: vi.fn().mockResolvedValue( undefined ), + }; + Object.defineProperty( navigator, 'clipboard', { + configurable: true, + value: clipboard, + } ); + Object.defineProperty( document, 'execCommand', { + configurable: true, + value: vi.fn().mockReturnValue( false ), + } ); + vi.stubGlobal( + 'ClipboardItem', + class { + representations: Record< string, Blob >; + constructor( representations: Record< string, Blob > ) { + this.representations = representations; + } + } + ); + } ); + + afterEach( () => { + document.getSelection()!.removeAllRanges(); + if ( clipboardDescriptor ) { + Object.defineProperty( + navigator, + 'clipboard', + clipboardDescriptor + ); + } else { + Reflect.deleteProperty( navigator, 'clipboard' ); + } + if ( execCommandDescriptor ) { + Object.defineProperty( + document, + 'execCommand', + execCommandDescriptor + ); + } else { + delete ( document as Partial< Document > ).execCommand; + } + vi.unstubAllGlobals(); + } ); + + it( 'preserves serialized block comments in the asynchronous text fallback', async () => { + const onSuccess = vi.fn(); + render( createElement( CopyButton, { onSuccess } ) ); + fireEvent.click( screen.getByRole( 'button', { name: 'Copy' } ) ); + + await waitFor( () => expect( onSuccess ).toHaveBeenCalledTimes( 1 ) ); + expect( clipboard.writeText ).toHaveBeenCalledWith( content.html ); + expect( clipboard.write ).not.toHaveBeenCalled(); + expect( screen.getByRole( 'button', { name: 'Copy' } ) ).toHaveFocus(); + } ); + + it( 'keeps unbound blocks on the serialized text path', async () => { + const onSuccess = vi.fn(); + render( + createElement( CopyButton, { + getContent: () => ( { + html: '

Stored text

', + hasBoundAttributes: false as const, + } ), + onSuccess, + } ) + ); + fireEvent.click( screen.getByRole( 'button', { name: 'Copy' } ) ); + + await waitFor( () => expect( onSuccess ).toHaveBeenCalledTimes( 1 ) ); + expect( clipboard.writeText ).toHaveBeenCalledWith( + '

Stored text

' + ); + expect( clipboard.write ).not.toHaveBeenCalled(); + } ); + + it( 'reads resolved values when the button is clicked', async () => { + let currentContent = content; + const onSuccess = vi.fn(); + render( + createElement( CopyButton, { + getContent: () => currentContent, + onSuccess, + } ) + ); + currentContent = { + ...content, + html: '

Updated text

', + plainText: 'Updated text', + }; + fireEvent.click( screen.getByRole( 'button', { name: 'Copy' } ) ); + + await waitFor( () => expect( onSuccess ).toHaveBeenCalledTimes( 1 ) ); + expect( clipboard.writeText ).toHaveBeenCalledWith( + currentContent.html + ); + } ); + + it( 'uses the copy event even when async rich clipboard writes are available', async () => { + render( + createElement( + 'div', + { + contentEditable: true, + suppressContentEditableWarning: true, + tabIndex: 0, + }, + 'Original selection' + ) + ); + const editable = screen.getByText( 'Original selection' ); + editable.focus(); + const range = document.createRange(); + range.selectNodeContents( editable ); + document.getSelection()!.removeAllRanges(); + document.getSelection()!.addRange( range ); + expect( document.getSelection()!.toString() ).toBe( + 'Original selection' + ); + const setData = vi.fn(); + let copyEvent!: Event; + vi.mocked( document.execCommand ).mockImplementation( () => { + copyEvent = createEvent.copy( screen.getByRole( 'textbox' ), { + clipboardData: { setData }, + } ); + fireEvent( screen.getByRole( 'textbox' ), copyEvent ); + return true; + } ); + + expect( await writeBlocksToClipboard( content, editable ) ).toBe( + true + ); + expect( copyEvent.defaultPrevented ).toBe( true ); + expect( clipboard.write ).not.toHaveBeenCalled(); + expect( setData ).toHaveBeenCalledWith( + 'text/plain', + content.plainText + ); + expect( setData ).toHaveBeenCalledWith( 'text/html', content.html ); + expect( screen.queryByRole( 'textbox' ) ).not.toBeInTheDocument(); + expect( editable ).toHaveFocus(); + expect( document.getSelection()!.toString() ).toBe( + 'Original selection' + ); + setData.mockClear(); + editable.dispatchEvent( copyEvent ); + expect( setData ).not.toHaveBeenCalled(); + } ); + + it( 'copies HTML with empty plain text when the fallback requires a nonempty selection', async () => { + vi.stubGlobal( 'ClipboardItem', undefined ); + const emptyTextContent = { + ...content, + html: '
', + plainText: '', + }; + render( createElement( 'button', null, 'Trigger' ) ); + const setData = vi.fn(); + vi.mocked( document.execCommand ).mockImplementation( () => { + const textarea = + screen.getByRole< HTMLTextAreaElement >( 'textbox' ); + if ( + ! textarea.value.length || + textarea.selectionStart === textarea.selectionEnd + ) { + return false; + } + fireEvent.copy( textarea, { clipboardData: { setData } } ); + return true; + } ); + + expect( + await writeBlocksToClipboard( + emptyTextContent, + screen.getByRole( 'button' ) + ) + ).toBe( true ); + expect( setData ).toHaveBeenCalledWith( + 'text/html', + emptyTextContent.html + ); + expect( setData ).toHaveBeenCalledWith( 'text/plain', '' ); + expect( screen.queryByRole( 'textbox' ) ).not.toBeInTheDocument(); + } ); + + it( 'restores an input selection when the fallback fails', async () => { + vi.stubGlobal( 'ClipboardItem', undefined ); + clipboard.writeText.mockRejectedValue( + new Error( 'Clipboard denied' ) + ); + render( + createElement( 'input', { + 'aria-label': 'Original input', + defaultValue: 'Original value', + } ) + ); + const input = screen.getByRole< HTMLInputElement >( 'textbox', { + name: 'Original input', + } ); + input.focus(); + input.setSelectionRange( 2, 6, 'backward' ); + vi.mocked( document.execCommand ).mockImplementation( () => { + throw new Error( 'Copy unavailable' ); + } ); + + expect( await writeBlocksToClipboard( content, input ) ).toBe( false ); + expect( input ).toHaveFocus(); + expect( input.selectionStart ).toBe( 2 ); + expect( input.selectionEnd ).toBe( 6 ); + expect( input.selectionDirection ).toBe( 'backward' ); + expect( screen.getAllByRole( 'textbox' ) ).toEqual( [ input ] ); + } ); + + it( 'does not report success when execCommand omits the copy event', async () => { + vi.stubGlobal( 'ClipboardItem', undefined ); + clipboard.writeText.mockRejectedValue( + new Error( 'Clipboard denied' ) + ); + vi.mocked( document.execCommand ).mockReturnValue( true ); + render( createElement( 'button', null, 'Trigger' ) ); + + expect( + await writeBlocksToClipboard( + content, + screen.getByRole( 'button' ) + ) + ).toBe( false ); + } ); + + it( 'does not run success callbacks if both clipboard methods fail', async () => { + clipboard.writeText.mockRejectedValue( + new Error( 'Clipboard denied' ) + ); + const onSuccess = vi.fn(); + render( createElement( CopyButton, { onSuccess } ) ); + fireEvent.click( screen.getByRole( 'button', { name: 'Copy' } ) ); + + await waitFor( () => + expect( document.execCommand ).toHaveBeenCalled() + ); + expect( onSuccess ).not.toHaveBeenCalled(); + expect( screen.queryByRole( 'textbox' ) ).not.toBeInTheDocument(); + } ); + + it( 'retains the serialized text fallback when there are no bindings', async () => { + Object.defineProperty( navigator, 'clipboard', { + configurable: true, + value: undefined, + } ); + vi.mocked( document.execCommand ).mockImplementation( () => { + expect( screen.getByRole( 'textbox' ) ).toHaveValue( + '

Stored text

' + ); + return true; + } ); + const onSuccess = vi.fn(); + render( + createElement( CopyButton, { + getContent: () => ( { + html: '

Stored text

', + hasBoundAttributes: false as const, + } ), + onSuccess, + } ) + ); + fireEvent.click( screen.getByRole( 'button', { name: 'Copy' } ) ); + + await waitFor( () => expect( onSuccess ).toHaveBeenCalledTimes( 1 ) ); + expect( screen.queryByRole( 'textbox' ) ).not.toBeInTheDocument(); + } ); + + it( 'runs the success callback after unmount without restoring focus to the removed button', async () => { + let finishWrite!: () => void; + clipboard.writeText.mockReturnValue( + new Promise< void >( ( resolve ) => { + finishWrite = resolve; + } ) + ); + const onSuccess = vi.fn(); + const { unmount } = render( + createElement( CopyButton, { onSuccess } ) + ); + const button = screen.getByRole( 'button', { name: 'Copy' } ); + const focus = vi.spyOn( button, 'focus' ); + fireEvent.click( button ); + unmount(); + finishWrite(); + + await waitFor( () => expect( onSuccess ).toHaveBeenCalledTimes( 1 ) ); + expect( focus ).not.toHaveBeenCalled(); + } ); +} ); diff --git a/packages/block-editor/src/components/block-settings-menu/use-block-copy-to-clipboard.ts b/packages/block-editor/src/components/block-settings-menu/use-block-copy-to-clipboard.ts new file mode 100644 index 00000000000000..2c5f3c7d2f59a4 --- /dev/null +++ b/packages/block-editor/src/components/block-settings-menu/use-block-copy-to-clipboard.ts @@ -0,0 +1,137 @@ +import { useRefEffect } from '@wordpress/compose'; +import { useLayoutEffect, useRef } from '@wordpress/element'; + +type ClipboardContent = + | { html: string; plainText: string; hasBoundAttributes: boolean } + | { html: string; hasBoundAttributes: false }; + +function copyBlocksWithEvent( + { html, plainText }: { html?: string; plainText: string }, + ownerDocument: Document +) { + const selection = ownerDocument.getSelection(); + const ranges = selection + ? Array.from( { length: selection.rangeCount }, ( _, index ) => + selection.getRangeAt( index ).cloneRange() + ) + : []; + const activeElement = ownerDocument.activeElement as HTMLElement | null; + const activeInput = activeElement as + HTMLInputElement | HTMLTextAreaElement | null; + const inputSelection = + activeInput && typeof activeInput.selectionStart === 'number' + ? { + start: activeInput.selectionStart, + end: activeInput.selectionEnd, + direction: activeInput.selectionDirection, + } + : undefined; + const textarea = ownerDocument.createElement( 'textarea' ); + textarea.value = html === undefined ? plainText : plainText || ' '; + textarea.setAttribute( 'readonly', '' ); + textarea.style.position = 'fixed'; + textarea.style.left = '-9999px'; + textarea.style.top = '-9999px'; + let copied = false; + const onCopy = ( event: ClipboardEvent ) => { + if ( + html === undefined || + event.target !== textarea || + ! event.clipboardData + ) { + return; + } + event.clipboardData.setData( 'text/html', html ); + event.clipboardData.setData( 'text/plain', plainText ); + event.preventDefault(); + copied = true; + }; + try { + ownerDocument.body.appendChild( textarea ); + ownerDocument.addEventListener( 'copy', onCopy, true ); + textarea.focus( { preventScroll: true } ); + textarea.select(); + return ( + ownerDocument.execCommand( 'copy' ) && + ( html === undefined || copied ) + ); + } catch { + return false; + } finally { + ownerDocument.removeEventListener( 'copy', onCopy, true ); + textarea.remove(); + activeElement?.focus( { preventScroll: true } ); + if ( inputSelection ) { + activeInput!.setSelectionRange( + inputSelection.start, + inputSelection.end!, + inputSelection.direction! + ); + } else if ( selection ) { + selection.removeAllRanges(); + ranges.forEach( ( range ) => selection.addRange( range ) ); + } + } +} + +export async function writeBlocksToClipboard( + content: { html: string; plainText: string }, + trigger?: HTMLElement | null +) { + const ownerDocument = trigger?.ownerDocument; + if ( ! ownerDocument ) { + return false; + } + // Async HTML writes can strip the comments that carry block attributes. + // Dispatch the copy event while the menu click still has user activation. + if ( copyBlocksWithEvent( content, ownerDocument ) ) { + return true; + } + // Keep the serialized block comments if the copy event is unavailable. + // A successful async HTML write can sanitize them and lose the bindings. + return writeTextToClipboard( content.html, trigger! ); +} + +async function writeTextToClipboard( text: string, trigger: HTMLElement ) { + const ownerDocument = trigger.ownerDocument; + const view = ownerDocument.defaultView; + try { + if ( view?.navigator.clipboard?.writeText ) { + await view.navigator.clipboard.writeText( text ); + return true; + } + return copyBlocksWithEvent( { plainText: text }, ownerDocument ); + } catch { + return false; + } +} + +export default function useBlockCopyToClipboard( + getContent: () => ClipboardContent, + onSuccess?: () => void +) { + const latestRef = useRef( { getContent, onSuccess } ); + useLayoutEffect( () => { + latestRef.current = { getContent, onSuccess }; + }, [ getContent, onSuccess ] ); + return useRefEffect< HTMLElement >( ( node ) => { + let isActive = true; + const onClick = async () => { + const content = latestRef.current.getContent(); + const success = content.hasBoundAttributes + ? await writeBlocksToClipboard( content, node ) + : await writeTextToClipboard( content.html, node ); + if ( success ) { + if ( isActive ) { + node.focus(); + } + latestRef.current.onSuccess?.(); + } + }; + node.addEventListener( 'click', onClick ); + return () => { + isActive = false; + node.removeEventListener( 'click', onClick ); + }; + }, [] ); +} diff --git a/packages/block-editor/src/components/list-view/use-clipboard-handler.ts b/packages/block-editor/src/components/list-view/use-clipboard-handler.ts index 677fe51e4ab3dc..080766eb00c505 100644 --- a/packages/block-editor/src/components/list-view/use-clipboard-handler.ts +++ b/packages/block-editor/src/components/list-view/use-clipboard-handler.ts @@ -1,9 +1,11 @@ import { useDispatch, useRegistry, useSelect } from '@wordpress/data'; import { useRefEffect } from '@wordpress/compose'; +import { useContext } from '@wordpress/element'; import { store as blockEditorStore } from '../../store'; import { useNotifyCopy } from '../../utils/use-notify-copy'; import { focusListItem } from './utils'; import { getPasteBlocks, setClipboardBlocks } from '../writing-flow/utils'; +import { BlockRefs } from '../provider/block-refs-provider'; import type { TreeBlock } from '../../store/types'; import type { ListViewSelectBlock } from './types'; @@ -15,6 +17,7 @@ export default function useClipboardHandler( { selectBlock: ListViewSelectBlock; } ) { const registry = useRegistry(); + const { attributesForCopy } = useContext( BlockRefs ); const { getBlockOrder, getBlockRootClientId, @@ -118,7 +121,12 @@ export default function useClipboardHandler( { const blocks = getBlocksByClientId( selectedBlockClientIds ) as TreeBlock[]; - setClipboardBlocks( event, blocks, registry ); + setClipboardBlocks( + event, + blocks, + registry, + attributesForCopy + ); } if ( event.type === 'cut' ) { diff --git a/packages/block-editor/src/components/provider/block-refs-provider.tsx b/packages/block-editor/src/components/provider/block-refs-provider.tsx index a0c01216dfa17b..b6141c04d1f8fc 100644 --- a/packages/block-editor/src/components/provider/block-refs-provider.tsx +++ b/packages/block-editor/src/components/provider/block-refs-provider.tsx @@ -1,6 +1,11 @@ import { createContext, useMemo } from '@wordpress/element'; import { observableMap } from '@wordpress/compose'; -import type { BlockRefsContextValue, BlockRefsProviderProps } from './types'; +import type { Block } from '@wordpress/blocks'; +import type { + AttributesForCopy, + BlockRefsContextValue, + BlockRefsProviderProps, +} from './types'; // `eventHandlers` maps a block's client ID to a ref holding its `wrapperProps` // event handlers, so the writing flow host can call them for a block that @@ -9,12 +14,49 @@ import type { BlockRefsContextValue, BlockRefsProviderProps } from './types'; export const BlockRefs = createContext< BlockRefsContextValue >( { refsMap: observableMap(), eventHandlers: new Map(), + attributesForCopy: new Map(), } ); BlockRefs.displayName = 'BlockRefsContext'; +export function getBoundAttributesForCopy( + block: Pick< Block, 'clientId' | 'attributes' >, + attributesForCopy?: AttributesForCopy +) { + const instances = attributesForCopy?.get( block.clientId ); + if ( instances?.size !== 1 ) { + return; + } + const { attributes, boundAttributeNames, getAttributesForCopy } = instances + .values() + .next().value!; + if ( attributes !== block.attributes ) { + return; + } + // A copy request can omit attributes that only have display placeholders. + const boundAttributes = getAttributesForCopy(); + const availableAttributeNames = boundAttributeNames.filter( + ( attributeName ) => + Object.hasOwn( boundAttributes, attributeName ) && + boundAttributes[ attributeName ] !== undefined + ); + if ( ! availableAttributeNames.length ) { + return; + } + return Object.fromEntries( + availableAttributeNames.map( ( attributeName ) => [ + attributeName, + boundAttributes[ attributeName ], + ] ) + ); +} + export function BlockRefsProvider( { children }: BlockRefsProviderProps ) { const value = useMemo< BlockRefsContextValue >( - () => ( { refsMap: observableMap(), eventHandlers: new Map() } ), + () => ( { + refsMap: observableMap(), + eventHandlers: new Map(), + attributesForCopy: new Map(), + } ), [] ); return ( diff --git a/packages/block-editor/src/components/provider/test/block-refs-provider.jsdom.test.ts b/packages/block-editor/src/components/provider/test/block-refs-provider.jsdom.test.ts new file mode 100644 index 00000000000000..05699d1bef454d --- /dev/null +++ b/packages/block-editor/src/components/provider/test/block-refs-provider.jsdom.test.ts @@ -0,0 +1,86 @@ +import { describe, expect, it, vi } from 'vitest'; +import { getBoundAttributesForCopy } from '../block-refs-provider'; + +describe( 'bound attributes for copying', () => { + const block = { + clientId: 'bound-block', + attributes: { content: 'Saved fallback' }, + }; + + function createSnapshot( + copyAttributes: Record< string, unknown > = { + content: 'Resolved value', + } + ) { + return { + attributes: block.attributes, + boundAttributeNames: [ 'content' ], + getAttributesForCopy: vi.fn( () => copyAttributes ), + }; + } + + it( 'resolves copy attributes lazily for a unique current instance', () => { + const snapshot = createSnapshot(); + const attributesForCopy = new Map( [ + [ block.clientId, new Map( [ [ {}, snapshot ] ] ) ], + ] ); + + expect( snapshot.getAttributesForCopy ).not.toHaveBeenCalled(); + expect( getBoundAttributesForCopy( block, attributesForCopy ) ).toEqual( + { + content: 'Resolved value', + } + ); + expect( snapshot.getAttributesForCopy ).toHaveBeenCalledOnce(); + } ); + + it.each( [ {}, { content: undefined } ] )( + 'keeps display placeholders out when copy values are %s', + ( copyAttributes ) => { + const snapshot = createSnapshot( copyAttributes ); + const attributesForCopy = new Map( [ + [ block.clientId, new Map( [ [ {}, snapshot ] ] ) ], + ] ); + + expect( + getBoundAttributesForCopy( block, attributesForCopy ) + ).toBeUndefined(); + expect( snapshot.getAttributesForCopy ).toHaveBeenCalledOnce(); + } + ); + + it( 'does not resolve a stale instance', () => { + const snapshot = createSnapshot(); + const attributesForCopy = new Map( [ + [ block.clientId, new Map( [ [ {}, snapshot ] ] ) ], + ] ); + + expect( + getBoundAttributesForCopy( + { ...block, attributes: { ...block.attributes } }, + attributesForCopy + ) + ).toBeUndefined(); + expect( snapshot.getAttributesForCopy ).not.toHaveBeenCalled(); + } ); + + it( 'does not resolve duplicate mounted instances', () => { + const snapshot = createSnapshot(); + const otherSnapshot = createSnapshot(); + const attributesForCopy = new Map( [ + [ + block.clientId, + new Map( [ + [ {}, snapshot ], + [ {}, otherSnapshot ], + ] ), + ], + ] ); + + expect( + getBoundAttributesForCopy( block, attributesForCopy ) + ).toBeUndefined(); + expect( snapshot.getAttributesForCopy ).not.toHaveBeenCalled(); + expect( otherSnapshot.getAttributesForCopy ).not.toHaveBeenCalled(); + } ); +} ); diff --git a/packages/block-editor/src/components/provider/types.ts b/packages/block-editor/src/components/provider/types.ts index 8c1ee86e25f9b5..f021fe08f92ea5 100644 --- a/packages/block-editor/src/components/provider/types.ts +++ b/packages/block-editor/src/components/provider/types.ts @@ -25,8 +25,21 @@ declare global { export interface BlockRefsContextValue { refsMap: ObservableMap< string, Element | null >; eventHandlers: Map< string, { current?: BlockEventHandlers } >; + attributesForCopy?: AttributesForCopy; } +/** Resolved bound attributes registered by each mounted block instance. */ +export interface BoundAttributesForCopy { + attributes: Block[ 'attributes' ]; + boundAttributeNames: string[]; + getAttributesForCopy: () => Record< string, unknown >; +} + +export type AttributesForCopy = Map< + string, + Map< object, BoundAttributesForCopy > +>; + /** * Props of `BlockRefsProvider`. */ diff --git a/packages/block-editor/src/components/use-paste-styles/index.ts b/packages/block-editor/src/components/use-paste-styles/index.ts index 71227f14baff48..0dc3f52480e57b 100644 --- a/packages/block-editor/src/components/use-paste-styles/index.ts +++ b/packages/block-editor/src/components/use-paste-styles/index.ts @@ -5,6 +5,10 @@ import { useDispatch, useRegistry } from '@wordpress/data'; import { store as noticesStore } from '@wordpress/notices'; import { __, sprintf } from '@wordpress/i18n'; import { store as blockEditorStore } from '../../store'; +import { + normalizeClipboardHTML, + stripBlockClipboardWrapper, +} from '../../utils/block-clipboard'; import { hasAlignSupport, hasBorderSupport, @@ -20,31 +24,70 @@ import { } from '../../hooks/supports'; /** - * Determine if the copied text looks like serialized blocks or not. - * Since plain text will always get parsed into a freeform block, - * we check that if the parsed blocks is anything other than that. + * Parse a clipboard representation that contains serialized blocks. * * @param text The copied text. - * @return True if the text looks like serialized blocks, false otherwise. + * @param type The clipboard representation's MIME type. + * @return The serialized blocks, or an empty array for other content. */ -function hasSerializedBlocks( text: string ): boolean { +function getSerializedBlocks( text: string, type = 'text/plain' ): Block[] { try { - const blocks = parse( text, { + const normalizedText = + type === 'text/html' ? normalizeClipboardHTML( text ) : text; + const content = stripBlockClipboardWrapper( normalizedText ); + const blocks = parse( content, { __unstableSkipMigrationLogs: true, __unstableSkipAutop: true, } ); if ( blocks.length === 1 && blocks[ 0 ].name === 'core/freeform' ) { - // It's likely that the text is just plain text and not serialized blocks. - return false; + return []; + } + if ( content !== normalizedText && blocks.length === 1 ) { + return blocks[ 0 ].innerBlocks; } - return true; + return blocks; } catch { - // Parsing error, the text is not serialized blocks. - // (Even though that it technically won't happen) - return false; + return []; } } +async function readCopiedBlocks( clipboard: Clipboard ): Promise< Block[] > { + if ( clipboard.read ) { + try { + const items = await clipboard.read(); + let hasReadError = false; + // Bound blocks have serialized markup in HTML and visible text in + // plain text. Copy styles and unbound blocks use serialized text. + for ( const type of [ 'text/html', 'text/plain' ] ) { + for ( const item of items ) { + if ( ! item.types.includes( type ) ) { + continue; + } + try { + const blocks = getSerializedBlocks( + await ( await item.getType( type ) ).text(), + type + ); + if ( blocks.length ) { + return blocks; + } + } catch { + hasReadError = true; + // An advertised representation can be unavailable. + // Try the others from this successful clipboard read. + } + } + } + if ( ! hasReadError ) { + return []; + } + } catch { + // Some browsers only allow the legacy text read. + } + } + return getSerializedBlocks( await clipboard.readText() ); +} + /** * Style attributes are attributes being added in `block-editor/src/hooks/*`. * (Except for some unrelated to style like `anchor` or `settings`.) @@ -145,7 +188,7 @@ export default function usePasteStyles() { return useCallback( async ( targetBlocks: Block[] ) => { - let html = ''; + let copiedBlocks: Block[]; try { // `http:` sites won't have the clipboard property on navigator. // (with the exception of localhost.) @@ -159,7 +202,9 @@ export default function usePasteStyles() { return; } - html = await window.navigator.clipboard.readText(); + copiedBlocks = await readCopiedBlocks( + window.navigator.clipboard + ); } catch { // Possibly the permission is denied. createErrorNotice( @@ -173,8 +218,7 @@ export default function usePasteStyles() { return; } - // Abort if the copied text is empty or doesn't look like serialized blocks. - if ( ! html || ! hasSerializedBlocks( html ) ) { + if ( ! copiedBlocks.length ) { createWarningNotice( __( "Unable to paste styles. Block styles couldn't be found within the copied content." @@ -186,8 +230,6 @@ export default function usePasteStyles() { return; } - const copiedBlocks = parse( html ); - if ( copiedBlocks.length === 1 ) { // Apply styles of the block to all the target blocks. registry.batch( () => { diff --git a/packages/block-editor/src/components/use-paste-styles/test/index.jsdom.test.ts b/packages/block-editor/src/components/use-paste-styles/test/index.jsdom.test.ts new file mode 100644 index 00000000000000..c525c73dba87ac --- /dev/null +++ b/packages/block-editor/src/components/use-paste-styles/test/index.jsdom.test.ts @@ -0,0 +1,510 @@ +import { + afterAll, + afterEach, + beforeAll, + describe, + expect, + it, + vi, +} from 'vitest'; +import { act, renderHook } from '@testing-library/react'; +import { + createBlock, + getBlockTypes, + registerBlockType, + serialize, + store as blocksStore, + unregisterBlockType, + __unstableGetInnerBlocksProps as getInnerBlocksProps, +} from '@wordpress/blocks'; +import { createRegistry, RegistryProvider } from '@wordpress/data'; +import { createElement, RawHTML } from '@wordpress/element'; +import { store as noticesStore } from '@wordpress/notices'; +import type { ReactNode } from 'react'; +import { store as blockEditorStore } from '../../../store'; +import { + getClipboardBlocksContent, + getPasteBlocks, + requiresWrapperOnCopy, +} from '../../writing-flow/utils'; +import { BLOCK_CLIPBOARD_WRAPPER } from '../../../utils/block-clipboard'; +import usePasteStyles from '../'; + +const blockName = 'core/paste-styles-test'; +const style = { typography: { fontSize: '23px' } }; + +function copiedMarkup() { + return serialize( [ + createBlock( blockName, { + content: 'Copied text', + style, + metadata: { + bindings: { content: { source: 'testing/copy' } }, + }, + } ), + ] ); +} + +function copiedGroupMarkup() { + return serialize( [ + createBlock( 'core/group', { style }, [ + createBlock( 'core/html', { + content: + '

Child text

', + } ), + ] ), + ] ); +} + +function clipboardItem( representations: Record< string, string | Error > ) { + return { + types: Object.keys( representations ), + getType: vi.fn( async ( type: string ) => { + const value = representations[ type ]; + if ( typeof value !== 'string' ) { + throw value; + } + return { text: async () => value } as Blob; + } ), + } as unknown as ClipboardItem; +} + +function copiedListMarkup( copyWholeList = false ) { + const registry = createRegistry(); + registry.register( blocksStore ); + registry.register( blockEditorStore ); + registry.dispatch( blocksStore ).addBlockTypes( getBlockTypes() ); + const item = createBlock( 'core/list-item', { + content: '', + fontSize: 'large', + metadata: { bindings: { content: { source: 'testing/copy' } } }, + } ); + const list = createBlock( + 'core/list', + { + ordered: true, + fontSize: 'small', + }, + [ item ] + ); + registry.dispatch( blockEditorStore ).resetBlocks( [ list ] ); + const attributesForCopy = new Map( [ + [ + item.clientId, + new Map( [ + [ + {}, + { + attributes: item.attributes, + getAttributesForCopy: () => ( { + ...item.attributes, + content: 'Bound item', + } ), + boundAttributeNames: [ 'content' ], + }, + ], + ] ), + ], + ] ); + return getClipboardBlocksContent( + [ copyWholeList ? list : item ], + registry, + attributesForCopy, + { addWrapper: true } + ); +} + +async function pasteStyles( clipboard: Partial< Clipboard > ) { + vi.stubGlobal( 'navigator', { clipboard } ); + const registry = createRegistry(); + registry.register( blocksStore ); + registry.register( blockEditorStore ); + registry.register( noticesStore ); + registry.dispatch( blocksStore ).addBlockTypes( getBlockTypes() ); + const target = createBlock( blockName, { content: 'Target text' } ); + await registry.dispatch( blockEditorStore ).resetBlocks( [ target ] ); + const { result } = renderHook( usePasteStyles, { + wrapper: ( { children }: { children: ReactNode } ) => + createElement( RegistryProvider, { value: registry }, children ), + } ); + + await act( () => result.current( [ target ] ) ); + + return { + attributes: registry + .select( blockEditorStore ) + .getBlockAttributes( target.clientId )!, + notices: registry.select( noticesStore ).getNotices(), + }; +} + +describe( 'usePasteStyles clipboard representations', () => { + beforeAll( () => { + registerBlockType< { + content: string; + style: Record< string, unknown >; + fontSize: string; + metadata: Record< string, unknown >; + } >( blockName, { + title: 'Paste styles test', + category: 'text', + apiVersion: 3, + attributes: { + content: { type: 'string', source: 'html', selector: 'p' }, + style: { type: 'object' }, + fontSize: { type: 'string' }, + metadata: { type: 'object' }, + }, + supports: { typography: { fontSize: true } }, + save: ( { attributes } ) => + createElement( + 'p', + null, + createElement( RawHTML, null, attributes.content ) + ), + } ); + for ( const name of [ 'core/list', 'core/list-item' ] ) { + registerBlockType< { + content: string; + ordered: boolean; + fontSize: string; + metadata: Record< string, unknown >; + } >( name, { + apiVersion: 3, + title: name, + category: 'text', + attributes: { + content: { type: 'string', source: 'html', selector: 'li' }, + ordered: { type: 'boolean' }, + fontSize: { type: 'string' }, + metadata: { type: 'object' }, + }, + supports: { typography: { fontSize: true } }, + ...( name === 'core/list-item' + ? { [ requiresWrapperOnCopy ]: true } + : {} ), + save: ( { attributes } ) => + name === 'core/list-item' + ? createElement( + 'li', + null, + createElement( + RawHTML, + null, + attributes.content + ) + ) + : createElement( + attributes.ordered ? 'ol' : 'ul', + getInnerBlocksProps() + ), + } ); + } + registerBlockType< { style: Record< string, unknown > } >( + 'core/group', + { + apiVersion: 3, + title: 'Group', + category: 'design', + attributes: { style: { type: 'object' } }, + supports: { typography: { fontSize: true } }, + save: () => createElement( 'div', getInnerBlocksProps() ), + } + ); + registerBlockType< { content: string } >( 'core/html', { + apiVersion: 3, + title: 'Custom HTML', + category: 'text', + attributes: { content: { type: 'string', source: 'html' } }, + save: ( { attributes } ) => + createElement( RawHTML, null, attributes.content ), + } ); + } ); + + afterAll( () => { + for ( const name of [ + blockName, + 'core/list', + 'core/list-item', + 'core/group', + 'core/html', + ] ) { + unregisterBlockType( name ); + } + } ); + afterEach( () => vi.unstubAllGlobals() ); + + it.each( [ 'ClipboardItem', 'readText' ] )( + 'keeps Group styles when plain text contains literal fragment comments (%s)', + async ( transport ) => { + const text = copiedGroupMarkup(); + const result = await pasteStyles( + transport === 'ClipboardItem' + ? { + read: vi + .fn() + .mockResolvedValue( [ + clipboardItem( { 'text/plain': text } ), + ] ), + } + : { readText: vi.fn().mockResolvedValue( text ) } + ); + expect( result.attributes.style ).toEqual( style ); + expect( result.attributes.content ).toBe( 'Target text' ); + } + ); + + it.each( [ + [ 'html', '', '' ], + [ 'text', '', '' ], + [ 'html', ' \n\t', '' ], + [ 'html', `\n`, '' ], + [ + 'html', + '\n', + '\n', + ], + ] )( + 'keeps the List wrapper for Paste and the selected item styles for Paste styles (%s, %s)', + async ( representation, prefix, suffix ) => { + const copied = copiedListMarkup(); + const { plainText } = copied; + const html = prefix + copied.html + suffix; + const result = await pasteStyles( + representation === 'html' + ? { + read: vi.fn().mockResolvedValue( [ + clipboardItem( { + 'text/html': html, + 'text/plain': plainText, + } ), + ] ), + } + : { readText: vi.fn().mockResolvedValue( html ) } + ); + expect( result.attributes.fontSize ).toBe( 'large' ); + expect( result.attributes.content ).toBe( 'Target text' ); + expect( result.attributes.metadata ).toBeUndefined(); + const representations: Record< string, string > = + representation === 'html' + ? { 'text/html': html, 'text/plain': plainText } + : { 'text/plain': html }; + const pasted = getPasteBlocks( { + clipboardData: { + getData: ( type: string ) => representations[ type ] ?? '', + files: [], + items: [], + } as unknown as DataTransfer, + } ); + expect( console ).toHaveLogged(); + expect( pasted ).toMatchObject( [ + { + name: 'core/list', + isValid: true, + attributes: { ordered: true, fontSize: 'small' }, + innerBlocks: [ + { + name: 'core/list-item', + isValid: true, + attributes: { + content: 'Bound item', + fontSize: 'large', + metadata: { + bindings: { + content: { source: 'testing/copy' }, + }, + }, + }, + }, + ], + }, + ] ); + expect( serialize( pasted ) ).not.toContain( + BLOCK_CLIPBOARD_WRAPPER + ); + expect( plainText ).toBe( 'Bound item' ); + } + ); + + it( 'keeps the styles of an actually selected List', async () => { + const { html } = copiedListMarkup( true ); + expect( html ).not.toContain( BLOCK_CLIPBOARD_WRAPPER ); + const result = await pasteStyles( { + read: vi + .fn() + .mockResolvedValue( [ + clipboardItem( { 'text/html': html } ), + ] ), + } ); + expect( result.attributes.fontSize ).toBe( 'small' ); + } ); + + it( 'uses serialized HTML and applies only its styles', async () => { + const readText = vi.fn(); + const result = await pasteStyles( { + read: vi.fn().mockResolvedValue( [ + clipboardItem( { + 'text/html': copiedMarkup(), + 'text/plain': 'Copied text', + } ), + ] ), + readText, + } ); + + expect( result.attributes ).toMatchObject( { + content: 'Target text', + style, + } ); + expect( result.attributes.metadata ).toBeUndefined(); + expect( result.notices ).toMatchObject( [ { status: 'success' } ] ); + expect( readText ).not.toHaveBeenCalled(); + } ); + + it( 'uses the same item plain text when its HTML representation is unavailable', async () => { + const item = clipboardItem( { + 'text/html': new DOMException( + 'Unavailable HTML', + 'NotFoundError' + ), + 'text/plain': copiedMarkup(), + } ); + const readText = vi + .fn() + .mockRejectedValue( + new DOMException( + 'No second clipboard activation', + 'NotAllowedError' + ) + ); + const result = await pasteStyles( { + read: vi.fn().mockResolvedValue( [ item ] ), + readText, + } ); + + expect( result.attributes.style ).toEqual( style ); + expect( item.getType ).toHaveBeenCalledWith( 'text/plain' ); + expect( readText ).not.toHaveBeenCalled(); + expect( result.notices ).toMatchObject( [ { status: 'success' } ] ); + } ); + + it( 'uses the next item when an HTML blob cannot be read', async () => { + const unavailableItem = { + types: [ 'text/html' ], + getType: vi.fn().mockResolvedValue( { + text: vi + .fn() + .mockRejectedValue( new Error( 'Unreadable HTML' ) ), + } ), + } as unknown as ClipboardItem; + const readText = vi + .fn() + .mockRejectedValue( + new DOMException( + 'No second clipboard activation', + 'NotAllowedError' + ) + ); + const result = await pasteStyles( { + read: vi + .fn() + .mockResolvedValue( [ + unavailableItem, + clipboardItem( { 'text/html': copiedMarkup() } ), + ] ), + readText, + } ); + + expect( result.attributes.style ).toEqual( style ); + expect( readText ).not.toHaveBeenCalled(); + } ); + + it( 'reads serialized plain text when the HTML has no block data', async () => { + const readText = vi.fn(); + const result = await pasteStyles( { + read: vi.fn().mockResolvedValue( [ + clipboardItem( { + 'text/html': '

Copied text

', + 'text/plain': copiedMarkup(), + } ), + ] ), + readText, + } ); + + expect( result.attributes.style ).toEqual( style ); + expect( readText ).not.toHaveBeenCalled(); + } ); + + it.each( [ 'unavailable', 'denied' ] )( + 'reads legacy serialized text when rich reading is %s', + async ( richReading ) => { + const readText = vi.fn().mockResolvedValue( copiedMarkup() ); + const result = await pasteStyles( { + ...( richReading === 'denied' + ? { + read: vi + .fn() + .mockRejectedValue( new Error( 'Denied' ) ), + } + : {} ), + readText, + } ); + + expect( result.attributes.style ).toEqual( style ); + expect( readText ).toHaveBeenCalledOnce(); + } + ); + + it( 'reads legacy serialized text after all item representations fail', async () => { + const readText = vi.fn().mockResolvedValue( copiedMarkup() ); + const result = await pasteStyles( { + read: vi.fn().mockResolvedValue( [ + clipboardItem( { + 'text/html': new Error( 'Unreadable HTML' ), + } ), + ] ), + readText, + } ); + + expect( result.attributes.style ).toEqual( style ); + expect( readText ).toHaveBeenCalledOnce(); + } ); + + it( 'reports an error when the item and legacy read are denied', async () => { + const result = await pasteStyles( { + read: vi.fn().mockResolvedValue( [ + clipboardItem( { + 'text/html': new Error( 'Denied HTML' ), + } ), + ] ), + readText: vi.fn().mockRejectedValue( new Error( 'Denied' ) ), + } ); + + expect( result.attributes.style ).toBeUndefined(); + expect( result.notices ).toMatchObject( [ { status: 'error' } ] ); + } ); + + it( 'warns when readable representations contain no serialized blocks', async () => { + const result = await pasteStyles( { + read: vi.fn().mockResolvedValue( [ + clipboardItem( { + 'text/html': '

Plain HTML

', + 'text/plain': 'Plain text', + } ), + ] ), + readText: vi.fn(), + } ); + + expect( result.attributes.style ).toBeUndefined(); + expect( result.notices ).toMatchObject( [ { status: 'warning' } ] ); + } ); + + it( 'reports an error when both clipboard reads are denied', async () => { + const result = await pasteStyles( { + read: vi.fn().mockRejectedValue( new Error( 'Denied' ) ), + readText: vi.fn().mockRejectedValue( new Error( 'Denied' ) ), + } ); + + expect( result.attributes.style ).toBeUndefined(); + expect( result.notices ).toMatchObject( [ { status: 'error' } ] ); + } ); +} ); diff --git a/packages/block-editor/src/components/writing-flow/test/use-bound-block-clipboard.jsdom.test.ts b/packages/block-editor/src/components/writing-flow/test/use-bound-block-clipboard.jsdom.test.ts new file mode 100644 index 00000000000000..78f6ad3030e91d --- /dev/null +++ b/packages/block-editor/src/components/writing-flow/test/use-bound-block-clipboard.jsdom.test.ts @@ -0,0 +1,549 @@ +import { + afterAll, + afterEach, + beforeAll, + describe, + expect, + it, + vi, +} from 'vitest'; +import { act, render, screen } from '@testing-library/react'; +import type { ComponentType, ContextType } from 'react'; +import { + createBlock, + parse, + registerBlockType, + unregisterBlockType, +} from '@wordpress/blocks'; +import type { Block } from '@wordpress/blocks'; +import { + createElement, + RawHTML, + useContext, + useLayoutEffect, +} from '@wordpress/element'; +import { useRegistry } from '@wordpress/data'; +import { store as blockEditorStore } from '../../../store'; +import { + BlockRefs, + BlockRefsProvider, +} from '../../provider/block-refs-provider'; +import withRegistryProvider from '../../provider/with-registry-provider'; +import useCanvasClipboardHandler from '../use-clipboard-handler'; +import useListViewClipboardHandler from '../../list-view/use-clipboard-handler'; +import type { BlockAttributes } from '../../../store/types'; + +type ClipboardContext = { + registry: ReturnType< typeof useRegistry >; + attributesForCopy: NonNullable< + ContextType< typeof BlockRefs >[ 'attributesForCopy' ] + >; +}; + +type ClipboardSurfaceProps = { + Surface: ComponentType< { focusedClientId: string } >; + focusedClientId: string; + onReady: ( context: ClipboardContext ) => void; +}; + +const bindings = { + content: { source: 'core/post-meta', args: { key: 'movie_field' } }, +}; + +function CanvasSurface() { + const ref = useCanvasClipboardHandler(); + return createElement( 'div', { + ref, + tabIndex: -1, + 'data-testid': 'surface', + } ); +} + +function ListViewSurface( { focusedClientId }: { focusedClientId: string } ) { + const ref = useListViewClipboardHandler( { selectBlock: vi.fn() } ); + return createElement( + 'div', + { ref }, + createElement( 'div', { + role: 'row', + 'data-block': focusedClientId, + tabIndex: -1, + 'data-testid': 'surface', + } ) + ); +} + +function ClipboardSurface( { + Surface, + focusedClientId, + onReady, +}: ClipboardSurfaceProps ) { + const registry = useRegistry(); + const { attributesForCopy } = useContext( BlockRefs ); + useLayoutEffect( () => { + onReady( { registry, attributesForCopy: attributesForCopy! } ); + }, [ registry, attributesForCopy, onReady ] ); + return createElement( Surface, { focusedClientId } ); +} + +// The registry wrapper forwards the surface props in addition to its own props. +const ClipboardProvider = ( + withRegistryProvider as unknown as ( + component: ComponentType< ClipboardSurfaceProps > + ) => ComponentType< ClipboardSurfaceProps > + )( ( props: ClipboardSurfaceProps ) => + createElement( + BlockRefsProvider, + null, + createElement( ClipboardSurface, props ) + ) +); + +function mountClipboard( + Surface: ClipboardSurfaceProps[ 'Surface' ], + blocks: Block[] +) { + let clipboardContext!: ClipboardContext; + render( + createElement( ClipboardProvider, { + Surface, + focusedClientId: blocks[ 0 ].clientId, + onReady: ( context: ClipboardContext ) => { + clipboardContext = context; + }, + } ) + ); + const { registry, attributesForCopy } = clipboardContext; + act( () => { + registry.dispatch( blockEditorStore ).resetBlocks( blocks ); + registry + .dispatch( blockEditorStore ) + .selectBlock( blocks[ 0 ].clientId ); + } ); + const boundBlock = registry + .select( blockEditorStore ) + .getBlock( blocks[ 0 ].clientId )!; + registerResolvedContent( + attributesForCopy, + boundBlock, + 'Bound text' + ); + const surface = screen.getByTestId( 'surface' ); + surface.focus(); + return { registry, surface, boundBlock, attributesForCopy }; +} + +function registerResolvedContent( + attributesForCopy: ClipboardContext[ 'attributesForCopy' ], + block: Block< BlockAttributes >, + content: string +) { + attributesForCopy.set( + block.clientId, + new Map( [ + [ + {}, + { + attributes: block.attributes, + getAttributesForCopy: () => ( { + ...block.attributes, + content, + } ), + boundAttributeNames: [ 'content' ], + }, + ], + ] ) + ); +} + +function selectPartialBlocks( + registry: ClipboardContext[ 'registry' ], + blocks: Block[], + startOffset: number, + endOffset: number, + reverse: boolean +) { + const start = { + clientId: blocks[ 0 ].clientId, + attributeKey: 'content', + offset: startOffset, + }; + const end = { + clientId: blocks[ blocks.length - 1 ].clientId, + attributeKey: 'content', + offset: endOffset, + }; + act( () => { + registry.dispatch( blockEditorStore ).selectionChange( { + start: reverse ? end : start, + end: reverse ? start : end, + } ); + } ); +} + +function dispatchClipboardEvent( surface: HTMLElement, type: 'copy' | 'cut' ) { + const clipboardContent = new Map< string, string >(); + const event = new Event( type, { bubbles: true, cancelable: true } ); + Object.defineProperty( event, 'clipboardData', { + value: { + setData: ( format: string, value: string ) => + clipboardContent.set( format, value ), + }, + } ); + act( () => { + surface.dispatchEvent( event ); + } ); + return { + plainText: clipboardContent.get( 'text/plain' ), + blocks: parse( + clipboardContent.get( 'text/html' )! + ) as Block< BlockAttributes >[], + defaultPrevented: event.defaultPrevented, + }; +} + +describe.each< [ string, ClipboardSurfaceProps[ 'Surface' ] ] >( [ + [ 'canvas', CanvasSurface ], + [ 'list view', ListViewSurface ], +] )( 'resolved block clipboard in the %s', ( name, Surface ) => { + beforeAll( () => { + registerBlockType< { + content: string; + metadata?: BlockAttributes[ 'metadata' ]; + } >( 'core/paragraph', { + apiVersion: 3, + title: 'Paragraph', + category: 'text', + merge: ( attributes, attributesToMerge ) => ( { + content: attributes.content + attributesToMerge.content, + } ), + attributes: { + metadata: { type: 'object' }, + content: { + type: 'string', + source: 'html', + selector: 'p', + default: '', + }, + }, + save: ( { attributes } ) => + createElement( + 'p', + null, + createElement( RawHTML, null, attributes.content ) + ), + } ); + } ); + + afterEach( () => { + document.getSelection()!.removeAllRanges(); + } ); + + afterAll( () => { + unregisterBlockType( 'core/paragraph' ); + } ); + + it( 'copies a bound block with both resolved text and its binding', () => { + const originalBlock = createBlock( 'core/paragraph', { + content: '', + metadata: { bindings }, + } ); + const { registry, surface, boundBlock } = mountClipboard( Surface, [ + originalBlock, + ] ); + + const copied = dispatchClipboardEvent( surface, 'copy' ); + + expect( copied.defaultPrevented ).toBe( true ); + expect( copied.plainText ).toBe( 'Bound text' ); + expect( copied.blocks ).toMatchObject( [ + { + name: 'core/paragraph', + attributes: { + content: 'Bound text', + metadata: { bindings }, + }, + isValid: true, + }, + ] ); + expect( registry.select( blockEditorStore ).getBlocks() ).toEqual( [ + boundBlock, + ] ); + expect( boundBlock.attributes.content ).toBe( '' ); + } ); + + it( 'includes resolved text when copying bound and normal blocks together', () => { + const blocks = [ + createBlock( 'core/paragraph', { + content: '', + metadata: { bindings }, + } ), + createBlock( 'core/paragraph', { content: 'Normal paragraph' } ), + ]; + const { registry, surface, boundBlock } = mountClipboard( + Surface, + blocks + ); + act( () => { + registry + .dispatch( blockEditorStore ) + .multiSelect( blocks[ 0 ].clientId, blocks[ 1 ].clientId ); + } ); + + const copied = dispatchClipboardEvent( surface, 'copy' ); + + expect( copied.plainText ).toBe( 'Bound text\n\nNormal paragraph' ); + expect( + copied.blocks.map( ( block ) => block.attributes.content ) + ).toEqual( [ 'Bound text', 'Normal paragraph' ] ); + expect( copied.blocks[ 0 ].attributes.metadata!.bindings ).toEqual( + bindings + ); + expect( boundBlock.attributes.content ).toBe( '' ); + expect( registry.select( blockEditorStore ).getBlocks() ).toHaveLength( + 2 + ); + } ); + + it( 'copies the resolved content before removing a cut block', () => { + const blocks = [ + createBlock( 'core/paragraph', { + content: '', + metadata: { bindings }, + } ), + createBlock( 'core/paragraph', { content: 'Remaining paragraph' } ), + ]; + const { registry, surface, boundBlock } = mountClipboard( + Surface, + blocks + ); + + const copied = dispatchClipboardEvent( surface, 'cut' ); + + expect( copied.plainText ).toBe( 'Bound text' ); + expect( copied.blocks[ 0 ].attributes ).toEqual( { + content: 'Bound text', + metadata: { bindings }, + } ); + expect( registry.select( blockEditorStore ).getBlocks() ).toMatchObject( + [ { attributes: { content: 'Remaining paragraph' } } ] + ); + expect( boundBlock.attributes.content ).toBe( '' ); + } ); + + if ( Surface === CanvasSurface ) { + it.each< [ string, boolean ] >( [ + [ '', false ], + [ '', true ], + [ 'Saved fallback', false ], + [ 'Saved fallback', true ], + ] )( + 'copies whole bound endpoint text with rich-text selection offsets (fallback=%j, reverse=%s)', + ( fallback, reverse ) => { + const blocks = [ + createBlock( 'core/paragraph', { + content: fallback, + metadata: { bindings }, + } ), + createBlock( 'core/paragraph', { + content: 'Normal paragraph', + } ), + ]; + const { registry, surface, boundBlock } = mountClipboard( + Surface, + blocks + ); + selectPartialBlocks( registry, blocks, 0, 16, reverse ); + + const copied = dispatchClipboardEvent( surface, 'copy' ); + + expect( copied.plainText ).toBe( + 'Bound text\n\nNormal paragraph' + ); + expect( copied.blocks ).toMatchObject( [ + { + attributes: { + content: 'Bound text', + metadata: { bindings }, + }, + isValid: true, + }, + { + attributes: { content: 'Normal paragraph' }, + isValid: true, + }, + ] ); + expect( boundBlock.attributes.content ).toBe( fallback ); + expect( + registry.select( blockEditorStore ).getBlocks()[ 0 ] + ).toBe( boundBlock ); + } + ); + + it.each( [ false, true ] )( + 'copies a bound tail using its resolved prefix (reverse=%s)', + ( reverse ) => { + const blocks = [ + createBlock( 'core/paragraph', { + content: 'Normal paragraph', + } ), + createBlock( 'core/paragraph', { + content: '', + metadata: { bindings }, + } ), + ]; + const { registry, surface, attributesForCopy } = mountClipboard( + Surface, + blocks + ); + attributesForCopy.delete( blocks[ 0 ].clientId ); + const boundTail = registry + .select( blockEditorStore ) + .getBlock( blocks[ 1 ].clientId )!; + registerResolvedContent( + attributesForCopy, + boundTail, + 'Bound text' + ); + selectPartialBlocks( registry, blocks, 7, 8, reverse ); + + const copied = dispatchClipboardEvent( surface, 'copy' ); + + expect( copied.plainText ).toBe( 'paragraph\n\nBound te' ); + expect( copied.blocks[ 1 ] ).toMatchObject( { + attributes: { + content: 'Bound te', + metadata: { bindings }, + }, + isValid: true, + } ); + expect( boundTail.attributes.content ).toBe( '' ); + } + ); + + it.each( [ false, true ] )( + 'copies only selected resolved suffix and prefix when both endpoints are bound (reverse=%s)', + ( reverse ) => { + const blocks = [ + createBlock( 'core/paragraph', { + content: '', + metadata: { bindings }, + } ), + createBlock( 'core/paragraph', { + content: 'Middle paragraph', + } ), + createBlock( 'core/paragraph', { + content: 'Saved fallback', + metadata: { bindings }, + } ), + ]; + const { registry, surface, boundBlock, attributesForCopy } = + mountClipboard( Surface, blocks ); + const boundTail = registry + .select( blockEditorStore ) + .getBlock( blocks[ 2 ].clientId )!; + registerResolvedContent( + attributesForCopy, + boundTail, + 'Tail content' + ); + selectPartialBlocks( registry, blocks, 6, 4, reverse ); + + const copied = dispatchClipboardEvent( surface, 'copy' ); + + expect( copied.plainText ).toBe( + 'text\n\nMiddle paragraph\n\nTail' + ); + expect( + copied.blocks.map( ( block ) => block.attributes.content ) + ).toEqual( [ + 'text', + 'Middle paragraph', + 'Tail', + ] ); + expect( + copied.blocks[ 0 ].attributes.metadata!.bindings + ).toEqual( bindings ); + expect( + copied.blocks[ 2 ].attributes.metadata!.bindings + ).toEqual( bindings ); + expect( + copied.blocks.every( ( block ) => block.isValid ) + ).toBe( true ); + expect( boundBlock.attributes.content ).toBe( '' ); + expect( boundTail.attributes.content ).toBe( 'Saved fallback' ); + } + ); + + it.each( [ 'missing', 'stale', 'duplicate' ] )( + 'uses the saved partial content when the bound snapshot is %s', + ( snapshotStatus ) => { + const blocks = [ + createBlock( 'core/paragraph', { + content: 'Saved fallback', + metadata: { bindings }, + } ), + createBlock( 'core/paragraph', { + content: 'Normal paragraph', + } ), + ]; + const { registry, surface, boundBlock, attributesForCopy } = + mountClipboard( Surface, blocks ); + if ( snapshotStatus === 'missing' ) { + attributesForCopy.delete( boundBlock.clientId ); + } else if ( snapshotStatus === 'duplicate' ) { + const instances = attributesForCopy.get( + boundBlock.clientId + )!; + instances.set( {}, instances.values().next().value! ); + } else { + act( () => { + registry + .dispatch( blockEditorStore ) + .updateBlockAttributes( boundBlock.clientId, { + content: 'Newer fallback', + } ); + } ); + } + selectPartialBlocks( registry, blocks, 6, 6, false ); + + const copied = dispatchClipboardEvent( surface, 'copy' ); + + expect( copied.plainText ).toBe( 'fallback\n\nNormal' ); + expect( copied.blocks[ 0 ].attributes ).toEqual( { + content: 'fallback', + metadata: { bindings }, + } ); + } + ); + + it( 'copies resolved partial content before cutting a rich-text block selection', () => { + const blocks = [ + createBlock( 'core/paragraph', { + content: '', + metadata: { bindings }, + } ), + createBlock( 'core/paragraph', { + content: 'Normal paragraph', + } ), + ]; + const { registry, surface, boundBlock } = mountClipboard( + Surface, + blocks + ); + selectPartialBlocks( registry, blocks, 6, 6, false ); + + const copied = dispatchClipboardEvent( surface, 'cut' ); + + expect( copied.plainText ).toBe( 'text\n\nNormal' ); + expect( copied.blocks[ 0 ].attributes ).toEqual( { + content: 'text', + metadata: { bindings }, + } ); + expect( + registry.select( blockEditorStore ).getBlocks() + ).toHaveLength( 1 ); + expect( boundBlock.attributes.content ).toBe( '' ); + } ); + } +} ); diff --git a/packages/block-editor/src/components/writing-flow/test/utils.jsdom.test.ts b/packages/block-editor/src/components/writing-flow/test/utils.jsdom.test.ts new file mode 100644 index 00000000000000..13ec5abcfc085a --- /dev/null +++ b/packages/block-editor/src/components/writing-flow/test/utils.jsdom.test.ts @@ -0,0 +1,370 @@ +import { afterAll, beforeAll, describe, expect, it } from 'vitest'; +import { + createBlock, + getFreeformContentHandlerName, + parse, + registerBlockType, + serialize, + setFreeformContentHandlerName, + unregisterBlockType, + __unstableGetInnerBlocksProps as getInnerBlocksProps, +} from '@wordpress/blocks'; +import { createElement, RawHTML } from '@wordpress/element'; +import type { Block } from '@wordpress/blocks'; +import { dispatch, select } from '@wordpress/data'; +import { store as blockEditorStore } from '../../../store'; +import { stripBlockClipboardWrapper } from '../../../utils/block-clipboard'; +import { + getClipboardBlocksContent, + requiresWrapperOnCopy, + setClipboardBlocks, +} from '../utils'; + +const bindings = { + content: { source: 'core/post-meta', args: { key: 'movie_field' } }, +}; +const registry = { select }; +const originalFreeformHandler = getFreeformContentHandlerName(); + +function createBoundParagraph( content = '' ) { + return createBlock( 'core/paragraph', { + content, + metadata: { bindings, name: 'Bound paragraph' }, + } ) as Block< { + content: string; + metadata: { bindings: typeof bindings; name: string }; + } >; +} + +function registerResolvedAttributes( + attributesForCopy: Map< string, unknown >, + block: Block, + content: string +) { + attributesForCopy.set( + block.clientId, + new Map( [ + [ + {}, + { + attributes: block.attributes, + getAttributesForCopy: () => ( { + ...block.attributes, + content, + metadata: { name: 'Resolved metadata' }, + } ), + boundAttributeNames: [ 'content' ], + }, + ], + ] ) + ); +} + +describe( 'block clipboard content', () => { + beforeAll( () => { + for ( const [ name, tagName ] of [ + [ 'core/paragraph', 'p' ], + [ 'core/heading', 'h2' ], + [ 'core/list-item', 'li' ], + ] ) { + registerBlockType< { + content: string; + metadata: Record< string, unknown >; + } >( name, { + apiVersion: 3, + title: name, + category: 'text', + attributes: { + metadata: { type: 'object' }, + content: { + type: 'string', + source: 'html', + selector: tagName, + default: '', + }, + }, + ...( name === 'core/list-item' + ? { [ requiresWrapperOnCopy ]: true } + : {} ), + save: ( { attributes } ) => + createElement( + tagName, + null, + createElement( RawHTML, null, attributes.content ) + ), + } ); + } + for ( const [ name, tagName ] of [ + [ 'core/group', 'div' ], + [ 'core/list', 'ul' ], + ] ) { + registerBlockType< { ordered?: boolean } >( name, { + attributes: + name === 'core/list' + ? { ordered: { type: 'boolean' } } + : {}, + apiVersion: 3, + title: name, + category: 'text', + save: ( { attributes } ) => + createElement( + attributes.ordered ? 'ol' : tagName, + getInnerBlocksProps() + ), + } ); + } + registerBlockType< { content: string } >( 'core/freeform', { + apiVersion: 3, + title: 'Classic', + category: 'text', + attributes: { content: { type: 'string', source: 'html' } }, + save: ( { attributes } ) => + createElement( RawHTML, null, attributes.content ), + } ); + setFreeformContentHandlerName( 'core/freeform' ); + } ); + + afterAll( () => { + // The block-name reducer treats an empty name as its initial null state. + setFreeformContentHandlerName( originalFreeformHandler ?? '' ); + for ( const name of [ + 'core/paragraph', + 'core/heading', + 'core/group', + 'core/list', + 'core/list-item', + 'core/freeform', + ] ) { + unregisterBlockType( name ); + } + } ); + + it( 'copies bound text and formatting as valid block HTML without changing the source', () => { + const block = createBoundParagraph(); + const attributesForCopy = new Map(); + registerResolvedAttributes( + attributesForCopy, + block, + 'Bound text' + ); + const originalHTML = serialize( [ block ] ); + Object.freeze( block.attributes ); + Object.freeze( block ); + + const { html, plainText, hasBoundAttributes } = + getClipboardBlocksContent( [ block ], registry, attributesForCopy ); + + expect( plainText ).toBe( 'Bound text' ); + expect( html ).toContain( '

Bound text

' ); + expect( hasBoundAttributes ).toBe( true ); + const [ pastedBlock ] = parse( html ); + expect( pastedBlock.isValid ).toBe( true ); + expect( pastedBlock.attributes ).toEqual( { + content: 'Bound text', + metadata: block.attributes.metadata, + } ); + expect( block.attributes.content ).toBe( '' ); + expect( block.attributes.metadata.bindings ).toBe( bindings ); + expect( serialize( [ block ] ) ).toBe( originalHTML ); + } ); + + it( 'resolves nested blocks in a mixed selection', () => { + const nestedBoundBlock = createBoundParagraph(); + const unboundBlock = createBlock( 'core/paragraph', { + content: 'Normal paragraph', + } ); + const group = createBlock( 'core/group', {}, [ + nestedBoundBlock, + unboundBlock, + ] ); + const heading = createBlock( 'core/heading', { content: 'Heading' } ); + const attributesForCopy = new Map(); + registerResolvedAttributes( + attributesForCopy, + nestedBoundBlock, + 'Bound text' + ); + const originalHTML = serialize( [ group, heading ] ); + + const { html, plainText } = getClipboardBlocksContent( + [ group, heading ], + registry, + attributesForCopy + ); + + expect( plainText ).toBe( 'Bound text\n\nNormal paragraph\n\nHeading' ); + const pastedBlocks = parse( html ); + expect( pastedBlocks[ 0 ].innerBlocks ).toMatchObject( [ + { + attributes: { + content: 'Bound text', + metadata: { bindings }, + }, + isValid: true, + }, + { attributes: { content: 'Normal paragraph' }, isValid: true }, + ] ); + expect( pastedBlocks[ 1 ] ).toMatchObject( { + name: 'core/heading', + isValid: true, + } ); + expect( group.innerBlocks[ 0 ] ).toBe( nestedBoundBlock ); + expect( serialize( [ group, heading ] ) ).toBe( originalHTML ); + } ); + + it( 'does not replace partial head and tail content with their whole bound values', () => { + const head = createBoundParagraph( 'Head fallback' ); + const middle = createBoundParagraph(); + const tail = createBoundParagraph( 'Tail fallback' ); + const attributesForCopy = new Map(); + for ( const [ block, content ] of [ + [ head, 'Whole head' ], + [ middle, 'Resolved middle' ], + [ tail, 'Whole tail' ], + ] as const ) { + registerResolvedAttributes( attributesForCopy, block, content ); + } + const partialBlocks = [ + { ...head, attributes: { ...head.attributes, content: 'head' } }, + middle, + { ...tail, attributes: { ...tail.attributes, content: 'tail' } }, + ]; + + const { html, plainText } = getClipboardBlocksContent( + partialBlocks, + registry, + attributesForCopy + ); + + expect( plainText ).toBe( 'head\n\nResolved middle\n\ntail' ); + expect( + parse( html ).map( ( block ) => block.attributes.content ) + ).toEqual( [ 'head', 'Resolved middle', 'tail' ] ); + } ); + + it( 'keeps the original serialized HTML for blocks without a resolved binding', () => { + const blocks = [ + createBlock( 'core/heading', { content: 'Heading' } ), + createBoundParagraph( 'Saved fallback' ), + ]; + + expect( + getClipboardBlocksContent( blocks, registry, new Map() ) + ).toEqual( { + html: serialize( blocks ), + plainText: 'Heading\n\nSaved fallback', + hasBoundAttributes: false, + } ); + } ); + + it( 'preserves the parent wrapper when setting clipboard data for a list item', () => { + const item = createBlock( 'core/list-item', { content: 'List item' } ); + const list = createBlock( 'core/list', {}, [ item ] ); + dispatch( blockEditorStore ).resetBlocks( [ list ] ); + const clipboardContent = new Map< string, string >(); + const clipboardData = { + setData: ( type: string, value: string ) => + clipboardContent.set( type, value ), + }; + + setClipboardBlocks( + { clipboardData } as unknown as ClipboardEvent, + [ item ], + registry, + new Map() + ); + + const [ pastedBlock ] = parse( + stripBlockClipboardWrapper( clipboardContent.get( 'text/html' )! ) + ); + expect( pastedBlock ).toMatchObject( { + name: 'core/list', + innerBlocks: [ + { + name: 'core/list-item', + attributes: { content: 'List item' }, + }, + ], + isValid: true, + } ); + expect( clipboardContent.get( 'text/plain' ) ).toBe( 'List item' ); + expect( + parse( + getClipboardBlocksContent( [ item ], registry, new Map() ).html + )[ 0 ].name + ).toBe( 'core/list-item' ); + } ); + + it( 'keeps a valid ordered List for editors that do not recognize the clipboard marker', () => { + const item = createBlock( 'core/list-item', { + metadata: { bindings }, + } ); + const list = createBlock( 'core/list', { ordered: true }, [ item ] ); + dispatch( blockEditorStore ).resetBlocks( [ list ] ); + const attributesForCopy = new Map(); + registerResolvedAttributes( attributesForCopy, item, 'Bound item' ); + + const { html, plainText } = getClipboardBlocksContent( + [ item ], + registry, + attributesForCopy, + { addWrapper: true } + ); + expect( html ).toContain( '
    ' ); + // Older editors pass the markup directly to their block parser. + const pasted = parse( html ); + expect( pasted ).toHaveLength( 1 ); + expect( pasted ).toMatchObject( [ + { + name: 'core/list', + isValid: true, + innerBlocks: [ + { + name: 'core/list-item', + isValid: true, + attributes: { + content: 'Bound item', + metadata: { bindings }, + }, + }, + ], + }, + ] ); + expect( plainText ).toBe( 'Bound item' ); + expect( + parse( + getClipboardBlocksContent( [ item ], registry, new Map(), { + addWrapper: true, + } ).html + )[ 0 ].name + ).toBe( 'core/list' ); + } ); + + it( 'sets both clipboard formats from the same resolved block content', () => { + const block = createBoundParagraph(); + const attributesForCopy = new Map(); + registerResolvedAttributes( + attributesForCopy, + block, + 'Bound text' + ); + const clipboardContent = new Map< string, string >(); + const clipboardData = { + setData: ( type: string, value: string ) => + clipboardContent.set( type, value ), + }; + + setClipboardBlocks( + { clipboardData } as unknown as ClipboardEvent, + [ block ], + registry, + attributesForCopy + ); + + expect( clipboardContent.get( 'text/plain' ) ).toBe( 'Bound text' ); + expect( clipboardContent.get( 'text/html' ) ).toContain( + '

    Bound text

    ' + ); + expect( block.attributes.content ).toBe( '' ); + } ); +} ); diff --git a/packages/block-editor/src/components/writing-flow/use-clipboard-handler.ts b/packages/block-editor/src/components/writing-flow/use-clipboard-handler.ts index 81228fc06da790..8d56a516e35a5b 100644 --- a/packages/block-editor/src/components/writing-flow/use-clipboard-handler.ts +++ b/packages/block-editor/src/components/writing-flow/use-clipboard-handler.ts @@ -13,11 +13,17 @@ import { } from '@wordpress/dom'; import { useDispatch, useRegistry, useSelect } from '@wordpress/data'; import { useRefEffect } from '@wordpress/compose'; +import { useContext } from '@wordpress/element'; import { store as blockEditorStore } from '../../store'; import { useNotifyCopy } from '../../utils/use-notify-copy'; -import { setClipboardBlocks, setContentEditableWrapper } from './utils'; +import { + getBoundPartialBlockForCopy, + setClipboardBlocks, + setContentEditableWrapper, +} from './utils'; import { getPasteEventData } from '../../utils/pasting'; import { getBlockClientId } from '../../utils/dom'; +import { BlockRefs } from '../provider/block-refs-provider'; import { getTextDropPoint } from '../rich-text/event-listeners/drag-and-drop'; import type { WritingFlowClipboardEvent } from './types'; @@ -48,6 +54,7 @@ function isBlockEntirelySelected( ownerDocument: Document, clientId: string ) { export default function useClipboardHandler() { const registry = useRegistry(); + const { attributesForCopy } = useContext( BlockRefs ); const { getBlocksByClientId, getSelectedBlockClientIds, @@ -62,6 +69,7 @@ export default function useClipboardHandler() { getBlockRootClientId, getBlockAttributes, getSelectionStart, + getSelectionEnd, } = useSelect( blockEditorStore ); const { flashBlock, @@ -204,21 +212,44 @@ export default function useClipboardHandler() { } else { const [ head, tail ] = __unstableGetSelectedBlocksWithPartialSelection(); - const inBetweenBlocks = getBlocksByClientId( - selectedBlockClientIds.slice( - 1, - selectedBlockClientIds.length - 1 - ) - ); - blocks = [ head, ...inBetweenBlocks, tail ]; + const selectedBlocks = getBlocksByClientId( + selectedBlockClientIds + ) as Block[]; + const selectionAnchor = getSelectionStart(); + const selectionFocus = getSelectionEnd(); + const [ selectionHead, selectionTail ] = + selectionAnchor.clientId === + selectedBlocks[ 0 ].clientId + ? [ selectionAnchor, selectionFocus ] + : [ selectionFocus, selectionAnchor ]; + blocks = [ + getBoundPartialBlockForCopy( + selectedBlocks[ 0 ], + head as Block, + attributesForCopy, + { + attributeKey: selectionHead.attributeKey, + startOffset: selectionHead.offset, + } + ), + ...selectedBlocks.slice( 1, -1 ), + getBoundPartialBlockForCopy( + selectedBlocks[ selectedBlocks.length - 1 ], + tail as Block, + attributesForCopy, + { + attributeKey: selectionTail.attributeKey, + endOffset: selectionTail.offset, + } + ), + ]; } - // The selected blocks exist, and copy and cut events are - // clipboard events. setClipboardBlocks( event as ClipboardEvent, blocks as Block[], - registry + registry, + attributesForCopy ); } } diff --git a/packages/block-editor/src/components/writing-flow/utils.ts b/packages/block-editor/src/components/writing-flow/utils.ts index 1e2cd3cf2f148d..d59222a608789e 100644 --- a/packages/block-editor/src/components/writing-flow/utils.ts +++ b/packages/block-editor/src/components/writing-flow/utils.ts @@ -1,5 +1,6 @@ import { __ } from '@wordpress/i18n'; import { __unstableStripHTML as stripHTML } from '@wordpress/dom'; +import { create, slice, toHTMLString } from '@wordpress/rich-text'; import { serialize, createBlock, @@ -12,28 +13,79 @@ import type { Block, BlockFilesTransform } from '@wordpress/blocks'; import type { DataRegistry } from '@wordpress/data'; import type { ClipboardEvent as ReactClipboardEvent } from 'react'; import { getPasteEventData } from '../../utils/pasting'; +import { addBlockClipboardWrapper } from '../../utils/block-clipboard'; import { store as blockEditorStore } from '../../store'; +import { getBoundAttributesForCopy } from '../provider/block-refs-provider'; +import type { AttributesForCopy } from '../provider/types'; export const requiresWrapperOnCopy = Symbol( 'requiresWrapperOnCopy' ); -/** - * Sets the clipboard data for the provided blocks, with both HTML and plain - * text representations. - * - * @param event Clipboard event. - * @param blocks Blocks to set as clipboard data. - * @param registry The registry to select from. - */ -export function setClipboardBlocks( - event: ClipboardEvent | ReactClipboardEvent, +export function getBoundPartialBlockForCopy( + block: Block, + partialBlock: Block, + attributesForCopy: AttributesForCopy | undefined, + { + attributeKey, + startOffset = 0, + endOffset, + }: { attributeKey?: string; startOffset?: number; endOffset?: number } +) { + const boundAttributes = getBoundAttributesForCopy( + block, + attributesForCopy + ); + if ( ! boundAttributes ) { + return partialBlock; + } + const attributes = { ...partialBlock.attributes, ...boundAttributes }; + if ( Object.hasOwn( boundAttributes, attributeKey! ) ) { + const value = create( { + html: boundAttributes[ attributeKey! ] as string, + } ); + attributes[ attributeKey! ] = toHTMLString( { + value: slice( value, startOffset, endOffset ?? value.text.length ), + } ); + } + return { ...partialBlock, attributes }; +} + +export function getClipboardBlocksContent( blocks: Block[], - registry: DataRegistry + registry: Pick< DataRegistry, 'select' >, + attributesForCopy?: AttributesForCopy, + { addWrapper = false }: { addWrapper?: boolean } = {} ) { - let _blocks: Block | Block[] = blocks; + let hasBoundAttributes = false; + function resolveBlockForCopy( block: Block ): Block { + const boundAttributes = getBoundAttributesForCopy( + block, + attributesForCopy + ); + const innerBlocks = block.innerBlocks.map( resolveBlockForCopy ); + const hasChangedInnerBlocks = innerBlocks.some( + ( innerBlock, index ) => innerBlock !== block.innerBlocks[ index ] + ); + + if ( ! boundAttributes && ! hasChangedInnerBlocks ) { + return block; + } + + hasBoundAttributes ||= !! boundAttributes; + return { + ...block, + attributes: boundAttributes + ? { ...block.attributes, ...boundAttributes } + : block.attributes, + innerBlocks, + }; + } + + let blocksForCopy: Block | Block[] = blocks.map( resolveBlockForCopy ); + let hasWrapper = false; const [ firstBlock ] = blocks; - if ( firstBlock ) { + if ( firstBlock && addWrapper ) { const firstBlockType = registry .select( blocksStore ) .getBlockType( firstBlock.name ); @@ -52,21 +104,48 @@ export function setClipboardBlocks( const wrapperBlockName = getBlockName( wrapperBlockClientId ); if ( wrapperBlockName ) { - // A named wrapper block exists, so it has attributes. - _blocks = createBlock( + blocksForCopy = createBlock( wrapperBlockName, getBlockAttributes( wrapperBlockClientId! )!, - _blocks + blocksForCopy ); + hasWrapper = true; } } } - const serialized = serialize( _blocks ); + const serialized = serialize( blocksForCopy ); + const html = hasWrapper + ? addBlockClipboardWrapper( serialized ) + : serialized; + + return { html, plainText: toPlainText( html ), hasBoundAttributes }; +} + +/** + * Sets the clipboard data for the provided blocks, with both HTML and plain + * text representations. + * + * @param event Clipboard event. + * @param blocks Blocks to set as clipboard data. + * @param registry The registry to select from. + * @param attributesForCopy Resolved bound attributes by block instance. + */ +export function setClipboardBlocks( + event: ClipboardEvent | ReactClipboardEvent, + blocks: Block[], + registry: Pick< DataRegistry, 'select' >, + attributesForCopy?: AttributesForCopy +) { + const { html, plainText } = getClipboardBlocksContent( + blocks, + registry, + attributesForCopy, + { addWrapper: true } + ); - // Copy and cut events carry clipboard data. - event.clipboardData!.setData( 'text/plain', toPlainText( serialized ) ); - event.clipboardData!.setData( 'text/html', serialized ); + event.clipboardData!.setData( 'text/plain', plainText ); + event.clipboardData!.setData( 'text/html', html ); } /** diff --git a/packages/block-editor/src/utils/block-clipboard.ts b/packages/block-editor/src/utils/block-clipboard.ts new file mode 100644 index 00000000000000..f73d423bcd6061 --- /dev/null +++ b/packages/block-editor/src/utils/block-clipboard.ts @@ -0,0 +1,57 @@ +// This clipboard-only marker distinguishes a copied selection's synthetic +// parent wrapper from a parent block that was itself selected. +// Keep it inside the delimiter so parsers unaware of this marker ignore the +// unknown attribute instead of creating a Classic block before the wrapper. +export const BLOCK_CLIPBOARD_WRAPPER = '"__wpClipboardWrapper":true'; + +export function addBlockClipboardWrapper( content: string ): string { + return content.replace( + /^(\s*'; + const startIdx = html.indexOf( startStr ); + if ( startIdx > -1 ) { + html = html.substring( startIdx + startStr.length ); + const endIdx = html.indexOf( '' ); + if ( endIdx > -1 ) { + html = html.substring( 0, endIdx ); + } + } + + // Chromium inserts this tag; ignore platform padding before it, too. + // https://github.com/WordPress/gutenberg/issues/33585 + // https://bugs.chromium.org/p/chromium/issues/detail?id=1264616 + return html.replace( /^\s*/, '' ); +} diff --git a/packages/block-editor/src/utils/pasting.ts b/packages/block-editor/src/utils/pasting.ts index 39e9998c69f286..bf321f594a8ec2 100644 --- a/packages/block-editor/src/utils/pasting.ts +++ b/packages/block-editor/src/utils/pasting.ts @@ -1,49 +1,8 @@ import { getFilesFromDataTransfer } from '@wordpress/dom'; - -/** - * Normalizes a given string of HTML to remove the Windows-specific "Fragment" - * comments and any preceding and trailing content. - * - * @param html the html to be normalized - * @return the normalized html - */ -function removeWindowsFragments( html: string ) { - const startStr = ''; - const startIdx = html.indexOf( startStr ); - if ( startIdx > -1 ) { - html = html.substring( startIdx + startStr.length ); - } else { - // No point looking for EndFragment - return html; - } - - const endStr = ''; - const endIdx = html.indexOf( endStr ); - if ( endIdx > -1 ) { - html = html.substring( 0, endIdx ); - } - - return html; -} - -/** - * Removes the charset meta tag inserted by Chromium. - * See: - * - https://github.com/WordPress/gutenberg/issues/33585 - * - https://bugs.chromium.org/p/chromium/issues/detail?id=1264616#c4 - * - * @param html the html to be stripped of the meta tag. - * @return the cleaned html - */ -function removeCharsetMetaTag( html: string ) { - const metaTag = ``; - - if ( html.startsWith( metaTag ) ) { - return html.slice( metaTag.length ); - } - - return html; -} +import { + normalizeClipboardHTML, + stripBlockClipboardWrapper, +} from './block-clipboard'; export function getPasteEventData( { clipboardData, @@ -63,11 +22,7 @@ export function getPasteEventData( { return; } - // Remove Windows-specific metadata appended within copied HTML text. - html = removeWindowsFragments( html ); - - // Strip meta tag. - html = removeCharsetMetaTag( html ); + html = normalizeClipboardHTML( html ); const files = getFilesFromDataTransfer( clipboardData ); @@ -75,7 +30,11 @@ export function getPasteEventData( { return { files }; } - return { html, plainText, files: [] }; + return { + html: stripBlockClipboardWrapper( html ), + plainText: stripBlockClipboardWrapper( plainText ), + files: [], + }; } /** diff --git a/packages/block-editor/src/utils/test/block-clipboard.jsdom.test.ts b/packages/block-editor/src/utils/test/block-clipboard.jsdom.test.ts new file mode 100644 index 00000000000000..9bfe807eee7701 --- /dev/null +++ b/packages/block-editor/src/utils/test/block-clipboard.jsdom.test.ts @@ -0,0 +1,81 @@ +import { describe, expect, it } from 'vitest'; +import { + BLOCK_CLIPBOARD_WRAPPER, + addBlockClipboardWrapper, + stripBlockClipboardWrapper, +} from '../block-clipboard'; +import { getPasteEventData } from '../pasting'; + +describe( 'copied block wrapper marker', () => { + it.each( [ + [ '', '', '' ], + [ ' \n\t', '', '', ' \n\t' ], + [ `\n`, '', '', '\n' ], + [ ` \n\n\t`, '', '', '\n\t' ], + [ + '\n', + '\n', + '\n', + '\n', + ], + ] )( + 'consumes only the leading marker after platform metadata (%s)', + ( prefix, suffix, trailingContent, leadingContent = '' ) => { + const content = `

    Text ${ BLOCK_CLIPBOARD_WRAPPER }

    `; + const event = { + clipboardData: { + getData: ( type: string ) => + type === 'text/html' + ? prefix + + addBlockClipboardWrapper( content ) + + suffix + : addBlockClipboardWrapper( content ), + files: [], + items: [], + } as unknown as DataTransfer, + }; + + expect( getPasteEventData( event ) ).toEqual( { + html: leadingContent + content + trailingContent, + plainText: content, + files: [], + } ); + expect( stripBlockClipboardWrapper( content ) ).toBe( content ); + } + ); + + it( 'does not remove identical marker text inside copied content', () => { + const content = `

    Text ${ BLOCK_CLIPBOARD_WRAPPER }

    `; + expect( stripBlockClipboardWrapper( content ) ).toBe( content ); + } ); + + it.each( [ + '
    ', + '
    ', + '
      ', + ' \n
      ', + ] )( 'preserves serialized attribute bytes: %s', ( content ) => { + const marked = addBlockClipboardWrapper( content ); + expect( marked ).toContain( BLOCK_CLIPBOARD_WRAPPER ); + expect( stripBlockClipboardWrapper( marked ) ).toBe( + content.replace( ' {} ', ' ' ) + ); + } ); + + it( 'leaves nested markers and an unflagged outer block untouched', () => { + const inner = addBlockClipboardWrapper( + '

      Text

      ' + ); + const content = `
      ${ inner }
      `; + expect( stripBlockClipboardWrapper( content ) ).toBe( content ); + expect( + stripBlockClipboardWrapper( addBlockClipboardWrapper( content ) ) + ).toBe( content ); + } ); + + it( 'leaves false markers untouched', () => { + const content = + '
        '; + expect( stripBlockClipboardWrapper( content ) ).toBe( content ); + } ); +} ); diff --git a/packages/blocks/CHANGELOG.md b/packages/blocks/CHANGELOG.md index 97ec0c6f8e217a..f3dbd5729b4c98 100644 --- a/packages/blocks/CHANGELOG.md +++ b/packages/blocks/CHANGELOG.md @@ -7,6 +7,10 @@ - Add the `rotate` style property, for the `transform.rotate` block support ([#86240](https://github.com/WordPress/gutenberg/pull/86240)). - Add the `translate` style property, for the `transform.translate` block support ([#86282](https://github.com/WordPress/gutenberg/pull/86282)). +### Enhancements + +- Block Bindings: Add the optional `supportsCopy` capability and `isForCopy` argument to `getValues` so sources can opt in to resolving copied values without saving display placeholders ([#84428](https://github.com/WordPress/gutenberg/pull/84428)). + ### Internal - Update `colord` dependency to 2.14.0 ([#87252](https://github.com/WordPress/gutenberg/pull/87252)). diff --git a/packages/blocks/src/api/registration.ts b/packages/blocks/src/api/registration.ts index e92550b97d9cae..5108689e2ff404 100644 --- a/packages/blocks/src/api/registration.ts +++ b/packages/blocks/src/api/registration.ts @@ -757,6 +757,7 @@ export const registerBlockBindingsSource = ( name, label, usesContext, + supportsCopy, getValues, setValues, canUserEditValue, @@ -835,6 +836,12 @@ export const registerBlockBindingsSource = ( return; } + // Check the `supportsCopy` property is correct. + if ( supportsCopy !== undefined && typeof supportsCopy !== 'boolean' ) { + warning( 'Block bindings source supportsCopy must be a boolean.' ); + return; + } + // Check the `getValues` property is correct. if ( getValues && typeof getValues !== 'function' ) { warning( 'Block bindings source getValues must be a function.' ); diff --git a/packages/blocks/src/api/test/registration.jsx b/packages/blocks/src/api/test/registration.jsx index 7ebd72f3c63ca6..180e6519df317f 100644 --- a/packages/blocks/src/api/test/registration.jsx +++ b/packages/blocks/src/api/test/registration.jsx @@ -1697,6 +1697,55 @@ describe( 'blocks', () => { ] ); } ); + it.each( [ true, false ] )( + 'preserves an explicit supportsCopy capability of %s', + ( supportsCopy ) => { + registerBlockBindingsSource( { + name: 'core/copy-support', + label: 'Copy support', + supportsCopy, + } ); + const source = getBlockBindingsSource( 'core/copy-support' ); + unregisterBlockBindingsSource( 'core/copy-support' ); + expect( source ).toHaveProperty( 'supportsCopy', supportsCopy ); + } + ); + + it.each( [ 0, '', null, 1, 'true', () => true, {} ] )( + 'rejects a defined non-boolean supportsCopy value of %j', + ( supportsCopy ) => { + registerBlockBindingsSource( { + name: 'core/invalid-copy-support', + label: 'Invalid copy support', + supportsCopy, + } ); + const source = getBlockBindingsSource( + 'core/invalid-copy-support' + ); + if ( source ) { + unregisterBlockBindingsSource( + 'core/invalid-copy-support' + ); + } + expect( console ).toHaveWarnedWith( + 'Block bindings source supportsCopy must be a boolean.' + ); + expect( source ).toBeUndefined(); + } + ); + + it( 'does not add a supportsCopy property to an unaware source', () => { + registerBlockBindingsSource( { + name: 'core/unaware-copy-support', + label: 'Unaware source', + } ); + const source = getBlockBindingsSource( + 'core/unaware-copy-support' + ); + unregisterBlockBindingsSource( 'core/unaware-copy-support' ); + expect( source ).not.toHaveProperty( 'supportsCopy' ); + } ); + // Check the `getValues` callback is correct. it( 'should reject invalid getValues callback', () => { registerBlockBindingsSource( { diff --git a/packages/blocks/src/store/private-actions.ts b/packages/blocks/src/store/private-actions.ts index 5885a3afea8eb1..315b54b13ba219 100644 --- a/packages/blocks/src/store/private-actions.ts +++ b/packages/blocks/src/store/private-actions.ts @@ -55,6 +55,9 @@ export function addBlockBindingsSource( source: BlockBindingsSource ): Action { name: source.name, label: source.label, usesContext: source.usesContext, + ...( source.supportsCopy === undefined + ? {} + : { supportsCopy: source.supportsCopy } ), getValues: source.getValues, setValues: source.setValues, canUserEditValue: source.canUserEditValue, diff --git a/packages/blocks/src/store/reducer.ts b/packages/blocks/src/store/reducer.ts index 663003cbcf9100..d6a97b3aaf50a2 100644 --- a/packages/blocks/src/store/reducer.ts +++ b/packages/blocks/src/store/reducer.ts @@ -384,6 +384,9 @@ export function blockBindingsSources( state[ action.name ]?.usesContext, action.usesContext ), + ...( action.supportsCopy === undefined + ? {} + : { supportsCopy: action.supportsCopy } ), getValues: action.getValues, setValues: action.setValues, // Only set `canUserEditValue` if `setValues` is also defined. diff --git a/packages/blocks/src/store/types.ts b/packages/blocks/src/store/types.ts index 1ac34c79f97c6a..73c8bced50baa9 100644 --- a/packages/blocks/src/store/types.ts +++ b/packages/blocks/src/store/types.ts @@ -125,6 +125,7 @@ export type Action = name: string; label?: string; usesContext?: string[]; + supportsCopy?: boolean; getValues?: Function; setValues?: Function; canUserEditValue?: Function; diff --git a/packages/blocks/src/types.ts b/packages/blocks/src/types.ts index dafeb81bc86ce7..11114a92a9665b 100644 --- a/packages/blocks/src/types.ts +++ b/packages/blocks/src/types.ts @@ -856,8 +856,16 @@ export interface BlockBindingsSource { * Optional array of context needed by the source only in the editor. */ usesContext?: string[]; + /** + * Opt in to resolving source values for copied blocks. Defaults to false. + */ + supportsCopy?: boolean; /** * Optional function to get the values from the source. + * Sources with `supportsCopy: true` receive `isForCopy: true` when resolving + * values for the clipboard. Other sources keep their saved fallback. + * In copy requests, omit unavailable attributes or return `undefined` for + * them instead of display placeholders to preserve their saved fallback. */ getValues?: Function; /** diff --git a/packages/editor/CHANGELOG.md b/packages/editor/CHANGELOG.md index b6a8d1d0701b61..6459acbe1a4e15 100644 --- a/packages/editor/CHANGELOG.md +++ b/packages/editor/CHANGELOG.md @@ -6,6 +6,7 @@ - `PageAttributesPanel`: Hide parent controls for non-hierarchical post types ([#85679](https://github.com/WordPress/gutenberg/pull/85679)). - Hide the decorative author avatar in the revisions timeline from assistive technologies, as the name of the author is next to it ([#87222](https://github.com/WordPress/gutenberg/pull/87222)). +- Block Bindings: Preserve saved fallbacks for unavailable post meta, post data, and term data, and retain explicitly empty pattern overrides when copying blocks ([#84428](https://github.com/WordPress/gutenberg/pull/84428)). ### Internal diff --git a/packages/editor/src/bindings/pattern-overrides.js b/packages/editor/src/bindings/pattern-overrides.js index 559f8ff54d2fbc..08617d35776b9d 100644 --- a/packages/editor/src/bindings/pattern-overrides.js +++ b/packages/editor/src/bindings/pattern-overrides.js @@ -7,7 +7,8 @@ const CONTENT = 'content'; */ export default { name: 'core/pattern-overrides', - getValues( { select, clientId, context, bindings } ) { + supportsCopy: true, + getValues( { select, clientId, context, bindings, isForCopy } ) { const patternOverridesContent = context[ 'pattern/overrides' ]; const { getBlockAttributes } = select( blockEditorStore ); const currentBlockAttributes = getBlockAttributes( clientId ); @@ -27,7 +28,9 @@ export default { continue; } else { overridesValues[ attributeName ] = - overridableValue === '' ? undefined : overridableValue; + overridableValue === '' && ! isForCopy + ? undefined + : overridableValue; } } return overridesValues; diff --git a/packages/editor/src/bindings/post-data.js b/packages/editor/src/bindings/post-data.js index e8854de9db4702..6ac206be810527 100644 --- a/packages/editor/src/bindings/post-data.js +++ b/packages/editor/src/bindings/post-data.js @@ -31,7 +31,8 @@ const postDataFields = [ */ export default { name: 'core/post-data', - getValues( { select, context, bindings, clientId } ) { + supportsCopy: true, + getValues( { select, context, bindings, clientId, isForCopy } ) { /* * BACKWARDS COMPATIBILITY: Hardcoded exception for navigation blocks. * Required for WordPress 6.9+ navigation blocks. DO NOT REMOVE. @@ -66,6 +67,14 @@ export default { ( field ) => field.args.field === binding.args.field ); + if ( + isForCopy && + ( ! postDataField || + entityDataValues?.[ binding.args.field ] === undefined ) + ) { + continue; + } + if ( ! postDataField ) { // If the field is unknown, return the field name. newValues[ attributeName ] = binding.args.field; diff --git a/packages/editor/src/bindings/post-meta.js b/packages/editor/src/bindings/post-meta.js index df48f4a178aab7..8de32fb48b9d99 100644 --- a/packages/editor/src/bindings/post-meta.js +++ b/packages/editor/src/bindings/post-meta.js @@ -49,7 +49,7 @@ function getPostMetaFields( select, context ) { return metaFields; } -function getValue( { select, context, args } ) { +function getValue( { select, context, args, isForCopy } ) { const metaFields = getPostMetaFields( select, context ); const metaField = metaFields.find( ( field ) => field.args.key === args.key @@ -57,13 +57,15 @@ function getValue( { select, context, args } ) { // If the meta field was not found, it's either protected, inaccessible, or simply doesn't exist. if ( ! metaField ) { - return args.key; + return isForCopy ? undefined : args.key; } // Without a postId, we cannot look up a meta value. if ( ! context?.postId ) { // Return the default value for the meta field if available. - return metaField.default || metaField.label || args.key; + return isForCopy + ? undefined + : metaField.default || metaField.label || args.key; } const { getEditedEntityRecord } = select( coreDataStore ); @@ -71,9 +73,12 @@ function getValue( { select, context, args } ) { 'postType', context?.postType, context?.postId - ).meta; + )?.meta; - return entityMetaValues?.[ args.key ] ?? metaField?.label ?? args.key; + const value = entityMetaValues?.[ args.key ]; + return isForCopy + ? ( value ?? undefined ) + : ( value ?? metaField.label ?? args.key ); } /** @@ -81,14 +86,19 @@ function getValue( { select, context, args } ) { */ export default { name: 'core/post-meta', - getValues( { select, context, bindings } ) { + supportsCopy: true, + getValues( { select, context, bindings, isForCopy } ) { const newValues = {}; for ( const [ attributeName, binding ] of Object.entries( bindings ) ) { - newValues[ attributeName ] = getValue( { + const value = getValue( { select, context, args: binding.args, + isForCopy, } ); + if ( ! isForCopy || value !== undefined ) { + newValues[ attributeName ] = value; + } } return newValues; }, diff --git a/packages/editor/src/bindings/term-data.js b/packages/editor/src/bindings/term-data.js index 041a9be10b4c22..2bcd508e79378a 100644 --- a/packages/editor/src/bindings/term-data.js +++ b/packages/editor/src/bindings/term-data.js @@ -52,7 +52,8 @@ export const termDataFields = [ export default { name: 'core/term-data', usesContext: [ 'taxonomy', 'termId', 'termData' ], - getValues( { select, context, bindings, clientId } ) { + supportsCopy: true, + getValues( { select, context, bindings, clientId, isForCopy } ) { const { getEntityRecord } = select( coreDataStore ); /* @@ -95,6 +96,13 @@ export default { const termDataField = termDataFields.find( ( field ) => field.args.field === binding.args.field ); + if ( + isForCopy && + ( ! termDataField || + termDataValues?.[ binding.args.field ] === undefined ) + ) { + continue; + } if ( ! termDataField ) { // If the field is unknown, return the field name. diff --git a/packages/editor/src/bindings/test/pattern-overrides.jsdom.test.js b/packages/editor/src/bindings/test/pattern-overrides.jsdom.test.js index 5708f0c01f555b..7bc8b4fa476ac4 100644 --- a/packages/editor/src/bindings/test/pattern-overrides.jsdom.test.js +++ b/packages/editor/src/bindings/test/pattern-overrides.jsdom.test.js @@ -17,6 +17,52 @@ describe( 'pattern-overrides bindings', () => { } ); describe( 'getValues', () => { + it( 'copies an explicit empty override instead of restoring the saved fallback', () => { + const options = { + select: makeSelect( blockAttributes ), + clientId: 'block-1', + context: { + 'pattern/overrides': { + 'Editable Paragraph': { content: '' }, + }, + }, + bindings: { content: { source: 'core/pattern-overrides' } }, + }; + + expect( patternOverridesBindings.getValues( options ) ).toEqual( { + content: undefined, + } ); + expect( + patternOverridesBindings.getValues( { + ...options, + isForCopy: true, + } ) + ).toEqual( { content: '' } ); + } ); + + it.each( [ 'Overridden content', 0, false, null ] )( + 'copies the genuine override %s', + ( value ) => { + const options = { + select: makeSelect( blockAttributes ), + clientId: 'block-1', + context: { + 'pattern/overrides': { + 'Editable Paragraph': { content: value }, + }, + }, + bindings: { content: { source: 'core/pattern-overrides' } }, + isForCopy: true, + }; + + expect( patternOverridesBindings.getValues( options ) ).toEqual( + { + content: value, + } + ); + } + ); + it( 'returns the current attribute value when there is no override', () => { const values = patternOverridesBindings.getValues( { select: makeSelect( blockAttributes ), diff --git a/packages/editor/src/bindings/test/post-data.jsdom.test.js b/packages/editor/src/bindings/test/post-data.jsdom.test.js index 1a7680e51c540c..a95e8230e3ff6b 100644 --- a/packages/editor/src/bindings/test/post-data.jsdom.test.js +++ b/packages/editor/src/bindings/test/post-data.jsdom.test.js @@ -202,3 +202,114 @@ describe( 'post-data bindings', () => { } ); } ); } ); + +describe( 'post-data values for copying', () => { + function createSelect( entityData, blockName = 'core/post-date' ) { + return ( store ) => + store === blockEditorStore + ? { + getBlockName: () => blockName, + getSelectedBlockClientId: () => 'block-1', + getBlockAttributes: () => ( { id: 456, type: 'page' } ), + } + : { + getEditedEntityRecord: () => entityData, + canUser: () => false, + }; + } + + it( 'omits an unknown field key even when the entity contains that property', () => { + const options = { + select: createSelect( { unknown: 'Not a supported field' } ), + context: { postId: 123, postType: 'post' }, + clientId: 'block-1', + bindings: { content: { args: { field: 'unknown' } } }, + }; + + expect( postDataBindings.getValues( options ) ).toEqual( { + content: 'unknown', + } ); + expect( + postDataBindings.getValues( { ...options, isForCopy: true } ) + ).toEqual( {} ); + } ); + + it( 'omits the display label when the entity is unavailable', () => { + const options = { + select: createSelect( undefined ), + context: { postId: 123, postType: 'post' }, + clientId: 'block-1', + bindings: { content: { args: { field: 'date' } } }, + }; + + expect( postDataBindings.getValues( options ) ).toEqual( { + content: 'Post Date', + } ); + expect( + postDataBindings.getValues( { ...options, isForCopy: true } ) + ).toEqual( {} ); + } ); + + it.each( [ 'date', 'Post Date', '', 0, false, null ] )( + 'copies the genuine read-only entity value %s', + ( value ) => { + const options = { + select: createSelect( { date: value } ), + context: { postId: 123, postType: 'post' }, + clientId: 'block-1', + bindings: { content: { args: { field: 'date' } } }, + }; + + expect( postDataBindings.canUserEditValue( options ) ).toBe( + false + ); + expect( postDataBindings.getValues( options ) ).toEqual( { + content: value, + } ); + expect( + postDataBindings.getValues( { ...options, isForCopy: true } ) + ).toEqual( { content: value } ); + } + ); + + it( 'omits only unavailable attributes in a batched copy request', () => { + expect( + postDataBindings.getValues( { + select: createSelect( { date: '2026-11-24 07:00:00' } ), + context: { postId: 123, postType: 'post' }, + clientId: 'block-1', + bindings: { + content: { args: { field: 'date' } }, + title: { args: { field: 'unknown' } }, + url: { args: { field: 'link' } }, + }, + isForCopy: true, + } ) + ).toEqual( { content: '2026-11-24 07:00:00' } ); + } ); + + it( 'copies a read-only navigation link from its own entity', () => { + const select = ( store ) => + store === blockEditorStore + ? { + getBlockName: () => 'core/navigation-link', + getBlockAttributes: () => ( { id: 456, type: 'page' } ), + } + : { + getEditedEntityRecord: ( _, type, id ) => + type === 'page' && id === 456 + ? { link: 'https://example.com/page' } + : undefined, + }; + + expect( + postDataBindings.getValues( { + select, + context: { postId: 123, postType: 'post' }, + clientId: 'block-1', + bindings: { url: { args: { field: 'link' } } }, + isForCopy: true, + } ) + ).toEqual( { url: 'https://example.com/page' } ); + } ); +} ); diff --git a/packages/editor/src/bindings/test/post-meta.jsdom.test.js b/packages/editor/src/bindings/test/post-meta.jsdom.test.js index a69145cba542f3..61184cb3e79570 100644 --- a/packages/editor/src/bindings/test/post-meta.jsdom.test.js +++ b/packages/editor/src/bindings/test/post-meta.jsdom.test.js @@ -205,3 +205,129 @@ describe( 'post-meta bindings', () => { } ); } ); } ); + +describe( 'post-meta values for copying', () => { + function createSelect( meta = {}, hasEntity = true ) { + const selectors = { + getEditedEntityRecord: () => ( hasEntity ? { meta } : undefined ), + getEditorSettings: () => ( { enableCustomFields: false } ), + canUser: () => false, + }; + lock( selectors, { + getRegisteredPostMeta: () => ( { + movie_field: { + title: 'Movie Field Label', + default: 'Movie field default value', + type: 'string', + }, + _protected_field: { type: 'string' }, + footnotes: { type: 'string' }, + } ), + } ); + return () => selectors; + } + + it( 'keeps the saved fallback when the edited entity is unavailable', () => { + const options = { + select: createSelect( {}, false ), + context: { postType: 'movie', postId: 123 }, + bindings: { content: { args: { key: 'movie_field' } } }, + }; + + expect( postMetaBindings.getValues( options ) ).toEqual( { + content: 'Movie Field Label', + } ); + expect( + postMetaBindings.getValues( { ...options, isForCopy: true } ) + ).toEqual( {} ); + } ); + + it.each( [ 'inaccessible_field', '_protected_field', 'footnotes' ] )( + 'omits the display key for unavailable field %s', + ( key ) => { + const options = { + select: createSelect( { [ key ]: 'Unavailable value' } ), + context: { postType: 'movie', postId: 123 }, + bindings: { content: { args: { key } } }, + }; + + expect( postMetaBindings.getValues( options ) ).toEqual( { + content: key, + } ); + expect( + postMetaBindings.getValues( { ...options, isForCopy: true } ) + ).toEqual( {} ); + } + ); + + it( 'omits a display default when no post is available', () => { + const options = { + select: createSelect(), + context: { postType: 'movie' }, + bindings: { content: { args: { key: 'movie_field' } } }, + }; + + expect( postMetaBindings.getValues( options ) ).toEqual( { + content: 'Movie field default value', + } ); + expect( + postMetaBindings.getValues( { ...options, isForCopy: true } ) + ).toEqual( {} ); + } ); + + it.each( [ undefined, null ] )( + 'omits the display label when the actual meta value is %s', + ( value ) => { + const options = { + select: createSelect( { movie_field: value } ), + context: { postType: 'movie', postId: 123 }, + bindings: { content: { args: { key: 'movie_field' } } }, + }; + + expect( postMetaBindings.getValues( options ) ).toEqual( { + content: 'Movie Field Label', + } ); + expect( + postMetaBindings.getValues( { ...options, isForCopy: true } ) + ).toEqual( {} ); + } + ); + + it.each( [ 'movie_field', 'Movie Field Label', '', 0, false ] )( + 'copies the genuine read-only meta value %s', + ( value ) => { + const options = { + select: createSelect( { movie_field: value } ), + context: { postType: 'movie', postId: 123 }, + bindings: { content: { args: { key: 'movie_field' } } }, + }; + + expect( + postMetaBindings.canUserEditValue( { + ...options, + args: { key: 'movie_field' }, + } ) + ).toBe( false ); + expect( postMetaBindings.getValues( options ) ).toEqual( { + content: value, + } ); + expect( + postMetaBindings.getValues( { ...options, isForCopy: true } ) + ).toEqual( { content: value } ); + } + ); + + it( 'omits only unavailable attributes in a batched copy request', () => { + expect( + postMetaBindings.getValues( { + select: createSelect( { movie_field: 'Readable value' } ), + context: { postType: 'movie', postId: 123 }, + bindings: { + content: { args: { key: 'movie_field' } }, + title: { args: { key: 'inaccessible_field' } }, + }, + isForCopy: true, + } ) + ).toEqual( { content: 'Readable value' } ); + } ); +} ); diff --git a/packages/editor/src/bindings/test/term-data.jsdom.test.js b/packages/editor/src/bindings/test/term-data.jsdom.test.js index 52349e1d7c8168..4950617bcee9ef 100644 --- a/packages/editor/src/bindings/test/term-data.jsdom.test.js +++ b/packages/editor/src/bindings/test/term-data.jsdom.test.js @@ -58,6 +58,99 @@ describe( 'term-data bindings', () => { }; describe( 'getValues', () => { + describe( 'clipboard values', () => { + function options( blockName, record, fields = bindings ) { + return { + select: ( store ) => + store === coreDataStore + ? { getEntityRecord: () => record } + : { + getBlockName: () => blockName, + getBlockAttributes: () => ( { + id: 123, + type: 'category', + } ), + getSelectedBlockClientId: () => + 'term-block', + }, + context: { taxonomy: 'category', termId: 123 }, + clientId: 'term-block', + bindings: fields, + }; + } + + it.each( [ 'core/paragraph', 'core/navigation-link' ] )( + 'omits unavailable field labels and unknown keys when copying %s', + ( blockName ) => { + const request = options( blockName, undefined ); + expect( + termDataBindings.getValues( request ) + ).toMatchObject( { + name: 'Name', + link: 'Link', + content: 'unknown', + } ); + expect( + termDataBindings.getValues( { + ...request, + isForCopy: true, + } ) + ).toEqual( {} ); + } + ); + + it.each( [ 'name', 'Name', '' ] )( + 'preserves a genuine read-only term name equal to %j', + ( name ) => { + const request = options( + 'core/navigation-link', + { name }, + { + label: { args: { field: 'name' } }, + url: { args: { field: 'link' } }, + } + ); + expect( termDataBindings.canUserEditValue( request ) ).toBe( + false + ); + expect( + termDataBindings.getValues( { + ...request, + isForCopy: true, + } ) + ).toEqual( { label: name } ); + } + ); + + it( 'preserves available zero, empty and formatted count values while omitting a missing field', () => { + const request = options( 'core/paragraph', { + id: 0, + name: '', + parent: 0, + count: 0, + } ); + expect( + termDataBindings.getValues( { + ...request, + isForCopy: true, + } ) + ).toEqual( { id: 0, name: '', parent: 0, count: '(0)' } ); + } ); + + it( 'copies genuine context term data when the entity record is unavailable', () => { + const request = options( 'core/paragraph', undefined, { + content: { args: { field: 'name' } }, + } ); + expect( + termDataBindings.getValues( { + ...request, + context: { termData: { name: 'Context name' } }, + isForCopy: true, + } ) + ).toEqual( { content: 'Context name' } ); + } ); + } ); + describe( 'for regular blocks using block context', () => { describe( 'when termId and taxonomy are provided in context', () => { const select = ( store ) => { diff --git a/packages/editor/src/bindings/test/visualization-date-example.test.ts b/packages/editor/src/bindings/test/visualization-date-example.test.ts new file mode 100644 index 00000000000000..18071347fe6561 --- /dev/null +++ b/packages/editor/src/bindings/test/visualization-date-example.test.ts @@ -0,0 +1,125 @@ +import { readFileSync } from 'node:fs'; +import { runInNewContext } from 'node:vm'; +import { describe, expect, it } from 'vitest'; + +interface SourceRequest { + select: ( store: unknown ) => { + getEditedEntityRecord: ( + kind: string, + postType: string, + postId: number + ) => { meta: { wp_movies_visualization_date?: string | null } }; + }; + context: { postType: string; postId: number }; + isForCopy?: boolean; +} + +interface DocumentedSource { + supportsCopy?: boolean; + getValues: ( request: SourceRequest ) => { content?: string }; +} + +const documentation = readFileSync( + new URL( + '../../../../../docs/reference-guides/block-api/block-bindings.md', + import.meta.url + ), + 'utf8' +).replace( /\r\n/g, '\n' ); +const example = Array.from( documentation.matchAll( /```js\n([\s\S]*?)```/g ) ) + .map( ( match ) => match[ 1 ] ) + .find( ( code ) => code.includes( "name: 'wpmovies/visualization-date'" ) ); + +function getSource() { + if ( ! example ) { + throw new Error( + 'The documented source registration example is missing.' + ); + } + let source: DocumentedSource | undefined; + runInNewContext( + example.replace( /^import .*;\n/gm, '' ), + { + registerBlockBindingsSource: ( value: DocumentedSource ) => { + source = value; + }, + __: ( text: string ) => text, + coreDataStore: {}, + Date: class extends Date { + toLocaleDateString() { + return 'Today placeholder'; + } + }, + }, + { timeout: 1000 } + ); + if ( ! source ) { + throw new Error( 'The documented source was not registered.' ); + } + return source; +} + +describe( 'the documented visualization-date source', () => { + it( 'opts in to copy resolution and keeps its display fallback out of the clipboard', () => { + const source = getSource(); + const request = { + select: () => ( { getEditedEntityRecord: () => ( { meta: {} } ) } ), + context: { postType: 'post', postId: 41 }, + }; + expect( source.getValues( request ).content ).toBe( + 'Today placeholder' + ); + expect( + source.getValues( { ...request, isForCopy: true } ) + ).not.toHaveProperty( 'content' ); + expect( source.supportsCopy ).toBe( true ); + } ); + + it( 'preserves a genuine stored date for display and copy', () => { + const source = getSource(); + const request = { + select: () => ( { + getEditedEntityRecord: () => ( { + meta: { wp_movies_visualization_date: '2026-11-23' }, + } ), + } ), + context: { postType: 'post', postId: 41 }, + }; + expect( source.getValues( request ).content ).toBe( '2026-11-23' ); + expect( + source.getValues( { ...request, isForCopy: true } ).content + ).toBe( '2026-11-23' ); + } ); + + const fallbackCases: { + label: string; + storedValue: string | null; + expectedCopy: { content?: string }; + }[] = [ + { + label: 'an empty string', + storedValue: '', + expectedCopy: { content: '' }, + }, + { label: 'null', storedValue: null, expectedCopy: {} }, + ]; + it.each( fallbackCases )( + 'keeps the display fallback separate from the copied value for $label', + ( { storedValue, expectedCopy } ) => { + const source = getSource(); + const request = { + select: () => ( { + getEditedEntityRecord: () => ( { + meta: { wp_movies_visualization_date: storedValue }, + } ), + } ), + context: { postType: 'post', postId: 41 }, + }; + expect( source.getValues( request ).content ).toBe( + 'Today placeholder' + ); + const copied = source.getValues( { ...request, isForCopy: true } ); + expect( { ...copied } ).toStrictEqual( expectedCopy ); + } + ); +} ); diff --git a/test/e2e/specs/editor/various/block-bindings/post-meta.spec.js b/test/e2e/specs/editor/various/block-bindings/post-meta.spec.js index 45b0ee9691e7b7..216e3888b8e9e5 100644 --- a/test/e2e/specs/editor/various/block-bindings/post-meta.spec.js +++ b/test/e2e/specs/editor/various/block-bindings/post-meta.spec.js @@ -1,5 +1,19 @@ const { test, expect } = require( '@wordpress/e2e-test-utils-playwright' ); +async function expectResolvedClipboard( page ) { + await expect + .poll( () => page.evaluate( () => navigator.clipboard.readText() ) ) + .toBe( 'Bound text' ); + const clipboardHtml = await page.evaluate( async () => { + const items = await navigator.clipboard.read(); + const item = items.find( ( entry ) => + entry.types.includes( 'text/html' ) + ); + return ( await item.getType( 'text/html' ) ).text(); + } ); + expect( clipboardHtml ).toContain( '

        Bound text

        ' ); +} + test.describe( 'Post Meta source', () => { test.beforeAll( async ( { requestUtils } ) => { await requestUtils.activateTheme( 'emptytheme' ); @@ -382,6 +396,228 @@ test.describe( 'Post Meta source', () => { await editor.openDocumentSettingsSidebar(); } ); + for ( const copyMethod of [ 'keyboard', 'menu', 'list view' ] ) { + const tag = copyMethod === 'menu' ? ' @webkit' : ''; + + test( `should copy resolved bound block content through the ${ copyMethod } and preserve its binding on paste${ tag }`, async ( { + editor, + page, + pageUtils, + context, + browserName, + } ) => { + if ( browserName === 'chromium' ) { + await context.grantPermissions( [ + 'clipboard-read', + 'clipboard-write', + ] ); + await page.evaluate( () => + navigator.clipboard.writeText( 'Uncopied' ) + ); + } + const modifier = + process.platform === 'darwin' ? 'Meta' : 'Control'; + await page.evaluate( () => { + window.wp.data.dispatch( 'core/editor' ).editPost( { + meta: { movie_field: 'Bound text' }, + } ); + } ); + const bindings = { + content: { + source: 'core/post-meta', + args: { key: 'movie_field' }, + }, + }; + const boundParagraph = { + name: 'core/paragraph', + attributes: { content: '', metadata: { bindings } }, + }; + await editor.insertBlock( boundParagraph ); + const paragraphBlock = editor.canvas.getByRole( 'document', { + name: 'Block: Paragraph', + } ); + await expect( paragraphBlock ).toHaveText( 'Bound text' ); + await paragraphBlock.click(); + if ( copyMethod === 'menu' ) { + await editor.clickBlockToolbarButton( 'Options' ); + await page + .getByRole( 'menu', { name: 'Options' } ) + .getByRole( 'menuitem' ) + .filter( { + has: page.getByText( 'Copy', { exact: true } ), + } ) + .click(); + } else if ( copyMethod === 'list view' ) { + await pageUtils.pressKeys( 'access+o' ); + await page + .getByRole( 'treegrid', { + name: 'Block navigation structure', + } ) + .getByRole( 'gridcell', { + name: 'Paragraph', + exact: true, + } ) + .click(); + await page.keyboard.press( `${ modifier }+c` ); + } else { + await page.keyboard.press( `${ modifier }+c` ); + } + + if ( browserName === 'chromium' ) { + await expectResolvedClipboard( page ); + } + expect( await editor.getBlocks() ).toMatchObject( [ + boundParagraph, + ] ); + if ( copyMethod === 'list view' ) { + await pageUtils.pressKeys( 'access+o' ); + } + await editor.insertBlock( { name: 'core/paragraph' } ); + await page.keyboard.press( `${ modifier }+v` ); + await expect.poll( editor.getBlocks ).toMatchObject( [ + boundParagraph, + { + name: 'core/paragraph', + attributes: { + content: 'Bound text', + metadata: { bindings }, + }, + }, + ] ); + } ); + } + + test( 'should paste styles from a bound paragraph copied through Options', async ( { + editor, + page, + context, + } ) => { + await context.grantPermissions( [ + 'clipboard-read', + 'clipboard-write', + ] ); + await page.evaluate( () => { + window.wp.data.dispatch( 'core/editor' ).editPost( { + meta: { movie_field: 'Bound text' }, + } ); + } ); + const style = { typography: { fontSize: '23px' } }; + await editor.insertBlock( { + name: 'core/paragraph', + attributes: { + style, + metadata: { + bindings: { + content: { + source: 'core/post-meta', + args: { key: 'movie_field' }, + }, + }, + }, + }, + } ); + await editor.insertBlock( { + name: 'core/paragraph', + attributes: { content: 'Target' }, + } ); + const paragraphs = editor.canvas.getByRole( 'document', { + name: 'Block: Paragraph', + } ); + await expect( paragraphs.first() ).toHaveText( 'Bound text' ); + await paragraphs.first().click(); + await editor.clickBlockToolbarButton( 'Options' ); + const menu = page.getByRole( 'menu', { name: 'Options' } ); + await menu + .getByRole( 'menuitem' ) + .filter( { has: page.getByText( 'Copy', { exact: true } ) } ) + .click(); + await expect + .poll( () => + page.evaluate( () => navigator.clipboard.readText() ) + ) + .toBe( 'Bound text' ); + await page.keyboard.press( 'Escape' ); + + await paragraphs.last().click(); + await editor.clickBlockToolbarButton( 'Options' ); + await menu + .getByRole( 'menuitem', { name: 'Paste styles' } ) + .click(); + await expect.poll( editor.getBlocks ).toMatchObject( [ + { name: 'core/paragraph', attributes: { style } }, + { + name: 'core/paragraph', + attributes: { content: 'Target', style }, + }, + ] ); + } ); + + test( 'should copy resolved text in a mixed block selection without changing the original blocks', async ( { + editor, + page, + context, + } ) => { + await context.grantPermissions( [ + 'clipboard-read', + 'clipboard-write', + ] ); + await page.evaluate( () => + navigator.clipboard.writeText( 'Uncopied' ) + ); + const modifier = process.platform === 'darwin' ? 'Meta' : 'Control'; + const bindings = { + content: { + source: 'core/post-meta', + args: { key: 'movie_field' }, + }, + }; + const boundParagraph = { + name: 'core/paragraph', + attributes: { content: '', metadata: { bindings } }, + }; + const normalParagraph = { + name: 'core/paragraph', + attributes: { content: 'Normal paragraph for comparison' }, + }; + await editor.insertBlock( boundParagraph ); + await editor.insertBlock( normalParagraph ); + const paragraphBlocks = editor.canvas.getByRole( 'document', { + name: 'Block: Paragraph', + } ); + await expect( paragraphBlocks.first() ).toHaveText( + 'Movie field default value' + ); + await paragraphBlocks.first().click(); + await page.keyboard.press( 'Home' ); + await paragraphBlocks.last().click( { modifiers: [ 'Shift' ] } ); + await page.keyboard.press( `${ modifier }+c` ); + await expect + .poll( () => + page.evaluate( () => navigator.clipboard.readText() ) + ) + .toBe( + 'Movie field default value\n\nNormal paragraph for comparison' + ); + expect( await editor.getBlocks() ).toMatchObject( [ + boundParagraph, + normalParagraph, + ] ); + await editor.insertBlock( { name: 'core/paragraph' } ); + await page.keyboard.press( `${ modifier }+v` ); + await expect.poll( editor.getBlocks ).toMatchObject( [ + boundParagraph, + normalParagraph, + { + name: 'core/paragraph', + attributes: { + content: 'Movie field default value', + metadata: { bindings }, + }, + }, + normalParagraph, + ] ); + } ); + test( 'should show the custom field value of that specific post', async ( { editor, } ) => {