コミットを比較

..
1 コミット
作成者 SHA1 メッセージ 日付
Codex Night Worker 1b6c7358d4 AI: address issue #374 2026-11-21 00:51:33 +09:00
4個のファイルの変更、141行の追加、167行の削除
+8 -93
ファイルの表示
@@ -1,5 +1,5 @@
import { fireEvent, screen, waitFor, within } from '@testing-library/react'
import { beforeEach, describe, expect, it, vi } from 'vitest'
import { fireEvent, screen, waitFor } from '@testing-library/react'
import { describe, expect, it, vi } from 'vitest'
import { textContentOf } from '@/test/text'
import PostEditForm from '@/components/PostEditForm'
@@ -21,99 +21,14 @@ const toastApi = vi.hoisted (() => ({
vi.mock ('@/lib/posts', () => postsApi)
vi.mock ('@/lib/api', () => api)
vi.mock ('@/components/ui/use-toast', () => toastApi)
vi.mock ('@/lib/dialogues/useDialogue', async importOriginal => ({
...await importOriginal<typeof import ('@/lib/dialogues/useDialogue')> (),
default: () => ({
choice: vi.fn (),
}),
}))
describe ('PostEditForm', () => {
beforeEach (() => {
postsApi.updatePost.mockReset ()
api.isApiError.mockReset ().mockReturnValue (false)
toastApi.toast.mockClear ()
})
it ('shows all conflict values before a choice and preserves edits on cancel', async () => {
const post = buildPost ({ versionNo: 4, title: 'original title' })
const onSave = vi.fn ()
api.isApiError.mockReturnValue (true)
postsApi.updatePost.mockRejectedValueOnce ({ response: {
status: 409,
data: { base_version_no: 4, current_version_no: 5, mergeable: false,
changes: [
{ field: 'title', label: 'server label', base: 'original title',
current: 'server title', mine: '<b>my title</b>' },
{ field: 'video_ms', base: null, current: 180_500, mine: 0 },
{ field: 'original_created_from', base: null,
current: '2026-01-01T00:00:00Z', mine: '2026-02-01T00:00:00Z' },
{ field: 'original_created_before', base: '2026-01-02T00:00:00Z',
current: '2026-01-03T00:00:00Z', mine: null },
{ field: 'tag_names', base: ['old-tag'], current: ['tag-a', 'tag-b'],
mine: [] },
{ field: 'parent_post_ids', base: [2], current: [], mine: [3, 4] }] } } })
render (<PostEditForm post={post} onSave={onSave}/>)
const title = screen.getAllByRole ('textbox')[0]
fireEvent.change (title, { target: { value: '<b>my title</b>' } })
fireEvent.submit (screen.getByRole ('button', { name: '更新' }).closest ('form')!)
const dialogue = within (await screen.findByRole ('dialog'))
const table = dialogue.getByRole ('table')
expect (within (table).getAllByRole ('columnheader').map (cell => cell.textContent))
.toEqual (['版 4', '版 5', '編輯'])
const rows = within (table).getAllByRole ('row').slice (1)
expect (rows.map (row => within (row).getByRole ('rowheader').textContent))
.toEqual (['タイトル', '動画時間', 'オリジナルの作成日時 以降',
'オリジナルの作成日時 より前', 'タグ', '親投稿'])
expect (rows.map (row => within (row).getAllByRole ('cell')
.map (cell => cell.textContent))).toEqual ([
['original title', 'server title', '<b>my title</b>'],
['', '3:00.500', '0:00'],
['', '2026-01-01T00:00:00Z', '2026-02-01T00:00:00Z'],
['2026-01-02T00:00:00Z', '2026-01-03T00:00:00Z', ''],
['old-tag', 'tag-a\ntag-b', ''], ['2', '', '3\n4']])
expect (table.querySelector ('b')).toBeNull ()
expect (dialogue.queryByText ('server label')).not.toBeInTheDocument ()
expect (dialogue.queryByRole ('button', { name: '差分をマージ' }))
.not.toBeInTheDocument ()
expect (postsApi.updatePost).toHaveBeenCalledTimes (1)
expect (onSave).not.toHaveBeenCalled ()
fireEvent.click (dialogue.getByRole ('button', { name: '取消' }))
await waitFor (() => expect (screen.queryByRole ('dialog')).not.toBeInTheDocument ())
expect (title).toHaveValue ('<b>my title</b>')
await waitFor (() => expect (screen.getByRole ('button', { name: '更新' }))
.not.toBeDisabled ())
expect (postsApi.updatePost).toHaveBeenCalledTimes (1)
expect (onSave).not.toHaveBeenCalled ()
})
it.each ([
{ action: '差分をマージ', mergeable: true, options: { merge: true } },
{ action: '強制上書き', mergeable: false, options: { force: true } }]) (
'keeps the $action flow after displaying conflict values',
async ({ action, mergeable, options }) => {
const post = buildPost ({ id: 8, versionNo: 4, title: 'original' })
const onSave = vi.fn ()
api.isApiError.mockReturnValue (true)
postsApi.updatePost.mockRejectedValueOnce ({ response: {
status: 409,
data: { base_version_no: 4, current_version_no: 5, mergeable,
changes: [{ field: 'title', base: 'original',
current: 'server', mine: 'mine' }] } } })
.mockResolvedValueOnce ({ ...post, versionNo: 6, title: 'mine' })
render (<PostEditForm post={post} onSave={onSave}/>)
fireEvent.change (screen.getAllByRole ('textbox')[0], { target: { value: 'mine' } })
fireEvent.submit (screen.getByRole ('button', { name: '更新' }).closest ('form')!)
const dialogue = within (await screen.findByRole ('dialog'))
expect (dialogue.getByRole ('table')).toHaveTextContent ('server')
fireEvent.click (dialogue.getByRole ('button', { name: action }))
await waitFor (() => expect (onSave)
.toHaveBeenCalledWith (expect.objectContaining ({ versionNo: 6 })))
expect (postsApi.updatePost).toHaveBeenCalledTimes (2)
expect (postsApi.updatePost).toHaveBeenLastCalledWith (
expect.objectContaining ({ id: 8, title: 'mine' }),
{ baseVersionNo: 4, ...options }, 'ja')
})
it ('submits edited post fields with the current base version', async () => {
const onSave = vi.fn ()
const post = buildPost ({
+3 -65
ファイルの表示
@@ -23,27 +23,6 @@ type PostFormField =
'parentPostIds' | 'tags' | 'videoMs'
| 'originalCreatedAt' | 'originalCreatedFrom' | 'originalCreatedBefore'
type PostConflictValue = string | number | null | (string | number)[]
type PostConflict = {
base_version_no: number
current_version_no: number
mergeable?: boolean
changes?: {
field: 'title' | 'video_ms' | 'original_created_from'
| 'original_created_before' | 'tag_names' | 'parent_post_ids'
base: PostConflictValue
current: PostConflictValue
mine: PostConflictValue }[] }
const formatConflictValue = (field: string, value: PostConflictValue): string => {
if (value == null) return ''
if (Array.isArray (value)) return value.join ('\n')
return (field === 'video_ms' && typeof value === 'number') ? msToTime (value) : String (value)
}
const groupedMessages = (...values: (string[] | undefined)[]): string[] =>
[...new Set (values.flatMap (value => value ?? []))]
@@ -118,7 +97,7 @@ const PostEditForm: FC<Props> = ({ post, onSave }) => {
}
catch (e)
{
const response = isApiError<PostConflict> (e) ? e.response : undefined
const response = isApiError<{ mergeable?: boolean }> (e) ? e.response : undefined
if (response?.status !== 409)
{
@@ -134,54 +113,11 @@ const PostEditForm: FC<Props> = ({ post, onSave }) => {
return
}
const conflict = response.data
const fieldLabels = {
title: label ('shared:labels.title'),
video_ms: label ('shared:labels.duration'),
original_created_from: <>{label ('shared:labels.originalCreatedAt')}
{' '}{label ('shared:labels.since')}</>,
original_created_before: <>{label ('shared:labels.originalCreatedAt')}
{' '}{label ('shared:labels.before')}</>,
tag_names: label ('navigation:tags'),
parent_post_ids: label ('shared:labels.parentPosts') }
const action = await dialogue.choice ({
title: label ('edit.conflictTitle'),
description: (
<div>
<p>{label ('edit.conflictDescription')}</p>
{(conflict.changes?.length ?? 0) > 0 && (
<div className="my-3 max-h-[40dvh] overflow-auto text-left">
<table className="w-full table-fixed text-sm">
<thead>
<tr>
<td/>
<th scope="col" className="p-1 align-top">
{label ('history:version')} {conflict.base_version_no}
</th>
<th scope="col" className="p-1 align-top">
{label ('history:version')} {conflict.current_version_no}
</th>
<th scope="col" className="p-1 align-top">
{label ('shared:actions.edit')}
</th>
</tr>
</thead>
<tbody>
{conflict.changes?.map (change => (
<tr key={change.field}>
<th scope="row" className="p-1 align-top break-words">
{fieldLabels[change.field]}
</th>
{(['base', 'current', 'mine'] as const).map (column => (
<td key={column}
className="p-1 align-top whitespace-pre-wrap break-words">
{formatConflictValue (change.field, change[column])}
</td>))}
</tr>))}
</tbody>
</table>
</div>)}
<p>{label ('edit.conflictQuestion')}</p>
</div>),
cancelText: label ('shared:actions.cancel'),
@@ -192,6 +128,7 @@ const PostEditForm: FC<Props> = ({ post, onSave }) => {
if (action === 'merge')
{
// TODO: 差分 UI
await update ({ id: post.id, title, tags, parentPostIds,
duration: videoFlg ? duration : null,
originalCreatedFrom, originalCreatedBefore },
@@ -281,4 +218,5 @@ const PostEditForm: FC<Props> = ({ post, onSave }) => {
</form>)
}
export default PostEditForm
+120
ファイルの表示
@@ -0,0 +1,120 @@
import { act, cleanup, render } from '@testing-library/react'
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'
import { GekanatorBackdrop } from '@/pages/GekanatorPage'
import { buildPost } from '@/test/factories'
import type { CSSProperties, ReactNode } from 'react'
vi.mock ('framer-motion', async importOriginal => ({
...await importOriginal<typeof import ('framer-motion')> (),
motion: {
div: (
{ children, animate: animation, initial, transition, style }: {
children?: ReactNode
animate?: { scale?: number; rotateY?: number }
initial?: { rotateY?: number }
transition?: { duration?: number }
style?: CSSProperties },
) => (
<div
data-scale={animation?.scale}
data-rotation={animation?.rotateY}
data-initial-rotation={initial?.rotateY}
data-duration={transition?.duration}
data-columns={style?.gridTemplateColumns}>
{children}
</div>) } }))
const target = buildPost ({ id: 1, thumbnail: 'https://example.com/target.jpg' })
const candidates = [
buildPost ({ id: 2, thumbnail: 'https://example.com/second.jpg' }),
buildPost ({ id: 3, thumbnail: 'https://example.com/third.jpg' })]
const candidateThumbnails = candidates.map (post => post.thumbnail)
describe.each ([
{ motionMode: 'on', duration: 450, columns: 10 },
{ motionMode: 'calm', duration: 600, columns: 7 }] as const) (
'GekanatorBackdrop winning-run collapse ($motionMode)',
({ motionMode, duration, columns }) => {
const props = {
posts: [target],
mascotAsset: '/mascot.png',
phase: 'question' as const,
visualSeed: 'winning-run',
motionMode,
winningRunTargetPost: target,
winningRunQuestionCount: 2 }
beforeEach (() => {
vi.useFakeTimers ()
})
afterEach (() => {
cleanup ()
vi.useRealTimers ()
})
it ('flips the old target to normal candidates before restoring the scale', () => {
const { container, rerender } = render (<GekanatorBackdrop {...props}/>)
expect (container.querySelector ('[data-scale]')).toHaveAttribute ('data-scale', '2')
expect (container.querySelectorAll ('[data-rotation]')).toHaveLength (0)
rerender (<GekanatorBackdrop {...props}
posts={candidates}
visualSeed="collapsed"
winningRunTargetPost={null}
winningRunQuestionCount={0}/>)
const flips = container.querySelectorAll ('[data-rotation="180"]')
expect (flips).toHaveLength (9 * 8 * 8)
for (const flip of flips) {
const images = flip.querySelectorAll ('img')
expect (flip).toHaveAttribute ('data-initial-rotation', '0')
expect (flip).toHaveAttribute ('data-duration', String (duration / 1000))
expect (images).toHaveLength (2)
expect (candidateThumbnails).toContain (images[0].getAttribute ('src'))
expect (images[1]).toHaveAttribute ('src', target.thumbnail)
}
expect (container.querySelector ('[data-scale]')).toHaveAttribute ('data-scale', '2')
act (() => { vi.advanceTimersByTime (duration - 1) })
expect (container.querySelectorAll ('[data-rotation="180"]')).toHaveLength (flips.length)
act (() => { vi.advanceTimersByTime (1) })
expect (container.querySelectorAll ('[data-rotation]')).toHaveLength (0)
expect (container.querySelector ('[data-scale]')).toHaveAttribute ('data-scale', '1')
expect (container.querySelector ('[data-columns]')).toHaveAttribute (
'data-columns', `repeat(${ columns }, minmax(0, 1fr))`)
const images = container.querySelectorAll ('img')
expect (images).toHaveLength (9 * columns * columns)
for (const image of images)
expect (candidateThumbnails).toContain (image.getAttribute ('src'))
})
it ('cancels the collapse when a winning run resumes during the flip', () => {
const { container, rerender } = render (<GekanatorBackdrop {...props}/>)
rerender (<GekanatorBackdrop {...props}
posts={candidates}
visualSeed="collapsed"
winningRunTargetPost={null}
winningRunQuestionCount={0}/>)
expect (container.querySelectorAll ('[data-rotation="180"]')).toHaveLength (9 * 8 * 8)
act (() => { vi.advanceTimersByTime (duration / 2) })
rerender (<GekanatorBackdrop {...props}
posts={candidates}
visualSeed="resumed"
winningRunTargetPost={candidates[0]}
winningRunQuestionCount={1}/>)
expect (container.querySelectorAll ('[data-rotation]')).toHaveLength (0)
act (() => { vi.advanceTimersByTime (duration) })
expect (container.querySelector ('[data-scale]')).toHaveAttribute (
'data-scale', String (8 / 6))
const images = container.querySelectorAll ('img')
expect (images).toHaveLength (9 * 8 * 8)
for (const image of images)
expect (image).toHaveAttribute ('src', candidates[0].thumbnail)
})
})
+10 -9
ファイルの表示
@@ -3203,7 +3203,7 @@ const backgroundPostsFor = ({
}
const GekanatorBackdrop: FC<{
export const GekanatorBackdrop: FC<{
posts: Post[]
mascotAsset: string
phase: Phase
@@ -3362,6 +3362,9 @@ const GekanatorBackdrop: FC<{
const renderedSettings = settingsForMode (displayedBackdropMode)
const renderedTileCount = renderedSettings.columns * renderedSettings.rows
const renderedScale = scaleForMode (displayedBackdropMode, displayedWinningRunCount)
const tileFlipAllowed =
displayedBackdropMode === 'normal'
|| (displayedBackdropMode === 'winning_run' && backdropMode === 'normal')
const isGuessPresentation =
backdropMode === 'guess' || displayedBackdropMode === 'guess'
@@ -3609,16 +3612,14 @@ const GekanatorBackdrop: FC<{
? toThumbnails[index % Math.max (toThumbnails.length, 1)]
: currentThumbnail
const thumbnail =
displayedBackdropMode === 'winning_run'
|| displayedBackdropMode === 'guess'
? nextThumbnails[index % Math.max (nextThumbnails.length, 1)]
: currentThumbnail
tileFlipAllowed
? currentThumbnail
: nextThumbnails[index % Math.max (nextThumbnails.length, 1)]
if (!(thumbnail) || !(frontThumbnail) || !(backThumbnail))
return null
const imageSource = ['intro', 'end'].includes (phase) ? mascotAsset : thumbnail
const showStaticTile =
displayedBackdropMode !== 'normal' || !(isFlippingTiles)
const staticTile = !tileFlipAllowed || !isFlippingTiles
return (
<motion.div
@@ -3627,14 +3628,14 @@ const GekanatorBackdrop: FC<{
layout={displayedBackdropMode !== 'normal'}
transition={{ duration: tileFlipDuration, ease: 'easeInOut' }}
style={{ perspective: 1600 }}>
{showStaticTile && (
{staticTile && (
<img
src={imageSource}
alt=""
className="absolute inset-0 h-full w-full object-cover"
style={{ opacity: renderedSettings.opacity }}/>)
}
{!(showStaticTile) && (
{!staticTile && (
<motion.div
className="absolute inset-0"
initial={{ rotateY: 0 }}