Skip to content

Commit

Permalink
Remap named guten formats to standard tags
Browse files Browse the repository at this point in the history
  • Loading branch information
mirka committed Feb 16, 2022
1 parent 93713b3 commit 9d35ae6
Show file tree
Hide file tree
Showing 3 changed files with 21 additions and 3 deletions.
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
import * as Y from 'yjs';

import { create, toHTMLString } from '@wordpress/rich-text';
import '@wordpress/format-library';

import { applyHTMLDelta, gutenFormatsToYFormats, stringAsMultiline } from '../rich-text';

Expand All @@ -13,7 +14,6 @@ const yxmlTextFrom = ( html, richTextOpts = {} ) => {
describe( 'gutenFormatsToYFormats', () => {
it( 'should convert to a range-based Yjs format', () => {
const { formats } = create( { html: '<a href="some-url">abc</a>' } );
const expectedFormatObj = formats[ 0 ][ 0 ];
const result = gutenFormatsToYFormats( formats );
expect( result ).toEqual( [ { format: { a: { href: 'some-url' } }, index: 0, length: 3 } ] );
} );
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,7 @@ import { isEqual } from 'lodash';
/**
* WordPress dependencies
*/
import { select } from '@wordpress/data';
import { create, __UNSTABLE_LINE_SEPARATOR } from '@wordpress/rich-text';

/**
Expand Down Expand Up @@ -39,7 +40,7 @@ export function gutenFormatsToYFormats( formats ) {
}

yFormats.push( {
format: { [ f.type ]: f.attributes || true },
format: namedGutenFormatToStandardTags( f ),
index: charIdx,
length: fLength,
} );
Expand All @@ -49,6 +50,22 @@ export function gutenFormatsToYFormats( formats ) {
return yFormats;
}

/**
* Converts registered formats back to their standard tag/attribute names.
*
* For example, `core/bold` will be converted back to `strong`.
*/
export function namedGutenFormatToStandardTags( format ) {
const { tagName, attributes = {} } = select( 'core/rich-text' ).getFormatType( format.type );
if ( ! format.attributes ) return { [ tagName ]: true };

const remappedEntries = Object.entries( format.attributes ).map( ( [ key, value ] ) => [
attributes[ key ],
value,
] );
return { [ tagName ]: Object.fromEntries( remappedEntries ) };
}

/**
* Apply the delta between two HTML strings to a Y.XmlText.
*
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -86,7 +86,8 @@ export function updateRichText( { oldText = '', newBlock, attributeKey, richText
}
const blockWithRichTexts = richTexts.get( newBlock.clientId );
if ( ! blockWithRichTexts.has( attributeKey ) ) {
blockWithRichTexts.set( attributeKey, new yjs.XmlText( oldText ) );
blockWithRichTexts.set( attributeKey, new yjs.XmlText() );
applyHTMLDelta( '', oldText, blockWithRichTexts.get( attributeKey ) );
}

const yxmlText = blockWithRichTexts.get( attributeKey );
Expand Down

0 comments on commit 9d35ae6

Please sign in to comment.