feat: add site search

This commit is contained in:
DIYgod
2023-04-12 02:33:38 +01:00
parent 9a579a05ab
commit 46fac4df3a
9 changed files with 332 additions and 66 deletions
+3 -1
View File
@@ -75,5 +75,7 @@
"Successfully followed": "嘿!你已经准备好<2>在这里跟上你关注的博主的最新动态</2>了。",
"Enable AI Filtering": "启用 AI 过滤",
"Filter out possible low-quality content based on AI ratings.": "基于 AI 评分过滤可能质量不佳的内容。",
"Refreshing": "刷新中"
"Refreshing": "刷新中",
"Search for your interest": "搜索你感兴趣的内容",
"results": "条结果"
}
+2 -1
View File
@@ -14,5 +14,6 @@
"View on Hoot It": "在 Hoot It 上查看",
"View on Crossbell Scan": "在 Crossbell Scan 上查看",
"Subscribe to JSON Feed": "订阅 JSON Feed",
"Subscribe to RSS": "订阅 RSS"
"Subscribe to RSS": "订阅 RSS",
"Search on this site": "在本站搜索"
}
+12 -27
View File
@@ -1,30 +1,16 @@
import { Profile } from "~/lib/types"
import { useAccountSites } from "~/queries/site"
import { useForm } from "react-hook-form"
import { useAccountState } from "@crossbell/connect-kit"
import { useState, useEffect } from "react"
import { useCommentPage, useUpdateComment } from "~/queries/page"
import { useRouter } from "next/router"
import { useTranslation } from "next-i18next"
import { cn } from "~/lib/utils"
export const SearchInput: React.FC<{
characterId?: string
value?: string
}> = ({ characterId, value }) => {
const account = useAccountState((s) => s.computed.account)
const userSites = useAccountSites()
const commentPage = useCommentPage()
const updateComment = useUpdateComment()
noBorder?: boolean
onSubmit?: (value?: string) => void
}> = ({ value, noBorder, onSubmit }) => {
const router = useRouter()
const [viewer, setViewer] = useState<Profile | null>(null)
const { t } = useTranslation(["common", "site"])
useEffect(() => {
if (userSites.isSuccess && userSites.data?.length) {
setViewer(userSites.data[0])
}
}, [userSites, router])
const form = useForm({
defaultValues: {
content: value || "",
@@ -33,14 +19,9 @@ export const SearchInput: React.FC<{
const handleSubmit = form.handleSubmit(async (values) => {
router.push(`/search?q=${values.content}`)
onSubmit?.(values.content)
})
useEffect(() => {
if (commentPage.isSuccess || updateComment.isSuccess) {
form.reset()
}
}, [commentPage.isSuccess, updateComment.isSuccess, form])
return (
<div className="xlog-comment-input flex">
<form className="w-full relative" onSubmit={handleSubmit}>
@@ -48,12 +29,16 @@ export const SearchInput: React.FC<{
className="absolute left-0 top-1/2 -translate-y-1/2 text-2xl text-zinc-500 h-11 w-14 flex items-center justify-center cursor-pointer"
onClick={handleSubmit}
>
<i className="i-mingcute:search-line block"></i>
<i className="i-mingcute:search-line block" />
</div>
<input
id="content"
className="rounded-full w-full pl-12 pr-5 h-11 border outline-none hover:shadow-md focus:shadow-md transition-shadow"
placeholder={t("Search for your interest", { ns: "site" }) || ""}
className={cn(
"w-full pl-12 pr-5 h-11 outline-none",
!noBorder &&
"border rounded-full hover:shadow-md focus:shadow-md transition-shadow",
)}
placeholder={t("Search for your interest") || ""}
{...form.register("content", {})}
/>
</form>
+61 -35
View File
@@ -20,6 +20,8 @@ import { Menu } from "~/components/ui/Menu"
import { useTranslation } from "next-i18next"
import { Tooltip } from "~/components/ui/Tooltip"
import { PatronButton } from "~/components/common/PatronButton"
import { Modal } from "~/components/ui/Modal"
import { SearchInput } from "~/components/common/SearchInput"
type HeaderLinkType = {
icon?: React.ReactNode
@@ -113,8 +115,20 @@ export const SiteHeader: React.FC<{
url: `/feed/xml`,
out: true,
},
{
text: "Search on this site",
icon: (
<span className="text-stone-400">
<i className="i-mingcute:search-line block text-2xl" />
</span>
),
onClick: () => setSearchOpen(true),
out: true,
},
]
const [searchOpen, setSearchOpen] = useState(false)
const avatarRef = useRef<HTMLImageElement>(null)
const bannerRef = useRef<HTMLImageElement | HTMLVideoElement>(null)
@@ -235,48 +249,55 @@ export const SiteHeader: React.FC<{
dropdown={
<div className="text-gray-600 bg-white rounded-lg ring-1 ring-zinc-100 shadow-md py-2 text-sm">
{moreMenuItems.map((item) => {
return (
<UniLink
key={item.text}
href={item.url}
className="h-10 flex w-full space-x-2 items-center px-3 hover:bg-hover"
>
<span className="fill-gray-500 flex w-4 h-4">
{item.icon}
</span>
<span>{t(item.text)}</span>
</UniLink>
)
if (!item.out) {
return (
<UniLink
key={item.text}
href={item.url}
className="h-10 flex w-full space-x-2 items-center px-3 hover:bg-hover"
>
<span className="fill-gray-500 flex w-4 h-4">
{item.icon}
</span>
<span>{t(item.text)}</span>
</UniLink>
)
}
})}
</div>
}
/>
</div>
<div className="xlog-site-more-out hidden sm:block">
{moreMenuItems.map((item) => {
if (item.out) {
return (
<Tooltip
label={t(item.text)}
key={item.text}
placement="bottom"
>
<Button
variant="text"
aria-label={item.text}
className="-mx-2"
onClick={() => window.open(item.url, "_blank")}
<div className="-mx-2 flex">
{moreMenuItems.map((item) => {
if (item.out) {
return (
<Tooltip
label={t(item.text)}
key={item.text}
placement="bottom"
>
<span className="fill-gray-500 flex w-6 h-6">
{item.icon}
</span>
</Button>
</Tooltip>
)
} else {
return null
}
})}
<Button
variant="text"
aria-label={item.text}
onClick={() =>
item.url
? window.open(item.url, "_blank")
: item.onClick?.()
}
>
<span className="fill-gray-500 flex w-6 h-6">
{item.icon}
</span>
</Button>
</Tooltip>
)
} else {
return null
}
})}
</div>
</div>
<div className="xlog-site-follow-button">
<FollowingButton site={site} />
@@ -311,6 +332,11 @@ export const SiteHeader: React.FC<{
</div>
</div>
</div>
<Modal open={searchOpen} setOpen={setSearchOpen}>
<div className="p-3">
<SearchInput noBorder={true} onSubmit={() => setSearchOpen(false)} />
</div>
</Modal>
</header>
)
}
+138
View File
@@ -0,0 +1,138 @@
import Link from "next/link"
import { useDate } from "~/hooks/useDate"
import { ExpandedNote, Notes } from "~/lib/types"
import { EmptyState } from "../ui/EmptyState"
import { useRouter } from "next/router"
import { Image } from "~/components/ui/Image"
import { Button } from "~/components/ui/Button"
import { useTranslation } from "next-i18next"
import { useEffect, useState } from "react"
export const SiteSearch: React.FC<{
postPages?: {
list: ExpandedNote[]
count: number
cursor: string | null
}[]
fetchNextPage: () => void
hasNextPage?: boolean
isFetchingNextPage?: boolean
}> = ({ postPages, fetchNextPage, hasNextPage, isFetchingNextPage }) => {
const router = useRouter()
const { t } = useTranslation(["common", "site"])
const date = useDate()
const [isMounted, setIsMounted] = useState(false)
useEffect(() => {
setIsMounted(true)
}, [])
if (!postPages?.length) return null
let currentLength = 0
return (
<>
{!postPages[0].count && <EmptyState />}
{!!postPages[0].count && (
<div className="xlog-posts space-y-8">
{postPages.map((posts) =>
posts.list.map((post) => {
currentLength++
return (
<Link
key={post.noteId}
href={`/${post.metadata.content.slug}`}
className="xlog-post sm:hover:bg-hover bg-white transition-all px-5 py-7 -mx-5 first:-mt-5 sm:rounded-xl flex flex-col sm:flex-row items-center"
>
<div className="flex-1 flex justify-center flex-col w-full min-w-0">
<h3 className="xlog-post-title text-2xl font-bold text-zinc-700">
{post.metadata.content.title}
</h3>
<div className="xlog-post-meta text-sm text-zinc-400 mt-1 space-x-4 flex items-center mr-8">
<time
dateTime={date.formatToISO(
post.metadata.content.date_published ||
post.createdAt,
)}
className="xlog-post-date whitespace-nowrap"
>
{date.formatDate(
post.metadata.content.date_published ||
post.createdAt,
undefined,
isMounted ? undefined : "America/Los_Angeles",
)}
</time>
{!!post.metadata.content.tags?.filter(
(tag) => tag !== "post" && tag !== "page",
).length && (
<span className="xlog-post-tags space-x-1 truncate min-w-0">
{post.metadata.content.tags
?.filter((tag) => tag !== "post" && tag !== "page")
.map((tag) => (
<span
className="hover:text-zinc-600"
key={tag}
onClick={(e) => {
e.preventDefault()
router.push(`/tag/${tag}`)
}}
>
#{tag}
</span>
))}
</span>
)}
<span className="xlog-post-views inline-flex items-center">
<i className="i-mingcute:eye-line mr-[2px]" />
<span>{post.metadata.content.views}</span>
</span>
</div>
<div
className="xlog-post-excerpt mt-3 text-zinc-500 line-clamp-2"
style={{
wordBreak: "break-word",
}}
>
{post.metadata.content.summary}
{post.metadata.content.summary && "..."}
</div>
</div>
{post.metadata.content.cover && (
<div className="xlog-post-cover flex items-center relative w-full sm:w-24 h-40 sm:h-24 mt-2 sm:ml-4 sm:mt-0">
<Image
className="object-cover rounded"
alt="cover"
fill={true}
src={post.metadata.content.cover}
></Image>
</div>
)}
</Link>
)
}),
)}
</div>
)}
{hasNextPage && (
<Button
className="mt-8 w-full bg-zinc-50 text-sm"
variant="text"
onClick={fetchNextPage}
isLoading={isFetchingNextPage}
aria-label="load more"
>
{t("load more", {
ns: "site",
name: t(
"post" + (postPages[0].total - currentLength > 1 ? "s" : ""),
),
count: postPages[0].total - currentLength,
})}
</Button>
)}
</>
)
}
+1
View File
@@ -12,6 +12,7 @@ const slugReservedWords = [
"sw.js",
"manifest.json",
"atom.xml",
"search",
]
export const checkSlugReservedWords = (word: string) => {
+27 -2
View File
@@ -1,5 +1,5 @@
import { notFound } from "~/lib/server-side-props"
import { PageVisibilityEnum, Notes, Note } from "~/lib/types"
import { PageVisibilityEnum, Notes, Note, ExpandedNote } from "~/lib/types"
import unidata from "~/queries/unidata.server"
import { indexer } from "@crossbell/indexer"
import { NoteMetadata } from "crossbell.js"
@@ -9,7 +9,7 @@ import type Unidata from "unidata.js"
import type { Contract } from "crossbell.js"
import { checkSlugReservedWords } from "~/lib/slug-reserved-words"
import { GeneralAccount } from "@crossbell/connect-kit"
import { expandUnidataNote } from "~/lib/expand-unit"
import { expandUnidataNote, expandCrossbellNote } from "~/lib/expand-unit"
export async function checkPageSlug(
input: {
@@ -296,6 +296,31 @@ export async function getPagesBySite(
return pages
}
export async function getSearchPagesBySite(input: {
characterId?: string
keyword?: string
cursor?: string
}) {
const result = await indexer.searchNotes(input.keyword || "", {
cursor: input.cursor,
characterId: input.characterId,
tags: ["post"],
sources: ["xlog"],
})
const list: ExpandedNote[] = await Promise.all(
result.list.map(async (page: any) => {
return await expandCrossbellNote(page, true)
}),
)
return {
list,
cursor: result.cursor,
count: result.count,
}
}
export async function getPage<TRender extends boolean = false>(
input: {
/** page slug or id, `site` is needed when `page` is a slug */
+73
View File
@@ -0,0 +1,73 @@
import { GetServerSideProps } from "next"
import { SiteSearch } from "~/components/site/SiteSearch"
import { SiteLayout } from "~/components/site/SiteLayout"
import { getServerSideProps as getLayoutServerSideProps } from "~/components/site/SiteLayout.server"
import { QueryClient } from "@tanstack/react-query"
import { useGetSearchPagesBySite } from "~/queries/page"
import type { ReactElement } from "react"
import { useGetSite } from "~/queries/site"
import { useRouter } from "next/router"
import { SearchInput } from "~/components/common/SearchInput"
import { useTranslation } from "next-i18next"
export const getServerSideProps: GetServerSideProps = async (ctx) => {
const queryClient = new QueryClient()
const domainOrSubdomain = ctx.params!.site as string
const { props: layoutProps } = await getLayoutServerSideProps(
ctx,
queryClient,
{
skipPages: true,
},
)
return {
props: {
...layoutProps,
domainOrSubdomain,
},
}
}
function SiteSearchPage({ domainOrSubdomain }: { domainOrSubdomain: string }) {
const site = useGetSite(domainOrSubdomain)
const router = useRouter()
const keyword = router.query.q as string
const { t } = useTranslation(["common"])
const posts = useGetSearchPagesBySite({
characterId: site.data?.metadata?.proof,
keyword,
})
return (
<>
<div className="sm:-mx-5">
<SearchInput value={keyword} />
</div>
<h2 className="mb-8 mt-5 text-zinc-500">
{posts.data?.pages?.[0].count || "0"} {t("results")}
</h2>
{posts.isLoading ? (
<>{t("Loading")}...</>
) : (
<SiteSearch
postPages={posts.data?.pages}
fetchNextPage={posts.fetchNextPage}
hasNextPage={posts.hasNextPage}
isFetchingNextPage={posts.isFetchingNextPage}
/>
)}
</>
)
}
SiteSearchPage.getLayout = (page: ReactElement) => {
return (
<SiteLayout useStat={true} type="index">
{page}
</SiteLayout>
)
}
export default SiteSearchPage
+15
View File
@@ -62,6 +62,21 @@ export const useGetPagesBySite = (
})
}
export const useGetSearchPagesBySite = (
input: Parameters<typeof pageModel.getSearchPagesBySite>[0],
) => {
return useInfiniteQuery({
queryKey: ["getSearchPagesBySite", input.characterId, input],
queryFn: async ({ pageParam }) => {
return pageModel.getSearchPagesBySite({
...input,
cursor: pageParam,
})
},
getNextPageParam: (lastPage) => lastPage.cursor || undefined,
})
}
export const useGetPage = (input: Parameters<typeof pageModel.getPage>[0]) => {
const unidata = useUnidata()
return useQuery(["getPage", input.page || input.pageId, input], async () => {