このコミットが含まれているのは:
2026-02-01 03:59:39 +09:00
コミット 8cc2a88e7c
12個のファイルの変更235行の追加215行の削除
+22 -20
ファイルの表示
@@ -13,6 +13,7 @@ import { Button } from '@/components/ui/button'
import { toast } from '@/components/ui/use-toast'
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'
@@ -26,12 +27,13 @@ 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: ['posts', String (id)],
queryFn: () => fetchPost (String (id)),
placeholderData: undefined })
enabled: Boolean (id),
queryKey: postKey,
queryFn: () => fetchPost (postId) })
const qc = useQueryClient ()
@@ -39,25 +41,25 @@ export default (({ user }: Props) => {
const changeViewedFlg = useMutation ({
mutationFn: async () => {
const next = !(post!.viewed)
await toggleViewedFlg (id!, next)
const cur = qc.getQueryData<any> (postKey)
const next = !(cur?.viewed)
await toggleViewedFlg (postId, next)
return next
},
onMutate: async () => {
await qc.cancelQueries ({ queryKey: ['posts', String (id)] })
const prev = qc.getQueryData<any> (['posts', String (id)])
qc.setQueryData (['posts', String (id)],
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 (['posts', String (id)], ctx.prev)
qc.setQueryData (postKey, ctx.prev)
toast ({ title: '失敗……', description: '通信に失敗しました……' })
},
onSuccess: () => {
qc.invalidateQueries ({ queryKey: ['posts', 'index'] })
qc.invalidateQueries ({ queryKey: ['related', String (id)] })
qc.invalidateQueries ({ queryKey: postsKeys.root })
} })
useEffect (() => {
@@ -115,14 +117,14 @@ export default (({ user }: Props) => {
</Tab>
{['admin', 'member'].some (r => user?.role === r) && (
<Tab name="編輯">
<PostEditForm post={post}
onSave={newPost => {
qc.setQueryData (['posts', String (id)],
(prev: any) => newPost ?? prev)
qc.invalidateQueries ({ queryKey: ['posts', 'index'] })
qc.invalidateQueries ({ queryKey: ['related', String (id)] })
toast ({ description: '更新しました.' })
}}/>
<PostEditForm
post={post}
onSave={newPost => {
qc.setQueryData (postsKeys.show (postId),
(prev: any) => newPost ?? prev)
qc.invalidateQueries ({ queryKey: postsKeys.root })
toast ({ description: '更新しました.' })
}}/>
</Tab>)}
</TabGroup>
</>)
+20 -78
ファイルの表示
@@ -1,94 +1,46 @@
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 { WikiPage } from '@/types'
export default () => {
const navigationType = useNavigationType ()
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 data = await fetchPosts ({
tags: tags.join (' '),
match: anyFlg ? 'any' : 'all',
...(page && { page }),
...(limit && { limit }),
...(withCursor && { cursor }) })
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)
}
setWikiPage (null)
if (tags.length === 1)
{
@@ -96,8 +48,7 @@ export default () => {
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)
setWikiPage (await fetchWikiPageByTitle (tagName, { }))
}
catch
{
@@ -131,28 +82,19 @@ 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>
+14 -23
ファイルの表示
@@ -1,17 +1,19 @@
import axios from 'axios'
import toCamel from 'camelcase-keys'
import { useEffect, useState } from 'react'
import { Helmet } from 'react-helmet-async'
import { Link, useLocation, useNavigate, useParams } from 'react-router-dom'
import { useLocation, useNavigate, useParams } from 'react-router-dom'
import PostList from '@/components/PostList'
import PrefetchLink from '@/components/PrefetchLink'
import TagLink from '@/components/TagLink'
import WikiBody from '@/components/WikiBody'
import PageTitle from '@/components/common/PageTitle'
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 { WikiIdBus } from '@/lib/eventBus/WikiIdBus'
import { fetchPosts } from '@/lib/posts'
import { fetchTagByName } from '@/lib/tags'
import { fetchWikiPage, fetchWikiPageByTitle } from '@/lib/wiki'
import type { Post, Tag, WikiPage } from '@/types'
@@ -39,8 +41,7 @@ export default () => {
setWikiPage (undefined)
try
{
const res = await axios.get (`${ API_BASE_URL }/wiki/${ title }`)
const data = res.data as WikiPage
const data = await fetchWikiPage (title)
navigate (`/wiki/${ encodeURIComponent(data.title) }`, { replace: true })
}
catch
@@ -56,10 +57,7 @@ export default () => {
setWikiPage (undefined)
try
{
const res = await axios.get (
`${ API_BASE_URL }/wiki/title/${ encodeURIComponent (title) }`,
{ params: version ? { version } : { } })
const data = toCamel (res.data as any, { deep: true }) as WikiPage
const data = await fetchWikiPageByTitle (title, version ? { version } : { })
if (data.title !== title)
navigate (`/wiki/${ encodeURIComponent(data.title) }`, { replace: true })
setWikiPage (data)
@@ -75,12 +73,7 @@ export default () => {
void (async () => {
try
{
const res = await axios.get (
`${ API_BASE_URL }/posts?${ new URLSearchParams ({ tags: title,
limit: '8' }) }`)
const data = toCamel (res.data as any,
{ deep: true }) as { posts: Post[]
nextCursor: string }
const data = await fetchPosts ({ tags: title, match: 'all', limit: 8 })
setPosts (data.posts)
}
catch
@@ -92,9 +85,7 @@ export default () => {
void (async () => {
try
{
const res = await axios.get (
`${ API_BASE_URL }/tags/name/${ encodeURIComponent (title) }`)
setTag (toCamel (res.data as any, { deep: true }) as Tag)
setTag (await fetchTagByName (title))
}
catch
{
@@ -115,16 +106,16 @@ export default () => {
{(wikiPage && version) && (
<div className="text-sm flex gap-3 items-center justify-center border border-gray-700 rounded px-2 py-1 mb-4">
{wikiPage.pred ? (
<Link to={`/wiki/${ encodeURIComponent (title) }?version=${ wikiPage.pred }`}>
<PrefetchLink to={`/wiki/${ encodeURIComponent (title) }?version=${ wikiPage.pred }`}>
&lt;
</Link>) : '(最古)'}
</PrefetchLink>) : '(最古)'}
<span>{wikiPage.updatedAt}</span>
{wikiPage.succ ? (
<Link to={`/wiki/${ encodeURIComponent (title) }?version=${ wikiPage.succ }`}>
<PrefetchLink to={`/wiki/${ encodeURIComponent (title) }?version=${ wikiPage.succ }`}>
&gt;
</Link>) : '(最新)'}
</PrefetchLink>) : '(最新)'}
</div>)}
<PageTitle>