Skip to content
Open
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
4 changes: 4 additions & 0 deletions components/content-picker/index.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,7 @@ import { StyledComponentContext } from '../styled-components-context';
import { defaultRenderItemType } from '../content-search/SearchItem';
import {
ContentSearchMode,
QueryArgs,
QueryFilter,
QueryFieldsFilter,
RenderItemComponentProps,
Expand Down Expand Up @@ -64,6 +65,7 @@ export interface ContentPickerProps {
queryFieldsFilter?: QueryFieldsFilter;
searchResultFilter?: SearchResultFilter;
pickedItemFilter?: PickedItemFilter;
includeEmbeds?: QueryArgs['includeEmbeds'];
maxContentItems?: number;
isOrderable?: boolean;
singlePickedLabel?: string;
Expand Down Expand Up @@ -92,6 +94,7 @@ export const ContentPicker: React.FC<ContentPickerProps> = ({
queryFieldsFilter,
searchResultFilter,
pickedItemFilter,
includeEmbeds,
maxContentItems = 1,
isOrderable = false,
singlePickedLabel = __('You have selected the following item:', '10up-block-components'),
Expand Down Expand Up @@ -173,6 +176,7 @@ export const ContentPicker: React.FC<ContentPickerProps> = ({
queryFilter={queryFilter}
queryFieldsFilter={queryFieldsFilter}
searchResultFilter={searchResultFilter}
includeEmbeds={includeEmbeds}
perPage={perPage}
fetchInitialResults={fetchInitialResults}
renderItemType={renderItemType}
Expand Down
5 changes: 5 additions & 0 deletions components/content-search/index.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,7 @@ import { StyledComponentContext } from '../styled-components-context';
import type {
ContentSearchMode,
IdentifiableObject,
QueryArgs,
QueryFilter,
QueryFieldsFilter,
RenderItemComponentProps,
Expand Down Expand Up @@ -83,6 +84,7 @@ export interface ContentSearchProps {
queryFilter?: QueryFilter;
queryFieldsFilter?: QueryFieldsFilter;
searchResultFilter?: SearchResultFilter;
includeEmbeds?: QueryArgs['includeEmbeds'];
excludeItems?: Array<IdentifiableObject>;
renderItemType?: (props: NormalizedSuggestion) => string;
renderItem?: (props: RenderItemComponentProps) => JSX.Element;
Expand All @@ -109,6 +111,7 @@ const ContentSearch: React.FC<ContentSearchProps> = ({
queryFilter = (query: string) => query,
queryFieldsFilter,
searchResultFilter,
includeEmbeds = false,
excludeItems = [],
renderItemType = undefined,
renderItem: SearchResultItem = SearchItem,
Expand Down Expand Up @@ -144,6 +147,7 @@ const ContentSearch: React.FC<ContentSearchProps> = ({
queryFilter,
queryFieldsFilter,
searchResultFilter,
includeEmbeds,
],
queryFn: async ({ pageParam = 1, signal }) =>
fetchSearchResults({
Expand All @@ -155,6 +159,7 @@ const ContentSearch: React.FC<ContentSearchProps> = ({
queryFilter,
queryFieldsFilter,
searchResultFilter,
includeEmbeds,
excludeItems,
signal,
}),
Expand Down
31 changes: 31 additions & 0 deletions components/content-search/readme.md
Original file line number Diff line number Diff line change
Expand Up @@ -67,6 +67,7 @@ function MyComponent( props ) {
| `queryFilter` | `function` | `(query, parametersObject) => query` | Function called to allow you to customize the query before it's made. It's advisable to use `useCallback` to save this parameter |
| `queryFieldsFilter` | `function` | `undefined` | Function to customize which fields are fetched from the API. Receives `(fields: string[], mode: ContentSearchMode) => string[]`. It's advisable to use `useCallback` to save this parameter. |
| `searchResultFilter` | `function` | `undefined` | Function to customize the normalized search result item. Receives `(item: NormalizedSuggestion, originalResult: WP_REST_API_Search_Result \| WP_REST_API_User) => NormalizedSuggestion`. It's advisable to use `useCallback` to save this parameter. |
| `includeEmbeds` | `bool, string, array` | `undefined` | Whether to include embedded items in the search results. A string or array of strings can be passed to specify the specific embeds. |
| `label` | `string` | `''` | Renders a label for the Search Field.
| `hideLabelFromVision` | `bool` | `true` | Whether to hide the label |
| `mode` | `string` | `'post'` | One of: `post`, `user`, `term` |
Expand All @@ -78,3 +79,33 @@ function MyComponent( props ) {
| `renderItem` | `function` | `undefined` | Function to customize the rendering of each search result item. Receives `RenderItemComponentProps` and must return a JSX element. |
| `fetchInitialResults` | `bool` | `false` | Fetch initial results to present when focusing the search input |
| `options.inputDelay` | `number` | `undefined` | Debounce delay passed to the internal search input, defaults to 350ms |

## Search Result Item Customization

There are a number of vectors for customizing how search results are rendered. You can customize the item type label (e.g. "Post", "Page", "Category") by passing a function to the `renderItemType` prop. This function returns a string and receives a single `suggestion` argument, an object with the following shape:

```js
{
id: number;
subtype: string;
title: string;
type: string;
url: string;
embedded?: object;
}
```

You can also customize the entire item by passing a function to the `renderItem` prop. This function should be a React component that receives these props:

```js
{
item: object; // The suggestion object (see above).
onSelect: () => void;
searchTerm: string;
id: string;
contentTypes: string[];
renderType: ( suggestion: object ) => string;
}
```

You may need more than the default suggestion fields to render your custom item. The search endpoint is limited (by design) in what fields it returns, but you can use the linking & embedding functionality of the REST API to include the entire post object (or term, or user) in the response via the `embedded` prop. To do this, pass the `includeEmbeds` prop, which can be a boolean (to include all embeds), a string (to include a single embed type), or an array of strings (to include multiple embed types). This is useful if you want to display additional information about a post, such as its publication date. See the [content search example](example/src/blocks/content-search-example/edit.tsx) for a demonstration of this in action.
1 change: 1 addition & 0 deletions components/content-search/types.ts
Original file line number Diff line number Diff line change
Expand Up @@ -31,6 +31,7 @@ export interface QueryArgs {
contentTypes: Array<string>;
mode: ContentSearchMode;
keyword: string;
includeEmbeds?: boolean | string | Array<string>;
}

export type QueryFilter = (query: string, args: QueryArgs) => string;
Expand Down
35 changes: 32 additions & 3 deletions components/content-search/utils.ts
Original file line number Diff line number Diff line change
Expand Up @@ -16,6 +16,7 @@ import { decodeEntities } from '@wordpress/html-entities';
*/
import type {
ContentSearchMode,
QueryArgs,
QueryFilter,
QueryFieldsFilter,
SearchResultFilter,
Expand Down Expand Up @@ -50,6 +51,7 @@ interface PrepareSearchQueryArgs {
contentTypes: Array<string>;
queryFilter: QueryFilter;
queryFieldsFilter?: QueryFieldsFilter;
includeEmbeds?: QueryArgs['includeEmbeds'];
}

/*
Expand All @@ -63,6 +65,7 @@ export const prepareSearchQuery = ({
contentTypes,
queryFilter,
queryFieldsFilter,
includeEmbeds = false,
}: PrepareSearchQueryArgs): string => {
let searchQuery;

Expand All @@ -78,10 +81,20 @@ export const prepareSearchQuery = ({
fields = queryFieldsFilter(fields, mode);
}

if (includeEmbeds) {
if (!fields.includes('_links')) {
fields.push('_links');
}
if (!fields.includes('_embedded')) {
fields.push('_embedded');
}
}

switch (mode) {
case 'user':
searchQuery = addQueryArgs('wp/v2/users', {
search: keyword,
...(includeEmbeds ? { _embed: includeEmbeds } : {}),
_fields: fields,
});
break;
Expand All @@ -90,7 +103,7 @@ export const prepareSearchQuery = ({
search: keyword,
subtype: contentTypes.join(','),
type: mode,
_embed: true,
...(includeEmbeds ? { _embed: includeEmbeds } : {}),
per_page: perPage,
page,
_fields: fields,
Expand All @@ -105,6 +118,7 @@ export const prepareSearchQuery = ({
contentTypes,
mode,
keyword,
includeEmbeds,
});
};

Expand All @@ -113,6 +127,7 @@ interface NormalizeResultsArgs {
results: WP_REST_API_Search_Result[] | WP_REST_API_User[];
excludeItems: Array<IdentifiableObject>;
searchResultFilter?: SearchResultFilter;
includeEmbeds?: QueryArgs['includeEmbeds'];
}

/**
Expand All @@ -129,7 +144,7 @@ export const toPlainTextTitle = (input: string | undefined | null): string => {
const doc = new DOMParser().parseFromString(String(input), 'text/html');
const text = doc.body.textContent ?? '';

return decodeEntities(text).replace(/\u00A0/g, ' ').trim();
return decodeEntities(text).replace(/ /g, ' ').trim();
};

/*
Expand All @@ -141,13 +156,15 @@ export const normalizeResults = ({
results,
excludeItems,
searchResultFilter,
includeEmbeds = false,
}: NormalizeResultsArgs): Array<{
id: number;
subtype: ContentSearchMode | string;
title: string;
type: ContentSearchMode | string;
url: string;
info?: string;
embedded?: WP_REST_API_Search_Result['_embedded'] | WP_REST_API_User['_embedded'];
}> => {
const filteredResults = filterOutExcludedItems({ results, excludeItems });
return filteredResults.map((item) => {
Expand All @@ -158,6 +175,7 @@ export const normalizeResults = ({
type: ContentSearchMode | string;
url: string;
info?: string;
embedded?: WP_REST_API_Search_Result['_embedded'] | WP_REST_API_User['_embedded'];
};

switch (mode) {
Expand All @@ -169,6 +187,7 @@ export const normalizeResults = ({
title: toPlainTextTitle(userItem.name),
type: mode,
url: userItem.link,
...(includeEmbeds ? { embedded: userItem._embedded } : {}),
};
break;
default:
Expand All @@ -179,6 +198,7 @@ export const normalizeResults = ({
title: toPlainTextTitle(searchItem.title),
type: searchItem.type,
url: searchItem.url,
...(includeEmbeds ? { embedded: searchItem._embedded } : {}),
};
break;
}
Expand All @@ -203,6 +223,7 @@ interface FetchSearchResultsArgs {
queryFilter: QueryFilter;
queryFieldsFilter?: QueryFieldsFilter;
searchResultFilter?: SearchResultFilter;
includeEmbeds?: QueryArgs['includeEmbeds'];
excludeItems: Array<IdentifiableObject>;
signal?: AbortSignal;
}
Expand All @@ -216,6 +237,7 @@ export async function fetchSearchResults({
queryFilter,
queryFieldsFilter,
searchResultFilter,
includeEmbeds,
excludeItems,
signal,
}: FetchSearchResultsArgs) {
Expand All @@ -227,6 +249,7 @@ export async function fetchSearchResults({
contentTypes,
queryFilter,
queryFieldsFilter,
includeEmbeds,
});
const response = await apiFetch<Response>({
path: searchQueryString,
Expand All @@ -250,7 +273,13 @@ export async function fetchSearchResults({
break;
}

const normalizedResults = normalizeResults({ results, excludeItems, mode, searchResultFilter });
const normalizedResults = normalizeResults({
results,
excludeItems,
mode,
searchResultFilter,
includeEmbeds,
});

const hasNextPage = totalPages > page;
const hasPreviousPage = page > 1;
Expand Down
14 changes: 12 additions & 2 deletions cypress/integration/ContentPicker.spec.js
Original file line number Diff line number Diff line change
Expand Up @@ -13,8 +13,18 @@ context('ContentPicker', () => {

it('allows the user to see results when on focus', () => {
cy.createPost({title: 'Post Picker'});
cy.insertBlock('Hello World');
cy.get('.wp-block-example-hello-world .components-text-control__input').focus();
cy.insertBlock('Content Picker');
cy.get('.wp-block-example-content-picker .components-input-control__input').focus();
cy.get('.tenup-content-search-list').should('exist');
})

it('displays the post date in the search results', () => {
cy.createPost({title: 'Post Picker with Post Date'});
cy.insertBlock('Content Picker');
cy.get('.wp-block-example-content-picker .components-input-control__input').focus();
cy.get('.tenup-content-search-list .tenup-content-search-list-item time').invoke('attr', 'datetime').then((datetime) => {
const date = new Date(datetime);
expect(date.toString()).to.not.equal('Invalid Date');
});
})
})
12 changes: 11 additions & 1 deletion cypress/integration/ContentSearch.spec.js
Original file line number Diff line number Diff line change
Expand Up @@ -14,7 +14,17 @@ context('ContentSearch', () => {
it('allows the user to see initial results on focus', () => {
cy.createPost({title: 'Post Searcher with fetchOnFocus'});
cy.insertBlock('Post Searcher');
cy.get('.wp-block-example-content-search .components-text-control__input').focus();
cy.get('.wp-block-example-content-search .components-input-control__input').focus();
cy.get('.tenup-content-search-list').should('exist');
})

it('displays the post date in the search results', () => {
cy.createPost({title: 'Post Searcher with Post Date'});
cy.insertBlock('Post Searcher');
cy.get('.wp-block-example-content-search .components-input-control__input').focus();
cy.get('.tenup-content-search-list .tenup-content-search-list-item time').invoke('attr', 'datetime').then((datetime) => {
const date = new Date(datetime);
expect(date.toString()).to.not.equal('Invalid Date');
});
})
})
Loading