mirror of
https://github.com/cupcakearmy/nicco.io.git
synced 2025-09-05 18:20:45 +00:00
search
This commit is contained in:
36
src/routes/search.json.js
Normal file
36
src/routes/search.json.js
Normal file
@@ -0,0 +1,36 @@
|
||||
import lunr from 'lunr'
|
||||
|
||||
import { getAll } from '../lib/wp'
|
||||
|
||||
function removeHTML(s) {
|
||||
return s.replace(/<.*?>|\s+|&#\d+;/g, ' ').trim()
|
||||
}
|
||||
|
||||
async function convertForIdx(type, fields = []) {
|
||||
const items = await getAll(type)
|
||||
const defaults = ['title', 'content', 'slug']
|
||||
return items.map((item) => ({
|
||||
url: `${item.type}/${item.slug}`,
|
||||
data: [...defaults, ...fields].map((field) => removeHTML(item[field])).join(' '),
|
||||
}))
|
||||
}
|
||||
|
||||
export async function get(req, res) {
|
||||
const all = await Promise.all([
|
||||
convertForIdx('projects', ['description']),
|
||||
convertForIdx('pages'),
|
||||
convertForIdx('posts'),
|
||||
convertForIdx('works', ['role']),
|
||||
])
|
||||
|
||||
const idx = lunr(function () {
|
||||
this.ref('url')
|
||||
this.field('data')
|
||||
|
||||
all.flat().forEach((doc) => {
|
||||
this.add(doc)
|
||||
})
|
||||
})
|
||||
res.setHeader('Content-Type', 'application/json')
|
||||
res.end(JSON.stringify(idx))
|
||||
}
|
58
src/routes/search.svelte
Normal file
58
src/routes/search.svelte
Normal file
@@ -0,0 +1,58 @@
|
||||
<script context="module">
|
||||
export async function preload() {
|
||||
const prebuilt = await this.fetch(`/search.json`).then((res) => res.json())
|
||||
return { prebuilt }
|
||||
}
|
||||
</script>
|
||||
|
||||
<script>
|
||||
import lunr from 'lunr'
|
||||
|
||||
import SearchResult from '../components/SearchResult.svelte'
|
||||
import SimplePage from '../components/SimplePage.svelte'
|
||||
|
||||
export let prebuilt
|
||||
|
||||
let needle
|
||||
let results = []
|
||||
|
||||
async function search(needle) {
|
||||
if (!needle || !idx) {
|
||||
results = []
|
||||
} else {
|
||||
let found = idx.search(needle + '~1')
|
||||
if (!found.length) found = idx.search(needle + '*')
|
||||
results = found.slice(0, 20)
|
||||
}
|
||||
}
|
||||
|
||||
$: idx = lunr.Index.load(prebuilt)
|
||||
$: search(needle)
|
||||
</script>
|
||||
|
||||
<style>
|
||||
input {
|
||||
appearance: none;
|
||||
margin: 0;
|
||||
padding: 0.5rem;
|
||||
font-size: 1em;
|
||||
width: 100%;
|
||||
outline: none;
|
||||
border: 1px solid var(--clr-dark);
|
||||
}
|
||||
|
||||
ul {
|
||||
margin-top: 2em;
|
||||
list-style: none;
|
||||
padding: 0;
|
||||
}
|
||||
</style>
|
||||
|
||||
<SimplePage title="Search" expanded={false}>
|
||||
<input bind:value={needle} placeholder="needle" />
|
||||
<ul>
|
||||
{#each results as result (result.ref)}
|
||||
<SearchResult {result} />
|
||||
{/each}
|
||||
</ul>
|
||||
</SimplePage>
|
Reference in New Issue
Block a user