コミットを比較

...

18 コミット

作成者 SHA1 メッセージ 日付
みてるぞ a751add415 #140 2026-02-06 02:26:53 +09:00
みてるぞ a39b86c456 #140 2026-02-05 00:45:18 +09:00
みてるぞ 57f28e4e5e #140 2026-02-04 23:08:28 +09:00
みてるぞ f56f16ad2f #140 2026-02-04 12:47:08 +09:00
みてるぞ 0a9f96743e #140 2026-02-04 01:56:15 +09:00
みてるぞ 0994d54f0f #140 2026-02-04 01:49:22 +09:00
みてるぞ d120df3493 #140 2026-02-04 01:44:21 +09:00
みてるぞ 914dc43889 #140 2026-02-04 00:51:40 +09:00
みてるぞ 4c559b30fe #140 2026-02-03 12:42:03 +09:00
みてるぞ e0446e35ff #140 2026-02-03 12:40:20 +09:00
みてるぞ 8cc2a88e7c #140 2026-02-01 03:59:39 +09:00
みてるぞ 145d93679c Merge remote-tracking branch 'origin/main' into feature/140 2026-01-31 16:26:23 +09:00
みてるぞ 51c20a42c7 Merge remote-tracking branch 'origin/main' into feature/140 2026-01-29 23:53:37 +09:00
みてるぞ 7df51fb34b #140 ぼちぼち 2025-12-07 17:21:58 +09:00
みてるぞ 4e00ec40ab Merge remote-tracking branch 'origin/main' into feature/140 2025-12-07 13:09:49 +09:00
みてるぞ 214c91e3bf #140 2025-10-05 17:05:05 +09:00
みてるぞ 5cbe21b5d7 #140 2025-10-05 12:52:43 +09:00
みてるぞ d5d7e0e22b #140 2025-10-05 03:15:46 +09:00
37個のファイルの変更898行の追加543行の削除
生成ファイル
+69 -1
ファイルの表示
@@ -16,6 +16,7 @@
"@radix-ui/react-dialog": "^1.1.14", "@radix-ui/react-dialog": "^1.1.14",
"@radix-ui/react-switch": "^1.2.5", "@radix-ui/react-switch": "^1.2.5",
"@radix-ui/react-toast": "^1.2.14", "@radix-ui/react-toast": "^1.2.14",
"@tanstack/react-query": "^5.90.2",
"axios": "^1.10.0", "axios": "^1.10.0",
"camelcase-keys": "^9.1.3", "camelcase-keys": "^9.1.3",
"class-variance-authority": "^0.7.1", "class-variance-authority": "^0.7.1",
@@ -24,6 +25,7 @@
"humps": "^2.0.1", "humps": "^2.0.1",
"lucide-react": "^0.511.0", "lucide-react": "^0.511.0",
"markdown-it": "^14.1.0", "markdown-it": "^14.1.0",
"path-to-regexp": "^8.3.0",
"react": "^19.1.0", "react": "^19.1.0",
"react-dom": "^19.1.0", "react-dom": "^19.1.0",
"react-helmet-async": "^2.0.5", "react-helmet-async": "^2.0.5",
@@ -33,7 +35,8 @@
"react-youtube": "^10.1.0", "react-youtube": "^10.1.0",
"remark-gfm": "^4.0.1", "remark-gfm": "^4.0.1",
"tailwind-merge": "^3.3.0", "tailwind-merge": "^3.3.0",
"unist-util-visit-parents": "^6.0.1" "unist-util-visit-parents": "^6.0.1",
"zustand": "^5.0.8"
}, },
"devDependencies": { "devDependencies": {
"@eslint/js": "^9.25.0", "@eslint/js": "^9.25.0",
@@ -1966,6 +1969,32 @@
"win32" "win32"
] ]
}, },
"node_modules/@tanstack/query-core": {
"version": "5.90.2",
"resolved": "https://registry.npmjs.org/@tanstack/query-core/-/query-core-5.90.2.tgz",
"integrity": "sha512-k/TcR3YalnzibscALLwxeiLUub6jN5EDLwKDiO7q5f4ICEoptJ+n9+7vcEFy5/x/i6Q+Lb/tXrsKCggf5uQJXQ==",
"license": "MIT",
"funding": {
"type": "github",
"url": "https://github.com/sponsors/tannerlinsley"
}
},
"node_modules/@tanstack/react-query": {
"version": "5.90.2",
"resolved": "https://registry.npmjs.org/@tanstack/react-query/-/react-query-5.90.2.tgz",
"integrity": "sha512-CLABiR+h5PYfOWr/z+vWFt5VsOA2ekQeRQBFSKlcoW6Ndx/f8rfyVmq4LbgOM4GG2qtxAxjLYLOpCNTYm4uKzw==",
"license": "MIT",
"dependencies": {
"@tanstack/query-core": "5.90.2"
},
"funding": {
"type": "github",
"url": "https://github.com/sponsors/tannerlinsley"
},
"peerDependencies": {
"react": "^18 || ^19"
}
},
"node_modules/@types/axios": { "node_modules/@types/axios": {
"version": "0.14.4", "version": "0.14.4",
"resolved": "https://registry.npmjs.org/@types/axios/-/axios-0.14.4.tgz", "resolved": "https://registry.npmjs.org/@types/axios/-/axios-0.14.4.tgz",
@@ -5552,6 +5581,16 @@
"dev": true, "dev": true,
"license": "ISC" "license": "ISC"
}, },
"node_modules/path-to-regexp": {
"version": "8.3.0",
"resolved": "https://registry.npmjs.org/path-to-regexp/-/path-to-regexp-8.3.0.tgz",
"integrity": "sha512-7jdwVIRtsP8MYpdXSwOS0YdD0Du+qOoF/AEPIt88PcCFrZCzx41oxku1jD88hZBwbNUIEfpqvuhjFaMAqMTWnA==",
"license": "MIT",
"funding": {
"type": "opencollective",
"url": "https://opencollective.com/express"
}
},
"node_modules/picocolors": { "node_modules/picocolors": {
"version": "1.1.1", "version": "1.1.1",
"resolved": "https://registry.npmjs.org/picocolors/-/picocolors-1.1.1.tgz", "resolved": "https://registry.npmjs.org/picocolors/-/picocolors-1.1.1.tgz",
@@ -7286,6 +7325,35 @@
"integrity": "sha512-Tpp60P6IUJDTuOq/5Z8cdskzJujfwqfOTkrwIwj7IRISpnkJnT6SyJ4PCPnGMoFjC9ddhal5KVIYtAt97ix05A==", "integrity": "sha512-Tpp60P6IUJDTuOq/5Z8cdskzJujfwqfOTkrwIwj7IRISpnkJnT6SyJ4PCPnGMoFjC9ddhal5KVIYtAt97ix05A==",
"license": "MIT" "license": "MIT"
}, },
"node_modules/zustand": {
"version": "5.0.8",
"resolved": "https://registry.npmjs.org/zustand/-/zustand-5.0.8.tgz",
"integrity": "sha512-gyPKpIaxY9XcO2vSMrLbiER7QMAMGOQZVRdJ6Zi782jkbzZygq5GI9nG8g+sMgitRtndwaBSl7uiqC49o1SSiw==",
"license": "MIT",
"engines": {
"node": ">=12.20.0"
},
"peerDependencies": {
"@types/react": ">=18.0.0",
"immer": ">=9.0.6",
"react": ">=18.0.0",
"use-sync-external-store": ">=1.2.0"
},
"peerDependenciesMeta": {
"@types/react": {
"optional": true
},
"immer": {
"optional": true
},
"react": {
"optional": true
},
"use-sync-external-store": {
"optional": true
}
}
},
"node_modules/zwitch": { "node_modules/zwitch": {
"version": "2.0.4", "version": "2.0.4",
"resolved": "https://registry.npmjs.org/zwitch/-/zwitch-2.0.4.tgz", "resolved": "https://registry.npmjs.org/zwitch/-/zwitch-2.0.4.tgz",
+3
ファイルの表示
@@ -18,6 +18,7 @@
"@radix-ui/react-dialog": "^1.1.14", "@radix-ui/react-dialog": "^1.1.14",
"@radix-ui/react-switch": "^1.2.5", "@radix-ui/react-switch": "^1.2.5",
"@radix-ui/react-toast": "^1.2.14", "@radix-ui/react-toast": "^1.2.14",
"@tanstack/react-query": "^5.90.2",
"axios": "^1.10.0", "axios": "^1.10.0",
"camelcase-keys": "^9.1.3", "camelcase-keys": "^9.1.3",
"class-variance-authority": "^0.7.1", "class-variance-authority": "^0.7.1",
@@ -26,6 +27,7 @@
"humps": "^2.0.1", "humps": "^2.0.1",
"lucide-react": "^0.511.0", "lucide-react": "^0.511.0",
"markdown-it": "^14.1.0", "markdown-it": "^14.1.0",
"path-to-regexp": "^8.3.0",
"react": "^19.1.0", "react": "^19.1.0",
"react-dom": "^19.1.0", "react-dom": "^19.1.0",
"react-helmet-async": "^2.0.5", "react-helmet-async": "^2.0.5",
@@ -35,6 +37,7 @@
"react-youtube": "^10.1.0", "react-youtube": "^10.1.0",
"remark-gfm": "^4.0.1", "remark-gfm": "^4.0.1",
"tailwind-merge": "^3.3.0", "tailwind-merge": "^3.3.0",
"zustand": "^5.0.8",
"unist-util-visit-parents": "^6.0.1" "unist-util-visit-parents": "^6.0.1"
}, },
"devDependencies": { "devDependencies": {
+42 -35
ファイルの表示
@@ -1,11 +1,10 @@
import axios from 'axios'
import toCamel from 'camelcase-keys'
import { useEffect, useState } from 'react' import { useEffect, useState } from 'react'
import { BrowserRouter, Navigate, Route, Routes } from 'react-router-dom' import { BrowserRouter, Navigate, Route, Routes, useLocation } from 'react-router-dom'
import RouteBlockerOverlay from '@/components/RouteBlockerOverlay'
import TopNav from '@/components/TopNav' import TopNav from '@/components/TopNav'
import { Toaster } from '@/components/ui/toaster' import { Toaster } from '@/components/ui/toaster'
import { API_BASE_URL } from '@/config' import { apiPost, isApiError } from '@/lib/api'
import NicoTagListPage from '@/pages/tags/NicoTagListPage' import NicoTagListPage from '@/pages/tags/NicoTagListPage'
import NotFound from '@/pages/NotFound' import NotFound from '@/pages/NotFound'
import PostDetailPage from '@/pages/posts/PostDetailPage' import PostDetailPage from '@/pages/posts/PostDetailPage'
@@ -26,18 +25,24 @@ import type { FC } from 'react'
import type { User } from '@/types' import type { User } from '@/types'
const PostDetailRoute = ({ user }: { user: User | null }) => {
const location = useLocation ()
const key = location.pathname
return <PostDetailPage key={key} user={user}/>
}
export default (() => { export default (() => {
const [user, setUser] = useState<User | null> (null) const [user, setUser] = useState<User | null> (null)
const [status, setStatus] = useState (200) const [status, setStatus] = useState (200)
useEffect (() => { useEffect (() => {
const createUser = async () => { const createUser = async () => {
const res = await axios.post (`${ API_BASE_URL }/users`) const data = await apiPost<{ code: string; user: User }> ('/users')
const data = res.data as { code: string; user: any }
if (data.code) if (data.code)
{ {
localStorage.setItem ('user_code', data.code) localStorage.setItem ('user_code', data.code)
setUser (toCamel (data.user, { deep: true }) as User) setUser (data.user)
} }
} }
@@ -47,17 +52,16 @@ export default (() => {
void (async () => { void (async () => {
try try
{ {
const res = await axios.post (`${ API_BASE_URL }/users/verify`, { code }) const data = await apiPost<{ valid: boolean; user: User }> ('/users/verify', { code })
const data = res.data as { valid: boolean, user: any }
if (data.valid) if (data.valid)
setUser (toCamel (data.user, { deep: true })) setUser (data.user)
else else
await createUser () await createUser ()
} }
catch (err) catch (err)
{ {
if (axios.isAxiosError (err)) if (isApiError (err))
setStatus (err.status ?? 200) setStatus (err.response?.status ?? 200)
} }
}) () }) ()
} }
@@ -72,27 +76,30 @@ export default (() => {
} }
return ( return (
<BrowserRouter> <>
<div className="flex flex-col h-screen w-screen"> <RouteBlockerOverlay/>
<TopNav user={user}/> <BrowserRouter>
<Routes> <div className="flex flex-col h-screen w-screen">
<Route path="/" element={<Navigate to="/posts" replace/>}/> <TopNav user={user}/>
<Route path="/posts" element={<PostListPage/>}/> <Routes>
<Route path="/posts/new" element={<PostNewPage user={user}/>}/> <Route path="/" element={<Navigate to="/posts" replace/>}/>
<Route path="/posts/:id" element={<PostDetailPage user={user}/>}/> <Route path="/posts" element={<PostListPage/>}/>
<Route path="/posts/changes" element={<PostHistoryPage/>}/> <Route path="/posts/new" element={<PostNewPage user={user}/>}/>
<Route path="/tags/nico" element={<NicoTagListPage user={user}/>}/> <Route path="/posts/:id" element={<PostDetailRoute user={user}/>}/>
<Route path="/wiki" element={<WikiSearchPage/>}/> <Route path="/posts/changes" element={<PostHistoryPage/>}/>
<Route path="/wiki/:title" element={<WikiDetailPage/>}/> <Route path="/tags/nico" element={<NicoTagListPage user={user}/>}/>
<Route path="/wiki/new" element={<WikiNewPage user={user}/>}/> <Route path="/wiki" element={<WikiSearchPage/>}/>
<Route path="/wiki/:id/edit" element={<WikiEditPage user={user}/>}/> <Route path="/wiki/:title" element={<WikiDetailPage/>}/>
<Route path="/wiki/:id/diff" element={<WikiDiffPage/>}/> <Route path="/wiki/new" element={<WikiNewPage user={user}/>}/>
<Route path="/wiki/changes" element={<WikiHistoryPage/>}/> <Route path="/wiki/:id/edit" element={<WikiEditPage user={user}/>}/>
<Route path="/users/settings" element={<SettingPage user={user} setUser={setUser}/>}/> <Route path="/wiki/:id/diff" element={<WikiDiffPage/>}/>
<Route path="/settings" element={<Navigate to="/users/settings" replace/>}/> <Route path="/wiki/changes" element={<WikiHistoryPage/>}/>
<Route path="*" element={<NotFound/>}/> <Route path="/users/settings" element={<SettingPage user={user} setUser={setUser}/>}/>
</Routes> <Route path="/settings" element={<Navigate to="/users/settings" replace/>}/>
</div> <Route path="*" element={<NotFound/>}/>
<Toaster/> </Routes>
</BrowserRouter>) </div>
<Toaster/>
</BrowserRouter>
</>)
}) satisfies FC }) satisfies FC
+5 -10
ファイルの表示
@@ -1,12 +1,10 @@
import axios from 'axios'
import toCamel from 'camelcase-keys'
import { useEffect, useState } from 'react' import { useEffect, useState } from 'react'
import PostFormTagsArea from '@/components/PostFormTagsArea' import PostFormTagsArea from '@/components/PostFormTagsArea'
import PostOriginalCreatedTimeField from '@/components/PostOriginalCreatedTimeField' import PostOriginalCreatedTimeField from '@/components/PostOriginalCreatedTimeField'
import Label from '@/components/common/Label' import Label from '@/components/common/Label'
import { Button } from '@/components/ui/button' import { Button } from '@/components/ui/button'
import { API_BASE_URL } from '@/config' import { apiPut } from '@/lib/api'
import type { FC } from 'react' import type { FC } from 'react'
@@ -41,14 +39,11 @@ export default (({ post, onSave }: Props) => {
const [tags, setTags] = useState<string> ('') const [tags, setTags] = useState<string> ('')
const handleSubmit = async () => { const handleSubmit = async () => {
const res = await axios.put ( const data = await apiPut<Post> (
`${ API_BASE_URL }/posts/${ post.id }`, `/posts/${ post.id }`,
{ title, tags, { title, tags, original_created_from: originalCreatedFrom,
original_created_from: originalCreatedFrom,
original_created_before: originalCreatedBefore }, original_created_before: originalCreatedBefore },
{ headers: { 'Content-Type': 'multipart/form-data', { headers: { 'Content-Type': 'multipart/form-data' } })
'X-Transfer-Code': localStorage.getItem ('user_code') ?? '' } })
const data = toCamel (res.data as any, { deep: true }) as Post
onSave ({ ...post, onSave ({ ...post,
title: data.title, title: data.title,
tags: data.tags, tags: data.tags,
+2 -5
ファイルの表示
@@ -1,11 +1,9 @@
import axios from 'axios'
import toCamel from 'camelcase-keys'
import { useRef, useState } from 'react' import { useRef, useState } from 'react'
import TagSearchBox from '@/components/TagSearchBox' import TagSearchBox from '@/components/TagSearchBox'
import Label from '@/components/common/Label' import Label from '@/components/common/Label'
import TextArea from '@/components/common/TextArea' import TextArea from '@/components/common/TextArea'
import { API_BASE_URL } from '@/config' import { apiGet } from '@/lib/api'
import type { FC, SyntheticEvent } from 'react' import type { FC, SyntheticEvent } from 'react'
@@ -59,8 +57,7 @@ export default (({ tags, setTags }: Props) => {
const recompute = async (pos: number, v: string = tags) => { const recompute = async (pos: number, v: string = tags) => {
const { start, end, token } = getTokenAt (v, pos) const { start, end, token } = getTokenAt (v, pos)
setBounds ({ start, end }) setBounds ({ start, end })
const res = await axios.get (`${ API_BASE_URL }/tags/autocomplete`, { params: { q: token } }) const data = await apiGet<Tag[]> ('/tags/autocomplete', { params: { q: token } })
const data = toCamel (res.data as any, { deep: true }) as Tag[]
setSuggestions (data.filter (t => t.postCount > 0)) setSuggestions (data.filter (t => t.postCount > 0))
setSuggestionsVsbl (suggestions.length > 0) setSuggestionsVsbl (suggestions.length > 0)
} }
+7 -6
ファイルの表示
@@ -1,4 +1,4 @@
import { Link } from 'react-router-dom' import PrefetchLink from '@/components/PrefetchLink'
import type { FC, MouseEvent } from 'react' import type { FC, MouseEvent } from 'react'
@@ -11,15 +11,16 @@ type Props = { posts: Post[]
export default (({ posts, onClick }: Props) => ( export default (({ posts, onClick }: Props) => (
<div className="flex flex-wrap gap-6 p-4"> <div className="flex flex-wrap gap-6 p-4">
{posts.map ((post, i) => ( {posts.map ((post, i) => (
<Link to={`/posts/${ post.id }`} <PrefetchLink
key={post.id} to={`/posts/${ post.id }`}
className="w-40 h-40 overflow-hidden rounded-lg shadow-md hover:shadow-lg" key={post.id}
onClick={onClick}> className="w-40 h-40 overflow-hidden rounded-lg shadow-md hover:shadow-lg"
onClick={onClick}>
<img src={post.thumbnail || post.thumbnailBase || undefined} <img src={post.thumbnail || post.thumbnailBase || undefined}
alt={post.title || post.url} alt={post.title || post.url}
title={post.title || post.url || undefined} title={post.title || post.url || undefined}
loading={i < 12 ? 'eager' : 'lazy'} loading={i < 12 ? 'eager' : 'lazy'}
decoding="async" decoding="async"
className="object-cover w-full h-full"/> className="object-cover w-full h-full"/>
</Link>))} </PrefetchLink>))}
</div>)) satisfies FC<Props> </div>)) satisfies FC<Props>
+89
ファイルの表示
@@ -0,0 +1,89 @@
import { useQueryClient } from '@tanstack/react-query'
import { forwardRef, useMemo } from 'react'
import { createPath, useNavigate } from 'react-router-dom'
import { useOverlayStore } from '@/components/RouteBlockerOverlay'
import { prefetchForURL } from '@/lib/prefetchers'
import { cn } from '@/lib/utils'
import type { AnchorHTMLAttributes, MouseEvent, TouchEvent } from 'react'
import type { To } from 'react-router-dom'
type Props = AnchorHTMLAttributes<HTMLAnchorElement> & {
to: To
replace?: boolean
className?: string
cancelOnError?: boolean }
export default forwardRef<HTMLAnchorElement, Props> (({
to,
replace,
className,
onMouseEnter,
onTouchStart,
onClick,
cancelOnError = false,
...rest }, ref) => {
const navigate = useNavigate ()
const qc = useQueryClient ()
const url = useMemo (() => {
const path = (typeof to === 'string') ? to : createPath (to)
return (new URL (path, location.origin)).toString ()
}, [to])
const setOverlay = useOverlayStore (s => s.setActive)
const doPrefetch = async () => {
try
{
await prefetchForURL (qc, url)
return true
}
catch (e)
{
console.error ('データ取得エラー', e)
return false
}
}
const handleMouseEnter = async (ev: MouseEvent<HTMLAnchorElement>) => {
onMouseEnter?.(ev)
await doPrefetch ()
}
const handleTouchStart = async (ev: TouchEvent<HTMLAnchorElement>) => {
onTouchStart?.(ev)
await doPrefetch ()
}
const handleClick = async (ev: MouseEvent<HTMLAnchorElement>) => {
onClick?.(ev)
if (ev.defaultPrevented
|| ev.metaKey
|| ev.ctrlKey
|| ev.shiftKey
|| ev.altKey)
return
ev.preventDefault ()
setOverlay (true)
const ok = await doPrefetch ()
setOverlay (false)
if (!(ok) && cancelOnError)
return
navigate (to, { replace })
}
return (
<a ref={ref}
href={typeof to === 'string' ? to : createPath (to)}
onMouseEnter={handleMouseEnter}
onTouchStart={handleTouchStart}
onClick={handleClick}
className={cn ('cursor-pointer', className)}
{...rest}/>)
})
+46
ファイルの表示
@@ -0,0 +1,46 @@
import { useEffect } from 'react'
import { create } from 'zustand'
import type { FC } from 'react'
type OverlayStore = {
active: boolean
setActive: (v: boolean) => void }
export const useOverlayStore = create<OverlayStore> (set => ({
active: false,
setActive: v => set ({ active: v }) }))
export default (() => {
const active = useOverlayStore (s => s.active)
useEffect (() => {
if (active)
{
document.body.style.overflow = 'hidden'
document.body.setAttribute ('aria-busy', 'true')
}
else
{
document.body.style.overflow = ''
document.body.removeAttribute ('aria-busy')
}
}, [active])
if (!(active))
return null
return (
<div
role="progressbar"
aria-label="Loading"
className="fixed inset-0 z-[9999] bg-black/50 backdrop-blur-sm pointer-events-auto">
<div className="absolute inset-0 flex items-center justify-center">
<div className="rounded-2xl bg-black/60 text-white px-6 py-3 text-sm">
Loading...
</div>
</div>
</div>)
}) satisfies FC
+10 -31
ファイルの表示
@@ -6,21 +6,19 @@ import { DndContext,
useSensor, useSensor,
useSensors } from '@dnd-kit/core' useSensors } from '@dnd-kit/core'
import { restrictToWindowEdges } from '@dnd-kit/modifiers' import { restrictToWindowEdges } from '@dnd-kit/modifiers'
import axios from 'axios'
import toCamel from 'camelcase-keys'
import { AnimatePresence, motion } from 'framer-motion' import { AnimatePresence, motion } from 'framer-motion'
import { useEffect, useRef, useState } from 'react' import { useEffect, useRef, useState } from 'react'
import { Link } from 'react-router-dom'
import DraggableDroppableTagRow from '@/components/DraggableDroppableTagRow' import DraggableDroppableTagRow from '@/components/DraggableDroppableTagRow'
import PrefetchLink from '@/components/PrefetchLink'
import TagLink from '@/components/TagLink' import TagLink from '@/components/TagLink'
import TagSearch from '@/components/TagSearch' import TagSearch from '@/components/TagSearch'
import SectionTitle from '@/components/common/SectionTitle' import SectionTitle from '@/components/common/SectionTitle'
import SubsectionTitle from '@/components/common/SubsectionTitle' import SubsectionTitle from '@/components/common/SubsectionTitle'
import SidebarComponent from '@/components/layout/SidebarComponent' import SidebarComponent from '@/components/layout/SidebarComponent'
import { toast } from '@/components/ui/use-toast' import { toast } from '@/components/ui/use-toast'
import { API_BASE_URL } from '@/config'
import { CATEGORIES } from '@/consts' import { CATEGORIES } from '@/consts'
import { apiDelete, apiGet, apiPatch, apiPost } from '@/lib/api'
import type { DragEndEvent } from '@dnd-kit/core' import type { DragEndEvent } from '@dnd-kit/core'
import type { FC, MutableRefObject, ReactNode } from 'react' import type { FC, MutableRefObject, ReactNode } from 'react'
@@ -132,10 +130,7 @@ const changeCategory = async (
tagId: number, tagId: number,
category: Category, category: Category,
): Promise<void> => { ): Promise<void> => {
await axios.patch ( await apiPatch (`/tags/${ tagId }`, { category })
`${ API_BASE_URL }/tags/${ tagId }`,
{ category },
{ headers: { 'X-Transfer-Code': localStorage.getItem ('user_code') ?? '' } })
} }
@@ -170,12 +165,7 @@ export default (({ post }: Props) => {
if (!(post)) if (!(post))
return return
const res = await axios.get ( setTags (buildTagByCategory (await apiGet<Post> (`/posts/${ post.id }`)))
`${ API_BASE_URL }/posts/${ post.id }`,
{ headers: { 'X-Transfer-Code': localStorage.getItem ('user_code') ?? '' } })
const data = toCamel (res.data as any, { deep: true }) as Post
setTags (buildTagByCategory (data))
} }
const onDragEnd = async (e: DragEndEvent) => { const onDragEnd = async (e: DragEndEvent) => {
@@ -216,16 +206,9 @@ export default (({ post }: Props) => {
return return
if (fromParentId != null) if (fromParentId != null)
{ await apiDelete (`/tags/${ fromParentId }/children/${ childId }`)
await axios.delete (
`${ API_BASE_URL }/tags/${ fromParentId }/children/${ childId }`,
{ headers: { 'X-Transfer-Code': localStorage.getItem ('user_code') ?? '' } })
}
await axios.post ( await apiPost (`/tags/${ parentId }/children/${ childId }`, { })
`${ API_BASE_URL }/tags/${ parentId }/children/${ childId }`,
{ },
{ headers: { 'X-Transfer-Code': localStorage.getItem ('user_code') ?? '' } })
await reloadTags () await reloadTags ()
toast ({ toast ({
@@ -245,11 +228,7 @@ export default (({ post }: Props) => {
await changeCategory (childId, cat) await changeCategory (childId, cat)
if (fromParentId != null) if (fromParentId != null)
{ await apiDelete (`/tags/${ fromParentId }/children/${ childId }`)
await axios.delete (
`${ API_BASE_URL }/tags/${ fromParentId }/children/${ childId }`,
{ headers: { 'X-Transfer-Code': localStorage.getItem ('user_code') ?? '' } })
}
const fromParent = fromParentId == null ? null : findTag (tags, fromParentId) const fromParent = fromParentId == null ? null : findTag (tags, fromParentId)
@@ -358,9 +337,9 @@ export default (({ post }: Props) => {
<>耕作者: </> <>耕作者: </>
{post.uploadedUser {post.uploadedUser
? ( ? (
<Link to={`/users/${ post.uploadedUser.id }`}> <PrefetchLink to={`/users/${ post.uploadedUser.id }`}>
{post.uploadedUser.name || '名もなきニジラー'} {post.uploadedUser.name || '名もなきニジラー'}
</Link>) </PrefetchLink>)
: 'bot操作'} : 'bot操作'}
</li> </li>
*/} */}
@@ -389,7 +368,7 @@ export default (({ post }: Props) => {
</>)} </>)}
</li> </li>
<li> <li>
<Link to={`/posts/changes?id=${ post.id }`}></Link> <PrefetchLink to={`/posts/changes?id=${ post.id }`}></PrefetchLink>
</li> </li>
</ul> </ul>
</div>)} </div>)}
+34 -18
ファイルの表示
@@ -1,27 +1,34 @@
import axios from 'axios'
import { useEffect, useState } from 'react' import { useEffect, useState } from 'react'
import { Link } from 'react-router-dom'
import { API_BASE_URL } from '@/config' import PrefetchLink from '@/components/PrefetchLink'
import { LIGHT_COLOUR_SHADE, DARK_COLOUR_SHADE, TAG_COLOUR } from '@/consts' import { LIGHT_COLOUR_SHADE, DARK_COLOUR_SHADE, TAG_COLOUR } from '@/consts'
import { apiGet } from '@/lib/api'
import { cn } from '@/lib/utils' import { cn } from '@/lib/utils'
import type { ComponentProps, FC, HTMLAttributes } from 'react' import type { ComponentProps, FC, HTMLAttributes } from 'react'
import type { Tag } from '@/types' import type { Tag } from '@/types'
type CommonProps = { tag: Tag type CommonProps = {
nestLevel?: number tag: Tag
withWiki?: boolean nestLevel?: number
withCount?: boolean } withWiki?: boolean
withCount?: boolean
prefetch?: boolean }
type PropsWithLink = type PropsWithLink =
CommonProps & { linkFlg?: true } & Partial<ComponentProps<typeof Link>> & CommonProps
& { linkFlg?: true }
& Partial<ComponentProps<typeof PrefetchLink>>
type PropsWithoutLink = type PropsWithoutLink =
CommonProps & { linkFlg: false } & Partial<HTMLAttributes<HTMLSpanElement>> & CommonProps
& { linkFlg: false }
& Partial<HTMLAttributes<HTMLSpanElement>>
type Props = PropsWithLink | PropsWithoutLink type Props =
| PropsWithLink
| PropsWithoutLink
export default (({ tag, export default (({ tag,
@@ -29,6 +36,7 @@ export default (({ tag,
linkFlg = true, linkFlg = true,
withWiki = true, withWiki = true,
withCount = true, withCount = true,
prefetch = false,
...props }: Props) => { ...props }: Props) => {
const [havingWiki, setHavingWiki] = useState (true) const [havingWiki, setHavingWiki] = useState (true)
@@ -43,7 +51,7 @@ export default (({ tag,
try try
{ {
await axios.get (`${ API_BASE_URL }/wiki/title/${ encodeURIComponent (tagName) }/exists`) await apiGet (`/wiki/title/${ encodeURIComponent (tagName) }/exists`)
setHavingWiki (true) setHavingWiki (true)
} }
catch catch
@@ -73,17 +81,17 @@ export default (({ tag,
<span className="mr-1"> <span className="mr-1">
{havingWiki {havingWiki
? ( ? (
<Link to={`/wiki/${ encodeURIComponent (tag.name) }`} <PrefetchLink to={`/wiki/${ encodeURIComponent (tag.name) }`}
className={linkClass}> className={linkClass}>
? ?
</Link>) </PrefetchLink>)
: ( : (
<Link to={`/wiki/${ encodeURIComponent (tag.name) }`} <PrefetchLink to={`/wiki/${ encodeURIComponent (tag.name) }`}
className="animate-[wiki-blink_.25s_steps(2,end)_infinite] className="animate-[wiki-blink_.25s_steps(2,end)_infinite]
dark:animate-[wiki-blink-dark_.25s_steps(2,end)_infinite]" dark:animate-[wiki-blink-dark_.25s_steps(2,end)_infinite]"
title={`${ tag.name } Wiki が存在しません.`}> title={`${ tag.name } Wiki が存在しません.`}>
! !
</Link>)} </PrefetchLink>)}
</span>)} </span>)}
{nestLevel > 0 && ( {nestLevel > 0 && (
<span <span
@@ -100,11 +108,19 @@ export default (({ tag,
</>)} </>)}
{linkFlg {linkFlg
? ( ? (
<Link to={`/posts?${ (new URLSearchParams ({ tags: tag.name })).toString () }`} prefetch
? <PrefetchLink
to={`/posts?${ (new URLSearchParams ({ tags: tag.name })).toString () }`}
className={linkClass} className={linkClass}
{...props}> {...props}>
{tag.name} {tag.name}
</Link>) </PrefetchLink>
: <PrefetchLink
to={`/posts?${ (new URLSearchParams ({ tags: tag.name })).toString () }`}
className={linkClass}
{...props}>
{tag.name}
</PrefetchLink>)
: ( : (
<span className={spanClass} <span className={spanClass}
{...props}> {...props}>
+6 -9
ファイルの表示
@@ -1,13 +1,11 @@
import axios from 'axios' import { useEffect, useState } from 'react'
import toCamel from 'camelcase-keys'
import React, { useEffect, useState } from 'react'
import { useNavigate, useLocation } from 'react-router-dom' import { useNavigate, useLocation } from 'react-router-dom'
import { API_BASE_URL } from '@/config' import { apiGet } from '@/lib/api'
import TagSearchBox from './TagSearchBox' import TagSearchBox from './TagSearchBox'
import type { FC } from 'react' import type { ChangeEvent, FC, KeyboardEvent } from 'react'
import type { Tag } from '@/types' import type { Tag } from '@/types'
@@ -21,7 +19,7 @@ export default (() => {
const [suggestions, setSuggestions] = useState<Tag[]> ([]) const [suggestions, setSuggestions] = useState<Tag[]> ([])
const [suggestionsVsbl, setSuggestionsVsbl] = useState (false) const [suggestionsVsbl, setSuggestionsVsbl] = useState (false)
const whenChanged = async (ev: React.ChangeEvent<HTMLInputElement>) => { const whenChanged = async (ev: ChangeEvent<HTMLInputElement>) => {
setSearch (ev.target.value) setSearch (ev.target.value)
const q = ev.target.value.trim ().split (' ').at (-1) const q = ev.target.value.trim ().split (' ').at (-1)
@@ -31,14 +29,13 @@ export default (() => {
return return
} }
const res = await axios.get (`${ API_BASE_URL }/tags/autocomplete`, { params: { q } }) const data = await apiGet<Tag[]> ('/tags/autocomplete', { params: { q } })
const data = toCamel (res.data, { deep: true }) as Tag[]
setSuggestions (data.filter (t => t.postCount > 0)) setSuggestions (data.filter (t => t.postCount > 0))
if (suggestions.length > 0) if (suggestions.length > 0)
setSuggestionsVsbl (true) setSuggestionsVsbl (true)
} }
const handleKeyDown = (ev: React.KeyboardEvent<HTMLInputElement>) => { const handleKeyDown = (ev: KeyboardEvent<HTMLInputElement>) => {
switch (ev.key) switch (ev.key)
{ {
case 'ArrowDown': case 'ArrowDown':
+9 -9
ファイルの表示
@@ -1,4 +1,3 @@
import axios from 'axios'
import { AnimatePresence, motion } from 'framer-motion' import { AnimatePresence, motion } from 'framer-motion'
import { useEffect, useState } from 'react' import { useEffect, useState } from 'react'
import { useLocation, useNavigate } from 'react-router-dom' import { useLocation, useNavigate } from 'react-router-dom'
@@ -7,19 +6,20 @@ import TagLink from '@/components/TagLink'
import TagSearch from '@/components/TagSearch' import TagSearch from '@/components/TagSearch'
import SectionTitle from '@/components/common/SectionTitle' import SectionTitle from '@/components/common/SectionTitle'
import SidebarComponent from '@/components/layout/SidebarComponent' import SidebarComponent from '@/components/layout/SidebarComponent'
import { API_BASE_URL } from '@/config'
import { CATEGORIES } from '@/consts' import { CATEGORIES } from '@/consts'
import { apiGet } from '@/lib/api'
import type { FC } from 'react' import type { FC, MouseEvent } from 'react'
import type { Post, Tag } from '@/types' import type { Post, Tag } from '@/types'
type TagByCategory = Record<string, Tag[]> type TagByCategory = Record<string, Tag[]>
type Props = { posts: Post[] } type Props = { posts: Post[]
onClick?: (event: MouseEvent<HTMLElement>) => void }
export default (({ posts }: Props) => { export default (({ posts, onClick }: Props) => {
const navigate = useNavigate () const navigate = useNavigate ()
const [tagsVsbl, setTagsVsbl] = useState (false) const [tagsVsbl, setTagsVsbl] = useState (false)
@@ -65,7 +65,7 @@ export default (({ posts }: Props) => {
{CATEGORIES.flatMap (cat => cat in tags ? ( {CATEGORIES.flatMap (cat => cat in tags ? (
tags[cat].map (tag => ( tags[cat].map (tag => (
<li key={tag.id} className="mb-1"> <li key={tag.id} className="mb-1">
<TagLink tag={tag}/> <TagLink tag={tag} prefetch onClick={onClick}/>
</li>))) : [])} </li>))) : [])}
</ul> </ul>
<SectionTitle></SectionTitle> <SectionTitle></SectionTitle>
@@ -76,10 +76,10 @@ export default (({ posts }: Props) => {
void ((async () => { void ((async () => {
try try
{ {
const { data } = await axios.get (`${ API_BASE_URL }/posts/random`, const data = await apiGet<Post> ('/posts/random',
{ params: { tags: tagsQuery.split (' ').filter (e => e !== '').join (' '), { params: { tags: tagsQuery.split (' ').filter (e => e !== '').join (' '),
match: (anyFlg ? 'any' : 'all') } }) match: (anyFlg ? 'any' : 'all') } })
navigate (`/posts/${ (data as Post).id }`) navigate (`/posts/${ data.id }`)
} }
catch catch
{ {
+42 -41
ファイルの表示
@@ -1,18 +1,18 @@
import axios from 'axios'
import toCamel from 'camelcase-keys'
import { AnimatePresence, motion } from 'framer-motion' import { AnimatePresence, motion } from 'framer-motion'
import { Fragment, useEffect, useLayoutEffect, useRef, useState } from 'react' import { Fragment, useEffect, useLayoutEffect, useRef, useState } from 'react'
import { Link, useLocation } from 'react-router-dom' import { useLocation } from 'react-router-dom'
import Separator from '@/components/MenuSeparator' import Separator from '@/components/MenuSeparator'
import PrefetchLink from '@/components/PrefetchLink'
import TopNavUser from '@/components/TopNavUser' import TopNavUser from '@/components/TopNavUser'
import { API_BASE_URL } from '@/config'
import { WikiIdBus } from '@/lib/eventBus/WikiIdBus' import { WikiIdBus } from '@/lib/eventBus/WikiIdBus'
import { fetchTagByName } from '@/lib/tags'
import { cn } from '@/lib/utils' import { cn } from '@/lib/utils'
import { fetchWikiPage } from '@/lib/wiki'
import type { FC } from 'react' import type { FC, MouseEvent } from 'react'
import type { Menu, Tag, User, WikiPage } from '@/types' import type { Menu, User } from '@/types'
type Props = { user: User | null } type Props = { user: User | null }
@@ -120,11 +120,8 @@ export default (({ user }: Props) => {
const fetchPostCount = async () => { const fetchPostCount = async () => {
try try
{ {
const pageRes = await axios.get (`${ API_BASE_URL }/wiki/${ wikiId }`) const wikiPage = await fetchWikiPage (String (wikiId ?? ''), { })
const wikiPage = toCamel (pageRes.data as any, { deep: true }) as WikiPage const tag = await fetchTagByName (wikiPage.title)
const tagRes = await axios.get (`${ API_BASE_URL }/tags/name/${ wikiPage.title }`)
const tag = toCamel (tagRes.data as any, { deep: true }) as Tag
setPostCount (tag.postCount) setPostCount (tag.postCount)
} }
@@ -141,11 +138,11 @@ export default (({ user }: Props) => {
<nav className="px-3 flex justify-between items-center w-full min-h-[48px] <nav className="px-3 flex justify-between items-center w-full min-h-[48px]
bg-yellow-200 dark:bg-red-975 md:bg-yellow-50"> bg-yellow-200 dark:bg-red-975 md:bg-yellow-50">
<div className="flex items-center gap-2 h-full"> <div className="flex items-center gap-2 h-full">
<Link to="/" <PrefetchLink to="/"
className="mx-4 text-xl font-bold text-pink-600 hover:text-pink-400 className="mx-4 text-xl font-bold text-pink-600 hover:text-pink-400
dark:text-pink-300 dark:hover:text-pink-100"> dark:text-pink-300 dark:hover:text-pink-100">
</Link> </PrefetchLink>
<div ref={navRef} className="relative hidden md:flex h-full items-center"> <div ref={navRef} className="relative hidden md:flex h-full items-center">
<div aria-hidden <div aria-hidden
@@ -157,15 +154,16 @@ export default (({ user }: Props) => {
opacity: hl.visible ? 1 : 0 }}/> opacity: hl.visible ? 1 : 0 }}/>
{menu.map ((item, i) => ( {menu.map ((item, i) => (
<Link key={i} <PrefetchLink
to={item.to} key={i}
ref={el => { to={item.to}
itemsRef.current[i] = el ref={(el: (HTMLAnchorElement | null)) => {
}} itemsRef.current[i] = el
className={cn ('relative z-10 flex h-full items-center px-5', }}
(i === openItemIdx) && 'font-bold')}> className={cn ('relative z-10 flex h-full items-center px-5',
(i === openItemIdx) && 'font-bold')}>
{item.name} {item.name}
</Link>))} </PrefetchLink>))}
</div> </div>
</div> </div>
@@ -203,11 +201,12 @@ export default (({ user }: Props) => {
'component' in item 'component' in item
? <Fragment key={`c-${ i }`}>{item.component}</Fragment> ? <Fragment key={`c-${ i }`}>{item.component}</Fragment>
: ( : (
<Link key={`l-${ i }`} <PrefetchLink
to={item.to} key={`l-${ i }`}
className="h-full flex items-center px-3"> to={item.to}
className="h-full flex items-center px-3">
{item.name} {item.name}
</Link>)))} </PrefetchLink>)))}
</motion.div> </motion.div>
</AnimatePresence> </AnimatePresence>
</div> </div>
@@ -229,19 +228,20 @@ export default (({ user }: Props) => {
<Separator/> <Separator/>
{menu.map ((item, i) => ( {menu.map ((item, i) => (
<Fragment key={i}> <Fragment key={i}>
<Link to={i === openItemIdx ? item.to : '#'} <PrefetchLink
className={cn ('w-full min-h-[40px] flex items-center pl-8', to={i === openItemIdx ? item.to : '#'}
((i === openItemIdx) className={cn ('w-full min-h-[40px] flex items-center pl-8',
&& 'font-bold bg-yellow-50 dark:bg-red-950'))} ((i === openItemIdx)
onClick={ev => { && 'font-bold bg-yellow-50 dark:bg-red-950'))}
if (i !== openItemIdx) onClick={(ev: MouseEvent<HTMLAnchorElement>) => {
{ if (i !== openItemIdx)
ev.preventDefault () {
setOpenItemIdx (i) ev.preventDefault ()
} setOpenItemIdx (i)
}}> }
}}>
{item.name} {item.name}
</Link> </PrefetchLink>
<AnimatePresence initial={false}> <AnimatePresence initial={false}>
{i === openItemIdx && ( {i === openItemIdx && (
@@ -267,11 +267,12 @@ export default (({ user }: Props) => {
{subItem.component} {subItem.component}
</Fragment>) </Fragment>)
: ( : (
<Link key={`sp-l-${ i }-${ j }`} <PrefetchLink
to={subItem.to} key={`sp-l-${ i }-${ j }`}
className="w-full min-h-[36px] flex items-center pl-12"> to={subItem.to}
className="w-full min-h-[36px] flex items-center pl-12">
{subItem.name} {subItem.name}
</Link>)))} </PrefetchLink>)))}
</motion.div>)} </motion.div>)}
</AnimatePresence> </AnimatePresence>
</Fragment>))} </Fragment>))}
+3 -4
ファイルの表示
@@ -1,6 +1,5 @@
import { Link } from 'react-router-dom'
import Separator from '@/components/MenuSeparator' import Separator from '@/components/MenuSeparator'
import PrefetchLink from '@/components/PrefetchLink'
import { cn } from '@/lib/utils' import { cn } from '@/lib/utils'
import type { FC } from 'react' import type { FC } from 'react'
@@ -24,9 +23,9 @@ export default (({ user, sp }: Props) => {
return ( return (
<> <>
{sp && <Separator/>} {sp && <Separator/>}
<Link to="/users/settings" <PrefetchLink to="/users/settings"
className={className}> className={className}>
{user.name || '名もなきニジラー'} {user.name || '名もなきニジラー'}
</Link> </PrefetchLink>
</>) </>)
}) satisfies FC<Props> }) satisfies FC<Props>
+4 -7
ファイルの表示
@@ -1,13 +1,11 @@
import axios from 'axios'
import toCamel from 'camelcase-keys'
import { useEffect, useMemo, useState } from 'react' import { useEffect, useMemo, useState } from 'react'
import ReactMarkdown from 'react-markdown' import ReactMarkdown from 'react-markdown'
import { Link } from 'react-router-dom'
import remarkGFM from 'remark-gfm' import remarkGFM from 'remark-gfm'
import PrefetchLink from '@/components/PrefetchLink'
import SectionTitle from '@/components/common/SectionTitle' import SectionTitle from '@/components/common/SectionTitle'
import SubsectionTitle from '@/components/common/SubsectionTitle' import SubsectionTitle from '@/components/common/SubsectionTitle'
import { API_BASE_URL } from '@/config' import { apiGet } from '@/lib/api'
import remarkWikiAutoLink from '@/lib/remark-wiki-autolink' import remarkWikiAutoLink from '@/lib/remark-wiki-autolink'
import type { FC } from 'react' import type { FC } from 'react'
@@ -24,7 +22,7 @@ const mdComponents = { h1: ({ children }) => <SectionTitle>{children}</SectionT
ul: ({ children }) => <ul className="list-disc pl-6">{children}</ul>, ul: ({ children }) => <ul className="list-disc pl-6">{children}</ul>,
a: (({ href, children }) => ( a: (({ href, children }) => (
['/', '.'].some (e => href?.startsWith (e)) ['/', '.'].some (e => href?.startsWith (e))
? <Link to={href!}>{children}</Link> ? <PrefetchLink to={href!}>{children}</PrefetchLink>
: ( : (
<a href={href} <a href={href}
target="_blank" target="_blank"
@@ -43,8 +41,7 @@ export default (({ title, body }: Props) => {
void (async () => { void (async () => {
try try
{ {
const res = await axios.get (`${ API_BASE_URL }/wiki`) const data = await apiGet<WikiPage[]> ('/wiki')
const data: WikiPage[] = toCamel (res.data as any, { deep: true })
setPageNames (data.map (page => page.title).sort ((a, b) => b.length - a.length)) setPageNames (data.map (page => page.title).sort ((a, b) => b.length - a.length))
} }
catch catch
+6 -4
ファイルの表示
@@ -1,4 +1,6 @@
import { Link, useLocation } from 'react-router-dom' import { useLocation } from 'react-router-dom'
import PrefetchLink from '@/components/PrefetchLink'
import type { FC } from 'react' import type { FC } from 'react'
@@ -61,7 +63,7 @@ export default (({ page, totalPages, siblingCount = 4 }) => {
<nav className="mt-4 flex justify-center" aria-label="Pagination"> <nav className="mt-4 flex justify-center" aria-label="Pagination">
<div className="flex items-center gap-2"> <div className="flex items-center gap-2">
{(page > 1) {(page > 1)
? <Link to={buildTo (page - 1)} aria-label="前のページ">&lt;</Link> ? <PrefetchLink to={buildTo (page - 1)} aria-label="前のページ">&lt;</PrefetchLink>
: <span aria-hidden>&lt;</span>} : <span aria-hidden>&lt;</span>}
{pages.map ((p, idx) => ( {pages.map ((p, idx) => (
@@ -69,10 +71,10 @@ export default (({ page, totalPages, siblingCount = 4 }) => {
? <span key={`dots-${ idx }`}></span> ? <span key={`dots-${ idx }`}></span>
: ((p === page) : ((p === page)
? <span key={p} className="font-bold" aria-current="page">{p}</span> ? <span key={p} className="font-bold" aria-current="page">{p}</span>
: <Link key={p} to={buildTo (p)}>{p}</Link>)))} : <PrefetchLink key={p} to={buildTo (p)}>{p}</PrefetchLink>)))}
{(page < totalPages) {(page < totalPages)
? <Link to={buildTo (page + 1)} aria-label="次のページ">&gt;</Link> ? <PrefetchLink to={buildTo (page + 1)} aria-label="次のページ">&gt;</PrefetchLink>
: <span aria-hidden>&gt;</span>} : <span aria-hidden>&gt;</span>}
</div> </div>
</nav>) </nav>)
+4 -6
ファイルの表示
@@ -1,5 +1,3 @@
import axios from 'axios'
import toCamel from 'camelcase-keys'
import { useState } from 'react' import { useState } from 'react'
import { Button } from '@/components/ui/button' import { Button } from '@/components/ui/button'
@@ -8,7 +6,7 @@ import { Dialog,
DialogTitle } from '@/components/ui/dialog' DialogTitle } from '@/components/ui/dialog'
import { Input } from '@/components/ui/input' import { Input } from '@/components/ui/input'
import { toast } from '@/components/ui/use-toast' import { toast } from '@/components/ui/use-toast'
import { API_BASE_URL } from '@/config' import { apiPost } from '@/lib/api'
import type { User } from '@/types' import type { User } from '@/types'
@@ -26,12 +24,12 @@ export default ({ visible, onVisibleChange, setUser }: Props) => {
try try
{ {
const res = await axios.post (`${ API_BASE_URL }/users/verify`, { code: inputCode }) const data = await apiPost<{ valid: boolean; user: User }> (
const data = res.data as { valid: boolean; user: any } '/users/verify', { code: inputCode })
if (data.valid) if (data.valid)
{ {
localStorage.setItem ('user_code', inputCode) localStorage.setItem ('user_code', inputCode)
setUser (toCamel (data.user, { deep: true })) setUser (data.user)
toast ({ title: '引継ぎ成功!' }) toast ({ title: '引継ぎ成功!' })
onVisibleChange (false) onVisibleChange (false)
} }
+3 -7
ファイルの表示
@@ -1,11 +1,9 @@
import axios from 'axios'
import { Button } from '@/components/ui/button' import { Button } from '@/components/ui/button'
import { Dialog, import { Dialog,
DialogContent, DialogContent,
DialogTitle } from '@/components/ui/dialog' DialogTitle } from '@/components/ui/dialog'
import { toast } from '@/components/ui/use-toast' import { toast } from '@/components/ui/use-toast'
import { API_BASE_URL } from '@/config' import { apiPost } from '@/lib/api'
import type { User } from '@/types' import type { User } from '@/types'
@@ -23,10 +21,8 @@ export default ({ visible, onVisibleChange, user, setUser }: Props) => {
if (!(confirm ('引継ぎコードを再発行しますか?\n再発行するとほかのブラウザからはログアウトされます.'))) if (!(confirm ('引継ぎコードを再発行しますか?\n再発行するとほかのブラウザからはログアウトされます.')))
return return
const res = await axios.post (`${ API_BASE_URL }/users/code/renew`, { }, { headers: { const data = await apiPost<{ code: string }> ('/users/code/renew', { },
'Content-Type': 'multipart/form-data', { headers: { 'Content-Type': 'multipart/form-data' } })
'X-Transfer-Code': localStorage.getItem ('user_code') || '' } })
const data = res.data as { code: string }
if (data.code) if (data.code)
{ {
localStorage.setItem ('user_code', data.code) localStorage.setItem ('user_code', data.code)
+76
ファイルの表示
@@ -0,0 +1,76 @@
import axios from 'axios'
import toCamel from 'camelcase-keys'
import { API_BASE_URL } from '@/config'
import type { AxiosError, AxiosRequestConfig } from 'axios'
type Opt = {
params?: AxiosRequestConfig['params']
headers?: Record<string, string>
responseType?: 'blob' }
const client = axios.create ({ baseURL: API_BASE_URL })
const withUserCode = (opt?: Opt): Opt => ({
...opt,
headers: { 'X-Transfer-Code': localStorage.getItem ('user_code') ?? '',
...(opt?.headers ?? { }) } })
const apiP = async <T> (
method: 'post' | 'put' | 'patch',
path: string,
body?: unknown,
opt?: Opt,
): Promise<T> => {
const res = await client[method] (path, body ?? { }, withUserCode (opt))
if (opt?.responseType === 'blob')
return res.data as T
return toCamel (res.data as any, { deep: true }) as T
}
export const apiGet = async <T> (
path: string,
opt?: Opt,
): Promise<T> => {
const res = await client.get (path, withUserCode (opt))
if (opt?.responseType === 'blob')
return res.data as T
return toCamel (res.data as any, { deep: true }) as T
}
export const apiPost = async <T> (
path: string,
body?: unknown,
opt?: Opt,
): Promise<T> => apiP ('post', path, body, opt)
export const apiPut = async <T> (
path: string,
body?: unknown,
opt?: Opt,
): Promise<T> => apiP ('put', path, body, opt)
export const apiPatch = async <T> (
path: string,
body?: unknown,
opt?: Opt,
): Promise<T> => apiP ('patch', path, body, opt)
export const apiDelete = async (
path: string,
opt?: Opt,
): Promise<void> => {
await client.delete (path, withUserCode (opt))
}
export const isApiError = (err: unknown): err is AxiosError =>
axios.isAxiosError (err)
+41
ファイルの表示
@@ -0,0 +1,41 @@
import { apiDelete, apiGet, apiPost } from '@/lib/api'
import type { Post, PostTagChange } from '@/types'
export const fetchPosts = async (
{ tags, match, page, limit, cursor }: {
tags: string
match: 'any' | 'all'
page?: number
limit?: number
cursor?: string }
): Promise<{
posts: Post[]
count: number
nextCursor: string }> =>
await apiGet ('/posts', { params: {
tags,
match,
...(page && { page }),
...(limit && { limit }),
...(cursor && { cursor }) } })
export const fetchPost = async (id: string): Promise<Post> => await apiGet (`/posts/${ id }`)
export const fetchPostChanges = async (
{ id, page, limit }: {
id?: string
page: number
limit: number },
): Promise<{
changes: PostTagChange[]
count: number }> =>
await apiGet ('/posts/changes', { params: { ...(id && { id }), page, limit } })
export const toggleViewedFlg = async (id: string, viewed: boolean): Promise<void> => {
await (viewed ? apiPost : apiDelete) (`/posts/${ id }/viewed`)
}
+88
ファイルの表示
@@ -0,0 +1,88 @@
import { QueryClient } from '@tanstack/react-query'
import { match } from 'path-to-regexp'
import { fetchPost, fetchPosts, fetchPostChanges } from '@/lib/posts'
import { postsKeys, wikiKeys } from '@/lib/queryKeys'
import { fetchWikiPageByTitle, fetchWikiPages } from '@/lib/wiki'
type Prefetcher = (qc: QueryClient, url: URL) => Promise<void>
const mPost = match<{ id: string }> ('/posts/:id')
const mWiki = match<{ title: string }> ('/wiki/:title')
const prefetchWikiPagesIndex: Prefetcher = async (qc, url) => {
const title = url.searchParams.get ('title') ?? ''
await qc.prefetchQuery ({
queryKey: wikiKeys.index ({ title }),
queryFn: () => fetchWikiPages ({ title }) })
}
const prefetchWikiPageShow: Prefetcher = async (qc, url) => {
const m = mWiki (url.pathname)
if (!(m))
return
const version = url.searchParams.get ('version')
const { title } = m.params
await qc.prefetchQuery ({
queryKey: wikiKeys.show (title, version ? { version } : { }),
queryFn: () => fetchWikiPageByTitle (title, version ? { version } : { }) })
}
const prefetchPostsIndex: Prefetcher = async (qc, url) => {
const tags = url.searchParams.get ('tags') ?? ''
const m = url.searchParams.get ('match') === 'any' ? 'any' : 'all'
const page = Number (url.searchParams.get ('page') || 1)
const limit = Number (url.searchParams.get ('limit') || 20)
await qc.prefetchQuery ({
queryKey: postsKeys.index ({ tags, match: m, page, limit }),
queryFn: () => fetchPosts ({ tags, match: m, page, limit }) })
}
const prefetchPostShow: Prefetcher = async (qc, url) => {
const m = mPost (url.pathname)
if (!(m))
return
const { id } = m.params
await qc.prefetchQuery ({
queryKey: postsKeys.show (id),
queryFn: () => fetchPost (id) })
}
const prefetchPostChanges: Prefetcher = async (qc, url) => {
const id = url.searchParams.get ('id')
const page = Number (url.searchParams.get ('page') || 1)
const limit = Number (url.searchParams.get ('limit') || 20)
await qc.prefetchQuery ({
queryKey: postsKeys.changes ({ ...(id && { id }), page, limit }),
queryFn: () => fetchPostChanges ({ ...(id && { id }), page, limit }) })
}
export const routePrefetchers: { test: (u: URL) => boolean; run: Prefetcher }[] = [
{ test: u => u.pathname === '/' || u.pathname === '/posts', run: prefetchPostsIndex },
{ test: u => (!(['/posts/new', '/posts/changes'].includes (u.pathname))
&& Boolean (mPost (u.pathname))),
run: prefetchPostShow },
{ test: u => u.pathname === '/posts/changes', run: prefetchPostChanges },
{ test: u => u.pathname === '/wiki', run: prefetchWikiPagesIndex },
{ test: u => (!(['/wiki/new', '/wiki/changes'].includes (u.pathname))
&& Boolean (mWiki (u.pathname))),
run: prefetchWikiPageShow },
]
export const prefetchForURL = async (qc: QueryClient, urlLike: string): Promise<void> => {
const u = new URL (urlLike, location.origin)
const jobs = routePrefetchers.filter (r => r.test (u)).map (r => r.run (qc, u))
if (jobs.length === 0)
return
await Promise.all (jobs)
}
+17
ファイルの表示
@@ -0,0 +1,17 @@
export const postsKeys = {
root: ['posts'] as const,
index: (p: { tags: string; match: 'any' | 'all'; page: number; limit: number }) =>
['posts', 'index', p] as const,
show: (id: string) => ['posts', id] as const,
related: (id: string) => ['related', id] as const,
changes: (p: { id?: string; page: number; limit: number }) =>
['posts', 'changes', p] as const }
export const tagsKeys = {
root: ['tags'] as const,
show: (name: string) => ['tags', name] as const }
export const wikiKeys = {
root: ['wiki'] as const,
index: (p: { title: string }) => ['wiki', 'index', p] as const,
show: (title: string, p: { version?: string }) => ['wiki', title, p] as const }
+7
ファイルの表示
@@ -0,0 +1,7 @@
import { apiGet } from '@/lib/api'
import type { Tag } from '@/types'
export const fetchTagByName = async (name: string): Promise<Tag> =>
await apiGet (`/tags/name/${ name }`)
+22
ファイルの表示
@@ -0,0 +1,22 @@
import { apiGet } from '@/lib/api'
import type { WikiPage } from '@/types'
export const fetchWikiPages = async ({ title }: { title: string }) =>
await apiGet ('/wiki', { params: { title } })
export const fetchWikiPage = async (
id: string,
{ version }: { version?: string },
): Promise<WikiPage> =>
await apiGet (`/wiki/${ id }`, { params: version ? { version } : { } })
export const fetchWikiPageByTitle = async (
title: string,
{ version }: { version?: string },
): Promise<WikiPage> =>
await apiGet (`/wiki/title/${ title }`,
{ params: version ? { version } : { } })
+10 -1
ファイルの表示
@@ -1,3 +1,4 @@
import { QueryClient, QueryClientProvider } from '@tanstack/react-query'
import { createRoot } from 'react-dom/client' import { createRoot } from 'react-dom/client'
import { HelmetProvider } from 'react-helmet-async' import { HelmetProvider } from 'react-helmet-async'
@@ -6,7 +7,15 @@ import App from '@/App'
const helmetContext = { } const helmetContext = { }
const client = new QueryClient ({
defaultOptions: {
queries: { staleTime: 5 * 60 * 1000,
gcTime: 30 * 60 * 1000,
retry: 1 }}})
createRoot (document.getElementById ('root')!).render ( createRoot (document.getElementById ('root')!).render (
<HelmetProvider context={helmetContext}> <HelmetProvider context={helmetContext}>
<App/> <QueryClientProvider client={client}>
<App/>
</QueryClientProvider>
</HelmetProvider>) </HelmetProvider>)
+59 -48
ファイルの表示
@@ -1,5 +1,4 @@
import axios from 'axios' import { useMutation, useQuery, useQueryClient } from '@tanstack/react-query'
import toCamel from 'camelcase-keys'
import { useEffect, useState } from 'react' import { useEffect, useState } from 'react'
import { Helmet } from 'react-helmet-async' import { Helmet } from 'react-helmet-async'
import { useParams } from 'react-router-dom' import { useParams } from 'react-router-dom'
@@ -12,63 +11,68 @@ import TabGroup, { Tab } from '@/components/common/TabGroup'
import MainArea from '@/components/layout/MainArea' import MainArea from '@/components/layout/MainArea'
import { Button } from '@/components/ui/button' import { Button } from '@/components/ui/button'
import { toast } from '@/components/ui/use-toast' 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 { cn } from '@/lib/utils'
import NotFound from '@/pages/NotFound' import NotFound from '@/pages/NotFound'
import ServiceUnavailable from '@/pages/ServiceUnavailable' import ServiceUnavailable from '@/pages/ServiceUnavailable'
import type { FC } from 'react' import type { FC } from 'react'
import type { Post, User } from '@/types' import type { User } from '@/types'
type Props = { user: User | null } type Props = { user: User | null }
export default (({ user }: Props) => { export default (({ user }: Props) => {
const { id } = useParams () 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 [status, setStatus] = useState (200)
const changeViewedFlg = async () => { const changeViewedFlg = useMutation ({
const url = `${ API_BASE_URL }/posts/${ id }/viewed` mutationFn: async () => {
const opt = { headers: { 'X-Transfer-Code': localStorage.getItem ('user_code') || '' } } const cur = qc.getQueryData<any> (postKey)
try const next = !(cur?.viewed)
{ await toggleViewedFlg (postId, next)
if (post!.viewed) return next
await axios.delete (url, opt) },
else onMutate: async () => {
await axios.post (url, { }, opt) await qc.cancelQueries ({ queryKey: postKey })
const prev = qc.getQueryData<any> (postKey)
// 通信に成功したら “閲覧済” をトグル qc.setQueryData (postKey,
setPost (post => ({ ...post!, viewed: !(post!.viewed) })) (cur: any) => cur ? { ...cur, viewed: !(cur.viewed) } : cur)
} return { prev }
catch },
{ onError: (...[, , ctx]) => {
toast ({ title: '失敗……', description: '通信に失敗しました……' }) if (ctx?.prev)
} qc.setQueryData (postKey, ctx.prev)
} toast ({ title: '失敗……', description: '通信に失敗しました……' })
},
onSuccess: () => {
qc.invalidateQueries ({ queryKey: postsKeys.root })
} })
useEffect (() => { useEffect (() => {
setPost (null) if (!(errorFlg))
if (!(id))
return return
const fetchPost = async () => { const code = (error as any)?.response.status ?? (error as any)?.status
try if (code)
{ setStatus (code)
const res = await axios.get (`${ API_BASE_URL }/posts/${ id }`, { headers: { }, [errorFlg, error])
'X-Transfer-Code': localStorage.getItem ('user_code') ?? '' } })
setPost (toCamel (res.data as any, { deep: true }) as Post) useEffect (() => {
} setStatus (200)
catch (err)
{
if (axios.isAxiosError (err))
setStatus (err.status ?? 200)
}
}
fetchPost ()
}, [id]) }, [id])
switch (status) switch (status)
@@ -90,15 +94,18 @@ export default (({ user }: Props) => {
<meta name="thumbnail" content={post.thumbnail || post.thumbnailBase}/>)} <meta name="thumbnail" content={post.thumbnail || post.thumbnailBase}/>)}
{post && <title>{`${ post.title || post.url } | ${ SITE_TITLE }`}</title>} {post && <title>{`${ post.title || post.url } | ${ SITE_TITLE }`}</title>}
</Helmet> </Helmet>
<div className="hidden md:block"> <div className="hidden md:block">
<TagDetailSidebar post={post}/> <TagDetailSidebar post={post ?? null}/>
</div> </div>
<MainArea> <MainArea>
{post {post
? ( ? (
<> <>
<PostEmbed post={post}/> <PostEmbed post={post}/>
<Button onClick={changeViewedFlg} <Button onClick={() => changeViewedFlg.mutate ()}
disabled={changeViewedFlg.isPending}
className={cn ('text-white', viewedClass)}> className={cn ('text-white', viewedClass)}>
{post.viewed ? '閲覧済' : '未閲覧'} {post.viewed ? '閲覧済' : '未閲覧'}
</Button> </Button>
@@ -110,18 +117,22 @@ export default (({ user }: Props) => {
</Tab> </Tab>
{['admin', 'member'].some (r => user?.role === r) && ( {['admin', 'member'].some (r => user?.role === r) && (
<Tab name="編輯"> <Tab name="編輯">
<PostEditForm post={post} <PostEditForm
onSave={newPost => { post={post}
setPost (newPost) onSave={newPost => {
toast ({ description: '更新しました.' }) qc.setQueryData (postsKeys.show (postId),
}}/> (prev: any) => newPost ?? prev)
qc.invalidateQueries ({ queryKey: postsKeys.root })
toast ({ description: '更新しました.' })
}}/>
</Tab>)} </Tab>)}
</TabGroup> </TabGroup>
</>) </>)
: 'Loading...'} : 'Loading...'}
</MainArea> </MainArea>
<div className="md:hidden"> <div className="md:hidden">
<TagDetailSidebar post={post}/> <TagDetailSidebar post={post ?? null}/>
</div> </div>
</div>) </div>)
}) satisfies FC<Props> }) satisfies FC<Props>
+63 -70
ファイルの表示
@@ -1,24 +1,20 @@
import axios from 'axios' import { useQuery } from '@tanstack/react-query'
import toCamel from 'camelcase-keys'
import { useEffect, useState } from 'react'
import { Helmet } from 'react-helmet-async' import { Helmet } from 'react-helmet-async'
import { Link, useLocation } from 'react-router-dom' import { useLocation } from 'react-router-dom'
import TagLink from '@/components/TagLink' import TagLink from '@/components/TagLink'
import PrefetchLink from '@/components/PrefetchLink'
import PageTitle from '@/components/common/PageTitle' import PageTitle from '@/components/common/PageTitle'
import Pagination from '@/components/common/Pagination' import Pagination from '@/components/common/Pagination'
import MainArea from '@/components/layout/MainArea' import MainArea from '@/components/layout/MainArea'
import { API_BASE_URL, SITE_TITLE } from '@/config' import { SITE_TITLE } from '@/config'
import { fetchPostChanges } from '@/lib/posts'
import { postsKeys } from '@/lib/queryKeys'
import type { FC } from 'react' import type { FC } from 'react'
import type { PostTagChange } from '@/types'
export default (() => { export default (() => {
const [changes, setChanges] = useState<PostTagChange[]> ([])
const [totalPages, setTotalPages] = useState<number> (0)
const location = useLocation () const location = useLocation ()
const query = new URLSearchParams (location.search) const query = new URLSearchParams (location.search)
const id = query.get ('id') const id = query.get ('id')
@@ -28,17 +24,11 @@ export default (() => {
// 投稿列の結合で使用 // 投稿列の結合で使用
let rowsCnt: number let rowsCnt: number
useEffect (() => { const { data, isLoading: loading } = useQuery ({
void (async () => { queryKey: postsKeys.changes ({ ...(id && { id }), page, limit }),
const res = await axios.get (`${ API_BASE_URL }/posts/changes`, queryFn: () => fetchPostChanges ({ ...(id && { id }), page, limit }) })
{ params: { ...(id && { id }), page, limit } }) const changes = data?.changes ?? []
const data = toCamel (res.data as any, { deep: true }) as { const totalPages = data ? Math.ceil (data.count / limit) : 0
changes: PostTagChange[]
count: number }
setChanges (data.changes)
setTotalPages (Math.ceil (data.count / limit))
}) ()
}, [id, page, limit])
return ( return (
<MainArea> <MainArea>
@@ -48,57 +38,60 @@ export default (() => {
<PageTitle> <PageTitle>
{id && <>: 稿 {<Link to={`/posts/${ id }`}>#{id}</Link>}</>} {id && <>: 稿 {<PrefetchLink to={`/posts/${ id }`}>#{id}</PrefetchLink>}</>}
</PageTitle> </PageTitle>
<table className="table-auto w-full border-collapse"> {loading ? 'Loading...' : (
<thead> <>
<tr> <table className="table-auto w-full border-collapse">
<th className="p-2 text-left">稿</th> <thead>
<th className="p-2 text-left"></th> <tr>
<th className="p-2 text-left"></th> <th className="p-2 text-left">稿</th>
</tr> <th className="p-2 text-left"></th>
</thead> <th className="p-2 text-left"></th>
<tbody> </tr>
{changes.map ((change, i) => { </thead>
let withPost = i === 0 || change.post.id !== changes[i - 1].post.id <tbody>
if (withPost) {changes.map ((change, i) => {
{ let withPost = i === 0 || change.post.id !== changes[i - 1].post.id
rowsCnt = 1 if (withPost)
for (let j = i + 1; {
(j < changes.length rowsCnt = 1
&& change.post.id === changes[j].post.id); for (let j = i + 1;
++j) (j < changes.length
++rowsCnt && change.post.id === changes[j].post.id);
} ++j)
return ( ++rowsCnt
<tr key={`${ change.timestamp }-${ change.post.id }-${ change.tag.id }`}> }
{withPost && ( return (
<td className="align-top" rowSpan={rowsCnt}> <tr key={`${ change.timestamp }-${ change.post.id }-${ change.tag.id }`}>
<Link to={`/posts/${ change.post.id }`}> {withPost && (
<img src={change.post.thumbnail || change.post.thumbnailBase || undefined} <td className="align-top" rowSpan={rowsCnt}>
alt={change.post.title || change.post.url} <PrefetchLink to={`/posts/${ change.post.id }`}>
title={change.post.title || change.post.url || undefined} <img src={change.post.thumbnail || change.post.thumbnailBase || undefined}
className="w-40"/> alt={change.post.title || change.post.url}
</Link> title={change.post.title || change.post.url || undefined}
</td>)} className="w-40"/>
<td> </PrefetchLink>
<TagLink tag={change.tag} withWiki={false} withCount={false}/> </td>)}
{`${ change.changeType === 'add' ? '追加' : '削除' }`} <td>
</td> <TagLink tag={change.tag} withWiki={false} withCount={false}/>
<td> {`${ change.changeType === 'add' ? '記載' : '消除' }`}
{change.user ? ( </td>
<Link to={`/users/${ change.user.id }`}> <td>
{change.user.name} {change.user ? (
</Link>) : 'bot 操作'} <PrefetchLink to={`/users/${ change.user.id }`}>
<br/> {change.user.name}
{change.timestamp} </PrefetchLink>) : 'bot 操作'}
</td> <br/>
</tr>) {change.timestamp}
})} </td>
</tbody> </tr>)
</table> })}
</tbody>
</table>
<Pagination page={page} totalPages={totalPages}/> <Pagination page={page} totalPages={totalPages}/>
</>)}
</MainArea>) </MainArea>)
}) satisfies FC }) satisfies FC
+28 -83
ファイルの表示
@@ -1,97 +1,46 @@
import axios from 'axios' import { useQuery } from '@tanstack/react-query'
import toCamel from 'camelcase-keys' import { useLayoutEffect, useRef, useState } from 'react'
import { useEffect, useLayoutEffect, useRef, useState } from 'react'
import { Helmet } from 'react-helmet-async' 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 PostList from '@/components/PostList'
import PrefetchLink from '@/components/PrefetchLink'
import TagSidebar from '@/components/TagSidebar' import TagSidebar from '@/components/TagSidebar'
import WikiBody from '@/components/WikiBody' import WikiBody from '@/components/WikiBody'
import Pagination from '@/components/common/Pagination' import Pagination from '@/components/common/Pagination'
import TabGroup, { Tab } from '@/components/common/TabGroup' import TabGroup, { Tab } from '@/components/common/TabGroup'
import MainArea from '@/components/layout/MainArea' 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 () => { export default () => {
const navigationType = useNavigationType ()
const containerRef = useRef<HTMLDivElement | null> (null) 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 [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 location = useLocation ()
const query = new URLSearchParams (location.search) const query = new URLSearchParams (location.search)
const tagsQuery = query.get ('tags') ?? '' const tagsQuery = query.get ('tags') ?? ''
const anyFlg = query.get ('match') === 'any' const anyFlg = query.get ('match') === 'any'
const match = anyFlg ? 'any' : 'all'
const tags = tagsQuery.split (' ').filter (e => e !== '') const tags = tagsQuery.split (' ').filter (e => e !== '')
const tagsKey = tags.join (' ')
const page = Number (query.get ('page') ?? 1) const page = Number (query.get ('page') ?? 1)
const limit = Number (query.get ('limit') ?? 20) const limit = Number (query.get ('limit') ?? 20)
useEffect(() => { const { data, isLoading: loading } = useQuery ({
const observer = new IntersectionObserver (entries => { queryKey: postsKeys.index ({ tags: tagsKey, match, page, limit }),
if (entries[0].isIntersecting && !(loading) && cursor) queryFn: () => fetchPosts ({ tags: tagsKey, match, page, limit }) })
loadMore (true) const posts = data?.posts ?? []
}, { threshold: 1 }) const cursor = data?.nextCursor ?? ''
const totalPages = data ? Math.ceil (data.count / limit) : 0
const target = loaderRef.current
target && observer.observe (target)
return () => {
target && observer.unobserve (target)
}
}, [loaderRef, loading])
useLayoutEffect (() => { 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) setWikiPage (null)
if (tags.length === 1) if (tags.length === 1)
{ {
@@ -99,8 +48,7 @@ export default () => {
try try
{ {
const tagName = tags[0] const tagName = tags[0]
const res = await axios.get (`${ API_BASE_URL }/wiki/title/${ tagName }`) setWikiPage (await fetchWikiPageByTitle (tagName, { }))
setWikiPage (toCamel (res.data as any, { deep: true }) as WikiPage)
} }
catch catch
{ {
@@ -120,7 +68,13 @@ export default () => {
</title> </title>
</Helmet> </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> <MainArea>
<TabGroup> <TabGroup>
@@ -128,28 +82,19 @@ export default () => {
{posts.length > 0 {posts.length > 0
? ( ? (
<> <>
<PostList posts={posts} onClick={() => { <PostList posts={posts}/>
// TODO: 無限ロード用なので復活時に戻す.
// const statesToSave = {
// posts, cursor,
// scroll: containerRef.current?.scrollTop ?? 0 }
// sessionStorage.setItem (`posts:${ tagsQuery }`,
// JSON.stringify (statesToSave))
}}/>
<Pagination page={page} totalPages={totalPages}/> <Pagination page={page} totalPages={totalPages}/>
</>) </>)
: !(loading) && '広場には何もありませんよ.'} : !(loading) && '広場には何もありませんよ.'}
{loading && 'Loading...'} {loading && 'Loading...'}
{/* TODO: 無限ローディング復活までコメント・アウト */}
{/* <div ref={loaderRef} className="h-12"/> */}
</Tab> </Tab>
{tags.length === 1 && ( {tags.length === 1 && (
<Tab name="Wiki"> <Tab name="Wiki">
<WikiBody title={tags[0]} body={wikiPage?.body}/> <WikiBody title={tags[0]} body={wikiPage?.body}/>
<div className="my-2"> <div className="my-2">
<Link to={`/wiki/${ encodeURIComponent (tags[0]) }`}> <PrefetchLink to={`/wiki/${ encodeURIComponent (tags[0]) }`}>
Wiki Wiki
</Link> </PrefetchLink>
</div> </div>
</Tab>)} </Tab>)}
</TabGroup> </TabGroup>
+6 -14
ファイルの表示
@@ -1,4 +1,3 @@
import axios from 'axios'
import { useEffect, useState, useRef } from 'react' import { useEffect, useState, useRef } from 'react'
import { Helmet } from 'react-helmet-async' import { Helmet } from 'react-helmet-async'
import { useNavigate } from 'react-router-dom' import { useNavigate } from 'react-router-dom'
@@ -11,7 +10,8 @@ import PageTitle from '@/components/common/PageTitle'
import MainArea from '@/components/layout/MainArea' import MainArea from '@/components/layout/MainArea'
import { Button } from '@/components/ui/button' import { Button } from '@/components/ui/button'
import { toast } from '@/components/ui/use-toast' import { toast } from '@/components/ui/use-toast'
import { API_BASE_URL, SITE_TITLE } from '@/config' import { SITE_TITLE } from '@/config'
import { apiGet, apiPost } from '@/lib/api'
import Forbidden from '@/pages/Forbidden' import Forbidden from '@/pages/Forbidden'
import type { FC } from 'react' import type { FC } from 'react'
@@ -55,9 +55,7 @@ export default (({ user }: Props) => {
try try
{ {
await axios.post (`${ API_BASE_URL }/posts`, formData, { headers: { await apiPost ('/posts', formData, { headers: { 'Content-Type': 'multipart/form-data' } })
'Content-Type': 'multipart/form-data',
'X-Transfer-Code': localStorage.getItem ('user_code') ?? '' } })
toast ({ title: '投稿成功!' }) toast ({ title: '投稿成功!' })
navigate ('/posts') navigate ('/posts')
} }
@@ -91,10 +89,7 @@ export default (({ user }: Props) => {
const fetchTitle = async () => { const fetchTitle = async () => {
setTitle ('') setTitle ('')
setTitleLoading (true) setTitleLoading (true)
const res = await axios.get (`${ API_BASE_URL }/preview/title`, { const data = await apiGet<{ title: string }> ('/preview/title', { params: { url } })
params: { url },
headers: { 'X-Transfer-Code': localStorage.getItem ('user_code') || '' } })
const data = res.data as { title: string }
setTitle (data.title || '') setTitle (data.title || '')
setTitleLoading (false) setTitleLoading (false)
} }
@@ -105,11 +100,8 @@ export default (({ user }: Props) => {
setThumbnailLoading (true) setThumbnailLoading (true)
if (thumbnailPreview) if (thumbnailPreview)
URL.revokeObjectURL (thumbnailPreview) URL.revokeObjectURL (thumbnailPreview)
const res = await axios.get (`${ API_BASE_URL }/preview/thumbnail`, { const data = await apiGet<Blob> ('/preview/thumbnail',
params: { url }, { params: { url }, responseType: 'blob' })
headers: { 'X-Transfer-Code': localStorage.getItem ('user_code') || '' },
responseType: 'blob' })
const data = res.data as Blob
const imageURL = URL.createObjectURL (data) const imageURL = URL.createObjectURL (data)
setThumbnailPreview (imageURL) setThumbnailPreview (imageURL)
setThumbnailFile (new File ([data], setThumbnailFile (new File ([data],
+6 -11
ファイルの表示
@@ -1,5 +1,3 @@
import axios from 'axios'
import toCamel from 'camelcase-keys'
import { useEffect, useRef, useState } from 'react' import { useEffect, useRef, useState } from 'react'
import { Helmet } from 'react-helmet-async' import { Helmet } from 'react-helmet-async'
@@ -8,7 +6,8 @@ import SectionTitle from '@/components/common/SectionTitle'
import TextArea from '@/components/common/TextArea' import TextArea from '@/components/common/TextArea'
import MainArea from '@/components/layout/MainArea' import MainArea from '@/components/layout/MainArea'
import { toast } from '@/components/ui/use-toast' import { toast } from '@/components/ui/use-toast'
import { API_BASE_URL, SITE_TITLE } from '@/config' import { SITE_TITLE } from '@/config'
import { apiGet, apiPut } from '@/lib/api'
import type { NicoTag, Tag, User } from '@/types' import type { NicoTag, Tag, User } from '@/types'
@@ -29,10 +28,8 @@ export default ({ user }: Props) => {
const loadMore = async (withCursor: boolean) => { const loadMore = async (withCursor: boolean) => {
setLoading (true) setLoading (true)
const res = await axios.get (`${ API_BASE_URL }/tags/nico`, { const data = await apiGet<{ tags: NicoTag[]; nextCursor: string }> (
params: { ...(withCursor ? { cursor } : { }) } }) '/tags/nico', { params: withCursor ? { cursor } : { } })
const data = toCamel (res.data as any, { deep: true }) as { tags: NicoTag[]
nextCursor: string }
setNicoTags (tags => [...(withCursor ? tags : []), ...data.tags]) setNicoTags (tags => [...(withCursor ? tags : []), ...data.tags])
setCursor (data.nextCursor) setCursor (data.nextCursor)
@@ -53,10 +50,8 @@ export default ({ user }: Props) => {
const formData = new FormData const formData = new FormData
formData.append ('tags', rawTags[id]) formData.append ('tags', rawTags[id])
const res = await axios.put (`${ API_BASE_URL }/tags/nico/${ id }`, formData, { headers: { const data = await apiPut<Tag[]> (`/tags/nico/${ id }`, formData,
'Content-Type': 'multipart/form-data', { headers: { 'Content-Type': 'multipart/form-data' } })
'X-Transfer-Code': localStorage.getItem ('user_code') ?? '' } })
const data = toCamel (res.data as any, { deep: true }) as Tag[]
setNicoTags (nicoTags => { setNicoTags (nicoTags => {
nicoTags.find (t => t.id === id)!.linkedTags = data nicoTags.find (t => t.id === id)!.linkedTags = data
return [...nicoTags] return [...nicoTags]
+5 -6
ファイルの表示
@@ -1,4 +1,3 @@
import axios from 'axios'
import { useEffect, useState } from 'react' import { useEffect, useState } from 'react'
import { Helmet } from 'react-helmet-async' import { Helmet } from 'react-helmet-async'
@@ -10,7 +9,8 @@ import InheritDialogue from '@/components/users/InheritDialogue'
import UserCodeDialogue from '@/components/users/UserCodeDialogue' import UserCodeDialogue from '@/components/users/UserCodeDialogue'
import { Button } from '@/components/ui/button' import { Button } from '@/components/ui/button'
import { toast } from '@/components/ui/use-toast' import { toast } from '@/components/ui/use-toast'
import { API_BASE_URL, SITE_TITLE } from '@/config' import { SITE_TITLE } from '@/config'
import { apiPut } from '@/lib/api'
import type { User } from '@/types' import type { User } from '@/types'
@@ -32,10 +32,9 @@ export default ({ user, setUser }: Props) => {
try try
{ {
const res = await axios.put (`${ API_BASE_URL }/users/${ user.id }`, formData, { const data = await apiPut<User> (
headers: { 'Content-Type': 'multipart/form-data', `/users/${ user.id }`, formData,
'X-Transfer-Code': localStorage.getItem ('user_code') || '' } }) { headers: { 'Content-Type': 'multipart/form-data' } })
const data = res.data as User
setUser (user => ({ ...user, ...data })) setUser (user => ({ ...user, ...data }))
toast ({ title: '設定を更新しました.' }) toast ({ title: '設定を更新しました.' })
} }
+51 -76
ファイルの表示
@@ -1,19 +1,23 @@
import axios from 'axios' import { useQuery } from '@tanstack/react-query'
import toCamel from 'camelcase-keys' import { useEffect, useMemo } from 'react'
import { useEffect, useState } from 'react'
import { Helmet } from 'react-helmet-async' 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 PostList from '@/components/PostList'
import PrefetchLink from '@/components/PrefetchLink'
import TagLink from '@/components/TagLink' import TagLink from '@/components/TagLink'
import WikiBody from '@/components/WikiBody' import WikiBody from '@/components/WikiBody'
import PageTitle from '@/components/common/PageTitle' import PageTitle from '@/components/common/PageTitle'
import TabGroup, { Tab } from '@/components/common/TabGroup' import TabGroup, { Tab } from '@/components/common/TabGroup'
import MainArea from '@/components/layout/MainArea' 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 { WikiIdBus } from '@/lib/eventBus/WikiIdBus'
import { fetchPosts } from '@/lib/posts'
import { postsKeys, tagsKeys, wikiKeys } from '@/lib/queryKeys'
import { fetchTagByName } from '@/lib/tags'
import { fetchWikiPage, fetchWikiPageByTitle } from '@/lib/wiki'
import type { Post, Tag, WikiPage } from '@/types' import type { Tag } from '@/types'
export default () => { export default () => {
@@ -23,87 +27,57 @@ export default () => {
const location = useLocation () const location = useLocation ()
const navigate = useNavigate () const navigate = useNavigate ()
const defaultTag = { name: title, category: 'general' } as Tag const defaultTag = useMemo (() => ({ name: title, category: 'general' } as Tag), [title])
const [posts, setPosts] = useState<Post[]> ([])
const [tag, setTag] = useState (defaultTag)
const [wikiPage, setWikiPage] = useState<WikiPage | null | undefined> (undefined)
const query = new URLSearchParams (location.search) const query = new URLSearchParams (location.search)
const version = query.get ('version') const version = query.get ('version')
const { data: wikiPage } = useQuery ({
enabled: Boolean (title) && !(/^\d+$/.test (title)),
queryKey: wikiKeys.show (title ?? '', version ? { version } : { }),
queryFn: () => fetchWikiPageByTitle (title ?? '', version ? { version } : { }) })
const effectiveTitle = wikiPage?.title ?? title
const { data: tag } = useQuery ({
enabled: Boolean (effectiveTitle),
queryKey: tagsKeys.show (effectiveTitle),
queryFn: () => fetchTagByName (effectiveTitle) })
const { data } = useQuery ({
enabled: Boolean (effectiveTitle) && !(version),
queryKey: postsKeys.index ({ tags: effectiveTitle, match: 'all', page: 1, limit: 8 }),
queryFn: () => fetchPosts ({ tags: effectiveTitle, match: 'all', page: 1, limit: 8 }) })
const posts = data?.posts || []
useEffect (() => { useEffect (() => {
if (/^\d+$/.test (title)) if (!(wikiPage))
{ return
void (async () => {
setWikiPage (undefined)
try
{
const res = await axios.get (`${ API_BASE_URL }/wiki/${ title }`)
const data = res.data as WikiPage
navigate (`/wiki/${ encodeURIComponent(data.title) }`, { replace: true })
}
catch
{
;
}
}) ()
return WikiIdBus.set (wikiPage.id)
}
void (async () => { if (wikiPage.title !== title)
setWikiPage (undefined) navigate (`/wiki/${ encodeURIComponent(wikiPage.title) }`, { replace: true })
try
{ return () => WikiIdBus.set (null)
const res = await axios.get ( }, [wikiPage, title, navigate])
`${ API_BASE_URL }/wiki/title/${ encodeURIComponent (title) }`,
{ params: version ? { version } : { } }) useEffect (() => {
const data = toCamel (res.data as any, { deep: true }) as WikiPage if (!(/^\d+$/.test (title)))
if (data.title !== title) return
navigate (`/wiki/${ encodeURIComponent(data.title) }`, { replace: true })
setWikiPage (data)
WikiIdBus.set (data.id)
}
catch
{
setWikiPage (null)
}
}) ()
setPosts ([])
void (async () => { void (async () => {
try try
{ {
const res = await axios.get ( const data = await fetchWikiPage (title, { })
`${ API_BASE_URL }/posts?${ new URLSearchParams ({ tags: title, navigate (`/wiki/${ encodeURIComponent(data.title) }`, { replace: true })
limit: '8' }) }`)
const data = toCamel (res.data as any,
{ deep: true }) as { posts: Post[]
nextCursor: string }
setPosts (data.posts)
} }
catch catch
{ {
; ;
} }
}) () }) ()
}, [title, version])
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)
}
catch
{
setTag (defaultTag)
}
}) ()
return () => WikiIdBus.set (null)
}, [title, location.search])
return ( return (
<MainArea> <MainArea>
@@ -113,22 +87,23 @@ export default () => {
</Helmet> </Helmet>
{(wikiPage && version) && ( {(wikiPage && version) && (
<div className="text-sm flex gap-3 items-center justify-center border border-gray-700 rounded px-2 py-1 mb-4"> <div className="text-sm flex gap-3 items-center justify-center
border border-gray-700 rounded px-2 py-1 mb-4">
{wikiPage.pred ? ( {wikiPage.pred ? (
<Link to={`/wiki/${ encodeURIComponent (title) }?version=${ wikiPage.pred }`}> <PrefetchLink to={`/wiki/${ encodeURIComponent (title) }?version=${ wikiPage.pred }`}>
&lt; &lt;
</Link>) : '(最古)'} </PrefetchLink>) : '(最古)'}
<span>{wikiPage.updatedAt}</span> <span>{wikiPage.updatedAt}</span>
{wikiPage.succ ? ( {wikiPage.succ ? (
<Link to={`/wiki/${ encodeURIComponent (title) }?version=${ wikiPage.succ }`}> <PrefetchLink to={`/wiki/${ encodeURIComponent (title) }?version=${ wikiPage.succ }`}>
&gt; &gt;
</Link>) : '(最新)'} </PrefetchLink>) : '(最新)'}
</div>)} </div>)}
<PageTitle> <PageTitle>
<TagLink tag={tag} <TagLink tag={tag ?? defaultTag}
withWiki={false} withWiki={false}
withCount={false} withCount={false}
{...(version && { to: `/wiki/${ encodeURIComponent (title) }` })}/> {...(version && { to: `/wiki/${ encodeURIComponent (title) }` })}/>
+3 -5
ファイルの表示
@@ -1,12 +1,11 @@
import axios from 'axios'
import toCamel from 'camelcase-keys'
import { useEffect, useState } from 'react' import { useEffect, useState } from 'react'
import { Helmet } from 'react-helmet-async' import { Helmet } from 'react-helmet-async'
import { useLocation, useParams } from 'react-router-dom' import { useLocation, useParams } from 'react-router-dom'
import PageTitle from '@/components/common/PageTitle' import PageTitle from '@/components/common/PageTitle'
import MainArea from '@/components/layout/MainArea' import MainArea from '@/components/layout/MainArea'
import { API_BASE_URL, SITE_TITLE } from '@/config' import { SITE_TITLE } from '@/config'
import { apiGet } from '@/lib/api'
import { cn } from '@/lib/utils' import { cn } from '@/lib/utils'
import type { WikiPageDiff } from '@/types' import type { WikiPageDiff } from '@/types'
@@ -25,8 +24,7 @@ export default () => {
useEffect (() => { useEffect (() => {
void (async () => { void (async () => {
const res = await axios.get (`${ API_BASE_URL }/wiki/${ id }/diff`, { params: { from, to } }) setDiff (await apiGet<WikiPageDiff> (`/wiki/${ id }/diff`, { params: { from, to } }))
setDiff (toCamel (res.data as any, { deep: true }) as WikiPageDiff)
}) () }) ()
}, []) }, [])
+5 -7
ファイルの表示
@@ -1,4 +1,3 @@
import axios from 'axios'
import MarkdownIt from 'markdown-it' import MarkdownIt from 'markdown-it'
import { useEffect, useState } from 'react' import { useEffect, useState } from 'react'
import { Helmet } from 'react-helmet-async' import { Helmet } from 'react-helmet-async'
@@ -7,7 +6,8 @@ import { useParams, useNavigate } from 'react-router-dom'
import MainArea from '@/components/layout/MainArea' import MainArea from '@/components/layout/MainArea'
import { toast } from '@/components/ui/use-toast' import { toast } from '@/components/ui/use-toast'
import { API_BASE_URL, SITE_TITLE } from '@/config' import { SITE_TITLE } from '@/config'
import { apiGet, apiPut } from '@/lib/api'
import Forbidden from '@/pages/Forbidden' import Forbidden from '@/pages/Forbidden'
import 'react-markdown-editor-lite/lib/index.css' import 'react-markdown-editor-lite/lib/index.css'
@@ -40,9 +40,8 @@ export default (({ user }: Props) => {
try try
{ {
await axios.put (`${ API_BASE_URL }/wiki/${ id }`, formData, { headers: { await apiPut (`/wiki/${ id }`, formData,
'Content-Type': 'multipart/form-data', { headers: { 'Content-Type': 'multipart/form-data' } })
'X-Transfer-Code': localStorage.getItem ('user_code') ?? '' } })
toast ({ title: '投稿成功!' }) toast ({ title: '投稿成功!' })
navigate (`/wiki/${ title }`) navigate (`/wiki/${ title }`)
} }
@@ -55,8 +54,7 @@ export default (({ user }: Props) => {
useEffect (() => { useEffect (() => {
void (async () => { void (async () => {
setLoading (true) setLoading (true)
const res = await axios.get (`${ API_BASE_URL }/wiki/${ id }`) const data = await apiGet<WikiPage> (`/wiki/${ id }`)
const data = res.data as WikiPage
setTitle (data.title) setTitle (data.title)
setBody (data.body) setBody (data.body)
setLoading (false) setLoading (false)
+13 -13
ファイルの表示
@@ -1,11 +1,11 @@
import axios from 'axios'
import toCamel from 'camelcase-keys'
import { useEffect, useState } from 'react' import { useEffect, useState } from 'react'
import { Helmet } from 'react-helmet-async' import { Helmet } from 'react-helmet-async'
import { Link, useLocation } from 'react-router-dom' import { useLocation } from 'react-router-dom'
import PrefetchLink from '@/components/PrefetchLink'
import MainArea from '@/components/layout/MainArea' import MainArea from '@/components/layout/MainArea'
import { API_BASE_URL, SITE_TITLE } from '@/config' import { SITE_TITLE } from '@/config'
import { apiGet } from '@/lib/api'
import type { WikiPageChange } from '@/types' import type { WikiPageChange } from '@/types'
@@ -19,9 +19,7 @@ export default () => {
useEffect (() => { useEffect (() => {
void (async () => { void (async () => {
const res = await axios.get (`${ API_BASE_URL }/wiki/changes`, setChanges (await apiGet<WikiPageChange[]> ('/wiki/changes', { params: id ? { id } : { } }))
{ params: { ...(id ? { id } : { }) } })
setChanges (toCamel (res.data as any, { deep: true }) as WikiPageChange[])
}) () }) ()
}, [location.search]) }, [location.search])
@@ -44,22 +42,24 @@ export default () => {
<tr key={change.revisionId}> <tr key={change.revisionId}>
<td> <td>
{change.pred != null && ( {change.pred != null && (
<Link to={`/wiki/${ change.wikiPage.id }/diff?from=${ change.pred }&to=${ change.revisionId }`}> <PrefetchLink
to={`/wiki/${ change.wikiPage.id }/diff?from=${ change.pred }&to=${ change.revisionId }`}>
</Link>)} </PrefetchLink>)}
</td> </td>
<td className="p-2"> <td className="p-2">
<Link to={`/wiki/${ encodeURIComponent (change.wikiPage.title) }?version=${ change.revisionId }`}> <PrefetchLink
to={`/wiki/${ encodeURIComponent (change.wikiPage.title) }?version=${ change.revisionId }`}>
{change.wikiPage.title} {change.wikiPage.title}
</Link> </PrefetchLink>
</td> </td>
<td className="p-2"> <td className="p-2">
{change.pred == null ? '新規' : '更新'} {change.pred == null ? '新規' : '更新'}
</td> </td>
<td className="p-2"> <td className="p-2">
<Link to={`/users/${ change.user.id }`}> <PrefetchLink to={`/users/${ change.user.id }`}>
{change.user.name} {change.user.name}
</Link> </PrefetchLink>
<br/> <br/>
{change.timestamp} {change.timestamp}
</td> </td>
+4 -6
ファイルの表示
@@ -1,4 +1,3 @@
import axios from 'axios'
import MarkdownIt from 'markdown-it' import MarkdownIt from 'markdown-it'
import { useState } from 'react' import { useState } from 'react'
import { Helmet } from 'react-helmet-async' import { Helmet } from 'react-helmet-async'
@@ -7,7 +6,8 @@ import { useLocation, useNavigate } from 'react-router-dom'
import MainArea from '@/components/layout/MainArea' import MainArea from '@/components/layout/MainArea'
import { toast } from '@/components/ui/use-toast' import { toast } from '@/components/ui/use-toast'
import { API_BASE_URL, SITE_TITLE } from '@/config' import { SITE_TITLE } from '@/config'
import { apiPost } from '@/lib/api'
import Forbidden from '@/pages/Forbidden' import Forbidden from '@/pages/Forbidden'
import 'react-markdown-editor-lite/lib/index.css' import 'react-markdown-editor-lite/lib/index.css'
@@ -39,10 +39,8 @@ export default ({ user }: Props) => {
try try
{ {
const res = await axios.post (`${ API_BASE_URL }/wiki`, formData, { headers: { const data = await apiPost<WikiPage> ('/wiki', formData,
'Content-Type': 'multipart/form-data', { headers: { 'Content-Type': 'multipart/form-data' } })
'X-Transfer-Code': localStorage.getItem ('user_code') || '' } })
const data = res.data as WikiPage
toast ({ title: '投稿成功!' }) toast ({ title: '投稿成功!' })
navigate (`/wiki/${ data.title }`) navigate (`/wiki/${ data.title }`)
} }
+10 -10
ファイルの表示
@@ -1,12 +1,13 @@
import axios from 'axios' import { useEffect, useState } from 'react'
import toCamel from 'camelcase-keys'
import React, { useEffect, useState } from 'react'
import { Helmet } from 'react-helmet-async' import { Helmet } from 'react-helmet-async'
import { Link } from 'react-router-dom'
import PrefetchLink from '@/components/PrefetchLink'
import SectionTitle from '@/components/common/SectionTitle' import SectionTitle from '@/components/common/SectionTitle'
import MainArea from '@/components/layout/MainArea' import MainArea from '@/components/layout/MainArea'
import { API_BASE_URL, SITE_TITLE } from '@/config' import { SITE_TITLE } from '@/config'
import { apiGet } from '@/lib/api'
import type { FormEvent } from 'react'
import type { WikiPage } from '@/types' import type { WikiPage } from '@/types'
@@ -17,11 +18,10 @@ export default () => {
const [results, setResults] = useState<WikiPage[]> ([]) const [results, setResults] = useState<WikiPage[]> ([])
const search = async () => { const search = async () => {
const res = await axios.get (`${ API_BASE_URL }/wiki/search`, { params: { title } }) setResults (await apiGet ('/wiki', { params: { title } }))
setResults (toCamel (res.data as any, { deep: true }) as WikiPage[])
} }
const handleSearch = (ev: React.FormEvent) => { const handleSearch = (ev: FormEvent) => {
ev.preventDefault () ev.preventDefault ()
search () search ()
} }
@@ -78,9 +78,9 @@ export default () => {
{results.map (page => ( {results.map (page => (
<tr key={page.id}> <tr key={page.id}>
<td className="p-2"> <td className="p-2">
<Link to={`/wiki/${ encodeURIComponent (page.title) }`}> <PrefetchLink to={`/wiki/${ encodeURIComponent (page.title) }`}>
{page.title} {page.title}
</Link> </PrefetchLink>
</td> </td>
<td className="p-2 text-gray-100 text-sm"> <td className="p-2 text-gray-100 text-sm">
{page.updatedAt} {page.updatedAt}