Files
bsky-social-app/src/lib/routes/router.ts
T
Paul Frazee a7e3ce2585 Add fulltext search for posts and profiles (closes #340) (#342)
* Refactor mobile search screen

* Remove 'staleness' fetch trigger on search

* Implement a temporary fulltext search solution

* Add missing key from profile search result

* A few UI & UX improvements to the search suggestions

* Update web search suggestions

* Implement search in web build
2023-03-21 17:58:50 -05:00

71 lines
1.9 KiB
TypeScript

import {RouteParams, Route} from './types'
export class Router {
routes: [string, Route][] = []
constructor(description: Record<string, string>) {
for (const [screen, pattern] of Object.entries(description)) {
this.routes.push([screen, createRoute(pattern)])
}
}
matchName(name: string): Route | undefined {
for (const [screenName, route] of this.routes) {
if (screenName === name) {
return route
}
}
}
matchPath(path: string): [string, RouteParams] {
let name = 'NotFound'
let params: RouteParams = {}
for (const [screenName, route] of this.routes) {
const res = route.match(path)
if (res) {
name = screenName
params = res.params
break
}
}
return [name, params]
}
}
function createRoute(pattern: string): Route {
const pathParamNames: Set<string> = new Set()
let matcherReInternal = pattern.replace(/:([\w]+)/g, (_m, name) => {
pathParamNames.add(name)
return `(?<${name}>[^/]+)`
})
const matcherRe = new RegExp(`^${matcherReInternal}([?]|$)`, 'i')
return {
match(path: string) {
const {pathname, searchParams} = new URL(path, 'http://throwaway.com')
const addedParams = Object.fromEntries(searchParams.entries())
const res = matcherRe.exec(pathname)
if (res) {
return {params: Object.assign(addedParams, res.groups || {})}
}
return undefined
},
build(params: Record<string, string>) {
const str = pattern.replace(
/:([\w]+)/g,
(_m, name) => params[name] || 'undefined',
)
let hasQp = false
const qp = new URLSearchParams()
for (const paramName in params) {
if (!pathParamNames.has(paramName)) {
qp.set(paramName, params[paramName])
hasQp = true
}
}
return str + (hasQp ? `?${qp.toString()}` : '')
},
}
}