Skip to content

Commit

Permalink
feat: ssr search
Browse files Browse the repository at this point in the history
  • Loading branch information
gaboesquivel committed Apr 19, 2024
1 parent fd6094f commit 00f952c
Show file tree
Hide file tree
Showing 6 changed files with 48 additions and 36 deletions.
2 changes: 1 addition & 1 deletion apps/masterbots.ai/app/(browse)/page.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -28,7 +28,7 @@ export default async function HomePage({ searchParams }: HomePageProps) {
return (
<div className="container">
<CategoryTabs categories={categories} />
{/* <SearchInput /> */}
<SearchInput />
{/* <div>Your query: {query}</div>
<ul>
{threads.map(t => (
Expand Down
23 changes: 13 additions & 10 deletions apps/masterbots.ai/components/shared/search-input.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -9,26 +9,29 @@ import { useGlobalStore } from '@/hooks/use-global-store'

export function SearchInput() {
const pathname = usePathname()
// const router = useRouter()
const { setGlobalQuery, ...global } = useGlobalStore()
const [query, setQuery] = useState(global.query)

const replaceUrl = () => {
// Encoding the query and managing search parameters
const searchParams = new URLSearchParams(window.location.search)
if (query) {
searchParams.set('query', encodeQuery(query))
} else {
console.log('delete')
searchParams.delete('query')
}
searchParams.delete('page')
if (!query) searchParams.delete('query')
searchParams.delete('page') // Always remove 'page' param to reset pagination or similar

history.pushState({}, undefined, `${pathname}?${searchParams.toString()}`)
// SSR wont work as Next is not updating the client component intial props on ThreadList
// ThreadList listes to changes on global store query state
//TODO: find out how to fix client component refresh issue
// in the meantime I'll use client global store
// update url for history navigation and reload support
history.pushState({}, undefined, `${pathname}?query=${encodeQuery(query)}`)

// const href = `${pathname}?${searchParams.toString()}`
// router.replace(href)
// router.refresh()
}

const handleSubmit = e => {
e.preventDefault()
// ThreadList listens to changes on global store query state
setGlobalQuery(encodeQuery(query))
replaceUrl()
}
Expand Down
47 changes: 28 additions & 19 deletions apps/masterbots.ai/components/shared/thread-list.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,7 @@ import { getBrowseThreads } from '@/services/hasura'
import { ThreadDialog } from './thread-dialog'
import { ThreadListAccordion } from './thread-list-accordion'
import { ThreadListChatItem } from './thread-list-chat-item'
import { useGlobalStore } from '@/hooks/use-global-store'

const limit = 20
export function ThreadList({
Expand All @@ -19,29 +20,36 @@ export function ThreadList({
chat = false,
dialog = false
}: ThreadListProps) {
// const globalStore = useGlobalStore()
const queryKey = [usePathname(), 'globalStore.query']
const { query } = useGlobalStore()
const loadMoreRef = useRef<HTMLDivElement>(null)
const queryClient = useQueryClient()
const [showSkeleton, setShowSkeleton] = useState(false)

const queryKey = [usePathname(), query]
const [lastQueryKey, setLastQueryKey] = useState(queryKey)
const { isFetchingNextPage, fetchNextPage, data, refetch } = useInfiniteQuery(
{
queryKey,
queryFn: async props => {
return getBrowseThreads({
...filter,
offset: props.pageParam * limit,
limit,
query
})
},
initialData: { pages: [initialThreads], pageParams: [1] },
initialPageParam: 2,
getNextPageParam: (_a, _b, lastPageParam) => {
return lastPageParam + 1
},
enabled: false
}
)

const { isFetchingNextPage, fetchNextPage, data } = useInfiniteQuery({
queryKey,
queryFn: async props => {
return getBrowseThreads({
...filter,
offset: props.pageParam * limit,
limit
})
},
initialData: { pages: [initialThreads], pageParams: [1] },
initialPageParam: 2,
getNextPageParam: (_a, _b, lastPageParam) => {
return lastPageParam + 1
},
enabled: false
})
useEffect(() => {
refetch()
}, [refetch, query])

// load mare item when it gets to the end
// TODO: read count from database
Expand Down Expand Up @@ -84,9 +92,10 @@ export function ThreadList({
queryClient.invalidateQueries({ queryKey }).then(() => {
queryClient.refetchQueries({ queryKey }).then(() => {
setShowSkeleton(false)
refetch()
})
})
}, [queryKey, setLastQueryKey, lastQueryKey, setShowSkeleton])
}, [queryKey, setLastQueryKey, lastQueryKey, setShowSkeleton, refetch])

// ThreadList can displays the rigth list item based on the context
// ThreadListChatItem is next shallow link for chat ui lists
Expand Down
9 changes: 5 additions & 4 deletions apps/masterbots.ai/lib/url.ts
Original file line number Diff line number Diff line change
@@ -1,12 +1,13 @@
import { z, ZodSchema } from 'zod'

// Zod schema for validating slug strings
export const SlugSchema: ZodSchema<string> = z.string()
export const SlugSchema: ZodSchema<string> = z
.string()
.min(1)
.regex(/^[a-z0-9]+[a-z0-9+_-]*[a-z0-9]+$/, "Invalid slug format.")
.regex(/^[a-z0-9]+[a-z0-9+_-]*[a-z0-9]+$/, 'Invalid slug format.')

// Function to convert a username into a slug
export const toSlug = (username: string, separator = '_' ): string => {
export const toSlug = (username: string, separator = '_'): string => {
return username
.toLowerCase()
.replace(/ & /g, '_and_')
Expand All @@ -24,7 +25,7 @@ export const fromSlug = (slug: string, separator = '_'): string => {

//Encodes a string for use in a URL, replacing spaces with the '+' character.
export const encodeQuery = (input: string): string => {
return encodeURIComponent(input).replace(/%20/g, '+')
return encodeURIComponent(input).replace(/%20/g, '+').replace(/ /g, '+')
}

//Decodes a URL-encoded string, converting '+' back into spaces.
Expand Down
2 changes: 1 addition & 1 deletion apps/masterbots.ai/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,7 @@
"private": true,
"name": "masterbots.ai",
"scripts": {
"dev": "next dev --turbo",
"dev": "rm -rf .next/ && next dev --turbo",
"build": "next build",
"start": "next start",
"lint": "next lint",
Expand Down
1 change: 0 additions & 1 deletion apps/masterbots.ai/services/hasura/hasura.service.ts
Original file line number Diff line number Diff line change
Expand Up @@ -357,7 +357,6 @@ export async function getBrowseThreads({
offset,
slug
}: GetBrowseThreadsParams) {

const client = getHasuraClient({})

const { thread } = await client.query({
Expand Down

0 comments on commit 00f952c

Please sign in to comment.