Typeahead is auto suggestion or completion based on what the user is starting to type, gets refined as the user types more.
<%= pb_rails("typeahead", props: { label: "user", name: :foo, data: { typeahead_example: true }, input_options: { classname: "my-typeahead-class", data: { typeahead_testing: "data field test" }, id: "typeahead-input-id-test", }, })%> <br><br><br> <%= pb_rails("card", props: { padding: "xl", data: { typeahead_example_selected_option: true } }) do %> <%= pb_rails("body") do %> Use the above input to search for users on Github, and see the results as you type. <% end %> <%= pb_rails("body") do %> When you make a selection, you will see it appear in the list below <% end %> <div data-selected-option></div> <% end %> <template data-typeahead-example-result-option> <%= pb_rails("user", props: { name: tag(:slot, name: "name"), orientation: "horizontal", align: "left", avatar_url: "data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAQAAAC1HAwCAAAAC0lEQVR4nGP6zwAAAgcBApocMXEAAAAASUVORK5CYII=", avatar: true }) %> </template> <%= javascript_tag defer: "defer" do %> document.addEventListener("pb-typeahead-kit-search", function(event) { if (!event.target.dataset || !event.target.dataset.typeaheadExample) return; fetch(`https://api.github.com/search/users?q=${encodeURIComponent(event.detail.searchingFor)}`) .then(response => response.json()) .then((result) => { const resultOptionTemplate = document.querySelector("[data-typeahead-example-result-option]") event.detail.setResults((result.items || []).map((user) => { const wrapper = resultOptionTemplate.content.cloneNode(true) wrapper.querySelector('slot[name="name"]').replaceWith(user.login) wrapper.querySelector('img').dataset.src = user.avatar_url return wrapper })) }) }) document.addEventListener("pb-typeahead-kit-result-option-selected", function(event) { if (!event.target.dataset.typeaheadExample) return; document.querySelector("[data-typeahead-example-selected-option] [data-selected-option]").innerHTML = "" document.querySelector("[data-typeahead-example-selected-option] [data-selected-option]").innerHTML = event.detail.selected.innerHTML }) <% end %>
<%= pb_rails("select", props: { label: "Colors", name: "foo", data: { context_select: true }, options: [ { value: "red", value_text: "Red" }, { value: "orange", value_text: "Orange" }, { value: "yellow", value_text: "Yellow" }, { value: "green", value_text: "Green" }, { value: "blue", value_text: "Blue" }, { value: "purple", value_text: "Purple" }, ] }) %> <%= pb_rails("typeahead", props: { label: "Crayola Crayons", name: :foo, data: { typeahead_example2: true, search_context_value_selector: "[data-context-select] select" } }) %> <br><br><br> <%= javascript_tag defer: "defer" do %> document.addEventListener("pb-typeahead-kit-search", function(event) { if (!event.target.dataset || !event.target.dataset.typeaheadExample2) return; const fuzzyMatch = function(string, term) { const ratio = 0.5; string = string.toLowerCase(); const compare = term.toLowerCase(); let matches = 0; if (string.indexOf(compare) > -1) return true; for (let index = 0; index < compare.length; index++) { if (string.indexOf(compare[index]) > -1) { matches += 1 } else { matches -=1; } } return (matches / string.length >= ratio || term == "") }; const colors = { red: ["Red", "Scarlet", "Chestnut", "Mahogany"], orange: ["Orange", "Apricot", "Peach", "Melon", "Burnt Sienna", "Macaroni and Cheese"], yellow: ["Yellow", "Gold", "Goldenrod", "Canary", "Laser Lemon"], green: ["Green", "Olive Green", "Granny Smith Apple", "Spring Green", "Sea Green"], blue: ["Blue", "Cerulean", "Bluetiful", "Sky Blue", "Cadet Blue", "Cornflower"], purple: ["Violet", "Indigo", "Wisteria", "Purple Mountain Majesty", "Lavender"] }; event.detail.setResults(colors[event.detail.searchingContext].filter((color) => fuzzyMatch(color, event.detail.searchingFor)).map((color) => document.createTextNode(color))); }) <% end %>
Typeahead kit is data-driven. The minimum default fields are label
and value
.
This is an example of an option: { label: 'Windows', value: '#FFA500' }
You can also pass default_options
which will populate the initial pill selections:
default_options: [{ label: 'Windows', value: '#FFA500' }]
JavaScript events are triggered based on actions you take within the kit such as selection, removal and clearing.
This kit utilizes a default id
prop named react-select-input
. It is highly advised to send your own unique id
prop when using this kit to ensure these events do not unintentionally affect other instances of the kit in the same view. The examples below will use the unique id
prop named typeahead-pills-example1
:
pb-typeahead-kit-typeahead-pills-example1-result-option-select
event to perform custom work when an option is clicked.
pb-typeahead-kit-typeahead-pills-example1-result-option-remove
event to perform custom work when a pill is clicked.
pb-typeahead-kit-typeahead-pills-example1-result-option-clear
event to perform custom work when all pills are removed upon clicking the X.
The same rule regarding the id
prop applies to publishing JS events. The examples below will use the unique id
prop named typeahead-pills-example1
:
pb-typeahead-kit-typeahead-pills-example1:clear
event to clear all options.
<% options = [ { label: 'Windows', value: '#FFA500' }, { label: 'Siding', value: '#FF0000' }, { label: 'Doors', value: '#00FF00' }, { label: 'Roofs', value: '#0000FF' }, ] %> <%= pb_rails("typeahead", props: { id: "typeahead-pills-example1", default_options: [options.first], options: options, label: "Colors", name: :foo, pills: true }) %> <%= pb_rails("button", props: {id: "clear-pills", text: "Clear All Options", variant: "secondary"}) %> <!-- This section is an example of the available JavaScript event hooks --> <%= javascript_tag defer: "defer" do %> document.addEventListener("pb-typeahead-kit-typeahead-pills-example1-result-option-select", function(event) { console.log('Option selected') console.dir(event.detail) }) document.addEventListener("pb-typeahead-kit-typeahead-pills-example1-result-option-remove", function(event) { console.log('Option removed') console.dir(event.detail) }) document.addEventListener("pb-typeahead-kit-typeahead-pills-example1-result-clear", function() { console.log('All options cleared') }) document.querySelector('#clear-pills').addEventListener('click', function() { document.dispatchEvent(new CustomEvent('pb-typeahead-kit-typeahead-pills-example1:clear')) }) <% end %>
Passing is_multi: false
will allow the user to only select one option from the drop down. Note: this will disable pills
prop.
<% options = [ { label: 'Windows', value: '#FFA500' }, { label: 'Siding', value: '#FF0000' }, { label: 'Doors', value: '#00FF00' }, { label: 'Roofs', value: '#0000FF' }, ] %> <%= pb_rails("typeahead", props: { id: "typeahead-without-pills-example1", placeholder: "All Colors", options: options, label: "Colors", name: :foo, is_multi: false }) %> <!-- This section is an example of the available JavaScript event hooks --> <%= javascript_tag defer: "defer" do %> document.addEventListener("pb-typeahead-kit-typeahead-without-pills-example1-result-option-select", function(event) { console.log('Single Option selected') console.dir(event.detail) }) document.addEventListener("pb-typeahead-kit-typeahead-without-pills-example1-result-clear", function() { console.log('All options cleared') }) <% end %>
load_options
Promise *Additional required props: * async: true
, pills: true
The prop load_options
, when used in conjunction with async: true
and pills: true
, points to a JavaScript function located within the global window namespace. This function should return a Promise
which resolves with the list of formatted options as described in prior examples above. This function is identical to the function provided to the React version of this kit. See the code example for more details.
loadOptions
*Additional required props: * async: true
As outlined in the react-select Async docs, loadOptions
expects to return a Promise that resolves resolves with the list of formatted options as described in prior examples above. See the code example for more details.
getOptionLabel
+ getOptionValue
If your server returns data that requires differing field names other than label
and value
See react-select
docs for more information: https://react-select.com/advanced#replacing-builtins
<%= pb_rails("typeahead", props: { async: true, get_option_label: 'getOptionLabel', get_option_value: 'getOptionValue', load_options: 'asyncPillsPromiseOptions', label: "Github Users", name: :foo, pills: true, placeholder: "type the name of a Github user" }) %> <!-- This section is an example of how to provide load_options prop for using dynamic options --> <%= javascript_tag defer: "defer" do %> // Simple filter function, providing a list of results in the expected data format const filterResults = function(results) { return results.items.map(function(result) { return { name: result.login, id: result.id, } }) } /* Note: Make sure you assign this to window or a namespace within window or it will not be accessible to the kit! */ window.asyncPillsPromiseOptions = function(inputValue) { return new Promise(function(resolve) { if (inputValue) { fetch(`https://api.github.com/search/users?q=${inputValue}`) .then(function(response) { return response.json() }) .then(function(results) { resolve(filterResults(results))}) } else { resolve([]) } }) } window.getOptionLabel = function(option) { return option.name; } window.getOptionValue = function(option) { return option.id; } <% end %>
If the data field imageUrl
is present, FormPill will receive that field as a prop and display the image.
<%= pb_rails("typeahead", props: { async: true, load_options: 'asyncPillsPromiseOptionsUsers', label: "Github Users", name: :foo, pills: true, placeholder: "type the name of a Github user" }) %> <%= javascript_tag defer: "defer" do %> const filterUserResults = function(results) { return results.items.map(function(result) { return { imageUrl: result.avatar_url, label: result.login, value: result.id, } }) } window.asyncPillsPromiseOptionsUsers = function(inputValue) { return new Promise(function(resolve) { if (inputValue) { fetch(`https://api.github.com/search/users?q=${inputValue}`) .then(function(response) { return response.json() }) .then(function(results) { resolve(filterUserResults(results))}) } else { resolve([]) } }) } <% end %>
<% synths = [ { label: 'Oberheim', value: 'OBXa' }, { label: 'Moog', value: 'Minimoog' }, { label: 'Roland', value: 'Juno' }, { label: 'Korg', value: 'MS-20' }, ] %> <% cities = [ { label: 'Budapest', value: 'Hungary' }, { label: 'Singapore', value: 'Singapore' }, { label: 'Oslo', value: 'Norway' }, { label: 'Lagos', value: 'Nigeria' }, ] %> <%= pb_rails("typeahead", props: { default_options: [synths.first], id: "typeahead-inline-example1", inline: true, options: synths, label: "Synths", placeholder: "Add synths", pills: true }) %> <%= pb_rails("typeahead", props: { id: "typeahead-inline-example2", inline: true, options: cities, label: "Cities", pills: true, placeholder: "Add cities", plus_icon: true }) %>
<% labels = [ { label: 'Verve', value: '1956' }, { label: 'Stax', value: '1957' }, { label: 'Motown', value: '1959' }, { label: 'Kudu', value: '1971' }, { label: 'Stones Throw', value: '1996' }, ] %> <% expressionists = [ { label: 'Kandinsky', value: 'Russia' }, { label: 'Klee', value: 'Switzerland' }, { label: 'Kokoschka', value: 'Austria' }, { label: 'Kirchner', value: 'Germany' }, ] %> <%= pb_rails("typeahead", props: { default_options: [labels.first], id: "typeahead-multi-kit-example1", options: labels, label: "Badges", multi_kit: "badge", pills: true }) %> <%= pb_rails("typeahead", props: { default_options: [expressionists.first], id: "typeahead-multi-kit-example2", options: expressionists, label: "Small Pills", multi_kit: "smallPill", pills: true, }) %>
Typeahead w/ Error shows that an option must be selected or the selected option is invalid (i.e., when used in a form it signals a user to fix an error).
<% options = [ { label: 'Windows', value: '#FFA500' }, { label: 'Siding', value: '#FF0000' }, { label: 'Doors', value: '#00FF00' }, { label: 'Roofs', value: '#0000FF' }, ] %> <%= pb_rails("typeahead", props: { id: "typeahead-error-example", options: options, error: "Please make a valid selection", label: "Products", name: :foo, is_multi: false }) %> <!-- This section is an example of the available JavaScript event hooks --> <%= javascript_tag defer: "defer" do %> document.addEventListener("pb-typeahead-kit-typeahead-error-example-result-option-select", function(event) { console.log('Option selected') console.dir(event.detail) }) <% end %>
Avoid using on questionaires, surverys, text input and textarea when users answers/inputs will be individualized.
Props | Type | Values |
---|---|---|
max_width |
array
|
xs
sm
md
lg
xl
0
none
|
z_index |
array
|
1
2
3
4
5
6
7
8
9
10
|
number_spacing |
array
|
tabular
|
shadow |
array
|
none
deep
deeper
deepest
|
line_height |
array
|
tightest
tighter
tight
normal
loose
looser
loosest
|
display |
array
|
block
inline_block
inline
flex
inline_flex
none
|
cursor |
array
|
auto
default
none
contextMenu
help
pointer
progress
wait
cell
crosshair
text
verticalText
alias
copy
move
noDrop
notAllowed
grab
grabbing
eResize
nResize
neResize
nwResize
sResize
seResize
swResize
wResize
ewResize
nsResize
neswResize
nwseResize
colResize
rowResize
allScroll
zoomIn
zoomOut
|
flex_direction |
array
|
row
column
rowReverse
columnReverse
|
flex_wrap |
array
|
wrap
nowrap
wrapReverse
|
justify_content |
array
|
start
end
center
spaceBetween
spaceAround
spaceEvenly
|
justify_self |
array
|
auto
start
end
center
stretch
|
align_items |
array
|
flexStart
flexEnd
start
end
center
baseline
stretch
|
align_content |
array
|
start
end
center
spaceBetween
spaceAround
spaceEvenly
|
align_self |
array
|
auto
start
end
center
stretch
baseline
|
flex |
array
|
auto
initial
0
1
2
3
4
5
6
7
8
9
10
11
12
none
|
flex_grow |
array
|
1
0
|
flex_shrink |
array
|
1
0
|
order |
array
|
1
2
3
4
5
6
7
8
9
10
11
12
|
position |
array
|
relative
absolute
fixed
sticky
|
margin |
array
|
none
xxs
xs
sm
md
lg
xl
|
margin_bottom |
array
|
none
xxs
xs
sm
md
lg
xl
|
margin_left |
array
|
none
xxs
xs
sm
md
lg
xl
|
margin_right |
array
|
none
xxs
xs
sm
md
lg
xl
|
margin_top |
array
|
none
xxs
xs
sm
md
lg
xl
|
margin_x |
array
|
none
xxs
xs
sm
md
lg
xl
|
margin_y |
array
|
none
xxs
xs
sm
md
lg
xl
|
padding |
array
|
none
xxs
xs
sm
md
lg
xl
|
padding_bottom |
array
|
none
xxs
xs
sm
md
lg
xl
|
padding_left |
array
|
none
xxs
xs
sm
md
lg
xl
|
padding_right |
array
|
none
xxs
xs
sm
md
lg
xl
|
padding_top |
array
|
none
xxs
xs
sm
md
lg
xl
|
padding_x |
array
|
none
xxs
xs
sm
md
lg
xl
|
padding_y |
array
|
none
xxs
xs
sm
md
lg
xl
|
classname |
string
|
|
dark |
boolean
|
|
data |
hash
|
|
aria |
hash
|
|
children |
proc
|
Props | Type | Values | Default |
---|---|---|---|
id |
string
|
||
async |
boolean
|
false
|
|
default_options |
hasharray
|
||
error |
string
|
||
get_option_label |
string
|
||
get_option_value |
string
|
||
inline |
boolean
|
false
|
|
label |
string
|
||
load_options |
string
|
||
multi_kit |
string
|
||
name |
string
|
||
options |
hasharray
|
||
input_options |
hash
|
||
is_multi |
boolean
|
true
|
|
pills |
boolean
|
false
|
|
placeholder |
string
|
||
plus_icon |
boolean
|
false
|
|
search_term_minimum_length |
string
|
3
|
|
search_debounce_timeout |
string
|
250
|
|
value |
string
|