diff --git a/packages/block-editor/src/hooks/html-attributes.ts b/packages/block-editor/src/hooks/html-attributes.ts new file mode 100644 index 00000000000000..2c2b9aa6170f84 --- /dev/null +++ b/packages/block-editor/src/hooks/html-attributes.ts @@ -0,0 +1,122 @@ +import { addFilter } from '@wordpress/hooks'; +import { getBlockType } from '@wordpress/blocks'; +import type { BlockType } from '@wordpress/blocks'; +import type { BlockListBlockFeatureProps, BlockWrapperProps } from './types'; + +type HtmlAttributes = Record< string, string >; + +/** + * Adds `htmlAttributes`: attributes of a block's element that the block + * doesn't know, read from its HTML. They're kept out of the delimiter. + * + * @param settings Block settings. + * + * @return Block settings. + */ +export function addAttribute( settings: BlockType ): BlockType { + settings.attributes = { + ...settings.attributes, + htmlAttributes: { type: 'object', role: 'local' }, + }; + return settings; +} + +/** + * Turns an inline style into a style object, as React expects. + * + * @param style Value of a `style` attribute. + */ +function getStyleObject( style: string ): Record< string, string > { + const styleObject: Record< string, string > = {}; + for ( const declaration of style.split( ';' ) ) { + const colonAt = declaration.indexOf( ':' ); + const property = declaration.slice( 0, colonAt ).trim(); + if ( colonAt === -1 || ! property ) { + continue; + } + const key = property.startsWith( '--' ) + ? property + : property + .toLowerCase() + .replace( /^-ms-/, 'ms-' ) + .replace( /-([a-z])/g, ( _match, letter ) => + letter.toUpperCase() + ); + styleObject[ key ] = declaration.slice( colonAt + 1 ).trim(); + } + return styleObject; +} + +/** + * Adds attributes to props without replacing the block's own: its style + * properties win over the same ones in `htmlAttributes`. + * + * @param props Props. + * @param htmlAttributes Attributes to add. + */ +function mergeHtmlAttributes( + props: BlockWrapperProps, + htmlAttributes: HtmlAttributes +): BlockWrapperProps { + const { style, ...attributes } = htmlAttributes; + const merged = { ...props }; + for ( const [ name, value ] of Object.entries( attributes ) ) { + if ( ! ( name in merged ) ) { + merged[ name ] = value; + } + } + if ( style ) { + merged.style = { ...getStyleObject( style ), ...props.style }; + } + return merged; +} + +export function addSaveProps( + extraProps: BlockWrapperProps, + _blockType: BlockType, + { htmlAttributes }: { htmlAttributes?: HtmlAttributes } +): BlockWrapperProps { + return htmlAttributes + ? mergeHtmlAttributes( extraProps, htmlAttributes ) + : extraProps; +} + +/** + * Shows `htmlAttributes` in the editor, leaving out event handlers, script + * links, and anything that would change how the block is edited. + * + * @param props Block props. + * @param props.htmlAttributes Attributes to show. + */ +function useBlockProps( { + htmlAttributes, +}: BlockListBlockFeatureProps ): BlockWrapperProps { + const safeAttributes = Object.fromEntries( + Object.entries( htmlAttributes as HtmlAttributes ).filter( + ( [ name, value ] ) => + ! name.startsWith( 'on' ) && + name !== 'contenteditable' && + ! /^\s*javascript:/i.test( value ) + ) + ); + return mergeHtmlAttributes( {}, safeAttributes ); +} + +export default { + useBlockProps, + addSaveProps, + attributeKeys: [ 'htmlAttributes' ], + hasSupport( nameOrType: string | BlockType ) { + const blockType = + typeof nameOrType === 'string' + ? getBlockType( nameOrType ) + : nameOrType; + return !! blockType?.attributes?.htmlAttributes; + }, +}; + +addFilter( + 'blocks.registerBlockType', + 'core/editor/html-attributes/attribute', + addAttribute +); diff --git a/packages/block-editor/src/hooks/index.ts b/packages/block-editor/src/hooks/index.ts index bdf8b72093fb9b..7d1790f845c09c 100644 --- a/packages/block-editor/src/hooks/index.ts +++ b/packages/block-editor/src/hooks/index.ts @@ -11,6 +11,7 @@ import allowedBlocks from './allowed-blocks'; import anchor from './anchor'; import ariaLabel from './aria-label'; import customClassName from './custom-class-name'; +import htmlAttributes from './html-attributes'; import './generated-class-name'; import style from './style'; import './settings'; @@ -57,6 +58,7 @@ createBlockEditFilter( ].filter( Boolean ) ); createBlockListBlockFilter( [ + htmlAttributes, align, textAlign, background, @@ -88,6 +90,8 @@ createBlockSaveFilter( [ fontFamily, fontSize, textShadow, + // Last, so the block's own styles win over these. + htmlAttributes, ] ); export { useCustomSides } from './dimensions'; diff --git a/packages/block-editor/src/hooks/test/html-attributes.ts b/packages/block-editor/src/hooks/test/html-attributes.ts new file mode 100644 index 00000000000000..3f6526195b15d9 --- /dev/null +++ b/packages/block-editor/src/hooks/test/html-attributes.ts @@ -0,0 +1,48 @@ +import { describe, expect, it } from 'vitest'; +import type { BlockType } from '@wordpress/blocks'; +import htmlAttributes, { addSaveProps } from '../html-attributes'; + +describe( 'htmlAttributes', () => { + it( 'shows attributes in the editor, without unsafe ones', () => { + expect( + htmlAttributes.useBlockProps( { + name: 'core/paragraph', + clientId: '1', + htmlAttributes: { + style: 'background:#fffbe6; border-left:4px solid;--gap:1em;-webkit-line-clamp:2', + 'data-note': 'tip', + onclick: 'alert(1)', + contenteditable: 'false', + 'data-href': ' javascript:alert(1)', + }, + } ) + ).toEqual( { + 'data-note': 'tip', + style: { + background: '#fffbe6', + borderLeft: '4px solid', + '--gap': '1em', + WebkitLineClamp: '2', + }, + } ); + } ); + + it( 'saves attributes under the block’s own props', () => { + expect( + addSaveProps( + { className: 'has-text-color', style: { color: '#000' } }, + {} as BlockType, + { + htmlAttributes: { + style: 'color:red;padding:1px', + 'data-note': 'tip', + }, + } + ) + ).toEqual( { + className: 'has-text-color', + style: { color: '#000', padding: '1px' }, + 'data-note': 'tip', + } ); + } ); +} ); diff --git a/packages/block-editor/src/store/utils.ts b/packages/block-editor/src/store/utils.ts index ad1ef5888563d7..a5e9a7a31dbaf8 100644 --- a/packages/block-editor/src/store/utils.ts +++ b/packages/block-editor/src/store/utils.ts @@ -63,10 +63,15 @@ export function mapUserPattern( }; } +// Pattern blocks are inserted as new blocks, not as the pattern is written. +function withoutSource( { undelimitedSource, ...block }: Block ): Block { + return { ...block, innerBlocks: block.innerBlocks.map( withoutSource ) }; +} + function parsePattern( pattern: BlockPattern ): ParsedBlockPattern { const blocks = parse( pattern.content, { __unstableSkipMigrationLogs: true, - } ); + } ).map( withoutSource ); if ( blocks.length === 1 ) { blocks[ 0 ].attributes = { ...blocks[ 0 ].attributes, diff --git a/packages/blocks/CHANGELOG.md b/packages/blocks/CHANGELOG.md index d2a33eac6c2bca..48040522c4682d 100644 --- a/packages/blocks/CHANGELOG.md +++ b/packages/blocks/CHANGELOG.md @@ -2,6 +2,10 @@ ## Unreleased +### New Features + +- `parse` reads HTML outside block delimiters as blocks instead of one Classic block, and `serialize` saves blocks that weren't edited as they were read: blocks with delimiters exactly, and HTML outside delimiters as the browser writes it, with nothing added. Blocks read without delimiters are saved without them unless an edit needs one; new blocks get delimiters, Classic blocks too ([#85524](https://github.com/WordPress/gutenberg/pull/85524)). + ### Bug Fixes - Add the `input` block transform type, and let `getSaveElement` take an element in place of inner blocks in the types, as the runtime already does ([#85025](https://github.com/WordPress/gutenberg/pull/85025)). diff --git a/packages/blocks/src/api/parser/apply-built-in-validation-fixes.ts b/packages/blocks/src/api/parser/apply-built-in-validation-fixes.ts index 1238881491f204..c90c0fcbe443ce 100644 --- a/packages/blocks/src/api/parser/apply-built-in-validation-fixes.ts +++ b/packages/blocks/src/api/parser/apply-built-in-validation-fixes.ts @@ -1,5 +1,6 @@ import { fixCustomClassname } from './fix-custom-classname'; import { fixGlobalAttribute } from './fix-global-attribute'; +import { fixHtmlAttributes } from './fix-html-attributes'; import type { Block, BlockAttribute, BlockType } from '../../types'; const ARIA_LABEL_ATTR_SCHEMA: BlockAttribute = { @@ -59,6 +60,13 @@ export function applyBuiltInValidationFixes( ANCHOR_ATTR_SCHEMA ); + // Keep any other attributes of the root element. + updatedBlockAttributes = fixHtmlAttributes( + updatedBlockAttributes, + blockType, + originalContent ?? '' + ); + return { ...block, attributes: updatedBlockAttributes, diff --git a/packages/blocks/src/api/parser/fix-html-attributes.ts b/packages/blocks/src/api/parser/fix-html-attributes.ts new file mode 100644 index 00000000000000..3f8ec568dddcdf --- /dev/null +++ b/packages/blocks/src/api/parser/fix-html-attributes.ts @@ -0,0 +1,76 @@ +import { getSaveContent } from '../serializer'; +import { getRootElement, readStyle } from '../undelimited'; +import type { BlockType } from '../../types'; + +/** + * Returns the attributes of the element a piece of HTML is. Attributes + * without a value are read as empty strings. + * + * @param html HTML. + */ +function getRootAttributes( html: string ): Map< string, string > | null { + const root = getRootElement( html ); + return root + ? new Map( + root + .getAttributeNames() + .map( ( name ) => [ + name, + root.getAttribute( name ) ?? '', + ] ) + ) + : null; +} + +/** + * Reads the attributes of a block's root element that its `save` doesn't + * produce into `htmlAttributes`, so they're shown in the editor and saved + * again. For `style`, only the properties `save` doesn't set are kept. + * + * @param blockAttributes Block attributes. + * @param blockType Block type. + * @param innerHTML The block's HTML. + * + * @return Block attributes. + */ +export function fixHtmlAttributes( + blockAttributes: Record< string, unknown >, + blockType: BlockType, + innerHTML: string +): Record< string, unknown > { + if ( ! blockType.attributes?.htmlAttributes ) { + return blockAttributes; + } + + const { htmlAttributes, ...attributes } = blockAttributes; + const written = getRootAttributes( innerHTML ); + const saved = getRootAttributes( getSaveContent( blockType, attributes ) ); + if ( ! written || ! saved ) { + return blockAttributes; + } + + const extra: Record< string, string > = {}; + for ( const [ name, value ] of written ) { + if ( name === 'style' ) { + const savedStyle = readStyle( saved.get( 'style' ) ?? '' ); + const style = value + .split( ';' ) + .filter( ( declaration ) => { + const property = declaration.split( ':' )[ 0 ].trim(); + return ( + property && ! savedStyle.has( property.toLowerCase() ) + ); + } ) + .join( ';' ); + if ( style ) { + extra.style = style; + } + } else if ( name !== 'class' && ! saved.has( name ) ) { + extra[ name ] = value; + } + } + + return Object.keys( extra ).length + ? { ...attributes, htmlAttributes: extra } + : attributes; +} diff --git a/packages/blocks/src/api/parser/index.ts b/packages/blocks/src/api/parser/index.ts index 0355a0cee0c609..8c6309357035b7 100644 --- a/packages/blocks/src/api/parser/index.ts +++ b/packages/blocks/src/api/parser/index.ts @@ -13,6 +13,7 @@ import { serializeRawBlock } from './serialize-raw-block'; import { getBlockAttributes } from './get-block-attributes'; import { applyBlockDeprecatedVersions } from './apply-block-deprecated-versions'; import { applyBuiltInValidationFixes } from './apply-built-in-validation-fixes'; +import { addSource, canReadHTML, parseUndelimited } from '../undelimited'; import type { Block, BlockType, RawBlock, ParseOptions } from '../../types'; /** @@ -150,18 +151,82 @@ function applyBlockValidation( return { ...fixedBlock, isValid: isFixedValid, validationIssues }; } +interface ParseContext { + isTopLevel?: boolean; + writtenBlocks?: WeakMap< RawBlock, string >; +} + +// The default block parser's pattern for delimiters. +const DELIMITER = + /)[^])*)\5|[^]*?)}\s+)?(\/)?-->/g; + +/** + * Finds the text each block was written as, so it can be saved exactly that + * way. The parser doesn't report where blocks start and end, so this walks + * the delimiters the same way; blocks appear in the order of their openers. + * + * @param content Post content. + * @param rawBlocks Blocks the parser read from it. + */ +function getWrittenBlocks( + content: string, + rawBlocks: RawBlock[] +): WeakMap< RawBlock, string > { + const written: Array< { name: string; text?: string } > = []; + const open: Array< { index: number; start: number } > = []; + for ( const match of content.matchAll( DELIMITER ) ) { + const [ token, isCloser, namespace, name, , , isVoid ] = match; + const start = match.index as number; + if ( isCloser ) { + const opener = open.pop(); + if ( opener ) { + written[ opener.index ].text = content.slice( + opener.start, + start + token.length + ); + } + continue; + } + written.push( { + name: ( namespace ?? 'core/' ) + name, + text: isVoid ? token : undefined, + } ); + if ( ! isVoid ) { + open.push( { index: written.length - 1, start } ); + } + } + + const writtenBlocks = new WeakMap< RawBlock, string >(); + let index = 0; + const visit = ( rawBlock: RawBlock ) => { + if ( rawBlock.blockName ) { + const { name, text } = written[ index++ ] ?? {}; + if ( text && name === rawBlock.blockName ) { + writtenBlocks.set( rawBlock, text ); + } + } + rawBlock.innerBlocks?.forEach( visit ); + }; + rawBlocks.forEach( visit ); + return writtenBlocks; +} + /** * Given a raw block returned by grammar parsing, returns a fully parsed block. * * @param rawBlock The raw block object. * @param options Extra options for handling block parsing. + * @param context Whether the block is top level, and the text each block was + * written as, for optional block delimiters. * * @return Fully parsed block. */ export function parseRawBlock( rawBlock: RawBlock, - options?: ParseOptions + options?: ParseOptions, + context: ParseContext = {} ): Block | undefined { + const { isTopLevel = false, writtenBlocks } = context; let normalizedBlock = normalizeRawBlock( rawBlock, options ); // During the lifecycle of the project, we renamed some old blocks @@ -192,10 +257,22 @@ export function parseRawBlock( // Parse inner blocks recursively. const parsedInnerBlocks = normalizedBlock.innerBlocks - .map( ( innerBlock ) => parseRawBlock( innerBlock, options ) ) + .map( ( innerBlock ) => + parseRawBlock( innerBlock, options, { writtenBlocks } ) + ) // See https://github.com/WordPress/gutenberg/pull/17164. .filter( ( innerBlock ) => !! innerBlock ); + // Remember the block as written, so it can be saved that way unless it's + // edited. `content` is the HTML to apply edits to. + const withSource = ( block: Block, content: string ) => + addSource( + block, + writtenBlocks?.get( rawBlock ) ?? serializeRawBlock( rawBlock ), + content, + { isInnerBlocks: ! isTopLevel } + ); + // Get the fully parsed block. const parsedBlock = createBlock( normalizedBlock.blockName!, @@ -218,7 +295,7 @@ export function parseRawBlock( ]; parsedBlock.isValid = true; parsedBlock.validationIssues = []; - return parsedBlock; + return withSource( parsedBlock, normalizedBlock.innerHTML ); } const validatedBlock = applyBlockValidation( parsedBlock, blockType ); @@ -264,7 +341,14 @@ export function parseRawBlock( validationIssues!.forEach( ( { log, args } ) => log( ...args ) ); } - return updatedBlock; + // A block read from an old format, or holding one, is saved in the new + // format. + return updatedBlock === validatedBlock && + updatedBlock.innerBlocks.every( ( { undelimitedSource } ) => + Boolean( undelimitedSource ) + ) + ? withSource( updatedBlock, normalizedBlock.innerHTML ) + : updatedBlock; } /** @@ -292,17 +376,23 @@ export default function parse( content: string, options?: ParseOptions ): Block[] { - return grammarParse( content ).reduce( - ( accumulator: Block[], rawBlock ) => { - const block = parseRawBlock( - rawBlock as unknown as RawBlock, - options - ); - if ( block ) { - accumulator.push( block ); - } - return accumulator; - }, - [] as Block[] + const rawBlocks = grammarParse( content ) as unknown as RawBlock[]; + const writtenBlocks = getWrittenBlocks( content, rawBlocks ); + const parseTopLevel = ( rawBlock: RawBlock ) => + parseRawBlock( rawBlock, options, { isTopLevel: true, writtenBlocks } ); + if ( ! canReadHTML() ) { + return rawBlocks + .map( parseTopLevel ) + .filter( ( block ): block is Block => !! block ); + } + // HTML outside delimiters is read as blocks, not Classic blocks. + return parseUndelimited( + rawBlocks + .map( ( rawBlock ) => + rawBlock.blockName + ? parseTopLevel( rawBlock ) + : rawBlock.innerHTML + ) + .filter( ( part ): part is string | Block => !! part ) ); } diff --git a/packages/blocks/src/api/raw-handling/paste-handler.ts b/packages/blocks/src/api/raw-handling/paste-handler.ts index 354c217b0bf2c0..3ceab14dd3d0d2 100644 --- a/packages/blocks/src/api/raw-handling/paste-handler.ts +++ b/packages/blocks/src/api/raw-handling/paste-handler.ts @@ -1,3 +1,4 @@ +import { parse as grammarParse } from '@wordpress/block-serialization-default-parser'; import { getPhrasingContentSchema, removeInvalidHTML } from '@wordpress/dom'; import { htmlToBlocks } from './html-to-blocks'; import { hasBlockSupport } from '../registration'; @@ -111,7 +112,11 @@ export function pasteHandler( { // Check plain text if there is no HTML. const content = HTML ? HTML : plainText; - if ( content.indexOf( ''; + +// A blank line ends a paragraph of text. +const BLANK_LINE = /\n[ \t]*\n/; + +/** + * Returns the body of a new document holding some HTML. + * + * @param html HTML. + */ +function getBody( html: string ): HTMLElement { + const { body } = document.implementation.createHTMLDocument( '' ); + body.innerHTML = html; + return body; +} + +/** + * Returns the HTML of some nodes, as the browser writes it. + * + * @param nodes Nodes. + */ +function getHTML( nodes: Node[] ): string { + const container = document.createElement( 'div' ); + container.append( ...nodes ); + return container.innerHTML; +} + +/** + * Returns the element a piece of HTML is, if it's exactly one element. + * + * @param html HTML. + */ +export function getRootElement( html: string ): Element | null { + const body = getBody( html.trim() ); + return body.childNodes.length === 1 ? body.firstElementChild : null; +} + +interface Piece { + html: string; + before: string; + bare: boolean; +} + +/** + * Splits HTML into top-level pieces: block elements, and paragraphs of text + * and inline elements separated by blank lines. + * + * @param html HTML without delimiters. + */ +function splitPieces( html: string ): { pieces: Piece[]; after: string } { + const pieces: Piece[] = []; + // Whitespace since the last piece, and the inline nodes of a paragraph. + let whitespace = ''; + let paragraph: { before: string; nodes: Node[] } | null = null; + + const endParagraph = () => { + if ( ! paragraph ) { + return; + } + const paragraphHTML = getHTML( paragraph.nodes ); + const trimmed = paragraphHTML.trimEnd(); + pieces.push( { before: paragraph.before, html: trimmed, bare: true } ); + whitespace = paragraphHTML.slice( trimmed.length ); + paragraph = null; + }; + + const addInline = ( node: Node ) => { + paragraph ??= { before: whitespace, nodes: [] }; + whitespace = ''; + paragraph.nodes.push( node ); + }; + + for ( const node of Array.from( getBody( html ).childNodes ) ) { + if ( node.nodeType === node.TEXT_NODE ) { + // Text ends a paragraph at each blank line. + for ( const part of ( node.textContent ?? '' ).split( + /(\n[ \t]*\n\s*)/ + ) ) { + if ( BLANK_LINE.test( part ) ) { + endParagraph(); + whitespace += part; + } else if ( part.trim() || paragraph ) { + const leading = paragraph ? '' : /^\s*/.exec( part )![ 0 ]; + whitespace += leading; + addInline( + document.createTextNode( part.slice( leading.length ) ) + ); + } else { + whitespace += part; + } + } + continue; + } + + // Block elements, and comments outside a paragraph, are pieces of + // their own and end the paragraph before them. + const tag = ( node as Element ).tagName; + if ( + BLOCK_ELEMENTS.has( tag ) || + RAW_TEXT_ELEMENTS.has( tag ) || + ( node.nodeType === node.COMMENT_NODE && + ( ! paragraph || getHTML( [ node.cloneNode() ] ) === SLOT ) ) + ) { + endParagraph(); + pieces.push( { + before: whitespace, + html: getHTML( [ node ] ), + bare: false, + } ); + whitespace = ''; + continue; + } + + // Anything else is inline content of a paragraph. + addInline( node ); + } + endParagraph(); + + return { pieces, after: whitespace }; +} + +/** + * Returns the block a piece of HTML reads as, if any block reads it. + * + * @param html Piece of HTML. + */ +function readBlock( html: string ): Block | null { + // Only read the piece as a block if the browser also sees one element. + if ( ! getRootElement( html ) ) { + return null; + } + + const blocks = htmlToBlocks( html, rawHandler ); + const blockType = getBlockType( blocks[ 0 ]?.name ); + if ( + blocks.length !== 1 || + ! blockType || + blockType.name === 'core/html' + ) { + return null; + } + // Read custom classes and global attributes, like the anchor, the way + // the parser does for delimited blocks. + return applyBuiltInValidationFixes( + { ...blocks[ 0 ], originalContent: html.trim() }, + blockType + ); +} + +// Marks where found inner blocks are in an HTML block's static HTML. +const FOUND = ''; + +/** + * Returns the block for a piece of HTML, or an HTML block holding it, with + * the elements in it that blocks read, and the delimited blocks in it, as + * inner blocks. + * + * @param piece Piece of HTML. + * @param delimited Delimited blocks still to place, in order. + */ +function pieceToBlock( piece: Piece, delimited: Block[] ): Block { + if ( piece.html === SLOT ) { + return delimited.shift() as Block; + } + + // Paragraphs of text get their `

` the way WordPress adds it. + const block = piece.html.includes( SLOT ) + ? null + : readBlock( piece.bare ? autop( piece.html ) : piece.html ); + if ( block ) { + return block; + } + + const body = getBody( piece.html ); + const found: Block[] = []; + const visit = ( parent: Element ) => { + for ( const element of Array.from( parent.children ) ) { + const html = element.outerHTML; + const innerBlock = + BLOCK_ELEMENTS.has( element.tagName ) && ! html.includes( SLOT ) + ? readBlock( html ) + : null; + if ( innerBlock ) { + found.push( + addSource( innerBlock, html, html, { isInnerBlocks: true } ) + ); + element.replaceWith( getBody( FOUND ).firstChild as Comment ); + } else { + visit( element ); + } + } + }; + visit( body ); + + // Inner blocks, found and delimited, in the order they appear. + const innerContent: Array< string | null > = []; + const innerBlocks: Block[] = []; + body.innerHTML + .split( new RegExp( `(${ FOUND }|${ SLOT })` ) ) + .forEach( ( part, index ) => { + if ( index % 2 ) { + innerContent.push( null ); + innerBlocks.push( + ( part === FOUND ? found : delimited ).shift() as Block + ); + } else { + innerContent.push( part ); + } + } ); + return createBlock( 'core/html', {}, innerBlocks, innerContent ); +} + +/** + * Returns a block's `save` output, with its inner blocks saved without + * delimiters. + * + * @param block Block. + * @param innerHTMLs HTML for each inner block. + */ +function getSavedHTML( block: Block, innerHTMLs: string[] ): string { + if ( block.name === 'core/html' ) { + let index = 0; + return ( block.innerContent ?? [] ) + .map( ( part ) => part ?? innerHTMLs[ index++ ] ?? '' ) + .join( '' ) + .trim(); + } + return getSaveContent( + block.name, + block.attributes, + createElement( RawHTML, { children: innerHTMLs.join( '' ) } ) as never + ); +} + +/** + * Returns a block's `save` output, with all inner blocks saved as they would + * be without any source. + * + * @param block Block. + */ +function getPlainSavedHTML( block: Block ): string { + return getSavedHTML( block, block.innerBlocks.map( getPlainSavedHTML ) ); +} + +/** + * Reads HTML outside delimiters as blocks. Delimited blocks inside an element + * of it become inner blocks of an HTML block. + * + * @param parts HTML outside delimiters, and the delimited blocks between it. + */ +export function parseUndelimited( parts: Array< string | Block > ): Block[] { + const delimited = parts.filter( + ( part ): part is Block => typeof part !== 'string' + ); + const { pieces, after } = splitPieces( + parts + .map( ( part ) => ( typeof part === 'string' ? part : SLOT ) ) + .join( '' ) + ); + return pieces.map( ( piece, index ) => { + const block = pieceToBlock( piece, delimited ); + const whitespace = { + before: piece.before, + after: index === pieces.length - 1 ? after : '', + isFirst: index === 0, + }; + if ( piece.html === SLOT ) { + Object.assign( block.undelimitedSource ?? {}, whitespace ); + return block; + } + // The HTML as written, with any delimited blocks in it as written. + const html = piece.html.includes( SLOT ) + ? getSavedHTML( + block, + block.innerBlocks.map( + ( innerBlock ) => + innerBlock.undelimitedSource?.html ?? '' + ) + ) + : piece.html; + block.undelimitedSource = { + html, + content: html, + ...whitespace, + bare: piece.bare, + savedHTML: getPlainSavedHTML( block ), + fingerprint: serializeBlockWithoutSource( block ), + }; + return block; + } ); +} + +/** + * Splits an inline style into declarations, keyed by property name. + * + * @param style Value of a `style` attribute. + */ +export function readStyle( style: string ): Map< string, string > { + const declarations = new Map< string, string >(); + for ( const declaration of style.split( ';' ) ) { + const colonAt = declaration.indexOf( ':' ); + if ( colonAt !== -1 ) { + declarations.set( + declaration.slice( 0, colonAt ).trim().toLowerCase(), + declaration.slice( colonAt + 1 ).trim() + ); + } + } + return declarations; +} + +/** + * Applies the change between two style values to a third, keeping the + * declarations the change didn't touch as written. + * + * @param style Style to change. + * @param before Style before the change. + * @param after Style after the change. + */ +function patchStyle( style: string, before: string, after: string ): string { + const beforeDeclarations = readStyle( before ); + const afterDeclarations = readStyle( after ); + const declarations = style.split( ';' ).filter( ( declaration ) => { + const name = declaration.split( ':' )[ 0 ].trim().toLowerCase(); + return ( + ! ( + beforeDeclarations.has( name ) && + ! afterDeclarations.has( name ) + ) && + ! ( + afterDeclarations.has( name ) && + afterDeclarations.get( name ) !== beforeDeclarations.get( name ) + ) + ); + } ); + for ( const [ name, value ] of afterDeclarations ) { + if ( value !== beforeDeclarations.get( name ) ) { + declarations.push( `${ name }:${ value }` ); + } + } + return declarations + .filter( ( declaration ) => declaration.trim() ) + .join( ';' ); +} + +/** + * Applies the change between a block's old and new `save` output to its + * original HTML, keeping everything the change didn't touch as written. + * + * @param source Original HTML. + * @param before `save` output when the block was read. + * @param after `save` output now. + * @param bare Whether the original is text without a wrapping element. + */ +function patch( + source: string, + before: string, + after: string, + bare: boolean +): string { + const beforeRoot = getRootElement( before ); + const afterRoot = getRootElement( after ); + const root = bare ? null : getRootElement( source ); + if ( ! beforeRoot || ! afterRoot || ( ! bare && ! root ) ) { + return after; + } + + // Text without a wrapping element stays that way if only the text changed. + if ( ! root ) { + return getHTML( [ beforeRoot.cloneNode() ] ) === + getHTML( [ afterRoot.cloneNode() ] ) + ? afterRoot.innerHTML + : after; + } + + for ( const name of new Set( [ + ...beforeRoot.getAttributeNames(), + ...afterRoot.getAttributeNames(), + ] ) ) { + const beforeValue = beforeRoot.getAttribute( name ); + const afterValue = afterRoot.getAttribute( name ); + if ( name === 'class' || beforeValue === afterValue ) { + continue; + } + if ( name === 'style' ) { + const patched = patchStyle( + root.getAttribute( 'style' ) ?? '', + beforeValue ?? '', + afterValue ?? '' + ); + if ( patched ) { + root.setAttribute( 'style', patched ); + } else { + root.removeAttribute( 'style' ); + } + } else if ( afterValue === null ) { + root.removeAttribute( name ); + } else { + root.setAttribute( name, afterValue ); + } + } + for ( const className of beforeRoot.classList ) { + if ( ! afterRoot.classList.contains( className ) ) { + root.classList.remove( className ); + } + } + for ( const className of afterRoot.classList ) { + if ( ! beforeRoot.classList.contains( className ) ) { + root.classList.add( className ); + } + } + if ( ! root.classList.length ) { + root.removeAttribute( 'class' ); + } + if ( beforeRoot.innerHTML !== afterRoot.innerHTML ) { + root.innerHTML = afterRoot.innerHTML; + } + if ( beforeRoot.tagName === afterRoot.tagName ) { + return root.outerHTML; + } + const renamed = document.createElement( afterRoot.localName ); + for ( const { name, value } of Array.from( root.attributes ) ) { + renamed.setAttribute( name, value ); + } + renamed.append( ...root.childNodes ); + return renamed.outerHTML; +} + +/** + * Remembers the HTML a delimited block was read from, so it can be saved + * that way unless it's edited. + * + * @param block Parsed block. + * @param html The block as written, with delimiters. + * @param content HTML to apply edits to; defaults to the + * block's `save` output. + * @param options Serialization options. + * @param options.isInnerBlocks Whether the block is an inner block. + */ +export function addSource( + block: Block, + html: string, + content: string | undefined, + options: { isInnerBlocks: boolean } +): Block { + let savedHTML = ''; + try { + savedHTML = getPlainSavedHTML( block ); + } catch {} + block.undelimitedSource = { + html, + content: content ?? savedHTML, + before: '', + after: '', + isFirst: false, + bare: false, + savedHTML, + fingerprint: serializeBlockWithoutSource( block, options ), + }; + return block; +} + +/** + * Returns a block and its inner blocks without the HTML they were read from. + * + * @param block Block. + */ +function withoutSources( block: Block ): Block { + return { + ...block, + undelimitedSource: undefined, + innerBlocks: block.innerBlocks.map( withoutSources ), + }; +} + +/** + * Returns the HTML to save for a block. New blocks, and blocks that had + * delimiters, get them; blocks written without get them only if reading them + * back without would give a different block. + * + * @param block Block. + * @param isInside Whether the block is inside another block's `save`, which + * is read back as a whole. + */ +function getBlockHTML( + block: Block, + isInside = false +): { html: string; delimited: boolean } { + const source = block.undelimitedSource; + const serialized = serializeBlockWithoutSource( block ); + if ( source && serialized === source.fingerprint ) { + return { html: source.html, delimited: source.html !== source.content }; + } + + // Invalid blocks keep the HTML they were read from, and without a way to + // read HTML back there's no telling whether a delimiter is needed. + if ( ! block.isValid || ! canReadHTML() ) { + return { html: serializeBlock( block ), delimited: true }; + } + + // New blocks get delimiters, classic blocks too. Blocks inside another + // block follow it. + if ( ! source && ! isInside ) { + return { + html: serializeBlock( block, { isInnerBlocks: true } ), + delimited: true, + }; + } + + const blockType = getBlockType( block.name ); + const hadDelimiters = !! source && source.html !== source.content; + // The HTML block's static HTML can hold inner blocks with or without + // delimiters. + const isHTMLBlock = block.name === 'core/html'; + const inner = block.innerBlocks.map( ( innerBlock ) => + getBlockHTML( innerBlock, ! isHTMLBlock ) + ); + const hasDelimitedInner = inner.some( ( { delimited } ) => delimited ); + if ( + ! blockType || + ( ! isHTMLBlock && + ( hasDelimitedInner || + ( hadDelimiters && block.innerBlocks.length ) ) ) + ) { + return { html: serializeBlock( block ), delimited: true }; + } + + let saved: string; + try { + saved = getSavedHTML( + block, + inner.map( ( innerBlock ) => innerBlock.html ) + ); + } catch { + return { html: serializeBlock( block ), delimited: true }; + } + // The HTML block's static HTML is already as written. + const html = + source && ! isHTMLBlock + ? patch( source.content, source.savedHTML, saved, source.bare ) + : saved; + + // The HTML block can hold delimited inner blocks without a delimiter. + if ( ! hadDelimiters && ( isHTMLBlock || ! hasDelimitedInner ) ) { + if ( isInside ) { + return { html, delimited: false }; + } + const [ readBack, ...rest ] = parse( html ); + if ( + ! rest.length && + readBack && + serializeBlockWithoutSource( withoutSources( readBack ) ) === + serializeBlockWithoutSource( withoutSources( block ) ) + ) { + return { html, delimited: false }; + } + } + + // Inner blocks without delimiters can't go inside one. + if ( ! isHTMLBlock && block.innerBlocks.length ) { + return { html: serializeBlock( block ), delimited: true }; + } + + // Keep the edited HTML, with a delimiter for what it can't hold. Text + // without its element can't go inside a delimiter. + return { + html: getCommentDelimitedContent( + block.name, + getCommentAttributes( blockType, block.attributes ), + source?.bare ? saved : html + ), + delimited: true, + }; +} + +/** + * Saves blocks, leaving out delimiters wherever they aren't needed. + * + * @param blocks Blocks. + */ +export function serializeUndelimited( blocks: Block[] ): string { + let content = ''; + let previous: Block | undefined; + let previousIsBare = false; + blocks.forEach( ( block ) => { + const source = block.undelimitedSource; + const { html, delimited } = getBlockHTML( block ); + const isBare = + ! delimited && !! source?.bare && ! html.startsWith( '<' ); + // Keep the whitespace that was written between blocks; new blocks + // get a blank line. + let before = + ( previous?.undelimitedSource?.after ?? '' ) + + ( previous || source?.isFirst ? ( source?.before ?? '' ) : '' ); + if ( + previous && + ( ! source || ! previous.undelimitedSource ) && + ! before.includes( '\n' ) + ) { + before = '\n\n'; + } + // Two paragraphs of text need a blank line to stay apart. + if ( isBare && previousIsBare && ! BLANK_LINE.test( before ) ) { + before = '\n\n'; + } + content += before + html; + previous = block; + previousIsBare = isBare; + } ); + return content + ( previous?.undelimitedSource?.after ?? '' ); +} diff --git a/packages/blocks/src/types.ts b/packages/blocks/src/types.ts index 4205f0645d28d6..8159dde2ee3306 100644 --- a/packages/blocks/src/types.ts +++ b/packages/blocks/src/types.ts @@ -797,6 +797,52 @@ export interface Block< * Un-processed original copy of block if created through parser. */ __unstableBlockSource?: RawBlock; + /** + * Where a block read from HTML without delimiters came from, so saving it + * can keep that HTML as written. Experimental. + */ + undelimitedSource?: UndelimitedSource; +} + +/** + * The original HTML of a block read without delimiters. + */ +export interface UndelimitedSource { + /** + * The block, exactly as written, with its delimiters if it had them. + */ + html: string; + /** + * The block's HTML, without delimiters. + */ + content: string; + /** + * The whitespace written before the block. + */ + before: string; + /** + * The whitespace written after the block, if it was the last one. + */ + after: string; + /** + * Whether the block was the first one, so the whitespace before it starts + * the content. + */ + isFirst: boolean; + /** + * Whether the block was text without a wrapping element, such as a + * paragraph in a classic post. + */ + bare: boolean; + /** + * The block's `save` output when it was read, to tell what an edit changed. + */ + savedHTML: string; + /** + * The block's delimited serialization when it was read, to tell whether it + * changed at all. + */ + fingerprint: string; } /** diff --git a/test/e2e/specs/editor/blocks/classic.spec.js b/test/e2e/specs/editor/blocks/classic.spec.js index 7a16663deb02a2..f7071ba4082a25 100644 --- a/test/e2e/specs/editor/blocks/classic.spec.js +++ b/test/e2e/specs/editor/blocks/classic.spec.js @@ -31,7 +31,11 @@ test.describe( 'Classic', () => { await page.keyboard.type( 'test' ); await page.getByRole( 'button', { name: 'Save' } ).click(); - await expect.poll( editor.getEditedPostContent ).toBe( 'test' ); + // A new Classic block keeps its delimiter, or it would be read back as + // a paragraph. + await expect + .poll( editor.getEditedPostContent ) + .toBe( '\n

test

\n' ); } ); test( 'should insert media, convert to blocks, and undo in one step', async ( { @@ -138,7 +142,11 @@ test.describe( 'Classic', () => { await classicBlock.click(); expect( errors ).toHaveLength( 0 ); - await expect.poll( editor.getEditedPostContent ).toBe( 'test' ); + // A new Classic block keeps its delimiter, or it would be read back as + // a paragraph. + await expect + .poll( editor.getEditedPostContent ) + .toBe( '\n

test

\n' ); } ); } ); diff --git a/test/e2e/specs/editor/plugins/block-hooks.spec.js b/test/e2e/specs/editor/plugins/block-hooks.spec.js index 5269fda3f45745..b410b68c2f7105 100644 --- a/test/e2e/specs/editor/plugins/block-hooks.spec.js +++ b/test/e2e/specs/editor/plugins/block-hooks.spec.js @@ -244,6 +244,23 @@ test.describe( 'Block Hooks API', () => { editor, page, } ) => { + // Classic content is read as blocks. + const expectedClassicBlocks = [ + { + name: 'core/heading', + attributes: { + className: 'dummy-classic-heading', + content: 'This is a dummy heading', + }, + }, + { + name: 'core/paragraph', + attributes: { + className: 'dummy-classic-paragraph', + content: 'This is a dummy paragraph.', + }, + }, + ]; const expectedHookedBlockLastChild = { name: 'core/paragraph', attributes: { @@ -258,7 +275,7 @@ test.describe( 'Block Hooks API', () => { await expect .poll( editor.getBlocks ) .toMatchObject( [ - { name: 'core/freeform' }, + ...expectedClassicBlocks, expectedHookedBlockLastChild, ] ); @@ -266,6 +283,8 @@ test.describe( 'Block Hooks API', () => { getHookedBlockContent( 'last_child', blockType ) ); await editor.selectBlocks( hookedBlock ); + // Move it above both classic blocks. + await editor.clickBlockToolbarButton( 'Move up' ); await editor.clickBlockToolbarButton( 'Move up' ); // Save updated post. @@ -284,7 +303,7 @@ test.describe( 'Block Hooks API', () => { .poll( editor.getBlocks ) .toMatchObject( [ expectedHookedBlockLastChild, - { name: 'core/freeform' }, + ...expectedClassicBlocks, ] ); // Verify that the frontend reflects the changes made in the editor. diff --git a/test/integration/fixtures/blocks/core__4-invalid-starting-letter.json b/test/integration/fixtures/blocks/core__4-invalid-starting-letter.json index c5980f635023ec..b411a8f5b3c33b 100644 --- a/test/integration/fixtures/blocks/core__4-invalid-starting-letter.json +++ b/test/integration/fixtures/blocks/core__4-invalid-starting-letter.json @@ -1,10 +1,9 @@ [ { - "name": "core/freeform", + "name": "core/html", "isValid": true, - "attributes": { - "content": "

" - }, - "innerBlocks": [] + "attributes": {}, + "innerBlocks": [], + "innerContent": [ "" ] } ] diff --git a/test/integration/fixtures/blocks/core__4-invalid-starting-letter.serialized.html b/test/integration/fixtures/blocks/core__4-invalid-starting-letter.serialized.html index fe35001a46b8eb..6236b2f47bba5c 100644 --- a/test/integration/fixtures/blocks/core__4-invalid-starting-letter.serialized.html +++ b/test/integration/fixtures/blocks/core__4-invalid-starting-letter.serialized.html @@ -1 +1,3 @@ -

+ + + diff --git a/test/integration/fixtures/blocks/core__freeform.serialized.html b/test/integration/fixtures/blocks/core__freeform.serialized.html index 632a89b49e626d..36744b6c7fb648 100644 --- a/test/integration/fixtures/blocks/core__freeform.serialized.html +++ b/test/integration/fixtures/blocks/core__freeform.serialized.html @@ -1,4 +1,6 @@ +

Testing freeform block with some

HTML content
+ diff --git a/test/integration/fixtures/blocks/core__freeform__undelimited.json b/test/integration/fixtures/blocks/core__freeform__undelimited.json deleted file mode 100644 index 856833136b663d..00000000000000 --- a/test/integration/fixtures/blocks/core__freeform__undelimited.json +++ /dev/null @@ -1,10 +0,0 @@ -[ - { - "name": "core/freeform", - "isValid": true, - "attributes": { - "content": "

Testing freeform block with some

\n
\n\tHTML content\n
" - }, - "innerBlocks": [] - } -] diff --git a/test/integration/fixtures/blocks/core__heading__deprecated-1.json b/test/integration/fixtures/blocks/core__heading__deprecated-1.json index ea57307f023f6e..ef0ee6b7722384 100644 --- a/test/integration/fixtures/blocks/core__heading__deprecated-1.json +++ b/test/integration/fixtures/blocks/core__heading__deprecated-1.json @@ -9,6 +9,9 @@ "typography": { "textAlign": "right" } + }, + "htmlAttributes": { + "style": "text-align:right" } }, "innerBlocks": [] diff --git a/test/integration/fixtures/blocks/core__heading__deprecated-1.serialized.html b/test/integration/fixtures/blocks/core__heading__deprecated-1.serialized.html index 0a51a3491cf734..5bf9cf86599d9f 100644 --- a/test/integration/fixtures/blocks/core__heading__deprecated-1.serialized.html +++ b/test/integration/fixtures/blocks/core__heading__deprecated-1.serialized.html @@ -1,3 +1,3 @@ -

A picture is worth a thousand words, or so the saying goes

+

A picture is worth a thousand words, or so the saying goes

diff --git a/test/integration/fixtures/blocks/core__heading__deprecated-3.json b/test/integration/fixtures/blocks/core__heading__deprecated-3.json index 8a271e870c758b..007fe2f2ad144c 100644 --- a/test/integration/fixtures/blocks/core__heading__deprecated-3.json +++ b/test/integration/fixtures/blocks/core__heading__deprecated-3.json @@ -5,10 +5,8 @@ "attributes": { "content": "Text", "level": 2, - "style": { - "color": { - "text": "#268ebb" - } + "htmlAttributes": { + "style": "color:#268ebb" } }, "innerBlocks": [] diff --git a/test/integration/fixtures/blocks/core__heading__deprecated-3.serialized.html b/test/integration/fixtures/blocks/core__heading__deprecated-3.serialized.html index 2e04a7e01f9778..15295fa062e61e 100644 --- a/test/integration/fixtures/blocks/core__heading__deprecated-3.serialized.html +++ b/test/integration/fixtures/blocks/core__heading__deprecated-3.serialized.html @@ -1,3 +1,3 @@ - -

Text

+ +

Text

diff --git a/test/integration/fixtures/blocks/core__image__deprecated-v1-add-responsive-class.json b/test/integration/fixtures/blocks/core__image__deprecated-v1-add-responsive-class.json index 6b2f1a80f52c6d..6bf7e4e2fb76a2 100644 --- a/test/integration/fixtures/blocks/core__image__deprecated-v1-add-responsive-class.json +++ b/test/integration/fixtures/blocks/core__image__deprecated-v1-add-responsive-class.json @@ -5,8 +5,12 @@ "attributes": { "url": "data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAYAAAAfFcSJAAAACklEQVR4nGMAAQAABQABDQottAAAAABJRU5ErkJggg==", "alt": "", - "caption": [], - "align": "left" + "caption": "", + "isDecorative": false, + "align": "left", + "htmlAttributes": { + "style": "max-width:50%" + } }, "innerBlocks": [] } diff --git a/test/integration/fixtures/blocks/core__image__deprecated-v1-add-responsive-class.serialized.html b/test/integration/fixtures/blocks/core__image__deprecated-v1-add-responsive-class.serialized.html index 30a0827e7eea8b..56a7cd4aad86a2 100644 --- a/test/integration/fixtures/blocks/core__image__deprecated-v1-add-responsive-class.serialized.html +++ b/test/integration/fixtures/blocks/core__image__deprecated-v1-add-responsive-class.serialized.html @@ -1,3 +1,3 @@ -
+
diff --git a/test/integration/fixtures/blocks/core__invalid-Capitals.json b/test/integration/fixtures/blocks/core__invalid-Capitals.json index bf49ed73beb824..6899b2402d87db 100644 --- a/test/integration/fixtures/blocks/core__invalid-Capitals.json +++ b/test/integration/fixtures/blocks/core__invalid-Capitals.json @@ -1,10 +1,9 @@ [ { - "name": "core/freeform", + "name": "core/html", "isValid": true, - "attributes": { - "content": "

" - }, - "innerBlocks": [] + "attributes": {}, + "innerBlocks": [], + "innerContent": [ "" ] } ] diff --git a/test/integration/fixtures/blocks/core__invalid-Capitals.serialized.html b/test/integration/fixtures/blocks/core__invalid-Capitals.serialized.html index 4b0ff53da71189..d5772158b4a90f 100644 --- a/test/integration/fixtures/blocks/core__invalid-Capitals.serialized.html +++ b/test/integration/fixtures/blocks/core__invalid-Capitals.serialized.html @@ -1 +1,3 @@ -

+ + + diff --git a/test/integration/fixtures/blocks/core__invalid-special.json b/test/integration/fixtures/blocks/core__invalid-special.json index 56edfa05ea3d3c..3da5b8c6771fed 100644 --- a/test/integration/fixtures/blocks/core__invalid-special.json +++ b/test/integration/fixtures/blocks/core__invalid-special.json @@ -1,10 +1,9 @@ [ { - "name": "core/freeform", + "name": "core/html", "isValid": true, - "attributes": { - "content": "

" - }, - "innerBlocks": [] + "attributes": {}, + "innerBlocks": [], + "innerContent": [ "" ] } ] diff --git a/test/integration/fixtures/blocks/core__invalid-special.serialized.html b/test/integration/fixtures/blocks/core__invalid-special.serialized.html index de4f2acc41f8d0..32bcf39e6d97c3 100644 --- a/test/integration/fixtures/blocks/core__invalid-special.serialized.html +++ b/test/integration/fixtures/blocks/core__invalid-special.serialized.html @@ -1 +1,3 @@ -

+ + + diff --git a/test/integration/fixtures/blocks/core__paragraph__deprecated-4.json b/test/integration/fixtures/blocks/core__paragraph__deprecated-4.json index dd069f9ebd0e79..77551e359f7ab6 100644 --- a/test/integration/fixtures/blocks/core__paragraph__deprecated-4.json +++ b/test/integration/fixtures/blocks/core__paragraph__deprecated-4.json @@ -5,10 +5,9 @@ "attributes": { "content": "... like this one, which is separate from the above and right aligned.", "dropCap": false, - "style": { - "typography": { - "textAlign": "right" - } + "align": "right", + "htmlAttributes": { + "style": "text-align:right" } }, "innerBlocks": [] diff --git a/test/integration/fixtures/blocks/core__paragraph__deprecated-4.serialized.html b/test/integration/fixtures/blocks/core__paragraph__deprecated-4.serialized.html index 41949cf25c784c..3e18265b5c44b1 100644 --- a/test/integration/fixtures/blocks/core__paragraph__deprecated-4.serialized.html +++ b/test/integration/fixtures/blocks/core__paragraph__deprecated-4.serialized.html @@ -1,3 +1,3 @@ - -

... like this one, which is separate from the above and right aligned.

+ +

... like this one, which is separate from the above and right aligned.

diff --git a/test/integration/fixtures/blocks/core__freeform__undelimited.html b/test/integration/fixtures/blocks/core__paragraph__undelimited.html similarity index 100% rename from test/integration/fixtures/blocks/core__freeform__undelimited.html rename to test/integration/fixtures/blocks/core__paragraph__undelimited.html diff --git a/test/integration/fixtures/blocks/core__paragraph__undelimited.json b/test/integration/fixtures/blocks/core__paragraph__undelimited.json new file mode 100644 index 00000000000000..b541cbdecf9e20 --- /dev/null +++ b/test/integration/fixtures/blocks/core__paragraph__undelimited.json @@ -0,0 +1,20 @@ +[ + { + "name": "core/paragraph", + "isValid": true, + "attributes": { + "content": "Testing freeform block with some", + "dropCap": false + }, + "innerBlocks": [] + }, + { + "name": "core/html", + "isValid": true, + "attributes": {}, + "innerBlocks": [], + "innerContent": [ + "
\n\tHTML content\n
" + ] + } +] diff --git a/test/integration/fixtures/blocks/core__freeform__undelimited.parsed.json b/test/integration/fixtures/blocks/core__paragraph__undelimited.parsed.json similarity index 100% rename from test/integration/fixtures/blocks/core__freeform__undelimited.parsed.json rename to test/integration/fixtures/blocks/core__paragraph__undelimited.parsed.json diff --git a/test/integration/fixtures/blocks/core__freeform__undelimited.serialized.html b/test/integration/fixtures/blocks/core__paragraph__undelimited.serialized.html similarity index 60% rename from test/integration/fixtures/blocks/core__freeform__undelimited.serialized.html rename to test/integration/fixtures/blocks/core__paragraph__undelimited.serialized.html index 632a89b49e626d..0bff9191fc26be 100644 --- a/test/integration/fixtures/blocks/core__freeform__undelimited.serialized.html +++ b/test/integration/fixtures/blocks/core__paragraph__undelimited.serialized.html @@ -1,4 +1,9 @@ +

Testing freeform block with some

+ + +
HTML content
+ diff --git a/test/integration/fixtures/blocks/core__verse__deprecated-v1.json b/test/integration/fixtures/blocks/core__verse__deprecated-v1.json index 0a9e3586ccf3c0..5ac97f5db5442e 100644 --- a/test/integration/fixtures/blocks/core__verse__deprecated-v1.json +++ b/test/integration/fixtures/blocks/core__verse__deprecated-v1.json @@ -4,10 +4,8 @@ "isValid": true, "attributes": { "content": "A verse…
And more!", - "style": { - "typography": { - "textAlign": "left" - } + "htmlAttributes": { + "style": "text-align:left" } }, "innerBlocks": [] diff --git a/test/integration/fixtures/blocks/core__verse__deprecated-v1.serialized.html b/test/integration/fixtures/blocks/core__verse__deprecated-v1.serialized.html index 3f6006c0214db2..baf32592cc419a 100644 --- a/test/integration/fixtures/blocks/core__verse__deprecated-v1.serialized.html +++ b/test/integration/fixtures/blocks/core__verse__deprecated-v1.serialized.html @@ -1,3 +1,3 @@ - -
A verse…
And more!
+ +
A verse…
And more!
diff --git a/test/integration/full-content/full-content.jsdom.test.js b/test/integration/full-content/full-content.jsdom.test.js index 339d37bee3a3d2..24d4a4937c9248 100644 --- a/test/integration/full-content/full-content.jsdom.test.js +++ b/test/integration/full-content/full-content.jsdom.test.js @@ -43,6 +43,19 @@ const normalizeParsedBlocks = ( blocks ) => ...( block.innerContent ? { innerContent: block.innerContent } : {} ), } ) ); +/** + * Returns blocks without the HTML they were read from, so they're saved from + * their attributes, as new blocks. + * + * @param {WPBlock[]} blocks Blocks. + */ +const withoutSources = ( blocks ) => + blocks.map( ( block ) => ( { + ...block, + undelimitedSource: undefined, + innerBlocks: withoutSources( block.innerBlocks ), + } ) ); + describe( 'full post content fixture', () => { beforeAll( () => { const blockMetadataFiles = glob.sync( @@ -185,8 +198,10 @@ describe( 'full post content fixture', () => { } // `serialize` doesn't have a trailing newline, but the fixture - // files should. - const serializedActual = serialize( blocksActual ) + '\n'; + // files should. Untouched blocks are saved as they were written, + // so this checks what the blocks themselves save. + const serializedActual = + serialize( withoutSources( blocksActual ) ) + '\n'; const { filename: serializedHTMLFileName, file: serializedHTMLFixtureContent, diff --git a/test/integration/optional-block-delimiters.jsdom.test.js b/test/integration/optional-block-delimiters.jsdom.test.js new file mode 100644 index 00000000000000..d565514e720b5a --- /dev/null +++ b/test/integration/optional-block-delimiters.jsdom.test.js @@ -0,0 +1,308 @@ +import fs from 'node:fs'; +import path from 'node:path'; +import { fileURLToPath } from 'node:url'; +import { afterAll, beforeAll, describe, expect, it, vi } from 'vitest'; +import { + createBlock, + getBlockTypes, + parse, + serialize, + setFreeformContentHandlerName, + unregisterBlockType, +} from '@wordpress/blocks'; +import { registerCoreBlocks } from '@wordpress/block-library'; + +vi.hoisted( () => globalThis.wpVitest.mockMatchMedia() ); + +const fixturesDirectory = path.join( + path.dirname( fileURLToPath( import.meta.url ) ), + 'fixtures/blocks' +); + +const classicPost = `Hello world, this is a classic post. +It has a line break. + +

A heading

+A second paragraph & more. + + + + +

Styled

+ +

Kept as is

+`; + +function update( block, attributes ) { + return { ...block, attributes: { ...block.attributes, ...attributes } }; +} + +describe( 'optional block delimiters', () => { + beforeAll( () => { + registerCoreBlocks(); + } ); + + afterAll( () => { + getBlockTypes().forEach( ( { name } ) => unregisterBlockType( name ) ); + } ); + + it( 'reads HTML without delimiters as blocks', () => { + expect( parse( classicPost ).map( ( block ) => block.name ) ).toEqual( [ + 'core/paragraph', + 'core/heading', + 'core/paragraph', + 'core/html', + 'core/list', + 'core/paragraph', + 'core/html', + 'core/html', + ] ); + } ); + + it( 'saves untouched blocks exactly as written', () => { + expect( serialize( parse( classicPost ) ) ).toBe( classicPost ); + } ); + + it( 'saves untouched HTML as the browser writes it, adding nothing', () => { + expect( + serialize( + parse( '

Hi
there

\n\n

A

' ) + ) + ).toBe( '

Hi
there

\n\n

A

' ); + } ); + + it( 'keeps HTML with delimiters as it is', () => { + const content = `\n

a

\n\n\n

b

`; + expect( serialize( parse( content ) ) ).toBe( content ); + } ); + + it( 'saves every untouched block fixture in the current format exactly as written', () => { + const fixtures = fs + .readdirSync( fixturesDirectory ) + .filter( + ( file ) => + file.endsWith( '.html' ) && + ! file.endsWith( '.serialized.html' ) + ); + const changed = fixtures.filter( ( file ) => { + const content = fs.readFileSync( + path.join( fixturesDirectory, file ), + 'utf8' + ); + const blocks = parse( content, { + __unstableSkipMigrationLogs: true, + } ); + // Blocks read from an old format are saved in the new one. + return ( + blocks.every( + ( { undelimitedSource } ) => undelimitedSource + ) && serialize( blocks ) !== content + ); + } ); + expect( changed ).toEqual( [] ); + // Old fixtures use the deprecated children source. + expect( console ).toHaveWarnedWith( + expect.stringContaining( + 'wp.blocks.children.matcher is deprecated' + ) + ); + } ); + + it( 'saves a block read from an old format in the new format', () => { + expect( + serialize( + parse( '' ) + ) + ).toBe( '' ); + } ); + + it( 'keeps the delimiter and unknown attributes of an edited block', () => { + const content = `\n

Old

\n`; + const [ block ] = parse( content ); + expect( serialize( [ update( block, { content: 'New' } ) ] ) ).toBe( + content.replace( 'data-x>Old', 'data-x="">New' ) + ); + } ); + + it( 'changes only the edited text of a paragraph', () => { + const blocks = parse( classicPost ); + blocks[ 0 ] = update( blocks[ 0 ], { + content: 'Hi all', + } ); + blocks[ 5 ] = update( blocks[ 5 ], { content: 'Restyled' } ); + expect( serialize( blocks ) ).toBe( + classicPost + .replace( + 'Hello world, this is a classic post.\nIt has a line break.', + 'Hi all' + ) + .replace( '>Styled<', '>Restyled<' ) + ); + } ); + + it( 'saves an edited list item without delimiters', () => { + const [ list ] = parse( '' ); + list.innerBlocks[ 0 ] = update( list.innerBlocks[ 0 ], { + content: 'Uno', + } ); + const content = serialize( [ list ] ); + expect( content ).toBe( '' ); + expect( serialize( parse( content ) ) ).toBe( content ); + } ); + + it( 'keeps unknown attributes when a setting changes', () => { + const blocks = parse( classicPost ); + blocks[ 1 ] = update( blocks[ 1 ], { level: 3 } ); + blocks[ 5 ] = update( blocks[ 5 ], { anchor: 'styled' } ); + expect( serialize( blocks ) ).toBe( + classicPost + .replace( + '

A heading

', + '

A heading

' + ) + .replace( 'data-x="1">Styled', 'data-x="1" id="styled">Styled' ) + ); + } ); + + it( 'keeps unknown attributes inside a delimiter when one is needed', () => { + const blocks = parse( classicPost ); + blocks[ 5 ] = update( blocks[ 5 ], { + style: { typography: { textAlign: 'center' } }, + } ); + const content = serialize( blocks ); + expect( content ).toBe( + classicPost.replace( + '

Styled

', + '\n

Styled

\n' + ) + ); + expect( serialize( parse( content ) ) ).toBe( content ); + } ); + + it( 'reads attributes a block does not know into htmlAttributes', () => { + const content = ``; + const [ block ] = parse( content ); + expect( block.attributes.htmlAttributes ).toEqual( { + style: 'background:#fffbe6;padding:12px', + 'data-note': 'tip', + hidden: '', + } ); + expect( serialize( [ update( block, { content: 'Tip!' } ) ] ) ).toBe( + content.replace( 'hidden>Tip<', 'hidden="">Tip!<' ) + ); + } ); + + it( 'keeps a delimited block with unknown attributes valid', () => { + const content = `\n

Tip

\n`; + const [ block ] = parse( content ); + expect( block.isValid ).toBe( true ); + expect( block.attributes.htmlAttributes ).toEqual( { + 'data-note': 'tip', + } ); + } ); + + it( 'saves htmlAttributes of a new block, under its own styles', () => { + const content = serialize( [ + createBlock( 'core/paragraph', { + content: 'New', + htmlAttributes: { + style: 'color:red;border-left:4px solid', + 'data-note': 'tip', + }, + style: { color: { text: '#000000' } }, + } ), + ] ); + expect( content ).toBe( + `\n

New

\n` + ); + expect( serialize( parse( content ) ) ).toBe( content ); + } ); + + it( 'gives a new HTML block a delimiter when it handles classic content', () => { + setFreeformContentHandlerName( 'core/html' ); + const content = serialize( [ + createBlock( 'core/html', {}, [], [ 'hello' ] ), + ] ); + setFreeformContentHandlerName( 'core/freeform' ); + expect( content ).toBe( '\nhello\n' ); + } ); + + it( 'drops the whitespace before a removed first block', () => { + const [ , ...blocks ] = parse( '\n

a

\n\n

b

\n' ); + expect( serialize( blocks ) ).toBe( '

b

\n' ); + } ); + + it( 'gives new blocks delimiters', () => { + const [ old ] = parse( '

Old

' ); + const content = serialize( [ + old, + createBlock( 'core/paragraph', { content: 'New' } ), + ] ); + expect( content ).toBe( + `

Old

\n\n\n

New

\n` + ); + expect( serialize( parse( content ) ) ).toBe( content ); + } ); + + describe( 'blocks inside HTML no block reads', () => { + const cards = `
+
+ Wildlife +

Heron island

+

Six nests this year.

+
+

Rope grooves.

+
`; + + it( 'reads them as inner blocks of an HTML block', () => { + const [ block ] = parse( cards ); + expect( block.name ).toBe( 'core/html' ); + expect( + block.innerBlocks.map( ( { name, attributes } ) => [ + name, + attributes.content.toString(), + ] ) + ).toEqual( [ + [ 'core/heading', 'Heron island' ], + [ 'core/paragraph', 'Six nests this year.' ], + [ 'core/paragraph', 'Rope grooves.' ], + ] ); + expect( serialize( [ block ] ) ).toBe( cards ); + } ); + + it( 'saves an edited inner block without a delimiter', () => { + const [ block ] = parse( cards ); + block.innerBlocks[ 2 ] = update( block.innerBlocks[ 2 ], { + content: 'Deep rope grooves.', + } ); + const content = serialize( [ block ] ); + expect( content ).toBe( + cards.replace( 'Rope grooves.', 'Deep rope grooves.' ) + ); + expect( serialize( parse( content ) ) ).toBe( content ); + } ); + + it( 'adds a delimiter only to the inner block that needs one', () => { + const [ block ] = parse( cards ); + block.innerBlocks[ 1 ] = update( block.innerBlocks[ 1 ], { + dropCap: true, + } ); + const content = serialize( [ block ] ); + expect( content ).toBe( + cards.replace( + '

Six nests this year.

', + '\n

Six nests this year.

\n' + ) + ); + const [ readBack ] = parse( content ); + expect( readBack.innerBlocks.map( ( { name } ) => name ) ).toEqual( + [ 'core/heading', 'core/paragraph', 'core/paragraph' ] + ); + expect( readBack.innerBlocks[ 1 ].attributes.dropCap ).toBe( true ); + expect( serialize( [ readBack ] ) ).toBe( content ); + } ); + } ); +} );