feat: renamed ArticalPage to component, added useParam for slug and reactivity

This commit is contained in:
Stepan Vladovskiy 2024-09-24 00:40:57 -03:00
parent fe76bb46e6
commit 343b71defd

View File

@ -1,6 +1,32 @@
import { RouteDefinition, RouteSectionProps, createAsync, useLocation } from '@solidjs/router' /**
* [slug].tsx
*
* # Dynamic Slug Route Handler
*
* ## Overview
*
* This file handles dynamic routing based on the `slug` parameter in the URL. Depending on the prefix of the slug, it renders different pages:
*
* - **Author Page**: If the `slug` starts with `@`, it renders the `AuthorPage` component for the specified author.
* - **Topic Page**: If the `slug` starts with `!`, it renders the `TopicPage` component for the specified topic.
* - **Article Page**: For all other slugs, it renders the `ArticlePageComponent`, displaying the full article details.
*
* ## Components
*
* - **SlugPage**: The main component that determines which page to render based on the `slug`.
* - **ArticlePageComponent**: Fetches and displays the detailed view of an article.
* - **AuthorPage**: Displays author-specific information (imported from `../author/[slug]/[...tab]`).
* - **TopicPage**: Displays topic-specific information (imported from `../topic/[slug]/[...tab]`).
*
* ## Data Fetching
*
* - **fetchShout**: Asynchronously fetches article data based on the `slug` using the `getShout` GraphQL query.
* - **createResource**: Utilized in `ArticlePageComponent` to fetch and manage article data reactively.**/
import { RouteDefinition, RouteSectionProps, useLocation, useParams } from '@solidjs/router'
import { HttpStatusCode } from '@solidjs/start' import { HttpStatusCode } from '@solidjs/start'
import { ErrorBoundary, Show, Suspense, createEffect, on, onMount } from 'solid-js' import { ErrorBoundary, Show, Suspense, createEffect, on, onMount, createResource } from 'solid-js'
import { FourOuFourView } from '~/components/Views/FourOuFour' import { FourOuFourView } from '~/components/Views/FourOuFour'
import { Loading } from '~/components/_shared/Loading' import { Loading } from '~/components/_shared/Loading'
import { gaIdentity } from '~/config' import { gaIdentity } from '~/config'
@ -16,7 +42,7 @@ import AuthorPage, { AuthorPageProps } from '../author/[slug]/[...tab]'
import TopicPage, { TopicPageProps } from '../topic/[slug]/[...tab]' import TopicPage, { TopicPageProps } from '../topic/[slug]/[...tab]'
const fetchShout = async (slug: string): Promise<Shout | undefined> => { const fetchShout = async (slug: string): Promise<Shout | undefined> => {
if (slug.startsWith('@')) return if (slug.startsWith('@') || slug.startsWith('!')) return
const shoutLoader = getShout({ slug }) const shoutLoader = getShout({ slug })
const result = await shoutLoader() const result = await shoutLoader()
return result return result
@ -43,67 +69,82 @@ export type SlugPageProps = {
topics: Topic[] topics: Topic[]
} }
export default function ArticlePage(props: RouteSectionProps<SlugPageProps>) { export default function SlugPage(props: RouteSectionProps<SlugPageProps>) {
if (props.params.slug.startsWith('@')) { const { t } = useLocalize()
const loc = useLocation()
const params = useParams()
const slug = createMemo(() => params.slug)
if (slug.startsWith('@')) {
console.debug('[routes] [slug]/[...tab] starts with @, render as author page') console.debug('[routes] [slug]/[...tab] starts with @, render as author page')
const patchedProps = { const patchedProps = {
...props, ...props,
params: { params: {
...props.params, ...props.params,
slug: props.params.slug.slice(1, props.params.slug.length) slug: slug.slice(1)
} }
} as RouteSectionProps<AuthorPageProps> } as RouteSectionProps<AuthorPageProps>
return <AuthorPage {...patchedProps} /> return <AuthorPage {...patchedProps} />
} }
if (props.params.slug.startsWith('!')) { if (slug.startsWith('!')) {
console.debug('[routes] [slug]/[...tab] starts with !, render as topic page') console.debug('[routes] [slug]/[...tab] starts with !, render as topic page')
const patchedProps = { const patchedProps = {
...props, ...props,
params: { params: {
...props.params, ...props.params,
slug: props.params.slug.slice(1, props.params.slug.length) slug: slug.slice(1)
} }
} as RouteSectionProps<TopicPageProps> } as RouteSectionProps<TopicPageProps>
return <TopicPage {...patchedProps} /> return <TopicPage {...patchedProps} />
} }
function ArticlePage(props: RouteSectionProps<ArticlePageProps>) { // Pass slug as a prop to ArticlePageComponent
return <ArticlePageComponent slug={slug()} {...props} />
}
function ArticlePageComponent(props: RouteSectionProps<SlugPageProps> & { slug: string }) {
const loc = useLocation() const loc = useLocation()
const { t } = useLocalize() const { t } = useLocalize()
const data = createAsync(async () => props.data?.article || (await fetchShout(props.params.slug))) const { slug } = props
onMount(async () => { // Define the fetcher function
if (gaIdentity && data()?.id) { const fetchArticle = async (slug: string): Promise<Shout | undefined> => {
try { return await fetchShout(slug)
await loadGAScript(gaIdentity)
initGA(gaIdentity)
} catch (error) {
console.warn('[routes] [slug]/[...tab] Failed to connect Google Analytics:', error)
} }
// Create a resource that fetches the article based on slug
const [article, { refetch, mutate }] = createResource(slug, fetchArticle)
// Handle Google Analytics
createEffect(() => {
const currentArticle = article()
if (gaIdentity && currentArticle?.id) {
loadGAScript(gaIdentity)
.then(() => initGA(gaIdentity))
.catch((error) => {
console.warn('[routes] [slug]/[...tab] Failed to connect Google Analytics:', error)
})
} }
}) })
createEffect( createEffect(() => {
on( const currentArticle = article()
data, if (currentArticle?.id) {
(a?: Shout) => {
if (!a?.id) return
window?.gtag?.('event', 'page_view', { window?.gtag?.('event', 'page_view', {
page_title: a.title, page_title: currentArticle.title,
page_location: window?.location.href || '', page_location: window?.location.href || '',
page_path: loc.pathname page_path: loc.pathname
}) })
}, }
{ defer: true } })
)
)
return ( return (
<ErrorBoundary fallback={() => <HttpStatusCode code={500} />}> <ErrorBoundary fallback={() => <HttpStatusCode code={500} />}>
<Suspense fallback={<Loading />}> <Suspense fallback={<Loading />}>
<Show <Show
when={data()?.id} when={article()}
fallback={ fallback={
<PageLayout isHeaderFixed={false} hideFooter={true} title={t('Nothing is here')}> <PageLayout isHeaderFixed={false} hideFooter={true} title={t('Nothing is here')}>
<FourOuFourView /> <FourOuFourView />
@ -112,21 +153,19 @@ export default function ArticlePage(props: RouteSectionProps<SlugPageProps>) {
} }
> >
<PageLayout <PageLayout
title={`${t('Discours')}${data()?.title ? ' :: ' : ''}${data()?.title || ''}`} title={`${t('Discours')}${article()?.title ? ' :: ' : ''}${article()?.title || ''}`}
desc={descFromBody(data()?.body || '')} desc={descFromBody(article()?.body || '')}
keywords={keywordsFromTopics(data()?.topics as { title: string }[])} keywords={keywordsFromTopics(article()?.topics as { title: string }[])}
headerTitle={data()?.title || ''} headerTitle={article()?.title || ''}
slug={data()?.slug} slug={article()?.slug}
cover={data()?.cover || ''} cover={article()?.cover || ''}
> >
<ReactionsProvider> <ReactionsProvider>
<FullArticle article={data() as Shout} /> <FullArticle article={article() as Shout} />
</ReactionsProvider> </ReactionsProvider>
</PageLayout> </PageLayout>
</Show> </Show>
</Suspense> </Suspense>
</ErrorBoundary> </ErrorBoundary>
) )
}
return <ArticlePage {...props} />
} }