コミットを比較

..

16 コミット

作成者 SHA1 メッセージ 日付
みてるぞ 41a98ff725 #306 2026-06-27 05:37:58 +09:00
みてるぞ c836369dfc #306 2026-06-27 05:30:23 +09:00
みてるぞ 363146c219 #306 2026-06-27 05:20:25 +09:00
みてるぞ ce28661271 #306 2026-06-26 01:56:01 +09:00
みてるぞ d7b136c198 #306 2026-06-26 01:20:30 +09:00
みてるぞ 4da3f0afba #306 2026-06-26 00:51:40 +09:00
みてるぞ daf9e7e6fa #306 2026-06-26 00:49:18 +09:00
みてるぞ 8304909c8c #306 2026-06-26 00:21:33 +09:00
みてるぞ 377a09ed70 #306 2026-06-25 17:40:34 +09:00
みてるぞ c10ba7a698 #306 2026-06-25 08:11:41 +09:00
みてるぞ fa6c547cc9 #306 2026-06-25 07:44:11 +09:00
みてるぞ dbc654f346 #306 2026-06-25 04:10:43 +09:00
みてるぞ c2102c8f96 #306 2026-06-24 01:26:26 +09:00
みてるぞ 510cbb0d78 #306 2026-06-24 00:38:29 +09:00
みてるぞ a820ce4c3e #306 事故が起きたので,エージェントへの指示を追加 2026-06-23 23:43:01 +09:00
みてるぞ 507ce1680e #306 2026-06-23 22:05:11 +09:00
19個のファイルの変更405行の追加647行の削除
+1 -6
ファイルの表示
@@ -271,12 +271,7 @@ const value =
- In TypeScript and TSX, convert every leading run of 8 spaces to a tab - In TypeScript and TSX, convert every leading run of 8 spaces to a tab
character. character.
- A leading tab is exactly equivalent to 8 leading spaces. - A leading tab is exactly equivalent to 8 leading spaces.
- In TypeScript and TSX function declarations, including `const` arrow - Never place a closing parenthesis at the beginning of a line.
function declarations, when the parameter list spans multiple lines, always
put the closing parenthesis at the beginning of its own line before the return
type or `=>`.
- In TypeScript and TSX, never place a closing parenthesis at the beginning of
a line except for a multi-line function declaration parameter list.
- Never place a closing square bracket at the beginning of a line. - Never place a closing square bracket at the beginning of a line.
- For object literals and other associative-array-style braces, do not place - For object literals and other associative-array-style braces, do not place
the closing brace at the beginning of a line. Function, lambda, callback, and the closing brace at the beginning of a line. Function, lambda, callback, and
+3 -4
ファイルの表示
@@ -140,11 +140,10 @@ class PostsController < ApplicationController
original_created_from = params[:original_created_from] original_created_from = params[:original_created_from]
original_created_before = params[:original_created_before] original_created_before = params[:original_created_before]
parent_post_ids = parse_parent_post_ids parent_post_ids = parse_parent_post_ids
resized_thumbnail = thumbnail.present? ? Post.resized_thumbnail_attachment(thumbnail) : nil
post = Post.new(title:, url:, thumbnail_base: nil, uploaded_user: current_user, post = Post.new(title:, url:, thumbnail_base: nil, uploaded_user: current_user,
original_created_from:, original_created_before:) original_created_from:, original_created_before:)
post.thumbnail.attach(resized_thumbnail) if resized_thumbnail post.thumbnail.attach(thumbnail) if thumbnail.present?
ApplicationRecord.transaction do ApplicationRecord.transaction do
post.save! post.save!
@@ -157,6 +156,8 @@ class PostsController < ApplicationController
sync_parent_posts!(post, parent_post_ids) sync_parent_posts!(post, parent_post_ids)
post.resized_thumbnail!
PostVersionRecorder.record!(post:, event_type: :create, created_by_user: current_user) PostVersionRecorder.record!(post:, event_type: :create, created_by_user: current_user)
end end
@@ -166,8 +167,6 @@ class PostsController < ApplicationController
render_validation_error fields: { tags: 'ニコニコ・タグは直接指定できません.' } render_validation_error fields: { tags: 'ニコニコ・タグは直接指定できません.' }
rescue Tag::DeprecatedTagNormalisationError rescue Tag::DeprecatedTagNormalisationError
render_unprocessable_entity '廃止済みタグは付与できません.', field: :tags render_unprocessable_entity '廃止済みタグは付与できません.', field: :tags
rescue MiniMagick::Error
render_validation_error fields: { thumbnail: ['サムネイル画像の変換に失敗しました.'] }
rescue ArgumentError => e rescue ArgumentError => e
render_validation_error fields: { parent_post_ids: [e.message] } render_validation_error fields: { parent_post_ids: [e.message] }
rescue ActiveRecord::RecordInvalid => e rescue ActiveRecord::RecordInvalid => e
+6 -15
ファイルの表示
@@ -1,19 +1,5 @@
class Post < ApplicationRecord class Post < ApplicationRecord
require 'mini_magick' require 'mini_magick'
require 'stringio'
def self.resized_thumbnail_attachment(upload)
upload.rewind
image = MiniMagick::Image.read(upload.read)
image.resize '180x180'
image.format 'jpg'
{ io: StringIO.new(image.to_blob),
filename: 'resized_thumbnail.jpg',
content_type: 'image/jpeg' }
ensure
upload.rewind
end
belongs_to :uploaded_user, class_name: 'User', optional: true belongs_to :uploaded_user, class_name: 'User', optional: true
@@ -101,7 +87,12 @@ class Post < ApplicationRecord
def resized_thumbnail! def resized_thumbnail!
return unless thumbnail.attached? return unless thumbnail.attached?
thumbnail.attach(self.class.resized_thumbnail_attachment(StringIO.new(thumbnail.download))) image = MiniMagick::Image.read(thumbnail.download)
image.resize '180x180'
thumbnail.purge
thumbnail.attach(io: File.open(image.path),
filename: 'resized_thumbnail.jpg',
content_type: 'image/jpeg')
end end
private private
+4 -11
ファイルの表示
@@ -26,19 +26,13 @@ module GoogleDrive
def list_material_files_under_folder folder_id def list_material_files_under_folder folder_id
files = [] files = []
each_material_file_under_folder(folder_id) { |entry| files << entry }
files
end
def each_material_file_under_folder folder_id
return enum_for(__method__, folder_id) unless block_given?
walk_folder(folder_id, nil) do |entry, relative_path| walk_folder(folder_id, nil) do |entry, relative_path|
next if entry['mimeType'] == FOLDER_MIME_TYPE next if entry['mimeType'] == FOLDER_MIME_TYPE
next if native_file?(entry['mimeType']) next if native_file?(entry['mimeType'])
yield build_file_entry(entry, relative_path) files << build_file_entry(entry, relative_path)
end end
files
end end
def fetch_material_file file_id def fetch_material_file file_id
@@ -50,10 +44,9 @@ module GoogleDrive
def download_to_tempfile file_id, filename: def download_to_tempfile file_id, filename:
tempfile = Tempfile.new(['material-sync', File.extname(filename.to_s)]) tempfile = Tempfile.new(['material-sync', File.extname(filename.to_s)])
tempfile.binmode
request_binary("/files/#{ file_id }", request_binary("/files/#{ file_id }",
{ alt: 'media', supportsAllDrives: true }) do |chunk| { alt: 'media', supportsAllDrives: true }) do |chunk|
tempfile.write(chunk.b) tempfile.write(chunk)
end end
tempfile.rewind tempfile.rewind
tempfile tempfile
@@ -146,7 +139,7 @@ module GoogleDrive
end end
response.read_body do |chunk| response.read_body do |chunk|
yield chunk.b yield chunk
end end
end end
end end
+3 -34
ファイルの表示
@@ -21,15 +21,11 @@ class MaterialSyncRunner
result = Result.new(imported: 0, updated: 0, unchanged: 0, result = Result.new(imported: 0, updated: 0, unchanged: 0,
suppressed: 0, failed: 0, errors: []) suppressed: 0, failed: 0, errors: [])
if @source.source_kind == 'google_drive_path'
sync_google_drive_path!(result)
else
candidates.each do |candidate| candidates.each do |candidate|
next if candidate.blank? next if candidate.blank?
sync_candidate!(candidate, result) sync_candidate!(candidate, result)
end end
end
@source.update!(last_synced_at: Time.current) @source.update!(last_synced_at: Time.current)
log_result(result) log_result(result)
@@ -47,6 +43,8 @@ class MaterialSyncRunner
case @source.source_kind case @source.source_kind
when 'uri' when 'uri'
[uri_candidate] [uri_candidate]
when 'google_drive_path'
google_drive_path_candidates
when 'google_drive_file' when 'google_drive_file'
[google_drive_file_candidate] [google_drive_file_candidate]
when 'legacy_drive_path' when 'legacy_drive_path'
@@ -106,25 +104,12 @@ class MaterialSyncRunner
def google_drive_path_candidates def google_drive_path_candidates
folder_id = google_drive_folder_id folder_id = google_drive_folder_id
Enumerator.new do |entries| Enumerator.new do |entries|
drive_client.each_material_file_under_folder(folder_id).each do |entry| drive_client.list_material_files_under_folder(folder_id).each do |entry|
entries << build_google_drive_candidate(entry) entries << build_google_drive_candidate(entry)
end end
end end
end end
def sync_google_drive_path! result
folder_id = google_drive_folder_id
scanned_count = 0
drive_client.each_material_file_under_folder(folder_id) do |entry|
scanned_count += 1
sync_candidate!(build_google_drive_candidate(entry), result)
log_google_drive_progress(folder_id, scanned_count, result) if progress_log_scan_count?(scanned_count)
end
log_google_drive_progress(folder_id, scanned_count, result, summary: true)
end
def google_drive_file_candidate def google_drive_file_candidate
entry = drive_client.fetch_material_file(google_drive_file_id) entry = drive_client.fetch_material_file(google_drive_file_id)
return nil unless entry return nil unless entry
@@ -228,22 +213,6 @@ class MaterialSyncRunner
failed: result.failed)) failed: result.failed))
end end
def progress_log_scan_count? scanned_count
scanned_count == 1 || (scanned_count % 50).zero?
end
def log_google_drive_progress folder_id, scanned_count, result, summary: false
Rails.logger.info(
material_sync_log(folder_id:,
scanned_count:,
imported: result.imported,
updated: result.updated,
unchanged: result.unchanged,
suppressed: result.suppressed,
failed: result.failed,
progress: summary ? 'summary' : 'scan'))
end
def material_sync_log fields def material_sync_log fields
{ material_sync_source_id: @source.id, { material_sync_source_id: @source.id,
material_sync_source_name: @source.name }.merge(fields).to_json material_sync_source_name: @source.name }.merge(fields).to_json
-78
ファイルの表示
@@ -1,5 +1,4 @@
require 'rails_helper' require 'rails_helper'
require 'base64'
require 'set' require 'set'
include ActiveSupport::Testing::TimeHelpers include ActiveSupport::Testing::TimeHelpers
@@ -9,11 +8,6 @@ RSpec.describe 'Posts API', type: :request do
# resized_thumbnail! が MiniMagick 依存でコケやすいので request spec ではスタブしとくのが無難。 # resized_thumbnail! が MiniMagick 依存でコケやすいので request spec ではスタブしとくのが無難。
before do before do
allow_any_instance_of(Post).to receive(:resized_thumbnail!).and_return(true) allow_any_instance_of(Post).to receive(:resized_thumbnail!).and_return(true)
allow(Post).to receive(:resized_thumbnail_attachment).and_return(
io: StringIO.new('dummy'),
filename: 'resized_thumbnail.jpg',
content_type: 'image/jpeg'
)
end end
def create_nico_tag!(name) def create_nico_tag!(name)
@@ -25,18 +19,6 @@ RSpec.describe 'Posts API', type: :request do
Rack::Test::UploadedFile.new(StringIO.new('dummy'), 'image/jpeg', original_filename: 'dummy.jpg') Rack::Test::UploadedFile.new(StringIO.new('dummy'), 'image/jpeg', original_filename: 'dummy.jpg')
end end
def real_thumbnail_upload
gif =
Base64.decode64(
'R0lGODdhAQABAIABAP///wAAACwAAAAAAQABAAACAkQBADs=')
Rack::Test::UploadedFile.new(
StringIO.new(gif),
'image/gif',
original_filename: 'thumbnail.gif'
)
end
def post_write_params params = { } def post_write_params params = { }
{ parent_post_ids: '' }.merge(params) { parent_post_ids: '' }.merge(params)
end end
@@ -714,66 +696,6 @@ RSpec.describe 'Posts API', type: :request do
expect(json['tags'][0]).to have_key('name') expect(json['tags'][0]).to have_key('name')
end end
it '201 when posting manually with a thumbnail' do
sign_in_as(member)
allow(Post).to receive(:resized_thumbnail_attachment).and_call_original
post '/posts', params: post_write_params(
title: 'thumbnail post',
url: 'https://example.com/thumbnail-post',
tags: 'spec_tag',
thumbnail: real_thumbnail_upload
)
expect(response).to have_http_status(:created)
post_record = Post.find(json.fetch('id'))
expect(post_record.thumbnail).to be_attached
expect(post_record.thumbnail.blob.content_type).to eq('image/jpeg')
expect { post_record.thumbnail.download }.not_to raise_error
end
it 'resizes the thumbnail before the create transaction begins' do
sign_in_as(member)
open_transactions = []
baseline_open_transactions = Post.connection.open_transactions
allow(Post).to receive(:resized_thumbnail_attachment) do |_upload|
open_transactions << Post.connection.open_transactions
{ io: StringIO.new('dummy'),
filename: 'resized_thumbnail.jpg',
content_type: 'image/jpeg' }
end
post '/posts', params: post_write_params(
title: 'transaction post',
url: 'https://example.com/transaction-post',
tags: 'spec_tag',
thumbnail: dummy_upload
)
expect(response).to have_http_status(:created)
expect(open_transactions).to eq([baseline_open_transactions])
end
it 'returns 422 and does not create a post when thumbnail resize fails' do
sign_in_as(member)
allow(Post).to receive(:resized_thumbnail_attachment).and_raise(MiniMagick::Error)
expect {
post '/posts', params: post_write_params(
title: 'broken thumbnail post',
url: 'https://example.com/broken-thumbnail-post',
tags: 'spec_tag',
thumbnail: dummy_upload
)
}.not_to change(Post, :count)
expect(response).to have_http_status(:unprocessable_entity)
expect(json.fetch('errors')).to include(
'thumbnail' => ['サムネイル画像の変換に失敗しました.']
)
end
it '201 and creates post + tags when member and tags have aliases' do it '201 and creates post + tags when member and tags have aliases' do
sign_in_as(member) sign_in_as(member)
-89
ファイルの表示
@@ -1,89 +0,0 @@
require 'rails_helper'
RSpec.describe MaterialSyncRunner do
let(:user) { create(:user, :member) }
let(:source) do
MaterialSyncSource.create!(
name: 'Drive source',
source_kind: 'google_drive_path',
source_file_id: 'folder-123',
profile: 'legacy_drive',
created_by_user: user,
updated_by_user: user)
end
let(:drive_client) { instance_double(GoogleDrive::ApiClient) }
describe '#sync!' do
it 'imports google drive path candidates as they are yielded' do
first_entry = { id: 'file-1',
name: 'a.png',
mime_type: 'image/png',
relative_path: '素材/a.png',
sha256_checksum: 'sha-a',
web_view_link: 'https://drive.google.com/file/d/file-1/view',
web_content_link: nil }
second_entry = { id: 'file-2',
name: 'b.png',
mime_type: 'image/png',
relative_path: '素材/b.png',
sha256_checksum: 'sha-b',
web_view_link: 'https://drive.google.com/file/d/file-2/view',
web_content_link: nil }
yielded = []
allow(GoogleDrive::ApiClient).to receive(:new).and_return(drive_client)
allow(drive_client).to receive(:each_material_file_under_folder) do |folder_id, &block|
expect(folder_id).to eq('folder-123')
block.call(first_entry)
expect(yielded).to eq(['素材/a.png'])
block.call(second_entry)
end
allow(MaterialSyncImporter).to receive(:import!) do |candidate|
yielded << candidate.fetch(:source_path)
instance_double(MaterialSyncImporter::Result,
action: yielded.last == '素材/a.png' ? :imported : :updated)
end
result = described_class.new(source).sync!
expect(yielded).to eq(['素材/a.png', '素材/b.png'])
expect(result.imported).to eq(1)
expect(result.updated).to eq(1)
expect(result.unchanged).to eq(0)
expect(source.reload.last_synced_at).to be_present
end
it 'logs google drive path progress at first item and summary' do
entry = { id: 'file-1',
name: 'a.png',
mime_type: 'image/png',
relative_path: '素材/a.png',
sha256_checksum: 'sha-a',
web_view_link: 'https://drive.google.com/file/d/file-1/view',
web_content_link: nil }
logged = []
allow(GoogleDrive::ApiClient).to receive(:new).and_return(drive_client)
allow(drive_client).to receive(:each_material_file_under_folder) do |_folder_id, &block|
block.call(entry)
end
allow(MaterialSyncImporter).to receive(:import!)
.and_return(instance_double(MaterialSyncImporter::Result, action: :imported))
allow(Rails.logger).to receive(:info) { |message| logged << JSON.parse(message) }
described_class.new(source).sync!
progress_logs = logged.select { |row| row['folder_id'] == 'folder-123' }
expect(progress_logs.map { |row| row['progress'] }).to eq(['scan', 'summary'])
expect(progress_logs.last).to include(
'material_sync_source_id' => source.id,
'material_sync_source_name' => 'Drive source',
'scanned_count' => 1,
'imported' => 1,
'updated' => 0,
'unchanged' => 0,
'suppressed' => 0,
'failed' => 0)
end
end
end
+1
ファイルの表示
@@ -75,6 +75,7 @@ const RouteTransitionWrapper = ({ user, setUser }: {
<Route path="suppressions" element={<MaterialSyncSuppressionsPage/>}/> <Route path="suppressions" element={<MaterialSyncSuppressionsPage/>}/>
<Route path=":id" element ={<MaterialDetailPage/>}/> <Route path=":id" element ={<MaterialDetailPage/>}/>
</Route> </Route>
{/* <Route path="/materials/search" element={<MaterialSearchPage/>}/> */}
<Route path="/wiki" element={<WikiSearchPage/>}/> <Route path="/wiki" element={<WikiSearchPage/>}/>
<Route path="/wiki/:title" element={<WikiDetailPage/>}/> <Route path="/wiki/:title" element={<WikiDetailPage/>}/>
<Route path="/wiki/new" element={<WikiNewPage user={user}/>}/> <Route path="/wiki/new" element={<WikiNewPage user={user}/>}/>
+86 -229
ファイルの表示
@@ -1,43 +1,29 @@
import { Fragment, useEffect, useRef, useState } from 'react'
import { useQuery } from '@tanstack/react-query' import { useQuery } from '@tanstack/react-query'
import { useEffect, useRef, useState } from 'react'
import { useLocation, useNavigate } from 'react-router-dom' import { useLocation, useNavigate } from 'react-router-dom'
import SidebarComponent from '@/components/layout/SidebarComponent' import PrefetchLink from '@/components/PrefetchLink'
import TagLink from '@/components/TagLink' import TagLink from '@/components/TagLink'
import { fetchMaterialTagTree, parseMaterialFilter } from '@/lib/materials' import SidebarComponent from '@/components/layout/SidebarComponent'
import { materialsKeys } from '@/lib/queryKeys' import { materialsKeys } from '@/lib/queryKeys'
import { cn } from '@/lib/utils' import { fetchMaterialTagTree, parseMaterialFilter } from '@/lib/materials'
import type { CSSProperties, Dispatch, FC, ReactNode, SetStateAction } from 'react' import type { Dispatch, FC, ReactNode, SetStateAction } from 'react'
import type { MaterialFilter, MaterialSidebarTag, Tag } from '@/types' import type { MaterialFilter, MaterialSidebarTag, Tag } from '@/types'
const FILTERS: MaterialFilter[] = ['missing', 'present', 'any'] const FILTERS: MaterialFilter[] = ['present', 'missing', 'any']
const FILTER_LABELS: Record<MaterialFilter, string> = { present: '有', missing: '無', any: '全' }
const FILTER_LABELS: Record<MaterialFilter, string> = {
const px = (value: string): number => { present: '素材あり',
const parsed = Number.parseFloat (value) missing: '素材なし',
return Number.isFinite (parsed) ? parsed : 0 any: 'すべて'}
}
const verticalChrome = (el: HTMLElement): number => {
const style = window.getComputedStyle (el)
return (
px (style.paddingTop)
+ px (style.paddingBottom)
+ px (style.borderTopWidth)
+ px (style.borderBottomWidth))
}
const setChildrenById = ( const setChildrenById = (
tags: MaterialSidebarTag[], tags: MaterialSidebarTag[],
targetId: number, targetId: number,
children: MaterialSidebarTag[], children: MaterialSidebarTag[]): MaterialSidebarTag[] => (
): MaterialSidebarTag[] => (
tags.map (tag => { tags.map (tag => {
if (tag.id === targetId) if (tag.id === targetId)
return { ...tag, children } return { ...tag, children }
@@ -51,12 +37,24 @@ const setChildrenById = (
const materialPath = ( const materialPath = (
tagId: number, tagId: number,
materialFilter: MaterialFilter, materialFilter: MaterialFilter): string =>
): string =>
`/materials?tag_id=${ tagId }&include_descendants=1&group_by=parent_tag` `/materials?tag_id=${ tagId }&include_descendants=1&group_by=parent_tag`
+ `&material_filter=${ materialFilter }` + `&material_filter=${ materialFilter }`
const clearTagSelectionPath = (
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 sidebarTagToTag = (tag: MaterialSidebarTag): Tag => ({ const sidebarTagToTag = (tag: MaterialSidebarTag): Tag => ({
id: tag.id, id: tag.id,
name: tag.name, name: tag.name,
@@ -74,42 +72,39 @@ const sidebarTagToTag = (tag: MaterialSidebarTag): Tag => ({
const tagSelectionShellClass = (selected: boolean): string => const tagSelectionShellClass = (selected: boolean): string =>
cn (selected selected
? ['rounded-md border border-sky-500 bg-sky-50 px-2 py-1 text-sky-700', ? 'rounded-md border border-sky-500 bg-sky-50 px-2 py-1 text-sky-700 '
'dark:border-sky-400 dark:bg-sky-950 dark:text-sky-100'] + 'dark:border-sky-400 dark:bg-sky-950 dark:text-sky-100'
: 'px-2 py-1') : 'px-2 py-1'
const updateMaterialFilterQuery = ( const updateMaterialFilterQuery = (
pathname: string, pathname: string,
locationSearch: string, locationSearch: string,
navigate: ReturnType<typeof useNavigate>, navigate: ReturnType<typeof useNavigate>,
materialFilter: MaterialFilter, materialFilter: MaterialFilter) => {
) => {
const qs = new URLSearchParams (locationSearch) const qs = new URLSearchParams (locationSearch)
qs.set ('material_filter', materialFilter) qs.set ('material_filter', materialFilter)
navigate (`${ pathname }${ qs.toString () ? `?${ qs.toString () }` : '' }`) navigate (`${ pathname }${ qs.toString () ? `?${ qs.toString () }` : '' }`)
} }
const MaterialFilterButtons: FC<{ materialFilter: MaterialFilter const MaterialFilterButtons: FC<{
onChange: (materialFilter: MaterialFilter) => void }> = ( materialFilter: MaterialFilter
{ materialFilter, onChange }, onChange: (materialFilter: MaterialFilter) => void
) => ( }> = ({ materialFilter, onChange }) => (
<div className="flex flex-wrap gap-2 justify-end md:justify-start flex-center"> <div className="flex flex-wrap gap-2">
<label className="my-auto text-sm font-bold"></label>
{FILTERS.map (value => ( {FILTERS.map (value => (
<button <button
key={value} key={value}
type="button" type="button"
onClick={() => onChange (value)} onClick={() => onChange (value)}
className={cn ( className={`rounded-full border px-3 py-1 text-sm ${
'rounded-full border px-3 py-1 text-sm', materialFilter === value
(materialFilter === value ? 'border-sky-500 bg-sky-50 text-sky-700 dark:border-sky-400 '
? ['border-sky-500 bg-sky-50 text-sky-700 dark:border-sky-400', + 'dark:bg-sky-950 dark:text-sky-100'
'dark:bg-sky-950 dark:text-sky-100'] : 'border-neutral-300 bg-white text-neutral-700 dark:border-stone-700 '
: ['border-neutral-300 bg-white text-neutral-700 dark:border-stone-700', + 'dark:bg-stone-900 dark:text-stone-200' }`}>
'dark:bg-stone-900 dark:text-stone-200']))}>
{FILTER_LABELS[value]} {FILTER_LABELS[value]}
</button>))} </button>))}
</div>) </div>)
@@ -137,10 +132,10 @@ const MaterialTreeNode: FC<{
}, [data, onChildren, open, tag.children.length, tag.id]) }, [data, onChildren, open, tag.children.length, tag.id])
return ( return (
<> <Fragment>
<li> <li>
<div className="flex flex-center"> <div className="flex">
<div className="flex-none w-4 my-auto"> <div className="flex-none w-4">
{tag.hasChildren && ( {tag.hasChildren && (
<button <button
type="button" type="button"
@@ -149,9 +144,8 @@ const MaterialTreeNode: FC<{
{open ? <>&minus;</> : '+'} {open ? <>&minus;</> : '+'}
</button>)} </button>)}
</div> </div>
<div className="min-w-0 flex-1 my-auto"> <div className="flex-1 truncate">
<div className={cn (tagSelectionShellClass (selectedTagId === tag.id), <div className={tagSelectionShellClass (selectedTagId === tag.id)}>
'min-w-0 truncate')}>
<TagLink <TagLink
tag={sidebarTagToTag (tag)} tag={sidebarTagToTag (tag)}
nestLevel={nestLevel} nestLevel={nestLevel}
@@ -176,39 +170,21 @@ const MaterialTreeNode: FC<{
setOpenTags={setOpenTags} setOpenTags={setOpenTags}
onChildren={onChildren}/>))} onChildren={onChildren}/>))}
</ul>)} </ul>)}
</>) </Fragment>)
} }
const MobileMaterialTreeNode: FC<{ depth?: number const MobileMaterialTreeNode: FC<{
availableInlineSizePx?: number | null depth?: number
materialFilter: MaterialFilter materialFilter: MaterialFilter
selectedTagId: number | null selectedTagId: number | null
onChildren: (tagId: number, children: MaterialSidebarTag[]) => onChildren: (tagId: number, children: MaterialSidebarTag[]) => void
void
openTags: Record<number, boolean> openTags: Record<number, boolean>
setOpenTags: Dispatch<SetStateAction<Record<number, boolean>>> setOpenTags: Dispatch<SetStateAction<Record<number, boolean>>>
tag: MaterialSidebarTag }> = ( tag: MaterialSidebarTag
{ }> = ({ depth = 0, materialFilter, onChildren, openTags, selectedTagId,
depth = 0, setOpenTags, tag }) => {
availableInlineSizePx = null,
materialFilter,
onChildren,
openTags,
selectedTagId,
setOpenTags,
tag,
},
) => {
const open = Boolean (openTags[tag.id]) const open = Boolean (openTags[tag.id])
const tagColumnRef = useRef<HTMLDivElement | null> (null)
const chipRef = useRef<HTMLDivElement | null> (null)
const buttonRef = useRef<HTMLButtonElement | null> (null)
const expansionSlotRef = useRef<HTMLDivElement | null> (null)
const expansionBorderRef = useRef<HTMLDivElement | null> (null)
const [tagChipInlineSizePx, setTagChipInlineSizePx] = useState<number | null> (null)
const [tagLinkInlineSizePx, setTagLinkInlineSizePx] = useState<number | null> (null)
const [childAvailableInlineSizePx, setChildAvailableInlineSizePx] = useState<number | null> (null)
const { data } = useQuery ({ const { data } = useQuery ({
queryKey: materialsKeys.tree ({ parentId: tag.id, materialFilter }), queryKey: materialsKeys.tree ({ parentId: tag.id, materialFilter }),
queryFn: () => fetchMaterialTagTree ({ parentId: tag.id, materialFilter }), queryFn: () => fetchMaterialTagTree ({ parentId: tag.id, materialFilter }),
@@ -219,155 +195,50 @@ const MobileMaterialTreeNode: FC<{ depth?: number
onChildren (tag.id, data) onChildren (tag.id, data)
}, [data, onChildren, open, tag.children.length, tag.id]) }, [data, onChildren, open, tag.children.length, tag.id])
useEffect (() => {
const tagColumn = tagColumnRef.current
const chip = chipRef.current
if (!(tagColumn) || !(chip))
return
const updateTagInlineSize = () => {
const buttonHeight = buttonRef.current?.offsetHeight ?? 0
const gap = tag.hasChildren ? px (window.getComputedStyle (tagColumn).rowGap) : 0
const columnHeight =
availableInlineSizePx == null
? tagColumn.clientHeight
: Math.min (tagColumn.clientHeight, availableInlineSizePx)
const nextChipInlineSize = Math.max (24, columnHeight - buttonHeight - gap)
const nextLinkInlineSize = Math.max (
16,
nextChipInlineSize - verticalChrome (chip),
)
setTagChipInlineSizePx (prev => prev === nextChipInlineSize ? prev : nextChipInlineSize)
setTagLinkInlineSizePx (prev => prev === nextLinkInlineSize ? prev : nextLinkInlineSize)
}
updateTagInlineSize ()
const resizeObserver = new ResizeObserver (() => {
updateTagInlineSize ()
})
resizeObserver.observe (tagColumn)
resizeObserver.observe (chip)
if (buttonRef.current)
resizeObserver.observe (buttonRef.current)
return () => {
resizeObserver.disconnect ()
}
}, [availableInlineSizePx, open, tag.hasChildren, tag.children.length])
useEffect (() => {
const expansionSlot = expansionSlotRef.current
const expansionBorder = expansionBorderRef.current
if (!(expansionSlot) || !(expansionBorder))
return
const updateChildInlineSize = () => {
const base =
availableInlineSizePx == null
? expansionSlot.clientHeight
: availableInlineSizePx
const chrome = verticalChrome (expansionSlot) + verticalChrome (expansionBorder)
const nextInlineSize = Math.max (24, base - chrome)
setChildAvailableInlineSizePx (prev => prev === nextInlineSize ? prev : nextInlineSize)
}
updateChildInlineSize ()
const resizeObserver = new ResizeObserver (() => {
updateChildInlineSize ()
})
resizeObserver.observe (expansionSlot)
resizeObserver.observe (expansionBorder)
return () => {
resizeObserver.disconnect ()
}
}, [availableInlineSizePx, open, tag.children.length])
return ( return (
<div className="flex h-full min-h-0 max-h-full flex-row-reverse items-start gap-2 <div className="flex flex-row-reverse items-start gap-2">
overflow-hidden"> <div className="flex flex-col items-center gap-1">
<div <div
ref={tagColumnRef} className={`${ tagSelectionShellClass (selectedTagId === tag.id) } rounded-xl
className="flex h-full min-h-0 max-h-full flex-col items-center gap-1 border px-3 py-2 text-sm shadow-sm`}
overflow-hidden"> style={{ writingMode: 'vertical-rl' }}>
<div
ref={chipRef}
className={cn (
tagSelectionShellClass (selectedTagId === tag.id),
'box-border rounded-xl border px-3 py-2 text-sm shadow-sm',
'min-h-0 overflow-hidden [max-inline-size:var(--tag-chip-inline-size)]',
'[max-height:var(--tag-chip-inline-size)]',
)}
style={{
writingMode: 'vertical-rl',
'--tag-chip-inline-size': (
tagChipInlineSizePx == null
? undefined
: `${ tagChipInlineSizePx }px`),
'--tag-link-inline-size': (
tagLinkInlineSizePx == null
? undefined
: `${ tagLinkInlineSizePx }px`),
} as CSSProperties}>
<TagLink <TagLink
tag={sidebarTagToTag (tag)} tag={sidebarTagToTag (tag)}
title={tag.name} title={tag.name}
withCount={false} withCount={false}
withWiki={false} withWiki={false}
to={materialPath (tag.id, materialFilter)} to={materialPath (tag.id, materialFilter)}/>
className="block overflow-hidden text-ellipsis whitespace-nowrap
[max-inline-size:var(--tag-link-inline-size)]
[max-height:var(--tag-link-inline-size)]"/>
</div> </div>
{tag.hasChildren && ( {tag.hasChildren && (
<button <button
ref={buttonRef}
type="button" type="button"
onClick={() => setOpenTags (prev => ({ ...prev, [tag.id]: !prev[tag.id] }))} onClick={() => setOpenTags (prev => ({ ...prev, [tag.id]: !prev[tag.id] }))}
className="flex-none rounded-full border border-stone-300 bg-white className="rounded-full border border-stone-300 bg-white px-2 py-0.5
px-2 py-0.5 text-sm text-stone-700 dark:border-stone-700 text-sm text-stone-700 dark:border-stone-700
dark:bg-stone-900 dark:text-stone-100"> dark:bg-stone-900 dark:text-stone-100">
{open ? <>&minus;</> : '+'} {open ? <>&minus;</> : '+'}
</button>)} </button>)}
</div> </div>
{open && tag.children.length > 0 && ( {open && tag.children.length > 0 && (
<div <div
ref={expansionSlotRef} className="relative flex flex-row-reverse items-start gap-2 rounded-2xl border
className={cn ( border-stone-200 bg-stone-100/70 py-2 pl-2 pr-2 text-stone-900
'h-full min-h-0 max-h-full overflow-hidden box-border', dark:border-stone-700 dark:bg-stone-900/70 dark:text-stone-100"
depth === 0 ? 'pt-5' : 'pt-3')}> style={{ marginTop: `${ depth === 0 ? 1.25 : .75 }rem` }}>
<div
ref={expansionBorderRef}
className="relative max-h-full overflow-hidden rounded-2xl border border-stone-200
bg-stone-100/70 py-2 pl-2 pr-2 text-stone-900
dark:border-stone-700 dark:bg-stone-900/70 dark:text-stone-100">
<div className="flex h-full min-h-0 max-h-full flex-row-reverse items-start gap-2
overflow-hidden">
<span <span
aria-hidden="true" aria-hidden="true"
className="absolute -right-3 top-4 h-px w-3 bg-stone-300 dark:bg-stone-600"/> className="absolute -right-3 top-4 h-px w-3 bg-stone-300 dark:bg-stone-600"/>
{tag.children.map (child => ( {tag.children.map (child => (
<div <div key={child.id} className="relative">
key={child.id}
className="relative h-full min-h-0 max-h-full overflow-hidden">
<MobileMaterialTreeNode <MobileMaterialTreeNode
tag={child} tag={child}
depth={depth + 1} depth={depth + 1}
availableInlineSizePx={childAvailableInlineSizePx}
materialFilter={materialFilter} materialFilter={materialFilter}
selectedTagId={selectedTagId} selectedTagId={selectedTagId}
openTags={openTags} openTags={openTags}
setOpenTags={setOpenTags} setOpenTags={setOpenTags}
onChildren={onChildren}/> onChildren={onChildren}/>
</div>))} </div>))}
</div>
</div>
</div>)} </div>)}
</div>) </div>)
} }
@@ -377,14 +248,12 @@ const MaterialSidebar: FC = () => {
const location = useLocation () const location = useLocation ()
const navigate = useNavigate () const navigate = useNavigate ()
const qs = new URLSearchParams (location.search) const qs = new URLSearchParams (location.search)
const materialFilter = parseMaterialFilter (qs.get ('material_filter'), 'any') const materialFilter = parseMaterialFilter (qs.get ('material_filter'), 'present')
const selectedTagId = Number (qs.get ('tag_id') ?? 0) || null const selectedTagId = Number (qs.get ('tag_id') ?? 0) || null
const [desktopTags, setDesktopTags] = useState<MaterialSidebarTag[]> ([]) const [desktopTags, setDesktopTags] = useState<MaterialSidebarTag[]> ([])
const [openTags, setOpenTags] = useState<Record<number, boolean>> ({ }) const [openTags, setOpenTags] = useState<Record<number, boolean>> ({ })
const mobileRailRef = useRef<HTMLDivElement | null> (null) const mobileRailRef = useRef<HTMLDivElement | null> (null)
const [mobileAvailableInlineSizePx, setMobileAvailableInlineSizePx] =
useState<number | null> (null)
const { data: rootTags = [], isLoading, isError } = useQuery ({ const { data: rootTags = [], isLoading, isError } = useQuery ({
queryKey: materialsKeys.tree ({ parentId: null, materialFilter }), queryKey: materialsKeys.tree ({ parentId: null, materialFilter }),
@@ -404,29 +273,6 @@ const MaterialSidebar: FC = () => {
}) })
}, [rootTags, materialFilter]) }, [rootTags, materialFilter])
useEffect (() => {
const el = mobileRailRef.current
if (!(el))
return
const updateAvailableInlineSize = () => {
const nextInlineSize = Math.max (24, el.clientHeight)
setMobileAvailableInlineSizePx (prev => prev === nextInlineSize ? prev : nextInlineSize)
}
updateAvailableInlineSize ()
const resizeObserver = new ResizeObserver (() => {
updateAvailableInlineSize ()
})
resizeObserver.observe (el)
return () => {
resizeObserver.disconnect ()
}
}, [rootTags, materialFilter])
const visibleRootTags = desktopTags.length > 0 ? desktopTags : rootTags const visibleRootTags = desktopTags.length > 0 ? desktopTags : rootTags
const setChildren = (tagId: number, children: MaterialSidebarTag[]) => { const setChildren = (tagId: number, children: MaterialSidebarTag[]) => {
@@ -442,6 +288,8 @@ const MaterialSidebar: FC = () => {
updateMaterialFilterQuery (location.pathname, location.search, navigate, value) updateMaterialFilterQuery (location.pathname, location.search, navigate, value)
} }
const clearTagSelection = clearTagSelectionPath (location.search, materialFilter)
const renderDesktopTree = (tags: MaterialSidebarTag[]): ReactNode => ( const renderDesktopTree = (tags: MaterialSidebarTag[]): ReactNode => (
tags.map (tag => ( tags.map (tag => (
<MaterialTreeNode <MaterialTreeNode
@@ -456,21 +304,24 @@ const MaterialSidebar: FC = () => {
return ( return (
<> <>
<div className="border-b bg-stone-50 p-3 dark:border-stone-700 dark:bg-stone-950 <div className="border-b bg-stone-50 p-3 dark:border-stone-700 dark:bg-stone-950
dark:text-stone-100 md:hidden flex h-[25dvh] min-h-0 flex-col dark:text-stone-100 md:hidden">
overflow-hidden"> <div className="mb-3">
<PrefetchLink
to={clearTagSelection}
className="text-sm text-sky-700 underline underline-offset-2
dark:text-sky-300">
{selectedTagId != null ? '選択解除' : '全素材'}
</PrefetchLink>
</div>
<MaterialFilterButtons <MaterialFilterButtons
materialFilter={materialFilter} materialFilter={materialFilter}
onChange={handleFilterChange}/> onChange={handleFilterChange}/>
<div <div ref={mobileRailRef} className="mt-3 overflow-x-auto">
ref={mobileRailRef} <div className="flex min-w-max flex-row-reverse gap-3 pb-1">
className="mt-3 min-h-0 flex-1 overflow-x-auto overflow-y-hidden">
<div className="flex min-w-max flex-row-reverse items-start gap-3 pb-1 h-full
min-h-0 max-h-full">
{visibleRootTags.map (tag => ( {visibleRootTags.map (tag => (
<MobileMaterialTreeNode <MobileMaterialTreeNode
key={tag.id} key={tag.id}
tag={tag} tag={tag}
availableInlineSizePx={mobileAvailableInlineSizePx}
materialFilter={materialFilter} materialFilter={materialFilter}
selectedTagId={selectedTagId} selectedTagId={selectedTagId}
openTags={openTags} openTags={openTags}
@@ -483,6 +334,12 @@ const MaterialSidebar: FC = () => {
<div className="hidden md:block"> <div className="hidden md:block">
<SidebarComponent> <SidebarComponent>
<div className="space-y-4"> <div className="space-y-4">
<PrefetchLink
to={clearTagSelection}
className="text-sm text-sky-700 underline underline-offset-2
dark:text-sky-300">
{selectedTagId != null ? '選択解除' : '全素材'}
</PrefetchLink>
<MaterialFilterButtons <MaterialFilterButtons
materialFilter={materialFilter} materialFilter={materialFilter}
onChange={handleFilterChange}/> onChange={handleFilterChange}/>
+3 -4
ファイルの表示
@@ -32,7 +32,6 @@ const TagLink: FC<Props> = ({ tag,
linkFlg = true, linkFlg = true,
withWiki = true, withWiki = true,
withCount = true, withCount = true,
className,
...props }) => { ...props }) => {
const spanClass = cn ( const spanClass = cn (
`text-${ TAG_COLOUR[tag.category] }-${ LIGHT_COLOUR_SHADE }`, `text-${ TAG_COLOUR[tag.category] }-${ LIGHT_COLOUR_SHADE }`,
@@ -106,7 +105,7 @@ const TagLink: FC<Props> = ({ tag,
</span>)} </span>)}
{tag.matchedAlias != null && ( {tag.matchedAlias != null && (
<> <>
<span className={cn (spanClass, className)} {...props}> <span className={spanClass} {...props}>
{tag.matchedAlias} {tag.matchedAlias}
</span> </span>
<> </> <> </>
@@ -115,12 +114,12 @@ const TagLink: FC<Props> = ({ tag,
? ( ? (
<PrefetchLink <PrefetchLink
to={`/posts?${ (new URLSearchParams ({ tags: tag.name })).toString () }`} to={`/posts?${ (new URLSearchParams ({ tags: tag.name })).toString () }`}
className={cn (linkClass, className)} className={linkClass}
{...props}> {...props}>
{tag.name} {tag.name}
</PrefetchLink>) </PrefetchLink>)
: ( : (
<span className={cn (spanClass, className)} <span className={spanClass}
{...props}> {...props}>
{tag.name} {tag.name}
</span>)} </span>)}
+11 -31
ファイルの表示
@@ -7,36 +7,30 @@ import Separator from '@/components/MenuSeparator'
import PrefetchLink from '@/components/PrefetchLink' import PrefetchLink from '@/components/PrefetchLink'
import TopNavUser from '@/components/TopNavUser' import TopNavUser from '@/components/TopNavUser'
import { WikiIdBus } from '@/lib/eventBus/WikiIdBus' import { WikiIdBus } from '@/lib/eventBus/WikiIdBus'
import { materialsKeys, tagsKeys, wikiKeys } from '@/lib/queryKeys' import { tagsKeys, wikiKeys } from '@/lib/queryKeys'
import { fetchTag, fetchTagByName } from '@/lib/tags' import { fetchTag, fetchTagByName } from '@/lib/tags'
import { fetchMaterial } from '@/lib/materials'
import { cn } from '@/lib/utils' import { cn } from '@/lib/utils'
import { fetchWikiPage } from '@/lib/wiki' import { fetchWikiPage } from '@/lib/wiki'
import type { FC, MouseEvent } from 'react' import type { FC, MouseEvent } from 'react'
import type { Material, Menu, MenuVisibleItem, Tag, User } from '@/types' import type { Menu, MenuVisibleItem, Tag, User } from '@/types'
type Props = { user: User | null } type Props = { user: User | null }
export const menuOutline = ( export const menuOutline = ({ tag, wikiId, user, pathName }: {
{ tag, material, wikiId, user, pathName }: {
tag?: Tag | null tag?: Tag | null
material?: Material | null
wikiId: number | null wikiId: number | null
user: User | null, user: User | null,
pathName: string }, pathName: string }): Menu => {
): Menu => { const postCount = tag?.postCount ?? 0
const postCount = tag?.postCount ?? material?.tag?.postCount ?? 0
const wikiPageFlg = Boolean (/^\/wiki\/(?!new|changes)[^/]+/.test (pathName) && wikiId) const wikiPageFlg = Boolean (/^\/wiki\/(?!new|changes)[^/]+/.test (pathName) && wikiId)
const wikiTitle = pathName.split ('/')[2] ?? '' const wikiTitle = pathName.split ('/')[2] ?? ''
const tagFlg = /^\/tags\/\d+/.test (pathName) const tagFlg = /^\/tags\/\d+/.test (pathName)
const materialFlg = /^\/materials\/\d+/.test (pathName)
return [ return [
{ name: '広場', to: '/posts', subMenu: [ { name: '広場', to: '/posts', subMenu: [
{ name: '一覧', to: '/posts' }, { name: '一覧', to: '/posts' },
@@ -55,18 +49,12 @@ export const menuOutline = (
visible: tagFlg }, visible: tagFlg },
{ name: '履歴', to: `/tags/changes?id=${ tag?.id }`, { name: '履歴', to: `/tags/changes?id=${ tag?.id }`,
visible: tagFlg && tag?.category !== 'nico' }] }, visible: tagFlg && tag?.category !== 'nico' }] },
{ name: '素材', to: '/materials', visible: true, subMenu: [ { name: '素材', to: '/materials', visible: false, subMenu: [
{ name: '一覧', to: '/materials' }, { name: '一覧', to: '/materials' },
{ name: '検索', to: '/materials/search', visible: false },
{ name: '追加', to: '/materials/new' }, { name: '追加', to: '/materials/new' },
{ name: '抑止', to: '/materials/suppressions' }, { name: '全体履歴', to: '/materials/changes', visible: false },
{ name: '全体履歴', to: '/materials/changes' }, { name: 'ヘルプ', to: '/wiki/ヘルプ:素材集' }] },
{ name: 'ヘルプ', to: '/wiki/ヘルプ:素材管理' },
{ component: <Separator/>, visible: materialFlg },
{ name: `広場 (${ postCount || 0 })`,
to: `/posts?tags=${ encodeURIComponent (material?.tag?.name ?? '') }`,
visible: materialFlg && Boolean (material?.tag) },
{ name: '履歴', to: `/materials/changes?material_id=${ material?.id }`,
visible: materialFlg }] },
{ name: 'Wiki', to: '/wiki/ヘルプ:ホーム', base: '/wiki', subMenu: [ { name: 'Wiki', to: '/wiki/ヘルプ:ホーム', base: '/wiki', subMenu: [
{ name: '検索', to: '/wiki' }, { name: '検索', to: '/wiki' },
{ name: '新規', to: '/wiki/new' }, { name: '新規', to: '/wiki/new' },
@@ -131,23 +119,15 @@ const TopNav: FC<Props> = ({ user }) => {
queryFn: () => fetchWikiPage (wikiIdStr, { }) }) queryFn: () => fetchWikiPage (wikiIdStr, { }) })
const tagFlg = /^\/tags\/\d+/.test (location.pathname) const tagFlg = /^\/tags\/\d+/.test (location.pathname)
const materialFlg = /^\/materials\/\d+/.test (location.pathname) const effectiveTitle = (tagFlg ? location.pathname.split ('/')[2] : wikiPage?.title) ?? ''
const effectiveTitle = (((tagFlg || materialFlg)
? location.pathname.split ('/')[2]
: wikiPage?.title)
?? '')
const { data: tag } = useQuery ({ const { data: tag } = useQuery ({
enabled: Boolean (effectiveTitle), enabled: Boolean (effectiveTitle),
queryKey: tagsKeys.show (effectiveTitle), queryKey: tagsKeys.show (effectiveTitle),
queryFn: () => (tagFlg ? fetchTag : fetchTagByName) (effectiveTitle) }) queryFn: () => (tagFlg ? fetchTag : fetchTagByName) (effectiveTitle) })
const { data: material } = useQuery ({
enabled: Boolean (effectiveTitle),
queryKey: materialsKeys.show (effectiveTitle),
queryFn: () => fetchMaterial (effectiveTitle) })
const menu = menuOutline ({ tag, material, wikiId, user, pathName: location.pathname }) const menu = menuOutline ({ tag, wikiId, user, pathName: location.pathname })
const visibleMenu = menu.filter ((item): item is MenuVisibleItem => item.visible ?? true) const visibleMenu = menu.filter ((item): item is MenuVisibleItem => item.visible ?? true)
const moreMenu = menu.filter (item => const moreMenu = menu.filter (item =>
!(item.visible ?? true) !(item.visible ?? true)
+3 -5
ファイルの表示
@@ -1,14 +1,12 @@
import React from 'react' import React from 'react'
import { cn } from '@/lib/utils'
import type { FC } from 'react' import type { FC } from 'react'
type Props = { children: React.ReactNode; className?: string } type Props = { children: React.ReactNode }
const PageTitle: FC<Props> = ({ children, className, ...rest }) => ( const PageTitle: FC<Props> = ({ children }) => (
<h1 className={cn ('text-2xl font-bold mb-2', className)} {...rest}> <h1 className="text-2xl font-bold mb-2">
{children} {children}
</h1>) </h1>)
+19 -10
ファイルの表示
@@ -1,31 +1,41 @@
import { apiGet, isApiError, apiPost, apiPut } from '@/lib/api' import {
apiGet,
isApiError,
apiPost,
apiPut,
} from '@/lib/api'
import type { Material, import type {
Material,
MaterialIndexResponse, MaterialIndexResponse,
MaterialVersion, MaterialVersion,
FetchMaterialsParams, FetchMaterialsParams,
MaterialFilter, MaterialFilter,
MaterialSyncSuppression, MaterialSyncSuppression,
MaterialSidebarTag, MaterialSidebarTag,
MaterialTagTree } from '@/types' MaterialTagTree,
} from '@/types'
export type FetchMaterialTreeParams = { export type FetchMaterialTreeParams = {
parentId?: number | null parentId?: number | null
materialFilter: MaterialFilter } materialFilter: MaterialFilter
}
export type MaterialSyncSuppressionResponse = { suppressions: MaterialSyncSuppression[] } export type MaterialSyncSuppressionResponse = {
suppressions: MaterialSyncSuppression[]
}
export type MaterialChangesResponse = { export type MaterialChangesResponse = {
versions: MaterialVersion[] versions: MaterialVersion[]
count: number } count: number
}
const MATERIAL_FILTERS: MaterialFilter[] = ['present', 'missing', 'any'] const MATERIAL_FILTERS: MaterialFilter[] = ['present', 'missing', 'any']
export const parseMaterialFilter = ( export const parseMaterialFilter = (
value: unknown, value: unknown,
fallback: MaterialFilter = 'present', fallback: MaterialFilter = 'present'): MaterialFilter =>
): MaterialFilter =>
typeof value === 'string' && MATERIAL_FILTERS.includes (value as MaterialFilter) typeof value === 'string' && MATERIAL_FILTERS.includes (value as MaterialFilter)
? value as MaterialFilter ? value as MaterialFilter
: fallback : fallback
@@ -35,8 +45,7 @@ export const fetchMaterials = async (
{ q, tagState, mediaKind, createdFrom, createdTo, { q, tagState, mediaKind, createdFrom, createdTo,
updatedFrom, updatedTo, sort, direction, page, updatedFrom, updatedTo, sort, direction, page,
tagId, includeDescendants, groupBy, tagId, includeDescendants, groupBy,
limit }: FetchMaterialsParams, limit }: FetchMaterialsParams): Promise<MaterialIndexResponse> =>
): Promise<MaterialIndexResponse> =>
await apiGet ('/materials', { params: { await apiGet ('/materials', { params: {
...(q && { q }), ...(q && { q }),
tag_state: tagState, tag_state: tagState,
+15 -3
ファイルの表示
@@ -8,6 +8,7 @@ import WikiBody from '@/components/WikiBody'
import FieldError from '@/components/common/FieldError' import FieldError from '@/components/common/FieldError'
import FormField from '@/components/common/FormField' import FormField from '@/components/common/FormField'
import PageTitle from '@/components/common/PageTitle' import PageTitle from '@/components/common/PageTitle'
import PrefetchLink from '@/components/PrefetchLink'
import TabGroup, { Tab } from '@/components/common/TabGroup' import TabGroup, { Tab } from '@/components/common/TabGroup'
import TagInput from '@/components/common/TagInput' import TagInput from '@/components/common/TagInput'
import MainArea from '@/components/layout/MainArea' import MainArea from '@/components/layout/MainArea'
@@ -118,6 +119,12 @@ const MaterialDetailPage: FC = () => {
: materialTitle} : materialTitle}
</PageTitle> </PageTitle>
<PrefetchLink
to={`/materials/changes?material_id=${ material.id }`}
className="text-sm text-sky-700 underline underline-offset-2 dark:text-sky-300">
</PrefetchLink>
{(material.file && material.contentType) && ( {(material.file && material.contentType) && (
(/image\/.*/.test (material.contentType) && ( (/image\/.*/.test (material.contentType) && (
<img src={material.file} alt={material.tag?.name || undefined}/>)) <img src={material.file} alt={material.tag?.name || undefined}/>))
@@ -127,12 +134,17 @@ const MaterialDetailPage: FC = () => {
<audio src={material.file} controls/>)))} <audio src={material.file} controls/>)))}
<TabGroup> <TabGroup>
{material.tag && (
<Tab name="Wiki"> <Tab name="Wiki">
{material.tag
? (
<WikiBody <WikiBody
title={material.tag.name} title={material.tag.name}
body={material.wikiPageBody ?? undefined}/> body={material.wikiPageBody ?? undefined}/>)
</Tab>)} : (
<p className="text-stone-700 dark:text-stone-300">
</p>)}
</Tab>
<Tab name="編輯"> <Tab name="編輯">
<div className="max-w-wl space-y-4 pt-2"> <div className="max-w-wl space-y-4 pt-2">
+24
ファイルの表示
@@ -80,7 +80,14 @@ const MaterialHistoryPage: FC = () => {
</Helmet> </Helmet>
<div className="space-y-5"> <div className="space-y-5">
<div className="flex flex-wrap items-center justify-between gap-3">
<PageTitle></PageTitle> <PageTitle></PageTitle>
<PrefetchLink
to="/materials"
className="text-sm text-sky-700 underline underline-offset-2 dark:text-sky-300">
</PrefetchLink>
</div>
<form <form
onSubmit={handleSearch} onSubmit={handleSearch}
@@ -105,6 +112,20 @@ const MaterialHistoryPage: FC = () => {
onChange={e => setTagInput (e.target.value)} onChange={e => setTagInput (e.target.value)}
className={inputClass (invalid)}/>)} className={inputClass (invalid)}/>)}
</FormField> </FormField>
<FormField label="イベント">
{({ invalid }) => (
<select
value={eventTypeInput}
onChange={e => setEventTypeInput (e.target.value)}
className={inputClass (invalid)}>
<option value=""></option>
<option value="create">create</option>
<option value="update">update</option>
<option value="discard">discard</option>
<option value="restore">restore</option>
</select>)}
</FormField>
</div> </div>
<button <button
@@ -129,6 +150,7 @@ const MaterialHistoryPage: FC = () => {
<table className="w-full min-w-[1200px] table-fixed border-collapse"> <table className="w-full min-w-[1200px] table-fixed border-collapse">
<colgroup> <colgroup>
<col className="w-48"/> <col className="w-48"/>
<col className="w-32"/>
<col className="w-28"/> <col className="w-28"/>
<col className="w-24"/> <col className="w-24"/>
<col className="w-64"/> <col className="w-64"/>
@@ -141,6 +163,7 @@ const MaterialHistoryPage: FC = () => {
<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"></th>
<th className="p-2 text-left">event_type</th>
<th className="p-2 text-left"> ID</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"></th>
@@ -157,6 +180,7 @@ const MaterialHistoryPage: FC = () => {
key={version.id} key={version.id}
className="even:bg-gray-100 dark:even:bg-gray-700"> className="even:bg-gray-100 dark:even:bg-gray-700">
<td className="p-2">{dateString (version.createdAt)}</td> <td className="p-2">{dateString (version.createdAt)}</td>
<td className="p-2">{version.eventType}</td>
<td className="p-2"> <td className="p-2">
<PrefetchLink to={`/materials/${ version.materialId }`}> <PrefetchLink to={`/materials/${ version.materialId }`}>
#{version.materialId} #{version.materialId}
+18 -3
ファイルの表示
@@ -33,7 +33,15 @@ describe ('MaterialListPage', () => {
} }, } },
) )
}) })
expect (await screen.findByText ('素材はありません')).toBeInTheDocument () expect (await screen.findByText ('素材はありません')).toBeInTheDocument ()
expect (screen.getByRole ('link', { name: '新規素材を追加' })).toHaveAttribute (
'href',
'/materials/new',
)
expect (screen.getByRole ('link', { name: '履歴' })).toHaveAttribute (
'href',
'/materials/changes',
)
}) })
it ('shows materials in the default card view', async () => { it ('shows materials in the default card view', async () => {
@@ -151,9 +159,16 @@ describe ('MaterialListPage', () => {
(_, element) => element?.textContent === '伊地知ニジカ 配下の素材を表示中', (_, element) => element?.textContent === '伊地知ニジカ 配下の素材を表示中',
)).toBeInTheDocument () )).toBeInTheDocument ()
expect (screen.getByRole ('link', { name: '泣き' })).toHaveAttribute ( const addLinks = screen.getAllByRole ('link', { name: 'このタグに素材を追加' })
expect (addLinks[0]).toHaveAttribute (
'href', 'href',
'/materials?tag_id=30&include_descendants=1&group_by=parent_tag&material_filter=present', '/materials/new?tag=%E4%BC%8A%E5%9C%B0%E7%9F%A5%E3%83%8B%E3%82%B8%E3%82%AB'
+ '&return_to=%2Fmaterials%3Ftag_id%3D20%26include_descendants%3D1%26group_by%3Dparent_tag',
)
expect (addLinks[1]).toHaveAttribute (
'href',
'/materials/new?tag=%E6%B3%A3%E3%81%8D'
+ '&return_to=%2Fmaterials%3Ftag_id%3D20%26include_descendants%3D1%26group_by%3Dparent_tag',
) )
expect (screen.getByRole ('link', { name: 'タグ選択を解除' })).toHaveAttribute ( expect (screen.getByRole ('link', { name: 'タグ選択を解除' })).toHaveAttribute (
'href', 'href',
+77 -39
ファイルの表示
@@ -10,14 +10,15 @@ import FormField from '@/components/common/FormField'
import PageTitle from '@/components/common/PageTitle' import PageTitle from '@/components/common/PageTitle'
import Pagination from '@/components/common/Pagination' import Pagination from '@/components/common/Pagination'
import MainArea from '@/components/layout/MainArea' import MainArea from '@/components/layout/MainArea'
import { SITE_TITLE } from '@/config' import { API_BASE_URL, SITE_TITLE } from '@/config'
import { fetchMaterials, parseMaterialFilter } from '@/lib/materials' import { fetchMaterials, parseMaterialFilter } from '@/lib/materials'
import { materialsKeys } from '@/lib/queryKeys' import { materialsKeys } from '@/lib/queryKeys'
import { dateString, inputClass } from '@/lib/utils' import { dateString, inputClass } from '@/lib/utils'
import type { FC, FormEvent } from 'react' import type { FC, FormEvent } from 'react'
import type { FetchMaterialsParams, import type {
FetchMaterialsParams,
Material, Material,
MaterialFilter, MaterialFilter,
MaterialIndexGroup, MaterialIndexGroup,
@@ -41,16 +42,20 @@ const MEDIA_FILTER_LABELS: Record<MaterialIndexMediaKind, string> = {
video: '動画', video: '動画',
audio: '音声', audio: '音声',
file_other: 'その他ファイル', file_other: 'その他ファイル',
url_only: '外部リンクのみ'} url_only: 'URL のみ'}
const SORT_LABELS: Record<MaterialIndexSort, string> = { const SORT_LABELS: Record<MaterialIndexSort, string> = {
created_at: '作成日時', created_at: '作成日時',
updated_at: '更新日時', updated_at: '更新日時',
tag_name: 'タグ名', tag_name: 'タグ名',
media_kind: '種類', media_kind: '種類',
file_byte_size: '容量', file_byte_size: 'ファイルサイズ',
version_no: '', version_no: 'バージョン',
id: 'Id.'} id: 'ID'}
const GROUP_BY_LABELS: Record<MaterialIndexGroupBy, string> = {
none: 'オフ',
parent_tag: '親タグ'}
const setIf = (qs: URLSearchParams, key: string, value: string | null) => { const setIf = (qs: URLSearchParams, key: string, value: string | null) => {
@@ -83,24 +88,21 @@ const materialTitle = (material: Material): string =>
const groupedTagPath = ( const groupedTagPath = (
tagId: number, tagId: number,
materialFilter: MaterialFilter, materialFilter: MaterialFilter): string =>
): string =>
`/materials?tag_id=${ tagId }&include_descendants=1&group_by=parent_tag` `/materials?tag_id=${ tagId }&include_descendants=1&group_by=parent_tag`
+ `&material_filter=${ materialFilter }` + `&material_filter=${ materialFilter }`
const materialNewPath = ( const materialNewPath = (
tagName: string, tagName: string,
returnTo: string, returnTo: string): string =>
): string =>
`/materials/new?tag=${ encodeURIComponent (tagName) }` `/materials/new?tag=${ encodeURIComponent (tagName) }`
+ `&return_to=${ encodeURIComponent (returnTo) }` + `&return_to=${ encodeURIComponent (returnTo) }`
const clearedTagSelectionPath = ( const clearedTagSelectionPath = (
locationSearch: string, locationSearch: string,
materialFilter: MaterialFilter, materialFilter: MaterialFilter): string => {
): string => {
const qs = new URLSearchParams (locationSearch) const qs = new URLSearchParams (locationSearch)
qs.delete ('tag_id') qs.delete ('tag_id')
qs.delete ('include_descendants') qs.delete ('include_descendants')
@@ -118,7 +120,7 @@ const MaterialThumb: FC<{ material: Material }> = ({ material }) => (
text-stone-900 shadow-sm dark:border-stone-700 dark:bg-stone-900 text-stone-900 shadow-sm dark:border-stone-700 dark:bg-stone-900
dark:text-stone-100`}> dark:text-stone-100`}>
{material.thumbnail {material.thumbnail
? <img src={material.thumbnail} alt="" className="block h-full w-full object-cover"/> ? <img src={material.thumbnail} alt="" className="h-full w-full object-contain"/>
: ( : (
<span <span
className="px-2 text-2xl leading-tight" className="px-2 text-2xl leading-tight"
@@ -189,22 +191,27 @@ const MaterialListItem: FC<{ material: Material }> = ({ material }) => (
const GroupHeading: FC<{ const GroupHeading: FC<{
count: number count: number
materialFilter: MaterialFilter materialFilter: MaterialFilter
returnTo: string
title: string title: string
tagId: number tagId: number
}> = ({ count, materialFilter, title, tagId }) => ( }> = ({ count, materialFilter, returnTo, title, tagId }) => (
<div className="flex items-center gap-2 border-b border-stone-200 pb-2 <div className="flex flex-wrap items-center gap-2 border-b border-stone-200 pb-2
dark:border-stone-700"> dark:border-stone-700">
<PrefetchLink <PrefetchLink
to={groupedTagPath (tagId, materialFilter)} to={groupedTagPath (tagId, materialFilter)}
className="font-medium text-sky-700 underline underline-offset-2 className="font-medium text-sky-700 underline underline-offset-2
dark:text-sky-300 w-full"> dark:text-sky-300">
{title} {title}
</PrefetchLink> </PrefetchLink>
<div className="text-right w-auto"> <span className="text-sm text-stone-600 dark:text-stone-300">
<span className="text-nowrap text-sm text-stone-600 dark:text-stone-300">
{count} {count}
</span> </span>
</div> <PrefetchLink
to={materialNewPath (title, returnTo)}
className="text-sm text-sky-700 underline underline-offset-2
dark:text-sky-300">
</PrefetchLink>
</div>) </div>)
@@ -376,7 +383,8 @@ const MaterialListPage: FC = () => {
tagId={group.tag.id} tagId={group.tag.id}
title={group.tag.name} title={group.tag.name}
count={group.count} count={group.count}
materialFilter={materialFilter}/> materialFilter={materialFilter}
returnTo={location.pathname + location.search}/>
{renderMaterialCollection (groupMaterials)} {renderMaterialCollection (groupMaterials)}
</section>) </section>)
})} })}
@@ -402,15 +410,35 @@ const MaterialListPage: FC = () => {
src: url(${ nikumaru }) format('opentype'); src: url(${ nikumaru }) format('opentype');
}`} }`}
</style> </style>
<title>{`素材管理 | ${ SITE_TITLE }`}</title> <title>{`素材一覧 | ${ SITE_TITLE }`}</title>
</Helmet> </Helmet>
<div className="space-y-5"> <div className="space-y-5">
<div className="flex flex-wrap items-center justify-between gap-3"> <div className="flex flex-wrap items-center justify-between gap-3">
<PageTitle className="my-auto"></PageTitle> <PageTitle></PageTitle>
<div className="flex flex-wrap gap-2"> <div className="flex flex-wrap gap-2">
{/* TODO: 局所出力を可能にする */} <PrefetchLink
{/* <a to="/materials/new"
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">
</PrefetchLink>
<PrefetchLink
to="/materials/suppressions"
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">
</PrefetchLink>
<PrefetchLink
to="/materials/changes"
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">
</PrefetchLink>
<a
href={`${ API_BASE_URL }/materials/download.zip?profile=legacy_drive`} href={`${ API_BASE_URL }/materials/download.zip?profile=legacy_drive`}
target="_blank" target="_blank"
rel="noopener noreferrer" rel="noopener noreferrer"
@@ -418,7 +446,7 @@ const MaterialListPage: FC = () => {
text-stone-900 hover:bg-stone-100 dark:border-stone-700 text-stone-900 hover:bg-stone-100 dark:border-stone-700
dark:bg-stone-900 dark:text-stone-100 dark:hover:bg-stone-800"> dark:bg-stone-900 dark:text-stone-100 dark:hover:bg-stone-800">
ZIP ZIP
</a> */} </a>
</div> </div>
</div> </div>
@@ -430,6 +458,12 @@ const MaterialListPage: FC = () => {
{tagScope.tag.name} {tagScope.tag.name}
{tagScope.includeDescendants ? ' 配下の素材を表示中' : ' の素材を表示中'} {tagScope.includeDescendants ? ' 配下の素材を表示中' : ' の素材を表示中'}
</span> </span>
<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>
<PrefetchLink <PrefetchLink
to={clearedTagSelectionPath (location.search, materialFilter)} to={clearedTagSelectionPath (location.search, materialFilter)}
className="font-medium underline underline-offset-2 className="font-medium underline underline-offset-2
@@ -500,6 +534,21 @@ const MaterialListPage: FC = () => {
</select>)} </select>)}
</FormField> </FormField>
<FormField label="グルーピング">
{({ invalid }) => (
<select
value={groupByInput}
onChange={e => setGroupByInput (
e.target.value as MaterialIndexGroupBy)}
disabled={tagId == null}
className={inputClass (invalid)}>
<option value="none">{GROUP_BY_LABELS.none}</option>
<option value="parent_tag" disabled={tagId == null}>
{GROUP_BY_LABELS.parent_tag}
</option>
</select>)}
</FormField>
<FormField label="作成日時"> <FormField label="作成日時">
{() => ( {() => (
<div className="flex flex-wrap items-center gap-2"> <div className="flex flex-wrap items-center gap-2">
@@ -542,7 +591,7 @@ const MaterialListPage: FC = () => {
: [ : [
'border-stone-300 bg-white text-stone-900 dark:border-stone-700', 'border-stone-300 bg-white text-stone-900 dark:border-stone-700',
'dark:bg-stone-900 dark:text-stone-100'].join (' ') }`}> 'dark:bg-stone-900 dark:text-stone-100'].join (' ') }`}>
</button> </button>
<button <button
type="button" type="button"
@@ -555,7 +604,7 @@ const MaterialListPage: FC = () => {
: [ : [
'border-stone-300 bg-white text-stone-900 dark:border-stone-700', 'border-stone-300 bg-white text-stone-900 dark:border-stone-700',
'dark:bg-stone-900 dark:text-stone-100'].join (' ') }`}> 'dark:bg-stone-900 dark:text-stone-100'].join (' ') }`}>
</button> </button>
</div> </div>
@@ -583,18 +632,7 @@ const MaterialListPage: FC = () => {
{isError && ( {isError && (
<p className="text-red-600 dark:text-red-300"></p>)} <p className="text-red-600 dark:text-red-300"></p>)}
{(!isLoading && !isError && materials.length === 0) && ( {(!isLoading && !isError && materials.length === 0) && (
<p> <p></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 && ( {materials.length > 0 && (
groupBy === 'parent_tag' && groups.length > 0 groupBy === 'parent_tag' && groups.length > 0
? renderGroupedMaterials (groups) ? renderGroupedMaterials (groups)
+51
ファイルの表示
@@ -0,0 +1,51 @@
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
+28 -34
ファイルの表示
@@ -2,13 +2,17 @@ import { useMutation, useQuery, useQueryClient } from '@tanstack/react-query'
import { useState } from 'react' import { useState } from 'react'
import { Helmet } from 'react-helmet-async' import { Helmet } from 'react-helmet-async'
import PrefetchLink from '@/components/PrefetchLink'
import FormField from '@/components/common/FormField' import FormField from '@/components/common/FormField'
import PageTitle from '@/components/common/PageTitle' import PageTitle from '@/components/common/PageTitle'
import MainArea from '@/components/layout/MainArea' import MainArea from '@/components/layout/MainArea'
import { Button } from '@/components/ui/button' import { Button } from '@/components/ui/button'
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 { createMaterialSyncSuppression, fetchMaterialSyncSuppressions } from '@/lib/materials' import {
createMaterialSyncSuppression,
fetchMaterialSyncSuppressions,
} from '@/lib/materials'
import { materialsKeys } from '@/lib/queryKeys' import { materialsKeys } from '@/lib/queryKeys'
import { dateString, inputClass } from '@/lib/utils' import { dateString, inputClass } from '@/lib/utils'
@@ -18,11 +22,11 @@ import type { MaterialSyncSuppressionSourceKind } from '@/types'
const SOURCE_KIND_LABELS: Record<MaterialSyncSuppressionSourceKind, string> = { const SOURCE_KIND_LABELS: Record<MaterialSyncSuppressionSourceKind, string> = {
uri: 'URI', uri: 'URI',
google_drive_path: 'Google Drive ファイル', google_drive_path: 'Google Drive path',
google_drive_path_prefix: 'Google Drive フォルダ', google_drive_path_prefix: 'Google Drive path prefix',
google_drive_file: 'Google Drive ファイル Id.', google_drive_file: 'Google Drive file ID',
legacy_drive_path: '汎用ファイル', legacy_drive_path: 'Legacy Drive path',
legacy_drive_path_prefix: '汎用フォルダ' } legacy_drive_path_prefix: 'Legacy Drive path prefix'}
const REASONS = [ const REASONS = [
'copyright_high_risk', 'copyright_high_risk',
@@ -32,23 +36,7 @@ const REASONS = [
'malware_or_dangerous_file', 'malware_or_dangerous_file',
'duplicate_or_low_quality', 'duplicate_or_low_quality',
'source_owner_request', 'source_owner_request',
'other'] as const 'other']
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 MaterialSyncSuppressionsPage: FC = () => {
@@ -58,7 +46,7 @@ const MaterialSyncSuppressionsPage: FC = () => {
const [sourceUri, setSourceUri] = useState ('') const [sourceUri, setSourceUri] = useState ('')
const [drivePath, setDrivePath] = useState ('') const [drivePath, setDrivePath] = useState ('')
const [driveFileId, setDriveFileId] = useState ('') const [driveFileId, setDriveFileId] = useState ('')
const [reason, setReason] = useState<MaterialSyncSuppressionReason> (REASONS[0]) const [reason, setReason] = useState (REASONS[0])
const { data, isError, isLoading } = useQuery ({ const { data, isError, isLoading } = useQuery ({
queryKey: materialsKeys.suppressions (), queryKey: materialsKeys.suppressions (),
@@ -94,11 +82,18 @@ const MaterialSyncSuppressionsPage: FC = () => {
return ( return (
<MainArea> <MainArea>
<Helmet> <Helmet>
<title>{`素材同期抑止 | ${ SITE_TITLE }`}</title> <title>{`同期抑止 | ${ SITE_TITLE }`}</title>
</Helmet> </Helmet>
<div className="space-y-5"> <div className="space-y-5">
<PageTitle></PageTitle> <div className="flex flex-wrap items-center justify-between gap-3">
<PageTitle></PageTitle>
<PrefetchLink
to="/materials"
className="text-sm text-sky-700 underline underline-offset-2 dark:text-sky-300">
</PrefetchLink>
</div>
<form <form
onSubmit={handleSubmit} onSubmit={handleSubmit}
@@ -120,7 +115,7 @@ const MaterialSyncSuppressionsPage: FC = () => {
</select>)} </select>)}
</FormField> </FormField>
<FormField label="同期元 URI"> <FormField label="Source URI">
{({ invalid }) => ( {({ invalid }) => (
<input <input
type="text" type="text"
@@ -129,7 +124,7 @@ const MaterialSyncSuppressionsPage: FC = () => {
className={inputClass (invalid)}/>)} className={inputClass (invalid)}/>)}
</FormField> </FormField>
<FormField label="Google Drive パス"> <FormField label="Drive path">
{({ invalid }) => ( {({ invalid }) => (
<input <input
type="text" type="text"
@@ -138,7 +133,7 @@ const MaterialSyncSuppressionsPage: FC = () => {
className={inputClass (invalid)}/>)} className={inputClass (invalid)}/>)}
</FormField> </FormField>
<FormField label="Google Drive ファイル Id."> <FormField label="Drive file ID">
{({ invalid }) => ( {({ invalid }) => (
<input <input
type="text" type="text"
@@ -147,15 +142,15 @@ const MaterialSyncSuppressionsPage: FC = () => {
className={inputClass (invalid)}/>)} className={inputClass (invalid)}/>)}
</FormField> </FormField>
<FormField label="由"> <FormField label="由">
{({ invalid }) => ( {({ invalid }) => (
<select <select
value={reason} value={reason}
onChange={e => setReason (e.target.value as MaterialSyncSuppressionReason)} onChange={e => setReason (e.target.value)}
className={inputClass (invalid)}> className={inputClass (invalid)}>
{REASONS.map (value => ( {REASONS.map (value => (
<option key={value} value={value}> <option key={value} value={value}>
{REASON_NAMES[value]} {value}
</option>))} </option>))}
</select>)} </select>)}
</FormField> </FormField>
@@ -190,8 +185,7 @@ const MaterialSyncSuppressionsPage: FC = () => {
{suppression.normalizedSourceKey} {suppression.normalizedSourceKey}
</div> </div>
<div className="mt-2 text-sm text-stone-600 dark:text-stone-400"> <div className="mt-2 text-sm text-stone-600 dark:text-stone-400">
: {reasonName (suppression.reason)} / : {suppression.reason} / : {dateString (suppression.createdAt)}
: {dateString (suppression.createdAt)}
</div> </div>
</article>))} </article>))}
</div> </div>