Skip to content

Commit

Permalink
Navigation: URL, mailto, tel, and internal urls should be persisted a…
Browse files Browse the repository at this point in the history
…s a custom type in block attributes
  • Loading branch information
gwwar committed May 1, 2021
1 parent c367c4e commit f77b6d7
Show file tree
Hide file tree
Showing 3 changed files with 346 additions and 44 deletions.
92 changes: 49 additions & 43 deletions packages/block-library/src/navigation-link/edit.js
Original file line number Diff line number Diff line change
Expand Up @@ -133,6 +133,50 @@ function getSuggestionsQuery( type, kind ) {
}
}

export const updateNavigationLinkBlockAttributes = (
updatedValue = {},
{ setAttributes, label = '' }
) => {
const {
title = '',
url = '',
opensInNewTab,
id,
kind = '',
type = '',
} = updatedValue;

const normalizedTitle = title.replace( /http(s?):\/\//gi, '' );
const normalizedURL = url.replace( /http(s?):\/\//gi, '' );
const escapeTitle =
title !== '' && normalizedTitle !== normalizedURL && label !== title;
const newLabel = escapeTitle
? escape( title )
: label || escape( normalizedURL );

const isBuiltInType =
[ 'post', 'page', 'tag', 'category', 'post_type' ].indexOf( type ) > -1;

if ( ! kind && ! isBuiltInType ) {
return setAttributes( {
url: encodeURI( url ),
label: newLabel,
opensInNewTab,
...( Number.isInteger( id ) && { id } ),
kind: 'custom',
} );
}

return setAttributes( {
url: encodeURI( url ),
label: newLabel,
opensInNewTab,
...( Number.isInteger( id ) && { id } ),
...( kind && { kind } ),
...( type && { type } ),
} );
};

export default function NavigationLinkEdit( {
attributes,
isSelected,
Expand Down Expand Up @@ -519,49 +563,11 @@ export default function NavigationLinkEdit( {
type,
kind
) }
onChange={ ( {
title: newTitle = '',
url: newURL = '',
opensInNewTab: newOpensInNewTab,
id,
kind: newKind = '',
type: newType = '',
} = {} ) =>
setAttributes( {
url: encodeURI( newURL ),
label: ( () => {
const normalizedTitle = newTitle.replace(
/http(s?):\/\//gi,
''
);
const normalizedURL = newURL.replace(
/http(s?):\/\//gi,
''
);
if (
newTitle !== '' &&
normalizedTitle !==
normalizedURL &&
label !== newTitle
) {
return escape( newTitle );
} else if ( label ) {
return label;
}
// If there's no label, add the URL.
return escape( normalizedURL );
} )(),
opensInNewTab: newOpensInNewTab,
id,
...( newKind && {
kind: newKind,
} ),
...( newType &&
newType !== 'URL' &&
newType !== 'post-format' && {
type: newType,
} ),
} )
onChange={ ( updatedValue ) =>
updateNavigationLinkBlockAttributes(
updatedValue,
{ setAttributes, label }
)
}
/>
</Popover>
Expand Down
Loading

0 comments on commit f77b6d7

Please sign in to comment.