コミットを比較
1
コミット
main
...
feature/97
| 作成者 | SHA1 | 日付 | |
|---|---|---|---|
|
|
e60c38c6b8 |
+2
-1
@@ -379,7 +379,8 @@ const RoutedApp = ({ locales }: { locales: AvailableLocale[] }) => {
|
|||||||
<PageHead>
|
<PageHead>
|
||||||
{robots != null && <meta name="robots" content={robots}/>}
|
{robots != null && <meta name="robots" content={robots}/>}
|
||||||
</PageHead>
|
</PageHead>
|
||||||
<UnsavedChangesGuardProvider>
|
<UnsavedChangesGuardProvider
|
||||||
|
draftScope={user == null ? '' : `${user.id}:${user.role}`}>
|
||||||
<KeyboardShortcutsProvider>
|
<KeyboardShortcutsProvider>
|
||||||
<MotionConfig
|
<MotionConfig
|
||||||
reducedMotion={
|
reducedMotion={
|
||||||
|
|||||||
@@ -1,5 +1,5 @@
|
|||||||
import { fireEvent, screen, waitFor } from '@testing-library/react'
|
import { fireEvent, screen, waitFor } from '@testing-library/react'
|
||||||
import { describe, expect, it, vi } from 'vitest'
|
import { beforeEach, 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'
|
||||||
@@ -29,6 +29,27 @@ vi.mock ('@/lib/dialogues/useDialogue', async importOriginal => ({
|
|||||||
}))
|
}))
|
||||||
|
|
||||||
describe ('PostEditForm', () => {
|
describe ('PostEditForm', () => {
|
||||||
|
beforeEach (() => vi.clearAllMocks ())
|
||||||
|
|
||||||
|
it ('submits restored edits against their original version', async () => {
|
||||||
|
const post = buildPost ({ id: 8, versionNo: 4 })
|
||||||
|
sessionStorage.setItem ('session-draft:1:anonymous:post:8:ja', JSON.stringify ({
|
||||||
|
baseVersionNo: 3, title: 'restored title', tags: 'テストタグ', duration: '',
|
||||||
|
parentPostIds: '', originalCreatedFrom: null, originalCreatedBefore: null }))
|
||||||
|
postsApi.updatePost.mockResolvedValueOnce ({ ...post, versionNo: 5 })
|
||||||
|
render (<PostEditForm post={post} onSave={vi.fn ()}/>)
|
||||||
|
|
||||||
|
expect (screen.getByDisplayValue ('restored title')).toBeInTheDocument ()
|
||||||
|
fireEvent.submit (screen.getByRole ('button', { name: '更新' }).closest ('form')!)
|
||||||
|
|
||||||
|
await waitFor (() => {
|
||||||
|
expect (postsApi.updatePost).toHaveBeenCalledWith (
|
||||||
|
expect.objectContaining ({ title: 'restored title' }),
|
||||||
|
{ baseVersionNo: 3 }, 'ja')
|
||||||
|
})
|
||||||
|
expect (sessionStorage.getItem ('session-draft:1:anonymous:post:8:ja')).toBeNull ()
|
||||||
|
})
|
||||||
|
|
||||||
it ('submits edited post fields with the current base version', async () => {
|
it ('submits edited post fields with the current base version', async () => {
|
||||||
const onSave = vi.fn ()
|
const onSave = vi.fn ()
|
||||||
const post = buildPost ({
|
const post = buildPost ({
|
||||||
|
|||||||
@@ -1,5 +1,6 @@
|
|||||||
import { useEffect, useMemo, useState } from 'react'
|
import { useMemo, useState } from 'react'
|
||||||
|
|
||||||
|
import { useSessionDraft } from '@/lib/useSessionDraft'
|
||||||
import { useLocale } from '@/lib/useLocale'
|
import { useLocale } from '@/lib/useLocale'
|
||||||
import PostOriginalCreatedTimeField from '@/components/PostOriginalCreatedTimeField'
|
import PostOriginalCreatedTimeField from '@/components/PostOriginalCreatedTimeField'
|
||||||
import FieldError from '@/components/common/FieldError'
|
import FieldError from '@/components/common/FieldError'
|
||||||
@@ -56,17 +57,17 @@ const PostEditForm: FC<Props> = ({ post, onSave }) => {
|
|||||||
const locale = useLocale ()
|
const locale = useLocale ()
|
||||||
const { label } = useUITranslation ('posts')
|
const { label } = useUITranslation ('posts')
|
||||||
const [disabled, setDisabled] = useState (false)
|
const [disabled, setDisabled] = useState (false)
|
||||||
const [duration, setDuration] = useState<string> (videoMsToDurationValue (post.videoMs))
|
|
||||||
const { baseErrors, fieldErrors, clearValidationErrors, applyValidationError } =
|
const { baseErrors, fieldErrors, clearValidationErrors, applyValidationError } =
|
||||||
useValidationErrors<PostFormField> ()
|
useValidationErrors<PostFormField> ()
|
||||||
const [originalCreatedBefore, setOriginalCreatedBefore] =
|
const { draft, setField, clearDraft } = useSessionDraft (`post:${post.id}:${locale}`, {
|
||||||
useState<string | null> (post.originalCreatedBefore)
|
baseVersionNo: post.versionNo,
|
||||||
const [originalCreatedFrom, setOriginalCreatedFrom] =
|
duration: videoMsToDurationValue (post.videoMs),
|
||||||
useState<string | null> (post.originalCreatedFrom)
|
originalCreatedBefore: post.originalCreatedBefore,
|
||||||
const [parentPostIds, setParentPostIds] =
|
originalCreatedFrom: post.originalCreatedFrom,
|
||||||
useState ((post.parentPosts ?? []).map (p => p.id).join (' '))
|
parentPostIds: (post.parentPosts ?? []).map (entry => entry.id).join (' '),
|
||||||
const [tags, setTags] = useState<string> (() => tagsToStr (post.tags))
|
tags: tagsToStr (post.tags), title: post.title })
|
||||||
const [title, setTitle] = useState (post.title)
|
const { baseVersionNo, duration, originalCreatedBefore, originalCreatedFrom,
|
||||||
|
parentPostIds, tags, title } = draft
|
||||||
|
|
||||||
const videoFlg =
|
const videoFlg =
|
||||||
useMemo (() => tags.split (/\s+/).some (tag => tag.replace (/\[.*\]$/, '') === '動画'),
|
useMemo (() => tags.split (/\s+/).some (tag => tag.replace (/\[.*\]$/, '') === '動画'),
|
||||||
@@ -83,6 +84,7 @@ const PostEditForm: FC<Props> = ({ post, onSave }) => {
|
|||||||
try
|
try
|
||||||
{
|
{
|
||||||
const data = await updatePost (postData, options, locale)
|
const data = await updatePost (postData, options, locale)
|
||||||
|
clearDraft ({ ...draft, baseVersionNo: data.versionNo })
|
||||||
onSave ({ ...post,
|
onSave ({ ...post,
|
||||||
versionNo: data.versionNo,
|
versionNo: data.versionNo,
|
||||||
title: data.title,
|
title: data.title,
|
||||||
@@ -132,7 +134,7 @@ const PostEditForm: FC<Props> = ({ post, onSave }) => {
|
|||||||
await update ({ id: post.id, title, tags, parentPostIds,
|
await update ({ id: post.id, title, tags, parentPostIds,
|
||||||
duration: videoFlg ? duration : null,
|
duration: videoFlg ? duration : null,
|
||||||
originalCreatedFrom, originalCreatedBefore },
|
originalCreatedFrom, originalCreatedBefore },
|
||||||
{ baseVersionNo: post.versionNo, merge: true })
|
{ baseVersionNo, merge: true })
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -141,7 +143,7 @@ const PostEditForm: FC<Props> = ({ post, onSave }) => {
|
|||||||
await update ({ id: post.id, title, tags, parentPostIds,
|
await update ({ id: post.id, title, tags, parentPostIds,
|
||||||
duration: videoFlg ? duration : null,
|
duration: videoFlg ? duration : null,
|
||||||
originalCreatedFrom, originalCreatedBefore },
|
originalCreatedFrom, originalCreatedBefore },
|
||||||
{ baseVersionNo: post.versionNo, force: true })
|
{ baseVersionNo, force: true })
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -156,7 +158,7 @@ const PostEditForm: FC<Props> = ({ post, onSave }) => {
|
|||||||
await update ({ id: post.id, title, tags, parentPostIds,
|
await update ({ id: post.id, title, tags, parentPostIds,
|
||||||
duration: videoFlg ? duration : null,
|
duration: videoFlg ? duration : null,
|
||||||
originalCreatedFrom, originalCreatedBefore },
|
originalCreatedFrom, originalCreatedBefore },
|
||||||
{ baseVersionNo: post.versionNo })
|
{ baseVersionNo })
|
||||||
}
|
}
|
||||||
finally
|
finally
|
||||||
{
|
{
|
||||||
@@ -164,11 +166,6 @@ const PostEditForm: FC<Props> = ({ post, onSave }) => {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
useEffect (() => {
|
|
||||||
setTags (tagsToStr (post.tags))
|
|
||||||
setDuration (videoMsToDurationValue (post.videoMs))
|
|
||||||
}, [post])
|
|
||||||
|
|
||||||
return (
|
return (
|
||||||
<form onSubmit={handleSubmit} className="max-w-xl pt-2 space-y-4">
|
<form onSubmit={handleSubmit} className="max-w-xl pt-2 space-y-4">
|
||||||
<FieldError messages={baseErrors}/>
|
<FieldError messages={baseErrors}/>
|
||||||
@@ -177,28 +174,28 @@ const PostEditForm: FC<Props> = ({ post, onSave }) => {
|
|||||||
label={label ('shared:labels.title')}
|
label={label ('shared:labels.title')}
|
||||||
value={title ?? ''}
|
value={title ?? ''}
|
||||||
disabled={disabled}
|
disabled={disabled}
|
||||||
onChange={setTitle}/>
|
onChange={value => setField ('title', value)}/>
|
||||||
|
|
||||||
<PostTextField
|
<PostTextField
|
||||||
label={label ('shared:labels.parentPosts')}
|
label={label ('shared:labels.parentPosts')}
|
||||||
value={parentPostIds}
|
value={parentPostIds}
|
||||||
disabled={disabled}
|
disabled={disabled}
|
||||||
errors={fieldErrors.parentPostIds}
|
errors={fieldErrors.parentPostIds}
|
||||||
onChange={setParentPostIds}/>
|
onChange={value => setField ('parentPostIds', value)}/>
|
||||||
|
|
||||||
<PostTagsField
|
<PostTagsField
|
||||||
disabled={disabled}
|
disabled={disabled}
|
||||||
tags={tags}
|
tags={tags}
|
||||||
setTags={setTags}
|
setTags={value => setField ('tags', value)}
|
||||||
errors={fieldErrors.tags}/>
|
errors={fieldErrors.tags}/>
|
||||||
|
|
||||||
{/* オリジナルの作成日時 */}
|
{/* オリジナルの作成日時 */}
|
||||||
<PostOriginalCreatedTimeField
|
<PostOriginalCreatedTimeField
|
||||||
disabled={disabled}
|
disabled={disabled}
|
||||||
originalCreatedFrom={originalCreatedFrom}
|
originalCreatedFrom={originalCreatedFrom}
|
||||||
setOriginalCreatedFrom={setOriginalCreatedFrom}
|
setOriginalCreatedFrom={value => setField ('originalCreatedFrom', value)}
|
||||||
originalCreatedBefore={originalCreatedBefore}
|
originalCreatedBefore={originalCreatedBefore}
|
||||||
setOriginalCreatedBefore={setOriginalCreatedBefore}
|
setOriginalCreatedBefore={value => setField ('originalCreatedBefore', value)}
|
||||||
errors={groupedMessages (
|
errors={groupedMessages (
|
||||||
fieldErrors.originalCreatedAt,
|
fieldErrors.originalCreatedAt,
|
||||||
fieldErrors.originalCreatedFrom,
|
fieldErrors.originalCreatedFrom,
|
||||||
@@ -209,7 +206,7 @@ const PostEditForm: FC<Props> = ({ post, onSave }) => {
|
|||||||
value={duration}
|
value={duration}
|
||||||
disabled={disabled}
|
disabled={disabled}
|
||||||
errors={fieldErrors.videoMs}
|
errors={fieldErrors.videoMs}
|
||||||
onChange={setDuration}/>)}
|
onChange={value => setField ('duration', value)}/>)}
|
||||||
|
|
||||||
{/* 送信 */}
|
{/* 送信 */}
|
||||||
<Button type="submit" disabled={disabled}>
|
<Button type="submit" disabled={disabled}>
|
||||||
|
|||||||
@@ -1,9 +1,25 @@
|
|||||||
import { fireEvent, render, screen } from '@testing-library/react'
|
import { fireEvent, render, screen, waitFor } from '@testing-library/react'
|
||||||
import { describe, expect, it } from 'vitest'
|
import { describe, expect, it, vi } from 'vitest'
|
||||||
|
|
||||||
import TabGroup, { Tab } from '@/components/common/TabGroup'
|
import TabGroup, { Tab } from '@/components/common/TabGroup'
|
||||||
|
|
||||||
describe ('TabGroup', () => {
|
describe ('TabGroup', () => {
|
||||||
|
it ('waits for approval and retains the current tab after cancellation', async () => {
|
||||||
|
const onBeforeChange = vi.fn ().mockResolvedValueOnce (false).mockResolvedValueOnce (true)
|
||||||
|
render (
|
||||||
|
<TabGroup onBeforeChange={onBeforeChange}>
|
||||||
|
<Tab name="A">Alpha</Tab>
|
||||||
|
<Tab name="B">Beta</Tab>
|
||||||
|
</TabGroup>)
|
||||||
|
|
||||||
|
fireEvent.click (screen.getByText ('B'))
|
||||||
|
await waitFor (() => expect (onBeforeChange).toHaveBeenCalledTimes (1))
|
||||||
|
expect (screen.getByText ('Alpha')).toBeInTheDocument ()
|
||||||
|
|
||||||
|
fireEvent.click (screen.getByText ('B'))
|
||||||
|
await waitFor (() => expect (screen.getByText ('Beta')).toBeInTheDocument ())
|
||||||
|
})
|
||||||
|
|
||||||
it ('uses the init tab and switches tabs when clicked', () => {
|
it ('uses the init tab and switches tabs when clicked', () => {
|
||||||
render (
|
render (
|
||||||
<TabGroup>
|
<TabGroup>
|
||||||
|
|||||||
@@ -10,12 +10,12 @@ type TabProps = { name: React.ReactNode
|
|||||||
type Props = {
|
type Props = {
|
||||||
children: React.ReactNode
|
children: React.ReactNode
|
||||||
rightAddon?: React.ReactNode
|
rightAddon?: React.ReactNode
|
||||||
}
|
onBeforeChange?: () => boolean | Promise<boolean> }
|
||||||
|
|
||||||
export const Tab = ({ children }: TabProps) => <>{children}</>
|
export const Tab = ({ children }: TabProps) => <>{children}</>
|
||||||
|
|
||||||
|
|
||||||
const TabGroup: FC<Props> = ({ children, rightAddon }) => {
|
const TabGroup: FC<Props> = ({ children, rightAddon, onBeforeChange }) => {
|
||||||
const tabs = React.Children.toArray (children) as React.ReactElement<TabProps>[]
|
const tabs = React.Children.toArray (children) as React.ReactElement<TabProps>[]
|
||||||
|
|
||||||
const [current, setCurrent] = useState<number> (() => {
|
const [current, setCurrent] = useState<number> (() => {
|
||||||
@@ -36,7 +36,9 @@ const TabGroup: FC<Props> = ({ children, rightAddon }) => {
|
|||||||
'focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring',
|
'focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring',
|
||||||
i === current && 'font-bold',
|
i === current && 'font-bold',
|
||||||
)}
|
)}
|
||||||
onClick={() => {
|
onClick={async () => {
|
||||||
|
if (i === current) return
|
||||||
|
if (onBeforeChange != null && !(await onBeforeChange ())) return
|
||||||
setCurrent (i)
|
setCurrent (i)
|
||||||
}}>
|
}}>
|
||||||
{tab.props.name}
|
{tab.props.name}
|
||||||
|
|||||||
@@ -1,4 +1,4 @@
|
|||||||
import { act, screen, waitFor } from '@testing-library/react'
|
import { act, fireEvent, screen, waitFor } from '@testing-library/react'
|
||||||
import { beforeEach, describe, expect, it, vi } from 'vitest'
|
import { beforeEach, describe, expect, it, vi } from 'vitest'
|
||||||
|
|
||||||
import PostImportRowForm from '@/components/posts/import/PostImportRowForm'
|
import PostImportRowForm from '@/components/posts/import/PostImportRowForm'
|
||||||
@@ -22,6 +22,19 @@ describe ('PostImportRowForm', () => {
|
|||||||
api.apiGet.mockResolvedValue (new Blob (['img'], { type: 'image/png' }))
|
api.apiGet.mockResolvedValue (new Blob (['img'], { type: 'image/png' }))
|
||||||
})
|
})
|
||||||
|
|
||||||
|
it ('restores pending row edits when the editor remounts', () => {
|
||||||
|
const row = buildPostImportRow ({ attributes: { title: 'original' } })
|
||||||
|
const controls: DialogueFormControls = {
|
||||||
|
close: vi.fn (), confirm: vi.fn (), setActions: vi.fn () }
|
||||||
|
const first = render (
|
||||||
|
<PostImportRowForm row={row} controls={controls} onSave={vi.fn ()}/>)
|
||||||
|
fireEvent.change (screen.getByDisplayValue ('original'), { target: { value: 'row draft' } })
|
||||||
|
first.unmount ()
|
||||||
|
|
||||||
|
render (<PostImportRowForm row={row} controls={controls} onSave={vi.fn ()}/>)
|
||||||
|
expect (screen.getByDisplayValue ('row draft')).toBeInTheDocument ()
|
||||||
|
})
|
||||||
|
|
||||||
it ('resets only the draft, then saves with resetRequested', async () => {
|
it ('resets only the draft, then saves with resetRequested', async () => {
|
||||||
const row = buildPostImportRow ()
|
const row = buildPostImportRow ()
|
||||||
row.attributes.title = 'manual title'
|
row.attributes.title = 'manual title'
|
||||||
|
|||||||
@@ -8,10 +8,11 @@ import PostTextField from '@/components/posts/PostTextField'
|
|||||||
import PostImportThumbnailPreview from '@/components/posts/import/PostImportThumbnailPreview'
|
import PostImportThumbnailPreview from '@/components/posts/import/PostImportThumbnailPreview'
|
||||||
import { hasThumbnailBaseValue, hasVideoTag } from '@/lib/postImportRows'
|
import { hasThumbnailBaseValue, hasVideoTag } from '@/lib/postImportRows'
|
||||||
import { renderPostImportMessage } from '@/components/posts/import/postImportRowStatus'
|
import { renderPostImportMessage } from '@/components/posts/import/postImportRowStatus'
|
||||||
|
import { useSessionDraft } from '@/lib/useSessionDraft'
|
||||||
import { useLocale } from '@/lib/useLocale'
|
import { useLocale } from '@/lib/useLocale'
|
||||||
import { useUITranslation } from '@/lib/useUITranslation'
|
import { useUITranslation } from '@/lib/useUITranslation'
|
||||||
|
|
||||||
import type { FC, ReactNode } from 'react'
|
import type { FC, ReactNode, SetStateAction } from 'react'
|
||||||
|
|
||||||
import type { DialogueFormControls } from '@/lib/dialogues/useDialogue'
|
import type { DialogueFormControls } from '@/lib/dialogues/useDialogue'
|
||||||
import type { PostImportEditableDraft, PostImportRow } from '@/lib/postImportTypes'
|
import type { PostImportEditableDraft, PostImportRow } from '@/lib/postImportTypes'
|
||||||
@@ -21,6 +22,7 @@ type Draft = PostImportEditableDraft
|
|||||||
type Props = {
|
type Props = {
|
||||||
row: PostImportRow
|
row: PostImportRow
|
||||||
controls: DialogueFormControls
|
controls: DialogueFormControls
|
||||||
|
onDirtyStateChange?: (dirty: boolean, discard: () => void) => void
|
||||||
onSave: (args: { draft: Draft
|
onSave: (args: { draft: Draft
|
||||||
resetRequested: boolean }) => Promise<{
|
resetRequested: boolean }) => Promise<{
|
||||||
saved: boolean
|
saved: boolean
|
||||||
@@ -96,6 +98,7 @@ const thumbnailWarnings = (
|
|||||||
const PostImportRowForm: FC<Props> = (
|
const PostImportRowForm: FC<Props> = (
|
||||||
{ row,
|
{ row,
|
||||||
controls,
|
controls,
|
||||||
|
onDirtyStateChange,
|
||||||
onSave },
|
onSave },
|
||||||
) => {
|
) => {
|
||||||
const locale = useLocale ()
|
const locale = useLocale ()
|
||||||
@@ -103,21 +106,26 @@ const PostImportRowForm: FC<Props> = (
|
|||||||
const groupedMessages = (...values: (string[] | undefined)[]): ReactNode[] =>
|
const groupedMessages = (...values: (string[] | undefined)[]): ReactNode[] =>
|
||||||
[...new Set (values.flatMap (value => value ?? []))]
|
[...new Set (values.flatMap (value => value ?? []))]
|
||||||
.map (value => renderPostImportMessage (value, locale))
|
.map (value => renderPostImportMessage (value, locale))
|
||||||
const [draft, setDraft] = useState<Draft> (() => buildDraft (row))
|
const { draft: state, setField, clearDraft, discardDraft, dirty } = useSessionDraft (
|
||||||
|
`post-import:row:${row.sourceRow}:${row.resetSnapshot.url}`,
|
||||||
|
{ value: buildDraft (row), resetRequested: false })
|
||||||
|
const { value: draft, resetRequested } = state
|
||||||
|
const setDraft = useCallback ((value: SetStateAction<Draft>) =>
|
||||||
|
setField ('value', value), [setField])
|
||||||
const [messageRow, setMessageRow] = useState<PostImportRow | null> (null)
|
const [messageRow, setMessageRow] = useState<PostImportRow | null> (null)
|
||||||
const [saving, setSaving] = useState (false)
|
const [saving, setSaving] = useState (false)
|
||||||
const [resetRequested, setResetRequested] = useState (false)
|
|
||||||
const [committedThumbnailBase, setCommittedThumbnailBase] = useState (
|
const [committedThumbnailBase, setCommittedThumbnailBase] = useState (
|
||||||
() => String (row.attributes.thumbnailBase ?? ''))
|
() => String (row.attributes.thumbnailBase ?? ''))
|
||||||
|
|
||||||
useEffect (() => {
|
useEffect (() => {
|
||||||
const nextDraft = buildDraft (row)
|
|
||||||
setDraft (nextDraft)
|
|
||||||
setMessageRow (null)
|
setMessageRow (null)
|
||||||
setResetRequested (false)
|
|
||||||
setCommittedThumbnailBase (String (row.attributes.thumbnailBase ?? ''))
|
setCommittedThumbnailBase (String (row.attributes.thumbnailBase ?? ''))
|
||||||
}, [row])
|
}, [row])
|
||||||
|
|
||||||
|
useEffect (() => {
|
||||||
|
onDirtyStateChange?.(dirty, discardDraft)
|
||||||
|
}, [dirty, discardDraft, onDirtyStateChange])
|
||||||
|
|
||||||
const displayRow = messageRow ?? row
|
const displayRow = messageRow ?? row
|
||||||
const resetDraft = useMemo (
|
const resetDraft = useMemo (
|
||||||
() => buildResetDraft (row),
|
() => buildResetDraft (row),
|
||||||
@@ -157,11 +165,11 @@ const PostImportRowForm: FC<Props> = (
|
|||||||
return false
|
return false
|
||||||
|
|
||||||
setDraft (resetDraft)
|
setDraft (resetDraft)
|
||||||
setResetRequested (true)
|
setField ('resetRequested', true)
|
||||||
setMessageRow (null)
|
setMessageRow (null)
|
||||||
setCommittedThumbnailBase (resetDraft.thumbnailBase)
|
setCommittedThumbnailBase (resetDraft.thumbnailBase)
|
||||||
return false
|
return false
|
||||||
}, [controls, resetDisabled, resetDraft, label])
|
}, [controls, resetDisabled, resetDraft, label, setDraft, setField])
|
||||||
|
|
||||||
const save = useCallback (async (): Promise<boolean> => {
|
const save = useCallback (async (): Promise<boolean> => {
|
||||||
setSaving (true)
|
setSaving (true)
|
||||||
@@ -169,7 +177,10 @@ const PostImportRowForm: FC<Props> = (
|
|||||||
{
|
{
|
||||||
const result = await onSave ({ draft, resetRequested })
|
const result = await onSave ({ draft, resetRequested })
|
||||||
if (result.saved)
|
if (result.saved)
|
||||||
|
{
|
||||||
|
clearDraft ()
|
||||||
return true
|
return true
|
||||||
|
}
|
||||||
|
|
||||||
if (result.row != null)
|
if (result.row != null)
|
||||||
setMessageRow (result.row)
|
setMessageRow (result.row)
|
||||||
@@ -179,7 +190,7 @@ const PostImportRowForm: FC<Props> = (
|
|||||||
{
|
{
|
||||||
setSaving (false)
|
setSaving (false)
|
||||||
}
|
}
|
||||||
}, [draft, onSave, resetRequested])
|
}, [clearDraft, draft, onSave, resetRequested])
|
||||||
|
|
||||||
useEffect (() => {
|
useEffect (() => {
|
||||||
controls.setActions ([{
|
controls.setActions ([{
|
||||||
|
|||||||
@@ -1,72 +1,17 @@
|
|||||||
import { translateUIMessage } from '@/lib/i18n'
|
import { translateUIMessage } from '@/lib/i18n'
|
||||||
|
import { readSessionStorage, writeSessionStorage, removeSessionStorage }
|
||||||
|
from '@/lib/sessionStorage'
|
||||||
|
|
||||||
import type { StorageErrorHandler } from '@/lib/postImportTypes'
|
import type { StorageErrorHandler } from '@/lib/postImportTypes'
|
||||||
|
|
||||||
const SOURCE_DRAFT_KEY = 'post-import-source-draft'
|
const SOURCE_DRAFT_KEY = 'post-import-source-draft'
|
||||||
|
|
||||||
|
|
||||||
const readStorage = (
|
|
||||||
key: string,
|
|
||||||
onError?: StorageErrorHandler,
|
|
||||||
): string | null => {
|
|
||||||
if (typeof window === 'undefined')
|
|
||||||
return null
|
|
||||||
|
|
||||||
try
|
|
||||||
{
|
|
||||||
return sessionStorage.getItem (key)
|
|
||||||
}
|
|
||||||
catch
|
|
||||||
{
|
|
||||||
onError?.(translateUIMessage ('storage.readFailed', 'imports', 'ja').text)
|
|
||||||
return null
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
|
|
||||||
const writeStorage = (
|
|
||||||
key: string,
|
|
||||||
value: string,
|
|
||||||
onError?: StorageErrorHandler,
|
|
||||||
): boolean => {
|
|
||||||
if (typeof window === 'undefined')
|
|
||||||
return false
|
|
||||||
|
|
||||||
try
|
|
||||||
{
|
|
||||||
sessionStorage.setItem (key, value)
|
|
||||||
return true
|
|
||||||
}
|
|
||||||
catch
|
|
||||||
{
|
|
||||||
onError?.(translateUIMessage ('storage.writeFailed', 'imports', 'ja').text)
|
|
||||||
return false
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
|
|
||||||
const removeStorage = (
|
|
||||||
key: string,
|
|
||||||
onError?: StorageErrorHandler,
|
|
||||||
) => {
|
|
||||||
if (typeof window === 'undefined')
|
|
||||||
return
|
|
||||||
|
|
||||||
try
|
|
||||||
{
|
|
||||||
sessionStorage.removeItem (key)
|
|
||||||
}
|
|
||||||
catch
|
|
||||||
{
|
|
||||||
onError?.(translateUIMessage ('storage.clearFailed', 'imports', 'ja').text)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
|
|
||||||
export const loadPostImportSourceDraft = (
|
export const loadPostImportSourceDraft = (
|
||||||
onError?: StorageErrorHandler,
|
onError?: StorageErrorHandler,
|
||||||
): { source: string } => {
|
): { source: string } => {
|
||||||
const raw = readStorage (SOURCE_DRAFT_KEY, onError)
|
const raw = readSessionStorage (SOURCE_DRAFT_KEY, () =>
|
||||||
|
onError?.(translateUIMessage ('storage.readFailed', 'imports', 'ja').text))
|
||||||
if (raw == null)
|
if (raw == null)
|
||||||
return { source: '' }
|
return { source: '' }
|
||||||
|
|
||||||
@@ -86,11 +31,13 @@ export const savePostImportSourceDraft = (
|
|||||||
source: string,
|
source: string,
|
||||||
onError?: StorageErrorHandler,
|
onError?: StorageErrorHandler,
|
||||||
): boolean =>
|
): boolean =>
|
||||||
writeStorage (SOURCE_DRAFT_KEY, JSON.stringify ({ source }), onError)
|
writeSessionStorage (SOURCE_DRAFT_KEY, JSON.stringify ({ source }), () =>
|
||||||
|
onError?.(translateUIMessage ('storage.writeFailed', 'imports', 'ja').text))
|
||||||
|
|
||||||
|
|
||||||
export const clearPostImportSourceDraft = (
|
export const clearPostImportSourceDraft = (
|
||||||
onError?: StorageErrorHandler,
|
onError?: StorageErrorHandler,
|
||||||
) => {
|
) => {
|
||||||
removeStorage (SOURCE_DRAFT_KEY, onError)
|
removeSessionStorage (SOURCE_DRAFT_KEY, () =>
|
||||||
|
onError?.(translateUIMessage ('storage.clearFailed', 'imports', 'ja').text))
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -0,0 +1,58 @@
|
|||||||
|
export const readSessionStorage = (
|
||||||
|
key: string,
|
||||||
|
onError?: () => void,
|
||||||
|
): string | null => {
|
||||||
|
if (typeof window === 'undefined')
|
||||||
|
return null
|
||||||
|
|
||||||
|
try
|
||||||
|
{
|
||||||
|
return sessionStorage.getItem (key)
|
||||||
|
}
|
||||||
|
catch
|
||||||
|
{
|
||||||
|
onError?.()
|
||||||
|
return null
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
export const writeSessionStorage = (
|
||||||
|
key: string,
|
||||||
|
value: string,
|
||||||
|
onError?: () => void,
|
||||||
|
): boolean => {
|
||||||
|
if (typeof window === 'undefined')
|
||||||
|
return false
|
||||||
|
|
||||||
|
try
|
||||||
|
{
|
||||||
|
sessionStorage.setItem (key, value)
|
||||||
|
return true
|
||||||
|
}
|
||||||
|
catch
|
||||||
|
{
|
||||||
|
onError?.()
|
||||||
|
return false
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
export const removeSessionStorage = (
|
||||||
|
key: string,
|
||||||
|
onError?: () => void,
|
||||||
|
) => {
|
||||||
|
if (typeof window === 'undefined')
|
||||||
|
return
|
||||||
|
|
||||||
|
try
|
||||||
|
{
|
||||||
|
sessionStorage.removeItem (key)
|
||||||
|
}
|
||||||
|
catch
|
||||||
|
{
|
||||||
|
onError?.()
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
@@ -0,0 +1,249 @@
|
|||||||
|
import { act, fireEvent, screen, waitFor } from '@testing-library/react'
|
||||||
|
import { renderToString } from 'react-dom/server'
|
||||||
|
import { createMemoryRouter, RouterProvider, useLocation, useNavigate } from 'react-router-dom'
|
||||||
|
import { beforeEach, describe, expect, it, vi } from 'vitest'
|
||||||
|
|
||||||
|
import DialogueProvider from '@/components/dialogues/DialogueProvider'
|
||||||
|
import { useSessionDraft } from '@/lib/useSessionDraft'
|
||||||
|
import { UnsavedChangesGuardProvider } from '@/lib/useUnsavedChangesGuard'
|
||||||
|
import { renderWithProviders } from '@/test/render'
|
||||||
|
|
||||||
|
const storageKey = 'session-draft:1:anonymous:editor'
|
||||||
|
const initialDraft = { title: 'original', file: null as File | null }
|
||||||
|
|
||||||
|
const Editor = (
|
||||||
|
{ name = 'editor', initial = initialDraft, active = true }: {
|
||||||
|
name?: string
|
||||||
|
initial?: typeof initialDraft
|
||||||
|
active?: boolean },
|
||||||
|
) => {
|
||||||
|
const { draft, setField, clearDraft, allowNextNavigation } =
|
||||||
|
useSessionDraft (name, initial, active)
|
||||||
|
const location = useLocation ()
|
||||||
|
const navigate = useNavigate ()
|
||||||
|
|
||||||
|
return (
|
||||||
|
<>
|
||||||
|
<output aria-label="location">{location.pathname}</output>
|
||||||
|
<input aria-label="title" value={draft.title}
|
||||||
|
onChange={event => setField ('title', event.target.value)}/>
|
||||||
|
<input aria-label="file" type="file"
|
||||||
|
onChange={event => setField ('file', event.target.files?.[0] ?? null)}/>
|
||||||
|
<output aria-label="filename">{draft.file?.name}</output>
|
||||||
|
<button onClick={() => navigate ('/away')}>leave</button>
|
||||||
|
<button onClick={() => navigate (-1)}>back</button>
|
||||||
|
<button onClick={() => {
|
||||||
|
clearDraft ()
|
||||||
|
allowNextNavigation ()
|
||||||
|
navigate ('/saved')
|
||||||
|
}}>save</button>
|
||||||
|
</>)
|
||||||
|
}
|
||||||
|
|
||||||
|
describe ('session drafts and navigation', () => {
|
||||||
|
beforeEach (() => sessionStorage.clear ())
|
||||||
|
|
||||||
|
it ('does not store pristine input or warn before it changes', () => {
|
||||||
|
renderWithProviders (<Editor/>, { route: '/editor' })
|
||||||
|
expect (sessionStorage.getItem (storageKey)).toBeNull ()
|
||||||
|
fireEvent.click (screen.getByText ('leave'))
|
||||||
|
expect (screen.getByLabelText ('location')).toHaveTextContent ('/away')
|
||||||
|
expect (screen.queryByRole ('dialog')).not.toBeInTheDocument ()
|
||||||
|
})
|
||||||
|
|
||||||
|
it ('stores changed input immediately and restores it after remounting', () => {
|
||||||
|
const first = renderWithProviders (<Editor/>)
|
||||||
|
fireEvent.change (screen.getByLabelText ('title'), { target: { value: 'draft' } })
|
||||||
|
expect (JSON.parse (sessionStorage.getItem (storageKey)!)).toEqual ({
|
||||||
|
title: 'draft', file: null })
|
||||||
|
first.unmount ()
|
||||||
|
|
||||||
|
renderWithProviders (<Editor/>)
|
||||||
|
expect (screen.getByLabelText ('title')).toHaveValue ('draft')
|
||||||
|
})
|
||||||
|
|
||||||
|
it ('preserves input and storage when navigation is cancelled', async () => {
|
||||||
|
renderWithProviders (<Editor/>, { route: '/editor' })
|
||||||
|
fireEvent.change (screen.getByLabelText ('title'), { target: { value: 'draft' } })
|
||||||
|
fireEvent.click (screen.getByText ('leave'))
|
||||||
|
fireEvent.click (await screen.findByRole ('button', { name: '取消' }))
|
||||||
|
|
||||||
|
await waitFor (() => expect (screen.queryByRole ('dialog')).not.toBeInTheDocument ())
|
||||||
|
expect (screen.getByLabelText ('location')).toHaveTextContent ('/editor')
|
||||||
|
expect (screen.getByLabelText ('title')).toHaveValue ('draft')
|
||||||
|
expect (sessionStorage.getItem (storageKey)).toContain ('draft')
|
||||||
|
})
|
||||||
|
|
||||||
|
it ('discards both live input and its stored copy after confirmation', async () => {
|
||||||
|
renderWithProviders (<Editor/>, { route: '/editor' })
|
||||||
|
fireEvent.change (screen.getByLabelText ('title'), { target: { value: 'draft' } })
|
||||||
|
fireEvent.click (screen.getByText ('leave'))
|
||||||
|
fireEvent.click (await screen.findByRole ('button', { name: '変更を破棄して移動' }))
|
||||||
|
|
||||||
|
await waitFor (() => {
|
||||||
|
expect (screen.getByLabelText ('location')).toHaveTextContent ('/away')
|
||||||
|
})
|
||||||
|
expect (sessionStorage.getItem (storageKey)).toBeNull ()
|
||||||
|
expect (screen.getByLabelText ('title')).toHaveValue ('original')
|
||||||
|
})
|
||||||
|
|
||||||
|
it ('warns for history navigation too', async () => {
|
||||||
|
renderWithProviders (<Editor/>, { route: '/editor' })
|
||||||
|
fireEvent.click (screen.getByText ('leave'))
|
||||||
|
fireEvent.change (screen.getByLabelText ('title'), { target: { value: 'draft' } })
|
||||||
|
fireEvent.click (screen.getByText ('back'))
|
||||||
|
expect (await screen.findByRole ('dialog')).toBeInTheDocument ()
|
||||||
|
expect (screen.getByLabelText ('location')).toHaveTextContent ('/away')
|
||||||
|
})
|
||||||
|
|
||||||
|
it ('clears successful submissions without prompting on their next navigation', () => {
|
||||||
|
renderWithProviders (<Editor/>, { route: '/editor' })
|
||||||
|
fireEvent.change (screen.getByLabelText ('title'), { target: { value: 'saved' } })
|
||||||
|
fireEvent.click (screen.getByText ('save'))
|
||||||
|
expect (screen.getByLabelText ('location')).toHaveTextContent ('/saved')
|
||||||
|
expect (sessionStorage.getItem (storageKey)).toBeNull ()
|
||||||
|
expect (screen.queryByRole ('dialog')).not.toBeInTheDocument ()
|
||||||
|
})
|
||||||
|
|
||||||
|
it ('retains drafts until a browser departure actually occurs', () => {
|
||||||
|
renderWithProviders (<Editor/>)
|
||||||
|
fireEvent.change (screen.getByLabelText ('title'), { target: { value: 'draft' } })
|
||||||
|
const event = new Event ('beforeunload', { cancelable: true })
|
||||||
|
window.dispatchEvent (event)
|
||||||
|
expect (event.defaultPrevented).toBe (true)
|
||||||
|
expect (sessionStorage.getItem (storageKey)).toContain ('draft')
|
||||||
|
|
||||||
|
fireEvent (window, new Event ('pagehide'))
|
||||||
|
expect (sessionStorage.getItem (storageKey)).toBeNull ()
|
||||||
|
expect (screen.getByLabelText ('title')).toHaveValue ('original')
|
||||||
|
})
|
||||||
|
|
||||||
|
it ('keeps dirty input across background data refreshes', () => {
|
||||||
|
const view = renderWithProviders (<Editor/>)
|
||||||
|
fireEvent.change (screen.getByLabelText ('title'), { target: { value: 'my draft' } })
|
||||||
|
view.rerender (<Editor initial={{ title: 'new server value', file: null }}/>)
|
||||||
|
expect (screen.getByLabelText ('title')).toHaveValue ('my draft')
|
||||||
|
})
|
||||||
|
|
||||||
|
it ('preserves newly added list rows with an empty nullable selection', () => {
|
||||||
|
const ListEditor = () => {
|
||||||
|
const { draft, setDraft } = useSessionDraft ('list', [
|
||||||
|
{ platform: 'youtube' as string | null, code: 'original' }])
|
||||||
|
return (
|
||||||
|
<>
|
||||||
|
<output aria-label="rows">{JSON.stringify (draft)}</output>
|
||||||
|
<button onClick={() => setDraft ([...draft, { platform: null, code: '' }])}>
|
||||||
|
add row
|
||||||
|
</button>
|
||||||
|
</>)
|
||||||
|
}
|
||||||
|
const first = renderWithProviders (<ListEditor/>)
|
||||||
|
fireEvent.click (screen.getByText ('add row'))
|
||||||
|
first.unmount ()
|
||||||
|
|
||||||
|
renderWithProviders (<ListEditor/>)
|
||||||
|
expect (JSON.parse (screen.getByLabelText ('rows').textContent!)).toEqual ([
|
||||||
|
{ platform: 'youtube', code: 'original' }, { platform: null, code: '' }])
|
||||||
|
})
|
||||||
|
|
||||||
|
it ('does not restore a different resource or an inactive editor', () => {
|
||||||
|
sessionStorage.setItem (storageKey, JSON.stringify ({ title: 'private draft', file: null }))
|
||||||
|
const view = renderWithProviders (<Editor name="other"/>)
|
||||||
|
expect (screen.getByLabelText ('title')).toHaveValue ('original')
|
||||||
|
view.rerender (<Editor active={false}/>)
|
||||||
|
expect (screen.getByLabelText ('title')).toHaveValue ('original')
|
||||||
|
expect (sessionStorage.getItem (storageKey)).toContain ('private draft')
|
||||||
|
})
|
||||||
|
|
||||||
|
it ('keeps drafts separate across accounts and roles', () => {
|
||||||
|
const first = renderWithProviders (<Editor/>, { draftScope: '1:admin' })
|
||||||
|
fireEvent.change (screen.getByLabelText ('title'), { target: { value: 'admin draft' } })
|
||||||
|
first.unmount ()
|
||||||
|
|
||||||
|
const second = renderWithProviders (<Editor/>, { draftScope: '1:member' })
|
||||||
|
expect (screen.getByLabelText ('title')).toHaveValue ('original')
|
||||||
|
second.unmount ()
|
||||||
|
|
||||||
|
renderWithProviders (<Editor/>, { draftScope: '2:admin' })
|
||||||
|
expect (screen.getByLabelText ('title')).toHaveValue ('original')
|
||||||
|
})
|
||||||
|
|
||||||
|
it ('removes the draft after all changes are reverted', () => {
|
||||||
|
renderWithProviders (<Editor/>)
|
||||||
|
fireEvent.change (screen.getByLabelText ('title'), { target: { value: 'draft' } })
|
||||||
|
fireEvent.change (screen.getByLabelText ('title'), { target: { value: 'original' } })
|
||||||
|
expect (sessionStorage.getItem (storageKey)).toBeNull ()
|
||||||
|
const event = new Event ('beforeunload', { cancelable: true })
|
||||||
|
window.dispatchEvent (event)
|
||||||
|
expect (event.defaultPrevented).toBe (false)
|
||||||
|
})
|
||||||
|
|
||||||
|
it.each (['{', 'null', '{"title":12,"file":null}']) (
|
||||||
|
'ignores corrupt or incompatible storage: %s', raw => {
|
||||||
|
sessionStorage.setItem (storageKey, raw)
|
||||||
|
renderWithProviders (<Editor/>)
|
||||||
|
expect (screen.getByLabelText ('title')).toHaveValue ('original')
|
||||||
|
expect (sessionStorage.getItem (storageKey)).toBeNull ()
|
||||||
|
})
|
||||||
|
|
||||||
|
it ('continues guarding input when browser storage is unavailable', async () => {
|
||||||
|
vi.spyOn (Storage.prototype, 'getItem').mockImplementation (() => {
|
||||||
|
throw new DOMException ('disabled')
|
||||||
|
})
|
||||||
|
vi.spyOn (Storage.prototype, 'setItem').mockImplementation (() => {
|
||||||
|
throw new DOMException ('quota')
|
||||||
|
})
|
||||||
|
renderWithProviders (<Editor/>)
|
||||||
|
fireEvent.change (screen.getByLabelText ('title'), { target: { value: 'draft' } })
|
||||||
|
fireEvent.click (screen.getByText ('leave'))
|
||||||
|
expect (await screen.findByRole ('dialog')).toBeInTheDocument ()
|
||||||
|
})
|
||||||
|
|
||||||
|
it ('restores selected file contents as well as text', async () => {
|
||||||
|
const first = renderWithProviders (<Editor/>)
|
||||||
|
const file = new File (['image data'], 'draft.png', { type: 'image/png' })
|
||||||
|
fireEvent.change (screen.getByLabelText ('file'), { target: { files: [file] } })
|
||||||
|
await waitFor (() => {
|
||||||
|
expect (sessionStorage.getItem (storageKey)).toContain ('draft.png')
|
||||||
|
})
|
||||||
|
first.unmount ()
|
||||||
|
|
||||||
|
renderWithProviders (<Editor/>)
|
||||||
|
expect (screen.getByLabelText ('filename')).toHaveTextContent ('draft.png')
|
||||||
|
expect (JSON.parse (sessionStorage.getItem (storageKey)!).file.data)
|
||||||
|
.toBe ('data:image/png;base64,aW1hZ2UgZGF0YQ==')
|
||||||
|
})
|
||||||
|
|
||||||
|
it ('does not recreate discarded drafts when a pending file read finishes', async () => {
|
||||||
|
const pending = { reader: null as FileReader | null }
|
||||||
|
vi.spyOn (FileReader.prototype, 'readAsDataURL').mockImplementation (function (this: FileReader) {
|
||||||
|
pending.reader = this
|
||||||
|
})
|
||||||
|
renderWithProviders (<Editor/>)
|
||||||
|
fireEvent.change (screen.getByLabelText ('file'), {
|
||||||
|
target: { files: [new File (['data'], 'pending.png')] } })
|
||||||
|
expect (pending.reader).not.toBeNull ()
|
||||||
|
|
||||||
|
fireEvent (window, new Event ('pagehide'))
|
||||||
|
const reader = pending.reader!
|
||||||
|
Object.defineProperty (reader, 'result', { value: 'data:;base64,ZGF0YQ==' })
|
||||||
|
await act (async () => {
|
||||||
|
reader.dispatchEvent (new ProgressEvent ('load'))
|
||||||
|
})
|
||||||
|
expect (sessionStorage.getItem (storageKey)).toBeNull ()
|
||||||
|
})
|
||||||
|
|
||||||
|
it ('keeps browser drafts out of the server render and initial hydration markup', () => {
|
||||||
|
sessionStorage.setItem (storageKey, JSON.stringify ({ title: 'browser draft', file: null }))
|
||||||
|
const router = createMemoryRouter ([{ path: '*', element: (
|
||||||
|
<DialogueProvider>
|
||||||
|
<UnsavedChangesGuardProvider>
|
||||||
|
<Editor/>
|
||||||
|
</UnsavedChangesGuardProvider>
|
||||||
|
</DialogueProvider>) }])
|
||||||
|
const html = renderToString (<RouterProvider router={router}/>)
|
||||||
|
expect (html).toContain ('original')
|
||||||
|
expect (html).not.toContain ('browser draft')
|
||||||
|
expect (sessionStorage.getItem (storageKey)).toContain ('browser draft')
|
||||||
|
})
|
||||||
|
})
|
||||||
@@ -0,0 +1,180 @@
|
|||||||
|
import { useCallback, useEffect, useRef, useState } from 'react'
|
||||||
|
|
||||||
|
import { readSessionStorage, removeSessionStorage, writeSessionStorage }
|
||||||
|
from '@/lib/sessionStorage'
|
||||||
|
import { useUnsavedChangesGuard } from '@/lib/useUnsavedChangesGuard'
|
||||||
|
|
||||||
|
import type { SetStateAction } from 'react'
|
||||||
|
|
||||||
|
const fileIds = new WeakMap<File, number> ()
|
||||||
|
let fileSequence = 0
|
||||||
|
|
||||||
|
const serialiseIdentity = (value: unknown): string =>
|
||||||
|
JSON.stringify (value, (_key, item) => {
|
||||||
|
if (typeof File === 'undefined' || !(item instanceof File)) return item
|
||||||
|
if (!fileIds.has (item)) fileIds.set (item, ++fileSequence)
|
||||||
|
return { fileId: fileIds.get (item) }
|
||||||
|
})
|
||||||
|
|
||||||
|
const serialiseDraft = (value: unknown): string | Promise<string> => {
|
||||||
|
const files: File[] = []
|
||||||
|
const raw = JSON.stringify (value, (_key, item) => {
|
||||||
|
if (typeof File === 'undefined' || !(item instanceof File)) return item
|
||||||
|
return { sessionDraftFileId: files.push (item) - 1 }
|
||||||
|
})
|
||||||
|
if (files.length === 0) return raw
|
||||||
|
return Promise.all (files.map (file => new Promise ((resolve, reject) => {
|
||||||
|
const reader = new FileReader ()
|
||||||
|
reader.onerror = () => reject (reader.error)
|
||||||
|
reader.onload = () => resolve ({
|
||||||
|
sessionDraftFileFlg: true, name: file.name, type: file.type,
|
||||||
|
lastModified: file.lastModified, data: reader.result })
|
||||||
|
reader.readAsDataURL (file)
|
||||||
|
}))).then (values => JSON.stringify (JSON.parse (raw, (_key, item) =>
|
||||||
|
item?.sessionDraftFileId == null ? item : values[item.sessionDraftFileId])))
|
||||||
|
}
|
||||||
|
|
||||||
|
const parseDraft = (raw: string): unknown =>
|
||||||
|
JSON.parse (raw, (_key, value) => {
|
||||||
|
if (value?.sessionDraftFileFlg !== true) return value
|
||||||
|
if (typeof value.name !== 'string' || typeof value.type !== 'string'
|
||||||
|
|| typeof value.lastModified !== 'number' || typeof value.data !== 'string')
|
||||||
|
throw new Error ('Invalid draft file')
|
||||||
|
const data = atob (value.data.slice (value.data.indexOf (',') + 1))
|
||||||
|
const bytes = Uint8Array.from (data, character => character.charCodeAt (0))
|
||||||
|
return new File ([bytes], value.name, {
|
||||||
|
type: value.type, lastModified: value.lastModified })
|
||||||
|
})
|
||||||
|
|
||||||
|
const validDraft = (value: unknown, initial: unknown, nullable = false): boolean => {
|
||||||
|
if (nullable && value == null && typeof initial !== 'object') return true
|
||||||
|
if (initial == null)
|
||||||
|
return value == null || typeof value === 'string' || typeof value === 'number'
|
||||||
|
|| (typeof File !== 'undefined' && value instanceof File)
|
||||||
|
if (Array.isArray (initial))
|
||||||
|
return Array.isArray (value)
|
||||||
|
&& (initial.length === 0 || value.every (item => validDraft (item, initial[0], true)))
|
||||||
|
if (typeof initial !== 'object') return typeof value === typeof initial
|
||||||
|
if (value == null || typeof value !== 'object' || Array.isArray (value)) return false
|
||||||
|
return Object.entries (initial).every (([key, item]) =>
|
||||||
|
validDraft ((value as Record<string, unknown>)[key], item, nullable))
|
||||||
|
}
|
||||||
|
|
||||||
|
type DraftEntry<T> = {
|
||||||
|
key: string
|
||||||
|
initial: string
|
||||||
|
baseline: T
|
||||||
|
value: T }
|
||||||
|
|
||||||
|
// Server data supplies the baseline; background refetches never replace dirty input.
|
||||||
|
export const useSessionDraft = <T,> (
|
||||||
|
name: string,
|
||||||
|
initial: T,
|
||||||
|
active = true,
|
||||||
|
difference?: (value: T, baseline: T) => boolean,
|
||||||
|
) => {
|
||||||
|
const { draftScope, allowNextNavigation, confirmNavigation } = useUnsavedChangesGuard ()
|
||||||
|
const key = `session-draft:1:${draftScope}:${name}`
|
||||||
|
const available = active && draftScope !== ''
|
||||||
|
const identity = serialiseIdentity (initial)
|
||||||
|
const [entry, setEntry] = useState<DraftEntry<T> | null> (null)
|
||||||
|
const revision = useRef (0)
|
||||||
|
const current = useRef ({ key, initial, identity, entry })
|
||||||
|
current.current = { key, initial, identity, entry }
|
||||||
|
const ready = available && entry?.key === key
|
||||||
|
const pristine = entry == null
|
||||||
|
|| serialiseIdentity (entry.value) === serialiseIdentity (entry.baseline)
|
||||||
|
const draft = ready && !(pristine && entry.initial !== identity) ? entry.value : initial
|
||||||
|
const dirty = ready && (difference?.(draft, entry.baseline) ?? !pristine)
|
||||||
|
|
||||||
|
useEffect (() => {
|
||||||
|
if (!available) return
|
||||||
|
const { initial } = current.current
|
||||||
|
setEntry (previous => {
|
||||||
|
if (previous?.key === key)
|
||||||
|
{
|
||||||
|
if (previous.initial === identity) return previous
|
||||||
|
const clean = serialiseIdentity (previous.value) === serialiseIdentity (previous.baseline)
|
||||||
|
return { key, initial: identity, baseline: initial,
|
||||||
|
value: clean ? initial : previous.value }
|
||||||
|
}
|
||||||
|
const raw = readSessionStorage (key)
|
||||||
|
try
|
||||||
|
{
|
||||||
|
const value: unknown = raw == null ? initial : parseDraft (raw)
|
||||||
|
if (validDraft (value, initial))
|
||||||
|
return { key, initial: identity, baseline: initial, value: value as T }
|
||||||
|
}
|
||||||
|
catch
|
||||||
|
{
|
||||||
|
// Corrupt or obsolete browser data must not break the editor.
|
||||||
|
}
|
||||||
|
removeSessionStorage (key)
|
||||||
|
return { key, initial: identity, baseline: initial, value: initial }
|
||||||
|
})
|
||||||
|
}, [available, key, identity])
|
||||||
|
|
||||||
|
useEffect (() => {
|
||||||
|
if (!ready) return
|
||||||
|
const sequence = ++revision.current
|
||||||
|
if (pristine)
|
||||||
|
{
|
||||||
|
removeSessionStorage (key)
|
||||||
|
return
|
||||||
|
}
|
||||||
|
const write = (value: string) => {
|
||||||
|
if (!writeSessionStorage (key, value)) removeSessionStorage (key)
|
||||||
|
}
|
||||||
|
const contents = serialiseDraft (draft)
|
||||||
|
if (typeof contents === 'string')
|
||||||
|
write (contents)
|
||||||
|
else
|
||||||
|
void contents.then (value => {
|
||||||
|
if (revision.current === sequence) write (value)
|
||||||
|
}).catch (() => {
|
||||||
|
// File failures leave the live input and navigation guard intact.
|
||||||
|
})
|
||||||
|
}, [pristine, draft, key, ready])
|
||||||
|
|
||||||
|
const setDraft = useCallback ((value: SetStateAction<T>) => {
|
||||||
|
const source = current.current
|
||||||
|
setEntry (previous => {
|
||||||
|
const present = previous?.key === source.key ? previous.value : source.initial
|
||||||
|
const next =
|
||||||
|
typeof value === 'function'
|
||||||
|
? (value as (current: T) => T) (present)
|
||||||
|
: value
|
||||||
|
return { key: source.key, initial: source.identity,
|
||||||
|
baseline: previous?.key === source.key ? previous.baseline : source.initial,
|
||||||
|
value: next }
|
||||||
|
})
|
||||||
|
}, [])
|
||||||
|
|
||||||
|
const setField = useCallback (<Key extends keyof T,> (
|
||||||
|
field: Key,
|
||||||
|
value: SetStateAction<T[Key]>,
|
||||||
|
) => setDraft (previous => ({ ...previous,
|
||||||
|
[field]:
|
||||||
|
typeof value === 'function'
|
||||||
|
? (value as (current: T[Key]) => T[Key]) (previous[field])
|
||||||
|
: value })), [setDraft])
|
||||||
|
|
||||||
|
const clearDraft = useCallback ((value?: T) => {
|
||||||
|
const source = current.current
|
||||||
|
++revision.current
|
||||||
|
removeSessionStorage (source.key)
|
||||||
|
const present = source.entry?.key === source.key ? source.entry.value : source.initial
|
||||||
|
const next = value ?? present
|
||||||
|
setEntry ({ key: source.key, initial: source.identity, baseline: next, value: next })
|
||||||
|
}, [])
|
||||||
|
|
||||||
|
const discardDraft = useCallback (() => {
|
||||||
|
const source = current.current
|
||||||
|
clearDraft (source.entry?.key === source.key ? source.entry.baseline : source.initial)
|
||||||
|
}, [clearDraft])
|
||||||
|
|
||||||
|
useUnsavedChangesGuard ({ dirty, onDiscard: discardDraft })
|
||||||
|
|
||||||
|
return { draft, setDraft, setField, clearDraft, discardDraft, dirty,
|
||||||
|
ready, allowNextNavigation, confirmNavigation }
|
||||||
|
}
|
||||||
@@ -6,11 +6,14 @@ import { describe, expect, it, vi } from 'vitest'
|
|||||||
import { useUnsavedChangesGuard } from '@/lib/useUnsavedChangesGuard'
|
import { useUnsavedChangesGuard } from '@/lib/useUnsavedChangesGuard'
|
||||||
import { renderWithProviders } from '@/test/render'
|
import { renderWithProviders } from '@/test/render'
|
||||||
|
|
||||||
const GuardHarness = () => {
|
const GuardHarness = ({ onDiscard }: { onDiscard?: () => void }) => {
|
||||||
const [dirty, setDirty] = useState (true)
|
const [dirty, setDirty] = useState (true)
|
||||||
const location = useLocation ()
|
const location = useLocation ()
|
||||||
const navigate = useNavigate ()
|
const navigate = useNavigate ()
|
||||||
const discard = vi.fn (() => setDirty (false))
|
const discard = () => {
|
||||||
|
onDiscard?.()
|
||||||
|
setDirty (false)
|
||||||
|
}
|
||||||
const { allowNextNavigation } = useUnsavedChangesGuard ({
|
const { allowNextNavigation } = useUnsavedChangesGuard ({
|
||||||
dirty,
|
dirty,
|
||||||
onDiscard: discard })
|
onDiscard: discard })
|
||||||
@@ -31,6 +34,18 @@ const GuardHarness = () => {
|
|||||||
}
|
}
|
||||||
|
|
||||||
describe ('useUnsavedChangesGuard', () => {
|
describe ('useUnsavedChangesGuard', () => {
|
||||||
|
it ('uses the current discard callback while dirty state stays unchanged', async () => {
|
||||||
|
const original = vi.fn ()
|
||||||
|
const current = vi.fn ()
|
||||||
|
const view = renderWithProviders (<GuardHarness onDiscard={original}/>)
|
||||||
|
view.rerender (<GuardHarness onDiscard={current}/>)
|
||||||
|
fireEvent.click (screen.getByRole ('button', { name: 'move' }))
|
||||||
|
fireEvent.click (await screen.findByRole ('button', { name: '変更を破棄して移動' }))
|
||||||
|
|
||||||
|
await waitFor (() => expect (current).toHaveBeenCalledTimes (1))
|
||||||
|
expect (original).not.toHaveBeenCalled ()
|
||||||
|
})
|
||||||
|
|
||||||
it ('blocks route changes and resets a cancelled transition', async () => {
|
it ('blocks route changes and resets a cancelled transition', async () => {
|
||||||
renderWithProviders (<GuardHarness/>, { route: '/current' })
|
renderWithProviders (<GuardHarness/>, { route: '/current' })
|
||||||
|
|
||||||
|
|||||||
@@ -23,17 +23,20 @@ type UseUnsavedChangesGuardOptions = {
|
|||||||
onDiscard?: () => void | Promise<void> }
|
onDiscard?: () => void | Promise<void> }
|
||||||
|
|
||||||
type UnsavedChangesGuardContextValue = {
|
type UnsavedChangesGuardContextValue = {
|
||||||
|
draftScope: string
|
||||||
hasUnsavedChanges: boolean
|
hasUnsavedChanges: boolean
|
||||||
registerUnsavedChangesSource: (
|
registerUnsavedChangesSource: (
|
||||||
source: UnsavedChangesSource,
|
source: UnsavedChangesSource,
|
||||||
) => () => void
|
) => () => void
|
||||||
allowNextNavigation: () => void }
|
allowNextNavigation: () => void
|
||||||
|
confirmNavigation: () => Promise<boolean> }
|
||||||
|
|
||||||
const UnsavedChangesGuardContext =
|
const UnsavedChangesGuardContext =
|
||||||
createContext<UnsavedChangesGuardContextValue | null> (null)
|
createContext<UnsavedChangesGuardContextValue | null> (null)
|
||||||
|
|
||||||
|
|
||||||
export const UnsavedChangesGuardProvider: FC<PropsWithChildren> = ({ children }) => {
|
export const UnsavedChangesGuardProvider: FC<PropsWithChildren<{
|
||||||
|
draftScope?: string }>> = ({ children, draftScope = 'anonymous' }) => {
|
||||||
const dialogue = useDialogue ()
|
const dialogue = useDialogue ()
|
||||||
const { label } = useUITranslation ('settings')
|
const { label } = useUITranslation ('settings')
|
||||||
const sourcesRef = useRef (new Map<symbol, UnsavedChangesSource> ())
|
const sourcesRef = useRef (new Map<symbol, UnsavedChangesSource> ())
|
||||||
@@ -117,6 +120,12 @@ export const UnsavedChangesGuardProvider: FC<PropsWithChildren> = ({ children })
|
|||||||
}
|
}
|
||||||
}, [dialogue, hasUnsavedChanges, label])
|
}, [dialogue, hasUnsavedChanges, label])
|
||||||
|
|
||||||
|
const confirmNavigation = useCallback (async (): Promise<boolean> => {
|
||||||
|
if (!(await confirmDiscardChanges ())) return false
|
||||||
|
await Promise.all (dirtySources.map (source => source.discard ()))
|
||||||
|
return true
|
||||||
|
}, [confirmDiscardChanges, dirtySources])
|
||||||
|
|
||||||
useEffect (() => {
|
useEffect (() => {
|
||||||
if (blocker.state !== 'blocked' || handlingBlockedTransitionRef.current)
|
if (blocker.state !== 'blocked' || handlingBlockedTransitionRef.current)
|
||||||
return
|
return
|
||||||
@@ -125,33 +134,24 @@ export const UnsavedChangesGuardProvider: FC<PropsWithChildren> = ({ children })
|
|||||||
void (async () => {
|
void (async () => {
|
||||||
try
|
try
|
||||||
{
|
{
|
||||||
const confirmed = await confirmDiscardChanges ()
|
const confirmed = await confirmNavigation ()
|
||||||
if (!(confirmed))
|
if (!confirmed) {
|
||||||
{
|
|
||||||
blocker.reset ()
|
|
||||||
return
|
|
||||||
}
|
|
||||||
|
|
||||||
let discardResults: Array<void | Promise<void>>
|
|
||||||
try
|
|
||||||
{
|
|
||||||
discardResults = dirtySources.map (source => source.discard ())
|
|
||||||
}
|
|
||||||
catch
|
|
||||||
{
|
|
||||||
blocker.reset ()
|
blocker.reset ()
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
|
|
||||||
blocker.proceed ()
|
blocker.proceed ()
|
||||||
await Promise.allSettled (discardResults)
|
}
|
||||||
|
catch
|
||||||
|
{
|
||||||
|
blocker.reset ()
|
||||||
}
|
}
|
||||||
finally
|
finally
|
||||||
{
|
{
|
||||||
handlingBlockedTransitionRef.current = false
|
handlingBlockedTransitionRef.current = false
|
||||||
}
|
}
|
||||||
}) ()
|
}) ()
|
||||||
}, [blocker, confirmDiscardChanges, dirtySources])
|
}, [blocker, confirmNavigation])
|
||||||
|
|
||||||
useEffect (() => {
|
useEffect (() => {
|
||||||
if (!(hasUnsavedChanges))
|
if (!(hasUnsavedChanges))
|
||||||
@@ -162,21 +162,30 @@ export const UnsavedChangesGuardProvider: FC<PropsWithChildren> = ({ children })
|
|||||||
event.returnValue = ''
|
event.returnValue = ''
|
||||||
}
|
}
|
||||||
|
|
||||||
|
const handlePageHide = () => {
|
||||||
|
for (const source of sourcesRef.current.values ())
|
||||||
|
if (source.dirty) void source.discard ()
|
||||||
|
}
|
||||||
|
|
||||||
window.addEventListener ('beforeunload', handleBeforeUnload)
|
window.addEventListener ('beforeunload', handleBeforeUnload)
|
||||||
|
window.addEventListener ('pagehide', handlePageHide)
|
||||||
return () => {
|
return () => {
|
||||||
window.removeEventListener ('beforeunload', handleBeforeUnload)
|
window.removeEventListener ('beforeunload', handleBeforeUnload)
|
||||||
|
window.removeEventListener ('pagehide', handlePageHide)
|
||||||
}
|
}
|
||||||
}, [hasUnsavedChanges])
|
}, [hasUnsavedChanges])
|
||||||
|
|
||||||
const value = useMemo<UnsavedChangesGuardContextValue> (() => ({
|
const value = useMemo<UnsavedChangesGuardContextValue> (() => ({
|
||||||
|
draftScope,
|
||||||
hasUnsavedChanges,
|
hasUnsavedChanges,
|
||||||
registerUnsavedChangesSource,
|
registerUnsavedChangesSource,
|
||||||
allowNextNavigation,
|
allowNextNavigation,
|
||||||
}), [
|
confirmNavigation }), [
|
||||||
allowNextNavigation,
|
allowNextNavigation,
|
||||||
|
confirmNavigation,
|
||||||
|
draftScope,
|
||||||
hasUnsavedChanges,
|
hasUnsavedChanges,
|
||||||
registerUnsavedChangesSource,
|
registerUnsavedChangesSource])
|
||||||
])
|
|
||||||
|
|
||||||
return (
|
return (
|
||||||
<UnsavedChangesGuardContext.Provider value={value}>
|
<UnsavedChangesGuardContext.Provider value={value}>
|
||||||
@@ -194,15 +203,17 @@ export const useUnsavedChangesGuard = (
|
|||||||
throw new Error ('UnsavedChangesGuardProvider が必要です.')
|
throw new Error ('UnsavedChangesGuardProvider が必要です.')
|
||||||
|
|
||||||
const { registerUnsavedChangesSource } = context
|
const { registerUnsavedChangesSource } = context
|
||||||
|
const source = useRef (options)
|
||||||
|
source.current = options
|
||||||
|
const active = options != null
|
||||||
|
|
||||||
useEffect (() => {
|
useEffect (() => {
|
||||||
if (options == null)
|
if (!active) return
|
||||||
return
|
|
||||||
|
|
||||||
return registerUnsavedChangesSource ({
|
return registerUnsavedChangesSource ({
|
||||||
dirty: options.dirty,
|
dirty: source.current?.dirty ?? false,
|
||||||
discard: options.onDiscard ?? (() => undefined) })
|
discard: () => source.current?.onDiscard?.() })
|
||||||
}, [options?.dirty, options?.onDiscard, registerUnsavedChangesSource])
|
}, [active, options?.dirty, registerUnsavedChangesSource])
|
||||||
|
|
||||||
return context
|
return context
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -2,6 +2,7 @@ import { animate, motion, useMotionTemplate, useMotionValue } from 'framer-motio
|
|||||||
import { useMutation, useQuery, useQueryClient } from '@tanstack/react-query'
|
import { useMutation, useQuery, useQueryClient } from '@tanstack/react-query'
|
||||||
import { useCallback, useEffect, useId, useMemo, useRef, useState } from 'react'
|
import { useCallback, useEffect, useId, useMemo, useRef, useState } from 'react'
|
||||||
|
|
||||||
|
import { useUnsavedChangesGuard } from '@/lib/useUnsavedChangesGuard'
|
||||||
import { useLocale } from '@/lib/useLocale'
|
import { useLocale } from '@/lib/useLocale'
|
||||||
import PrefetchLink from '@/components/PrefetchLink'
|
import PrefetchLink from '@/components/PrefetchLink'
|
||||||
import MainArea from '@/components/layout/MainArea'
|
import MainArea from '@/components/layout/MainArea'
|
||||||
@@ -4190,6 +4191,14 @@ const GekanatorPage: FC<{ user: User | null }> = ({ user }) => {
|
|||||||
setHistory ([])
|
setHistory ([])
|
||||||
}
|
}
|
||||||
|
|
||||||
|
useUnsavedChangesGuard ({
|
||||||
|
dirty: !restorePromptVisible && (
|
||||||
|
(!saved && answers.length > 0)
|
||||||
|
|| questionSuggestion.trim () !== ''
|
||||||
|
|| questionSuggestionSelectedId != null
|
||||||
|
|| (extraQuestionState !== 'saved' && Object.keys (extraQuestionAnswers).length > 0)),
|
||||||
|
onDiscard: reset })
|
||||||
|
|
||||||
const continueStoredGame = () => {
|
const continueStoredGame = () => {
|
||||||
setRestorePromptVisible (false)
|
setRestorePromptVisible (false)
|
||||||
setPhase (storedGame?.phase ?? 'question')
|
setPhase (storedGame?.phase ?? 'question')
|
||||||
|
|||||||
@@ -2,6 +2,7 @@ import { useQuery, useQueryClient } from '@tanstack/react-query'
|
|||||||
import { useEffect, useMemo, useState } from 'react'
|
import { useEffect, useMemo, useState } from 'react'
|
||||||
import { useParams } from 'react-router-dom'
|
import { useParams } from 'react-router-dom'
|
||||||
|
|
||||||
|
import { useSessionDraft } from '@/lib/useSessionDraft'
|
||||||
import { useLocale } from '@/lib/useLocale'
|
import { useLocale } from '@/lib/useLocale'
|
||||||
import { useUITranslation } from '@/lib/useUITranslation'
|
import { useUITranslation } from '@/lib/useUITranslation'
|
||||||
import TagLink from '@/components/TagLink'
|
import TagLink from '@/components/TagLink'
|
||||||
@@ -38,8 +39,9 @@ const DeerjikistDetailPage: FC = () => {
|
|||||||
const tag = qData?.tag
|
const tag = qData?.tag
|
||||||
const deerjikists = useMemo (() => qData?.deerjikists ?? [], [qData])
|
const deerjikists = useMemo (() => qData?.deerjikists ?? [], [qData])
|
||||||
|
|
||||||
const [data, setData] =
|
const { draft: data, setDraft: setData, clearDraft } = useSessionDraft<
|
||||||
useState<(Omit<Deerjikist, 'platform'> & { platform: Platform | null })[]> (deerjikists)
|
(Omit<Deerjikist, 'platform'> & { platform: Platform | null })[]> (
|
||||||
|
`deerjikists:${tagId}:${locale}`, deerjikists, tag != null)
|
||||||
const [disabled, setDisabled] = useState (tag == null)
|
const [disabled, setDisabled] = useState (tag == null)
|
||||||
const { baseErrors, fieldErrors, clearValidationErrors, applyValidationError } =
|
const { baseErrors, fieldErrors, clearValidationErrors, applyValidationError } =
|
||||||
useValidationErrors<DeerjikistFormField> ()
|
useValidationErrors<DeerjikistFormField> ()
|
||||||
@@ -54,7 +56,7 @@ const DeerjikistDetailPage: FC = () => {
|
|||||||
{
|
{
|
||||||
setDisabled (true)
|
setDisabled (true)
|
||||||
|
|
||||||
setData (await apiPut<Deerjikist[]> (`/tags/${ id }/deerjikists`, data, { locale }))
|
clearDraft (await apiPut<Deerjikist[]> (`/tags/${ id }/deerjikists`, data, { locale }))
|
||||||
qc.invalidateQueries ({ queryKey: tagsKeys.root })
|
qc.invalidateQueries ({ queryKey: tagsKeys.root })
|
||||||
|
|
||||||
toast ({ description: label ('messages.updated') })
|
toast ({ description: label ('messages.updated') })
|
||||||
@@ -78,7 +80,6 @@ const DeerjikistDetailPage: FC = () => {
|
|||||||
return
|
return
|
||||||
}
|
}
|
||||||
|
|
||||||
setData (deerjikists)
|
|
||||||
setDisabled (false)
|
setDisabled (false)
|
||||||
}, [tag, deerjikists])
|
}, [tag, deerjikists])
|
||||||
|
|
||||||
|
|||||||
@@ -2,6 +2,7 @@ import { useMutation, useQuery, useQueryClient } from '@tanstack/react-query'
|
|||||||
import { useEffect, useState } from 'react'
|
import { useEffect, useState } from 'react'
|
||||||
import { useParams } from 'react-router-dom'
|
import { useParams } from 'react-router-dom'
|
||||||
|
|
||||||
|
import { useSessionDraft } from '@/lib/useSessionDraft'
|
||||||
import { useLocale } from '@/lib/useLocale'
|
import { useLocale } from '@/lib/useLocale'
|
||||||
import TagLink from '@/components/TagLink'
|
import TagLink from '@/components/TagLink'
|
||||||
import WikiBody from '@/components/WikiBody'
|
import WikiBody from '@/components/WikiBody'
|
||||||
@@ -40,12 +41,23 @@ const MaterialDetailPage: FC = () => {
|
|||||||
queryFn: () => fetchMaterial (id ?? '', locale),
|
queryFn: () => fetchMaterial (id ?? '', locale),
|
||||||
enabled: id != null })
|
enabled: id != null })
|
||||||
|
|
||||||
const [exportPath, setExportPath] = useState (material?.exportPaths.legacyDrive ?? '')
|
const { draft, setField, clearDraft, confirmNavigation } =
|
||||||
const [file, setFile] = useState<File | null> (null)
|
useSessionDraft (`material:${id}:${locale}`, {
|
||||||
const [filePreview, setFilePreview] = useState (
|
tag: material?.tag?.name ?? '', url: material?.url ?? '',
|
||||||
material?.contentType != null ? material.file ?? '' : '')
|
exportPath: material?.exportPaths.legacyDrive ?? '', file: null as File | null },
|
||||||
const [tag, setTag] = useState (material?.tag?.name ?? '')
|
material != null)
|
||||||
const [url, setURL] = useState (material?.url ?? '')
|
const { tag, url, exportPath, file } = draft
|
||||||
|
const [filePreview, setFilePreview] = useState ('')
|
||||||
|
useEffect (() => {
|
||||||
|
const preview =
|
||||||
|
file == null
|
||||||
|
? (material?.contentType != null ? material.file ?? '' : '')
|
||||||
|
: URL.createObjectURL (file)
|
||||||
|
setFilePreview (preview)
|
||||||
|
return () => {
|
||||||
|
if (file != null) URL.revokeObjectURL (preview)
|
||||||
|
}
|
||||||
|
}, [file, material?.contentType, material?.file])
|
||||||
const { baseErrors, fieldErrors, clearValidationErrors, applyValidationError } =
|
const { baseErrors, fieldErrors, clearValidationErrors, applyValidationError } =
|
||||||
useValidationErrors<MaterialFormField> ()
|
useValidationErrors<MaterialFormField> ()
|
||||||
|
|
||||||
@@ -53,20 +65,6 @@ const MaterialDetailPage: FC = () => {
|
|||||||
? material.tag?.name ?? message ('unnamed', { id: material.id }).text
|
? material.tag?.name ?? message ('unnamed', { id: material.id }).text
|
||||||
: ''
|
: ''
|
||||||
|
|
||||||
useEffect (() => {
|
|
||||||
if (!(material))
|
|
||||||
return
|
|
||||||
|
|
||||||
setTag (material.tag?.name ?? '')
|
|
||||||
setURL (material.url ?? '')
|
|
||||||
setExportPath (material.exportPaths.legacyDrive ?? '')
|
|
||||||
if (material.file && material.contentType)
|
|
||||||
{
|
|
||||||
setFilePreview (material.file)
|
|
||||||
setFile (null)
|
|
||||||
}
|
|
||||||
}, [material])
|
|
||||||
|
|
||||||
const invalidateMaterialQueries = async () => {
|
const invalidateMaterialQueries = async () => {
|
||||||
await qc.invalidateQueries ({ queryKey: materialsKeys.root })
|
await qc.invalidateQueries ({ queryKey: materialsKeys.root })
|
||||||
}
|
}
|
||||||
@@ -85,6 +83,8 @@ const MaterialDetailPage: FC = () => {
|
|||||||
return await updateMaterial (id ?? '', formData, locale)
|
return await updateMaterial (id ?? '', formData, locale)
|
||||||
},
|
},
|
||||||
onSuccess: async data => {
|
onSuccess: async data => {
|
||||||
|
clearDraft ({ tag: data.tag?.name ?? '', url: data.url ?? '',
|
||||||
|
exportPath: data.exportPaths.legacyDrive ?? '', file: null })
|
||||||
qc.setQueryData (materialsKeys.show (id ?? '', locale), data)
|
qc.setQueryData (materialsKeys.show (id ?? '', locale), data)
|
||||||
await invalidateMaterialQueries ()
|
await invalidateMaterialQueries ()
|
||||||
toast ({ title: label ('updated') })
|
toast ({ title: label ('updated') })
|
||||||
@@ -133,7 +133,7 @@ const MaterialDetailPage: FC = () => {
|
|||||||
|| (/audio\/.*/.test (material.contentType) && (
|
|| (/audio\/.*/.test (material.contentType) && (
|
||||||
<audio src={material.file} controls/>)))}
|
<audio src={material.file} controls/>)))}
|
||||||
|
|
||||||
<TabGroup>
|
<TabGroup onBeforeChange={confirmNavigation}>
|
||||||
{material.tag && (
|
{material.tag && (
|
||||||
<Tab name={label ('navigation:wiki')}>
|
<Tab name={label ('navigation:wiki')}>
|
||||||
<WikiBody
|
<WikiBody
|
||||||
@@ -152,7 +152,7 @@ const MaterialDetailPage: FC = () => {
|
|||||||
describedBy={describedBy}
|
describedBy={describedBy}
|
||||||
invalid={invalid}
|
invalid={invalid}
|
||||||
value={tag}
|
value={tag}
|
||||||
setValue={setTag}/>)}
|
setValue={value => setField ('tag', value)}/>)}
|
||||||
</FormField>
|
</FormField>
|
||||||
|
|
||||||
<FormField label={label ('file')} messages={fieldErrors.file}>
|
<FormField label={label ('file')} messages={fieldErrors.file}>
|
||||||
@@ -165,9 +165,7 @@ const MaterialDetailPage: FC = () => {
|
|||||||
aria-invalid={invalid}
|
aria-invalid={invalid}
|
||||||
onChange={e => {
|
onChange={e => {
|
||||||
const nextFile = e.target.files?.[0]
|
const nextFile = e.target.files?.[0]
|
||||||
setFile (nextFile ?? null)
|
setField ('file', nextFile ?? null)
|
||||||
setFilePreview (
|
|
||||||
nextFile ? URL.createObjectURL (nextFile) : '')
|
|
||||||
}}/>
|
}}/>
|
||||||
{(file && filePreview) && (
|
{(file && filePreview) && (
|
||||||
(/image\/.*/.test (file.type) && (
|
(/image\/.*/.test (file.type) && (
|
||||||
@@ -198,7 +196,7 @@ const MaterialDetailPage: FC = () => {
|
|||||||
<input
|
<input
|
||||||
type="url"
|
type="url"
|
||||||
value={url}
|
value={url}
|
||||||
onChange={e => setURL (e.target.value)}
|
onChange={e => setField ('url', e.target.value)}
|
||||||
aria-describedby={describedBy}
|
aria-describedby={describedBy}
|
||||||
aria-invalid={invalid}
|
aria-invalid={invalid}
|
||||||
className={inputClass (invalid)}/>)}
|
className={inputClass (invalid)}/>)}
|
||||||
@@ -209,7 +207,7 @@ const MaterialDetailPage: FC = () => {
|
|||||||
<input
|
<input
|
||||||
type="text"
|
type="text"
|
||||||
value={exportPath}
|
value={exportPath}
|
||||||
onChange={e => setExportPath (e.target.value)}
|
onChange={e => setField ('exportPath', e.target.value)}
|
||||||
placeholder={message ('exportPlaceholder').text}
|
placeholder={message ('exportPlaceholder').text}
|
||||||
lang={message ('exportPlaceholder').language}
|
lang={message ('exportPlaceholder').language}
|
||||||
aria-describedby={describedBy}
|
aria-describedby={describedBy}
|
||||||
|
|||||||
@@ -1,7 +1,8 @@
|
|||||||
import { useMutation, useQueryClient } from '@tanstack/react-query'
|
import { useMutation, useQueryClient } from '@tanstack/react-query'
|
||||||
import { useState } from 'react'
|
import { useEffect, useState } from 'react'
|
||||||
import { useLocation } from 'react-router-dom'
|
import { useLocation } from 'react-router-dom'
|
||||||
|
|
||||||
|
import { useSessionDraft } from '@/lib/useSessionDraft'
|
||||||
import { useLocale, useLocaleNavigate } from '@/lib/useLocale'
|
import { useLocale, useLocaleNavigate } from '@/lib/useLocale'
|
||||||
import FieldError from '@/components/common/FieldError'
|
import FieldError from '@/components/common/FieldError'
|
||||||
import Form from '@/components/common/Form'
|
import Form from '@/components/common/Form'
|
||||||
@@ -37,11 +38,18 @@ const MaterialNewPage: FC = () => {
|
|||||||
|
|
||||||
const navigate = useLocaleNavigate ()
|
const navigate = useLocaleNavigate ()
|
||||||
|
|
||||||
const [file, setFile] = useState<File | null> (null)
|
const { draft, setField, clearDraft, allowNextNavigation } =
|
||||||
|
useSessionDraft (`material:new:${locale}`, {
|
||||||
|
tag: tagQuery, url: '', exportPath: '', file: null as File | null })
|
||||||
|
const { tag, url, exportPath, file } = draft
|
||||||
const [filePreview, setFilePreview] = useState ('')
|
const [filePreview, setFilePreview] = useState ('')
|
||||||
const [tag, setTag] = useState (tagQuery)
|
useEffect (() => {
|
||||||
const [url, setURL] = useState ('')
|
const preview = file == null ? '' : URL.createObjectURL (file)
|
||||||
const [exportPath, setExportPath] = useState ('')
|
setFilePreview (preview)
|
||||||
|
return () => {
|
||||||
|
if (file != null) URL.revokeObjectURL (preview)
|
||||||
|
}
|
||||||
|
}, [file])
|
||||||
const { baseErrors, fieldErrors, clearValidationErrors, applyValidationError } =
|
const { baseErrors, fieldErrors, clearValidationErrors, applyValidationError } =
|
||||||
useValidationErrors<MaterialFormField> ()
|
useValidationErrors<MaterialFormField> ()
|
||||||
|
|
||||||
@@ -59,8 +67,10 @@ const MaterialNewPage: FC = () => {
|
|||||||
return await createMaterial (formData, locale)
|
return await createMaterial (formData, locale)
|
||||||
},
|
},
|
||||||
onSuccess: async () => {
|
onSuccess: async () => {
|
||||||
|
clearDraft ()
|
||||||
await qc.invalidateQueries ({ queryKey: materialsKeys.root })
|
await qc.invalidateQueries ({ queryKey: materialsKeys.root })
|
||||||
toast ({ title: label ('sent') })
|
toast ({ title: label ('sent') })
|
||||||
|
allowNextNavigation ()
|
||||||
navigate (safeReturnTo || '/materials')
|
navigate (safeReturnTo || '/materials')
|
||||||
},
|
},
|
||||||
onError: error => {
|
onError: error => {
|
||||||
@@ -88,7 +98,7 @@ const MaterialNewPage: FC = () => {
|
|||||||
describedBy={describedBy}
|
describedBy={describedBy}
|
||||||
invalid={invalid}
|
invalid={invalid}
|
||||||
value={tag}
|
value={tag}
|
||||||
setValue={setTag}/>)}
|
setValue={value => setField ('tag', value)}/>)}
|
||||||
</FormField>
|
</FormField>
|
||||||
|
|
||||||
{/* ファイル */}
|
{/* ファイル */}
|
||||||
@@ -102,8 +112,7 @@ const MaterialNewPage: FC = () => {
|
|||||||
aria-invalid={invalid}
|
aria-invalid={invalid}
|
||||||
onChange={e => {
|
onChange={e => {
|
||||||
const f = e.target.files?.[0]
|
const f = e.target.files?.[0]
|
||||||
setFile (f ?? null)
|
setField ('file', f ?? null)
|
||||||
setFilePreview (f ? URL.createObjectURL (f) : '')
|
|
||||||
}}/>
|
}}/>
|
||||||
{(file && filePreview) && (
|
{(file && filePreview) && (
|
||||||
(/image\/.*/.test (file.type) && (
|
(/image\/.*/.test (file.type) && (
|
||||||
@@ -135,7 +144,7 @@ const MaterialNewPage: FC = () => {
|
|||||||
<input
|
<input
|
||||||
type="url"
|
type="url"
|
||||||
value={url}
|
value={url}
|
||||||
onChange={e => setURL (e.target.value)}
|
onChange={e => setField ('url', e.target.value)}
|
||||||
aria-describedby={describedBy}
|
aria-describedby={describedBy}
|
||||||
aria-invalid={invalid}
|
aria-invalid={invalid}
|
||||||
className={inputClass (invalid)}/>)}
|
className={inputClass (invalid)}/>)}
|
||||||
@@ -148,7 +157,7 @@ const MaterialNewPage: FC = () => {
|
|||||||
<input
|
<input
|
||||||
type="text"
|
type="text"
|
||||||
value={exportPath}
|
value={exportPath}
|
||||||
onChange={e => setExportPath (e.target.value)}
|
onChange={e => setField ('exportPath', e.target.value)}
|
||||||
placeholder={message ('exportPlaceholder').text}
|
placeholder={message ('exportPlaceholder').text}
|
||||||
lang={message ('exportPlaceholder').language}
|
lang={message ('exportPlaceholder').language}
|
||||||
aria-describedby={describedBy}
|
aria-describedby={describedBy}
|
||||||
|
|||||||
@@ -1,6 +1,6 @@
|
|||||||
import { useMutation, useQuery, useQueryClient } from '@tanstack/react-query'
|
import { useMutation, useQuery, useQueryClient } from '@tanstack/react-query'
|
||||||
import { useState } from 'react'
|
|
||||||
|
|
||||||
|
import { useSessionDraft } from '@/lib/useSessionDraft'
|
||||||
import { useLocale } from '@/lib/useLocale'
|
import { useLocale } from '@/lib/useLocale'
|
||||||
import FormField from '@/components/common/FormField'
|
import FormField from '@/components/common/FormField'
|
||||||
import PageTitle from '@/components/common/PageTitle'
|
import PageTitle from '@/components/common/PageTitle'
|
||||||
@@ -41,12 +41,11 @@ const MaterialSyncSuppressionsPage: FC = () => {
|
|||||||
const locale = useLocale ()
|
const locale = useLocale ()
|
||||||
const { message, label } = useUITranslation ('materials')
|
const { message, label } = useUITranslation ('materials')
|
||||||
const qc = useQueryClient ()
|
const qc = useQueryClient ()
|
||||||
const [sourceKind, setSourceKind] =
|
const { draft, setField, clearDraft } = useSessionDraft (`material-suppressions:${locale}`, {
|
||||||
useState<MaterialSyncSuppressionSourceKind> ('uri')
|
sourceKind: 'uri' as MaterialSyncSuppressionSourceKind,
|
||||||
const [sourceUri, setSourceUri] = useState ('')
|
sourceUri: '', drivePath: '', driveFileId: '',
|
||||||
const [drivePath, setDrivePath] = useState ('')
|
reason: REASONS[0] as MaterialSyncSuppressionReason })
|
||||||
const [driveFileId, setDriveFileId] = useState ('')
|
const { sourceKind, sourceUri, drivePath, driveFileId, reason } = draft
|
||||||
const [reason, setReason] = useState<MaterialSyncSuppressionReason> (REASONS[0])
|
|
||||||
|
|
||||||
const { data, isError, isLoading } = useQuery ({
|
const { data, isError, isLoading } = useQuery ({
|
||||||
queryKey: materialsKeys.suppressions (locale),
|
queryKey: materialsKeys.suppressions (locale),
|
||||||
@@ -63,9 +62,7 @@ const MaterialSyncSuppressionsPage: FC = () => {
|
|||||||
onSuccess: async () => {
|
onSuccess: async () => {
|
||||||
await qc.invalidateQueries ({ queryKey: materialsKeys.suppressions (locale) })
|
await qc.invalidateQueries ({ queryKey: materialsKeys.suppressions (locale) })
|
||||||
await qc.invalidateQueries ({ queryKey: materialsKeys.root })
|
await qc.invalidateQueries ({ queryKey: materialsKeys.root })
|
||||||
setSourceUri ('')
|
clearDraft ({ ...draft, sourceUri: '', drivePath: '', driveFileId: '' })
|
||||||
setDrivePath ('')
|
|
||||||
setDriveFileId ('')
|
|
||||||
toast ({ title: label ('suppressions.registered') })
|
toast ({ title: label ('suppressions.registered') })
|
||||||
},
|
},
|
||||||
onError: () => {
|
onError: () => {
|
||||||
@@ -96,7 +93,7 @@ const MaterialSyncSuppressionsPage: FC = () => {
|
|||||||
{({ invalid }) => (
|
{({ invalid }) => (
|
||||||
<select
|
<select
|
||||||
value={sourceKind}
|
value={sourceKind}
|
||||||
onChange={e => setSourceKind (
|
onChange={e => setField ('sourceKind',
|
||||||
e.target.value as MaterialSyncSuppressionSourceKind)}
|
e.target.value as MaterialSyncSuppressionSourceKind)}
|
||||||
className={inputClass (invalid)}>
|
className={inputClass (invalid)}>
|
||||||
{Object.entries (SOURCE_KIND_LABELS).map (([value, key]) => (
|
{Object.entries (SOURCE_KIND_LABELS).map (([value, key]) => (
|
||||||
@@ -111,7 +108,7 @@ const MaterialSyncSuppressionsPage: FC = () => {
|
|||||||
<input
|
<input
|
||||||
type="text"
|
type="text"
|
||||||
value={sourceUri}
|
value={sourceUri}
|
||||||
onChange={e => setSourceUri (e.target.value)}
|
onChange={e => setField ('sourceUri', e.target.value)}
|
||||||
className={inputClass (invalid)}/>)}
|
className={inputClass (invalid)}/>)}
|
||||||
</FormField>
|
</FormField>
|
||||||
|
|
||||||
@@ -120,7 +117,7 @@ const MaterialSyncSuppressionsPage: FC = () => {
|
|||||||
<input
|
<input
|
||||||
type="text"
|
type="text"
|
||||||
value={drivePath}
|
value={drivePath}
|
||||||
onChange={e => setDrivePath (e.target.value)}
|
onChange={e => setField ('drivePath', e.target.value)}
|
||||||
className={inputClass (invalid)}/>)}
|
className={inputClass (invalid)}/>)}
|
||||||
</FormField>
|
</FormField>
|
||||||
|
|
||||||
@@ -129,7 +126,7 @@ const MaterialSyncSuppressionsPage: FC = () => {
|
|||||||
<input
|
<input
|
||||||
type="text"
|
type="text"
|
||||||
value={driveFileId}
|
value={driveFileId}
|
||||||
onChange={e => setDriveFileId (e.target.value)}
|
onChange={e => setField ('driveFileId', e.target.value)}
|
||||||
className={inputClass (invalid)}/>)}
|
className={inputClass (invalid)}/>)}
|
||||||
</FormField>
|
</FormField>
|
||||||
|
|
||||||
@@ -137,7 +134,7 @@ const MaterialSyncSuppressionsPage: FC = () => {
|
|||||||
{({ invalid }) => (
|
{({ invalid }) => (
|
||||||
<select
|
<select
|
||||||
value={reason}
|
value={reason}
|
||||||
onChange={e => setReason (e.target.value as MaterialSyncSuppressionReason)}
|
onChange={e => setField ('reason', e.target.value as MaterialSyncSuppressionReason)}
|
||||||
className={inputClass (invalid)}>
|
className={inputClass (invalid)}>
|
||||||
{REASONS.map (value => (
|
{REASONS.map (value => (
|
||||||
<option key={value} value={value}
|
<option key={value} value={value}
|
||||||
|
|||||||
@@ -2,6 +2,8 @@ import { useMutation, useQuery, useQueryClient } from '@tanstack/react-query'
|
|||||||
import { motion } from 'framer-motion'
|
import { motion } from 'framer-motion'
|
||||||
import { useEffect, useRef } from 'react'
|
import { useEffect, useRef } from 'react'
|
||||||
import { useParams } from 'react-router-dom'
|
import { useParams } from 'react-router-dom'
|
||||||
|
|
||||||
|
import { useUnsavedChangesGuard } from '@/lib/useUnsavedChangesGuard'
|
||||||
import { useLocale } from '@/lib/useLocale'
|
import { useLocale } from '@/lib/useLocale'
|
||||||
import PostEditForm from '@/components/PostEditForm'
|
import PostEditForm from '@/components/PostEditForm'
|
||||||
import PostEmbed from '@/components/PostEmbed'
|
import PostEmbed from '@/components/PostEmbed'
|
||||||
@@ -33,6 +35,7 @@ const PostDetailPage: FC<Props> = ({ user }) => {
|
|||||||
const locale = useLocale ()
|
const locale = useLocale ()
|
||||||
const { message, label } = useUITranslation ('posts')
|
const { message, label } = useUITranslation ('posts')
|
||||||
const editable = canEditContent (user)
|
const editable = canEditContent (user)
|
||||||
|
const { confirmNavigation } = useUnsavedChangesGuard ()
|
||||||
const behaviourSettings = useClientBehaviourSettings ()
|
const behaviourSettings = useClientBehaviourSettings ()
|
||||||
const thumbnailMode = behaviourSettings.thumbnailMode ?? 'normal'
|
const thumbnailMode = behaviourSettings.thumbnailMode ?? 'normal'
|
||||||
const animationMode = behaviourSettings.animation ?? 'normal'
|
const animationMode = behaviourSettings.animation ?? 'normal'
|
||||||
@@ -163,7 +166,7 @@ const PostDetailPage: FC<Props> = ({ user }) => {
|
|||||||
className={cn ('text-white', viewedClass)}>
|
className={cn ('text-white', viewedClass)}>
|
||||||
{label (post.viewed ? 'detail.viewed' : 'detail.unviewed')}
|
{label (post.viewed ? 'detail.viewed' : 'detail.unviewed')}
|
||||||
</Button>
|
</Button>
|
||||||
<TabGroup>
|
<TabGroup onBeforeChange={confirmNavigation}>
|
||||||
<Tab name={label ('shared:labels.relations')}>
|
<Tab name={label ('shared:labels.relations')}>
|
||||||
{post.related.length > 0
|
{post.related.length > 0
|
||||||
? <PostList posts={post.related}/>
|
? <PostList posts={post.related}/>
|
||||||
|
|||||||
@@ -42,13 +42,14 @@ import {
|
|||||||
} from '@/lib/postImportRows'
|
} from '@/lib/postImportRows'
|
||||||
import { clearPostImportSourceDraft } from '@/lib/postImportStorage'
|
import { clearPostImportSourceDraft } from '@/lib/postImportStorage'
|
||||||
import { useClientBehaviourSettings } from '@/lib/useClientBehaviourSettings'
|
import { useClientBehaviourSettings } from '@/lib/useClientBehaviourSettings'
|
||||||
import { useUnsavedChangesGuard } from '@/lib/useUnsavedChangesGuard'
|
import { useSessionDraft } from '@/lib/useSessionDraft'
|
||||||
import { cn } from '@/lib/utils'
|
import { cn } from '@/lib/utils'
|
||||||
import { canEditContent } from '@/lib/users'
|
import { canEditContent } from '@/lib/users'
|
||||||
import Forbidden from '@/pages/Forbidden'
|
import Forbidden from '@/pages/Forbidden'
|
||||||
|
|
||||||
import type { FC } from 'react'
|
import type { FC } from 'react'
|
||||||
|
|
||||||
|
import type { DialogueFormControls } from '@/lib/dialogues/useDialogue'
|
||||||
import type {
|
import type {
|
||||||
PostImportDisplayTag,
|
PostImportDisplayTag,
|
||||||
PostImportEditableDraft,
|
PostImportEditableDraft,
|
||||||
@@ -578,26 +579,6 @@ const ExistingSkippedRows: FC<ExistingSkippedRowsProps> = ({ id, rows }) => {
|
|||||||
}
|
}
|
||||||
|
|
||||||
|
|
||||||
const editableRowDirty = (row: PostImportRow): boolean =>
|
|
||||||
row.skipReason === 'manual'
|
|
||||||
|| row.url !== row.resetSnapshot.url
|
|
||||||
|| String (row.attributes.title ?? '')
|
|
||||||
!== String (row.resetSnapshot.attributes.title ?? '')
|
|
||||||
|| String (row.attributes.thumbnailBase ?? '')
|
|
||||||
!== String (row.resetSnapshot.attributes.thumbnailBase ?? '')
|
|
||||||
|| String (row.attributes.originalCreatedFrom ?? '')
|
|
||||||
!== String (row.resetSnapshot.attributes.originalCreatedFrom ?? '')
|
|
||||||
|| String (row.attributes.originalCreatedBefore ?? '')
|
|
||||||
!== String (row.resetSnapshot.attributes.originalCreatedBefore ?? '')
|
|
||||||
|| String (row.attributes.duration ?? '')
|
|
||||||
!== String (row.resetSnapshot.attributes.duration ?? '')
|
|
||||||
|| String (row.attributes.tags ?? '')
|
|
||||||
!== String (row.resetSnapshot.attributes.tags ?? '')
|
|
||||||
|| String (row.attributes.parentPostIds ?? '')
|
|
||||||
!== String (row.resetSnapshot.attributes.parentPostIds ?? '')
|
|
||||||
|| row.thumbnailFile != null
|
|
||||||
|
|
||||||
|
|
||||||
const PostImportReviewPage: FC<Props> = ({ user }) => {
|
const PostImportReviewPage: FC<Props> = ({ user }) => {
|
||||||
const locale = useLocale ()
|
const locale = useLocale ()
|
||||||
const { message, label } = useUITranslation ('imports')
|
const { message, label } = useUITranslation ('imports')
|
||||||
@@ -614,8 +595,13 @@ const PostImportReviewPage: FC<Props> = ({ user }) => {
|
|||||||
? { duration: .08, ease: 'linear' as const }
|
? { duration: .08, ease: 'linear' as const }
|
||||||
: { duration: .2, ease: 'easeOut' as const }
|
: { duration: .2, ease: 'easeOut' as const }
|
||||||
|
|
||||||
const [rows, setRows] = useState<PostImportRow[] | null> (
|
const { draft: rows, setDraft: setRows, clearDraft, allowNextNavigation, ready } =
|
||||||
() => buildInitialRows (parsePostNewReviewUrls (location.search)))
|
useSessionDraft (`post-import:review:${location.search}`,
|
||||||
|
buildInitialRows (parsePostNewReviewUrls (location.search)), editable,
|
||||||
|
value => value.some (row => row.importStatus !== 'created'
|
||||||
|
&& row.skipReason !== 'existing'))
|
||||||
|
const { clearDraft: clearSourceDraft } =
|
||||||
|
useSessionDraft ('post-import:source', '', editable)
|
||||||
const [metadataLoading, setMetadataLoading] = useState (false)
|
const [metadataLoading, setMetadataLoading] = useState (false)
|
||||||
const [submitting, setSubmitting] = useState (false)
|
const [submitting, setSubmitting] = useState (false)
|
||||||
const [busyRowIds, setBusyRowIds] = useState<Set<number>> (new Set ())
|
const [busyRowIds, setBusyRowIds] = useState<Set<number>> (new Set ())
|
||||||
@@ -623,22 +609,13 @@ const PostImportReviewPage: FC<Props> = ({ user }) => {
|
|||||||
const [showExistingRows, setShowExistingRows] = useState (false)
|
const [showExistingRows, setShowExistingRows] = useState (false)
|
||||||
const rowsRef = useRef<PostImportRow[]> ([])
|
const rowsRef = useRef<PostImportRow[]> ([])
|
||||||
const metadataSequenceRef = useRef (0)
|
const metadataSequenceRef = useRef (0)
|
||||||
const discardChanges = useCallback (() => undefined, [])
|
rowsRef.current = rows
|
||||||
|
|
||||||
const dirty = useMemo (
|
|
||||||
() => rows?.some (row => editableRowDirty (row)) ?? false,
|
|
||||||
[rows],
|
|
||||||
)
|
|
||||||
const { allowNextNavigation } = useUnsavedChangesGuard ({
|
|
||||||
dirty,
|
|
||||||
onDiscard: discardChanges,
|
|
||||||
})
|
|
||||||
|
|
||||||
const commitRows = useCallback ((nextRows: PostImportRow[]) => {
|
const commitRows = useCallback ((nextRows: PostImportRow[]) => {
|
||||||
rowsRef.current = nextRows
|
rowsRef.current = nextRows
|
||||||
setRows (nextRows)
|
setRows (nextRows)
|
||||||
return nextRows
|
return nextRows
|
||||||
}, [])
|
}, [setRows])
|
||||||
|
|
||||||
const updateRows = useCallback ((
|
const updateRows = useCallback ((
|
||||||
updater: (currentRows: PostImportRow[]) => PostImportRow[],
|
updater: (currentRows: PostImportRow[]) => PostImportRow[],
|
||||||
@@ -654,17 +631,18 @@ const PostImportReviewPage: FC<Props> = ({ user }) => {
|
|||||||
[])
|
[])
|
||||||
|
|
||||||
const finishImport = useCallback (() => {
|
const finishImport = useCallback (() => {
|
||||||
allowNextNavigation ()
|
clearDraft ()
|
||||||
|
clearSourceDraft ('')
|
||||||
clearPostImportSourceDraft (message =>
|
clearPostImportSourceDraft (message =>
|
||||||
toast ({ title: label ('review.clearFailed'),
|
toast ({ title: label ('review.clearFailed'),
|
||||||
description: renderPostImportMessage (message, locale) }))
|
description: renderPostImportMessage (message, locale) }))
|
||||||
|
allowNextNavigation ()
|
||||||
navigate ('/posts')
|
navigate ('/posts')
|
||||||
}, [allowNextNavigation, navigate, label, locale])
|
}, [allowNextNavigation, clearDraft, clearSourceDraft, navigate, label, locale])
|
||||||
|
|
||||||
useEffect (() => {
|
useEffect (() => {
|
||||||
const urls = parsePostNewReviewUrls (location.search)
|
if (!ready) return
|
||||||
const initialRows = buildInitialRows (urls)
|
const initialRows = rowsRef.current
|
||||||
commitRows (initialRows)
|
|
||||||
|
|
||||||
let active = true
|
let active = true
|
||||||
const sequence = ++metadataSequenceRef.current
|
const sequence = ++metadataSequenceRef.current
|
||||||
@@ -778,7 +756,7 @@ const PostImportReviewPage: FC<Props> = ({ user }) => {
|
|||||||
active = false
|
active = false
|
||||||
controllers.forEach (controller => controller.abort ())
|
controllers.forEach (controller => controller.abort ())
|
||||||
}
|
}
|
||||||
}, [commitRows, currentRowBySource, location.search, updateRows, locale])
|
}, [currentRowBySource, location.search, updateRows, locale, ready])
|
||||||
|
|
||||||
useEffect (() => {
|
useEffect (() => {
|
||||||
if (editingRow == null || resultRepairMode (rowsRef.current) !== 'failed')
|
if (editingRow == null || resultRepairMode (rowsRef.current) !== 'failed')
|
||||||
@@ -924,6 +902,9 @@ const PostImportReviewPage: FC<Props> = ({ user }) => {
|
|||||||
}
|
}
|
||||||
|
|
||||||
const openEditingDialogue = async (row: PostImportRow) => {
|
const openEditingDialogue = async (row: PostImportRow) => {
|
||||||
|
const draftState = { dirty: false, discard: () => { },
|
||||||
|
confirm: null as null | DialogueFormControls['confirm'] }
|
||||||
|
|
||||||
const saveRowDraft = (
|
const saveRowDraft = (
|
||||||
{ draft, resetRequested }: {
|
{ draft, resetRequested }: {
|
||||||
draft: PostImportEditableDraft
|
draft: PostImportEditableDraft
|
||||||
@@ -934,12 +915,23 @@ const PostImportReviewPage: FC<Props> = ({ user }) => {
|
|||||||
await dialogue.form ({
|
await dialogue.form ({
|
||||||
title: label ('review.editPost'),
|
title: label ('review.editPost'),
|
||||||
cancelText: label ('shared:actions.cancel'),
|
cancelText: label ('shared:actions.cancel'),
|
||||||
|
onCancel: async () => !draftState.dirty
|
||||||
|
|| (await draftState.confirm?.({
|
||||||
|
title: label ('settings:unsaved.leavePage'),
|
||||||
|
confirmText: label ('settings:unsaved.discardAndMove'),
|
||||||
|
cancelText: label ('shared:actions.cancel'), variant: 'danger' })) === true,
|
||||||
size: 'large',
|
size: 'large',
|
||||||
body: controls => (
|
body: controls => (
|
||||||
<PostImportRowForm
|
<PostImportRowForm
|
||||||
row={row}
|
row={row}
|
||||||
controls={controls}
|
controls={controls}
|
||||||
|
onDirtyStateChange={(dirty, discard) => {
|
||||||
|
draftState.dirty = dirty
|
||||||
|
draftState.discard = discard
|
||||||
|
draftState.confirm = controls.confirm
|
||||||
|
}}
|
||||||
onSave={saveRowDraft}/>) })
|
onSave={saveRowDraft}/>) })
|
||||||
|
draftState.discard ()
|
||||||
}
|
}
|
||||||
|
|
||||||
const editRow = async (row: PostImportRow) => {
|
const editRow = async (row: PostImportRow) => {
|
||||||
|
|||||||
@@ -1,6 +1,7 @@
|
|||||||
import { useEffect, useRef, useState } from 'react'
|
import { useState } from 'react'
|
||||||
|
|
||||||
|
|
||||||
|
import { useSessionDraft } from '@/lib/useSessionDraft'
|
||||||
import { useLocale, useLocaleNavigate } from '@/lib/useLocale'
|
import { useLocale, useLocaleNavigate } from '@/lib/useLocale'
|
||||||
import { useUITranslation } from '@/lib/useUITranslation'
|
import { useUITranslation } from '@/lib/useUITranslation'
|
||||||
import { renderPostImportMessage } from '@/components/posts/import/postImportRowStatus'
|
import { renderPostImportMessage } from '@/components/posts/import/postImportRowStatus'
|
||||||
@@ -22,10 +23,6 @@ import {
|
|||||||
extractImportSourceUrls,
|
extractImportSourceUrls,
|
||||||
validateImportSource,
|
validateImportSource,
|
||||||
} from '@/lib/postImportSourceValidation'
|
} from '@/lib/postImportSourceValidation'
|
||||||
import {
|
|
||||||
loadPostImportSourceDraft,
|
|
||||||
savePostImportSourceDraft,
|
|
||||||
} from '@/lib/postImportStorage'
|
|
||||||
import { canEditContent } from '@/lib/users'
|
import { canEditContent } from '@/lib/users'
|
||||||
import Forbidden from '@/pages/Forbidden'
|
import Forbidden from '@/pages/Forbidden'
|
||||||
|
|
||||||
@@ -45,12 +42,11 @@ const PostImportSourcePage: FC<Props> = ({ user }) => {
|
|||||||
const { message: uiMessage, label } = useUITranslation ('imports')
|
const { message: uiMessage, label } = useUITranslation ('imports')
|
||||||
const editable = canEditContent (user)
|
const editable = canEditContent (user)
|
||||||
const navigate = useLocaleNavigate ()
|
const navigate = useLocaleNavigate ()
|
||||||
const [source, setSource] = useState ('')
|
const { draft: source, setDraft: setSource, allowNextNavigation } =
|
||||||
|
useSessionDraft ('post-import:source', '', editable)
|
||||||
const [loading, setLoading] = useState (false)
|
const [loading, setLoading] = useState (false)
|
||||||
const [sourceIssues, setSourceIssues] = useState<ReturnType<typeof validateImportSource>> ([])
|
const [sourceIssues, setSourceIssues] = useState<ReturnType<typeof validateImportSource>> ([])
|
||||||
const [sourceError, setSourceError] = useState<string | null> (null)
|
const [sourceError, setSourceError] = useState<string | null> (null)
|
||||||
const saveTimer = useRef<number | null> (null)
|
|
||||||
const editedRef = useRef (false)
|
|
||||||
|
|
||||||
const lineCount = countImportSourceLines (source)
|
const lineCount = countImportSourceLines (source)
|
||||||
const sourceUrls = extractImportSourceUrls (source)
|
const sourceUrls = extractImportSourceUrls (source)
|
||||||
@@ -62,36 +58,6 @@ const PostImportSourcePage: FC<Props> = ({ user }) => {
|
|||||||
.filter (value => value != null)
|
.filter (value => value != null)
|
||||||
.join (' ')
|
.join (' ')
|
||||||
|
|
||||||
useEffect (() => {
|
|
||||||
const draft = loadPostImportSourceDraft (message =>
|
|
||||||
toast ({ title: label ('source.restoreFailed'),
|
|
||||||
description: renderPostImportMessage (message, locale) }))
|
|
||||||
|
|
||||||
if (!(editedRef.current))
|
|
||||||
{
|
|
||||||
setSource (current =>
|
|
||||||
current === ''
|
|
||||||
? draft.source
|
|
||||||
: current)
|
|
||||||
}
|
|
||||||
}, [label, locale])
|
|
||||||
|
|
||||||
useEffect (() => {
|
|
||||||
if (saveTimer.current != null)
|
|
||||||
window.clearTimeout (saveTimer.current)
|
|
||||||
|
|
||||||
saveTimer.current = window.setTimeout (() => {
|
|
||||||
savePostImportSourceDraft (source, message =>
|
|
||||||
toast ({ title: label ('source.saveFailed'),
|
|
||||||
description: renderPostImportMessage (message, locale) }))
|
|
||||||
}, 300)
|
|
||||||
|
|
||||||
return () => {
|
|
||||||
if (saveTimer.current != null)
|
|
||||||
window.clearTimeout (saveTimer.current)
|
|
||||||
}
|
|
||||||
}, [source, label, locale])
|
|
||||||
|
|
||||||
const preview = async () => {
|
const preview = async () => {
|
||||||
if (lineCount === 0)
|
if (lineCount === 0)
|
||||||
{
|
{
|
||||||
@@ -115,6 +81,7 @@ const PostImportSourcePage: FC<Props> = ({ user }) => {
|
|||||||
setSourceError (null)
|
setSourceError (null)
|
||||||
try
|
try
|
||||||
{
|
{
|
||||||
|
allowNextNavigation ()
|
||||||
navigate (buildPostNewReviewPath (sourceUrls))
|
navigate (buildPostNewReviewPath (sourceUrls))
|
||||||
}
|
}
|
||||||
finally
|
finally
|
||||||
@@ -147,7 +114,6 @@ const PostImportSourcePage: FC<Props> = ({ user }) => {
|
|||||||
description: renderPostImportMessage (message, locale) }))
|
description: renderPostImportMessage (message, locale) }))
|
||||||
}}
|
}}
|
||||||
onChange={ev => {
|
onChange={ev => {
|
||||||
editedRef.current = true
|
|
||||||
setSource (ev.target.value)
|
setSource (ev.target.value)
|
||||||
setSourceError (null)
|
setSourceError (null)
|
||||||
setSourceIssues ([])
|
setSourceIssues ([])
|
||||||
|
|||||||
@@ -3,6 +3,7 @@ import { Check, LoaderCircle, Pencil, X } from 'lucide-react'
|
|||||||
import { Fragment, useEffect, useMemo, useState } from 'react'
|
import { Fragment, useEffect, useMemo, useState } from 'react'
|
||||||
import { useLocation } from 'react-router-dom'
|
import { useLocation } from 'react-router-dom'
|
||||||
|
|
||||||
|
import { useSessionDraft } from '@/lib/useSessionDraft'
|
||||||
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'
|
||||||
@@ -27,7 +28,7 @@ import { useUITranslation } from '@/lib/useUITranslation'
|
|||||||
import { translateUIMessage } from '@/lib/i18n'
|
import { translateUIMessage } from '@/lib/i18n'
|
||||||
import { canEditContent } from '@/lib/users'
|
import { canEditContent } from '@/lib/users'
|
||||||
|
|
||||||
import type { FC, FormEvent } from 'react'
|
import type { FC, FormEvent, SetStateAction } from 'react'
|
||||||
|
|
||||||
import type { FetchNicoTagsOrder, FetchNicoTagsOrderField, NicoTag, Tag, User } from '@/types'
|
import type { FetchNicoTagsOrder, FetchNicoTagsOrderField, NicoTag, Tag, User } from '@/types'
|
||||||
|
|
||||||
@@ -61,12 +62,10 @@ const NicoTagListPage: FC<Props> = ({ user }) => {
|
|||||||
const qLinkStatus = (query.get ('link_status') || 'all') as LinkStatus
|
const qLinkStatus = (query.get ('link_status') || 'all') as LinkStatus
|
||||||
const order = (query.get ('order') || 'updated_at:desc') as FetchNicoTagsOrder
|
const order = (query.get ('order') || 'updated_at:desc') as FetchNicoTagsOrder
|
||||||
|
|
||||||
const [editingId, setEditingId] = useState<number | null> (null)
|
|
||||||
const [errorsByTagId, setErrorsByTagId] = useState<Record<number, string[]>> ({ })
|
const [errorsByTagId, setErrorsByTagId] = useState<Record<number, string[]>> ({ })
|
||||||
const [linkStatus, setLinkStatus] = useState<LinkStatus> ('all')
|
const [linkStatus, setLinkStatus] = useState<LinkStatus> ('all')
|
||||||
const [linkedTag, setLinkedTag] = useState ('')
|
const [linkedTag, setLinkedTag] = useState ('')
|
||||||
const [name, setName] = useState ('')
|
const [name, setName] = useState ('')
|
||||||
const [rawTags, setRawTags] = useState<Record<number, string>> ({ })
|
|
||||||
const [savingId, setSavingId] = useState<number | null> (null)
|
const [savingId, setSavingId] = useState<number | null> (null)
|
||||||
|
|
||||||
const keys = {
|
const keys = {
|
||||||
@@ -79,6 +78,19 @@ const NicoTagListPage: FC<Props> = ({ user }) => {
|
|||||||
|
|
||||||
const editable = canEditContent (user)
|
const editable = canEditContent (user)
|
||||||
const totalPages = Math.ceil (count / limit)
|
const totalPages = Math.ceil (count / limit)
|
||||||
|
const { draft, setField, clearDraft } = useSessionDraft (
|
||||||
|
`nico-links:${locale}:${location.search}`,
|
||||||
|
{ editingId: null as number | null, rawTags: { } as Record<number, string> },
|
||||||
|
editable && data != null, value => {
|
||||||
|
const tag = nicoTags.find (tag => tag.id === value.editingId)
|
||||||
|
return tag != null
|
||||||
|
&& value.rawTags[tag.id] !== tag.linkedTags.map (entry => entry.name).join (' ')
|
||||||
|
})
|
||||||
|
const { editingId, rawTags } = draft
|
||||||
|
const setEditingId = (value: number | null) => setField ('editingId', value)
|
||||||
|
const setRawTags = (value: SetStateAction<Record<number, string>>) =>
|
||||||
|
setField ('rawTags', value)
|
||||||
|
|
||||||
|
|
||||||
const handleSearch = (e: FormEvent) => {
|
const handleSearch = (e: FormEvent) => {
|
||||||
e.preventDefault ()
|
e.preventDefault ()
|
||||||
@@ -111,18 +123,14 @@ const NicoTagListPage: FC<Props> = ({ user }) => {
|
|||||||
variant: 'danger'})))
|
variant: 'danger'})))
|
||||||
return
|
return
|
||||||
|
|
||||||
|
clearDraft ({ editingId: null, rawTags: { } })
|
||||||
setEditingId (tag.id)
|
setEditingId (tag.id)
|
||||||
setRawTags (rawTags => ({
|
setRawTags ({ [tag.id]: tag.linkedTags.map (linkedTag => linkedTag.name).join (' ') })
|
||||||
...rawTags,
|
|
||||||
[tag.id]: tag.linkedTags.map (linkedTag => linkedTag.name).join (' ')}))
|
|
||||||
setErrorsByTagId (errors => ({ ...errors, [tag.id]: [] }))
|
setErrorsByTagId (errors => ({ ...errors, [tag.id]: [] }))
|
||||||
}
|
}
|
||||||
|
|
||||||
const cancelEdit = (tag: NicoTag) => {
|
const cancelEdit = (tag: NicoTag) => {
|
||||||
setEditingId (null)
|
clearDraft ({ editingId: null, rawTags: { } })
|
||||||
setRawTags (rawTags => ({
|
|
||||||
...rawTags,
|
|
||||||
[tag.id]: tag.linkedTags.map (linkedTag => linkedTag.name).join (' ')}))
|
|
||||||
setErrorsByTagId (errors => ({ ...errors, [tag.id]: [] }))
|
setErrorsByTagId (errors => ({ ...errors, [tag.id]: [] }))
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -136,7 +144,7 @@ const NicoTagListPage: FC<Props> = ({ user }) => {
|
|||||||
await apiPut<Tag[]> (`/tags/nico/${ id }`, formData,
|
await apiPut<Tag[]> (`/tags/nico/${ id }`, formData,
|
||||||
{ locale, headers: { 'Content-Type': 'multipart/form-data' } })
|
{ locale, headers: { 'Content-Type': 'multipart/form-data' } })
|
||||||
setErrorsByTagId (errors => ({ ...errors, [id]: [] }))
|
setErrorsByTagId (errors => ({ ...errors, [id]: [] }))
|
||||||
setEditingId (null)
|
clearDraft ({ editingId: null, rawTags: { } })
|
||||||
await queryClient.invalidateQueries ({ queryKey: tagsKeys.nicoRoot })
|
await queryClient.invalidateQueries ({ queryKey: tagsKeys.nicoRoot })
|
||||||
toast ({ description: label ('nico.updated') })
|
toast ({ description: label ('nico.updated') })
|
||||||
}
|
}
|
||||||
@@ -161,21 +169,11 @@ const NicoTagListPage: FC<Props> = ({ user }) => {
|
|||||||
setName (qName)
|
setName (qName)
|
||||||
setLinkedTag (qLinkedTag)
|
setLinkedTag (qLinkedTag)
|
||||||
setLinkStatus (qLinkStatus)
|
setLinkStatus (qLinkStatus)
|
||||||
setEditingId (null)
|
|
||||||
|
|
||||||
document.querySelector ('table')?.scrollIntoView ({
|
document.querySelector ('table')?.scrollIntoView ({
|
||||||
behavior: clientScrollBehaviour (animationMode) })
|
behavior: clientScrollBehaviour (animationMode) })
|
||||||
}, [animationMode, location.search, qLinkedTag, qLinkStatus, qName])
|
}, [animationMode, location.search, qLinkedTag, qLinkStatus, qName])
|
||||||
|
|
||||||
useEffect (() => {
|
|
||||||
if (!(data))
|
|
||||||
return
|
|
||||||
|
|
||||||
setRawTags (Object.fromEntries (data.tags.map (tag => [
|
|
||||||
tag.id,
|
|
||||||
tag.linkedTags.map (linkedTag => linkedTag.name).join (' ')])))
|
|
||||||
}, [data])
|
|
||||||
|
|
||||||
useEffect (() => {
|
useEffect (() => {
|
||||||
if (isError)
|
if (isError)
|
||||||
{
|
{
|
||||||
|
|||||||
@@ -2,6 +2,7 @@ import { useQuery, useQueryClient } from '@tanstack/react-query'
|
|||||||
import { useEffect, useState } from 'react'
|
import { useEffect, useState } from 'react'
|
||||||
import { useParams } from 'react-router-dom'
|
import { useParams } from 'react-router-dom'
|
||||||
|
|
||||||
|
import { useSessionDraft } from '@/lib/useSessionDraft'
|
||||||
import { useLocale } from '@/lib/useLocale'
|
import { useLocale } from '@/lib/useLocale'
|
||||||
import TagLink from '@/components/TagLink'
|
import TagLink from '@/components/TagLink'
|
||||||
import FieldError from '@/components/common/FieldError'
|
import FieldError from '@/components/common/FieldError'
|
||||||
@@ -42,12 +43,12 @@ const TagDetailPage: FC = () => {
|
|||||||
queryKey: tagKey,
|
queryKey: tagKey,
|
||||||
queryFn: () => fetchTag (tagId, locale) })
|
queryFn: () => fetchTag (tagId, locale) })
|
||||||
|
|
||||||
const [name, setName] = useState (tag?.name ?? '')
|
const { draft, setField, clearDraft } = useSessionDraft (`tag:${tagId}:${locale}`, {
|
||||||
const [category, setCategory] = useState<Category> (tag?.category ?? 'general')
|
name: tag?.name ?? '', category: (tag?.category ?? 'general') as Category,
|
||||||
const [aliases, setAliases] = useState (tag?.aliases.join (' ') ?? '')
|
aliases: tag?.aliases.join (' ') ?? '',
|
||||||
const [parentTags, setParentTags] = useState (tag?.parents.map (entry => entry.name).join (' ')
|
parentTags: tag?.parents.map (entry => entry.name).join (' ') ?? '',
|
||||||
?? '')
|
deprecated: tag?.deprecatedAt != null }, tag != null && tag.category !== 'nico')
|
||||||
const [deprecated, setDeprecated] = useState (tag?.deprecatedAt != null)
|
const { name, category, aliases, parentTags, deprecated } = draft
|
||||||
const [disabled, setDisabled] = useState (tag == null || tag.category === 'nico')
|
const [disabled, setDisabled] = useState (tag == null || tag.category === 'nico')
|
||||||
const { baseErrors, fieldErrors, clearValidationErrors, applyValidationError } =
|
const { baseErrors, fieldErrors, clearValidationErrors, applyValidationError } =
|
||||||
useValidationErrors<TagFormField> ()
|
useValidationErrors<TagFormField> ()
|
||||||
@@ -69,11 +70,10 @@ const TagDetailPage: FC = () => {
|
|||||||
{
|
{
|
||||||
const data = await apiPut<Tag> (`/tags/${ id }`, formData, { locale })
|
const data = await apiPut<Tag> (`/tags/${ id }`, formData, { locale })
|
||||||
|
|
||||||
setName (data.name)
|
clearDraft ({ name: data.name, category: data.category as Category,
|
||||||
setCategory (data.category as Category)
|
aliases: data.aliases.join (' '),
|
||||||
setAliases (data.aliases.join (' '))
|
parentTags: data.parents.map (entry => entry.name).join (' '),
|
||||||
setParentTags (data.parents.map (t => t.name).join (' '))
|
deprecated: data.deprecatedAt != null })
|
||||||
setDeprecated (Boolean (data.deprecatedAt))
|
|
||||||
|
|
||||||
qc.invalidateQueries ({ queryKey: postsKeys.root })
|
qc.invalidateQueries ({ queryKey: postsKeys.root })
|
||||||
qc.invalidateQueries ({ queryKey: tagsKeys.root })
|
qc.invalidateQueries ({ queryKey: tagsKeys.root })
|
||||||
@@ -94,11 +94,6 @@ const TagDetailPage: FC = () => {
|
|||||||
return
|
return
|
||||||
}
|
}
|
||||||
|
|
||||||
setName (tag.name)
|
|
||||||
setCategory (tag.category as Category)
|
|
||||||
setAliases (tag.aliases.join (' '))
|
|
||||||
setParentTags (tag.parents.map (t => t.name).join (' '))
|
|
||||||
setDeprecated (Boolean (tag.deprecatedAt))
|
|
||||||
setDisabled (tag.category === 'nico')
|
setDisabled (tag.category === 'nico')
|
||||||
}, [tag])
|
}, [tag])
|
||||||
|
|
||||||
@@ -129,7 +124,7 @@ const TagDetailPage: FC = () => {
|
|||||||
type="text"
|
type="text"
|
||||||
disabled={disabled}
|
disabled={disabled}
|
||||||
value={name}
|
value={name}
|
||||||
onChange={e => setName (e.target.value)}
|
onChange={e => setField ('name', e.target.value)}
|
||||||
aria-describedby={describedBy}
|
aria-describedby={describedBy}
|
||||||
aria-invalid={invalid}
|
aria-invalid={invalid}
|
||||||
className={inputClass (invalid)}/>
|
className={inputClass (invalid)}/>
|
||||||
@@ -142,7 +137,7 @@ const TagDetailPage: FC = () => {
|
|||||||
<select
|
<select
|
||||||
disabled={disabled}
|
disabled={disabled}
|
||||||
value={category ?? ''}
|
value={category ?? ''}
|
||||||
onChange={e => setCategory(e.target.value as Category)}
|
onChange={e => setField ('category', e.target.value as Category)}
|
||||||
aria-describedby={describedBy}
|
aria-describedby={describedBy}
|
||||||
aria-invalid={invalid}
|
aria-invalid={invalid}
|
||||||
className={inputClass (invalid)}>
|
className={inputClass (invalid)}>
|
||||||
@@ -164,7 +159,7 @@ const TagDetailPage: FC = () => {
|
|||||||
type="text"
|
type="text"
|
||||||
disabled={disabled}
|
disabled={disabled}
|
||||||
value={aliases}
|
value={aliases}
|
||||||
onChange={e => setAliases (e.target.value)}
|
onChange={e => setField ('aliases', e.target.value)}
|
||||||
aria-describedby={describedBy}
|
aria-describedby={describedBy}
|
||||||
aria-invalid={invalid}
|
aria-invalid={invalid}
|
||||||
className={inputClass (invalid)}/>
|
className={inputClass (invalid)}/>
|
||||||
@@ -180,7 +175,7 @@ const TagDetailPage: FC = () => {
|
|||||||
type="text"
|
type="text"
|
||||||
disabled={disabled}
|
disabled={disabled}
|
||||||
value={parentTags}
|
value={parentTags}
|
||||||
onChange={e => setParentTags (e.target.value)}
|
onChange={e => setField ('parentTags', e.target.value)}
|
||||||
aria-describedby={describedBy}
|
aria-describedby={describedBy}
|
||||||
aria-invalid={invalid}
|
aria-invalid={invalid}
|
||||||
className={inputClass (invalid)}/>
|
className={inputClass (invalid)}/>
|
||||||
@@ -193,7 +188,7 @@ const TagDetailPage: FC = () => {
|
|||||||
type="checkbox"
|
type="checkbox"
|
||||||
disabled={disabled}
|
disabled={disabled}
|
||||||
checked={deprecated}
|
checked={deprecated}
|
||||||
onChange={e => setDeprecated (e.target.checked)}
|
onChange={e => setField ('deprecated', e.target.checked)}
|
||||||
aria-describedby={describedBy}
|
aria-describedby={describedBy}
|
||||||
aria-invalid={invalid}/>)}
|
aria-invalid={invalid}/>)}
|
||||||
</FormField>
|
</FormField>
|
||||||
|
|||||||
@@ -3,6 +3,7 @@ import { useQuery } from '@tanstack/react-query'
|
|||||||
import { useCallback, useEffect, useMemo, useRef, useState } from 'react'
|
import { useCallback, useEffect, useMemo, useRef, useState } from 'react'
|
||||||
import { useParams } from 'react-router-dom'
|
import { useParams } from 'react-router-dom'
|
||||||
|
|
||||||
|
import { useSessionDraft } from '@/lib/useSessionDraft'
|
||||||
import { useLocale } from '@/lib/useLocale'
|
import { useLocale } from '@/lib/useLocale'
|
||||||
import ErrorScreen from '@/components/ErrorScreen'
|
import ErrorScreen from '@/components/ErrorScreen'
|
||||||
import PostEditForm from '@/components/PostEditForm'
|
import PostEditForm from '@/components/PostEditForm'
|
||||||
@@ -238,7 +239,8 @@ const TheatreDetailPage: FC<Props> = ({ user }: Props) => {
|
|||||||
const [rightSidebarWidth, setRightSidebarWidth] = useState (256)
|
const [rightSidebarWidth, setRightSidebarWidth] = useState (256)
|
||||||
const [sidebarContainerWidth, setSidebarContainerWidth] = useState (0)
|
const [sidebarContainerWidth, setSidebarContainerWidth] = useState (0)
|
||||||
const [comments, setComments] = useState<TheatreComment[]> ([])
|
const [comments, setComments] = useState<TheatreComment[]> ([])
|
||||||
const [content, setContent] = useState ('')
|
const { draft: content, setDraft: setContent, clearDraft } =
|
||||||
|
useSessionDraft (`theatre:${id}:comment:${locale}`, '')
|
||||||
const [editingPost, setEditingPost] = useState<Post | null> (null)
|
const [editingPost, setEditingPost] = useState<Post | null> (null)
|
||||||
const [loading, setLoading] = useState (false)
|
const [loading, setLoading] = useState (false)
|
||||||
const { data: initialTheatre, error: theatreError } = useQuery ({
|
const { data: initialTheatre, error: theatreError } = useQuery ({
|
||||||
@@ -620,7 +622,7 @@ const TheatreDetailPage: FC<Props> = ({ user }: Props) => {
|
|||||||
setSending (true)
|
setSending (true)
|
||||||
clearValidationErrors ()
|
clearValidationErrors ()
|
||||||
await apiPost (`/theatres/${ id }/comments`, { content }, { locale })
|
await apiPost (`/theatres/${ id }/comments`, { content }, { locale })
|
||||||
setContent ('')
|
clearDraft ('')
|
||||||
commentsRef.current?.scrollTo ({
|
commentsRef.current?.scrollTo ({
|
||||||
top: 0,
|
top: 0,
|
||||||
behavior: clientScrollBehaviour (animationMode) })
|
behavior: clientScrollBehaviour (animationMode) })
|
||||||
|
|||||||
@@ -38,6 +38,7 @@ import {
|
|||||||
upsertUserThemeSlot,
|
upsertUserThemeSlot,
|
||||||
USER_THEME_SLOT_SELECTIONS,
|
USER_THEME_SLOT_SELECTIONS,
|
||||||
} from '@/lib/settings'
|
} from '@/lib/settings'
|
||||||
|
import { useSessionDraft } from '@/lib/useSessionDraft'
|
||||||
import { useUnsavedChangesGuard } from '@/lib/useUnsavedChangesGuard'
|
import { useUnsavedChangesGuard } from '@/lib/useUnsavedChangesGuard'
|
||||||
import { useKeyboardShortcutSettings, useKeyboardShortcuts } from '@/lib/useKeyboardShortcuts'
|
import { useKeyboardShortcutSettings, useKeyboardShortcuts } from '@/lib/useKeyboardShortcuts'
|
||||||
import { cn, inputClass } from '@/lib/utils'
|
import { cn, inputClass } from '@/lib/utils'
|
||||||
@@ -672,11 +673,13 @@ const SettingPage: FC<Props> = ({ user, setUser }) => {
|
|||||||
const location = useLocation ()
|
const location = useLocation ()
|
||||||
const navigate = useLocaleNavigate ()
|
const navigate = useLocaleNavigate ()
|
||||||
const dialogue = useDialogue ()
|
const dialogue = useDialogue ()
|
||||||
const { registerUnsavedChangesSource } = useUnsavedChangesGuard ()
|
const { registerUnsavedChangesSource, allowNextNavigation } = useUnsavedChangesGuard ()
|
||||||
|
|
||||||
const [inheritVsbl, setInheritVsbl] = useState (false)
|
const [inheritVsbl, setInheritVsbl] = useState (false)
|
||||||
const [loading, setLoading] = useState (initialSettings == null)
|
const [loading, setLoading] = useState (initialSettings == null)
|
||||||
const [name, setName] = useState (user?.name ?? '')
|
const { draft: name, setDraft: setName, clearDraft: clearNameDraft,
|
||||||
|
discardDraft: discardNameDraft } =
|
||||||
|
useSessionDraft ('settings:account', user?.name ?? '', user != null)
|
||||||
const [settingsError, setSettingsError] = useState<string | null> (null)
|
const [settingsError, setSettingsError] = useState<string | null> (null)
|
||||||
const [savedThemeMode, setSavedThemeMode] =
|
const [savedThemeMode, setSavedThemeMode] =
|
||||||
useState<ClientThemeMode> (initialSettings?.theme ?? 'system')
|
useState<ClientThemeMode> (initialSettings?.theme ?? 'system')
|
||||||
@@ -693,9 +696,9 @@ const SettingPage: FC<Props> = ({ user, setUser }) => {
|
|||||||
const [savedThemeSlots, setSavedThemeSlots] =
|
const [savedThemeSlots, setSavedThemeSlots] =
|
||||||
useState<UserThemeSlotMap> (() => ensureCompleteThemeSlots (
|
useState<UserThemeSlotMap> (() => ensureCompleteThemeSlots (
|
||||||
normaliseUserThemeSlots (initialThemeSlots ?? [])))
|
normaliseUserThemeSlots (initialThemeSlots ?? [])))
|
||||||
const [draftThemeSlots, setDraftThemeSlots] =
|
const { draft: draftThemeSlots, setDraft: setDraftThemeSlots,
|
||||||
useState<UserThemeSlotMap> (() => ensureCompleteThemeSlots (
|
clearDraft: clearThemeDraft } =
|
||||||
normaliseUserThemeSlots (initialThemeSlots ?? [])))
|
useSessionDraft ('settings:theme-slots', savedThemeSlots, user != null && !loading)
|
||||||
const [dirtyStates, setDirtyStates] =
|
const [dirtyStates, setDirtyStates] =
|
||||||
useState<Partial<Record<SettingsTab, SettingsTabDirtyState>>> ({ })
|
useState<Partial<Record<SettingsTab, SettingsTabDirtyState>>> ({ })
|
||||||
const [userCodeVsbl, setUserCodeVsbl] = useState (false)
|
const [userCodeVsbl, setUserCodeVsbl] = useState (false)
|
||||||
@@ -819,7 +822,7 @@ const SettingPage: FC<Props> = ({ user, setUser }) => {
|
|||||||
}
|
}
|
||||||
|
|
||||||
const discardAccountChanges = () => {
|
const discardAccountChanges = () => {
|
||||||
setName (savedName)
|
discardNameDraft ()
|
||||||
clearUserValidationErrors ()
|
clearUserValidationErrors ()
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -898,6 +901,7 @@ const SettingPage: FC<Props> = ({ user, setUser }) => {
|
|||||||
return
|
return
|
||||||
|
|
||||||
await discardCurrentTabChanges ()
|
await discardCurrentTabChanges ()
|
||||||
|
allowNextNavigation ()
|
||||||
applyActiveTab (nextTab)
|
applyActiveTab (nextTab)
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -1057,7 +1061,7 @@ const SettingPage: FC<Props> = ({ user, setUser }) => {
|
|||||||
`/users/${ user.id }`, formData,
|
`/users/${ user.id }`, formData,
|
||||||
{ headers: { 'Content-Type': 'multipart/form-data' } })
|
{ headers: { 'Content-Type': 'multipart/form-data' } })
|
||||||
setUser (currentUser => ({ ...currentUser, ...data }))
|
setUser (currentUser => ({ ...currentUser, ...data }))
|
||||||
setName (data.name ?? '')
|
clearNameDraft (data.name ?? '')
|
||||||
toast ({ title: label ('account.nameSaved') })
|
toast ({ title: label ('account.nameSaved') })
|
||||||
}
|
}
|
||||||
catch (submitError)
|
catch (submitError)
|
||||||
@@ -1091,7 +1095,7 @@ const SettingPage: FC<Props> = ({ user, setUser }) => {
|
|||||||
const completeThemeSlots = ensureCompleteThemeSlots (nextSavedThemeSlots)
|
const completeThemeSlots = ensureCompleteThemeSlots (nextSavedThemeSlots)
|
||||||
|
|
||||||
setSavedThemeSlots (completeThemeSlots)
|
setSavedThemeSlots (completeThemeSlots)
|
||||||
setDraftThemeSlots (completeThemeSlots)
|
clearThemeDraft (completeThemeSlots)
|
||||||
setCachedUserThemeSlots (completeThemeSlots)
|
setCachedUserThemeSlots (completeThemeSlots)
|
||||||
applyClientAppearance (completeThemeSlots)
|
applyClientAppearance (completeThemeSlots)
|
||||||
toast ({ title: label ('theme.saved') })
|
toast ({ title: label ('theme.saved') })
|
||||||
@@ -1107,13 +1111,6 @@ const SettingPage: FC<Props> = ({ user, setUser }) => {
|
|||||||
discardThemeChanges ()
|
discardThemeChanges ()
|
||||||
}
|
}
|
||||||
|
|
||||||
useEffect (() => {
|
|
||||||
if (!user)
|
|
||||||
return
|
|
||||||
|
|
||||||
setName (user.name ?? '')
|
|
||||||
}, [user])
|
|
||||||
|
|
||||||
useEffect (() => {
|
useEffect (() => {
|
||||||
if (!(user))
|
if (!(user))
|
||||||
return
|
return
|
||||||
@@ -1146,7 +1143,6 @@ const SettingPage: FC<Props> = ({ user, setUser }) => {
|
|||||||
setSavedActiveDarkThemeSlotNo (activeDarkThemeSlotNo)
|
setSavedActiveDarkThemeSlotNo (activeDarkThemeSlotNo)
|
||||||
setDraftActiveDarkThemeSlotNo (activeDarkThemeSlotNo)
|
setDraftActiveDarkThemeSlotNo (activeDarkThemeSlotNo)
|
||||||
setSavedThemeSlots (completeThemeSlots)
|
setSavedThemeSlots (completeThemeSlots)
|
||||||
setDraftThemeSlots (completeThemeSlots)
|
|
||||||
setCachedUserThemeSlots (completeThemeSlots)
|
setCachedUserThemeSlots (completeThemeSlots)
|
||||||
applyThemeAppearanceState ({ themeMode,
|
applyThemeAppearanceState ({ themeMode,
|
||||||
activeLightThemeSlotNo,
|
activeLightThemeSlotNo,
|
||||||
|
|||||||
@@ -1,6 +1,6 @@
|
|||||||
import { fireEvent, screen, waitFor } from '@testing-library/react'
|
import { fireEvent, screen, waitFor } from '@testing-library/react'
|
||||||
import { Route, Routes } from 'react-router-dom'
|
import { Route, Routes } from 'react-router-dom'
|
||||||
import { describe, expect, it, vi } from 'vitest'
|
import { beforeEach, describe, expect, it, vi } from 'vitest'
|
||||||
|
|
||||||
import { textContentOf } from '@/test/text'
|
import { textContentOf } from '@/test/text'
|
||||||
import WikiEditPage from '@/pages/wiki/WikiEditPage'
|
import WikiEditPage from '@/pages/wiki/WikiEditPage'
|
||||||
@@ -10,6 +10,7 @@ import { renderWithProviders } from '@/test/render'
|
|||||||
const api = vi.hoisted (() => ({
|
const api = vi.hoisted (() => ({
|
||||||
apiGet: vi.fn (),
|
apiGet: vi.fn (),
|
||||||
apiPut: vi.fn (),
|
apiPut: vi.fn (),
|
||||||
|
isApiError: vi.fn (() => false),
|
||||||
}))
|
}))
|
||||||
|
|
||||||
const toastApi = vi.hoisted (() => ({
|
const toastApi = vi.hoisted (() => ({
|
||||||
@@ -39,6 +40,34 @@ const renderPage = (user = buildUser ({ role: 'member' })) =>
|
|||||||
)
|
)
|
||||||
|
|
||||||
describe ('WikiEditPage', () => {
|
describe ('WikiEditPage', () => {
|
||||||
|
beforeEach (() => vi.clearAllMocks ())
|
||||||
|
|
||||||
|
it ('restores a draft after the server baseline arrives', async () => {
|
||||||
|
sessionStorage.setItem ('session-draft:1:anonymous:wiki:ja:9', JSON.stringify ({
|
||||||
|
title: '入力中の表題', body: '入力中の本文' }))
|
||||||
|
api.apiGet.mockResolvedValueOnce (buildWikiPage ({ title: '既存', body: '本文' }))
|
||||||
|
|
||||||
|
renderPage ()
|
||||||
|
|
||||||
|
expect (await screen.findByDisplayValue ('入力中の表題')).toBeInTheDocument ()
|
||||||
|
expect (screen.getByLabelText ('本文エディタ')).toHaveValue ('入力中の本文')
|
||||||
|
})
|
||||||
|
|
||||||
|
it ('keeps the draft after a rejected submission', async () => {
|
||||||
|
api.apiGet.mockResolvedValueOnce (buildWikiPage ({ title: '既存', body: '本文' }))
|
||||||
|
api.apiPut.mockRejectedValueOnce (new Error ('unavailable'))
|
||||||
|
renderPage ()
|
||||||
|
|
||||||
|
fireEvent.change (await screen.findByDisplayValue ('既存'), {
|
||||||
|
target: { value: '未送信の表題' } })
|
||||||
|
fireEvent.click (screen.getByRole ('button', { name: '編輯' }))
|
||||||
|
|
||||||
|
await waitFor (() => expect (api.apiPut).toHaveBeenCalled ())
|
||||||
|
expect (screen.getByDisplayValue ('未送信の表題')).toBeInTheDocument ()
|
||||||
|
expect (sessionStorage.getItem ('session-draft:1:anonymous:wiki:ja:9'))
|
||||||
|
.toContain ('未送信の表題')
|
||||||
|
})
|
||||||
|
|
||||||
it ('blocks guests', () => {
|
it ('blocks guests', () => {
|
||||||
renderPage (buildUser ({ role: 'guest' }))
|
renderPage (buildUser ({ role: 'guest' }))
|
||||||
|
|
||||||
|
|||||||
@@ -1,9 +1,9 @@
|
|||||||
import { useQuery, useQueryClient } from '@tanstack/react-query'
|
import { useQuery, useQueryClient } from '@tanstack/react-query'
|
||||||
import MarkdownIt from 'markdown-it'
|
import MarkdownIt from 'markdown-it'
|
||||||
import { useEffect, useState } from 'react'
|
|
||||||
import MdEditor from 'react-markdown-editor-lite'
|
import MdEditor from 'react-markdown-editor-lite'
|
||||||
import { useParams } from 'react-router-dom'
|
import { useParams } from 'react-router-dom'
|
||||||
|
|
||||||
|
import { useSessionDraft } from '@/lib/useSessionDraft'
|
||||||
import { useLocale, useLocaleNavigate } from '@/lib/useLocale'
|
import { useLocale, useLocaleNavigate } from '@/lib/useLocale'
|
||||||
import { useUITranslation } from '@/lib/useUITranslation'
|
import { useUITranslation } from '@/lib/useUITranslation'
|
||||||
import FieldError from '@/components/common/FieldError'
|
import FieldError from '@/components/common/FieldError'
|
||||||
@@ -52,10 +52,11 @@ const WikiEditPage: FC<Props> = ({ user }) => {
|
|||||||
queryKey: wikiKeys.show (id ?? '', { }, locale),
|
queryKey: wikiKeys.show (id ?? '', { }, locale),
|
||||||
queryFn: () => apiGet<WikiPage> (`/wiki/${ encodeURIComponent (id ?? '') }`, { locale }),
|
queryFn: () => apiGet<WikiPage> (`/wiki/${ encodeURIComponent (id ?? '') }`, { locale }),
|
||||||
enabled: editable })
|
enabled: editable })
|
||||||
const [body, setBody] = useState (wiki?.body ?? '')
|
const { draft, setField, clearDraft, allowNextNavigation } =
|
||||||
const [loadedSource, setLoadedSource] = useState (wiki == null ? '' : source)
|
useSessionDraft (`wiki:${source}`, { title: wiki?.title ?? '', body: wiki?.body ?? '' },
|
||||||
const pending = loading || loadedSource !== source
|
editable && wiki != null)
|
||||||
const [title, setTitle] = useState (wiki?.title ?? '')
|
const { title, body } = draft
|
||||||
|
const pending = loading
|
||||||
const { baseErrors, fieldErrors, clearValidationErrors, applyValidationError } =
|
const { baseErrors, fieldErrors, clearValidationErrors, applyValidationError } =
|
||||||
useValidationErrors<WikiFormField> ()
|
useValidationErrors<WikiFormField> ()
|
||||||
|
|
||||||
@@ -77,6 +78,8 @@ const WikiEditPage: FC<Props> = ({ user }) => {
|
|||||||
prev == null ? prev : { ...prev, title, body })
|
prev == null ? prev : { ...prev, title, body })
|
||||||
qc.invalidateQueries ({ queryKey: wikiKeys.root })
|
qc.invalidateQueries ({ queryKey: wikiKeys.root })
|
||||||
toast ({ title: label ('shared:messages.postSuccess') })
|
toast ({ title: label ('shared:messages.postSuccess') })
|
||||||
|
clearDraft ()
|
||||||
|
allowNextNavigation ()
|
||||||
navigate (`/wiki/${ encodeURIComponent (title) }`)
|
navigate (`/wiki/${ encodeURIComponent (title) }`)
|
||||||
}
|
}
|
||||||
catch (e)
|
catch (e)
|
||||||
@@ -87,14 +90,6 @@ const WikiEditPage: FC<Props> = ({ user }) => {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
useEffect (() => {
|
|
||||||
if (!(editable) || wiki == null)
|
|
||||||
return
|
|
||||||
setTitle (wiki.title)
|
|
||||||
setBody (wiki.body)
|
|
||||||
setLoadedSource (source)
|
|
||||||
}, [editable, source, wiki])
|
|
||||||
|
|
||||||
if (!(editable))
|
if (!(editable))
|
||||||
return <Forbidden/>
|
return <Forbidden/>
|
||||||
|
|
||||||
@@ -114,7 +109,7 @@ const WikiEditPage: FC<Props> = ({ user }) => {
|
|||||||
{({ describedBy, invalid }) => (
|
{({ describedBy, invalid }) => (
|
||||||
<input type="text"
|
<input type="text"
|
||||||
value={title}
|
value={title}
|
||||||
onChange={e => setTitle (e.target.value)}
|
onChange={e => setField ('title', e.target.value)}
|
||||||
aria-describedby={describedBy}
|
aria-describedby={describedBy}
|
||||||
aria-invalid={invalid}
|
aria-invalid={invalid}
|
||||||
className={inputClass (invalid)}/>)}
|
className={inputClass (invalid)}/>)}
|
||||||
@@ -127,7 +122,7 @@ const WikiEditPage: FC<Props> = ({ user }) => {
|
|||||||
style={{ height: '500px' }}
|
style={{ height: '500px' }}
|
||||||
config={{ view: FIXED_WIKI_EDITOR_VIEW }}
|
config={{ view: FIXED_WIKI_EDITOR_VIEW }}
|
||||||
renderHTML={text => mdParser.render (text)}
|
renderHTML={text => mdParser.render (text)}
|
||||||
onChange={({ text }) => setBody (text)}/>)}
|
onChange={({ text }) => setField ('body', text)}/>)}
|
||||||
</FormField>
|
</FormField>
|
||||||
|
|
||||||
{/* 送信 */}
|
{/* 送信 */}
|
||||||
|
|||||||
@@ -1,10 +1,10 @@
|
|||||||
import { useQueryClient } from '@tanstack/react-query'
|
import { useQueryClient } from '@tanstack/react-query'
|
||||||
import MarkdownIt from 'markdown-it'
|
import MarkdownIt from 'markdown-it'
|
||||||
import { useState } from 'react'
|
|
||||||
import MdEditor from 'react-markdown-editor-lite'
|
import MdEditor from 'react-markdown-editor-lite'
|
||||||
import { useLocation } from 'react-router-dom'
|
import { useLocation } from 'react-router-dom'
|
||||||
import 'react-markdown-editor-lite/lib/index.css'
|
import 'react-markdown-editor-lite/lib/index.css'
|
||||||
|
|
||||||
|
import { useSessionDraft } from '@/lib/useSessionDraft'
|
||||||
import { useLocale, useLocaleNavigate } from '@/lib/useLocale'
|
import { useLocale, useLocaleNavigate } from '@/lib/useLocale'
|
||||||
import { useUITranslation } from '@/lib/useUITranslation'
|
import { useUITranslation } from '@/lib/useUITranslation'
|
||||||
import FieldError from '@/components/common/FieldError'
|
import FieldError from '@/components/common/FieldError'
|
||||||
@@ -47,8 +47,9 @@ const WikiNewPage: FC<Props> = ({ user }) => {
|
|||||||
const query = new URLSearchParams (location.search)
|
const query = new URLSearchParams (location.search)
|
||||||
const titleQuery = query.get ('title') ?? ''
|
const titleQuery = query.get ('title') ?? ''
|
||||||
|
|
||||||
const [title, setTitle] = useState (titleQuery)
|
const { draft, setField, clearDraft, allowNextNavigation } =
|
||||||
const [body, setBody] = useState ('')
|
useSessionDraft (`wiki:new:${locale}`, { title: titleQuery, body: '' }, editable)
|
||||||
|
const { title, body } = draft
|
||||||
const { baseErrors, fieldErrors, clearValidationErrors, applyValidationError } =
|
const { baseErrors, fieldErrors, clearValidationErrors, applyValidationError } =
|
||||||
useValidationErrors<WikiFormField> ()
|
useValidationErrors<WikiFormField> ()
|
||||||
|
|
||||||
@@ -69,6 +70,8 @@ const WikiNewPage: FC<Props> = ({ user }) => {
|
|||||||
qc.invalidateQueries ({ queryKey: wikiKeys.root }),
|
qc.invalidateQueries ({ queryKey: wikiKeys.root }),
|
||||||
qc.invalidateQueries ({ queryKey: tagsKeys.root })])
|
qc.invalidateQueries ({ queryKey: tagsKeys.root })])
|
||||||
toast ({ title: label ('shared:messages.postSuccess') })
|
toast ({ title: label ('shared:messages.postSuccess') })
|
||||||
|
clearDraft ()
|
||||||
|
allowNextNavigation ()
|
||||||
navigate (`/wiki/${ encodeURIComponent (data.title) }`)
|
navigate (`/wiki/${ encodeURIComponent (data.title) }`)
|
||||||
}
|
}
|
||||||
catch (e)
|
catch (e)
|
||||||
@@ -95,7 +98,7 @@ const WikiNewPage: FC<Props> = ({ user }) => {
|
|||||||
{({ describedBy, invalid }) => (
|
{({ describedBy, invalid }) => (
|
||||||
<input type="text"
|
<input type="text"
|
||||||
value={title}
|
value={title}
|
||||||
onChange={e => setTitle (e.target.value)}
|
onChange={e => setField ('title', e.target.value)}
|
||||||
aria-describedby={describedBy}
|
aria-describedby={describedBy}
|
||||||
aria-invalid={invalid}
|
aria-invalid={invalid}
|
||||||
className={inputClass (invalid)}/>)}
|
className={inputClass (invalid)}/>)}
|
||||||
@@ -108,7 +111,7 @@ const WikiNewPage: FC<Props> = ({ user }) => {
|
|||||||
style={{ height: '500px' }}
|
style={{ height: '500px' }}
|
||||||
config={{ view: FIXED_WIKI_EDITOR_VIEW }}
|
config={{ view: FIXED_WIKI_EDITOR_VIEW }}
|
||||||
renderHTML={text => mdParser.render (text)}
|
renderHTML={text => mdParser.render (text)}
|
||||||
onChange={({ text }) => setBody (text)}/>)}
|
onChange={({ text }) => setField ('body', text)}/>)}
|
||||||
</FormField>
|
</FormField>
|
||||||
|
|
||||||
{/* 送信 */}
|
{/* 送信 */}
|
||||||
|
|||||||
@@ -12,17 +12,18 @@ import type { ReactElement, ReactNode } from 'react'
|
|||||||
|
|
||||||
type Options = {
|
type Options = {
|
||||||
route?: string
|
route?: string
|
||||||
queryClient?: QueryClient }
|
queryClient?: QueryClient
|
||||||
|
draftScope?: string }
|
||||||
|
|
||||||
const TestContentContext = createContext<ReactNode> (null)
|
const TestContentContext = createContext<ReactNode> (null)
|
||||||
|
|
||||||
|
|
||||||
const TestRoute = () => {
|
const TestRoute = ({ draftScope }: { draftScope?: string }) => {
|
||||||
const children = useContext (TestContentContext)
|
const children = useContext (TestContentContext)
|
||||||
|
|
||||||
return (
|
return (
|
||||||
<DialogueProvider>
|
<DialogueProvider>
|
||||||
<UnsavedChangesGuardProvider>
|
<UnsavedChangesGuardProvider draftScope={draftScope}>
|
||||||
<KeyboardShortcutsProvider>
|
<KeyboardShortcutsProvider>
|
||||||
{children}
|
{children}
|
||||||
</KeyboardShortcutsProvider>
|
</KeyboardShortcutsProvider>
|
||||||
@@ -40,7 +41,7 @@ export const renderWithProviders = (
|
|||||||
const Wrapper = ({ children }: { children: ReactNode }) => {
|
const Wrapper = ({ children }: { children: ReactNode }) => {
|
||||||
const [router] = useState (() => createMemoryRouter ([{
|
const [router] = useState (() => createMemoryRouter ([{
|
||||||
path: '*',
|
path: '*',
|
||||||
element: <TestRoute/> }], {
|
element: <TestRoute draftScope={options.draftScope}/> }], {
|
||||||
initialEntries: [options.route ?? '/'] }))
|
initialEntries: [options.route ?? '/'] }))
|
||||||
|
|
||||||
return (
|
return (
|
||||||
|
|||||||
@@ -9,6 +9,7 @@ beforeEach (() => {
|
|||||||
afterEach (() => {
|
afterEach (() => {
|
||||||
cleanup ()
|
cleanup ()
|
||||||
localStorage.clear ()
|
localStorage.clear ()
|
||||||
|
sessionStorage.clear ()
|
||||||
vi.restoreAllMocks ()
|
vi.restoreAllMocks ()
|
||||||
})
|
})
|
||||||
|
|
||||||
|
|||||||
新しいイシューから参照
ユーザーをブロックする