開発環境では、**DB を壊さない前提で、migration → API → 画面 → 同期 → ZIP → 履歴**の順に見るのがよいです。今回の差分は素材管理全体に触っているので、単体でチョンチョン見るより、素材の一生を通すのが早いです。
## 0. 先に方針
**やらないこと:**
```sh id="snb3i6"
rails db:drop
rails db:reset
rails db:setup
DISABLE_DATABASE_ENVIRONMENT_CHECK=1 ...
```
これは禁止。
開発 DB に本番データを入れているなら、床板を剥がして耐震確認するようなものです。
---
## 1. migration 確認
まず現在の状態を見る。
```sh id="qsdfpt"
cd backend
RAILS_ENV=development bundle exec rails db:migrate:status
```
その後、通常 migration。
```sh id="a89fir"
RAILS_ENV=development bundle exec rails db:migrate
```
見るポイント:
```txt id="c1u57a"
materials に source_* / normalized_source_key / version_no がある
material_versions に event_type / file snapshot / source snapshot がある
material_export_items がある
material_sync_suppressions がある
material_sync_sources がある
既存 materials に material_versions version_no=1 create が backfill されている
```
確認用:
```sh id="g4vd4m"
RAILS_ENV=development bundle exec rails runner '
puts "materials=#{Material.count}"
puts "versions=#{MaterialVersion.count}"
puts "materials without versions=#{Material.left_joins(:material_versions).where(material_versions: { id: nil }).count}"
puts "sync suppressions table=#{ActiveRecord::Base.connection.table_exists?(:material_sync_suppressions)}"
'
```
ここで `materials without versions=0` になれば、backfill は通っています。
---
## 2. 既存素材一覧の画面確認
フロントを起動して `/materials` を見る。
```sh id="vl28jd"
cd frontend
npm run dev
```
見る観点:
```txt id="i2ovxw"
初期表示で素材が出る
初期表示ではグルーピングがオフ
タグなし素材も出る
カード表示でサムネまたは代替テキストが出る
一覧表示に切り替えられる
q / tag_state / media_kind / sort / direction が効く
```
ここでまず、普通の素材一覧が壊れていないことを確認します。
---
## 3. 左タグバーの確認
`/materials` を開いて左タグバーからタグを選ぶ。
見る観点:
```txt id="n6udul"
URL が tag_id=...&include_descendants=1&group_by=parent_tag になる
選択中タグが左バーで強調される
一覧上部に「選択中」の表示が出る
「タグ選択を解除」で通常表示に戻れる
解除後、tag_id / include_descendants / group_by / page が消える
子タグ・孫タグの素材も一覧に出る
親タググルーピングされる
```
特に重要なのはこれ。
```txt id="d33os0"
親タグ A を選択
A に直接紐づく素材
A > B に紐づく素材
A > B > C に紐づく素材
が同じ一覧に出ること
```
---
## 4. 選択タグから素材追加
左タグからタグを選択した状態で、一覧上部の **このタグに素材を追加** を押す。
見る観点:
```txt id="qdd5uw"
素材追加画面の tag 欄に選択中タグ名が初期入力されている
file または url を指定して保存できる
保存後 return_to で元のタグ選択済み一覧に戻る
戻った一覧に追加した素材が出る
material_versions に create が 1 件できる
```
Rails console でも確認できます。
```sh id="i07rrb"
RAILS_ENV=development bundle exec rails runner '
m = Material.order(id: :desc).first
puts({ id: m.id, tag: m.tag&.name, versions: m.material_versions.count, version_no: m.version_no }.inspect)
'
```
---
## 5. グループ見出しから素材追加
親タググルーピング表示中に、各グループ見出しの **このタグに素材を追加** を押す。
見る観点:
```txt id="fpx8w4"
グループタグ名が tag 欄に初期入力される
保存後、元の一覧に戻る
追加素材がそのグループ内に出る
```
ここは今回の導線の肝です。棚の見出しから直接その棚へ素材を置けるかを見る。
---
## 6. 素材更新と履歴
既存素材の詳細または編集導線から、タグ・URL・ファイル・export path を更新する。
見る観点:
```txt id="w36i61"
更新前 snapshot が無ければ create が補われる
更新後 update version ができる
file_blob_id / file_filename / file_sha256 が material_versions に入る
export_paths_json が履歴に残る
/materials/changes または /materials/versions で履歴が見える
```
console:
```sh id="a3okhv"
RAILS_ENV=development bundle exec rails runner '
m = Material.order(updated_at: :desc).first
puts m.material_versions.order(:version_no).map { |v|
[v.version_no, v.event_type, v.tag_name, v.file_filename, v.file_sha256, v.export_paths_hash]
}.inspect
'
```
---
## 7. サムネイル
画像素材を追加して、一覧にサムネイルが出るか確認。
動画素材があるなら、`ffmpeg` が入っている環境で backfill。
```sh id="qxm8fj"
cd backend
RAILS_ENV=development bundle exec rails materials:thumbnails:backfill
```
見る観点:
```txt id="s9a1vf"
画像は 180x180 のサムネが付く
動画はフレームからサムネが作られる
非対応ファイルは代替テキスト表示になる
ログに result が出る
```
---
## 8. ZIP export
export path がある素材を用意して、ブラウザで確認。
```txt id="aq7f7o"
/materials/download.zip?profile=legacy_drive
```
見る観点:
```txt id="h4rve5"
ZIP が落ちる
entry path が material_export_items.export_path になる
disabled な export item は入らない
ファイル実体が欠けている場合は 422 と missing_files が返る
```
---
## 9. 抑止
`/materials/suppressions` で path prefix 抑止を追加する。
見る観点:
```txt id="w80jbu"
member で作成できる
guest は forbidden / unauthorized
google_drive_path_prefix で既存素材が discard される
discard 履歴が material_versions に残る
同期時に同じ source_path 配下が再作成されない
```
---
## 10. Google Drive 同期
開発環境では、まず小さいフォルダでやるのがよいです。
いきなり本番素材集フォルダを食わせると、ログが藪になります 🌿
必要な ENV:
```sh id="kzbb7f"
GOOGLE_DRIVE_SERVICE_ACCOUNT_EMAIL=...
GOOGLE_DRIVE_PRIVATE_KEY_PATH=...
MATERIAL_SYNC_SOURCE_KIND=google_drive_path
MATERIAL_SYNC_SOURCE_FILE_ID=<folder_id>
MATERIAL_SYNC_SOURCE_NAME=dev-small-folder
MATERIAL_SYNC_SOURCE_PROFILE=legacy_drive
```
seed で source 作成、または console で作成。
```sh id="sec40c"
RAILS_ENV=development bundle exec rails db:seed
RAILS_ENV=development bundle exec rails materials:sync
```
見る観点:
```txt id="a5ltqu"
imported / updated / unchanged / suppressed / failed がログに出る
2 回目実行で unchanged が増える
tag は nil のままでも保存できる
人手で tag / url を付けた既存同期素材が、再同期で消えない
Google native file は skip される
download 後 sha256 block が効く
```
---
## 11. schema.rb は別途確認
これはテストというより merge gate です。
今回まだ怪しいので、差分に以下が混ざっていないことを確認します。
```txt id="s3k6da"
wiki_assets 削除
wiki_pages.next_asset_no 削除
素材管理と無関係な CHECK constraint 削除
素材管理と無関係な index order 消失
```
ここが残るなら、機能テストが通っても merge は止めた方がいいです。
---
## 最小テスト順
時間がないなら、この順で十分です。
```txt id="c1k2pw"
1. db:migrate
2. materials without versions = 0 を確認
3. /materials 初期表示
4. 左タグ選択 → 子孫込み表示 → グルーピング
5. タグ選択解除
6. 選択タグから素材追加 → return_to で戻る
7. グループ見出しから素材追加
8. 更新して material_versions を確認
9. ZIP export
10. 小さい Drive folder で materials:sync を 2 回
```
これで、今回の差分の主要な導線はほぼ踏めます。
Reviewed-on: #381
Co-authored-by: miteruzo <miteruzo@naver.com>
Co-committed-by: miteruzo <miteruzo@naver.com>
このコミットはPull リクエスト #381 でマージされました.
このコミットが含まれているのは:
@@ -238,8 +238,7 @@ const createGameSeed = (): string => {
|
||||
|
||||
const normalizeStoredQuestionId = (
|
||||
questionId: string,
|
||||
condition?: GekanatorQuestionCondition,
|
||||
): string => {
|
||||
condition?: GekanatorQuestionCondition): string => {
|
||||
if (condition?.type === 'title-length-greater-than')
|
||||
return `title:length-at-least:${ condition.length + 1 }`
|
||||
|
||||
@@ -312,8 +311,7 @@ const sourcePriorityForMerge = (question: GekanatorQuestion): number => {
|
||||
|
||||
const shouldReplaceMergedQuestion = (
|
||||
current: GekanatorQuestion | undefined,
|
||||
candidate: GekanatorQuestion,
|
||||
): boolean => {
|
||||
candidate: GekanatorQuestion): boolean => {
|
||||
if (!(current))
|
||||
return true
|
||||
|
||||
@@ -408,8 +406,7 @@ const loadRecentGames = (): RecentGameSummary[] => {
|
||||
|
||||
|
||||
const storeRecentGameSummary = (
|
||||
summary: RecentGameSummary,
|
||||
): RecentGameSummary[] => {
|
||||
summary: RecentGameSummary): RecentGameSummary[] => {
|
||||
const next =
|
||||
[summary,
|
||||
...loadRecentGames ().filter (item => (item.savedAt !== summary.savedAt
|
||||
@@ -459,8 +456,7 @@ const resettableExtraQuestionState = (): {
|
||||
|
||||
const recoveredCandidateMapFromStored = (
|
||||
items: RecoveredCandidatePost[],
|
||||
scores: [number, number][],
|
||||
): Map<number, RecoveredCandidateState> => {
|
||||
scores: [number, number][]): Map<number, RecoveredCandidateState> => {
|
||||
const storedScores = new Map (scores)
|
||||
|
||||
return new Map (items.map (item => [item.postId, {
|
||||
@@ -470,8 +466,7 @@ const recoveredCandidateMapFromStored = (
|
||||
|
||||
|
||||
const storedRecoveredCandidatesFromMap = (
|
||||
recoveredCandidatePosts: Map<number, RecoveredCandidateState>,
|
||||
): RecoveredCandidatePost[] =>
|
||||
recoveredCandidatePosts: Map<number, RecoveredCandidateState>): RecoveredCandidatePost[] =>
|
||||
[...recoveredCandidatePosts.entries ()]
|
||||
.map (([postId, recoveredCandidate]) => ({
|
||||
postId,
|
||||
@@ -513,8 +508,7 @@ const distributionEntropy = (weights: number[]): number =>
|
||||
const questionCategoryPenalty = (
|
||||
question: GekanatorQuestion,
|
||||
answerCount: number,
|
||||
repeatPenalty: number,
|
||||
): number => {
|
||||
repeatPenalty: number): number => {
|
||||
const earlyFactor = Math.max (0, (3 - answerCount) / 3)
|
||||
const titleLengthPenalty = (() => {
|
||||
if (titleLengthMinimumForCondition (question.condition) == null)
|
||||
@@ -553,8 +547,7 @@ const relatedPostIdsOf = (post: Post): number[] => {
|
||||
|
||||
const userPriorWeightsFor = (
|
||||
posts: Post[],
|
||||
recentGames: RecentGameSummary[],
|
||||
): Map<number, number> => {
|
||||
recentGames: RecentGameSummary[]): Map<number, number> => {
|
||||
const postById = new Map (posts.map (post => [post.id, post]))
|
||||
const weights = new Map<number, number> ()
|
||||
const addWeight = (postId: number, weight: number) => {
|
||||
@@ -581,14 +574,12 @@ const userPriorWeightsFor = (
|
||||
|
||||
const answerWeightFor = (
|
||||
questionId: string,
|
||||
softenedQuestionIds: Set<string>,
|
||||
): number => softenedQuestionIds.has (questionId) ? softenedAnswerWeight : 1
|
||||
softenedQuestionIds: Set<string>): number => softenedQuestionIds.has (questionId) ? softenedAnswerWeight : 1
|
||||
|
||||
|
||||
const scoreWeightForAnswer = (
|
||||
answer: GekanatorAnswerLog,
|
||||
softenedQuestionIds: Set<string>,
|
||||
): number =>
|
||||
softenedQuestionIds: Set<string>): number =>
|
||||
answerWeightFor (answer.questionId, softenedQuestionIds)
|
||||
* (
|
||||
answer.questionPurpose === 'learning_user_suggested'
|
||||
@@ -638,8 +629,7 @@ const titleTermPattern =
|
||||
const addPostIdToIndex = <K extends string | number> (
|
||||
index: Map<K, Set<number>>,
|
||||
key: K,
|
||||
postId: number,
|
||||
) => {
|
||||
postId: number) => {
|
||||
const current = index.get (key)
|
||||
if (current)
|
||||
{
|
||||
@@ -652,8 +642,7 @@ const addPostIdToIndex = <K extends string | number> (
|
||||
|
||||
|
||||
const buildMaterialIndex = (
|
||||
posts: Post[],
|
||||
): GekanatorQuestionMaterialIndex => {
|
||||
posts: Post[]): GekanatorQuestionMaterialIndex => {
|
||||
const postById = new Map<number, Post> ()
|
||||
const tagKeysByPostId = new Map<number, string[]> ()
|
||||
const postIdsByTagKey = new Map<string, Set<number>> ()
|
||||
@@ -784,8 +773,7 @@ const originalDateQuestionTextFor = (
|
||||
condition: Extract<
|
||||
GekanatorQuestionCondition,
|
||||
{ type: 'original-year' | 'original-month' | 'original-month-day' }
|
||||
>,
|
||||
): string => {
|
||||
>): string => {
|
||||
switch (condition.type)
|
||||
{
|
||||
case 'original-year':
|
||||
@@ -852,8 +840,7 @@ const isLearnableTagKey = (key: string): boolean => !(key.startsWith ('nico:'))
|
||||
|
||||
|
||||
const isUserSuggestedLearnedSemanticQuestion = (
|
||||
question: GekanatorQuestion,
|
||||
): boolean => isLearnedSemanticQuestion (question)
|
||||
question: GekanatorQuestion): boolean => isLearnedSemanticQuestion (question)
|
||||
|
||||
|
||||
type LearnedSemanticCandidateStats = {
|
||||
@@ -872,8 +859,7 @@ const learnedSemanticStatsForCandidateIds = (
|
||||
question }: {
|
||||
candidateIds: number[]
|
||||
posts: Post[]
|
||||
question: GekanatorQuestion },
|
||||
): LearnedSemanticCandidateStats => {
|
||||
question: GekanatorQuestion }): LearnedSemanticCandidateStats => {
|
||||
const candidateIdSet = new Set (candidateIds)
|
||||
const positiveIds = new Set<number> ()
|
||||
const negativeIds = new Set<number> ()
|
||||
@@ -915,8 +901,7 @@ const learnedSemanticQuestionIsEffectiveForCandidateIds = (
|
||||
question }: {
|
||||
candidateIds: number[]
|
||||
posts: Post[]
|
||||
question: GekanatorQuestion },
|
||||
): boolean => {
|
||||
question: GekanatorQuestion }): boolean => {
|
||||
if (!(isUserSuggestedLearnedSemanticQuestion (question)))
|
||||
return false
|
||||
|
||||
@@ -936,8 +921,7 @@ const learnedSemanticQuestionIsEffectiveForCandidateIds = (
|
||||
|
||||
const directSemanticAnswerForPost = (
|
||||
question: GekanatorQuestion,
|
||||
post: Post,
|
||||
): GekanatorAnswerValue | null => {
|
||||
post: Post): GekanatorAnswerValue | null => {
|
||||
const direct = question.exampleAnswers?.[String (post.id) as `${ number }`]
|
||||
if (direct)
|
||||
return direct
|
||||
@@ -956,8 +940,7 @@ const learnedSemanticLearningValueForTopPosts = (
|
||||
question: GekanatorQuestion
|
||||
learningTargetPosts: Post[]
|
||||
candidateIds: number[]
|
||||
posts: Post[] },
|
||||
): { missingTopCount: number
|
||||
posts: Post[] }): { missingTopCount: number
|
||||
knownCount: number
|
||||
hasLearningValue: boolean } => {
|
||||
const missingTopCount =
|
||||
@@ -1000,8 +983,7 @@ const learningTargetPostsForCandidates = ({
|
||||
|
||||
|
||||
const questionPurposeCountsFor = (
|
||||
answers: GekanatorAnswerLog[],
|
||||
): {
|
||||
answers: GekanatorAnswerLog[]): {
|
||||
effectiveUserSuggestedCount: number
|
||||
learningUserSuggestedCount: number
|
||||
normalQuestionCount: number
|
||||
@@ -1041,8 +1023,7 @@ const questionPurposeCountsFor = (
|
||||
|
||||
const learnedSemanticNarrowPenaltyForStats = (
|
||||
candidateCount: number,
|
||||
stats: LearnedSemanticCandidateStats,
|
||||
): number => {
|
||||
stats: LearnedSemanticCandidateStats): number => {
|
||||
const minSide = candidateCount < 10 ? 1 : Math.max (3, candidateCount * .08)
|
||||
return stats.positiveCount < minSide || stats.negativeCount < minSide ? .15 : 0
|
||||
}
|
||||
@@ -1050,8 +1031,7 @@ const learnedSemanticNarrowPenaltyForStats = (
|
||||
|
||||
const learnedSemanticScoreDeltaForExpectedAnswer = (
|
||||
userAnswer: GekanatorAnswerValue,
|
||||
expectedAnswer: GekanatorAnswerValue | null,
|
||||
): number => {
|
||||
expectedAnswer: GekanatorAnswerValue | null): number => {
|
||||
switch (userAnswer)
|
||||
{
|
||||
case 'yes':
|
||||
@@ -1089,8 +1069,7 @@ const learnedSemanticScoreDeltaForExpectedAnswer = (
|
||||
const scoreDropDeltaForRecoveredPost = (
|
||||
postId: number,
|
||||
totalScore: number,
|
||||
recoveredCandidatePosts: Map<number, RecoveredCandidateState>,
|
||||
): number => {
|
||||
recoveredCandidatePosts: Map<number, RecoveredCandidateState>): number => {
|
||||
const recoveredCandidate = recoveredCandidatePosts.get (postId)
|
||||
if (recoveredCandidate == null)
|
||||
return totalScore
|
||||
@@ -1114,8 +1093,7 @@ const postPassesScoreDrop = (
|
||||
recoveredCandidatePosts }: {
|
||||
postId: number
|
||||
scores: Map<number, number>
|
||||
recoveredCandidatePosts: Map<number, RecoveredCandidateState> },
|
||||
): boolean => {
|
||||
recoveredCandidatePosts: Map<number, RecoveredCandidateState> }): boolean => {
|
||||
if (!(activeCandidateScoreDropEnabled (scores)))
|
||||
return true
|
||||
|
||||
@@ -1129,8 +1107,7 @@ const postPassesScoreDrop = (
|
||||
|
||||
// `post_similarities` is the score-propagation graph, not the question kind.
|
||||
const questionUsesPostSimilarityPropagationGraphForScoring = (
|
||||
question: GekanatorQuestion,
|
||||
): boolean =>
|
||||
question: GekanatorQuestion): boolean =>
|
||||
(question.kind === 'post_similarity'
|
||||
&& !(isUserSuggestedLearnedSemanticQuestion (question)))
|
||||
|| (question.kind === 'tag'
|
||||
@@ -1139,8 +1116,7 @@ const questionUsesPostSimilarityPropagationGraphForScoring = (
|
||||
|
||||
|
||||
const questionSupportsAnswerBasedHardFiltering = (
|
||||
question: GekanatorQuestion,
|
||||
): boolean => !(questionUsesPostSimilarityPropagationGraphForScoring (question))
|
||||
question: GekanatorQuestion): boolean => !(questionUsesPostSimilarityPropagationGraphForScoring (question))
|
||||
&& !(isUserSuggestedLearnedSemanticQuestion (question))
|
||||
|
||||
|
||||
@@ -1160,8 +1136,7 @@ const usesLearnedTagExamples = (question: GekanatorQuestion): boolean =>
|
||||
|
||||
const searchedQuestionsFor = (
|
||||
questions: GekanatorQuestion[],
|
||||
search: string,
|
||||
): GekanatorQuestion[] => {
|
||||
search: string): GekanatorQuestion[] => {
|
||||
const needle = search.trim ()
|
||||
if (!(needle))
|
||||
return []
|
||||
@@ -1235,8 +1210,7 @@ type QuestionMatchResolver = {
|
||||
|
||||
const buildGekanatorMatchIndex = (
|
||||
posts: Post[],
|
||||
questions: GekanatorQuestion[],
|
||||
): GekanatorMatchIndex => new Map (
|
||||
questions: GekanatorQuestion[]): GekanatorMatchIndex => new Map (
|
||||
questions.map (question => [
|
||||
question.id,
|
||||
new Set (
|
||||
@@ -1285,8 +1259,7 @@ const matchingPostIdsForQuestion = ({
|
||||
|
||||
|
||||
const positiveMatchingPostIdsForQuestion = (
|
||||
resolver: QuestionMatchResolver,
|
||||
): Set<number> => {
|
||||
resolver: QuestionMatchResolver): Set<number> => {
|
||||
if (isUserSuggestedLearnedSemanticQuestion (resolver.question))
|
||||
{
|
||||
const cached = resolver.dynamicMatchIndex?.get (resolver.question.id)
|
||||
@@ -1356,8 +1329,7 @@ const matchingWeightInCandidates = (
|
||||
materialIndex: GekanatorQuestionMaterialIndex
|
||||
matchIndex: GekanatorMatchIndex
|
||||
question: GekanatorQuestion
|
||||
dynamicMatchIndex?: GekanatorMatchIndex },
|
||||
): number => {
|
||||
dynamicMatchIndex?: GekanatorMatchIndex }): number => {
|
||||
const matched = positiveMatchingPostIdsForQuestion ({
|
||||
posts,
|
||||
materialIndex,
|
||||
@@ -1380,8 +1352,7 @@ const signatureForCandidateIds = (
|
||||
materialIndex: GekanatorQuestionMaterialIndex
|
||||
matchIndex: GekanatorMatchIndex
|
||||
question: GekanatorQuestion
|
||||
dynamicMatchIndex?: GekanatorMatchIndex },
|
||||
): string => {
|
||||
dynamicMatchIndex?: GekanatorMatchIndex }): string => {
|
||||
if (isUserSuggestedLearnedSemanticQuestion (question))
|
||||
{
|
||||
const postById = new Map (posts.map (post => [post.id, post]))
|
||||
@@ -1421,8 +1392,7 @@ const postIdsForHardAnswer = (
|
||||
posts: Post[]
|
||||
materialIndex: GekanatorQuestionMaterialIndex
|
||||
matchIndex: GekanatorMatchIndex
|
||||
dynamicMatchIndex?: GekanatorMatchIndex },
|
||||
): number[] => {
|
||||
dynamicMatchIndex?: GekanatorMatchIndex }): number[] => {
|
||||
if (!(questionSupportsAnswerBasedHardFiltering (question)))
|
||||
return candidateIds
|
||||
|
||||
@@ -1562,8 +1532,7 @@ const buildIndexedQuestion = (
|
||||
text: string
|
||||
kind: GekanatorQuestionKind
|
||||
priorityWeight: number
|
||||
materialIndex: GekanatorQuestionMaterialIndex },
|
||||
): GekanatorQuestion => ({
|
||||
materialIndex: GekanatorQuestionMaterialIndex }): GekanatorQuestion => ({
|
||||
id: questionIdForCondition (condition),
|
||||
text,
|
||||
kind,
|
||||
@@ -1578,8 +1547,7 @@ const buildIndexedQuestion = (
|
||||
const rankedEntriesForCounts = <T extends string | number> (
|
||||
{ counts, total, cap }: { counts: Map<T, number>
|
||||
total: number
|
||||
cap: number },
|
||||
): [T, number][] =>
|
||||
cap: number }): [T, number][] =>
|
||||
([...counts.entries ()]
|
||||
.filter (([, count]) => count > 0 && count < total)
|
||||
.sort ((a, b) => Math.abs (total / 2 - a[1]) - Math.abs (total / 2 - b[1]))
|
||||
@@ -1594,8 +1562,7 @@ const buildQuestionsForCandidateIds = (
|
||||
materialIndex: GekanatorQuestionMaterialIndex
|
||||
acceptedQuestions: GekanatorQuestion[]
|
||||
mode?: QuestionBuildMode
|
||||
confirmationPostId?: number | null },
|
||||
): GekanatorQuestion[] => {
|
||||
confirmationPostId?: number | null }): GekanatorQuestion[] => {
|
||||
const total = candidateIds.length
|
||||
const confirmationPost = (() => {
|
||||
if (confirmationPostId == null)
|
||||
@@ -1652,8 +1619,7 @@ const buildQuestionsForCandidateIds = (
|
||||
condition: Extract<
|
||||
GekanatorQuestionCondition,
|
||||
{ type: 'original-year' | 'original-month' | 'original-month-day' }
|
||||
>,
|
||||
): GekanatorQuestion => {
|
||||
>): GekanatorQuestion => {
|
||||
const priorityWeight = (() => {
|
||||
if (condition.type === 'original-year')
|
||||
return 1.04
|
||||
@@ -1673,8 +1639,7 @@ const buildQuestionsForCandidateIds = (
|
||||
const specialMonthDays = rankedEntriesForCounts ({
|
||||
counts: monthDayCounts,
|
||||
total,
|
||||
cap: factCap
|
||||
}).filter (([monthDay]) => specialOriginalMonthDayLabelFor (String (monthDay)) != null)
|
||||
cap: factCap}).filter (([monthDay]) => specialOriginalMonthDayLabelFor (String (monthDay)) != null)
|
||||
|
||||
if (mode === 'split')
|
||||
{
|
||||
@@ -2124,8 +2089,7 @@ type ExclusiveConditionGroup =
|
||||
|
||||
|
||||
const exclusiveConditionGroupFor = (
|
||||
condition: GekanatorQuestion['condition'],
|
||||
): ExclusiveConditionGroup | null => {
|
||||
condition: GekanatorQuestion['condition']): ExclusiveConditionGroup | null => {
|
||||
switch (condition.type)
|
||||
{
|
||||
case 'original-month':
|
||||
@@ -2144,8 +2108,7 @@ const exclusiveConditionGroupFor = (
|
||||
|
||||
const sameConditionValue = (
|
||||
left: GekanatorQuestion['condition'],
|
||||
right: GekanatorQuestion['condition'],
|
||||
): boolean => {
|
||||
right: GekanatorQuestion['condition']): boolean => {
|
||||
const leftTitleLength = titleLengthMinimumForCondition (left)
|
||||
const rightTitleLength = titleLengthMinimumForCondition (right)
|
||||
if (leftTitleLength != null || rightTitleLength != null)
|
||||
@@ -2187,8 +2150,7 @@ const sameConditionValue = (
|
||||
|
||||
const isMonthCrossMatch = (
|
||||
candidate: GekanatorQuestion['condition'],
|
||||
previous: GekanatorQuestion['condition'],
|
||||
): boolean => {
|
||||
previous: GekanatorQuestion['condition']): boolean => {
|
||||
const candidateMonth = monthForCondition (candidate)
|
||||
const previousMonth = monthForCondition (previous)
|
||||
if (candidateMonth == null || previousMonth == null)
|
||||
@@ -2204,8 +2166,7 @@ const isMonthCrossMatch = (
|
||||
|
||||
const isExclusiveContradiction = (
|
||||
candidate: GekanatorQuestion['condition'],
|
||||
previous: GekanatorQuestion['condition'],
|
||||
): boolean => {
|
||||
previous: GekanatorQuestion['condition']): boolean => {
|
||||
const candidateGroup = exclusiveConditionGroupFor (candidate)
|
||||
const previousGroup = exclusiveConditionGroupFor (previous)
|
||||
|
||||
@@ -2242,16 +2203,14 @@ const contradictionPenaltyFor = ({
|
||||
case 'no':
|
||||
if (
|
||||
sameConditionValue (question.condition, previous)
|
||||
|| isMonthCrossMatch (question.condition, previous)
|
||||
)
|
||||
|| isMonthCrossMatch (question.condition, previous))
|
||||
return sum + 40
|
||||
|
||||
return sum
|
||||
case 'probably_no':
|
||||
if (
|
||||
sameConditionValue (question.condition, previous)
|
||||
|| isMonthCrossMatch (question.condition, previous)
|
||||
)
|
||||
|| isMonthCrossMatch (question.condition, previous))
|
||||
return sum + 20
|
||||
|
||||
return sum
|
||||
@@ -2281,8 +2240,7 @@ const chooseQuestion = (
|
||||
recentFirstQuestionPenaltyById: Map<string, number>
|
||||
userPriorWeights: Map<number, number>
|
||||
materialIndex: GekanatorQuestionMaterialIndex
|
||||
matchIndex: GekanatorMatchIndex },
|
||||
): QuestionSelection | null => {
|
||||
matchIndex: GekanatorMatchIndex }): QuestionSelection | null => {
|
||||
const dynamicMatchIndex = new Map<string, Set<number>> ()
|
||||
|
||||
const invertedSignature = (signature: string): string =>
|
||||
@@ -2327,8 +2285,7 @@ const chooseQuestion = (
|
||||
const rank = (
|
||||
questionsToRank: GekanatorQuestion[],
|
||||
candidates: { post: Post; score: number }[],
|
||||
weightedCandidates: { post: Post; score: number; weight: number }[],
|
||||
) => {
|
||||
weightedCandidates: { post: Post; score: number; weight: number }[]) => {
|
||||
const redundant = redundantSignatures (candidates.map (item => item.post))
|
||||
const candidateById = new Map (candidates.map (item => [item.post.id, item.post]))
|
||||
const candidateIds = candidates.map (item => item.post.id)
|
||||
@@ -2613,8 +2570,7 @@ const chooseQuestion = (
|
||||
if (
|
||||
effectiveRatio < targetEffectiveUserSuggestedQuestionRatio
|
||||
&& totalUserSuggestedRatio < targetTotalUserSuggestedQuestionRatio
|
||||
&& effectiveUserSuggestedPool.length > 0
|
||||
)
|
||||
&& effectiveUserSuggestedPool.length > 0)
|
||||
{
|
||||
selectedPool = effectiveUserSuggestedPool
|
||||
selectedPurpose = 'effective_user_suggested'
|
||||
@@ -2622,8 +2578,7 @@ const chooseQuestion = (
|
||||
else if (
|
||||
learningRatio < targetLearningUserSuggestedQuestionRatio
|
||||
&& totalUserSuggestedRatio < targetTotalUserSuggestedQuestionRatio
|
||||
&& learningUserSuggestedPool.length > 0
|
||||
)
|
||||
&& learningUserSuggestedPool.length > 0)
|
||||
{
|
||||
selectedPool = learningUserSuggestedPool
|
||||
selectedPurpose = 'learning_user_suggested'
|
||||
@@ -2683,8 +2638,7 @@ const chooseQuestion = (
|
||||
|
||||
|
||||
const winningRunPriorityFor = (
|
||||
expected: GekanatorAnswerValue,
|
||||
): number | null => {
|
||||
expected: GekanatorAnswerValue): number | null => {
|
||||
if (expected === 'yes')
|
||||
return 0
|
||||
if (expected === 'partial')
|
||||
@@ -2719,8 +2673,7 @@ const chooseWinningRunQuestion = ({
|
||||
materialIndex,
|
||||
acceptedQuestions,
|
||||
mode: 'confirmation',
|
||||
confirmationPostId: targetPost.id
|
||||
})
|
||||
confirmationPostId: targetPost.id})
|
||||
.filter (question => {
|
||||
if (askedIds.has (question.id))
|
||||
return false
|
||||
@@ -2829,8 +2782,7 @@ const chooseFallbackQuestion = ({
|
||||
materialIndex,
|
||||
acceptedQuestions: [],
|
||||
mode: 'confirmation',
|
||||
confirmationPostId: post.id
|
||||
})))
|
||||
confirmationPostId: post.id})))
|
||||
.slice (0, 32)
|
||||
const dynamicMatchIndex = new Map<string, Set<number>> ()
|
||||
const ranked = mergeQuestions ([
|
||||
@@ -2905,8 +2857,7 @@ const chooseFallbackQuestion = ({
|
||||
|
||||
|
||||
const shouldEnterGuessPhase = (
|
||||
reason: GuessReason | null,
|
||||
): reason is 'hard_max_questions' | 'winning_run_finished' | 'question_count_checkpoint' =>
|
||||
reason: GuessReason | null): reason is 'hard_max_questions' | 'winning_run_finished' | 'question_count_checkpoint' =>
|
||||
(reason === 'hard_max_questions'
|
||||
|| reason === 'winning_run_finished'
|
||||
|| reason === 'question_count_checkpoint')
|
||||
@@ -2914,15 +2865,13 @@ const shouldEnterGuessPhase = (
|
||||
|
||||
const isWinningRunActive = (
|
||||
winningRunTargetId: number | null,
|
||||
winningRunStartAnswerCount: number | null,
|
||||
): boolean =>
|
||||
winningRunStartAnswerCount: number | null): boolean =>
|
||||
winningRunTargetId != null && winningRunStartAnswerCount != null
|
||||
|
||||
|
||||
const winningRunQuestionCount = (
|
||||
answers: GekanatorAnswerLog[],
|
||||
winningRunStartAnswerCount: number | null,
|
||||
): number => {
|
||||
winningRunStartAnswerCount: number | null): number => {
|
||||
if (winningRunStartAnswerCount == null)
|
||||
return 0
|
||||
|
||||
@@ -2962,8 +2911,7 @@ const nextQuestionPlanFor = (
|
||||
matchIndex: GekanatorMatchIndex
|
||||
lastGuessQuestionCount: number
|
||||
winningRunTargetId: number | null
|
||||
winningRunStartAnswerCount: number | null },
|
||||
): { question: GekanatorQuestion | null
|
||||
winningRunStartAnswerCount: number | null }): { question: GekanatorQuestion | null
|
||||
guess: Post | null
|
||||
guessReason: GuessReason | null
|
||||
questionMode: QuestionMode
|
||||
@@ -3013,8 +2961,7 @@ const nextQuestionPlanFor = (
|
||||
if (
|
||||
isWinningRunActive (winningRunTargetId, winningRunStartAnswerCount)
|
||||
&& winningRunTargetId === nextWinningRunTargetId
|
||||
&& winningRunStartAnswerCount != null
|
||||
)
|
||||
&& winningRunStartAnswerCount != null)
|
||||
return winningRunStartAnswerCount
|
||||
|
||||
return answers.length
|
||||
@@ -3188,8 +3135,7 @@ const mascotStateFor = (
|
||||
resultWon: boolean | null,
|
||||
eligiblePostCount: number,
|
||||
bestConfidencePercent: number,
|
||||
winningRunActive: boolean,
|
||||
): MascotState => {
|
||||
winningRunActive: boolean): MascotState => {
|
||||
const resultPhase =
|
||||
phase === 'end'
|
||||
|| phase === 'review'
|
||||
@@ -3210,13 +3156,11 @@ const mascotStateFor = (
|
||||
if (
|
||||
winningRunActive
|
||||
|| eligiblePostCount <= 2
|
||||
|| bestConfidencePercent >= 70
|
||||
)
|
||||
|| bestConfidencePercent >= 70)
|
||||
return 'thinking_near'
|
||||
if (
|
||||
eligiblePostCount >= 15
|
||||
&& bestConfidencePercent < 45
|
||||
)
|
||||
&& bestConfidencePercent < 45)
|
||||
return 'thinking_far'
|
||||
return 'thinking_mid'
|
||||
case 'guess':
|
||||
@@ -3327,8 +3271,7 @@ const GekanatorBackdrop: FC<{
|
||||
|
||||
const settingsForMode = useCallback (
|
||||
(
|
||||
mode: 'normal' | 'winning_run' | 'guess',
|
||||
): { columns: number; rows: number; opacity: number } => {
|
||||
mode: 'normal' | 'winning_run' | 'guess'): { columns: number; rows: number; opacity: number } => {
|
||||
if (mode === 'winning_run' || mode === 'guess')
|
||||
return { columns: 8, rows: 8, opacity: motionMode === 'calm' ? .18 : .24 }
|
||||
|
||||
@@ -3342,8 +3285,7 @@ const GekanatorBackdrop: FC<{
|
||||
const scaleForMode = useCallback (
|
||||
(
|
||||
mode: 'normal' | 'winning_run' | 'guess',
|
||||
displayedWinningCount: number,
|
||||
): number => {
|
||||
displayedWinningCount: number): number => {
|
||||
if (mode === 'guess')
|
||||
return 8
|
||||
|
||||
@@ -3355,8 +3297,7 @@ const GekanatorBackdrop: FC<{
|
||||
[])
|
||||
|
||||
const postsForMode = useCallback ((
|
||||
mode: 'normal' | 'winning_run' | 'guess',
|
||||
): Post[] => {
|
||||
mode: 'normal' | 'winning_run' | 'guess'): Post[] => {
|
||||
if (mode === 'guess' && displayedGuess)
|
||||
return [displayedGuess]
|
||||
if (mode === 'winning_run' && winningRunTargetPost)
|
||||
@@ -3366,8 +3307,7 @@ const GekanatorBackdrop: FC<{
|
||||
|
||||
const thumbnailsForMode = useCallback ((
|
||||
mode: 'normal' | 'winning_run' | 'guess',
|
||||
count: number,
|
||||
): string[] => {
|
||||
count: number): string[] => {
|
||||
const modePosts = postsForMode (mode)
|
||||
if (modePosts.length === 0)
|
||||
return []
|
||||
@@ -3734,8 +3674,7 @@ const GekanatorBackdrop: FC<{
|
||||
|
||||
const expectedAnswerFor = (
|
||||
question: GekanatorQuestion | undefined,
|
||||
correctPost: Post | null,
|
||||
): GekanatorAnswerValue | null =>
|
||||
correctPost: Post | null): GekanatorAnswerValue | null =>
|
||||
expectedAnswerForQuestion (question, correctPost)
|
||||
|
||||
|
||||
@@ -4169,8 +4108,7 @@ const GekanatorPage: FC<{ user: User | null }> = ({ user }) => {
|
||||
setSaved (true)
|
||||
setSavedGameId (data.id)
|
||||
setLearnedExampleCount (data.learnedExampleCount)
|
||||
setResultWon (variables.guessedPostId === variables.correctPostId)
|
||||
}})
|
||||
setResultWon (variables.guessedPostId === variables.correctPostId)}})
|
||||
const questionSuggestionMutation = useMutation ({
|
||||
mutationFn: saveGekanatorQuestionSuggestion,
|
||||
onSuccess: async data => {
|
||||
@@ -4180,15 +4118,13 @@ const GekanatorPage: FC<{ user: User | null }> = ({ user }) => {
|
||||
setQuestionSuggestionSearch ('')
|
||||
setQuestionSuggestionSelectedId (null)
|
||||
setQuestionSuggestion ('')
|
||||
setQuestionSuggestionAnswer ('yes')
|
||||
}})
|
||||
setQuestionSuggestionAnswer ('yes')}})
|
||||
const extraQuestionAnswersMutation = useMutation ({
|
||||
mutationFn: saveGekanatorExtraQuestionAnswers,
|
||||
onSuccess: async () => {
|
||||
await queryClient.refetchQueries ({ queryKey: gekanatorKeys.questions () })
|
||||
setExtraQuestionState ('saved')
|
||||
setPhase ('end')
|
||||
}})
|
||||
setPhase ('end')}})
|
||||
|
||||
const resetExtraQuestionState = () => {
|
||||
const next = resettableExtraQuestionState ()
|
||||
@@ -4330,8 +4266,7 @@ const GekanatorPage: FC<{ user: User | null }> = ({ user }) => {
|
||||
if (
|
||||
!(allowPreQuestionRecovery)
|
||||
|| recoveredEligiblePosts.length === 0
|
||||
|| recoveredEligiblePosts.length === 1
|
||||
)
|
||||
|| recoveredEligiblePosts.length === 1)
|
||||
return false
|
||||
|
||||
const nextQuestion = chooseQuestion ({
|
||||
@@ -4493,8 +4428,7 @@ const GekanatorPage: FC<{ user: User | null }> = ({ user }) => {
|
||||
if (
|
||||
!(nextPlan.question)
|
||||
&& !(shouldEnterGuessPhase (nextPlan.guessReason))
|
||||
&& recovered.eligiblePosts.length !== 1
|
||||
)
|
||||
&& recovered.eligiblePosts.length !== 1)
|
||||
{
|
||||
const recoveredForQuestion = recoverQuestionState ({
|
||||
nextAnswers,
|
||||
@@ -4602,8 +4536,7 @@ const GekanatorPage: FC<{ user: User | null }> = ({ user }) => {
|
||||
!(canPersistGame)
|
||||
|| reviewGuessedPostId == null
|
||||
|| reviewCorrectPostId == null
|
||||
|| saveMutation.isPending
|
||||
)
|
||||
|| saveMutation.isPending)
|
||||
return
|
||||
|
||||
if (savedGameId != null)
|
||||
@@ -4666,8 +4599,7 @@ const GekanatorPage: FC<{ user: User | null }> = ({ user }) => {
|
||||
!(canPersistGame)
|
||||
|| savedGameId == null
|
||||
|| extraQuestionAnswersMutation.isPending
|
||||
|| extraQuestions.some (question => !(extraQuestionAnswers[String (question.id)]))
|
||||
)
|
||||
|| extraQuestions.some (question => !(extraQuestionAnswers[String (question.id)])))
|
||||
return
|
||||
|
||||
extraQuestionAnswersMutation.mutate ({
|
||||
@@ -4870,8 +4802,7 @@ const GekanatorPage: FC<{ user: User | null }> = ({ user }) => {
|
||||
|
||||
const answerExtraQuestion = (
|
||||
questionId: number,
|
||||
value: GekanatorAnswerValue,
|
||||
) => {
|
||||
value: GekanatorAnswerValue) => {
|
||||
setExtraQuestionAnswers ({
|
||||
...extraQuestionAnswers,
|
||||
[String (questionId)]: value })
|
||||
@@ -4909,8 +4840,7 @@ const GekanatorPage: FC<{ user: User | null }> = ({ user }) => {
|
||||
|| isLoading
|
||||
|| acceptedQuestionsLoading
|
||||
|| shouldEnterGuessPhase (questionPlan.guessReason)
|
||||
|| eligiblePosts.length === 1
|
||||
)
|
||||
|| eligiblePosts.length === 1)
|
||||
return
|
||||
|
||||
const recovered = recoverQuestionState ({
|
||||
@@ -4926,8 +4856,7 @@ const GekanatorPage: FC<{ user: User | null }> = ({ user }) => {
|
||||
if (
|
||||
recovered.recoveryStepCount === recoveryStepCount
|
||||
&& recovered.recoveredCandidatePosts.size === recoveredCandidatePosts.size
|
||||
&& recovered.softenedQuestionIds.size === softenedQuestionIds.size
|
||||
)
|
||||
&& recovered.softenedQuestionIds.size === softenedQuestionIds.size)
|
||||
return
|
||||
|
||||
setSoftenedQuestionIds (recovered.softenedQuestionIds)
|
||||
@@ -4954,15 +4883,13 @@ const GekanatorPage: FC<{ user: User | null }> = ({ user }) => {
|
||||
if (
|
||||
phase !== 'question'
|
||||
|| isLoading
|
||||
|| acceptedQuestionsLoading
|
||||
)
|
||||
|| acceptedQuestionsLoading)
|
||||
return
|
||||
|
||||
if (
|
||||
currentQuestion
|
||||
|| !(questionPlan.guess)
|
||||
|| !(shouldEnterGuessPhase (questionPlan.guessReason))
|
||||
)
|
||||
|| !(shouldEnterGuessPhase (questionPlan.guessReason)))
|
||||
return
|
||||
|
||||
setWinningRunTargetId (questionPlan.winningRunTargetId)
|
||||
|
||||
@@ -145,8 +145,7 @@ const DeerjikistDetailPage: FC = () => {
|
||||
return rtn
|
||||
})}/>)}
|
||||
</FormField>
|
||||
</fieldset>
|
||||
))}
|
||||
</fieldset>))}
|
||||
|
||||
<div className="py-3">
|
||||
<button
|
||||
@@ -169,8 +168,7 @@ const DeerjikistDetailPage: FC = () => {
|
||||
</button>
|
||||
</div>
|
||||
</form>
|
||||
</div>
|
||||
)}
|
||||
</div>)}
|
||||
</MainArea>)
|
||||
}
|
||||
|
||||
|
||||
@@ -7,8 +7,9 @@ import { buildMaterial, buildTag } from '@/test/factories'
|
||||
import { renderWithProviders } from '@/test/render'
|
||||
|
||||
const api = vi.hoisted (() => ({
|
||||
apiGet: vi.fn (),
|
||||
apiPut: vi.fn (),
|
||||
apiGet: vi.fn (),
|
||||
apiPut: vi.fn (),
|
||||
isApiError: vi.fn (),
|
||||
}))
|
||||
|
||||
const wikiApi = vi.hoisted (() => ({
|
||||
@@ -26,7 +27,7 @@ vi.mock ('@/components/ui/use-toast', () => toastApi)
|
||||
const renderPage = () =>
|
||||
renderWithProviders (
|
||||
<Routes>
|
||||
<Route path="/materials/:id" element={<MaterialDetailPage/>}/>
|
||||
<Route path="/materials/:id" element={<MaterialDetailPage user={null}/>}/>
|
||||
</Routes>,
|
||||
{ route: '/materials/8' },
|
||||
)
|
||||
@@ -34,7 +35,11 @@ const renderPage = () =>
|
||||
describe ('MaterialDetailPage', () => {
|
||||
beforeEach (() => {
|
||||
vi.clearAllMocks ()
|
||||
api.apiGet.mockResolvedValue ([])
|
||||
api.apiGet.mockImplementation (async (path: string) =>
|
||||
path === '/tags/autocomplete'
|
||||
? []
|
||||
: buildMaterial ({ id: 8 }))
|
||||
api.isApiError.mockReturnValue (false)
|
||||
wikiApi.fetchWikiPages.mockResolvedValue ([])
|
||||
vi.stubGlobal ('fetch', vi.fn (async () => ({
|
||||
blob: async () => new Blob (['image'], { type: 'image/png' }),
|
||||
@@ -73,6 +78,7 @@ describe ('MaterialDetailPage', () => {
|
||||
const textboxes = screen.getAllByRole ('textbox')
|
||||
fireEvent.change (textboxes[0], { target: { value: 'new' } })
|
||||
fireEvent.change (textboxes[1], { target: { value: 'https://example.com/ref' } })
|
||||
fireEvent.change (textboxes[2], { target: { value: '素材/new.png' } })
|
||||
fireEvent.click (screen.getByRole ('button', { name: '更新' }))
|
||||
|
||||
await waitFor (() => {
|
||||
@@ -81,6 +87,25 @@ describe ('MaterialDetailPage', () => {
|
||||
const formData = api.apiPut.mock.calls[0]?.[1] as FormData
|
||||
expect (formData.get ('tag')).toBe ('new')
|
||||
expect (formData.get ('url')).toBe ('https://example.com/ref')
|
||||
expect (formData.get ('export_paths[legacy_drive]')).toBe ('素材/new.png')
|
||||
expect (toastApi.toast).toHaveBeenCalledWith ({ title: '更新成功!' })
|
||||
})
|
||||
|
||||
it ('shows not found when material API returns 404', async () => {
|
||||
api.isApiError.mockReturnValue (true)
|
||||
api.apiGet.mockRejectedValueOnce ({ response: { status: 404 } })
|
||||
|
||||
renderPage ()
|
||||
|
||||
expect (await screen.findByText ('素材が見つかりませんでした.')).toBeInTheDocument ()
|
||||
})
|
||||
|
||||
it ('shows an error for non-404 material API failures', async () => {
|
||||
api.isApiError.mockReturnValue (false)
|
||||
api.apiGet.mockRejectedValueOnce (new Error ('network error'))
|
||||
|
||||
renderPage ()
|
||||
|
||||
expect (await screen.findByText ('素材の取得に失敗しました.')).toBeInTheDocument ()
|
||||
})
|
||||
})
|
||||
|
||||
@@ -1,3 +1,4 @@
|
||||
import { useMutation, useQuery, useQueryClient } from '@tanstack/react-query'
|
||||
import { useEffect, useState } from 'react'
|
||||
import { Helmet } from 'react-helmet-async'
|
||||
import { useParams } from 'react-router-dom'
|
||||
@@ -13,124 +14,130 @@ import MainArea from '@/components/layout/MainArea'
|
||||
import { Button } from '@/components/ui/button'
|
||||
import { toast } from '@/components/ui/use-toast'
|
||||
import { SITE_TITLE } from '@/config'
|
||||
import { apiGet, apiPut } from '@/lib/api'
|
||||
import {
|
||||
fetchMaterial,
|
||||
updateMaterial,
|
||||
} from '@/lib/materials'
|
||||
import { materialsKeys } from '@/lib/queryKeys'
|
||||
import { inputClass } from '@/lib/utils'
|
||||
import { useValidationErrors } from '@/lib/useValidationErrors'
|
||||
|
||||
import type { FC } from 'react'
|
||||
|
||||
import type { Material, Tag } from '@/types'
|
||||
|
||||
type MaterialWithTag = Material & { tag: Tag }
|
||||
|
||||
type MaterialFormField = 'tag' | 'file' | 'url'
|
||||
type MaterialFormField = 'tag' | 'file' | 'url' | 'exportPaths'
|
||||
|
||||
|
||||
const MaterialDetailPage: FC = () => {
|
||||
const { id } = useParams ()
|
||||
const qc = useQueryClient ()
|
||||
|
||||
const [exportPath, setExportPath] = useState ('')
|
||||
const [file, setFile] = useState<File | null> (null)
|
||||
const [filePreview, setFilePreview] = useState ('')
|
||||
const [loading, setLoading] = useState (false)
|
||||
const [material, setMaterial] = useState<MaterialWithTag | null> (null)
|
||||
const [sending, setSending] = useState (false)
|
||||
const [tag, setTag] = useState ('')
|
||||
const [url, setURL] = useState ('')
|
||||
const { baseErrors, fieldErrors, clearValidationErrors, applyValidationError } =
|
||||
useValidationErrors<MaterialFormField> ()
|
||||
|
||||
const handleSubmit = async () => {
|
||||
clearValidationErrors ()
|
||||
|
||||
const formData = new FormData
|
||||
if (tag.trim ())
|
||||
formData.append ('tag', tag)
|
||||
if (file)
|
||||
formData.append ('file', file)
|
||||
if (url.trim ())
|
||||
formData.append ('url', url)
|
||||
|
||||
try
|
||||
{
|
||||
setSending (true)
|
||||
const data = await apiPut<Material> (`/materials/${ id }`, formData)
|
||||
setMaterial (data)
|
||||
toast ({ title: '更新成功!' })
|
||||
}
|
||||
catch (e)
|
||||
{
|
||||
applyValidationError (e)
|
||||
toast ({ title: '更新失敗……', description: '入力を見直してください.' })
|
||||
}
|
||||
finally
|
||||
{
|
||||
setSending (false)
|
||||
}
|
||||
}
|
||||
const { data: material, isError, isLoading } = useQuery ({
|
||||
queryKey: materialsKeys.show (id ?? ''),
|
||||
queryFn: () => fetchMaterial (id ?? ''),
|
||||
enabled: id != null})
|
||||
const materialTitle = material
|
||||
? material.tag?.name ?? `素材 #${ material.id }`
|
||||
: ''
|
||||
|
||||
useEffect (() => {
|
||||
if (!(id))
|
||||
if (!(material))
|
||||
return
|
||||
|
||||
void (async () => {
|
||||
try
|
||||
setTag (material.tag?.name ?? '')
|
||||
setURL (material.url ?? '')
|
||||
setExportPath (material.exportPaths.legacyDrive ?? '')
|
||||
if (material.file && material.contentType)
|
||||
{
|
||||
setLoading (true)
|
||||
const data = await apiGet<MaterialWithTag> (`/materials/${ id }`)
|
||||
setMaterial (data)
|
||||
setTag (data.tag.name)
|
||||
if (data.file && data.contentType)
|
||||
{
|
||||
setFilePreview (data.file)
|
||||
setFile (new File ([await (await fetch (data.file)).blob ()],
|
||||
data.file,
|
||||
{ type: data.contentType }))
|
||||
}
|
||||
setURL (data.url ?? '')
|
||||
setFilePreview (material.file)
|
||||
setFile (null)
|
||||
}
|
||||
finally
|
||||
{
|
||||
setLoading (false)
|
||||
}
|
||||
}) ()
|
||||
}, [id])
|
||||
}, [material])
|
||||
|
||||
const invalidateMaterialQueries = async () => {
|
||||
await qc.invalidateQueries ({ queryKey: materialsKeys.root })
|
||||
}
|
||||
|
||||
const updateMutation = useMutation ({
|
||||
mutationFn: async () => {
|
||||
const formData = new FormData
|
||||
if (tag.trim ())
|
||||
formData.append ('tag', tag)
|
||||
if (file)
|
||||
formData.append ('file', file)
|
||||
if (url.trim ())
|
||||
formData.append ('url', url)
|
||||
formData.append ('export_paths[legacy_drive]', exportPath)
|
||||
|
||||
return await updateMaterial (id ?? '', formData)
|
||||
},
|
||||
onSuccess: async data => {
|
||||
qc.setQueryData (materialsKeys.show (id ?? ''), data)
|
||||
await invalidateMaterialQueries ()
|
||||
toast ({ title: '更新成功!' })
|
||||
},
|
||||
onError: error => {
|
||||
applyValidationError (error)
|
||||
toast ({ title: '更新失敗……', description: '入力を見直してください.' })
|
||||
}})
|
||||
|
||||
const handleSubmit = () => {
|
||||
clearValidationErrors ()
|
||||
updateMutation.mutate ()
|
||||
}
|
||||
|
||||
return (
|
||||
<MainArea>
|
||||
{material && (
|
||||
<Helmet>
|
||||
<title>{`${ material.tag.name } 素材照会 | ${ SITE_TITLE }`}</title>
|
||||
<title>{`${ materialTitle } 素材照会 | ${ SITE_TITLE }`}</title>
|
||||
</Helmet>)}
|
||||
|
||||
{loading ? 'Loading...' : (material && (
|
||||
{isLoading ? 'Loading...' : isError ? (
|
||||
<p className="text-red-600 dark:text-red-300">
|
||||
素材の取得に失敗しました.
|
||||
</p>) : material == null ? (
|
||||
<p className="text-stone-700 dark:text-stone-300">
|
||||
素材が見つかりませんでした.
|
||||
</p>) : (
|
||||
<>
|
||||
<PageTitle>
|
||||
<TagLink
|
||||
tag={material.tag}
|
||||
withWiki={false}
|
||||
withCount={false}/>
|
||||
{material.tag
|
||||
? (
|
||||
<TagLink
|
||||
tag={material.tag}
|
||||
withWiki={false}
|
||||
withCount={false}/>)
|
||||
: materialTitle}
|
||||
</PageTitle>
|
||||
|
||||
{(material.file && material.contentType) && (
|
||||
(/image\/.*/.test (material.contentType) && (
|
||||
<img src={material.file} alt={material.tag.name || undefined}/>))
|
||||
<img src={material.file} alt={material.tag?.name || undefined}/>))
|
||||
|| (/video\/.*/.test (material.contentType) && (
|
||||
<video src={material.file} controls/>))
|
||||
|| (/audio\/.*/.test (material.contentType) && (
|
||||
<audio src={material.file} controls/>)))}
|
||||
|
||||
<TabGroup>
|
||||
<Tab name="Wiki">
|
||||
<WikiBody
|
||||
title={material.tag.name}
|
||||
body={material.wikiPageBody ?? undefined}/>
|
||||
</Tab>
|
||||
{material.tag && (
|
||||
<Tab name="Wiki">
|
||||
<WikiBody
|
||||
title={material.tag.name}
|
||||
body={material.wikiPageBody ?? undefined}/>
|
||||
</Tab>)}
|
||||
|
||||
<Tab name="編輯">
|
||||
<div className="max-w-wl pt-2 space-y-4">
|
||||
<div className="max-w-wl space-y-4 pt-2">
|
||||
<FieldError messages={baseErrors}/>
|
||||
|
||||
{/* タグ */}
|
||||
<FormField label="タグ" messages={fieldErrors.tag}>
|
||||
{({ describedBy, invalid }) => (
|
||||
<TagInput
|
||||
@@ -140,7 +147,6 @@ const MaterialDetailPage: FC = () => {
|
||||
setValue={setTag}/>)}
|
||||
</FormField>
|
||||
|
||||
{/* ファイル */}
|
||||
<FormField label="ファイル" messages={fieldErrors.file}>
|
||||
{({ describedBy, invalid }) => (
|
||||
<>
|
||||
@@ -150,9 +156,10 @@ const MaterialDetailPage: FC = () => {
|
||||
aria-describedby={describedBy}
|
||||
aria-invalid={invalid}
|
||||
onChange={e => {
|
||||
const f = e.target.files?.[0]
|
||||
setFile (f ?? null)
|
||||
setFilePreview (f ? URL.createObjectURL (f) : '')
|
||||
const nextFile = e.target.files?.[0]
|
||||
setFile (nextFile ?? null)
|
||||
setFilePreview (
|
||||
nextFile ? URL.createObjectURL (nextFile) : '')
|
||||
}}/>
|
||||
{(file && filePreview) && (
|
||||
(/image\/.*/.test (file.type) && (
|
||||
@@ -177,7 +184,6 @@ const MaterialDetailPage: FC = () => {
|
||||
</>)}
|
||||
</FormField>
|
||||
|
||||
{/* 参考 URL */}
|
||||
<FormField label="参考 URL" messages={fieldErrors.url}>
|
||||
{({ describedBy, invalid }) => (
|
||||
<input
|
||||
@@ -189,17 +195,31 @@ const MaterialDetailPage: FC = () => {
|
||||
className={inputClass (invalid)}/>)}
|
||||
</FormField>
|
||||
|
||||
{/* 送信 */}
|
||||
<Button
|
||||
onClick={handleSubmit}
|
||||
className="px-4 py-2 bg-blue-600 text-white rounded disabled:bg-gray-400"
|
||||
disabled={sending}>
|
||||
更新
|
||||
</Button>
|
||||
<FormField label="ZIP 出力パス" messages={fieldErrors.exportPaths}>
|
||||
{({ describedBy, invalid }) => (
|
||||
<input
|
||||
type="text"
|
||||
value={exportPath}
|
||||
onChange={e => setExportPath (e.target.value)}
|
||||
placeholder="伊地知ニジカ/表情/泣き.png"
|
||||
aria-describedby={describedBy}
|
||||
aria-invalid={invalid}
|
||||
className={inputClass (invalid)}/>)}
|
||||
</FormField>
|
||||
|
||||
<div className="flex flex-wrap gap-2">
|
||||
<Button
|
||||
onClick={handleSubmit}
|
||||
className="rounded bg-blue-600 px-4 py-2 text-white
|
||||
disabled:bg-gray-400"
|
||||
disabled={updateMutation.isPending}>
|
||||
更新
|
||||
</Button>
|
||||
</div>
|
||||
</div>
|
||||
</Tab>
|
||||
</TabGroup>
|
||||
</>))}
|
||||
</>)}
|
||||
</MainArea>)
|
||||
}
|
||||
|
||||
|
||||
@@ -0,0 +1,189 @@
|
||||
import { useQuery } from '@tanstack/react-query'
|
||||
import { useEffect, useState } from 'react'
|
||||
import { Helmet } from 'react-helmet-async'
|
||||
import { useLocation, useNavigate } from 'react-router-dom'
|
||||
|
||||
import PrefetchLink from '@/components/PrefetchLink'
|
||||
import FormField from '@/components/common/FormField'
|
||||
import PageTitle from '@/components/common/PageTitle'
|
||||
import Pagination from '@/components/common/Pagination'
|
||||
import MainArea from '@/components/layout/MainArea'
|
||||
import { SITE_TITLE } from '@/config'
|
||||
import { fetchMaterialChanges } from '@/lib/materials'
|
||||
import { materialsKeys } from '@/lib/queryKeys'
|
||||
import { dateString, inputClass } from '@/lib/utils'
|
||||
|
||||
import type { FC, FormEvent } from 'react'
|
||||
|
||||
|
||||
const MaterialHistoryPage: FC = () => {
|
||||
const location = useLocation ()
|
||||
const navigate = useNavigate ()
|
||||
const query = new URLSearchParams (location.search)
|
||||
|
||||
const materialId = query.get ('material_id') ?? ''
|
||||
const tag = query.get ('tag') ?? ''
|
||||
const eventType = query.get ('event_type') ?? ''
|
||||
const page = Number (query.get ('page') ?? 1)
|
||||
const limit = Number (query.get ('limit') ?? 20)
|
||||
|
||||
const [materialIdInput, setMaterialIdInput] = useState (materialId)
|
||||
const [tagInput, setTagInput] = useState (tag)
|
||||
const [eventTypeInput, setEventTypeInput] = useState (eventType)
|
||||
|
||||
useEffect (() => {
|
||||
setMaterialIdInput (materialId)
|
||||
setTagInput (tag)
|
||||
setEventTypeInput (eventType)
|
||||
}, [eventType, materialId, tag])
|
||||
|
||||
const { data, isLoading, isError } = useQuery ({
|
||||
queryKey: materialsKeys.changes ({
|
||||
...(materialId && { materialId }),
|
||||
...(tag && { tag }),
|
||||
...(eventType && { eventType }),
|
||||
page,
|
||||
limit }),
|
||||
queryFn: () => fetchMaterialChanges ({
|
||||
...(materialId && { materialId }),
|
||||
...(tag && { tag }),
|
||||
...(eventType && { eventType }),
|
||||
page,
|
||||
limit }) })
|
||||
|
||||
const versions = data?.versions ?? []
|
||||
const totalPages = data ? Math.ceil (data.count / limit) : 0
|
||||
|
||||
useEffect (() => {
|
||||
document.querySelector ('table')?.scrollIntoView ({ behavior: 'smooth' })
|
||||
}, [location.search])
|
||||
|
||||
const handleSearch = (event: FormEvent) => {
|
||||
event.preventDefault ()
|
||||
|
||||
const qs = new URLSearchParams ()
|
||||
if (materialIdInput.trim ())
|
||||
qs.set ('material_id', materialIdInput.trim ())
|
||||
if (tagInput.trim ())
|
||||
qs.set ('tag', tagInput.trim ())
|
||||
if (eventTypeInput.trim ())
|
||||
qs.set ('event_type', eventTypeInput.trim ())
|
||||
qs.set ('page', '1')
|
||||
qs.set ('limit', String (limit))
|
||||
navigate (`/materials/changes?${ qs.toString () }`)
|
||||
}
|
||||
|
||||
return (
|
||||
<MainArea>
|
||||
<Helmet>
|
||||
<title>{`素材履歴 | ${ SITE_TITLE }`}</title>
|
||||
</Helmet>
|
||||
|
||||
<div className="space-y-5">
|
||||
<PageTitle>素材履歴</PageTitle>
|
||||
|
||||
<form
|
||||
onSubmit={handleSearch}
|
||||
className="max-w-3xl rounded-lg border border-stone-200 bg-white p-4
|
||||
text-stone-900 dark:border-stone-700 dark:bg-stone-900
|
||||
dark:text-stone-100">
|
||||
<div className="space-y-3">
|
||||
<FormField label="素材 ID">
|
||||
{({ invalid }) => (
|
||||
<input
|
||||
type="text"
|
||||
value={materialIdInput}
|
||||
onChange={e => setMaterialIdInput (e.target.value)}
|
||||
className={inputClass (invalid)}/>)}
|
||||
</FormField>
|
||||
|
||||
<FormField label="タグ名">
|
||||
{({ invalid }) => (
|
||||
<input
|
||||
type="text"
|
||||
value={tagInput}
|
||||
onChange={e => setTagInput (e.target.value)}
|
||||
className={inputClass (invalid)}/>)}
|
||||
</FormField>
|
||||
</div>
|
||||
|
||||
<button
|
||||
type="submit"
|
||||
className="mt-4 rounded-full border border-stone-300 bg-white px-4 py-2
|
||||
text-sm text-stone-900 hover:bg-stone-100 dark:border-stone-700
|
||||
dark:bg-stone-900 dark:text-stone-100 dark:hover:bg-stone-800">
|
||||
絞り込む
|
||||
</button>
|
||||
</form>
|
||||
|
||||
{isLoading
|
||||
? 'Loading...'
|
||||
: isError
|
||||
? (
|
||||
<p className="text-red-600 dark:text-red-300">
|
||||
素材履歴の取得に失敗しました.
|
||||
</p>)
|
||||
: (
|
||||
<>
|
||||
<div className="overflow-x-auto">
|
||||
<table className="w-full min-w-[1200px] table-fixed border-collapse">
|
||||
<colgroup>
|
||||
<col className="w-48"/>
|
||||
<col className="w-28"/>
|
||||
<col className="w-24"/>
|
||||
<col className="w-64"/>
|
||||
<col className="w-64"/>
|
||||
<col className="w-80"/>
|
||||
<col className="w-80"/>
|
||||
<col className="w-48"/>
|
||||
</colgroup>
|
||||
|
||||
<thead className="border-b-2 border-black dark:border-white">
|
||||
<tr>
|
||||
<th className="p-2 text-left">日時</th>
|
||||
<th className="p-2 text-left">素材 ID</th>
|
||||
<th className="p-2 text-left">版</th>
|
||||
<th className="p-2 text-left">タグ名</th>
|
||||
<th className="p-2 text-left">ファイル名</th>
|
||||
<th className="p-2 text-left">URL</th>
|
||||
<th className="p-2 text-left">export_path</th>
|
||||
<th className="p-2 text-left">操作者</th>
|
||||
</tr>
|
||||
</thead>
|
||||
|
||||
<tbody>
|
||||
{versions.map (version => (
|
||||
<tr
|
||||
key={version.id}
|
||||
className="even:bg-gray-100 dark:even:bg-gray-700">
|
||||
<td className="p-2">{dateString (version.createdAt)}</td>
|
||||
<td className="p-2">
|
||||
<PrefetchLink to={`/materials/${ version.materialId }`}>
|
||||
#{version.materialId}
|
||||
</PrefetchLink>
|
||||
</td>
|
||||
<td className="p-2">{version.versionNo}</td>
|
||||
<td className="p-2 break-all">{version.tagName}</td>
|
||||
<td className="p-2 break-all">{version.fileFilename}</td>
|
||||
<td className="p-2 break-all">{version.url}</td>
|
||||
<td className="p-2 break-all">
|
||||
{version.exportPathsJson.legacy_drive}
|
||||
</td>
|
||||
<td className="p-2">
|
||||
{version.createdByUser
|
||||
? version.createdByUser.name || `#${ version.createdByUser.id }`
|
||||
: 'bot 操作'}
|
||||
</td>
|
||||
</tr>))}
|
||||
</tbody>
|
||||
</table>
|
||||
</div>
|
||||
|
||||
<Pagination page={page} totalPages={totalPages}/>
|
||||
</>)}
|
||||
</div>
|
||||
</MainArea>)
|
||||
}
|
||||
|
||||
|
||||
export default MaterialHistoryPage
|
||||
@@ -1,5 +1,5 @@
|
||||
import { screen, waitFor } from '@testing-library/react'
|
||||
import { describe, expect, it, vi } from 'vitest'
|
||||
import { fireEvent, screen, waitFor } from '@testing-library/react'
|
||||
import { beforeEach, describe, expect, it, vi } from 'vitest'
|
||||
|
||||
import MaterialListPage from '@/pages/materials/MaterialListPage'
|
||||
import { buildMaterial, buildTag } from '@/test/factories'
|
||||
@@ -12,51 +12,169 @@ const api = vi.hoisted (() => ({
|
||||
vi.mock ('@/lib/api', () => api)
|
||||
|
||||
describe ('MaterialListPage', () => {
|
||||
it ('shows the empty selection guide without a tag query', () => {
|
||||
renderWithProviders (<MaterialListPage/>, { route: '/materials' })
|
||||
|
||||
expect (screen.getByText ('左のリストから照会したいタグを選択してください。')).toBeInTheDocument ()
|
||||
expect (screen.getByRole ('link', { name: '素材を新規追加する' })).toHaveAttribute (
|
||||
'href',
|
||||
'/materials/new',
|
||||
)
|
||||
beforeEach (() => {
|
||||
vi.clearAllMocks ()
|
||||
api.apiGet.mockResolvedValue ({ materials: [], count: 0 })
|
||||
})
|
||||
|
||||
it ('loads materials for a tag query', async () => {
|
||||
const tag = {
|
||||
...buildTag ({
|
||||
id: 4,
|
||||
name: '素材タグ',
|
||||
category: 'material',
|
||||
}),
|
||||
material: buildMaterial ({ id: 8, contentType: 'image/png', file: 'image.png' }),
|
||||
children: [],
|
||||
}
|
||||
api.apiGet.mockResolvedValueOnce (tag)
|
||||
|
||||
renderWithProviders (<MaterialListPage/>, { route: '/materials?tag=%E7%B4%A0%E6%9D%90' })
|
||||
it ('loads the material index on the initial page', async () => {
|
||||
renderWithProviders (<MaterialListPage/>, { route: '/materials' })
|
||||
|
||||
await waitFor (() => {
|
||||
expect (api.apiGet).toHaveBeenCalledWith (
|
||||
'/tags/name/%E7%B4%A0%E6%9D%90/materials',
|
||||
'/materials',
|
||||
{ params: {
|
||||
tag_state: 'all',
|
||||
media_kind: 'all',
|
||||
sort: 'created_at',
|
||||
direction: 'desc',
|
||||
page: 1,
|
||||
limit: 20,
|
||||
} },
|
||||
)
|
||||
})
|
||||
expect (await screen.findByRole ('link', { name: '素材タグ' })).toBeInTheDocument ()
|
||||
expect (screen.getByRole ('link', { name: '' })).toHaveAttribute ('href', '/materials/8')
|
||||
expect (await screen.findByText ('素材はありません。')).toBeInTheDocument ()
|
||||
})
|
||||
|
||||
it ('offers adding a missing non-meme material', async () => {
|
||||
it ('shows materials in the default card view', async () => {
|
||||
api.apiGet.mockResolvedValueOnce ({
|
||||
...buildTag ({ name: '未登録', category: 'material' }),
|
||||
material: null,
|
||||
children: [],
|
||||
materials: [
|
||||
buildMaterial ({
|
||||
id: 8,
|
||||
tag: buildTag ({ name: '素材タグ', category: 'material' }),
|
||||
thumbnail: 'thumb.png',
|
||||
mediaKind: 'image',
|
||||
contentType: 'image/png',
|
||||
}),
|
||||
],
|
||||
count: 1,
|
||||
})
|
||||
|
||||
renderWithProviders (<MaterialListPage/>, { route: '/materials?tag=x' })
|
||||
renderWithProviders (<MaterialListPage/>, { route: '/materials' })
|
||||
|
||||
expect (await screen.findByRole ('link', { name: '追加' })).toHaveAttribute (
|
||||
expect ((await screen.findByText ('素材タグ')).closest ('a'))
|
||||
.toHaveAttribute ('href', '/materials/8')
|
||||
expect (screen.getByText (/画像 \/ 令和8年1月2日/)).toBeInTheDocument ()
|
||||
})
|
||||
|
||||
it ('submits list filters as material index params', async () => {
|
||||
renderWithProviders (<MaterialListPage/>, { route: '/materials' })
|
||||
|
||||
fireEvent.change (screen.getByPlaceholderText ('タグ名 / URL / ファイル名'), {
|
||||
target: { value: '虹夏' },
|
||||
})
|
||||
const selects = screen.getAllByRole ('combobox')
|
||||
fireEvent.change (selects[0], {
|
||||
target: { value: 'untagged' },
|
||||
})
|
||||
fireEvent.change (selects[1], {
|
||||
target: { value: 'image' },
|
||||
})
|
||||
fireEvent.click (screen.getByRole ('button', { name: '検索' }))
|
||||
|
||||
await waitFor (() => {
|
||||
expect (api.apiGet).toHaveBeenCalledWith (
|
||||
'/materials',
|
||||
expect.objectContaining ({ params: expect.objectContaining ({
|
||||
q: '虹夏',
|
||||
tag_state: 'untagged',
|
||||
media_kind: 'image',
|
||||
}) }),
|
||||
)
|
||||
})
|
||||
})
|
||||
|
||||
it ('keeps a route back to the material search top for untagged materials', async () => {
|
||||
renderWithProviders (
|
||||
<MaterialListPage/>,
|
||||
{ route: '/materials?tag_state=untagged&material_filter=any' },
|
||||
)
|
||||
|
||||
expect (await screen.findByRole (
|
||||
'link',
|
||||
{ name: '素材検索トップへ戻る' },
|
||||
)).toHaveAttribute ('href', '/materials?material_filter=any')
|
||||
})
|
||||
|
||||
it ('uses list view for detailed material rows', async () => {
|
||||
api.apiGet.mockResolvedValueOnce ({
|
||||
materials: [
|
||||
buildMaterial ({
|
||||
id: 9,
|
||||
tag: buildTag ({ name: '詳細素材', category: 'material' }),
|
||||
mediaKind: 'file_other',
|
||||
fileByteSize: 2048,
|
||||
}),
|
||||
],
|
||||
count: 1,
|
||||
})
|
||||
|
||||
renderWithProviders (<MaterialListPage/>, { route: '/materials?view=list' })
|
||||
|
||||
expect (await screen.findByRole ('link', { name: '詳細素材' })).toHaveAttribute (
|
||||
'href',
|
||||
'/materials/new?tag=%E6%9C%AA%E7%99%BB%E9%8C%B2',
|
||||
'/materials/9',
|
||||
)
|
||||
expect (screen.getByText ('サイズ:')).toBeInTheDocument ()
|
||||
expect (screen.getByText ('2.0 KB')).toBeInTheDocument ()
|
||||
})
|
||||
|
||||
it ('shows the selected tag scope and tag-specific add links', async () => {
|
||||
api.apiGet.mockResolvedValueOnce ({
|
||||
materials: [
|
||||
buildMaterial ({
|
||||
id: 10,
|
||||
tag: buildTag ({ id: 30, name: '泣き', category: 'material' }),
|
||||
}),
|
||||
],
|
||||
count: 1,
|
||||
tagScope: {
|
||||
tag: { id: 20, name: '伊地知ニジカ', category: 'material' },
|
||||
includeDescendants: true,
|
||||
},
|
||||
groups: [
|
||||
{
|
||||
key: 'tag:30',
|
||||
tag: { id: 30, name: '泣き', category: 'material' },
|
||||
materialIds: [10],
|
||||
count: 1,
|
||||
},
|
||||
],
|
||||
})
|
||||
|
||||
renderWithProviders (
|
||||
<MaterialListPage/>,
|
||||
{ route: '/materials?tag_id=20&include_descendants=1&group_by=parent_tag' },
|
||||
)
|
||||
|
||||
expect (await screen.findByText (
|
||||
(_, element) => element?.textContent === '伊地知ニジカ 配下の素材を表示中',
|
||||
)).toBeInTheDocument ()
|
||||
|
||||
expect (screen.getByRole ('link', { name: '泣き' })).toHaveAttribute (
|
||||
'href',
|
||||
'/materials?tag_id=30&include_descendants=1&group_by=parent_tag&material_filter=present',
|
||||
)
|
||||
expect (screen.getByRole ('link', { name: 'タグ選択を解除' })).toHaveAttribute (
|
||||
'href',
|
||||
'/materials?material_filter=present',
|
||||
)
|
||||
})
|
||||
|
||||
it ('shows a clear link when tag_id does not resolve to tag_scope', async () => {
|
||||
api.apiGet.mockResolvedValueOnce ({
|
||||
materials: [],
|
||||
count: 0,
|
||||
tagScope: null,
|
||||
groups: [],
|
||||
})
|
||||
|
||||
renderWithProviders (<MaterialListPage/>, { route: '/materials?tag_id=999' })
|
||||
|
||||
expect (await screen.findByText ('選択中タグが見つかりません.')).toBeInTheDocument ()
|
||||
expect (screen.getByRole ('link', { name: 'タグ選択を解除' })).toHaveAttribute (
|
||||
'href',
|
||||
'/materials?material_filter=present',
|
||||
)
|
||||
})
|
||||
})
|
||||
|
||||
@@ -1,75 +1,395 @@
|
||||
import { Fragment, useEffect, useState } from 'react'
|
||||
import { useQuery } from '@tanstack/react-query'
|
||||
import { useEffect, useMemo, useState } from 'react'
|
||||
import { Helmet } from 'react-helmet-async'
|
||||
import { useLocation } from 'react-router-dom'
|
||||
import { useLocation, useNavigate } from 'react-router-dom'
|
||||
|
||||
import nikumaru from '@/assets/fonts/nikumaru.otf'
|
||||
import PrefetchLink from '@/components/PrefetchLink'
|
||||
import TagLink from '@/components/TagLink'
|
||||
import DateTimeField from '@/components/common/DateTimeField'
|
||||
import FormField from '@/components/common/FormField'
|
||||
import PageTitle from '@/components/common/PageTitle'
|
||||
import SectionTitle from '@/components/common/SectionTitle'
|
||||
import SubsectionTitle from '@/components/common/SubsectionTitle'
|
||||
import Pagination from '@/components/common/Pagination'
|
||||
import MainArea from '@/components/layout/MainArea'
|
||||
import { SITE_TITLE } from '@/config'
|
||||
import { apiGet } from '@/lib/api'
|
||||
import { fetchMaterials, parseMaterialFilter } from '@/lib/materials'
|
||||
import { materialsKeys } from '@/lib/queryKeys'
|
||||
import { dateString, inputClass } from '@/lib/utils'
|
||||
|
||||
import type { FC } from 'react'
|
||||
import type { FC, FormEvent } from 'react'
|
||||
|
||||
import type { Material, Tag } from '@/types'
|
||||
import type { FetchMaterialsParams,
|
||||
Material,
|
||||
MaterialFilter,
|
||||
MaterialIndexGroup,
|
||||
MaterialIndexGroupBy,
|
||||
MaterialIndexDirection,
|
||||
MaterialIndexMediaKind,
|
||||
MaterialIndexSort,
|
||||
MaterialIndexTagState,
|
||||
MaterialIndexView } from '@/types'
|
||||
|
||||
type TagWithMaterial = Omit<Tag, 'children'> & {
|
||||
children: TagWithMaterial[]
|
||||
material: Material | null }
|
||||
const MEDIA_KIND_LABELS: Record<Material['mediaKind'], string> = {
|
||||
image: '画像',
|
||||
video: '動画',
|
||||
audio: '音声',
|
||||
file_other: 'その他ファイル',
|
||||
url_only: 'URL のみ'}
|
||||
|
||||
const MEDIA_FILTER_LABELS: Record<MaterialIndexMediaKind, string> = {
|
||||
all: 'すべて',
|
||||
image: '画像',
|
||||
video: '動画',
|
||||
audio: '音声',
|
||||
file_other: 'その他ファイル',
|
||||
url_only: '外部リンクのみ'}
|
||||
|
||||
const SORT_LABELS: Record<MaterialIndexSort, string> = {
|
||||
created_at: '作成日時',
|
||||
updated_at: '更新日時',
|
||||
tag_name: 'タグ名',
|
||||
media_kind: '種類',
|
||||
file_byte_size: '容量',
|
||||
version_no: '版',
|
||||
id: 'Id.'}
|
||||
|
||||
|
||||
const MaterialCard = ({ tag }: { tag: TagWithMaterial }) => {
|
||||
if (!(tag.material))
|
||||
return
|
||||
|
||||
return (
|
||||
<PrefetchLink
|
||||
to={`/materials/${ tag.material.id }`}
|
||||
className="block w-40 h-40">
|
||||
<div
|
||||
className="w-full h-full overflow-hidden rounded-xl shadow
|
||||
text-center content-center text-4xl"
|
||||
style={{ fontFamily: 'Nikumaru' }}>
|
||||
{(tag.material.contentType && /image\/.*/.test (tag.material.contentType))
|
||||
? <img src={tag.material.file || undefined}/>
|
||||
: <span>照会</span>}
|
||||
</div>
|
||||
</PrefetchLink>)
|
||||
const setIf = (qs: URLSearchParams, key: string, value: string | null) => {
|
||||
const next = value?.trim ()
|
||||
if (next)
|
||||
qs.set (key, next)
|
||||
}
|
||||
|
||||
|
||||
const MaterialListPage: FC = () => {
|
||||
const [loading, setLoading] = useState (false)
|
||||
const [tag, setTag] = useState<TagWithMaterial | null> (null)
|
||||
const parseOption = <T extends string> (
|
||||
value: string | null,
|
||||
allowed: readonly T[],
|
||||
fallback: T): T => allowed.includes (value as T) ? value as T : fallback
|
||||
|
||||
|
||||
const fileSizeText = (bytes: number | null): string => {
|
||||
if (bytes == null)
|
||||
return ''
|
||||
if (bytes < 1024)
|
||||
return `${ bytes } B`
|
||||
if (bytes < 1024 * 1024)
|
||||
return `${ (bytes / 1024).toFixed (1) } KB`
|
||||
return `${ (bytes / 1024 / 1024).toFixed (1) } MB`
|
||||
}
|
||||
|
||||
|
||||
const materialTitle = (material: Material): string =>
|
||||
material.tag?.name ?? `素材 #${ material.id }`
|
||||
|
||||
|
||||
const groupedTagPath = (
|
||||
tagId: number,
|
||||
materialFilter: MaterialFilter,
|
||||
): string =>
|
||||
`/materials?tag_id=${ tagId }&include_descendants=1&group_by=parent_tag`
|
||||
+ `&material_filter=${ materialFilter }`
|
||||
|
||||
|
||||
const materialNewPath = (
|
||||
tagName: string,
|
||||
returnTo: string,
|
||||
): string =>
|
||||
`/materials/new?tag=${ encodeURIComponent (tagName) }`
|
||||
+ `&return_to=${ encodeURIComponent (returnTo) }`
|
||||
|
||||
|
||||
const clearedTagSelectionPath = (
|
||||
locationSearch: string,
|
||||
materialFilter: MaterialFilter,
|
||||
): string => {
|
||||
const qs = new URLSearchParams (locationSearch)
|
||||
qs.delete ('tag_id')
|
||||
qs.delete ('include_descendants')
|
||||
qs.delete ('group_by')
|
||||
qs.delete ('page')
|
||||
qs.set ('material_filter', materialFilter)
|
||||
return `/materials?${ qs.toString () }`
|
||||
}
|
||||
|
||||
|
||||
const MaterialThumb: FC<{ material: Material }> = ({ material }) => (
|
||||
<div
|
||||
className={`flex aspect-square h-[180px] w-[180px] items-center justify-center
|
||||
overflow-hidden rounded-lg border border-stone-200 bg-white text-center
|
||||
text-stone-900 shadow-sm dark:border-stone-700 dark:bg-stone-900
|
||||
dark:text-stone-100`}>
|
||||
{material.thumbnail
|
||||
? <img src={material.thumbnail} alt="" className="block h-full w-full object-cover"/>
|
||||
: (
|
||||
<span
|
||||
className="px-2 text-2xl leading-tight"
|
||||
style={{ fontFamily: material.thumbnailFallbackKind === 'tag_name'
|
||||
? 'Nikumaru'
|
||||
: undefined }}>
|
||||
{material.thumbnailFallbackText}
|
||||
</span>)}
|
||||
</div>)
|
||||
|
||||
|
||||
const MaterialCard: FC<{ material: Material }> = ({ material }) => (
|
||||
<article className="w-[180px] justify-self-center">
|
||||
<PrefetchLink to={`/materials/${ material.id }`} className="block">
|
||||
<MaterialThumb material={material}/>
|
||||
<div className="mt-2 w-[180px]">
|
||||
<p className="truncate text-sm font-medium text-stone-900 dark:text-stone-100">
|
||||
{materialTitle (material)}
|
||||
</p>
|
||||
<p className="truncate text-xs text-stone-600 dark:text-stone-300">
|
||||
{MEDIA_KIND_LABELS[material.mediaKind]} / {dateString (material.createdAt)}
|
||||
</p>
|
||||
</div>
|
||||
</PrefetchLink>
|
||||
</article>)
|
||||
|
||||
|
||||
const MaterialListItem: FC<{ material: Material }> = ({ material }) => (
|
||||
<article
|
||||
className="rounded-lg border border-stone-200 bg-white p-3 text-stone-900
|
||||
shadow-sm dark:border-stone-700 dark:bg-stone-900 dark:text-stone-100">
|
||||
<div className="flex gap-3">
|
||||
<MaterialThumb material={material}/>
|
||||
<div className="min-w-0 flex-1 space-y-2">
|
||||
<div>
|
||||
<PrefetchLink
|
||||
to={`/materials/${ material.id }`}
|
||||
className="font-medium text-sky-700 underline underline-offset-2
|
||||
dark:text-sky-300">
|
||||
{materialTitle (material)}
|
||||
</PrefetchLink>
|
||||
</div>
|
||||
<dl className="space-y-1 text-sm text-stone-600 dark:text-stone-300">
|
||||
<div>
|
||||
<dt className="inline">種類: </dt>
|
||||
<dd className="inline">{MEDIA_KIND_LABELS[material.mediaKind]}</dd>
|
||||
</div>
|
||||
{material.fileByteSize != null && (
|
||||
<div>
|
||||
<dt className="inline">サイズ: </dt>
|
||||
<dd className="inline">{fileSizeText (material.fileByteSize)}</dd>
|
||||
</div>)}
|
||||
{material.url && (
|
||||
<div>
|
||||
<dt className="inline">URL: </dt>
|
||||
<dd className="inline break-all">{material.url}</dd>
|
||||
</div>)}
|
||||
<div>
|
||||
<dt className="inline">作成: </dt>
|
||||
<dd className="inline">{dateString (material.createdAt)}</dd>
|
||||
</div>
|
||||
</dl>
|
||||
</div>
|
||||
</div>
|
||||
</article>)
|
||||
|
||||
|
||||
const GroupHeading: FC<{
|
||||
count: number
|
||||
materialFilter: MaterialFilter
|
||||
title: string
|
||||
tagId: number
|
||||
}> = ({ count, materialFilter, title, tagId }) => (
|
||||
<div className="flex items-center gap-2 border-b border-stone-200 pb-2
|
||||
dark:border-stone-700">
|
||||
<PrefetchLink
|
||||
to={groupedTagPath (tagId, materialFilter)}
|
||||
className="font-medium text-sky-700 underline underline-offset-2
|
||||
dark:text-sky-300 w-full">
|
||||
{title}
|
||||
</PrefetchLink>
|
||||
<div className="text-right w-auto">
|
||||
<span className="text-nowrap text-sm text-stone-600 dark:text-stone-300">
|
||||
{count} 件
|
||||
</span>
|
||||
</div>
|
||||
</div>)
|
||||
|
||||
|
||||
const MaterialListPage: FC = () => {
|
||||
const location = useLocation ()
|
||||
const query = new URLSearchParams (location.search)
|
||||
const tagQuery = query.get ('tag') ?? ''
|
||||
const navigate = useNavigate ()
|
||||
const query = useMemo (() => new URLSearchParams (location.search), [location.search])
|
||||
const materialFilter = parseMaterialFilter (query.get ('material_filter'), 'present')
|
||||
|
||||
const page = Number (query.get ('page') ?? 1)
|
||||
const limit = Number (query.get ('limit') ?? 20)
|
||||
const qQuery = query.get ('q') ?? ''
|
||||
const tagIdQuery = Number (query.get ('tag_id') ?? 0)
|
||||
const tagId = tagIdQuery > 0 ? tagIdQuery : null
|
||||
const includeDescendants = query.get ('include_descendants') === '1'
|
||||
const tagState = query.get ('unclassified') === '1'
|
||||
? 'untagged'
|
||||
: parseOption<MaterialIndexTagState> (
|
||||
query.get ('tag_state'),
|
||||
['all', 'tagged', 'untagged'],
|
||||
'all')
|
||||
const mediaKind = parseOption<MaterialIndexMediaKind> (
|
||||
query.get ('media_kind'),
|
||||
['all', 'image', 'video', 'audio', 'file_other', 'url_only'],
|
||||
'all')
|
||||
const sort = parseOption<MaterialIndexSort> (
|
||||
query.get ('sort'),
|
||||
['created_at', 'updated_at', 'tag_name', 'media_kind', 'file_byte_size',
|
||||
'version_no', 'id'],
|
||||
'created_at')
|
||||
const direction = parseOption<MaterialIndexDirection> (
|
||||
query.get ('direction'),
|
||||
['asc', 'desc'],
|
||||
'desc')
|
||||
const groupByQuery = parseOption<MaterialIndexGroupBy> (
|
||||
query.get ('group_by'),
|
||||
['none', 'parent_tag'],
|
||||
'none')
|
||||
const groupBy = tagId == null ? 'none' : groupByQuery
|
||||
const view = parseOption<MaterialIndexView> (query.get ('view'), ['card', 'list'], 'card')
|
||||
const createdFromQuery = query.get ('created_from') ?? ''
|
||||
const createdToQuery = query.get ('created_to') ?? ''
|
||||
const updatedFromQuery = query.get ('updated_from') ?? ''
|
||||
const updatedToQuery = query.get ('updated_to') ?? ''
|
||||
|
||||
const [q, setQ] = useState ('')
|
||||
const [tagStateInput, setTagStateInput] = useState<MaterialIndexTagState> ('all')
|
||||
const [mediaKindInput, setMediaKindInput] = useState<MaterialIndexMediaKind> ('all')
|
||||
const [groupByInput, setGroupByInput] = useState<MaterialIndexGroupBy> ('none')
|
||||
const [createdFrom, setCreatedFrom] = useState<string | null> (null)
|
||||
const [createdTo, setCreatedTo] = useState<string | null> (null)
|
||||
const [updatedFrom, setUpdatedFrom] = useState<string | null> (null)
|
||||
const [updatedTo, setUpdatedTo] = useState<string | null> (null)
|
||||
|
||||
const keys: FetchMaterialsParams = {
|
||||
q: qQuery,
|
||||
tagState,
|
||||
mediaKind,
|
||||
tagId,
|
||||
includeDescendants,
|
||||
groupBy,
|
||||
createdFrom: createdFromQuery,
|
||||
createdTo: createdToQuery,
|
||||
updatedFrom: updatedFromQuery,
|
||||
updatedTo: updatedToQuery,
|
||||
sort,
|
||||
direction,
|
||||
view,
|
||||
page,
|
||||
limit}
|
||||
const { data, isLoading, isError } = useQuery ({
|
||||
queryKey: materialsKeys.index (keys),
|
||||
queryFn: () => fetchMaterials (keys)})
|
||||
const tagScope = data?.tagScope ?? null
|
||||
const materials = data?.materials ?? []
|
||||
const groups = data?.groups ?? []
|
||||
const totalPages = data ? Math.ceil (data.count / limit) : 0
|
||||
const materialsById = useMemo (
|
||||
() => new Map (materials.map (material => [material.id, material])),
|
||||
[materials],
|
||||
)
|
||||
const groupedMaterialIds = useMemo (
|
||||
() => new Set (groups.flatMap (group => group.materialIds)),
|
||||
[groups],
|
||||
)
|
||||
const ungroupedMaterials = useMemo (
|
||||
() => materials.filter (material => !groupedMaterialIds.has (material.id)),
|
||||
[groupedMaterialIds, materials],
|
||||
)
|
||||
|
||||
useEffect (() => {
|
||||
if (!(tagQuery))
|
||||
{
|
||||
setTag (null)
|
||||
return
|
||||
}
|
||||
setQ (qQuery)
|
||||
setTagStateInput (tagState)
|
||||
setMediaKindInput (mediaKind)
|
||||
setGroupByInput (groupBy)
|
||||
setCreatedFrom (createdFromQuery)
|
||||
setCreatedTo (createdToQuery)
|
||||
setUpdatedFrom (updatedFromQuery)
|
||||
setUpdatedTo (updatedToQuery)
|
||||
}, [createdFromQuery, createdToQuery, groupBy, mediaKind, qQuery, tagState,
|
||||
updatedFromQuery, updatedToQuery])
|
||||
|
||||
void (async () => {
|
||||
try
|
||||
{
|
||||
setLoading (true)
|
||||
setTag (
|
||||
await apiGet<TagWithMaterial> (
|
||||
`/tags/name/${ encodeURIComponent (tagQuery) }/materials`))
|
||||
}
|
||||
finally
|
||||
{
|
||||
setLoading (false)
|
||||
}
|
||||
}) ()
|
||||
}, [location.search, tagQuery])
|
||||
const search = (e: FormEvent) => {
|
||||
e.preventDefault ()
|
||||
|
||||
const qs = new URLSearchParams ()
|
||||
setIf (qs, 'q', q)
|
||||
qs.set ('tag_state', tagStateInput)
|
||||
qs.set ('media_kind', mediaKindInput)
|
||||
setIf (qs, 'created_from', createdFrom)
|
||||
setIf (qs, 'created_to', createdTo)
|
||||
setIf (qs, 'updated_from', updatedFrom)
|
||||
setIf (qs, 'updated_to', updatedTo)
|
||||
qs.set ('sort', sort)
|
||||
qs.set ('direction', direction)
|
||||
qs.set ('group_by', tagId == null ? 'none' : groupByInput)
|
||||
qs.set ('view', view)
|
||||
qs.set ('page', '1')
|
||||
qs.set ('limit', String (limit))
|
||||
qs.set ('material_filter', materialFilter)
|
||||
if (tagId != null)
|
||||
qs.set ('tag_id', String (tagId))
|
||||
|
||||
if (includeDescendants)
|
||||
qs.set ('include_descendants', '1')
|
||||
|
||||
navigate (`/materials?${ qs.toString () }`)
|
||||
}
|
||||
|
||||
const updateQuery = (changes: Record<string, string>) => {
|
||||
const qs = new URLSearchParams (location.search)
|
||||
Object.entries (changes).forEach (([key, value]) => {
|
||||
if (value === '')
|
||||
qs.delete (key)
|
||||
else
|
||||
qs.set (key, value)
|
||||
})
|
||||
navigate (`/materials?${ qs.toString () }`)
|
||||
}
|
||||
|
||||
const renderMaterialCollection = (rows: Material[]) =>
|
||||
view === 'card'
|
||||
? (
|
||||
<div className="grid grid-cols-[repeat(auto-fill,minmax(196px,1fr))]
|
||||
justify-items-center gap-4">
|
||||
{rows.map (material => (
|
||||
<MaterialCard key={material.id} material={material}/>))}
|
||||
</div>)
|
||||
: (
|
||||
<div className="space-y-3">
|
||||
{rows.map (material => (
|
||||
<MaterialListItem key={material.id} material={material}/>))}
|
||||
</div>)
|
||||
|
||||
const renderGroupedMaterials = (materialGroups: MaterialIndexGroup[]) => (
|
||||
<div className="space-y-6">
|
||||
{materialGroups.map (group => {
|
||||
const groupMaterials =
|
||||
group.materialIds
|
||||
.map (materialId => materialsById.get (materialId))
|
||||
.filter ((material): material is Material => material != null)
|
||||
|
||||
if (groupMaterials.length === 0)
|
||||
return null
|
||||
|
||||
return (
|
||||
<section key={group.key} className="space-y-3">
|
||||
<GroupHeading
|
||||
tagId={group.tag.id}
|
||||
title={group.tag.name}
|
||||
count={group.count}
|
||||
materialFilter={materialFilter}/>
|
||||
{renderMaterialCollection (groupMaterials)}
|
||||
</section>)
|
||||
})}
|
||||
{ungroupedMaterials.length > 0 && (
|
||||
<section className="space-y-3">
|
||||
<div className="border-b border-stone-200 pb-2 dark:border-stone-700">
|
||||
<span className="font-medium text-stone-900 dark:text-stone-100">
|
||||
その他
|
||||
</span>
|
||||
</div>
|
||||
{renderMaterialCollection (ungroupedMaterials)}
|
||||
</section>)}
|
||||
</div>)
|
||||
|
||||
return (
|
||||
<MainArea>
|
||||
@@ -82,86 +402,205 @@ const MaterialListPage: FC = () => {
|
||||
src: url(${ nikumaru }) format('opentype');
|
||||
}`}
|
||||
</style>
|
||||
<title>{`${ tag ? `${ tag.name } 素材集` : '素材集' } | ${ SITE_TITLE }`}</title>
|
||||
<title>{`素材管理 | ${ SITE_TITLE }`}</title>
|
||||
</Helmet>
|
||||
|
||||
{loading ? 'Loading...' : (
|
||||
tag
|
||||
? (
|
||||
<>
|
||||
<PageTitle>
|
||||
<TagLink
|
||||
tag={tag}
|
||||
withWiki={false}
|
||||
withCount={false}
|
||||
to={tag.material
|
||||
? `/materials/${ tag.material.id }`
|
||||
: `/materials?tag=${ encodeURIComponent (tag.name) }`}/>
|
||||
</PageTitle>
|
||||
{(!(tag.material) && tag.category !== 'meme') && (
|
||||
<div className="-mt-2">
|
||||
<PrefetchLink
|
||||
to={`/materials/new?tag=${ encodeURIComponent (tag.name) }`}>
|
||||
追加
|
||||
</PrefetchLink>
|
||||
</div>)}
|
||||
<div className="space-y-5">
|
||||
<div className="flex flex-wrap items-center justify-between gap-3">
|
||||
<PageTitle className="my-auto">素材管理</PageTitle>
|
||||
<div className="flex flex-wrap gap-2">
|
||||
{/* TODO: 局所出力を可能にする */}
|
||||
{/* <a
|
||||
href={`${ API_BASE_URL }/materials/download.zip?profile=legacy_drive`}
|
||||
target="_blank"
|
||||
rel="noopener noreferrer"
|
||||
className="rounded-full border border-stone-300 bg-white px-4 py-2 text-sm
|
||||
text-stone-900 hover:bg-stone-100 dark:border-stone-700
|
||||
dark:bg-stone-900 dark:text-stone-100 dark:hover:bg-stone-800">
|
||||
ZIP をダウンロード
|
||||
</a> */}
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<MaterialCard tag={tag}/>
|
||||
{tagScope && (
|
||||
<div className="flex flex-wrap items-center gap-3 rounded-lg border
|
||||
border-sky-200 bg-sky-50 px-4 py-3 text-sm text-sky-900
|
||||
dark:border-sky-800 dark:bg-sky-950 dark:text-sky-100">
|
||||
<span>
|
||||
{tagScope.tag.name}
|
||||
{tagScope.includeDescendants ? ' 配下の素材を表示中' : ' の素材を表示中'}
|
||||
</span>
|
||||
<PrefetchLink
|
||||
to={clearedTagSelectionPath (location.search, materialFilter)}
|
||||
className="font-medium underline underline-offset-2
|
||||
text-sky-700 dark:text-sky-300">
|
||||
タグ選択を解除
|
||||
</PrefetchLink>
|
||||
</div>)}
|
||||
{(tagId != null && tagScope == null) && (
|
||||
<div className="flex flex-wrap items-center gap-3 rounded-lg border
|
||||
border-amber-200 bg-amber-50 px-4 py-3 text-sm text-amber-900
|
||||
dark:border-amber-800 dark:bg-amber-950 dark:text-amber-100">
|
||||
<span>選択中タグが見つかりません.</span>
|
||||
<PrefetchLink
|
||||
to={clearedTagSelectionPath (location.search, materialFilter)}
|
||||
className="font-medium underline underline-offset-2
|
||||
text-amber-800 dark:text-amber-200">
|
||||
タグ選択を解除
|
||||
</PrefetchLink>
|
||||
</div>)}
|
||||
|
||||
<div className="ml-2">
|
||||
{tag.children.map (c2 => (
|
||||
<Fragment key={c2.id}>
|
||||
<SectionTitle>
|
||||
<TagLink
|
||||
tag={c2}
|
||||
withWiki={false}
|
||||
withCount={false}
|
||||
to={`/materials?tag=${ encodeURIComponent (c2.name) }`}/>
|
||||
</SectionTitle>
|
||||
{(!(c2.material) && c2.category !== 'meme') && (
|
||||
<div className="-mt-4">
|
||||
<PrefetchLink
|
||||
to={`/materials/new?tag=${ encodeURIComponent (c2.name) }`}>
|
||||
追加
|
||||
</PrefetchLink>
|
||||
</div>)}
|
||||
{tagState === 'untagged' && (
|
||||
<PrefetchLink
|
||||
to={`/materials?material_filter=${ materialFilter }`}
|
||||
className="text-sm text-sky-700 underline underline-offset-2 dark:text-sky-300">
|
||||
素材検索トップへ戻る
|
||||
</PrefetchLink>)}
|
||||
|
||||
<MaterialCard tag={c2}/>
|
||||
<form
|
||||
onSubmit={search}
|
||||
className="max-w-3xl rounded-lg border border-stone-200 bg-white p-4
|
||||
text-stone-900 dark:border-stone-700 dark:bg-stone-900
|
||||
dark:text-stone-100">
|
||||
<div className="space-y-3">
|
||||
<FormField label="検索">
|
||||
{({ invalid }) => (
|
||||
<input
|
||||
type="search"
|
||||
value={q}
|
||||
onChange={e => setQ (e.target.value)}
|
||||
placeholder="タグ名 / URL / ファイル名"
|
||||
className={inputClass (invalid)}/>)}
|
||||
</FormField>
|
||||
|
||||
<div className="ml-2">
|
||||
{c2.children.map (c3 => (
|
||||
<Fragment key={c3.id}>
|
||||
<SubsectionTitle>
|
||||
<TagLink
|
||||
tag={c3}
|
||||
withWiki={false}
|
||||
withCount={false}
|
||||
to={`/materials?tag=${ encodeURIComponent (c3.name) }`}/>
|
||||
</SubsectionTitle>
|
||||
{(!(c3.material) && c3.category !== 'meme') && (
|
||||
<div className="-mt-2">
|
||||
<PrefetchLink
|
||||
to={`/materials/new?tag=${
|
||||
encodeURIComponent (c3.name) }`}>
|
||||
追加
|
||||
</PrefetchLink>
|
||||
</div>)}
|
||||
<FormField label="タグ状態">
|
||||
{({ invalid }) => (
|
||||
<select
|
||||
value={tagStateInput}
|
||||
onChange={e => setTagStateInput (
|
||||
e.target.value as MaterialIndexTagState)}
|
||||
className={inputClass (invalid)}>
|
||||
<option value="all">すべて</option>
|
||||
<option value="tagged">タグあり</option>
|
||||
<option value="untagged">タグなし</option>
|
||||
</select>)}
|
||||
</FormField>
|
||||
|
||||
<MaterialCard tag={c3}/>
|
||||
</Fragment>))}
|
||||
</div>
|
||||
</Fragment>))}
|
||||
</div>
|
||||
</>)
|
||||
: (
|
||||
<>
|
||||
<p>左のリストから照会したいタグを選択してください。</p>
|
||||
<p>もしくは……</p>
|
||||
<ul>
|
||||
<li><PrefetchLink to="/materials/new">素材を新規追加する</PrefetchLink></li>
|
||||
{/* <li><a href="#">すべての素材をダウンロードする</a></li> */}
|
||||
</ul>
|
||||
</>))}
|
||||
<FormField label="メディア">
|
||||
{({ invalid }) => (
|
||||
<select
|
||||
value={mediaKindInput}
|
||||
onChange={e => setMediaKindInput (
|
||||
e.target.value as MaterialIndexMediaKind)}
|
||||
className={inputClass (invalid)}>
|
||||
{Object.entries (MEDIA_FILTER_LABELS).map (([value, label]) => (
|
||||
<option key={value} value={value}>
|
||||
{label}
|
||||
</option>))}
|
||||
</select>)}
|
||||
</FormField>
|
||||
|
||||
<FormField label="作成日時">
|
||||
{() => (
|
||||
<div className="flex flex-wrap items-center gap-2">
|
||||
<DateTimeField value={createdFrom ?? undefined} onChange={setCreatedFrom}/>
|
||||
<span>〜</span>
|
||||
<DateTimeField value={createdTo ?? undefined} onChange={setCreatedTo}/>
|
||||
</div>)}
|
||||
</FormField>
|
||||
|
||||
<FormField label="更新日時">
|
||||
{() => (
|
||||
<div className="flex flex-wrap items-center gap-2">
|
||||
<DateTimeField value={updatedFrom ?? undefined} onChange={setUpdatedFrom}/>
|
||||
<span>〜</span>
|
||||
<DateTimeField value={updatedTo ?? undefined} onChange={setUpdatedTo}/>
|
||||
</div>)}
|
||||
</FormField>
|
||||
</div>
|
||||
|
||||
<div className="mt-4 flex flex-wrap gap-3">
|
||||
<button
|
||||
type="submit"
|
||||
className="rounded bg-sky-600 px-4 py-2 text-white hover:bg-sky-700
|
||||
dark:bg-sky-500 dark:text-stone-950 dark:hover:bg-sky-400">
|
||||
検索
|
||||
</button>
|
||||
</div>
|
||||
</form>
|
||||
|
||||
<div className="flex flex-wrap items-center justify-between gap-3">
|
||||
<div className="flex flex-wrap gap-2">
|
||||
<button
|
||||
type="button"
|
||||
onClick={() => updateQuery ({ view: 'card' })}
|
||||
className={`rounded-full border px-4 py-2 text-sm ${
|
||||
view === 'card'
|
||||
? [
|
||||
'border-sky-500 bg-sky-50 text-sky-700 dark:border-sky-400',
|
||||
'dark:bg-sky-950 dark:text-sky-100'].join (' ')
|
||||
: [
|
||||
'border-stone-300 bg-white text-stone-900 dark:border-stone-700',
|
||||
'dark:bg-stone-900 dark:text-stone-100'].join (' ') }`}>
|
||||
アイコン
|
||||
</button>
|
||||
<button
|
||||
type="button"
|
||||
onClick={() => updateQuery ({ view: 'list' })}
|
||||
className={`rounded-full border px-4 py-2 text-sm ${
|
||||
view === 'list'
|
||||
? [
|
||||
'border-sky-500 bg-sky-50 text-sky-700 dark:border-sky-400',
|
||||
'dark:bg-sky-950 dark:text-sky-100'].join (' ')
|
||||
: [
|
||||
'border-stone-300 bg-white text-stone-900 dark:border-stone-700',
|
||||
'dark:bg-stone-900 dark:text-stone-100'].join (' ') }`}>
|
||||
詳細
|
||||
</button>
|
||||
</div>
|
||||
|
||||
<div className="flex flex-wrap items-center gap-2 text-sm">
|
||||
<select
|
||||
value={sort}
|
||||
onChange={e => updateQuery ({ sort: e.target.value, page: '1' })}
|
||||
className={inputClass (false, 'w-auto')}>
|
||||
{Object.entries (SORT_LABELS).map (([value, label]) => (
|
||||
<option key={value} value={value}>
|
||||
{label}
|
||||
</option>))}
|
||||
</select>
|
||||
<select
|
||||
value={direction}
|
||||
onChange={e => updateQuery ({ direction: e.target.value, page: '1' })}
|
||||
className={inputClass (false, 'w-auto')}>
|
||||
<option value="desc">降順</option>
|
||||
<option value="asc">昇順</option>
|
||||
</select>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{isLoading && <p>Loading...</p>}
|
||||
{isError && (
|
||||
<p className="text-red-600 dark:text-red-300">素材一覧の取得に失敗しました.</p>)}
|
||||
{(!isLoading && !isError && materials.length === 0) && (
|
||||
<p>
|
||||
素材はありません。
|
||||
{(tagScope && ['character', 'material'].includes (tagScope.tag.category)) && (
|
||||
<>
|
||||
<PrefetchLink
|
||||
to={materialNewPath (tagScope.tag.name, location.pathname + location.search)}
|
||||
className="font-medium underline underline-offset-2
|
||||
text-sky-700 dark:text-sky-300">
|
||||
追加してください
|
||||
</PrefetchLink>。
|
||||
</>)}
|
||||
</p>)}
|
||||
{materials.length > 0 && (
|
||||
groupBy === 'parent_tag' && groups.length > 0
|
||||
? renderGroupedMaterials (groups)
|
||||
: renderMaterialCollection (materials))}
|
||||
<Pagination page={page} totalPages={totalPages}/>
|
||||
</div>
|
||||
</MainArea>)
|
||||
}
|
||||
|
||||
|
||||
@@ -1,5 +1,6 @@
|
||||
import { fireEvent, screen, waitFor } from '@testing-library/react'
|
||||
import { beforeEach, describe, expect, it, vi } from 'vitest'
|
||||
import { Route, Routes, useLocation } from 'react-router-dom'
|
||||
|
||||
import MaterialNewPage from '@/pages/materials/MaterialNewPage'
|
||||
import { renderWithProviders } from '@/test/render'
|
||||
@@ -17,6 +18,11 @@ const toastApi = vi.hoisted (() => ({
|
||||
vi.mock ('@/lib/api', () => api)
|
||||
vi.mock ('@/components/ui/use-toast', () => toastApi)
|
||||
|
||||
const LocationView = () => {
|
||||
const location = useLocation ()
|
||||
return <div>{location.pathname + location.search}</div>
|
||||
}
|
||||
|
||||
describe ('MaterialNewPage', () => {
|
||||
beforeEach (() => {
|
||||
vi.clearAllMocks ()
|
||||
@@ -69,4 +75,50 @@ describe ('MaterialNewPage', () => {
|
||||
expect (await screen.findAllByText ('ファイルまたは URL は必須です.')).toHaveLength (2)
|
||||
expect (screen.getAllByRole ('textbox')[1]).toHaveAttribute ('aria-invalid', 'true')
|
||||
})
|
||||
|
||||
it ('returns only to safe material URLs after successful creation', async () => {
|
||||
api.apiPost.mockResolvedValueOnce ({})
|
||||
|
||||
renderWithProviders (
|
||||
<Routes>
|
||||
<Route path="/materials/new" element={<MaterialNewPage/>}/>
|
||||
<Route path="/materials" element={<LocationView/>}/>
|
||||
</Routes>,
|
||||
{
|
||||
route:
|
||||
'/materials/new?tag=%E8%99%B9%E5%A4%8F'
|
||||
+ '&return_to=%2Fmaterials%3Ftag_id%3D20',
|
||||
},
|
||||
)
|
||||
|
||||
fireEvent.change (screen.getAllByRole ('textbox')[1], {
|
||||
target: { value: 'https://example.com/ref' },
|
||||
})
|
||||
fireEvent.click (screen.getByRole ('button', { name: '追加' }))
|
||||
|
||||
expect (await screen.findByText ('/materials?tag_id=20')).toBeInTheDocument ()
|
||||
})
|
||||
|
||||
it ('ignores unsafe return_to values after successful creation', async () => {
|
||||
api.apiPost.mockResolvedValueOnce ({})
|
||||
|
||||
renderWithProviders (
|
||||
<Routes>
|
||||
<Route path="/materials/new" element={<MaterialNewPage/>}/>
|
||||
<Route path="/materials" element={<LocationView/>}/>
|
||||
</Routes>,
|
||||
{
|
||||
route:
|
||||
'/materials/new?tag=%E8%99%B9%E5%A4%8F'
|
||||
+ '&return_to=https%3A%2F%2Fexample.com%2Fevil',
|
||||
},
|
||||
)
|
||||
|
||||
fireEvent.change (screen.getAllByRole ('textbox')[1], {
|
||||
target: { value: 'https://example.com/ref' },
|
||||
})
|
||||
fireEvent.click (screen.getByRole ('button', { name: '追加' }))
|
||||
|
||||
expect (await screen.findByText ('/materials')).toBeInTheDocument ()
|
||||
})
|
||||
})
|
||||
|
||||
@@ -1,3 +1,4 @@
|
||||
import { useMutation, useQueryClient } from '@tanstack/react-query'
|
||||
import { useState } from 'react'
|
||||
import { Helmet } from 'react-helmet-async'
|
||||
import { useLocation, useNavigate } from 'react-router-dom'
|
||||
@@ -11,57 +12,60 @@ import MainArea from '@/components/layout/MainArea'
|
||||
import { Button } from '@/components/ui/button'
|
||||
import { toast } from '@/components/ui/use-toast'
|
||||
import { SITE_TITLE } from '@/config'
|
||||
import { apiPost } from '@/lib/api'
|
||||
import { createMaterial } from '@/lib/materials'
|
||||
import { materialsKeys } from '@/lib/queryKeys'
|
||||
import { inputClass } from '@/lib/utils'
|
||||
import { useValidationErrors } from '@/lib/useValidationErrors'
|
||||
|
||||
import type { FC } from 'react'
|
||||
|
||||
type MaterialFormField = 'tag' | 'file' | 'url'
|
||||
type MaterialFormField = 'tag' | 'file' | 'url' | 'exportPaths'
|
||||
|
||||
|
||||
const MaterialNewPage: FC = () => {
|
||||
const qc = useQueryClient ()
|
||||
const location = useLocation ()
|
||||
const query = new URLSearchParams (location.search)
|
||||
const tagQuery = query.get ('tag') ?? ''
|
||||
const returnToQuery = query.get ('return_to') ?? ''
|
||||
const safeReturnTo = returnToQuery.startsWith ('/materials') ? returnToQuery : ''
|
||||
|
||||
const navigate = useNavigate ()
|
||||
|
||||
const [file, setFile] = useState<File | null> (null)
|
||||
const [filePreview, setFilePreview] = useState ('')
|
||||
const [sending, setSending] = useState (false)
|
||||
const [tag, setTag] = useState (tagQuery)
|
||||
const [url, setURL] = useState ('')
|
||||
const [exportPath, setExportPath] = useState ('')
|
||||
const { baseErrors, fieldErrors, clearValidationErrors, applyValidationError } =
|
||||
useValidationErrors<MaterialFormField> ()
|
||||
|
||||
const handleSubmit = async () => {
|
||||
const createMutation = useMutation ({
|
||||
mutationFn: async () => {
|
||||
const formData = new FormData
|
||||
if (tag)
|
||||
formData.append ('tag', tag)
|
||||
if (file)
|
||||
formData.append ('file', file)
|
||||
if (url)
|
||||
formData.append ('url', url)
|
||||
formData.append ('export_paths[legacy_drive]', exportPath)
|
||||
|
||||
return await createMaterial (formData)
|
||||
},
|
||||
onSuccess: async () => {
|
||||
await qc.invalidateQueries ({ queryKey: materialsKeys.root })
|
||||
toast ({ title: '送信成功!' })
|
||||
navigate (safeReturnTo || '/materials')
|
||||
},
|
||||
onError: error => {
|
||||
applyValidationError (error)
|
||||
toast ({ title: '送信失敗……', description: '入力を見直してください.' })
|
||||
}})
|
||||
|
||||
const handleSubmit = () => {
|
||||
clearValidationErrors ()
|
||||
|
||||
const formData = new FormData
|
||||
if (tag)
|
||||
formData.append ('tag', tag)
|
||||
if (file)
|
||||
formData.append ('file', file)
|
||||
if (url)
|
||||
formData.append ('url', url)
|
||||
|
||||
try
|
||||
{
|
||||
setSending (true)
|
||||
await apiPost ('/materials', formData)
|
||||
toast ({ title: '送信成功!' })
|
||||
navigate (`/materials?tag=${ encodeURIComponent (tag) }`)
|
||||
}
|
||||
catch (e)
|
||||
{
|
||||
applyValidationError (e)
|
||||
toast ({ title: '送信失敗……', description: '入力を見直してください.' })
|
||||
}
|
||||
finally
|
||||
{
|
||||
setSending (false)
|
||||
}
|
||||
createMutation.mutate ()
|
||||
}
|
||||
|
||||
return (
|
||||
@@ -133,11 +137,25 @@ const MaterialNewPage: FC = () => {
|
||||
className={inputClass (invalid)}/>)}
|
||||
</FormField>
|
||||
|
||||
<FormField
|
||||
label="ZIP 出力パス"
|
||||
messages={fieldErrors.exportPaths}>
|
||||
{({ describedBy, invalid }) => (
|
||||
<input
|
||||
type="text"
|
||||
value={exportPath}
|
||||
onChange={e => setExportPath (e.target.value)}
|
||||
placeholder="伊地知ニジカ/表情/泣き.png"
|
||||
aria-describedby={describedBy}
|
||||
aria-invalid={invalid}
|
||||
className={inputClass (invalid)}/>)}
|
||||
</FormField>
|
||||
|
||||
{/* 送信 */}
|
||||
<Button
|
||||
onClick={handleSubmit}
|
||||
className="px-4 py-2 bg-blue-600 text-white rounded disabled:bg-gray-400"
|
||||
disabled={sending}>
|
||||
disabled={createMutation.isPending}>
|
||||
追加
|
||||
</Button>
|
||||
</Form>
|
||||
|
||||
@@ -1,51 +0,0 @@
|
||||
import { useState } from 'react'
|
||||
import { Helmet } from 'react-helmet-async'
|
||||
|
||||
import FormField from '@/components/common/FormField'
|
||||
import PageTitle from '@/components/common/PageTitle'
|
||||
import TagInput from '@/components/common/TagInput'
|
||||
import MainArea from '@/components/layout/MainArea'
|
||||
import { SITE_TITLE } from '@/config'
|
||||
|
||||
import type { FC, FormEvent } from 'react'
|
||||
|
||||
|
||||
const MaterialSearchPage: FC = () => {
|
||||
const [tagName, setTagName] = useState ('')
|
||||
const [parentTagName, setParentTagName] = useState ('')
|
||||
|
||||
const handleSearch = (e: FormEvent) => {
|
||||
e.preventDefault ()
|
||||
}
|
||||
|
||||
return (
|
||||
<MainArea>
|
||||
<Helmet>
|
||||
<title>素材集 | {SITE_TITLE}</title>
|
||||
</Helmet>
|
||||
|
||||
<div className="max-w-xl">
|
||||
<PageTitle>素材集</PageTitle>
|
||||
|
||||
<form onSubmit={handleSearch} className="space-y-2">
|
||||
{/* タグ */}
|
||||
<FormField label="タグ">
|
||||
{() => (
|
||||
<TagInput
|
||||
value={tagName}
|
||||
setValue={setTagName}/>)}
|
||||
</FormField>
|
||||
|
||||
{/* 親タグ */}
|
||||
<FormField label="親タグ">
|
||||
{() => (
|
||||
<TagInput
|
||||
value={parentTagName}
|
||||
setValue={setParentTagName}/>)}
|
||||
</FormField>
|
||||
</form>
|
||||
</div>
|
||||
</MainArea>)
|
||||
}
|
||||
|
||||
export default MaterialSearchPage
|
||||
@@ -0,0 +1,202 @@
|
||||
import { useMutation, useQuery, useQueryClient } from '@tanstack/react-query'
|
||||
import { useState } from 'react'
|
||||
import { Helmet } from 'react-helmet-async'
|
||||
|
||||
import FormField from '@/components/common/FormField'
|
||||
import PageTitle from '@/components/common/PageTitle'
|
||||
import MainArea from '@/components/layout/MainArea'
|
||||
import { Button } from '@/components/ui/button'
|
||||
import { toast } from '@/components/ui/use-toast'
|
||||
import { SITE_TITLE } from '@/config'
|
||||
import { createMaterialSyncSuppression, fetchMaterialSyncSuppressions } from '@/lib/materials'
|
||||
import { materialsKeys } from '@/lib/queryKeys'
|
||||
import { dateString, inputClass } from '@/lib/utils'
|
||||
|
||||
import type { FC, FormEvent } from 'react'
|
||||
|
||||
import type { MaterialSyncSuppressionSourceKind } from '@/types'
|
||||
|
||||
const SOURCE_KIND_LABELS: Record<MaterialSyncSuppressionSourceKind, string> = {
|
||||
uri: 'URI',
|
||||
google_drive_path: 'Google Drive ファイル',
|
||||
google_drive_path_prefix: 'Google Drive フォルダ',
|
||||
google_drive_file: 'Google Drive ファイル Id.',
|
||||
legacy_drive_path: '汎用ファイル',
|
||||
legacy_drive_path_prefix: '汎用フォルダ' }
|
||||
|
||||
const REASONS = [
|
||||
'copyright_high_risk',
|
||||
'copyright_takedown',
|
||||
'adult_or_sensitive',
|
||||
'personal_information',
|
||||
'malware_or_dangerous_file',
|
||||
'duplicate_or_low_quality',
|
||||
'source_owner_request',
|
||||
'other'] as const
|
||||
|
||||
type MaterialSyncSuppressionReason = typeof REASONS[number]
|
||||
|
||||
const REASON_NAMES: Record<MaterialSyncSuppressionReason, string> = {
|
||||
['copyright_high_risk']: '著作権への懸念',
|
||||
['copyright_takedown']: '著作者からの申出',
|
||||
['adult_or_sensitive']: '成人向け',
|
||||
['personal_information']: '個人情報',
|
||||
['malware_or_dangerous_file']: '危険なソフトウェア',
|
||||
['duplicate_or_low_quality']: '重複',
|
||||
['source_owner_request']: '同期元管理者からの申出',
|
||||
['other']: 'その他' } as const
|
||||
|
||||
|
||||
const reasonName = (reason: string): string =>
|
||||
REASON_NAMES[reason as MaterialSyncSuppressionReason] ?? reason
|
||||
|
||||
|
||||
const MaterialSyncSuppressionsPage: FC = () => {
|
||||
const qc = useQueryClient ()
|
||||
const [sourceKind, setSourceKind] =
|
||||
useState<MaterialSyncSuppressionSourceKind> ('uri')
|
||||
const [sourceUri, setSourceUri] = useState ('')
|
||||
const [drivePath, setDrivePath] = useState ('')
|
||||
const [driveFileId, setDriveFileId] = useState ('')
|
||||
const [reason, setReason] = useState<MaterialSyncSuppressionReason> (REASONS[0])
|
||||
|
||||
const { data, isError, isLoading } = useQuery ({
|
||||
queryKey: materialsKeys.suppressions (),
|
||||
queryFn: fetchMaterialSyncSuppressions})
|
||||
|
||||
const createMutation = useMutation ({
|
||||
mutationFn: async () =>
|
||||
await createMaterialSyncSuppression ({
|
||||
sourceKind,
|
||||
sourceUri,
|
||||
drivePath,
|
||||
driveFileId,
|
||||
reason}),
|
||||
onSuccess: async () => {
|
||||
await qc.invalidateQueries ({ queryKey: materialsKeys.suppressions () })
|
||||
await qc.invalidateQueries ({ queryKey: materialsKeys.root })
|
||||
setSourceUri ('')
|
||||
setDrivePath ('')
|
||||
setDriveFileId ('')
|
||||
toast ({ title: '同期元抑止を登録しました' })
|
||||
},
|
||||
onError: () => {
|
||||
toast ({ title: '同期元抑止の登録に失敗しました' })
|
||||
}})
|
||||
|
||||
const handleSubmit = (event: FormEvent) => {
|
||||
event.preventDefault ()
|
||||
createMutation.mutate ()
|
||||
}
|
||||
|
||||
const suppressions = data?.suppressions ?? []
|
||||
|
||||
return (
|
||||
<MainArea>
|
||||
<Helmet>
|
||||
<title>{`素材同期抑止 | ${ SITE_TITLE }`}</title>
|
||||
</Helmet>
|
||||
|
||||
<div className="space-y-5">
|
||||
<PageTitle>同期抑止</PageTitle>
|
||||
|
||||
<form
|
||||
onSubmit={handleSubmit}
|
||||
className="max-w-3xl rounded-lg border border-stone-200 bg-white p-4
|
||||
text-stone-900 dark:border-stone-700 dark:bg-stone-900
|
||||
dark:text-stone-100">
|
||||
<div className="space-y-3">
|
||||
<FormField label="同期元種別">
|
||||
{({ invalid }) => (
|
||||
<select
|
||||
value={sourceKind}
|
||||
onChange={e => setSourceKind (
|
||||
e.target.value as MaterialSyncSuppressionSourceKind)}
|
||||
className={inputClass (invalid)}>
|
||||
{Object.entries (SOURCE_KIND_LABELS).map (([value, label]) => (
|
||||
<option key={value} value={value}>
|
||||
{label}
|
||||
</option>))}
|
||||
</select>)}
|
||||
</FormField>
|
||||
|
||||
<FormField label="同期元 URI">
|
||||
{({ invalid }) => (
|
||||
<input
|
||||
type="text"
|
||||
value={sourceUri}
|
||||
onChange={e => setSourceUri (e.target.value)}
|
||||
className={inputClass (invalid)}/>)}
|
||||
</FormField>
|
||||
|
||||
<FormField label="Google Drive パス">
|
||||
{({ invalid }) => (
|
||||
<input
|
||||
type="text"
|
||||
value={drivePath}
|
||||
onChange={e => setDrivePath (e.target.value)}
|
||||
className={inputClass (invalid)}/>)}
|
||||
</FormField>
|
||||
|
||||
<FormField label="Google Drive ファイル Id.">
|
||||
{({ invalid }) => (
|
||||
<input
|
||||
type="text"
|
||||
value={driveFileId}
|
||||
onChange={e => setDriveFileId (e.target.value)}
|
||||
className={inputClass (invalid)}/>)}
|
||||
</FormField>
|
||||
|
||||
<FormField label="事由">
|
||||
{({ invalid }) => (
|
||||
<select
|
||||
value={reason}
|
||||
onChange={e => setReason (e.target.value as MaterialSyncSuppressionReason)}
|
||||
className={inputClass (invalid)}>
|
||||
{REASONS.map (value => (
|
||||
<option key={value} value={value}>
|
||||
{REASON_NAMES[value]}
|
||||
</option>))}
|
||||
</select>)}
|
||||
</FormField>
|
||||
</div>
|
||||
|
||||
<Button
|
||||
type="submit"
|
||||
className="mt-4 rounded bg-blue-600 px-4 py-2 text-white
|
||||
disabled:bg-gray-400"
|
||||
disabled={createMutation.isPending}>
|
||||
登録
|
||||
</Button>
|
||||
</form>
|
||||
|
||||
{isLoading && <p>Loading...</p>}
|
||||
{isError && (
|
||||
<p className="text-red-600 dark:text-red-300">
|
||||
同期元抑止一覧の取得に失敗しました.
|
||||
</p>)}
|
||||
|
||||
<div className="space-y-3">
|
||||
{suppressions.map (suppression => (
|
||||
<article
|
||||
key={suppression.id}
|
||||
className="rounded-lg border border-stone-200 bg-white p-3
|
||||
text-stone-900 shadow-sm dark:border-stone-700
|
||||
dark:bg-stone-900 dark:text-stone-100">
|
||||
<div className="font-medium">
|
||||
{SOURCE_KIND_LABELS[suppression.sourceKind]}
|
||||
</div>
|
||||
<div className="break-all text-sm text-stone-700 dark:text-stone-300">
|
||||
{suppression.normalizedSourceKey}
|
||||
</div>
|
||||
<div className="mt-2 text-sm text-stone-600 dark:text-stone-400">
|
||||
事由: {reasonName (suppression.reason)} /
|
||||
登録: {dateString (suppression.createdAt)}
|
||||
</div>
|
||||
</article>))}
|
||||
</div>
|
||||
</div>
|
||||
</MainArea>)
|
||||
}
|
||||
|
||||
export default MaterialSyncSuppressionsPage
|
||||
@@ -62,8 +62,7 @@ const PostDetailPage: FC<Props> = ({ user }) => {
|
||||
toast ({ title: '失敗……', description: '通信に失敗しました……' })
|
||||
},
|
||||
onSuccess: () => {
|
||||
qc.invalidateQueries ({ queryKey: postsKeys.root })
|
||||
} })
|
||||
qc.invalidateQueries ({ queryKey: postsKeys.root })} })
|
||||
|
||||
useEffect (() => {
|
||||
if (!(errorFlg))
|
||||
@@ -114,8 +113,7 @@ const PostDetailPage: FC<Props> = ({ user }) => {
|
||||
<PostList posts={[{ ...post, childPosts: [{ } as Post] },
|
||||
...post.childPosts!.map (p => ({
|
||||
...p, parentPosts: [{ } as Post] }))]}/>
|
||||
</div>
|
||||
)}
|
||||
</div>)}
|
||||
{(post.parentPosts ?? []).map (pp => {
|
||||
const siblings = post.siblingPosts?.[String (pp.id) as `${ number }`]
|
||||
if (!(siblings))
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
import { useQuery, useQueryClient } from '@tanstack/react-query'
|
||||
import { Check, LoaderCircle, Pencil, X } from 'lucide-react'
|
||||
import { useEffect, useMemo, useState } from 'react'
|
||||
import { Fragment, useEffect, useMemo, useState } from 'react'
|
||||
import { Helmet } from 'react-helmet-async'
|
||||
import { useLocation, useNavigate } from 'react-router-dom'
|
||||
|
||||
@@ -87,8 +87,7 @@ const NicoTagListPage: FC<Props> = ({ user }) => {
|
||||
const defaultDirection = {
|
||||
name: 'asc',
|
||||
created_at: 'desc',
|
||||
updated_at: 'desc',
|
||||
} as const
|
||||
updated_at: 'desc'} as const
|
||||
|
||||
const beginEdit = async (tag: NicoTag) => {
|
||||
const editingTag = nicoTags.find (tag => tag.id === editingId)
|
||||
@@ -99,15 +98,13 @@ const NicoTagListPage: FC<Props> = ({ user }) => {
|
||||
&& !(await dialogue.confirm ({
|
||||
title: '編集中の内容を破棄しますか?',
|
||||
confirmText: '破棄',
|
||||
variant: 'danger',
|
||||
})))
|
||||
variant: 'danger'})))
|
||||
return
|
||||
|
||||
setEditingId (tag.id)
|
||||
setRawTags (rawTags => ({
|
||||
...rawTags,
|
||||
[tag.id]: tag.linkedTags.map (linkedTag => linkedTag.name).join (' '),
|
||||
}))
|
||||
[tag.id]: tag.linkedTags.map (linkedTag => linkedTag.name).join (' ')}))
|
||||
setErrorsByTagId (errors => ({ ...errors, [tag.id]: [] }))
|
||||
}
|
||||
|
||||
@@ -115,8 +112,7 @@ const NicoTagListPage: FC<Props> = ({ user }) => {
|
||||
setEditingId (null)
|
||||
setRawTags (rawTags => ({
|
||||
...rawTags,
|
||||
[tag.id]: tag.linkedTags.map (linkedTag => linkedTag.name).join (' '),
|
||||
}))
|
||||
[tag.id]: tag.linkedTags.map (linkedTag => linkedTag.name).join (' ')}))
|
||||
setErrorsByTagId (errors => ({ ...errors, [tag.id]: [] }))
|
||||
}
|
||||
|
||||
@@ -141,8 +137,7 @@ const NicoTagListPage: FC<Props> = ({ user }) => {
|
||||
...errors,
|
||||
[id]: validationError?.fieldErrors.tags
|
||||
?? validationError?.baseErrors
|
||||
?? ['更新できませんでした.'],
|
||||
}))
|
||||
?? ['更新できませんでした.']}))
|
||||
toast ({ title: '更新失敗', description: '入力内容を確認してください.' })
|
||||
}
|
||||
finally
|
||||
@@ -166,8 +161,7 @@ const NicoTagListPage: FC<Props> = ({ user }) => {
|
||||
|
||||
setRawTags (Object.fromEntries (data.tags.map (tag => [
|
||||
tag.id,
|
||||
tag.linkedTags.map (linkedTag => linkedTag.name).join (' '),
|
||||
])))
|
||||
tag.linkedTags.map (linkedTag => linkedTag.name).join (' ')])))
|
||||
}, [data])
|
||||
|
||||
useEffect (() => {
|
||||
@@ -282,7 +276,8 @@ const NicoTagListPage: FC<Props> = ({ user }) => {
|
||||
{nicoTags.map (tag => {
|
||||
const isEditing = editingId === tag.id
|
||||
|
||||
return [
|
||||
return (
|
||||
<Fragment key={tag.id}>
|
||||
<tr
|
||||
key={tag.id}
|
||||
className={cn (
|
||||
@@ -321,8 +316,8 @@ const NicoTagListPage: FC<Props> = ({ user }) => {
|
||||
編集
|
||||
</button>)}
|
||||
</td>)}
|
||||
</tr>,
|
||||
isEditing && (
|
||||
</tr>
|
||||
{isEditing && (
|
||||
<tr key={`${ tag.id }-edit`}
|
||||
className="border-b border-rose-200 bg-rose-50 dark:border-rose-900
|
||||
dark:bg-rose-950/30">
|
||||
@@ -340,8 +335,7 @@ const NicoTagListPage: FC<Props> = ({ user }) => {
|
||||
placeholder="タグ名を空白または改行で区切って入力"
|
||||
onChange={e => setRawTags (rawTags => ({
|
||||
...rawTags,
|
||||
[tag.id]: e.target.value,
|
||||
}))}/>
|
||||
[tag.id]: e.target.value}))}/>
|
||||
<FieldError messages={errorsByTagId[tag.id]}/>
|
||||
<div className="flex justify-end gap-2">
|
||||
<button
|
||||
@@ -368,8 +362,8 @@ const NicoTagListPage: FC<Props> = ({ user }) => {
|
||||
</div>
|
||||
</div>
|
||||
</td>
|
||||
</tr>),
|
||||
]
|
||||
</tr>)}
|
||||
</Fragment>)
|
||||
})}
|
||||
</tbody>
|
||||
</table>
|
||||
|
||||
@@ -69,8 +69,7 @@ const userName = (user: Pick<User, 'id' | 'name'> | null | undefined): string =>
|
||||
|
||||
const commentBox = (
|
||||
comment: TheatreComment,
|
||||
programme: TheatreProgramme | null = null,
|
||||
): ReactNode[] =>
|
||||
programme: TheatreProgramme | null = null): ReactNode[] =>
|
||||
[(
|
||||
<div key={`${ comment.no }-content`} className="w-full">
|
||||
{comment.deleted
|
||||
@@ -120,8 +119,7 @@ const tagsByCategory = (tags: Tag[]): Partial<Record<Category, Tag[]>> => {
|
||||
|
||||
|
||||
const TagList: FC<{ tags: Tag[]; compact?: boolean; flow?: TagFlow }> = (
|
||||
{ tags, compact, flow = 'vertical' },
|
||||
) => {
|
||||
{ tags, compact, flow = 'vertical' }) => {
|
||||
const grouped = tagsByCategory (tags)
|
||||
|
||||
if (flow === 'horizontal')
|
||||
|
||||
新しい課題から参照
ユーザをブロックする