ファイル
btrc-hub/frontend/src/pages/posts/PostDetailPage.tsx
T

193 行
6.5 KiB
TypeScript

import { useMutation, useQuery, useQueryClient } from '@tanstack/react-query'
import { motion } from 'framer-motion'
import { useEffect, useRef } from 'react'
import { useParams } from 'react-router-dom'
import { useLocale } from '@/lib/useLocale'
import PostEditForm from '@/components/PostEditForm'
import PostEmbed from '@/components/PostEmbed'
import PostList from '@/components/PostList'
import TagDetailSidebar from '@/components/TagDetailSidebar'
import TabGroup, { Tab } from '@/components/common/TabGroup'
import MainArea from '@/components/layout/MainArea'
import { Button } from '@/components/ui/button'
import { toast } from '@/components/ui/use-toast'
import PageHead from '@/components/common/PageHead'
import { isApiError } from '@/lib/api'
import { fetchPost, toggleViewedFlg } from '@/lib/posts'
import { postsKeys, tagsKeys } from '@/lib/queryKeys'
import { useClientBehaviourSettings } from '@/lib/useClientBehaviourSettings'
import { canEditContent } from '@/lib/users'
import { cn } from '@/lib/utils'
import { useUITranslation } from '@/lib/useUITranslation'
import NotFound from '@/pages/NotFound'
import ServiceUnavailable from '@/pages/ServiceUnavailable'
import type { FC } from 'react'
import type { NiconicoViewerHandle, Post, User } from '@/types'
type Props = { user: User | null }
const PostDetailPage: FC<Props> = ({ user }) => {
const locale = useLocale ()
const { message, label } = useUITranslation ('posts')
const editable = canEditContent (user)
const behaviourSettings = useClientBehaviourSettings ()
const thumbnailMode = behaviourSettings.thumbnailMode ?? 'normal'
const animationMode = behaviourSettings.animation ?? 'normal'
const { id } = useParams ()
const heroLayoutId = animationMode === 'off' ? undefined : `page-${ id }`
const heroTransition =
animationMode === 'off'
? { duration: 0 }
: animationMode === 'reduced'
? { duration: .08, ease: 'linear' as const }
: { duration: .2, ease: 'easeOut' as const }
const postId = String (id ?? '')
const postKey = postsKeys.show (postId, locale)
const { data: post, isError: errorFlg, error } = useQuery ({
enabled: Boolean (id),
queryKey: postKey,
queryFn: () => fetchPost (postId, locale) })
const qc = useQueryClient ()
const embedRef = useRef<NiconicoViewerHandle> (null)
const status = (errorFlg && isApiError (error)) ? error.response?.status ?? 200 : 200
const changeViewedFlg = useMutation ({
mutationFn: async (next: boolean) => {
await toggleViewedFlg (postId, next)
return next
},
onMutate: async (next: boolean) => {
await qc.cancelQueries ({ queryKey: postKey })
const prev = qc.getQueryData<Post> (postKey)
qc.setQueryData (postKey,
(cur: Post | undefined) => cur ? { ...cur, viewed: next } : cur)
return { prev }
},
onError: (...[, , ctx]) => {
if (ctx?.prev)
qc.setQueryData (postKey, ctx.prev)
toast ({ title: label ('shared:messages.failed'),
description: label ('detail.networkFailed') })
},
onSuccess: () => {
qc.invalidateQueries ({ queryKey: postsKeys.root })} })
useEffect (() => {
scroll (0, 0)
}, [id])
switch (status)
{
case 404:
return <NotFound/>
case 503:
return <ServiceUnavailable/>
}
const viewedClass = (post?.viewed
? 'bg-blue-600 hover:bg-blue-700'
: 'bg-gray-500 hover:bg-gray-600')
return (
<div
data-sidebar-container
className="md:flex md:flex-1 overflow-y-auto md:overflow-y-hidden">
<PageHead title={post?.title || post?.url || message ('navigation:posts')}>
{(post?.thumbnail || post?.thumbnailBase) && (
<meta name="thumbnail" content={post.thumbnail! || post.thumbnailBase!}/>)}
</PageHead>
{post && <TagDetailSidebar post={post} className="hidden md:block"/>}
<MainArea className="relative" verticalContent={false}>
{post
? (
<>
{(post.childPosts ?? []).length > 0 && (
<div className="mb-4 bg-green-200 dark:bg-green-800 text-sm p-2 rounded-md">
<p>{label ('detail.children', { count: post.childPosts!.length })}</p>
<PostList posts={[{ ...post, childPosts: [{ } as Post] },
...post.childPosts!.map (p => ({
...p, parentPosts: [{ } as Post] }))]}/>
</div>)}
{(post.parentPosts ?? []).map (pp => {
const siblings = post.siblingPosts?.[String (pp.id) as `${ number }`]
if (!(siblings))
return
return (
<div
key={pp.id}
className="mb-4 bg-yellow-200 dark:bg-yellow-800 text-sm p-2 rounded-md">
<p>
{siblings.length > 1
? label ('detail.parentAndSiblings', { count: siblings.length - 1 })
: label ('detail.parent')}
</p>
<PostList posts={[{ ...pp, childPosts: [{ } as Post] },
...siblings.map (p => ({
...p, parentPosts: [{ } as Post] }))]}/>
</div>)
})}
{thumbnailMode !== 'off' && (post.thumbnail || post.thumbnailBase) && (
<motion.div
layoutId={heroLayoutId}
className="absolute top-4 left-4 w-[min(640px,calc(100vw-2rem))] h-[360px]
overflow-hidden rounded-xl pointer-events-none z-50"
initial={{ opacity: 1 }}
animate={{ opacity: 0 }}
transition={heroTransition}>
<img src={post.thumbnail || post.thumbnailBase || undefined}
alt={post.title || post.url}
title={post.title || post.url || undefined}
loading={thumbnailMode === 'light' ? 'lazy' : 'eager'}
decoding="async"
className="object-cover w-full h-full"/>
</motion.div>)}
<PostEmbed
ref={embedRef}
post={post}
onLoadComplete={() => embedRef.current?.play ()}/>
<Button onClick={() => changeViewedFlg.mutate (!(post.viewed))}
disabled={changeViewedFlg.isPending}
className={cn ('text-white', viewedClass)}>
{label (post.viewed ? 'detail.viewed' : 'detail.unviewed')}
</Button>
<TabGroup>
<Tab name={label ('shared:labels.relations')}>
{post.related.length > 0
? <PostList posts={post.related}/>
: label ('detail.emptyRelated')}
</Tab>
{editable && (
<Tab name={label ('shared:actions.edit')}>
<PostEditForm
post={post}
onSave={newPost => {
qc.setQueryData (postsKeys.show (postId, locale),
(prev: Post | undefined) => newPost ?? prev)
qc.invalidateQueries ({ queryKey: postsKeys.root })
qc.invalidateQueries ({ queryKey: tagsKeys.root })
}}/>
</Tab>)}
</TabGroup>
</>)
: label ('common:loading')}
</MainArea>
{post && <TagDetailSidebar post={post} sp className="md:hidden"/>}
</div>)
}
export default PostDetailPage