diff --git a/components/content-picker/index.tsx b/components/content-picker/index.tsx index 2820cd10..f28e8222 100644 --- a/components/content-picker/index.tsx +++ b/components/content-picker/index.tsx @@ -11,6 +11,7 @@ import { StyledComponentContext } from '../styled-components-context'; import { defaultRenderItemType } from '../content-search/SearchItem'; import { ContentSearchMode, + QueryArgs, QueryFilter, QueryFieldsFilter, RenderItemComponentProps, @@ -64,6 +65,7 @@ export interface ContentPickerProps { queryFieldsFilter?: QueryFieldsFilter; searchResultFilter?: SearchResultFilter; pickedItemFilter?: PickedItemFilter; + includeEmbeds?: QueryArgs['includeEmbeds']; maxContentItems?: number; isOrderable?: boolean; singlePickedLabel?: string; @@ -92,6 +94,7 @@ export const ContentPicker: React.FC = ({ queryFieldsFilter, searchResultFilter, pickedItemFilter, + includeEmbeds, maxContentItems = 1, isOrderable = false, singlePickedLabel = __('You have selected the following item:', '10up-block-components'), @@ -173,6 +176,7 @@ export const ContentPicker: React.FC = ({ queryFilter={queryFilter} queryFieldsFilter={queryFieldsFilter} searchResultFilter={searchResultFilter} + includeEmbeds={includeEmbeds} perPage={perPage} fetchInitialResults={fetchInitialResults} renderItemType={renderItemType} diff --git a/components/content-search/index.tsx b/components/content-search/index.tsx index b92b912f..ebabff82 100644 --- a/components/content-search/index.tsx +++ b/components/content-search/index.tsx @@ -9,6 +9,7 @@ import { StyledComponentContext } from '../styled-components-context'; import type { ContentSearchMode, IdentifiableObject, + QueryArgs, QueryFilter, QueryFieldsFilter, RenderItemComponentProps, @@ -83,6 +84,7 @@ export interface ContentSearchProps { queryFilter?: QueryFilter; queryFieldsFilter?: QueryFieldsFilter; searchResultFilter?: SearchResultFilter; + includeEmbeds?: QueryArgs['includeEmbeds']; excludeItems?: Array; renderItemType?: (props: NormalizedSuggestion) => string; renderItem?: (props: RenderItemComponentProps) => JSX.Element; @@ -109,6 +111,7 @@ const ContentSearch: React.FC = ({ queryFilter = (query: string) => query, queryFieldsFilter, searchResultFilter, + includeEmbeds = false, excludeItems = [], renderItemType = undefined, renderItem: SearchResultItem = SearchItem, @@ -144,6 +147,7 @@ const ContentSearch: React.FC = ({ queryFilter, queryFieldsFilter, searchResultFilter, + includeEmbeds, ], queryFn: async ({ pageParam = 1, signal }) => fetchSearchResults({ @@ -155,6 +159,7 @@ const ContentSearch: React.FC = ({ queryFilter, queryFieldsFilter, searchResultFilter, + includeEmbeds, excludeItems, signal, }), diff --git a/components/content-search/readme.md b/components/content-search/readme.md index 028f816b..9527e9bc 100644 --- a/components/content-search/readme.md +++ b/components/content-search/readme.md @@ -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` | @@ -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. diff --git a/components/content-search/types.ts b/components/content-search/types.ts index 5f8723ba..4c28a455 100644 --- a/components/content-search/types.ts +++ b/components/content-search/types.ts @@ -31,6 +31,7 @@ export interface QueryArgs { contentTypes: Array; mode: ContentSearchMode; keyword: string; + includeEmbeds?: boolean | string | Array; } export type QueryFilter = (query: string, args: QueryArgs) => string; diff --git a/components/content-search/utils.ts b/components/content-search/utils.ts index b71aaf31..2bbdddc4 100644 --- a/components/content-search/utils.ts +++ b/components/content-search/utils.ts @@ -16,6 +16,7 @@ import { decodeEntities } from '@wordpress/html-entities'; */ import type { ContentSearchMode, + QueryArgs, QueryFilter, QueryFieldsFilter, SearchResultFilter, @@ -50,6 +51,7 @@ interface PrepareSearchQueryArgs { contentTypes: Array; queryFilter: QueryFilter; queryFieldsFilter?: QueryFieldsFilter; + includeEmbeds?: QueryArgs['includeEmbeds']; } /* @@ -63,6 +65,7 @@ export const prepareSearchQuery = ({ contentTypes, queryFilter, queryFieldsFilter, + includeEmbeds = false, }: PrepareSearchQueryArgs): string => { let searchQuery; @@ -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; @@ -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, @@ -105,6 +118,7 @@ export const prepareSearchQuery = ({ contentTypes, mode, keyword, + includeEmbeds, }); }; @@ -113,6 +127,7 @@ interface NormalizeResultsArgs { results: WP_REST_API_Search_Result[] | WP_REST_API_User[]; excludeItems: Array; searchResultFilter?: SearchResultFilter; + includeEmbeds?: QueryArgs['includeEmbeds']; } /** @@ -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(); }; /* @@ -141,6 +156,7 @@ export const normalizeResults = ({ results, excludeItems, searchResultFilter, + includeEmbeds = false, }: NormalizeResultsArgs): Array<{ id: number; subtype: ContentSearchMode | string; @@ -148,6 +164,7 @@ export const normalizeResults = ({ 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) => { @@ -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) { @@ -169,6 +187,7 @@ export const normalizeResults = ({ title: toPlainTextTitle(userItem.name), type: mode, url: userItem.link, + ...(includeEmbeds ? { embedded: userItem._embedded } : {}), }; break; default: @@ -179,6 +198,7 @@ export const normalizeResults = ({ title: toPlainTextTitle(searchItem.title), type: searchItem.type, url: searchItem.url, + ...(includeEmbeds ? { embedded: searchItem._embedded } : {}), }; break; } @@ -203,6 +223,7 @@ interface FetchSearchResultsArgs { queryFilter: QueryFilter; queryFieldsFilter?: QueryFieldsFilter; searchResultFilter?: SearchResultFilter; + includeEmbeds?: QueryArgs['includeEmbeds']; excludeItems: Array; signal?: AbortSignal; } @@ -216,6 +237,7 @@ export async function fetchSearchResults({ queryFilter, queryFieldsFilter, searchResultFilter, + includeEmbeds, excludeItems, signal, }: FetchSearchResultsArgs) { @@ -227,6 +249,7 @@ export async function fetchSearchResults({ contentTypes, queryFilter, queryFieldsFilter, + includeEmbeds, }); const response = await apiFetch({ path: searchQueryString, @@ -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; diff --git a/cypress/integration/ContentPicker.spec.js b/cypress/integration/ContentPicker.spec.js index 8e1040bd..8f15d9f2 100644 --- a/cypress/integration/ContentPicker.spec.js +++ b/cypress/integration/ContentPicker.spec.js @@ -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'); + }); + }) }) diff --git a/cypress/integration/ContentSearch.spec.js b/cypress/integration/ContentSearch.spec.js index 5ff4d389..f5978388 100644 --- a/cypress/integration/ContentSearch.spec.js +++ b/cypress/integration/ContentSearch.spec.js @@ -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'); + }); + }) }) diff --git a/example/src/blocks/content-picker-example/edit.tsx b/example/src/blocks/content-picker-example/edit.tsx index 0b841b7b..ffba8a5e 100644 --- a/example/src/blocks/content-picker-example/edit.tsx +++ b/example/src/blocks/content-picker-example/edit.tsx @@ -3,9 +3,28 @@ import { useCallback } from '@wordpress/element'; import { __ } from '@wordpress/i18n'; import { InspectorControls, useBlockProps } from '@wordpress/block-editor'; import { PanelBody, Placeholder } from '@wordpress/components'; +import { addQueryArgs } from '@wordpress/url'; import { ContentPicker } from '@10up/block-components'; +/** + * Example search result customization that uses embedded data to display the + * post date. + */ +const renderItemType = ( props ) => { + const { type, subtype, embedded } = props; + const { date } = embedded?.self?.[ 0 ] ?? {}; + const postDate = new Date( Date.parse( date ) ); + + return ( + <> + { subtype ? subtype : type } +
+ + + ); +}; + export const BlockEdit = (props) => { const { attributes: {selectedPosts}, @@ -35,38 +54,46 @@ export const BlockEdit = (props) => { const blockProps = useBlockProps(); + /** + * Example query string filter that returns results in reverse chronological + * order. + */ + const queryFilter = ( query ) => { + return addQueryArgs( query, { + orderby: 'date', + order: 'desc', + } ); + }; + + const ContentPickerControl = () => ( + + ); + return ( <> - +
- +
) -} \ No newline at end of file +} diff --git a/example/src/blocks/content-search-example/edit.tsx b/example/src/blocks/content-search-example/edit.tsx index e8d14a09..599dcdbc 100644 --- a/example/src/blocks/content-search-example/edit.tsx +++ b/example/src/blocks/content-search-example/edit.tsx @@ -3,9 +3,28 @@ import { useCallback } from '@wordpress/element'; import { __ } from '@wordpress/i18n'; import { InspectorControls, useBlockProps } from '@wordpress/block-editor'; import { PanelBody, Placeholder } from '@wordpress/components'; +import { addQueryArgs } from '@wordpress/url'; import { ContentSearch } from '@10up/block-components'; +/** + * Example search result customization that uses embedded data to display the + * post date. + */ +const renderItemType = ( props ) => { + const { type, subtype, embedded } = props; + const { date } = embedded?.self?.[ 0 ] ?? {}; + const postDate = new Date( Date.parse( date ) ); + + return ( + <> + { subtype ? subtype : type } +
+ + + ); +}; + export const BlockEdit = (props) => { const { attributes: {selectedPost}, @@ -33,38 +52,48 @@ export const BlockEdit = (props) => { const blockProps = useBlockProps(); + /** + * Example query string filter that returns results in reverse chronological + * order. + */ + const queryFilter = ( query ) => { + return addQueryArgs( query, { + orderby: 'date', + order: 'desc', + } ); + }; + + const ContentSearchControl = () => ( + + ); + return ( <> - +
-
- { - selectedPost && +
+ { selectedPost && (

{__('Selected Post:', 'example')} {selectedPost.title}

- } + ) }
- +
) -} \ No newline at end of file +}