アニメーション(#139) (#252)

#139

#139

#139

#139

#139

Merge branch 'feature/140' into feature/139

Merge remote-tracking branch 'origin/main' into feature/139

#140

Merge remote-tracking branch 'origin/main' into feature/140

Merge remote-tracking branch 'origin/main' into feature/140

#140 ぼちぼち

Merge remote-tracking branch 'origin/main' into feature/140

#140

#140

#140

#139 アニメーション

Co-authored-by: miteruzo <miteruzo@naver.com>
Reviewed-on: #252
This commit was merged in pull request #252.
This commit is contained in:
2026-02-05 23:25:27 +09:00
parent f3cd108b2e
commit 797e67ac37
22 changed files with 810 additions and 311 deletions
+111 -81
View File
@@ -1,74 +1,81 @@
import axios from 'axios'
import toCamel from 'camelcase-keys'
import { useMutation, useQuery, useQueryClient } from '@tanstack/react-query'
import { motion } from 'framer-motion'
import { useEffect, useState } from 'react'
import { Helmet } from 'react-helmet-async'
import { useParams } from 'react-router-dom'
import PostList from '@/components/PostList'
import TagDetailSidebar from '@/components/TagDetailSidebar'
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 { API_BASE_URL, SITE_TITLE } from '@/config'
import { SITE_TITLE } from '@/config'
import { fetchPost, toggleViewedFlg } from '@/lib/posts'
import { postsKeys } from '@/lib/queryKeys'
import { cn } from '@/lib/utils'
import NotFound from '@/pages/NotFound'
import ServiceUnavailable from '@/pages/ServiceUnavailable'
import type { FC } from 'react'
import type { Post, User } from '@/types'
import type { User } from '@/types'
type Props = { user: User | null }
export default (({ user }: Props) => {
const { id } = useParams ()
const postId = String (id ?? '')
const postKey = postsKeys.show (postId)
const { data: post, isError: errorFlg, error } = useQuery ({
enabled: Boolean (id),
queryKey: postKey,
queryFn: () => fetchPost (postId) })
const qc = useQueryClient ()
const [post, setPost] = useState<Post | null> (null)
const [status, setStatus] = useState (200)
const changeViewedFlg = async () => {
const url = `${ API_BASE_URL }/posts/${ id }/viewed`
const opt = { headers: { 'X-Transfer-Code': localStorage.getItem ('user_code') || '' } }
try
{
if (post!.viewed)
await axios.delete (url, opt)
else
await axios.post (url, { }, opt)
// 通信に成功したら “閲覧済” をトグル
setPost (post => ({ ...post!, viewed: !(post!.viewed) }))
}
catch
{
toast ({ title: '失敗……', description: '通信に失敗しました……' })
}
}
const changeViewedFlg = useMutation ({
mutationFn: async () => {
const cur = qc.getQueryData<any> (postKey)
const next = !(cur?.viewed)
await toggleViewedFlg (postId, next)
return next
},
onMutate: async () => {
await qc.cancelQueries ({ queryKey: postKey })
const prev = qc.getQueryData<any> (postKey)
qc.setQueryData (postKey,
(cur: any) => cur ? { ...cur, viewed: !(cur.viewed) } : cur)
return { prev }
},
onError: (...[, , ctx]) => {
if (ctx?.prev)
qc.setQueryData (postKey, ctx.prev)
toast ({ title: '失敗……', description: '通信に失敗しました……' })
},
onSuccess: () => {
qc.invalidateQueries ({ queryKey: postsKeys.root })
} })
useEffect (() => {
setPost (null)
if (!(id))
if (!(errorFlg))
return
const fetchPost = async () => {
try
{
const res = await axios.get (`${ API_BASE_URL }/posts/${ id }`, { headers: {
'X-Transfer-Code': localStorage.getItem ('user_code') ?? '' } })
setPost (toCamel (res.data as any, { deep: true }) as Post)
}
catch (err)
{
if (axios.isAxiosError (err))
setStatus (err.status ?? 200)
}
}
fetchPost ()
const code = (error as any)?.response.status ?? (error as any)?.status
if (code)
setStatus (code)
}, [errorFlg, error])
useEffect (() => {
scroll (0, 0)
setStatus (200)
}, [id])
switch (status)
@@ -84,44 +91,67 @@ export default (({ user }: Props) => {
: 'bg-gray-500 hover:bg-gray-600')
return (
<div className="md:flex md:flex-1">
<Helmet>
{(post?.thumbnail || post?.thumbnailBase) && (
<meta name="thumbnail" content={post.thumbnail || post.thumbnailBase}/>)}
{post && <title>{`${ post.title || post.url } | ${ SITE_TITLE }`}</title>}
</Helmet>
<div className="hidden md:block">
<TagDetailSidebar post={post}/>
<>
<div className="md:flex md:flex-1">
<Helmet>
{(post?.thumbnail || post?.thumbnailBase) && (
<meta name="thumbnail" content={post.thumbnail || post.thumbnailBase}/>)}
{post && <title>{`${ post.title || post.url } | ${ SITE_TITLE }`}</title>}
</Helmet>
<div className="hidden md:block">
<TagDetailSidebar post={post ?? null}/>
</div>
<MainArea className="relative">
{post
? (
<>
{(post.thumbnail || post.thumbnailBase) && (
<motion.div
layoutId={`page-${ id }`}
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={{ duration: .2, ease: 'easeOut' }}>
<img src={post.thumbnail || post.thumbnailBase}
alt={post.title || post.url}
title={post.title || post.url || undefined}
className="object-cover w-full h-full"/>
</motion.div>)}
<PostEmbed post={post}/>
<Button onClick={() => changeViewedFlg.mutate ()}
disabled={changeViewedFlg.isPending}
className={cn ('text-white', viewedClass)}>
{post.viewed ? '閲覧済' : '未閲覧'}
</Button>
<TabGroup>
<Tab name="関聯">
{post.related.length > 0
? <PostList posts={post.related}/>
: 'まだないよ(笑)'}
</Tab>
{['admin', 'member'].some (r => user?.role === r) && (
<Tab name="編輯">
<PostEditForm
post={post}
onSave={newPost => {
qc.setQueryData (postsKeys.show (postId),
(prev: any) => newPost ?? prev)
qc.invalidateQueries ({ queryKey: postsKeys.root })
toast ({ description: '更新しました.' })
}}/>
</Tab>)}
</TabGroup>
</>)
: 'Loading...'}
</MainArea>
<div className="md:hidden">
<TagDetailSidebar post={post ?? null}/>
</div>
</div>
<MainArea>
{post
? (
<>
<PostEmbed post={post}/>
<Button onClick={changeViewedFlg}
className={cn ('text-white', viewedClass)}>
{post.viewed ? '閲覧済' : '未閲覧'}
</Button>
<TabGroup>
<Tab name="関聯">
{post.related.length > 0
? <PostList posts={post.related}/>
: 'まだないよ(笑)'}
</Tab>
{['admin', 'member'].some (r => user?.role === r) && (
<Tab name="編輯">
<PostEditForm post={post}
onSave={newPost => {
setPost (newPost)
toast ({ description: '更新しました.' })
}}/>
</Tab>)}
</TabGroup>
</>)
: 'Loading...'}
</MainArea>
<div className="md:hidden">
<TagDetailSidebar post={post}/>
</div>
</div>)
</>)
}) satisfies FC<Props>
+45 -95
View File
@@ -1,113 +1,66 @@
import axios from 'axios'
import toCamel from 'camelcase-keys'
import { useEffect, useLayoutEffect, useRef, useState } from 'react'
import { useQuery } from '@tanstack/react-query'
import { useLayoutEffect, useRef, useState } from 'react'
import { Helmet } from 'react-helmet-async'
import { Link, useLocation, useNavigationType } from 'react-router-dom'
import { useLocation } from 'react-router-dom'
import PostList from '@/components/PostList'
import PrefetchLink from '@/components/PrefetchLink'
import TagSidebar from '@/components/TagSidebar'
import WikiBody from '@/components/WikiBody'
import Pagination from '@/components/common/Pagination'
import TabGroup, { Tab } from '@/components/common/TabGroup'
import MainArea from '@/components/layout/MainArea'
import { API_BASE_URL, SITE_TITLE } from '@/config'
import { SITE_TITLE } from '@/config'
import { fetchPosts } from '@/lib/posts'
import { postsKeys } from '@/lib/queryKeys'
import { fetchWikiPageByTitle } from '@/lib/wiki'
import type { Post, WikiPage } from '@/types'
import type { FC } from 'react'
import type { WikiPage } from '@/types'
export default () => {
const navigationType = useNavigationType ()
export default (() => {
const containerRef = useRef<HTMLDivElement | null> (null)
const loaderRef = useRef<HTMLDivElement | null> (null)
const [cursor, setCursor] = useState ('')
const [loading, setLoading] = useState (false)
const [posts, setPosts] = useState<Post[]> ([])
const [totalPages, setTotalPages] = useState (0)
const [wikiPage, setWikiPage] = useState<WikiPage | null> (null)
const loadMore = async (withCursor: boolean) => {
setLoading (true)
const res = await axios.get (`${ API_BASE_URL }/posts`, {
params: { tags: tags.join (' '),
match: anyFlg ? 'any' : 'all',
...(page && { page }),
...(limit && { limit }),
...(withCursor && { cursor }) } })
const data = toCamel (res.data as any, { deep: true }) as {
posts: Post[]
count: number
nextCursor: string }
setPosts (posts => (
[...((new Map ([...(withCursor ? posts : []), ...data.posts]
.map (post => [post.id, post])))
.values ())]))
setCursor (data.nextCursor)
setTotalPages (Math.ceil (data.count / limit))
setLoading (false)
}
const location = useLocation ()
const query = new URLSearchParams (location.search)
const tagsQuery = query.get ('tags') ?? ''
const anyFlg = query.get ('match') === 'any'
const match = anyFlg ? 'any' : 'all'
const tags = tagsQuery.split (' ').filter (e => e !== '')
const tagsKey = tags.join (' ')
const page = Number (query.get ('page') ?? 1)
const limit = Number (query.get ('limit') ?? 20)
useEffect(() => {
const observer = new IntersectionObserver (entries => {
if (entries[0].isIntersecting && !(loading) && cursor)
loadMore (true)
}, { threshold: 1 })
const target = loaderRef.current
target && observer.observe (target)
return () => {
target && observer.unobserve (target)
}
}, [loaderRef, loading])
const { data, isLoading: loading } = useQuery ({
queryKey: postsKeys.index ({ tags: tagsKey, match, page, limit }),
queryFn: () => fetchPosts ({ tags: tagsKey, match, page, limit }) })
const posts = data?.posts ?? []
const cursor = data?.nextCursor ?? ''
const totalPages = data ? Math.ceil (data.count / limit) : 0
useLayoutEffect (() => {
// TODO: 無限ロード用
const savedState = /* sessionStorage.getItem (`posts:${ tagsQuery }`) */ null
if (savedState && navigationType === 'POP')
{
const { posts, cursor, scroll } = JSON.parse (savedState)
setPosts (posts)
setCursor (cursor)
if (containerRef.current)
containerRef.current.scrollTop = scroll
loadMore (true)
}
else
{
setPosts ([])
loadMore (false)
}
scroll (0, 0)
setWikiPage (null)
if (tags.length === 1)
if (tags.length !== 1)
return
void (async () => {
try
{
void (async () => {
try
{
const tagName = tags[0]
const res = await axios.get (`${ API_BASE_URL }/wiki/title/${ tagName }`)
setWikiPage (toCamel (res.data as any, { deep: true }) as WikiPage)
}
catch
{
;
}
}) ()
const tagName = tags[0]
setWikiPage (await fetchWikiPageByTitle (tagName, { }))
}
catch
{
;
}
}) ()
}, [location.search])
return (
@@ -120,7 +73,13 @@ export default () => {
</title>
</Helmet>
<TagSidebar posts={posts.slice (0, 20)}/>
<TagSidebar posts={posts.slice (0, 20)} onClick={() => {
const statesToSave = {
posts, cursor,
scroll: containerRef.current?.scrollTop ?? 0 }
sessionStorage.setItem (`posts:${ tagsQuery }`,
JSON.stringify (statesToSave))
}}/>
<MainArea>
<TabGroup>
@@ -128,31 +87,22 @@ export default () => {
{posts.length > 0
? (
<>
<PostList posts={posts} onClick={() => {
// TODO: 無限ロード用なので復活時に戻す.
// const statesToSave = {
// posts, cursor,
// scroll: containerRef.current?.scrollTop ?? 0 }
// sessionStorage.setItem (`posts:${ tagsQuery }`,
// JSON.stringify (statesToSave))
}}/>
<PostList posts={posts}/>
<Pagination page={page} totalPages={totalPages}/>
</>)
: !(loading) && '広場には何もありませんよ.'}
{loading && 'Loading...'}
{/* TODO: 無限ローディング復活までコメント・アウト */}
{/* <div ref={loaderRef} className="h-12"/> */}
</Tab>
{tags.length === 1 && (
<Tab name="Wiki">
<WikiBody title={tags[0]} body={wikiPage?.body}/>
<div className="my-2">
<Link to={`/wiki/${ encodeURIComponent (tags[0]) }`}>
<PrefetchLink to={`/wiki/${ encodeURIComponent (tags[0]) }`}>
Wiki
</Link>
</PrefetchLink>
</div>
</Tab>)}
</TabGroup>
</MainArea>
</div>)
}
}) satisfies FC