Skip to content

Commit

Permalink
feat: edge config all
Browse files Browse the repository at this point in the history
  • Loading branch information
Innei committed Jul 9, 2023
1 parent ea0db85 commit d7714df
Show file tree
Hide file tree
Showing 11 changed files with 126 additions and 33 deletions.
12 changes: 9 additions & 3 deletions src/app/(home)/page.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -19,14 +19,16 @@ import {
softBouncePrest,
softSpringPreset,
} from '~/constants/spring'
import { useConfig } from '~/hooks/data/use-config'
import { isDev } from '~/lib/env'
import { clsxm } from '~/lib/helper'
import { noopObj } from '~/lib/noop'
import { apiClient } from '~/lib/request'
import { routeBuilder, Routes } from '~/lib/route-builder'
import { springScrollToTop } from '~/lib/scroller'
import { useAggregationSelector } from '~/providers/root/aggregation-data-provider'
import {
useAggregationSelector,
useAppConfigSelector,
} from '~/providers/root/aggregation-data-provider'

import { useHomeQueryData } from './query'

Expand Down Expand Up @@ -110,7 +112,11 @@ const TwoColumnLayout = ({
}

const Welcome = () => {
const { title, description } = useConfig().hero
const { title, description } = useAppConfigSelector((config) => {
return {
...config.hero,
}
})!
const siteOwner = useAggregationSelector((agg) => agg.user)
const { avatar, socialIds } = siteOwner || {}

Expand Down
10 changes: 6 additions & 4 deletions src/app/api/bilibili/check_live/route.ts
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
import axios from 'axios'
import type { NextRequest } from 'next/server'
import type { BLUser } from './types/user'

import { appConfig } from '~/app.config'
import { NextServerResponse } from '~/lib/edge-function.server'
import { getQueryClient } from '~/lib/query-client.server'

Expand All @@ -10,9 +10,11 @@ const headers = {
'User-Agent': `Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/106.0.0.0 Safari/537.36 Shiro`,
}
export const runtime = 'edge'
export const GET = async () => {
const liveId = appConfig.module.bilibili.liveId

export const GET = async (req: NextRequest) => {
const liveId = req.nextUrl.searchParams.get('liveId')
if (!liveId) {
return new NextServerResponse().status(400).end()
}
const queryClient = getQueryClient()
const res = await queryClient.fetchQuery({
queryKey: ['bilibili-live', liveId],
Expand Down
32 changes: 32 additions & 0 deletions src/app/config.d.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,32 @@
export interface AppConfig {
site: Site
hero: Hero
module: Module
}
export interface Site {
favicon: string
}
export interface Hero {
title: Title
description: string
}
export interface Title {
template: TemplateItem[]
}
export interface TemplateItem {
type: string
text?: string
class?: string
}
export interface Module {
donate: Donate
bilibili: Bilibili
}
export interface Donate {
enable: boolean
link: string
qrcode: string[]
}
export interface Bilibili {
liveId: number
}
15 changes: 12 additions & 3 deletions src/app/layout.tsx
Original file line number Diff line number Diff line change
@@ -1,13 +1,15 @@
import '../styles/index.css'

import { Analytics } from '@vercel/analytics/react'
import { cache } from 'react'
import { ToastContainer } from 'react-toastify'
import type { AggregateRoot } from '@mx-space/api-client'
import type { AppConfig } from './config'

import { ClerkProvider } from '@clerk/nextjs'
import { get } from '@vercel/edge-config'

import PKG from '~/../package.json'
import { appConfig } from '~/app.config'
import { Root } from '~/components/layout/root/Root'
import { TocAutoScroll } from '~/components/widgets/toc/TocAutoScroll'
import { attachUA } from '~/lib/attach-ua'
Expand All @@ -24,12 +26,18 @@ import { init } from './init'
const { version } = PKG
init()

const getAppConfig = cache(() => {
return get('config') as Promise<AppConfig>
})

let aggregationData: AggregateRoot | null = null
export const generateMetadata = defineMetadata(async (_, getData) => {
const fetchedData = aggregationData ?? (await getData())
aggregationData = fetchedData
const { seo, url, user } = fetchedData

const config = getAppConfig()

return {
metadataBase: new URL(url.webUrl),
title: {
Expand All @@ -40,7 +48,7 @@ export const generateMetadata = defineMetadata(async (_, getData) => {
keywords: seo.keywords?.join(',') || '',
icons: [
{
url: appConfig.site.favicon,
url: config.site.favicon,
type: 'image/svg+xml',
sizes: 'any',
},
Expand Down Expand Up @@ -102,6 +110,7 @@ export default async function RootLayout(props: Props) {

aggregationData = data

const appConfig = await getAppConfig()
return (
// <ClerkProvider localization={ClerkZhCN}>
<ClerkProvider>
Expand All @@ -113,7 +122,7 @@ export default async function RootLayout(props: Props) {
className={`${sansFont.variable} ${serifFont.variable} m-0 h-full p-0 font-sans`}
>
<Providers>
<AggregationProvider aggregationData={data} />
<AggregationProvider aggregationData={data} appConfig={appConfig} />

<Root>{children}</Root>

Expand Down
8 changes: 4 additions & 4 deletions src/components/layout/header/internal/AnimatedLogo.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -7,9 +7,9 @@ import { useRouter } from 'next/navigation'

import { getAdminUrl, isLogged, useViewport } from '~/atoms'
import { useSingleAndDoubleClick } from '~/hooks/common/use-single-double-click'
import { useConfig } from '~/hooks/data/use-config'
import { Routes } from '~/lib/route-builder'
import { toast } from '~/lib/toast'
import { useAppConfigSelector } from '~/providers/root/aggregation-data-provider'

import { Activity } from './Activity'
import { useHeaderMetaShouldShow } from './hooks'
Expand All @@ -22,9 +22,9 @@ const TapableLogo = () => {
queryKey: ['live-check'],
enabled: false,
})
const {
module: { bilibili: { liveId } = {} },
} = useConfig()

const { liveId } = useAppConfigSelector((config) => config.module.bilibili)!

const goLive = useCallback(() => {
window.open(`https://live.bilibili.com/${liveId}`)
}, [liveId])
Expand Down
9 changes: 7 additions & 2 deletions src/components/layout/header/internal/SiteOwnerAvatar.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -5,21 +5,26 @@ import { useCallback } from 'react'
import Image from 'next/image'

import { clsxm } from '~/lib/helper'
import { useAggregationSelector } from '~/providers/root/aggregation-data-provider'
import {
useAggregationSelector,
useAppConfigSelector,
} from '~/providers/root/aggregation-data-provider'

export const SiteOwnerAvatar: Component = ({ className }) => {
const avatar = useAggregationSelector((data) => data.user.avatar)
const liveId = useAppConfigSelector((config) => config.module.bilibili.liveId)

const { data: isLiving } = useQuery({
queryKey: ['live-check'],
queryFn: () =>
fetch('/api/bilibili/check_live')
fetch(`/api/bilibili/check_live?liveId=${liveId}`)
.then((res) => res.json())
.catch(() => null),
select: useCallback((data: any) => {
return !!data
}, []),
refetchInterval: 1000 * 60,
enabled: !!liveId,
meta: {
persist: false,
},
Expand Down
11 changes: 3 additions & 8 deletions src/components/widgets/shared/AsideDonateButton.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -6,8 +6,8 @@ import type { HTMLMotionProps } from 'framer-motion'
import { MotionButtonBase } from '~/components/ui/button'
import { DialogOverlay } from '~/components/ui/dlalog/DialogOverlay'
import { useIsClient } from '~/hooks/common/use-is-client'
import { useConfig } from '~/hooks/data/use-config'
import { clsxm } from '~/lib/helper'
import { useAppConfigSelector } from '~/providers/root/aggregation-data-provider'

// TODO this component only use once in current page.
const positionAtom = atom({
Expand All @@ -18,9 +18,7 @@ const overlayShowAtom = atom(false)

export const AsideDonateButton = () => {
const isClient = useIsClient()
const {
module: { donate },
} = useConfig()
const donate = useAppConfigSelector((config) => config.module.donate)!

const overlayOpen = useAtomValue(overlayShowAtom)

Expand Down Expand Up @@ -103,10 +101,7 @@ const DonateButtonInternal: Component<HTMLMotionProps<'button'>> = ({

...props
}) => {
const {
module: { donate },
} = useConfig()

const donate = useAppConfigSelector((config) => config.module.donate)
if (!donate) return null
return (
<MotionButtonBase
Expand Down
4 changes: 0 additions & 4 deletions src/hooks/data/use-config.ts

This file was deleted.

6 changes: 2 additions & 4 deletions src/lib/url-builder.ts
Original file line number Diff line number Diff line change
Expand Up @@ -6,13 +6,11 @@ import type {
} from '@mx-space/api-client'

import { isDev } from '~/lib/env'
import { aggregationDataAtom } from '~/providers/root/aggregation-data-provider'

import { jotaiStore } from './store'
import { getAggregationData } from '~/providers/root/aggregation-data-provider'

export function urlBuilder(path = '') {
if (isDev) return new URL(path, 'http://localhost:2323')
return new URL(path, jotaiStore.get(aggregationDataAtom)?.url.webUrl)
return new URL(path, getAggregationData()?.url.webUrl)
}

function isPostModel(model: any): model is PostModel {
Expand Down
31 changes: 30 additions & 1 deletion src/providers/root/aggregation-data-provider.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@ import { useCallback, useEffect, useRef } from 'react'
import { atom, useAtomValue } from 'jotai'
import { selectAtom } from 'jotai/utils'
import type { AggregateRoot } from '@mx-space/api-client'
import type { AppConfig } from '~/app/config'
import type { FC, PropsWithChildren } from 'react'

import { fetchAppUrl } from '~/atoms'
Expand All @@ -12,16 +13,27 @@ import { useBeforeMounted } from '~/hooks/common/use-before-mounted'
import { jotaiStore } from '~/lib/store'

export const aggregationDataAtom = atom<null | AggregateRoot>(null)
const appConfigAtom = atom<AppConfig | null>(null)

export const AggregationProvider: FC<
PropsWithChildren<{
aggregationData: AggregateRoot
appConfig: AppConfig
}>
> = ({ children, aggregationData }) => {
> = ({ children, aggregationData, appConfig }) => {
useBeforeMounted(() => {
if (!aggregationData) return
jotaiStore.set(aggregationDataAtom, aggregationData)
})
useBeforeMounted(() => {
if (!appConfig) return
jotaiStore.set(appConfigAtom, appConfig)
})

useEffect(() => {
if (!appConfig) return
jotaiStore.set(appConfigAtom, appConfig)
}, [appConfig])

useEffect(() => {
if (!aggregationData) return
Expand Down Expand Up @@ -62,4 +74,21 @@ export const useAggregationSelector = <T,>(
),
)

export const useAppConfigSelector = <T,>(
selector: (atomValue: AppConfig) => T,
deps: any[] = [],
): T | null =>
useAtomValue(
// @ts-ignore
selectAtom(
appConfigAtom,
useCallback(
(atomValue) => (!atomValue ? null : selector(atomValue)),
deps,
),
),
)

export const getAggregationData = () => jotaiStore.get(aggregationDataAtom)

export const getAppConfig = () => jotaiStore.get(appConfigAtom)
21 changes: 21 additions & 0 deletions tailwind.config.ts
Original file line number Diff line number Diff line change
Expand Up @@ -169,6 +169,27 @@ const UIKitColors = {
const twConfig: Config = {
content: ['./src/**/*.{js,jsx,ts,tsx}'],
darkMode: ['class', '[data-theme="dark"]'],
safelist: [
'font-light',
'text-3xl',
'rounded',
'p-1',
'bg-gray-200',
'dark:bg-gray-800/0',
'hover:dark:bg-gray-800/100',
'bg-opacity-0',
'hover:bg-opacity-100',
'transition-background',

'w-[1px]',
'h-8',
'-bottom-2',
'bg-gray-800/80',
'dark:bg-gray-200/80',
'group-hover:opacity-100',
'transition-opacity',
'group-hover:animation-blink',
],
theme: {
// colors: createVariableColors(twColors),

Expand Down

0 comments on commit d7714df

Please sign in to comment.