This is the 11th day of my participation in the Gwen Challenge in November. Check out the details: The last Gwen Challenge in 2021

The article translation: hacks.mozilla.org/2021/08/mdn… By Peter Bengtsson

MDN Web Docs has a new search result auto-completion feature that allows you to quickly jump directly to the document you are looking for by typing part of the document title. This is an article about how this function is done. If you follow through, I’ll share an “Easter egg” feature.

series

How does MDN autocomplete search results? (a)

How does MDN autocomplete search results? (2)

Implementation details

In the last article, we saw a rough code structure that looked like this for the search section

(async function() { 
    const response = await fetch('/en-US/search-index.json'); 
    const documents = await response.json(); 
    const inputValue = document.querySelector( 'input[type="search"]' ).value; 
    const flex = FlexSearch.create(); 
    documents.forEach(({ title }, i) = > { 
        flex.add(i, title); 
    }); 
    const indexResults = flex.search(inputValue); 
    const foundDocuments = indexResults.map((index) = > documents[index]); 
    displayFoundDocuments(foundDocuments.slice(0.10)); }) ();Copy the code

First, a React library called Downshift is used, which handles all interactions, displays, and ensures that the search results displayed are accessible. Downshift is a mature library that addresses numerous challenges by building widgets like this, especially in terms of accessibility.

Downshift address: www.npmjs.com/package/dow…

Second, the FlexSearch library, a third-party library, is used to ensure that searches for titles take natural language into account. It describes itself as “the fastest, most memory-flexible, zero-dependency full-text search library on the Web.” This is much more efficient and accurate than trying to simply look up a string in a long list of other strings.

Decide which results to show first

To be fair, if the user typed foreAC, it would not be difficult to narrow down more than 10,000 document titles to foreAC-only titles, but we needed to decide which results to display first. The way we do this is by counting page views. We recorded, for each MDN URL, which received the most page views, determining the “popularity” of the page. The document that most people decide to arrive at is most likely the one the user is searching for.

This part of the concrete can see: hacks.mozilla.org/2021/03/how…

The source address

All of this code is in the Yari Repo, a project that builds and previews all of the MDN content. To find the exact code, click client/ SRC /search.tsx. You’ll find all the code lazy loaded, searched, preloaded, and displayed to automatically complete the search.