このコミットが含まれているのは:
@@ -1,8 +1,6 @@
|
||||
import { useEffect, useMemo, useState } from 'react'
|
||||
import { Helmet } from 'react-helmet-async'
|
||||
import { useNavigate,
|
||||
useParams,
|
||||
useSearchParams } from 'react-router-dom'
|
||||
import { useNavigate, useParams, useSearchParams } from 'react-router-dom'
|
||||
|
||||
import PageTitle from '@/components/common/PageTitle'
|
||||
import MainArea from '@/components/layout/MainArea'
|
||||
@@ -20,14 +18,14 @@ import { loadPostImportSession,
|
||||
mergeValidatedImportRows,
|
||||
processableImportRows,
|
||||
reviewSummaryCounts,
|
||||
savePostImportSession,
|
||||
type PostImportResultRow,
|
||||
type PostImportRow,
|
||||
type PostImportSession } from '@/lib/postImportSession'
|
||||
savePostImportSession } from '@/lib/postImportSession'
|
||||
import Forbidden from '@/pages/Forbidden'
|
||||
|
||||
import type { FC } from 'react'
|
||||
|
||||
import type { PostImportResultRow,
|
||||
PostImportRow,
|
||||
PostImportSession } from '@/lib/postImportSession'
|
||||
import type { User } from '@/types'
|
||||
|
||||
type Props = { user: User | null }
|
||||
@@ -44,297 +42,298 @@ type Draft = {
|
||||
|
||||
|
||||
const PostImportReviewPage: FC<Props> = ({ user }) => {
|
||||
const editable = canEditContent (user)
|
||||
const navigate = useNavigate ()
|
||||
const { sessionId } = useParams ()
|
||||
const [searchParams, setSearchParams] = useSearchParams ()
|
||||
const editable = canEditContent (user)
|
||||
const navigate = useNavigate ()
|
||||
const { sessionId } = useParams ()
|
||||
const [searchParams, setSearchParams] = useSearchParams ()
|
||||
|
||||
const [session, setSession] = useState<PostImportSession | null> (null)
|
||||
const [loading, setLoading] = useState (false)
|
||||
const [missing, setMissing] = useState (false)
|
||||
const [savingRow, setSavingRow] = useState<number | null> (null)
|
||||
const [dialogMessageRow, setDialogMessageRow] = useState<PostImportRow | null> (null)
|
||||
const [session, setSession] = useState<PostImportSession | null> (null)
|
||||
const [loading, setLoading] = useState (false)
|
||||
const [missing, setMissing] = useState (false)
|
||||
const [savingRow, setSavingRow] = useState<number | null> (null)
|
||||
const [dialogMessageRow, setDialogMessageRow] = useState<PostImportRow | null> (null)
|
||||
|
||||
useEffect (() => {
|
||||
if (sessionId == null)
|
||||
return
|
||||
useEffect (() => {
|
||||
if (sessionId == null)
|
||||
return
|
||||
|
||||
const loaded = loadPostImportSession (sessionId, message =>
|
||||
toast ({ title: '取込状態を復元できませんでした', description: message }))
|
||||
setSession (loaded)
|
||||
setMissing (loaded == null)
|
||||
}, [sessionId])
|
||||
const loaded = loadPostImportSession (sessionId, message =>
|
||||
toast ({ title: '取込状態を復元できませんでした', description: message }))
|
||||
setSession (loaded)
|
||||
setMissing (loaded == null)
|
||||
}, [sessionId])
|
||||
|
||||
useEffect (() => {
|
||||
if (sessionId == null || session == null)
|
||||
return
|
||||
useEffect (() => {
|
||||
if (sessionId == null || session == null)
|
||||
return
|
||||
|
||||
savePostImportSession (sessionId, session, message =>
|
||||
toast ({ title: '取込状態を保存できませんでした', description: message }))
|
||||
}, [session, sessionId])
|
||||
savePostImportSession (sessionId, session, message =>
|
||||
toast ({ title: '取込状態を保存できませんでした', description: message }))
|
||||
}, [session, sessionId])
|
||||
|
||||
const rows = session?.rows ?? []
|
||||
const editingSourceRow = Number (searchParams.get ('edit') ?? '')
|
||||
const editingRow =
|
||||
Number.isFinite (editingSourceRow)
|
||||
? rows.find (_1 => _1.sourceRow === editingSourceRow) ?? null
|
||||
: null
|
||||
const counts = useMemo (() => reviewSummaryCounts (rows), [rows])
|
||||
const processable = useMemo (
|
||||
() => processableImportRows (rows),
|
||||
[rows])
|
||||
const creatable = useMemo (
|
||||
() => creatableImportRows (rows),
|
||||
[rows])
|
||||
const reviewRows =
|
||||
session?.repairMode === 'failed'
|
||||
? [...rows].sort ((a, b) => {
|
||||
const rows = session?.rows ?? []
|
||||
const editingSourceRow = Number (searchParams.get ('edit') ?? '')
|
||||
const editingRow =
|
||||
Number.isFinite (editingSourceRow)
|
||||
? rows.find (_1 => _1.sourceRow === editingSourceRow) ?? null
|
||||
: null
|
||||
const counts = useMemo (() => reviewSummaryCounts (rows), [rows])
|
||||
const processable = useMemo (
|
||||
() => processableImportRows (rows),
|
||||
[rows])
|
||||
const creatable = useMemo (
|
||||
() => creatableImportRows (rows),
|
||||
[rows])
|
||||
const reviewRows =
|
||||
session?.repairMode === 'failed'
|
||||
? (
|
||||
[...rows].sort ((a, b) => {
|
||||
const aFailed = a.importStatus === 'failed' ? 0 : 1
|
||||
const bFailed = b.importStatus === 'failed' ? 0 : 1
|
||||
return aFailed - bFailed || a.sourceRow - b.sourceRow
|
||||
})
|
||||
: rows
|
||||
}))
|
||||
: rows
|
||||
|
||||
useEffect (() => {
|
||||
if (editingRow == null || session?.repairMode !== 'failed')
|
||||
return
|
||||
useEffect (() => {
|
||||
if (editingRow == null || session?.repairMode !== 'failed')
|
||||
return
|
||||
|
||||
const element = document.getElementById (`post-import-row-${ editingRow.sourceRow }`)
|
||||
element?.scrollIntoView ({ block: 'center', behavior: 'smooth' })
|
||||
}, [editingRow, session?.repairMode])
|
||||
const element = document.getElementById (`post-import-row-${ editingRow.sourceRow }`)
|
||||
element?.scrollIntoView ({ block: 'center', behavior: 'smooth' })
|
||||
}, [editingRow, session?.repairMode])
|
||||
|
||||
useEffect (() => {
|
||||
if (editingRow == null)
|
||||
{
|
||||
setDialogMessageRow (null)
|
||||
return
|
||||
}
|
||||
if (dialogMessageRow?.sourceRow !== editingRow.sourceRow)
|
||||
setDialogMessageRow (null)
|
||||
}, [editingRow, dialogMessageRow])
|
||||
|
||||
const updateSessionRows = (nextRows: PostImportRow[]) =>
|
||||
setSession (current =>
|
||||
current != null ? { ...current, rows: nextRows } : current)
|
||||
|
||||
const saveDraft = async (
|
||||
{ draft, resetRequested, resetSnapshot }: {
|
||||
draft: Draft
|
||||
resetRequested: boolean
|
||||
resetSnapshot: PostImportRow['resetSnapshot'] },
|
||||
): Promise<boolean> => {
|
||||
if (session == null)
|
||||
return false
|
||||
if (editingRow == null)
|
||||
return false
|
||||
|
||||
const baseRow =
|
||||
resetRequested
|
||||
? {
|
||||
...editingRow,
|
||||
url: resetSnapshot.url,
|
||||
attributes: { ...resetSnapshot.attributes },
|
||||
provenance: { ...resetSnapshot.provenance },
|
||||
tagSources: { ...resetSnapshot.tagSources },
|
||||
fieldWarnings: Object.fromEntries (
|
||||
Object.entries (resetSnapshot.fieldWarnings)
|
||||
.map (([key, values]) => [key, [...values]])),
|
||||
baseWarnings: [...resetSnapshot.baseWarnings],
|
||||
metadataUrl: resetSnapshot.metadataUrl }
|
||||
: editingRow
|
||||
const urlChanged = draft.url !== baseRow.url
|
||||
const nextRow = buildNextEditedRow (baseRow, draft, urlChanged)
|
||||
|
||||
setSavingRow (editingRow.sourceRow)
|
||||
const nextRows = session.rows.map (row =>
|
||||
row.sourceRow === editingRow.sourceRow
|
||||
? nextRow
|
||||
: row)
|
||||
try
|
||||
{
|
||||
const validated = await apiPost<{ rows: PostImportRow[] }> ('/posts/import/validate', {
|
||||
rows: nextRows
|
||||
.filter (row => row.importStatus !== 'created')
|
||||
.map (row => ({
|
||||
sourceRow: row.sourceRow,
|
||||
url: row.url,
|
||||
attributes: row.attributes,
|
||||
provenance: row.provenance,
|
||||
tagSources: row.tagSources,
|
||||
metadataUrl: row.metadataUrl })),
|
||||
changed_row: urlChanged ? editingRow.sourceRow : -1 })
|
||||
const validatedRows = initialisePreviewRows (validated.rows)
|
||||
const target = validatedRows.find (row => row.sourceRow === editingRow.sourceRow)
|
||||
if (target != null && Object.keys (target.validationErrors).length > 0)
|
||||
{
|
||||
setDialogMessageRow (target)
|
||||
return false
|
||||
}
|
||||
updateSessionRows (mergeValidatedImportRows (nextRows, validatedRows))
|
||||
setDialogMessageRow (null)
|
||||
setSearchParams ({ })
|
||||
return true
|
||||
}
|
||||
catch
|
||||
{
|
||||
toast ({ title: '行の再検証に失敗しました' })
|
||||
return false
|
||||
}
|
||||
finally
|
||||
{
|
||||
setSavingRow (null)
|
||||
}
|
||||
}
|
||||
|
||||
const submit = async () => {
|
||||
if (sessionId == null || session == null || processable.length === 0)
|
||||
return
|
||||
|
||||
setLoading (true)
|
||||
try
|
||||
{
|
||||
const validated = await apiPost<{ rows: PostImportRow[] }> ('/posts/import/validate', {
|
||||
rows: session.rows
|
||||
.filter (row => row.importStatus !== 'created')
|
||||
.map (row => ({
|
||||
sourceRow: row.sourceRow,
|
||||
url: row.url,
|
||||
attributes: row.attributes,
|
||||
provenance: row.provenance,
|
||||
tagSources: row.tagSources,
|
||||
metadataUrl: row.metadataUrl })),
|
||||
changed_row: -1 })
|
||||
const validatedRows = initialisePreviewRows (validated.rows)
|
||||
const mergedRows = mergeValidatedImportRows (session.rows, validatedRows)
|
||||
const firstInvalid = mergedRows.find (row => Object.keys (row.validationErrors).length > 0)
|
||||
if (firstInvalid != null)
|
||||
{
|
||||
setSession ({ ...session, rows: mergedRows })
|
||||
setDialogMessageRow (firstInvalid)
|
||||
setSearchParams ({ edit: String (firstInvalid.sourceRow) })
|
||||
return
|
||||
}
|
||||
|
||||
const result = await apiPost<{
|
||||
created: number
|
||||
skipped: number
|
||||
failed: number
|
||||
rows: PostImportResultRow[] }> ('/posts/import', {
|
||||
rows: processableImportRows (mergedRows).map (row => ({
|
||||
sourceRow: row.sourceRow,
|
||||
url: row.url,
|
||||
attributes: row.attributes,
|
||||
provenance: row.provenance,
|
||||
tagSources: row.tagSources,
|
||||
metadataUrl: row.metadataUrl })) })
|
||||
const mergedResults = mergeImportResults (mergedRows, result.rows)
|
||||
const recoverableRows = result.rows.filter (row =>
|
||||
row.status === 'failed'
|
||||
&& row.recoverable
|
||||
&& Object.keys (row.errors ?? { }).length > 0)
|
||||
const nextRows = mergedResults.map (row => {
|
||||
const recoverable = recoverableRows.find (_1 => _1.sourceRow === row.sourceRow)
|
||||
if (recoverable == null)
|
||||
return row
|
||||
return {
|
||||
...row,
|
||||
importStatus: 'pending',
|
||||
validationErrors: recoverable.errors ?? { },
|
||||
importErrors: undefined }
|
||||
})
|
||||
const firstRecoverable = nextRows.find (row =>
|
||||
Object.keys (row.validationErrors).length > 0
|
||||
&& row.importStatus !== 'created')
|
||||
if (firstRecoverable != null)
|
||||
{
|
||||
const repairSession = { ...session,
|
||||
rows: nextRows,
|
||||
repairMode: 'failed' as const }
|
||||
setSession (repairSession)
|
||||
setDialogMessageRow (firstRecoverable)
|
||||
const saved = savePostImportSession (sessionId, repairSession, message =>
|
||||
toast ({ title: '取込状態を保存できませんでした', description: message }))
|
||||
if (saved)
|
||||
setSearchParams ({ edit: String (firstRecoverable.sourceRow) })
|
||||
return
|
||||
}
|
||||
const nextSession = { ...session, rows: nextRows, repairMode: 'all' as const }
|
||||
setSession (nextSession)
|
||||
const saved = savePostImportSession (sessionId, nextSession, message =>
|
||||
toast ({ title: '取込状態を保存できませんでした', description: message }))
|
||||
if (!(saved))
|
||||
return
|
||||
navigate (`/posts/import/${ sessionId }/result`)
|
||||
}
|
||||
catch
|
||||
{
|
||||
toast ({ title: '登録に失敗しました' })
|
||||
}
|
||||
finally
|
||||
{
|
||||
setLoading (false)
|
||||
}
|
||||
}
|
||||
|
||||
if (!(editable))
|
||||
return <Forbidden/>
|
||||
|
||||
if (missing || sessionId == null || session == null)
|
||||
useEffect (() => {
|
||||
if (editingRow == null)
|
||||
{
|
||||
return (
|
||||
<MainArea>
|
||||
<div className="mx-auto max-w-4xl space-y-4 p-4">
|
||||
<PageTitle>投稿インポート</PageTitle>
|
||||
<div className="text-red-700 dark:text-red-300">取込状態が見つかりません.</div>
|
||||
<Button type="button" onClick={() => navigate ('/posts/import')}>
|
||||
URL リスト入力へ戻る
|
||||
</Button>
|
||||
</div>
|
||||
</MainArea>)
|
||||
setDialogMessageRow (null)
|
||||
return
|
||||
}
|
||||
if (dialogMessageRow?.sourceRow !== editingRow.sourceRow)
|
||||
setDialogMessageRow (null)
|
||||
}, [editingRow, dialogMessageRow])
|
||||
|
||||
return (
|
||||
<>
|
||||
<Helmet>
|
||||
<title>{`投稿インポート確認 | ${ SITE_TITLE }`}</title>
|
||||
</Helmet>
|
||||
const updateSessionRows = (nextRows: PostImportRow[]) =>
|
||||
setSession (current =>
|
||||
current != null ? { ...current, rows: nextRows } : current)
|
||||
|
||||
<MainArea className="min-h-0">
|
||||
<div className="mx-auto max-w-6xl space-y-4 p-4">
|
||||
<PageTitle>投稿情報の確認・編輯</PageTitle>
|
||||
const saveDraft = async (
|
||||
{ draft, resetRequested, resetSnapshot }: {
|
||||
draft: Draft
|
||||
resetRequested: boolean
|
||||
resetSnapshot: PostImportRow['resetSnapshot'] },
|
||||
): Promise<boolean> => {
|
||||
if (session == null)
|
||||
return false
|
||||
|
||||
<div className="space-y-3">
|
||||
{reviewRows.map (row => (
|
||||
<div key={row.sourceRow} id={`post-import-row-${ row.sourceRow }`}>
|
||||
<PostImportRowSummary
|
||||
row={row}
|
||||
onEdit={() => {
|
||||
setSearchParams ({ edit: String (row.sourceRow) })
|
||||
}}/>
|
||||
</div>))}
|
||||
</div>
|
||||
if (editingRow == null)
|
||||
return false
|
||||
|
||||
const baseRow =
|
||||
resetRequested
|
||||
? { ...editingRow,
|
||||
url: resetSnapshot.url,
|
||||
attributes: { ...resetSnapshot.attributes },
|
||||
provenance: { ...resetSnapshot.provenance },
|
||||
tagSources: { ...resetSnapshot.tagSources },
|
||||
fieldWarnings: Object.fromEntries (
|
||||
Object.entries (resetSnapshot.fieldWarnings)
|
||||
.map (([key, values]) => [key, [...values]])),
|
||||
baseWarnings: [...resetSnapshot.baseWarnings],
|
||||
metadataUrl: resetSnapshot.metadataUrl }
|
||||
: editingRow
|
||||
const urlChanged = draft.url !== baseRow.url
|
||||
const nextRow = buildNextEditedRow (baseRow, draft, urlChanged)
|
||||
|
||||
setSavingRow (editingRow.sourceRow)
|
||||
const nextRows = session.rows.map (row =>
|
||||
row.sourceRow === editingRow.sourceRow
|
||||
? nextRow
|
||||
: row)
|
||||
try
|
||||
{
|
||||
const validated = await apiPost<{ rows: PostImportRow[] }> ('/posts/import/validate', {
|
||||
rows:
|
||||
nextRows
|
||||
.filter (row => row.importStatus !== 'created')
|
||||
.map (row => ({ sourceRow: row.sourceRow,
|
||||
url: row.url,
|
||||
attributes: row.attributes,
|
||||
provenance: row.provenance,
|
||||
tagSources: row.tagSources,
|
||||
metadataUrl: row.metadataUrl })),
|
||||
changed_row: urlChanged ? editingRow.sourceRow : -1 })
|
||||
const validatedRows = initialisePreviewRows (validated.rows)
|
||||
const target = validatedRows.find (row => row.sourceRow === editingRow.sourceRow)
|
||||
if (target != null && Object.keys (target.validationErrors).length > 0)
|
||||
{
|
||||
setDialogMessageRow (target)
|
||||
return false
|
||||
}
|
||||
updateSessionRows (mergeValidatedImportRows (nextRows, validatedRows))
|
||||
setDialogMessageRow (null)
|
||||
setSearchParams ({ })
|
||||
return true
|
||||
}
|
||||
catch
|
||||
{
|
||||
toast ({ title: '行の再検証に失敗しました' })
|
||||
return false
|
||||
}
|
||||
finally
|
||||
{
|
||||
setSavingRow (null)
|
||||
}
|
||||
}
|
||||
|
||||
const submit = async () => {
|
||||
if (sessionId == null || session == null || processable.length === 0)
|
||||
return
|
||||
|
||||
setLoading (true)
|
||||
try
|
||||
{
|
||||
const validated = await apiPost<{ rows: PostImportRow[] }> ('/posts/import/validate', {
|
||||
rows:
|
||||
session.rows
|
||||
.filter (row => row.importStatus !== 'created')
|
||||
.map (row => ({ sourceRow: row.sourceRow,
|
||||
url: row.url,
|
||||
attributes: row.attributes,
|
||||
provenance: row.provenance,
|
||||
tagSources: row.tagSources,
|
||||
metadataUrl: row.metadataUrl })),
|
||||
changed_row: -1 })
|
||||
const validatedRows = initialisePreviewRows (validated.rows)
|
||||
const mergedRows = mergeValidatedImportRows (session.rows, validatedRows)
|
||||
const firstInvalid = mergedRows.find (row => Object.keys (row.validationErrors).length > 0)
|
||||
if (firstInvalid != null)
|
||||
{
|
||||
setSession ({ ...session, rows: mergedRows })
|
||||
setDialogMessageRow (firstInvalid)
|
||||
setSearchParams ({ edit: String (firstInvalid.sourceRow) })
|
||||
return
|
||||
}
|
||||
|
||||
const result = await apiPost<{
|
||||
created: number
|
||||
skipped: number
|
||||
failed: number
|
||||
rows: PostImportResultRow[] }> ('/posts/import', {
|
||||
rows: processableImportRows (mergedRows).map (row => ({
|
||||
sourceRow: row.sourceRow,
|
||||
url: row.url,
|
||||
attributes: row.attributes,
|
||||
provenance: row.provenance,
|
||||
tagSources: row.tagSources,
|
||||
metadataUrl: row.metadataUrl })) })
|
||||
const mergedResults = mergeImportResults (mergedRows, result.rows)
|
||||
const recoverableRows = result.rows.filter (row =>
|
||||
row.status === 'failed'
|
||||
&& row.recoverable
|
||||
&& Object.keys (row.errors ?? { }).length > 0)
|
||||
const nextRows = mergedResults.map (row => {
|
||||
const recoverable = recoverableRows.find (rr => rr.sourceRow === row.sourceRow)
|
||||
if (recoverable == null)
|
||||
return row
|
||||
return {
|
||||
...row,
|
||||
importStatus: 'pending',
|
||||
validationErrors: recoverable.errors ?? { },
|
||||
importErrors: undefined }
|
||||
})
|
||||
const firstRecoverable = nextRows.find (row =>
|
||||
Object.keys (row.validationErrors).length > 0
|
||||
&& row.importStatus !== 'created')
|
||||
if (firstRecoverable != null)
|
||||
{
|
||||
const repairSession = { ...session,
|
||||
rows: nextRows,
|
||||
repairMode: 'failed' as const }
|
||||
setSession (repairSession)
|
||||
setDialogMessageRow (firstRecoverable)
|
||||
const saved = savePostImportSession (sessionId, repairSession, message =>
|
||||
toast ({ title: '取込状態を保存できませんでした', description: message }))
|
||||
if (saved)
|
||||
setSearchParams ({ edit: String (firstRecoverable.sourceRow) })
|
||||
return
|
||||
}
|
||||
const nextSession = { ...session, rows: nextRows, repairMode: 'all' as const }
|
||||
setSession (nextSession)
|
||||
const saved = savePostImportSession (sessionId, nextSession, message =>
|
||||
toast ({ title: '取込状態を保存できませんでした', description: message }))
|
||||
if (!(saved))
|
||||
return
|
||||
navigate (`/posts/import/${ sessionId }/result`)
|
||||
}
|
||||
catch
|
||||
{
|
||||
toast ({ title: '登録に失敗しました' })
|
||||
}
|
||||
finally
|
||||
{
|
||||
setLoading (false)
|
||||
}
|
||||
}
|
||||
|
||||
if (!(editable))
|
||||
return <Forbidden/>
|
||||
|
||||
if (missing || sessionId == null || session == null)
|
||||
{
|
||||
return (
|
||||
<MainArea>
|
||||
<div className="mx-auto max-w-4xl space-y-4 p-4">
|
||||
<PageTitle>投稿インポート</PageTitle>
|
||||
<div className="text-red-700 dark:text-red-300">取込状態が見つかりません.</div>
|
||||
<Button type="button" onClick={() => navigate ('/posts/import')}>
|
||||
URL リスト入力へ戻る
|
||||
</Button>
|
||||
</div>
|
||||
</MainArea>
|
||||
</MainArea>)
|
||||
}
|
||||
|
||||
<PostImportFooter
|
||||
loading={loading}
|
||||
processableCount={processable.length}
|
||||
creatableCount={creatable.length}
|
||||
skipPlannedCount={counts.skipPlanned}
|
||||
onBack={() => navigate ('/posts/import')}
|
||||
onSubmit={submit}/>
|
||||
return (
|
||||
<>
|
||||
<Helmet>
|
||||
<title>{`投稿インポート確認 | ${ SITE_TITLE }`}</title>
|
||||
</Helmet>
|
||||
|
||||
<PostImportRowDialog
|
||||
open={editingRow != null}
|
||||
row={editingRow}
|
||||
messageRow={dialogMessageRow}
|
||||
saving={savingRow != null}
|
||||
onOpenChange={open => {
|
||||
if (!open)
|
||||
setSearchParams ({ })
|
||||
}}
|
||||
onSave={saveDraft}/>
|
||||
</>)
|
||||
<MainArea className="min-h-0">
|
||||
<div className="mx-auto max-w-6xl space-y-4 p-4">
|
||||
<PageTitle>投稿情報の確認・編輯</PageTitle>
|
||||
|
||||
<div className="space-y-3">
|
||||
{reviewRows.map (row => (
|
||||
<div key={row.sourceRow} id={`post-import-row-${ row.sourceRow }`}>
|
||||
<PostImportRowSummary
|
||||
row={row}
|
||||
onEdit={() => {
|
||||
setSearchParams ({ edit: String (row.sourceRow) })
|
||||
}}/>
|
||||
</div>))}
|
||||
</div>
|
||||
</div>
|
||||
</MainArea>
|
||||
|
||||
<PostImportFooter
|
||||
loading={loading}
|
||||
processableCount={processable.length}
|
||||
creatableCount={creatable.length}
|
||||
skipPlannedCount={counts.skipPlanned}
|
||||
onBack={() => navigate ('/posts/import')}
|
||||
onSubmit={submit}/>
|
||||
|
||||
<PostImportRowDialog
|
||||
open={editingRow != null}
|
||||
row={editingRow}
|
||||
messageRow={dialogMessageRow}
|
||||
saving={savingRow != null}
|
||||
onOpenChange={open => {
|
||||
if (!open)
|
||||
setSearchParams ({ })
|
||||
}}
|
||||
onSave={saveDraft}/>
|
||||
</>)
|
||||
}
|
||||
|
||||
const PostImportFooter = (
|
||||
@@ -343,13 +342,12 @@ const PostImportFooter = (
|
||||
creatableCount,
|
||||
skipPlannedCount,
|
||||
onBack,
|
||||
onSubmit }: {
|
||||
loading: boolean
|
||||
processableCount: number
|
||||
creatableCount: number
|
||||
skipPlannedCount: number
|
||||
onBack: () => void
|
||||
onSubmit: () => void },
|
||||
onSubmit }: { loading: boolean
|
||||
processableCount: number
|
||||
creatableCount: number
|
||||
skipPlannedCount: number
|
||||
onBack: () => void
|
||||
onSubmit: () => void },
|
||||
) => (
|
||||
<div
|
||||
className="shrink-0 border-t bg-white/95 p-4 backdrop-blur
|
||||
|
||||
@@ -20,12 +20,12 @@ import { countImportSourceLines,
|
||||
loadPostImportSourceDraft,
|
||||
savePostImportSession,
|
||||
savePostImportSourceDraft,
|
||||
validateImportSource,
|
||||
type PostImportRow } from '@/lib/postImportSession'
|
||||
validateImportSource } from '@/lib/postImportSession'
|
||||
import Forbidden from '@/pages/Forbidden'
|
||||
|
||||
import type { FC } from 'react'
|
||||
|
||||
import type { PostImportRow } from '@/lib/postImportSeession'
|
||||
import type { User } from '@/types'
|
||||
|
||||
type Props = { user: User | null }
|
||||
@@ -35,177 +35,176 @@ const SOURCE_ERROR_ID = 'post-import-source-error'
|
||||
const SOURCE_ISSUES_ID = 'post-import-source-issues'
|
||||
|
||||
const urlIssuesFromRows = (rows: PostImportRow[], source: string) => {
|
||||
const sourceLines = source.split (/\r\n|\n|\r/)
|
||||
const sourceLines = source.split (/\r\n|\n|\r/)
|
||||
|
||||
return rows.flatMap (row =>
|
||||
(row.validationErrors.url ?? []).map (message => ({
|
||||
sourceRow: row.sourceRow,
|
||||
message,
|
||||
url: sourceLines[row.sourceRow - 1]?.trim () ?? row.url })))
|
||||
return rows.flatMap (row =>
|
||||
(row.validationErrors.url ?? []).map (message => ({
|
||||
sourceRow: row.sourceRow,
|
||||
message,
|
||||
url: sourceLines[row.sourceRow - 1]?.trim () ?? row.url })))
|
||||
}
|
||||
|
||||
|
||||
const PostImportSourcePage: FC<Props> = ({ user }) => {
|
||||
const editable = canEditContent (user)
|
||||
const navigate = useNavigate ()
|
||||
const [source, setSource] = useState ('')
|
||||
const [loading, setLoading] = useState (false)
|
||||
const [sourceIssues, setSourceIssues] = useState<ReturnType<typeof validateImportSource>> ([])
|
||||
const [sourceError, setSourceError] = useState<string | null> (null)
|
||||
const saveTimer = useRef<number | null> (null)
|
||||
const editedRef = useRef (false)
|
||||
const editable = canEditContent (user)
|
||||
const navigate = useNavigate ()
|
||||
const [source, setSource] = useState ('')
|
||||
const [loading, setLoading] = useState (false)
|
||||
const [sourceIssues, setSourceIssues] = useState<ReturnType<typeof validateImportSource>> ([])
|
||||
const [sourceError, setSourceError] = useState<string | null> (null)
|
||||
const saveTimer = useRef<number | null> (null)
|
||||
const editedRef = useRef (false)
|
||||
|
||||
const lineCount = countImportSourceLines (source)
|
||||
const messages = sourceError != null ? [sourceError] : []
|
||||
const sourceDescribedBy = [
|
||||
sourceError != null ? SOURCE_ERROR_ID : null,
|
||||
sourceIssues.length > 0 ? SOURCE_ISSUES_ID : null]
|
||||
.filter (_1 => _1 != null)
|
||||
.join (' ')
|
||||
const lineCount = countImportSourceLines (source)
|
||||
const messages = sourceError != null ? [sourceError] : []
|
||||
const sourceDescribedBy =
|
||||
[sourceError != null ? SOURCE_ERROR_ID : null,
|
||||
sourceIssues.length > 0 ? SOURCE_ISSUES_ID : null]
|
||||
.filter (_1 => _1 != null)
|
||||
.join (' ')
|
||||
|
||||
useEffect (() => {
|
||||
cleanupExpiredPostImportSessions (message =>
|
||||
toast ({ title: '保存済みデータを整理できませんでした', description: message }))
|
||||
useEffect (() => {
|
||||
cleanupExpiredPostImportSessions (message =>
|
||||
toast ({ title: '保存済みデータを整理できませんでした', description: message }))
|
||||
|
||||
const draft = loadPostImportSourceDraft (message =>
|
||||
toast ({ title: '保存済み入力を復元できませんでした', description: message }))
|
||||
if (!(editedRef.current))
|
||||
{
|
||||
setSource (current => current === '' ? draft.source : current)
|
||||
}
|
||||
}, [])
|
||||
const draft = loadPostImportSourceDraft (message =>
|
||||
toast ({ title: '保存済み入力を復元できませんでした', description: message }))
|
||||
|
||||
useEffect (() => {
|
||||
if (saveTimer.current != null)
|
||||
window.clearTimeout (saveTimer.current)
|
||||
saveTimer.current = window.setTimeout (() => {
|
||||
savePostImportSourceDraft (source, message =>
|
||||
toast ({ title: '入力内容を保存できませんでした', description: message }))
|
||||
}, 300)
|
||||
return () => {
|
||||
if (saveTimer.current != null)
|
||||
window.clearTimeout (saveTimer.current)
|
||||
}
|
||||
}, [source])
|
||||
if (!(editedRef.current))
|
||||
setSource (current => current === '' ? draft.source : current)
|
||||
}, [])
|
||||
|
||||
const preview = async () => {
|
||||
if (lineCount === 0)
|
||||
{
|
||||
setSourceIssues ([])
|
||||
setSourceError ('URL を入力してください.')
|
||||
return
|
||||
}
|
||||
useEffect (() => {
|
||||
if (saveTimer.current != null)
|
||||
window.clearTimeout (saveTimer.current)
|
||||
|
||||
const issues = validateImportSource (source)
|
||||
if (issues.length > 0)
|
||||
{
|
||||
setSourceIssues (issues)
|
||||
setSourceError (null)
|
||||
return
|
||||
}
|
||||
saveTimer.current = window.setTimeout (() => {
|
||||
savePostImportSourceDraft (source, message =>
|
||||
toast ({ title: '入力内容を保存できませんでした', description: message }))
|
||||
}, 300)
|
||||
|
||||
setLoading (true)
|
||||
setSourceIssues ([])
|
||||
setSourceError (null)
|
||||
try
|
||||
{
|
||||
const data = await apiPost<{ rows: PostImportRow[] }> ('/posts/import/preview', {
|
||||
source })
|
||||
const urlIssues = urlIssuesFromRows (data.rows, source)
|
||||
if (urlIssues.length > 0)
|
||||
{
|
||||
setSourceIssues (urlIssues)
|
||||
return
|
||||
}
|
||||
const sessionId = createPostImportSessionId ()
|
||||
const saved = savePostImportSession (sessionId, {
|
||||
source,
|
||||
rows: initialisePreviewRows (data.rows),
|
||||
repairMode: 'all' }, message =>
|
||||
toast ({ title: '取込状態を保存できませんでした', description: message }))
|
||||
if (!(saved))
|
||||
return
|
||||
navigate (`/posts/import/${ sessionId }/review`)
|
||||
}
|
||||
catch (requestError)
|
||||
{
|
||||
const message =
|
||||
isApiError<{ message?: string, baseErrors?: string[] }> (requestError)
|
||||
? requestError.response?.data?.message
|
||||
?? requestError.response?.data?.baseErrors?.[0]
|
||||
: undefined
|
||||
setSourceError (message ?? '入力を確認してください.')
|
||||
toast ({
|
||||
title: '投稿情報の取得に失敗しました',
|
||||
description: message ?? '入力を確認してください.' })
|
||||
}
|
||||
finally
|
||||
{
|
||||
setLoading (false)
|
||||
}
|
||||
return () => {
|
||||
if (saveTimer.current != null)
|
||||
window.clearTimeout (saveTimer.current)
|
||||
}
|
||||
}, [source])
|
||||
|
||||
if (!(editable))
|
||||
return <Forbidden/>
|
||||
const preview = async () => {
|
||||
if (lineCount === 0)
|
||||
{
|
||||
setSourceIssues ([])
|
||||
setSourceError ('URL を入力してください.')
|
||||
return
|
||||
}
|
||||
|
||||
return (
|
||||
<MainArea>
|
||||
<Helmet>
|
||||
<title>{`投稿インポート | ${ SITE_TITLE }`}</title>
|
||||
</Helmet>
|
||||
const issues = validateImportSource (source)
|
||||
if (issues.length > 0)
|
||||
{
|
||||
setSourceIssues (issues)
|
||||
setSourceError (null)
|
||||
return
|
||||
}
|
||||
|
||||
<Form className="max-w-4xl">
|
||||
<PageTitle>投稿インポート</PageTitle>
|
||||
<FormField label="URL リスト">
|
||||
{() => (
|
||||
<textarea
|
||||
value={source}
|
||||
rows={14}
|
||||
aria-invalid={messages.length > 0 || sourceIssues.length > 0}
|
||||
aria-describedby={sourceDescribedBy || undefined}
|
||||
className={inputClass (
|
||||
messages.length > 0 || sourceIssues.length > 0,
|
||||
'font-mono text-sm')}
|
||||
onBlur={() => {
|
||||
savePostImportSourceDraft (source, message =>
|
||||
toast ({
|
||||
title: '入力内容を保存できませんでした',
|
||||
description: message }))
|
||||
}}
|
||||
onChange={ev => {
|
||||
editedRef.current = true
|
||||
setSource (ev.target.value)
|
||||
setSourceError (null)
|
||||
setSourceIssues ([])
|
||||
}}/>)}
|
||||
</FormField>
|
||||
<div id={messages.length > 0 ? SOURCE_ERROR_ID : undefined}>
|
||||
<FieldError messages={messages}/>
|
||||
setLoading (true)
|
||||
setSourceIssues ([])
|
||||
setSourceError (null)
|
||||
try
|
||||
{
|
||||
const data = await apiPost<{ rows: PostImportRow[] }> ('/posts/import/preview', { source })
|
||||
const urlIssues = urlIssuesFromRows (data.rows, source)
|
||||
if (urlIssues.length > 0)
|
||||
{
|
||||
setSourceIssues (urlIssues)
|
||||
return
|
||||
}
|
||||
const sessionId = createPostImportSessionId ()
|
||||
const saved = savePostImportSession (
|
||||
sessionId,
|
||||
{ source,
|
||||
rows: initialisePreviewRows (data.rows),
|
||||
repairMode: 'all' },
|
||||
message => toast ({ title: '取込状態を保存できませんでした', description: message }))
|
||||
if (!(saved))
|
||||
return
|
||||
navigate (`/posts/import/${ sessionId }/review`)
|
||||
}
|
||||
catch (requestError)
|
||||
{
|
||||
const message =
|
||||
isApiError<{ message?: string, baseErrors?: string[] }> (requestError)
|
||||
? (requestError.response?.data?.message
|
||||
?? requestError.response?.data?.baseErrors?.[0])
|
||||
: undefined
|
||||
setSourceError (message ?? '入力を確認してください.')
|
||||
toast ({ title: '投稿情報の取得に失敗しました',
|
||||
description: message ?? '入力を確認してください.' })
|
||||
}
|
||||
finally
|
||||
{
|
||||
setLoading (false)
|
||||
}
|
||||
}
|
||||
|
||||
if (!(editable))
|
||||
return <Forbidden/>
|
||||
|
||||
return (
|
||||
<MainArea>
|
||||
<Helmet>
|
||||
<title>{`投稿インポート | ${ SITE_TITLE }`}</title>
|
||||
</Helmet>
|
||||
|
||||
<Form className="max-w-4xl">
|
||||
<PageTitle>投稿インポート</PageTitle>
|
||||
<FormField label="URL リスト">
|
||||
{() => (
|
||||
<textarea
|
||||
value={source}
|
||||
rows={14}
|
||||
aria-invalid={messages.length > 0 || sourceIssues.length > 0}
|
||||
aria-describedby={sourceDescribedBy || undefined}
|
||||
className={inputClass (
|
||||
messages.length > 0 || sourceIssues.length > 0,
|
||||
'font-mono text-sm')}
|
||||
onBlur={() => {
|
||||
savePostImportSourceDraft (source, message =>
|
||||
toast ({ title: '入力内容を保存できませんでした',
|
||||
description: message }))
|
||||
}}
|
||||
onChange={ev => {
|
||||
editedRef.current = true
|
||||
setSource (ev.target.value)
|
||||
setSourceError (null)
|
||||
setSourceIssues ([])
|
||||
}}/>)}
|
||||
</FormField>
|
||||
<div id={messages.length > 0 ? SOURCE_ERROR_ID : undefined}>
|
||||
<FieldError messages={messages}/>
|
||||
</div>
|
||||
<ul
|
||||
id={SOURCE_ISSUES_ID}
|
||||
className="space-y-2 text-sm text-red-700 dark:text-red-300">
|
||||
{sourceIssues.map (issue => (
|
||||
<li key={`${ issue.sourceRow }-${ issue.message }-${ issue.url }`}>
|
||||
<div>{issue.sourceRow} 行目: {issue.message}</div>
|
||||
<div className="break-all font-mono text-xs">{issue.url}</div>
|
||||
</li>))}
|
||||
</ul>
|
||||
|
||||
<div className="flex items-center justify-between gap-3">
|
||||
<div className="text-sm text-neutral-600 dark:text-neutral-300">
|
||||
入力行数 {lineCount} / {MAX_ROWS}
|
||||
</div>
|
||||
<ul
|
||||
id={SOURCE_ISSUES_ID}
|
||||
className="space-y-2 text-sm text-red-700 dark:text-red-300">
|
||||
{sourceIssues.map (issue => (
|
||||
<li key={`${ issue.sourceRow }-${ issue.message }-${ issue.url }`}>
|
||||
<div>{issue.sourceRow} 行目: {issue.message}</div>
|
||||
<div className="break-all font-mono text-xs">{issue.url}</div>
|
||||
</li>))}
|
||||
</ul>
|
||||
|
||||
<div className="flex items-center justify-between gap-3">
|
||||
<div className="text-sm text-neutral-600 dark:text-neutral-300">
|
||||
入力行数 {lineCount} / {MAX_ROWS}
|
||||
</div>
|
||||
<Button
|
||||
type="button"
|
||||
className="shrink-0"
|
||||
onClick={preview}
|
||||
disabled={loading}>
|
||||
次へ
|
||||
</Button>
|
||||
</div>
|
||||
</Form>
|
||||
</MainArea>)
|
||||
<Button
|
||||
type="button"
|
||||
className="shrink-0"
|
||||
onClick={preview}
|
||||
disabled={loading}>
|
||||
次へ
|
||||
</Button>
|
||||
</div>
|
||||
</Form>
|
||||
</MainArea>)
|
||||
}
|
||||
|
||||
export default PostImportSourcePage
|
||||
|
||||
新しい課題から参照
ユーザをブロックする