萬盛學電腦網

您现在的位置: 萬盛學電腦網 >> 程式設計 >  >> 腳本程式專題 >> JavaScript

JavaScript 實現搜尋框智慧提示(自動完成):從原生 AJAX 到現代架構的完整演進

搜尋框智慧提示(Autocomplete/Typeahead)是提升使用者體驗的關鍵元件。本文從原生 XMLHttpRequest 實作切入,逐步演進至防抖、快取、鍵盤導航、無障礙、虛擬滾動、框架整合的完整方案。

核心需求清單

  • 使用者輸入時延遲發送請求(防抖)
  • 相同關鍵字不重複請求(快取)
  • 請求取消機制(AbortController)避免競態
  • 鍵盤 ↑/↓/Enter/ESC 完整操作
  • 無障礙屬性(ARIA)
  • 大量建議項目虛擬滾動

階段 1:原生 JS 基礎版(對應原文邏輯)


class SimpleAutocomplete {
  constructor(inputEl, fetchSuggestions) {
    this.input = inputEl;
    this.fetch = fetchSuggestions;
    this.cache = new Map();
    this.debounceTimer = null;
    this.currentFocus = -1;
    this.suggestions = [];
    this._initDOM();
    this._bindEvents();
  }

  _initDOM() {
    this.wrapper = document.createElement('div');
    this.wrapper.className = 'autocomplete-wrapper';
    this.input.parentNode.insertBefore(this.wrapper, this.input.nextSibling);
    this.wrapper.appendChild(this.input);
    this.list = document.createElement('ul');
    this.list.className = 'autocomplete-list';
    this.list.setAttribute('role', 'listbox');
    this.list.setAttribute('id', `ac-list-${Date.now()}`);
    this.wrapper.appendChild(this.list);
    this.input.setAttribute('autocomplete', 'off');
    this.input.setAttribute('aria-autocomplete', 'list');
    this.input.setAttribute('aria-controls', this.list.id);
    this.input.setAttribute('aria-expanded', 'false');
  }

  _bindEvents() {
    this.input.addEventListener('input', () => this._onInput());
    this.input.addEventListener('keydown', (e) => this._onKeydown(e));
    document.addEventListener('click', (e) => {
      if (!this.wrapper.contains(e.target)) this.close();
    });
  }

  _onInput() {
    clearTimeout(this.debounceTimer);
    this.debounceTimer = setTimeout(() => this._fetch(), 200);
  }

  async _fetch() {
    const query = this.input.value.trim();
    if (!query) return this.close();
    
    if (this.cache.has(query)) {
      this._render(this.cache.get(query));
      return;
    }

    this.controller?.abort();
    this.controller = new AbortController();
    
    try {
      const data = await this.fetch(query, { signal: this.controller.signal });
      this.cache.set(query, data);
      this._render(data);
    } catch (e) {
      if (e.name !== 'AbortError') console.error(e);
    }
  }

  _render(items) {
    this.suggestions = items;
    this.currentFocus = -1;
    this.list.innerHTML = '';
    if (!items.length) return this.close();
    
    const frag = document.createDocumentFragment();
    items.forEach((item, i) => {
      const li = document.createElement('li');
      li.setAttribute('role', 'option');
      li.setAttribute('id', `${this.list.id}-${i}`);
      li.textContent = item.label ?? item;
      li.dataset.value = item.value ?? item;
      frag.appendChild(li);
    });
    this.list.appendChild(frag);
    this.open();
  }

  _onKeydown(e) {
    if (!this.isOpen) return;
    const items = this.list.querySelectorAll('[role="option"]');
    switch (e.key) {
      case 'ArrowDown':
        e.preventDefault();
        this.currentFocus = Math.min(this.currentFocus + 1, items.length - 1);
        this._updateFocus(items);
        break;
      case 'ArrowUp':
        e.preventDefault();
        this.currentFocus = Math.max(this.currentFocus - 1, -1);
        this._updateFocus(items);
        break;
      case 'Enter':
        if (this.currentFocus > -1) {
          e.preventDefault();
          this._select(items[this.currentFocus]);
        }
        break;
      case 'Escape':
        this.close();
        this.input.blur();
        break;
    }
  }

  _updateFocus(items) {
    items.forEach((el, i) => {
      const selected = i === this.currentFocus;
      el.setAttribute('aria-selected', selected);
      el.classList.toggle('focused', selected);
      if (selected) el.scrollIntoView({ block: 'nearest' });
    });
  }

  _select(el) {
    this.input.value = el.textContent;
    this.input.dispatchEvent(new CustomEvent('autocomplete-select', { detail: el.dataset.value }));
    this.close();
  }

  open() {
    this.list.hidden = false;
    this.input.setAttribute('aria-expanded', 'true');
    this.isOpen = true;
  }

  close() {
    this.list.hidden = true;
    this.input.setAttribute('aria-expanded', 'false');
    this.isOpen = false;
  }
}

// 使用
const input = document.getElementById('search');
new SimpleAutocomplete(input, async (q) => {
  const res = await fetch(`/api/suggest?q=${encodeURIComponent(q)}`);
  return res.json(); // [{label:'...', value:'...'}, ...]
});

階段 2:生產級增強功能

功能實作要點
請求去重進行中請求用 Map 記錄,相同 query 直接等待同一 Promise
快取策略LRU 快取(如 lru-cache)、TTL 過期、預先預熱熱門查詢
錯誤重試指數退避、最多 2 次、靜默失敗不阻塞 UI
分組顯示資料含 group 欄位,渲染時插入 <li class="group">
異步建議支援 fetch 回傳 Promise 或 Observable
虛擬滾動建議項 > 50 時啟用,僅渲染可視區 + 緩衝區
無障礙ARIA 屬性完整、焦點管理、螢幕閱讀器宣告

階段 3:框架整合(Vue 3 / React 範例)

Vue 3 Composables


// useAutocomplete.js
import { ref, watch, onMounted, onUnmounted } from 'vue';

export function useAutocomplete(fetchFn, options = {}) {
  const query = ref('');
  const suggestions = ref([]);
  const isOpen = ref(false);
  const highlightedIndex = ref(-1);
  const cache = new Map();
  let abortCtrl = null;

  const fetch = async (q) => {
    if (!q) return suggestions.value = [];
    if (cache.has(q)) return suggestions.value = cache.get(q);
    abortCtrl?.abort();
    abortCtrl = new AbortController();
    try {
      const data = await fetchFn(q, { signal: abortCtrl.signal });
      cache.set(q, data);
      suggestions.value = data;
      isOpen.value = true;
    } catch (e) { if (e.name !== 'AbortError') console.error(e); }
  };

  watch(query, (q) => { clearTimeout(timer); timer = setTimeout(() => fetch(q), options.debounce ?? 200); });
  
  // 鍵盤、選取、關閉等邏輯...
  return { query, suggestions, isOpen, highlightedIndex, select: (item) => { query.value = item.label; isOpen.value = false; } };
}

React Hook


// useAutocomplete.js
import { useState, useEffect, useRef, useCallback } from 'react';

export function useAutocomplete(fetchFn, { debounce = 200 } = {}) {
  const [query, setQuery] = useState('');
  const [suggestions, setSuggestions] = useState([]);
  const [isOpen, setIsOpen] = useState(false);
  const [highlighted, setHighlighted] = useState(-1);
  const cacheRef = useRef(new Map());
  const abortRef = useRef(null);

  const fetch = useCallback(async (q) => {
    if (!q) return setSuggestions([]);
    if (cacheRef.current.has(q)) return setSuggestions(cacheRef.current.get(q));
    abortRef.current?.abort();
    abortRef.current = new AbortController();
    try {
      const data = await fetchFn(q, { signal: abortRef.current.signal });
      cacheRef.current.set(q, data);
      setSuggestions(data);
      setIsOpen(true);
    } catch (e) { if (e.name !== 'AbortError') console.error(e); }
  }, [fetchFn]);

  useEffect(() => {
    const t = setTimeout(() => fetch(query), debounce);
    return () => clearTimeout(t);
  }, [query, fetch, debounce]);

  // 鍵盤處理、選取等...
  return { query, setQuery, suggestions, isOpen, setIsOpen, highlighted, setHighlighted };
}

CSS 關鍵樣式(無障礙、虛擬滾動就緒)


.autocomplete-wrapper { position: relative; display: inline-block; width: 100%; }
.autocomplete-list {
  position: absolute; top: 100%; left: 0; right: 0;
  max-height: 280px; overflow-y: auto;
  background: #fff; border: 1px solid #ddd; border-top: none;
  border-radius: 0 0 8px 8px; box-shadow: 0 8px 16px rgba(0,0,0,.1);
  margin: 0; padding: 4px 0; list-style: none; z-index: 100;
}
.autocomplete-list[hidden] { display: none; }
.autocomplete-list [role="option"] {
  padding: 8px 12px; cursor: pointer; white-space: nowrap; overflow: hidden; text-overflow: ellipsis;
}
.autocomplete-list [role="option"].focused,
.autocomplete-list [role="option"]:hover { background: #e8f2fe; }
.autocomplete-list .group { padding: 6px 12px; font-weight: 600; color: #666; cursor: default; }

結語

智慧提示元件看似簡單,實則包含防抖、快取、取消、鍵盤、無障礙、虛擬滾動、分組、錯誤處理等工程細節。建議專案採用成熟元件庫(如 @headlessui/combobox、downshift、autocomplete.js、Vue Autocomplete、React Select),而非重複造輪子。若必須自建,請以本文「階段 1」為骨架,逐步疊加「階段 2」功能,並編寫完整單元/整合測試(Jest + Testing Library)。

copyright © 萬盛學電腦網 all rights reserved