フォームのバリデーションとニコ連携の画面変更 (#090) #355
@@ -1,26 +1,69 @@
|
|||||||
class NicoTagsController < ApplicationController
|
class NicoTagsController < ApplicationController
|
||||||
def index
|
def index
|
||||||
limit = (params[:limit] || 20).to_i
|
name = params[:name].presence
|
||||||
cursor = params[:cursor].presence
|
linked_tag = params[:linked_tag].presence
|
||||||
|
link_status = params[:link_status].presence
|
||||||
|
order = params[:order].to_s.split(':', 2).map(&:strip)
|
||||||
|
order[0] = 'updated_at' unless order[0].in?(['name', 'created_at', 'updated_at'])
|
||||||
|
unless order[1].in?(['asc', 'desc'])
|
||||||
|
order[1] = order[0] == 'name' ? 'asc' : 'desc'
|
||||||
|
end
|
||||||
|
page = (params[:page].presence || 1).to_i
|
||||||
|
limit = (params[:limit].presence || 20).to_i
|
||||||
|
|
||||||
|
page = 1 if page < 1
|
||||||
|
limit = 1 if limit < 1
|
||||||
|
|
||||||
|
post_tag_max_sql =
|
||||||
|
PostTag
|
||||||
|
.select('tag_id, MAX(created_at) AS max_created_at')
|
||||||
|
.group('tag_id')
|
||||||
|
.to_sql
|
||||||
|
|
||||||
q = Tag.nico_tags
|
q = Tag.nico_tags
|
||||||
|
.joins(:tag_name)
|
||||||
|
.joins("LEFT JOIN (#{ post_tag_max_sql }) post_tag_max " \
|
||||||
|
'ON post_tag_max.tag_id = tags.id')
|
||||||
.includes(:tag_name, tag_name: :wiki_page, linked_tags: { tag_name: :wiki_page })
|
.includes(:tag_name, tag_name: :wiki_page, linked_tags: { tag_name: :wiki_page })
|
||||||
.order(updated_at: :desc)
|
q = q.where('tag_names.name LIKE ?', "%#{ name }%") if name
|
||||||
q = q.where('tags.updated_at < ?', Time.iso8601(cursor)) if cursor
|
if linked_tag
|
||||||
|
linked_tag_ids =
|
||||||
tags = q.limit(limit + 1).to_a
|
Tag
|
||||||
|
.joins(:tag_name)
|
||||||
next_cursor = nil
|
.where('tag_names.name LIKE ?', "%#{ linked_tag }%")
|
||||||
if tags.size > limit
|
.pluck(:id)
|
||||||
next_cursor = tags.last.updated_at.iso8601(6)
|
linked_nico_tag_ids = NicoTagRelation.where(tag_id: linked_tag_ids).pluck(:nico_tag_id)
|
||||||
tags = tags.first(limit)
|
q = q.where(id: linked_nico_tag_ids)
|
||||||
|
end
|
||||||
|
if link_status.in?(['linked', 'unlinked'])
|
||||||
|
exists_sql =
|
||||||
|
'EXISTS (SELECT 1 FROM nico_tag_relations ' \
|
||||||
|
'WHERE nico_tag_relations.nico_tag_id = tags.id)'
|
||||||
|
q = link_status == 'linked' ? q.where(exists_sql) : q.where("NOT #{ exists_sql }")
|
||||||
end
|
end
|
||||||
|
|
||||||
|
count = q.count
|
||||||
|
sort_sql =
|
||||||
|
case order[0]
|
||||||
|
when 'name'
|
||||||
|
'tag_names.name'
|
||||||
|
when 'updated_at'
|
||||||
|
'post_tag_max.max_created_at'
|
||||||
|
else
|
||||||
|
"tags.#{ order[0] }"
|
||||||
|
end
|
||||||
|
tags = q.reselect('tags.*',
|
||||||
|
Arel.sql('post_tag_max.max_created_at AS recent_post_tag_created_at'))
|
||||||
|
.order(Arel.sql("#{ sort_sql } #{ order[1] }, tags.id #{ order[1] }"))
|
||||||
|
.limit(limit)
|
||||||
|
.offset((page - 1) * limit)
|
||||||
|
.to_a
|
||||||
|
|
||||||
render json: { tags: tags.map { |tag|
|
render json: { tags: tags.map { |tag|
|
||||||
TagRepr.base(tag).merge(linked_tags: tag.linked_tags.map { |lt|
|
TagRepr.base(tag).merge(
|
||||||
TagRepr.base(lt)
|
recent_post_tag_created_at: tag.recent_post_tag_created_at,
|
||||||
})
|
linked_tags: tag.linked_tags.map { |lt| TagRepr.base(lt) })
|
||||||
}, next_cursor: }
|
}, count: }
|
||||||
end
|
end
|
||||||
|
|
||||||
def update
|
def update
|
||||||
|
|||||||
@@ -3,12 +3,68 @@ require 'rails_helper'
|
|||||||
|
|
||||||
RSpec.describe 'NicoTags', type: :request do
|
RSpec.describe 'NicoTags', type: :request do
|
||||||
describe 'GET /tags/nico' do
|
describe 'GET /tags/nico' do
|
||||||
it 'returns tags and next_cursor when overflowing limit' do
|
it 'returns paginated tags and total count' do
|
||||||
create_list(:tag, 21, :nico)
|
create_list(:tag, 3, :nico)
|
||||||
get '/tags/nico', params: { limit: 20 }
|
|
||||||
|
get '/tags/nico', params: { page: 2, limit: 2 }
|
||||||
|
|
||||||
expect(response).to have_http_status(:ok)
|
expect(response).to have_http_status(:ok)
|
||||||
expect(json['tags'].size).to eq(20)
|
expect(json['tags'].size).to eq(1)
|
||||||
expect(json['next_cursor']).to be_present
|
expect(json['count']).to eq(3)
|
||||||
|
end
|
||||||
|
|
||||||
|
it 'filters by nico tag name, linked tag name, and link status' do
|
||||||
|
linked = create(:tag, :nico)
|
||||||
|
linked.tag_name.update!(name: 'nico:search_linked')
|
||||||
|
unlinked = create(:tag, :nico)
|
||||||
|
unlinked.tag_name.update!(name: 'nico:search_unlinked')
|
||||||
|
other = create(:tag, :nico)
|
||||||
|
other.tag_name.update!(name: 'nico:other')
|
||||||
|
destination = create(:tag, :general)
|
||||||
|
destination.tag_name.update!(name: 'destination_search')
|
||||||
|
NicoTagRelation.create!(nico_tag: linked, tag: destination)
|
||||||
|
NicoTagRelation.create!(nico_tag: other, tag: create(:tag, :general))
|
||||||
|
|
||||||
|
get '/tags/nico', params: {
|
||||||
|
name: 'search_',
|
||||||
|
linked_tag: 'destination_',
|
||||||
|
link_status: 'linked'
|
||||||
|
}
|
||||||
|
|
||||||
|
expect(response).to have_http_status(:ok)
|
||||||
|
expect(json['count']).to eq(1)
|
||||||
|
expect(json.fetch('tags').map { |tag| tag['id'] }).to eq([linked.id])
|
||||||
|
|
||||||
|
get '/tags/nico', params: { name: 'search_', link_status: 'unlinked' }
|
||||||
|
|
||||||
|
expect(json['count']).to eq(1)
|
||||||
|
expect(json.fetch('tags').map { |tag| tag['id'] }).to eq([unlinked.id])
|
||||||
|
end
|
||||||
|
|
||||||
|
it 'sorts by name and timestamps' do
|
||||||
|
older = create(:tag, :nico)
|
||||||
|
older.tag_name.update!(name: 'nico:a')
|
||||||
|
older.update_columns(created_at: 2.days.ago)
|
||||||
|
newer = create(:tag, :nico)
|
||||||
|
newer.tag_name.update!(name: 'nico:b')
|
||||||
|
newer.update_columns(created_at: 1.day.ago)
|
||||||
|
older_post_tag =
|
||||||
|
PostTag.create!(post: Post.create!(url: 'https://example.com/nico-older'), tag: older)
|
||||||
|
older_post_tag.update_columns(created_at: 1.hour.ago)
|
||||||
|
newer_post_tag =
|
||||||
|
PostTag.create!(post: Post.create!(url: 'https://example.com/nico-newer'), tag: newer)
|
||||||
|
newer_post_tag.update_columns(created_at: 2.hours.ago)
|
||||||
|
|
||||||
|
get '/tags/nico', params: { order: 'name:desc' }
|
||||||
|
expect(json.fetch('tags').map { |tag| tag['id'] }).to eq([newer.id, older.id])
|
||||||
|
|
||||||
|
get '/tags/nico', params: { order: 'created_at:asc' }
|
||||||
|
expect(json.fetch('tags').map { |tag| tag['id'] }).to eq([older.id, newer.id])
|
||||||
|
|
||||||
|
get '/tags/nico', params: { order: 'updated_at:desc' }
|
||||||
|
expect(json.fetch('tags').map { |tag| tag['id'] }).to eq([older.id, newer.id])
|
||||||
|
expect(Time.zone.parse(json.fetch('tags').first.fetch('recent_post_tag_created_at')))
|
||||||
|
.to be_within(1.second).of(older_post_tag.created_at)
|
||||||
end
|
end
|
||||||
end
|
end
|
||||||
|
|
||||||
|
|||||||
@@ -62,6 +62,7 @@ const RouteTransitionWrapper = ({ user, setUser }: {
|
|||||||
<Route path="/tags/:id" element={<TagDetailPage/>}/>
|
<Route path="/tags/:id" element={<TagDetailPage/>}/>
|
||||||
<Route path="/tags/:id/deerjikists" element={<DeerjikistDetailPage/>}/>
|
<Route path="/tags/:id/deerjikists" element={<DeerjikistDetailPage/>}/>
|
||||||
<Route path="/tags/nico" element={<NicoTagListPage user={user}/>}/>
|
<Route path="/tags/nico" element={<NicoTagListPage user={user}/>}/>
|
||||||
|
<Route path="/nico/tags" element={<NicoTagListPage user={user}/>}/>
|
||||||
<Route path="/tags/changes" element={<TagHistoryPage/>}/>
|
<Route path="/tags/changes" element={<TagHistoryPage/>}/>
|
||||||
<Route path="/theatres/:id" element={<TheatreDetailPage/>}/>
|
<Route path="/theatres/:id" element={<TheatreDetailPage/>}/>
|
||||||
<Route path="/materials" element={<MaterialBasePage/>}>
|
<Route path="/materials" element={<MaterialBasePage/>}>
|
||||||
|
|||||||
@@ -10,6 +10,7 @@ const postsApi = vi.hoisted (() => ({
|
|||||||
}))
|
}))
|
||||||
|
|
||||||
const tagsApi = vi.hoisted (() => ({
|
const tagsApi = vi.hoisted (() => ({
|
||||||
|
fetchNicoTags: vi.fn (),
|
||||||
fetchTag: vi.fn (),
|
fetchTag: vi.fn (),
|
||||||
fetchTagByName: vi.fn (),
|
fetchTagByName: vi.fn (),
|
||||||
fetchTagChanges: vi.fn (),
|
fetchTagChanges: vi.fn (),
|
||||||
@@ -37,6 +38,7 @@ describe ('prefetchForURL', () => {
|
|||||||
postsApi.fetchPost.mockResolvedValue ({ id: 1 })
|
postsApi.fetchPost.mockResolvedValue ({ id: 1 })
|
||||||
postsApi.fetchPostChanges.mockResolvedValue ({ versions: [], count: 0 })
|
postsApi.fetchPostChanges.mockResolvedValue ({ versions: [], count: 0 })
|
||||||
tagsApi.fetchTags.mockResolvedValue ({ tags: [], count: 0 })
|
tagsApi.fetchTags.mockResolvedValue ({ tags: [], count: 0 })
|
||||||
|
tagsApi.fetchNicoTags.mockResolvedValue ({ tags: [], count: 0 })
|
||||||
tagsApi.fetchTag.mockResolvedValue ({ id: 1 })
|
tagsApi.fetchTag.mockResolvedValue ({ id: 1 })
|
||||||
tagsApi.fetchTagByName.mockResolvedValue (null)
|
tagsApi.fetchTagByName.mockResolvedValue (null)
|
||||||
tagsApi.fetchTagChanges.mockResolvedValue ({ versions: [], count: 0 })
|
tagsApi.fetchTagChanges.mockResolvedValue ({ versions: [], count: 0 })
|
||||||
@@ -85,6 +87,32 @@ describe ('prefetchForURL', () => {
|
|||||||
)
|
)
|
||||||
})
|
})
|
||||||
|
|
||||||
|
it ('prefetches nico tag indexes and their alias from query parameters', async () => {
|
||||||
|
await prefetchForURL (
|
||||||
|
qc (),
|
||||||
|
'http://localhost/tags/nico?name=source&linked_tag=destination'
|
||||||
|
+ '&link_status=linked&page=3&limit=10',
|
||||||
|
)
|
||||||
|
await prefetchForURL (qc (), 'http://localhost/nico/tags?page=2')
|
||||||
|
|
||||||
|
expect (tagsApi.fetchNicoTags).toHaveBeenNthCalledWith (1, {
|
||||||
|
name: 'source',
|
||||||
|
linkedTag: 'destination',
|
||||||
|
linkStatus: 'linked',
|
||||||
|
page: 3,
|
||||||
|
limit: 10,
|
||||||
|
order: 'updated_at:desc',
|
||||||
|
})
|
||||||
|
expect (tagsApi.fetchNicoTags).toHaveBeenNthCalledWith (2, {
|
||||||
|
name: '',
|
||||||
|
linkedTag: '',
|
||||||
|
linkStatus: 'all',
|
||||||
|
page: 2,
|
||||||
|
limit: 20,
|
||||||
|
order: 'updated_at:desc',
|
||||||
|
})
|
||||||
|
})
|
||||||
|
|
||||||
it ('prefetches wiki show pages and related tag/post data', async () => {
|
it ('prefetches wiki show pages and related tag/post data', async () => {
|
||||||
wikiApi.fetchWikiPageByTitle.mockResolvedValueOnce ({
|
wikiApi.fetchWikiPageByTitle.mockResolvedValueOnce ({
|
||||||
id: 3,
|
id: 3,
|
||||||
|
|||||||
@@ -3,7 +3,7 @@ import { match } from 'path-to-regexp'
|
|||||||
|
|
||||||
import { fetchPost, fetchPosts, fetchPostChanges } from '@/lib/posts'
|
import { fetchPost, fetchPosts, fetchPostChanges } from '@/lib/posts'
|
||||||
import { postsKeys, tagsKeys, wikiKeys } from '@/lib/queryKeys'
|
import { postsKeys, tagsKeys, wikiKeys } from '@/lib/queryKeys'
|
||||||
import { fetchTagByName, fetchTag, fetchTagChanges, fetchTags } from '@/lib/tags'
|
import { fetchNicoTags, fetchTagByName, fetchTag, fetchTagChanges, fetchTags } from '@/lib/tags'
|
||||||
import { fetchWikiPage,
|
import { fetchWikiPage,
|
||||||
fetchWikiPageByTitle,
|
fetchWikiPageByTitle,
|
||||||
fetchWikiPages } from '@/lib/wiki'
|
fetchWikiPages } from '@/lib/wiki'
|
||||||
@@ -170,6 +170,24 @@ const prefetchTagsIndex: Prefetcher = async (qc, url) => {
|
|||||||
}
|
}
|
||||||
|
|
||||||
|
|
||||||
|
const prefetchNicoTagsIndex: Prefetcher = async (qc, url) => {
|
||||||
|
const keys = {
|
||||||
|
name: url.searchParams.get ('name') ?? '',
|
||||||
|
linkedTag: url.searchParams.get ('linked_tag') ?? '',
|
||||||
|
linkStatus: (url.searchParams.get ('link_status') || 'all') as
|
||||||
|
'all' | 'linked' | 'unlinked',
|
||||||
|
page: Number (url.searchParams.get ('page') || 1),
|
||||||
|
limit: Number (url.searchParams.get ('limit') || 20),
|
||||||
|
order: (url.searchParams.get ('order') || 'updated_at:desc') as
|
||||||
|
'name:asc' | 'name:desc' | 'created_at:asc' | 'created_at:desc'
|
||||||
|
| 'updated_at:asc' | 'updated_at:desc' }
|
||||||
|
|
||||||
|
await qc.prefetchQuery ({
|
||||||
|
queryKey: tagsKeys.nicoIndex (keys),
|
||||||
|
queryFn: () => fetchNicoTags (keys) })
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
const prefetchTagShow: Prefetcher = async (qc, url) => {
|
const prefetchTagShow: Prefetcher = async (qc, url) => {
|
||||||
const m = mTag (url.pathname)
|
const m = mTag (url.pathname)
|
||||||
if (!(m))
|
if (!(m))
|
||||||
@@ -206,6 +224,8 @@ export const routePrefetchers: { test: (u: URL) => boolean; run: Prefetcher }[]
|
|||||||
&& Boolean (mWiki (u.pathname))),
|
&& Boolean (mWiki (u.pathname))),
|
||||||
run: prefetchWikiPageShow },
|
run: prefetchWikiPageShow },
|
||||||
{ test: u => u.pathname === '/tags', run: prefetchTagsIndex },
|
{ test: u => u.pathname === '/tags', run: prefetchTagsIndex },
|
||||||
|
{ test: u => ['/tags/nico', '/nico/tags'].includes (u.pathname),
|
||||||
|
run: prefetchNicoTagsIndex },
|
||||||
{ test: u => (!(['/tags/nico', '/tags/changes'].includes (u.pathname))
|
{ test: u => (!(['/tags/nico', '/tags/changes'].includes (u.pathname))
|
||||||
&& Boolean (mTag (u.pathname))),
|
&& Boolean (mTag (u.pathname))),
|
||||||
run: prefetchTagShow },
|
run: prefetchTagShow },
|
||||||
|
|||||||
@@ -1,4 +1,4 @@
|
|||||||
import type { FetchPostsParams, FetchTagsParams } from '@/types'
|
import type { FetchNicoTagsParams, FetchPostsParams, FetchTagsParams } from '@/types'
|
||||||
|
|
||||||
export const postsKeys = {
|
export const postsKeys = {
|
||||||
root: ['posts'] as const,
|
root: ['posts'] as const,
|
||||||
@@ -11,6 +11,8 @@ export const postsKeys = {
|
|||||||
export const tagsKeys = {
|
export const tagsKeys = {
|
||||||
root: ['tags'] as const,
|
root: ['tags'] as const,
|
||||||
index: (p: FetchTagsParams) => ['tags', 'index', p] as const,
|
index: (p: FetchTagsParams) => ['tags', 'index', p] as const,
|
||||||
|
nicoRoot: ['tags', 'nico'] as const,
|
||||||
|
nicoIndex: (p: FetchNicoTagsParams) => ['tags', 'nico', 'index', p] as const,
|
||||||
show: (name: string) => ['tags', name] as const,
|
show: (name: string) => ['tags', name] as const,
|
||||||
changes: (p: { id?: string; page: number; limit: number }) =>
|
changes: (p: { id?: string; page: number; limit: number }) =>
|
||||||
['tags', 'changes', p] as const,
|
['tags', 'changes', p] as const,
|
||||||
|
|||||||
+19
-1
@@ -1,6 +1,11 @@
|
|||||||
import { apiGet } from '@/lib/api'
|
import { apiGet } from '@/lib/api'
|
||||||
|
|
||||||
import type { Deerjikist, FetchTagsParams, Tag, TagVersion } from '@/types'
|
import type { Deerjikist,
|
||||||
|
FetchNicoTagsParams,
|
||||||
|
FetchTagsParams,
|
||||||
|
NicoTag,
|
||||||
|
Tag,
|
||||||
|
TagVersion } from '@/types'
|
||||||
|
|
||||||
|
|
||||||
export const fetchTags = async (
|
export const fetchTags = async (
|
||||||
@@ -23,6 +28,19 @@ export const fetchTags = async (
|
|||||||
...(order && { order }) } })
|
...(order && { order }) } })
|
||||||
|
|
||||||
|
|
||||||
|
export const fetchNicoTags = async (
|
||||||
|
{ name, linkedTag, linkStatus, page, limit, order }: FetchNicoTagsParams,
|
||||||
|
): Promise<{ tags: NicoTag[]
|
||||||
|
count: number }> =>
|
||||||
|
await apiGet ('/tags/nico', { params: {
|
||||||
|
page,
|
||||||
|
limit,
|
||||||
|
name,
|
||||||
|
linked_tag: linkedTag,
|
||||||
|
link_status: linkStatus === 'all' ? '' : linkStatus,
|
||||||
|
order } })
|
||||||
|
|
||||||
|
|
||||||
export const fetchTag = async (id: string): Promise<Tag | null> => {
|
export const fetchTag = async (id: string): Promise<Tag | null> => {
|
||||||
try
|
try
|
||||||
{
|
{
|
||||||
|
|||||||
@@ -0,0 +1,273 @@
|
|||||||
|
import { fireEvent, screen, waitFor } from '@testing-library/react'
|
||||||
|
import { beforeEach, describe, expect, it, vi } from 'vitest'
|
||||||
|
|
||||||
|
import NicoTagListPage from '@/pages/tags/NicoTagListPage'
|
||||||
|
import { dateString } from '@/lib/utils'
|
||||||
|
import { buildTag, buildUser } from '@/test/factories'
|
||||||
|
import { renderWithProviders } from '@/test/render'
|
||||||
|
|
||||||
|
import type { NicoTag } from '@/types'
|
||||||
|
|
||||||
|
const api = vi.hoisted (() => ({
|
||||||
|
apiGet: vi.fn (),
|
||||||
|
apiPut: vi.fn (),
|
||||||
|
isApiError: vi.fn (),
|
||||||
|
}))
|
||||||
|
|
||||||
|
const toastApi = vi.hoisted (() => ({
|
||||||
|
toast: vi.fn (),
|
||||||
|
}))
|
||||||
|
|
||||||
|
const dialogue = vi.hoisted (() => ({
|
||||||
|
confirm: vi.fn (),
|
||||||
|
}))
|
||||||
|
|
||||||
|
const scrollIntoView = vi.fn ()
|
||||||
|
|
||||||
|
vi.mock ('@/lib/api', () => api)
|
||||||
|
vi.mock ('@/components/ui/use-toast', () => toastApi)
|
||||||
|
vi.mock ('@/components/dialogues/DialogueProvider', () => ({
|
||||||
|
useDialogue: () => dialogue,
|
||||||
|
}))
|
||||||
|
|
||||||
|
const buildNicoTag = (values: Partial<NicoTag> = {}): NicoTag => ({
|
||||||
|
...buildTag (),
|
||||||
|
...values,
|
||||||
|
category: 'nico',
|
||||||
|
linkedTags: values.linkedTags ?? [],
|
||||||
|
recentPostTagCreatedAt: values.recentPostTagCreatedAt ?? null,
|
||||||
|
})
|
||||||
|
|
||||||
|
const renderPage = (route = '/tags/nico') =>
|
||||||
|
renderWithProviders (
|
||||||
|
<NicoTagListPage user={buildUser ({ role: 'member' })}/>,
|
||||||
|
{ route },
|
||||||
|
)
|
||||||
|
|
||||||
|
describe ('NicoTagListPage', () => {
|
||||||
|
beforeEach (() => {
|
||||||
|
vi.clearAllMocks ()
|
||||||
|
api.isApiError.mockReturnValue (false)
|
||||||
|
dialogue.confirm.mockResolvedValue (true)
|
||||||
|
Element.prototype.scrollIntoView = scrollIntoView
|
||||||
|
scrollIntoView.mockClear ()
|
||||||
|
})
|
||||||
|
|
||||||
|
it ('loads a filtered page from URL search parameters', async () => {
|
||||||
|
api.apiGet.mockResolvedValue ({
|
||||||
|
tags: [buildNicoTag ({
|
||||||
|
id: 1,
|
||||||
|
name: 'nico:linked',
|
||||||
|
createdAt: '2024-01-02T03:04:05Z',
|
||||||
|
recentPostTagCreatedAt: '2025-01-02T03:04:05Z',
|
||||||
|
updatedAt: '2026-01-02T03:04:05Z',
|
||||||
|
})],
|
||||||
|
count: 21,
|
||||||
|
})
|
||||||
|
|
||||||
|
renderPage (
|
||||||
|
'/tags/nico?name=linked&linked_tag=destination&link_status=linked'
|
||||||
|
+ '&page=2&order=name:asc',
|
||||||
|
)
|
||||||
|
|
||||||
|
await waitFor (() => {
|
||||||
|
expect (api.apiGet).toHaveBeenCalledWith (
|
||||||
|
'/tags/nico',
|
||||||
|
{ params: {
|
||||||
|
page: 2,
|
||||||
|
limit: 20,
|
||||||
|
name: 'linked',
|
||||||
|
linked_tag: 'destination',
|
||||||
|
link_status: 'linked',
|
||||||
|
order: 'name:asc',
|
||||||
|
} },
|
||||||
|
)
|
||||||
|
})
|
||||||
|
expect (await screen.findByText ('21 件')).toBeInTheDocument ()
|
||||||
|
expect (screen.getByLabelText ('前のページ')).toBeInTheDocument ()
|
||||||
|
expect (screen.queryByText ('なし')).not.toBeInTheDocument ()
|
||||||
|
expect (screen.getByText (dateString ('2025-01-02T03:04:05Z'))).toBeInTheDocument ()
|
||||||
|
expect (screen.queryByText (dateString ('2026-01-02T03:04:05Z'))).not.toBeInTheDocument ()
|
||||||
|
expect (screen.getByRole ('link', { name: 'ニコニコタグ ▲' })).toHaveAttribute (
|
||||||
|
'href',
|
||||||
|
expect.stringContaining ('order=name%3Adesc'),
|
||||||
|
)
|
||||||
|
expect (screen.getByRole ('link', { name: '最初に記載された日時' })).toHaveAttribute (
|
||||||
|
'href',
|
||||||
|
expect.stringContaining ('order=created_at%3Adesc'),
|
||||||
|
)
|
||||||
|
expect (screen.getByRole ('link', { name: '最近記載された日時' })).toHaveAttribute (
|
||||||
|
'href',
|
||||||
|
expect.stringContaining ('order=updated_at%3Adesc'),
|
||||||
|
)
|
||||||
|
|
||||||
|
fireEvent.mouseEnter (screen.getByLabelText ('前のページ'))
|
||||||
|
await waitFor (() => {
|
||||||
|
expect (api.apiGet).toHaveBeenLastCalledWith (
|
||||||
|
'/tags/nico',
|
||||||
|
{ params: {
|
||||||
|
page: 1,
|
||||||
|
limit: 20,
|
||||||
|
name: 'linked',
|
||||||
|
linked_tag: 'destination',
|
||||||
|
link_status: 'linked',
|
||||||
|
order: 'name:asc',
|
||||||
|
} },
|
||||||
|
)
|
||||||
|
})
|
||||||
|
})
|
||||||
|
|
||||||
|
it ('scrolls to the table when moving between pages', async () => {
|
||||||
|
api.apiGet.mockResolvedValue ({
|
||||||
|
tags: [buildNicoTag ({ id: 1, name: 'nico:linked' })],
|
||||||
|
count: 21,
|
||||||
|
})
|
||||||
|
|
||||||
|
renderPage ()
|
||||||
|
|
||||||
|
fireEvent.click (await screen.findByLabelText ('次のページ'))
|
||||||
|
|
||||||
|
await waitFor (() => {
|
||||||
|
expect (scrollIntoView).toHaveBeenCalledWith ({ behavior: 'smooth' })
|
||||||
|
})
|
||||||
|
})
|
||||||
|
|
||||||
|
it ('navigates with submitted search conditions', async () => {
|
||||||
|
api.apiGet.mockResolvedValue ({ tags: [], count: 0 })
|
||||||
|
renderPage ()
|
||||||
|
|
||||||
|
fireEvent.change (screen.getByLabelText ('ニコニコタグ'), {
|
||||||
|
target: { value: 'source' },
|
||||||
|
})
|
||||||
|
fireEvent.change (screen.getByLabelText ('連携タグ'), {
|
||||||
|
target: { value: 'destination' },
|
||||||
|
})
|
||||||
|
fireEvent.change (screen.getByLabelText ('連携状態'), {
|
||||||
|
target: { value: 'unlinked' },
|
||||||
|
})
|
||||||
|
fireEvent.submit (screen.getByRole ('button', { name: '検索' }).closest ('form')!)
|
||||||
|
|
||||||
|
await waitFor (() => {
|
||||||
|
expect (api.apiGet).toHaveBeenLastCalledWith (
|
||||||
|
'/tags/nico',
|
||||||
|
{ params: expect.objectContaining ({
|
||||||
|
page: 1,
|
||||||
|
name: 'source',
|
||||||
|
linked_tag: 'destination',
|
||||||
|
link_status: 'unlinked',
|
||||||
|
}) },
|
||||||
|
)
|
||||||
|
})
|
||||||
|
})
|
||||||
|
|
||||||
|
it ('updates links from a tag card', async () => {
|
||||||
|
api.apiGet
|
||||||
|
.mockResolvedValueOnce ({
|
||||||
|
tags: [buildNicoTag ({ id: 7, name: 'nico:source' })],
|
||||||
|
count: 1,
|
||||||
|
})
|
||||||
|
.mockResolvedValueOnce ({
|
||||||
|
tags: [
|
||||||
|
buildNicoTag ({
|
||||||
|
id: 7,
|
||||||
|
name: 'nico:source',
|
||||||
|
linkedTags: [buildTag ({ id: 8, name: '連携先' })],
|
||||||
|
}),
|
||||||
|
],
|
||||||
|
count: 1,
|
||||||
|
})
|
||||||
|
api.apiPut.mockResolvedValueOnce ([buildTag ({ id: 8, name: '連携先' })])
|
||||||
|
|
||||||
|
renderPage ()
|
||||||
|
|
||||||
|
fireEvent.click (await screen.findByRole ('button', { name: '編集' }))
|
||||||
|
fireEvent.change (screen.getByLabelText ('連携する広場タグ'), {
|
||||||
|
target: { value: '連携先' },
|
||||||
|
})
|
||||||
|
fireEvent.click (screen.getByRole ('button', { name: '保存' }))
|
||||||
|
|
||||||
|
await waitFor (() => {
|
||||||
|
expect (api.apiPut).toHaveBeenCalledWith (
|
||||||
|
'/tags/nico/7',
|
||||||
|
expect.any (FormData),
|
||||||
|
{ headers: { 'Content-Type': 'multipart/form-data' } },
|
||||||
|
)
|
||||||
|
})
|
||||||
|
expect (await screen.findByText ('1 件')).toBeInTheDocument ()
|
||||||
|
})
|
||||||
|
|
||||||
|
it ('asks before discarding changes when editing another tag', async () => {
|
||||||
|
api.apiGet.mockResolvedValueOnce ({
|
||||||
|
tags: [
|
||||||
|
buildNicoTag ({ id: 1, name: 'nico:first' }),
|
||||||
|
buildNicoTag ({ id: 2, name: 'nico:second' }),
|
||||||
|
],
|
||||||
|
count: 2,
|
||||||
|
})
|
||||||
|
|
||||||
|
renderPage ()
|
||||||
|
dialogue.confirm.mockResolvedValueOnce (false)
|
||||||
|
|
||||||
|
const editButtons = await screen.findAllByRole ('button', { name: '編集' })
|
||||||
|
fireEvent.click (editButtons[0])
|
||||||
|
fireEvent.change (screen.getByLabelText ('連携する広場タグ'), {
|
||||||
|
target: { value: '入力中' },
|
||||||
|
})
|
||||||
|
fireEvent.click (screen.getAllByRole ('button', { name: '編集' })[0])
|
||||||
|
|
||||||
|
await waitFor (() => {
|
||||||
|
expect (dialogue.confirm).toHaveBeenCalledWith ({
|
||||||
|
title: '編集中の内容を破棄しますか?',
|
||||||
|
confirmText: '破棄',
|
||||||
|
variant: 'danger',
|
||||||
|
})
|
||||||
|
})
|
||||||
|
expect (screen.getAllByLabelText ('連携する広場タグ')).toHaveLength (1)
|
||||||
|
expect (screen.getByLabelText ('連携する広場タグ')).toHaveValue ('入力中')
|
||||||
|
})
|
||||||
|
|
||||||
|
it ('switches editing rows without confirmation when unchanged', async () => {
|
||||||
|
api.apiGet.mockResolvedValueOnce ({
|
||||||
|
tags: [
|
||||||
|
buildNicoTag ({ id: 1, name: 'nico:first' }),
|
||||||
|
buildNicoTag ({ id: 2, name: 'nico:second' }),
|
||||||
|
],
|
||||||
|
count: 2,
|
||||||
|
})
|
||||||
|
|
||||||
|
renderPage ()
|
||||||
|
|
||||||
|
const editButtons = await screen.findAllByRole ('button', { name: '編集' })
|
||||||
|
fireEvent.click (editButtons[0])
|
||||||
|
fireEvent.click (screen.getAllByRole ('button', { name: '編集' })[0])
|
||||||
|
|
||||||
|
expect (dialogue.confirm).not.toHaveBeenCalled ()
|
||||||
|
expect (screen.getAllByLabelText ('連携する広場タグ')).toHaveLength (1)
|
||||||
|
})
|
||||||
|
|
||||||
|
it ('shows tags field validation errors inside the edited card', async () => {
|
||||||
|
api.apiGet.mockResolvedValueOnce ({
|
||||||
|
tags: [buildNicoTag ({ id: 7, name: 'nico:source' })],
|
||||||
|
count: 1,
|
||||||
|
})
|
||||||
|
api.isApiError.mockReturnValue (true)
|
||||||
|
api.apiPut.mockRejectedValueOnce ({
|
||||||
|
response: {
|
||||||
|
status: 422,
|
||||||
|
data: {
|
||||||
|
type: 'validation_error',
|
||||||
|
errors: { tags: ['タグ名を確認してください.'] },
|
||||||
|
base_errors: [],
|
||||||
|
},
|
||||||
|
},
|
||||||
|
})
|
||||||
|
|
||||||
|
renderPage ()
|
||||||
|
|
||||||
|
fireEvent.click (await screen.findByRole ('button', { name: '編集' }))
|
||||||
|
fireEvent.click (screen.getByRole ('button', { name: '保存' }))
|
||||||
|
|
||||||
|
expect (await screen.findByText ('タグ名を確認してください.')).toBeInTheDocument ()
|
||||||
|
expect (screen.getByLabelText ('連携する広場タグ')).toHaveAttribute ('aria-invalid', 'true')
|
||||||
|
})
|
||||||
|
})
|
||||||
@@ -1,120 +1,179 @@
|
|||||||
import type { FC } from 'react'
|
import { useQuery, useQueryClient } from '@tanstack/react-query'
|
||||||
|
import { Check, LoaderCircle, Pencil, X } from 'lucide-react'
|
||||||
import { useCallback, useEffect, useRef, useState } from 'react'
|
import { useEffect, useMemo, useState } from 'react'
|
||||||
import { Helmet } from 'react-helmet-async'
|
import { Helmet } from 'react-helmet-async'
|
||||||
|
import { useLocation, useNavigate } from 'react-router-dom'
|
||||||
|
|
||||||
import TagLink from '@/components/TagLink'
|
import TagLink from '@/components/TagLink'
|
||||||
|
import SortHeader from '@/components/SortHeader'
|
||||||
import FieldError from '@/components/common/FieldError'
|
import FieldError from '@/components/common/FieldError'
|
||||||
|
import FormField from '@/components/common/FormField'
|
||||||
import PageTitle from '@/components/common/PageTitle'
|
import PageTitle from '@/components/common/PageTitle'
|
||||||
|
import Pagination from '@/components/common/Pagination'
|
||||||
import TextArea from '@/components/common/TextArea'
|
import TextArea from '@/components/common/TextArea'
|
||||||
|
import { useDialogue } from '@/components/dialogues/DialogueProvider'
|
||||||
import MainArea from '@/components/layout/MainArea'
|
import MainArea from '@/components/layout/MainArea'
|
||||||
import { toast } from '@/components/ui/use-toast'
|
import { toast } from '@/components/ui/use-toast'
|
||||||
import { SITE_TITLE } from '@/config'
|
import { SITE_TITLE } from '@/config'
|
||||||
import { apiGet, apiPut } from '@/lib/api'
|
import { apiPut } from '@/lib/api'
|
||||||
import { extractValidationError } from '@/lib/apiErrors'
|
import { extractValidationError } from '@/lib/apiErrors'
|
||||||
|
import { tagsKeys } from '@/lib/queryKeys'
|
||||||
|
import { fetchNicoTags } from '@/lib/tags'
|
||||||
|
import { cn, dateString, inputClass } from '@/lib/utils'
|
||||||
import { canEditContent } from '@/lib/users'
|
import { canEditContent } from '@/lib/users'
|
||||||
|
|
||||||
import type { NicoTag, Tag, User } from '@/types'
|
import type { FC, FormEvent } from 'react'
|
||||||
|
|
||||||
|
import type { FetchNicoTagsOrder, FetchNicoTagsOrderField, NicoTag, Tag, User } from '@/types'
|
||||||
|
|
||||||
|
type LinkStatus = 'all' | 'linked' | 'unlinked'
|
||||||
type Props = { user: User | null }
|
type Props = { user: User | null }
|
||||||
|
|
||||||
|
|
||||||
const NicoTagListPage: FC<Props> = ({ user }) => {
|
const setIf = (qs: URLSearchParams, key: string, value: string) => {
|
||||||
const [cursor, setCursor] = useState ('')
|
const trimmed = value.trim ()
|
||||||
const [editing, setEditing] = useState<{ [key: number]: boolean }> ({ })
|
if (trimmed)
|
||||||
const [errorsByTagId, setErrorsByTagId] = useState<Record<number, string[]>> ({ })
|
qs.set (key, trimmed)
|
||||||
const [loading, setLoading] = useState (false)
|
}
|
||||||
const [nicoTags, setNicoTags] = useState<NicoTag[]> ([])
|
|
||||||
const [rawTags, setRawTags] = useState<{ [key: number]: string }> ({ })
|
|
||||||
|
|
||||||
const loaderRef = useRef<HTMLDivElement | null> (null)
|
|
||||||
|
const NicoTagListPage: FC<Props> = ({ user }) => {
|
||||||
|
const dialogue = useDialogue ()
|
||||||
|
const location = useLocation ()
|
||||||
|
const navigate = useNavigate ()
|
||||||
|
const queryClient = useQueryClient ()
|
||||||
|
const query = useMemo (() => new URLSearchParams (location.search), [location.search])
|
||||||
|
|
||||||
|
const page = Number (query.get ('page') ?? 1)
|
||||||
|
const limit = Number (query.get ('limit') ?? 20)
|
||||||
|
const qName = query.get ('name') ?? ''
|
||||||
|
const qLinkedTag = query.get ('linked_tag') ?? ''
|
||||||
|
const qLinkStatus = (query.get ('link_status') || 'all') as LinkStatus
|
||||||
|
const order = (query.get ('order') || 'updated_at:desc') as FetchNicoTagsOrder
|
||||||
|
|
||||||
|
const [editingId, setEditingId] = useState<number | null> (null)
|
||||||
|
const [errorsByTagId, setErrorsByTagId] = useState<Record<number, string[]>> ({ })
|
||||||
|
const [linkStatus, setLinkStatus] = useState<LinkStatus> ('all')
|
||||||
|
const [linkedTag, setLinkedTag] = useState ('')
|
||||||
|
const [name, setName] = useState ('')
|
||||||
|
const [rawTags, setRawTags] = useState<Record<number, string>> ({ })
|
||||||
|
const [savingId, setSavingId] = useState<number | null> (null)
|
||||||
|
|
||||||
|
const keys = {
|
||||||
|
name: qName, linkedTag: qLinkedTag, linkStatus: qLinkStatus, page, limit, order }
|
||||||
|
const { data, isError, isLoading: loading } = useQuery ({
|
||||||
|
queryKey: tagsKeys.nicoIndex (keys),
|
||||||
|
queryFn: () => fetchNicoTags (keys) })
|
||||||
|
const nicoTags = data?.tags ?? []
|
||||||
|
const count = data?.count ?? 0
|
||||||
|
|
||||||
const editable = canEditContent (user)
|
const editable = canEditContent (user)
|
||||||
|
const totalPages = Math.ceil (count / limit)
|
||||||
|
|
||||||
const applyLoadedTags = useCallback ((data: { tags: NicoTag[]; nextCursor: string },
|
const handleSearch = (e: FormEvent) => {
|
||||||
withCursor: boolean) => {
|
e.preventDefault ()
|
||||||
setNicoTags (tags => [...(withCursor ? tags : []), ...data.tags])
|
|
||||||
setCursor (data.nextCursor)
|
|
||||||
|
|
||||||
const newEditing = Object.fromEntries (data.tags.map (t => [t.id, false]))
|
const qs = new URLSearchParams ()
|
||||||
setEditing (editing => ({ ...editing, ...newEditing }))
|
setIf (qs, 'name', name)
|
||||||
|
setIf (qs, 'linked_tag', linkedTag)
|
||||||
|
if (linkStatus !== 'all')
|
||||||
|
qs.set ('link_status', linkStatus)
|
||||||
|
qs.set ('page', '1')
|
||||||
|
qs.set ('limit', String (limit))
|
||||||
|
qs.set ('order', order)
|
||||||
|
navigate (`${ location.pathname }?${ qs.toString () }`)
|
||||||
|
}
|
||||||
|
|
||||||
const newRawTags = Object.fromEntries (
|
const defaultDirection = {
|
||||||
data.tags.map (t => [t.id, t.linkedTags.map (lt => lt.name).join (' ')]))
|
name: 'asc',
|
||||||
setRawTags (rawTags => ({ ...rawTags, ...newRawTags }))
|
created_at: 'desc',
|
||||||
}, [])
|
updated_at: 'desc',
|
||||||
|
} as const
|
||||||
|
|
||||||
const loadInitial = useCallback (async () => {
|
const beginEdit = async (tag: NicoTag) => {
|
||||||
setLoading (true)
|
const editingTag = nicoTags.find (tag => tag.id === editingId)
|
||||||
|
const editingValue = editingTag?.linkedTags.map (tag => tag.name).join (' ') ?? ''
|
||||||
|
const editingChanged = editingId != null && rawTags[editingId] !== editingValue
|
||||||
|
|
||||||
const data = await apiGet<{ tags: NicoTag[]; nextCursor: string }> ('/tags/nico')
|
if (editingId != null && editingId !== tag.id && editingChanged
|
||||||
applyLoadedTags (data, false)
|
&& !(await dialogue.confirm ({
|
||||||
|
title: '編集中の内容を破棄しますか?',
|
||||||
|
confirmText: '破棄',
|
||||||
|
variant: 'danger',
|
||||||
|
})))
|
||||||
|
return
|
||||||
|
|
||||||
setLoading (false)
|
setEditingId (tag.id)
|
||||||
}, [applyLoadedTags])
|
setRawTags (rawTags => ({
|
||||||
|
...rawTags,
|
||||||
|
[tag.id]: tag.linkedTags.map (linkedTag => linkedTag.name).join (' '),
|
||||||
|
}))
|
||||||
|
setErrorsByTagId (errors => ({ ...errors, [tag.id]: [] }))
|
||||||
|
}
|
||||||
|
|
||||||
const loadMore = useCallback (async () => {
|
const cancelEdit = (tag: NicoTag) => {
|
||||||
setLoading (true)
|
setEditingId (null)
|
||||||
|
setRawTags (rawTags => ({
|
||||||
|
...rawTags,
|
||||||
|
[tag.id]: tag.linkedTags.map (linkedTag => linkedTag.name).join (' '),
|
||||||
|
}))
|
||||||
|
setErrorsByTagId (errors => ({ ...errors, [tag.id]: [] }))
|
||||||
|
}
|
||||||
|
|
||||||
const data = await apiGet<{ tags: NicoTag[]; nextCursor: string }> (
|
const saveLinks = async (id: number) => {
|
||||||
'/tags/nico', { params: { cursor } })
|
|
||||||
applyLoadedTags (data, true)
|
|
||||||
|
|
||||||
setLoading (false)
|
|
||||||
}, [applyLoadedTags, cursor])
|
|
||||||
|
|
||||||
const handleEdit = async (id: number) => {
|
|
||||||
if (editing[id])
|
|
||||||
{
|
|
||||||
const formData = new FormData
|
const formData = new FormData
|
||||||
formData.append ('tags', rawTags[id])
|
formData.append ('tags', rawTags[id] ?? '')
|
||||||
|
setSavingId (id)
|
||||||
|
|
||||||
try
|
try
|
||||||
{
|
{
|
||||||
const data = await apiPut<Tag[]> (`/tags/nico/${ id }`, formData,
|
await apiPut<Tag[]> (`/tags/nico/${ id }`, formData,
|
||||||
{ headers: { 'Content-Type': 'multipart/form-data' } })
|
{ headers: { 'Content-Type': 'multipart/form-data' } })
|
||||||
setNicoTags (nicoTags => {
|
|
||||||
nicoTags.find (t => t.id === id)!.linkedTags = data
|
|
||||||
return [...nicoTags]
|
|
||||||
})
|
|
||||||
setRawTags (rawTags => ({ ...rawTags, [id]: data.map (t => t.name).join (' ') }))
|
|
||||||
setErrorsByTagId (errors => ({ ...errors, [id]: [] }))
|
setErrorsByTagId (errors => ({ ...errors, [id]: [] }))
|
||||||
|
setEditingId (null)
|
||||||
toast ({ title: '更新しました.' })
|
await queryClient.invalidateQueries ({ queryKey: tagsKeys.nicoRoot })
|
||||||
|
toast ({ description: '連携を更新しました.' })
|
||||||
}
|
}
|
||||||
catch (e)
|
catch (e)
|
||||||
{
|
{
|
||||||
const validationError = extractValidationError<'tags'> (e)
|
const validationError = extractValidationError<'tags'> (e)
|
||||||
setErrorsByTagId (errors => ({ ...errors,
|
setErrorsByTagId (errors => ({
|
||||||
[id]: validationError?.fieldErrors.tags ?? [] }))
|
...errors,
|
||||||
|
[id]: validationError?.fieldErrors.tags
|
||||||
|
?? validationError?.baseErrors
|
||||||
|
?? ['更新できませんでした.'],
|
||||||
|
}))
|
||||||
toast ({ title: '更新失敗', description: '入力内容を確認してください.' })
|
toast ({ title: '更新失敗', description: '入力内容を確認してください.' })
|
||||||
return
|
}
|
||||||
|
finally
|
||||||
|
{
|
||||||
|
setSavingId (null)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
setEditing (editing => ({ ...editing, [id]: !(editing[id]) }))
|
|
||||||
}
|
|
||||||
|
|
||||||
useEffect(() => {
|
|
||||||
const observer = new IntersectionObserver (entries => {
|
|
||||||
if (entries[0].isIntersecting && !(loading) && cursor)
|
|
||||||
loadMore ()
|
|
||||||
}, { threshold: 1 })
|
|
||||||
|
|
||||||
const target = loaderRef.current
|
|
||||||
if (target)
|
|
||||||
observer.observe (target)
|
|
||||||
|
|
||||||
return () => {
|
|
||||||
if (target)
|
|
||||||
observer.unobserve (target)
|
|
||||||
}
|
|
||||||
}, [cursor, loadMore, loading])
|
|
||||||
|
|
||||||
useEffect (() => {
|
useEffect (() => {
|
||||||
setNicoTags ([])
|
setName (qName)
|
||||||
loadInitial ()
|
setLinkedTag (qLinkedTag)
|
||||||
}, [loadInitial])
|
setLinkStatus (qLinkStatus)
|
||||||
|
setEditingId (null)
|
||||||
|
|
||||||
|
document.querySelector ('table')?.scrollIntoView ({ behavior: 'smooth' })
|
||||||
|
}, [location.search, qLinkedTag, qLinkStatus, qName])
|
||||||
|
|
||||||
|
useEffect (() => {
|
||||||
|
if (!(data))
|
||||||
|
return
|
||||||
|
|
||||||
|
setRawTags (Object.fromEntries (data.tags.map (tag => [
|
||||||
|
tag.id,
|
||||||
|
tag.linkedTags.map (linkedTag => linkedTag.name).join (' '),
|
||||||
|
])))
|
||||||
|
}, [data])
|
||||||
|
|
||||||
|
useEffect (() => {
|
||||||
|
if (isError)
|
||||||
|
toast ({ title: '読込失敗', description: 'ニコニコ連携を読み込めませんでした.' })
|
||||||
|
}, [isError])
|
||||||
|
|
||||||
return (
|
return (
|
||||||
<MainArea>
|
<MainArea>
|
||||||
@@ -124,66 +183,201 @@ const NicoTagListPage: FC<Props> = ({ user }) => {
|
|||||||
|
|
||||||
<div className="max-w-xl">
|
<div className="max-w-xl">
|
||||||
<PageTitle>ニコニコ連携</PageTitle>
|
<PageTitle>ニコニコ連携</PageTitle>
|
||||||
|
<p className="mb-4 text-sm text-gray-600 dark:text-gray-300">
|
||||||
|
ニコニコタグを広場のタグへ結び付けます.
|
||||||
|
</p>
|
||||||
|
|
||||||
|
<form onSubmit={handleSearch} className="space-y-2">
|
||||||
|
<FormField label="ニコニコタグ">
|
||||||
|
{({ invalid }) => (
|
||||||
|
<input
|
||||||
|
type="text"
|
||||||
|
aria-label="ニコニコタグ"
|
||||||
|
value={name}
|
||||||
|
onChange={e => setName (e.target.value)}
|
||||||
|
className={inputClass (invalid)}/>)}
|
||||||
|
</FormField>
|
||||||
|
|
||||||
|
<FormField label="連携タグ">
|
||||||
|
{({ invalid }) => (
|
||||||
|
<input
|
||||||
|
type="text"
|
||||||
|
aria-label="連携タグ"
|
||||||
|
value={linkedTag}
|
||||||
|
onChange={e => setLinkedTag (e.target.value)}
|
||||||
|
className={inputClass (invalid)}/>)}
|
||||||
|
</FormField>
|
||||||
|
|
||||||
|
<FormField label="連携状態">
|
||||||
|
{({ invalid }) => (
|
||||||
|
<select
|
||||||
|
aria-label="連携状態"
|
||||||
|
value={linkStatus}
|
||||||
|
onChange={e => setLinkStatus (e.target.value as LinkStatus)}
|
||||||
|
className={inputClass (invalid)}>
|
||||||
|
<option value="all">すべて</option>
|
||||||
|
<option value="linked">連携済み</option>
|
||||||
|
<option value="unlinked">未連携</option>
|
||||||
|
</select>)}
|
||||||
|
</FormField>
|
||||||
|
|
||||||
|
<div className="py-3">
|
||||||
|
<button
|
||||||
|
type="submit"
|
||||||
|
className="rounded bg-blue-500 px-4 py-2 text-white">
|
||||||
|
検索
|
||||||
|
</button>
|
||||||
|
</div>
|
||||||
|
</form>
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
<div className="mt-4">
|
{loading
|
||||||
{nicoTags.length > 0 && (
|
? 'Loading...'
|
||||||
<table className="table-auto w-full border-collapse mb-4">
|
: (
|
||||||
|
<div className="mt-6">
|
||||||
|
<div className="mb-3 flex items-baseline justify-between gap-4">
|
||||||
|
<h2 className="text-lg font-bold">検索結果</h2>
|
||||||
|
<span className="text-sm text-gray-500 dark:text-gray-400">{count} 件</span>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
{nicoTags.length > 0
|
||||||
|
? (
|
||||||
|
<div className="overflow-x-auto">
|
||||||
|
<table className="w-full min-w-[800px] table-fixed border-collapse">
|
||||||
|
<colgroup>
|
||||||
|
<col className="w-64"/>
|
||||||
|
<col/>
|
||||||
|
<col className="w-56"/>
|
||||||
|
<col className="w-56"/>
|
||||||
|
{editable && <col className="w-24"/>}
|
||||||
|
</colgroup>
|
||||||
<thead className="border-b-2 border-black dark:border-white">
|
<thead className="border-b-2 border-black dark:border-white">
|
||||||
<tr>
|
<tr>
|
||||||
<th className="p-2 text-left">ニコニコタグ</th>
|
<th className="p-2 text-left whitespace-nowrap">
|
||||||
|
<SortHeader<FetchNicoTagsOrderField>
|
||||||
|
by="name"
|
||||||
|
label="ニコニコタグ"
|
||||||
|
currentOrder={order}
|
||||||
|
defaultDirection={defaultDirection}/>
|
||||||
|
</th>
|
||||||
<th className="p-2 text-left">連携タグ</th>
|
<th className="p-2 text-left">連携タグ</th>
|
||||||
{editable && <th></th>}
|
<th className="p-2 text-left whitespace-nowrap">
|
||||||
|
<SortHeader<FetchNicoTagsOrderField>
|
||||||
|
by="created_at"
|
||||||
|
label="最初に記載された日時"
|
||||||
|
currentOrder={order}
|
||||||
|
defaultDirection={defaultDirection}/>
|
||||||
|
</th>
|
||||||
|
<th className="p-2 text-left whitespace-nowrap">
|
||||||
|
<SortHeader<FetchNicoTagsOrderField>
|
||||||
|
by="updated_at"
|
||||||
|
label="最近記載された日時"
|
||||||
|
currentOrder={order}
|
||||||
|
defaultDirection={defaultDirection}/>
|
||||||
|
</th>
|
||||||
|
{editable && <th className="p-2"></th>}
|
||||||
</tr>
|
</tr>
|
||||||
</thead>
|
</thead>
|
||||||
<tbody>
|
<tbody>
|
||||||
{nicoTags.map ((tag, i) => (
|
{nicoTags.map (tag => {
|
||||||
<tr key={i} className="even:bg-gray-100 dark:even:bg-gray-700">
|
const isEditing = editingId === tag.id
|
||||||
<td className="p-2">
|
|
||||||
|
return [
|
||||||
|
<tr
|
||||||
|
key={tag.id}
|
||||||
|
className={cn (
|
||||||
|
'border-b border-gray-200 dark:border-gray-700',
|
||||||
|
isEditing
|
||||||
|
? 'bg-rose-50 dark:bg-rose-950/30'
|
||||||
|
: 'even:bg-gray-100 dark:even:bg-gray-800')}>
|
||||||
|
<td className="p-2 align-top font-semibold">
|
||||||
<TagLink tag={tag} withWiki={false} withCount={false}/>
|
<TagLink tag={tag} withWiki={false} withCount={false}/>
|
||||||
</td>
|
</td>
|
||||||
<td className="p-2">
|
<td className="p-2 align-top">
|
||||||
{editing[tag.id]
|
{tag.linkedTags.map ((linkedTag, i) => (
|
||||||
? (
|
<span key={linkedTag.id}>
|
||||||
<>
|
{i > 0 && ' '}
|
||||||
<TextArea
|
<TagLink
|
||||||
value={rawTags[tag.id]}
|
tag={linkedTag}
|
||||||
invalid={(errorsByTagId[tag.id] ?? []).length > 0}
|
|
||||||
onChange={ev => {
|
|
||||||
setRawTags (rawTags => ({
|
|
||||||
...rawTags,
|
|
||||||
[tag.id]: ev.target.value }))
|
|
||||||
}}/>
|
|
||||||
<FieldError messages={errorsByTagId[tag.id]}/>
|
|
||||||
</>)
|
|
||||||
: tag.linkedTags.map((lt, j) => (
|
|
||||||
<span key={j} className="mr-2">
|
|
||||||
<TagLink tag={lt}
|
|
||||||
linkFlg={false}
|
linkFlg={false}
|
||||||
withCount={false}/>
|
withCount={false}/>
|
||||||
</span>))}
|
</span>))}
|
||||||
</td>
|
</td>
|
||||||
|
<td className="p-2 align-top whitespace-nowrap">
|
||||||
|
{dateString (tag.createdAt)}
|
||||||
|
</td>
|
||||||
|
<td className="p-2 align-top whitespace-nowrap">
|
||||||
|
{tag.recentPostTagCreatedAt && dateString (tag.recentPostTagCreatedAt)}
|
||||||
|
</td>
|
||||||
{editable && (
|
{editable && (
|
||||||
<td className="p-2">
|
<td className="p-2 text-right align-top">
|
||||||
<a href="#" onClick={ev => {
|
{!(isEditing) && (
|
||||||
ev.preventDefault ()
|
<button
|
||||||
handleEdit (tag.id)
|
type="button"
|
||||||
}}>
|
onClick={() => beginEdit (tag)}
|
||||||
{editing[tag.id]
|
className="inline-flex items-center gap-1 text-sm text-blue-700
|
||||||
? (
|
hover:underline dark:text-blue-300">
|
||||||
<span className="text-red-600 hover:text-red-400
|
<Pencil className="size-3.5"/>
|
||||||
dark:text-red-300 dark:hover:text-red-100">
|
編集
|
||||||
更新
|
</button>)}
|
||||||
</span>)
|
|
||||||
: <span>編輯</span>}
|
|
||||||
</a>
|
|
||||||
</td>)}
|
</td>)}
|
||||||
</tr>))}
|
</tr>,
|
||||||
</tbody>
|
isEditing && (
|
||||||
</table>)}
|
<tr key={`${ tag.id }-edit`}
|
||||||
{loading && 'Loading...'}
|
className="border-b border-rose-200 bg-rose-50 dark:border-rose-900
|
||||||
<div ref={loaderRef} className="h-12"></div>
|
dark:bg-rose-950/30">
|
||||||
|
<td colSpan={editable ? 5 : 4} className="p-3">
|
||||||
|
<div className="space-y-2">
|
||||||
|
<label htmlFor={`nico-links-${ tag.id }`}
|
||||||
|
className="block text-sm font-semibold">
|
||||||
|
連携する広場タグ
|
||||||
|
</label>
|
||||||
|
<TextArea
|
||||||
|
id={`nico-links-${ tag.id }`}
|
||||||
|
value={rawTags[tag.id] ?? ''}
|
||||||
|
invalid={(errorsByTagId[tag.id] ?? []).length > 0}
|
||||||
|
className="min-h-24 resize-y"
|
||||||
|
placeholder="タグ名を空白または改行で区切って入力"
|
||||||
|
onChange={e => setRawTags (rawTags => ({
|
||||||
|
...rawTags,
|
||||||
|
[tag.id]: e.target.value,
|
||||||
|
}))}/>
|
||||||
|
<FieldError messages={errorsByTagId[tag.id]}/>
|
||||||
|
<div className="flex justify-end gap-2">
|
||||||
|
<button
|
||||||
|
type="button"
|
||||||
|
disabled={savingId === tag.id}
|
||||||
|
onClick={() => cancelEdit (tag)}
|
||||||
|
className="inline-flex items-center gap-1 rounded border
|
||||||
|
border-gray-300 px-3 py-1.5 text-sm
|
||||||
|
disabled:opacity-50 dark:border-gray-700">
|
||||||
|
<X className="size-3.5"/>
|
||||||
|
取消
|
||||||
|
</button>
|
||||||
|
<button
|
||||||
|
type="button"
|
||||||
|
disabled={savingId === tag.id}
|
||||||
|
onClick={() => saveLinks (tag.id)}
|
||||||
|
className="inline-flex items-center gap-1 rounded bg-rose-700
|
||||||
|
px-3 py-1.5 text-sm text-white disabled:opacity-50">
|
||||||
|
{savingId === tag.id
|
||||||
|
? <LoaderCircle className="size-3.5 animate-spin"/>
|
||||||
|
: <Check className="size-3.5"/>}
|
||||||
|
保存
|
||||||
|
</button>
|
||||||
</div>
|
</div>
|
||||||
|
</div>
|
||||||
|
</td>
|
||||||
|
</tr>),
|
||||||
|
]
|
||||||
|
})}
|
||||||
|
</tbody>
|
||||||
|
</table>
|
||||||
|
</div>)
|
||||||
|
: <p>結果ないよ(笑)</p>}
|
||||||
|
|
||||||
|
<Pagination page={page} totalPages={totalPages}/>
|
||||||
|
</div>)}
|
||||||
</MainArea>)
|
</MainArea>)
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
+14
-1
@@ -52,6 +52,18 @@ export type FetchTagsParams = {
|
|||||||
limit: number
|
limit: number
|
||||||
order: FetchTagsOrder }
|
order: FetchTagsOrder }
|
||||||
|
|
||||||
|
export type FetchNicoTagsParams = {
|
||||||
|
name: string
|
||||||
|
linkedTag: string
|
||||||
|
linkStatus: 'all' | 'linked' | 'unlinked'
|
||||||
|
page: number
|
||||||
|
limit: number
|
||||||
|
order: FetchNicoTagsOrder }
|
||||||
|
|
||||||
|
export type FetchNicoTagsOrder = `${ FetchNicoTagsOrderField }:${ 'asc' | 'desc' }`
|
||||||
|
|
||||||
|
export type FetchNicoTagsOrderField = 'name' | 'created_at' | 'updated_at'
|
||||||
|
|
||||||
export type Material = {
|
export type Material = {
|
||||||
id: number
|
id: number
|
||||||
tag: Tag
|
tag: Tag
|
||||||
@@ -84,7 +96,8 @@ export type MenuVisibleItem = {
|
|||||||
|
|
||||||
export type NicoTag = Tag & {
|
export type NicoTag = Tag & {
|
||||||
category: 'nico'
|
category: 'nico'
|
||||||
linkedTags: Tag[] }
|
linkedTags: Tag[]
|
||||||
|
recentPostTagCreatedAt: string | null }
|
||||||
|
|
||||||
export type NiconicoMetadata = {
|
export type NiconicoMetadata = {
|
||||||
currentTime: number
|
currentTime: number
|
||||||
|
|||||||
新しい課題から参照
ユーザをブロックする