Skip to content

Instantly share code, notes, and snippets.

@filzrev
Last active September 14, 2023 12:45
Show Gist options
  • Save filzrev/9a046c40f6df63d01f40018d8a19bd47 to your computer and use it in GitHub Desktop.
Save filzrev/9a046c40f6df63d01f40018d8a19bd47 to your computer and use it in GitHub Desktop.
Custom docfx template to replace search library from `lunr.js` to `fuse.js`

Summary

This script is used to replace docfx's lunr.js search to fuse.js based search. To use this script. simply replace public/search-worker.min.js with this gist content.

Note

This script works only when using modern template. To support default template. it needs to replace import Fuse from statement with equivalent code that don't use ESM.

"use strict";
import Fuse from 'https://cdn.jsdelivr.net/npm/fuse.js@latest/+esm'
let fuseIndex
let searchData
// See: https://www.fusejs.io/api/options.html
const fuseOptions = {
threshold: 0.0,
minMatchCharLength: 1,
ignoreLocation: true,
useExtendedSearch: true,
keys: [
{ name: 'href', weight: 0.8 },
{ name: 'title', weight: 0.8 },
{ name: 'keywords', weight: 0.5 }
]
};
onmessage = oEvent => {
const q = oEvent.data.q
let results = []
if (fuseIndex) {
const hits = fuseIndex.search(q)
results = hits.map((hit) => {
const item = hit.item
return {
href: item.href,
title: item.title,
keywords: item.keywords
}
})
}
postMessage({ e: "query-ready", q, d: results })
}
async function buildIndex() {
// Try to load pre-generated search index
const response = await fetch("../index.fuse.json")
if(response.ok)
{
const json = await response.json()
const index = Fuse.parseIndex(json)
fuseIndex = new Fuse(null, fuseOptions, index)
}
else
{
const response = await fetch("../index.json")
if(!response.ok)
return
var json = await response.json()
searchData = Object.values(json) // Convert to items.
if (searchData && searchData.length > 0) {
fuseIndex = new Fuse(searchData, fuseOptions)
}
}
postMessage({ e: "index-ready" })
}
await buildIndex()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment