recent-searches
Version:
A JavaScript module to help anyone easily build recent searches functionality into their search.
841 lines (837 loc) • 114 kB
HTML
<!doctype html>
<html class="default no-js">
<head>
<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<title>recent-searches</title>
<meta name="description" content="">
<meta name="viewport" content="width=device-width, initial-scale=1">
<link rel="stylesheet" href="assets/css/main.css">
</head>
<body>
<header>
<div class="tsd-page-toolbar">
<div class="container">
<div class="table-wrap">
<div class="table-cell" id="tsd-search" data-index="assets/js/search.js" data-base=".">
<div class="field">
<label for="tsd-search-field" class="tsd-widget search no-caption">Search</label>
<input id="tsd-search-field" type="text" />
</div>
<ul class="results">
<li class="state loading">Preparing search index...</li>
<li class="state failure">The search index is not available</li>
</ul>
<a href="index.html" class="title">recent-searches</a>
</div>
<div class="table-cell" id="tsd-widgets">
<div id="tsd-filter">
<a href="#" class="tsd-widget options no-caption" data-toggle="options">Options</a>
<div class="tsd-filter-group">
<div class="tsd-select" id="tsd-filter-visibility">
<span class="tsd-select-label">All</span>
<ul class="tsd-select-list">
<li data-value="public">Public</li>
<li data-value="protected">Public/Protected</li>
<li data-value="private" class="selected">All</li>
</ul>
</div>
<input type="checkbox" id="tsd-filter-inherited" checked />
<label class="tsd-widget" for="tsd-filter-inherited">Inherited</label>
<input type="checkbox" id="tsd-filter-externals" checked />
<label class="tsd-widget" for="tsd-filter-externals">Externals</label>
<input type="checkbox" id="tsd-filter-only-exported" />
<label class="tsd-widget" for="tsd-filter-only-exported">Only exported</label>
</div>
</div>
<a href="#" class="tsd-widget menu no-caption" data-toggle="menu">Menu</a>
</div>
</div>
</div>
</div>
<div class="tsd-page-title">
<div class="container">
<ul class="tsd-breadcrumb">
<li>
<a href="globals.html">Globals</a>
</li>
</ul>
<h1> recent-searches</h1>
</div>
</div>
</header>
<div class="container container-main">
<div class="row">
<div class="col-8 col-content">
<div class="tsd-panel tsd-typography">
<h1 align="center">
recent-searches 🕵️♀️🕵️♂️
<br>
<!-- <img src="https://recent-searches.netlify.com/logo/recent-searches.svg" alt="recent-searches logo" title="recent-searches logo" width="300"> -->
<br>
</h1>
<p align="center" style="font-size: 1.2rem;">A JavaScript module that helps anyone build recent searches functionality.
</p>
<hr />
<p><a href="https://travis-ci.org/recent-searches-js/recent-searches"><img src="https://img.shields.io/travis/recent-searches-js/recent-searches.svg?style=flat-square" alt="Build Status"></a>
<a href="https://codecov.io/github/recent-searches-js/recent-searches"><img src="https://img.shields.io/codecov/c/github/recent-searches-js/recent-searches.svg?style=flat-square" alt="Code Coverage"></a>
<a href="http://npmcharts.com/compare/recent-searches"><img src="https://img.shields.io/npm/dm/recent-searches.svg?style=flat-square" alt="downloads"></a> <a href="https://www.npmjs.com/package/recent-searches"><img src="https://img.shields.io/npm/v/recent-searches.svg?style=flat-square" alt="version"></a>
<a href="https://github.com/recent-searches-js/recent-searches/blob/master/LICENSE"><img src="https://img.shields.io/npm/l/recent-searches.svg?style=flat-square" alt="MIT License"></a></p>
<p><a href="http://makeapullrequest.com"><img src="https://img.shields.io/badge/PRs-welcome-brightgreen.svg?style=flat-square" alt="PRs Welcome"></a></p>
<p><a href="https://unpkg.com/recent-searches/dist/"><img src="http://img.badgesize.io/https://unpkg.com/recent-searches/dist/recent-searches.umd.min.js?label=size&style=flat-square" alt="size"></a> <a href="https://unpkg.com/recent-searches/dist/"><img src="http://img.badgesize.io/https://unpkg.com/recent-searches/dist/recent-searches.umd.min.js?compression=gzip&label=gzip%20size&style=flat-square" alt="gzip size"></a>
<a href="https://unpkg.com/recent-searches/dist/"><img src="https://img.shields.io/badge/module%20formats-umd%2C%20cjs%2C%20es-green.svg?style=flat-square" alt="module formats: umd, cjs, and es"></a></p>
<h2 id="the-problem">The problem</h2>
<p>Building recent searches experience can be trickier than you think, recent-searches module helps you easily build that experience and handle the edge cases while also giving you flexibility on how to rank those suggestions. Since I couldn't find a good existing solution I decided to build one.</p>
<h2 id="this-solution">This solution</h2>
<p>recent-searches is a module that handles storing, retrieving and ranking of recent searches. If available, it uses <a href="https://developer.mozilla.org/en-US/docs/Web/API/Window/localStorage">localStorage</a> to store suggestions cross sessions and in the rare cases where it might not be available uses a fallback memory storage, thus loosing it's cross session functionality.</p>
<p>The module handles expiry of searches, ranking of results and degrading their ranking through their lifecycle as well as a simple prefix search.</p>
<h2 id="table-of-contents">Table of Contents</h2>
<!-- START doctoc -->
<!-- END doctoc -->
<h2 id="installation">Installation</h2>
<p>recent-searches is published on npm's public registry, you can install it as a dependancy of your project with the following command.</p>
<pre><code>npm <span class="hljs-keyword">install</span> <span class="hljs-comment">--save recent-searches</span></code></pre><h2 id="usage">Usage</h2>
<blockquote>
<p><a href="https://codesandbox.io/s/6z67jvklw3">Try it out in the browser</a></p>
</blockquote>
<p>Initializing the module</p>
<pre><code class="language-ts"><span class="hljs-keyword">import</span> RecentSearches <span class="hljs-keyword">from</span> <span class="hljs-string">'recent-searches'</span>
<span class="hljs-keyword">const</span> searches = <span class="hljs-keyword">new</span> RecentSearches({
ttl: <span class="hljs-built_in">number</span>, <span class="hljs-comment">// Optional: ttl of searches in milliseconds, default to 1h (1000 * 60 * 60)</span>
limit: <span class="hljs-built_in">number</span>, <span class="hljs-comment">// Optional: max number of entries that will be persisted, defaults is 10</span>
<span class="hljs-keyword">namespace</span>: <span class="hljs-built_in">string</span>, <span class="hljs-comment">// Optional: custom localStorage namespace</span>
rankBy: <span class="hljs-built_in">string</span> <span class="hljs-comment">// Optional: ranking strategy of recent searches, "PROXIMITY" | "TIME" | "PROXIMITY_AND_TIME", default is "PROXIMITY_AND_TIME"</span>
})
</code></pre>
<p>Setting and retrieving relevant searches.</p>
<pre><code class="language-ts"><span class="hljs-comment">// To retrieve searches for a given query</span>
<span class="hljs-keyword">const</span> previousSearchesForJohn = searches.getRecentSearches(<span class="hljs-string">"John"</span>)
<span class="hljs-comment">// [{query: "John", timestamp: ...}, {query: "Marc John", timestamp: ...}] </span>
<span class="hljs-comment">// To set a recent search</span>
searches.setRecentSearch(<span class="hljs-string">"John"</span>, resultData)</code></pre>
<h2 id="basic-props">Basic Props</h2>
<p>This is the list of props that you should probably know about. There are some
<a href="#advanced-props">advanced props</a> below as well.</p>
<h3 id="children">children</h3>
<blockquote>
<p><code>function({})</code> | <em>required</em></p>
</blockquote>
<p>This is called with an object. Read more about the properties of this object in
the section "<a href="#children-function">Children Function</a>".</p>
<h3 id="itemtostring">itemToString</h3>
<blockquote>
<p><code>function(item: any)</code> | defaults to: <code>i => (i == null ? '' : String(i))</code></p>
</blockquote>
<p>Used to determine the string value for the selected item (which is used to
compute the <code>inputValue</code>).</p>
<h3 id="onchange">onChange</h3>
<blockquote>
<p><code>function(selectedItem: any, stateAndHelpers: object)</code> | optional, no useful
default</p>
</blockquote>
<p>Called when the user selects an item and the selected item has changed. Called
with the item that was selected and the new state of <code>recent-searches</code>. (see
<code>onStateChange</code> for more info on <code>stateAndHelpers</code>).</p>
<ul>
<li><code>selectedItem</code>: The item that was just selected</li>
<li><code>stateAndHelpers</code>: This is the same thing your <code>children</code> function is
called with (see <a href="#children-function">Children Function</a>)</li>
</ul>
<h3 id="statereducer">stateReducer</h3>
<blockquote>
<p><code>function(state: object, changes: object)</code> | optional</p>
</blockquote>
<p><strong>🚨 This is a really handy power feature 🚨</strong></p>
<p>This function will be called each time <code>recent-searches</code> sets its internal state
(or calls your <code>onStateChange</code> handler for control props). It allows you to
modify the state change that will take place which can give you fine grain
control over how the component interacts with user updates without having to
use <a href="#control-props">Control Props</a>. It gives you the current state and the
state that will be set, and you return the state that you want to set.</p>
<ul>
<li><code>state</code>: The full current state of recent-searches.</li>
<li><code>changes</code>: These are the properties that are about to change. This also has a
<code>type</code> property which you can learn more about in the
<a href="#statechangetypes"><code>stateChangeTypes</code></a> section.</li>
</ul>
<pre><code class="language-jsx"><span class="hljs-keyword">const</span> ui = (
<span class="xml"><span class="hljs-tag"><<span class="hljs-name">recent-searches</span> <span class="hljs-attr">stateReducer</span>=<span class="hljs-string">{stateReducer}</span>></span>{/* your callback */}<span class="hljs-tag"></<span class="hljs-name">recent-searches</span>></span>
)
function stateReducer(state, changes) {
// this prevents the menu from being closed when the user
// selects an item with a keyboard or mouse
switch (changes.type) {
case recent-searches.stateChangeTypes.keyDownEnter:
case recent-searches.stateChangeTypes.clickItem:
return {
...changes,
isOpen: state.isOpen,
highlightedIndex: state.highlightedIndex,
}
default:
return changes
}
}</span></code></pre>
<blockquote>
<p>NOTE: This is only called when state actually changes. You should not attempt
to use this to handle events. If you wish to handle events, put your event
handlers directly on the elements (make sure to use the prop getters though!
For example: <code><input onBlur={handleBlur} /></code> should be
<code><input {...getInputProps({onBlur: handleBlur})} /></code>). Also, your reducer
function should be "pure." This means it should do nothing other than return
the state changes you want to have happen.</p>
</blockquote>
<h2 id="advanced-props">Advanced Props</h2>
<h3 id="initialselecteditem">initialSelectedItem</h3>
<blockquote>
<p><code>any</code> | defaults to <code>null</code></p>
</blockquote>
<p>Pass an item or an array of items that should be selected when recent-searches is initialized.</p>
<h3 id="initialinputvalue">initialInputValue</h3>
<blockquote>
<p><code>string</code> | defaults to <code>''</code></p>
</blockquote>
<p>This is the initial input value when recent-searches is initialized.</p>
<h3 id="initialhighlightedindex">initialHighlightedIndex</h3>
<blockquote>
<p><code>number</code>/<code>null</code> | defaults to <code>defaultHighlightedIndex</code></p>
</blockquote>
<p>This is the initial value to set the highlighted index to when recent-searches is initialized.</p>
<h3 id="initialisopen">initialIsOpen</h3>
<blockquote>
<p><code>boolean</code> | defaults to <code>defaultIsOpen</code></p>
</blockquote>
<p>This is the initial <code>isOpen</code> value when recent-searches is initialized.</p>
<h3 id="defaulthighlightedindex">defaultHighlightedIndex</h3>
<blockquote>
<p><code>number</code>/<code>null</code> | defaults to <code>null</code></p>
</blockquote>
<p>This is the value to set the <code>highlightedIndex</code> to anytime recent-searches is reset,
when the the selection is cleared, when an item is selected or when the inputValue is changed.</p>
<h3 id="defaultisopen">defaultIsOpen</h3>
<blockquote>
<p><code>boolean</code> | defaults to <code>false</code></p>
</blockquote>
<p>This is the value to set the <code>isOpen</code> to anytime recent-searches is reset, when the
the selection is cleared, or when an item is selected.</p>
<h3 id="selecteditemchanged">selectedItemChanged</h3>
<blockquote>
<p><code>function(prevItem: any, item: any)</code> | defaults to: <code>(prevItem, item) => (prevItem !== item)</code></p>
</blockquote>
<p>Used to determine if the new <code>selectedItem</code> has changed compared to the previous
<code>selectedItem</code> and properly update recent-searches's internal state.</p>
<h3 id="geta11ystatusmessage">getA11yStatusMessage</h3>
<blockquote>
<p><code>function({/* see below */})</code> | default messages provided in English</p>
</blockquote>
<p>This function is passed as props to a <code>Status</code> component nested within and
allows you to create your own assertive ARIA statuses.</p>
<p>A default <code>getA11yStatusMessage</code> function is provided that will check
<code>resultCount</code> and return "No results." or if there are results but no item is
highlighted, "<code>resultCount</code> results are available, use up and down arrow keys to
navigate." If an item is highlighted it will run <code>itemToString(highlightedItem)</code>
and display the value of the <code>highlightedItem</code>.</p>
<p>The object you are passed to generate your status message has the following
properties:</p>
<!-- This table was generated via http://www.tablesgenerator.com/markdown_tables -->
<table>
<thead>
<tr>
<th>property</th>
<th>type</th>
<th>description</th>
</tr>
</thead>
<tbody><tr>
<td><code>highlightedIndex</code></td>
<td><code>number</code>/<code>null</code></td>
<td>The currently highlighted index</td>
</tr>
<tr>
<td><code>highlightedItem</code></td>
<td><code>any</code></td>
<td>The value of the highlighted item</td>
</tr>
<tr>
<td><code>inputValue</code></td>
<td><code>string</code></td>
<td>The current input value</td>
</tr>
<tr>
<td><code>isOpen</code></td>
<td><code>boolean</code></td>
<td>The <code>isOpen</code> state</td>
</tr>
<tr>
<td><code>itemToString</code></td>
<td><code>function(any)</code></td>
<td>The <code>itemToString</code> function (see props) for getting the string value from one of the options</td>
</tr>
<tr>
<td><code>previousResultCount</code></td>
<td><code>number</code></td>
<td>The total items showing in the dropdown the last time the status was updated</td>
</tr>
<tr>
<td><code>resultCount</code></td>
<td><code>number</code></td>
<td>The total items showing in the dropdown</td>
</tr>
<tr>
<td><code>selectedItem</code></td>
<td><code>any</code></td>
<td>The value of the currently selected item</td>
</tr>
</tbody></table>
<h3 id="onselect">onSelect</h3>
<blockquote>
<p><code>function(selectedItem: any, stateAndHelpers: object)</code> | optional, no useful
default</p>
</blockquote>
<p>Called when the user selects an item, regardless of the previous selected item.
Called with the item that was selected and the new state of <code>recent-searches</code>. (see
<code>onStateChange</code> for more info on <code>stateAndHelpers</code>).</p>
<ul>
<li><code>selectedItem</code>: The item that was just selected</li>
<li><code>stateAndHelpers</code>: This is the same thing your <code>children</code> function is
called with (see <a href="#children-function">Children Function</a>)</li>
</ul>
<h3 id="onstatechange">onStateChange</h3>
<blockquote>
<p><code>function(changes: object, stateAndHelpers: object)</code> | optional, no useful
default</p>
</blockquote>
<p>This function is called anytime the internal state changes. This can be useful
if you're using recent-searches as a "controlled" component, where you manage some or
all of the state (e.g. isOpen, selectedItem, highlightedIndex, etc) and then
pass it as props, rather than letting recent-searches control all its state itself.
The parameters both take the shape of internal state (<code>{highlightedIndex: number, inputValue: string, isOpen: boolean, selectedItem: any}</code>) but differ
slightly.</p>
<ul>
<li><code>changes</code>: These are the properties that actually have changed since the last
state change. This also has a <code>type</code> property which you can learn more about
in the <a href="#statechangetypes"><code>stateChangeTypes</code></a> section.</li>
<li><code>stateAndHelpers</code>: This is the exact same thing your <code>children</code> function is
called with (see <a href="#children-function">Children Function</a>)</li>
</ul>
<blockquote>
<p>Tip: This function will be called any time <em>any</em> state is changed. The best
way to determine whether any particular state was changed, you can use
<code>changes.hasOwnProperty('propName')</code>.</p>
</blockquote>
<blockquote>
<p>NOTE: This is only called when state actually changes. You should not attempt
to use this to handle events. If you wish to handle events, put your event
handlers directly on the elements (make sure to use the prop getters though!
For example: <code><input onBlur={handleBlur} /></code> should be
<code><input {...getInputProps({onBlur: handleBlur})} /></code>).</p>
</blockquote>
<h3 id="oninputvaluechange">onInputValueChange</h3>
<blockquote>
<p><code>function(inputValue: string, stateAndHelpers: object)</code> | optional, no useful
default</p>
</blockquote>
<p>Called whenever the input value changes. Useful to use instead or in combination
of <code>onStateChange</code> when <code>inputValue</code> is a controlled prop to
<a href="https://github.com/recent-searches-js/recent-searches/issues/217">avoid issues with cursor positions</a>.</p>
<ul>
<li><code>inputValue</code>: The current value of the input</li>
<li><code>stateAndHelpers</code>: This is the same thing your <code>children</code> function is
called with (see <a href="#children-function">Children Function</a>)</li>
</ul>
<h3 id="itemcount">itemCount</h3>
<blockquote>
<p><code>number</code> | optional, defaults the number of times you call getItemProps</p>
</blockquote>
<p>This is useful if you're using some kind of virtual listing component for
"windowing" (like
<a href="https://github.com/bvaughn/react-virtualized"><code>react-virtualized</code></a>).</p>
<h3 id="highlightedindex">highlightedIndex</h3>
<blockquote>
<p><code>number</code> | <strong>control prop</strong> (read more about this in
<a href="#control-props">the Control Props section</a>)</p>
</blockquote>
<p>The index that should be highlighted</p>
<h3 id="inputvalue">inputValue</h3>
<blockquote>
<p><code>string</code> | <strong>control prop</strong> (read more about this in
<a href="#control-props">the Control Props section</a>)</p>
</blockquote>
<p>The value the input should have</p>
<h3 id="isopen">isOpen</h3>
<blockquote>
<p><code>boolean</code> | <strong>control prop</strong> (read more about this in
<a href="#control-props">the Control Props section</a>)</p>
</blockquote>
<p>Whether the menu should be considered open or closed. Some aspects of the
recent-searches component respond differently based on this value (for example, if
<code>isOpen</code> is true when the user hits "Enter" on the input field, then the item at
the <code>highlightedIndex</code> item is selected).</p>
<h3 id="selecteditem">selectedItem</h3>
<blockquote>
<p><code>any</code>/<code>Array(any)</code> | <strong>control prop</strong> (read more about this in
<a href="#control-props">the Control Props section</a>)</p>
</blockquote>
<p>The currently selected item.</p>
<h3 id="id">id</h3>
<blockquote>
<p><code>string</code> | defaults to a generated ID</p>
</blockquote>
<p>You should not normally need to set this prop. It's only useful if you're server
rendering items (which each have an <code>id</code> prop generated based on the <code>recent-searches</code>
<code>id</code>). For more information see the <code>FAQ</code> below.</p>
<h3 id="inputid">inputId</h3>
<blockquote>
<p><code>string</code> | defaults to a generated ID</p>
</blockquote>
<p>Used for <code>aria</code> attributes and the <code>id</code> prop of the element (<code>input</code>) you use
<a href="#getinputprops"><code>getInputProps</code></a> with.</p>
<h3 id="labelid">labelId</h3>
<blockquote>
<p><code>string</code> | defaults to a generated ID</p>
</blockquote>
<p>Used for <code>aria</code> attributes and the <code>id</code> prop of the element (<code>label</code>) you use
<a href="#getlabelprops"><code>getLabelProps</code></a> with.</p>
<h3 id="menuid">menuId</h3>
<blockquote>
<p><code>string</code> | defaults to a generated ID</p>
</blockquote>
<p>Used for <code>aria</code> attributes and the <code>id</code> prop of the element (<code>ul</code>) you use
<a href="#getmenuprops"><code>getMenuProps</code></a> with.</p>
<h3 id="getitemid">getItemId</h3>
<blockquote>
<p><code>function(index)</code> | defaults to a function that generates an ID based on the index</p>
</blockquote>
<p>Used for <code>aria</code> attributes and the <code>id</code> prop of the element (<code>li</code>) you use
<a href="#getinputprops"><code>getInputProps</code></a> with.</p>
<h3 id="environment">environment</h3>
<blockquote>
<p><code>window</code> | defaults to <code>window</code></p>
</blockquote>
<p>This prop is only useful if you're rendering recent-searches within a different <code>window</code> context from where your JavaScript is running; for example, an iframe or a shadow-root. If the given context is lacking <code>document</code> and/or <code>add|removeEventListener</code> on its prototype (as is the case for a shadow-root) then you will need to pass in a custom object that is able to provide <a href="https://gist.github.com/Rendez/1dd55882e9b850dd3990feefc9d6e177">access to these properties</a> for recent-searches.</p>
<h3 id="onouterclick">onOuterClick</h3>
<blockquote>
<p><code>function(stateAndHelpers: object)</code> | optional</p>
</blockquote>
<p>A helper callback to help control internal state of recent-searches like <code>isOpen</code> as
mentioned in <a href="https://github.com/recent-searches-js/recent-searches/issues/206">this issue</a>. The
same behavior can be achieved using <code>onStateChange</code>, but this prop is provided
as a helper because it's a fairly common use-case if you're controlling the
<code>isOpen</code> state:</p>
<pre><code class="language-jsx"><span class="hljs-keyword">const</span> ui = (
<span class="xml"><span class="hljs-tag"><<span class="hljs-name">recent-searches</span>
<span class="hljs-attr">isOpen</span>=<span class="hljs-string">{this.state.menuIsOpen}</span>
<span class="hljs-attr">onOuterClick</span>=<span class="hljs-string">{()</span> =></span> this.setState({menuIsOpen: false})}
>
{/* your callback */}
<span class="hljs-tag"></<span class="hljs-name">recent-searches</span>></span>
)</span></code></pre>
<p>This callback will only be called if <code>isOpen</code> is <code>true</code>.</p>
<h3 id="scrollintoview">scrollIntoView</h3>
<blockquote>
<p><code>function(node: HTMLElement, menuNode: HTMLElement)</code> | defaults to internal
implementation</p>
</blockquote>
<p>This allows you to customize how the scrolling works when the highlighted index
changes. It receives the node to be scrolled to and the root node (the root
node you render in recent-searches). Internally we use
<a href="https://www.npmjs.com/package/compute-scroll-into-view"><code>compute-scroll-into-view</code></a>
so if you use that package then you wont be adding any additional bytes to your
bundle :)</p>
<h2 id="statechangetypes">stateChangeTypes</h2>
<p>There are a few props that expose changes to state
(<a href="#onstatechange"><code>onStateChange</code></a> and <a href="#statereducer"><code>stateReducer</code></a>).
For you to make the most of these APIs, it's important for you to understand
why state is being changed. To accomplish this, there's a <code>type</code> property on the
<code>changes</code> object you get. This <code>type</code> corresponds to a
<code>recent-searches.stateChangeTypes</code> property.</p>
<p>The list of all possible values this <code>type</code> property can take is defined in
<a href="https://github.com/recent-searches-js/recent-searches/blob/master/src/stateChangeTypes.js">this file</a>
and is as follows:</p>
<ul>
<li><code>recent-searches.stateChangeTypes.unknown</code></li>
<li><code>recent-searches.stateChangeTypes.mouseUp</code></li>
<li><code>recent-searches.stateChangeTypes.itemMouseEnter</code></li>
<li><code>recent-searches.stateChangeTypes.keyDownArrowUp</code></li>
<li><code>recent-searches.stateChangeTypes.keyDownArrowDown</code></li>
<li><code>recent-searches.stateChangeTypes.keyDownEscape</code></li>
<li><code>recent-searches.stateChangeTypes.keyDownEnter</code></li>
<li><code>recent-searches.stateChangeTypes.clickItem</code></li>
<li><code>recent-searches.stateChangeTypes.blurInput</code></li>
<li><code>recent-searches.stateChangeTypes.changeInput</code></li>
<li><code>recent-searches.stateChangeTypes.keyDownSpaceButton</code></li>
<li><code>recent-searches.stateChangeTypes.clickButton</code></li>
<li><code>recent-searches.stateChangeTypes.blurButton</code></li>
<li><code>recent-searches.stateChangeTypes.controlledPropUpdatedSelectedItem</code></li>
<li><code>recent-searches.stateChangeTypes.touchEnd</code></li>
</ul>
<p>See <a href="#statereducer"><code>stateReducer</code></a> for a concrete example on how to use the
<code>type</code> property.</p>
<h2 id="control-props">Control Props</h2>
<p>recent-searches manages its own state internally and calls your <code>onChange</code> and
<code>onStateChange</code> handlers with any relevant changes. The state that recent-searches
manages includes: <code>isOpen</code>, <code>selectedItem</code>, <code>inputValue</code>, and
<code>highlightedIndex</code>. Your Children function (read more below) can be used to
manipulate this state and can likely support many of your use cases.</p>
<p>However, if more control is needed, you can pass any of these pieces of state as
a prop (as indicated above) and that state becomes controlled. As soon as
<code>this.props[statePropKey] !== undefined</code>, internally, <code>recent-searches</code> will determine
its state based on your prop's value rather than its own internal state. You
will be required to keep the state up to date (this is where <code>onStateChange</code>
comes in really handy), but you can also control the state from anywhere, be
that state from other components, <code>redux</code>, <code>react-router</code>, or anywhere else.</p>
<blockquote>
<p>Note: This is very similar to how normal controlled components work elsewhere
in react (like <code><input /></code>). If you want to learn more about this concept, you
can learn about that from this the
<a href="#advanced-react-component-patterns-course">Advanced React Component Patterns course</a></p>
</blockquote>
<h2 id="children-function">Children Function</h2>
<p>This is where you render whatever you want to based on the state of <code>recent-searches</code>.
You use it like so:</p>
<pre><code class="language-javascript"><span class="hljs-keyword">const</span> ui = (
<span class="xml"><span class="hljs-tag"><<span class="hljs-name">recent-searches</span>></span>
{recent-searches => (
// use recent-searches utilities and state here, like recent-searches.isOpen,
// recent-searches.getInputProps, etc.
<span class="hljs-tag"><<span class="hljs-name">div</span>></span>{/* more jsx here */}<span class="hljs-tag"></<span class="hljs-name">div</span>></span>
)}
<span class="hljs-tag"></<span class="hljs-name">recent-searches</span>></span>
)</span></code></pre>
<p>The properties of this <code>recent-searches</code> object can be split into three categories as
indicated below:</p>
<h3 id="prop-getters">prop getters</h3>
<blockquote>
<p>See
<a href="https://blog.kentcdodds.com/how-to-give-rendering-control-to-users-with-prop-getters-549eaef76acf">the blog post about prop getters</a></p>
</blockquote>
<blockquote>
<p>NOTE: These prop-getters provide important <code>aria-</code> attributes which are very
important to your component being accessible. It's recommended that you
utilize these functions and apply the props they give you to your components.</p>
</blockquote>
<p>These functions are used to apply props to the elements that you render. This
gives you maximum flexibility to render what, when, and wherever you like. You
call these on the element in question (for example: <code><input {...getInputProps()}</code>)). It's advisable to pass all your props to that function
rather than applying them on the element yourself to avoid your props being
overridden (or overriding the props returned). For example:
<code>getInputProps({onKeyUp(event) {console.log(event)}})</code>.</p>
<!-- This table was generated via http://www.tablesgenerator.com/markdown_tables -->
<table>
<thead>
<tr>
<th>property</th>
<th>type</th>
<th>description</th>
</tr>
</thead>
<tbody><tr>
<td><code>getToggleButtonProps</code></td>
<td><code>function({})</code></td>
<td>returns the props you should apply to any menu toggle button element you render.</td>
</tr>
<tr>
<td><code>getInputProps</code></td>
<td><code>function({})</code></td>
<td>returns the props you should apply to the <code>input</code> element that you render.</td>
</tr>
<tr>
<td><code>getItemProps</code></td>
<td><code>function({})</code></td>
<td>returns the props you should apply to any menu item elements you render.</td>
</tr>
<tr>
<td><code>getLabelProps</code></td>
<td><code>function({})</code></td>
<td>returns the props you should apply to the <code>label</code> element that you render.</td>
</tr>
<tr>
<td><code>getMenuProps</code></td>
<td><code>function({},{})</code></td>
<td>returns the props you should apply to the <code>ul</code> element (or root of your menu) that you render.</td>
</tr>
<tr>
<td><code>getRootProps</code></td>
<td><code>function({},{})</code></td>
<td>returns the props you should apply to the root element that you render. It can be optional.</td>
</tr>
</tbody></table>
<h4 id="getrootprops"><code>getRootProps</code></h4>
<details>
<summary>
If you cannot render a div as the root element, then read this
</summary>
<p>Most of the time, you can just render a <code>div</code> yourself and <code>recent-searches</code> will
apply the props it needs to do its job (and you don't need to call this
function). However, if you're rendering a composite component (custom component)
as the root element, then you'll need to call <code>getRootProps</code> and apply that to
your root element (recent-searches will throw an error otherwise).</p>
<p>There are no required properties for this method.</p>
<p>Optional properties:</p>
<ul>
<li><code>refKey</code>: if you're rendering a composite component, that component will need
to accept a prop which it forwards to the root DOM element. Commonly, folks
call this <code>innerRef</code>. So you'd call: <code>getRootProps({refKey: 'innerRef'})</code> and
your composite component would forward like: <code><div ref={props.innerRef} /></code></li>
</ul>
<p>If you're rendering a composite component, <code>recent-searches</code> checks that
<code>getRootProps</code> is called and that <code>refKey</code> is a prop of the returned composite
component. This is done to catch common causes of errors but, in some cases, the
check could fail even if the ref is correctly forwarded to the root DOM
component. In these cases, you can provide the object <code>{suppressRefError : true}</code> as the second argument to <code>getRootProps</code> to completely bypass the check.\
<strong>Please use it with extreme care and only if you are absolutely sure that the ref
is correctly forwarded otherwise <code>recent-searches</code> will unexpectedly fail.</strong>\
See <a href="https://github.com/recent-searches-js/recent-searches/issues/235">#235</a> for the discussion that lead to this.</p>
</details>
<h4 id="getinputprops"><code>getInputProps</code></h4>
<p>This method should be applied to the <code>input</code> you render. It is recommended that
you pass all props as an object to this method which will compose together any
of the event handlers you need to apply to the <code>input</code> while preserving the ones
that <code>recent-searches</code> needs to apply to make the <code>input</code> behave.</p>
<p>There are no required properties for this method.</p>
<p>Optional properties:</p>
<ul>
<li><code>disabled</code>: If this is set to true, then no event handlers will be returned
from <code>getInputProps</code> and a <code>disabled</code> prop will be returned (effectively
disabling the input).</li>
</ul>
<h4 id="getlabelprops"><code>getLabelProps</code></h4>
<p>This method should be applied to the <code>label</code> you render. It is useful for
ensuring that the <code>for</code> attribute on the <code><label></code> (<code>htmlFor</code> as a react prop)
is the same as the <code>id</code> that appears on the <code>input</code>. If no <code>htmlFor</code> is provided
(the normal case) then an ID will be generated and used for the <code>input</code> and the
<code>label</code> <code>for</code> attribute.</p>
<p>There are no required properties for this method.</p>
<blockquote>
<p>Note: For accessibility purposes, calling this method is highly recommended.</p>
</blockquote>
<h4 id="getmenuprops"><code>getMenuProps</code></h4>
<p>This method should be applied to the element which contains your list of items.
Typically, this will be a <code><div></code> or a <code><ul></code> that surrounds a <code>map</code> expression.
This handles the proper ARIA roles and attributes.</p>
<p>Optional properties:</p>
<ul>
<li><p><code>refKey</code>: if you're rendering a composite component, that component will need
to accept a prop which it forwards to the root DOM element. Commonly, folks
call this <code>innerRef</code>. So you'd call: <code>getMenuProps({refKey: 'innerRef'})</code> and
your composite component would forward like: <code><ul ref={props.innerRef} /></code>.
However, if you are just rendering a primitive component like <code><div></code>, there
is no need to specify this property.</p>
<p>Please keep in mind that menus, for accessiblity purposes, should always be
rendered, regardless of whether you hide it or not. Otherwise, <code>getMenuProps</code>
may throw error if you unmount and remount the menu.</p>
</li>
<li><p><code>aria-label</code>: By default the menu will add an <code>aria-labelledby</code> that refers
to the <code><label></code> rendered with <code>getLabelProps</code>. However, if you provide
<code>aria-label</code> to give a more specific label that describes the options
available, then <code>aria-labelledby</code> will not be provided and screen readers
can use your <code>aria-label</code> instead.</p>
</li>
</ul>
<p>In some cases, you might want to completely bypass the <code>refKey</code> check. Then you
can provide the object <code>{suppressRefError : true}</code> as the second argument to
<code>getMenuProps</code>.
<strong>Please use it with extreme care and only if you are absolutely sure that the ref
is correctly forwarded otherwise <code>recent-searches</code> will unexpectedly fail.</strong></p>
<pre><code class="language-jsx"><ul {...getMenuProps()}>
{!isOpen
? <span class="hljs-literal">null</span>
: items.map(<span class="hljs-function">(<span class="hljs-params">item, index</span>) =></span> (
<span class="xml"><span class="hljs-tag"><<span class="hljs-name">li</span> {<span class="hljs-attr">...getItemProps</span>({<span class="hljs-attr">item</span>, <span class="hljs-attr">index</span>, <span class="hljs-attr">key:</span> <span class="hljs-attr">item.id</span>})}></span>{item.name}<span class="hljs-tag"></<span class="hljs-name">li</span>></span></span>
))}
<<span class="hljs-regexp">/ul></span></code></pre>
<blockquote>
<p>Note that for accessibility reasons it's best if you always render this
element whether or not recent-searches is in an <code>isOpen</code> state.</p>
</blockquote>
<h4 id="getitemprops"><code>getItemProps</code></h4>
<p>The props returned from calling this function should be applied to any menu
items you render.</p>
<p><strong>This is an impure function</strong>, so it should only be called when you will
actually be applying the props to an item.</p>
<details>
<summary>What do you mean by impure function?</summary>
<p>Basically just don't do this:</p>
<pre><code class="language-jsx">items.map(<span class="hljs-function"><span class="hljs-params">item</span> =></span> {
<span class="hljs-keyword">const</span> props = getItemProps({item}) <span class="hljs-comment">// we're calling it here</span>
<span class="hljs-keyword">if</span> (!shouldRenderItem(item)) {
<span class="hljs-keyword">return</span> <span class="hljs-literal">null</span> <span class="hljs-comment">// but we're not using props, and recent-searches thinks we are...</span>
}
<span class="hljs-keyword">return</span> <span class="xml"><span class="hljs-tag"><<span class="hljs-name">div</span> {<span class="hljs-attr">...props</span>} /></span>
})</span></code></pre>
<p>Instead, you could do this:</p>
<pre><code class="language-jsx">items.filter(shouldRenderItem).map(<span class="hljs-function"><span class="hljs-params">item</span> =></span> <div {...getItemProps({item})} />)</code></pre>
</details>
<p>Required properties:</p>
<ul>
<li><code>item</code>: this is the item data that will be selected when the user selects a
particular item.</li>
</ul>
<p>Optional properties:</p>
<ul>
<li><code>index</code>: This is how <code>recent-searches</code> keeps track of your item when updating the
<code>highlightedIndex</code> as the user keys around. By default, <code>recent-searches</code> will
assume the <code>index</code> is the order in which you're calling <code>getItemProps</code>. This
is often good enough, but if you find odd behavior, try setting this
explicitly. It's probably best to be explicit about <code>index</code> when using a
windowing library like <code>react-virtualized</code>.</li>
<li><code>disabled</code>: If this is set to <code>true</code>, then all of the recent-searches item event
handlers will be omitted. Items will not be highlighted when hovered,
and items will not be selected when clicked.</li>
</ul>
<h4 id="gettogglebuttonprops"><code>getToggleButtonProps</code></h4>
<p>Call this and apply the returned props to a <code>button</code>. It allows you to toggle
the <code>Menu</code> component. You can definitely build something like this yourself (all
of the available APIs are exposed to you), but this is nice because it will also
apply all of the proper ARIA attributes.</p>
<p>Optional properties:</p>
<ul>
<li><code>disabled</code>: If this is set to <code>true</code>, then all of the recent-searches button event
handlers will be omitted (it wont toggle the menu when clicked).</li>
<li><code>aria-label</code>: The <code>aria-label</code> prop is in English. You should probably override
this yourself so you can provide translations:</li>
</ul>
<pre><code class="language-jsx"><span class="hljs-keyword">const</span> myButton = (
<span class="xml"><span class="hljs-tag"><<span class="hljs-name">button</span>
{<span class="hljs-attr">...getToggleButtonProps</span>({
'<span class="hljs-attr">aria-label</span>'<span class="hljs-attr">:</span> <span class="hljs-attr">translateWithId</span>(<span class="hljs-attr">isOpen</span> ? '<span class="hljs-attr">close.menu</span>' <span class="hljs-attr">:</span> '<span class="hljs-attr">open.menu</span>'),
})}
/></span>
)</span></code></pre>
<h3 id="actions">actions</h3>
<p>These are functions you can call to change the state of the recent-searches component.</p>
<!-- This table was generated via http://www.tablesgenerator.com/markdown_tables -->
<table>
<thead>
<tr>
<th>property</th>
<th>type</th>
<th>description</th>
</tr>
</thead>
<tbody><tr>
<td><code>clearSelection</code></td>
<td><code>function(cb: Function)</code></td>
<td>clears the selection</td>
</tr>
<tr>
<td><code>clearItems</code></td>
<td><code>function()</code></td>
<td>Clears recent-searches's record of all the items. Only really useful if you render your items asynchronously within recent-searches. See <a href="https://github.com/recent-searches-js/recent-searches/issues/186">#186</a></td>
</tr>
<tr>
<td><code>closeMenu</code></td>
<td><code>function(cb: Function)</code></td>
<td>closes the menu</td>
</tr>
<tr>
<td><code>openMenu</code></td>
<td><code>function(cb: Function)</code></td>
<td>opens the menu</td>
</tr>
<tr>
<td><code>selectHighlightedItem</code></td>
<td><code>function(otherStateToSet: object, cb: Function)</code></td>
<td>selects the item that is currently highlighted</td>
</tr>
<tr>
<td><code>selectItem</code></td>
<td><code>function(item: any, otherStateToSet: object, cb: Function)</code></td>
<td>selects the given item</td>
</tr>
<tr>
<td><code>selectItemAtIndex</code></td>
<td><code>function(index: number, otherStateToSet: object, cb: Function)</code></td>
<td>selects the item at the given index</td>
</tr>
<tr>
<td><code>setHighlightedIndex</code></td>
<td><code>function(index: number, otherStateToSet: object, cb: Function)</code></td>
<td>call to set a new highlighted index</td>
</tr>
<tr>
<td><code>toggleMenu</code></td>
<td><code>function(otherStateToSet: object, cb: Function)</code></td>
<td>toggle the menu open state</td>
</tr>
<tr>
<td><code>reset</code></td>
<td><code>function(otherStateToSet: object, cb: Function)</code></td>
<td>this resets recent-searches's state to a reasonable default</td>
</tr>
<tr>
<td><code>setItemCount</code></td>
<td><code>function(count: number)</code></td>
<td>this sets the <code>itemCount</code>. Handy in situations where you're using windowing and the items are loaded asynchronously from within recent-searches (so you can't use the <code>itemCount</code> prop.</td>
</tr>
<tr>
<td><code>unsetItemCount</code></td>
<td><code>function()</code></td>
<td>this unsets the <code>itemCount</code> which means the item count will be calculated instead by the <code>itemCount</code> prop or based on how many times you call <code>getItemProps</code>.</td>
</tr>
<tr>
<td><code>setState</code></td>
<td><code>function(stateToSet: object, cb: Function)</code></td>
<td>This is a general <code>setState</code> function. It uses recent-searches's <code>internalSetState</code> function which works with control props and calls your <code>onSelect</code>, <code>onChange</code>, etc. (Note, you can specify a <code>type</code> which you can reference in some other APIs like the <code>stateReducer</code>).</td>
</tr>
</tbody></table>
<blockquote>
<p><code>otherStateToSet</code> refers to an object to set other internal state. It is
recommended to avoid abusing this, but is available if you need it.</p>
</blockquote>
<h3 id="state">state</h3>
<p>These are values that represent the current state of the recent-searches component.</p>
<!-- This table was generated via http://www.tablesgenerator.com/markdown_tables -->
<table>
<thead>
<tr>
<th>property</th>
<th>type</th>
<th>description</th>
</tr>
</thead>
<tbody><tr>
<td><code>highlightedIndex</code></td>
<td><code>number</code> / <code>null</code></td>
<td>the currently highlighted item</td>
</tr>
<tr>
<td><code>inputValue</code></td>
<td><code>string</code> / <code>null</code></td>
<td>the current value of the <code>getInputProps</code> input</td>
</tr>
<tr>
<td><code>isOpen</code></td>
<td><code>boolean</code></td>
<td>the menu open state</td>
</tr>
<tr>
<td><code>selectedItem</code></td>
<td><code>any</code></td>
<td>the currently selected item input</td>
</tr>
</tbody></table>
<h3 id="props">props</h3>
<p>As a convenience, the <code>id</code> and <code>itemToString</code> props which you pass to
<code><recent-searches /></code> are available here as well.</p>
<h2 id="event-handlers">Event Handlers</h2>
<p>recent-searches has a few events for which it provides implicit handlers. Several of
these handlers call <code>event.preventDefault()</code>. Their additional functionality is
described below.</p>
<h3 id="default-handlers">default handlers</h3>
<ul>
<li><p><code>ArrowDown</code>: if menu is closed, opens it and moves the highlighted index to
<code>defaultHighlightedIndex + 1</code>, if <code>defaultHighlightedIndex</code> is provided, or
to the top-most item, if not. If menu is open, it moves the highlighted index
down by 1. If the shift key is held when this event fires, the highlighted
index will jump down 5 indices instead of 1. NOTE: if the current highlighed
index is within the bottom 5 indices, the top-most index will be highlighted.)</p>
</li>
<li><p><code>ArrowUp</code>: if menu is closed, opens it and moves the highlighted index to
<code>defaultHighlightedIndex - 1</code>, if <code>defaultHighlightedIndex</code> is provided, or
to the bottom-most item, if not. If menu is open, moves the highlighted index
up by 1. If the shift key is held when this event fires, the highlighted
index will jump up 5 indices instead of 1. NOTE: if the current highlighed
index is within the top 5 indices, the bottom-most index will be highlighted.)</p>
</li>
<li><p><code>Home</code>: if menu is closed, it will not add any other behavior. If menu is open,