Guide

Examples you can copy

Live autocomplete demos with copyable source: search, events, forms, pills, hooks, plugins, state, headless search, a command palette and dependent fields.

Every preview runs the real package against local data, the site’s public cities JSON file or a simulated async directory. Each one offers HTML / CDN and Package / ESM files, separately or as one complete document, and the copied code is tested in a browser exactly as shown.

The first examples cover a single option at a time; the later ones combine several: pills compose the single-selection API into a multiple selection, the command palette mixes sections, keyword filters, custom rendering and recent picks, and dependent fields narrow one search by another. The headless directory uses createSearch without the combobox, so its ARIA and keyboard behavior belong to the application.

Search a remote list as you type

BasicLive preview

Two characters start a debounced request. Arrow keys, Home, End, Enter, Escape and Tab work out of the box, and a late response never reopens a closed list.

Nothing selected yet.

Explore the code

HTML / CDN

HTML

index.html
<!doctype html>
<html lang="en">
  <head>
    <meta charset="utf-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1" />
    <title>Search a remote list as you type</title>
    <link
      rel="stylesheet"
      href="https://cdn.jsdelivr.net/npm/@samline/autocomplete@3.0.0/dist/style.css"
    />
    <link rel="stylesheet" href="./style.css" />
  </head>
  <body>
    <main>
      <div class="field">
        <label for="city">City</label>
        <input id="city" type="text" />
      </div>
      <p id="selected" aria-live="polite">Nothing selected yet.</p>
    </main>
    <script src="https://cdn.jsdelivr.net/npm/@samline/autocomplete@3.0.0/dist/browser/autocomplete.global.js"></script>
    <script src="./main.js" defer></script>
  </body>
</html>

CSS

style.css
.field {
  position: relative;
  max-width: 28rem;
  margin-bottom: 0.75rem;
}
label {
  display: block;
  margin-bottom: 0.5rem;
  font-weight: 600;
}
input {
  width: 100%;
  padding: 0.75rem 1rem;
  border: 1px solid #aaa;
  border-radius: 0.5rem;
  font: inherit;
}

JavaScript

main.js
window.Autocomplete.newAutocomplete({
  id: 'city',
  options: {
    endpoint: 'https://samline.github.io/autocomplete/cities.json',
    minLength: 2,
    mapResponse: (payload, response, query) =>
      payload.results.filter(city => city.name.toLowerCase().includes(query.toLowerCase())),
    getId: city => city.key,
    getLabel: city => `${city.name}, ${city.country}`,
    getValue: city => city.name,
    onSelect: city => {
      document.querySelector('#selected').textContent = `Selected ${city.name}.`
    },
  },
})

Complete file

index.html
<!doctype html>
<html lang="en">
  <head>
    <meta charset="utf-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1" />
    <title>Search a remote list as you type</title>
    <link
      rel="stylesheet"
      href="https://cdn.jsdelivr.net/npm/@samline/autocomplete@3.0.0/dist/style.css"
    />
    <style>
      .field {
        position: relative;
        max-width: 28rem;
        margin-bottom: 0.75rem;
      }
      label {
        display: block;
        margin-bottom: 0.5rem;
        font-weight: 600;
      }
      input {
        width: 100%;
        padding: 0.75rem 1rem;
        border: 1px solid #aaa;
        border-radius: 0.5rem;
        font: inherit;
      }
    </style>
  </head>
  <body>
    <main>
      <div class="field">
        <label for="city">City</label>
        <input id="city" type="text" />
      </div>
      <p id="selected" aria-live="polite">Nothing selected yet.</p>
    </main>
    <script src="https://cdn.jsdelivr.net/npm/@samline/autocomplete@3.0.0/dist/browser/autocomplete.global.js"></script>
    <script>
      window.Autocomplete.newAutocomplete({
        id: 'city',
        options: {
          endpoint: 'https://samline.github.io/autocomplete/cities.json',
          minLength: 2,
          mapResponse: (payload, response, query) =>
            payload.results.filter(city => city.name.toLowerCase().includes(query.toLowerCase())),
          getId: city => city.key,
          getLabel: city => `${city.name}, ${city.country}`,
          getValue: city => city.name,
          onSelect: city => {
            document.querySelector('#selected').textContent = `Selected ${city.name}.`
          },
        },
      })
    </script>
  </body>
</html>

Package / ESM

HTML

index.html
<!doctype html>
<html lang="en">
  <head>
    <meta charset="utf-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1" />
    <title>Search a remote list as you type</title>
    <link rel="stylesheet" href="./style.css" />
  </head>
  <body>
    <main>
      <div class="field">
        <label for="city">City</label>
        <input id="city" type="text" />
      </div>
      <p id="selected" aria-live="polite">Nothing selected yet.</p>
    </main>
    <script type="module" src="./main.js"></script>
  </body>
</html>

CSS

style.css
.field {
  position: relative;
  max-width: 28rem;
  margin-bottom: 0.75rem;
}
label {
  display: block;
  margin-bottom: 0.5rem;
  font-weight: 600;
}
input {
  width: 100%;
  padding: 0.75rem 1rem;
  border: 1px solid #aaa;
  border-radius: 0.5rem;
  font: inherit;
}

JavaScript

main.js
import { Autocomplete } from '@samline/autocomplete/browser'
import '@samline/autocomplete/style.css'

Autocomplete.newAutocomplete({
  id: 'city',
  options: {
    endpoint: 'https://samline.github.io/autocomplete/cities.json',
    minLength: 2,
    mapResponse: (payload, response, query) =>
      payload.results.filter(city => city.name.toLowerCase().includes(query.toLowerCase())),
    getId: city => city.key,
    getLabel: city => `${city.name}, ${city.country}`,
    getValue: city => city.name,
    onSelect: city => {
      document.querySelector('#selected').textContent = `Selected ${city.name}.`
    },
  },
})

Complete file

index.html
<!doctype html>
<html lang="en">
  <head>
    <meta charset="utf-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1" />
    <title>Search a remote list as you type</title>
    <style>
      .field {
        position: relative;
        max-width: 28rem;
        margin-bottom: 0.75rem;
      }
      label {
        display: block;
        margin-bottom: 0.5rem;
        font-weight: 600;
      }
      input {
        width: 100%;
        padding: 0.75rem 1rem;
        border: 1px solid #aaa;
        border-radius: 0.5rem;
        font: inherit;
      }
    </style>
  </head>
  <body>
    <main>
      <div class="field">
        <label for="city">City</label>
        <input id="city" type="text" />
      </div>
      <p id="selected" aria-live="polite">Nothing selected yet.</p>
    </main>
    <script type="module">
      import { Autocomplete } from '@samline/autocomplete/browser'
      import '@samline/autocomplete/style.css'

      Autocomplete.newAutocomplete({
        id: 'city',
        options: {
          endpoint: 'https://samline.github.io/autocomplete/cities.json',
          minLength: 2,
          mapResponse: (payload, response, query) =>
            payload.results.filter(city => city.name.toLowerCase().includes(query.toLowerCase())),
          getId: city => city.key,
          getLabel: city => `${city.name}, ${city.country}`,
          getValue: city => city.name,
          onSelect: city => {
            document.querySelector('#selected').textContent = `Selected ${city.name}.`
          },
        },
      })
    </script>
  </body>
</html>

Render richer options

Custom optionsLive preview

renderOption receives each option element, its suggestion and the render context, so you can append a secondary line with DOM nodes instead of HTML strings.

Explore the code

HTML / CDN

HTML

index.html
<!doctype html>
<html lang="en">
  <head>
    <meta charset="utf-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1" />
    <title>Render richer options</title>
    <link
      rel="stylesheet"
      href="https://cdn.jsdelivr.net/npm/@samline/autocomplete@3.0.0/dist/style.css"
    />
    <link rel="stylesheet" href="./style.css" />
  </head>
  <body>
    <main>
      <div class="field">
        <label for="destination">Destination</label>
        <input id="destination" type="text" />
      </div>
    </main>
    <script src="https://cdn.jsdelivr.net/npm/@samline/autocomplete@3.0.0/dist/browser/autocomplete.global.js"></script>
    <script src="./main.js" defer></script>
  </body>
</html>

CSS

style.css
.field {
  position: relative;
  max-width: 28rem;
  margin-bottom: 0.75rem;
}
label {
  display: block;
  margin-bottom: 0.5rem;
  font-weight: 600;
}
input {
  width: 100%;
  padding: 0.75rem 1rem;
  border: 1px solid #aaa;
  border-radius: 0.5rem;
  font: inherit;
}
[data-autocomplete-option] small {
  display: block;
  color: #666;
}

JavaScript

main.js
window.Autocomplete.newAutocomplete({
  id: 'destination',
  options: {
    endpoint: 'https://samline.github.io/autocomplete/cities.json',
    minLength: 1,
    maxResults: 5,
    mapResponse: (payload, response, query) =>
      payload.results.filter(city => city.name.toLowerCase().includes(query.toLowerCase())),
    getId: city => city.key,
    getLabel: city => city.name,
    renderOption: (option, city) => {
      const country = document.createElement('small')
      country.textContent = city.country
      option.append(country)
    },
  },
})

Complete file

index.html
<!doctype html>
<html lang="en">
  <head>
    <meta charset="utf-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1" />
    <title>Render richer options</title>
    <link
      rel="stylesheet"
      href="https://cdn.jsdelivr.net/npm/@samline/autocomplete@3.0.0/dist/style.css"
    />
    <style>
      .field {
        position: relative;
        max-width: 28rem;
        margin-bottom: 0.75rem;
      }
      label {
        display: block;
        margin-bottom: 0.5rem;
        font-weight: 600;
      }
      input {
        width: 100%;
        padding: 0.75rem 1rem;
        border: 1px solid #aaa;
        border-radius: 0.5rem;
        font: inherit;
      }
      [data-autocomplete-option] small {
        display: block;
        color: #666;
      }
    </style>
  </head>
  <body>
    <main>
      <div class="field">
        <label for="destination">Destination</label>
        <input id="destination" type="text" />
      </div>
    </main>
    <script src="https://cdn.jsdelivr.net/npm/@samline/autocomplete@3.0.0/dist/browser/autocomplete.global.js"></script>
    <script>
      window.Autocomplete.newAutocomplete({
        id: 'destination',
        options: {
          endpoint: 'https://samline.github.io/autocomplete/cities.json',
          minLength: 1,
          maxResults: 5,
          mapResponse: (payload, response, query) =>
            payload.results.filter(city => city.name.toLowerCase().includes(query.toLowerCase())),
          getId: city => city.key,
          getLabel: city => city.name,
          renderOption: (option, city) => {
            const country = document.createElement('small')
            country.textContent = city.country
            option.append(country)
          },
        },
      })
    </script>
  </body>
</html>

Package / ESM

HTML

index.html
<!doctype html>
<html lang="en">
  <head>
    <meta charset="utf-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1" />
    <title>Render richer options</title>
    <link rel="stylesheet" href="./style.css" />
  </head>
  <body>
    <main>
      <div class="field">
        <label for="destination">Destination</label>
        <input id="destination" type="text" />
      </div>
    </main>
    <script type="module" src="./main.js"></script>
  </body>
</html>

CSS

style.css
.field {
  position: relative;
  max-width: 28rem;
  margin-bottom: 0.75rem;
}
label {
  display: block;
  margin-bottom: 0.5rem;
  font-weight: 600;
}
input {
  width: 100%;
  padding: 0.75rem 1rem;
  border: 1px solid #aaa;
  border-radius: 0.5rem;
  font: inherit;
}
[data-autocomplete-option] small {
  display: block;
  color: #666;
}

JavaScript

main.js
import { Autocomplete } from '@samline/autocomplete/browser'
import '@samline/autocomplete/style.css'

Autocomplete.newAutocomplete({
  id: 'destination',
  options: {
    endpoint: 'https://samline.github.io/autocomplete/cities.json',
    minLength: 1,
    maxResults: 5,
    mapResponse: (payload, response, query) =>
      payload.results.filter(city => city.name.toLowerCase().includes(query.toLowerCase())),
    getId: city => city.key,
    getLabel: city => city.name,
    renderOption: (option, city) => {
      const country = document.createElement('small')
      country.textContent = city.country
      option.append(country)
    },
  },
})

Complete file

index.html
<!doctype html>
<html lang="en">
  <head>
    <meta charset="utf-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1" />
    <title>Render richer options</title>
    <style>
      .field {
        position: relative;
        max-width: 28rem;
        margin-bottom: 0.75rem;
      }
      label {
        display: block;
        margin-bottom: 0.5rem;
        font-weight: 600;
      }
      input {
        width: 100%;
        padding: 0.75rem 1rem;
        border: 1px solid #aaa;
        border-radius: 0.5rem;
        font: inherit;
      }
      [data-autocomplete-option] small {
        display: block;
        color: #666;
      }
    </style>
  </head>
  <body>
    <main>
      <div class="field">
        <label for="destination">Destination</label>
        <input id="destination" type="text" />
      </div>
    </main>
    <script type="module">
      import { Autocomplete } from '@samline/autocomplete/browser'
      import '@samline/autocomplete/style.css'

      Autocomplete.newAutocomplete({
        id: 'destination',
        options: {
          endpoint: 'https://samline.github.io/autocomplete/cities.json',
          minLength: 1,
          maxResults: 5,
          mapResponse: (payload, response, query) =>
            payload.results.filter(city => city.name.toLowerCase().includes(query.toLowerCase())),
          getId: city => city.key,
          getLabel: city => city.name,
          renderOption: (option, city) => {
            const country = document.createElement('small')
            country.textContent = city.country
            option.append(country)
          },
        },
      })
    </script>
  </body>
</html>

Follow the lifecycle with events

EventsLive preview

controller.on() subscribes to loadstart, load, open, close, select, clear and error. Type “lis”, retype it to see a cache hit, pick a city, then edit the text or press Clear. The same events bubble from the input as autocomplete:* DOM events.

    Explore the code

    HTML / CDN

    HTML

    index.html
    <!doctype html>
    <html lang="en">
      <head>
        <meta charset="utf-8" />
        <meta name="viewport" content="width=device-width, initial-scale=1" />
        <title>Follow the lifecycle with events</title>
        <link
          rel="stylesheet"
          href="https://cdn.jsdelivr.net/npm/@samline/autocomplete@3.0.0/dist/style.css"
        />
        <link rel="stylesheet" href="./style.css" />
      </head>
      <body>
        <main>
          <div class="field">
            <label for="origin">Origin</label>
            <input id="origin" type="text" />
          </div>
          <button type="button" id="reset">Clear</button>
          <ol id="log" aria-label="Event log"></ol>
        </main>
        <script src="https://cdn.jsdelivr.net/npm/@samline/autocomplete@3.0.0/dist/browser/autocomplete.global.js"></script>
        <script src="./main.js" defer></script>
      </body>
    </html>
    

    CSS

    style.css
    .field {
      position: relative;
      max-width: 28rem;
      margin-bottom: 0.75rem;
    }
    label {
      display: block;
      margin-bottom: 0.5rem;
      font-weight: 600;
    }
    input {
      width: 100%;
      padding: 0.75rem 1rem;
      border: 1px solid #aaa;
      border-radius: 0.5rem;
      font: inherit;
    }
    #log {
      font:
        0.875rem/1.6 ui-monospace,
        monospace;
    }
    

    JavaScript

    main.js
    const log = document.querySelector('#log')
    const write = text => {
      const entry = document.createElement('li')
      entry.textContent = text
      log.prepend(entry)
      log.querySelectorAll('li:nth-child(n + 7)').forEach(item => item.remove())
    }
    
    const controller = window.Autocomplete.newAutocomplete({
      id: 'origin',
      options: {
        endpoint: 'https://samline.github.io/autocomplete/cities.json',
        mapResponse: (payload, response, query) =>
          payload.results.filter(city => city.name.toLowerCase().includes(query.toLowerCase())),
        getId: city => city.key,
        getLabel: city => city.name,
      },
    })
    
    // on() unwraps event.detail and returns an unsubscribe function.
    controller.on('loadstart', ({ query }) => write(`loadstart “${query}”`))
    controller.on('load', ({ suggestions, cached }) =>
      write(`load ${suggestions.length} results${cached ? ' (cache)' : ''}`)
    )
    controller.on('open', () => write('open'))
    controller.on('close', () => write('close'))
    controller.on('select', ({ label, value }) => write(`select ${label} → ${value}`))
    controller.on('clear', () => write('clear'))
    controller.on('error', ({ error }) => write(`error ${error}`))
    document.querySelector('#reset').addEventListener('click', () => controller.clear())
    

    Complete file

    index.html
    <!doctype html>
    <html lang="en">
      <head>
        <meta charset="utf-8" />
        <meta name="viewport" content="width=device-width, initial-scale=1" />
        <title>Follow the lifecycle with events</title>
        <link
          rel="stylesheet"
          href="https://cdn.jsdelivr.net/npm/@samline/autocomplete@3.0.0/dist/style.css"
        />
        <style>
          .field {
            position: relative;
            max-width: 28rem;
            margin-bottom: 0.75rem;
          }
          label {
            display: block;
            margin-bottom: 0.5rem;
            font-weight: 600;
          }
          input {
            width: 100%;
            padding: 0.75rem 1rem;
            border: 1px solid #aaa;
            border-radius: 0.5rem;
            font: inherit;
          }
          #log {
            font:
              0.875rem/1.6 ui-monospace,
              monospace;
          }
        </style>
      </head>
      <body>
        <main>
          <div class="field">
            <label for="origin">Origin</label>
            <input id="origin" type="text" />
          </div>
          <button type="button" id="reset">Clear</button>
          <ol id="log" aria-label="Event log"></ol>
        </main>
        <script src="https://cdn.jsdelivr.net/npm/@samline/autocomplete@3.0.0/dist/browser/autocomplete.global.js"></script>
        <script>
          const log = document.querySelector('#log')
          const write = text => {
            const entry = document.createElement('li')
            entry.textContent = text
            log.prepend(entry)
            log.querySelectorAll('li:nth-child(n + 7)').forEach(item => item.remove())
          }
    
          const controller = window.Autocomplete.newAutocomplete({
            id: 'origin',
            options: {
              endpoint: 'https://samline.github.io/autocomplete/cities.json',
              mapResponse: (payload, response, query) =>
                payload.results.filter(city => city.name.toLowerCase().includes(query.toLowerCase())),
              getId: city => city.key,
              getLabel: city => city.name,
            },
          })
    
          // on() unwraps event.detail and returns an unsubscribe function.
          controller.on('loadstart', ({ query }) => write(`loadstart “${query}”`))
          controller.on('load', ({ suggestions, cached }) =>
            write(`load ${suggestions.length} results${cached ? ' (cache)' : ''}`)
          )
          controller.on('open', () => write('open'))
          controller.on('close', () => write('close'))
          controller.on('select', ({ label, value }) => write(`select ${label} → ${value}`))
          controller.on('clear', () => write('clear'))
          controller.on('error', ({ error }) => write(`error ${error}`))
          document.querySelector('#reset').addEventListener('click', () => controller.clear())
        </script>
      </body>
    </html>
    

    Package / ESM

    HTML

    index.html
    <!doctype html>
    <html lang="en">
      <head>
        <meta charset="utf-8" />
        <meta name="viewport" content="width=device-width, initial-scale=1" />
        <title>Follow the lifecycle with events</title>
        <link rel="stylesheet" href="./style.css" />
      </head>
      <body>
        <main>
          <div class="field">
            <label for="origin">Origin</label>
            <input id="origin" type="text" />
          </div>
          <button type="button" id="reset">Clear</button>
          <ol id="log" aria-label="Event log"></ol>
        </main>
        <script type="module" src="./main.js"></script>
      </body>
    </html>
    

    CSS

    style.css
    .field {
      position: relative;
      max-width: 28rem;
      margin-bottom: 0.75rem;
    }
    label {
      display: block;
      margin-bottom: 0.5rem;
      font-weight: 600;
    }
    input {
      width: 100%;
      padding: 0.75rem 1rem;
      border: 1px solid #aaa;
      border-radius: 0.5rem;
      font: inherit;
    }
    #log {
      font:
        0.875rem/1.6 ui-monospace,
        monospace;
    }
    

    JavaScript

    main.js
    import { Autocomplete } from '@samline/autocomplete/browser'
    import '@samline/autocomplete/style.css'
    
    const log = document.querySelector('#log')
    const write = text => {
      const entry = document.createElement('li')
      entry.textContent = text
      log.prepend(entry)
      log.querySelectorAll('li:nth-child(n + 7)').forEach(item => item.remove())
    }
    
    const controller = Autocomplete.newAutocomplete({
      id: 'origin',
      options: {
        endpoint: 'https://samline.github.io/autocomplete/cities.json',
        mapResponse: (payload, response, query) =>
          payload.results.filter(city => city.name.toLowerCase().includes(query.toLowerCase())),
        getId: city => city.key,
        getLabel: city => city.name,
      },
    })
    
    // on() unwraps event.detail and returns an unsubscribe function.
    controller.on('loadstart', ({ query }) => write(`loadstart “${query}”`))
    controller.on('load', ({ suggestions, cached }) =>
      write(`load ${suggestions.length} results${cached ? ' (cache)' : ''}`)
    )
    controller.on('open', () => write('open'))
    controller.on('close', () => write('close'))
    controller.on('select', ({ label, value }) => write(`select ${label} → ${value}`))
    controller.on('clear', () => write('clear'))
    controller.on('error', ({ error }) => write(`error ${error}`))
    document.querySelector('#reset').addEventListener('click', () => controller.clear())
    

    Complete file

    index.html
    <!doctype html>
    <html lang="en">
      <head>
        <meta charset="utf-8" />
        <meta name="viewport" content="width=device-width, initial-scale=1" />
        <title>Follow the lifecycle with events</title>
        <style>
          .field {
            position: relative;
            max-width: 28rem;
            margin-bottom: 0.75rem;
          }
          label {
            display: block;
            margin-bottom: 0.5rem;
            font-weight: 600;
          }
          input {
            width: 100%;
            padding: 0.75rem 1rem;
            border: 1px solid #aaa;
            border-radius: 0.5rem;
            font: inherit;
          }
          #log {
            font:
              0.875rem/1.6 ui-monospace,
              monospace;
          }
        </style>
      </head>
      <body>
        <main>
          <div class="field">
            <label for="origin">Origin</label>
            <input id="origin" type="text" />
          </div>
          <button type="button" id="reset">Clear</button>
          <ol id="log" aria-label="Event log"></ol>
        </main>
        <script type="module">
          import { Autocomplete } from '@samline/autocomplete/browser'
          import '@samline/autocomplete/style.css'
    
          const log = document.querySelector('#log')
          const write = text => {
            const entry = document.createElement('li')
            entry.textContent = text
            log.prepend(entry)
            log.querySelectorAll('li:nth-child(n + 7)').forEach(item => item.remove())
          }
    
          const controller = Autocomplete.newAutocomplete({
            id: 'origin',
            options: {
              endpoint: 'https://samline.github.io/autocomplete/cities.json',
              mapResponse: (payload, response, query) =>
                payload.results.filter(city => city.name.toLowerCase().includes(query.toLowerCase())),
              getId: city => city.key,
              getLabel: city => city.name,
            },
          })
    
          // on() unwraps event.detail and returns an unsubscribe function.
          controller.on('loadstart', ({ query }) => write(`loadstart “${query}”`))
          controller.on('load', ({ suggestions, cached }) =>
            write(`load ${suggestions.length} results${cached ? ' (cache)' : ''}`)
          )
          controller.on('open', () => write('open'))
          controller.on('close', () => write('close'))
          controller.on('select', ({ label, value }) => write(`select ${label} → ${value}`))
          controller.on('clear', () => write('clear'))
          controller.on('error', ({ error }) => write(`error ${error}`))
          document.querySelector('#reset').addEventListener('click', () => controller.clear())
        </script>
      </body>
    </html>
    

    Filter a local list without a server

    Local dataLive preview

    Pass an array as source and the list is filtered in the browser, ignoring case and accents: typing “merida” finds “Mérida”. The matching part of each label is highlighted.

    Explore the code

    HTML / CDN

    HTML

    index.html
    <!doctype html>
    <html lang="en">
      <head>
        <meta charset="utf-8" />
        <meta name="viewport" content="width=device-width, initial-scale=1" />
        <title>Filter a local list without a server</title>
        <link
          rel="stylesheet"
          href="https://cdn.jsdelivr.net/npm/@samline/autocomplete@3.0.0/dist/style.css"
        />
        <link rel="stylesheet" href="./style.css" />
      </head>
      <body>
        <main>
          <div class="field">
            <label for="state">Mexican state</label>
            <input id="state" type="text" />
          </div>
        </main>
        <script src="https://cdn.jsdelivr.net/npm/@samline/autocomplete@3.0.0/dist/browser/autocomplete.global.js"></script>
        <script src="./main.js" defer></script>
      </body>
    </html>
    

    CSS

    style.css
    .field {
      position: relative;
      max-width: 28rem;
      margin-bottom: 0.75rem;
    }
    label {
      display: block;
      margin-bottom: 0.5rem;
      font-weight: 600;
    }
    input {
      width: 100%;
      padding: 0.75rem 1rem;
      border: 1px solid #aaa;
      border-radius: 0.5rem;
      font: inherit;
    }
    

    JavaScript

    main.js
    window.Autocomplete.newAutocomplete({
      id: 'state',
      options: {
        source: [
          'Aguascalientes',
          'Baja California',
          'Campeche',
          'Ciudad de México',
          'Michoacán',
          'Morelos',
          'Nuevo León',
          'Querétaro',
          'San Luis Potosí',
          'Yucatán',
        ],
        messages: { empty: ({ query }) => `No state matches “${query}”` },
      },
    })
    

    Complete file

    index.html
    <!doctype html>
    <html lang="en">
      <head>
        <meta charset="utf-8" />
        <meta name="viewport" content="width=device-width, initial-scale=1" />
        <title>Filter a local list without a server</title>
        <link
          rel="stylesheet"
          href="https://cdn.jsdelivr.net/npm/@samline/autocomplete@3.0.0/dist/style.css"
        />
        <style>
          .field {
            position: relative;
            max-width: 28rem;
            margin-bottom: 0.75rem;
          }
          label {
            display: block;
            margin-bottom: 0.5rem;
            font-weight: 600;
          }
          input {
            width: 100%;
            padding: 0.75rem 1rem;
            border: 1px solid #aaa;
            border-radius: 0.5rem;
            font: inherit;
          }
        </style>
      </head>
      <body>
        <main>
          <div class="field">
            <label for="state">Mexican state</label>
            <input id="state" type="text" />
          </div>
        </main>
        <script src="https://cdn.jsdelivr.net/npm/@samline/autocomplete@3.0.0/dist/browser/autocomplete.global.js"></script>
        <script>
          window.Autocomplete.newAutocomplete({
            id: 'state',
            options: {
              source: [
                'Aguascalientes',
                'Baja California',
                'Campeche',
                'Ciudad de México',
                'Michoacán',
                'Morelos',
                'Nuevo León',
                'Querétaro',
                'San Luis Potosí',
                'Yucatán',
              ],
              messages: { empty: ({ query }) => `No state matches “${query}”` },
            },
          })
        </script>
      </body>
    </html>
    

    Package / ESM

    HTML

    index.html
    <!doctype html>
    <html lang="en">
      <head>
        <meta charset="utf-8" />
        <meta name="viewport" content="width=device-width, initial-scale=1" />
        <title>Filter a local list without a server</title>
        <link rel="stylesheet" href="./style.css" />
      </head>
      <body>
        <main>
          <div class="field">
            <label for="state">Mexican state</label>
            <input id="state" type="text" />
          </div>
        </main>
        <script type="module" src="./main.js"></script>
      </body>
    </html>
    

    CSS

    style.css
    .field {
      position: relative;
      max-width: 28rem;
      margin-bottom: 0.75rem;
    }
    label {
      display: block;
      margin-bottom: 0.5rem;
      font-weight: 600;
    }
    input {
      width: 100%;
      padding: 0.75rem 1rem;
      border: 1px solid #aaa;
      border-radius: 0.5rem;
      font: inherit;
    }
    

    JavaScript

    main.js
    import { Autocomplete } from '@samline/autocomplete/browser'
    import '@samline/autocomplete/style.css'
    
    Autocomplete.newAutocomplete({
      id: 'state',
      options: {
        source: [
          'Aguascalientes',
          'Baja California',
          'Campeche',
          'Ciudad de México',
          'Michoacán',
          'Morelos',
          'Nuevo León',
          'Querétaro',
          'San Luis Potosí',
          'Yucatán',
        ],
        messages: { empty: ({ query }) => `No state matches “${query}”` },
      },
    })
    

    Complete file

    index.html
    <!doctype html>
    <html lang="en">
      <head>
        <meta charset="utf-8" />
        <meta name="viewport" content="width=device-width, initial-scale=1" />
        <title>Filter a local list without a server</title>
        <style>
          .field {
            position: relative;
            max-width: 28rem;
            margin-bottom: 0.75rem;
          }
          label {
            display: block;
            margin-bottom: 0.5rem;
            font-weight: 600;
          }
          input {
            width: 100%;
            padding: 0.75rem 1rem;
            border: 1px solid #aaa;
            border-radius: 0.5rem;
            font: inherit;
          }
        </style>
      </head>
      <body>
        <main>
          <div class="field">
            <label for="state">Mexican state</label>
            <input id="state" type="text" />
          </div>
        </main>
        <script type="module">
          import { Autocomplete } from '@samline/autocomplete/browser'
          import '@samline/autocomplete/style.css'
    
          Autocomplete.newAutocomplete({
            id: 'state',
            options: {
              source: [
                'Aguascalientes',
                'Baja California',
                'Campeche',
                'Ciudad de México',
                'Michoacán',
                'Morelos',
                'Nuevo León',
                'Querétaro',
                'San Luis Potosí',
                'Yucatán',
              ],
              messages: { empty: ({ query }) => `No state matches “${query}”` },
            },
          })
        </script>
      </body>
    </html>
    

    Group several sources and remember recent picks

    SectionsLive preview

    sections searches a local list and a remote endpoint in parallel and renders each under its own heading. With recent, the last selections appear when the empty input gets focus or ArrowDown.

    Explore the code

    HTML / CDN

    HTML

    index.html
    <!doctype html>
    <html lang="en">
      <head>
        <meta charset="utf-8" />
        <meta name="viewport" content="width=device-width, initial-scale=1" />
        <title>Group several sources and remember recent picks</title>
        <link
          rel="stylesheet"
          href="https://cdn.jsdelivr.net/npm/@samline/autocomplete@3.0.0/dist/style.css"
        />
        <link rel="stylesheet" href="./style.css" />
      </head>
      <body>
        <main>
          <div class="field">
            <label for="place">Country or city</label>
            <input id="place" type="text" placeholder="Try “sp” or “ja”" />
          </div>
        </main>
        <script src="https://cdn.jsdelivr.net/npm/@samline/autocomplete@3.0.0/dist/browser/autocomplete.global.js"></script>
        <script src="./main.js" defer></script>
      </body>
    </html>
    

    CSS

    style.css
    .field {
      position: relative;
      max-width: 28rem;
      margin-bottom: 0.75rem;
    }
    label {
      display: block;
      margin-bottom: 0.5rem;
      font-weight: 600;
    }
    input {
      width: 100%;
      padding: 0.75rem 1rem;
      border: 1px solid #aaa;
      border-radius: 0.5rem;
      font: inherit;
    }
    

    JavaScript

    main.js
    window.Autocomplete.newAutocomplete({
      id: 'place',
      options: {
        sections: [
          {
            id: 'countries',
            label: 'Countries',
            source: ['Argentina', 'Canada', 'Japan', 'Mexico', 'Portugal', 'Spain'],
          },
          {
            id: 'cities',
            label: 'Cities',
            maxResults: 4,
            source: async (query, { signal }) => {
              const response = await fetch('https://samline.github.io/autocomplete/cities.json', {
                signal,
              })
              const payload = await response.json()
              return payload.results
                .filter(city => city.name.toLowerCase().includes(query.toLowerCase()))
                .map(city => city.name)
            },
          },
        ],
        minLength: 2,
        recent: { label: 'Recent' },
      },
    })
    

    Complete file

    index.html
    <!doctype html>
    <html lang="en">
      <head>
        <meta charset="utf-8" />
        <meta name="viewport" content="width=device-width, initial-scale=1" />
        <title>Group several sources and remember recent picks</title>
        <link
          rel="stylesheet"
          href="https://cdn.jsdelivr.net/npm/@samline/autocomplete@3.0.0/dist/style.css"
        />
        <style>
          .field {
            position: relative;
            max-width: 28rem;
            margin-bottom: 0.75rem;
          }
          label {
            display: block;
            margin-bottom: 0.5rem;
            font-weight: 600;
          }
          input {
            width: 100%;
            padding: 0.75rem 1rem;
            border: 1px solid #aaa;
            border-radius: 0.5rem;
            font: inherit;
          }
        </style>
      </head>
      <body>
        <main>
          <div class="field">
            <label for="place">Country or city</label>
            <input id="place" type="text" placeholder="Try “sp” or “ja”" />
          </div>
        </main>
        <script src="https://cdn.jsdelivr.net/npm/@samline/autocomplete@3.0.0/dist/browser/autocomplete.global.js"></script>
        <script>
          window.Autocomplete.newAutocomplete({
            id: 'place',
            options: {
              sections: [
                {
                  id: 'countries',
                  label: 'Countries',
                  source: ['Argentina', 'Canada', 'Japan', 'Mexico', 'Portugal', 'Spain'],
                },
                {
                  id: 'cities',
                  label: 'Cities',
                  maxResults: 4,
                  source: async (query, { signal }) => {
                    const response = await fetch('https://samline.github.io/autocomplete/cities.json', {
                      signal,
                    })
                    const payload = await response.json()
                    return payload.results
                      .filter(city => city.name.toLowerCase().includes(query.toLowerCase()))
                      .map(city => city.name)
                  },
                },
              ],
              minLength: 2,
              recent: { label: 'Recent' },
            },
          })
        </script>
      </body>
    </html>
    

    Package / ESM

    HTML

    index.html
    <!doctype html>
    <html lang="en">
      <head>
        <meta charset="utf-8" />
        <meta name="viewport" content="width=device-width, initial-scale=1" />
        <title>Group several sources and remember recent picks</title>
        <link rel="stylesheet" href="./style.css" />
      </head>
      <body>
        <main>
          <div class="field">
            <label for="place">Country or city</label>
            <input id="place" type="text" placeholder="Try “sp” or “ja”" />
          </div>
        </main>
        <script type="module" src="./main.js"></script>
      </body>
    </html>
    

    CSS

    style.css
    .field {
      position: relative;
      max-width: 28rem;
      margin-bottom: 0.75rem;
    }
    label {
      display: block;
      margin-bottom: 0.5rem;
      font-weight: 600;
    }
    input {
      width: 100%;
      padding: 0.75rem 1rem;
      border: 1px solid #aaa;
      border-radius: 0.5rem;
      font: inherit;
    }
    

    JavaScript

    main.js
    import { Autocomplete } from '@samline/autocomplete/browser'
    import '@samline/autocomplete/style.css'
    
    Autocomplete.newAutocomplete({
      id: 'place',
      options: {
        sections: [
          {
            id: 'countries',
            label: 'Countries',
            source: ['Argentina', 'Canada', 'Japan', 'Mexico', 'Portugal', 'Spain'],
          },
          {
            id: 'cities',
            label: 'Cities',
            maxResults: 4,
            source: async (query, { signal }) => {
              const response = await fetch('https://samline.github.io/autocomplete/cities.json', {
                signal,
              })
              const payload = await response.json()
              return payload.results
                .filter(city => city.name.toLowerCase().includes(query.toLowerCase()))
                .map(city => city.name)
            },
          },
        ],
        minLength: 2,
        recent: { label: 'Recent' },
      },
    })
    

    Complete file

    index.html
    <!doctype html>
    <html lang="en">
      <head>
        <meta charset="utf-8" />
        <meta name="viewport" content="width=device-width, initial-scale=1" />
        <title>Group several sources and remember recent picks</title>
        <style>
          .field {
            position: relative;
            max-width: 28rem;
            margin-bottom: 0.75rem;
          }
          label {
            display: block;
            margin-bottom: 0.5rem;
            font-weight: 600;
          }
          input {
            width: 100%;
            padding: 0.75rem 1rem;
            border: 1px solid #aaa;
            border-radius: 0.5rem;
            font: inherit;
          }
        </style>
      </head>
      <body>
        <main>
          <div class="field">
            <label for="place">Country or city</label>
            <input id="place" type="text" placeholder="Try “sp” or “ja”" />
          </div>
        </main>
        <script type="module">
          import { Autocomplete } from '@samline/autocomplete/browser'
          import '@samline/autocomplete/style.css'
    
          Autocomplete.newAutocomplete({
            id: 'place',
            options: {
              sections: [
                {
                  id: 'countries',
                  label: 'Countries',
                  source: ['Argentina', 'Canada', 'Japan', 'Mexico', 'Portugal', 'Spain'],
                },
                {
                  id: 'cities',
                  label: 'Cities',
                  maxResults: 4,
                  source: async (query, { signal }) => {
                    const response = await fetch('https://samline.github.io/autocomplete/cities.json', {
                      signal,
                    })
                    const payload = await response.json()
                    return payload.results
                      .filter(city => city.name.toLowerCase().includes(query.toLowerCase()))
                      .map(city => city.name)
                  },
                },
              ],
              minLength: 2,
              recent: { label: 'Recent' },
            },
          })
        </script>
      </body>
    </html>
    

    Submit an id with a form

    FormsLive preview

    hiddenInput creates a named hidden field that holds the selected id and empties when the text changes. popover renders the list in the top layer, so it escapes the card’s overflow: hidden.

    Nothing submitted yet.

    Explore the code

    HTML / CDN

    HTML

    index.html
    <!doctype html>
    <html lang="en">
      <head>
        <meta charset="utf-8" />
        <meta name="viewport" content="width=device-width, initial-scale=1" />
        <title>Submit an id with a form</title>
        <link
          rel="stylesheet"
          href="https://cdn.jsdelivr.net/npm/@samline/autocomplete@3.0.0/dist/style.css"
        />
        <link rel="stylesheet" href="./style.css" />
      </head>
      <body>
        <main>
          <form id="trip" class="card">
            <div class="field">
              <label for="destination-city">Destination</label>
              <input id="destination-city" type="text" />
            </div>
            <button type="submit">Submit</button>
          </form>
          <p id="submitted" aria-live="polite">Nothing submitted yet.</p>
        </main>
        <script src="https://cdn.jsdelivr.net/npm/@samline/autocomplete@3.0.0/dist/browser/autocomplete.global.js"></script>
        <script src="./main.js" defer></script>
      </body>
    </html>
    

    CSS

    style.css
    .field {
      position: relative;
      max-width: 28rem;
      margin-bottom: 0.75rem;
    }
    label {
      display: block;
      margin-bottom: 0.5rem;
      font-weight: 600;
    }
    input {
      width: 100%;
      padding: 0.75rem 1rem;
      border: 1px solid #aaa;
      border-radius: 0.5rem;
      font: inherit;
    }
    .card {
      overflow: hidden;
      max-width: 28rem;
      padding: 1rem;
      border: 1px solid #aaa;
      border-radius: 0.75rem;
    }
    

    JavaScript

    main.js
    window.Autocomplete.newAutocomplete({
      id: 'destination-city',
      options: {
        endpoint: 'https://samline.github.io/autocomplete/cities.json',
        mapResponse: (payload, response, query) =>
          payload.results.filter(city => city.name.toLowerCase().includes(query.toLowerCase())),
        getId: city => city.key,
        getLabel: city => city.name,
        hiddenInput: 'city_id',
        popover: true,
      },
    })
    
    document.querySelector('#trip').addEventListener('submit', event => {
      event.preventDefault()
      const cityId = new FormData(event.currentTarget).get('city_id')
      document.querySelector('#submitted').textContent = cityId
        ? `Submitted city_id=${cityId}.`
        : 'Pick a city first.'
    })
    

    Complete file

    index.html
    <!doctype html>
    <html lang="en">
      <head>
        <meta charset="utf-8" />
        <meta name="viewport" content="width=device-width, initial-scale=1" />
        <title>Submit an id with a form</title>
        <link
          rel="stylesheet"
          href="https://cdn.jsdelivr.net/npm/@samline/autocomplete@3.0.0/dist/style.css"
        />
        <style>
          .field {
            position: relative;
            max-width: 28rem;
            margin-bottom: 0.75rem;
          }
          label {
            display: block;
            margin-bottom: 0.5rem;
            font-weight: 600;
          }
          input {
            width: 100%;
            padding: 0.75rem 1rem;
            border: 1px solid #aaa;
            border-radius: 0.5rem;
            font: inherit;
          }
          .card {
            overflow: hidden;
            max-width: 28rem;
            padding: 1rem;
            border: 1px solid #aaa;
            border-radius: 0.75rem;
          }
        </style>
      </head>
      <body>
        <main>
          <form id="trip" class="card">
            <div class="field">
              <label for="destination-city">Destination</label>
              <input id="destination-city" type="text" />
            </div>
            <button type="submit">Submit</button>
          </form>
          <p id="submitted" aria-live="polite">Nothing submitted yet.</p>
        </main>
        <script src="https://cdn.jsdelivr.net/npm/@samline/autocomplete@3.0.0/dist/browser/autocomplete.global.js"></script>
        <script>
          window.Autocomplete.newAutocomplete({
            id: 'destination-city',
            options: {
              endpoint: 'https://samline.github.io/autocomplete/cities.json',
              mapResponse: (payload, response, query) =>
                payload.results.filter(city => city.name.toLowerCase().includes(query.toLowerCase())),
              getId: city => city.key,
              getLabel: city => city.name,
              hiddenInput: 'city_id',
              popover: true,
            },
          })
    
          document.querySelector('#trip').addEventListener('submit', event => {
            event.preventDefault()
            const cityId = new FormData(event.currentTarget).get('city_id')
            document.querySelector('#submitted').textContent = cityId
              ? `Submitted city_id=${cityId}.`
              : 'Pick a city first.'
          })
        </script>
      </body>
    </html>
    

    Package / ESM

    HTML

    index.html
    <!doctype html>
    <html lang="en">
      <head>
        <meta charset="utf-8" />
        <meta name="viewport" content="width=device-width, initial-scale=1" />
        <title>Submit an id with a form</title>
        <link rel="stylesheet" href="./style.css" />
      </head>
      <body>
        <main>
          <form id="trip" class="card">
            <div class="field">
              <label for="destination-city">Destination</label>
              <input id="destination-city" type="text" />
            </div>
            <button type="submit">Submit</button>
          </form>
          <p id="submitted" aria-live="polite">Nothing submitted yet.</p>
        </main>
        <script type="module" src="./main.js"></script>
      </body>
    </html>
    

    CSS

    style.css
    .field {
      position: relative;
      max-width: 28rem;
      margin-bottom: 0.75rem;
    }
    label {
      display: block;
      margin-bottom: 0.5rem;
      font-weight: 600;
    }
    input {
      width: 100%;
      padding: 0.75rem 1rem;
      border: 1px solid #aaa;
      border-radius: 0.5rem;
      font: inherit;
    }
    .card {
      overflow: hidden;
      max-width: 28rem;
      padding: 1rem;
      border: 1px solid #aaa;
      border-radius: 0.75rem;
    }
    

    JavaScript

    main.js
    import { Autocomplete } from '@samline/autocomplete/browser'
    import '@samline/autocomplete/style.css'
    
    Autocomplete.newAutocomplete({
      id: 'destination-city',
      options: {
        endpoint: 'https://samline.github.io/autocomplete/cities.json',
        mapResponse: (payload, response, query) =>
          payload.results.filter(city => city.name.toLowerCase().includes(query.toLowerCase())),
        getId: city => city.key,
        getLabel: city => city.name,
        hiddenInput: 'city_id',
        popover: true,
      },
    })
    
    document.querySelector('#trip').addEventListener('submit', event => {
      event.preventDefault()
      const cityId = new FormData(event.currentTarget).get('city_id')
      document.querySelector('#submitted').textContent = cityId
        ? `Submitted city_id=${cityId}.`
        : 'Pick a city first.'
    })
    

    Complete file

    index.html
    <!doctype html>
    <html lang="en">
      <head>
        <meta charset="utf-8" />
        <meta name="viewport" content="width=device-width, initial-scale=1" />
        <title>Submit an id with a form</title>
        <style>
          .field {
            position: relative;
            max-width: 28rem;
            margin-bottom: 0.75rem;
          }
          label {
            display: block;
            margin-bottom: 0.5rem;
            font-weight: 600;
          }
          input {
            width: 100%;
            padding: 0.75rem 1rem;
            border: 1px solid #aaa;
            border-radius: 0.5rem;
            font: inherit;
          }
          .card {
            overflow: hidden;
            max-width: 28rem;
            padding: 1rem;
            border: 1px solid #aaa;
            border-radius: 0.75rem;
          }
        </style>
      </head>
      <body>
        <main>
          <form id="trip" class="card">
            <div class="field">
              <label for="destination-city">Destination</label>
              <input id="destination-city" type="text" />
            </div>
            <button type="submit">Submit</button>
          </form>
          <p id="submitted" aria-live="polite">Nothing submitted yet.</p>
        </main>
        <script type="module">
          import { Autocomplete } from '@samline/autocomplete/browser'
          import '@samline/autocomplete/style.css'
    
          Autocomplete.newAutocomplete({
            id: 'destination-city',
            options: {
              endpoint: 'https://samline.github.io/autocomplete/cities.json',
              mapResponse: (payload, response, query) =>
                payload.results.filter(city => city.name.toLowerCase().includes(query.toLowerCase())),
              getId: city => city.key,
              getLabel: city => city.name,
              hiddenInput: 'city_id',
              popover: true,
            },
          })
    
          document.querySelector('#trip').addEventListener('submit', event => {
            event.preventDefault()
            const cityId = new FormData(event.currentTarget).get('city_id')
            document.querySelector('#submitted').textContent = cityId
              ? `Submitted city_id=${cityId}.`
              : 'Pick a city first.'
          })
        </script>
      </body>
    </html>
    

    Configure it with data attributes

    No JavaScriptLive preview

    The standalone script mounts every input with data-autocomplete. Point it at an endpoint or a JSON list and tune it with data-autocomplete-* attributes, without writing a line of JavaScript.

    Explore the code

    HTML / CDN

    HTML

    index.html
    <!doctype html>
    <html lang="en">
      <head>
        <meta charset="utf-8" />
        <meta name="viewport" content="width=device-width, initial-scale=1" />
        <title>Configure it with data attributes</title>
        <link
          rel="stylesheet"
          href="https://cdn.jsdelivr.net/npm/@samline/autocomplete@3.0.0/dist/style.css"
        />
        <link rel="stylesheet" href="./style.css" />
      </head>
      <body>
        <main>
          <script type="application/json" id="fruits">
            ["Aguacate", "Guayaba", "Limón", "Mamey", "Mango", "Papaya", "Pitahaya", "Tamarindo"]
          </script>
    
          <div class="field">
            <label for="fruit">Fruit</label>
            <input
              id="fruit"
              type="text"
              data-autocomplete
              data-autocomplete-source="#fruits"
              data-autocomplete-empty="No fruit matches"
            />
          </div>
        </main>
        <script src="https://cdn.jsdelivr.net/npm/@samline/autocomplete@3.0.0/dist/browser/autocomplete.global.js"></script>
        <script src="./main.js" defer></script>
      </body>
    </html>
    

    CSS

    style.css
    .field {
      position: relative;
      max-width: 28rem;
      margin-bottom: 0.75rem;
    }
    label {
      display: block;
      margin-bottom: 0.5rem;
      font-weight: 600;
    }
    input {
      width: 100%;
      padding: 0.75rem 1rem;
      border: 1px solid #aaa;
      border-radius: 0.5rem;
      font: inherit;
    }
    

    JavaScript

    main.js
    // Nothing to write: the browser bundle mounts input[data-autocomplete] on load.
    // Read a mounted controller with window.Autocomplete.getAutocomplete('fruit').
    

    Complete file

    index.html
    <!doctype html>
    <html lang="en">
      <head>
        <meta charset="utf-8" />
        <meta name="viewport" content="width=device-width, initial-scale=1" />
        <title>Configure it with data attributes</title>
        <link
          rel="stylesheet"
          href="https://cdn.jsdelivr.net/npm/@samline/autocomplete@3.0.0/dist/style.css"
        />
        <style>
          .field {
            position: relative;
            max-width: 28rem;
            margin-bottom: 0.75rem;
          }
          label {
            display: block;
            margin-bottom: 0.5rem;
            font-weight: 600;
          }
          input {
            width: 100%;
            padding: 0.75rem 1rem;
            border: 1px solid #aaa;
            border-radius: 0.5rem;
            font: inherit;
          }
        </style>
      </head>
      <body>
        <main>
          <script type="application/json" id="fruits">
            ["Aguacate", "Guayaba", "Limón", "Mamey", "Mango", "Papaya", "Pitahaya", "Tamarindo"]
          </script>
    
          <div class="field">
            <label for="fruit">Fruit</label>
            <input
              id="fruit"
              type="text"
              data-autocomplete
              data-autocomplete-source="#fruits"
              data-autocomplete-empty="No fruit matches"
            />
          </div>
        </main>
        <script src="https://cdn.jsdelivr.net/npm/@samline/autocomplete@3.0.0/dist/browser/autocomplete.global.js"></script>
        <script>
          // Nothing to write: the browser bundle mounts input[data-autocomplete] on load.
          // Read a mounted controller with window.Autocomplete.getAutocomplete('fruit').
        </script>
      </body>
    </html>
    

    Package / ESM

    HTML

    index.html
    <!doctype html>
    <html lang="en">
      <head>
        <meta charset="utf-8" />
        <meta name="viewport" content="width=device-width, initial-scale=1" />
        <title>Configure it with data attributes</title>
        <link rel="stylesheet" href="./style.css" />
      </head>
      <body>
        <main>
          <script type="application/json" id="fruits">
            ["Aguacate", "Guayaba", "Limón", "Mamey", "Mango", "Papaya", "Pitahaya", "Tamarindo"]
          </script>
    
          <div class="field">
            <label for="fruit">Fruit</label>
            <input
              id="fruit"
              type="text"
              data-autocomplete
              data-autocomplete-source="#fruits"
              data-autocomplete-empty="No fruit matches"
            />
          </div>
        </main>
        <script type="module" src="./main.js"></script>
      </body>
    </html>
    

    CSS

    style.css
    .field {
      position: relative;
      max-width: 28rem;
      margin-bottom: 0.75rem;
    }
    label {
      display: block;
      margin-bottom: 0.5rem;
      font-weight: 600;
    }
    input {
      width: 100%;
      padding: 0.75rem 1rem;
      border: 1px solid #aaa;
      border-radius: 0.5rem;
      font: inherit;
    }
    

    JavaScript

    main.js
    import { Autocomplete } from '@samline/autocomplete/browser'
    import '@samline/autocomplete/style.css'
    
    Autocomplete.mount()
    

    Complete file

    index.html
    <!doctype html>
    <html lang="en">
      <head>
        <meta charset="utf-8" />
        <meta name="viewport" content="width=device-width, initial-scale=1" />
        <title>Configure it with data attributes</title>
        <style>
          .field {
            position: relative;
            max-width: 28rem;
            margin-bottom: 0.75rem;
          }
          label {
            display: block;
            margin-bottom: 0.5rem;
            font-weight: 600;
          }
          input {
            width: 100%;
            padding: 0.75rem 1rem;
            border: 1px solid #aaa;
            border-radius: 0.5rem;
            font: inherit;
          }
        </style>
      </head>
      <body>
        <main>
          <script type="application/json" id="fruits">
            ["Aguacate", "Guayaba", "Limón", "Mamey", "Mango", "Papaya", "Pitahaya", "Tamarindo"]
          </script>
    
          <div class="field">
            <label for="fruit">Fruit</label>
            <input
              id="fruit"
              type="text"
              data-autocomplete
              data-autocomplete-source="#fruits"
              data-autocomplete-empty="No fruit matches"
            />
          </div>
        </main>
        <script type="module">
          import { Autocomplete } from '@samline/autocomplete/browser'
          import '@samline/autocomplete/style.css'
    
          Autocomplete.mount()
        </script>
      </body>
    </html>
    

    Select several items as removable pills

    PillsLive preview

    Switch where the pills live: inside the field next to the input, or in their own list below it. The suggestions always open below the whole field, because the example moves controller.popupElement after it. transformSuggestions hides chosen teams and each pill is submitted as a repeated teams[] field; this composes the single-selection API, it is not a built-in multiple mode. With an empty input, Backspace focuses the last pill, Delete removes it, arrows move between pills and Escape returns to typing.

    Show selected teams

      With no text, Backspace focuses the last pill and Delete removes it.

      No teams selected.

      Nothing submitted yet.

      Explore the code

      HTML / CDN

      HTML

      index.html
      <!doctype html>
      <html lang="en">
        <head>
          <meta charset="utf-8" />
          <meta name="viewport" content="width=device-width, initial-scale=1" />
          <title>Select several items as removable pills</title>
          <link
            rel="stylesheet"
            href="https://cdn.jsdelivr.net/npm/@samline/autocomplete@3.0.0/dist/style.css"
          />
          <link rel="stylesheet" href="./style.css" />
        </head>
        <body>
          <main>
            <div data-example="pills">
              <fieldset class="layout">
                <legend>Show selected teams</legend>
                <label
                  ><input type="radio" name="pills-layout" value="inside" checked /> Inside the
                  field</label
                >
                <label><input type="radio" name="pills-layout" value="below" /> Below the field</label>
              </fieldset>
              <form>
                <div class="field">
                  <label for="pills-input">Teams</label>
                  <div class="pill-field">
                    <ul data-pills aria-label="Selected teams"></ul>
                    <input
                      id="pills-input"
                      type="text"
                      aria-describedby="pills-help"
                      placeholder="Add a team"
                    />
                  </div>
                </div>
                <div data-pills-below></div>
                <p id="pills-help">
                  With no text, Backspace focuses the last pill and Delete removes it.
                </p>
                <div data-values></div>
                <p data-announcement role="status">No teams selected.</p>
                <div class="actions">
                  <button type="submit">Submit teams</button><button type="reset">Reset teams</button>
                </div>
                <p data-submitted aria-live="polite">Nothing submitted yet.</p>
              </form>
            </div>
          </main>
          <script src="https://cdn.jsdelivr.net/npm/@samline/autocomplete@3.0.0/dist/browser/autocomplete.global.js"></script>
          <script src="./main.js" defer></script>
        </body>
      </html>
      

      CSS

      style.css
      [data-example] {
        display: grid;
        gap: 0.75rem;
      }
      /* Forms lay out like the example root: actions never touch the fields. */
      [data-example] form {
        display: grid;
        gap: 0.75rem;
      }
      [data-example] .field {
        position: relative;
      }
      [data-example] label {
        display: block;
        margin-bottom: 0.5rem;
      }
      [data-example] input[type='text'] {
        box-sizing: border-box;
        width: 100%;
        padding: 0.75rem 1rem;
        border: 1px solid var(--color-border, #888);
        border-radius: 0.5rem;
        background: var(--color-bg-soft, #fff);
        color: inherit;
        font: inherit;
      }
      [data-example] button {
        padding: 0.5rem 0.75rem;
        border: 1px solid var(--color-border, #888);
        border-radius: 0.5rem;
        background: var(--color-bg-soft, #fff);
        color: inherit;
        font: inherit;
        cursor: pointer;
      }
      [data-example] button:focus-visible,
      [data-example] input:focus-visible {
        outline: 2px solid currentColor;
        outline-offset: 3px;
      }
      [data-example] p {
        margin: 0;
        overflow-wrap: anywhere;
      }
      [data-example] .actions {
        display: flex;
        flex-wrap: wrap;
        gap: 0.5rem;
      }
      [data-example] [data-pills] {
        display: flex;
        flex-wrap: wrap;
        gap: 0.375rem;
        margin: 0;
        padding: 0;
        list-style: none;
      }
      [data-example] [data-pills]:empty {
        display: none;
      }
      [data-example] .pill {
        display: flex;
        max-width: 100%;
      }
      [data-example] .pill button {
        box-sizing: border-box;
        display: inline-flex;
        align-items: center;
        gap: 0.375rem;
        max-width: 100%;
        height: 2rem;
        padding: 0 0.625rem;
        border: 1px solid var(--color-border, #888);
        border-radius: 1rem;
        background: var(--color-bg, #f4f4f5);
        color: inherit;
        font: inherit;
        font-size: 0.875rem;
        line-height: 1;
        overflow-wrap: anywhere;
        cursor: pointer;
      }
      [data-example] .pill button:hover {
        background: var(--color-bg-soft, #e4e4e7);
      }
      [data-example] .pill button svg {
        width: 0.875rem;
        height: 0.875rem;
        flex: none;
        fill: none;
        stroke: currentColor;
        stroke-width: 2;
        stroke-linecap: round;
        opacity: 0.7;
      }
      [data-example] .pill button:hover svg {
        opacity: 1;
      }
      [data-example] .pill-field {
        display: flex;
        flex-wrap: wrap;
        align-items: center;
        gap: 0.375rem;
        box-sizing: border-box;
        min-height: 3.125rem;
        padding: 0.5rem 0.75rem;
        border: 1px solid var(--color-border, #888);
        border-radius: 0.5rem;
        background: var(--color-bg-soft, #fff);
        cursor: text;
      }
      [data-example] .pill-field:focus-within {
        outline: 2px solid currentColor;
        outline-offset: 2px;
      }
      [data-example] .pill-field input[type='text'] {
        flex: 1 1 8rem;
        width: auto;
        min-width: 0;
        height: 2rem;
        padding: 0;
        border: 0;
        background: transparent;
      }
      [data-example] .pill-field input[type='text']:focus-visible {
        outline: none;
      }
      /* The popup sits after the whole field and overlays what follows it. */
      [data-example='pills'] {
        --autocomplete-max-height: 10rem;
      }
      [data-example='pills'] form {
        display: grid;
        gap: 0.5rem;
      }
      [data-example='pills'] .field [data-autocomplete-popup] {
        position: absolute;
        top: 100%;
      }
      /* One reserved pill row: switching layouts never shifts what follows. */
      [data-example] [data-pills-below] {
        min-height: 2.25rem;
      }
      [data-example] .layout {
        display: flex;
        flex-wrap: wrap;
        gap: 0.25rem;
        margin: 0;
        padding: 0.25rem;
        border: 1px solid var(--color-border, #888);
        border-radius: 0.625rem;
        justify-self: start;
      }
      [data-example] .layout legend {
        position: absolute;
        width: 1px;
        height: 1px;
        overflow: hidden;
        clip-path: inset(50%);
        white-space: nowrap;
      }
      [data-example] .layout label {
        position: relative;
        display: flex;
        align-items: center;
        margin: 0;
        padding: 0.375rem 0.75rem;
        border-radius: 0.375rem;
        font-size: 0.875rem;
        cursor: pointer;
      }
      [data-example] .layout input {
        position: absolute;
        inset: 0;
        width: 100%;
        height: 100%;
        margin: 0;
        opacity: 0;
        pointer-events: none;
      }
      [data-example] .layout label:has(:checked) {
        background: var(--color-bg-soft, #e4e4e7);
        box-shadow: inset 0 0 0 1px var(--color-border, #888);
        font-weight: 600;
      }
      [data-example] .layout label:has(:focus-visible) {
        outline: 2px solid currentColor;
        outline-offset: 2px;
      }
      [data-example] .directory {
        display: grid;
        gap: 0.5rem;
        padding: 0;
        margin: 0;
        list-style: none;
      }
      [data-example] .directory button {
        width: 100%;
        text-align: left;
      }
      [data-example] [aria-disabled='true'] {
        opacity: 0.65;
      }
      [data-example] select {
        padding: 0.75rem 1rem;
        border: 1px solid var(--color-border, #888);
        border-radius: 0.5rem;
        background: var(--color-bg-soft, #fff);
        color: inherit;
        font: inherit;
      }
      [data-example] input[type='text']:disabled {
        opacity: 0.65;
        cursor: not-allowed;
      }
      [data-example] [data-autocomplete-option] small {
        display: block;
        opacity: 0.75;
      }
      [data-example] kbd {
        float: right;
        padding: 0 0.375rem;
        border: 1px solid currentColor;
        border-radius: 0.25rem;
        font:
          0.75rem/1.5 ui-monospace,
          monospace;
        opacity: 0.75;
      }
      

      JavaScript

      main.js
      const setup = (root, createAutocomplete) => {
        const form = root.querySelector('form')
        const input = root.querySelector('input[type="text"]')
        const pills = root.querySelector('[data-pills]')
        const field = root.querySelector('.pill-field')
        const below = root.querySelector('[data-pills-below]')
        const values = root.querySelector('[data-values]')
        const announcement = root.querySelector('[data-announcement]')
        const submitted = root.querySelector('[data-submitted]')
        const selected = /* @__PURE__ */ new Map()
        const events = new AbortController()
        const source = [
          {
            id: 'design',
            label: 'Design',
          },
          {
            id: 'engineering',
            label: 'Engineering',
          },
          {
            id: 'marketing',
            label: 'Marketing',
          },
          {
            id: 'operations',
            label: 'Operations',
          },
          {
            id: 'support',
            label: 'Support',
          },
        ]
        const render = () => {
          pills.replaceChildren()
          values.replaceChildren()
          for (const item of selected.values()) {
            const pill = document.createElement('li')
            pill.className = 'pill'
            const remove = document.createElement('button')
            remove.type = 'button'
            remove.setAttribute('aria-label', `Remove ${item.label}`)
            const label = document.createElement('span')
            label.textContent = item.label
            const icon = document.createElementNS('http://www.w3.org/2000/svg', 'svg')
            icon.setAttribute('viewBox', '0 0 24 24')
            icon.setAttribute('aria-hidden', 'true')
            icon.innerHTML = '<path d="M6 6l12 12M18 6 6 18" />'
            remove.append(label, icon)
            remove.addEventListener('click', () => {
              selected.delete(item.id)
              render()
              controller.clear()
              input.focus()
              announcement.textContent = `${item.label} removed. ${selected.size} selected.`
            })
            pill.append(remove)
            pills.append(pill)
            const hidden = document.createElement('input')
            hidden.type = 'hidden'
            hidden.name = 'teams[]'
            hidden.value = item.id
            values.append(hidden)
          }
        }
        const controller = createAutocomplete(input, {
          source,
          minLength: 0,
          debounce: 0,
          placement: 'bottom',
          getId: item => item.id,
          getLabel: item => item.label,
          transformSuggestions: items => items.filter(item => !selected.has(item.id)),
          beforeSelect: item => !selected.has(item.id),
          messages: { empty: 'No more matching teams.' },
          onSelect: item => {
            selected.set(item.id, item)
            render()
            controller.clear()
            announcement.textContent = `${item.label} added. ${selected.size} selected.`
          },
        })
        field.after(controller.popupElement)
        const place = layout => {
          if (layout === 'inside') field.prepend(pills)
          else below.append(pills)
        }
        root
          .querySelector('.layout')
          .addEventListener('change', event => place(event.target.value), { signal: events.signal })
        place(root.querySelector('.layout input:checked').value)
        field.addEventListener(
          'click',
          event => {
            if (event.target === field) input.focus()
          },
          { signal: events.signal }
        )
        render()
        input.addEventListener(
          'keydown',
          event => {
            if (event.isComposing || input.value || !selected.size) return
            if (event.key === 'Backspace' || event.key === 'ArrowLeft') {
              event.preventDefault()
              controller.close()
              pills.querySelector('li:last-child button')?.focus()
            }
          },
          { signal: events.signal }
        )
        pills.addEventListener(
          'keydown',
          event => {
            const buttons = [...pills.querySelectorAll('button')]
            const index = buttons.indexOf(document.activeElement)
            if (index < 0 || event.isComposing) return
            if (event.key === 'Backspace' || event.key === 'Delete') {
              event.preventDefault()
              buttons[index].click()
            } else if (event.key === 'ArrowLeft' || event.key === 'ArrowRight') {
              event.preventDefault()
              ;(buttons[index + (event.key === 'ArrowLeft' ? -1 : 1)] ?? input).focus()
            } else if (event.key === 'Escape') {
              event.preventDefault()
              input.focus()
            }
          },
          { signal: events.signal }
        )
        form.addEventListener(
          'submit',
          event => {
            event.preventDefault()
            const ids = new FormData(form).getAll('teams[]')
            submitted.textContent = ids.length
              ? `Submitted teams: ${ids.join(', ')}.`
              : 'Select at least one team.'
          },
          { signal: events.signal }
        )
        form.addEventListener(
          'reset',
          () => {
            selected.clear()
            render()
            controller.clear()
            announcement.textContent = 'All teams removed.'
            submitted.textContent = 'Nothing submitted yet.'
          },
          { signal: events.signal }
        )
        return () => {
          events.abort()
          controller.destroy()
          field.prepend(pills)
          pills.replaceChildren()
          values.replaceChildren()
        }
      }
      setup(document, window.Autocomplete.autocomplete)
      

      Complete file

      index.html
      <!doctype html>
      <html lang="en">
        <head>
          <meta charset="utf-8" />
          <meta name="viewport" content="width=device-width, initial-scale=1" />
          <title>Select several items as removable pills</title>
          <link
            rel="stylesheet"
            href="https://cdn.jsdelivr.net/npm/@samline/autocomplete@3.0.0/dist/style.css"
          />
          <style>
            [data-example] {
              display: grid;
              gap: 0.75rem;
            }
            /* Forms lay out like the example root: actions never touch the fields. */
            [data-example] form {
              display: grid;
              gap: 0.75rem;
            }
            [data-example] .field {
              position: relative;
            }
            [data-example] label {
              display: block;
              margin-bottom: 0.5rem;
            }
            [data-example] input[type='text'] {
              box-sizing: border-box;
              width: 100%;
              padding: 0.75rem 1rem;
              border: 1px solid var(--color-border, #888);
              border-radius: 0.5rem;
              background: var(--color-bg-soft, #fff);
              color: inherit;
              font: inherit;
            }
            [data-example] button {
              padding: 0.5rem 0.75rem;
              border: 1px solid var(--color-border, #888);
              border-radius: 0.5rem;
              background: var(--color-bg-soft, #fff);
              color: inherit;
              font: inherit;
              cursor: pointer;
            }
            [data-example] button:focus-visible,
            [data-example] input:focus-visible {
              outline: 2px solid currentColor;
              outline-offset: 3px;
            }
            [data-example] p {
              margin: 0;
              overflow-wrap: anywhere;
            }
            [data-example] .actions {
              display: flex;
              flex-wrap: wrap;
              gap: 0.5rem;
            }
            [data-example] [data-pills] {
              display: flex;
              flex-wrap: wrap;
              gap: 0.375rem;
              margin: 0;
              padding: 0;
              list-style: none;
            }
            [data-example] [data-pills]:empty {
              display: none;
            }
            [data-example] .pill {
              display: flex;
              max-width: 100%;
            }
            [data-example] .pill button {
              box-sizing: border-box;
              display: inline-flex;
              align-items: center;
              gap: 0.375rem;
              max-width: 100%;
              height: 2rem;
              padding: 0 0.625rem;
              border: 1px solid var(--color-border, #888);
              border-radius: 1rem;
              background: var(--color-bg, #f4f4f5);
              color: inherit;
              font: inherit;
              font-size: 0.875rem;
              line-height: 1;
              overflow-wrap: anywhere;
              cursor: pointer;
            }
            [data-example] .pill button:hover {
              background: var(--color-bg-soft, #e4e4e7);
            }
            [data-example] .pill button svg {
              width: 0.875rem;
              height: 0.875rem;
              flex: none;
              fill: none;
              stroke: currentColor;
              stroke-width: 2;
              stroke-linecap: round;
              opacity: 0.7;
            }
            [data-example] .pill button:hover svg {
              opacity: 1;
            }
            [data-example] .pill-field {
              display: flex;
              flex-wrap: wrap;
              align-items: center;
              gap: 0.375rem;
              box-sizing: border-box;
              min-height: 3.125rem;
              padding: 0.5rem 0.75rem;
              border: 1px solid var(--color-border, #888);
              border-radius: 0.5rem;
              background: var(--color-bg-soft, #fff);
              cursor: text;
            }
            [data-example] .pill-field:focus-within {
              outline: 2px solid currentColor;
              outline-offset: 2px;
            }
            [data-example] .pill-field input[type='text'] {
              flex: 1 1 8rem;
              width: auto;
              min-width: 0;
              height: 2rem;
              padding: 0;
              border: 0;
              background: transparent;
            }
            [data-example] .pill-field input[type='text']:focus-visible {
              outline: none;
            }
            /* The popup sits after the whole field and overlays what follows it. */
            [data-example='pills'] {
              --autocomplete-max-height: 10rem;
            }
            [data-example='pills'] form {
              display: grid;
              gap: 0.5rem;
            }
            [data-example='pills'] .field [data-autocomplete-popup] {
              position: absolute;
              top: 100%;
            }
            /* One reserved pill row: switching layouts never shifts what follows. */
            [data-example] [data-pills-below] {
              min-height: 2.25rem;
            }
            [data-example] .layout {
              display: flex;
              flex-wrap: wrap;
              gap: 0.25rem;
              margin: 0;
              padding: 0.25rem;
              border: 1px solid var(--color-border, #888);
              border-radius: 0.625rem;
              justify-self: start;
            }
            [data-example] .layout legend {
              position: absolute;
              width: 1px;
              height: 1px;
              overflow: hidden;
              clip-path: inset(50%);
              white-space: nowrap;
            }
            [data-example] .layout label {
              position: relative;
              display: flex;
              align-items: center;
              margin: 0;
              padding: 0.375rem 0.75rem;
              border-radius: 0.375rem;
              font-size: 0.875rem;
              cursor: pointer;
            }
            [data-example] .layout input {
              position: absolute;
              inset: 0;
              width: 100%;
              height: 100%;
              margin: 0;
              opacity: 0;
              pointer-events: none;
            }
            [data-example] .layout label:has(:checked) {
              background: var(--color-bg-soft, #e4e4e7);
              box-shadow: inset 0 0 0 1px var(--color-border, #888);
              font-weight: 600;
            }
            [data-example] .layout label:has(:focus-visible) {
              outline: 2px solid currentColor;
              outline-offset: 2px;
            }
            [data-example] .directory {
              display: grid;
              gap: 0.5rem;
              padding: 0;
              margin: 0;
              list-style: none;
            }
            [data-example] .directory button {
              width: 100%;
              text-align: left;
            }
            [data-example] [aria-disabled='true'] {
              opacity: 0.65;
            }
            [data-example] select {
              padding: 0.75rem 1rem;
              border: 1px solid var(--color-border, #888);
              border-radius: 0.5rem;
              background: var(--color-bg-soft, #fff);
              color: inherit;
              font: inherit;
            }
            [data-example] input[type='text']:disabled {
              opacity: 0.65;
              cursor: not-allowed;
            }
            [data-example] [data-autocomplete-option] small {
              display: block;
              opacity: 0.75;
            }
            [data-example] kbd {
              float: right;
              padding: 0 0.375rem;
              border: 1px solid currentColor;
              border-radius: 0.25rem;
              font:
                0.75rem/1.5 ui-monospace,
                monospace;
              opacity: 0.75;
            }
          </style>
        </head>
        <body>
          <main>
            <div data-example="pills">
              <fieldset class="layout">
                <legend>Show selected teams</legend>
                <label
                  ><input type="radio" name="pills-layout" value="inside" checked /> Inside the
                  field</label
                >
                <label><input type="radio" name="pills-layout" value="below" /> Below the field</label>
              </fieldset>
              <form>
                <div class="field">
                  <label for="pills-input">Teams</label>
                  <div class="pill-field">
                    <ul data-pills aria-label="Selected teams"></ul>
                    <input
                      id="pills-input"
                      type="text"
                      aria-describedby="pills-help"
                      placeholder="Add a team"
                    />
                  </div>
                </div>
                <div data-pills-below></div>
                <p id="pills-help">
                  With no text, Backspace focuses the last pill and Delete removes it.
                </p>
                <div data-values></div>
                <p data-announcement role="status">No teams selected.</p>
                <div class="actions">
                  <button type="submit">Submit teams</button><button type="reset">Reset teams</button>
                </div>
                <p data-submitted aria-live="polite">Nothing submitted yet.</p>
              </form>
            </div>
          </main>
          <script src="https://cdn.jsdelivr.net/npm/@samline/autocomplete@3.0.0/dist/browser/autocomplete.global.js"></script>
          <script>
            const setup = (root, createAutocomplete) => {
              const form = root.querySelector('form')
              const input = root.querySelector('input[type="text"]')
              const pills = root.querySelector('[data-pills]')
              const field = root.querySelector('.pill-field')
              const below = root.querySelector('[data-pills-below]')
              const values = root.querySelector('[data-values]')
              const announcement = root.querySelector('[data-announcement]')
              const submitted = root.querySelector('[data-submitted]')
              const selected = /* @__PURE__ */ new Map()
              const events = new AbortController()
              const source = [
                {
                  id: 'design',
                  label: 'Design',
                },
                {
                  id: 'engineering',
                  label: 'Engineering',
                },
                {
                  id: 'marketing',
                  label: 'Marketing',
                },
                {
                  id: 'operations',
                  label: 'Operations',
                },
                {
                  id: 'support',
                  label: 'Support',
                },
              ]
              const render = () => {
                pills.replaceChildren()
                values.replaceChildren()
                for (const item of selected.values()) {
                  const pill = document.createElement('li')
                  pill.className = 'pill'
                  const remove = document.createElement('button')
                  remove.type = 'button'
                  remove.setAttribute('aria-label', `Remove ${item.label}`)
                  const label = document.createElement('span')
                  label.textContent = item.label
                  const icon = document.createElementNS('http://www.w3.org/2000/svg', 'svg')
                  icon.setAttribute('viewBox', '0 0 24 24')
                  icon.setAttribute('aria-hidden', 'true')
                  icon.innerHTML = '<path d="M6 6l12 12M18 6 6 18" />'
                  remove.append(label, icon)
                  remove.addEventListener('click', () => {
                    selected.delete(item.id)
                    render()
                    controller.clear()
                    input.focus()
                    announcement.textContent = `${item.label} removed. ${selected.size} selected.`
                  })
                  pill.append(remove)
                  pills.append(pill)
                  const hidden = document.createElement('input')
                  hidden.type = 'hidden'
                  hidden.name = 'teams[]'
                  hidden.value = item.id
                  values.append(hidden)
                }
              }
              const controller = createAutocomplete(input, {
                source,
                minLength: 0,
                debounce: 0,
                placement: 'bottom',
                getId: item => item.id,
                getLabel: item => item.label,
                transformSuggestions: items => items.filter(item => !selected.has(item.id)),
                beforeSelect: item => !selected.has(item.id),
                messages: { empty: 'No more matching teams.' },
                onSelect: item => {
                  selected.set(item.id, item)
                  render()
                  controller.clear()
                  announcement.textContent = `${item.label} added. ${selected.size} selected.`
                },
              })
              field.after(controller.popupElement)
              const place = layout => {
                if (layout === 'inside') field.prepend(pills)
                else below.append(pills)
              }
              root
                .querySelector('.layout')
                .addEventListener('change', event => place(event.target.value), { signal: events.signal })
              place(root.querySelector('.layout input:checked').value)
              field.addEventListener(
                'click',
                event => {
                  if (event.target === field) input.focus()
                },
                { signal: events.signal }
              )
              render()
              input.addEventListener(
                'keydown',
                event => {
                  if (event.isComposing || input.value || !selected.size) return
                  if (event.key === 'Backspace' || event.key === 'ArrowLeft') {
                    event.preventDefault()
                    controller.close()
                    pills.querySelector('li:last-child button')?.focus()
                  }
                },
                { signal: events.signal }
              )
              pills.addEventListener(
                'keydown',
                event => {
                  const buttons = [...pills.querySelectorAll('button')]
                  const index = buttons.indexOf(document.activeElement)
                  if (index < 0 || event.isComposing) return
                  if (event.key === 'Backspace' || event.key === 'Delete') {
                    event.preventDefault()
                    buttons[index].click()
                  } else if (event.key === 'ArrowLeft' || event.key === 'ArrowRight') {
                    event.preventDefault()
                    ;(buttons[index + (event.key === 'ArrowLeft' ? -1 : 1)] ?? input).focus()
                  } else if (event.key === 'Escape') {
                    event.preventDefault()
                    input.focus()
                  }
                },
                { signal: events.signal }
              )
              form.addEventListener(
                'submit',
                event => {
                  event.preventDefault()
                  const ids = new FormData(form).getAll('teams[]')
                  submitted.textContent = ids.length
                    ? `Submitted teams: ${ids.join(', ')}.`
                    : 'Select at least one team.'
                },
                { signal: events.signal }
              )
              form.addEventListener(
                'reset',
                () => {
                  selected.clear()
                  render()
                  controller.clear()
                  announcement.textContent = 'All teams removed.'
                  submitted.textContent = 'Nothing submitted yet.'
                },
                { signal: events.signal }
              )
              return () => {
                events.abort()
                controller.destroy()
                field.prepend(pills)
                pills.replaceChildren()
                values.replaceChildren()
              }
            }
            setup(document, window.Autocomplete.autocomplete)
          </script>
        </body>
      </html>
      

      Package / ESM

      HTML

      index.html
      <!doctype html>
      <html lang="en">
        <head>
          <meta charset="utf-8" />
          <meta name="viewport" content="width=device-width, initial-scale=1" />
          <title>Select several items as removable pills</title>
          <link rel="stylesheet" href="./style.css" />
        </head>
        <body>
          <main>
            <div data-example="pills">
              <fieldset class="layout">
                <legend>Show selected teams</legend>
                <label
                  ><input type="radio" name="pills-layout" value="inside" checked /> Inside the
                  field</label
                >
                <label><input type="radio" name="pills-layout" value="below" /> Below the field</label>
              </fieldset>
              <form>
                <div class="field">
                  <label for="pills-input">Teams</label>
                  <div class="pill-field">
                    <ul data-pills aria-label="Selected teams"></ul>
                    <input
                      id="pills-input"
                      type="text"
                      aria-describedby="pills-help"
                      placeholder="Add a team"
                    />
                  </div>
                </div>
                <div data-pills-below></div>
                <p id="pills-help">
                  With no text, Backspace focuses the last pill and Delete removes it.
                </p>
                <div data-values></div>
                <p data-announcement role="status">No teams selected.</p>
                <div class="actions">
                  <button type="submit">Submit teams</button><button type="reset">Reset teams</button>
                </div>
                <p data-submitted aria-live="polite">Nothing submitted yet.</p>
              </form>
            </div>
          </main>
          <script type="module" src="./main.js"></script>
        </body>
      </html>
      

      CSS

      style.css
      [data-example] {
        display: grid;
        gap: 0.75rem;
      }
      /* Forms lay out like the example root: actions never touch the fields. */
      [data-example] form {
        display: grid;
        gap: 0.75rem;
      }
      [data-example] .field {
        position: relative;
      }
      [data-example] label {
        display: block;
        margin-bottom: 0.5rem;
      }
      [data-example] input[type='text'] {
        box-sizing: border-box;
        width: 100%;
        padding: 0.75rem 1rem;
        border: 1px solid var(--color-border, #888);
        border-radius: 0.5rem;
        background: var(--color-bg-soft, #fff);
        color: inherit;
        font: inherit;
      }
      [data-example] button {
        padding: 0.5rem 0.75rem;
        border: 1px solid var(--color-border, #888);
        border-radius: 0.5rem;
        background: var(--color-bg-soft, #fff);
        color: inherit;
        font: inherit;
        cursor: pointer;
      }
      [data-example] button:focus-visible,
      [data-example] input:focus-visible {
        outline: 2px solid currentColor;
        outline-offset: 3px;
      }
      [data-example] p {
        margin: 0;
        overflow-wrap: anywhere;
      }
      [data-example] .actions {
        display: flex;
        flex-wrap: wrap;
        gap: 0.5rem;
      }
      [data-example] [data-pills] {
        display: flex;
        flex-wrap: wrap;
        gap: 0.375rem;
        margin: 0;
        padding: 0;
        list-style: none;
      }
      [data-example] [data-pills]:empty {
        display: none;
      }
      [data-example] .pill {
        display: flex;
        max-width: 100%;
      }
      [data-example] .pill button {
        box-sizing: border-box;
        display: inline-flex;
        align-items: center;
        gap: 0.375rem;
        max-width: 100%;
        height: 2rem;
        padding: 0 0.625rem;
        border: 1px solid var(--color-border, #888);
        border-radius: 1rem;
        background: var(--color-bg, #f4f4f5);
        color: inherit;
        font: inherit;
        font-size: 0.875rem;
        line-height: 1;
        overflow-wrap: anywhere;
        cursor: pointer;
      }
      [data-example] .pill button:hover {
        background: var(--color-bg-soft, #e4e4e7);
      }
      [data-example] .pill button svg {
        width: 0.875rem;
        height: 0.875rem;
        flex: none;
        fill: none;
        stroke: currentColor;
        stroke-width: 2;
        stroke-linecap: round;
        opacity: 0.7;
      }
      [data-example] .pill button:hover svg {
        opacity: 1;
      }
      [data-example] .pill-field {
        display: flex;
        flex-wrap: wrap;
        align-items: center;
        gap: 0.375rem;
        box-sizing: border-box;
        min-height: 3.125rem;
        padding: 0.5rem 0.75rem;
        border: 1px solid var(--color-border, #888);
        border-radius: 0.5rem;
        background: var(--color-bg-soft, #fff);
        cursor: text;
      }
      [data-example] .pill-field:focus-within {
        outline: 2px solid currentColor;
        outline-offset: 2px;
      }
      [data-example] .pill-field input[type='text'] {
        flex: 1 1 8rem;
        width: auto;
        min-width: 0;
        height: 2rem;
        padding: 0;
        border: 0;
        background: transparent;
      }
      [data-example] .pill-field input[type='text']:focus-visible {
        outline: none;
      }
      /* The popup sits after the whole field and overlays what follows it. */
      [data-example='pills'] {
        --autocomplete-max-height: 10rem;
      }
      [data-example='pills'] form {
        display: grid;
        gap: 0.5rem;
      }
      [data-example='pills'] .field [data-autocomplete-popup] {
        position: absolute;
        top: 100%;
      }
      /* One reserved pill row: switching layouts never shifts what follows. */
      [data-example] [data-pills-below] {
        min-height: 2.25rem;
      }
      [data-example] .layout {
        display: flex;
        flex-wrap: wrap;
        gap: 0.25rem;
        margin: 0;
        padding: 0.25rem;
        border: 1px solid var(--color-border, #888);
        border-radius: 0.625rem;
        justify-self: start;
      }
      [data-example] .layout legend {
        position: absolute;
        width: 1px;
        height: 1px;
        overflow: hidden;
        clip-path: inset(50%);
        white-space: nowrap;
      }
      [data-example] .layout label {
        position: relative;
        display: flex;
        align-items: center;
        margin: 0;
        padding: 0.375rem 0.75rem;
        border-radius: 0.375rem;
        font-size: 0.875rem;
        cursor: pointer;
      }
      [data-example] .layout input {
        position: absolute;
        inset: 0;
        width: 100%;
        height: 100%;
        margin: 0;
        opacity: 0;
        pointer-events: none;
      }
      [data-example] .layout label:has(:checked) {
        background: var(--color-bg-soft, #e4e4e7);
        box-shadow: inset 0 0 0 1px var(--color-border, #888);
        font-weight: 600;
      }
      [data-example] .layout label:has(:focus-visible) {
        outline: 2px solid currentColor;
        outline-offset: 2px;
      }
      [data-example] .directory {
        display: grid;
        gap: 0.5rem;
        padding: 0;
        margin: 0;
        list-style: none;
      }
      [data-example] .directory button {
        width: 100%;
        text-align: left;
      }
      [data-example] [aria-disabled='true'] {
        opacity: 0.65;
      }
      [data-example] select {
        padding: 0.75rem 1rem;
        border: 1px solid var(--color-border, #888);
        border-radius: 0.5rem;
        background: var(--color-bg-soft, #fff);
        color: inherit;
        font: inherit;
      }
      [data-example] input[type='text']:disabled {
        opacity: 0.65;
        cursor: not-allowed;
      }
      [data-example] [data-autocomplete-option] small {
        display: block;
        opacity: 0.75;
      }
      [data-example] kbd {
        float: right;
        padding: 0 0.375rem;
        border: 1px solid currentColor;
        border-radius: 0.25rem;
        font:
          0.75rem/1.5 ui-monospace,
          monospace;
        opacity: 0.75;
      }
      

      JavaScript

      main.js
      import { autocomplete } from '@samline/autocomplete'
      import '@samline/autocomplete/style.css'
      const setup = (root, createAutocomplete) => {
        const form = root.querySelector('form')
        const input = root.querySelector('input[type="text"]')
        const pills = root.querySelector('[data-pills]')
        const field = root.querySelector('.pill-field')
        const below = root.querySelector('[data-pills-below]')
        const values = root.querySelector('[data-values]')
        const announcement = root.querySelector('[data-announcement]')
        const submitted = root.querySelector('[data-submitted]')
        const selected = /* @__PURE__ */ new Map()
        const events = new AbortController()
        const source = [
          {
            id: 'design',
            label: 'Design',
          },
          {
            id: 'engineering',
            label: 'Engineering',
          },
          {
            id: 'marketing',
            label: 'Marketing',
          },
          {
            id: 'operations',
            label: 'Operations',
          },
          {
            id: 'support',
            label: 'Support',
          },
        ]
        const render = () => {
          pills.replaceChildren()
          values.replaceChildren()
          for (const item of selected.values()) {
            const pill = document.createElement('li')
            pill.className = 'pill'
            const remove = document.createElement('button')
            remove.type = 'button'
            remove.setAttribute('aria-label', `Remove ${item.label}`)
            const label = document.createElement('span')
            label.textContent = item.label
            const icon = document.createElementNS('http://www.w3.org/2000/svg', 'svg')
            icon.setAttribute('viewBox', '0 0 24 24')
            icon.setAttribute('aria-hidden', 'true')
            icon.innerHTML = '<path d="M6 6l12 12M18 6 6 18" />'
            remove.append(label, icon)
            remove.addEventListener('click', () => {
              selected.delete(item.id)
              render()
              controller.clear()
              input.focus()
              announcement.textContent = `${item.label} removed. ${selected.size} selected.`
            })
            pill.append(remove)
            pills.append(pill)
            const hidden = document.createElement('input')
            hidden.type = 'hidden'
            hidden.name = 'teams[]'
            hidden.value = item.id
            values.append(hidden)
          }
        }
        const controller = createAutocomplete(input, {
          source,
          minLength: 0,
          debounce: 0,
          placement: 'bottom',
          getId: item => item.id,
          getLabel: item => item.label,
          transformSuggestions: items => items.filter(item => !selected.has(item.id)),
          beforeSelect: item => !selected.has(item.id),
          messages: { empty: 'No more matching teams.' },
          onSelect: item => {
            selected.set(item.id, item)
            render()
            controller.clear()
            announcement.textContent = `${item.label} added. ${selected.size} selected.`
          },
        })
        field.after(controller.popupElement)
        const place = layout => {
          if (layout === 'inside') field.prepend(pills)
          else below.append(pills)
        }
        root
          .querySelector('.layout')
          .addEventListener('change', event => place(event.target.value), { signal: events.signal })
        place(root.querySelector('.layout input:checked').value)
        field.addEventListener(
          'click',
          event => {
            if (event.target === field) input.focus()
          },
          { signal: events.signal }
        )
        render()
        input.addEventListener(
          'keydown',
          event => {
            if (event.isComposing || input.value || !selected.size) return
            if (event.key === 'Backspace' || event.key === 'ArrowLeft') {
              event.preventDefault()
              controller.close()
              pills.querySelector('li:last-child button')?.focus()
            }
          },
          { signal: events.signal }
        )
        pills.addEventListener(
          'keydown',
          event => {
            const buttons = [...pills.querySelectorAll('button')]
            const index = buttons.indexOf(document.activeElement)
            if (index < 0 || event.isComposing) return
            if (event.key === 'Backspace' || event.key === 'Delete') {
              event.preventDefault()
              buttons[index].click()
            } else if (event.key === 'ArrowLeft' || event.key === 'ArrowRight') {
              event.preventDefault()
              ;(buttons[index + (event.key === 'ArrowLeft' ? -1 : 1)] ?? input).focus()
            } else if (event.key === 'Escape') {
              event.preventDefault()
              input.focus()
            }
          },
          { signal: events.signal }
        )
        form.addEventListener(
          'submit',
          event => {
            event.preventDefault()
            const ids = new FormData(form).getAll('teams[]')
            submitted.textContent = ids.length
              ? `Submitted teams: ${ids.join(', ')}.`
              : 'Select at least one team.'
          },
          { signal: events.signal }
        )
        form.addEventListener(
          'reset',
          () => {
            selected.clear()
            render()
            controller.clear()
            announcement.textContent = 'All teams removed.'
            submitted.textContent = 'Nothing submitted yet.'
          },
          { signal: events.signal }
        )
        return () => {
          events.abort()
          controller.destroy()
          field.prepend(pills)
          pills.replaceChildren()
          values.replaceChildren()
        }
      }
      setup(document, autocomplete)
      

      Complete file

      index.html
      <!doctype html>
      <html lang="en">
        <head>
          <meta charset="utf-8" />
          <meta name="viewport" content="width=device-width, initial-scale=1" />
          <title>Select several items as removable pills</title>
          <style>
            [data-example] {
              display: grid;
              gap: 0.75rem;
            }
            /* Forms lay out like the example root: actions never touch the fields. */
            [data-example] form {
              display: grid;
              gap: 0.75rem;
            }
            [data-example] .field {
              position: relative;
            }
            [data-example] label {
              display: block;
              margin-bottom: 0.5rem;
            }
            [data-example] input[type='text'] {
              box-sizing: border-box;
              width: 100%;
              padding: 0.75rem 1rem;
              border: 1px solid var(--color-border, #888);
              border-radius: 0.5rem;
              background: var(--color-bg-soft, #fff);
              color: inherit;
              font: inherit;
            }
            [data-example] button {
              padding: 0.5rem 0.75rem;
              border: 1px solid var(--color-border, #888);
              border-radius: 0.5rem;
              background: var(--color-bg-soft, #fff);
              color: inherit;
              font: inherit;
              cursor: pointer;
            }
            [data-example] button:focus-visible,
            [data-example] input:focus-visible {
              outline: 2px solid currentColor;
              outline-offset: 3px;
            }
            [data-example] p {
              margin: 0;
              overflow-wrap: anywhere;
            }
            [data-example] .actions {
              display: flex;
              flex-wrap: wrap;
              gap: 0.5rem;
            }
            [data-example] [data-pills] {
              display: flex;
              flex-wrap: wrap;
              gap: 0.375rem;
              margin: 0;
              padding: 0;
              list-style: none;
            }
            [data-example] [data-pills]:empty {
              display: none;
            }
            [data-example] .pill {
              display: flex;
              max-width: 100%;
            }
            [data-example] .pill button {
              box-sizing: border-box;
              display: inline-flex;
              align-items: center;
              gap: 0.375rem;
              max-width: 100%;
              height: 2rem;
              padding: 0 0.625rem;
              border: 1px solid var(--color-border, #888);
              border-radius: 1rem;
              background: var(--color-bg, #f4f4f5);
              color: inherit;
              font: inherit;
              font-size: 0.875rem;
              line-height: 1;
              overflow-wrap: anywhere;
              cursor: pointer;
            }
            [data-example] .pill button:hover {
              background: var(--color-bg-soft, #e4e4e7);
            }
            [data-example] .pill button svg {
              width: 0.875rem;
              height: 0.875rem;
              flex: none;
              fill: none;
              stroke: currentColor;
              stroke-width: 2;
              stroke-linecap: round;
              opacity: 0.7;
            }
            [data-example] .pill button:hover svg {
              opacity: 1;
            }
            [data-example] .pill-field {
              display: flex;
              flex-wrap: wrap;
              align-items: center;
              gap: 0.375rem;
              box-sizing: border-box;
              min-height: 3.125rem;
              padding: 0.5rem 0.75rem;
              border: 1px solid var(--color-border, #888);
              border-radius: 0.5rem;
              background: var(--color-bg-soft, #fff);
              cursor: text;
            }
            [data-example] .pill-field:focus-within {
              outline: 2px solid currentColor;
              outline-offset: 2px;
            }
            [data-example] .pill-field input[type='text'] {
              flex: 1 1 8rem;
              width: auto;
              min-width: 0;
              height: 2rem;
              padding: 0;
              border: 0;
              background: transparent;
            }
            [data-example] .pill-field input[type='text']:focus-visible {
              outline: none;
            }
            /* The popup sits after the whole field and overlays what follows it. */
            [data-example='pills'] {
              --autocomplete-max-height: 10rem;
            }
            [data-example='pills'] form {
              display: grid;
              gap: 0.5rem;
            }
            [data-example='pills'] .field [data-autocomplete-popup] {
              position: absolute;
              top: 100%;
            }
            /* One reserved pill row: switching layouts never shifts what follows. */
            [data-example] [data-pills-below] {
              min-height: 2.25rem;
            }
            [data-example] .layout {
              display: flex;
              flex-wrap: wrap;
              gap: 0.25rem;
              margin: 0;
              padding: 0.25rem;
              border: 1px solid var(--color-border, #888);
              border-radius: 0.625rem;
              justify-self: start;
            }
            [data-example] .layout legend {
              position: absolute;
              width: 1px;
              height: 1px;
              overflow: hidden;
              clip-path: inset(50%);
              white-space: nowrap;
            }
            [data-example] .layout label {
              position: relative;
              display: flex;
              align-items: center;
              margin: 0;
              padding: 0.375rem 0.75rem;
              border-radius: 0.375rem;
              font-size: 0.875rem;
              cursor: pointer;
            }
            [data-example] .layout input {
              position: absolute;
              inset: 0;
              width: 100%;
              height: 100%;
              margin: 0;
              opacity: 0;
              pointer-events: none;
            }
            [data-example] .layout label:has(:checked) {
              background: var(--color-bg-soft, #e4e4e7);
              box-shadow: inset 0 0 0 1px var(--color-border, #888);
              font-weight: 600;
            }
            [data-example] .layout label:has(:focus-visible) {
              outline: 2px solid currentColor;
              outline-offset: 2px;
            }
            [data-example] .directory {
              display: grid;
              gap: 0.5rem;
              padding: 0;
              margin: 0;
              list-style: none;
            }
            [data-example] .directory button {
              width: 100%;
              text-align: left;
            }
            [data-example] [aria-disabled='true'] {
              opacity: 0.65;
            }
            [data-example] select {
              padding: 0.75rem 1rem;
              border: 1px solid var(--color-border, #888);
              border-radius: 0.5rem;
              background: var(--color-bg-soft, #fff);
              color: inherit;
              font: inherit;
            }
            [data-example] input[type='text']:disabled {
              opacity: 0.65;
              cursor: not-allowed;
            }
            [data-example] [data-autocomplete-option] small {
              display: block;
              opacity: 0.75;
            }
            [data-example] kbd {
              float: right;
              padding: 0 0.375rem;
              border: 1px solid currentColor;
              border-radius: 0.25rem;
              font:
                0.75rem/1.5 ui-monospace,
                monospace;
              opacity: 0.75;
            }
          </style>
        </head>
        <body>
          <main>
            <div data-example="pills">
              <fieldset class="layout">
                <legend>Show selected teams</legend>
                <label
                  ><input type="radio" name="pills-layout" value="inside" checked /> Inside the
                  field</label
                >
                <label><input type="radio" name="pills-layout" value="below" /> Below the field</label>
              </fieldset>
              <form>
                <div class="field">
                  <label for="pills-input">Teams</label>
                  <div class="pill-field">
                    <ul data-pills aria-label="Selected teams"></ul>
                    <input
                      id="pills-input"
                      type="text"
                      aria-describedby="pills-help"
                      placeholder="Add a team"
                    />
                  </div>
                </div>
                <div data-pills-below></div>
                <p id="pills-help">
                  With no text, Backspace focuses the last pill and Delete removes it.
                </p>
                <div data-values></div>
                <p data-announcement role="status">No teams selected.</p>
                <div class="actions">
                  <button type="submit">Submit teams</button><button type="reset">Reset teams</button>
                </div>
                <p data-submitted aria-live="polite">Nothing submitted yet.</p>
              </form>
            </div>
          </main>
          <script type="module">
            import { autocomplete } from '@samline/autocomplete'
            import '@samline/autocomplete/style.css'
            const setup = (root, createAutocomplete) => {
              const form = root.querySelector('form')
              const input = root.querySelector('input[type="text"]')
              const pills = root.querySelector('[data-pills]')
              const field = root.querySelector('.pill-field')
              const below = root.querySelector('[data-pills-below]')
              const values = root.querySelector('[data-values]')
              const announcement = root.querySelector('[data-announcement]')
              const submitted = root.querySelector('[data-submitted]')
              const selected = /* @__PURE__ */ new Map()
              const events = new AbortController()
              const source = [
                {
                  id: 'design',
                  label: 'Design',
                },
                {
                  id: 'engineering',
                  label: 'Engineering',
                },
                {
                  id: 'marketing',
                  label: 'Marketing',
                },
                {
                  id: 'operations',
                  label: 'Operations',
                },
                {
                  id: 'support',
                  label: 'Support',
                },
              ]
              const render = () => {
                pills.replaceChildren()
                values.replaceChildren()
                for (const item of selected.values()) {
                  const pill = document.createElement('li')
                  pill.className = 'pill'
                  const remove = document.createElement('button')
                  remove.type = 'button'
                  remove.setAttribute('aria-label', `Remove ${item.label}`)
                  const label = document.createElement('span')
                  label.textContent = item.label
                  const icon = document.createElementNS('http://www.w3.org/2000/svg', 'svg')
                  icon.setAttribute('viewBox', '0 0 24 24')
                  icon.setAttribute('aria-hidden', 'true')
                  icon.innerHTML = '<path d="M6 6l12 12M18 6 6 18" />'
                  remove.append(label, icon)
                  remove.addEventListener('click', () => {
                    selected.delete(item.id)
                    render()
                    controller.clear()
                    input.focus()
                    announcement.textContent = `${item.label} removed. ${selected.size} selected.`
                  })
                  pill.append(remove)
                  pills.append(pill)
                  const hidden = document.createElement('input')
                  hidden.type = 'hidden'
                  hidden.name = 'teams[]'
                  hidden.value = item.id
                  values.append(hidden)
                }
              }
              const controller = createAutocomplete(input, {
                source,
                minLength: 0,
                debounce: 0,
                placement: 'bottom',
                getId: item => item.id,
                getLabel: item => item.label,
                transformSuggestions: items => items.filter(item => !selected.has(item.id)),
                beforeSelect: item => !selected.has(item.id),
                messages: { empty: 'No more matching teams.' },
                onSelect: item => {
                  selected.set(item.id, item)
                  render()
                  controller.clear()
                  announcement.textContent = `${item.label} added. ${selected.size} selected.`
                },
              })
              field.after(controller.popupElement)
              const place = layout => {
                if (layout === 'inside') field.prepend(pills)
                else below.append(pills)
              }
              root
                .querySelector('.layout')
                .addEventListener('change', event => place(event.target.value), { signal: events.signal })
              place(root.querySelector('.layout input:checked').value)
              field.addEventListener(
                'click',
                event => {
                  if (event.target === field) input.focus()
                },
                { signal: events.signal }
              )
              render()
              input.addEventListener(
                'keydown',
                event => {
                  if (event.isComposing || input.value || !selected.size) return
                  if (event.key === 'Backspace' || event.key === 'ArrowLeft') {
                    event.preventDefault()
                    controller.close()
                    pills.querySelector('li:last-child button')?.focus()
                  }
                },
                { signal: events.signal }
              )
              pills.addEventListener(
                'keydown',
                event => {
                  const buttons = [...pills.querySelectorAll('button')]
                  const index = buttons.indexOf(document.activeElement)
                  if (index < 0 || event.isComposing) return
                  if (event.key === 'Backspace' || event.key === 'Delete') {
                    event.preventDefault()
                    buttons[index].click()
                  } else if (event.key === 'ArrowLeft' || event.key === 'ArrowRight') {
                    event.preventDefault()
                    ;(buttons[index + (event.key === 'ArrowLeft' ? -1 : 1)] ?? input).focus()
                  } else if (event.key === 'Escape') {
                    event.preventDefault()
                    input.focus()
                  }
                },
                { signal: events.signal }
              )
              form.addEventListener(
                'submit',
                event => {
                  event.preventDefault()
                  const ids = new FormData(form).getAll('teams[]')
                  submitted.textContent = ids.length
                    ? `Submitted teams: ${ids.join(', ')}.`
                    : 'Select at least one team.'
                },
                { signal: events.signal }
              )
              form.addEventListener(
                'reset',
                () => {
                  selected.clear()
                  render()
                  controller.clear()
                  announcement.textContent = 'All teams removed.'
                  submitted.textContent = 'Nothing submitted yet.'
                },
                { signal: events.signal }
              )
              return () => {
                events.abort()
                controller.destroy()
                field.prepend(pills)
                pills.replaceChildren()
                values.replaceChildren()
              }
            }
            setup(document, autocomplete)
          </script>
        </body>
      </html>
      

      Normalize, deduplicate and guard selections

      HooksLive preview

      Type “#de” to strip the # before searching and see one Design result despite duplicate source records. Type “en” and try Enterprise: beforeSelect rejects it and keeps the list open. No source-specific behavior is added to the package.

      Search with an optional # prefix.

      Explore the code

      HTML / CDN

      HTML

      index.html
      <!doctype html>
      <html lang="en">
        <head>
          <meta charset="utf-8" />
          <meta name="viewport" content="width=device-width, initial-scale=1" />
          <title>Normalize, deduplicate and guard selections</title>
          <link
            rel="stylesheet"
            href="https://cdn.jsdelivr.net/npm/@samline/autocomplete@3.0.0/dist/style.css"
          />
          <link rel="stylesheet" href="./style.css" />
        </head>
        <body>
          <main>
            <div data-example="hooks">
              <div class="field">
                <label for="hooks-input">Team</label
                ><input id="hooks-input" type="text" placeholder="Try #de or en" />
              </div>
              <p data-note role="status">Search with an optional # prefix.</p>
            </div>
          </main>
          <script src="https://cdn.jsdelivr.net/npm/@samline/autocomplete@3.0.0/dist/browser/autocomplete.global.js"></script>
          <script src="./main.js" defer></script>
        </body>
      </html>
      

      CSS

      style.css
      [data-example] {
        display: grid;
        gap: 0.75rem;
      }
      /* Forms lay out like the example root: actions never touch the fields. */
      [data-example] form {
        display: grid;
        gap: 0.75rem;
      }
      [data-example] .field {
        position: relative;
      }
      [data-example] label {
        display: block;
        margin-bottom: 0.5rem;
      }
      [data-example] input[type='text'] {
        box-sizing: border-box;
        width: 100%;
        padding: 0.75rem 1rem;
        border: 1px solid var(--color-border, #888);
        border-radius: 0.5rem;
        background: var(--color-bg-soft, #fff);
        color: inherit;
        font: inherit;
      }
      [data-example] button {
        padding: 0.5rem 0.75rem;
        border: 1px solid var(--color-border, #888);
        border-radius: 0.5rem;
        background: var(--color-bg-soft, #fff);
        color: inherit;
        font: inherit;
        cursor: pointer;
      }
      [data-example] button:focus-visible,
      [data-example] input:focus-visible {
        outline: 2px solid currentColor;
        outline-offset: 3px;
      }
      [data-example] p {
        margin: 0;
        overflow-wrap: anywhere;
      }
      [data-example] .actions {
        display: flex;
        flex-wrap: wrap;
        gap: 0.5rem;
      }
      [data-example] [data-pills] {
        display: flex;
        flex-wrap: wrap;
        gap: 0.375rem;
        margin: 0;
        padding: 0;
        list-style: none;
      }
      [data-example] [data-pills]:empty {
        display: none;
      }
      [data-example] .pill {
        display: flex;
        max-width: 100%;
      }
      [data-example] .pill button {
        box-sizing: border-box;
        display: inline-flex;
        align-items: center;
        gap: 0.375rem;
        max-width: 100%;
        height: 2rem;
        padding: 0 0.625rem;
        border: 1px solid var(--color-border, #888);
        border-radius: 1rem;
        background: var(--color-bg, #f4f4f5);
        color: inherit;
        font: inherit;
        font-size: 0.875rem;
        line-height: 1;
        overflow-wrap: anywhere;
        cursor: pointer;
      }
      [data-example] .pill button:hover {
        background: var(--color-bg-soft, #e4e4e7);
      }
      [data-example] .pill button svg {
        width: 0.875rem;
        height: 0.875rem;
        flex: none;
        fill: none;
        stroke: currentColor;
        stroke-width: 2;
        stroke-linecap: round;
        opacity: 0.7;
      }
      [data-example] .pill button:hover svg {
        opacity: 1;
      }
      [data-example] .pill-field {
        display: flex;
        flex-wrap: wrap;
        align-items: center;
        gap: 0.375rem;
        box-sizing: border-box;
        min-height: 3.125rem;
        padding: 0.5rem 0.75rem;
        border: 1px solid var(--color-border, #888);
        border-radius: 0.5rem;
        background: var(--color-bg-soft, #fff);
        cursor: text;
      }
      [data-example] .pill-field:focus-within {
        outline: 2px solid currentColor;
        outline-offset: 2px;
      }
      [data-example] .pill-field input[type='text'] {
        flex: 1 1 8rem;
        width: auto;
        min-width: 0;
        height: 2rem;
        padding: 0;
        border: 0;
        background: transparent;
      }
      [data-example] .pill-field input[type='text']:focus-visible {
        outline: none;
      }
      /* The popup sits after the whole field and overlays what follows it. */
      [data-example='pills'] {
        --autocomplete-max-height: 10rem;
      }
      [data-example='pills'] form {
        display: grid;
        gap: 0.5rem;
      }
      [data-example='pills'] .field [data-autocomplete-popup] {
        position: absolute;
        top: 100%;
      }
      /* One reserved pill row: switching layouts never shifts what follows. */
      [data-example] [data-pills-below] {
        min-height: 2.25rem;
      }
      [data-example] .layout {
        display: flex;
        flex-wrap: wrap;
        gap: 0.25rem;
        margin: 0;
        padding: 0.25rem;
        border: 1px solid var(--color-border, #888);
        border-radius: 0.625rem;
        justify-self: start;
      }
      [data-example] .layout legend {
        position: absolute;
        width: 1px;
        height: 1px;
        overflow: hidden;
        clip-path: inset(50%);
        white-space: nowrap;
      }
      [data-example] .layout label {
        position: relative;
        display: flex;
        align-items: center;
        margin: 0;
        padding: 0.375rem 0.75rem;
        border-radius: 0.375rem;
        font-size: 0.875rem;
        cursor: pointer;
      }
      [data-example] .layout input {
        position: absolute;
        inset: 0;
        width: 100%;
        height: 100%;
        margin: 0;
        opacity: 0;
        pointer-events: none;
      }
      [data-example] .layout label:has(:checked) {
        background: var(--color-bg-soft, #e4e4e7);
        box-shadow: inset 0 0 0 1px var(--color-border, #888);
        font-weight: 600;
      }
      [data-example] .layout label:has(:focus-visible) {
        outline: 2px solid currentColor;
        outline-offset: 2px;
      }
      [data-example] .directory {
        display: grid;
        gap: 0.5rem;
        padding: 0;
        margin: 0;
        list-style: none;
      }
      [data-example] .directory button {
        width: 100%;
        text-align: left;
      }
      [data-example] [aria-disabled='true'] {
        opacity: 0.65;
      }
      [data-example] select {
        padding: 0.75rem 1rem;
        border: 1px solid var(--color-border, #888);
        border-radius: 0.5rem;
        background: var(--color-bg-soft, #fff);
        color: inherit;
        font: inherit;
      }
      [data-example] input[type='text']:disabled {
        opacity: 0.65;
        cursor: not-allowed;
      }
      [data-example] [data-autocomplete-option] small {
        display: block;
        opacity: 0.75;
      }
      [data-example] kbd {
        float: right;
        padding: 0 0.375rem;
        border: 1px solid currentColor;
        border-radius: 0.25rem;
        font:
          0.75rem/1.5 ui-monospace,
          monospace;
        opacity: 0.75;
      }
      

      JavaScript

      main.js
      const setup = (root, createAutocomplete) => {
        const note = root.querySelector('[data-note]')
        const controller = createAutocomplete(root.querySelector('input'), {
          source: [
            {
              id: 'design',
              label: 'Design',
              enabled: true,
            },
            {
              id: 'design',
              label: 'Design',
              enabled: true,
            },
            {
              id: 'engineering',
              label: 'Engineering',
              enabled: true,
            },
            {
              id: 'enterprise',
              label: 'Enterprise (unavailable)',
              enabled: false,
            },
          ],
          minLength: 1,
          debounce: 0,
          getId: item => item.id,
          getLabel: item => item.label,
          beforeSearch: query => {
            const clean = query.trim().replace(/^#/, '')
            note.textContent = clean ? `Searching for “${clean}”.` : 'Type a team after #.'
            return clean || false
          },
          transformSuggestions: items =>
            [...new Map(items.map(item => [item.id, item])).values()].sort((a, b) =>
              a.label.localeCompare(b.label)
            ),
          beforeSelect: item => {
            if (!item.enabled) {
              note.textContent = 'Enterprise is unavailable. Choose another team.'
              return false
            }
          },
          renderOption: (element, item) => {
            if (!item.enabled) element.setAttribute('aria-disabled', 'true')
          },
          onSelect: item => {
            note.textContent = `Selected ${item.label}.`
          },
        })
        return () => controller.destroy()
      }
      setup(document, window.Autocomplete.autocomplete)
      

      Complete file

      index.html
      <!doctype html>
      <html lang="en">
        <head>
          <meta charset="utf-8" />
          <meta name="viewport" content="width=device-width, initial-scale=1" />
          <title>Normalize, deduplicate and guard selections</title>
          <link
            rel="stylesheet"
            href="https://cdn.jsdelivr.net/npm/@samline/autocomplete@3.0.0/dist/style.css"
          />
          <style>
            [data-example] {
              display: grid;
              gap: 0.75rem;
            }
            /* Forms lay out like the example root: actions never touch the fields. */
            [data-example] form {
              display: grid;
              gap: 0.75rem;
            }
            [data-example] .field {
              position: relative;
            }
            [data-example] label {
              display: block;
              margin-bottom: 0.5rem;
            }
            [data-example] input[type='text'] {
              box-sizing: border-box;
              width: 100%;
              padding: 0.75rem 1rem;
              border: 1px solid var(--color-border, #888);
              border-radius: 0.5rem;
              background: var(--color-bg-soft, #fff);
              color: inherit;
              font: inherit;
            }
            [data-example] button {
              padding: 0.5rem 0.75rem;
              border: 1px solid var(--color-border, #888);
              border-radius: 0.5rem;
              background: var(--color-bg-soft, #fff);
              color: inherit;
              font: inherit;
              cursor: pointer;
            }
            [data-example] button:focus-visible,
            [data-example] input:focus-visible {
              outline: 2px solid currentColor;
              outline-offset: 3px;
            }
            [data-example] p {
              margin: 0;
              overflow-wrap: anywhere;
            }
            [data-example] .actions {
              display: flex;
              flex-wrap: wrap;
              gap: 0.5rem;
            }
            [data-example] [data-pills] {
              display: flex;
              flex-wrap: wrap;
              gap: 0.375rem;
              margin: 0;
              padding: 0;
              list-style: none;
            }
            [data-example] [data-pills]:empty {
              display: none;
            }
            [data-example] .pill {
              display: flex;
              max-width: 100%;
            }
            [data-example] .pill button {
              box-sizing: border-box;
              display: inline-flex;
              align-items: center;
              gap: 0.375rem;
              max-width: 100%;
              height: 2rem;
              padding: 0 0.625rem;
              border: 1px solid var(--color-border, #888);
              border-radius: 1rem;
              background: var(--color-bg, #f4f4f5);
              color: inherit;
              font: inherit;
              font-size: 0.875rem;
              line-height: 1;
              overflow-wrap: anywhere;
              cursor: pointer;
            }
            [data-example] .pill button:hover {
              background: var(--color-bg-soft, #e4e4e7);
            }
            [data-example] .pill button svg {
              width: 0.875rem;
              height: 0.875rem;
              flex: none;
              fill: none;
              stroke: currentColor;
              stroke-width: 2;
              stroke-linecap: round;
              opacity: 0.7;
            }
            [data-example] .pill button:hover svg {
              opacity: 1;
            }
            [data-example] .pill-field {
              display: flex;
              flex-wrap: wrap;
              align-items: center;
              gap: 0.375rem;
              box-sizing: border-box;
              min-height: 3.125rem;
              padding: 0.5rem 0.75rem;
              border: 1px solid var(--color-border, #888);
              border-radius: 0.5rem;
              background: var(--color-bg-soft, #fff);
              cursor: text;
            }
            [data-example] .pill-field:focus-within {
              outline: 2px solid currentColor;
              outline-offset: 2px;
            }
            [data-example] .pill-field input[type='text'] {
              flex: 1 1 8rem;
              width: auto;
              min-width: 0;
              height: 2rem;
              padding: 0;
              border: 0;
              background: transparent;
            }
            [data-example] .pill-field input[type='text']:focus-visible {
              outline: none;
            }
            /* The popup sits after the whole field and overlays what follows it. */
            [data-example='pills'] {
              --autocomplete-max-height: 10rem;
            }
            [data-example='pills'] form {
              display: grid;
              gap: 0.5rem;
            }
            [data-example='pills'] .field [data-autocomplete-popup] {
              position: absolute;
              top: 100%;
            }
            /* One reserved pill row: switching layouts never shifts what follows. */
            [data-example] [data-pills-below] {
              min-height: 2.25rem;
            }
            [data-example] .layout {
              display: flex;
              flex-wrap: wrap;
              gap: 0.25rem;
              margin: 0;
              padding: 0.25rem;
              border: 1px solid var(--color-border, #888);
              border-radius: 0.625rem;
              justify-self: start;
            }
            [data-example] .layout legend {
              position: absolute;
              width: 1px;
              height: 1px;
              overflow: hidden;
              clip-path: inset(50%);
              white-space: nowrap;
            }
            [data-example] .layout label {
              position: relative;
              display: flex;
              align-items: center;
              margin: 0;
              padding: 0.375rem 0.75rem;
              border-radius: 0.375rem;
              font-size: 0.875rem;
              cursor: pointer;
            }
            [data-example] .layout input {
              position: absolute;
              inset: 0;
              width: 100%;
              height: 100%;
              margin: 0;
              opacity: 0;
              pointer-events: none;
            }
            [data-example] .layout label:has(:checked) {
              background: var(--color-bg-soft, #e4e4e7);
              box-shadow: inset 0 0 0 1px var(--color-border, #888);
              font-weight: 600;
            }
            [data-example] .layout label:has(:focus-visible) {
              outline: 2px solid currentColor;
              outline-offset: 2px;
            }
            [data-example] .directory {
              display: grid;
              gap: 0.5rem;
              padding: 0;
              margin: 0;
              list-style: none;
            }
            [data-example] .directory button {
              width: 100%;
              text-align: left;
            }
            [data-example] [aria-disabled='true'] {
              opacity: 0.65;
            }
            [data-example] select {
              padding: 0.75rem 1rem;
              border: 1px solid var(--color-border, #888);
              border-radius: 0.5rem;
              background: var(--color-bg-soft, #fff);
              color: inherit;
              font: inherit;
            }
            [data-example] input[type='text']:disabled {
              opacity: 0.65;
              cursor: not-allowed;
            }
            [data-example] [data-autocomplete-option] small {
              display: block;
              opacity: 0.75;
            }
            [data-example] kbd {
              float: right;
              padding: 0 0.375rem;
              border: 1px solid currentColor;
              border-radius: 0.25rem;
              font:
                0.75rem/1.5 ui-monospace,
                monospace;
              opacity: 0.75;
            }
          </style>
        </head>
        <body>
          <main>
            <div data-example="hooks">
              <div class="field">
                <label for="hooks-input">Team</label
                ><input id="hooks-input" type="text" placeholder="Try #de or en" />
              </div>
              <p data-note role="status">Search with an optional # prefix.</p>
            </div>
          </main>
          <script src="https://cdn.jsdelivr.net/npm/@samline/autocomplete@3.0.0/dist/browser/autocomplete.global.js"></script>
          <script>
            const setup = (root, createAutocomplete) => {
              const note = root.querySelector('[data-note]')
              const controller = createAutocomplete(root.querySelector('input'), {
                source: [
                  {
                    id: 'design',
                    label: 'Design',
                    enabled: true,
                  },
                  {
                    id: 'design',
                    label: 'Design',
                    enabled: true,
                  },
                  {
                    id: 'engineering',
                    label: 'Engineering',
                    enabled: true,
                  },
                  {
                    id: 'enterprise',
                    label: 'Enterprise (unavailable)',
                    enabled: false,
                  },
                ],
                minLength: 1,
                debounce: 0,
                getId: item => item.id,
                getLabel: item => item.label,
                beforeSearch: query => {
                  const clean = query.trim().replace(/^#/, '')
                  note.textContent = clean ? `Searching for “${clean}”.` : 'Type a team after #.'
                  return clean || false
                },
                transformSuggestions: items =>
                  [...new Map(items.map(item => [item.id, item])).values()].sort((a, b) =>
                    a.label.localeCompare(b.label)
                  ),
                beforeSelect: item => {
                  if (!item.enabled) {
                    note.textContent = 'Enterprise is unavailable. Choose another team.'
                    return false
                  }
                },
                renderOption: (element, item) => {
                  if (!item.enabled) element.setAttribute('aria-disabled', 'true')
                },
                onSelect: item => {
                  note.textContent = `Selected ${item.label}.`
                },
              })
              return () => controller.destroy()
            }
            setup(document, window.Autocomplete.autocomplete)
          </script>
        </body>
      </html>
      

      Package / ESM

      HTML

      index.html
      <!doctype html>
      <html lang="en">
        <head>
          <meta charset="utf-8" />
          <meta name="viewport" content="width=device-width, initial-scale=1" />
          <title>Normalize, deduplicate and guard selections</title>
          <link rel="stylesheet" href="./style.css" />
        </head>
        <body>
          <main>
            <div data-example="hooks">
              <div class="field">
                <label for="hooks-input">Team</label
                ><input id="hooks-input" type="text" placeholder="Try #de or en" />
              </div>
              <p data-note role="status">Search with an optional # prefix.</p>
            </div>
          </main>
          <script type="module" src="./main.js"></script>
        </body>
      </html>
      

      CSS

      style.css
      [data-example] {
        display: grid;
        gap: 0.75rem;
      }
      /* Forms lay out like the example root: actions never touch the fields. */
      [data-example] form {
        display: grid;
        gap: 0.75rem;
      }
      [data-example] .field {
        position: relative;
      }
      [data-example] label {
        display: block;
        margin-bottom: 0.5rem;
      }
      [data-example] input[type='text'] {
        box-sizing: border-box;
        width: 100%;
        padding: 0.75rem 1rem;
        border: 1px solid var(--color-border, #888);
        border-radius: 0.5rem;
        background: var(--color-bg-soft, #fff);
        color: inherit;
        font: inherit;
      }
      [data-example] button {
        padding: 0.5rem 0.75rem;
        border: 1px solid var(--color-border, #888);
        border-radius: 0.5rem;
        background: var(--color-bg-soft, #fff);
        color: inherit;
        font: inherit;
        cursor: pointer;
      }
      [data-example] button:focus-visible,
      [data-example] input:focus-visible {
        outline: 2px solid currentColor;
        outline-offset: 3px;
      }
      [data-example] p {
        margin: 0;
        overflow-wrap: anywhere;
      }
      [data-example] .actions {
        display: flex;
        flex-wrap: wrap;
        gap: 0.5rem;
      }
      [data-example] [data-pills] {
        display: flex;
        flex-wrap: wrap;
        gap: 0.375rem;
        margin: 0;
        padding: 0;
        list-style: none;
      }
      [data-example] [data-pills]:empty {
        display: none;
      }
      [data-example] .pill {
        display: flex;
        max-width: 100%;
      }
      [data-example] .pill button {
        box-sizing: border-box;
        display: inline-flex;
        align-items: center;
        gap: 0.375rem;
        max-width: 100%;
        height: 2rem;
        padding: 0 0.625rem;
        border: 1px solid var(--color-border, #888);
        border-radius: 1rem;
        background: var(--color-bg, #f4f4f5);
        color: inherit;
        font: inherit;
        font-size: 0.875rem;
        line-height: 1;
        overflow-wrap: anywhere;
        cursor: pointer;
      }
      [data-example] .pill button:hover {
        background: var(--color-bg-soft, #e4e4e7);
      }
      [data-example] .pill button svg {
        width: 0.875rem;
        height: 0.875rem;
        flex: none;
        fill: none;
        stroke: currentColor;
        stroke-width: 2;
        stroke-linecap: round;
        opacity: 0.7;
      }
      [data-example] .pill button:hover svg {
        opacity: 1;
      }
      [data-example] .pill-field {
        display: flex;
        flex-wrap: wrap;
        align-items: center;
        gap: 0.375rem;
        box-sizing: border-box;
        min-height: 3.125rem;
        padding: 0.5rem 0.75rem;
        border: 1px solid var(--color-border, #888);
        border-radius: 0.5rem;
        background: var(--color-bg-soft, #fff);
        cursor: text;
      }
      [data-example] .pill-field:focus-within {
        outline: 2px solid currentColor;
        outline-offset: 2px;
      }
      [data-example] .pill-field input[type='text'] {
        flex: 1 1 8rem;
        width: auto;
        min-width: 0;
        height: 2rem;
        padding: 0;
        border: 0;
        background: transparent;
      }
      [data-example] .pill-field input[type='text']:focus-visible {
        outline: none;
      }
      /* The popup sits after the whole field and overlays what follows it. */
      [data-example='pills'] {
        --autocomplete-max-height: 10rem;
      }
      [data-example='pills'] form {
        display: grid;
        gap: 0.5rem;
      }
      [data-example='pills'] .field [data-autocomplete-popup] {
        position: absolute;
        top: 100%;
      }
      /* One reserved pill row: switching layouts never shifts what follows. */
      [data-example] [data-pills-below] {
        min-height: 2.25rem;
      }
      [data-example] .layout {
        display: flex;
        flex-wrap: wrap;
        gap: 0.25rem;
        margin: 0;
        padding: 0.25rem;
        border: 1px solid var(--color-border, #888);
        border-radius: 0.625rem;
        justify-self: start;
      }
      [data-example] .layout legend {
        position: absolute;
        width: 1px;
        height: 1px;
        overflow: hidden;
        clip-path: inset(50%);
        white-space: nowrap;
      }
      [data-example] .layout label {
        position: relative;
        display: flex;
        align-items: center;
        margin: 0;
        padding: 0.375rem 0.75rem;
        border-radius: 0.375rem;
        font-size: 0.875rem;
        cursor: pointer;
      }
      [data-example] .layout input {
        position: absolute;
        inset: 0;
        width: 100%;
        height: 100%;
        margin: 0;
        opacity: 0;
        pointer-events: none;
      }
      [data-example] .layout label:has(:checked) {
        background: var(--color-bg-soft, #e4e4e7);
        box-shadow: inset 0 0 0 1px var(--color-border, #888);
        font-weight: 600;
      }
      [data-example] .layout label:has(:focus-visible) {
        outline: 2px solid currentColor;
        outline-offset: 2px;
      }
      [data-example] .directory {
        display: grid;
        gap: 0.5rem;
        padding: 0;
        margin: 0;
        list-style: none;
      }
      [data-example] .directory button {
        width: 100%;
        text-align: left;
      }
      [data-example] [aria-disabled='true'] {
        opacity: 0.65;
      }
      [data-example] select {
        padding: 0.75rem 1rem;
        border: 1px solid var(--color-border, #888);
        border-radius: 0.5rem;
        background: var(--color-bg-soft, #fff);
        color: inherit;
        font: inherit;
      }
      [data-example] input[type='text']:disabled {
        opacity: 0.65;
        cursor: not-allowed;
      }
      [data-example] [data-autocomplete-option] small {
        display: block;
        opacity: 0.75;
      }
      [data-example] kbd {
        float: right;
        padding: 0 0.375rem;
        border: 1px solid currentColor;
        border-radius: 0.25rem;
        font:
          0.75rem/1.5 ui-monospace,
          monospace;
        opacity: 0.75;
      }
      

      JavaScript

      main.js
      import { autocomplete } from '@samline/autocomplete'
      import '@samline/autocomplete/style.css'
      const setup = (root, createAutocomplete) => {
        const note = root.querySelector('[data-note]')
        const controller = createAutocomplete(root.querySelector('input'), {
          source: [
            {
              id: 'design',
              label: 'Design',
              enabled: true,
            },
            {
              id: 'design',
              label: 'Design',
              enabled: true,
            },
            {
              id: 'engineering',
              label: 'Engineering',
              enabled: true,
            },
            {
              id: 'enterprise',
              label: 'Enterprise (unavailable)',
              enabled: false,
            },
          ],
          minLength: 1,
          debounce: 0,
          getId: item => item.id,
          getLabel: item => item.label,
          beforeSearch: query => {
            const clean = query.trim().replace(/^#/, '')
            note.textContent = clean ? `Searching for “${clean}”.` : 'Type a team after #.'
            return clean || false
          },
          transformSuggestions: items =>
            [...new Map(items.map(item => [item.id, item])).values()].sort((a, b) =>
              a.label.localeCompare(b.label)
            ),
          beforeSelect: item => {
            if (!item.enabled) {
              note.textContent = 'Enterprise is unavailable. Choose another team.'
              return false
            }
          },
          renderOption: (element, item) => {
            if (!item.enabled) element.setAttribute('aria-disabled', 'true')
          },
          onSelect: item => {
            note.textContent = `Selected ${item.label}.`
          },
        })
        return () => controller.destroy()
      }
      setup(document, autocomplete)
      

      Complete file

      index.html
      <!doctype html>
      <html lang="en">
        <head>
          <meta charset="utf-8" />
          <meta name="viewport" content="width=device-width, initial-scale=1" />
          <title>Normalize, deduplicate and guard selections</title>
          <style>
            [data-example] {
              display: grid;
              gap: 0.75rem;
            }
            /* Forms lay out like the example root: actions never touch the fields. */
            [data-example] form {
              display: grid;
              gap: 0.75rem;
            }
            [data-example] .field {
              position: relative;
            }
            [data-example] label {
              display: block;
              margin-bottom: 0.5rem;
            }
            [data-example] input[type='text'] {
              box-sizing: border-box;
              width: 100%;
              padding: 0.75rem 1rem;
              border: 1px solid var(--color-border, #888);
              border-radius: 0.5rem;
              background: var(--color-bg-soft, #fff);
              color: inherit;
              font: inherit;
            }
            [data-example] button {
              padding: 0.5rem 0.75rem;
              border: 1px solid var(--color-border, #888);
              border-radius: 0.5rem;
              background: var(--color-bg-soft, #fff);
              color: inherit;
              font: inherit;
              cursor: pointer;
            }
            [data-example] button:focus-visible,
            [data-example] input:focus-visible {
              outline: 2px solid currentColor;
              outline-offset: 3px;
            }
            [data-example] p {
              margin: 0;
              overflow-wrap: anywhere;
            }
            [data-example] .actions {
              display: flex;
              flex-wrap: wrap;
              gap: 0.5rem;
            }
            [data-example] [data-pills] {
              display: flex;
              flex-wrap: wrap;
              gap: 0.375rem;
              margin: 0;
              padding: 0;
              list-style: none;
            }
            [data-example] [data-pills]:empty {
              display: none;
            }
            [data-example] .pill {
              display: flex;
              max-width: 100%;
            }
            [data-example] .pill button {
              box-sizing: border-box;
              display: inline-flex;
              align-items: center;
              gap: 0.375rem;
              max-width: 100%;
              height: 2rem;
              padding: 0 0.625rem;
              border: 1px solid var(--color-border, #888);
              border-radius: 1rem;
              background: var(--color-bg, #f4f4f5);
              color: inherit;
              font: inherit;
              font-size: 0.875rem;
              line-height: 1;
              overflow-wrap: anywhere;
              cursor: pointer;
            }
            [data-example] .pill button:hover {
              background: var(--color-bg-soft, #e4e4e7);
            }
            [data-example] .pill button svg {
              width: 0.875rem;
              height: 0.875rem;
              flex: none;
              fill: none;
              stroke: currentColor;
              stroke-width: 2;
              stroke-linecap: round;
              opacity: 0.7;
            }
            [data-example] .pill button:hover svg {
              opacity: 1;
            }
            [data-example] .pill-field {
              display: flex;
              flex-wrap: wrap;
              align-items: center;
              gap: 0.375rem;
              box-sizing: border-box;
              min-height: 3.125rem;
              padding: 0.5rem 0.75rem;
              border: 1px solid var(--color-border, #888);
              border-radius: 0.5rem;
              background: var(--color-bg-soft, #fff);
              cursor: text;
            }
            [data-example] .pill-field:focus-within {
              outline: 2px solid currentColor;
              outline-offset: 2px;
            }
            [data-example] .pill-field input[type='text'] {
              flex: 1 1 8rem;
              width: auto;
              min-width: 0;
              height: 2rem;
              padding: 0;
              border: 0;
              background: transparent;
            }
            [data-example] .pill-field input[type='text']:focus-visible {
              outline: none;
            }
            /* The popup sits after the whole field and overlays what follows it. */
            [data-example='pills'] {
              --autocomplete-max-height: 10rem;
            }
            [data-example='pills'] form {
              display: grid;
              gap: 0.5rem;
            }
            [data-example='pills'] .field [data-autocomplete-popup] {
              position: absolute;
              top: 100%;
            }
            /* One reserved pill row: switching layouts never shifts what follows. */
            [data-example] [data-pills-below] {
              min-height: 2.25rem;
            }
            [data-example] .layout {
              display: flex;
              flex-wrap: wrap;
              gap: 0.25rem;
              margin: 0;
              padding: 0.25rem;
              border: 1px solid var(--color-border, #888);
              border-radius: 0.625rem;
              justify-self: start;
            }
            [data-example] .layout legend {
              position: absolute;
              width: 1px;
              height: 1px;
              overflow: hidden;
              clip-path: inset(50%);
              white-space: nowrap;
            }
            [data-example] .layout label {
              position: relative;
              display: flex;
              align-items: center;
              margin: 0;
              padding: 0.375rem 0.75rem;
              border-radius: 0.375rem;
              font-size: 0.875rem;
              cursor: pointer;
            }
            [data-example] .layout input {
              position: absolute;
              inset: 0;
              width: 100%;
              height: 100%;
              margin: 0;
              opacity: 0;
              pointer-events: none;
            }
            [data-example] .layout label:has(:checked) {
              background: var(--color-bg-soft, #e4e4e7);
              box-shadow: inset 0 0 0 1px var(--color-border, #888);
              font-weight: 600;
            }
            [data-example] .layout label:has(:focus-visible) {
              outline: 2px solid currentColor;
              outline-offset: 2px;
            }
            [data-example] .directory {
              display: grid;
              gap: 0.5rem;
              padding: 0;
              margin: 0;
              list-style: none;
            }
            [data-example] .directory button {
              width: 100%;
              text-align: left;
            }
            [data-example] [aria-disabled='true'] {
              opacity: 0.65;
            }
            [data-example] select {
              padding: 0.75rem 1rem;
              border: 1px solid var(--color-border, #888);
              border-radius: 0.5rem;
              background: var(--color-bg-soft, #fff);
              color: inherit;
              font: inherit;
            }
            [data-example] input[type='text']:disabled {
              opacity: 0.65;
              cursor: not-allowed;
            }
            [data-example] [data-autocomplete-option] small {
              display: block;
              opacity: 0.75;
            }
            [data-example] kbd {
              float: right;
              padding: 0 0.375rem;
              border: 1px solid currentColor;
              border-radius: 0.25rem;
              font:
                0.75rem/1.5 ui-monospace,
                monospace;
              opacity: 0.75;
            }
          </style>
        </head>
        <body>
          <main>
            <div data-example="hooks">
              <div class="field">
                <label for="hooks-input">Team</label
                ><input id="hooks-input" type="text" placeholder="Try #de or en" />
              </div>
              <p data-note role="status">Search with an optional # prefix.</p>
            </div>
          </main>
          <script type="module">
            import { autocomplete } from '@samline/autocomplete'
            import '@samline/autocomplete/style.css'
            const setup = (root, createAutocomplete) => {
              const note = root.querySelector('[data-note]')
              const controller = createAutocomplete(root.querySelector('input'), {
                source: [
                  {
                    id: 'design',
                    label: 'Design',
                    enabled: true,
                  },
                  {
                    id: 'design',
                    label: 'Design',
                    enabled: true,
                  },
                  {
                    id: 'engineering',
                    label: 'Engineering',
                    enabled: true,
                  },
                  {
                    id: 'enterprise',
                    label: 'Enterprise (unavailable)',
                    enabled: false,
                  },
                ],
                minLength: 1,
                debounce: 0,
                getId: item => item.id,
                getLabel: item => item.label,
                beforeSearch: query => {
                  const clean = query.trim().replace(/^#/, '')
                  note.textContent = clean ? `Searching for “${clean}”.` : 'Type a team after #.'
                  return clean || false
                },
                transformSuggestions: items =>
                  [...new Map(items.map(item => [item.id, item])).values()].sort((a, b) =>
                    a.label.localeCompare(b.label)
                  ),
                beforeSelect: item => {
                  if (!item.enabled) {
                    note.textContent = 'Enterprise is unavailable. Choose another team.'
                    return false
                  }
                },
                renderOption: (element, item) => {
                  if (!item.enabled) element.setAttribute('aria-disabled', 'true')
                },
                onSelect: item => {
                  note.textContent = `Selected ${item.label}.`
                },
              })
              return () => controller.destroy()
            }
            setup(document, autocomplete)
          </script>
        </body>
      </html>
      

      Observe cache hits through a reusable plugin

      Plugins and cacheLive preview

      The telemetry plugin listens to load events and cleans up with destroy. Search for “en”, repeat it to hit the cache, then clear the cache and repeat to call the async source again. max and ttl bound the cache.

      Source calls: 0

      No searches yet.

      Explore the code

      HTML / CDN

      HTML

      index.html
      <!doctype html>
      <html lang="en">
        <head>
          <meta charset="utf-8" />
          <meta name="viewport" content="width=device-width, initial-scale=1" />
          <title>Observe cache hits through a reusable plugin</title>
          <link
            rel="stylesheet"
            href="https://cdn.jsdelivr.net/npm/@samline/autocomplete@3.0.0/dist/style.css"
          />
          <link rel="stylesheet" href="./style.css" />
        </head>
        <body>
          <main>
            <div data-example="plugins">
              <div class="field">
                <label for="plugins-input">Team directory</label
                ><input id="plugins-input" type="text" placeholder="Try en" />
              </div>
              <p data-requests>Source calls: 0</p>
              <p data-note role="status">No searches yet.</p>
              <div class="actions">
                <button type="button" data-repeat>Repeat search</button
                ><button type="button" data-clear-cache>Clear cache</button>
              </div>
            </div>
          </main>
          <script src="https://cdn.jsdelivr.net/npm/@samline/autocomplete@3.0.0/dist/browser/autocomplete.global.js"></script>
          <script src="./main.js" defer></script>
        </body>
      </html>
      

      CSS

      style.css
      [data-example] {
        display: grid;
        gap: 0.75rem;
      }
      /* Forms lay out like the example root: actions never touch the fields. */
      [data-example] form {
        display: grid;
        gap: 0.75rem;
      }
      [data-example] .field {
        position: relative;
      }
      [data-example] label {
        display: block;
        margin-bottom: 0.5rem;
      }
      [data-example] input[type='text'] {
        box-sizing: border-box;
        width: 100%;
        padding: 0.75rem 1rem;
        border: 1px solid var(--color-border, #888);
        border-radius: 0.5rem;
        background: var(--color-bg-soft, #fff);
        color: inherit;
        font: inherit;
      }
      [data-example] button {
        padding: 0.5rem 0.75rem;
        border: 1px solid var(--color-border, #888);
        border-radius: 0.5rem;
        background: var(--color-bg-soft, #fff);
        color: inherit;
        font: inherit;
        cursor: pointer;
      }
      [data-example] button:focus-visible,
      [data-example] input:focus-visible {
        outline: 2px solid currentColor;
        outline-offset: 3px;
      }
      [data-example] p {
        margin: 0;
        overflow-wrap: anywhere;
      }
      [data-example] .actions {
        display: flex;
        flex-wrap: wrap;
        gap: 0.5rem;
      }
      [data-example] [data-pills] {
        display: flex;
        flex-wrap: wrap;
        gap: 0.375rem;
        margin: 0;
        padding: 0;
        list-style: none;
      }
      [data-example] [data-pills]:empty {
        display: none;
      }
      [data-example] .pill {
        display: flex;
        max-width: 100%;
      }
      [data-example] .pill button {
        box-sizing: border-box;
        display: inline-flex;
        align-items: center;
        gap: 0.375rem;
        max-width: 100%;
        height: 2rem;
        padding: 0 0.625rem;
        border: 1px solid var(--color-border, #888);
        border-radius: 1rem;
        background: var(--color-bg, #f4f4f5);
        color: inherit;
        font: inherit;
        font-size: 0.875rem;
        line-height: 1;
        overflow-wrap: anywhere;
        cursor: pointer;
      }
      [data-example] .pill button:hover {
        background: var(--color-bg-soft, #e4e4e7);
      }
      [data-example] .pill button svg {
        width: 0.875rem;
        height: 0.875rem;
        flex: none;
        fill: none;
        stroke: currentColor;
        stroke-width: 2;
        stroke-linecap: round;
        opacity: 0.7;
      }
      [data-example] .pill button:hover svg {
        opacity: 1;
      }
      [data-example] .pill-field {
        display: flex;
        flex-wrap: wrap;
        align-items: center;
        gap: 0.375rem;
        box-sizing: border-box;
        min-height: 3.125rem;
        padding: 0.5rem 0.75rem;
        border: 1px solid var(--color-border, #888);
        border-radius: 0.5rem;
        background: var(--color-bg-soft, #fff);
        cursor: text;
      }
      [data-example] .pill-field:focus-within {
        outline: 2px solid currentColor;
        outline-offset: 2px;
      }
      [data-example] .pill-field input[type='text'] {
        flex: 1 1 8rem;
        width: auto;
        min-width: 0;
        height: 2rem;
        padding: 0;
        border: 0;
        background: transparent;
      }
      [data-example] .pill-field input[type='text']:focus-visible {
        outline: none;
      }
      /* The popup sits after the whole field and overlays what follows it. */
      [data-example='pills'] {
        --autocomplete-max-height: 10rem;
      }
      [data-example='pills'] form {
        display: grid;
        gap: 0.5rem;
      }
      [data-example='pills'] .field [data-autocomplete-popup] {
        position: absolute;
        top: 100%;
      }
      /* One reserved pill row: switching layouts never shifts what follows. */
      [data-example] [data-pills-below] {
        min-height: 2.25rem;
      }
      [data-example] .layout {
        display: flex;
        flex-wrap: wrap;
        gap: 0.25rem;
        margin: 0;
        padding: 0.25rem;
        border: 1px solid var(--color-border, #888);
        border-radius: 0.625rem;
        justify-self: start;
      }
      [data-example] .layout legend {
        position: absolute;
        width: 1px;
        height: 1px;
        overflow: hidden;
        clip-path: inset(50%);
        white-space: nowrap;
      }
      [data-example] .layout label {
        position: relative;
        display: flex;
        align-items: center;
        margin: 0;
        padding: 0.375rem 0.75rem;
        border-radius: 0.375rem;
        font-size: 0.875rem;
        cursor: pointer;
      }
      [data-example] .layout input {
        position: absolute;
        inset: 0;
        width: 100%;
        height: 100%;
        margin: 0;
        opacity: 0;
        pointer-events: none;
      }
      [data-example] .layout label:has(:checked) {
        background: var(--color-bg-soft, #e4e4e7);
        box-shadow: inset 0 0 0 1px var(--color-border, #888);
        font-weight: 600;
      }
      [data-example] .layout label:has(:focus-visible) {
        outline: 2px solid currentColor;
        outline-offset: 2px;
      }
      [data-example] .directory {
        display: grid;
        gap: 0.5rem;
        padding: 0;
        margin: 0;
        list-style: none;
      }
      [data-example] .directory button {
        width: 100%;
        text-align: left;
      }
      [data-example] [aria-disabled='true'] {
        opacity: 0.65;
      }
      [data-example] select {
        padding: 0.75rem 1rem;
        border: 1px solid var(--color-border, #888);
        border-radius: 0.5rem;
        background: var(--color-bg-soft, #fff);
        color: inherit;
        font: inherit;
      }
      [data-example] input[type='text']:disabled {
        opacity: 0.65;
        cursor: not-allowed;
      }
      [data-example] [data-autocomplete-option] small {
        display: block;
        opacity: 0.75;
      }
      [data-example] kbd {
        float: right;
        padding: 0 0.375rem;
        border: 1px solid currentColor;
        border-radius: 0.25rem;
        font:
          0.75rem/1.5 ui-monospace,
          monospace;
        opacity: 0.75;
      }
      

      JavaScript

      main.js
      const setup = (root, createAutocomplete) => {
        const input = root.querySelector('input')
        const note = root.querySelector('[data-note]')
        const requests = root.querySelector('[data-requests]')
        const events = new AbortController()
        let calls = 0
        const telemetry = output => ({
          name: 'search-telemetry',
          setup: controller => {
            return {
              destroy: controller.on('load', ({ query, cached, suggestions }) => {
                output.textContent = `“${query}”: ${suggestions.length} results · ${cached ? 'cache hit' : 'source called'}`
              }),
            }
          },
        })
        const controller = createAutocomplete(input, {
          source: async query => {
            calls += 1
            requests.textContent = `Source calls: ${calls}`
            return ['Design', 'Engineering', 'Marketing'].filter(label =>
              label.toLowerCase().includes(query.toLowerCase())
            )
          },
          popover: true,
          placement: 'top',
          debounce: 0,
          cache: {
            max: 10,
            ttl: 6e4,
          },
          plugins: [telemetry(note)],
        })
        root.querySelector('[data-repeat]').addEventListener(
          'click',
          () => {
            controller.search(input.value || 'en')
          },
          { signal: events.signal }
        )
        root.querySelector('[data-clear-cache]').addEventListener(
          'click',
          () => {
            controller.clearCache()
            note.textContent = 'Cache cleared. Repeat the search to call the source again.'
          },
          { signal: events.signal }
        )
        return () => {
          events.abort()
          controller.destroy()
        }
      }
      setup(document, window.Autocomplete.autocomplete)
      

      Complete file

      index.html
      <!doctype html>
      <html lang="en">
        <head>
          <meta charset="utf-8" />
          <meta name="viewport" content="width=device-width, initial-scale=1" />
          <title>Observe cache hits through a reusable plugin</title>
          <link
            rel="stylesheet"
            href="https://cdn.jsdelivr.net/npm/@samline/autocomplete@3.0.0/dist/style.css"
          />
          <style>
            [data-example] {
              display: grid;
              gap: 0.75rem;
            }
            /* Forms lay out like the example root: actions never touch the fields. */
            [data-example] form {
              display: grid;
              gap: 0.75rem;
            }
            [data-example] .field {
              position: relative;
            }
            [data-example] label {
              display: block;
              margin-bottom: 0.5rem;
            }
            [data-example] input[type='text'] {
              box-sizing: border-box;
              width: 100%;
              padding: 0.75rem 1rem;
              border: 1px solid var(--color-border, #888);
              border-radius: 0.5rem;
              background: var(--color-bg-soft, #fff);
              color: inherit;
              font: inherit;
            }
            [data-example] button {
              padding: 0.5rem 0.75rem;
              border: 1px solid var(--color-border, #888);
              border-radius: 0.5rem;
              background: var(--color-bg-soft, #fff);
              color: inherit;
              font: inherit;
              cursor: pointer;
            }
            [data-example] button:focus-visible,
            [data-example] input:focus-visible {
              outline: 2px solid currentColor;
              outline-offset: 3px;
            }
            [data-example] p {
              margin: 0;
              overflow-wrap: anywhere;
            }
            [data-example] .actions {
              display: flex;
              flex-wrap: wrap;
              gap: 0.5rem;
            }
            [data-example] [data-pills] {
              display: flex;
              flex-wrap: wrap;
              gap: 0.375rem;
              margin: 0;
              padding: 0;
              list-style: none;
            }
            [data-example] [data-pills]:empty {
              display: none;
            }
            [data-example] .pill {
              display: flex;
              max-width: 100%;
            }
            [data-example] .pill button {
              box-sizing: border-box;
              display: inline-flex;
              align-items: center;
              gap: 0.375rem;
              max-width: 100%;
              height: 2rem;
              padding: 0 0.625rem;
              border: 1px solid var(--color-border, #888);
              border-radius: 1rem;
              background: var(--color-bg, #f4f4f5);
              color: inherit;
              font: inherit;
              font-size: 0.875rem;
              line-height: 1;
              overflow-wrap: anywhere;
              cursor: pointer;
            }
            [data-example] .pill button:hover {
              background: var(--color-bg-soft, #e4e4e7);
            }
            [data-example] .pill button svg {
              width: 0.875rem;
              height: 0.875rem;
              flex: none;
              fill: none;
              stroke: currentColor;
              stroke-width: 2;
              stroke-linecap: round;
              opacity: 0.7;
            }
            [data-example] .pill button:hover svg {
              opacity: 1;
            }
            [data-example] .pill-field {
              display: flex;
              flex-wrap: wrap;
              align-items: center;
              gap: 0.375rem;
              box-sizing: border-box;
              min-height: 3.125rem;
              padding: 0.5rem 0.75rem;
              border: 1px solid var(--color-border, #888);
              border-radius: 0.5rem;
              background: var(--color-bg-soft, #fff);
              cursor: text;
            }
            [data-example] .pill-field:focus-within {
              outline: 2px solid currentColor;
              outline-offset: 2px;
            }
            [data-example] .pill-field input[type='text'] {
              flex: 1 1 8rem;
              width: auto;
              min-width: 0;
              height: 2rem;
              padding: 0;
              border: 0;
              background: transparent;
            }
            [data-example] .pill-field input[type='text']:focus-visible {
              outline: none;
            }
            /* The popup sits after the whole field and overlays what follows it. */
            [data-example='pills'] {
              --autocomplete-max-height: 10rem;
            }
            [data-example='pills'] form {
              display: grid;
              gap: 0.5rem;
            }
            [data-example='pills'] .field [data-autocomplete-popup] {
              position: absolute;
              top: 100%;
            }
            /* One reserved pill row: switching layouts never shifts what follows. */
            [data-example] [data-pills-below] {
              min-height: 2.25rem;
            }
            [data-example] .layout {
              display: flex;
              flex-wrap: wrap;
              gap: 0.25rem;
              margin: 0;
              padding: 0.25rem;
              border: 1px solid var(--color-border, #888);
              border-radius: 0.625rem;
              justify-self: start;
            }
            [data-example] .layout legend {
              position: absolute;
              width: 1px;
              height: 1px;
              overflow: hidden;
              clip-path: inset(50%);
              white-space: nowrap;
            }
            [data-example] .layout label {
              position: relative;
              display: flex;
              align-items: center;
              margin: 0;
              padding: 0.375rem 0.75rem;
              border-radius: 0.375rem;
              font-size: 0.875rem;
              cursor: pointer;
            }
            [data-example] .layout input {
              position: absolute;
              inset: 0;
              width: 100%;
              height: 100%;
              margin: 0;
              opacity: 0;
              pointer-events: none;
            }
            [data-example] .layout label:has(:checked) {
              background: var(--color-bg-soft, #e4e4e7);
              box-shadow: inset 0 0 0 1px var(--color-border, #888);
              font-weight: 600;
            }
            [data-example] .layout label:has(:focus-visible) {
              outline: 2px solid currentColor;
              outline-offset: 2px;
            }
            [data-example] .directory {
              display: grid;
              gap: 0.5rem;
              padding: 0;
              margin: 0;
              list-style: none;
            }
            [data-example] .directory button {
              width: 100%;
              text-align: left;
            }
            [data-example] [aria-disabled='true'] {
              opacity: 0.65;
            }
            [data-example] select {
              padding: 0.75rem 1rem;
              border: 1px solid var(--color-border, #888);
              border-radius: 0.5rem;
              background: var(--color-bg-soft, #fff);
              color: inherit;
              font: inherit;
            }
            [data-example] input[type='text']:disabled {
              opacity: 0.65;
              cursor: not-allowed;
            }
            [data-example] [data-autocomplete-option] small {
              display: block;
              opacity: 0.75;
            }
            [data-example] kbd {
              float: right;
              padding: 0 0.375rem;
              border: 1px solid currentColor;
              border-radius: 0.25rem;
              font:
                0.75rem/1.5 ui-monospace,
                monospace;
              opacity: 0.75;
            }
          </style>
        </head>
        <body>
          <main>
            <div data-example="plugins">
              <div class="field">
                <label for="plugins-input">Team directory</label
                ><input id="plugins-input" type="text" placeholder="Try en" />
              </div>
              <p data-requests>Source calls: 0</p>
              <p data-note role="status">No searches yet.</p>
              <div class="actions">
                <button type="button" data-repeat>Repeat search</button
                ><button type="button" data-clear-cache>Clear cache</button>
              </div>
            </div>
          </main>
          <script src="https://cdn.jsdelivr.net/npm/@samline/autocomplete@3.0.0/dist/browser/autocomplete.global.js"></script>
          <script>
            const setup = (root, createAutocomplete) => {
              const input = root.querySelector('input')
              const note = root.querySelector('[data-note]')
              const requests = root.querySelector('[data-requests]')
              const events = new AbortController()
              let calls = 0
              const telemetry = output => ({
                name: 'search-telemetry',
                setup: controller => {
                  return {
                    destroy: controller.on('load', ({ query, cached, suggestions }) => {
                      output.textContent = `“${query}”: ${suggestions.length} results · ${cached ? 'cache hit' : 'source called'}`
                    }),
                  }
                },
              })
              const controller = createAutocomplete(input, {
                source: async query => {
                  calls += 1
                  requests.textContent = `Source calls: ${calls}`
                  return ['Design', 'Engineering', 'Marketing'].filter(label =>
                    label.toLowerCase().includes(query.toLowerCase())
                  )
                },
                popover: true,
                placement: 'top',
                debounce: 0,
                cache: {
                  max: 10,
                  ttl: 6e4,
                },
                plugins: [telemetry(note)],
              })
              root.querySelector('[data-repeat]').addEventListener(
                'click',
                () => {
                  controller.search(input.value || 'en')
                },
                { signal: events.signal }
              )
              root.querySelector('[data-clear-cache]').addEventListener(
                'click',
                () => {
                  controller.clearCache()
                  note.textContent = 'Cache cleared. Repeat the search to call the source again.'
                },
                { signal: events.signal }
              )
              return () => {
                events.abort()
                controller.destroy()
              }
            }
            setup(document, window.Autocomplete.autocomplete)
          </script>
        </body>
      </html>
      

      Package / ESM

      HTML

      index.html
      <!doctype html>
      <html lang="en">
        <head>
          <meta charset="utf-8" />
          <meta name="viewport" content="width=device-width, initial-scale=1" />
          <title>Observe cache hits through a reusable plugin</title>
          <link rel="stylesheet" href="./style.css" />
        </head>
        <body>
          <main>
            <div data-example="plugins">
              <div class="field">
                <label for="plugins-input">Team directory</label
                ><input id="plugins-input" type="text" placeholder="Try en" />
              </div>
              <p data-requests>Source calls: 0</p>
              <p data-note role="status">No searches yet.</p>
              <div class="actions">
                <button type="button" data-repeat>Repeat search</button
                ><button type="button" data-clear-cache>Clear cache</button>
              </div>
            </div>
          </main>
          <script type="module" src="./main.js"></script>
        </body>
      </html>
      

      CSS

      style.css
      [data-example] {
        display: grid;
        gap: 0.75rem;
      }
      /* Forms lay out like the example root: actions never touch the fields. */
      [data-example] form {
        display: grid;
        gap: 0.75rem;
      }
      [data-example] .field {
        position: relative;
      }
      [data-example] label {
        display: block;
        margin-bottom: 0.5rem;
      }
      [data-example] input[type='text'] {
        box-sizing: border-box;
        width: 100%;
        padding: 0.75rem 1rem;
        border: 1px solid var(--color-border, #888);
        border-radius: 0.5rem;
        background: var(--color-bg-soft, #fff);
        color: inherit;
        font: inherit;
      }
      [data-example] button {
        padding: 0.5rem 0.75rem;
        border: 1px solid var(--color-border, #888);
        border-radius: 0.5rem;
        background: var(--color-bg-soft, #fff);
        color: inherit;
        font: inherit;
        cursor: pointer;
      }
      [data-example] button:focus-visible,
      [data-example] input:focus-visible {
        outline: 2px solid currentColor;
        outline-offset: 3px;
      }
      [data-example] p {
        margin: 0;
        overflow-wrap: anywhere;
      }
      [data-example] .actions {
        display: flex;
        flex-wrap: wrap;
        gap: 0.5rem;
      }
      [data-example] [data-pills] {
        display: flex;
        flex-wrap: wrap;
        gap: 0.375rem;
        margin: 0;
        padding: 0;
        list-style: none;
      }
      [data-example] [data-pills]:empty {
        display: none;
      }
      [data-example] .pill {
        display: flex;
        max-width: 100%;
      }
      [data-example] .pill button {
        box-sizing: border-box;
        display: inline-flex;
        align-items: center;
        gap: 0.375rem;
        max-width: 100%;
        height: 2rem;
        padding: 0 0.625rem;
        border: 1px solid var(--color-border, #888);
        border-radius: 1rem;
        background: var(--color-bg, #f4f4f5);
        color: inherit;
        font: inherit;
        font-size: 0.875rem;
        line-height: 1;
        overflow-wrap: anywhere;
        cursor: pointer;
      }
      [data-example] .pill button:hover {
        background: var(--color-bg-soft, #e4e4e7);
      }
      [data-example] .pill button svg {
        width: 0.875rem;
        height: 0.875rem;
        flex: none;
        fill: none;
        stroke: currentColor;
        stroke-width: 2;
        stroke-linecap: round;
        opacity: 0.7;
      }
      [data-example] .pill button:hover svg {
        opacity: 1;
      }
      [data-example] .pill-field {
        display: flex;
        flex-wrap: wrap;
        align-items: center;
        gap: 0.375rem;
        box-sizing: border-box;
        min-height: 3.125rem;
        padding: 0.5rem 0.75rem;
        border: 1px solid var(--color-border, #888);
        border-radius: 0.5rem;
        background: var(--color-bg-soft, #fff);
        cursor: text;
      }
      [data-example] .pill-field:focus-within {
        outline: 2px solid currentColor;
        outline-offset: 2px;
      }
      [data-example] .pill-field input[type='text'] {
        flex: 1 1 8rem;
        width: auto;
        min-width: 0;
        height: 2rem;
        padding: 0;
        border: 0;
        background: transparent;
      }
      [data-example] .pill-field input[type='text']:focus-visible {
        outline: none;
      }
      /* The popup sits after the whole field and overlays what follows it. */
      [data-example='pills'] {
        --autocomplete-max-height: 10rem;
      }
      [data-example='pills'] form {
        display: grid;
        gap: 0.5rem;
      }
      [data-example='pills'] .field [data-autocomplete-popup] {
        position: absolute;
        top: 100%;
      }
      /* One reserved pill row: switching layouts never shifts what follows. */
      [data-example] [data-pills-below] {
        min-height: 2.25rem;
      }
      [data-example] .layout {
        display: flex;
        flex-wrap: wrap;
        gap: 0.25rem;
        margin: 0;
        padding: 0.25rem;
        border: 1px solid var(--color-border, #888);
        border-radius: 0.625rem;
        justify-self: start;
      }
      [data-example] .layout legend {
        position: absolute;
        width: 1px;
        height: 1px;
        overflow: hidden;
        clip-path: inset(50%);
        white-space: nowrap;
      }
      [data-example] .layout label {
        position: relative;
        display: flex;
        align-items: center;
        margin: 0;
        padding: 0.375rem 0.75rem;
        border-radius: 0.375rem;
        font-size: 0.875rem;
        cursor: pointer;
      }
      [data-example] .layout input {
        position: absolute;
        inset: 0;
        width: 100%;
        height: 100%;
        margin: 0;
        opacity: 0;
        pointer-events: none;
      }
      [data-example] .layout label:has(:checked) {
        background: var(--color-bg-soft, #e4e4e7);
        box-shadow: inset 0 0 0 1px var(--color-border, #888);
        font-weight: 600;
      }
      [data-example] .layout label:has(:focus-visible) {
        outline: 2px solid currentColor;
        outline-offset: 2px;
      }
      [data-example] .directory {
        display: grid;
        gap: 0.5rem;
        padding: 0;
        margin: 0;
        list-style: none;
      }
      [data-example] .directory button {
        width: 100%;
        text-align: left;
      }
      [data-example] [aria-disabled='true'] {
        opacity: 0.65;
      }
      [data-example] select {
        padding: 0.75rem 1rem;
        border: 1px solid var(--color-border, #888);
        border-radius: 0.5rem;
        background: var(--color-bg-soft, #fff);
        color: inherit;
        font: inherit;
      }
      [data-example] input[type='text']:disabled {
        opacity: 0.65;
        cursor: not-allowed;
      }
      [data-example] [data-autocomplete-option] small {
        display: block;
        opacity: 0.75;
      }
      [data-example] kbd {
        float: right;
        padding: 0 0.375rem;
        border: 1px solid currentColor;
        border-radius: 0.25rem;
        font:
          0.75rem/1.5 ui-monospace,
          monospace;
        opacity: 0.75;
      }
      

      JavaScript

      main.js
      import { autocomplete } from '@samline/autocomplete'
      import '@samline/autocomplete/style.css'
      const setup = (root, createAutocomplete) => {
        const input = root.querySelector('input')
        const note = root.querySelector('[data-note]')
        const requests = root.querySelector('[data-requests]')
        const events = new AbortController()
        let calls = 0
        const telemetry = output => ({
          name: 'search-telemetry',
          setup: controller => {
            return {
              destroy: controller.on('load', ({ query, cached, suggestions }) => {
                output.textContent = `“${query}”: ${suggestions.length} results · ${cached ? 'cache hit' : 'source called'}`
              }),
            }
          },
        })
        const controller = createAutocomplete(input, {
          source: async query => {
            calls += 1
            requests.textContent = `Source calls: ${calls}`
            return ['Design', 'Engineering', 'Marketing'].filter(label =>
              label.toLowerCase().includes(query.toLowerCase())
            )
          },
          popover: true,
          placement: 'top',
          debounce: 0,
          cache: {
            max: 10,
            ttl: 6e4,
          },
          plugins: [telemetry(note)],
        })
        root.querySelector('[data-repeat]').addEventListener(
          'click',
          () => {
            controller.search(input.value || 'en')
          },
          { signal: events.signal }
        )
        root.querySelector('[data-clear-cache]').addEventListener(
          'click',
          () => {
            controller.clearCache()
            note.textContent = 'Cache cleared. Repeat the search to call the source again.'
          },
          { signal: events.signal }
        )
        return () => {
          events.abort()
          controller.destroy()
        }
      }
      setup(document, autocomplete)
      

      Complete file

      index.html
      <!doctype html>
      <html lang="en">
        <head>
          <meta charset="utf-8" />
          <meta name="viewport" content="width=device-width, initial-scale=1" />
          <title>Observe cache hits through a reusable plugin</title>
          <style>
            [data-example] {
              display: grid;
              gap: 0.75rem;
            }
            /* Forms lay out like the example root: actions never touch the fields. */
            [data-example] form {
              display: grid;
              gap: 0.75rem;
            }
            [data-example] .field {
              position: relative;
            }
            [data-example] label {
              display: block;
              margin-bottom: 0.5rem;
            }
            [data-example] input[type='text'] {
              box-sizing: border-box;
              width: 100%;
              padding: 0.75rem 1rem;
              border: 1px solid var(--color-border, #888);
              border-radius: 0.5rem;
              background: var(--color-bg-soft, #fff);
              color: inherit;
              font: inherit;
            }
            [data-example] button {
              padding: 0.5rem 0.75rem;
              border: 1px solid var(--color-border, #888);
              border-radius: 0.5rem;
              background: var(--color-bg-soft, #fff);
              color: inherit;
              font: inherit;
              cursor: pointer;
            }
            [data-example] button:focus-visible,
            [data-example] input:focus-visible {
              outline: 2px solid currentColor;
              outline-offset: 3px;
            }
            [data-example] p {
              margin: 0;
              overflow-wrap: anywhere;
            }
            [data-example] .actions {
              display: flex;
              flex-wrap: wrap;
              gap: 0.5rem;
            }
            [data-example] [data-pills] {
              display: flex;
              flex-wrap: wrap;
              gap: 0.375rem;
              margin: 0;
              padding: 0;
              list-style: none;
            }
            [data-example] [data-pills]:empty {
              display: none;
            }
            [data-example] .pill {
              display: flex;
              max-width: 100%;
            }
            [data-example] .pill button {
              box-sizing: border-box;
              display: inline-flex;
              align-items: center;
              gap: 0.375rem;
              max-width: 100%;
              height: 2rem;
              padding: 0 0.625rem;
              border: 1px solid var(--color-border, #888);
              border-radius: 1rem;
              background: var(--color-bg, #f4f4f5);
              color: inherit;
              font: inherit;
              font-size: 0.875rem;
              line-height: 1;
              overflow-wrap: anywhere;
              cursor: pointer;
            }
            [data-example] .pill button:hover {
              background: var(--color-bg-soft, #e4e4e7);
            }
            [data-example] .pill button svg {
              width: 0.875rem;
              height: 0.875rem;
              flex: none;
              fill: none;
              stroke: currentColor;
              stroke-width: 2;
              stroke-linecap: round;
              opacity: 0.7;
            }
            [data-example] .pill button:hover svg {
              opacity: 1;
            }
            [data-example] .pill-field {
              display: flex;
              flex-wrap: wrap;
              align-items: center;
              gap: 0.375rem;
              box-sizing: border-box;
              min-height: 3.125rem;
              padding: 0.5rem 0.75rem;
              border: 1px solid var(--color-border, #888);
              border-radius: 0.5rem;
              background: var(--color-bg-soft, #fff);
              cursor: text;
            }
            [data-example] .pill-field:focus-within {
              outline: 2px solid currentColor;
              outline-offset: 2px;
            }
            [data-example] .pill-field input[type='text'] {
              flex: 1 1 8rem;
              width: auto;
              min-width: 0;
              height: 2rem;
              padding: 0;
              border: 0;
              background: transparent;
            }
            [data-example] .pill-field input[type='text']:focus-visible {
              outline: none;
            }
            /* The popup sits after the whole field and overlays what follows it. */
            [data-example='pills'] {
              --autocomplete-max-height: 10rem;
            }
            [data-example='pills'] form {
              display: grid;
              gap: 0.5rem;
            }
            [data-example='pills'] .field [data-autocomplete-popup] {
              position: absolute;
              top: 100%;
            }
            /* One reserved pill row: switching layouts never shifts what follows. */
            [data-example] [data-pills-below] {
              min-height: 2.25rem;
            }
            [data-example] .layout {
              display: flex;
              flex-wrap: wrap;
              gap: 0.25rem;
              margin: 0;
              padding: 0.25rem;
              border: 1px solid var(--color-border, #888);
              border-radius: 0.625rem;
              justify-self: start;
            }
            [data-example] .layout legend {
              position: absolute;
              width: 1px;
              height: 1px;
              overflow: hidden;
              clip-path: inset(50%);
              white-space: nowrap;
            }
            [data-example] .layout label {
              position: relative;
              display: flex;
              align-items: center;
              margin: 0;
              padding: 0.375rem 0.75rem;
              border-radius: 0.375rem;
              font-size: 0.875rem;
              cursor: pointer;
            }
            [data-example] .layout input {
              position: absolute;
              inset: 0;
              width: 100%;
              height: 100%;
              margin: 0;
              opacity: 0;
              pointer-events: none;
            }
            [data-example] .layout label:has(:checked) {
              background: var(--color-bg-soft, #e4e4e7);
              box-shadow: inset 0 0 0 1px var(--color-border, #888);
              font-weight: 600;
            }
            [data-example] .layout label:has(:focus-visible) {
              outline: 2px solid currentColor;
              outline-offset: 2px;
            }
            [data-example] .directory {
              display: grid;
              gap: 0.5rem;
              padding: 0;
              margin: 0;
              list-style: none;
            }
            [data-example] .directory button {
              width: 100%;
              text-align: left;
            }
            [data-example] [aria-disabled='true'] {
              opacity: 0.65;
            }
            [data-example] select {
              padding: 0.75rem 1rem;
              border: 1px solid var(--color-border, #888);
              border-radius: 0.5rem;
              background: var(--color-bg-soft, #fff);
              color: inherit;
              font: inherit;
            }
            [data-example] input[type='text']:disabled {
              opacity: 0.65;
              cursor: not-allowed;
            }
            [data-example] [data-autocomplete-option] small {
              display: block;
              opacity: 0.75;
            }
            [data-example] kbd {
              float: right;
              padding: 0 0.375rem;
              border: 1px solid currentColor;
              border-radius: 0.25rem;
              font:
                0.75rem/1.5 ui-monospace,
                monospace;
              opacity: 0.75;
            }
          </style>
        </head>
        <body>
          <main>
            <div data-example="plugins">
              <div class="field">
                <label for="plugins-input">Team directory</label
                ><input id="plugins-input" type="text" placeholder="Try en" />
              </div>
              <p data-requests>Source calls: 0</p>
              <p data-note role="status">No searches yet.</p>
              <div class="actions">
                <button type="button" data-repeat>Repeat search</button
                ><button type="button" data-clear-cache>Clear cache</button>
              </div>
            </div>
          </main>
          <script type="module">
            import { autocomplete } from '@samline/autocomplete'
            import '@samline/autocomplete/style.css'
            const setup = (root, createAutocomplete) => {
              const input = root.querySelector('input')
              const note = root.querySelector('[data-note]')
              const requests = root.querySelector('[data-requests]')
              const events = new AbortController()
              let calls = 0
              const telemetry = output => ({
                name: 'search-telemetry',
                setup: controller => {
                  return {
                    destroy: controller.on('load', ({ query, cached, suggestions }) => {
                      output.textContent = `“${query}”: ${suggestions.length} results · ${cached ? 'cache hit' : 'source called'}`
                    }),
                  }
                },
              })
              const controller = createAutocomplete(input, {
                source: async query => {
                  calls += 1
                  requests.textContent = `Source calls: ${calls}`
                  return ['Design', 'Engineering', 'Marketing'].filter(label =>
                    label.toLowerCase().includes(query.toLowerCase())
                  )
                },
                popover: true,
                placement: 'top',
                debounce: 0,
                cache: {
                  max: 10,
                  ttl: 6e4,
                },
                plugins: [telemetry(note)],
              })
              root.querySelector('[data-repeat]').addEventListener(
                'click',
                () => {
                  controller.search(input.value || 'en')
                },
                { signal: events.signal }
              )
              root.querySelector('[data-clear-cache]').addEventListener(
                'click',
                () => {
                  controller.clearCache()
                  note.textContent = 'Cache cleared. Repeat the search to call the source again.'
                },
                { signal: events.signal }
              )
              return () => {
                events.abort()
                controller.destroy()
              }
            }
            setup(document, autocomplete)
          </script>
        </body>
      </html>
      

      Prefill an edit form and observe its state

      State and prefillLive preview

      setValue restores a saved object and its hidden id without a selection event. subscribe updates the status display; getState supplies the initial snapshot. Editing the label clears the selected id, and destroy releases the subscription.

      Nothing submitted yet.

      Explore the code

      HTML / CDN

      HTML

      index.html
      <!doctype html>
      <html lang="en">
        <head>
          <meta charset="utf-8" />
          <meta name="viewport" content="width=device-width, initial-scale=1" />
          <title>Prefill an edit form and observe its state</title>
          <link
            rel="stylesheet"
            href="https://cdn.jsdelivr.net/npm/@samline/autocomplete@3.0.0/dist/style.css"
          />
          <link rel="stylesheet" href="./style.css" />
        </head>
        <body>
          <main>
            <div data-example="state">
              <form>
                <div class="field">
                  <label for="state-input">Assigned team</label><input id="state-input" type="text" />
                </div>
                <div class="actions">
                  <button type="button" data-prefill>Restore saved team</button
                  ><button type="button" data-clear>Clear team</button
                  ><button type="submit">Save assignment</button>
                </div>
              </form>
              <p data-state role="status"></p>
              <p data-submitted aria-live="polite">Nothing submitted yet.</p>
            </div>
          </main>
          <script src="https://cdn.jsdelivr.net/npm/@samline/autocomplete@3.0.0/dist/browser/autocomplete.global.js"></script>
          <script src="./main.js" defer></script>
        </body>
      </html>
      

      CSS

      style.css
      [data-example] {
        display: grid;
        gap: 0.75rem;
      }
      /* Forms lay out like the example root: actions never touch the fields. */
      [data-example] form {
        display: grid;
        gap: 0.75rem;
      }
      [data-example] .field {
        position: relative;
      }
      [data-example] label {
        display: block;
        margin-bottom: 0.5rem;
      }
      [data-example] input[type='text'] {
        box-sizing: border-box;
        width: 100%;
        padding: 0.75rem 1rem;
        border: 1px solid var(--color-border, #888);
        border-radius: 0.5rem;
        background: var(--color-bg-soft, #fff);
        color: inherit;
        font: inherit;
      }
      [data-example] button {
        padding: 0.5rem 0.75rem;
        border: 1px solid var(--color-border, #888);
        border-radius: 0.5rem;
        background: var(--color-bg-soft, #fff);
        color: inherit;
        font: inherit;
        cursor: pointer;
      }
      [data-example] button:focus-visible,
      [data-example] input:focus-visible {
        outline: 2px solid currentColor;
        outline-offset: 3px;
      }
      [data-example] p {
        margin: 0;
        overflow-wrap: anywhere;
      }
      [data-example] .actions {
        display: flex;
        flex-wrap: wrap;
        gap: 0.5rem;
      }
      [data-example] [data-pills] {
        display: flex;
        flex-wrap: wrap;
        gap: 0.375rem;
        margin: 0;
        padding: 0;
        list-style: none;
      }
      [data-example] [data-pills]:empty {
        display: none;
      }
      [data-example] .pill {
        display: flex;
        max-width: 100%;
      }
      [data-example] .pill button {
        box-sizing: border-box;
        display: inline-flex;
        align-items: center;
        gap: 0.375rem;
        max-width: 100%;
        height: 2rem;
        padding: 0 0.625rem;
        border: 1px solid var(--color-border, #888);
        border-radius: 1rem;
        background: var(--color-bg, #f4f4f5);
        color: inherit;
        font: inherit;
        font-size: 0.875rem;
        line-height: 1;
        overflow-wrap: anywhere;
        cursor: pointer;
      }
      [data-example] .pill button:hover {
        background: var(--color-bg-soft, #e4e4e7);
      }
      [data-example] .pill button svg {
        width: 0.875rem;
        height: 0.875rem;
        flex: none;
        fill: none;
        stroke: currentColor;
        stroke-width: 2;
        stroke-linecap: round;
        opacity: 0.7;
      }
      [data-example] .pill button:hover svg {
        opacity: 1;
      }
      [data-example] .pill-field {
        display: flex;
        flex-wrap: wrap;
        align-items: center;
        gap: 0.375rem;
        box-sizing: border-box;
        min-height: 3.125rem;
        padding: 0.5rem 0.75rem;
        border: 1px solid var(--color-border, #888);
        border-radius: 0.5rem;
        background: var(--color-bg-soft, #fff);
        cursor: text;
      }
      [data-example] .pill-field:focus-within {
        outline: 2px solid currentColor;
        outline-offset: 2px;
      }
      [data-example] .pill-field input[type='text'] {
        flex: 1 1 8rem;
        width: auto;
        min-width: 0;
        height: 2rem;
        padding: 0;
        border: 0;
        background: transparent;
      }
      [data-example] .pill-field input[type='text']:focus-visible {
        outline: none;
      }
      /* The popup sits after the whole field and overlays what follows it. */
      [data-example='pills'] {
        --autocomplete-max-height: 10rem;
      }
      [data-example='pills'] form {
        display: grid;
        gap: 0.5rem;
      }
      [data-example='pills'] .field [data-autocomplete-popup] {
        position: absolute;
        top: 100%;
      }
      /* One reserved pill row: switching layouts never shifts what follows. */
      [data-example] [data-pills-below] {
        min-height: 2.25rem;
      }
      [data-example] .layout {
        display: flex;
        flex-wrap: wrap;
        gap: 0.25rem;
        margin: 0;
        padding: 0.25rem;
        border: 1px solid var(--color-border, #888);
        border-radius: 0.625rem;
        justify-self: start;
      }
      [data-example] .layout legend {
        position: absolute;
        width: 1px;
        height: 1px;
        overflow: hidden;
        clip-path: inset(50%);
        white-space: nowrap;
      }
      [data-example] .layout label {
        position: relative;
        display: flex;
        align-items: center;
        margin: 0;
        padding: 0.375rem 0.75rem;
        border-radius: 0.375rem;
        font-size: 0.875rem;
        cursor: pointer;
      }
      [data-example] .layout input {
        position: absolute;
        inset: 0;
        width: 100%;
        height: 100%;
        margin: 0;
        opacity: 0;
        pointer-events: none;
      }
      [data-example] .layout label:has(:checked) {
        background: var(--color-bg-soft, #e4e4e7);
        box-shadow: inset 0 0 0 1px var(--color-border, #888);
        font-weight: 600;
      }
      [data-example] .layout label:has(:focus-visible) {
        outline: 2px solid currentColor;
        outline-offset: 2px;
      }
      [data-example] .directory {
        display: grid;
        gap: 0.5rem;
        padding: 0;
        margin: 0;
        list-style: none;
      }
      [data-example] .directory button {
        width: 100%;
        text-align: left;
      }
      [data-example] [aria-disabled='true'] {
        opacity: 0.65;
      }
      [data-example] select {
        padding: 0.75rem 1rem;
        border: 1px solid var(--color-border, #888);
        border-radius: 0.5rem;
        background: var(--color-bg-soft, #fff);
        color: inherit;
        font: inherit;
      }
      [data-example] input[type='text']:disabled {
        opacity: 0.65;
        cursor: not-allowed;
      }
      [data-example] [data-autocomplete-option] small {
        display: block;
        opacity: 0.75;
      }
      [data-example] kbd {
        float: right;
        padding: 0 0.375rem;
        border: 1px solid currentColor;
        border-radius: 0.25rem;
        font:
          0.75rem/1.5 ui-monospace,
          monospace;
        opacity: 0.75;
      }
      

      JavaScript

      main.js
      const setup = (root, createAutocomplete) => {
        const output = root.querySelector('[data-state]')
        const submitted = root.querySelector('[data-submitted]')
        const events = new AbortController()
        const saved = {
          id: 'engineering',
          label: 'Engineering',
        }
        const controller = createAutocomplete(root.querySelector('input[type="text"]'), {
          source: [
            {
              id: 'design',
              label: 'Design',
            },
            saved,
            {
              id: 'support',
              label: 'Support',
            },
          ],
          popover: true,
          placement: 'top',
          debounce: 0,
          getId: item => item.id,
          getLabel: item => item.label,
          hiddenInput: 'team_id',
        })
        const render = state => {
          output.textContent = `Status: ${state.status} · Open: ${state.open} · Results: ${state.suggestions.length} · Selected: ${state.selected?.label ?? 'none'}`
        }
        const unsubscribe = controller.subscribe(render)
        controller.setValue(saved)
        render(controller.getState())
        root.querySelector('[data-prefill]').addEventListener(
          'click',
          () => {
            controller.setValue(saved)
          },
          { signal: events.signal }
        )
        root
          .querySelector('[data-clear]')
          .addEventListener('click', () => controller.clear(), { signal: events.signal })
        root.querySelector('form').addEventListener(
          'submit',
          event => {
            event.preventDefault()
            const id = new FormData(event.currentTarget).get('team_id')
            submitted.textContent = id ? `Submitted team_id=${id}.` : 'Pick a team first.'
          },
          { signal: events.signal }
        )
        return () => {
          events.abort()
          unsubscribe()
          controller.destroy()
        }
      }
      setup(document, window.Autocomplete.autocomplete)
      

      Complete file

      index.html
      <!doctype html>
      <html lang="en">
        <head>
          <meta charset="utf-8" />
          <meta name="viewport" content="width=device-width, initial-scale=1" />
          <title>Prefill an edit form and observe its state</title>
          <link
            rel="stylesheet"
            href="https://cdn.jsdelivr.net/npm/@samline/autocomplete@3.0.0/dist/style.css"
          />
          <style>
            [data-example] {
              display: grid;
              gap: 0.75rem;
            }
            /* Forms lay out like the example root: actions never touch the fields. */
            [data-example] form {
              display: grid;
              gap: 0.75rem;
            }
            [data-example] .field {
              position: relative;
            }
            [data-example] label {
              display: block;
              margin-bottom: 0.5rem;
            }
            [data-example] input[type='text'] {
              box-sizing: border-box;
              width: 100%;
              padding: 0.75rem 1rem;
              border: 1px solid var(--color-border, #888);
              border-radius: 0.5rem;
              background: var(--color-bg-soft, #fff);
              color: inherit;
              font: inherit;
            }
            [data-example] button {
              padding: 0.5rem 0.75rem;
              border: 1px solid var(--color-border, #888);
              border-radius: 0.5rem;
              background: var(--color-bg-soft, #fff);
              color: inherit;
              font: inherit;
              cursor: pointer;
            }
            [data-example] button:focus-visible,
            [data-example] input:focus-visible {
              outline: 2px solid currentColor;
              outline-offset: 3px;
            }
            [data-example] p {
              margin: 0;
              overflow-wrap: anywhere;
            }
            [data-example] .actions {
              display: flex;
              flex-wrap: wrap;
              gap: 0.5rem;
            }
            [data-example] [data-pills] {
              display: flex;
              flex-wrap: wrap;
              gap: 0.375rem;
              margin: 0;
              padding: 0;
              list-style: none;
            }
            [data-example] [data-pills]:empty {
              display: none;
            }
            [data-example] .pill {
              display: flex;
              max-width: 100%;
            }
            [data-example] .pill button {
              box-sizing: border-box;
              display: inline-flex;
              align-items: center;
              gap: 0.375rem;
              max-width: 100%;
              height: 2rem;
              padding: 0 0.625rem;
              border: 1px solid var(--color-border, #888);
              border-radius: 1rem;
              background: var(--color-bg, #f4f4f5);
              color: inherit;
              font: inherit;
              font-size: 0.875rem;
              line-height: 1;
              overflow-wrap: anywhere;
              cursor: pointer;
            }
            [data-example] .pill button:hover {
              background: var(--color-bg-soft, #e4e4e7);
            }
            [data-example] .pill button svg {
              width: 0.875rem;
              height: 0.875rem;
              flex: none;
              fill: none;
              stroke: currentColor;
              stroke-width: 2;
              stroke-linecap: round;
              opacity: 0.7;
            }
            [data-example] .pill button:hover svg {
              opacity: 1;
            }
            [data-example] .pill-field {
              display: flex;
              flex-wrap: wrap;
              align-items: center;
              gap: 0.375rem;
              box-sizing: border-box;
              min-height: 3.125rem;
              padding: 0.5rem 0.75rem;
              border: 1px solid var(--color-border, #888);
              border-radius: 0.5rem;
              background: var(--color-bg-soft, #fff);
              cursor: text;
            }
            [data-example] .pill-field:focus-within {
              outline: 2px solid currentColor;
              outline-offset: 2px;
            }
            [data-example] .pill-field input[type='text'] {
              flex: 1 1 8rem;
              width: auto;
              min-width: 0;
              height: 2rem;
              padding: 0;
              border: 0;
              background: transparent;
            }
            [data-example] .pill-field input[type='text']:focus-visible {
              outline: none;
            }
            /* The popup sits after the whole field and overlays what follows it. */
            [data-example='pills'] {
              --autocomplete-max-height: 10rem;
            }
            [data-example='pills'] form {
              display: grid;
              gap: 0.5rem;
            }
            [data-example='pills'] .field [data-autocomplete-popup] {
              position: absolute;
              top: 100%;
            }
            /* One reserved pill row: switching layouts never shifts what follows. */
            [data-example] [data-pills-below] {
              min-height: 2.25rem;
            }
            [data-example] .layout {
              display: flex;
              flex-wrap: wrap;
              gap: 0.25rem;
              margin: 0;
              padding: 0.25rem;
              border: 1px solid var(--color-border, #888);
              border-radius: 0.625rem;
              justify-self: start;
            }
            [data-example] .layout legend {
              position: absolute;
              width: 1px;
              height: 1px;
              overflow: hidden;
              clip-path: inset(50%);
              white-space: nowrap;
            }
            [data-example] .layout label {
              position: relative;
              display: flex;
              align-items: center;
              margin: 0;
              padding: 0.375rem 0.75rem;
              border-radius: 0.375rem;
              font-size: 0.875rem;
              cursor: pointer;
            }
            [data-example] .layout input {
              position: absolute;
              inset: 0;
              width: 100%;
              height: 100%;
              margin: 0;
              opacity: 0;
              pointer-events: none;
            }
            [data-example] .layout label:has(:checked) {
              background: var(--color-bg-soft, #e4e4e7);
              box-shadow: inset 0 0 0 1px var(--color-border, #888);
              font-weight: 600;
            }
            [data-example] .layout label:has(:focus-visible) {
              outline: 2px solid currentColor;
              outline-offset: 2px;
            }
            [data-example] .directory {
              display: grid;
              gap: 0.5rem;
              padding: 0;
              margin: 0;
              list-style: none;
            }
            [data-example] .directory button {
              width: 100%;
              text-align: left;
            }
            [data-example] [aria-disabled='true'] {
              opacity: 0.65;
            }
            [data-example] select {
              padding: 0.75rem 1rem;
              border: 1px solid var(--color-border, #888);
              border-radius: 0.5rem;
              background: var(--color-bg-soft, #fff);
              color: inherit;
              font: inherit;
            }
            [data-example] input[type='text']:disabled {
              opacity: 0.65;
              cursor: not-allowed;
            }
            [data-example] [data-autocomplete-option] small {
              display: block;
              opacity: 0.75;
            }
            [data-example] kbd {
              float: right;
              padding: 0 0.375rem;
              border: 1px solid currentColor;
              border-radius: 0.25rem;
              font:
                0.75rem/1.5 ui-monospace,
                monospace;
              opacity: 0.75;
            }
          </style>
        </head>
        <body>
          <main>
            <div data-example="state">
              <form>
                <div class="field">
                  <label for="state-input">Assigned team</label><input id="state-input" type="text" />
                </div>
                <div class="actions">
                  <button type="button" data-prefill>Restore saved team</button
                  ><button type="button" data-clear>Clear team</button
                  ><button type="submit">Save assignment</button>
                </div>
              </form>
              <p data-state role="status"></p>
              <p data-submitted aria-live="polite">Nothing submitted yet.</p>
            </div>
          </main>
          <script src="https://cdn.jsdelivr.net/npm/@samline/autocomplete@3.0.0/dist/browser/autocomplete.global.js"></script>
          <script>
            const setup = (root, createAutocomplete) => {
              const output = root.querySelector('[data-state]')
              const submitted = root.querySelector('[data-submitted]')
              const events = new AbortController()
              const saved = {
                id: 'engineering',
                label: 'Engineering',
              }
              const controller = createAutocomplete(root.querySelector('input[type="text"]'), {
                source: [
                  {
                    id: 'design',
                    label: 'Design',
                  },
                  saved,
                  {
                    id: 'support',
                    label: 'Support',
                  },
                ],
                popover: true,
                placement: 'top',
                debounce: 0,
                getId: item => item.id,
                getLabel: item => item.label,
                hiddenInput: 'team_id',
              })
              const render = state => {
                output.textContent = `Status: ${state.status} · Open: ${state.open} · Results: ${state.suggestions.length} · Selected: ${state.selected?.label ?? 'none'}`
              }
              const unsubscribe = controller.subscribe(render)
              controller.setValue(saved)
              render(controller.getState())
              root.querySelector('[data-prefill]').addEventListener(
                'click',
                () => {
                  controller.setValue(saved)
                },
                { signal: events.signal }
              )
              root
                .querySelector('[data-clear]')
                .addEventListener('click', () => controller.clear(), { signal: events.signal })
              root.querySelector('form').addEventListener(
                'submit',
                event => {
                  event.preventDefault()
                  const id = new FormData(event.currentTarget).get('team_id')
                  submitted.textContent = id ? `Submitted team_id=${id}.` : 'Pick a team first.'
                },
                { signal: events.signal }
              )
              return () => {
                events.abort()
                unsubscribe()
                controller.destroy()
              }
            }
            setup(document, window.Autocomplete.autocomplete)
          </script>
        </body>
      </html>
      

      Package / ESM

      HTML

      index.html
      <!doctype html>
      <html lang="en">
        <head>
          <meta charset="utf-8" />
          <meta name="viewport" content="width=device-width, initial-scale=1" />
          <title>Prefill an edit form and observe its state</title>
          <link rel="stylesheet" href="./style.css" />
        </head>
        <body>
          <main>
            <div data-example="state">
              <form>
                <div class="field">
                  <label for="state-input">Assigned team</label><input id="state-input" type="text" />
                </div>
                <div class="actions">
                  <button type="button" data-prefill>Restore saved team</button
                  ><button type="button" data-clear>Clear team</button
                  ><button type="submit">Save assignment</button>
                </div>
              </form>
              <p data-state role="status"></p>
              <p data-submitted aria-live="polite">Nothing submitted yet.</p>
            </div>
          </main>
          <script type="module" src="./main.js"></script>
        </body>
      </html>
      

      CSS

      style.css
      [data-example] {
        display: grid;
        gap: 0.75rem;
      }
      /* Forms lay out like the example root: actions never touch the fields. */
      [data-example] form {
        display: grid;
        gap: 0.75rem;
      }
      [data-example] .field {
        position: relative;
      }
      [data-example] label {
        display: block;
        margin-bottom: 0.5rem;
      }
      [data-example] input[type='text'] {
        box-sizing: border-box;
        width: 100%;
        padding: 0.75rem 1rem;
        border: 1px solid var(--color-border, #888);
        border-radius: 0.5rem;
        background: var(--color-bg-soft, #fff);
        color: inherit;
        font: inherit;
      }
      [data-example] button {
        padding: 0.5rem 0.75rem;
        border: 1px solid var(--color-border, #888);
        border-radius: 0.5rem;
        background: var(--color-bg-soft, #fff);
        color: inherit;
        font: inherit;
        cursor: pointer;
      }
      [data-example] button:focus-visible,
      [data-example] input:focus-visible {
        outline: 2px solid currentColor;
        outline-offset: 3px;
      }
      [data-example] p {
        margin: 0;
        overflow-wrap: anywhere;
      }
      [data-example] .actions {
        display: flex;
        flex-wrap: wrap;
        gap: 0.5rem;
      }
      [data-example] [data-pills] {
        display: flex;
        flex-wrap: wrap;
        gap: 0.375rem;
        margin: 0;
        padding: 0;
        list-style: none;
      }
      [data-example] [data-pills]:empty {
        display: none;
      }
      [data-example] .pill {
        display: flex;
        max-width: 100%;
      }
      [data-example] .pill button {
        box-sizing: border-box;
        display: inline-flex;
        align-items: center;
        gap: 0.375rem;
        max-width: 100%;
        height: 2rem;
        padding: 0 0.625rem;
        border: 1px solid var(--color-border, #888);
        border-radius: 1rem;
        background: var(--color-bg, #f4f4f5);
        color: inherit;
        font: inherit;
        font-size: 0.875rem;
        line-height: 1;
        overflow-wrap: anywhere;
        cursor: pointer;
      }
      [data-example] .pill button:hover {
        background: var(--color-bg-soft, #e4e4e7);
      }
      [data-example] .pill button svg {
        width: 0.875rem;
        height: 0.875rem;
        flex: none;
        fill: none;
        stroke: currentColor;
        stroke-width: 2;
        stroke-linecap: round;
        opacity: 0.7;
      }
      [data-example] .pill button:hover svg {
        opacity: 1;
      }
      [data-example] .pill-field {
        display: flex;
        flex-wrap: wrap;
        align-items: center;
        gap: 0.375rem;
        box-sizing: border-box;
        min-height: 3.125rem;
        padding: 0.5rem 0.75rem;
        border: 1px solid var(--color-border, #888);
        border-radius: 0.5rem;
        background: var(--color-bg-soft, #fff);
        cursor: text;
      }
      [data-example] .pill-field:focus-within {
        outline: 2px solid currentColor;
        outline-offset: 2px;
      }
      [data-example] .pill-field input[type='text'] {
        flex: 1 1 8rem;
        width: auto;
        min-width: 0;
        height: 2rem;
        padding: 0;
        border: 0;
        background: transparent;
      }
      [data-example] .pill-field input[type='text']:focus-visible {
        outline: none;
      }
      /* The popup sits after the whole field and overlays what follows it. */
      [data-example='pills'] {
        --autocomplete-max-height: 10rem;
      }
      [data-example='pills'] form {
        display: grid;
        gap: 0.5rem;
      }
      [data-example='pills'] .field [data-autocomplete-popup] {
        position: absolute;
        top: 100%;
      }
      /* One reserved pill row: switching layouts never shifts what follows. */
      [data-example] [data-pills-below] {
        min-height: 2.25rem;
      }
      [data-example] .layout {
        display: flex;
        flex-wrap: wrap;
        gap: 0.25rem;
        margin: 0;
        padding: 0.25rem;
        border: 1px solid var(--color-border, #888);
        border-radius: 0.625rem;
        justify-self: start;
      }
      [data-example] .layout legend {
        position: absolute;
        width: 1px;
        height: 1px;
        overflow: hidden;
        clip-path: inset(50%);
        white-space: nowrap;
      }
      [data-example] .layout label {
        position: relative;
        display: flex;
        align-items: center;
        margin: 0;
        padding: 0.375rem 0.75rem;
        border-radius: 0.375rem;
        font-size: 0.875rem;
        cursor: pointer;
      }
      [data-example] .layout input {
        position: absolute;
        inset: 0;
        width: 100%;
        height: 100%;
        margin: 0;
        opacity: 0;
        pointer-events: none;
      }
      [data-example] .layout label:has(:checked) {
        background: var(--color-bg-soft, #e4e4e7);
        box-shadow: inset 0 0 0 1px var(--color-border, #888);
        font-weight: 600;
      }
      [data-example] .layout label:has(:focus-visible) {
        outline: 2px solid currentColor;
        outline-offset: 2px;
      }
      [data-example] .directory {
        display: grid;
        gap: 0.5rem;
        padding: 0;
        margin: 0;
        list-style: none;
      }
      [data-example] .directory button {
        width: 100%;
        text-align: left;
      }
      [data-example] [aria-disabled='true'] {
        opacity: 0.65;
      }
      [data-example] select {
        padding: 0.75rem 1rem;
        border: 1px solid var(--color-border, #888);
        border-radius: 0.5rem;
        background: var(--color-bg-soft, #fff);
        color: inherit;
        font: inherit;
      }
      [data-example] input[type='text']:disabled {
        opacity: 0.65;
        cursor: not-allowed;
      }
      [data-example] [data-autocomplete-option] small {
        display: block;
        opacity: 0.75;
      }
      [data-example] kbd {
        float: right;
        padding: 0 0.375rem;
        border: 1px solid currentColor;
        border-radius: 0.25rem;
        font:
          0.75rem/1.5 ui-monospace,
          monospace;
        opacity: 0.75;
      }
      

      JavaScript

      main.js
      import { autocomplete } from '@samline/autocomplete'
      import '@samline/autocomplete/style.css'
      const setup = (root, createAutocomplete) => {
        const output = root.querySelector('[data-state]')
        const submitted = root.querySelector('[data-submitted]')
        const events = new AbortController()
        const saved = {
          id: 'engineering',
          label: 'Engineering',
        }
        const controller = createAutocomplete(root.querySelector('input[type="text"]'), {
          source: [
            {
              id: 'design',
              label: 'Design',
            },
            saved,
            {
              id: 'support',
              label: 'Support',
            },
          ],
          popover: true,
          placement: 'top',
          debounce: 0,
          getId: item => item.id,
          getLabel: item => item.label,
          hiddenInput: 'team_id',
        })
        const render = state => {
          output.textContent = `Status: ${state.status} · Open: ${state.open} · Results: ${state.suggestions.length} · Selected: ${state.selected?.label ?? 'none'}`
        }
        const unsubscribe = controller.subscribe(render)
        controller.setValue(saved)
        render(controller.getState())
        root.querySelector('[data-prefill]').addEventListener(
          'click',
          () => {
            controller.setValue(saved)
          },
          { signal: events.signal }
        )
        root
          .querySelector('[data-clear]')
          .addEventListener('click', () => controller.clear(), { signal: events.signal })
        root.querySelector('form').addEventListener(
          'submit',
          event => {
            event.preventDefault()
            const id = new FormData(event.currentTarget).get('team_id')
            submitted.textContent = id ? `Submitted team_id=${id}.` : 'Pick a team first.'
          },
          { signal: events.signal }
        )
        return () => {
          events.abort()
          unsubscribe()
          controller.destroy()
        }
      }
      setup(document, autocomplete)
      

      Complete file

      index.html
      <!doctype html>
      <html lang="en">
        <head>
          <meta charset="utf-8" />
          <meta name="viewport" content="width=device-width, initial-scale=1" />
          <title>Prefill an edit form and observe its state</title>
          <style>
            [data-example] {
              display: grid;
              gap: 0.75rem;
            }
            /* Forms lay out like the example root: actions never touch the fields. */
            [data-example] form {
              display: grid;
              gap: 0.75rem;
            }
            [data-example] .field {
              position: relative;
            }
            [data-example] label {
              display: block;
              margin-bottom: 0.5rem;
            }
            [data-example] input[type='text'] {
              box-sizing: border-box;
              width: 100%;
              padding: 0.75rem 1rem;
              border: 1px solid var(--color-border, #888);
              border-radius: 0.5rem;
              background: var(--color-bg-soft, #fff);
              color: inherit;
              font: inherit;
            }
            [data-example] button {
              padding: 0.5rem 0.75rem;
              border: 1px solid var(--color-border, #888);
              border-radius: 0.5rem;
              background: var(--color-bg-soft, #fff);
              color: inherit;
              font: inherit;
              cursor: pointer;
            }
            [data-example] button:focus-visible,
            [data-example] input:focus-visible {
              outline: 2px solid currentColor;
              outline-offset: 3px;
            }
            [data-example] p {
              margin: 0;
              overflow-wrap: anywhere;
            }
            [data-example] .actions {
              display: flex;
              flex-wrap: wrap;
              gap: 0.5rem;
            }
            [data-example] [data-pills] {
              display: flex;
              flex-wrap: wrap;
              gap: 0.375rem;
              margin: 0;
              padding: 0;
              list-style: none;
            }
            [data-example] [data-pills]:empty {
              display: none;
            }
            [data-example] .pill {
              display: flex;
              max-width: 100%;
            }
            [data-example] .pill button {
              box-sizing: border-box;
              display: inline-flex;
              align-items: center;
              gap: 0.375rem;
              max-width: 100%;
              height: 2rem;
              padding: 0 0.625rem;
              border: 1px solid var(--color-border, #888);
              border-radius: 1rem;
              background: var(--color-bg, #f4f4f5);
              color: inherit;
              font: inherit;
              font-size: 0.875rem;
              line-height: 1;
              overflow-wrap: anywhere;
              cursor: pointer;
            }
            [data-example] .pill button:hover {
              background: var(--color-bg-soft, #e4e4e7);
            }
            [data-example] .pill button svg {
              width: 0.875rem;
              height: 0.875rem;
              flex: none;
              fill: none;
              stroke: currentColor;
              stroke-width: 2;
              stroke-linecap: round;
              opacity: 0.7;
            }
            [data-example] .pill button:hover svg {
              opacity: 1;
            }
            [data-example] .pill-field {
              display: flex;
              flex-wrap: wrap;
              align-items: center;
              gap: 0.375rem;
              box-sizing: border-box;
              min-height: 3.125rem;
              padding: 0.5rem 0.75rem;
              border: 1px solid var(--color-border, #888);
              border-radius: 0.5rem;
              background: var(--color-bg-soft, #fff);
              cursor: text;
            }
            [data-example] .pill-field:focus-within {
              outline: 2px solid currentColor;
              outline-offset: 2px;
            }
            [data-example] .pill-field input[type='text'] {
              flex: 1 1 8rem;
              width: auto;
              min-width: 0;
              height: 2rem;
              padding: 0;
              border: 0;
              background: transparent;
            }
            [data-example] .pill-field input[type='text']:focus-visible {
              outline: none;
            }
            /* The popup sits after the whole field and overlays what follows it. */
            [data-example='pills'] {
              --autocomplete-max-height: 10rem;
            }
            [data-example='pills'] form {
              display: grid;
              gap: 0.5rem;
            }
            [data-example='pills'] .field [data-autocomplete-popup] {
              position: absolute;
              top: 100%;
            }
            /* One reserved pill row: switching layouts never shifts what follows. */
            [data-example] [data-pills-below] {
              min-height: 2.25rem;
            }
            [data-example] .layout {
              display: flex;
              flex-wrap: wrap;
              gap: 0.25rem;
              margin: 0;
              padding: 0.25rem;
              border: 1px solid var(--color-border, #888);
              border-radius: 0.625rem;
              justify-self: start;
            }
            [data-example] .layout legend {
              position: absolute;
              width: 1px;
              height: 1px;
              overflow: hidden;
              clip-path: inset(50%);
              white-space: nowrap;
            }
            [data-example] .layout label {
              position: relative;
              display: flex;
              align-items: center;
              margin: 0;
              padding: 0.375rem 0.75rem;
              border-radius: 0.375rem;
              font-size: 0.875rem;
              cursor: pointer;
            }
            [data-example] .layout input {
              position: absolute;
              inset: 0;
              width: 100%;
              height: 100%;
              margin: 0;
              opacity: 0;
              pointer-events: none;
            }
            [data-example] .layout label:has(:checked) {
              background: var(--color-bg-soft, #e4e4e7);
              box-shadow: inset 0 0 0 1px var(--color-border, #888);
              font-weight: 600;
            }
            [data-example] .layout label:has(:focus-visible) {
              outline: 2px solid currentColor;
              outline-offset: 2px;
            }
            [data-example] .directory {
              display: grid;
              gap: 0.5rem;
              padding: 0;
              margin: 0;
              list-style: none;
            }
            [data-example] .directory button {
              width: 100%;
              text-align: left;
            }
            [data-example] [aria-disabled='true'] {
              opacity: 0.65;
            }
            [data-example] select {
              padding: 0.75rem 1rem;
              border: 1px solid var(--color-border, #888);
              border-radius: 0.5rem;
              background: var(--color-bg-soft, #fff);
              color: inherit;
              font: inherit;
            }
            [data-example] input[type='text']:disabled {
              opacity: 0.65;
              cursor: not-allowed;
            }
            [data-example] [data-autocomplete-option] small {
              display: block;
              opacity: 0.75;
            }
            [data-example] kbd {
              float: right;
              padding: 0 0.375rem;
              border: 1px solid currentColor;
              border-radius: 0.25rem;
              font:
                0.75rem/1.5 ui-monospace,
                monospace;
              opacity: 0.75;
            }
          </style>
        </head>
        <body>
          <main>
            <div data-example="state">
              <form>
                <div class="field">
                  <label for="state-input">Assigned team</label><input id="state-input" type="text" />
                </div>
                <div class="actions">
                  <button type="button" data-prefill>Restore saved team</button
                  ><button type="button" data-clear>Clear team</button
                  ><button type="submit">Save assignment</button>
                </div>
              </form>
              <p data-state role="status"></p>
              <p data-submitted aria-live="polite">Nothing submitted yet.</p>
            </div>
          </main>
          <script type="module">
            import { autocomplete } from '@samline/autocomplete'
            import '@samline/autocomplete/style.css'
            const setup = (root, createAutocomplete) => {
              const output = root.querySelector('[data-state]')
              const submitted = root.querySelector('[data-submitted]')
              const events = new AbortController()
              const saved = {
                id: 'engineering',
                label: 'Engineering',
              }
              const controller = createAutocomplete(root.querySelector('input[type="text"]'), {
                source: [
                  {
                    id: 'design',
                    label: 'Design',
                  },
                  saved,
                  {
                    id: 'support',
                    label: 'Support',
                  },
                ],
                popover: true,
                placement: 'top',
                debounce: 0,
                getId: item => item.id,
                getLabel: item => item.label,
                hiddenInput: 'team_id',
              })
              const render = state => {
                output.textContent = `Status: ${state.status} · Open: ${state.open} · Results: ${state.suggestions.length} · Selected: ${state.selected?.label ?? 'none'}`
              }
              const unsubscribe = controller.subscribe(render)
              controller.setValue(saved)
              render(controller.getState())
              root.querySelector('[data-prefill]').addEventListener(
                'click',
                () => {
                  controller.setValue(saved)
                },
                { signal: events.signal }
              )
              root
                .querySelector('[data-clear]')
                .addEventListener('click', () => controller.clear(), { signal: events.signal })
              root.querySelector('form').addEventListener(
                'submit',
                event => {
                  event.preventDefault()
                  const id = new FormData(event.currentTarget).get('team_id')
                  submitted.textContent = id ? `Submitted team_id=${id}.` : 'Pick a team first.'
                },
                { signal: events.signal }
              )
              return () => {
                events.abort()
                unsubscribe()
                controller.destroy()
              }
            }
            setup(document, autocomplete)
          </script>
        </body>
      </html>
      

      Customize loading, empty and error states

      Status and contentLive preview

      A simulated async directory makes loading visible. Search for “en” for results with a custom header and footer, “zzz” for an empty state, or enable Simulate failure and search again for an error. All content is rendered with textContent.

      Explore the code

      HTML / CDN

      HTML

      index.html
      <!doctype html>
      <html lang="en">
        <head>
          <meta charset="utf-8" />
          <meta name="viewport" content="width=device-width, initial-scale=1" />
          <title>Customize loading, empty and error states</title>
          <link
            rel="stylesheet"
            href="https://cdn.jsdelivr.net/npm/@samline/autocomplete@3.0.0/dist/style.css"
          />
          <link rel="stylesheet" href="./style.css" />
        </head>
        <body>
          <main>
            <div data-example="rendering">
              <div class="field">
                <label for="rendering-input">Team directory</label
                ><input id="rendering-input" type="text" placeholder="Try en or zzz" />
              </div>
              <label><input type="checkbox" /> Simulate failure</label>
            </div>
          </main>
          <script src="https://cdn.jsdelivr.net/npm/@samline/autocomplete@3.0.0/dist/browser/autocomplete.global.js"></script>
          <script src="./main.js" defer></script>
        </body>
      </html>
      

      CSS

      style.css
      [data-example] {
        display: grid;
        gap: 0.75rem;
      }
      /* Forms lay out like the example root: actions never touch the fields. */
      [data-example] form {
        display: grid;
        gap: 0.75rem;
      }
      [data-example] .field {
        position: relative;
      }
      [data-example] label {
        display: block;
        margin-bottom: 0.5rem;
      }
      [data-example] input[type='text'] {
        box-sizing: border-box;
        width: 100%;
        padding: 0.75rem 1rem;
        border: 1px solid var(--color-border, #888);
        border-radius: 0.5rem;
        background: var(--color-bg-soft, #fff);
        color: inherit;
        font: inherit;
      }
      [data-example] button {
        padding: 0.5rem 0.75rem;
        border: 1px solid var(--color-border, #888);
        border-radius: 0.5rem;
        background: var(--color-bg-soft, #fff);
        color: inherit;
        font: inherit;
        cursor: pointer;
      }
      [data-example] button:focus-visible,
      [data-example] input:focus-visible {
        outline: 2px solid currentColor;
        outline-offset: 3px;
      }
      [data-example] p {
        margin: 0;
        overflow-wrap: anywhere;
      }
      [data-example] .actions {
        display: flex;
        flex-wrap: wrap;
        gap: 0.5rem;
      }
      [data-example] [data-pills] {
        display: flex;
        flex-wrap: wrap;
        gap: 0.375rem;
        margin: 0;
        padding: 0;
        list-style: none;
      }
      [data-example] [data-pills]:empty {
        display: none;
      }
      [data-example] .pill {
        display: flex;
        max-width: 100%;
      }
      [data-example] .pill button {
        box-sizing: border-box;
        display: inline-flex;
        align-items: center;
        gap: 0.375rem;
        max-width: 100%;
        height: 2rem;
        padding: 0 0.625rem;
        border: 1px solid var(--color-border, #888);
        border-radius: 1rem;
        background: var(--color-bg, #f4f4f5);
        color: inherit;
        font: inherit;
        font-size: 0.875rem;
        line-height: 1;
        overflow-wrap: anywhere;
        cursor: pointer;
      }
      [data-example] .pill button:hover {
        background: var(--color-bg-soft, #e4e4e7);
      }
      [data-example] .pill button svg {
        width: 0.875rem;
        height: 0.875rem;
        flex: none;
        fill: none;
        stroke: currentColor;
        stroke-width: 2;
        stroke-linecap: round;
        opacity: 0.7;
      }
      [data-example] .pill button:hover svg {
        opacity: 1;
      }
      [data-example] .pill-field {
        display: flex;
        flex-wrap: wrap;
        align-items: center;
        gap: 0.375rem;
        box-sizing: border-box;
        min-height: 3.125rem;
        padding: 0.5rem 0.75rem;
        border: 1px solid var(--color-border, #888);
        border-radius: 0.5rem;
        background: var(--color-bg-soft, #fff);
        cursor: text;
      }
      [data-example] .pill-field:focus-within {
        outline: 2px solid currentColor;
        outline-offset: 2px;
      }
      [data-example] .pill-field input[type='text'] {
        flex: 1 1 8rem;
        width: auto;
        min-width: 0;
        height: 2rem;
        padding: 0;
        border: 0;
        background: transparent;
      }
      [data-example] .pill-field input[type='text']:focus-visible {
        outline: none;
      }
      /* The popup sits after the whole field and overlays what follows it. */
      [data-example='pills'] {
        --autocomplete-max-height: 10rem;
      }
      [data-example='pills'] form {
        display: grid;
        gap: 0.5rem;
      }
      [data-example='pills'] .field [data-autocomplete-popup] {
        position: absolute;
        top: 100%;
      }
      /* One reserved pill row: switching layouts never shifts what follows. */
      [data-example] [data-pills-below] {
        min-height: 2.25rem;
      }
      [data-example] .layout {
        display: flex;
        flex-wrap: wrap;
        gap: 0.25rem;
        margin: 0;
        padding: 0.25rem;
        border: 1px solid var(--color-border, #888);
        border-radius: 0.625rem;
        justify-self: start;
      }
      [data-example] .layout legend {
        position: absolute;
        width: 1px;
        height: 1px;
        overflow: hidden;
        clip-path: inset(50%);
        white-space: nowrap;
      }
      [data-example] .layout label {
        position: relative;
        display: flex;
        align-items: center;
        margin: 0;
        padding: 0.375rem 0.75rem;
        border-radius: 0.375rem;
        font-size: 0.875rem;
        cursor: pointer;
      }
      [data-example] .layout input {
        position: absolute;
        inset: 0;
        width: 100%;
        height: 100%;
        margin: 0;
        opacity: 0;
        pointer-events: none;
      }
      [data-example] .layout label:has(:checked) {
        background: var(--color-bg-soft, #e4e4e7);
        box-shadow: inset 0 0 0 1px var(--color-border, #888);
        font-weight: 600;
      }
      [data-example] .layout label:has(:focus-visible) {
        outline: 2px solid currentColor;
        outline-offset: 2px;
      }
      [data-example] .directory {
        display: grid;
        gap: 0.5rem;
        padding: 0;
        margin: 0;
        list-style: none;
      }
      [data-example] .directory button {
        width: 100%;
        text-align: left;
      }
      [data-example] [aria-disabled='true'] {
        opacity: 0.65;
      }
      [data-example] select {
        padding: 0.75rem 1rem;
        border: 1px solid var(--color-border, #888);
        border-radius: 0.5rem;
        background: var(--color-bg-soft, #fff);
        color: inherit;
        font: inherit;
      }
      [data-example] input[type='text']:disabled {
        opacity: 0.65;
        cursor: not-allowed;
      }
      [data-example] [data-autocomplete-option] small {
        display: block;
        opacity: 0.75;
      }
      [data-example] kbd {
        float: right;
        padding: 0 0.375rem;
        border: 1px solid currentColor;
        border-radius: 0.25rem;
        font:
          0.75rem/1.5 ui-monospace,
          monospace;
        opacity: 0.75;
      }
      

      JavaScript

      main.js
      const setup = (root, createAutocomplete) => {
        const failure = root.querySelector('input[type="checkbox"]')
        const controller = createAutocomplete(root.querySelector('input[type="text"]'), {
          source: async (query, { signal }) => {
            await new Promise((resolve, reject) => {
              const abort = () => {
                clearTimeout(timer)
                reject(new DOMException('Aborted', 'AbortError'))
              }
              const timer = setTimeout(() => {
                signal.removeEventListener('abort', abort)
                resolve()
              }, 350)
              if (signal.aborted) abort()
              else signal.addEventListener('abort', abort, { once: true })
            })
            if (failure.checked) throw new Error('Demo service unavailable')
            return ['Design', 'Engineering', 'Marketing'].filter(label =>
              label.toLowerCase().includes(query.toLowerCase())
            )
          },
          popover: true,
          placement: 'top',
          debounce: 0,
          cache: false,
          renderStatus: (element, { state, query }) => {
            element.textContent =
              state === 'loading'
                ? 'Checking the team directory…'
                : state === 'error'
                  ? 'Directory unavailable. Turn off “Simulate failure” and search again.'
                  : `No teams match “${query}”. Try “en”.`
          },
          renderHeader: (element, { count }) => {
            element.textContent = `Team directory · ${count} matches`
          },
          renderFooter: element => {
            element.textContent = 'Use ↑ ↓ to navigate and Enter to choose.'
          },
        })
        return () => controller.destroy()
      }
      setup(document, window.Autocomplete.autocomplete)
      

      Complete file

      index.html
      <!doctype html>
      <html lang="en">
        <head>
          <meta charset="utf-8" />
          <meta name="viewport" content="width=device-width, initial-scale=1" />
          <title>Customize loading, empty and error states</title>
          <link
            rel="stylesheet"
            href="https://cdn.jsdelivr.net/npm/@samline/autocomplete@3.0.0/dist/style.css"
          />
          <style>
            [data-example] {
              display: grid;
              gap: 0.75rem;
            }
            /* Forms lay out like the example root: actions never touch the fields. */
            [data-example] form {
              display: grid;
              gap: 0.75rem;
            }
            [data-example] .field {
              position: relative;
            }
            [data-example] label {
              display: block;
              margin-bottom: 0.5rem;
            }
            [data-example] input[type='text'] {
              box-sizing: border-box;
              width: 100%;
              padding: 0.75rem 1rem;
              border: 1px solid var(--color-border, #888);
              border-radius: 0.5rem;
              background: var(--color-bg-soft, #fff);
              color: inherit;
              font: inherit;
            }
            [data-example] button {
              padding: 0.5rem 0.75rem;
              border: 1px solid var(--color-border, #888);
              border-radius: 0.5rem;
              background: var(--color-bg-soft, #fff);
              color: inherit;
              font: inherit;
              cursor: pointer;
            }
            [data-example] button:focus-visible,
            [data-example] input:focus-visible {
              outline: 2px solid currentColor;
              outline-offset: 3px;
            }
            [data-example] p {
              margin: 0;
              overflow-wrap: anywhere;
            }
            [data-example] .actions {
              display: flex;
              flex-wrap: wrap;
              gap: 0.5rem;
            }
            [data-example] [data-pills] {
              display: flex;
              flex-wrap: wrap;
              gap: 0.375rem;
              margin: 0;
              padding: 0;
              list-style: none;
            }
            [data-example] [data-pills]:empty {
              display: none;
            }
            [data-example] .pill {
              display: flex;
              max-width: 100%;
            }
            [data-example] .pill button {
              box-sizing: border-box;
              display: inline-flex;
              align-items: center;
              gap: 0.375rem;
              max-width: 100%;
              height: 2rem;
              padding: 0 0.625rem;
              border: 1px solid var(--color-border, #888);
              border-radius: 1rem;
              background: var(--color-bg, #f4f4f5);
              color: inherit;
              font: inherit;
              font-size: 0.875rem;
              line-height: 1;
              overflow-wrap: anywhere;
              cursor: pointer;
            }
            [data-example] .pill button:hover {
              background: var(--color-bg-soft, #e4e4e7);
            }
            [data-example] .pill button svg {
              width: 0.875rem;
              height: 0.875rem;
              flex: none;
              fill: none;
              stroke: currentColor;
              stroke-width: 2;
              stroke-linecap: round;
              opacity: 0.7;
            }
            [data-example] .pill button:hover svg {
              opacity: 1;
            }
            [data-example] .pill-field {
              display: flex;
              flex-wrap: wrap;
              align-items: center;
              gap: 0.375rem;
              box-sizing: border-box;
              min-height: 3.125rem;
              padding: 0.5rem 0.75rem;
              border: 1px solid var(--color-border, #888);
              border-radius: 0.5rem;
              background: var(--color-bg-soft, #fff);
              cursor: text;
            }
            [data-example] .pill-field:focus-within {
              outline: 2px solid currentColor;
              outline-offset: 2px;
            }
            [data-example] .pill-field input[type='text'] {
              flex: 1 1 8rem;
              width: auto;
              min-width: 0;
              height: 2rem;
              padding: 0;
              border: 0;
              background: transparent;
            }
            [data-example] .pill-field input[type='text']:focus-visible {
              outline: none;
            }
            /* The popup sits after the whole field and overlays what follows it. */
            [data-example='pills'] {
              --autocomplete-max-height: 10rem;
            }
            [data-example='pills'] form {
              display: grid;
              gap: 0.5rem;
            }
            [data-example='pills'] .field [data-autocomplete-popup] {
              position: absolute;
              top: 100%;
            }
            /* One reserved pill row: switching layouts never shifts what follows. */
            [data-example] [data-pills-below] {
              min-height: 2.25rem;
            }
            [data-example] .layout {
              display: flex;
              flex-wrap: wrap;
              gap: 0.25rem;
              margin: 0;
              padding: 0.25rem;
              border: 1px solid var(--color-border, #888);
              border-radius: 0.625rem;
              justify-self: start;
            }
            [data-example] .layout legend {
              position: absolute;
              width: 1px;
              height: 1px;
              overflow: hidden;
              clip-path: inset(50%);
              white-space: nowrap;
            }
            [data-example] .layout label {
              position: relative;
              display: flex;
              align-items: center;
              margin: 0;
              padding: 0.375rem 0.75rem;
              border-radius: 0.375rem;
              font-size: 0.875rem;
              cursor: pointer;
            }
            [data-example] .layout input {
              position: absolute;
              inset: 0;
              width: 100%;
              height: 100%;
              margin: 0;
              opacity: 0;
              pointer-events: none;
            }
            [data-example] .layout label:has(:checked) {
              background: var(--color-bg-soft, #e4e4e7);
              box-shadow: inset 0 0 0 1px var(--color-border, #888);
              font-weight: 600;
            }
            [data-example] .layout label:has(:focus-visible) {
              outline: 2px solid currentColor;
              outline-offset: 2px;
            }
            [data-example] .directory {
              display: grid;
              gap: 0.5rem;
              padding: 0;
              margin: 0;
              list-style: none;
            }
            [data-example] .directory button {
              width: 100%;
              text-align: left;
            }
            [data-example] [aria-disabled='true'] {
              opacity: 0.65;
            }
            [data-example] select {
              padding: 0.75rem 1rem;
              border: 1px solid var(--color-border, #888);
              border-radius: 0.5rem;
              background: var(--color-bg-soft, #fff);
              color: inherit;
              font: inherit;
            }
            [data-example] input[type='text']:disabled {
              opacity: 0.65;
              cursor: not-allowed;
            }
            [data-example] [data-autocomplete-option] small {
              display: block;
              opacity: 0.75;
            }
            [data-example] kbd {
              float: right;
              padding: 0 0.375rem;
              border: 1px solid currentColor;
              border-radius: 0.25rem;
              font:
                0.75rem/1.5 ui-monospace,
                monospace;
              opacity: 0.75;
            }
          </style>
        </head>
        <body>
          <main>
            <div data-example="rendering">
              <div class="field">
                <label for="rendering-input">Team directory</label
                ><input id="rendering-input" type="text" placeholder="Try en or zzz" />
              </div>
              <label><input type="checkbox" /> Simulate failure</label>
            </div>
          </main>
          <script src="https://cdn.jsdelivr.net/npm/@samline/autocomplete@3.0.0/dist/browser/autocomplete.global.js"></script>
          <script>
            const setup = (root, createAutocomplete) => {
              const failure = root.querySelector('input[type="checkbox"]')
              const controller = createAutocomplete(root.querySelector('input[type="text"]'), {
                source: async (query, { signal }) => {
                  await new Promise((resolve, reject) => {
                    const abort = () => {
                      clearTimeout(timer)
                      reject(new DOMException('Aborted', 'AbortError'))
                    }
                    const timer = setTimeout(() => {
                      signal.removeEventListener('abort', abort)
                      resolve()
                    }, 350)
                    if (signal.aborted) abort()
                    else signal.addEventListener('abort', abort, { once: true })
                  })
                  if (failure.checked) throw new Error('Demo service unavailable')
                  return ['Design', 'Engineering', 'Marketing'].filter(label =>
                    label.toLowerCase().includes(query.toLowerCase())
                  )
                },
                popover: true,
                placement: 'top',
                debounce: 0,
                cache: false,
                renderStatus: (element, { state, query }) => {
                  element.textContent =
                    state === 'loading'
                      ? 'Checking the team directory…'
                      : state === 'error'
                        ? 'Directory unavailable. Turn off “Simulate failure” and search again.'
                        : `No teams match “${query}”. Try “en”.`
                },
                renderHeader: (element, { count }) => {
                  element.textContent = `Team directory · ${count} matches`
                },
                renderFooter: element => {
                  element.textContent = 'Use ↑ ↓ to navigate and Enter to choose.'
                },
              })
              return () => controller.destroy()
            }
            setup(document, window.Autocomplete.autocomplete)
          </script>
        </body>
      </html>
      

      Package / ESM

      HTML

      index.html
      <!doctype html>
      <html lang="en">
        <head>
          <meta charset="utf-8" />
          <meta name="viewport" content="width=device-width, initial-scale=1" />
          <title>Customize loading, empty and error states</title>
          <link rel="stylesheet" href="./style.css" />
        </head>
        <body>
          <main>
            <div data-example="rendering">
              <div class="field">
                <label for="rendering-input">Team directory</label
                ><input id="rendering-input" type="text" placeholder="Try en or zzz" />
              </div>
              <label><input type="checkbox" /> Simulate failure</label>
            </div>
          </main>
          <script type="module" src="./main.js"></script>
        </body>
      </html>
      

      CSS

      style.css
      [data-example] {
        display: grid;
        gap: 0.75rem;
      }
      /* Forms lay out like the example root: actions never touch the fields. */
      [data-example] form {
        display: grid;
        gap: 0.75rem;
      }
      [data-example] .field {
        position: relative;
      }
      [data-example] label {
        display: block;
        margin-bottom: 0.5rem;
      }
      [data-example] input[type='text'] {
        box-sizing: border-box;
        width: 100%;
        padding: 0.75rem 1rem;
        border: 1px solid var(--color-border, #888);
        border-radius: 0.5rem;
        background: var(--color-bg-soft, #fff);
        color: inherit;
        font: inherit;
      }
      [data-example] button {
        padding: 0.5rem 0.75rem;
        border: 1px solid var(--color-border, #888);
        border-radius: 0.5rem;
        background: var(--color-bg-soft, #fff);
        color: inherit;
        font: inherit;
        cursor: pointer;
      }
      [data-example] button:focus-visible,
      [data-example] input:focus-visible {
        outline: 2px solid currentColor;
        outline-offset: 3px;
      }
      [data-example] p {
        margin: 0;
        overflow-wrap: anywhere;
      }
      [data-example] .actions {
        display: flex;
        flex-wrap: wrap;
        gap: 0.5rem;
      }
      [data-example] [data-pills] {
        display: flex;
        flex-wrap: wrap;
        gap: 0.375rem;
        margin: 0;
        padding: 0;
        list-style: none;
      }
      [data-example] [data-pills]:empty {
        display: none;
      }
      [data-example] .pill {
        display: flex;
        max-width: 100%;
      }
      [data-example] .pill button {
        box-sizing: border-box;
        display: inline-flex;
        align-items: center;
        gap: 0.375rem;
        max-width: 100%;
        height: 2rem;
        padding: 0 0.625rem;
        border: 1px solid var(--color-border, #888);
        border-radius: 1rem;
        background: var(--color-bg, #f4f4f5);
        color: inherit;
        font: inherit;
        font-size: 0.875rem;
        line-height: 1;
        overflow-wrap: anywhere;
        cursor: pointer;
      }
      [data-example] .pill button:hover {
        background: var(--color-bg-soft, #e4e4e7);
      }
      [data-example] .pill button svg {
        width: 0.875rem;
        height: 0.875rem;
        flex: none;
        fill: none;
        stroke: currentColor;
        stroke-width: 2;
        stroke-linecap: round;
        opacity: 0.7;
      }
      [data-example] .pill button:hover svg {
        opacity: 1;
      }
      [data-example] .pill-field {
        display: flex;
        flex-wrap: wrap;
        align-items: center;
        gap: 0.375rem;
        box-sizing: border-box;
        min-height: 3.125rem;
        padding: 0.5rem 0.75rem;
        border: 1px solid var(--color-border, #888);
        border-radius: 0.5rem;
        background: var(--color-bg-soft, #fff);
        cursor: text;
      }
      [data-example] .pill-field:focus-within {
        outline: 2px solid currentColor;
        outline-offset: 2px;
      }
      [data-example] .pill-field input[type='text'] {
        flex: 1 1 8rem;
        width: auto;
        min-width: 0;
        height: 2rem;
        padding: 0;
        border: 0;
        background: transparent;
      }
      [data-example] .pill-field input[type='text']:focus-visible {
        outline: none;
      }
      /* The popup sits after the whole field and overlays what follows it. */
      [data-example='pills'] {
        --autocomplete-max-height: 10rem;
      }
      [data-example='pills'] form {
        display: grid;
        gap: 0.5rem;
      }
      [data-example='pills'] .field [data-autocomplete-popup] {
        position: absolute;
        top: 100%;
      }
      /* One reserved pill row: switching layouts never shifts what follows. */
      [data-example] [data-pills-below] {
        min-height: 2.25rem;
      }
      [data-example] .layout {
        display: flex;
        flex-wrap: wrap;
        gap: 0.25rem;
        margin: 0;
        padding: 0.25rem;
        border: 1px solid var(--color-border, #888);
        border-radius: 0.625rem;
        justify-self: start;
      }
      [data-example] .layout legend {
        position: absolute;
        width: 1px;
        height: 1px;
        overflow: hidden;
        clip-path: inset(50%);
        white-space: nowrap;
      }
      [data-example] .layout label {
        position: relative;
        display: flex;
        align-items: center;
        margin: 0;
        padding: 0.375rem 0.75rem;
        border-radius: 0.375rem;
        font-size: 0.875rem;
        cursor: pointer;
      }
      [data-example] .layout input {
        position: absolute;
        inset: 0;
        width: 100%;
        height: 100%;
        margin: 0;
        opacity: 0;
        pointer-events: none;
      }
      [data-example] .layout label:has(:checked) {
        background: var(--color-bg-soft, #e4e4e7);
        box-shadow: inset 0 0 0 1px var(--color-border, #888);
        font-weight: 600;
      }
      [data-example] .layout label:has(:focus-visible) {
        outline: 2px solid currentColor;
        outline-offset: 2px;
      }
      [data-example] .directory {
        display: grid;
        gap: 0.5rem;
        padding: 0;
        margin: 0;
        list-style: none;
      }
      [data-example] .directory button {
        width: 100%;
        text-align: left;
      }
      [data-example] [aria-disabled='true'] {
        opacity: 0.65;
      }
      [data-example] select {
        padding: 0.75rem 1rem;
        border: 1px solid var(--color-border, #888);
        border-radius: 0.5rem;
        background: var(--color-bg-soft, #fff);
        color: inherit;
        font: inherit;
      }
      [data-example] input[type='text']:disabled {
        opacity: 0.65;
        cursor: not-allowed;
      }
      [data-example] [data-autocomplete-option] small {
        display: block;
        opacity: 0.75;
      }
      [data-example] kbd {
        float: right;
        padding: 0 0.375rem;
        border: 1px solid currentColor;
        border-radius: 0.25rem;
        font:
          0.75rem/1.5 ui-monospace,
          monospace;
        opacity: 0.75;
      }
      

      JavaScript

      main.js
      import { autocomplete } from '@samline/autocomplete'
      import '@samline/autocomplete/style.css'
      const setup = (root, createAutocomplete) => {
        const failure = root.querySelector('input[type="checkbox"]')
        const controller = createAutocomplete(root.querySelector('input[type="text"]'), {
          source: async (query, { signal }) => {
            await new Promise((resolve, reject) => {
              const abort = () => {
                clearTimeout(timer)
                reject(new DOMException('Aborted', 'AbortError'))
              }
              const timer = setTimeout(() => {
                signal.removeEventListener('abort', abort)
                resolve()
              }, 350)
              if (signal.aborted) abort()
              else signal.addEventListener('abort', abort, { once: true })
            })
            if (failure.checked) throw new Error('Demo service unavailable')
            return ['Design', 'Engineering', 'Marketing'].filter(label =>
              label.toLowerCase().includes(query.toLowerCase())
            )
          },
          popover: true,
          placement: 'top',
          debounce: 0,
          cache: false,
          renderStatus: (element, { state, query }) => {
            element.textContent =
              state === 'loading'
                ? 'Checking the team directory…'
                : state === 'error'
                  ? 'Directory unavailable. Turn off “Simulate failure” and search again.'
                  : `No teams match “${query}”. Try “en”.`
          },
          renderHeader: (element, { count }) => {
            element.textContent = `Team directory · ${count} matches`
          },
          renderFooter: element => {
            element.textContent = 'Use ↑ ↓ to navigate and Enter to choose.'
          },
        })
        return () => controller.destroy()
      }
      setup(document, autocomplete)
      

      Complete file

      index.html
      <!doctype html>
      <html lang="en">
        <head>
          <meta charset="utf-8" />
          <meta name="viewport" content="width=device-width, initial-scale=1" />
          <title>Customize loading, empty and error states</title>
          <style>
            [data-example] {
              display: grid;
              gap: 0.75rem;
            }
            /* Forms lay out like the example root: actions never touch the fields. */
            [data-example] form {
              display: grid;
              gap: 0.75rem;
            }
            [data-example] .field {
              position: relative;
            }
            [data-example] label {
              display: block;
              margin-bottom: 0.5rem;
            }
            [data-example] input[type='text'] {
              box-sizing: border-box;
              width: 100%;
              padding: 0.75rem 1rem;
              border: 1px solid var(--color-border, #888);
              border-radius: 0.5rem;
              background: var(--color-bg-soft, #fff);
              color: inherit;
              font: inherit;
            }
            [data-example] button {
              padding: 0.5rem 0.75rem;
              border: 1px solid var(--color-border, #888);
              border-radius: 0.5rem;
              background: var(--color-bg-soft, #fff);
              color: inherit;
              font: inherit;
              cursor: pointer;
            }
            [data-example] button:focus-visible,
            [data-example] input:focus-visible {
              outline: 2px solid currentColor;
              outline-offset: 3px;
            }
            [data-example] p {
              margin: 0;
              overflow-wrap: anywhere;
            }
            [data-example] .actions {
              display: flex;
              flex-wrap: wrap;
              gap: 0.5rem;
            }
            [data-example] [data-pills] {
              display: flex;
              flex-wrap: wrap;
              gap: 0.375rem;
              margin: 0;
              padding: 0;
              list-style: none;
            }
            [data-example] [data-pills]:empty {
              display: none;
            }
            [data-example] .pill {
              display: flex;
              max-width: 100%;
            }
            [data-example] .pill button {
              box-sizing: border-box;
              display: inline-flex;
              align-items: center;
              gap: 0.375rem;
              max-width: 100%;
              height: 2rem;
              padding: 0 0.625rem;
              border: 1px solid var(--color-border, #888);
              border-radius: 1rem;
              background: var(--color-bg, #f4f4f5);
              color: inherit;
              font: inherit;
              font-size: 0.875rem;
              line-height: 1;
              overflow-wrap: anywhere;
              cursor: pointer;
            }
            [data-example] .pill button:hover {
              background: var(--color-bg-soft, #e4e4e7);
            }
            [data-example] .pill button svg {
              width: 0.875rem;
              height: 0.875rem;
              flex: none;
              fill: none;
              stroke: currentColor;
              stroke-width: 2;
              stroke-linecap: round;
              opacity: 0.7;
            }
            [data-example] .pill button:hover svg {
              opacity: 1;
            }
            [data-example] .pill-field {
              display: flex;
              flex-wrap: wrap;
              align-items: center;
              gap: 0.375rem;
              box-sizing: border-box;
              min-height: 3.125rem;
              padding: 0.5rem 0.75rem;
              border: 1px solid var(--color-border, #888);
              border-radius: 0.5rem;
              background: var(--color-bg-soft, #fff);
              cursor: text;
            }
            [data-example] .pill-field:focus-within {
              outline: 2px solid currentColor;
              outline-offset: 2px;
            }
            [data-example] .pill-field input[type='text'] {
              flex: 1 1 8rem;
              width: auto;
              min-width: 0;
              height: 2rem;
              padding: 0;
              border: 0;
              background: transparent;
            }
            [data-example] .pill-field input[type='text']:focus-visible {
              outline: none;
            }
            /* The popup sits after the whole field and overlays what follows it. */
            [data-example='pills'] {
              --autocomplete-max-height: 10rem;
            }
            [data-example='pills'] form {
              display: grid;
              gap: 0.5rem;
            }
            [data-example='pills'] .field [data-autocomplete-popup] {
              position: absolute;
              top: 100%;
            }
            /* One reserved pill row: switching layouts never shifts what follows. */
            [data-example] [data-pills-below] {
              min-height: 2.25rem;
            }
            [data-example] .layout {
              display: flex;
              flex-wrap: wrap;
              gap: 0.25rem;
              margin: 0;
              padding: 0.25rem;
              border: 1px solid var(--color-border, #888);
              border-radius: 0.625rem;
              justify-self: start;
            }
            [data-example] .layout legend {
              position: absolute;
              width: 1px;
              height: 1px;
              overflow: hidden;
              clip-path: inset(50%);
              white-space: nowrap;
            }
            [data-example] .layout label {
              position: relative;
              display: flex;
              align-items: center;
              margin: 0;
              padding: 0.375rem 0.75rem;
              border-radius: 0.375rem;
              font-size: 0.875rem;
              cursor: pointer;
            }
            [data-example] .layout input {
              position: absolute;
              inset: 0;
              width: 100%;
              height: 100%;
              margin: 0;
              opacity: 0;
              pointer-events: none;
            }
            [data-example] .layout label:has(:checked) {
              background: var(--color-bg-soft, #e4e4e7);
              box-shadow: inset 0 0 0 1px var(--color-border, #888);
              font-weight: 600;
            }
            [data-example] .layout label:has(:focus-visible) {
              outline: 2px solid currentColor;
              outline-offset: 2px;
            }
            [data-example] .directory {
              display: grid;
              gap: 0.5rem;
              padding: 0;
              margin: 0;
              list-style: none;
            }
            [data-example] .directory button {
              width: 100%;
              text-align: left;
            }
            [data-example] [aria-disabled='true'] {
              opacity: 0.65;
            }
            [data-example] select {
              padding: 0.75rem 1rem;
              border: 1px solid var(--color-border, #888);
              border-radius: 0.5rem;
              background: var(--color-bg-soft, #fff);
              color: inherit;
              font: inherit;
            }
            [data-example] input[type='text']:disabled {
              opacity: 0.65;
              cursor: not-allowed;
            }
            [data-example] [data-autocomplete-option] small {
              display: block;
              opacity: 0.75;
            }
            [data-example] kbd {
              float: right;
              padding: 0 0.375rem;
              border: 1px solid currentColor;
              border-radius: 0.25rem;
              font:
                0.75rem/1.5 ui-monospace,
                monospace;
              opacity: 0.75;
            }
          </style>
        </head>
        <body>
          <main>
            <div data-example="rendering">
              <div class="field">
                <label for="rendering-input">Team directory</label
                ><input id="rendering-input" type="text" placeholder="Try en or zzz" />
              </div>
              <label><input type="checkbox" /> Simulate failure</label>
            </div>
          </main>
          <script type="module">
            import { autocomplete } from '@samline/autocomplete'
            import '@samline/autocomplete/style.css'
            const setup = (root, createAutocomplete) => {
              const failure = root.querySelector('input[type="checkbox"]')
              const controller = createAutocomplete(root.querySelector('input[type="text"]'), {
                source: async (query, { signal }) => {
                  await new Promise((resolve, reject) => {
                    const abort = () => {
                      clearTimeout(timer)
                      reject(new DOMException('Aborted', 'AbortError'))
                    }
                    const timer = setTimeout(() => {
                      signal.removeEventListener('abort', abort)
                      resolve()
                    }, 350)
                    if (signal.aborted) abort()
                    else signal.addEventListener('abort', abort, { once: true })
                  })
                  if (failure.checked) throw new Error('Demo service unavailable')
                  return ['Design', 'Engineering', 'Marketing'].filter(label =>
                    label.toLowerCase().includes(query.toLowerCase())
                  )
                },
                popover: true,
                placement: 'top',
                debounce: 0,
                cache: false,
                renderStatus: (element, { state, query }) => {
                  element.textContent =
                    state === 'loading'
                      ? 'Checking the team directory…'
                      : state === 'error'
                        ? 'Directory unavailable. Turn off “Simulate failure” and search again.'
                        : `No teams match “${query}”. Try “en”.`
                },
                renderHeader: (element, { count }) => {
                  element.textContent = `Team directory · ${count} matches`
                },
                renderFooter: element => {
                  element.textContent = 'Use ↑ ↓ to navigate and Enter to choose.'
                },
              })
              return () => controller.destroy()
            }
            setup(document, autocomplete)
          </script>
        </body>
      </html>
      

      Render a directory with the search pipeline alone

      HeadlessLive preview

      createSearch handles filtering while the application renders a persistent list of native buttons. Tab and Enter operate the results. This is a filterable directory, not a combobox: a custom combobox would also need application-owned ARIA and arrow-key behavior. The ESM version imports @samline/autocomplete/core; the CDN version loads that same module, since the browser bundle only exposes the controller.

        Explore the code

        HTML / CDN

        HTML

        index.html
        <!doctype html>
        <html lang="en">
          <head>
            <meta charset="utf-8" />
            <meta name="viewport" content="width=device-width, initial-scale=1" />
            <title>Render a directory with the search pipeline alone</title>
            <link
              rel="stylesheet"
              href="https://cdn.jsdelivr.net/npm/@samline/autocomplete@3.0.0/dist/style.css"
            />
            <link rel="stylesheet" href="./style.css" />
          </head>
          <body>
            <main>
              <div data-example="headless">
                <label for="headless-input">Filter teams</label><input id="headless-input" type="text" />
                <p data-note role="status"></p>
                <ul class="directory" data-results aria-label="Matching teams"></ul>
              </div>
            </main>
            <script src="https://cdn.jsdelivr.net/npm/@samline/autocomplete@3.0.0/dist/browser/autocomplete.global.js"></script>
            <script src="./main.js" defer></script>
          </body>
        </html>
        

        CSS

        style.css
        [data-example] {
          display: grid;
          gap: 0.75rem;
        }
        /* Forms lay out like the example root: actions never touch the fields. */
        [data-example] form {
          display: grid;
          gap: 0.75rem;
        }
        [data-example] .field {
          position: relative;
        }
        [data-example] label {
          display: block;
          margin-bottom: 0.5rem;
        }
        [data-example] input[type='text'] {
          box-sizing: border-box;
          width: 100%;
          padding: 0.75rem 1rem;
          border: 1px solid var(--color-border, #888);
          border-radius: 0.5rem;
          background: var(--color-bg-soft, #fff);
          color: inherit;
          font: inherit;
        }
        [data-example] button {
          padding: 0.5rem 0.75rem;
          border: 1px solid var(--color-border, #888);
          border-radius: 0.5rem;
          background: var(--color-bg-soft, #fff);
          color: inherit;
          font: inherit;
          cursor: pointer;
        }
        [data-example] button:focus-visible,
        [data-example] input:focus-visible {
          outline: 2px solid currentColor;
          outline-offset: 3px;
        }
        [data-example] p {
          margin: 0;
          overflow-wrap: anywhere;
        }
        [data-example] .actions {
          display: flex;
          flex-wrap: wrap;
          gap: 0.5rem;
        }
        [data-example] [data-pills] {
          display: flex;
          flex-wrap: wrap;
          gap: 0.375rem;
          margin: 0;
          padding: 0;
          list-style: none;
        }
        [data-example] [data-pills]:empty {
          display: none;
        }
        [data-example] .pill {
          display: flex;
          max-width: 100%;
        }
        [data-example] .pill button {
          box-sizing: border-box;
          display: inline-flex;
          align-items: center;
          gap: 0.375rem;
          max-width: 100%;
          height: 2rem;
          padding: 0 0.625rem;
          border: 1px solid var(--color-border, #888);
          border-radius: 1rem;
          background: var(--color-bg, #f4f4f5);
          color: inherit;
          font: inherit;
          font-size: 0.875rem;
          line-height: 1;
          overflow-wrap: anywhere;
          cursor: pointer;
        }
        [data-example] .pill button:hover {
          background: var(--color-bg-soft, #e4e4e7);
        }
        [data-example] .pill button svg {
          width: 0.875rem;
          height: 0.875rem;
          flex: none;
          fill: none;
          stroke: currentColor;
          stroke-width: 2;
          stroke-linecap: round;
          opacity: 0.7;
        }
        [data-example] .pill button:hover svg {
          opacity: 1;
        }
        [data-example] .pill-field {
          display: flex;
          flex-wrap: wrap;
          align-items: center;
          gap: 0.375rem;
          box-sizing: border-box;
          min-height: 3.125rem;
          padding: 0.5rem 0.75rem;
          border: 1px solid var(--color-border, #888);
          border-radius: 0.5rem;
          background: var(--color-bg-soft, #fff);
          cursor: text;
        }
        [data-example] .pill-field:focus-within {
          outline: 2px solid currentColor;
          outline-offset: 2px;
        }
        [data-example] .pill-field input[type='text'] {
          flex: 1 1 8rem;
          width: auto;
          min-width: 0;
          height: 2rem;
          padding: 0;
          border: 0;
          background: transparent;
        }
        [data-example] .pill-field input[type='text']:focus-visible {
          outline: none;
        }
        /* The popup sits after the whole field and overlays what follows it. */
        [data-example='pills'] {
          --autocomplete-max-height: 10rem;
        }
        [data-example='pills'] form {
          display: grid;
          gap: 0.5rem;
        }
        [data-example='pills'] .field [data-autocomplete-popup] {
          position: absolute;
          top: 100%;
        }
        /* One reserved pill row: switching layouts never shifts what follows. */
        [data-example] [data-pills-below] {
          min-height: 2.25rem;
        }
        [data-example] .layout {
          display: flex;
          flex-wrap: wrap;
          gap: 0.25rem;
          margin: 0;
          padding: 0.25rem;
          border: 1px solid var(--color-border, #888);
          border-radius: 0.625rem;
          justify-self: start;
        }
        [data-example] .layout legend {
          position: absolute;
          width: 1px;
          height: 1px;
          overflow: hidden;
          clip-path: inset(50%);
          white-space: nowrap;
        }
        [data-example] .layout label {
          position: relative;
          display: flex;
          align-items: center;
          margin: 0;
          padding: 0.375rem 0.75rem;
          border-radius: 0.375rem;
          font-size: 0.875rem;
          cursor: pointer;
        }
        [data-example] .layout input {
          position: absolute;
          inset: 0;
          width: 100%;
          height: 100%;
          margin: 0;
          opacity: 0;
          pointer-events: none;
        }
        [data-example] .layout label:has(:checked) {
          background: var(--color-bg-soft, #e4e4e7);
          box-shadow: inset 0 0 0 1px var(--color-border, #888);
          font-weight: 600;
        }
        [data-example] .layout label:has(:focus-visible) {
          outline: 2px solid currentColor;
          outline-offset: 2px;
        }
        [data-example] .directory {
          display: grid;
          gap: 0.5rem;
          padding: 0;
          margin: 0;
          list-style: none;
        }
        [data-example] .directory button {
          width: 100%;
          text-align: left;
        }
        [data-example] [aria-disabled='true'] {
          opacity: 0.65;
        }
        [data-example] select {
          padding: 0.75rem 1rem;
          border: 1px solid var(--color-border, #888);
          border-radius: 0.5rem;
          background: var(--color-bg-soft, #fff);
          color: inherit;
          font: inherit;
        }
        [data-example] input[type='text']:disabled {
          opacity: 0.65;
          cursor: not-allowed;
        }
        [data-example] [data-autocomplete-option] small {
          display: block;
          opacity: 0.75;
        }
        [data-example] kbd {
          float: right;
          padding: 0 0.375rem;
          border: 1px solid currentColor;
          border-radius: 0.25rem;
          font:
            0.75rem/1.5 ui-monospace,
            monospace;
          opacity: 0.75;
        }
        

        JavaScript

        main.js
        const setup = (root, createSearch) => {
          const input = root.querySelector('input')
          const results = root.querySelector('[data-results]')
          const note = root.querySelector('[data-note]')
          const events = new AbortController()
          const engine = createSearch({
            source: [
              {
                id: 'design',
                label: 'Design',
                description: 'Visual systems and product experiences',
              },
              {
                id: 'engineering',
                label: 'Engineering',
                description: 'Software and infrastructure',
              },
              {
                id: 'support',
                label: 'Support',
                description: 'Help for our customers',
              },
            ],
            getLabel: item => item.label,
          })
          let pending
          const search = async () => {
            pending?.abort()
            const request = new AbortController()
            pending = request
            const result = await engine.run(input.value, {
              signal: request.signal,
              input,
            })
            if (request.signal.aborted || result.aborted) return
            results.replaceChildren()
            for (const { suggestions } of result.sections)
              for (const item of suggestions) {
                const li = document.createElement('li')
                const button = document.createElement('button')
                button.type = 'button'
                button.textContent = `${item.label} — ${item.description}`
                button.addEventListener('click', () => {
                  note.textContent = `Opened ${item.label}.`
                })
                li.append(button)
                results.append(li)
              }
            note.textContent = `${result.count} teams available. Tab to a result and press Enter.`
          }
          input.addEventListener('input', search, { signal: events.signal })
          search()
          return () => {
            events.abort()
            pending?.abort()
            engine.clearCache()
            results.replaceChildren()
          }
        }
        import('https://cdn.jsdelivr.net/npm/@samline/autocomplete@3.0.0/dist/core/index.js')
          .then(({ createSearch }) => setup(document, createSearch))
          .catch(() => {
            document.querySelector('[data-note]').textContent = 'Could not load the search module.'
          })
        

        Complete file

        index.html
        <!doctype html>
        <html lang="en">
          <head>
            <meta charset="utf-8" />
            <meta name="viewport" content="width=device-width, initial-scale=1" />
            <title>Render a directory with the search pipeline alone</title>
            <link
              rel="stylesheet"
              href="https://cdn.jsdelivr.net/npm/@samline/autocomplete@3.0.0/dist/style.css"
            />
            <style>
              [data-example] {
                display: grid;
                gap: 0.75rem;
              }
              /* Forms lay out like the example root: actions never touch the fields. */
              [data-example] form {
                display: grid;
                gap: 0.75rem;
              }
              [data-example] .field {
                position: relative;
              }
              [data-example] label {
                display: block;
                margin-bottom: 0.5rem;
              }
              [data-example] input[type='text'] {
                box-sizing: border-box;
                width: 100%;
                padding: 0.75rem 1rem;
                border: 1px solid var(--color-border, #888);
                border-radius: 0.5rem;
                background: var(--color-bg-soft, #fff);
                color: inherit;
                font: inherit;
              }
              [data-example] button {
                padding: 0.5rem 0.75rem;
                border: 1px solid var(--color-border, #888);
                border-radius: 0.5rem;
                background: var(--color-bg-soft, #fff);
                color: inherit;
                font: inherit;
                cursor: pointer;
              }
              [data-example] button:focus-visible,
              [data-example] input:focus-visible {
                outline: 2px solid currentColor;
                outline-offset: 3px;
              }
              [data-example] p {
                margin: 0;
                overflow-wrap: anywhere;
              }
              [data-example] .actions {
                display: flex;
                flex-wrap: wrap;
                gap: 0.5rem;
              }
              [data-example] [data-pills] {
                display: flex;
                flex-wrap: wrap;
                gap: 0.375rem;
                margin: 0;
                padding: 0;
                list-style: none;
              }
              [data-example] [data-pills]:empty {
                display: none;
              }
              [data-example] .pill {
                display: flex;
                max-width: 100%;
              }
              [data-example] .pill button {
                box-sizing: border-box;
                display: inline-flex;
                align-items: center;
                gap: 0.375rem;
                max-width: 100%;
                height: 2rem;
                padding: 0 0.625rem;
                border: 1px solid var(--color-border, #888);
                border-radius: 1rem;
                background: var(--color-bg, #f4f4f5);
                color: inherit;
                font: inherit;
                font-size: 0.875rem;
                line-height: 1;
                overflow-wrap: anywhere;
                cursor: pointer;
              }
              [data-example] .pill button:hover {
                background: var(--color-bg-soft, #e4e4e7);
              }
              [data-example] .pill button svg {
                width: 0.875rem;
                height: 0.875rem;
                flex: none;
                fill: none;
                stroke: currentColor;
                stroke-width: 2;
                stroke-linecap: round;
                opacity: 0.7;
              }
              [data-example] .pill button:hover svg {
                opacity: 1;
              }
              [data-example] .pill-field {
                display: flex;
                flex-wrap: wrap;
                align-items: center;
                gap: 0.375rem;
                box-sizing: border-box;
                min-height: 3.125rem;
                padding: 0.5rem 0.75rem;
                border: 1px solid var(--color-border, #888);
                border-radius: 0.5rem;
                background: var(--color-bg-soft, #fff);
                cursor: text;
              }
              [data-example] .pill-field:focus-within {
                outline: 2px solid currentColor;
                outline-offset: 2px;
              }
              [data-example] .pill-field input[type='text'] {
                flex: 1 1 8rem;
                width: auto;
                min-width: 0;
                height: 2rem;
                padding: 0;
                border: 0;
                background: transparent;
              }
              [data-example] .pill-field input[type='text']:focus-visible {
                outline: none;
              }
              /* The popup sits after the whole field and overlays what follows it. */
              [data-example='pills'] {
                --autocomplete-max-height: 10rem;
              }
              [data-example='pills'] form {
                display: grid;
                gap: 0.5rem;
              }
              [data-example='pills'] .field [data-autocomplete-popup] {
                position: absolute;
                top: 100%;
              }
              /* One reserved pill row: switching layouts never shifts what follows. */
              [data-example] [data-pills-below] {
                min-height: 2.25rem;
              }
              [data-example] .layout {
                display: flex;
                flex-wrap: wrap;
                gap: 0.25rem;
                margin: 0;
                padding: 0.25rem;
                border: 1px solid var(--color-border, #888);
                border-radius: 0.625rem;
                justify-self: start;
              }
              [data-example] .layout legend {
                position: absolute;
                width: 1px;
                height: 1px;
                overflow: hidden;
                clip-path: inset(50%);
                white-space: nowrap;
              }
              [data-example] .layout label {
                position: relative;
                display: flex;
                align-items: center;
                margin: 0;
                padding: 0.375rem 0.75rem;
                border-radius: 0.375rem;
                font-size: 0.875rem;
                cursor: pointer;
              }
              [data-example] .layout input {
                position: absolute;
                inset: 0;
                width: 100%;
                height: 100%;
                margin: 0;
                opacity: 0;
                pointer-events: none;
              }
              [data-example] .layout label:has(:checked) {
                background: var(--color-bg-soft, #e4e4e7);
                box-shadow: inset 0 0 0 1px var(--color-border, #888);
                font-weight: 600;
              }
              [data-example] .layout label:has(:focus-visible) {
                outline: 2px solid currentColor;
                outline-offset: 2px;
              }
              [data-example] .directory {
                display: grid;
                gap: 0.5rem;
                padding: 0;
                margin: 0;
                list-style: none;
              }
              [data-example] .directory button {
                width: 100%;
                text-align: left;
              }
              [data-example] [aria-disabled='true'] {
                opacity: 0.65;
              }
              [data-example] select {
                padding: 0.75rem 1rem;
                border: 1px solid var(--color-border, #888);
                border-radius: 0.5rem;
                background: var(--color-bg-soft, #fff);
                color: inherit;
                font: inherit;
              }
              [data-example] input[type='text']:disabled {
                opacity: 0.65;
                cursor: not-allowed;
              }
              [data-example] [data-autocomplete-option] small {
                display: block;
                opacity: 0.75;
              }
              [data-example] kbd {
                float: right;
                padding: 0 0.375rem;
                border: 1px solid currentColor;
                border-radius: 0.25rem;
                font:
                  0.75rem/1.5 ui-monospace,
                  monospace;
                opacity: 0.75;
              }
            </style>
          </head>
          <body>
            <main>
              <div data-example="headless">
                <label for="headless-input">Filter teams</label><input id="headless-input" type="text" />
                <p data-note role="status"></p>
                <ul class="directory" data-results aria-label="Matching teams"></ul>
              </div>
            </main>
            <script src="https://cdn.jsdelivr.net/npm/@samline/autocomplete@3.0.0/dist/browser/autocomplete.global.js"></script>
            <script>
              const setup = (root, createSearch) => {
                const input = root.querySelector('input')
                const results = root.querySelector('[data-results]')
                const note = root.querySelector('[data-note]')
                const events = new AbortController()
                const engine = createSearch({
                  source: [
                    {
                      id: 'design',
                      label: 'Design',
                      description: 'Visual systems and product experiences',
                    },
                    {
                      id: 'engineering',
                      label: 'Engineering',
                      description: 'Software and infrastructure',
                    },
                    {
                      id: 'support',
                      label: 'Support',
                      description: 'Help for our customers',
                    },
                  ],
                  getLabel: item => item.label,
                })
                let pending
                const search = async () => {
                  pending?.abort()
                  const request = new AbortController()
                  pending = request
                  const result = await engine.run(input.value, {
                    signal: request.signal,
                    input,
                  })
                  if (request.signal.aborted || result.aborted) return
                  results.replaceChildren()
                  for (const { suggestions } of result.sections)
                    for (const item of suggestions) {
                      const li = document.createElement('li')
                      const button = document.createElement('button')
                      button.type = 'button'
                      button.textContent = `${item.label} — ${item.description}`
                      button.addEventListener('click', () => {
                        note.textContent = `Opened ${item.label}.`
                      })
                      li.append(button)
                      results.append(li)
                    }
                  note.textContent = `${result.count} teams available. Tab to a result and press Enter.`
                }
                input.addEventListener('input', search, { signal: events.signal })
                search()
                return () => {
                  events.abort()
                  pending?.abort()
                  engine.clearCache()
                  results.replaceChildren()
                }
              }
              import('https://cdn.jsdelivr.net/npm/@samline/autocomplete@3.0.0/dist/core/index.js')
                .then(({ createSearch }) => setup(document, createSearch))
                .catch(() => {
                  document.querySelector('[data-note]').textContent = 'Could not load the search module.'
                })
            </script>
          </body>
        </html>
        

        Package / ESM

        HTML

        index.html
        <!doctype html>
        <html lang="en">
          <head>
            <meta charset="utf-8" />
            <meta name="viewport" content="width=device-width, initial-scale=1" />
            <title>Render a directory with the search pipeline alone</title>
            <link rel="stylesheet" href="./style.css" />
          </head>
          <body>
            <main>
              <div data-example="headless">
                <label for="headless-input">Filter teams</label><input id="headless-input" type="text" />
                <p data-note role="status"></p>
                <ul class="directory" data-results aria-label="Matching teams"></ul>
              </div>
            </main>
            <script type="module" src="./main.js"></script>
          </body>
        </html>
        

        CSS

        style.css
        [data-example] {
          display: grid;
          gap: 0.75rem;
        }
        /* Forms lay out like the example root: actions never touch the fields. */
        [data-example] form {
          display: grid;
          gap: 0.75rem;
        }
        [data-example] .field {
          position: relative;
        }
        [data-example] label {
          display: block;
          margin-bottom: 0.5rem;
        }
        [data-example] input[type='text'] {
          box-sizing: border-box;
          width: 100%;
          padding: 0.75rem 1rem;
          border: 1px solid var(--color-border, #888);
          border-radius: 0.5rem;
          background: var(--color-bg-soft, #fff);
          color: inherit;
          font: inherit;
        }
        [data-example] button {
          padding: 0.5rem 0.75rem;
          border: 1px solid var(--color-border, #888);
          border-radius: 0.5rem;
          background: var(--color-bg-soft, #fff);
          color: inherit;
          font: inherit;
          cursor: pointer;
        }
        [data-example] button:focus-visible,
        [data-example] input:focus-visible {
          outline: 2px solid currentColor;
          outline-offset: 3px;
        }
        [data-example] p {
          margin: 0;
          overflow-wrap: anywhere;
        }
        [data-example] .actions {
          display: flex;
          flex-wrap: wrap;
          gap: 0.5rem;
        }
        [data-example] [data-pills] {
          display: flex;
          flex-wrap: wrap;
          gap: 0.375rem;
          margin: 0;
          padding: 0;
          list-style: none;
        }
        [data-example] [data-pills]:empty {
          display: none;
        }
        [data-example] .pill {
          display: flex;
          max-width: 100%;
        }
        [data-example] .pill button {
          box-sizing: border-box;
          display: inline-flex;
          align-items: center;
          gap: 0.375rem;
          max-width: 100%;
          height: 2rem;
          padding: 0 0.625rem;
          border: 1px solid var(--color-border, #888);
          border-radius: 1rem;
          background: var(--color-bg, #f4f4f5);
          color: inherit;
          font: inherit;
          font-size: 0.875rem;
          line-height: 1;
          overflow-wrap: anywhere;
          cursor: pointer;
        }
        [data-example] .pill button:hover {
          background: var(--color-bg-soft, #e4e4e7);
        }
        [data-example] .pill button svg {
          width: 0.875rem;
          height: 0.875rem;
          flex: none;
          fill: none;
          stroke: currentColor;
          stroke-width: 2;
          stroke-linecap: round;
          opacity: 0.7;
        }
        [data-example] .pill button:hover svg {
          opacity: 1;
        }
        [data-example] .pill-field {
          display: flex;
          flex-wrap: wrap;
          align-items: center;
          gap: 0.375rem;
          box-sizing: border-box;
          min-height: 3.125rem;
          padding: 0.5rem 0.75rem;
          border: 1px solid var(--color-border, #888);
          border-radius: 0.5rem;
          background: var(--color-bg-soft, #fff);
          cursor: text;
        }
        [data-example] .pill-field:focus-within {
          outline: 2px solid currentColor;
          outline-offset: 2px;
        }
        [data-example] .pill-field input[type='text'] {
          flex: 1 1 8rem;
          width: auto;
          min-width: 0;
          height: 2rem;
          padding: 0;
          border: 0;
          background: transparent;
        }
        [data-example] .pill-field input[type='text']:focus-visible {
          outline: none;
        }
        /* The popup sits after the whole field and overlays what follows it. */
        [data-example='pills'] {
          --autocomplete-max-height: 10rem;
        }
        [data-example='pills'] form {
          display: grid;
          gap: 0.5rem;
        }
        [data-example='pills'] .field [data-autocomplete-popup] {
          position: absolute;
          top: 100%;
        }
        /* One reserved pill row: switching layouts never shifts what follows. */
        [data-example] [data-pills-below] {
          min-height: 2.25rem;
        }
        [data-example] .layout {
          display: flex;
          flex-wrap: wrap;
          gap: 0.25rem;
          margin: 0;
          padding: 0.25rem;
          border: 1px solid var(--color-border, #888);
          border-radius: 0.625rem;
          justify-self: start;
        }
        [data-example] .layout legend {
          position: absolute;
          width: 1px;
          height: 1px;
          overflow: hidden;
          clip-path: inset(50%);
          white-space: nowrap;
        }
        [data-example] .layout label {
          position: relative;
          display: flex;
          align-items: center;
          margin: 0;
          padding: 0.375rem 0.75rem;
          border-radius: 0.375rem;
          font-size: 0.875rem;
          cursor: pointer;
        }
        [data-example] .layout input {
          position: absolute;
          inset: 0;
          width: 100%;
          height: 100%;
          margin: 0;
          opacity: 0;
          pointer-events: none;
        }
        [data-example] .layout label:has(:checked) {
          background: var(--color-bg-soft, #e4e4e7);
          box-shadow: inset 0 0 0 1px var(--color-border, #888);
          font-weight: 600;
        }
        [data-example] .layout label:has(:focus-visible) {
          outline: 2px solid currentColor;
          outline-offset: 2px;
        }
        [data-example] .directory {
          display: grid;
          gap: 0.5rem;
          padding: 0;
          margin: 0;
          list-style: none;
        }
        [data-example] .directory button {
          width: 100%;
          text-align: left;
        }
        [data-example] [aria-disabled='true'] {
          opacity: 0.65;
        }
        [data-example] select {
          padding: 0.75rem 1rem;
          border: 1px solid var(--color-border, #888);
          border-radius: 0.5rem;
          background: var(--color-bg-soft, #fff);
          color: inherit;
          font: inherit;
        }
        [data-example] input[type='text']:disabled {
          opacity: 0.65;
          cursor: not-allowed;
        }
        [data-example] [data-autocomplete-option] small {
          display: block;
          opacity: 0.75;
        }
        [data-example] kbd {
          float: right;
          padding: 0 0.375rem;
          border: 1px solid currentColor;
          border-radius: 0.25rem;
          font:
            0.75rem/1.5 ui-monospace,
            monospace;
          opacity: 0.75;
        }
        

        JavaScript

        main.js
        import { createSearch } from '@samline/autocomplete/core'
        const setup = (root, createSearch) => {
          const input = root.querySelector('input')
          const results = root.querySelector('[data-results]')
          const note = root.querySelector('[data-note]')
          const events = new AbortController()
          const engine = createSearch({
            source: [
              {
                id: 'design',
                label: 'Design',
                description: 'Visual systems and product experiences',
              },
              {
                id: 'engineering',
                label: 'Engineering',
                description: 'Software and infrastructure',
              },
              {
                id: 'support',
                label: 'Support',
                description: 'Help for our customers',
              },
            ],
            getLabel: item => item.label,
          })
          let pending
          const search = async () => {
            pending?.abort()
            const request = new AbortController()
            pending = request
            const result = await engine.run(input.value, {
              signal: request.signal,
              input,
            })
            if (request.signal.aborted || result.aborted) return
            results.replaceChildren()
            for (const { suggestions } of result.sections)
              for (const item of suggestions) {
                const li = document.createElement('li')
                const button = document.createElement('button')
                button.type = 'button'
                button.textContent = `${item.label} — ${item.description}`
                button.addEventListener('click', () => {
                  note.textContent = `Opened ${item.label}.`
                })
                li.append(button)
                results.append(li)
              }
            note.textContent = `${result.count} teams available. Tab to a result and press Enter.`
          }
          input.addEventListener('input', search, { signal: events.signal })
          search()
          return () => {
            events.abort()
            pending?.abort()
            engine.clearCache()
            results.replaceChildren()
          }
        }
        setup(document, createSearch)
        

        Complete file

        index.html
        <!doctype html>
        <html lang="en">
          <head>
            <meta charset="utf-8" />
            <meta name="viewport" content="width=device-width, initial-scale=1" />
            <title>Render a directory with the search pipeline alone</title>
            <style>
              [data-example] {
                display: grid;
                gap: 0.75rem;
              }
              /* Forms lay out like the example root: actions never touch the fields. */
              [data-example] form {
                display: grid;
                gap: 0.75rem;
              }
              [data-example] .field {
                position: relative;
              }
              [data-example] label {
                display: block;
                margin-bottom: 0.5rem;
              }
              [data-example] input[type='text'] {
                box-sizing: border-box;
                width: 100%;
                padding: 0.75rem 1rem;
                border: 1px solid var(--color-border, #888);
                border-radius: 0.5rem;
                background: var(--color-bg-soft, #fff);
                color: inherit;
                font: inherit;
              }
              [data-example] button {
                padding: 0.5rem 0.75rem;
                border: 1px solid var(--color-border, #888);
                border-radius: 0.5rem;
                background: var(--color-bg-soft, #fff);
                color: inherit;
                font: inherit;
                cursor: pointer;
              }
              [data-example] button:focus-visible,
              [data-example] input:focus-visible {
                outline: 2px solid currentColor;
                outline-offset: 3px;
              }
              [data-example] p {
                margin: 0;
                overflow-wrap: anywhere;
              }
              [data-example] .actions {
                display: flex;
                flex-wrap: wrap;
                gap: 0.5rem;
              }
              [data-example] [data-pills] {
                display: flex;
                flex-wrap: wrap;
                gap: 0.375rem;
                margin: 0;
                padding: 0;
                list-style: none;
              }
              [data-example] [data-pills]:empty {
                display: none;
              }
              [data-example] .pill {
                display: flex;
                max-width: 100%;
              }
              [data-example] .pill button {
                box-sizing: border-box;
                display: inline-flex;
                align-items: center;
                gap: 0.375rem;
                max-width: 100%;
                height: 2rem;
                padding: 0 0.625rem;
                border: 1px solid var(--color-border, #888);
                border-radius: 1rem;
                background: var(--color-bg, #f4f4f5);
                color: inherit;
                font: inherit;
                font-size: 0.875rem;
                line-height: 1;
                overflow-wrap: anywhere;
                cursor: pointer;
              }
              [data-example] .pill button:hover {
                background: var(--color-bg-soft, #e4e4e7);
              }
              [data-example] .pill button svg {
                width: 0.875rem;
                height: 0.875rem;
                flex: none;
                fill: none;
                stroke: currentColor;
                stroke-width: 2;
                stroke-linecap: round;
                opacity: 0.7;
              }
              [data-example] .pill button:hover svg {
                opacity: 1;
              }
              [data-example] .pill-field {
                display: flex;
                flex-wrap: wrap;
                align-items: center;
                gap: 0.375rem;
                box-sizing: border-box;
                min-height: 3.125rem;
                padding: 0.5rem 0.75rem;
                border: 1px solid var(--color-border, #888);
                border-radius: 0.5rem;
                background: var(--color-bg-soft, #fff);
                cursor: text;
              }
              [data-example] .pill-field:focus-within {
                outline: 2px solid currentColor;
                outline-offset: 2px;
              }
              [data-example] .pill-field input[type='text'] {
                flex: 1 1 8rem;
                width: auto;
                min-width: 0;
                height: 2rem;
                padding: 0;
                border: 0;
                background: transparent;
              }
              [data-example] .pill-field input[type='text']:focus-visible {
                outline: none;
              }
              /* The popup sits after the whole field and overlays what follows it. */
              [data-example='pills'] {
                --autocomplete-max-height: 10rem;
              }
              [data-example='pills'] form {
                display: grid;
                gap: 0.5rem;
              }
              [data-example='pills'] .field [data-autocomplete-popup] {
                position: absolute;
                top: 100%;
              }
              /* One reserved pill row: switching layouts never shifts what follows. */
              [data-example] [data-pills-below] {
                min-height: 2.25rem;
              }
              [data-example] .layout {
                display: flex;
                flex-wrap: wrap;
                gap: 0.25rem;
                margin: 0;
                padding: 0.25rem;
                border: 1px solid var(--color-border, #888);
                border-radius: 0.625rem;
                justify-self: start;
              }
              [data-example] .layout legend {
                position: absolute;
                width: 1px;
                height: 1px;
                overflow: hidden;
                clip-path: inset(50%);
                white-space: nowrap;
              }
              [data-example] .layout label {
                position: relative;
                display: flex;
                align-items: center;
                margin: 0;
                padding: 0.375rem 0.75rem;
                border-radius: 0.375rem;
                font-size: 0.875rem;
                cursor: pointer;
              }
              [data-example] .layout input {
                position: absolute;
                inset: 0;
                width: 100%;
                height: 100%;
                margin: 0;
                opacity: 0;
                pointer-events: none;
              }
              [data-example] .layout label:has(:checked) {
                background: var(--color-bg-soft, #e4e4e7);
                box-shadow: inset 0 0 0 1px var(--color-border, #888);
                font-weight: 600;
              }
              [data-example] .layout label:has(:focus-visible) {
                outline: 2px solid currentColor;
                outline-offset: 2px;
              }
              [data-example] .directory {
                display: grid;
                gap: 0.5rem;
                padding: 0;
                margin: 0;
                list-style: none;
              }
              [data-example] .directory button {
                width: 100%;
                text-align: left;
              }
              [data-example] [aria-disabled='true'] {
                opacity: 0.65;
              }
              [data-example] select {
                padding: 0.75rem 1rem;
                border: 1px solid var(--color-border, #888);
                border-radius: 0.5rem;
                background: var(--color-bg-soft, #fff);
                color: inherit;
                font: inherit;
              }
              [data-example] input[type='text']:disabled {
                opacity: 0.65;
                cursor: not-allowed;
              }
              [data-example] [data-autocomplete-option] small {
                display: block;
                opacity: 0.75;
              }
              [data-example] kbd {
                float: right;
                padding: 0 0.375rem;
                border: 1px solid currentColor;
                border-radius: 0.25rem;
                font:
                  0.75rem/1.5 ui-monospace,
                  monospace;
                opacity: 0.75;
              }
            </style>
          </head>
          <body>
            <main>
              <div data-example="headless">
                <label for="headless-input">Filter teams</label><input id="headless-input" type="text" />
                <p data-note role="status"></p>
                <ul class="directory" data-results aria-label="Matching teams"></ul>
              </div>
            </main>
            <script type="module">
              import { createSearch } from '@samline/autocomplete/core'
              const setup = (root, createSearch) => {
                const input = root.querySelector('input')
                const results = root.querySelector('[data-results]')
                const note = root.querySelector('[data-note]')
                const events = new AbortController()
                const engine = createSearch({
                  source: [
                    {
                      id: 'design',
                      label: 'Design',
                      description: 'Visual systems and product experiences',
                    },
                    {
                      id: 'engineering',
                      label: 'Engineering',
                      description: 'Software and infrastructure',
                    },
                    {
                      id: 'support',
                      label: 'Support',
                      description: 'Help for our customers',
                    },
                  ],
                  getLabel: item => item.label,
                })
                let pending
                const search = async () => {
                  pending?.abort()
                  const request = new AbortController()
                  pending = request
                  const result = await engine.run(input.value, {
                    signal: request.signal,
                    input,
                  })
                  if (request.signal.aborted || result.aborted) return
                  results.replaceChildren()
                  for (const { suggestions } of result.sections)
                    for (const item of suggestions) {
                      const li = document.createElement('li')
                      const button = document.createElement('button')
                      button.type = 'button'
                      button.textContent = `${item.label} — ${item.description}`
                      button.addEventListener('click', () => {
                        note.textContent = `Opened ${item.label}.`
                      })
                      li.append(button)
                      results.append(li)
                    }
                  note.textContent = `${result.count} teams available. Tab to a result and press Enter.`
                }
                input.addEventListener('input', search, { signal: events.signal })
                search()
                return () => {
                  events.abort()
                  pending?.abort()
                  engine.clearCache()
                  results.replaceChildren()
                }
              }
              setup(document, createSearch)
            </script>
          </body>
        </html>
        

        Build a command palette with actions and pages

        Command paletteLive preview

        Two local sections share a filter that also matches hidden keywords: “invoice” finds Billing and renderOption explains why. Shortcut hints and a footer are plain DOM nodes. The select event reports the section, the palette clears itself after each command and the last three picks return as Recent on an empty field.

        Nothing run yet.

        Explore the code

        HTML / CDN

        HTML

        index.html
        <!doctype html>
        <html lang="en">
          <head>
            <meta charset="utf-8" />
            <meta name="viewport" content="width=device-width, initial-scale=1" />
            <title>Build a command palette with actions and pages</title>
            <link
              rel="stylesheet"
              href="https://cdn.jsdelivr.net/npm/@samline/autocomplete@3.0.0/dist/style.css"
            />
            <link rel="stylesheet" href="./style.css" />
          </head>
          <body>
            <main>
              <div data-example="palette">
                <div class="field">
                  <label for="palette-input">Command</label
                  ><input id="palette-input" type="text" placeholder="Try new, invoice or theme" />
                </div>
                <p data-output role="status">Nothing run yet.</p>
              </div>
            </main>
            <script src="https://cdn.jsdelivr.net/npm/@samline/autocomplete@3.0.0/dist/browser/autocomplete.global.js"></script>
            <script src="./main.js" defer></script>
          </body>
        </html>
        

        CSS

        style.css
        [data-example] {
          display: grid;
          gap: 0.75rem;
        }
        /* Forms lay out like the example root: actions never touch the fields. */
        [data-example] form {
          display: grid;
          gap: 0.75rem;
        }
        [data-example] .field {
          position: relative;
        }
        [data-example] label {
          display: block;
          margin-bottom: 0.5rem;
        }
        [data-example] input[type='text'] {
          box-sizing: border-box;
          width: 100%;
          padding: 0.75rem 1rem;
          border: 1px solid var(--color-border, #888);
          border-radius: 0.5rem;
          background: var(--color-bg-soft, #fff);
          color: inherit;
          font: inherit;
        }
        [data-example] button {
          padding: 0.5rem 0.75rem;
          border: 1px solid var(--color-border, #888);
          border-radius: 0.5rem;
          background: var(--color-bg-soft, #fff);
          color: inherit;
          font: inherit;
          cursor: pointer;
        }
        [data-example] button:focus-visible,
        [data-example] input:focus-visible {
          outline: 2px solid currentColor;
          outline-offset: 3px;
        }
        [data-example] p {
          margin: 0;
          overflow-wrap: anywhere;
        }
        [data-example] .actions {
          display: flex;
          flex-wrap: wrap;
          gap: 0.5rem;
        }
        [data-example] [data-pills] {
          display: flex;
          flex-wrap: wrap;
          gap: 0.375rem;
          margin: 0;
          padding: 0;
          list-style: none;
        }
        [data-example] [data-pills]:empty {
          display: none;
        }
        [data-example] .pill {
          display: flex;
          max-width: 100%;
        }
        [data-example] .pill button {
          box-sizing: border-box;
          display: inline-flex;
          align-items: center;
          gap: 0.375rem;
          max-width: 100%;
          height: 2rem;
          padding: 0 0.625rem;
          border: 1px solid var(--color-border, #888);
          border-radius: 1rem;
          background: var(--color-bg, #f4f4f5);
          color: inherit;
          font: inherit;
          font-size: 0.875rem;
          line-height: 1;
          overflow-wrap: anywhere;
          cursor: pointer;
        }
        [data-example] .pill button:hover {
          background: var(--color-bg-soft, #e4e4e7);
        }
        [data-example] .pill button svg {
          width: 0.875rem;
          height: 0.875rem;
          flex: none;
          fill: none;
          stroke: currentColor;
          stroke-width: 2;
          stroke-linecap: round;
          opacity: 0.7;
        }
        [data-example] .pill button:hover svg {
          opacity: 1;
        }
        [data-example] .pill-field {
          display: flex;
          flex-wrap: wrap;
          align-items: center;
          gap: 0.375rem;
          box-sizing: border-box;
          min-height: 3.125rem;
          padding: 0.5rem 0.75rem;
          border: 1px solid var(--color-border, #888);
          border-radius: 0.5rem;
          background: var(--color-bg-soft, #fff);
          cursor: text;
        }
        [data-example] .pill-field:focus-within {
          outline: 2px solid currentColor;
          outline-offset: 2px;
        }
        [data-example] .pill-field input[type='text'] {
          flex: 1 1 8rem;
          width: auto;
          min-width: 0;
          height: 2rem;
          padding: 0;
          border: 0;
          background: transparent;
        }
        [data-example] .pill-field input[type='text']:focus-visible {
          outline: none;
        }
        /* The popup sits after the whole field and overlays what follows it. */
        [data-example='pills'] {
          --autocomplete-max-height: 10rem;
        }
        [data-example='pills'] form {
          display: grid;
          gap: 0.5rem;
        }
        [data-example='pills'] .field [data-autocomplete-popup] {
          position: absolute;
          top: 100%;
        }
        /* One reserved pill row: switching layouts never shifts what follows. */
        [data-example] [data-pills-below] {
          min-height: 2.25rem;
        }
        [data-example] .layout {
          display: flex;
          flex-wrap: wrap;
          gap: 0.25rem;
          margin: 0;
          padding: 0.25rem;
          border: 1px solid var(--color-border, #888);
          border-radius: 0.625rem;
          justify-self: start;
        }
        [data-example] .layout legend {
          position: absolute;
          width: 1px;
          height: 1px;
          overflow: hidden;
          clip-path: inset(50%);
          white-space: nowrap;
        }
        [data-example] .layout label {
          position: relative;
          display: flex;
          align-items: center;
          margin: 0;
          padding: 0.375rem 0.75rem;
          border-radius: 0.375rem;
          font-size: 0.875rem;
          cursor: pointer;
        }
        [data-example] .layout input {
          position: absolute;
          inset: 0;
          width: 100%;
          height: 100%;
          margin: 0;
          opacity: 0;
          pointer-events: none;
        }
        [data-example] .layout label:has(:checked) {
          background: var(--color-bg-soft, #e4e4e7);
          box-shadow: inset 0 0 0 1px var(--color-border, #888);
          font-weight: 600;
        }
        [data-example] .layout label:has(:focus-visible) {
          outline: 2px solid currentColor;
          outline-offset: 2px;
        }
        [data-example] .directory {
          display: grid;
          gap: 0.5rem;
          padding: 0;
          margin: 0;
          list-style: none;
        }
        [data-example] .directory button {
          width: 100%;
          text-align: left;
        }
        [data-example] [aria-disabled='true'] {
          opacity: 0.65;
        }
        [data-example] select {
          padding: 0.75rem 1rem;
          border: 1px solid var(--color-border, #888);
          border-radius: 0.5rem;
          background: var(--color-bg-soft, #fff);
          color: inherit;
          font: inherit;
        }
        [data-example] input[type='text']:disabled {
          opacity: 0.65;
          cursor: not-allowed;
        }
        [data-example] [data-autocomplete-option] small {
          display: block;
          opacity: 0.75;
        }
        [data-example] kbd {
          float: right;
          padding: 0 0.375rem;
          border: 1px solid currentColor;
          border-radius: 0.25rem;
          font:
            0.75rem/1.5 ui-monospace,
            monospace;
          opacity: 0.75;
        }
        

        JavaScript

        main.js
        const setup = (root, createAutocomplete) => {
          const input = root.querySelector('input')
          const output = root.querySelector('[data-output]')
          const actions = [
            {
              id: 'new-document',
              label: 'New document',
              keywords: 'create add file',
              shortcut: 'N',
            },
            {
              id: 'invite',
              label: 'Invite a teammate',
              keywords: 'share people member',
              shortcut: 'I',
            },
            {
              id: 'theme',
              label: 'Switch theme',
              keywords: 'dark light appearance',
              shortcut: 'T',
            },
          ]
          const pages = [
            {
              id: 'billing',
              label: 'Billing',
              keywords: 'invoice payment plan',
            },
            {
              id: 'reports',
              label: 'Reports',
              keywords: 'analytics charts metrics',
            },
            {
              id: 'settings',
              label: 'Settings',
              keywords: 'preferences account profile',
            },
          ]
          const isAction = new Set(actions.map(item => item.id))
          const normalize = text => text.normalize('NFD').replace(/\p{M}/gu, '').toLowerCase()
          const filter = (item, query) =>
            normalize(`${item.label} ${item.keywords}`).includes(normalize(query))
          const controller = createAutocomplete(input, {
            sections: [
              {
                id: 'actions',
                label: 'Actions',
                source: actions,
                filter,
              },
              {
                id: 'pages',
                label: 'Go to',
                source: pages,
                filter,
              },
            ],
            getId: item => item.id,
            getLabel: item => item.label,
            recent: {
              label: 'Recent',
              max: 3,
            },
            renderOption: (element, item, { highlight, query }) => {
              if (query && !highlight.some(part => part.match)) {
                const hint = document.createElement('small')
                hint.textContent = `Matches “${query}” in ${item.keywords}`
                element.append(hint)
              }
              if (item.shortcut) {
                const key = document.createElement('kbd')
                key.textContent = item.shortcut
                key.setAttribute('aria-hidden', 'true')
                element.prepend(key)
              }
            },
            renderFooter: element => {
              element.textContent = '↑ ↓ to move · Enter to run · Esc to close'
            },
          })
          const off = controller.on('select', ({ suggestion, section }) => {
            const verb = isAction.has(suggestion.id) ? 'Ran' : 'Opened'
            output.textContent = `${verb} “${suggestion.label}” from ${section}.`
            controller.clear()
          })
          return () => {
            off()
            controller.destroy()
          }
        }
        setup(document, window.Autocomplete.autocomplete)
        

        Complete file

        index.html
        <!doctype html>
        <html lang="en">
          <head>
            <meta charset="utf-8" />
            <meta name="viewport" content="width=device-width, initial-scale=1" />
            <title>Build a command palette with actions and pages</title>
            <link
              rel="stylesheet"
              href="https://cdn.jsdelivr.net/npm/@samline/autocomplete@3.0.0/dist/style.css"
            />
            <style>
              [data-example] {
                display: grid;
                gap: 0.75rem;
              }
              /* Forms lay out like the example root: actions never touch the fields. */
              [data-example] form {
                display: grid;
                gap: 0.75rem;
              }
              [data-example] .field {
                position: relative;
              }
              [data-example] label {
                display: block;
                margin-bottom: 0.5rem;
              }
              [data-example] input[type='text'] {
                box-sizing: border-box;
                width: 100%;
                padding: 0.75rem 1rem;
                border: 1px solid var(--color-border, #888);
                border-radius: 0.5rem;
                background: var(--color-bg-soft, #fff);
                color: inherit;
                font: inherit;
              }
              [data-example] button {
                padding: 0.5rem 0.75rem;
                border: 1px solid var(--color-border, #888);
                border-radius: 0.5rem;
                background: var(--color-bg-soft, #fff);
                color: inherit;
                font: inherit;
                cursor: pointer;
              }
              [data-example] button:focus-visible,
              [data-example] input:focus-visible {
                outline: 2px solid currentColor;
                outline-offset: 3px;
              }
              [data-example] p {
                margin: 0;
                overflow-wrap: anywhere;
              }
              [data-example] .actions {
                display: flex;
                flex-wrap: wrap;
                gap: 0.5rem;
              }
              [data-example] [data-pills] {
                display: flex;
                flex-wrap: wrap;
                gap: 0.375rem;
                margin: 0;
                padding: 0;
                list-style: none;
              }
              [data-example] [data-pills]:empty {
                display: none;
              }
              [data-example] .pill {
                display: flex;
                max-width: 100%;
              }
              [data-example] .pill button {
                box-sizing: border-box;
                display: inline-flex;
                align-items: center;
                gap: 0.375rem;
                max-width: 100%;
                height: 2rem;
                padding: 0 0.625rem;
                border: 1px solid var(--color-border, #888);
                border-radius: 1rem;
                background: var(--color-bg, #f4f4f5);
                color: inherit;
                font: inherit;
                font-size: 0.875rem;
                line-height: 1;
                overflow-wrap: anywhere;
                cursor: pointer;
              }
              [data-example] .pill button:hover {
                background: var(--color-bg-soft, #e4e4e7);
              }
              [data-example] .pill button svg {
                width: 0.875rem;
                height: 0.875rem;
                flex: none;
                fill: none;
                stroke: currentColor;
                stroke-width: 2;
                stroke-linecap: round;
                opacity: 0.7;
              }
              [data-example] .pill button:hover svg {
                opacity: 1;
              }
              [data-example] .pill-field {
                display: flex;
                flex-wrap: wrap;
                align-items: center;
                gap: 0.375rem;
                box-sizing: border-box;
                min-height: 3.125rem;
                padding: 0.5rem 0.75rem;
                border: 1px solid var(--color-border, #888);
                border-radius: 0.5rem;
                background: var(--color-bg-soft, #fff);
                cursor: text;
              }
              [data-example] .pill-field:focus-within {
                outline: 2px solid currentColor;
                outline-offset: 2px;
              }
              [data-example] .pill-field input[type='text'] {
                flex: 1 1 8rem;
                width: auto;
                min-width: 0;
                height: 2rem;
                padding: 0;
                border: 0;
                background: transparent;
              }
              [data-example] .pill-field input[type='text']:focus-visible {
                outline: none;
              }
              /* The popup sits after the whole field and overlays what follows it. */
              [data-example='pills'] {
                --autocomplete-max-height: 10rem;
              }
              [data-example='pills'] form {
                display: grid;
                gap: 0.5rem;
              }
              [data-example='pills'] .field [data-autocomplete-popup] {
                position: absolute;
                top: 100%;
              }
              /* One reserved pill row: switching layouts never shifts what follows. */
              [data-example] [data-pills-below] {
                min-height: 2.25rem;
              }
              [data-example] .layout {
                display: flex;
                flex-wrap: wrap;
                gap: 0.25rem;
                margin: 0;
                padding: 0.25rem;
                border: 1px solid var(--color-border, #888);
                border-radius: 0.625rem;
                justify-self: start;
              }
              [data-example] .layout legend {
                position: absolute;
                width: 1px;
                height: 1px;
                overflow: hidden;
                clip-path: inset(50%);
                white-space: nowrap;
              }
              [data-example] .layout label {
                position: relative;
                display: flex;
                align-items: center;
                margin: 0;
                padding: 0.375rem 0.75rem;
                border-radius: 0.375rem;
                font-size: 0.875rem;
                cursor: pointer;
              }
              [data-example] .layout input {
                position: absolute;
                inset: 0;
                width: 100%;
                height: 100%;
                margin: 0;
                opacity: 0;
                pointer-events: none;
              }
              [data-example] .layout label:has(:checked) {
                background: var(--color-bg-soft, #e4e4e7);
                box-shadow: inset 0 0 0 1px var(--color-border, #888);
                font-weight: 600;
              }
              [data-example] .layout label:has(:focus-visible) {
                outline: 2px solid currentColor;
                outline-offset: 2px;
              }
              [data-example] .directory {
                display: grid;
                gap: 0.5rem;
                padding: 0;
                margin: 0;
                list-style: none;
              }
              [data-example] .directory button {
                width: 100%;
                text-align: left;
              }
              [data-example] [aria-disabled='true'] {
                opacity: 0.65;
              }
              [data-example] select {
                padding: 0.75rem 1rem;
                border: 1px solid var(--color-border, #888);
                border-radius: 0.5rem;
                background: var(--color-bg-soft, #fff);
                color: inherit;
                font: inherit;
              }
              [data-example] input[type='text']:disabled {
                opacity: 0.65;
                cursor: not-allowed;
              }
              [data-example] [data-autocomplete-option] small {
                display: block;
                opacity: 0.75;
              }
              [data-example] kbd {
                float: right;
                padding: 0 0.375rem;
                border: 1px solid currentColor;
                border-radius: 0.25rem;
                font:
                  0.75rem/1.5 ui-monospace,
                  monospace;
                opacity: 0.75;
              }
            </style>
          </head>
          <body>
            <main>
              <div data-example="palette">
                <div class="field">
                  <label for="palette-input">Command</label
                  ><input id="palette-input" type="text" placeholder="Try new, invoice or theme" />
                </div>
                <p data-output role="status">Nothing run yet.</p>
              </div>
            </main>
            <script src="https://cdn.jsdelivr.net/npm/@samline/autocomplete@3.0.0/dist/browser/autocomplete.global.js"></script>
            <script>
              const setup = (root, createAutocomplete) => {
                const input = root.querySelector('input')
                const output = root.querySelector('[data-output]')
                const actions = [
                  {
                    id: 'new-document',
                    label: 'New document',
                    keywords: 'create add file',
                    shortcut: 'N',
                  },
                  {
                    id: 'invite',
                    label: 'Invite a teammate',
                    keywords: 'share people member',
                    shortcut: 'I',
                  },
                  {
                    id: 'theme',
                    label: 'Switch theme',
                    keywords: 'dark light appearance',
                    shortcut: 'T',
                  },
                ]
                const pages = [
                  {
                    id: 'billing',
                    label: 'Billing',
                    keywords: 'invoice payment plan',
                  },
                  {
                    id: 'reports',
                    label: 'Reports',
                    keywords: 'analytics charts metrics',
                  },
                  {
                    id: 'settings',
                    label: 'Settings',
                    keywords: 'preferences account profile',
                  },
                ]
                const isAction = new Set(actions.map(item => item.id))
                const normalize = text => text.normalize('NFD').replace(/\p{M}/gu, '').toLowerCase()
                const filter = (item, query) =>
                  normalize(`${item.label} ${item.keywords}`).includes(normalize(query))
                const controller = createAutocomplete(input, {
                  sections: [
                    {
                      id: 'actions',
                      label: 'Actions',
                      source: actions,
                      filter,
                    },
                    {
                      id: 'pages',
                      label: 'Go to',
                      source: pages,
                      filter,
                    },
                  ],
                  getId: item => item.id,
                  getLabel: item => item.label,
                  recent: {
                    label: 'Recent',
                    max: 3,
                  },
                  renderOption: (element, item, { highlight, query }) => {
                    if (query && !highlight.some(part => part.match)) {
                      const hint = document.createElement('small')
                      hint.textContent = `Matches “${query}” in ${item.keywords}`
                      element.append(hint)
                    }
                    if (item.shortcut) {
                      const key = document.createElement('kbd')
                      key.textContent = item.shortcut
                      key.setAttribute('aria-hidden', 'true')
                      element.prepend(key)
                    }
                  },
                  renderFooter: element => {
                    element.textContent = '↑ ↓ to move · Enter to run · Esc to close'
                  },
                })
                const off = controller.on('select', ({ suggestion, section }) => {
                  const verb = isAction.has(suggestion.id) ? 'Ran' : 'Opened'
                  output.textContent = `${verb} “${suggestion.label}” from ${section}.`
                  controller.clear()
                })
                return () => {
                  off()
                  controller.destroy()
                }
              }
              setup(document, window.Autocomplete.autocomplete)
            </script>
          </body>
        </html>
        

        Package / ESM

        HTML

        index.html
        <!doctype html>
        <html lang="en">
          <head>
            <meta charset="utf-8" />
            <meta name="viewport" content="width=device-width, initial-scale=1" />
            <title>Build a command palette with actions and pages</title>
            <link rel="stylesheet" href="./style.css" />
          </head>
          <body>
            <main>
              <div data-example="palette">
                <div class="field">
                  <label for="palette-input">Command</label
                  ><input id="palette-input" type="text" placeholder="Try new, invoice or theme" />
                </div>
                <p data-output role="status">Nothing run yet.</p>
              </div>
            </main>
            <script type="module" src="./main.js"></script>
          </body>
        </html>
        

        CSS

        style.css
        [data-example] {
          display: grid;
          gap: 0.75rem;
        }
        /* Forms lay out like the example root: actions never touch the fields. */
        [data-example] form {
          display: grid;
          gap: 0.75rem;
        }
        [data-example] .field {
          position: relative;
        }
        [data-example] label {
          display: block;
          margin-bottom: 0.5rem;
        }
        [data-example] input[type='text'] {
          box-sizing: border-box;
          width: 100%;
          padding: 0.75rem 1rem;
          border: 1px solid var(--color-border, #888);
          border-radius: 0.5rem;
          background: var(--color-bg-soft, #fff);
          color: inherit;
          font: inherit;
        }
        [data-example] button {
          padding: 0.5rem 0.75rem;
          border: 1px solid var(--color-border, #888);
          border-radius: 0.5rem;
          background: var(--color-bg-soft, #fff);
          color: inherit;
          font: inherit;
          cursor: pointer;
        }
        [data-example] button:focus-visible,
        [data-example] input:focus-visible {
          outline: 2px solid currentColor;
          outline-offset: 3px;
        }
        [data-example] p {
          margin: 0;
          overflow-wrap: anywhere;
        }
        [data-example] .actions {
          display: flex;
          flex-wrap: wrap;
          gap: 0.5rem;
        }
        [data-example] [data-pills] {
          display: flex;
          flex-wrap: wrap;
          gap: 0.375rem;
          margin: 0;
          padding: 0;
          list-style: none;
        }
        [data-example] [data-pills]:empty {
          display: none;
        }
        [data-example] .pill {
          display: flex;
          max-width: 100%;
        }
        [data-example] .pill button {
          box-sizing: border-box;
          display: inline-flex;
          align-items: center;
          gap: 0.375rem;
          max-width: 100%;
          height: 2rem;
          padding: 0 0.625rem;
          border: 1px solid var(--color-border, #888);
          border-radius: 1rem;
          background: var(--color-bg, #f4f4f5);
          color: inherit;
          font: inherit;
          font-size: 0.875rem;
          line-height: 1;
          overflow-wrap: anywhere;
          cursor: pointer;
        }
        [data-example] .pill button:hover {
          background: var(--color-bg-soft, #e4e4e7);
        }
        [data-example] .pill button svg {
          width: 0.875rem;
          height: 0.875rem;
          flex: none;
          fill: none;
          stroke: currentColor;
          stroke-width: 2;
          stroke-linecap: round;
          opacity: 0.7;
        }
        [data-example] .pill button:hover svg {
          opacity: 1;
        }
        [data-example] .pill-field {
          display: flex;
          flex-wrap: wrap;
          align-items: center;
          gap: 0.375rem;
          box-sizing: border-box;
          min-height: 3.125rem;
          padding: 0.5rem 0.75rem;
          border: 1px solid var(--color-border, #888);
          border-radius: 0.5rem;
          background: var(--color-bg-soft, #fff);
          cursor: text;
        }
        [data-example] .pill-field:focus-within {
          outline: 2px solid currentColor;
          outline-offset: 2px;
        }
        [data-example] .pill-field input[type='text'] {
          flex: 1 1 8rem;
          width: auto;
          min-width: 0;
          height: 2rem;
          padding: 0;
          border: 0;
          background: transparent;
        }
        [data-example] .pill-field input[type='text']:focus-visible {
          outline: none;
        }
        /* The popup sits after the whole field and overlays what follows it. */
        [data-example='pills'] {
          --autocomplete-max-height: 10rem;
        }
        [data-example='pills'] form {
          display: grid;
          gap: 0.5rem;
        }
        [data-example='pills'] .field [data-autocomplete-popup] {
          position: absolute;
          top: 100%;
        }
        /* One reserved pill row: switching layouts never shifts what follows. */
        [data-example] [data-pills-below] {
          min-height: 2.25rem;
        }
        [data-example] .layout {
          display: flex;
          flex-wrap: wrap;
          gap: 0.25rem;
          margin: 0;
          padding: 0.25rem;
          border: 1px solid var(--color-border, #888);
          border-radius: 0.625rem;
          justify-self: start;
        }
        [data-example] .layout legend {
          position: absolute;
          width: 1px;
          height: 1px;
          overflow: hidden;
          clip-path: inset(50%);
          white-space: nowrap;
        }
        [data-example] .layout label {
          position: relative;
          display: flex;
          align-items: center;
          margin: 0;
          padding: 0.375rem 0.75rem;
          border-radius: 0.375rem;
          font-size: 0.875rem;
          cursor: pointer;
        }
        [data-example] .layout input {
          position: absolute;
          inset: 0;
          width: 100%;
          height: 100%;
          margin: 0;
          opacity: 0;
          pointer-events: none;
        }
        [data-example] .layout label:has(:checked) {
          background: var(--color-bg-soft, #e4e4e7);
          box-shadow: inset 0 0 0 1px var(--color-border, #888);
          font-weight: 600;
        }
        [data-example] .layout label:has(:focus-visible) {
          outline: 2px solid currentColor;
          outline-offset: 2px;
        }
        [data-example] .directory {
          display: grid;
          gap: 0.5rem;
          padding: 0;
          margin: 0;
          list-style: none;
        }
        [data-example] .directory button {
          width: 100%;
          text-align: left;
        }
        [data-example] [aria-disabled='true'] {
          opacity: 0.65;
        }
        [data-example] select {
          padding: 0.75rem 1rem;
          border: 1px solid var(--color-border, #888);
          border-radius: 0.5rem;
          background: var(--color-bg-soft, #fff);
          color: inherit;
          font: inherit;
        }
        [data-example] input[type='text']:disabled {
          opacity: 0.65;
          cursor: not-allowed;
        }
        [data-example] [data-autocomplete-option] small {
          display: block;
          opacity: 0.75;
        }
        [data-example] kbd {
          float: right;
          padding: 0 0.375rem;
          border: 1px solid currentColor;
          border-radius: 0.25rem;
          font:
            0.75rem/1.5 ui-monospace,
            monospace;
          opacity: 0.75;
        }
        

        JavaScript

        main.js
        import { autocomplete } from '@samline/autocomplete'
        import '@samline/autocomplete/style.css'
        const setup = (root, createAutocomplete) => {
          const input = root.querySelector('input')
          const output = root.querySelector('[data-output]')
          const actions = [
            {
              id: 'new-document',
              label: 'New document',
              keywords: 'create add file',
              shortcut: 'N',
            },
            {
              id: 'invite',
              label: 'Invite a teammate',
              keywords: 'share people member',
              shortcut: 'I',
            },
            {
              id: 'theme',
              label: 'Switch theme',
              keywords: 'dark light appearance',
              shortcut: 'T',
            },
          ]
          const pages = [
            {
              id: 'billing',
              label: 'Billing',
              keywords: 'invoice payment plan',
            },
            {
              id: 'reports',
              label: 'Reports',
              keywords: 'analytics charts metrics',
            },
            {
              id: 'settings',
              label: 'Settings',
              keywords: 'preferences account profile',
            },
          ]
          const isAction = new Set(actions.map(item => item.id))
          const normalize = text => text.normalize('NFD').replace(/\p{M}/gu, '').toLowerCase()
          const filter = (item, query) =>
            normalize(`${item.label} ${item.keywords}`).includes(normalize(query))
          const controller = createAutocomplete(input, {
            sections: [
              {
                id: 'actions',
                label: 'Actions',
                source: actions,
                filter,
              },
              {
                id: 'pages',
                label: 'Go to',
                source: pages,
                filter,
              },
            ],
            getId: item => item.id,
            getLabel: item => item.label,
            recent: {
              label: 'Recent',
              max: 3,
            },
            renderOption: (element, item, { highlight, query }) => {
              if (query && !highlight.some(part => part.match)) {
                const hint = document.createElement('small')
                hint.textContent = `Matches “${query}” in ${item.keywords}`
                element.append(hint)
              }
              if (item.shortcut) {
                const key = document.createElement('kbd')
                key.textContent = item.shortcut
                key.setAttribute('aria-hidden', 'true')
                element.prepend(key)
              }
            },
            renderFooter: element => {
              element.textContent = '↑ ↓ to move · Enter to run · Esc to close'
            },
          })
          const off = controller.on('select', ({ suggestion, section }) => {
            const verb = isAction.has(suggestion.id) ? 'Ran' : 'Opened'
            output.textContent = `${verb} “${suggestion.label}” from ${section}.`
            controller.clear()
          })
          return () => {
            off()
            controller.destroy()
          }
        }
        setup(document, autocomplete)
        

        Complete file

        index.html
        <!doctype html>
        <html lang="en">
          <head>
            <meta charset="utf-8" />
            <meta name="viewport" content="width=device-width, initial-scale=1" />
            <title>Build a command palette with actions and pages</title>
            <style>
              [data-example] {
                display: grid;
                gap: 0.75rem;
              }
              /* Forms lay out like the example root: actions never touch the fields. */
              [data-example] form {
                display: grid;
                gap: 0.75rem;
              }
              [data-example] .field {
                position: relative;
              }
              [data-example] label {
                display: block;
                margin-bottom: 0.5rem;
              }
              [data-example] input[type='text'] {
                box-sizing: border-box;
                width: 100%;
                padding: 0.75rem 1rem;
                border: 1px solid var(--color-border, #888);
                border-radius: 0.5rem;
                background: var(--color-bg-soft, #fff);
                color: inherit;
                font: inherit;
              }
              [data-example] button {
                padding: 0.5rem 0.75rem;
                border: 1px solid var(--color-border, #888);
                border-radius: 0.5rem;
                background: var(--color-bg-soft, #fff);
                color: inherit;
                font: inherit;
                cursor: pointer;
              }
              [data-example] button:focus-visible,
              [data-example] input:focus-visible {
                outline: 2px solid currentColor;
                outline-offset: 3px;
              }
              [data-example] p {
                margin: 0;
                overflow-wrap: anywhere;
              }
              [data-example] .actions {
                display: flex;
                flex-wrap: wrap;
                gap: 0.5rem;
              }
              [data-example] [data-pills] {
                display: flex;
                flex-wrap: wrap;
                gap: 0.375rem;
                margin: 0;
                padding: 0;
                list-style: none;
              }
              [data-example] [data-pills]:empty {
                display: none;
              }
              [data-example] .pill {
                display: flex;
                max-width: 100%;
              }
              [data-example] .pill button {
                box-sizing: border-box;
                display: inline-flex;
                align-items: center;
                gap: 0.375rem;
                max-width: 100%;
                height: 2rem;
                padding: 0 0.625rem;
                border: 1px solid var(--color-border, #888);
                border-radius: 1rem;
                background: var(--color-bg, #f4f4f5);
                color: inherit;
                font: inherit;
                font-size: 0.875rem;
                line-height: 1;
                overflow-wrap: anywhere;
                cursor: pointer;
              }
              [data-example] .pill button:hover {
                background: var(--color-bg-soft, #e4e4e7);
              }
              [data-example] .pill button svg {
                width: 0.875rem;
                height: 0.875rem;
                flex: none;
                fill: none;
                stroke: currentColor;
                stroke-width: 2;
                stroke-linecap: round;
                opacity: 0.7;
              }
              [data-example] .pill button:hover svg {
                opacity: 1;
              }
              [data-example] .pill-field {
                display: flex;
                flex-wrap: wrap;
                align-items: center;
                gap: 0.375rem;
                box-sizing: border-box;
                min-height: 3.125rem;
                padding: 0.5rem 0.75rem;
                border: 1px solid var(--color-border, #888);
                border-radius: 0.5rem;
                background: var(--color-bg-soft, #fff);
                cursor: text;
              }
              [data-example] .pill-field:focus-within {
                outline: 2px solid currentColor;
                outline-offset: 2px;
              }
              [data-example] .pill-field input[type='text'] {
                flex: 1 1 8rem;
                width: auto;
                min-width: 0;
                height: 2rem;
                padding: 0;
                border: 0;
                background: transparent;
              }
              [data-example] .pill-field input[type='text']:focus-visible {
                outline: none;
              }
              /* The popup sits after the whole field and overlays what follows it. */
              [data-example='pills'] {
                --autocomplete-max-height: 10rem;
              }
              [data-example='pills'] form {
                display: grid;
                gap: 0.5rem;
              }
              [data-example='pills'] .field [data-autocomplete-popup] {
                position: absolute;
                top: 100%;
              }
              /* One reserved pill row: switching layouts never shifts what follows. */
              [data-example] [data-pills-below] {
                min-height: 2.25rem;
              }
              [data-example] .layout {
                display: flex;
                flex-wrap: wrap;
                gap: 0.25rem;
                margin: 0;
                padding: 0.25rem;
                border: 1px solid var(--color-border, #888);
                border-radius: 0.625rem;
                justify-self: start;
              }
              [data-example] .layout legend {
                position: absolute;
                width: 1px;
                height: 1px;
                overflow: hidden;
                clip-path: inset(50%);
                white-space: nowrap;
              }
              [data-example] .layout label {
                position: relative;
                display: flex;
                align-items: center;
                margin: 0;
                padding: 0.375rem 0.75rem;
                border-radius: 0.375rem;
                font-size: 0.875rem;
                cursor: pointer;
              }
              [data-example] .layout input {
                position: absolute;
                inset: 0;
                width: 100%;
                height: 100%;
                margin: 0;
                opacity: 0;
                pointer-events: none;
              }
              [data-example] .layout label:has(:checked) {
                background: var(--color-bg-soft, #e4e4e7);
                box-shadow: inset 0 0 0 1px var(--color-border, #888);
                font-weight: 600;
              }
              [data-example] .layout label:has(:focus-visible) {
                outline: 2px solid currentColor;
                outline-offset: 2px;
              }
              [data-example] .directory {
                display: grid;
                gap: 0.5rem;
                padding: 0;
                margin: 0;
                list-style: none;
              }
              [data-example] .directory button {
                width: 100%;
                text-align: left;
              }
              [data-example] [aria-disabled='true'] {
                opacity: 0.65;
              }
              [data-example] select {
                padding: 0.75rem 1rem;
                border: 1px solid var(--color-border, #888);
                border-radius: 0.5rem;
                background: var(--color-bg-soft, #fff);
                color: inherit;
                font: inherit;
              }
              [data-example] input[type='text']:disabled {
                opacity: 0.65;
                cursor: not-allowed;
              }
              [data-example] [data-autocomplete-option] small {
                display: block;
                opacity: 0.75;
              }
              [data-example] kbd {
                float: right;
                padding: 0 0.375rem;
                border: 1px solid currentColor;
                border-radius: 0.25rem;
                font:
                  0.75rem/1.5 ui-monospace,
                  monospace;
                opacity: 0.75;
              }
            </style>
          </head>
          <body>
            <main>
              <div data-example="palette">
                <div class="field">
                  <label for="palette-input">Command</label
                  ><input id="palette-input" type="text" placeholder="Try new, invoice or theme" />
                </div>
                <p data-output role="status">Nothing run yet.</p>
              </div>
            </main>
            <script type="module">
              import { autocomplete } from '@samline/autocomplete'
              import '@samline/autocomplete/style.css'
              const setup = (root, createAutocomplete) => {
                const input = root.querySelector('input')
                const output = root.querySelector('[data-output]')
                const actions = [
                  {
                    id: 'new-document',
                    label: 'New document',
                    keywords: 'create add file',
                    shortcut: 'N',
                  },
                  {
                    id: 'invite',
                    label: 'Invite a teammate',
                    keywords: 'share people member',
                    shortcut: 'I',
                  },
                  {
                    id: 'theme',
                    label: 'Switch theme',
                    keywords: 'dark light appearance',
                    shortcut: 'T',
                  },
                ]
                const pages = [
                  {
                    id: 'billing',
                    label: 'Billing',
                    keywords: 'invoice payment plan',
                  },
                  {
                    id: 'reports',
                    label: 'Reports',
                    keywords: 'analytics charts metrics',
                  },
                  {
                    id: 'settings',
                    label: 'Settings',
                    keywords: 'preferences account profile',
                  },
                ]
                const isAction = new Set(actions.map(item => item.id))
                const normalize = text => text.normalize('NFD').replace(/\p{M}/gu, '').toLowerCase()
                const filter = (item, query) =>
                  normalize(`${item.label} ${item.keywords}`).includes(normalize(query))
                const controller = createAutocomplete(input, {
                  sections: [
                    {
                      id: 'actions',
                      label: 'Actions',
                      source: actions,
                      filter,
                    },
                    {
                      id: 'pages',
                      label: 'Go to',
                      source: pages,
                      filter,
                    },
                  ],
                  getId: item => item.id,
                  getLabel: item => item.label,
                  recent: {
                    label: 'Recent',
                    max: 3,
                  },
                  renderOption: (element, item, { highlight, query }) => {
                    if (query && !highlight.some(part => part.match)) {
                      const hint = document.createElement('small')
                      hint.textContent = `Matches “${query}” in ${item.keywords}`
                      element.append(hint)
                    }
                    if (item.shortcut) {
                      const key = document.createElement('kbd')
                      key.textContent = item.shortcut
                      key.setAttribute('aria-hidden', 'true')
                      element.prepend(key)
                    }
                  },
                  renderFooter: element => {
                    element.textContent = '↑ ↓ to move · Enter to run · Esc to close'
                  },
                })
                const off = controller.on('select', ({ suggestion, section }) => {
                  const verb = isAction.has(suggestion.id) ? 'Ran' : 'Opened'
                  output.textContent = `${verb} “${suggestion.label}” from ${section}.`
                  controller.clear()
                })
                return () => {
                  off()
                  controller.destroy()
                }
              }
              setup(document, autocomplete)
            </script>
          </body>
        </html>
        

        Narrow one field by another

        Dependent fieldsLive preview

        The country select drives the city search through a function endpoint, so each request reads the current country. Because results are cached per query, changing the country calls clearCache and clear. minLength: 0 lists every city of the country on focus, and the form submits both values.

        Choose a country first.

        Explore the code

        HTML / CDN

        HTML

        index.html
        <!doctype html>
        <html lang="en">
          <head>
            <meta charset="utf-8" />
            <meta name="viewport" content="width=device-width, initial-scale=1" />
            <title>Narrow one field by another</title>
            <link
              rel="stylesheet"
              href="https://cdn.jsdelivr.net/npm/@samline/autocomplete@3.0.0/dist/style.css"
            />
            <link rel="stylesheet" href="./style.css" />
          </head>
          <body>
            <main>
              <div
                data-example="dependent"
                data-endpoint="https://samline.github.io/autocomplete/cities.json"
              >
                <form>
                  <div class="field">
                    <label for="dependent-country">Country</label
                    ><select id="dependent-country" name="country">
                      <option value="">Choose a country</option>
                      <option>Colombia</option>
                      <option>Mexico</option>
                      <option>Spain</option>
                    </select>
                  </div>
                  <div class="field">
                    <label for="dependent-input">City</label
                    ><input id="dependent-input" type="text" disabled />
                  </div>
                  <div class="actions"><button type="submit">Submit</button></div>
                </form>
                <p data-note role="status">Choose a country first.</p>
              </div>
            </main>
            <script src="https://cdn.jsdelivr.net/npm/@samline/autocomplete@3.0.0/dist/browser/autocomplete.global.js"></script>
            <script src="./main.js" defer></script>
          </body>
        </html>
        

        CSS

        style.css
        [data-example] {
          display: grid;
          gap: 0.75rem;
        }
        /* Forms lay out like the example root: actions never touch the fields. */
        [data-example] form {
          display: grid;
          gap: 0.75rem;
        }
        [data-example] .field {
          position: relative;
        }
        [data-example] label {
          display: block;
          margin-bottom: 0.5rem;
        }
        [data-example] input[type='text'] {
          box-sizing: border-box;
          width: 100%;
          padding: 0.75rem 1rem;
          border: 1px solid var(--color-border, #888);
          border-radius: 0.5rem;
          background: var(--color-bg-soft, #fff);
          color: inherit;
          font: inherit;
        }
        [data-example] button {
          padding: 0.5rem 0.75rem;
          border: 1px solid var(--color-border, #888);
          border-radius: 0.5rem;
          background: var(--color-bg-soft, #fff);
          color: inherit;
          font: inherit;
          cursor: pointer;
        }
        [data-example] button:focus-visible,
        [data-example] input:focus-visible {
          outline: 2px solid currentColor;
          outline-offset: 3px;
        }
        [data-example] p {
          margin: 0;
          overflow-wrap: anywhere;
        }
        [data-example] .actions {
          display: flex;
          flex-wrap: wrap;
          gap: 0.5rem;
        }
        [data-example] [data-pills] {
          display: flex;
          flex-wrap: wrap;
          gap: 0.375rem;
          margin: 0;
          padding: 0;
          list-style: none;
        }
        [data-example] [data-pills]:empty {
          display: none;
        }
        [data-example] .pill {
          display: flex;
          max-width: 100%;
        }
        [data-example] .pill button {
          box-sizing: border-box;
          display: inline-flex;
          align-items: center;
          gap: 0.375rem;
          max-width: 100%;
          height: 2rem;
          padding: 0 0.625rem;
          border: 1px solid var(--color-border, #888);
          border-radius: 1rem;
          background: var(--color-bg, #f4f4f5);
          color: inherit;
          font: inherit;
          font-size: 0.875rem;
          line-height: 1;
          overflow-wrap: anywhere;
          cursor: pointer;
        }
        [data-example] .pill button:hover {
          background: var(--color-bg-soft, #e4e4e7);
        }
        [data-example] .pill button svg {
          width: 0.875rem;
          height: 0.875rem;
          flex: none;
          fill: none;
          stroke: currentColor;
          stroke-width: 2;
          stroke-linecap: round;
          opacity: 0.7;
        }
        [data-example] .pill button:hover svg {
          opacity: 1;
        }
        [data-example] .pill-field {
          display: flex;
          flex-wrap: wrap;
          align-items: center;
          gap: 0.375rem;
          box-sizing: border-box;
          min-height: 3.125rem;
          padding: 0.5rem 0.75rem;
          border: 1px solid var(--color-border, #888);
          border-radius: 0.5rem;
          background: var(--color-bg-soft, #fff);
          cursor: text;
        }
        [data-example] .pill-field:focus-within {
          outline: 2px solid currentColor;
          outline-offset: 2px;
        }
        [data-example] .pill-field input[type='text'] {
          flex: 1 1 8rem;
          width: auto;
          min-width: 0;
          height: 2rem;
          padding: 0;
          border: 0;
          background: transparent;
        }
        [data-example] .pill-field input[type='text']:focus-visible {
          outline: none;
        }
        /* The popup sits after the whole field and overlays what follows it. */
        [data-example='pills'] {
          --autocomplete-max-height: 10rem;
        }
        [data-example='pills'] form {
          display: grid;
          gap: 0.5rem;
        }
        [data-example='pills'] .field [data-autocomplete-popup] {
          position: absolute;
          top: 100%;
        }
        /* One reserved pill row: switching layouts never shifts what follows. */
        [data-example] [data-pills-below] {
          min-height: 2.25rem;
        }
        [data-example] .layout {
          display: flex;
          flex-wrap: wrap;
          gap: 0.25rem;
          margin: 0;
          padding: 0.25rem;
          border: 1px solid var(--color-border, #888);
          border-radius: 0.625rem;
          justify-self: start;
        }
        [data-example] .layout legend {
          position: absolute;
          width: 1px;
          height: 1px;
          overflow: hidden;
          clip-path: inset(50%);
          white-space: nowrap;
        }
        [data-example] .layout label {
          position: relative;
          display: flex;
          align-items: center;
          margin: 0;
          padding: 0.375rem 0.75rem;
          border-radius: 0.375rem;
          font-size: 0.875rem;
          cursor: pointer;
        }
        [data-example] .layout input {
          position: absolute;
          inset: 0;
          width: 100%;
          height: 100%;
          margin: 0;
          opacity: 0;
          pointer-events: none;
        }
        [data-example] .layout label:has(:checked) {
          background: var(--color-bg-soft, #e4e4e7);
          box-shadow: inset 0 0 0 1px var(--color-border, #888);
          font-weight: 600;
        }
        [data-example] .layout label:has(:focus-visible) {
          outline: 2px solid currentColor;
          outline-offset: 2px;
        }
        [data-example] .directory {
          display: grid;
          gap: 0.5rem;
          padding: 0;
          margin: 0;
          list-style: none;
        }
        [data-example] .directory button {
          width: 100%;
          text-align: left;
        }
        [data-example] [aria-disabled='true'] {
          opacity: 0.65;
        }
        [data-example] select {
          padding: 0.75rem 1rem;
          border: 1px solid var(--color-border, #888);
          border-radius: 0.5rem;
          background: var(--color-bg-soft, #fff);
          color: inherit;
          font: inherit;
        }
        [data-example] input[type='text']:disabled {
          opacity: 0.65;
          cursor: not-allowed;
        }
        [data-example] [data-autocomplete-option] small {
          display: block;
          opacity: 0.75;
        }
        [data-example] kbd {
          float: right;
          padding: 0 0.375rem;
          border: 1px solid currentColor;
          border-radius: 0.25rem;
          font:
            0.75rem/1.5 ui-monospace,
            monospace;
          opacity: 0.75;
        }
        

        JavaScript

        main.js
        const setup = (root, createAutocomplete) => {
          const form = root.querySelector('form')
          const country = root.querySelector('select')
          const input = root.querySelector('input[type="text"]')
          const note = root.querySelector('[data-note]')
          const { endpoint } = root.querySelector('[data-endpoint]').dataset
          const events = new AbortController()
          const controller = createAutocomplete(input, {
            endpoint: () => `${endpoint}?country=${encodeURIComponent(country.value)}`,
            mapResponse: (payload, _response, query) =>
              payload.results.filter(
                city =>
                  city.country === country.value && city.name.toLowerCase().includes(query.toLowerCase())
              ),
            minLength: 0,
            getId: city => city.key,
            getLabel: city => city.name,
            hiddenInput: 'city_id',
            messages: { empty: ({ query }) => `No city in ${country.value} matches “${query}”.` },
          })
          country.addEventListener(
            'change',
            () => {
              controller.clearCache()
              controller.clear()
              input.disabled = !country.value
              note.textContent = country.value
                ? `Cities in ${country.value}. Focus the field to list them all.`
                : 'Choose a country first.'
              if (country.value) input.focus()
            },
            { signal: events.signal }
          )
          form.addEventListener(
            'submit',
            event => {
              event.preventDefault()
              const data = new FormData(form)
              note.textContent = data.get('city_id')
                ? `Submitted country=${data.get('country')}, city_id=${data.get('city_id')}.`
                : 'Pick a city first.'
            },
            { signal: events.signal }
          )
          return () => {
            events.abort()
            controller.destroy()
          }
        }
        setup(document, window.Autocomplete.autocomplete)
        

        Complete file

        index.html
        <!doctype html>
        <html lang="en">
          <head>
            <meta charset="utf-8" />
            <meta name="viewport" content="width=device-width, initial-scale=1" />
            <title>Narrow one field by another</title>
            <link
              rel="stylesheet"
              href="https://cdn.jsdelivr.net/npm/@samline/autocomplete@3.0.0/dist/style.css"
            />
            <style>
              [data-example] {
                display: grid;
                gap: 0.75rem;
              }
              /* Forms lay out like the example root: actions never touch the fields. */
              [data-example] form {
                display: grid;
                gap: 0.75rem;
              }
              [data-example] .field {
                position: relative;
              }
              [data-example] label {
                display: block;
                margin-bottom: 0.5rem;
              }
              [data-example] input[type='text'] {
                box-sizing: border-box;
                width: 100%;
                padding: 0.75rem 1rem;
                border: 1px solid var(--color-border, #888);
                border-radius: 0.5rem;
                background: var(--color-bg-soft, #fff);
                color: inherit;
                font: inherit;
              }
              [data-example] button {
                padding: 0.5rem 0.75rem;
                border: 1px solid var(--color-border, #888);
                border-radius: 0.5rem;
                background: var(--color-bg-soft, #fff);
                color: inherit;
                font: inherit;
                cursor: pointer;
              }
              [data-example] button:focus-visible,
              [data-example] input:focus-visible {
                outline: 2px solid currentColor;
                outline-offset: 3px;
              }
              [data-example] p {
                margin: 0;
                overflow-wrap: anywhere;
              }
              [data-example] .actions {
                display: flex;
                flex-wrap: wrap;
                gap: 0.5rem;
              }
              [data-example] [data-pills] {
                display: flex;
                flex-wrap: wrap;
                gap: 0.375rem;
                margin: 0;
                padding: 0;
                list-style: none;
              }
              [data-example] [data-pills]:empty {
                display: none;
              }
              [data-example] .pill {
                display: flex;
                max-width: 100%;
              }
              [data-example] .pill button {
                box-sizing: border-box;
                display: inline-flex;
                align-items: center;
                gap: 0.375rem;
                max-width: 100%;
                height: 2rem;
                padding: 0 0.625rem;
                border: 1px solid var(--color-border, #888);
                border-radius: 1rem;
                background: var(--color-bg, #f4f4f5);
                color: inherit;
                font: inherit;
                font-size: 0.875rem;
                line-height: 1;
                overflow-wrap: anywhere;
                cursor: pointer;
              }
              [data-example] .pill button:hover {
                background: var(--color-bg-soft, #e4e4e7);
              }
              [data-example] .pill button svg {
                width: 0.875rem;
                height: 0.875rem;
                flex: none;
                fill: none;
                stroke: currentColor;
                stroke-width: 2;
                stroke-linecap: round;
                opacity: 0.7;
              }
              [data-example] .pill button:hover svg {
                opacity: 1;
              }
              [data-example] .pill-field {
                display: flex;
                flex-wrap: wrap;
                align-items: center;
                gap: 0.375rem;
                box-sizing: border-box;
                min-height: 3.125rem;
                padding: 0.5rem 0.75rem;
                border: 1px solid var(--color-border, #888);
                border-radius: 0.5rem;
                background: var(--color-bg-soft, #fff);
                cursor: text;
              }
              [data-example] .pill-field:focus-within {
                outline: 2px solid currentColor;
                outline-offset: 2px;
              }
              [data-example] .pill-field input[type='text'] {
                flex: 1 1 8rem;
                width: auto;
                min-width: 0;
                height: 2rem;
                padding: 0;
                border: 0;
                background: transparent;
              }
              [data-example] .pill-field input[type='text']:focus-visible {
                outline: none;
              }
              /* The popup sits after the whole field and overlays what follows it. */
              [data-example='pills'] {
                --autocomplete-max-height: 10rem;
              }
              [data-example='pills'] form {
                display: grid;
                gap: 0.5rem;
              }
              [data-example='pills'] .field [data-autocomplete-popup] {
                position: absolute;
                top: 100%;
              }
              /* One reserved pill row: switching layouts never shifts what follows. */
              [data-example] [data-pills-below] {
                min-height: 2.25rem;
              }
              [data-example] .layout {
                display: flex;
                flex-wrap: wrap;
                gap: 0.25rem;
                margin: 0;
                padding: 0.25rem;
                border: 1px solid var(--color-border, #888);
                border-radius: 0.625rem;
                justify-self: start;
              }
              [data-example] .layout legend {
                position: absolute;
                width: 1px;
                height: 1px;
                overflow: hidden;
                clip-path: inset(50%);
                white-space: nowrap;
              }
              [data-example] .layout label {
                position: relative;
                display: flex;
                align-items: center;
                margin: 0;
                padding: 0.375rem 0.75rem;
                border-radius: 0.375rem;
                font-size: 0.875rem;
                cursor: pointer;
              }
              [data-example] .layout input {
                position: absolute;
                inset: 0;
                width: 100%;
                height: 100%;
                margin: 0;
                opacity: 0;
                pointer-events: none;
              }
              [data-example] .layout label:has(:checked) {
                background: var(--color-bg-soft, #e4e4e7);
                box-shadow: inset 0 0 0 1px var(--color-border, #888);
                font-weight: 600;
              }
              [data-example] .layout label:has(:focus-visible) {
                outline: 2px solid currentColor;
                outline-offset: 2px;
              }
              [data-example] .directory {
                display: grid;
                gap: 0.5rem;
                padding: 0;
                margin: 0;
                list-style: none;
              }
              [data-example] .directory button {
                width: 100%;
                text-align: left;
              }
              [data-example] [aria-disabled='true'] {
                opacity: 0.65;
              }
              [data-example] select {
                padding: 0.75rem 1rem;
                border: 1px solid var(--color-border, #888);
                border-radius: 0.5rem;
                background: var(--color-bg-soft, #fff);
                color: inherit;
                font: inherit;
              }
              [data-example] input[type='text']:disabled {
                opacity: 0.65;
                cursor: not-allowed;
              }
              [data-example] [data-autocomplete-option] small {
                display: block;
                opacity: 0.75;
              }
              [data-example] kbd {
                float: right;
                padding: 0 0.375rem;
                border: 1px solid currentColor;
                border-radius: 0.25rem;
                font:
                  0.75rem/1.5 ui-monospace,
                  monospace;
                opacity: 0.75;
              }
            </style>
          </head>
          <body>
            <main>
              <div
                data-example="dependent"
                data-endpoint="https://samline.github.io/autocomplete/cities.json"
              >
                <form>
                  <div class="field">
                    <label for="dependent-country">Country</label
                    ><select id="dependent-country" name="country">
                      <option value="">Choose a country</option>
                      <option>Colombia</option>
                      <option>Mexico</option>
                      <option>Spain</option>
                    </select>
                  </div>
                  <div class="field">
                    <label for="dependent-input">City</label
                    ><input id="dependent-input" type="text" disabled />
                  </div>
                  <div class="actions"><button type="submit">Submit</button></div>
                </form>
                <p data-note role="status">Choose a country first.</p>
              </div>
            </main>
            <script src="https://cdn.jsdelivr.net/npm/@samline/autocomplete@3.0.0/dist/browser/autocomplete.global.js"></script>
            <script>
              const setup = (root, createAutocomplete) => {
                const form = root.querySelector('form')
                const country = root.querySelector('select')
                const input = root.querySelector('input[type="text"]')
                const note = root.querySelector('[data-note]')
                const { endpoint } = root.querySelector('[data-endpoint]').dataset
                const events = new AbortController()
                const controller = createAutocomplete(input, {
                  endpoint: () => `${endpoint}?country=${encodeURIComponent(country.value)}`,
                  mapResponse: (payload, _response, query) =>
                    payload.results.filter(
                      city =>
                        city.country === country.value &&
                        city.name.toLowerCase().includes(query.toLowerCase())
                    ),
                  minLength: 0,
                  getId: city => city.key,
                  getLabel: city => city.name,
                  hiddenInput: 'city_id',
                  messages: { empty: ({ query }) => `No city in ${country.value} matches “${query}”.` },
                })
                country.addEventListener(
                  'change',
                  () => {
                    controller.clearCache()
                    controller.clear()
                    input.disabled = !country.value
                    note.textContent = country.value
                      ? `Cities in ${country.value}. Focus the field to list them all.`
                      : 'Choose a country first.'
                    if (country.value) input.focus()
                  },
                  { signal: events.signal }
                )
                form.addEventListener(
                  'submit',
                  event => {
                    event.preventDefault()
                    const data = new FormData(form)
                    note.textContent = data.get('city_id')
                      ? `Submitted country=${data.get('country')}, city_id=${data.get('city_id')}.`
                      : 'Pick a city first.'
                  },
                  { signal: events.signal }
                )
                return () => {
                  events.abort()
                  controller.destroy()
                }
              }
              setup(document, window.Autocomplete.autocomplete)
            </script>
          </body>
        </html>
        

        Package / ESM

        HTML

        index.html
        <!doctype html>
        <html lang="en">
          <head>
            <meta charset="utf-8" />
            <meta name="viewport" content="width=device-width, initial-scale=1" />
            <title>Narrow one field by another</title>
            <link rel="stylesheet" href="./style.css" />
          </head>
          <body>
            <main>
              <div
                data-example="dependent"
                data-endpoint="https://samline.github.io/autocomplete/cities.json"
              >
                <form>
                  <div class="field">
                    <label for="dependent-country">Country</label
                    ><select id="dependent-country" name="country">
                      <option value="">Choose a country</option>
                      <option>Colombia</option>
                      <option>Mexico</option>
                      <option>Spain</option>
                    </select>
                  </div>
                  <div class="field">
                    <label for="dependent-input">City</label
                    ><input id="dependent-input" type="text" disabled />
                  </div>
                  <div class="actions"><button type="submit">Submit</button></div>
                </form>
                <p data-note role="status">Choose a country first.</p>
              </div>
            </main>
            <script type="module" src="./main.js"></script>
          </body>
        </html>
        

        CSS

        style.css
        [data-example] {
          display: grid;
          gap: 0.75rem;
        }
        /* Forms lay out like the example root: actions never touch the fields. */
        [data-example] form {
          display: grid;
          gap: 0.75rem;
        }
        [data-example] .field {
          position: relative;
        }
        [data-example] label {
          display: block;
          margin-bottom: 0.5rem;
        }
        [data-example] input[type='text'] {
          box-sizing: border-box;
          width: 100%;
          padding: 0.75rem 1rem;
          border: 1px solid var(--color-border, #888);
          border-radius: 0.5rem;
          background: var(--color-bg-soft, #fff);
          color: inherit;
          font: inherit;
        }
        [data-example] button {
          padding: 0.5rem 0.75rem;
          border: 1px solid var(--color-border, #888);
          border-radius: 0.5rem;
          background: var(--color-bg-soft, #fff);
          color: inherit;
          font: inherit;
          cursor: pointer;
        }
        [data-example] button:focus-visible,
        [data-example] input:focus-visible {
          outline: 2px solid currentColor;
          outline-offset: 3px;
        }
        [data-example] p {
          margin: 0;
          overflow-wrap: anywhere;
        }
        [data-example] .actions {
          display: flex;
          flex-wrap: wrap;
          gap: 0.5rem;
        }
        [data-example] [data-pills] {
          display: flex;
          flex-wrap: wrap;
          gap: 0.375rem;
          margin: 0;
          padding: 0;
          list-style: none;
        }
        [data-example] [data-pills]:empty {
          display: none;
        }
        [data-example] .pill {
          display: flex;
          max-width: 100%;
        }
        [data-example] .pill button {
          box-sizing: border-box;
          display: inline-flex;
          align-items: center;
          gap: 0.375rem;
          max-width: 100%;
          height: 2rem;
          padding: 0 0.625rem;
          border: 1px solid var(--color-border, #888);
          border-radius: 1rem;
          background: var(--color-bg, #f4f4f5);
          color: inherit;
          font: inherit;
          font-size: 0.875rem;
          line-height: 1;
          overflow-wrap: anywhere;
          cursor: pointer;
        }
        [data-example] .pill button:hover {
          background: var(--color-bg-soft, #e4e4e7);
        }
        [data-example] .pill button svg {
          width: 0.875rem;
          height: 0.875rem;
          flex: none;
          fill: none;
          stroke: currentColor;
          stroke-width: 2;
          stroke-linecap: round;
          opacity: 0.7;
        }
        [data-example] .pill button:hover svg {
          opacity: 1;
        }
        [data-example] .pill-field {
          display: flex;
          flex-wrap: wrap;
          align-items: center;
          gap: 0.375rem;
          box-sizing: border-box;
          min-height: 3.125rem;
          padding: 0.5rem 0.75rem;
          border: 1px solid var(--color-border, #888);
          border-radius: 0.5rem;
          background: var(--color-bg-soft, #fff);
          cursor: text;
        }
        [data-example] .pill-field:focus-within {
          outline: 2px solid currentColor;
          outline-offset: 2px;
        }
        [data-example] .pill-field input[type='text'] {
          flex: 1 1 8rem;
          width: auto;
          min-width: 0;
          height: 2rem;
          padding: 0;
          border: 0;
          background: transparent;
        }
        [data-example] .pill-field input[type='text']:focus-visible {
          outline: none;
        }
        /* The popup sits after the whole field and overlays what follows it. */
        [data-example='pills'] {
          --autocomplete-max-height: 10rem;
        }
        [data-example='pills'] form {
          display: grid;
          gap: 0.5rem;
        }
        [data-example='pills'] .field [data-autocomplete-popup] {
          position: absolute;
          top: 100%;
        }
        /* One reserved pill row: switching layouts never shifts what follows. */
        [data-example] [data-pills-below] {
          min-height: 2.25rem;
        }
        [data-example] .layout {
          display: flex;
          flex-wrap: wrap;
          gap: 0.25rem;
          margin: 0;
          padding: 0.25rem;
          border: 1px solid var(--color-border, #888);
          border-radius: 0.625rem;
          justify-self: start;
        }
        [data-example] .layout legend {
          position: absolute;
          width: 1px;
          height: 1px;
          overflow: hidden;
          clip-path: inset(50%);
          white-space: nowrap;
        }
        [data-example] .layout label {
          position: relative;
          display: flex;
          align-items: center;
          margin: 0;
          padding: 0.375rem 0.75rem;
          border-radius: 0.375rem;
          font-size: 0.875rem;
          cursor: pointer;
        }
        [data-example] .layout input {
          position: absolute;
          inset: 0;
          width: 100%;
          height: 100%;
          margin: 0;
          opacity: 0;
          pointer-events: none;
        }
        [data-example] .layout label:has(:checked) {
          background: var(--color-bg-soft, #e4e4e7);
          box-shadow: inset 0 0 0 1px var(--color-border, #888);
          font-weight: 600;
        }
        [data-example] .layout label:has(:focus-visible) {
          outline: 2px solid currentColor;
          outline-offset: 2px;
        }
        [data-example] .directory {
          display: grid;
          gap: 0.5rem;
          padding: 0;
          margin: 0;
          list-style: none;
        }
        [data-example] .directory button {
          width: 100%;
          text-align: left;
        }
        [data-example] [aria-disabled='true'] {
          opacity: 0.65;
        }
        [data-example] select {
          padding: 0.75rem 1rem;
          border: 1px solid var(--color-border, #888);
          border-radius: 0.5rem;
          background: var(--color-bg-soft, #fff);
          color: inherit;
          font: inherit;
        }
        [data-example] input[type='text']:disabled {
          opacity: 0.65;
          cursor: not-allowed;
        }
        [data-example] [data-autocomplete-option] small {
          display: block;
          opacity: 0.75;
        }
        [data-example] kbd {
          float: right;
          padding: 0 0.375rem;
          border: 1px solid currentColor;
          border-radius: 0.25rem;
          font:
            0.75rem/1.5 ui-monospace,
            monospace;
          opacity: 0.75;
        }
        

        JavaScript

        main.js
        import { autocomplete } from '@samline/autocomplete'
        import '@samline/autocomplete/style.css'
        const setup = (root, createAutocomplete) => {
          const form = root.querySelector('form')
          const country = root.querySelector('select')
          const input = root.querySelector('input[type="text"]')
          const note = root.querySelector('[data-note]')
          const { endpoint } = root.querySelector('[data-endpoint]').dataset
          const events = new AbortController()
          const controller = createAutocomplete(input, {
            endpoint: () => `${endpoint}?country=${encodeURIComponent(country.value)}`,
            mapResponse: (payload, _response, query) =>
              payload.results.filter(
                city =>
                  city.country === country.value && city.name.toLowerCase().includes(query.toLowerCase())
              ),
            minLength: 0,
            getId: city => city.key,
            getLabel: city => city.name,
            hiddenInput: 'city_id',
            messages: { empty: ({ query }) => `No city in ${country.value} matches “${query}”.` },
          })
          country.addEventListener(
            'change',
            () => {
              controller.clearCache()
              controller.clear()
              input.disabled = !country.value
              note.textContent = country.value
                ? `Cities in ${country.value}. Focus the field to list them all.`
                : 'Choose a country first.'
              if (country.value) input.focus()
            },
            { signal: events.signal }
          )
          form.addEventListener(
            'submit',
            event => {
              event.preventDefault()
              const data = new FormData(form)
              note.textContent = data.get('city_id')
                ? `Submitted country=${data.get('country')}, city_id=${data.get('city_id')}.`
                : 'Pick a city first.'
            },
            { signal: events.signal }
          )
          return () => {
            events.abort()
            controller.destroy()
          }
        }
        setup(document, autocomplete)
        

        Complete file

        index.html
        <!doctype html>
        <html lang="en">
          <head>
            <meta charset="utf-8" />
            <meta name="viewport" content="width=device-width, initial-scale=1" />
            <title>Narrow one field by another</title>
            <style>
              [data-example] {
                display: grid;
                gap: 0.75rem;
              }
              /* Forms lay out like the example root: actions never touch the fields. */
              [data-example] form {
                display: grid;
                gap: 0.75rem;
              }
              [data-example] .field {
                position: relative;
              }
              [data-example] label {
                display: block;
                margin-bottom: 0.5rem;
              }
              [data-example] input[type='text'] {
                box-sizing: border-box;
                width: 100%;
                padding: 0.75rem 1rem;
                border: 1px solid var(--color-border, #888);
                border-radius: 0.5rem;
                background: var(--color-bg-soft, #fff);
                color: inherit;
                font: inherit;
              }
              [data-example] button {
                padding: 0.5rem 0.75rem;
                border: 1px solid var(--color-border, #888);
                border-radius: 0.5rem;
                background: var(--color-bg-soft, #fff);
                color: inherit;
                font: inherit;
                cursor: pointer;
              }
              [data-example] button:focus-visible,
              [data-example] input:focus-visible {
                outline: 2px solid currentColor;
                outline-offset: 3px;
              }
              [data-example] p {
                margin: 0;
                overflow-wrap: anywhere;
              }
              [data-example] .actions {
                display: flex;
                flex-wrap: wrap;
                gap: 0.5rem;
              }
              [data-example] [data-pills] {
                display: flex;
                flex-wrap: wrap;
                gap: 0.375rem;
                margin: 0;
                padding: 0;
                list-style: none;
              }
              [data-example] [data-pills]:empty {
                display: none;
              }
              [data-example] .pill {
                display: flex;
                max-width: 100%;
              }
              [data-example] .pill button {
                box-sizing: border-box;
                display: inline-flex;
                align-items: center;
                gap: 0.375rem;
                max-width: 100%;
                height: 2rem;
                padding: 0 0.625rem;
                border: 1px solid var(--color-border, #888);
                border-radius: 1rem;
                background: var(--color-bg, #f4f4f5);
                color: inherit;
                font: inherit;
                font-size: 0.875rem;
                line-height: 1;
                overflow-wrap: anywhere;
                cursor: pointer;
              }
              [data-example] .pill button:hover {
                background: var(--color-bg-soft, #e4e4e7);
              }
              [data-example] .pill button svg {
                width: 0.875rem;
                height: 0.875rem;
                flex: none;
                fill: none;
                stroke: currentColor;
                stroke-width: 2;
                stroke-linecap: round;
                opacity: 0.7;
              }
              [data-example] .pill button:hover svg {
                opacity: 1;
              }
              [data-example] .pill-field {
                display: flex;
                flex-wrap: wrap;
                align-items: center;
                gap: 0.375rem;
                box-sizing: border-box;
                min-height: 3.125rem;
                padding: 0.5rem 0.75rem;
                border: 1px solid var(--color-border, #888);
                border-radius: 0.5rem;
                background: var(--color-bg-soft, #fff);
                cursor: text;
              }
              [data-example] .pill-field:focus-within {
                outline: 2px solid currentColor;
                outline-offset: 2px;
              }
              [data-example] .pill-field input[type='text'] {
                flex: 1 1 8rem;
                width: auto;
                min-width: 0;
                height: 2rem;
                padding: 0;
                border: 0;
                background: transparent;
              }
              [data-example] .pill-field input[type='text']:focus-visible {
                outline: none;
              }
              /* The popup sits after the whole field and overlays what follows it. */
              [data-example='pills'] {
                --autocomplete-max-height: 10rem;
              }
              [data-example='pills'] form {
                display: grid;
                gap: 0.5rem;
              }
              [data-example='pills'] .field [data-autocomplete-popup] {
                position: absolute;
                top: 100%;
              }
              /* One reserved pill row: switching layouts never shifts what follows. */
              [data-example] [data-pills-below] {
                min-height: 2.25rem;
              }
              [data-example] .layout {
                display: flex;
                flex-wrap: wrap;
                gap: 0.25rem;
                margin: 0;
                padding: 0.25rem;
                border: 1px solid var(--color-border, #888);
                border-radius: 0.625rem;
                justify-self: start;
              }
              [data-example] .layout legend {
                position: absolute;
                width: 1px;
                height: 1px;
                overflow: hidden;
                clip-path: inset(50%);
                white-space: nowrap;
              }
              [data-example] .layout label {
                position: relative;
                display: flex;
                align-items: center;
                margin: 0;
                padding: 0.375rem 0.75rem;
                border-radius: 0.375rem;
                font-size: 0.875rem;
                cursor: pointer;
              }
              [data-example] .layout input {
                position: absolute;
                inset: 0;
                width: 100%;
                height: 100%;
                margin: 0;
                opacity: 0;
                pointer-events: none;
              }
              [data-example] .layout label:has(:checked) {
                background: var(--color-bg-soft, #e4e4e7);
                box-shadow: inset 0 0 0 1px var(--color-border, #888);
                font-weight: 600;
              }
              [data-example] .layout label:has(:focus-visible) {
                outline: 2px solid currentColor;
                outline-offset: 2px;
              }
              [data-example] .directory {
                display: grid;
                gap: 0.5rem;
                padding: 0;
                margin: 0;
                list-style: none;
              }
              [data-example] .directory button {
                width: 100%;
                text-align: left;
              }
              [data-example] [aria-disabled='true'] {
                opacity: 0.65;
              }
              [data-example] select {
                padding: 0.75rem 1rem;
                border: 1px solid var(--color-border, #888);
                border-radius: 0.5rem;
                background: var(--color-bg-soft, #fff);
                color: inherit;
                font: inherit;
              }
              [data-example] input[type='text']:disabled {
                opacity: 0.65;
                cursor: not-allowed;
              }
              [data-example] [data-autocomplete-option] small {
                display: block;
                opacity: 0.75;
              }
              [data-example] kbd {
                float: right;
                padding: 0 0.375rem;
                border: 1px solid currentColor;
                border-radius: 0.25rem;
                font:
                  0.75rem/1.5 ui-monospace,
                  monospace;
                opacity: 0.75;
              }
            </style>
          </head>
          <body>
            <main>
              <div
                data-example="dependent"
                data-endpoint="https://samline.github.io/autocomplete/cities.json"
              >
                <form>
                  <div class="field">
                    <label for="dependent-country">Country</label
                    ><select id="dependent-country" name="country">
                      <option value="">Choose a country</option>
                      <option>Colombia</option>
                      <option>Mexico</option>
                      <option>Spain</option>
                    </select>
                  </div>
                  <div class="field">
                    <label for="dependent-input">City</label
                    ><input id="dependent-input" type="text" disabled />
                  </div>
                  <div class="actions"><button type="submit">Submit</button></div>
                </form>
                <p data-note role="status">Choose a country first.</p>
              </div>
            </main>
            <script type="module">
              import { autocomplete } from '@samline/autocomplete'
              import '@samline/autocomplete/style.css'
              const setup = (root, createAutocomplete) => {
                const form = root.querySelector('form')
                const country = root.querySelector('select')
                const input = root.querySelector('input[type="text"]')
                const note = root.querySelector('[data-note]')
                const { endpoint } = root.querySelector('[data-endpoint]').dataset
                const events = new AbortController()
                const controller = createAutocomplete(input, {
                  endpoint: () => `${endpoint}?country=${encodeURIComponent(country.value)}`,
                  mapResponse: (payload, _response, query) =>
                    payload.results.filter(
                      city =>
                        city.country === country.value &&
                        city.name.toLowerCase().includes(query.toLowerCase())
                    ),
                  minLength: 0,
                  getId: city => city.key,
                  getLabel: city => city.name,
                  hiddenInput: 'city_id',
                  messages: { empty: ({ query }) => `No city in ${country.value} matches “${query}”.` },
                })
                country.addEventListener(
                  'change',
                  () => {
                    controller.clearCache()
                    controller.clear()
                    input.disabled = !country.value
                    note.textContent = country.value
                      ? `Cities in ${country.value}. Focus the field to list them all.`
                      : 'Choose a country first.'
                    if (country.value) input.focus()
                  },
                  { signal: events.signal }
                )
                form.addEventListener(
                  'submit',
                  event => {
                    event.preventDefault()
                    const data = new FormData(form)
                    note.textContent = data.get('city_id')
                      ? `Submitted country=${data.get('country')}, city_id=${data.get('city_id')}.`
                      : 'Pick a city first.'
                  },
                  { signal: events.signal }
                )
                return () => {
                  events.abort()
                  controller.destroy()
                }
              }
              setup(document, autocomplete)
            </script>
          </body>
        </html>