feat: use app router for site home

This commit is contained in:
DIYgod
2023-05-07 17:12:17 +01:00
parent d3f83e3090
commit 5d9194787b
26 changed files with 422 additions and 180 deletions
+157
View File
@@ -0,0 +1,157 @@
import { notFound } from "next/navigation"
import { Hydrate, dehydrate } from "@tanstack/react-query"
import { BlockchainInfo } from "~/components/common/BlockchainInfo"
import { Style } from "~/components/common/Style"
import { BackToTopFAB } from "~/components/site/BackToTopFAB"
import { SiteFooter } from "~/components/site/SiteFooter"
import { SiteHeader } from "~/components/site/SiteHeader"
import { FABContainer } from "~/components/ui/FAB"
import getQueryClient from "~/lib/query-client"
import { ExpandedNote } from "~/lib/types"
import { cn } from "~/lib/utils"
import { fetchGetPage } from "~/queries/page.server"
import {
fetchGetSite,
prefetchGetSiteSubscriptions,
prefetchGetSiteToSubscriptions,
} from "~/queries/site.server"
export default async function SiteLayout({
children,
params,
}: {
children?: React.ReactNode
params: {
site: string
page?: string
tag?: string
}
}) {
const queryClient = getQueryClient()
const site = await fetchGetSite(params.site, queryClient)
let page
if (site?.characterId) {
const result = await Promise.all([
prefetchGetSiteSubscriptions(
{
characterId: site.characterId,
},
queryClient,
),
prefetchGetSiteToSubscriptions(
{
characterId: site.characterId,
},
queryClient,
),
new Promise<ExpandedNote | null>(async (resolve, reject) => {
if (params.page) {
try {
const page = await fetchGetPage(
{
characterId: site.characterId,
slug: params.page,
useStat: true,
},
queryClient,
)
if (
!page ||
new Date(page!.metadata?.content?.date_published || "") >
new Date()
) {
reject(notFound())
} else {
resolve(page)
}
} catch (error) {
reject(error)
}
} else {
// if (!options?.skipPages) {
// await prefetchGetPagesBySite(
// {
// characterId: site.characterId,
// ...(options?.limit && { limit: options.limit }),
// type: "post",
// visibility: PageVisibilityEnum.Published,
// ...(params.tag && { tags: [params.tag] }),
// ...(options?.useStat && {
// useStat: true,
// }),
// },
// queryClient,
// )
// }
resolve(null)
}
}),
])
page = result[2]
} else {
notFound()
}
const dehydratedState = dehydrate(queryClient)
return (
<Hydrate state={dehydratedState}>
<div
className={cn()
// TODO
// {
// "xlog-user": true,
// "xlog-user-login": isConnected,
// "xlog-user-site-owner": userRole?.data === "owner",
// "xlog-user-site-operator": userRole?.data === "operator",
// "xlog-user-site-follower": subscription?.data,
// "xlog-user-post-liker": isLiked,
// "xlog-user-post-minter": isMint?.data?.count,
// },
// `xlog-page-${type}`,
}
>
{/* <SEOHead
title={title || tag || page.data?.metadata?.content?.title || ""}
siteName={site.data?.metadata?.content?.name || ""}
description={
page.data?.metadata?.content?.summary ??
site.data?.metadata?.content?.bio?.replace(/<[^>]*>/g, "")
}
image={
page.data?.metadata?.content?.cover ||
getUserContentsUrl(site.data?.metadata?.content?.avatars?.[0])
}
icon={getUserContentsUrl(site.data?.metadata?.content?.avatars?.[0])}
site={domainOrSubdomain}
/> */}
<Style content={site?.metadata?.content?.css} />
{site && <SiteHeader site={site} />}
<div
className={cn(
"max-w-screen-md mx-auto px-5 pt-12 relative",
page && `xlog-post-id-${page.characterId}-${page.noteId}`,
page?.metadata?.content?.tags?.map((tag) => `xlog-post-tag-${tag}`),
)}
>
{children}
</div>
{site && (
<div className="max-w-screen-md mx-auto pt-12 pb-10">
<BlockchainInfo site={site} page={page || undefined} />
</div>
)}
<SiteFooter site={site || undefined} />
<FABContainer>
<BackToTopFAB />
</FABContainer>
</div>
</Hydrate>
)
}
+38
View File
@@ -0,0 +1,38 @@
import { Hydrate, dehydrate } from "@tanstack/react-query"
import SiteHome from "~/components/site/SiteHome"
import getQueryClient from "~/lib/query-client"
import { PageVisibilityEnum } from "~/lib/types"
import { prefetchGetPagesBySite } from "~/queries/page.server"
import { fetchGetSite } from "~/queries/site.server"
async function SiteIndexPage({
params,
}: {
params: {
site: string
}
}) {
const queryClient = getQueryClient()
const site = await fetchGetSite(params.site, queryClient)
prefetchGetPagesBySite(
{
characterId: site?.characterId,
type: "post",
visibility: PageVisibilityEnum.Published,
useStat: true,
},
queryClient,
)
const dehydratedState = dehydrate(queryClient)
return (
<Hydrate state={dehydratedState}>
<SiteHome handle={params.site} />
</Hydrate>
)
}
export default SiteIndexPage
+3 -2
View File
@@ -1,9 +1,10 @@
import { useTranslation } from "next-i18next"
"use client"
import { Disclosure } from "@headlessui/react"
import { BlockchainIcon } from "~/components/icons/BlockchainIcon"
import { CSB_SCAN } from "~/lib/env"
import { useTranslation } from "~/lib/i18n/client"
import { toCid, toGateway, toIPFS } from "~/lib/ipfs-parser"
import { ExpandedCharacter, ExpandedNote } from "~/lib/types"
import { cn } from "~/lib/utils"
@@ -13,7 +14,7 @@ export const BlockchainInfo: React.FC<{
site?: ExpandedCharacter
page?: ExpandedNote
}> = ({ site, page }) => {
const { t } = useTranslation(["common", "site"])
const { t } = useTranslation("common")
const ipfs = (page ? page.metadata?.uri : site?.metadata?.uri) || ""
const greenfieldId = useGetGreenfieldId(toCid(ipfs))
+2
View File
@@ -1,3 +1,5 @@
"use client"
import { useEffect, useState } from "react"
import { throttle } from "~/lib/utils"
+2 -9
View File
@@ -1,10 +1,9 @@
import { Trans } from "next-i18next"
import Script from "next/script"
import { useEffect, useState } from "react"
import { Logo } from "~/components/common/Logo"
import { Platform } from "~/components/site/Platform"
import { SITE_URL } from "~/lib/env"
import { Trans } from "~/lib/i18n"
import { ExpandedCharacter } from "~/lib/types"
import { DarkModeSwitch } from "../common/DarkModeSwitch"
@@ -13,19 +12,13 @@ import { UniLink } from "../ui/UniLink"
export const SiteFooter: React.FC<{
site?: ExpandedCharacter
}> = ({ site }) => {
const [logoType, setLogoType] = useState<"svg" | "png" | "lottie">("svg")
useEffect(() => {
setLogoType("lottie")
}, [])
const LogoWithLink = () => {
return (
<UniLink
href={SITE_URL}
className="inline-flex items-center align-text-top mx-1"
>
<Logo type={logoType} width={20} height={20} autoplay={false} />
<Logo type="lottie" width={20} height={20} autoplay={false} />
</UniLink>
)
}
+6 -4
View File
@@ -1,7 +1,8 @@
"use client"
import chroma from "chroma-js"
import { FastAverageColor } from "fast-average-color"
import { useTranslation } from "next-i18next"
import { useRouter } from "next/router"
import { usePathname } from "next/navigation"
import { MutableRefObject, RefObject, useEffect, useRef, useState } from "react"
import { XCharLogo, XFeedLogo } from "@crossbell/ui"
@@ -17,6 +18,7 @@ import { Modal } from "~/components/ui/Modal"
import { Tooltip } from "~/components/ui/Tooltip"
import { useIsDark } from "~/hooks/useDarkMode"
import { CSB_IO, CSB_SCAN, CSB_XCHAR } from "~/lib/env"
import { useTranslation } from "~/lib/i18n/client"
import { ExpandedCharacter } from "~/lib/types"
import { getUserContentsUrl } from "~/lib/user-contents"
import { cn } from "~/lib/utils"
@@ -37,9 +39,9 @@ type HeaderLinkType = {
const fac = new FastAverageColor()
const HeaderLink: React.FC<{ link: HeaderLinkType }> = ({ link }) => {
const router = useRouter()
const pathname = usePathname()
const { t } = useTranslation("site")
const active = router.asPath === link.url
const active = pathname === link.url // TODO
return (
<UniLink
href={link.url}
+28 -26
View File
@@ -1,29 +1,30 @@
import { useTranslation } from "next-i18next"
"use client"
import Link from "next/link"
import { useRouter } from "next/router"
import { useRouter } from "next/navigation"
import { useEffect, useState } from "react"
import type { InfiniteData } from "@tanstack/react-query"
import { Button } from "~/components/ui/Button"
import { EmptyState } from "~/components/ui/EmptyState"
import { Image } from "~/components/ui/Image"
import { useDate } from "~/hooks/useDate"
import { getSlugUrl } from "~/lib/helpers"
import { ExpandedNote } from "~/lib/types"
import { useTranslation } from "~/lib/i18n/client"
import { PageVisibilityEnum } from "~/lib/types"
import { useGetPagesBySiteLite } from "~/queries/page"
import { useGetSite } from "~/queries/site"
import { EmptyState } from "../ui/EmptyState"
export const SiteHome: React.FC<{
posts?: InfiniteData<{
list: ExpandedNote[]
count: number
}>
fetchNextPage: () => void
hasNextPage?: boolean
isFetchingNextPage?: boolean
}> = ({ posts, fetchNextPage, hasNextPage, isFetchingNextPage }) => {
export default function SiteHome({ handle }: { handle: string }) {
const router = useRouter()
const { t } = useTranslation(["common", "site"])
const site = useGetSite(handle)
const posts = useGetPagesBySiteLite({
characterId: site.data?.characterId,
type: "post",
visibility: PageVisibilityEnum.Published,
useStat: true,
})
const { t } = useTranslation("site")
const date = useDate()
const [isMounted, setIsMounted] = useState(false)
@@ -32,16 +33,16 @@ export const SiteHome: React.FC<{
setIsMounted(true)
}, [])
if (!posts?.pages?.length) return null
if (!posts.data?.pages?.length) return null
let currentLength = 0
return (
<>
{!posts.pages[0].count && <EmptyState />}
{!!posts.pages[0].count && (
{!posts.data.pages[0].count && <EmptyState />}
{!!posts.data.pages[0].count && (
<div className="xlog-posts space-y-8">
{posts.pages.map((posts) =>
{posts.data.pages.map((posts) =>
posts.list.map((post) => {
currentLength++
return (
@@ -127,20 +128,21 @@ export const SiteHome: React.FC<{
)}
</div>
)}
{hasNextPage && (
{posts.hasNextPage && (
<Button
className="mt-8 w-full bg-zinc-50 text-sm"
variant="text"
onClick={fetchNextPage}
isLoading={isFetchingNextPage}
onClick={() => posts.fetchNextPage()}
isLoading={posts.isFetchingNextPage}
aria-label="load more"
>
{t("load more", {
ns: "site",
name: t(
"post" + (posts?.pages[0].count - currentLength > 1 ? "s" : ""),
"post" +
(posts.data?.pages[0].count - currentLength > 1 ? "s" : ""),
),
count: posts?.pages[0].count - currentLength,
count: posts.data?.pages[0].count - currentLength,
})}
</Button>
)}
+2
View File
@@ -1,3 +1,5 @@
"use client"
import React, { memo } from "react"
import { cn } from "~/lib/utils"
+2
View File
@@ -1,3 +1,5 @@
"use client"
import React, { FC, PropsWithChildren, useEffect, useState } from "react"
import { useGetState } from "~/hooks/useGetState"
+2 -1
View File
@@ -8,9 +8,10 @@ import localizedFormat from "dayjs/plugin/localizedFormat"
import relativeTime from "dayjs/plugin/relativeTime"
import tz from "dayjs/plugin/timezone"
import utc from "dayjs/plugin/utc"
import { useTranslation } from "next-i18next"
import { useMemo } from "react"
import { useTranslation } from "~/lib/i18n/client"
dayjs.extend(localizedFormat)
dayjs.extend(utc)
dayjs.extend(tz)
+42
View File
@@ -0,0 +1,42 @@
import dayjs from "dayjs"
import "dayjs/locale/en"
import "dayjs/locale/ja"
import "dayjs/locale/zh"
import "dayjs/locale/zh-tw"
import duration from "dayjs/plugin/duration"
import localizedFormat from "dayjs/plugin/localizedFormat"
import relativeTime from "dayjs/plugin/relativeTime"
import tz from "dayjs/plugin/timezone"
import utc from "dayjs/plugin/utc"
import { useMemo } from "react"
import { useTranslation } from "~/lib/i18n"
dayjs.extend(localizedFormat)
dayjs.extend(utc)
dayjs.extend(tz)
dayjs.extend(duration)
dayjs.extend(relativeTime)
export async function useDate() {
const { i18n } = await useTranslation()
const memoizedDateUtils = useMemo(() => {
dayjs.locale(i18n.resolvedLanguage)
return {
dayjs,
formatDate: (date: string | Date, format = "ll", timezone?: string) => {
return dayjs(date).tz(timezone).format(format)
},
formatToISO: (date: string | Date) => {
return dayjs(date || undefined).toISOString()
},
inLocalTimezone: (date: string | Date) => {
return dayjs(date).tz().toDate()
},
}
}, [i18n.resolvedLanguage])
return memoizedDateUtils
}
+1 -1
View File
@@ -1,4 +1,4 @@
import { NoteEntity } from "crossbell.js"
import type { NoteEntity } from "crossbell.js"
import { ExpandedCharacter, ExpandedNote } from "~/lib/types"
+2 -2
View File
@@ -9,7 +9,7 @@ import {
import { useLang } from "~/hooks/useLang"
import { getOptions } from "./settings"
import { defaultNS, getOptions } from "./settings"
i18next
.use(initReactI18next)
@@ -23,7 +23,7 @@ i18next
...getOptions(),
})
export function useTranslation(ns: string) {
export function useTranslation(ns: string = defaultNS) {
const { lang } = useLang()
if (i18next.resolvedLanguage !== lang) {
i18next.changeLanguage(lang)
+2 -2
View File
@@ -5,7 +5,7 @@ import { initReactI18next } from "react-i18next/initReactI18next"
import { useAcceptLang } from "~/hooks/useAcceptLang"
import { getOptions } from "./settings"
import { defaultNS, getOptions } from "./settings"
const initI18next = async (lng: string, ns: string) => {
const i18nInstance = createInstance()
@@ -21,7 +21,7 @@ const initI18next = async (lng: string, ns: string) => {
return i18nInstance
}
export async function useTranslation(ns: string) {
export async function useTranslation(ns: string = defaultNS) {
const lang = useAcceptLang()
const i18nextInstance = await initI18next(lang, ns)
return {
+1 -1
View File
@@ -1,4 +1,4 @@
import { CharacterEntity, NoteEntity } from "crossbell.js"
import type { CharacterEntity, NoteEntity } from "crossbell.js"
export type Site = {
id: string
+1 -1
View File
@@ -78,7 +78,7 @@ export default async function middleware(req: NextRequest) {
if (tenant?.subdomain) {
const url = req.nextUrl.clone()
url.pathname = `/_site/${tenant?.subdomain}${url.pathname}`
url.pathname = `/site/${tenant?.subdomain}${url.pathname}`
return NextResponse.rewrite(url)
}
+38 -37
View File
@@ -371,45 +371,46 @@ export function useGetSummary(input: { cid?: string; lang?: string }) {
})
}
export function useGetMirrorXyz(input: { address?: string }) {
return useQuery(["getMirror", input.address], async () => {
const { getDefaultSlug } = await import("~/lib/default-slug")
// TODO
// export function useGetMirrorXyz(input: { address?: string }) {
// return useQuery(["getMirror", input.address], async () => {
// const { getDefaultSlug } = await import("~/lib/default-slug")
if (!input.address) {
return null
}
const response = await (
await fetch(
"/api/import/mirror.xyz?" +
new URLSearchParams({
...input,
} as any),
)
).json()
// if (!input.address) {
// return null
// }
// const response = await (
// await fetch(
// "/api/import/mirror.xyz?" +
// new URLSearchParams({
// ...input,
// } as any),
// )
// ).json()
return response?.data?.projectFeed?.posts?.map((post: any) => {
return {
title: post.title,
date_published: new Date(
post.publishedAtTimestamp * 1000,
).toISOString(),
slug: getDefaultSlug(post.title, post.digest),
tags: ["Mirror.xyz"],
content: post.body,
external_urls: [`https://mirror.xyz/${input.address}/${post.digest}`],
}
}) as {
title: string
type: string
size: number
date_published: string
slug: string
tags: string[]
content: string
external_urls: string[]
}[]
})
}
// return response?.data?.projectFeed?.posts?.map((post: any) => {
// return {
// title: post.title,
// date_published: new Date(
// post.publishedAtTimestamp * 1000,
// ).toISOString(),
// slug: getDefaultSlug(post.title, post.digest),
// tags: ["Mirror.xyz"],
// content: post.body,
// external_urls: [`https://mirror.xyz/${input.address}/${post.digest}`],
// }
// }) as {
// title: string
// type: string
// size: number
// date_published: string
// slug: string
// tags: string[]
// content: string
// external_urls: string[]
// }[]
// })
// }
export function useCheckMirror(characterId?: number) {
return useQuery(["checkMirror", characterId], async () => {