ぼざクリタグ広場 https://hub.nizika.monster
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
 
 
 
 

189 lines
5.7 KiB

  1. import { useMutation, useQuery, useQueryClient } from '@tanstack/react-query'
  2. import { motion } from 'framer-motion'
  3. import { useEffect, useRef, useState } from 'react'
  4. import { Helmet } from 'react-helmet-async'
  5. import { useParams } from 'react-router-dom'
  6. import PostEditForm from '@/components/PostEditForm'
  7. import PostEmbed from '@/components/PostEmbed'
  8. import PostList from '@/components/PostList'
  9. import TagDetailSidebar from '@/components/TagDetailSidebar'
  10. import TabGroup, { Tab } from '@/components/common/TabGroup'
  11. import MainArea from '@/components/layout/MainArea'
  12. import { Button } from '@/components/ui/button'
  13. import { toast } from '@/components/ui/use-toast'
  14. import { SITE_TITLE } from '@/config'
  15. import { isApiError } from '@/lib/api'
  16. import { fetchPost, toggleViewedFlg } from '@/lib/posts'
  17. import { postsKeys, tagsKeys } from '@/lib/queryKeys'
  18. import { cn } from '@/lib/utils'
  19. import NotFound from '@/pages/NotFound'
  20. import ServiceUnavailable from '@/pages/ServiceUnavailable'
  21. import type { FC } from 'react'
  22. import type { NiconicoViewerHandle, Post, User } from '@/types'
  23. type Props = { user: User | null }
  24. const PostDetailPage: FC<Props> = ({ user }) => {
  25. const { id } = useParams ()
  26. const postId = String (id ?? '')
  27. const postKey = postsKeys.show (postId)
  28. const { data: post, isError: errorFlg, error } = useQuery ({
  29. enabled: Boolean (id),
  30. queryKey: postKey,
  31. queryFn: () => fetchPost (postId) })
  32. const qc = useQueryClient ()
  33. const embedRef = useRef<NiconicoViewerHandle> (null)
  34. const [status, setStatus] = useState (200)
  35. const changeViewedFlg = useMutation ({
  36. mutationFn: async (next: boolean) => {
  37. await toggleViewedFlg (postId, next)
  38. return next
  39. },
  40. onMutate: async (next: boolean) => {
  41. await qc.cancelQueries ({ queryKey: postKey })
  42. const prev = qc.getQueryData<Post> (postKey)
  43. qc.setQueryData (postKey,
  44. (cur: Post | undefined) => cur ? { ...cur, viewed: next } : cur)
  45. return { prev }
  46. },
  47. onError: (...[, , ctx]) => {
  48. if (ctx?.prev)
  49. qc.setQueryData (postKey, ctx.prev)
  50. toast ({ title: '失敗……', description: '通信に失敗しました……' })
  51. },
  52. onSuccess: () => {
  53. qc.invalidateQueries ({ queryKey: postsKeys.root })
  54. } })
  55. useEffect (() => {
  56. if (!(errorFlg))
  57. return
  58. const code = isApiError (error) ? error.response?.status : undefined
  59. if (code)
  60. setStatus (code)
  61. }, [errorFlg, error])
  62. useEffect (() => {
  63. scroll (0, 0)
  64. setStatus (200)
  65. }, [id])
  66. switch (status)
  67. {
  68. case 404:
  69. return <NotFound/>
  70. case 503:
  71. return <ServiceUnavailable/>
  72. }
  73. const viewedClass = (post?.viewed
  74. ? 'bg-blue-600 hover:bg-blue-700'
  75. : 'bg-gray-500 hover:bg-gray-600')
  76. return (
  77. <div className="md:flex md:flex-1 overflow-y-auto md:overflow-y-hidden">
  78. <Helmet>
  79. {(post?.thumbnail || post?.thumbnailBase) && (
  80. <meta name="thumbnail" content={post.thumbnail! || post.thumbnailBase!}/>)}
  81. {post && <title>{`${ post.title || post.url } | ${ SITE_TITLE }`}</title>}
  82. </Helmet>
  83. <div className="hidden md:block">
  84. {post && <TagDetailSidebar post={post}/>}
  85. </div>
  86. <MainArea className="relative">
  87. {post
  88. ? (
  89. <>
  90. {(post.childPosts ?? []).length > 0 && (
  91. <div className="mb-4 bg-green-200 dark:bg-green-800 text-sm p-2 rounded-md">
  92. <p>この投稿には {post.childPosts!.length} 件の子投稿があります.</p>
  93. <PostList posts={[{ ...post, childPosts: [{ } as Post] },
  94. ...post.childPosts!.map (p => ({
  95. ...p, parentPosts: [{ } as Post] }))]}/>
  96. </div>
  97. )}
  98. {(post.parentPosts ?? []).map (pp => {
  99. const siblings = post.siblingPosts?.[String (pp.id) as `${ number }`]
  100. if (!(siblings))
  101. return
  102. return (
  103. <div
  104. key={pp.id}
  105. className="mb-4 bg-yellow-200 dark:bg-yellow-800 text-sm p-2 rounded-md">
  106. <p>
  107. この投稿には 1 件の親投稿{
  108. siblings.length > 1
  109. && `と ${ siblings.length - 1 } 件の姉妹投稿`}があります.
  110. </p>
  111. <PostList posts={[{ ...pp, childPosts: [{ } as Post] },
  112. ...siblings.map (p => ({
  113. ...p, parentPosts: [{ } as Post] }))]}/>
  114. </div>)
  115. })}
  116. {(post.thumbnail || post.thumbnailBase) && (
  117. <motion.div
  118. layoutId={`page-${ id }`}
  119. className="absolute top-4 left-4 w-[min(640px,calc(100vw-2rem))] h-[360px]
  120. overflow-hidden rounded-xl pointer-events-none z-50"
  121. initial={{ opacity: 1 }}
  122. animate={{ opacity: 0 }}
  123. transition={{ duration: .2, ease: 'easeOut' }}>
  124. <img src={post.thumbnail || post.thumbnailBase || undefined}
  125. alt={post.title || post.url}
  126. title={post.title || post.url || undefined}
  127. className="object-cover w-full h-full"/>
  128. </motion.div>)}
  129. <PostEmbed
  130. ref={embedRef}
  131. post={post}
  132. onLoadComplete={() => embedRef.current?.play ()}/>
  133. <Button onClick={() => changeViewedFlg.mutate (!(post.viewed))}
  134. disabled={changeViewedFlg.isPending}
  135. className={cn ('text-white', viewedClass)}>
  136. {post.viewed ? '閲覧済' : '未閲覧'}
  137. </Button>
  138. <TabGroup>
  139. <Tab name="関聯">
  140. {post.related.length > 0
  141. ? <PostList posts={post.related}/>
  142. : 'まだないよ(笑)'}
  143. </Tab>
  144. {['admin', 'member'].some (r => user?.role === r) && (
  145. <Tab name="編輯">
  146. <PostEditForm
  147. post={post}
  148. onSave={newPost => {
  149. qc.setQueryData (postsKeys.show (postId),
  150. (prev: Post | undefined) => newPost ?? prev)
  151. qc.invalidateQueries ({ queryKey: postsKeys.root })
  152. qc.invalidateQueries ({ queryKey: tagsKeys.root })
  153. }}/>
  154. </Tab>)}
  155. </TabGroup>
  156. </>)
  157. : 'Loading...'}
  158. </MainArea>
  159. <div className="md:hidden">
  160. {post && <TagDetailSidebar post={post} sp/>}
  161. </div>
  162. </div>)
  163. }
  164. export default PostDetailPage