feat: add tweet detail page

This commit is contained in:
2026-07-14 00:50:08 +09:00
parent 8e6ff70d81
commit da72094e07
9 changed files with 272 additions and 30 deletions
+1 -1
View File
@@ -4,7 +4,7 @@ export function AppShell({
active, active,
children, children,
}: { }: {
active: 'user' | 'search' active?: 'user' | 'search'
children: React.ReactNode children: React.ReactNode
}) { }) {
return ( return (
@@ -80,6 +80,21 @@ describe('PostCard', () => {
expect(screen.getByText('@yuta').closest('a')).toBeNull() expect(screen.getByText('@yuta').closest('a')).toBeNull()
}) })
it('links deliberately to the internal detail page', () => {
render(<PostCard post={richPost} />)
expect(
screen.getByRole('link', { name: '詳細・スレッド' }),
).toHaveAttribute('href', '/status/123')
})
it('marks the focal post without linking to its current page', () => {
render(<PostCard current post={{ ...richPost, quotedTweet: undefined }} />)
expect(screen.queryByRole('link', { name: '詳細・スレッド' })).toBeNull()
expect(screen.getByRole('article')).toHaveClass('current-post')
})
it('collapses a malformed optional timestamp without losing the post', () => { it('collapses a malformed optional timestamp without losing the post', () => {
const { container } = render( const { container } = render(
<PostCard post={{ ...richPost, createdAt: 'not-a-date' }} />, <PostCard post={{ ...richPost, createdAt: 'not-a-date' }} />,
+10 -1
View File
@@ -41,15 +41,19 @@ function formattedTime(createdAt?: string): string | undefined {
export function PostCard({ export function PostCard({
post, post,
quoted = false, quoted = false,
current = false,
}: { }: {
post: Post post: Post
quoted?: boolean quoted?: boolean
current?: boolean
}) { }) {
const time = formattedTime(post.createdAt) const time = formattedTime(post.createdAt)
const original = `https://x.com/${encodeURIComponent(post.author.username)}/status/${encodeURIComponent(post.id)}` const original = `https://x.com/${encodeURIComponent(post.author.username)}/status/${encodeURIComponent(post.id)}`
return ( return (
<article className={quoted ? 'post quote' : 'post'}> <article
className={quoted ? 'post quote' : current ? 'post current-post' : 'post'}
>
<header className="post-header"> <header className="post-header">
{post.author.profileImageUrl ? ( {post.author.profileImageUrl ? (
<img <img
@@ -86,6 +90,11 @@ export function PostCard({
返信 {post.replyCount ?? 0} 再投稿 {post.retweetCount ?? 0} いいね{' '} 返信 {post.replyCount ?? 0} 再投稿 {post.retweetCount ?? 0} いいね{' '}
{post.likeCount ?? 0} {post.likeCount ?? 0}
</span> </span>
{!current ? (
<a href={`/status/${encodeURIComponent(post.id)}`}>
詳細・スレッド
</a>
) : null}
<a href={original} rel="noreferrer noopener" target="_blank"> <a href={original} rel="noreferrer noopener" target="_blank">
元の投稿を開く 元の投稿を開く
</a> </a>
@@ -154,6 +154,90 @@ describe('PostFeed', () => {
expect(screen.queryByRole('alert')).not.toBeInTheDocument() expect(screen.queryByRole('alert')).not.toBeInTheDocument()
}) })
it('renders the focal post once above its deduplicated conversation', () => {
usePostFeed.mockReturnValue({
...queryResult(),
data: {
pages: [
{
focalPost: post('2'),
conversationId: '1',
nextCursor: 'next',
tweets: [post('1'), post('2')],
},
{
conversationId: '1',
tweets: [post('2'), post('3')],
},
],
pageParams: [undefined, { cursor: 'next', conversationId: '1' }],
},
} as never)
const { container } = render(
<PostFeed request={{ kind: 'thread', tweetId: '2' }} />,
)
expect(screen.getByText('表示中の投稿')).toBeVisible()
expect(screen.getAllByText('post-2')).toHaveLength(1)
expect(screen.getAllByRole('article')).toHaveLength(3)
expect(container.querySelector('.current-post')).toBeInTheDocument()
})
it('keeps the focal post visible when there are no other posts', () => {
usePostFeed.mockReturnValue({
...queryResult(),
data: {
pages: [
{
focalPost: post('2'),
conversationId: '1',
tweets: [post('2')],
},
],
pageParams: [undefined],
},
} as never)
render(<PostFeed request={{ kind: 'thread', tweetId: '2' }} />)
expect(screen.getByText('post-2')).toBeVisible()
expect(screen.getByText('会話にほかの投稿はありません。')).toBeVisible()
})
it('keeps the focal post and conversation across a later-page error', () => {
usePostFeed.mockReturnValue({
...queryResult(),
data: {
pages: [
{
focalPost: post('2'),
conversationId: '1',
nextCursor: 'next',
tweets: [post('1'), post('2')],
},
],
pageParams: [undefined],
},
error: new PostLoadError({
code: 'upstream',
message: 'X から投稿を取得できませんでした。',
retryable: true,
}),
hasNextPage: true,
isError: true,
isFetchNextPageError: true,
} as never)
render(<PostFeed request={{ kind: 'thread', tweetId: '2' }} />)
expect(screen.getByText('post-2')).toBeVisible()
expect(screen.getByText('post-1')).toBeVisible()
expect(screen.getByRole('alert')).toHaveTextContent(
'続きの投稿を取得できませんでした。',
)
})
it('retries an initial retryable error with refetch', () => { it('retries an initial retryable error with refetch', () => {
const refetch = vi.fn().mockResolvedValue(undefined) const refetch = vi.fn().mockResolvedValue(undefined)
usePostFeed.mockReturnValue({ usePostFeed.mockReturnValue({
+36 -3
View File
@@ -1,12 +1,33 @@
import { useEffect, useRef } from 'react' import { useEffect, useRef } from 'react'
import { flattenPostPages } from '../page' import {
flattenConversationPages,
flattenPostPages,
focalPostFromPages,
} from '../page'
import type { Post } from '../types'
import { type FeedRequest, PostLoadError, usePostFeed } from '../use-post-feed' import { type FeedRequest, PostLoadError, usePostFeed } from '../use-post-feed'
import { PostCard } from './post-card' import { PostCard } from './post-card'
function FocalPost({ post }: { post: Post }) {
return (
<section aria-labelledby="focal-post-label" className="focal-post">
<p className="focal-label" id="focal-post-label">
表示中の投稿
</p>
<PostCard current post={post} />
</section>
)
}
export function PostFeed({ request }: { request: FeedRequest | undefined }) { export function PostFeed({ request }: { request: FeedRequest | undefined }) {
const query = usePostFeed(request) const query = usePostFeed(request)
const sentinel = useRef<HTMLDivElement>(null) const sentinel = useRef<HTMLDivElement>(null)
const posts = query.data ? flattenPostPages(query.data.pages) : [] const pages = query.data?.pages ?? []
const focalPost =
request?.kind === 'thread' ? focalPostFromPages(pages) : undefined
const posts = focalPost
? flattenConversationPages(pages, focalPost.id)
: flattenPostPages(pages)
useEffect(() => { useEffect(() => {
if ( if (
@@ -62,10 +83,21 @@ export function PostFeed({ request }: { request: FeedRequest | undefined }) {
) )
} }
if (posts.length === 0 && !query.hasNextPage) { if (posts.length === 0 && !query.hasNextPage) {
return <p className="state">条件に一致する投稿はありません。</p> return (
<>
{focalPost ? <FocalPost post={focalPost} /> : null}
<p className="state">
{focalPost
? '会話にほかの投稿はありません。'
: '条件に一致する投稿はありません。'}
</p>
</>
)
} }
return ( return (
<>
{focalPost ? <FocalPost post={focalPost} /> : null}
<section aria-live="polite" className="feed"> <section aria-live="polite" className="feed">
{posts.map((post) => ( {posts.map((post) => (
<PostCard key={post.id} post={post} /> <PostCard key={post.id} post={post} />
@@ -88,5 +120,6 @@ export function PostFeed({ request }: { request: FeedRequest | undefined }) {
<p className="state">これ以上の投稿はありません。</p> <p className="state">これ以上の投稿はありません。</p>
) : null} ) : null}
</section> </section>
</>
) )
} }
+21 -3
View File
@@ -12,6 +12,7 @@ import { Route as rootRouteImport } from './routes/__root'
import { Route as UserRouteImport } from './routes/user' import { Route as UserRouteImport } from './routes/user'
import { Route as SearchRouteImport } from './routes/search' import { Route as SearchRouteImport } from './routes/search'
import { Route as IndexRouteImport } from './routes/index' import { Route as IndexRouteImport } from './routes/index'
import { Route as StatusTweetIdRouteImport } from './routes/status.$tweetId'
const UserRoute = UserRouteImport.update({ const UserRoute = UserRouteImport.update({
id: '/user', id: '/user',
@@ -28,35 +29,44 @@ const IndexRoute = IndexRouteImport.update({
path: '/', path: '/',
getParentRoute: () => rootRouteImport, getParentRoute: () => rootRouteImport,
} as any) } as any)
const StatusTweetIdRoute = StatusTweetIdRouteImport.update({
id: '/status/$tweetId',
path: '/status/$tweetId',
getParentRoute: () => rootRouteImport,
} as any)
export interface FileRoutesByFullPath { export interface FileRoutesByFullPath {
'/': typeof IndexRoute '/': typeof IndexRoute
'/search': typeof SearchRoute '/search': typeof SearchRoute
'/user': typeof UserRoute '/user': typeof UserRoute
'/status/$tweetId': typeof StatusTweetIdRoute
} }
export interface FileRoutesByTo { export interface FileRoutesByTo {
'/': typeof IndexRoute '/': typeof IndexRoute
'/search': typeof SearchRoute '/search': typeof SearchRoute
'/user': typeof UserRoute '/user': typeof UserRoute
'/status/$tweetId': typeof StatusTweetIdRoute
} }
export interface FileRoutesById { export interface FileRoutesById {
__root__: typeof rootRouteImport __root__: typeof rootRouteImport
'/': typeof IndexRoute '/': typeof IndexRoute
'/search': typeof SearchRoute '/search': typeof SearchRoute
'/user': typeof UserRoute '/user': typeof UserRoute
'/status/$tweetId': typeof StatusTweetIdRoute
} }
export interface FileRouteTypes { export interface FileRouteTypes {
fileRoutesByFullPath: FileRoutesByFullPath fileRoutesByFullPath: FileRoutesByFullPath
fullPaths: '/' | '/search' | '/user' fullPaths: '/' | '/search' | '/user' | '/status/$tweetId'
fileRoutesByTo: FileRoutesByTo fileRoutesByTo: FileRoutesByTo
to: '/' | '/search' | '/user' to: '/' | '/search' | '/user' | '/status/$tweetId'
id: '__root__' | '/' | '/search' | '/user' id: '__root__' | '/' | '/search' | '/user' | '/status/$tweetId'
fileRoutesById: FileRoutesById fileRoutesById: FileRoutesById
} }
export interface RootRouteChildren { export interface RootRouteChildren {
IndexRoute: typeof IndexRoute IndexRoute: typeof IndexRoute
SearchRoute: typeof SearchRoute SearchRoute: typeof SearchRoute
UserRoute: typeof UserRoute UserRoute: typeof UserRoute
StatusTweetIdRoute: typeof StatusTweetIdRoute
} }
declare module '@tanstack/react-router' { declare module '@tanstack/react-router' {
@@ -82,6 +92,13 @@ declare module '@tanstack/react-router' {
preLoaderRoute: typeof IndexRouteImport preLoaderRoute: typeof IndexRouteImport
parentRoute: typeof rootRouteImport parentRoute: typeof rootRouteImport
} }
'/status/$tweetId': {
id: '/status/$tweetId'
path: '/status/$tweetId'
fullPath: '/status/$tweetId'
preLoaderRoute: typeof StatusTweetIdRouteImport
parentRoute: typeof rootRouteImport
}
} }
} }
@@ -89,6 +106,7 @@ const rootRouteChildren: RootRouteChildren = {
IndexRoute: IndexRoute, IndexRoute: IndexRoute,
SearchRoute: SearchRoute, SearchRoute: SearchRoute,
UserRoute: UserRoute, UserRoute: UserRoute,
StatusTweetIdRoute: StatusTweetIdRoute,
} }
export const routeTree = rootRouteImport export const routeTree = rootRouteImport
._addFileChildren(rootRouteChildren) ._addFileChildren(rootRouteChildren)
+27
View File
@@ -88,4 +88,31 @@ describe('post feed route wiring', () => {
}), }),
) )
}) })
it('turns a decimal status path into a deliberate thread request', async () => {
await renderRoute('/status/123')
expect(await screen.findByRole('heading', { name: '会話' })).toBeVisible()
await waitFor(() =>
expect(usePostFeed).toHaveBeenCalledWith({
kind: 'thread',
tweetId: '123',
}),
)
expect(
screen.queryByRole('link', { name: 'ユーザー', current: 'page' }),
).toBeNull()
expect(
screen.queryByRole('link', { name: '検索', current: 'page' }),
).toBeNull()
})
it('keeps an invalid status path local and idle', async () => {
await renderRoute('/status/not-a-tweet')
expect(await screen.findByRole('alert')).toHaveTextContent(
'投稿 ID を確認してください。',
)
expect(usePostFeed).toHaveBeenCalledWith(undefined)
})
}) })
+36
View File
@@ -0,0 +1,36 @@
import { createFileRoute } from '@tanstack/react-router'
import { AppShell } from '#/components/app-shell'
import { PostFeed } from '#/features/posts/components/post-feed'
import { InputError, normalizeTweetId } from '#/features/posts/inputs'
export const Route = createFileRoute('/status/$tweetId')({
component: StatusRoute,
})
function StatusRoute() {
const { tweetId: rawTweetId } = Route.useParams()
let tweetId: string | undefined
let error: string | undefined
try {
tweetId = normalizeTweetId(rawTweetId)
} catch (cause) {
error =
cause instanceof InputError
? cause.message
: '投稿 ID を確認してください。'
}
return (
<AppShell>
<h1>会話</h1>
<p className="intro">選んだ投稿と、その会話だけを表示します。</p>
{error ? (
<p className="state" role="alert">
{error}
</p>
) : null}
<PostFeed request={tweetId ? { kind: 'thread', tweetId } : undefined} />
</AppShell>
)
}
+20
View File
@@ -254,6 +254,20 @@ a {
grid-column: 1 / -1; grid-column: 1 / -1;
} }
.focal-post {
display: grid;
gap: 0.5rem;
margin-top: 1.4rem;
}
.focal-label {
margin: 0;
color: var(--accent);
font-size: 0.72rem;
font-weight: 750;
letter-spacing: 0.08em;
}
.feed { .feed {
display: grid; display: grid;
gap: 0.85rem; gap: 0.85rem;
@@ -268,6 +282,11 @@ a {
background: var(--paper); background: var(--paper);
} }
.current-post {
border-color: var(--accent);
box-shadow: 0 0 0 1px color-mix(in srgb, var(--accent) 25%, transparent);
}
.post-header { .post-header {
display: grid; display: grid;
grid-template-columns: auto minmax(0, 1fr) auto; grid-template-columns: auto minmax(0, 1fr) auto;
@@ -361,6 +380,7 @@ video.media {
.post-footer { .post-footer {
display: flex; display: flex;
flex-wrap: wrap; flex-wrap: wrap;
align-items: center;
justify-content: space-between; justify-content: space-between;
gap: 0.75rem 1rem; gap: 0.75rem 1rem;
margin-top: 1rem; margin-top: 1rem;