Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Remove base url from link control search results #54553

Merged
merged 14 commits into from
Sep 21, 2023
Merged
Original file line number Diff line number Diff line change
Expand Up @@ -13,7 +13,8 @@ import {
file,
} from '@wordpress/icons';
import { __unstableStripHTML as stripHTML } from '@wordpress/dom';
import { safeDecodeURI, filterURLForDisplay } from '@wordpress/url';
import { safeDecodeURI, filterURLForDisplay, getPath } from '@wordpress/url';
import { compose } from '@wordpress/compose';

const ICONS_MAP = {
post: postList,
Expand Down Expand Up @@ -44,6 +45,38 @@ function SearchItemIcon( { isURL, suggestion } ) {
return null;
}

/**
* Adds a leading slash to a url if it doesn't already have one.
* @param {string} url the url to add a leading slash to.
* @return {string} the url with a leading slash.
*/
function addLeadingSlash( url ) {
return url?.replace( /^\/?/, '/' );
}

const partialRight =
( fn, ...partialArgs ) =>
( ...args ) =>
fn( ...args, ...partialArgs );

/**
* Prepares a URL for display in the UI.
* - decodes the URL.
* - filters it (removes protocol, www, etc.).
* - truncates it if necessary.
* - adds a leading slash.
* @param {string} url the url.
* @return {string} the processed url to display.
*/
function getURLForDisplay( url = '' ) {
return compose(
addLeadingSlash,
partialRight( filterURLForDisplay, 24 ),
getPath,
safeDecodeURI
)( url );
}

export const LinkControlSearchItem = ( {
itemProps,
suggestion,
Expand All @@ -54,7 +87,7 @@ export const LinkControlSearchItem = ( {
} ) => {
const info = isURL
? __( 'Press ENTER to add this link' )
: filterURLForDisplay( safeDecodeURI( suggestion?.url ), 24 );
: getURLForDisplay( suggestion?.url );

return (
<MenuItem
Expand Down
2 changes: 2 additions & 0 deletions packages/url/src/filter-url-for-display.js
Original file line number Diff line number Diff line change
Expand Up @@ -13,6 +13,8 @@
* @return {string} Displayed URL.
*/
export function filterURLForDisplay( url, maxLength = null ) {
if ( ! url ) return url;
Mamaduka marked this conversation as resolved.
Show resolved Hide resolved

// Remove protocol and www prefixes.
let filteredURL = url.replace( /^(?:https?:)\/\/(?:www\.)?/, '' );

Expand Down
Loading