Skip to content

Commit

Permalink
Avoid loss of hyphens and colons in attribute names (#5)
Browse files Browse the repository at this point in the history
  • Loading branch information
stokesman authored Jan 23, 2022
1 parent a768149 commit 41ff413
Showing 1 changed file with 13 additions and 7 deletions.
20 changes: 13 additions & 7 deletions src/save.js
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@
* External dependencies
*/
import classnames from 'classnames';
import parse from 'html-react-parser';
import parse, { domToReact } from 'html-react-parser';
import { isEmpty } from 'lodash';

/**
Expand Down Expand Up @@ -53,19 +53,25 @@ export default function Save( props ) {
if ( icon && isEmpty( namedIcon ) ) {
const newIcon = icon.trim();

customIcon = parse( newIcon, {
const parseOptions = {
trim: true,
replace: ( domNode ) => {
replace: ( { attribs, children, name, parent, type } ) => {
// TODO: Very basic SVG sanitization, needs more refinement.
if (
domNode.type !== 'tag' ||
( ! domNode.parent && domNode.name !== 'svg' ) ||
! domNode.name
type !== 'tag' ||
( ! parent && name !== 'svg' ) ||
! name
) {
return <></>;
}
// Hyphens or colons in attribute names are lost in the default process of
// html-react-parser. Spreading the attribs object as props avoids the loss.
const Tag = `${ name }`;
return <Tag { ...attribs }>{ domToReact( children, parseOptions ) }</Tag>;
},
} );
}

customIcon = parse( newIcon, parseOptions );

if ( isEmpty( customIcon?.props ) ) {
customIcon = '';
Expand Down

0 comments on commit 41ff413

Please sign in to comment.