Skip to content

Instantly share code, notes, and snippets.

@burningTyger
Last active February 20, 2019 23:13
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save burningTyger/07ff8b15b72ae609c723d529c29180d5 to your computer and use it in GitHub Desktop.
Save burningTyger/07ff8b15b72ae609c723d529c29180d5 to your computer and use it in GitHub Desktop.
autocomplete

This is an example svelte autocomplete component. There is not much to do with it unless you want to query the farhang database. But feel free to copy and paste things into your projects. This repo is public domain.

<h1>{selected.link || 'No selection'}</h1>
<div class="search">
<input bind:value={term} on:keydown={keydown} class="input" on:blur={() => options = []}>
<ul class="list">
{#each options as t,i}
<li
class={`item ${i+1 === pos ? 'active':''}`}
value={t.link}
on:click={() => select(t)}
>{t.value}</li>
{/each}
</ul>
</div>
<script>
let term = 'a'
let options = []
let pos
let selected = {}
$: fetch_options(term)
function select (t) {
selected = t
term = ''
pos = 1
}
function fetch_options (term) {
term.length > 0
? fetch(`https://farhang.im/search/autocomplete.json?term=${term}`)
.then(async res => {options = await res.json(); pos = 1})
.catch(e => options = [])
: options = []
}
const keydown = (e) => {
switch (e.key) {
case 'ArrowDown':
e.preventDefault();
options.length > pos && (pos += 1)
break;
case 'ArrowUp':
e.preventDefault();
pos > 1 && (pos -=1)
break;
case 'Enter':
e.preventDefault();
select(options[pos-1])
break;
case 'Tab':
e.preventDefault();
options.length > 0 && (term = options[pos-1].value)
break;
case 'Escape':
e.preventDefault();
options = []
break
}
}
</script>
<style>
* {
box-sizing: border-box;
}
.input {
height: 2rem;
font-size: 1rem;
padding: 0.25rem 0.5rem;
}
.search {
position: relative;
}
.list {
padding: 0;
margin: 0;
border: 1px solid #dbdbdb;
overflow: auto;
background-color: white;
box-shadow: 2px 2px 24px rgba(0, 0, 0, 0.1);
position: absolute;
z-index: 100;
}
.item {
/* color: #7a7a7a; */
list-style: none;
text-align: left;
height: 2rem;
padding: 0.25rem 0.5rem;
cursor: pointer;
}
.item.active,
.item:hover {
background-color: #dbdbdb;
}
</style>
{
"svelte": true
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment