コミットを比較

...

10 コミット

作成者 SHA1 メッセージ 日付
みてるぞ c9b22d346b #306 2026-06-28 06:35:07 +09:00
みてるぞ 283c20b9da #306 2026-06-28 05:59:44 +09:00
みてるぞ ec98c6b756 #306 2026-06-28 03:40:35 +09:00
みてるぞ d721a64e33 #306 2026-06-27 19:06:28 +09:00
みてるぞ 0eb45372c3 #306 2026-06-27 18:52:50 +09:00
みてるぞ 27aa5321a1 #306 2026-06-27 18:43:40 +09:00
みてるぞ 4c0a4f5d9b #306 2026-06-27 18:27:10 +09:00
みてるぞ 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
27個のファイルの変更847行の追加409行の削除
+6 -1
ファイルの表示
@@ -271,7 +271,12 @@ const value =
- In TypeScript and TSX, convert every leading run of 8 spaces to a tab
character.
- A leading tab is exactly equivalent to 8 leading spaces.
- Never place a closing parenthesis at the beginning of a line.
- In TypeScript and TSX function declarations, including `const` arrow
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.
- 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
+1 -4
ファイルの表示
@@ -523,10 +523,7 @@ class MaterialsController < ApplicationController
content_type: file.content_type,
)
if file_sha256.present?
blob.metadata['sha256'] = file_sha256
blob.save! if blob.changed?
end
MaterialFileSha256.assign_metadata_sha256!(blob, file_sha256)
blob
ensure
+4 -1
ファイルの表示
@@ -1,6 +1,9 @@
class Material < ApplicationRecord
include MyDiscard
SOURCE_KINDS = ['uri', 'google_drive_path', 'google_drive_file',
'legacy_drive_path'].freeze
default_scope -> { kept }
belongs_to :parent, class_name: 'Material', optional: true
@@ -20,7 +23,7 @@ class Material < ApplicationRecord
validates :tag_id, uniqueness: true, allow_nil: true
validates :source_kind,
inclusion: { in: MaterialSyncSuppression::SOURCE_KINDS },
inclusion: { in: SOURCE_KINDS },
allow_blank: true
validate :file_must_be_attached
+11 -4
ファイルの表示
@@ -26,13 +26,19 @@ module GoogleDrive
def list_material_files_under_folder folder_id
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|
next if entry['mimeType'] == FOLDER_MIME_TYPE
next if native_file?(entry['mimeType'])
files << build_file_entry(entry, relative_path)
yield build_file_entry(entry, relative_path)
end
files
end
def fetch_material_file file_id
@@ -44,9 +50,10 @@ module GoogleDrive
def download_to_tempfile file_id, filename:
tempfile = Tempfile.new(['material-sync', File.extname(filename.to_s)])
tempfile.binmode
request_binary("/files/#{ file_id }",
{ alt: 'media', supportsAllDrives: true }) do |chunk|
tempfile.write(chunk)
tempfile.write(chunk.b)
end
tempfile.rewind
tempfile
@@ -139,7 +146,7 @@ module GoogleDrive
end
response.read_body do |chunk|
yield chunk
yield chunk.b
end
end
end
+26 -3
ファイルの表示
@@ -1,16 +1,39 @@
require 'digest'
require 'json'
class MaterialFileSha256
def self.blob_metadata blob
metadata = blob.metadata
return metadata if metadata.is_a?(Hash)
return { } if metadata.blank?
JSON.parse(metadata)
rescue JSON::ParserError
{ }
end
def self.metadata_sha256 blob
blob_metadata(blob)['sha256'].presence
end
def self.assign_metadata_sha256! blob, sha256
return if sha256.blank?
metadata = blob_metadata(blob)
metadata['sha256'] = sha256
blob.metadata = metadata
blob.save! if blob.changed?
end
def self.from_blob blob, allow_download: false
sha256 = blob.metadata['sha256']
sha256 = metadata_sha256(blob)
return sha256 if sha256.present?
return nil unless allow_download
begin
blob.open do |file|
sha256 = Digest::SHA256.file(file.path).hexdigest
blob.metadata['sha256'] = sha256
blob.save! if blob.changed?
assign_metadata_sha256!(blob, sha256)
sha256
end
rescue ActiveStorage::FileNotFoundError, ArgumentError => error
+2 -3
ファイルの表示
@@ -148,8 +148,7 @@ class MaterialSyncImporter
io: tempfile,
filename: @attributes[:filename],
content_type: @attributes[:content_type])
blob.metadata['sha256'] = file_sha256 if file_sha256.present?
blob.save! if blob.changed?
MaterialFileSha256.assign_metadata_sha256!(blob, file_sha256)
tempfile.rewind
blob
end
@@ -226,7 +225,7 @@ class MaterialSyncImporter
if expected_sha256.present?
return false unless material.file.attached?
return material.file.blob.metadata['sha256'] == expected_sha256
return MaterialFileSha256.metadata_sha256(material.file.blob) == expected_sha256
end
!material.file.attached?
+37 -6
ファイルの表示
@@ -21,10 +21,14 @@ class MaterialSyncRunner
result = Result.new(imported: 0, updated: 0, unchanged: 0,
suppressed: 0, failed: 0, errors: [])
candidates.each do |candidate|
next if candidate.blank?
if @source.source_kind == 'google_drive_path'
sync_google_drive_path!(result)
else
candidates.each do |candidate|
next if candidate.blank?
sync_candidate!(candidate, result)
sync_candidate!(candidate, result)
end
end
@source.update!(last_synced_at: Time.current)
@@ -43,8 +47,6 @@ class MaterialSyncRunner
case @source.source_kind
when 'uri'
[uri_candidate]
when 'google_drive_path'
google_drive_path_candidates
when 'google_drive_file'
[google_drive_file_candidate]
when 'legacy_drive_path'
@@ -104,12 +106,25 @@ class MaterialSyncRunner
def google_drive_path_candidates
folder_id = google_drive_folder_id
Enumerator.new do |entries|
drive_client.list_material_files_under_folder(folder_id).each do |entry|
drive_client.each_material_file_under_folder(folder_id).each do |entry|
entries << build_google_drive_candidate(entry)
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
entry = drive_client.fetch_material_file(google_drive_file_id)
return nil unless entry
@@ -213,6 +228,22 @@ class MaterialSyncRunner
failed: result.failed))
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
{ material_sync_source_id: @source.id,
material_sync_source_name: @source.name }.merge(fields).to_json
+1 -1
ファイルの表示
@@ -57,7 +57,7 @@ class MaterialVersionRecorder < VersionRecorder
file_content_type: blob.content_type,
file_byte_size: blob.byte_size,
file_checksum: blob.checksum,
file_sha256: blob.metadata['sha256'] }
file_sha256: MaterialFileSha256.metadata_sha256(blob) }
end
def empty_file_snapshot
生成ファイル
+35 -8
ファイルの表示
@@ -72,6 +72,7 @@ ActiveRecord::Schema[8.0].define(version: 2026_06_26_010000) do
t.index ["correct_post_id"], name: "index_gekanator_games_on_correct_post_id"
t.index ["guessed_post_id"], name: "index_gekanator_games_on_guessed_post_id"
t.index ["user_id"], name: "index_gekanator_games_on_user_id"
t.check_constraint "`question_count` >= 0", name: "chk_gekanator_games_question_count_nonnegative"
end
create_table "gekanator_question_examples", charset: "utf8mb4", collation: "utf8mb4_0900_ai_ci", force: :cascade do |t|
@@ -274,9 +275,10 @@ ActiveRecord::Schema[8.0].define(version: 2026_06_26_010000) do
t.datetime "created_at", null: false
t.bigint "created_by_user_id"
t.index ["created_at"], name: "index_nico_tag_versions_on_created_at"
t.index ["created_by_user_id", "created_at"], name: "index_nico_tag_versions_on_created_by_user_id_and_created_at"
t.index ["tag_id", "created_at"], name: "index_nico_tag_versions_on_tag_id_and_created_at"
t.index ["created_by_user_id", "created_at"], name: "index_nico_tag_versions_on_created_by_user_id_and_created_at", order: { created_at: :desc }
t.index ["tag_id", "created_at"], name: "index_nico_tag_versions_on_tag_id_and_created_at", order: { created_at: :desc }
t.index ["tag_id", "version_no"], name: "index_nico_tag_versions_on_tag_id_and_version_no", unique: true
t.check_constraint "`version_no` > 0", name: "nico_tag_versions_version_no_positive"
end
create_table "post_implications", primary_key: ["post_id", "parent_post_id"], charset: "utf8mb4", collation: "utf8mb4_0900_ai_ci", force: :cascade do |t|
@@ -285,13 +287,14 @@ ActiveRecord::Schema[8.0].define(version: 2026_06_26_010000) do
t.datetime "created_at", null: false
t.datetime "updated_at", null: false
t.index ["parent_post_id"], name: "index_post_implications_on_parent_post_id"
t.check_constraint "`post_id` <> `parent_post_id`", name: "chk_post_implications_no_self"
end
create_table "post_similarities", primary_key: ["post_id", "target_post_id"], charset: "utf8mb4", collation: "utf8mb4_0900_ai_ci", force: :cascade do |t|
t.bigint "post_id", null: false
t.bigint "target_post_id", null: false
t.float "cos", null: false
t.index ["post_id", "cos"], name: "index_post_similarities_on_post_id_and_cos"
t.index ["post_id", "cos"], name: "index_post_similarities_on_post_id_and_cos", order: { cos: :desc }
t.index ["target_post_id"], name: "index_post_similarities_on_target_post_id"
end
@@ -331,6 +334,8 @@ ActiveRecord::Schema[8.0].define(version: 2026_06_26_010000) do
t.index ["created_by_user_id"], name: "index_post_versions_on_created_by_user_id"
t.index ["post_id", "version_no"], name: "index_post_versions_on_post_id_and_version_no", unique: true
t.index ["post_id"], name: "index_post_versions_on_post_id"
t.check_constraint "`event_type` in (_utf8mb4'create',_utf8mb4'update',_utf8mb4'discard',_utf8mb4'restore')", name: "post_versions_event_type_valid"
t.check_constraint "`version_no` > 0", name: "post_versions_version_no_positive"
end
create_table "posts", charset: "utf8mb4", collation: "utf8mb4_0900_ai_ci", force: :cascade do |t|
@@ -345,6 +350,7 @@ ActiveRecord::Schema[8.0].define(version: 2026_06_26_010000) do
t.integer "version_no", null: false
t.index ["uploaded_user_id"], name: "index_posts_on_uploaded_user_id"
t.index ["url"], name: "index_posts_on_url", unique: true
t.check_constraint "`version_no` > 0", name: "chk_posts_version_no_positive"
end
create_table "settings", charset: "utf8mb4", collation: "utf8mb4_0900_ai_ci", force: :cascade do |t|
@@ -391,7 +397,7 @@ ActiveRecord::Schema[8.0].define(version: 2026_06_26_010000) do
t.bigint "tag_id", null: false
t.bigint "target_tag_id", null: false
t.float "cos", null: false
t.index ["tag_id", "cos"], name: "index_tag_similarities_on_tag_id_and_cos"
t.index ["tag_id", "cos"], name: "index_tag_similarities_on_tag_id_and_cos", order: { cos: :desc }
t.index ["target_tag_id"], name: "index_tag_similarities_on_target_tag_id"
end
@@ -401,30 +407,32 @@ ActiveRecord::Schema[8.0].define(version: 2026_06_26_010000) do
t.string "event_type", null: false
t.string "name", null: false
t.string "category", null: false
t.datetime "deprecated_at"
t.text "aliases", null: false
t.text "parent_tag_ids", null: false
t.datetime "deprecated_at"
t.datetime "created_at", null: false
t.bigint "created_by_user_id"
t.index ["created_at"], name: "index_tag_versions_on_created_at"
t.index ["created_by_user_id", "created_at"], name: "index_tag_versions_on_created_by_user_id_and_created_at"
t.index ["tag_id", "created_at"], name: "index_tag_versions_on_tag_id_and_created_at"
t.index ["created_by_user_id", "created_at"], name: "index_tag_versions_on_created_by_user_id_and_created_at", order: { created_at: :desc }
t.index ["tag_id", "created_at"], name: "index_tag_versions_on_tag_id_and_created_at", order: { created_at: :desc }
t.index ["tag_id", "version_no"], name: "index_tag_versions_on_tag_id_and_version_no", unique: true
t.check_constraint "`version_no` > 0", name: "tag_versions_version_no_positive"
end
create_table "tags", charset: "utf8mb4", collation: "utf8mb4_0900_ai_ci", force: :cascade do |t|
t.bigint "tag_name_id", null: false
t.string "category", default: "general", null: false
t.datetime "deprecated_at"
t.datetime "created_at", null: false
t.datetime "updated_at", null: false
t.integer "post_count", default: 0, null: false
t.datetime "deprecated_at"
t.datetime "discarded_at"
t.integer "version_no", null: false
t.index ["deprecated_at"], name: "index_tags_on_deprecated_at"
t.index ["discarded_at"], name: "index_tags_on_discarded_at"
t.index ["tag_name_id"], name: "index_tags_on_tag_name_id", unique: true
t.check_constraint "(`deprecated_at` is null) or (`category` <> _utf8mb4'nico')", name: "chk_tags_deprecated_at_not_nico"
t.check_constraint "`version_no` > 0", name: "chk_tags_version_no_positive"
end
create_table "theatre_comments", primary_key: ["theatre_id", "no"], charset: "utf8mb4", collation: "utf8mb4_0900_ai_ci", force: :cascade do |t|
@@ -549,6 +557,19 @@ ActiveRecord::Schema[8.0].define(version: 2026_06_26_010000) do
t.index ["banned_at"], name: "index_users_on_banned_at"
end
create_table "wiki_assets", charset: "utf8mb4", collation: "utf8mb4_0900_ai_ci", force: :cascade do |t|
t.bigint "wiki_page_id", null: false
t.integer "no", null: false
t.string "alt_text"
t.binary "sha256", limit: 32, null: false
t.bigint "created_by_user_id", null: false
t.datetime "created_at", null: false
t.datetime "updated_at", null: false
t.index ["created_by_user_id"], name: "index_wiki_assets_on_created_by_user_id"
t.index ["wiki_page_id", "no"], name: "index_wiki_assets_on_wiki_page_id_and_no", unique: true
t.index ["wiki_page_id", "sha256"], name: "index_wiki_assets_on_wiki_page_id_and_sha256", unique: true
end
create_table "wiki_lines", charset: "utf8mb4", collation: "utf8mb4_0900_ai_ci", force: :cascade do |t|
t.string "sha256", limit: 64, null: false
t.text "body", null: false
@@ -565,11 +586,13 @@ ActiveRecord::Schema[8.0].define(version: 2026_06_26_010000) do
t.datetime "created_at", null: false
t.datetime "updated_at", null: false
t.datetime "discarded_at"
t.integer "next_asset_no", default: 1, null: false
t.integer "version_no", null: false
t.index ["created_user_id"], name: "index_wiki_pages_on_created_user_id"
t.index ["discarded_at"], name: "index_wiki_pages_on_discarded_at"
t.index ["tag_name_id"], name: "index_wiki_pages_on_tag_name_id", unique: true
t.index ["updated_user_id"], name: "index_wiki_pages_on_updated_user_id"
t.check_constraint "`version_no` > 0", name: "chk_wiki_pages_version_no_positive"
end
create_table "wiki_revision_lines", charset: "utf8mb4", collation: "utf8mb4_0900_ai_ci", force: :cascade do |t|
@@ -614,6 +637,8 @@ ActiveRecord::Schema[8.0].define(version: 2026_06_26_010000) do
t.index ["created_by_user_id"], name: "index_wiki_versions_on_created_by_user_id"
t.index ["wiki_page_id", "version_no"], name: "index_wiki_versions_on_wiki_page_id_and_version_no", unique: true
t.index ["wiki_page_id"], name: "index_wiki_versions_on_wiki_page_id"
t.check_constraint "`event_type` in (_utf8mb4'create',_utf8mb4'update',_utf8mb4'discard',_utf8mb4'restore')", name: "wiki_versions_event_type_valid"
t.check_constraint "`version_no` > 0", name: "wiki_versions_version_no_positive"
end
add_foreign_key "active_storage_attachments", "active_storage_blobs", column: "blob_id"
@@ -692,6 +717,8 @@ ActiveRecord::Schema[8.0].define(version: 2026_06_26_010000) do
add_foreign_key "user_ips", "users"
add_foreign_key "user_post_views", "posts"
add_foreign_key "user_post_views", "users"
add_foreign_key "wiki_assets", "users", column: "created_by_user_id"
add_foreign_key "wiki_assets", "wiki_pages"
add_foreign_key "wiki_pages", "tag_names"
add_foreign_key "wiki_pages", "users", column: "created_user_id"
add_foreign_key "wiki_pages", "users", column: "updated_user_id"
+19
ファイルの表示
@@ -0,0 +1,19 @@
require 'rails_helper'
RSpec.describe Material, type: :model do
let(:user) { create(:user, :member) }
it 'allows only material source kinds, not suppression prefix kinds' do
material = described_class.new(url: 'https://example.com/material',
source_kind: 'google_drive_path_prefix',
source_path: '素材/危険',
created_by_user: user,
updated_by_user: user)
expect(material).not_to be_valid
expect(material.errors[:source_kind]).to be_present
material.source_kind = 'google_drive_path'
expect(material).to be_valid
end
end
+62
ファイルの表示
@@ -113,6 +113,68 @@ RSpec.describe 'Materials API', type: :request do
expect(response_materials.size).to eq(1)
expect(response_materials.first['id']).to eq(material_b.id)
end
it 'filters by descendant tags and returns stable parent tag groups' do
root =
Tag.create!(tag_name: TagName.create!(name: 'material_scope_root'),
category: :material)
child_b =
Tag.create!(tag_name: TagName.create!(name: 'material_scope_b'),
category: :material)
child_a =
Tag.create!(tag_name: TagName.create!(name: 'material_scope_a'),
category: :material)
deprecated =
Tag.create!(tag_name: TagName.create!(name: 'material_scope_old'),
category: :material,
deprecated_at: Time.current)
grandchild =
Tag.create!(tag_name: TagName.create!(name: 'material_scope_grandchild'),
category: :material)
root_material =
build_material(tag: root, user: member_user,
file: dummy_upload(filename: 'root.png'))
child_a_material =
build_material(tag: child_a, user: member_user,
file: dummy_upload(filename: 'child_a.png'))
grandchild_material =
build_material(tag: grandchild, user: member_user,
file: dummy_upload(filename: 'grandchild.png'))
TagImplication.create!(parent_tag: root, tag: child_b)
TagImplication.create!(parent_tag: root, tag: child_a)
TagImplication.create!(parent_tag: child_b, tag: deprecated)
TagImplication.create!(parent_tag: deprecated, tag: grandchild)
get '/materials',
params: { tag_id: root.id, include_descendants: '1',
group_by: 'parent_tag', sort: 'id', direction: 'asc' }
expect(response).to have_http_status(:ok)
expect(response_materials.map { |m| m['id'] })
.to include(root_material.id, child_a_material.id, grandchild_material.id)
expect(json['tag_scope']).to eq(
'tag' => {
'id' => root.id,
'name' => 'material_scope_root',
'category' => 'material'
},
'include_descendants' => true
)
expect(json['groups'].map { |group| group.dig('tag', 'name') })
.to eq(['material_scope_a', 'material_scope_b', 'material_scope_root'])
expect(json['groups'].find { |group| group.dig('tag', 'id') == child_b.id }
.fetch('material_ids')).to eq([grandchild_material.id])
end
it 'returns nil tag_scope when tag_id is unknown' do
get '/materials', params: { tag_id: 999_999, group_by: 'parent_tag' }
expect(response).to have_http_status(:ok)
expect(json['tag_scope']).to be_nil
expect(json['groups']).to eq([])
expect(response_materials).to eq([])
end
end
describe 'GET /materials/:id' do
+23
ファイルの表示
@@ -0,0 +1,23 @@
require 'rails_helper'
RSpec.describe MaterialFileSha256 do
describe '.metadata_sha256' do
it 'reads sha256 from Hash metadata' do
blob = instance_double(ActiveStorage::Blob, metadata: { 'sha256' => 'abc123' })
expect(described_class.metadata_sha256(blob)).to eq('abc123')
end
it 'reads sha256 from JSON string metadata' do
blob = instance_double(ActiveStorage::Blob, metadata: '{"sha256":"abc123"}')
expect(described_class.metadata_sha256(blob)).to eq('abc123')
end
it 'returns nil for invalid metadata' do
blob = instance_double(ActiveStorage::Blob, metadata: '{')
expect(described_class.metadata_sha256(blob)).to be_nil
end
end
end
+89
ファイルの表示
@@ -0,0 +1,89 @@
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,7 +75,6 @@ const RouteTransitionWrapper = ({ user, setUser }: {
<Route path="suppressions" element={<MaterialSyncSuppressionsPage/>}/>
<Route path=":id" element ={<MaterialDetailPage/>}/>
</Route>
{/* <Route path="/materials/search" element={<MaterialSearchPage/>}/> */}
<Route path="/wiki" element={<WikiSearchPage/>}/>
<Route path="/wiki/:title" element={<WikiDetailPage/>}/>
<Route path="/wiki/new" element={<WikiNewPage user={user}/>}/>
+251 -108
ファイルの表示
@@ -1,29 +1,43 @@
import { Fragment, useEffect, useRef, useState } from 'react'
import { useQuery } from '@tanstack/react-query'
import { useEffect, useRef, useState } from 'react'
import { useLocation, useNavigate } from 'react-router-dom'
import PrefetchLink from '@/components/PrefetchLink'
import TagLink from '@/components/TagLink'
import SidebarComponent from '@/components/layout/SidebarComponent'
import { materialsKeys } from '@/lib/queryKeys'
import TagLink from '@/components/TagLink'
import { fetchMaterialTagTree, parseMaterialFilter } from '@/lib/materials'
import { materialsKeys } from '@/lib/queryKeys'
import { cn } from '@/lib/utils'
import type { Dispatch, FC, ReactNode, SetStateAction } from 'react'
import type { CSSProperties, Dispatch, FC, ReactNode, SetStateAction } from 'react'
import type { MaterialFilter, MaterialSidebarTag, Tag } from '@/types'
const FILTERS: MaterialFilter[] = ['present', 'missing', 'any']
const FILTERS: MaterialFilter[] = ['missing', 'present', 'any']
const FILTER_LABELS: Record<MaterialFilter, string> = { present: '有', missing: '無', any: '全' }
const FILTER_LABELS: Record<MaterialFilter, string> = {
present: '素材あり',
missing: '素材なし',
any: 'すべて'}
const px = (value: string): number => {
const parsed = Number.parseFloat (value)
return Number.isFinite (parsed) ? parsed : 0
}
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 = (
tags: MaterialSidebarTag[],
targetId: number,
children: MaterialSidebarTag[]): MaterialSidebarTag[] => (
children: MaterialSidebarTag[],
): MaterialSidebarTag[] => (
tags.map (tag => {
if (tag.id === targetId)
return { ...tag, children }
@@ -37,24 +51,12 @@ const setChildrenById = (
const materialPath = (
tagId: number,
materialFilter: MaterialFilter): string =>
materialFilter: MaterialFilter,
): string =>
`/materials?tag_id=${ tagId }&include_descendants=1&group_by=parent_tag`
+ `&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 => ({
id: tag.id,
name: tag.name,
@@ -72,39 +74,42 @@ const sidebarTagToTag = (tag: MaterialSidebarTag): Tag => ({
const tagSelectionShellClass = (selected: boolean): string =>
selected
? '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'
: 'px-2 py-1'
cn (selected
? ['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']
: 'px-2 py-1')
const updateMaterialFilterQuery = (
pathname: string,
locationSearch: string,
navigate: ReturnType<typeof useNavigate>,
materialFilter: MaterialFilter) => {
const qs = new URLSearchParams (locationSearch)
qs.set ('material_filter', materialFilter)
navigate (`${ pathname }${ qs.toString () ? `?${ qs.toString () }` : '' }`)
materialFilter: MaterialFilter,
) => {
const qs = new URLSearchParams (locationSearch)
qs.set ('material_filter', materialFilter)
navigate (`${ pathname }${ qs.toString () ? `?${ qs.toString () }` : '' }`)
}
const MaterialFilterButtons: FC<{
materialFilter: MaterialFilter
onChange: (materialFilter: MaterialFilter) => void
}> = ({ materialFilter, onChange }) => (
<div className="flex flex-wrap gap-2">
const MaterialFilterButtons: FC<{ materialFilter: MaterialFilter
onChange: (materialFilter: MaterialFilter) => void }> = (
{ materialFilter, onChange },
) => (
<div className="flex flex-wrap gap-2 justify-end md:justify-start flex-center">
<label className="my-auto text-sm font-bold"></label>
{FILTERS.map (value => (
<button
<button
key={value}
type="button"
onClick={() => onChange (value)}
className={`rounded-full border px-3 py-1 text-sm ${
materialFilter === value
? 'border-sky-500 bg-sky-50 text-sky-700 dark:border-sky-400 '
+ 'dark:bg-sky-950 dark:text-sky-100'
: 'border-neutral-300 bg-white text-neutral-700 dark:border-stone-700 '
+ 'dark:bg-stone-900 dark:text-stone-200' }`}>
className={cn (
'rounded-full border px-3 py-1 text-sm',
(materialFilter === value
? ['border-sky-500 bg-sky-50 text-sky-700 dark:border-sky-400',
'dark:bg-sky-950 dark:text-sky-100']
: ['border-neutral-300 bg-white text-neutral-700 dark:border-stone-700',
'dark:bg-stone-900 dark:text-stone-200']))}>
{FILTER_LABELS[value]}
</button>))}
</div>)
@@ -132,10 +137,10 @@ const MaterialTreeNode: FC<{
}, [data, onChildren, open, tag.children.length, tag.id])
return (
<Fragment>
<>
<li>
<div className="flex">
<div className="flex-none w-4">
<div className="flex flex-center">
<div className="flex-none w-4 my-auto">
{tag.hasChildren && (
<button
type="button"
@@ -144,8 +149,9 @@ const MaterialTreeNode: FC<{
{open ? <>&minus;</> : '+'}
</button>)}
</div>
<div className="flex-1 truncate">
<div className={tagSelectionShellClass (selectedTagId === tag.id)}>
<div className="min-w-0 flex-1 my-auto">
<div className={cn (tagSelectionShellClass (selectedTagId === tag.id),
'min-w-0 truncate')}>
<TagLink
tag={sidebarTagToTag (tag)}
nestLevel={nestLevel}
@@ -160,7 +166,7 @@ const MaterialTreeNode: FC<{
{open && tag.children.length > 0 && (
<ul>
{tag.children.map (child => (
<MaterialTreeNode
<MaterialTreeNode
key={child.id}
tag={child}
nestLevel={nestLevel + 1}
@@ -170,21 +176,39 @@ const MaterialTreeNode: FC<{
setOpenTags={setOpenTags}
onChildren={onChildren}/>))}
</ul>)}
</Fragment>)
</>)
}
const MobileMaterialTreeNode: FC<{
depth?: number
materialFilter: MaterialFilter
selectedTagId: number | null
onChildren: (tagId: number, children: MaterialSidebarTag[]) => void
openTags: Record<number, boolean>
setOpenTags: Dispatch<SetStateAction<Record<number, boolean>>>
tag: MaterialSidebarTag
}> = ({ depth = 0, materialFilter, onChildren, openTags, selectedTagId,
setOpenTags, tag }) => {
const MobileMaterialTreeNode: FC<{ depth?: number
availableInlineSizePx?: number | null
materialFilter: MaterialFilter
selectedTagId: number | null
onChildren: (tagId: number, children: MaterialSidebarTag[]) =>
void
openTags: Record<number, boolean>
setOpenTags: Dispatch<SetStateAction<Record<number, boolean>>>
tag: MaterialSidebarTag }> = (
{
depth = 0,
availableInlineSizePx = null,
materialFilter,
onChildren,
openTags,
selectedTagId,
setOpenTags,
tag,
},
) => {
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 ({
queryKey: materialsKeys.tree ({ parentId: tag.id, materialFilter }),
queryFn: () => fetchMaterialTagTree ({ parentId: tag.id, materialFilter }),
@@ -195,50 +219,155 @@ const MobileMaterialTreeNode: FC<{
onChildren (tag.id, data)
}, [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 (
<div className="flex flex-row-reverse items-start gap-2">
<div className="flex flex-col items-center gap-1">
<div className="flex h-full min-h-0 max-h-full flex-row-reverse items-start gap-2
overflow-hidden">
<div
ref={tagColumnRef}
className="flex h-full min-h-0 max-h-full flex-col items-center gap-1
overflow-hidden">
<div
className={`${ tagSelectionShellClass (selectedTagId === tag.id) } rounded-xl
border px-3 py-2 text-sm shadow-sm`}
style={{ writingMode: 'vertical-rl' }}>
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
tag={sidebarTagToTag (tag)}
title={tag.name}
withCount={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>
{tag.hasChildren && (
<button
ref={buttonRef}
type="button"
onClick={() => setOpenTags (prev => ({ ...prev, [tag.id]: !prev[tag.id] }))}
className="rounded-full border border-stone-300 bg-white px-2 py-0.5
text-sm text-stone-700 dark:border-stone-700
className="flex-none rounded-full border border-stone-300 bg-white
px-2 py-0.5 text-sm text-stone-700 dark:border-stone-700
dark:bg-stone-900 dark:text-stone-100">
{open ? <>&minus;</> : '+'}
</button>)}
</div>
{open && tag.children.length > 0 && (
<div
className="relative flex flex-row-reverse items-start gap-2 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"
style={{ marginTop: `${ depth === 0 ? 1.25 : .75 }rem` }}>
<span
aria-hidden="true"
className="absolute -right-3 top-4 h-px w-3 bg-stone-300 dark:bg-stone-600"/>
{tag.children.map (child => (
<div key={child.id} className="relative">
<MobileMaterialTreeNode
tag={child}
depth={depth + 1}
materialFilter={materialFilter}
selectedTagId={selectedTagId}
openTags={openTags}
setOpenTags={setOpenTags}
onChildren={onChildren}/>
</div>))}
ref={expansionSlotRef}
className={cn (
'h-full min-h-0 max-h-full overflow-hidden box-border',
depth === 0 ? 'pt-5' : 'pt-3')}>
<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
aria-hidden="true"
className="absolute -right-3 top-4 h-px w-3 bg-stone-300 dark:bg-stone-600"/>
{tag.children.map (child => (
<div
key={child.id}
className="relative h-full min-h-0 max-h-full overflow-hidden">
<MobileMaterialTreeNode
tag={child}
depth={depth + 1}
availableInlineSizePx={childAvailableInlineSizePx}
materialFilter={materialFilter}
selectedTagId={selectedTagId}
openTags={openTags}
setOpenTags={setOpenTags}
onChildren={onChildren}/>
</div>))}
</div>
</div>
</div>)}
</div>)
}
@@ -248,12 +377,14 @@ const MaterialSidebar: FC = () => {
const location = useLocation ()
const navigate = useNavigate ()
const qs = new URLSearchParams (location.search)
const materialFilter = parseMaterialFilter (qs.get ('material_filter'), 'present')
const materialFilter = parseMaterialFilter (qs.get ('material_filter'), 'any')
const selectedTagId = Number (qs.get ('tag_id') ?? 0) || null
const [desktopTags, setDesktopTags] = useState<MaterialSidebarTag[]> ([])
const [openTags, setOpenTags] = useState<Record<number, boolean>> ({ })
const mobileRailRef = useRef<HTMLDivElement | null> (null)
const [mobileAvailableInlineSizePx, setMobileAvailableInlineSizePx] =
useState<number | null> (null)
const { data: rootTags = [], isLoading, isError } = useQuery ({
queryKey: materialsKeys.tree ({ parentId: null, materialFilter }),
@@ -273,6 +404,29 @@ const MaterialSidebar: FC = () => {
})
}, [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 setChildren = (tagId: number, children: MaterialSidebarTag[]) => {
@@ -288,8 +442,6 @@ const MaterialSidebar: FC = () => {
updateMaterialFilterQuery (location.pathname, location.search, navigate, value)
}
const clearTagSelection = clearTagSelectionPath (location.search, materialFilter)
const renderDesktopTree = (tags: MaterialSidebarTag[]): ReactNode => (
tags.map (tag => (
<MaterialTreeNode
@@ -304,24 +456,21 @@ const MaterialSidebar: FC = () => {
return (
<>
<div className="border-b bg-stone-50 p-3 dark:border-stone-700 dark:bg-stone-950
dark:text-stone-100 md: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>
dark:text-stone-100 md:hidden flex h-[25dvh] min-h-0 flex-col
overflow-hidden">
<MaterialFilterButtons
materialFilter={materialFilter}
onChange={handleFilterChange}/>
<div ref={mobileRailRef} className="mt-3 overflow-x-auto">
<div className="flex min-w-max flex-row-reverse gap-3 pb-1">
<div
ref={mobileRailRef}
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 => (
<MobileMaterialTreeNode
key={tag.id}
tag={tag}
availableInlineSizePx={mobileAvailableInlineSizePx}
materialFilter={materialFilter}
selectedTagId={selectedTagId}
openTags={openTags}
@@ -334,12 +483,6 @@ const MaterialSidebar: FC = () => {
<div className="hidden md:block">
<SidebarComponent>
<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
materialFilter={materialFilter}
onChange={handleFilterChange}/>
+9 -8
ファイルの表示
@@ -28,11 +28,12 @@ type Props =
const TagLink: FC<Props> = ({ tag,
nestLevel = 0,
linkFlg = true,
withWiki = true,
withCount = true,
...props }) => {
nestLevel = 0,
linkFlg = true,
withWiki = true,
withCount = true,
className,
...props }) => {
const spanClass = cn (
`text-${ TAG_COLOUR[tag.category] }-${ LIGHT_COLOUR_SHADE }`,
`dark:text-${ TAG_COLOUR[tag.category] }-${ DARK_COLOUR_SHADE }`)
@@ -105,7 +106,7 @@ const TagLink: FC<Props> = ({ tag,
</span>)}
{tag.matchedAlias != null && (
<>
<span className={spanClass} {...props}>
<span className={cn (spanClass, className)} {...props}>
{tag.matchedAlias}
</span>
<> </>
@@ -114,12 +115,12 @@ const TagLink: FC<Props> = ({ tag,
? (
<PrefetchLink
to={`/posts?${ (new URLSearchParams ({ tags: tag.name })).toString () }`}
className={linkClass}
className={cn (linkClass, className)}
{...props}>
{tag.name}
</PrefetchLink>)
: (
<span className={spanClass}
<span className={cn (spanClass, className)}
{...props}>
{tag.name}
</span>)}
+34 -14
ファイルの表示
@@ -7,30 +7,36 @@ import Separator from '@/components/MenuSeparator'
import PrefetchLink from '@/components/PrefetchLink'
import TopNavUser from '@/components/TopNavUser'
import { WikiIdBus } from '@/lib/eventBus/WikiIdBus'
import { tagsKeys, wikiKeys } from '@/lib/queryKeys'
import { materialsKeys, tagsKeys, wikiKeys } from '@/lib/queryKeys'
import { fetchTag, fetchTagByName } from '@/lib/tags'
import { fetchMaterial } from '@/lib/materials'
import { cn } from '@/lib/utils'
import { fetchWikiPage } from '@/lib/wiki'
import type { FC, MouseEvent } from 'react'
import type { Menu, MenuVisibleItem, Tag, User } from '@/types'
import type { Material, Menu, MenuVisibleItem, Tag, User } from '@/types'
type Props = { user: User | null }
export const menuOutline = ({ tag, wikiId, user, pathName }: {
tag?: Tag | null
wikiId: number | null
user: User | null,
pathName: string }): Menu => {
const postCount = tag?.postCount ?? 0
export const menuOutline = (
{ tag, material, wikiId, user, pathName }: {
tag?: Tag | null
material?: Material | null
wikiId: number | null
user: User | null,
pathName: string },
): Menu => {
const postCount = tag?.postCount ?? material?.tag?.postCount ?? 0
const wikiPageFlg = Boolean (/^\/wiki\/(?!new|changes)[^/]+/.test (pathName) && wikiId)
const wikiTitle = pathName.split ('/')[2] ?? ''
const tagFlg = /^\/tags\/\d+/.test (pathName)
const materialFlg = /^\/materials\/\d+/.test (pathName)
return [
{ name: '広場', to: '/posts', subMenu: [
{ name: '一覧', to: '/posts' },
@@ -49,12 +55,18 @@ export const menuOutline = ({ tag, wikiId, user, pathName }: {
visible: tagFlg },
{ name: '履歴', to: `/tags/changes?id=${ tag?.id }`,
visible: tagFlg && tag?.category !== 'nico' }] },
{ name: '素材', to: '/materials', visible: false, subMenu: [
{ name: '素材', to: '/materials', visible: true, subMenu: [
{ name: '一覧', to: '/materials' },
{ name: '検索', to: '/materials/search', visible: false },
{ name: '追加', to: '/materials/new' },
{ name: '全体履歴', to: '/materials/changes', visible: false },
{ name: 'ヘルプ', to: '/wiki/ヘルプ:素材集' }] },
{ name: '抑止', to: '/materials/suppressions' },
{ name: '全体履歴', to: '/materials/changes' },
{ 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: '検索', to: '/wiki' },
{ name: '新規', to: '/wiki/new' },
@@ -119,15 +131,23 @@ const TopNav: FC<Props> = ({ user }) => {
queryFn: () => fetchWikiPage (wikiIdStr, { }) })
const tagFlg = /^\/tags\/\d+/.test (location.pathname)
const effectiveTitle = (tagFlg ? location.pathname.split ('/')[2] : wikiPage?.title) ?? ''
const materialFlg = /^\/materials\/\d+/.test (location.pathname)
const effectiveTitle = (((tagFlg || materialFlg)
? location.pathname.split ('/')[2]
: wikiPage?.title)
?? '')
const { data: tag } = useQuery ({
enabled: Boolean (effectiveTitle),
queryKey: tagsKeys.show (effectiveTitle),
queryFn: () => (tagFlg ? fetchTag : fetchTagByName) (effectiveTitle) })
const { data: material } = useQuery ({
enabled: Boolean (effectiveTitle),
queryKey: materialsKeys.show (effectiveTitle),
queryFn: () => fetchMaterial (effectiveTitle) })
const menu = menuOutline ({ tag, wikiId, user, pathName: location.pathname })
const menu = menuOutline ({ tag, material, wikiId, user, pathName: location.pathname })
const visibleMenu = menu.filter ((item): item is MenuVisibleItem => item.visible ?? true)
const moreMenu = menu.filter (item =>
!(item.visible ?? true)
+5 -3
ファイルの表示
@@ -1,12 +1,14 @@
import React from 'react'
import { cn } from '@/lib/utils'
import type { FC } from 'react'
type Props = { children: React.ReactNode }
type Props = { children: React.ReactNode; className?: string }
const PageTitle: FC<Props> = ({ children }) => (
<h1 className="text-2xl font-bold mb-2">
const PageTitle: FC<Props> = ({ children, className, ...rest }) => (
<h1 className={cn ('text-2xl font-bold mb-2', className)} {...rest}>
{children}
</h1>)
+16 -25
ファイルの表示
@@ -1,41 +1,31 @@
import {
apiGet,
isApiError,
apiPost,
apiPut,
} from '@/lib/api'
import { apiGet, isApiError, apiPost, apiPut } from '@/lib/api'
import type {
Material,
MaterialIndexResponse,
MaterialVersion,
FetchMaterialsParams,
MaterialFilter,
MaterialSyncSuppression,
MaterialSidebarTag,
MaterialTagTree,
} from '@/types'
import type { Material,
MaterialIndexResponse,
MaterialVersion,
FetchMaterialsParams,
MaterialFilter,
MaterialSyncSuppression,
MaterialSidebarTag,
MaterialTagTree } from '@/types'
export type FetchMaterialTreeParams = {
parentId?: number | null
materialFilter: MaterialFilter
}
materialFilter: MaterialFilter }
export type MaterialSyncSuppressionResponse = {
suppressions: MaterialSyncSuppression[]
}
export type MaterialSyncSuppressionResponse = { suppressions: MaterialSyncSuppression[] }
export type MaterialChangesResponse = {
versions: MaterialVersion[]
count: number
}
count: number }
const MATERIAL_FILTERS: MaterialFilter[] = ['present', 'missing', 'any']
export const parseMaterialFilter = (
value: unknown,
fallback: MaterialFilter = 'present'): MaterialFilter =>
fallback: MaterialFilter = 'present',
): MaterialFilter =>
typeof value === 'string' && MATERIAL_FILTERS.includes (value as MaterialFilter)
? value as MaterialFilter
: fallback
@@ -45,7 +35,8 @@ export const fetchMaterials = async (
{ q, tagState, mediaKind, createdFrom, createdTo,
updatedFrom, updatedTo, sort, direction, page,
tagId, includeDescendants, groupBy,
limit }: FetchMaterialsParams): Promise<MaterialIndexResponse> =>
limit }: FetchMaterialsParams,
): Promise<MaterialIndexResponse> =>
await apiGet ('/materials', { params: {
...(q && { q }),
tag_state: tagState,
+4 -16
ファイルの表示
@@ -8,7 +8,6 @@ import WikiBody from '@/components/WikiBody'
import FieldError from '@/components/common/FieldError'
import FormField from '@/components/common/FormField'
import PageTitle from '@/components/common/PageTitle'
import PrefetchLink from '@/components/PrefetchLink'
import TabGroup, { Tab } from '@/components/common/TabGroup'
import TagInput from '@/components/common/TagInput'
import MainArea from '@/components/layout/MainArea'
@@ -119,12 +118,6 @@ const MaterialDetailPage: FC = () => {
: materialTitle}
</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) && (
(/image\/.*/.test (material.contentType) && (
<img src={material.file} alt={material.tag?.name || undefined}/>))
@@ -134,17 +127,12 @@ const MaterialDetailPage: FC = () => {
<audio src={material.file} controls/>)))}
<TabGroup>
<Tab name="Wiki">
{material.tag
? (
{material.tag && (
<Tab name="Wiki">
<WikiBody
title={material.tag.name}
body={material.wikiPageBody ?? undefined}/>)
: (
<p className="text-stone-700 dark:text-stone-300">
</p>)}
</Tab>
body={material.wikiPageBody ?? undefined}/>
</Tab>)}
<Tab name="編輯">
<div className="max-w-wl space-y-4 pt-2">
+1 -25
ファイルの表示
@@ -80,14 +80,7 @@ const MaterialHistoryPage: FC = () => {
</Helmet>
<div className="space-y-5">
<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>
<PageTitle></PageTitle>
<form
onSubmit={handleSearch}
@@ -112,20 +105,6 @@ const MaterialHistoryPage: FC = () => {
onChange={e => setTagInput (e.target.value)}
className={inputClass (invalid)}/>)}
</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>
<button
@@ -150,7 +129,6 @@ const MaterialHistoryPage: FC = () => {
<table className="w-full min-w-[1200px] table-fixed border-collapse">
<colgroup>
<col className="w-48"/>
<col className="w-32"/>
<col className="w-28"/>
<col className="w-24"/>
<col className="w-64"/>
@@ -163,7 +141,6 @@ const MaterialHistoryPage: FC = () => {
<thead className="border-b-2 border-black dark:border-white">
<tr>
<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"></th>
<th className="p-2 text-left"></th>
@@ -180,7 +157,6 @@ const MaterialHistoryPage: FC = () => {
key={version.id}
className="even:bg-gray-100 dark:even:bg-gray-700">
<td className="p-2">{dateString (version.createdAt)}</td>
<td className="p-2">{version.eventType}</td>
<td className="p-2">
<PrefetchLink to={`/materials/${ version.materialId }`}>
#{version.materialId}
+60 -9
ファイルの表示
@@ -33,15 +33,7 @@ describe ('MaterialListPage', () => {
} },
)
})
expect (await screen.findByText ('素材はありません')).toBeInTheDocument ()
expect (screen.getByRole ('link', { name: '新規素材を追加' })).toHaveAttribute (
'href',
'/materials/new',
)
expect (screen.getByRole ('link', { name: '履歴' })).toHaveAttribute (
'href',
'/materials/changes',
)
expect (await screen.findByText ('素材はありません')).toBeInTheDocument ()
})
it ('shows materials in the default card view', async () => {
@@ -126,4 +118,63 @@ describe ('MaterialListPage', () => {
expect (screen.getByText ('サイズ:')).toBeInTheDocument ()
expect (screen.getByText ('2.0 KB')).toBeInTheDocument ()
})
it ('shows the selected tag scope and tag-specific add links', async () => {
api.apiGet.mockResolvedValueOnce ({
materials: [
buildMaterial ({
id: 10,
tag: buildTag ({ id: 30, name: '泣き', category: 'material' }),
}),
],
count: 1,
tagScope: {
tag: { id: 20, name: '伊地知ニジカ', category: 'material' },
includeDescendants: true,
},
groups: [
{
key: 'tag:30',
tag: { id: 30, name: '泣き', category: 'material' },
materialIds: [10],
count: 1,
},
],
})
renderWithProviders (
<MaterialListPage/>,
{ route: '/materials?tag_id=20&include_descendants=1&group_by=parent_tag' },
)
expect (await screen.findByText (
(_, element) => element?.textContent === '伊地知ニジカ 配下の素材を表示中',
)).toBeInTheDocument ()
expect (screen.getByRole ('link', { name: '泣き' })).toHaveAttribute (
'href',
'/materials?tag_id=30&include_descendants=1&group_by=parent_tag&material_filter=present',
)
expect (screen.getByRole ('link', { name: 'タグ選択を解除' })).toHaveAttribute (
'href',
'/materials?material_filter=present',
)
})
it ('shows a clear link when tag_id does not resolve to tag_scope', async () => {
api.apiGet.mockResolvedValueOnce ({
materials: [],
count: 0,
tagScope: null,
groups: [],
})
renderWithProviders (<MaterialListPage/>, { route: '/materials?tag_id=999' })
expect (await screen.findByText ('選択中タグが見つかりません.')).toBeInTheDocument ()
expect (screen.getByRole ('link', { name: 'タグ選択を解除' })).toHaveAttribute (
'href',
'/materials?material_filter=present',
)
})
})
+63 -89
ファイルの表示
@@ -10,24 +10,23 @@ import FormField from '@/components/common/FormField'
import PageTitle from '@/components/common/PageTitle'
import Pagination from '@/components/common/Pagination'
import MainArea from '@/components/layout/MainArea'
import { API_BASE_URL, SITE_TITLE } from '@/config'
import { SITE_TITLE } from '@/config'
import { fetchMaterials, parseMaterialFilter } from '@/lib/materials'
import { materialsKeys } from '@/lib/queryKeys'
import { dateString, inputClass } from '@/lib/utils'
import type { FC, FormEvent } from 'react'
import type {
FetchMaterialsParams,
Material,
MaterialFilter,
MaterialIndexGroup,
MaterialIndexGroupBy,
MaterialIndexDirection,
MaterialIndexMediaKind,
MaterialIndexSort,
MaterialIndexTagState,
MaterialIndexView } from '@/types'
import type { FetchMaterialsParams,
Material,
MaterialFilter,
MaterialIndexGroup,
MaterialIndexGroupBy,
MaterialIndexDirection,
MaterialIndexMediaKind,
MaterialIndexSort,
MaterialIndexTagState,
MaterialIndexView } from '@/types'
const MEDIA_KIND_LABELS: Record<Material['mediaKind'], string> = {
image: '画像',
@@ -42,20 +41,16 @@ const MEDIA_FILTER_LABELS: Record<MaterialIndexMediaKind, string> = {
video: '動画',
audio: '音声',
file_other: 'その他ファイル',
url_only: 'URL のみ'}
url_only: '外部リンクのみ'}
const SORT_LABELS: Record<MaterialIndexSort, string> = {
created_at: '作成日時',
updated_at: '更新日時',
tag_name: 'タグ名',
media_kind: '種類',
file_byte_size: 'ファイルサイズ',
version_no: 'バージョン',
id: 'ID'}
const GROUP_BY_LABELS: Record<MaterialIndexGroupBy, string> = {
none: 'オフ',
parent_tag: '親タグ'}
file_byte_size: '容量',
version_no: '',
id: 'Id.'}
const setIf = (qs: URLSearchParams, key: string, value: string | null) => {
@@ -88,25 +83,28 @@ const materialTitle = (material: Material): string =>
const groupedTagPath = (
tagId: number,
materialFilter: MaterialFilter): string =>
materialFilter: MaterialFilter,
): string =>
`/materials?tag_id=${ tagId }&include_descendants=1&group_by=parent_tag`
+ `&material_filter=${ materialFilter }`
const materialNewPath = (
tagName: string,
returnTo: string): string =>
returnTo: string,
): string =>
`/materials/new?tag=${ encodeURIComponent (tagName) }`
+ `&return_to=${ encodeURIComponent (returnTo) }`
const clearedTagSelectionPath = (
locationSearch: string,
materialFilter: MaterialFilter): string => {
materialFilter: MaterialFilter,
): string => {
const qs = new URLSearchParams (locationSearch)
qs.delete ('tag_id')
qs.delete ('include_descendants')
qs.set ('group_by', 'none')
qs.delete ('group_by')
qs.delete ('page')
qs.set ('material_filter', materialFilter)
return `/materials?${ qs.toString () }`
@@ -120,7 +118,7 @@ const MaterialThumb: FC<{ material: Material }> = ({ material }) => (
text-stone-900 shadow-sm dark:border-stone-700 dark:bg-stone-900
dark:text-stone-100`}>
{material.thumbnail
? <img src={material.thumbnail} alt="" className="h-full w-full object-contain"/>
? <img src={material.thumbnail} alt="" className="block h-full w-full object-cover"/>
: (
<span
className="px-2 text-2xl leading-tight"
@@ -191,27 +189,22 @@ const MaterialListItem: FC<{ material: Material }> = ({ material }) => (
const GroupHeading: FC<{
count: number
materialFilter: MaterialFilter
returnTo: string
title: string
tagId: number
}> = ({ count, materialFilter, returnTo, title, tagId }) => (
<div className="flex flex-wrap items-center gap-2 border-b border-stone-200 pb-2
}> = ({ count, materialFilter, title, tagId }) => (
<div className="flex items-center gap-2 border-b border-stone-200 pb-2
dark:border-stone-700">
<PrefetchLink
to={groupedTagPath (tagId, materialFilter)}
className="font-medium text-sky-700 underline underline-offset-2
dark:text-sky-300">
dark:text-sky-300 w-full">
{title}
</PrefetchLink>
<span className="text-sm text-stone-600 dark:text-stone-300">
{count}
</span>
<PrefetchLink
to={materialNewPath (title, returnTo)}
className="text-sm text-sky-700 underline underline-offset-2
dark:text-sky-300">
</PrefetchLink>
<div className="text-right w-auto">
<span className="text-nowrap text-sm text-stone-600 dark:text-stone-300">
{count}
</span>
</div>
</div>)
@@ -383,8 +376,7 @@ const MaterialListPage: FC = () => {
tagId={group.tag.id}
title={group.tag.name}
count={group.count}
materialFilter={materialFilter}
returnTo={location.pathname + location.search}/>
materialFilter={materialFilter}/>
{renderMaterialCollection (groupMaterials)}
</section>)
})}
@@ -410,35 +402,15 @@ const MaterialListPage: FC = () => {
src: url(${ nikumaru }) format('opentype');
}`}
</style>
<title>{`素材一覧 | ${ SITE_TITLE }`}</title>
<title>{`素材管理 | ${ SITE_TITLE }`}</title>
</Helmet>
<div className="space-y-5">
<div className="flex flex-wrap items-center justify-between gap-3">
<PageTitle></PageTitle>
<PageTitle className="my-auto"></PageTitle>
<div className="flex flex-wrap gap-2">
<PrefetchLink
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
{/* TODO: 局所出力を可能にする */}
{/* <a
href={`${ API_BASE_URL }/materials/download.zip?profile=legacy_drive`}
target="_blank"
rel="noopener noreferrer"
@@ -446,7 +418,7 @@ const MaterialListPage: FC = () => {
text-stone-900 hover:bg-stone-100 dark:border-stone-700
dark:bg-stone-900 dark:text-stone-100 dark:hover:bg-stone-800">
ZIP
</a>
</a> */}
</div>
</div>
@@ -458,12 +430,6 @@ const MaterialListPage: FC = () => {
{tagScope.tag.name}
{tagScope.includeDescendants ? ' 配下の素材を表示中' : ' の素材を表示中'}
</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
to={clearedTagSelectionPath (location.search, materialFilter)}
className="font-medium underline underline-offset-2
@@ -471,6 +437,18 @@ const MaterialListPage: FC = () => {
</PrefetchLink>
</div>)}
{(tagId != null && tagScope == null) && (
<div className="flex flex-wrap items-center gap-3 rounded-lg border
border-amber-200 bg-amber-50 px-4 py-3 text-sm text-amber-900
dark:border-amber-800 dark:bg-amber-950 dark:text-amber-100">
<span></span>
<PrefetchLink
to={clearedTagSelectionPath (location.search, materialFilter)}
className="font-medium underline underline-offset-2
text-amber-800 dark:text-amber-200">
</PrefetchLink>
</div>)}
{tagState === 'untagged' && (
<PrefetchLink
@@ -522,21 +500,6 @@ const MaterialListPage: FC = () => {
</select>)}
</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="作成日時">
{() => (
<div className="flex flex-wrap items-center gap-2">
@@ -579,7 +542,7 @@ const MaterialListPage: FC = () => {
: [
'border-stone-300 bg-white text-stone-900 dark:border-stone-700',
'dark:bg-stone-900 dark:text-stone-100'].join (' ') }`}>
</button>
<button
type="button"
@@ -592,7 +555,7 @@ const MaterialListPage: FC = () => {
: [
'border-stone-300 bg-white text-stone-900 dark:border-stone-700',
'dark:bg-stone-900 dark:text-stone-100'].join (' ') }`}>
</button>
</div>
@@ -620,7 +583,18 @@ const MaterialListPage: FC = () => {
{isError && (
<p className="text-red-600 dark:text-red-300"></p>)}
{(!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 && (
groupBy === 'parent_tag' && groups.length > 0
? renderGroupedMaterials (groups)
+52
ファイルの表示
@@ -1,5 +1,6 @@
import { fireEvent, screen, waitFor } from '@testing-library/react'
import { beforeEach, describe, expect, it, vi } from 'vitest'
import { Route, Routes, useLocation } from 'react-router-dom'
import MaterialNewPage from '@/pages/materials/MaterialNewPage'
import { renderWithProviders } from '@/test/render'
@@ -17,6 +18,11 @@ const toastApi = vi.hoisted (() => ({
vi.mock ('@/lib/api', () => api)
vi.mock ('@/components/ui/use-toast', () => toastApi)
const LocationView = () => {
const location = useLocation ()
return <div>{location.pathname + location.search}</div>
}
describe ('MaterialNewPage', () => {
beforeEach (() => {
vi.clearAllMocks ()
@@ -69,4 +75,50 @@ describe ('MaterialNewPage', () => {
expect (await screen.findAllByText ('ファイルまたは URL は必須です.')).toHaveLength (2)
expect (screen.getAllByRole ('textbox')[1]).toHaveAttribute ('aria-invalid', 'true')
})
it ('returns only to safe material URLs after successful creation', async () => {
api.apiPost.mockResolvedValueOnce ({})
renderWithProviders (
<Routes>
<Route path="/materials/new" element={<MaterialNewPage/>}/>
<Route path="/materials" element={<LocationView/>}/>
</Routes>,
{
route:
'/materials/new?tag=%E8%99%B9%E5%A4%8F'
+ '&return_to=%2Fmaterials%3Ftag_id%3D20',
},
)
fireEvent.change (screen.getAllByRole ('textbox')[1], {
target: { value: 'https://example.com/ref' },
})
fireEvent.click (screen.getByRole ('button', { name: '追加' }))
expect (await screen.findByText ('/materials?tag_id=20')).toBeInTheDocument ()
})
it ('ignores unsafe return_to values after successful creation', async () => {
api.apiPost.mockResolvedValueOnce ({})
renderWithProviders (
<Routes>
<Route path="/materials/new" element={<MaterialNewPage/>}/>
<Route path="/materials" element={<LocationView/>}/>
</Routes>,
{
route:
'/materials/new?tag=%E8%99%B9%E5%A4%8F'
+ '&return_to=https%3A%2F%2Fexample.com%2Fevil',
},
)
fireEvent.change (screen.getAllByRole ('textbox')[1], {
target: { value: 'https://example.com/ref' },
})
fireEvent.click (screen.getByRole ('button', { name: '追加' }))
expect (await screen.findByText ('/materials')).toBeInTheDocument ()
})
})
+2 -1
ファイルの表示
@@ -28,6 +28,7 @@ const MaterialNewPage: FC = () => {
const query = new URLSearchParams (location.search)
const tagQuery = query.get ('tag') ?? ''
const returnToQuery = query.get ('return_to') ?? ''
const safeReturnTo = returnToQuery.startsWith ('/materials') ? returnToQuery : ''
const navigate = useNavigate ()
@@ -55,7 +56,7 @@ const MaterialNewPage: FC = () => {
onSuccess: async () => {
await qc.invalidateQueries ({ queryKey: materialsKeys.root })
toast ({ title: '送信成功!' })
navigate (returnToQuery || `/materials?tag=${ encodeURIComponent (tag) }`)
navigate (safeReturnTo || '/materials')
},
onError: error => {
applyValidationError (error)
-51
ファイルの表示
@@ -1,51 +0,0 @@
import { useState } from 'react'
import { Helmet } from 'react-helmet-async'
import FormField from '@/components/common/FormField'
import PageTitle from '@/components/common/PageTitle'
import TagInput from '@/components/common/TagInput'
import MainArea from '@/components/layout/MainArea'
import { SITE_TITLE } from '@/config'
import type { FC, FormEvent } from 'react'
const MaterialSearchPage: FC = () => {
const [tagName, setTagName] = useState ('')
const [parentTagName, setParentTagName] = useState ('')
const handleSearch = (e: FormEvent) => {
e.preventDefault ()
}
return (
<MainArea>
<Helmet>
<title> | {SITE_TITLE}</title>
</Helmet>
<div className="max-w-xl">
<PageTitle></PageTitle>
<form onSubmit={handleSearch} className="space-y-2">
{/* タグ */}
<FormField label="タグ">
{() => (
<TagInput
value={tagName}
setValue={setTagName}/>)}
</FormField>
{/* 親タグ */}
<FormField label="親タグ">
{() => (
<TagInput
value={parentTagName}
setValue={setParentTagName}/>)}
</FormField>
</form>
</div>
</MainArea>)
}
export default MaterialSearchPage
+34 -28
ファイルの表示
@@ -2,17 +2,13 @@ import { useMutation, useQuery, useQueryClient } from '@tanstack/react-query'
import { useState } from 'react'
import { Helmet } from 'react-helmet-async'
import PrefetchLink from '@/components/PrefetchLink'
import FormField from '@/components/common/FormField'
import PageTitle from '@/components/common/PageTitle'
import MainArea from '@/components/layout/MainArea'
import { Button } from '@/components/ui/button'
import { toast } from '@/components/ui/use-toast'
import { SITE_TITLE } from '@/config'
import {
createMaterialSyncSuppression,
fetchMaterialSyncSuppressions,
} from '@/lib/materials'
import { createMaterialSyncSuppression, fetchMaterialSyncSuppressions } from '@/lib/materials'
import { materialsKeys } from '@/lib/queryKeys'
import { dateString, inputClass } from '@/lib/utils'
@@ -22,11 +18,11 @@ import type { MaterialSyncSuppressionSourceKind } from '@/types'
const SOURCE_KIND_LABELS: Record<MaterialSyncSuppressionSourceKind, string> = {
uri: 'URI',
google_drive_path: 'Google Drive path',
google_drive_path_prefix: 'Google Drive path prefix',
google_drive_file: 'Google Drive file ID',
legacy_drive_path: 'Legacy Drive path',
legacy_drive_path_prefix: 'Legacy Drive path prefix'}
google_drive_path: 'Google Drive ファイル',
google_drive_path_prefix: 'Google Drive フォルダ',
google_drive_file: 'Google Drive ファイル Id.',
legacy_drive_path: '汎用ファイル',
legacy_drive_path_prefix: '汎用フォルダ' }
const REASONS = [
'copyright_high_risk',
@@ -36,7 +32,23 @@ const REASONS = [
'malware_or_dangerous_file',
'duplicate_or_low_quality',
'source_owner_request',
'other']
'other'] as const
type MaterialSyncSuppressionReason = typeof REASONS[number]
const REASON_NAMES: Record<MaterialSyncSuppressionReason, string> = {
['copyright_high_risk']: '著作権への懸念',
['copyright_takedown']: '著作者からの申出',
['adult_or_sensitive']: '成人向け',
['personal_information']: '個人情報',
['malware_or_dangerous_file']: '危険なソフトウェア',
['duplicate_or_low_quality']: '重複',
['source_owner_request']: '同期元管理者からの申出',
['other']: 'その他' } as const
const reasonName = (reason: string): string =>
REASON_NAMES[reason as MaterialSyncSuppressionReason] ?? reason
const MaterialSyncSuppressionsPage: FC = () => {
@@ -46,7 +58,7 @@ const MaterialSyncSuppressionsPage: FC = () => {
const [sourceUri, setSourceUri] = useState ('')
const [drivePath, setDrivePath] = useState ('')
const [driveFileId, setDriveFileId] = useState ('')
const [reason, setReason] = useState (REASONS[0])
const [reason, setReason] = useState<MaterialSyncSuppressionReason> (REASONS[0])
const { data, isError, isLoading } = useQuery ({
queryKey: materialsKeys.suppressions (),
@@ -82,18 +94,11 @@ const MaterialSyncSuppressionsPage: FC = () => {
return (
<MainArea>
<Helmet>
<title>{`同期抑止 | ${ SITE_TITLE }`}</title>
<title>{`素材同期抑止 | ${ SITE_TITLE }`}</title>
</Helmet>
<div className="space-y-5">
<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>
<PageTitle></PageTitle>
<form
onSubmit={handleSubmit}
@@ -115,7 +120,7 @@ const MaterialSyncSuppressionsPage: FC = () => {
</select>)}
</FormField>
<FormField label="Source URI">
<FormField label="同期元 URI">
{({ invalid }) => (
<input
type="text"
@@ -124,7 +129,7 @@ const MaterialSyncSuppressionsPage: FC = () => {
className={inputClass (invalid)}/>)}
</FormField>
<FormField label="Drive path">
<FormField label="Google Drive パス">
{({ invalid }) => (
<input
type="text"
@@ -133,7 +138,7 @@ const MaterialSyncSuppressionsPage: FC = () => {
className={inputClass (invalid)}/>)}
</FormField>
<FormField label="Drive file ID">
<FormField label="Google Drive ファイル Id.">
{({ invalid }) => (
<input
type="text"
@@ -142,15 +147,15 @@ const MaterialSyncSuppressionsPage: FC = () => {
className={inputClass (invalid)}/>)}
</FormField>
<FormField label="由">
<FormField label="由">
{({ invalid }) => (
<select
value={reason}
onChange={e => setReason (e.target.value)}
onChange={e => setReason (e.target.value as MaterialSyncSuppressionReason)}
className={inputClass (invalid)}>
{REASONS.map (value => (
<option key={value} value={value}>
{value}
{REASON_NAMES[value]}
</option>))}
</select>)}
</FormField>
@@ -185,7 +190,8 @@ const MaterialSyncSuppressionsPage: FC = () => {
{suppression.normalizedSourceKey}
</div>
<div className="mt-2 text-sm text-stone-600 dark:text-stone-400">
: {suppression.reason} / : {dateString (suppression.createdAt)}
: {reasonName (suppression.reason)} /
: {dateString (suppression.createdAt)}
</div>
</article>))}
</div>