加载搜索结果,取消过期的请求,并获取下一页。

useAsyncOptions 在用户输入时加载条目。它会等输入停下来,取消被取代的请求,并在加载期间保留之前的结果。

<script lang="ts">
  import { CheckIcon, ChevronDownIcon } from "@lucide/svelte"
  import {
    Combobox,
    ComboboxContent,
    ComboboxEmpty,
    ComboboxInput,
    ComboboxItem,
    ComboboxItemIndicator,
    ComboboxLabel,
    ComboboxList,
    ComboboxStatus,
    ComboboxTrigger,
  } from "@ui-sdk/svelte/combobox"
  import { useAsyncOptions } from "@ui-sdk/svelte/async-options"

  const movieTitles = [
    "The Shawshank Redemption",
    "The Godfather",
    "The Dark Knight",
    "Pulp Fiction",
    "Schindler's List",
    "The Lord of the Rings",
    "Fight Club",
    "Forrest Gump",
    "Inception",
    "The Matrix",
    "Goodfellas",
    "Interstellar",
    "Parasite",
    "Spirited Away",
    "Whiplash",
    "The Prestige",
    "The Departed",
    "Gladiator",
    "Alien",
    "Casablanca",
    "Amélie",
    "Arrival",
  ]

  function searchMovies(query: string, { signal }: { signal: AbortSignal }) {
    return new Promise<{ value: string; label: string }[]>(
      (resolve, reject) => {
        const timer = setTimeout(() => {
          const needle = query.trim().toLowerCase()
          resolve(
            movieTitles
              .filter((title) => title.toLowerCase().includes(needle))
              .map((title) => ({
                value: title.toLowerCase().replace(/\W+/g, "-"),
                label: title,
              }))
          )
        }, 500)
        signal.addEventListener("abort", () => {
          clearTimeout(timer)
          reject(signal.reason)
        })
      }
    )
  }

  const movies = useAsyncOptions(searchMovies, {
    debounce: 300,
    query: "the",
    immediate: true,
  })
</script>

<Combobox
  items={movies.state.items}
  defaultQuery="the"
  filter={false}
  status={movies.state.status}
  onQueryChange={(query) => movies.setQuery(query)}
>
  <div data-slot="stack">
    <ComboboxLabel>Movie</ComboboxLabel>
    <div data-slot="row">
      <ComboboxInput placeholder="Search movies…" />
      <ComboboxTrigger aria-label="Show movies">
        <ChevronDownIcon aria-hidden="true" />
      </ComboboxTrigger>
    </div>
  </div>
  <ComboboxContent>
    <ComboboxStatus>
      {#snippet children(state)}
        {state.status === "error"
          ? "Couldn't load movies."
          : state.loading
            ? "Searching…"
            : `${state.count} ${state.count === 1 ? "movie" : "movies"}`}
      {/snippet}
    </ComboboxStatus>
    <ComboboxEmpty>
      {#snippet children(state)}
        {#if state.empty && !state.loading}No movies match “{state.query}”.{/if}
      {/snippet}
    </ComboboxEmpty>
    <ComboboxList>
      {#snippet children(state)}
        {#each state.items as { value: string; label: string; disabled?: boolean }[] as item (item.value)}
          <ComboboxItem
            value={item.value}
            label={item.label}
            disabled={item.disabled}
          >
            {item.label}
            <ComboboxItemIndicator>
              <CheckIcon aria-hidden="true" />
            </ComboboxItemIndicator>
          </ComboboxItem>
        {/each}
      {/snippet}
    </ComboboxList>
  </ComboboxContent>
</Combobox>
更改电影搜索,等待结果。用方向键选择一部电影,然后按 Enter。

加载结果

把加载函数传给这个辅助函数。这个示例期望 /api/movies 返回一个电影标题数组:

<script lang="ts">
  import { useAsyncOptions } from "@ui-sdk/svelte/async-options"
  import {
    Combobox,
    ComboboxContent,
    ComboboxInput,
  } from "@ui-sdk/svelte/combobox"

  const movies = useAsyncOptions<string>(async (query, { signal }) => {
    const response = await fetch(`/api/movies?q=${encodeURIComponent(query)}`, {
      signal,
    })
    if (!response.ok) throw new Error("Couldn't load movies")
    return response.json()
  })
</script>

<Combobox
  items={movies.state.items}
  filter={false}
  status={movies.state.status}
  onQueryChange={movies.setQuery}
>
  <ComboboxInput aria-label="Movie" placeholder="Search movies…" />
  <ComboboxContent />
</Combobox>

在标记里读 movies.state,这样 Svelte 才能跟踪它。解构状态只会留下当前的值。

把 signal 传给 fetch,这样更新的搜索可以取消这个请求。组件卸载时,这个辅助函数也会取消。把 filter 设为 false,就把匹配和排序交给服务器。

用 ComboboxStatus 和 ComboboxEmpty 显示加载中、错误和空结果的消息,就像演示里那样。同样的模式也适用于 Select、Autocomplete 和 Command。

选择何时加载

第二个参数设置起始行为:

选项作用默认值
debounce请求开始前,输入必须暂停的毫秒数。200
query起始的搜索文本。""
immediate组件一挂载就加载这段文本。false
minLength文本在开始加载前所需的字符数。更短的文本会清空条目。0

要获取初始选项,就在加载函数后面加上 { immediate: true, debounce: 300 }。在第一次加载开始之前,status 就已经是 "loading",所以列表不会闪一下空状态。如果你设置了 query,就让组件的 defaultQuery 使用同样的起始文本。

加载更多

对于分页的结果,加载函数会收到从 0 开始的 page。返回 { items, hasMore }:

import type { AsyncOptionsContext } from "@ui-sdk/svelte/async-options"

async function loadMoviePages(
  query: string,
  { signal, page }: AsyncOptionsContext
) {
  const response = await fetch(
    `/api/movies?q=${encodeURIComponent(query)}&page=${page}`,
    { signal }
  )
  if (!response.ok) throw new Error("Couldn't load movies")
  const data: { titles: string[]; next: number | null } = await response.json()
  return { items: data.titles, hasMore: data.next !== null }
}

export { loadMoviePages }

把 loadMoviePages 传给 useAsyncOptions,替换上面内联的加载函数。

在 Combobox 上绑定 onLoadMore={movies.loadMore}。当滚动或键盘导航到达最后一个条目时,它会请求另一页。这个辅助函数会把新条目追加到后面。

<script lang="ts">
  import { CheckIcon, ChevronDownIcon } from "@lucide/svelte"
  import {
    Combobox,
    ComboboxContent,
    ComboboxEmpty,
    ComboboxInput,
    ComboboxItem,
    ComboboxItemIndicator,
    ComboboxLabel,
    ComboboxList,
    ComboboxStatus,
    ComboboxTrigger,
  } from "@ui-sdk/svelte/combobox"
  import { useAsyncOptions } from "@ui-sdk/svelte/async-options"

  const movieTitles = [
    "The Shawshank Redemption",
    "The Godfather",
    "The Dark Knight",
    "Pulp Fiction",
    "Schindler's List",
    "The Lord of the Rings",
    "Fight Club",
    "Forrest Gump",
    "Inception",
    "The Matrix",
    "Goodfellas",
    "Interstellar",
    "Parasite",
    "Spirited Away",
    "Whiplash",
    "The Prestige",
    "The Departed",
    "Gladiator",
    "Alien",
    "Casablanca",
    "Amélie",
    "Arrival",
  ]

  function searchMoviePages(
    query: string,
    { signal, page }: { signal: AbortSignal; page: number }
  ) {
    return new Promise<{
      items: { value: string; label: string }[]
      hasMore: boolean
    }>((resolve, reject) => {
      const timer = setTimeout(() => {
        const needle = query.trim().toLowerCase()
        const found = movieTitles
          .filter((title) => title.toLowerCase().includes(needle))
          .map((title) => ({
            value: title.toLowerCase().replace(/\W+/g, "-"),
            label: title,
          }))
        resolve({
          items: found.slice(page * 5, page * 5 + 5),
          hasMore: found.length > page * 5 + 5,
        })
      }, 500)
      signal.addEventListener("abort", () => {
        clearTimeout(timer)
        reject(signal.reason)
      })
    })
  }

  const movies = useAsyncOptions(searchMoviePages, { immediate: true })
</script>

<Combobox
  items={movies.state.items}
  filter={false}
  status={movies.state.status}
  onQueryChange={(query) => movies.setQuery(query)}
  onLoadMore={movies.loadMore}
>
  <div data-slot="stack">
    <ComboboxLabel>Movie</ComboboxLabel>
    <div data-slot="row">
      <ComboboxInput placeholder="Search movies…" />
      <ComboboxTrigger aria-label="Show movies">
        <ChevronDownIcon aria-hidden="true" />
      </ComboboxTrigger>
    </div>
  </div>
  <ComboboxContent>
    <ComboboxEmpty>
      {#snippet children(state)}
        {#if state.empty && !state.loading}No movies found.{/if}
      {/snippet}
    </ComboboxEmpty>
    <ComboboxList>
      {#snippet children(state)}
        {#each state.items as { value: string; label: string; disabled?: boolean }[] as item (item.value)}
          <ComboboxItem
            value={item.value}
            label={item.label}
            disabled={item.disabled}
          >
            {item.label}
            <ComboboxItemIndicator>
              <CheckIcon aria-hidden="true" />
            </ComboboxItemIndicator>
          </ComboboxItem>
        {/each}
      {/snippet}
    </ComboboxList>
    <ComboboxStatus>
      {#snippet children(state)}
        {state.loading
          ? "Loading more…"
          : movies.state.hasMore
            ? `${state.count} loaded`
            : `All ${state.count}`}
      {/snippet}
    </ComboboxStatus>
  </ComboboxContent>
</Combobox>
打开电影列表并向下滚动,或用 Arrow Down 到达最后一个结果。下一页会加到列表里。

请求进行中时,status 是 "loading";失败之后是 "error";其他时候是 "idle"。error 保存失败信息,之前的结果仍然可用。

在重试按钮里调用 movies.reload(),从第 0 页开始重新加载当前的查询。movies.state.hasMore 告诉你是否还有另一页可用。