TypeaheadSearch
A search form with stylized autocomplete suggestions.
TypeaheadSearch contains a form with a text input, a submit button, and a slot for hidden inputs. The parent component must listen for changes in the search query (which are debounced by default), fetch or calculate search results, then provide them as an array of search results for display to the user as a menu of ListTiles.
At the end of the list of search results, a final option to go to the search page for the current search query is provided.
Events are emitted to the parent when a search result is selected and when the form is submitted, with data about the selected item (e.g. for analytics).
TextInput props apply
This component contains a TextInput component. You can bind TextInput props to this component and they will be passed to the TextInput within.
Attributes passed to input
This component will pass any HTML attributes applied to it, except for CSS class, to the <input> element within the component.
Demos
Search Wikipedia articles
This implementation of TypeaheadSearch fetches articles from English Wikipedia. Note that the input expands on focus via the autoExpandWidth prop. Open the console to see emitted events.
<template>
<div>
<cdx-typeahead-search
id="typeahead-search-wikipedia"
form-action="https://en.wikipedia.org/w/index.php"
button-label="Search"
search-results-label="Search results"
:search-results="searchResults"
:search-footer-url="searchFooterUrl"
:highlight-query="true"
:auto-expand-width="true"
placeholder="Search Wikipedia"
@new-input="onNewInput"
@search-result-click="onSearchResultClick"
@submit="onSubmit"
>
<template #default>
<input
type="hidden"
name="language"
value="en"
>
<input
type="hidden"
name="title"
value="Special:Search"
>
</template>
<template #search-footer-text="{ searchQuery }">
Search Wikipedia for pages containing
<strong class="cdx-typeahead-search__search-footer__query">
{{ searchQuery }}
</strong>
</template>
</cdx-typeahead-search>
</div>
</template>
<script lang="ts">
import { defineComponent, ref } from 'vue';
import { CdxTypeaheadSearch, SearchResult, SearchResultClickEvent } from '@wikimedia/codex';
import { RestResult } from './types';
export default defineComponent( {
name: 'TypeaheadSearchWikipedia',
components: { CdxTypeaheadSearch },
setup() {
const searchResults = ref<SearchResult[]>( [] );
const searchFooterUrl = ref( '' );
const currentSearchTerm = ref( '' );
function onNewInput( value: string ) {
console.log( '"new-input" event emitted with value: ' + value );
currentSearchTerm.value = value;
if ( !value || value === '' ) {
searchResults.value = [];
searchFooterUrl.value = '';
return;
}
function adaptApiResponse( pages: RestResult[] ): SearchResult[] {
return pages.map( ( { id, key, title, description, thumbnail } ) => ( {
label: title,
value: id,
description: description,
url: `https://en.wikipedia.org/wiki/${encodeURIComponent( key )}`,
thumbnail: thumbnail ? {
url: thumbnail.url,
width: thumbnail.width ?? undefined,
height: thumbnail.height ?? undefined
} : undefined
} ) );
}
fetch(
`https://en.wikipedia.org/w/rest.php/v1/search/title?q=${encodeURIComponent( value )}&limit=10&`
).then( ( resp ) => resp.json() )
.then( ( data ) => {
if ( currentSearchTerm.value === value ) {
searchResults.value = data.pages && data.pages.length > 0 ?
adaptApiResponse( data.pages ) :
[];
searchFooterUrl.value = `https://en.wikipedia.org/w/index.php?title=Special%3ASearch&fulltext=1&search=${encodeURIComponent( value )}`;
}
} ).catch( () => {
searchResults.value = [];
searchFooterUrl.value = '';
} );
}
function onSearchResultClick( event: SearchResultClickEvent ) {
console.log( '"search-result-click" event emitted with value:' );
console.log( event );
}
function onSubmit( event: SearchResultClickEvent ) {
console.log( '"submit" event emitted with value:' );
console.log( event );
}
return {
searchResults,
searchFooterUrl,
onNewInput,
onSearchResultClick,
onSubmit
};
}
} );
</script>
Search Wikidata items
In this example, results are fetched from Wikidata. Note that thumbnails are hidden via the hideThumbnail prop. Open the console to see emitted events.
<template>
<div>
<cdx-typeahead-search
id="typeahead-search-wikidata"
form-action="https://www.wikidata.org/w/index.php"
button-label="Search"
search-results-label="Search results"
:search-results="searchResults"
:search-footer-url="searchFooterUrl"
:highlight-query="true"
:hide-thumbnail="true"
placeholder="Search Wikidata"
@new-input="onNewInput"
@search-result-click="onSearchResultClick"
@submit="onSubmit"
>
<template #default>
<input
type="hidden"
name="language"
value="en"
>
<input
type="hidden"
name="title"
value="Special:Search"
>
</template>
<template #search-footer-text="{ searchQuery }">
Search Wikidata for pages containing
<strong class="cdx-typeahead-search__search-footer__query">
{{ searchQuery }}
</strong>
</template>
</cdx-typeahead-search>
</div>
</template>
<script lang="ts">
import { defineComponent, ref } from 'vue';
import { CdxTypeaheadSearch, SearchResult, SearchResultClickEvent } from '@wikimedia/codex';
import { Result } from './types';
export default defineComponent( {
name: 'TypeaheadSearchWikidata',
components: { CdxTypeaheadSearch },
setup() {
const searchResults = ref<SearchResult[]>( [] );
const searchFooterUrl = ref( '' );
const currentSearchTerm = ref( '' );
function onNewInput( value: string ) {
console.log( '"new-input" event emitted with value: ' + value );
currentSearchTerm.value = value;
if ( !value || value === '' ) {
searchResults.value = [];
searchFooterUrl.value = '';
return;
}
function adaptApiResponse( pages: Result[] ): SearchResult[] {
return pages.map( ( { id, label, url, match, description } ) => ( {
label: match.type === 'alias' ? label + ` (${match.text})` : label,
value: id,
description,
url
} ) );
}
fetch(
`https://www.wikidata.org/w/api.php?origin=*&action=wbsearchentities&format=json&search=${encodeURIComponent( value )}&language=en&uselang=en&type=item`
).then( ( resp ) => resp.json() )
.then( ( data ) => {
if ( currentSearchTerm.value === value ) {
searchResults.value = data.search && data.search.length > 0 ?
adaptApiResponse( data.search ) :
[];
searchFooterUrl.value = `https://www.wikidata.org/w/index.php?search=${encodeURIComponent( value )}&title=Special%3ASearch&fulltext=1`;
}
} ).catch( () => {
searchResults.value = [];
searchFooterUrl.value = '';
} );
}
function onSearchResultClick( event: SearchResultClickEvent ) {
console.log( '"search-result-click" event emitted with value:' );
console.log( event );
}
function onSubmit( event: SearchResultClickEvent ) {
console.log( '"submit" event emitted with value:' );
console.log( event );
}
return {
searchResults,
searchFooterUrl,
onNewInput,
onSearchResultClick,
onSubmit
};
}
} );
</script>
The initialInputValue prop can be used to pass in the initial value of the TextInput. This is useful when replacing a server-rendered UI where the user may have started typing a search query, or for pre-populating the search term when a user navigates back to a page where they had previously entered one.
On mount, TypeaheadSearch will fetch search results for the initial input value if it's provided. After that, the input value is tracked internally and will be emitted up to the parent component when the value changes.
<template>
<div>
<cdx-typeahead-search
id="typeahead-search-default"
form-action="https://en.wikipedia.org/w/index.php"
button-label="Search"
search-results-label="Search results"
:initial-input-value="initialInputValue"
:search-results="searchResults"
:search-footer-url="searchFooterUrl"
:highlight-query="true"
placeholder="Search Wikipedia"
@new-input="onNewInput"
>
<template #search-footer-text="{ searchQuery }">
Search Wikipedia for pages containing
<strong class="cdx-typeahead-search__search-footer__query">
{{ searchQuery }}
</strong>
</template>
</cdx-typeahead-search>
</div>
</template>
<script lang="ts">
import { defineComponent, ref } from 'vue';
import { CdxTypeaheadSearch, SearchResult } from '@wikimedia/codex';
import { RestResult } from './types';
export default defineComponent( {
name: 'TypeaheadSearchWikipedia',
components: { CdxTypeaheadSearch },
props: {
initialInputValue: {
type: String,
default: ''
}
},
setup() {
const searchResults = ref<SearchResult[]>( [] );
const searchFooterUrl = ref( '' );
const currentSearchTerm = ref( '' );
function onNewInput( value: string ) {
currentSearchTerm.value = value;
if ( !value || value === '' ) {
searchResults.value = [];
searchFooterUrl.value = '';
return;
}
function adaptApiResponse( pages: RestResult[] ): SearchResult[] {
return pages.map( ( { id, key, title, description, thumbnail } ) => ( {
label: title,
value: id,
description: description,
url: `https://en.wikipedia.org/wiki/${encodeURIComponent( key )}`,
thumbnail: thumbnail ? {
url: thumbnail.url,
width: thumbnail.width ?? undefined,
height: thumbnail.height ?? undefined
} : undefined
} ) );
}
fetch(
`https://en.wikipedia.org/w/rest.php/v1/search/title?q=${encodeURIComponent( value )}&limit=10&`
).then( ( resp ) => resp.json() )
.then( ( data ) => {
if ( currentSearchTerm.value === value ) {
searchResults.value = data.pages && data.pages.length > 0 ?
adaptApiResponse( data.pages ) :
[];
searchFooterUrl.value = `https://en.wikipedia.org/w/index.php?title=Special%3ASearch&fulltext=1&search=${encodeURIComponent( value )}`;
}
} ).catch( () => {
searchResults.value = [];
searchFooterUrl.value = '';
} );
}
return {
searchResults,
searchFooterUrl,
onNewInput
};
}
} );
</script>
Usage
Props
| Prop name | Description | Type | Values | Default |
|---|
id(required) | ID attribute for the form. | string | - | |
formAction(required) | Action attribute for form. | string | - | |
buttonLabel(required) | Submit button text. | string | - | |
searchResultsLabel(required) | Label attribute for the list of search results. | string | - | |
searchResults | List of search results. See the SearchResult type. | SearchResult[] | - | () => [] |
initialInputValue | Initial value for the text input.
Triggers an initial new-input event on mount. | string | - | '' |
searchFooterUrl | Link for the final option.
This will typically be a link to the search page for the current search query. | string | - | '' |
debounceInterval | Time interval for debouncing input events, in ms. | number | - | DebounceInterval |
highlightQuery | Whether the search query should be highlighted within a search result's title. | boolean | - | false |
hideThumbnail | Whether to hide search results' thumbnails. | boolean | - | false |
hideDescription | Whether to hide search results' descriptions. | boolean | - | false |
autoExpandWidth | Contract the width of the input when unfocused and expand the width of the input when focused to accomodate the extra width of the thumbnails. | boolean | - | false |
Methods
focus
Focus the component's input element.
Return
Events
| Event name | Properties | Description |
|---|
| new-input | value string - The new input value | When the text input value changes. Debounced by default. |
| search-result-click | event SearchResultClickEvent - Data for the selected result | When a search result is selected. |
| submit | event SearchResultClickEvent - Data for the selected result | When the form is submitted. |
Slots
| Name | Description | Bindings |
|---|
| search-footer-text | A slot for passing in translated search footer text. | searchQuery string - Input text entered by the user |
| default | A slot for passing hidden inputs, i.e. <input type="hidden" name="language" value="en"> | |