Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions packages/block-editor/CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,7 @@
- Inserter: Open faster when many block types are registered ([#83446](https://github.com/WordPress/gutenberg/pull/83446)).
- State control badges: migrate from the private `@wordpress/components` `Badge` to `@wordpress/ui` `Badge` ([#82608](https://github.com/WordPress/gutenberg/pull/82608)).
- Use the `inertValue` helper to set `inert` attributes, for better React 18/19 compatibility ([#83871](https://github.com/WordPress/gutenberg/pull/83871)).
- `LinkControl`: Add a `transformSuggestions` prop, so a consumer can filter, order or add to the search suggestions before they are shown ([#83652](https://github.com/WordPress/gutenberg/pull/83652)).

### Bug Fixes

Expand Down
78 changes: 78 additions & 0 deletions packages/block-editor/src/components/link-control/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -172,6 +172,84 @@ Controls the query parameters used to search for suggestions. For example, to li
/>
```

### transformSuggestions

- Type: `Function`
- Required: No

Changes the search suggestions before they are shown. It can filter them, reorder them, or add new ones.

It is called with the suggestions and an object with two properties:

- `searchTerm`: what the user typed.
- `isInitialSuggestions`: `true` for the suggestions shown before anything is typed.

Return the suggestions to show, as an array or a Promise that resolves to one. It is not called when the user types a URL.

Each suggestion is an object. These are the properties `LinkControl` reads:

- `id` (`string|number`): identifies the suggestion, together with its `type`. A suggestion without one is treated as a typed URL, and its `url` must be valid.
- `title` (`string`): the text shown for the suggestion.
- `type` (`string`): what kind of result it is, such as `page` or `post`. It is shown beside the title, unless `typeLabel` is set.
- `url` (`string`, optional): shown under the title, and used as the link's URL when the suggestion is chosen.
- `typeLabel` (`string`, optional): the label shown beside the title, in place of `type`.
- `icon` (`Element`, optional): the icon shown before the title, such as one from `@wordpress/icons`. Without it, a known `type` shows its own icon.

Choosing a suggestion calls `onChange` with it, including any properties of your own. To act on a suggestion that is not a link, give it a property only your suggestions have and check for that in `onChange`. Don't rely on `type` alone: a site can register a post type with the same name, and its results will arrive with that `type`.

Leave out media results:

```jsx
<LinkControl
transformSuggestions={ ( suggestions ) =>
suggestions.filter( ( suggestion ) => suggestion.kind !== 'media' )
}
/>
```

Add a suggestion that runs an action instead of setting a link:

```jsx
import { __ } from '@wordpress/i18n';
import { plus } from '@wordpress/icons';

function MyLinkControl( { link, setLink, openNewPageForm } ) {
return (
<LinkControl
value={ link }
transformSuggestions={ (
suggestions,
{ searchTerm, isInitialSuggestions }
) => {
if ( isInitialSuggestions ) {
return suggestions;
}

return [
...suggestions,
{
id: 'new-page',
type: 'action',
title: searchTerm,
typeLabel: __( 'New page' ),
icon: plus,
isNewPageAction: true,
},
];
} }
onChange={ ( nextValue ) => {
if ( nextValue.isNewPageAction ) {
openNewPageForm( nextValue.title );
return;
}

setLink( nextValue );
} }
/>
);
}
```

### forceIsEditingLink

- Type: `boolean`
Expand Down
5 changes: 5 additions & 0 deletions packages/block-editor/src/components/link-control/index.jsx
Original file line number Diff line number Diff line change
Expand Up @@ -102,6 +102,9 @@ import normalizeUrl from './normalize-url';
* @property {boolean=} showInitialSuggestions Whether to present initial suggestions immediately.
* @property {boolean=} withCreateSuggestion Whether to allow creation of link value from suggestion.
* @property {Object=} suggestionsQuery Query parameters to pass along to wp.blockEditor.__experimentalFetchLinkSuggestions.
* @property {Function=} transformSuggestions Changes the search suggestions before they are shown. Called
* with the suggestions and `{ searchTerm, isInitialSuggestions }`,
* and returns the suggestions to show or a Promise of them.
* @property {boolean=} noURLSuggestion Whether to add a fallback suggestion which treats the search query as a URL.
* @property {boolean=} hasTextControl Whether to add a text field to the UI to update the value.title.
* @property {string|Function|undefined} createSuggestionButtonText The text to use in the button that calls createSuggestion.
Expand Down Expand Up @@ -168,6 +171,7 @@ function LinkControl( {
withCreateSuggestion,
inputValue: propInputValue = '',
suggestionsQuery = {},
transformSuggestions,
noURLSuggestion = false,
createSuggestionButtonText,
hasRichPreviews = false,
Expand Down Expand Up @@ -690,6 +694,7 @@ function LinkControl( {
allowDirectEntry={ ! noDirectEntry }
showSuggestions={ showSuggestions }
suggestionsQuery={ suggestionsQuery }
transformSuggestions={ transformSuggestions }
withURLSuggestion={ ! noURLSuggestion }
createSuggestionButtonText={
createSuggestionButtonText
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -33,7 +33,7 @@ const LinkControlSearchInput = forwardRef(
allowDirectEntry = true,
showInitialSuggestions = false,
suggestionsQuery = {},
withURLSuggestion = true,
transformSuggestions = null,
createSuggestionButtonText,
hideLabelFromVision = false,
suffix,
Expand All @@ -46,7 +46,7 @@ const LinkControlSearchInput = forwardRef(
suggestionsQuery,
allowDirectEntry,
withCreateSuggestion,
withURLSuggestion
transformSuggestions
);

const searchHandler = showSuggestions
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -42,7 +42,10 @@ const TYPES = {
function SearchItemIcon( { isURL, suggestion } ) {
let icon = null;

if ( isURL ) {
// A suggestion added by `transformSuggestions` can bring its own icon.
if ( suggestion.icon ) {
icon = suggestion.icon;
} else if ( isURL ) {
icon = globe;
} else if ( suggestion.type in TYPES ) {
icon = TYPES[ suggestion.type ].icon;
Expand Down Expand Up @@ -168,6 +171,11 @@ function getVisualTypeName( suggestion ) {
return __( 'Blog home' );
}

// A suggestion added by `transformSuggestions` can bring its own label.
if ( suggestion.typeLabel ) {
return suggestion.typeLabel;
}

// Provide translated labels for built-in post types. Ideally, the API would return the localised CPT or taxonomy label.
if ( suggestion.type in TYPES ) {
return TYPES[ suggestion.type ].label;
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -27,6 +27,7 @@ import {
uniqueId,
} from './fixtures';
import { expectValidatedInputControlDeprecationIfCalled } from '../../url-input/test/fixtures/validated-input-control-deprecation';
import { CREATE_TYPE } from '../constants';

globalThis.wpVitest.mockMatchMedia();

Expand Down Expand Up @@ -3669,3 +3670,224 @@ describe( 'Front page and blog home labelling', () => {
expect( option ).not.toHaveTextContent( 'Front page' );
} );
} );

describe( 'Transforming suggestions', () => {
it( 'should render the suggestions returned by transformSuggestions', async () => {
const user = userEvent.setup();
const [ firstSuggestion ] = fauxEntitySuggestions;
const transformSuggestions = vi.fn( () => [ firstSuggestion ] );

render( <LinkControl transformSuggestions={ transformSuggestions } /> );

await user.type(
screen.getByRole( 'combobox', { name: 'Search or type URL' } ),
'Hello'
);

const searchResults = await screen.findByRole( 'listbox', {
name: /Search results for.*/,
} );

expect( transformSuggestions ).toHaveBeenCalledWith(
fauxEntitySuggestions,
expect.objectContaining( {
isInitialSuggestions: false,
searchTerm: 'Hello',
} )
);

const options = within( searchResults ).getAllByRole( 'option' );

expect( options ).toHaveLength( 1 );
expect( options[ 0 ] ).toHaveTextContent( firstSuggestion.title );
} );

it( 'should add the create suggestion after the transformed suggestions', async () => {
const user = userEvent.setup();
const transformSuggestions = vi.fn( ( suggestions ) =>
[ ...suggestions ].reverse()
);

render(
<LinkControl
createSuggestion={ vi.fn() }
transformSuggestions={ transformSuggestions }
/>
);

await user.type(
screen.getByRole( 'combobox', { name: 'Search or type URL' } ),
'Hello'
);

const searchResults = await screen.findByRole( 'listbox', {
name: /Search results for.*/,
} );

// The create option is not a search result, so it keeps its place
// at the end whatever order the consumer chooses.
for ( const [ suggestions ] of transformSuggestions.mock.calls ) {
expect( suggestions ).not.toContainEqual(
expect.objectContaining( { type: CREATE_TYPE } )
);
}

const options = within( searchResults ).getAllByRole( 'option' );

expect( options.at( -1 ) ).toHaveTextContent( 'Create:' );
} );

it( 'should label a front page that transformSuggestions adds', async () => {
const user = userEvent.setup();
const frontPage = {
id: 1,
title: 'Home',
type: 'page',
kind: 'post-type',
url: '/home',
};
const transformSuggestions = vi.fn( ( suggestions ) => [
frontPage,
...suggestions,
] );

useSelect.mockImplementation( () => ( {
fetchSearchSuggestions: () => Promise.resolve( [] ),
fetchRichUrlData: mockFetchRichUrlData,
pageOnFront: 1,
pageForPosts: 2,
} ) );

render( <LinkControl transformSuggestions={ transformSuggestions } /> );

await user.type(
screen.getByRole( 'combobox', { name: 'Search or type URL' } ),
'Home'
);

const searchResults = await screen.findByRole( 'listbox', {
name: /Search results for.*/,
} );

expect(
within( searchResults ).getByRole( 'option', { name: /Home/ } )
).toHaveTextContent( 'Front page' );
} );

it( 'should not call transformSuggestions for a URL', async () => {
const user = userEvent.setup();
const transformSuggestions = vi.fn( ( suggestions ) => suggestions );

render( <LinkControl transformSuggestions={ transformSuggestions } /> );

await user.click(
screen.getByRole( 'combobox', { name: 'Search or type URL' } )
);
await user.paste( 'https://example.com' );

await screen.findByRole( 'listbox', {
name: /Search results for.*/,
} );

expect( transformSuggestions ).not.toHaveBeenCalled();
} );

it( 'should call transformSuggestions for initial suggestions too', async () => {
const transformSuggestions = vi.fn( ( suggestions ) => suggestions );

render(
<LinkControl
showInitialSuggestions
transformSuggestions={ transformSuggestions }
/>
);

await screen.findByRole( 'listbox', {
name: 'Suggestions',
} );

expect( transformSuggestions ).toHaveBeenCalledWith(
fauxEntitySuggestions.slice( 0, 3 ),
expect.objectContaining( { isInitialSuggestions: true } )
);
} );

describe( 'with a suggestion that is not a link', () => {
const blockSuggestion = {
id: 'core/home-link',
type: 'block',
title: 'Home Link',
icon: <svg data-testid="block-suggestion-icon" />,
typeLabel: 'Block',
};

it( 'should show the icon and type label the suggestion provides', async () => {
const user = userEvent.setup();

render(
<LinkControl
transformSuggestions={ ( suggestions ) => [
blockSuggestion,
...suggestions,
] }
/>
);

await user.type(
screen.getByRole( 'combobox', { name: 'Search or type URL' } ),
'Home'
);

const searchResults = await screen.findByRole( 'listbox', {
name: /Search results for.*/,
} );
const option = within( searchResults ).getByRole( 'option', {
name: /Home Link/,
} );

expect( option ).toHaveTextContent( 'Block' );
expect(
within( option ).getByTestId( 'block-suggestion-icon' )
).toBeVisible();
} );

// It has no URL of its own, so it must not be held back by URL
// validation.
it( 'should pass the suggestion to onChange', async () => {
const user = userEvent.setup();
const mockOnChange = vi.fn();

render(
<LinkControl
onChange={ mockOnChange }
transformSuggestions={ ( suggestions ) => [
blockSuggestion,
...suggestions,
] }
/>
);

await user.type(
screen.getByRole( 'combobox', { name: 'Search or type URL' } ),
'Home'
);

const searchResults = await screen.findByRole( 'listbox', {
name: /Search results for.*/,
} );

await user.click(
within( searchResults ).getByRole( 'option', {
name: /Home Link/,
} )
);

expect( mockOnChange ).toHaveBeenCalledWith(
expect.objectContaining( {
id: 'core/home-link',
type: 'block',
} )
);
} );
} );
} );
Loading
Loading