コミットを比較

..
2 コミット
作成者 SHA1 メッセージ 日付
Codex Night Worker 3dba626e3f AI: address review on PR #467 2026-11-13 12:42:35 +09:00
Codex Night Worker 76ca985096 AI: address issue #320 2026-11-13 07:40:54 +09:00
5個のファイルの変更、49行の追加、125行の削除
+6 -50
ファイルの表示
@@ -1,13 +1,11 @@
import { act, fireEvent, screen, waitFor } from '@testing-library/react' import { fireEvent, screen, waitFor } from '@testing-library/react'
import { beforeEach, describe, expect, it, vi } from 'vitest' import { describe, expect, it, vi } from 'vitest'
import { textContentOf } from '@/test/text' import { textContentOf } from '@/test/text'
import PostEditForm from '@/components/PostEditForm' import PostEditForm from '@/components/PostEditForm'
import { buildPost, buildTag } from '@/test/factories' import { buildPost, buildTag } from '@/test/factories'
import { renderWithProviders as render } from '@/test/render' import { renderWithProviders as render } from '@/test/render'
import type { DialogueAPI } from '@/lib/dialogues/useDialogue'
const postsApi = vi.hoisted (() => ({ const postsApi = vi.hoisted (() => ({
updatePost: vi.fn (), updatePost: vi.fn (),
})) }))
@@ -20,27 +18,18 @@ const toastApi = vi.hoisted (() => ({
toast: vi.fn (), toast: vi.fn (),
})) }))
const dialogue = vi.hoisted (() => ({
confirm: vi.fn<DialogueAPI['confirm']> (),
choice: vi.fn () }))
vi.mock ('@/lib/posts', () => postsApi) vi.mock ('@/lib/posts', () => postsApi)
vi.mock ('@/lib/api', () => api) vi.mock ('@/lib/api', () => api)
vi.mock ('@/components/ui/use-toast', () => toastApi) vi.mock ('@/components/ui/use-toast', () => toastApi)
vi.mock ('@/lib/dialogues/useDialogue', async importOriginal => ({ vi.mock ('@/lib/dialogues/useDialogue', async importOriginal => ({
...await importOriginal<typeof import ('@/lib/dialogues/useDialogue')> (), ...await importOriginal<typeof import ('@/lib/dialogues/useDialogue')> (),
default: () => dialogue })) default: () => ({
choice: vi.fn (),
}),
}))
describe ('PostEditForm', () => { describe ('PostEditForm', () => {
beforeEach (() => {
vi.resetAllMocks ()
})
it ('submits edited post fields with the current base version', async () => { it ('submits edited post fields with the current base version', async () => {
const confirm = vi.fn<(value: boolean) => void> ()
dialogue.confirm.mockReturnValueOnce (new Promise<boolean> (resolve => {
confirm.mockImplementation (resolve)
}))
const onSave = vi.fn () const onSave = vi.fn ()
const post = buildPost ({ const post = buildPost ({
id: 8, id: 8,
@@ -66,16 +55,6 @@ describe ('PostEditForm', () => {
fireEvent.change (parentIds, { target: { value: '3 4' } }) fireEvent.change (parentIds, { target: { value: '3 4' } })
fireEvent.submit (screen.getByRole ('button', { name: '更新' }).closest ('form')!) fireEvent.submit (screen.getByRole ('button', { name: '更新' }).closest ('form')!)
expect (postsApi.updatePost).not.toHaveBeenCalled ()
expect (dialogue.confirm).toHaveBeenCalledTimes (1)
const difference = textContentOf (
dialogue.confirm.mock.calls[0][0].description)
expect (difference).toContain ('oldnew')
expect (difference).toContain ('23 4')
expect (difference).not.toContain ('general-tag')
await act (async () => { confirm (true) })
await waitFor (() => { await waitFor (() => {
expect (postsApi.updatePost).toHaveBeenCalledWith ( expect (postsApi.updatePost).toHaveBeenCalledWith (
expect.objectContaining ({ expect.objectContaining ({
@@ -92,28 +71,6 @@ describe ('PostEditForm', () => {
expect (textContentOf (toastApi.toast.mock.calls[0][0].description)).toBe ('更新しました.') expect (textContentOf (toastApi.toast.mock.calls[0][0].description)).toBe ('更新しました.')
}) })
it ('keeps edited fields without submitting when confirmation is cancelled', async () => {
const onSave = vi.fn ()
dialogue.confirm.mockResolvedValueOnce (false)
render (<PostEditForm post={buildPost ()} onSave={onSave}/>)
const [title, parentIds] = screen.getAllByRole ('textbox')
fireEvent.change (title, { target: { value: 'new' } })
fireEvent.change (parentIds, { target: { value: '3 4' } })
const button = screen.getByRole ('button', { name: '更新' })
fireEvent.submit (button.closest ('form')!)
await waitFor (() => {
expect (button).toBeEnabled ()
})
expect (dialogue.confirm).toHaveBeenCalledTimes (1)
expect (postsApi.updatePost).not.toHaveBeenCalled ()
expect (onSave).not.toHaveBeenCalled ()
expect (toastApi.toast).not.toHaveBeenCalled ()
expect (title).toHaveValue ('new')
expect (parentIds).toHaveValue ('3 4')
})
it ('preserves duration while the video tag is temporarily removed', () => { it ('preserves duration while the video tag is temporarily removed', () => {
const post = buildPost ({ const post = buildPost ({
videoMs: 180_500, videoMs: 180_500,
@@ -143,7 +100,6 @@ describe ('PostEditForm', () => {
'shows deduplicated original-created endpoint errors on the shared datetime field', 'shows deduplicated original-created endpoint errors on the shared datetime field',
async () => { async () => {
const post = buildPost () const post = buildPost ()
dialogue.confirm.mockResolvedValueOnce (true)
api.isApiError.mockReturnValue (true) api.isApiError.mockReturnValue (true)
postsApi.updatePost.mockRejectedValueOnce ({ postsApi.updatePost.mockRejectedValueOnce ({
response: { response: {
+3 -56
ファイルの表示
@@ -15,7 +15,7 @@ import { msToTime } from '@/lib/utils'
import { useValidationErrors } from '@/lib/useValidationErrors' import { useValidationErrors } from '@/lib/useValidationErrors'
import { useUITranslation } from '@/lib/useUITranslation' import { useUITranslation } from '@/lib/useUITranslation'
import type { FC, FormEvent, ReactNode } from 'react' import type { FC, FormEvent } from 'react'
import type { Post, TagWithSections } from '@/types' import type { Post, TagWithSections } from '@/types'
@@ -23,8 +23,6 @@ type PostFormField =
'parentPostIds' | 'tags' | 'videoMs' 'parentPostIds' | 'tags' | 'videoMs'
| 'originalCreatedAt' | 'originalCreatedFrom' | 'originalCreatedBefore' | 'originalCreatedAt' | 'originalCreatedFrom' | 'originalCreatedBefore'
type PostEditData = Omit<Parameters<typeof updatePost>[0], 'id'>
const groupedMessages = (...values: (string[] | undefined)[]): string[] => const groupedMessages = (...values: (string[] | undefined)[]): string[] =>
[...new Set (values.flatMap (value => value ?? []))] [...new Set (values.flatMap (value => value ?? []))]
@@ -152,63 +150,12 @@ const PostEditForm: FC<Props> = ({ post, onSave }) => {
const handleSubmit = async (e: FormEvent) => { const handleSubmit = async (e: FormEvent) => {
e.preventDefault () e.preventDefault ()
if (disabled) return
setDisabled (true) setDisabled (true)
try try
{ {
const current: PostEditData = { await update ({ id: post.id, title, tags, parentPostIds,
title, tags, parentPostIds,
duration: videoFlg ? duration : null, duration: videoFlg ? duration : null,
originalCreatedFrom, originalCreatedBefore } originalCreatedFrom, originalCreatedBefore },
const fields: {
[Key in keyof PostEditData]-?: {
name: ReactNode
prev: PostEditData[Key] } } = {
title: { name: label ('shared:labels.title'), prev: post.title },
parentPostIds: {
name: label ('shared:labels.parentPosts'),
prev: (post.parentPosts ?? []).map (parent => parent.id).join (' ') },
tags: { name: label ('tags:title'), prev: tagsToStr (post.tags) },
duration: {
name: label ('shared:labels.duration'),
prev: videoMsToDurationValue (post.videoMs) },
originalCreatedFrom: {
name: <>{label ('shared:labels.originalCreatedAt')}{' '}
{label ('shared:labels.since')}</>,
prev: post.originalCreatedFrom },
originalCreatedBefore: {
name: <>{label ('shared:labels.originalCreatedAt')}{' '}
{label ('shared:labels.before')}</>,
prev: post.originalCreatedBefore } }
const differences = (Object.keys (fields) as (keyof PostEditData)[])
.map (key => ({ key, name: fields[key].name,
prev: fields[key].prev ?? '', current: current[key] ?? '' }))
.filter (row => row.prev !== row.current)
if (!(await dialogue.confirm ({
title: label ('shared:actions.diff'),
confirmText: label ('shared:actions.update'),
description: (
<dl className="max-h-[60dvh] overflow-y-auto space-y-3 text-left">
{differences.map (row => (
<div key={row.key}>
<dt className="font-semibold">{row.name}</dt>
<dd className="whitespace-pre-wrap break-words">
{row.prev && (
<del className="block text-red-600 dark:text-red-400">
{row.prev}
</del>)}
{row.current && (
<ins className="block text-green-700 dark:text-green-400">
{row.current}
</ins>)}
</dd>
</div>))}
</dl>) })))
return
await update ({ id: post.id, ...current },
{ baseVersionNo: post.versionNo }) { baseVersionNo: post.versionNo })
} }
finally finally
+8 -2
ファイルの表示
@@ -36,10 +36,13 @@ const replaceToken = (value: string, start: number, end: number, text: string) =
type Props = Omit<ComponentPropsWithoutRef<'textarea'>, 'value' | 'onChange' | 'onBlur'> & { type Props = Omit<ComponentPropsWithoutRef<'textarea'>, 'value' | 'onChange' | 'onBlur'> & {
tags: string tags: string
setTags: (tags: string) => void setTags: (tags: string) => void
label?: ReactNode
errors?: ReactNode[] } errors?: ReactNode[] }
const PostFormTagsArea: FC<Props> = ({ tags, setTags, errors, ...rest }) => { const PostFormTagsArea: FC<Props> = (
{ tags, setTags, label: fieldLabel, errors, ...rest },
) => {
const { label } = useUITranslation ('navigation') const { label } = useUITranslation ('navigation')
const locale = useLocale () const locale = useLocale ()
const ref = useRef<HTMLTextAreaElement> (null) const ref = useRef<HTMLTextAreaElement> (null)
@@ -117,7 +120,10 @@ const PostFormTagsArea: FC<Props> = ({ tags, setTags, errors, ...rest }) => {
}, [locale]) }, [locale])
return ( return (
<FormField className="relative w-full" label={label ('tags')} messages={errors}> <FormField
className="relative w-full"
label={fieldLabel ?? label ('tags')}
messages={errors}>
{({ describedBy, invalid }) => ( {({ describedBy, invalid }) => (
<> <>
<TextArea <TextArea
+22 -3
ファイルの表示
@@ -162,12 +162,13 @@ describe ('NicoTagListPage', () => {
}) })
}) })
it ('updates links from a tag card', async () => { it ('saves links after completing the tag at the cursor', async () => {
api.apiGet api.apiGet
.mockResolvedValueOnce ({ .mockResolvedValueOnce ({
tags: [buildNicoTag ({ id: 7, name: 'nico:source' })], tags: [buildNicoTag ({ id: 7, name: 'nico:source' })],
count: 1, count: 1,
}) })
.mockResolvedValueOnce ([buildTag ({ id: 8, name: '連携先', postCount: 3 })])
.mockResolvedValueOnce ({ .mockResolvedValueOnce ({
tags: [ tags: [
buildNicoTag ({ buildNicoTag ({
@@ -183,8 +184,24 @@ describe ('NicoTagListPage', () => {
renderPage () renderPage ()
fireEvent.click (await screen.findByRole ('button', { name: '編集' })) fireEvent.click (await screen.findByRole ('button', { name: '編集' }))
fireEvent.change (screen.getByLabelText ('連携する広場タグ'), { const textarea = screen.getByLabelText ('連携する広場タグ')
target: { value: '連携先' }, fireEvent.change (textarea, { target: { value: '既存 連携\n後続' } })
fireEvent.focus (textarea)
fireEvent.select (textarea, {
target: { selectionStart: 4, selectionEnd: 4 } })
await waitFor (() => {
expect (api.apiGet).toHaveBeenCalledWith (
'/tags/autocomplete',
{ locale: 'ja', params: { q: '連携', nico: '0' },
signal: expect.any (AbortSignal) })
})
fireEvent.mouseDown (await screen.findByText ('連携先'))
expect (textarea).toHaveValue ('既存 連携先 \n後続')
await waitFor (() => {
expect ((textarea as HTMLTextAreaElement).selectionStart).toBe (7)
expect ((textarea as HTMLTextAreaElement).selectionEnd).toBe (7)
}) })
fireEvent.click (screen.getByRole ('button', { name: '保存' })) fireEvent.click (screen.getByRole ('button', { name: '保存' }))
@@ -195,6 +212,8 @@ describe ('NicoTagListPage', () => {
{ locale: 'ja', headers: { 'Content-Type': 'multipart/form-data' } }, { locale: 'ja', headers: { 'Content-Type': 'multipart/form-data' } },
) )
}) })
const payload = api.apiPut.mock.calls[0][1] as FormData
expect (payload.get ('tags')).toBe ('既存 連携先 \n後続')
expect (await screen.findByText ('1 件')).toBeInTheDocument () expect (await screen.findByText ('1 件')).toBeInTheDocument ()
}) })
+8 -12
ファイルの表示
@@ -6,11 +6,10 @@ import { useLocation } from 'react-router-dom'
import { useLocale, useLocaleNavigate } from '@/lib/useLocale' import { useLocale, useLocaleNavigate } from '@/lib/useLocale'
import TagLink from '@/components/TagLink' import TagLink from '@/components/TagLink'
import SortHeader from '@/components/SortHeader' import SortHeader from '@/components/SortHeader'
import FieldError from '@/components/common/FieldError' import PostFormTagsArea from '@/components/PostFormTagsArea'
import FormField from '@/components/common/FormField' import FormField from '@/components/common/FormField'
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 TextArea from '@/components/common/TextArea'
import useDialogue from '@/lib/dialogues/useDialogue' import useDialogue from '@/lib/dialogues/useDialogue'
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'
@@ -357,21 +356,18 @@ const NicoTagListPage: FC<Props> = ({ user }) => {
dark:bg-rose-950/30"> dark:bg-rose-950/30">
<td colSpan={editable ? 5 : 4} className="p-3"> <td colSpan={editable ? 5 : 4} className="p-3">
<div className="space-y-2"> <div className="space-y-2">
<label htmlFor={`nico-links-${ tag.id }`} <PostFormTagsArea
className="block text-sm font-semibold">
{label ('nico.tagsToLink')}
</label>
<TextArea
id={`nico-links-${ tag.id }`} id={`nico-links-${ tag.id }`}
value={rawTags[tag.id] ?? ''} label={label ('nico.tagsToLink')}
invalid={(errorsByTagId[tag.id] ?? []).length > 0} aria-label={message ('nico.tagsToLink').text}
tags={rawTags[tag.id] ?? ''}
errors={errors}
className="min-h-24 resize-y" className="min-h-24 resize-y"
placeholder={message ('nico.tagsPlaceholder').text} placeholder={message ('nico.tagsPlaceholder').text}
lang={message ('nico.tagsPlaceholder').language} lang={message ('nico.tagsPlaceholder').language}
onChange={e => setRawTags (rawTags => ({ setTags={value => setRawTags (rawTags => ({
...rawTags, ...rawTags,
[tag.id]: e.target.value}))}/> [tag.id]: value}))}/>
<FieldError messages={errors}/>
<div className="flex justify-end gap-2"> <div className="flex justify-end gap-2">
<button <button
type="button" type="button"