feat: the search bar opens a link when you type its name
A link whose name, or a word of it, starts with what was typed is highlighted and Enter opens it. Arrow up from the first row leaves no row highlighted, so Enter searches the web for the same word.
This commit is contained in:
+22
-1
@@ -1,6 +1,27 @@
|
||||
import assert from "node:assert/strict"
|
||||
import { test } from "node:test"
|
||||
import { parseSuggestions, searchUrl } from "./search.ts"
|
||||
import { matchLinks, parseSuggestions, searchUrl } from "./search.ts"
|
||||
|
||||
test("matchLinks", () => {
|
||||
const links = ["Grafana", "Home Assistant", "IT-Tools", "Sonarr"].map(
|
||||
(name) => ({ name })
|
||||
)
|
||||
const names = (typed: string) => {
|
||||
const { links: found, starts } = matchLinks(links, typed)
|
||||
return [found.map((l) => l.name).join(","), starts]
|
||||
}
|
||||
// the start of the name or of a word in it comes first and counts as a start
|
||||
assert.deepEqual(names("so"), ["Sonarr", 1])
|
||||
assert.deepEqual(names(" ASSIST "), ["Home Assistant", 1])
|
||||
assert.deepEqual(names("tools"), ["IT-Tools", 1])
|
||||
// only inside a word: listed, but Enter does not open it
|
||||
assert.deepEqual(names("ana"), ["Grafana", 0])
|
||||
assert.deepEqual(names("a"), ["Home Assistant,Grafana,Sonarr", 1])
|
||||
assert.deepEqual(names("plex"), ["", 0])
|
||||
// a query with a space is one phrase
|
||||
assert.deepEqual(names("home a"), ["Home Assistant", 1])
|
||||
assert.deepEqual(names("grafana docs"), ["", 0])
|
||||
})
|
||||
|
||||
test("searchUrl", () => {
|
||||
assert.equal(
|
||||
|
||||
@@ -29,6 +29,26 @@ export function searchUrl(
|
||||
return `https://duckduckgo.com/?q=${q}`
|
||||
}
|
||||
|
||||
/**
|
||||
* The links for what was typed. First the ones where the name or a word of it starts
|
||||
* with it (`starts` of them: Enter opens the first), then the ones that contain it.
|
||||
*/
|
||||
export function matchLinks<TLink extends { name: string }>(
|
||||
links: TLink[],
|
||||
typed: string
|
||||
) {
|
||||
const q = typed.trim().toLowerCase()
|
||||
const starts: TLink[] = []
|
||||
const contains: TLink[] = []
|
||||
for (const link of links) {
|
||||
const name = link.name.toLowerCase()
|
||||
const words = [name, ...name.split(/[^\p{L}\p{N}]+/u)]
|
||||
if (words.some((word) => word.startsWith(q))) starts.push(link)
|
||||
else if (name.includes(q)) contains.push(link)
|
||||
}
|
||||
return { links: [...starts, ...contains], starts: starts.length }
|
||||
}
|
||||
|
||||
/** Both DuckDuckGo and SearXNG answer in OpenSearch form: [query, [suggestions]] */
|
||||
export function parseSuggestions(body: unknown): string[] {
|
||||
const list = Array.isArray(body) && Array.isArray(body[1]) ? body[1] : body
|
||||
|
||||
Reference in New Issue
Block a user