コミットを比較
9 コミット
| 作成者 | SHA1 | 日付 | |
|---|---|---|---|
| 8304909c8c | |||
| 377a09ed70 | |||
| c10ba7a698 | |||
| fa6c547cc9 | |||
| dbc654f346 | |||
| c2102c8f96 | |||
| 510cbb0d78 | |||
| a820ce4c3e | |||
| 507ce1680e |
@@ -271,12 +271,7 @@ 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.
|
||||
- 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 parenthesis 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
|
||||
the closing brace at the beginning of a line. Function, lambda, callback, and
|
||||
|
||||
@@ -35,11 +35,6 @@ class MaterialVersionsController < ApplicationController
|
||||
tag_name: row.tag_name,
|
||||
tag_category: row.tag_category,
|
||||
url: row.url,
|
||||
source_kind: row.source_kind,
|
||||
source_uri: row.source_uri,
|
||||
source_path: row.source_path,
|
||||
source_file_id: row.source_file_id,
|
||||
normalized_source_key: row.normalized_source_key,
|
||||
file_blob_id: row.file_blob_id,
|
||||
file_filename: row.file_filename,
|
||||
file_content_type: row.file_content_type,
|
||||
|
||||
@@ -1,6 +1,3 @@
|
||||
require 'set'
|
||||
|
||||
|
||||
class MaterialsController < ApplicationController
|
||||
rescue_from MaterialZipExporter::EmptyExportError, with: :render_zip_empty
|
||||
rescue_from MaterialZipExporter::DuplicatePathError, with: :render_zip_duplicate_path
|
||||
@@ -16,14 +13,12 @@ class MaterialsController < ApplicationController
|
||||
offset = (page - 1) * limit
|
||||
|
||||
filters = material_index_filters
|
||||
tag_graph = material_index_tag_graph(filters)
|
||||
q = Material.includes(:material_export_items,
|
||||
thumbnail_attachment: :blob,
|
||||
file_attachment: :blob,
|
||||
tag: :tag_name)
|
||||
q = q.where(tag_id: nil) if filters[:tag_state] == 'untagged'
|
||||
q = q.where.not(tag_id: nil) if filters[:tag_state] == 'tagged'
|
||||
q = apply_material_tag_filter(q, filters, tag_graph)
|
||||
q = q.where('materials.created_at >= ?', filters[:created_from]) if filters[:created_from]
|
||||
q = q.where('materials.created_at <= ?', filters[:created_to]) if filters[:created_to]
|
||||
q = q.where('materials.updated_at >= ?', filters[:updated_from]) if filters[:updated_from]
|
||||
@@ -42,16 +37,8 @@ class MaterialsController < ApplicationController
|
||||
.offset(offset)
|
||||
.to_a
|
||||
|
||||
response = { materials: MaterialRepr.list_many(materials, host: request.base_url),
|
||||
count: }
|
||||
if filters[:tag_id]
|
||||
response[:tag_scope] = material_index_tag_scope(filters, tag_graph)
|
||||
end
|
||||
if filters[:group_by] == 'parent_tag'
|
||||
response[:groups] = material_index_groups(materials, tag_graph)
|
||||
end
|
||||
|
||||
render json: response
|
||||
render json: { materials: MaterialRepr.list_many(materials, host: request.base_url),
|
||||
count: }
|
||||
end
|
||||
|
||||
def show
|
||||
@@ -211,18 +198,9 @@ class MaterialsController < ApplicationController
|
||||
direction = params[:direction].to_s.downcase
|
||||
direction = 'desc' unless ['asc', 'desc'].include?(direction)
|
||||
|
||||
group_by = params[:group_by].to_s.presence
|
||||
group_by = 'none' unless ['none', 'parent_tag'].include?(group_by)
|
||||
|
||||
tag_id = params[:tag_id].to_i
|
||||
tag_id = nil if tag_id <= 0
|
||||
|
||||
{ q: params[:q].to_s.strip.presence,
|
||||
tag_state:,
|
||||
media_kind:,
|
||||
tag_id:,
|
||||
include_descendants: bool?(:include_descendants),
|
||||
group_by:,
|
||||
created_from: parse_time_param(:created_from),
|
||||
created_to: parse_time_param(:created_to),
|
||||
updated_from: parse_time_param(:updated_from),
|
||||
@@ -292,147 +270,6 @@ class MaterialsController < ApplicationController
|
||||
end
|
||||
end
|
||||
|
||||
def apply_material_tag_filter q, filters, tag_graph
|
||||
return q unless filters[:tag_id]
|
||||
|
||||
tag_ids =
|
||||
if tag_graph
|
||||
tag_graph[:scope_tag_ids]
|
||||
else
|
||||
[filters[:tag_id]]
|
||||
end
|
||||
|
||||
q.where(tag_id: tag_ids)
|
||||
end
|
||||
|
||||
def material_index_tag_graph filters
|
||||
return nil unless filters[:tag_id]
|
||||
|
||||
children_by_parent_id = Hash.new { |h, k| h[k] = [] }
|
||||
TagImplication.pluck(:parent_tag_id, :tag_id).each do |parent_id, child_id|
|
||||
children_by_parent_id[parent_id] << child_id
|
||||
end
|
||||
|
||||
scope_tag_ids =
|
||||
if filters[:include_descendants]
|
||||
collect_material_descendant_ids(filters[:tag_id], children_by_parent_id)
|
||||
else
|
||||
Set.new([filters[:tag_id]])
|
||||
end
|
||||
tags_by_id =
|
||||
Tag
|
||||
.joins(:tag_name)
|
||||
.where(id: scope_tag_ids)
|
||||
.pluck('tags.id', 'tag_names.name', 'tags.category', 'tags.deprecated_at')
|
||||
.each_with_object({ }) do |(id, name, category, deprecated_at), hash|
|
||||
hash[id] = { id:, name:, category:, deprecated: deprecated_at.present? }
|
||||
end
|
||||
|
||||
selected_tag = tags_by_id[filters[:tag_id]]
|
||||
return nil unless selected_tag
|
||||
|
||||
group_tag_id_by_tag_id = { }
|
||||
children_by_parent_id[filters[:tag_id]].each do |child_tag_id|
|
||||
assign_material_group_branch(child_tag_id,
|
||||
children_by_parent_id:,
|
||||
tags_by_id:,
|
||||
group_tag_id_by_tag_id:,
|
||||
current_group_tag_id: nil,
|
||||
seen: Set.new([filters[:tag_id]]))
|
||||
end
|
||||
|
||||
{ selected_tag_id: filters[:tag_id],
|
||||
selected_tag:,
|
||||
scope_tag_ids: scope_tag_ids.to_a,
|
||||
tags_by_id:,
|
||||
group_tag_id_by_tag_id: }
|
||||
end
|
||||
|
||||
def collect_material_descendant_ids selected_tag_id, children_by_parent_id
|
||||
ids = Set.new([selected_tag_id])
|
||||
stack = [selected_tag_id]
|
||||
|
||||
until stack.empty?
|
||||
tag_id = stack.pop
|
||||
children_by_parent_id[tag_id].each do |child_tag_id|
|
||||
next if ids.include?(child_tag_id)
|
||||
|
||||
ids << child_tag_id
|
||||
stack << child_tag_id
|
||||
end
|
||||
end
|
||||
|
||||
ids
|
||||
end
|
||||
|
||||
def assign_material_group_branch tag_id, children_by_parent_id:, tags_by_id:,
|
||||
group_tag_id_by_tag_id:, current_group_tag_id:, seen:
|
||||
return if seen.include?(tag_id)
|
||||
|
||||
tag = tags_by_id[tag_id]
|
||||
return unless tag
|
||||
|
||||
seen = seen.dup << tag_id
|
||||
next_group_tag_id = current_group_tag_id
|
||||
next_group_tag_id = tag_id if next_group_tag_id.nil? && !tag[:deprecated]
|
||||
group_tag_id_by_tag_id[tag_id] = next_group_tag_id if next_group_tag_id
|
||||
|
||||
children_by_parent_id[tag_id].each do |child_tag_id|
|
||||
assign_material_group_branch(child_tag_id,
|
||||
children_by_parent_id:,
|
||||
tags_by_id:,
|
||||
group_tag_id_by_tag_id:,
|
||||
current_group_tag_id: next_group_tag_id,
|
||||
seen:)
|
||||
end
|
||||
end
|
||||
|
||||
def material_index_groups materials, tag_graph
|
||||
return [] unless tag_graph
|
||||
|
||||
groups_by_key = { }
|
||||
|
||||
materials.each do |material|
|
||||
next unless material.tag_id
|
||||
|
||||
group_tag_id =
|
||||
if material.tag_id == tag_graph[:selected_tag_id]
|
||||
tag_graph[:selected_tag_id]
|
||||
else
|
||||
tag_graph[:group_tag_id_by_tag_id][material.tag_id] || tag_graph[:selected_tag_id]
|
||||
end
|
||||
|
||||
group_tag = tag_graph[:tags_by_id][group_tag_id]
|
||||
next unless group_tag
|
||||
|
||||
key = "tag:#{ group_tag_id }"
|
||||
group =
|
||||
groups_by_key[key] ||= { key:,
|
||||
tag: group_tag_repr(group_tag),
|
||||
material_ids: [],
|
||||
count: 0 }
|
||||
group[:material_ids] << material.id
|
||||
group[:count] += 1
|
||||
end
|
||||
|
||||
groups_by_key.values.sort_by { |group| group[:tag][:name] }
|
||||
end
|
||||
|
||||
def material_index_tag_scope filters, tag_graph
|
||||
return nil unless tag_graph
|
||||
|
||||
{
|
||||
tag: group_tag_repr(tag_graph[:selected_tag]),
|
||||
include_descendants: filters[:include_descendants]
|
||||
}
|
||||
end
|
||||
|
||||
def group_tag_repr group_tag
|
||||
{ id: group_tag[:id],
|
||||
name: group_tag[:name],
|
||||
category: group_tag[:category] }
|
||||
end
|
||||
|
||||
def material_index_order_sql filters
|
||||
direction = filters[:direction] == 'asc' ? 'ASC' : 'DESC'
|
||||
sort_sql =
|
||||
@@ -523,7 +360,10 @@ class MaterialsController < ApplicationController
|
||||
content_type: file.content_type,
|
||||
)
|
||||
|
||||
MaterialFileSha256.assign_metadata_sha256!(blob, file_sha256)
|
||||
if file_sha256.present?
|
||||
blob.metadata['sha256'] = file_sha256
|
||||
blob.save! if blob.changed?
|
||||
end
|
||||
|
||||
blob
|
||||
ensure
|
||||
|
||||
@@ -140,11 +140,10 @@ class PostsController < ApplicationController
|
||||
original_created_from = params[:original_created_from]
|
||||
original_created_before = params[:original_created_before]
|
||||
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,
|
||||
original_created_from:, original_created_before:)
|
||||
post.thumbnail.attach(resized_thumbnail) if resized_thumbnail
|
||||
post.thumbnail.attach(thumbnail) if thumbnail.present?
|
||||
|
||||
ApplicationRecord.transaction do
|
||||
post.save!
|
||||
@@ -157,6 +156,8 @@ class PostsController < ApplicationController
|
||||
|
||||
sync_parent_posts!(post, parent_post_ids)
|
||||
|
||||
post.resized_thumbnail!
|
||||
|
||||
PostVersionRecorder.record!(post:, event_type: :create, created_by_user: current_user)
|
||||
end
|
||||
|
||||
@@ -166,8 +167,6 @@ class PostsController < ApplicationController
|
||||
render_validation_error fields: { tags: 'ニコニコ・タグは直接指定できません.' }
|
||||
rescue Tag::DeprecatedTagNormalisationError
|
||||
render_unprocessable_entity '廃止済みタグは付与できません.', field: :tags
|
||||
rescue MiniMagick::Error
|
||||
render_validation_error fields: { thumbnail: ['サムネイル画像の変換に失敗しました.'] }
|
||||
rescue ArgumentError => e
|
||||
render_validation_error fields: { parent_post_ids: [e.message] }
|
||||
rescue ActiveRecord::RecordInvalid => e
|
||||
|
||||
@@ -379,20 +379,12 @@ class TagsController < ApplicationController
|
||||
end
|
||||
|
||||
def visible_root_tag_ids graph
|
||||
root_ids = Set.new
|
||||
|
||||
graph[:tags_by_id].each do |tag_id, attrs|
|
||||
graph[:tags_by_id].filter_map do |tag_id, _attrs|
|
||||
next unless visible_root_tag?(tag_id, graph)
|
||||
next unless visible_subtree?(tag_id, graph)
|
||||
|
||||
if attrs[:deprecated]
|
||||
collect_visible_child_tag_ids(tag_id, graph, root_ids, Set.new)
|
||||
else
|
||||
root_ids << tag_id
|
||||
end
|
||||
tag_id
|
||||
end
|
||||
|
||||
root_ids.to_a
|
||||
end
|
||||
|
||||
def visible_root_tag? tag_id, graph
|
||||
|
||||
@@ -1,9 +1,6 @@
|
||||
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
|
||||
@@ -23,7 +20,7 @@ class Material < ApplicationRecord
|
||||
|
||||
validates :tag_id, uniqueness: true, allow_nil: true
|
||||
validates :source_kind,
|
||||
inclusion: { in: SOURCE_KINDS },
|
||||
inclusion: { in: MaterialSyncSuppression::SOURCE_KINDS },
|
||||
allow_blank: true
|
||||
|
||||
validate :file_must_be_attached
|
||||
|
||||
@@ -1,13 +1,11 @@
|
||||
class MaterialSyncSource < ApplicationRecord
|
||||
SOURCE_KINDS = ['uri', 'google_drive_path', 'google_drive_file', 'legacy_drive_path'].freeze
|
||||
|
||||
belongs_to :created_by_user, class_name: 'User', optional: true
|
||||
belongs_to :updated_by_user, class_name: 'User', optional: true
|
||||
|
||||
validates :name, presence: true
|
||||
validates :source_kind,
|
||||
presence: true,
|
||||
inclusion: { in: SOURCE_KINDS }
|
||||
inclusion: { in: MaterialSyncSuppression::SOURCE_KINDS }
|
||||
validates :profile, presence: true, inclusion: { in: MaterialExportItem::VALID_PROFILES }
|
||||
validate :source_value_must_be_present
|
||||
|
||||
@@ -35,7 +33,7 @@ class MaterialSyncSource < ApplicationRecord
|
||||
when 'google_drive_file'
|
||||
source_file_id.present? || source_uri.present?
|
||||
when 'google_drive_path'
|
||||
source_file_id.present? || source_uri.present?
|
||||
source_file_id.present? || source_uri.present? || source_path.present?
|
||||
when 'legacy_drive_path'
|
||||
source_path.present?
|
||||
else
|
||||
|
||||
@@ -1,19 +1,5 @@
|
||||
class Post < ApplicationRecord
|
||||
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
|
||||
|
||||
@@ -101,7 +87,12 @@ class Post < ApplicationRecord
|
||||
def resized_thumbnail!
|
||||
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
|
||||
|
||||
private
|
||||
|
||||
@@ -11,7 +11,6 @@ module GoogleDrive
|
||||
DRIVE_ENDPOINT = 'https://www.googleapis.com/drive/v3'
|
||||
TOKEN_ENDPOINT = 'https://oauth2.googleapis.com/token'
|
||||
FOLDER_MIME_TYPE = 'application/vnd.google-apps.folder'
|
||||
NATIVE_FILE_MIME_TYPE_PREFIX = 'application/vnd.google-apps.'
|
||||
DRIVE_SCOPE = 'https://www.googleapis.com/auth/drive.readonly'
|
||||
|
||||
def initialize service_account_email: ENV['GOOGLE_DRIVE_SERVICE_ACCOUNT_EMAIL'],
|
||||
@@ -26,34 +25,24 @@ 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'])
|
||||
|
||||
yield build_file_entry(entry, relative_path)
|
||||
files << build_file_entry(entry, relative_path)
|
||||
end
|
||||
files
|
||||
end
|
||||
|
||||
def fetch_material_file file_id
|
||||
metadata = get_file(file_id)
|
||||
return nil if native_file?(metadata['mimeType'])
|
||||
|
||||
build_file_entry(metadata, metadata['name'])
|
||||
end
|
||||
|
||||
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.b)
|
||||
tempfile.write(chunk)
|
||||
end
|
||||
tempfile.rewind
|
||||
tempfile
|
||||
@@ -96,7 +85,6 @@ module GoogleDrive
|
||||
name: entry['name'],
|
||||
mime_type: entry['mimeType'],
|
||||
relative_path: MaterialSyncExportPath.normalize_path(relative_path),
|
||||
sha256_checksum: entry['sha256Checksum'],
|
||||
web_view_link: entry['webViewLink'],
|
||||
web_content_link: entry['webContentLink'] }
|
||||
end
|
||||
@@ -109,8 +97,7 @@ module GoogleDrive
|
||||
response =
|
||||
request_json('/files', {
|
||||
q: "'#{ folder_id }' in parents and trashed = false",
|
||||
fields: 'nextPageToken,files(id,name,mimeType,sha256Checksum,' \
|
||||
'webViewLink,webContentLink)',
|
||||
fields: 'nextPageToken,files(id,name,mimeType,webViewLink,webContentLink)',
|
||||
orderBy: 'folder,name',
|
||||
pageSize: 1000,
|
||||
supportsAllDrives: true,
|
||||
@@ -126,7 +113,7 @@ module GoogleDrive
|
||||
|
||||
def get_file file_id
|
||||
request_json("/files/#{ file_id }",
|
||||
fields: 'id,name,mimeType,sha256Checksum,webViewLink,webContentLink',
|
||||
fields: 'id,name,mimeType,webViewLink,webContentLink',
|
||||
supportsAllDrives: true)
|
||||
end
|
||||
|
||||
@@ -140,14 +127,13 @@ module GoogleDrive
|
||||
end
|
||||
|
||||
def request_binary path, params = {}
|
||||
request(:get, path, params:) do |response|
|
||||
unless response.is_a?(Net::HTTPSuccess)
|
||||
raise "Google Drive download error: #{ response.code } #{ response.body }"
|
||||
end
|
||||
response = request(:get, path, params:)
|
||||
unless response.is_a?(Net::HTTPSuccess)
|
||||
raise "Google Drive download error: #{ response.code } #{ response.body }"
|
||||
end
|
||||
|
||||
response.read_body do |chunk|
|
||||
yield chunk.b
|
||||
end
|
||||
response.read_body do |chunk|
|
||||
yield chunk
|
||||
end
|
||||
end
|
||||
|
||||
@@ -170,13 +156,7 @@ module GoogleDrive
|
||||
use_ssl: true,
|
||||
open_timeout: 10,
|
||||
read_timeout: 60) do |http|
|
||||
if block_given?
|
||||
http.request(request) do |response|
|
||||
return yield response
|
||||
end
|
||||
else
|
||||
http.request(request)
|
||||
end
|
||||
http.request(request)
|
||||
end
|
||||
end
|
||||
|
||||
@@ -225,9 +205,5 @@ module GoogleDrive
|
||||
|
||||
OpenSSL::PKey::RSA.new(raw)
|
||||
end
|
||||
|
||||
def native_file? mime_type
|
||||
mime_type.to_s.start_with?(NATIVE_FILE_MIME_TYPE_PREFIX)
|
||||
end
|
||||
end
|
||||
end
|
||||
|
||||
@@ -1,39 +1,16 @@
|
||||
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 = metadata_sha256(blob)
|
||||
sha256 = blob.metadata['sha256']
|
||||
return sha256 if sha256.present?
|
||||
return nil unless allow_download
|
||||
|
||||
begin
|
||||
blob.open do |file|
|
||||
sha256 = Digest::SHA256.file(file.path).hexdigest
|
||||
assign_metadata_sha256!(blob, sha256)
|
||||
blob.metadata['sha256'] = sha256
|
||||
blob.save! if blob.changed?
|
||||
sha256
|
||||
end
|
||||
rescue ActiveStorage::FileNotFoundError, ArgumentError => error
|
||||
|
||||
@@ -28,13 +28,6 @@ class MaterialSyncImporter
|
||||
Material
|
||||
.unscoped
|
||||
.find_or_initialize_by(normalized_source_key: key)
|
||||
if unchanged?(material, source)
|
||||
return Result.new(material:,
|
||||
action: :unchanged,
|
||||
suppressed: false,
|
||||
suppression: nil)
|
||||
end
|
||||
|
||||
event_type =
|
||||
if material.new_record?
|
||||
:create
|
||||
@@ -44,19 +37,13 @@ class MaterialSyncImporter
|
||||
:update
|
||||
end
|
||||
uploaded_blob = uploaded_blob!
|
||||
if @import_block
|
||||
return Result.new(material: nil,
|
||||
action: :suppressed,
|
||||
suppressed: true,
|
||||
suppression: @import_block)
|
||||
end
|
||||
|
||||
Material.transaction do
|
||||
if material.persisted?
|
||||
MaterialVersionRecorder.ensure_snapshot!(material,
|
||||
created_by_user: @attributes[:updated_by_user])
|
||||
end
|
||||
material.assign_attributes(material_attributes_for(material).merge(source))
|
||||
material.assign_attributes(material_attributes.merge(source))
|
||||
material.discarded_at = nil if material.respond_to?(:discarded_at=)
|
||||
material.file.attach(uploaded_blob) if uploaded_blob
|
||||
material.save!
|
||||
@@ -94,28 +81,10 @@ class MaterialSyncImporter
|
||||
source_file_id: source[:source_file_id])
|
||||
end
|
||||
|
||||
def material_attributes_for material
|
||||
attrs =
|
||||
@attributes
|
||||
.except(:source_kind, :source_uri, :source_path, :source_file_id,
|
||||
:file_blob, :file_tempfile, :file_downloader,
|
||||
:filename, :content_type,
|
||||
:file_sha256, :export_path, :profile, :tag, :url)
|
||||
|
||||
if material.new_record?
|
||||
attrs[:tag] = @attributes[:tag] if @attributes.key?(:tag)
|
||||
attrs[:url] = @attributes[:url] if @attributes.key?(:url)
|
||||
return attrs
|
||||
end
|
||||
|
||||
if @attributes.key?(:tag) && @attributes[:tag].present?
|
||||
attrs[:tag] = @attributes[:tag]
|
||||
end
|
||||
if @attributes.key?(:url) && @attributes[:url].present?
|
||||
attrs[:url] = @attributes[:url]
|
||||
end
|
||||
|
||||
attrs
|
||||
def material_attributes
|
||||
@attributes.except(:source_kind, :source_uri, :source_path, :source_file_id,
|
||||
:file_blob, :file_tempfile, :filename, :content_type,
|
||||
:file_sha256, :export_path, :profile)
|
||||
end
|
||||
|
||||
def suppression_for source
|
||||
@@ -131,44 +100,33 @@ class MaterialSyncImporter
|
||||
def uploaded_blob!
|
||||
return @attributes[:file_blob] if @attributes[:file_blob]
|
||||
|
||||
tempfile = upload_tempfile
|
||||
tempfile = @attributes[:file_tempfile]
|
||||
return nil unless tempfile
|
||||
|
||||
tempfile.rewind
|
||||
file_sha256 = @attributes[:file_sha256] || Digest::SHA256.file(tempfile.path).hexdigest
|
||||
@attributes[:file_sha256] = file_sha256
|
||||
|
||||
@import_block = MaterialImportBlockMatcher.match_for_sha256(file_sha256)
|
||||
if @import_block
|
||||
tempfile.rewind
|
||||
return nil
|
||||
end
|
||||
|
||||
blob = ActiveStorage::Blob.create_and_upload!(
|
||||
io: tempfile,
|
||||
filename: @attributes[:filename],
|
||||
content_type: @attributes[:content_type])
|
||||
MaterialFileSha256.assign_metadata_sha256!(blob, file_sha256)
|
||||
file_sha256 = @attributes[:file_sha256] || Digest::SHA256.file(tempfile.path).hexdigest
|
||||
blob.metadata['sha256'] = file_sha256 if file_sha256.present?
|
||||
blob.save! if blob.changed?
|
||||
tempfile.rewind
|
||||
blob
|
||||
end
|
||||
|
||||
def upload_tempfile
|
||||
return @upload_tempfile if defined?(@upload_tempfile)
|
||||
|
||||
@upload_tempfile = @attributes[:file_tempfile]
|
||||
if @upload_tempfile.blank? && @attributes[:file_downloader]
|
||||
@upload_tempfile = @attributes[:file_downloader].call
|
||||
end
|
||||
@upload_tempfile
|
||||
end
|
||||
|
||||
def upsert_export_item! material
|
||||
export_path = resolved_export_path(material)
|
||||
export_path = @attributes[:export_path].to_s.strip
|
||||
return if export_path.blank?
|
||||
|
||||
item = material.material_export_items.find_or_initialize_by(profile: effective_profile)
|
||||
item.export_path = export_path
|
||||
profile = @attributes[:profile].presence || 'legacy_drive'
|
||||
path = export_path
|
||||
if export_path_taken_by_other?(material, profile, path)
|
||||
path = MaterialSyncExportPath.uniquify(path, @attributes[:source_file_id])
|
||||
end
|
||||
|
||||
item = material.material_export_items.find_or_initialize_by(profile:)
|
||||
item.export_path = path
|
||||
item.enabled = true
|
||||
item.created_by_user ||= @attributes[:created_by_user]
|
||||
item.save!
|
||||
@@ -182,78 +140,11 @@ class MaterialSyncImporter
|
||||
end
|
||||
|
||||
def close_tempfile!
|
||||
tempfile = upload_tempfile
|
||||
tempfile = @attributes[:file_tempfile]
|
||||
return unless tempfile
|
||||
|
||||
tempfile.close! unless tempfile.closed?
|
||||
rescue StandardError
|
||||
nil
|
||||
end
|
||||
|
||||
def unchanged? material, source
|
||||
return false if material.new_record? || material.discarded?
|
||||
return false unless same_source_attributes?(material, source)
|
||||
return false unless same_export_path?(material)
|
||||
return false unless same_material_attributes?(material)
|
||||
|
||||
same_file_snapshot?(material)
|
||||
end
|
||||
|
||||
def same_source_attributes? material, source
|
||||
material.source_kind == source[:source_kind] \
|
||||
&& material.source_uri == source[:source_uri] \
|
||||
&& material.source_path == source[:source_path] \
|
||||
&& material.source_file_id == source[:source_file_id]
|
||||
end
|
||||
|
||||
def same_export_path? material
|
||||
expected = resolved_export_path(material)
|
||||
current = material.material_export_items.find { |item| item.profile == effective_profile }
|
||||
|
||||
return current.blank? if expected.blank?
|
||||
|
||||
current&.enabled && current.export_path == expected
|
||||
end
|
||||
|
||||
def same_material_attributes? material
|
||||
same_tag_attribute?(material) && same_url_attribute?(material)
|
||||
end
|
||||
|
||||
def same_file_snapshot? material
|
||||
expected_sha256 = @attributes[:file_sha256].to_s.presence
|
||||
|
||||
if expected_sha256.present?
|
||||
return false unless material.file.attached?
|
||||
|
||||
return MaterialFileSha256.metadata_sha256(material.file.blob) == expected_sha256
|
||||
end
|
||||
|
||||
!material.file.attached?
|
||||
end
|
||||
|
||||
def effective_profile
|
||||
@attributes[:profile].presence || 'legacy_drive'
|
||||
end
|
||||
|
||||
def resolved_export_path material
|
||||
export_path = @attributes[:export_path].to_s.strip
|
||||
return export_path if export_path.blank?
|
||||
return export_path unless export_path_taken_by_other?(material, effective_profile, export_path)
|
||||
|
||||
MaterialSyncExportPath.uniquify(export_path, @attributes[:source_file_id])
|
||||
end
|
||||
|
||||
def same_tag_attribute? material
|
||||
return true unless @attributes.key?(:tag)
|
||||
return true if @attributes[:tag].blank?
|
||||
|
||||
material.tag_id == @attributes[:tag].id
|
||||
end
|
||||
|
||||
def same_url_attribute? material
|
||||
return true unless @attributes.key?(:url)
|
||||
return true if @attributes[:url].blank?
|
||||
|
||||
material.url == @attributes[:url]
|
||||
end
|
||||
end
|
||||
|
||||
@@ -1,13 +1,13 @@
|
||||
require 'digest'
|
||||
|
||||
class MaterialSyncRunner
|
||||
Result = Struct.new(:imported, :updated, :unchanged, :suppressed, :failed,
|
||||
:errors, keyword_init: true)
|
||||
Result = Struct.new(:imported, :updated, :suppressed, :failed, :errors, keyword_init: true)
|
||||
|
||||
def self.sync_enabled!
|
||||
results = MaterialSyncSource.enabled.order(:id).map { |source| new(source).sync! }
|
||||
|
||||
Result.new(imported: results.sum(&:imported),
|
||||
updated: results.sum(&:updated),
|
||||
unchanged: results.sum(&:unchanged),
|
||||
suppressed: results.sum(&:suppressed),
|
||||
failed: results.sum(&:failed),
|
||||
errors: results.flat_map(&:errors))
|
||||
@@ -18,17 +18,10 @@ class MaterialSyncRunner
|
||||
end
|
||||
|
||||
def sync!
|
||||
result = Result.new(imported: 0, updated: 0, unchanged: 0,
|
||||
suppressed: 0, failed: 0, errors: [])
|
||||
result = Result.new(imported: 0, updated: 0, suppressed: 0, failed: 0, errors: [])
|
||||
|
||||
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)
|
||||
end
|
||||
candidates.each do |candidate|
|
||||
sync_candidate!(candidate, result)
|
||||
end
|
||||
|
||||
@source.update!(last_synced_at: Time.current)
|
||||
@@ -47,6 +40,8 @@ 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'
|
||||
@@ -106,30 +101,15 @@ class MaterialSyncRunner
|
||||
def google_drive_path_candidates
|
||||
folder_id = google_drive_folder_id
|
||||
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)
|
||||
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
|
||||
|
||||
build_google_drive_candidate(entry, single_file: true)
|
||||
build_google_drive_candidate(drive_client.fetch_material_file(google_drive_file_id),
|
||||
single_file: true)
|
||||
end
|
||||
|
||||
def build_google_drive_candidate entry, single_file: false
|
||||
@@ -144,6 +124,10 @@ class MaterialSyncRunner
|
||||
relative_path:,
|
||||
filename: entry[:name],
|
||||
source_file_id: entry[:id])
|
||||
tempfile =
|
||||
drive_client.download_to_tempfile(entry[:id], filename: entry[:name])
|
||||
file_sha256 = Digest::SHA256.file(tempfile.path).hexdigest
|
||||
tempfile.rewind
|
||||
|
||||
{ source_kind: 'google_drive_file',
|
||||
source_uri: entry[:web_view_link] || google_drive_file_url(entry[:id]),
|
||||
@@ -151,10 +135,8 @@ class MaterialSyncRunner
|
||||
source_file_id: entry[:id],
|
||||
filename: entry[:name],
|
||||
content_type: entry[:mime_type],
|
||||
file_downloader: lambda {
|
||||
drive_client.download_to_tempfile(entry[:id], filename: entry[:name])
|
||||
},
|
||||
file_sha256: entry[:sha256_checksum],
|
||||
file_tempfile: tempfile,
|
||||
file_sha256:,
|
||||
export_path:,
|
||||
profile: @source.profile,
|
||||
tag: nil,
|
||||
@@ -189,17 +171,13 @@ class MaterialSyncRunner
|
||||
|
||||
def google_drive_folder_id
|
||||
google_drive_target_id.tap do |id|
|
||||
if id.blank?
|
||||
raise ArgumentError, 'google_drive_path source_file_id or source_uri is required'
|
||||
end
|
||||
raise ArgumentError, 'google_drive_path source_file_id or source_uri is required' if id.blank?
|
||||
end
|
||||
end
|
||||
|
||||
def google_drive_file_id
|
||||
google_drive_target_id.tap do |id|
|
||||
if id.blank?
|
||||
raise ArgumentError, 'google_drive_file source_file_id or source_uri is required'
|
||||
end
|
||||
raise ArgumentError, 'google_drive_file source_file_id or source_uri is required' if id.blank?
|
||||
end
|
||||
end
|
||||
|
||||
@@ -223,27 +201,10 @@ class MaterialSyncRunner
|
||||
def log_result result
|
||||
Rails.logger.info(material_sync_log(imported: result.imported,
|
||||
updated: result.updated,
|
||||
unchanged: result.unchanged,
|
||||
suppressed: result.suppressed,
|
||||
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
|
||||
|
||||
@@ -33,11 +33,6 @@ class MaterialVersionRecorder < VersionRecorder
|
||||
tag: @record.tag,
|
||||
tag_name: @record.tag&.name,
|
||||
tag_category: @record.tag&.category,
|
||||
source_kind: @record.source_kind,
|
||||
source_uri: @record.source_uri,
|
||||
source_path: @record.source_path,
|
||||
source_file_id: @record.source_file_id,
|
||||
normalized_source_key: @record.normalized_source_key,
|
||||
export_paths_json: @record.snapshot_export_paths,
|
||||
discarded_at: @record.discarded_at,
|
||||
file_blob_id: file_snapshot[:file_blob_id],
|
||||
@@ -57,7 +52,7 @@ class MaterialVersionRecorder < VersionRecorder
|
||||
file_content_type: blob.content_type,
|
||||
file_byte_size: blob.byte_size,
|
||||
file_checksum: blob.checksum,
|
||||
file_sha256: MaterialFileSha256.metadata_sha256(blob) }
|
||||
file_sha256: blob.metadata['sha256'] }
|
||||
end
|
||||
|
||||
def empty_file_snapshot
|
||||
|
||||
@@ -2,6 +2,9 @@ class EnhanceMaterialManagement < ActiveRecord::Migration[8.0]
|
||||
def up
|
||||
change_table :materials, bulk: true do |t|
|
||||
t.integer :version_no, null: false, default: 1
|
||||
t.datetime :file_suppressed_at
|
||||
t.references :file_suppressed_by_user, foreign_key: { to_table: :users }
|
||||
t.string :file_suppression_reason
|
||||
end
|
||||
|
||||
change_table :material_versions, bulk: true do |t|
|
||||
@@ -15,6 +18,8 @@ class EnhanceMaterialManagement < ActiveRecord::Migration[8.0]
|
||||
t.bigint :file_byte_size
|
||||
t.string :file_checksum
|
||||
t.string :file_sha256
|
||||
t.datetime :file_suppressed_at
|
||||
t.string :file_suppression_reason
|
||||
end
|
||||
|
||||
execute <<~SQL.squish
|
||||
@@ -30,7 +35,7 @@ class EnhanceMaterialManagement < ActiveRecord::Migration[8.0]
|
||||
add_index :material_versions, :file_blob_id
|
||||
|
||||
add_check_constraint :material_versions,
|
||||
"event_type IN ('create', 'update', 'discard', 'restore')",
|
||||
"event_type IN ('create', 'update', 'discard', 'restore', 'suppress')",
|
||||
name: 'material_versions_event_type_valid'
|
||||
|
||||
create_table :material_export_items do |t|
|
||||
@@ -82,7 +87,12 @@ class EnhanceMaterialManagement < ActiveRecord::Migration[8.0]
|
||||
remove_column :material_versions, :file_byte_size
|
||||
remove_column :material_versions, :file_checksum
|
||||
remove_column :material_versions, :file_sha256
|
||||
remove_column :material_versions, :file_suppressed_at
|
||||
remove_column :material_versions, :file_suppression_reason
|
||||
|
||||
remove_reference :materials, :file_suppressed_by_user, foreign_key: { to_table: :users }
|
||||
remove_column :materials, :version_no
|
||||
remove_column :materials, :file_suppressed_at
|
||||
remove_column :materials, :file_suppression_reason
|
||||
end
|
||||
end
|
||||
|
||||
@@ -1,19 +0,0 @@
|
||||
class AddSourceSnapshotToMaterialVersions < ActiveRecord::Migration[8.0]
|
||||
def change
|
||||
unless column_exists?(:material_versions, :source_kind)
|
||||
add_column :material_versions, :source_kind, :string
|
||||
end
|
||||
unless column_exists?(:material_versions, :source_uri)
|
||||
add_column :material_versions, :source_uri, :string
|
||||
end
|
||||
unless column_exists?(:material_versions, :source_path)
|
||||
add_column :material_versions, :source_path, :string
|
||||
end
|
||||
unless column_exists?(:material_versions, :source_file_id)
|
||||
add_column :material_versions, :source_file_id, :string
|
||||
end
|
||||
unless column_exists?(:material_versions, :normalized_source_key)
|
||||
add_column :material_versions, :normalized_source_key, :string
|
||||
end
|
||||
end
|
||||
end
|
||||
@@ -1,171 +0,0 @@
|
||||
require 'json'
|
||||
|
||||
class BackfillInitialMaterialVersions < ActiveRecord::Migration[8.0]
|
||||
class MigrationMaterial < ActiveRecord::Base
|
||||
self.table_name = 'materials'
|
||||
end
|
||||
|
||||
class MigrationMaterialExportItem < ActiveRecord::Base
|
||||
self.table_name = 'material_export_items'
|
||||
end
|
||||
|
||||
class MigrationMaterialVersion < ActiveRecord::Base
|
||||
self.table_name = 'material_versions'
|
||||
end
|
||||
|
||||
class MigrationStorageAttachment < ActiveRecord::Base
|
||||
self.table_name = 'active_storage_attachments'
|
||||
end
|
||||
|
||||
class MigrationStorageBlob < ActiveRecord::Base
|
||||
self.table_name = 'active_storage_blobs'
|
||||
end
|
||||
|
||||
class MigrationTag < ActiveRecord::Base
|
||||
self.table_name = 'tags'
|
||||
end
|
||||
|
||||
class MigrationTagName < ActiveRecord::Base
|
||||
self.table_name = 'tag_names'
|
||||
end
|
||||
|
||||
def up
|
||||
say_with_time 'Backfilling initial material versions' do
|
||||
materials_without_versions.find_in_batches(batch_size: 500) do |materials|
|
||||
material_ids = materials.map(&:id)
|
||||
tags_by_id = load_tags(materials.map(&:tag_id).compact.uniq)
|
||||
export_paths_by_material_id = load_export_paths(material_ids)
|
||||
file_snapshots_by_material_id = load_file_snapshots(material_ids)
|
||||
|
||||
rows = materials.map do |material|
|
||||
tag = tags_by_id[material.tag_id]
|
||||
file_snapshot = file_snapshots_by_material_id[material.id] || empty_file_snapshot
|
||||
|
||||
{ material_id: material.id,
|
||||
version_no: 1,
|
||||
event_type: 'create',
|
||||
url: material.url,
|
||||
parent_id: material.parent_id,
|
||||
tag_id: material.tag_id,
|
||||
tag_name: tag&.fetch(:name, nil),
|
||||
tag_category: tag&.fetch(:category, nil),
|
||||
source_kind: material.source_kind,
|
||||
source_uri: material.source_uri,
|
||||
source_path: material.source_path,
|
||||
source_file_id: material.source_file_id,
|
||||
normalized_source_key: material.normalized_source_key,
|
||||
export_paths_json: export_paths_by_material_id[material.id] || { },
|
||||
discarded_at: material.discarded_at,
|
||||
file_blob_id: file_snapshot[:file_blob_id],
|
||||
file_filename: file_snapshot[:file_filename],
|
||||
file_content_type: file_snapshot[:file_content_type],
|
||||
file_byte_size: file_snapshot[:file_byte_size],
|
||||
file_checksum: file_snapshot[:file_checksum],
|
||||
file_sha256: file_snapshot[:file_sha256],
|
||||
created_by_user_id: material.created_by_user_id,
|
||||
updated_by_user_id: material.updated_by_user_id,
|
||||
created_at: material.created_at,
|
||||
updated_at: material.created_at }
|
||||
end
|
||||
|
||||
MigrationMaterialVersion.insert_all!(rows) if rows.present?
|
||||
end
|
||||
end
|
||||
|
||||
execute <<~SQL.squish
|
||||
UPDATE materials
|
||||
SET version_no = COALESCE(
|
||||
(
|
||||
SELECT MAX(material_versions.version_no)
|
||||
FROM material_versions
|
||||
WHERE material_versions.material_id = materials.id
|
||||
),
|
||||
1
|
||||
)
|
||||
SQL
|
||||
end
|
||||
|
||||
def down
|
||||
raise ActiveRecord::IrreversibleMigration
|
||||
end
|
||||
|
||||
private
|
||||
|
||||
def materials_without_versions
|
||||
MigrationMaterial.where.not(id: MigrationMaterialVersion.select(:material_id))
|
||||
end
|
||||
|
||||
def load_tags tag_ids
|
||||
return { } if tag_ids.empty?
|
||||
|
||||
tag_name_ids_by_tag_id = MigrationTag.where(id: tag_ids).pluck(:id, :tag_name_id).to_h
|
||||
tag_names_by_id =
|
||||
MigrationTagName
|
||||
.where(id: tag_name_ids_by_tag_id.values.uniq)
|
||||
.pluck(:id, :name)
|
||||
.to_h
|
||||
categories_by_tag_id = MigrationTag.where(id: tag_ids).pluck(:id, :category).to_h
|
||||
|
||||
tag_ids.each_with_object({ }) do |tag_id, hash|
|
||||
hash[tag_id] = { name: tag_names_by_id[tag_name_ids_by_tag_id[tag_id]],
|
||||
category: categories_by_tag_id[tag_id] }
|
||||
end
|
||||
end
|
||||
|
||||
def load_export_paths material_ids
|
||||
MigrationMaterialExportItem
|
||||
.where(material_id: material_ids)
|
||||
.order(:material_id, :profile)
|
||||
.pluck(:material_id, :profile, :export_path)
|
||||
.each_with_object({ }) do |(material_id, profile, export_path), hash|
|
||||
hash[material_id] ||= { }
|
||||
hash[material_id][profile] = export_path
|
||||
end
|
||||
end
|
||||
|
||||
def load_file_snapshots material_ids
|
||||
attachments_by_material_id =
|
||||
MigrationStorageAttachment
|
||||
.where(record_type: 'Material', name: 'file', record_id: material_ids)
|
||||
.pluck(:record_id, :blob_id)
|
||||
.to_h
|
||||
|
||||
blobs_by_id =
|
||||
MigrationStorageBlob
|
||||
.where(id: attachments_by_material_id.values.uniq)
|
||||
.index_by(&:id)
|
||||
|
||||
attachments_by_material_id.each_with_object({ }) do |(material_id, blob_id), hash|
|
||||
blob = blobs_by_id[blob_id]
|
||||
next unless blob
|
||||
|
||||
hash[material_id] = {
|
||||
file_blob_id: blob.id,
|
||||
file_filename: blob.filename.to_s,
|
||||
file_content_type: blob.content_type,
|
||||
file_byte_size: blob.byte_size,
|
||||
file_checksum: blob.checksum,
|
||||
file_sha256: blob_metadata(blob)['sha256']
|
||||
}
|
||||
end
|
||||
end
|
||||
|
||||
def empty_file_snapshot
|
||||
{ file_blob_id: nil,
|
||||
file_filename: nil,
|
||||
file_content_type: nil,
|
||||
file_byte_size: nil,
|
||||
file_checksum: nil,
|
||||
file_sha256: nil }
|
||||
end
|
||||
|
||||
def blob_metadata blob
|
||||
metadata = blob.metadata
|
||||
return metadata if metadata.is_a?(Hash)
|
||||
return { } if metadata.blank?
|
||||
|
||||
JSON.parse(metadata)
|
||||
rescue JSON::ParserError
|
||||
{ }
|
||||
end
|
||||
end
|
||||
生成ファイル
+9
-41
@@ -10,7 +10,7 @@
|
||||
#
|
||||
# It's strongly recommended that you check this file into your version control system.
|
||||
|
||||
ActiveRecord::Schema[8.0].define(version: 2026_06_26_010000) do
|
||||
ActiveRecord::Schema[8.0].define(version: 2026_06_25_010000) do
|
||||
create_table "active_storage_attachments", charset: "utf8mb4", collation: "utf8mb4_0900_ai_ci", force: :cascade do |t|
|
||||
t.string "name", null: false
|
||||
t.string "record_type", null: false
|
||||
@@ -72,7 +72,6 @@ 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|
|
||||
@@ -214,11 +213,6 @@ ActiveRecord::Schema[8.0].define(version: 2026_06_26_010000) do
|
||||
t.bigint "file_byte_size"
|
||||
t.string "file_checksum"
|
||||
t.string "file_sha256"
|
||||
t.string "source_kind"
|
||||
t.string "source_uri"
|
||||
t.string "source_path"
|
||||
t.string "source_file_id"
|
||||
t.string "normalized_source_key"
|
||||
t.index ["created_by_user_id"], name: "index_material_versions_on_created_by_user_id"
|
||||
t.index ["discarded_at"], name: "index_material_versions_on_discarded_at"
|
||||
t.index ["file_blob_id"], name: "index_material_versions_on_file_blob_id"
|
||||
@@ -275,10 +269,9 @@ 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", 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 ["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 ["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|
|
||||
@@ -287,14 +280,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.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", order: { cos: :desc }
|
||||
t.index ["post_id", "cos"], name: "index_post_similarities_on_post_id_and_cos"
|
||||
t.index ["target_post_id"], name: "index_post_similarities_on_target_post_id"
|
||||
end
|
||||
|
||||
@@ -334,8 +326,6 @@ 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|
|
||||
@@ -350,7 +340,6 @@ 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|
|
||||
@@ -397,7 +386,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", order: { cos: :desc }
|
||||
t.index ["tag_id", "cos"], name: "index_tag_similarities_on_tag_id_and_cos"
|
||||
t.index ["target_tag_id"], name: "index_tag_similarities_on_target_tag_id"
|
||||
end
|
||||
|
||||
@@ -407,32 +396,30 @@ 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", 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 ["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 ["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|
|
||||
@@ -557,19 +544,6 @@ 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
|
||||
@@ -586,13 +560,11 @@ 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|
|
||||
@@ -637,8 +609,6 @@ 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"
|
||||
@@ -717,8 +687,6 @@ 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"
|
||||
|
||||
+4
-4
@@ -9,19 +9,19 @@
|
||||
# end
|
||||
|
||||
material_sync_source_uri = ENV['MATERIAL_SYNC_SOURCE_URI']
|
||||
material_sync_source_file_id = ENV['MATERIAL_SYNC_SOURCE_FILE_ID']
|
||||
material_sync_source_tag_name = ENV['MATERIAL_SYNC_SOURCE_TAG_NAME']
|
||||
|
||||
if material_sync_source_uri.present? || material_sync_source_file_id.present?
|
||||
if material_sync_source_uri.present? && material_sync_source_tag_name.present?
|
||||
source = MaterialSyncSource.find_or_initialize_by(
|
||||
name: ENV.fetch('MATERIAL_SYNC_SOURCE_NAME', 'Legacy URI material sync'))
|
||||
source.assign_attributes(
|
||||
source_kind: ENV.fetch('MATERIAL_SYNC_SOURCE_KIND', 'uri'),
|
||||
source_uri: material_sync_source_uri,
|
||||
source_path: ENV['MATERIAL_SYNC_SOURCE_PATH'],
|
||||
source_file_id: material_sync_source_file_id,
|
||||
source_file_id: ENV['MATERIAL_SYNC_SOURCE_FILE_ID'],
|
||||
profile: ENV.fetch('MATERIAL_SYNC_SOURCE_PROFILE', 'legacy_drive'),
|
||||
enabled: ENV.fetch('MATERIAL_SYNC_SOURCE_ENABLED', 'true') != 'false',
|
||||
default_tag_name: ENV['MATERIAL_SYNC_SOURCE_TAG_NAME'],
|
||||
default_tag_name: material_sync_source_tag_name,
|
||||
export_path_prefix: ENV['MATERIAL_SYNC_EXPORT_PATH_PREFIX'])
|
||||
source.save!
|
||||
end
|
||||
|
||||
@@ -5,7 +5,6 @@ namespace :materials do
|
||||
message = [
|
||||
"materials:sync imported=#{ result.imported }",
|
||||
"updated=#{ result.updated }",
|
||||
"unchanged=#{ result.unchanged }",
|
||||
"suppressed=#{ result.suppressed }",
|
||||
"failed=#{ result.failed }"
|
||||
].join(' ')
|
||||
|
||||
@@ -1,19 +0,0 @@
|
||||
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
|
||||
@@ -64,36 +64,27 @@ RSpec.describe 'Materials API', type: :request do
|
||||
'name' => 'material_index_b',
|
||||
'category' => 'material'
|
||||
)
|
||||
expect(row['created_by_user']).to include(
|
||||
'id' => member_user.id,
|
||||
'name' => member_user.name
|
||||
)
|
||||
expect(row['content_type']).to eq('image/png')
|
||||
expect(row['media_kind']).to eq('image')
|
||||
end
|
||||
|
||||
it 'filters materials by q' do
|
||||
get '/materials', params: { q: 'material_index_a' }
|
||||
it 'filters materials by tag_id' do
|
||||
get '/materials', params: { tag_id: material_a.tag_id }
|
||||
|
||||
expect(response).to have_http_status(:ok)
|
||||
expect(json['count']).to eq(1)
|
||||
expect(response_materials.map { |m| m['id'] }).to eq([material_a.id])
|
||||
end
|
||||
|
||||
it 'filters materials by tag_state' do
|
||||
untagged =
|
||||
build_material(tag: nil, user: member_user,
|
||||
file: dummy_upload(filename: 'untagged.png'))
|
||||
|
||||
get '/materials', params: { tag_state: 'untagged' }
|
||||
it 'filters materials by parent_id' do
|
||||
get '/materials', params: { parent_id: material_a.id }
|
||||
|
||||
expect(response).to have_http_status(:ok)
|
||||
expect(json['count']).to eq(1)
|
||||
expect(response_materials.map { |m| m['id'] }).to eq([untagged.id])
|
||||
end
|
||||
|
||||
it 'filters materials by media_kind' do
|
||||
get '/materials', params: { media_kind: 'image' }
|
||||
|
||||
expect(response).to have_http_status(:ok)
|
||||
expect(json['count']).to eq(2)
|
||||
expect(response_materials.map { |m| m['media_kind'] }).to all(eq('image'))
|
||||
expect(response_materials.map { |m| m['id'] }).to eq([material_b.id])
|
||||
end
|
||||
|
||||
it 'paginates and keeps total count' do
|
||||
@@ -113,68 +104,6 @@ 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
|
||||
@@ -599,8 +528,9 @@ RSpec.describe 'Materials API', type: :request do
|
||||
expect(response.body.b).not_to include('素材/b.png'.b)
|
||||
end
|
||||
|
||||
it 'does not include disabled export items' do
|
||||
material_b.material_export_items.first.update!(enabled: false)
|
||||
it 'does not include suppressed materials' do
|
||||
material_b.update!(file_suppressed_at: Time.current,
|
||||
file_suppression_reason: 'copyright_high_risk')
|
||||
|
||||
get '/materials/download.zip', params: { profile: 'legacy_drive' }
|
||||
|
||||
@@ -610,78 +540,62 @@ RSpec.describe 'Materials API', type: :request do
|
||||
end
|
||||
end
|
||||
|
||||
describe 'GET /materials/versions' do
|
||||
describe 'PATCH /materials/:id/suppress_file' do
|
||||
let!(:tag) do
|
||||
Tag.create!(tag_name: TagName.create!(name: 'material_history'), category: :material)
|
||||
Tag.create!(tag_name: TagName.create!(name: 'material_suppress'), category: :material)
|
||||
end
|
||||
let!(:material) do
|
||||
build_material(tag:, user: member_user, file: dummy_upload(filename: 'history.png'))
|
||||
build_material(tag:, user: member_user, file: dummy_upload(filename: 'suppress.png'))
|
||||
end
|
||||
|
||||
it 'returns material versions in reverse chronological order' do
|
||||
it 'allows admin to suppress a file and records a suppress version' do
|
||||
sign_in_as(admin_user)
|
||||
MaterialVersionRecorder.record!(material:, event_type: :create,
|
||||
created_by_user: member_user)
|
||||
material.update!(url: 'https://example.com/history')
|
||||
MaterialVersionRecorder.record!(material:, event_type: :update,
|
||||
created_by_user: admin_user)
|
||||
|
||||
get '/materials/versions', params: { material_id: material.id }
|
||||
|
||||
expect(response).to have_http_status(:ok)
|
||||
expect(json['count']).to eq(2)
|
||||
versions = json.fetch('versions')
|
||||
expect(versions.map { |v| v['version_no'] }).to eq([2, 1])
|
||||
expect(versions.first).to include(
|
||||
'material_id' => material.id,
|
||||
'event_type' => 'update',
|
||||
'tag_name' => 'material_history',
|
||||
'file_filename' => 'history.png',
|
||||
'url' => 'https://example.com/history'
|
||||
)
|
||||
expect(versions.first['created_by_user']).to include('id' => admin_user.id)
|
||||
end
|
||||
|
||||
it 'filters material versions by tag and event_type' do
|
||||
MaterialVersionRecorder.record!(material:, event_type: :create,
|
||||
created_by_user: member_user)
|
||||
|
||||
get '/materials/versions', params: {
|
||||
tag: 'material_history',
|
||||
event_type: 'create'
|
||||
}
|
||||
|
||||
expect(response).to have_http_status(:ok)
|
||||
expect(json.fetch('versions').map { |v| v['material_id'] }).to include(material.id)
|
||||
expect(json.fetch('versions').map { |v| v['event_type'] }).to all(eq('create'))
|
||||
end
|
||||
end
|
||||
|
||||
describe 'material sync suppressions' do
|
||||
it 'requires member permission for index' do
|
||||
sign_out
|
||||
|
||||
get '/materials/suppressions'
|
||||
|
||||
expect(response).to have_http_status(:unauthorized)
|
||||
end
|
||||
|
||||
it 'creates source suppression as member' do
|
||||
sign_in_as(member_user)
|
||||
|
||||
expect do
|
||||
post '/materials/suppressions', params: {
|
||||
source_kind: 'google_drive_path_prefix',
|
||||
drive_path: '伊地知ニジカ/危険素材',
|
||||
reason: 'copyright_high_risk'
|
||||
}
|
||||
end.to change(MaterialSyncSuppression, :count).by(1)
|
||||
patch "/materials/#{ material.id }/suppress_file",
|
||||
params: { reason: 'copyright_high_risk' }
|
||||
end.to change(MaterialVersion, :count).by(1)
|
||||
|
||||
expect(response).to have_http_status(:created)
|
||||
expect(json).to include(
|
||||
'source_kind' => 'google_drive_path_prefix',
|
||||
'drive_path' => '伊地知ニジカ/危険素材',
|
||||
'normalized_source_key' => 'google_drive_path_prefix:伊地知ニジカ/危険素材'
|
||||
)
|
||||
expect(response).to have_http_status(:ok)
|
||||
|
||||
material.reload
|
||||
expect(material.file_suppressed_at).to be_present
|
||||
expect(material.file_suppressed_by_user).to eq(admin_user)
|
||||
expect(material.file_suppression_reason).to eq('copyright_high_risk')
|
||||
expect(material.material_versions.order(:version_no).last.event_type).to eq('suppress')
|
||||
expect(json['file']).to be_nil
|
||||
expect(json['file_suppressed_at']).to be_present
|
||||
end
|
||||
|
||||
it 'purges blob when purge=true is requested' do
|
||||
sign_in_as(admin_user)
|
||||
old_blob_id = material.file.blob.id
|
||||
MaterialVersionRecorder.record!(material:, event_type: :create,
|
||||
created_by_user: member_user)
|
||||
|
||||
expect do
|
||||
patch "/materials/#{ material.id }/suppress_file",
|
||||
params: { reason: 'copyright_takedown', purge: '1' }
|
||||
end.to have_enqueued_job(ActiveStorage::PurgeJob)
|
||||
|
||||
expect(response).to have_http_status(:ok)
|
||||
|
||||
version = material.material_versions.order(:version_no).last
|
||||
expect(version.event_type).to eq('suppress')
|
||||
expect(version.file_blob_id).to eq(old_blob_id)
|
||||
expect(version.file_filename).to eq('suppress.png')
|
||||
expect(version.file_sha256).to be_present
|
||||
end
|
||||
|
||||
it 'rejects member suppression' do
|
||||
sign_in_as(member_user)
|
||||
|
||||
patch "/materials/#{ material.id }/suppress_file",
|
||||
params: { reason: 'copyright_high_risk' }
|
||||
|
||||
expect(response).to have_http_status(:forbidden)
|
||||
end
|
||||
end
|
||||
|
||||
|
||||
@@ -1,5 +1,4 @@
|
||||
require 'rails_helper'
|
||||
require 'base64'
|
||||
require 'set'
|
||||
|
||||
include ActiveSupport::Testing::TimeHelpers
|
||||
@@ -9,11 +8,6 @@ RSpec.describe 'Posts API', type: :request do
|
||||
# resized_thumbnail! が MiniMagick 依存でコケやすいので request spec ではスタブしとくのが無難。
|
||||
before do
|
||||
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
|
||||
|
||||
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')
|
||||
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 = { }
|
||||
{ parent_post_ids: '' }.merge(params)
|
||||
end
|
||||
@@ -714,66 +696,6 @@ RSpec.describe 'Posts API', type: :request do
|
||||
expect(json['tags'][0]).to have_key('name')
|
||||
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
|
||||
sign_in_as(member)
|
||||
|
||||
|
||||
@@ -1,23 +0,0 @@
|
||||
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
|
||||
@@ -1,128 +0,0 @@
|
||||
require 'rails_helper'
|
||||
|
||||
RSpec.describe MaterialSyncImporter do
|
||||
let(:user) { create(:user, :member) }
|
||||
let(:tag) { Tag.create!(tag_name: TagName.create!(name: 'sync_tag'), category: :material) }
|
||||
|
||||
def tempfile_for body
|
||||
Tempfile.new(['material-sync-importer', '.png']).tap do |file|
|
||||
file.binmode
|
||||
file.write(body)
|
||||
file.rewind
|
||||
end
|
||||
end
|
||||
|
||||
it 'creates an untagged material from a sync candidate with file_downloader' do
|
||||
result =
|
||||
described_class.import!(
|
||||
source_kind: 'google_drive_file',
|
||||
source_path: '素材/a.png',
|
||||
source_file_id: 'drive-file-a',
|
||||
normalized_source_key: 'google_drive_file:drive-file-a',
|
||||
filename: 'a.png',
|
||||
content_type: 'image/png',
|
||||
file_sha256: Digest::SHA256.hexdigest('sync-body'),
|
||||
file_downloader: -> { tempfile_for('sync-body') },
|
||||
export_path: '素材/a.png',
|
||||
tag: nil,
|
||||
url: nil,
|
||||
created_by_user: user,
|
||||
updated_by_user: user)
|
||||
|
||||
material = result.material.reload
|
||||
expect(result.action).to eq(:imported)
|
||||
expect(material.tag).to be_nil
|
||||
expect(material.url).to be_nil
|
||||
expect(material.file).to be_attached
|
||||
expect(material.file.blob.filename.to_s).to eq('a.png')
|
||||
expect(material.material_export_items.first.export_path).to eq('素材/a.png')
|
||||
end
|
||||
|
||||
it 'does not clear a human-assigned tag or URL on existing Drive sync' do
|
||||
material =
|
||||
Material.create!(tag:, url: 'https://example.com/human',
|
||||
source_kind: 'google_drive_file',
|
||||
source_path: '素材/a.png',
|
||||
source_file_id: 'drive-file-a',
|
||||
created_by_user: user,
|
||||
updated_by_user: user)
|
||||
material.file.attach(
|
||||
io: StringIO.new('same-body'),
|
||||
filename: 'a.png',
|
||||
content_type: 'image/png')
|
||||
material.file.blob.metadata['sha256'] = Digest::SHA256.hexdigest('same-body')
|
||||
material.file.blob.save!
|
||||
MaterialExportItem.create!(material:,
|
||||
profile: 'legacy_drive',
|
||||
export_path: '素材/a.png',
|
||||
created_by_user: user)
|
||||
|
||||
result =
|
||||
described_class.import!(
|
||||
source_kind: 'google_drive_file',
|
||||
source_path: '素材/a.png',
|
||||
source_file_id: 'drive-file-a',
|
||||
filename: 'a.png',
|
||||
content_type: 'image/png',
|
||||
file_sha256: Digest::SHA256.hexdigest('same-body'),
|
||||
export_path: '素材/a.png',
|
||||
tag: nil,
|
||||
url: nil,
|
||||
updated_by_user: user)
|
||||
|
||||
expect(result.action).to eq(:unchanged)
|
||||
expect(material.reload.tag).to eq(tag)
|
||||
expect(material.url).to eq('https://example.com/human')
|
||||
end
|
||||
|
||||
it 'suppresses a Google Drive candidate by relative path prefix' do
|
||||
MaterialSyncSuppression.create!(source_kind: 'google_drive_path_prefix',
|
||||
drive_path: '素材/危険',
|
||||
reason: 'copyright_high_risk',
|
||||
created_by_user: user)
|
||||
|
||||
result =
|
||||
described_class.import!(
|
||||
source_kind: 'google_drive_file',
|
||||
source_path: '素材/危険/a.png',
|
||||
source_file_id: 'drive-file-b',
|
||||
filename: 'a.png',
|
||||
content_type: 'image/png',
|
||||
file_sha256: Digest::SHA256.hexdigest('blocked-body'),
|
||||
file_downloader: -> { tempfile_for('blocked-body') },
|
||||
export_path: '素材/危険/a.png',
|
||||
updated_by_user: user)
|
||||
|
||||
expect(result.action).to eq(:suppressed)
|
||||
expect(result.suppression.normalized_source_key)
|
||||
.to eq('google_drive_path_prefix:素材/危険')
|
||||
expect(Material.find_by(source_file_id: 'drive-file-b')).to be_nil
|
||||
end
|
||||
|
||||
it 'rechecks import blocks after downloaded file sha256 is known' do
|
||||
MaterialImportBlock.create!(match_kind: 'sha256',
|
||||
sha256: Digest::SHA256.hexdigest('blocked-body'),
|
||||
reason: 'copyright_high_risk',
|
||||
created_by_user: user)
|
||||
blob_count = ActiveStorage::Blob.count
|
||||
|
||||
expect do
|
||||
result =
|
||||
described_class.import!(
|
||||
source_kind: 'google_drive_file',
|
||||
source_path: '素材/blocked.png',
|
||||
source_file_id: 'drive-file-blocked',
|
||||
filename: 'blocked.png',
|
||||
content_type: 'image/png',
|
||||
file_downloader: -> { tempfile_for('blocked-body') },
|
||||
export_path: '素材/blocked.png',
|
||||
updated_by_user: user)
|
||||
|
||||
expect(result.action).to eq(:suppressed)
|
||||
expect(result.suppression.reason).to eq('copyright_high_risk')
|
||||
end.not_to change(Material, :count)
|
||||
|
||||
expect(ActiveStorage::Blob.count).to eq(blob_count)
|
||||
expect(Material.find_by(source_file_id: 'drive-file-blocked')).to be_nil
|
||||
end
|
||||
end
|
||||
@@ -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
|
||||
@@ -75,6 +75,7 @@ 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}/>}/>
|
||||
|
||||
@@ -1,43 +1,28 @@
|
||||
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 SidebarComponent from '@/components/layout/SidebarComponent'
|
||||
import TagLink from '@/components/TagLink'
|
||||
import { fetchMaterialTagTree, parseMaterialFilter } from '@/lib/materials'
|
||||
import SidebarComponent from '@/components/layout/SidebarComponent'
|
||||
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'
|
||||
|
||||
const FILTERS: MaterialFilter[] = ['missing', 'present', 'any']
|
||||
const FILTER_LABELS: Record<MaterialFilter, string> = { present: '有', missing: '無', any: '全' }
|
||||
const FILTERS: MaterialFilter[] = ['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 FILTER_LABELS: Record<MaterialFilter, string> = {
|
||||
present: '素材あり',
|
||||
missing: '素材なし',
|
||||
any: 'すべて'}
|
||||
|
||||
|
||||
const setChildrenById = (
|
||||
tags: MaterialSidebarTag[],
|
||||
targetId: number,
|
||||
children: MaterialSidebarTag[],
|
||||
): MaterialSidebarTag[] => (
|
||||
children: MaterialSidebarTag[]): MaterialSidebarTag[] => (
|
||||
tags.map (tag => {
|
||||
if (tag.id === targetId)
|
||||
return { ...tag, children }
|
||||
@@ -50,11 +35,8 @@ const setChildrenById = (
|
||||
|
||||
|
||||
const materialPath = (
|
||||
tagId: number,
|
||||
materialFilter: MaterialFilter,
|
||||
): string =>
|
||||
`/materials?tag_id=${ tagId }&include_descendants=1&group_by=parent_tag`
|
||||
+ `&material_filter=${ materialFilter }`
|
||||
tagName: string,
|
||||
materialFilter: MaterialFilter): string => `/materials?q=${ encodeURIComponent (tagName) }&material_filter=${ materialFilter }`
|
||||
|
||||
|
||||
const sidebarTagToTag = (tag: MaterialSidebarTag): Tag => ({
|
||||
@@ -73,43 +55,33 @@ const sidebarTagToTag = (tag: MaterialSidebarTag): Tag => ({
|
||||
matchedAlias: null })
|
||||
|
||||
|
||||
const tagSelectionShellClass = (selected: boolean): string =>
|
||||
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 justify-end md:justify-start flex-center">
|
||||
<label className="my-auto text-sm font-bold">素材:</label>
|
||||
const MaterialFilterButtons: FC<{
|
||||
materialFilter: MaterialFilter
|
||||
onChange: (materialFilter: MaterialFilter) => void
|
||||
}> = ({ materialFilter, onChange }) => (
|
||||
<div className="flex flex-wrap gap-2">
|
||||
{FILTERS.map (value => (
|
||||
<button
|
||||
key={value}
|
||||
type="button"
|
||||
onClick={() => onChange (value)}
|
||||
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']))}>
|
||||
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' }`}>
|
||||
{FILTER_LABELS[value]}
|
||||
</button>))}
|
||||
</div>)
|
||||
@@ -117,14 +89,12 @@ const MaterialFilterButtons: FC<{ materialFilter: MaterialFilter
|
||||
|
||||
const MaterialTreeNode: FC<{
|
||||
materialFilter: MaterialFilter
|
||||
selectedTagId: number | null
|
||||
nestLevel?: number
|
||||
onChildren: (tagId: number, children: MaterialSidebarTag[]) => void
|
||||
openTags: Record<number, boolean>
|
||||
setOpenTags: Dispatch<SetStateAction<Record<number, boolean>>>
|
||||
tag: MaterialSidebarTag
|
||||
}> = ({ materialFilter, nestLevel = 0, onChildren, openTags, selectedTagId,
|
||||
setOpenTags, tag }) => {
|
||||
}> = ({ materialFilter, nestLevel = 0, onChildren, openTags, setOpenTags, tag }) => {
|
||||
const open = Boolean (openTags[tag.id])
|
||||
const { data } = useQuery ({
|
||||
queryKey: materialsKeys.tree ({ parentId: tag.id, materialFilter }),
|
||||
@@ -137,10 +107,10 @@ const MaterialTreeNode: FC<{
|
||||
}, [data, onChildren, open, tag.children.length, tag.id])
|
||||
|
||||
return (
|
||||
<>
|
||||
<Fragment>
|
||||
<li>
|
||||
<div className="flex flex-center">
|
||||
<div className="flex-none w-4 my-auto">
|
||||
<div className="flex">
|
||||
<div className="flex-none w-4">
|
||||
{tag.hasChildren && (
|
||||
<button
|
||||
type="button"
|
||||
@@ -149,17 +119,14 @@ const MaterialTreeNode: FC<{
|
||||
{open ? <>−</> : '+'}
|
||||
</button>)}
|
||||
</div>
|
||||
<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}
|
||||
title={tag.name}
|
||||
withCount={false}
|
||||
withWiki={false}
|
||||
to={materialPath (tag.id, materialFilter)}/>
|
||||
</div>
|
||||
<div className="flex-1 truncate">
|
||||
<TagLink
|
||||
tag={sidebarTagToTag (tag)}
|
||||
nestLevel={nestLevel}
|
||||
title={tag.name}
|
||||
withCount={false}
|
||||
withWiki={false}
|
||||
to={materialPath (tag.name, materialFilter)}/>
|
||||
</div>
|
||||
</div>
|
||||
</li>
|
||||
@@ -171,44 +138,23 @@ const MaterialTreeNode: FC<{
|
||||
tag={child}
|
||||
nestLevel={nestLevel + 1}
|
||||
materialFilter={materialFilter}
|
||||
selectedTagId={selectedTagId}
|
||||
openTags={openTags}
|
||||
setOpenTags={setOpenTags}
|
||||
onChildren={onChildren}/>))}
|
||||
</ul>)}
|
||||
</>)
|
||||
</Fragment>)
|
||||
}
|
||||
|
||||
|
||||
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 MobileMaterialTreeNode: FC<{
|
||||
depth?: number
|
||||
materialFilter: MaterialFilter
|
||||
onChildren: (tagId: number, children: MaterialSidebarTag[]) => void
|
||||
openTags: Record<number, boolean>
|
||||
setOpenTags: Dispatch<SetStateAction<Record<number, boolean>>>
|
||||
tag: MaterialSidebarTag
|
||||
}> = ({ depth = 0, materialFilter, onChildren, openTags, 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 }),
|
||||
@@ -219,155 +165,50 @@ const MobileMaterialTreeNode: FC<{ depth?: number
|
||||
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 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="flex flex-row-reverse items-start gap-2">
|
||||
<div className="flex flex-col items-center gap-1">
|
||||
<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}>
|
||||
className="rounded-xl border border-stone-300 bg-white px-3 py-2 text-sm
|
||||
text-stone-900 shadow-sm dark:border-stone-700 dark:bg-stone-900
|
||||
dark:text-stone-100"
|
||||
style={{ writingMode: 'vertical-rl' }}>
|
||||
<TagLink
|
||||
tag={sidebarTagToTag (tag)}
|
||||
title={tag.name}
|
||||
withCount={false}
|
||||
withWiki={false}
|
||||
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)]"/>
|
||||
to={materialPath (tag.name, materialFilter)}/>
|
||||
</div>
|
||||
{tag.hasChildren && (
|
||||
<button
|
||||
ref={buttonRef}
|
||||
type="button"
|
||||
onClick={() => setOpenTags (prev => ({ ...prev, [tag.id]: !prev[tag.id] }))}
|
||||
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
|
||||
className="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 ? <>−</> : '+'}
|
||||
</button>)}
|
||||
</div>
|
||||
{open && tag.children.length > 0 && (
|
||||
<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>
|
||||
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}
|
||||
openTags={openTags}
|
||||
setOpenTags={setOpenTags}
|
||||
onChildren={onChildren}/>
|
||||
</div>))}
|
||||
</div>)}
|
||||
</div>)
|
||||
}
|
||||
@@ -377,14 +218,11 @@ const MaterialSidebar: FC = () => {
|
||||
const location = useLocation ()
|
||||
const navigate = useNavigate ()
|
||||
const qs = new URLSearchParams (location.search)
|
||||
const materialFilter = parseMaterialFilter (qs.get ('material_filter'), 'any')
|
||||
const selectedTagId = Number (qs.get ('tag_id') ?? 0) || null
|
||||
const materialFilter = parseMaterialFilter (qs.get ('material_filter'), 'present')
|
||||
|
||||
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 }),
|
||||
@@ -404,29 +242,6 @@ 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[]) => {
|
||||
@@ -448,7 +263,6 @@ const MaterialSidebar: FC = () => {
|
||||
key={tag.id}
|
||||
tag={tag}
|
||||
materialFilter={materialFilter}
|
||||
selectedTagId={selectedTagId}
|
||||
openTags={openTags}
|
||||
setOpenTags={setOpenTags}
|
||||
onChildren={setChildren}/>)))
|
||||
@@ -456,23 +270,17 @@ 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 flex h-[25dvh] min-h-0 flex-col
|
||||
overflow-hidden">
|
||||
dark:text-stone-100 md:hidden">
|
||||
<MaterialFilterButtons
|
||||
materialFilter={materialFilter}
|
||||
onChange={handleFilterChange}/>
|
||||
<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">
|
||||
<div ref={mobileRailRef} className="mt-3 overflow-x-auto">
|
||||
<div className="flex min-w-max flex-row-reverse gap-3 pb-1">
|
||||
{visibleRootTags.map (tag => (
|
||||
<MobileMaterialTreeNode
|
||||
key={tag.id}
|
||||
tag={tag}
|
||||
availableInlineSizePx={mobileAvailableInlineSizePx}
|
||||
materialFilter={materialFilter}
|
||||
selectedTagId={selectedTagId}
|
||||
openTags={openTags}
|
||||
setOpenTags={setOpenTags}
|
||||
onChildren={setChildren}/>))}
|
||||
|
||||
@@ -28,12 +28,11 @@ type Props =
|
||||
|
||||
|
||||
const TagLink: FC<Props> = ({ tag,
|
||||
nestLevel = 0,
|
||||
linkFlg = true,
|
||||
withWiki = true,
|
||||
withCount = true,
|
||||
className,
|
||||
...props }) => {
|
||||
nestLevel = 0,
|
||||
linkFlg = true,
|
||||
withWiki = true,
|
||||
withCount = true,
|
||||
...props }) => {
|
||||
const spanClass = cn (
|
||||
`text-${ TAG_COLOUR[tag.category] }-${ LIGHT_COLOUR_SHADE }`,
|
||||
`dark:text-${ TAG_COLOUR[tag.category] }-${ DARK_COLOUR_SHADE }`)
|
||||
@@ -106,7 +105,7 @@ const TagLink: FC<Props> = ({ tag,
|
||||
</span>)}
|
||||
{tag.matchedAlias != null && (
|
||||
<>
|
||||
<span className={cn (spanClass, className)} {...props}>
|
||||
<span className={spanClass} {...props}>
|
||||
{tag.matchedAlias}
|
||||
</span>
|
||||
<> → </>
|
||||
@@ -115,12 +114,12 @@ const TagLink: FC<Props> = ({ tag,
|
||||
? (
|
||||
<PrefetchLink
|
||||
to={`/posts?${ (new URLSearchParams ({ tags: tag.name })).toString () }`}
|
||||
className={cn (linkClass, className)}
|
||||
className={linkClass}
|
||||
{...props}>
|
||||
{tag.name}
|
||||
</PrefetchLink>)
|
||||
: (
|
||||
<span className={cn (spanClass, className)}
|
||||
<span className={spanClass}
|
||||
{...props}>
|
||||
{tag.name}
|
||||
</span>)}
|
||||
|
||||
@@ -7,36 +7,30 @@ import Separator from '@/components/MenuSeparator'
|
||||
import PrefetchLink from '@/components/PrefetchLink'
|
||||
import TopNavUser from '@/components/TopNavUser'
|
||||
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 { fetchMaterial } from '@/lib/materials'
|
||||
import { cn } from '@/lib/utils'
|
||||
import { fetchWikiPage } from '@/lib/wiki'
|
||||
|
||||
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 }
|
||||
|
||||
|
||||
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
|
||||
export const menuOutline = ({ tag, wikiId, user, pathName }: {
|
||||
tag?: Tag | null
|
||||
wikiId: number | null
|
||||
user: User | null,
|
||||
pathName: string }): Menu => {
|
||||
const postCount = 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' },
|
||||
@@ -55,18 +49,12 @@ export const menuOutline = (
|
||||
visible: tagFlg },
|
||||
{ name: '履歴', to: `/tags/changes?id=${ tag?.id }`,
|
||||
visible: tagFlg && tag?.category !== 'nico' }] },
|
||||
{ name: '素材', to: '/materials', visible: true, subMenu: [
|
||||
{ name: '素材', to: '/materials', visible: false, subMenu: [
|
||||
{ name: '一覧', to: '/materials' },
|
||||
{ name: '検索', to: '/materials/search', visible: false },
|
||||
{ name: '追加', to: '/materials/new' },
|
||||
{ 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: '全体履歴', to: '/materials/changes', visible: false },
|
||||
{ name: 'ヘルプ', to: '/wiki/ヘルプ:素材集' }] },
|
||||
{ name: 'Wiki', to: '/wiki/ヘルプ:ホーム', base: '/wiki', subMenu: [
|
||||
{ name: '検索', to: '/wiki' },
|
||||
{ name: '新規', to: '/wiki/new' },
|
||||
@@ -131,23 +119,15 @@ const TopNav: FC<Props> = ({ user }) => {
|
||||
queryFn: () => fetchWikiPage (wikiIdStr, { }) })
|
||||
|
||||
const tagFlg = /^\/tags\/\d+/.test (location.pathname)
|
||||
const materialFlg = /^\/materials\/\d+/.test (location.pathname)
|
||||
const effectiveTitle = (((tagFlg || materialFlg)
|
||||
? location.pathname.split ('/')[2]
|
||||
: wikiPage?.title)
|
||||
?? '')
|
||||
const effectiveTitle = (tagFlg ? 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, 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 moreMenu = menu.filter (item =>
|
||||
!(item.visible ?? true)
|
||||
|
||||
@@ -1,14 +1,12 @@
|
||||
import React from 'react'
|
||||
|
||||
import { cn } from '@/lib/utils'
|
||||
|
||||
import type { FC } from 'react'
|
||||
|
||||
type Props = { children: React.ReactNode; className?: string }
|
||||
type Props = { children: React.ReactNode }
|
||||
|
||||
|
||||
const PageTitle: FC<Props> = ({ children, className, ...rest }) => (
|
||||
<h1 className={cn ('text-2xl font-bold mb-2', className)} {...rest}>
|
||||
const PageTitle: FC<Props> = ({ children }) => (
|
||||
<h1 className="text-2xl font-bold mb-2">
|
||||
{children}
|
||||
</h1>)
|
||||
|
||||
|
||||
@@ -1,19 +1,19 @@
|
||||
import * as React from 'react'
|
||||
|
||||
import { cn } from '@/lib/utils'
|
||||
|
||||
const Input = React.forwardRef<HTMLInputElement, React.ComponentProps<'input'>>(
|
||||
({ className, type, ...props }, ref) => {
|
||||
return (
|
||||
<input
|
||||
type={type}
|
||||
className={cn(
|
||||
'flex h-10 w-full rounded-md border border-input bg-background px-3 py-2 text-base ring-offset-background file:border-0 file:bg-transparent file:text-sm file:font-medium file:text-foreground placeholder:text-muted-foreground focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring focus-visible:ring-offset-2 disabled:cursor-not-allowed disabled:opacity-50 md:text-sm',
|
||||
className)}
|
||||
ref={ref}
|
||||
{...props}
|
||||
/>)
|
||||
})
|
||||
Input.displayName = 'Input'
|
||||
|
||||
export { Input }
|
||||
import * as React from "react"
|
||||
|
||||
import { cn } from "@/lib/utils"
|
||||
|
||||
const Input = React.forwardRef<HTMLInputElement, React.ComponentProps<"input">>(
|
||||
({ className, type, ...props }, ref) => {
|
||||
return (
|
||||
<input
|
||||
type={type}
|
||||
className={cn(
|
||||
"flex h-10 w-full rounded-md border border-input bg-background px-3 py-2 text-base ring-offset-background file:border-0 file:bg-transparent file:text-sm file:font-medium file:text-foreground placeholder:text-muted-foreground focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring focus-visible:ring-offset-2 disabled:cursor-not-allowed disabled:opacity-50 md:text-sm",
|
||||
className
)}
|
||||
ref={ref}
|
||||
{...props}
|
||||
/>
)
|
||||
}
)
|
||||
Input.displayName = "Input"
|
||||
|
||||
export { Input }
|
||||
|
||||
@@ -1,26 +1,26 @@
|
||||
'use client'
|
||||
|
||||
import * as React from 'react'
|
||||
import * as SwitchPrimitives from '@radix-ui/react-switch'
|
||||
|
||||
import { cn } from '@/lib/utils'
|
||||
|
||||
const Switch = React.forwardRef<
|
||||
React.ElementRef<typeof SwitchPrimitives.Root>,
|
||||
React.ComponentPropsWithoutRef<typeof SwitchPrimitives.Root>
|
||||
>(({ className, ...props }, ref) => (
|
||||
<SwitchPrimitives.Root
|
||||
className={cn(
|
||||
'peer inline-flex h-6 w-11 shrink-0 cursor-pointer items-center rounded-full border-2 border-transparent transition-colors focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring focus-visible:ring-offset-2 focus-visible:ring-offset-background disabled:cursor-not-allowed disabled:opacity-50 data-[state=checked]:bg-primary data-[state=unchecked]:bg-input',
|
||||
className)}
|
||||
{...props}
|
||||
ref={ref}
|
||||
>
|
||||
<SwitchPrimitives.Thumb
|
||||
className={cn(
|
||||
'pointer-events-none block h-5 w-5 rounded-full bg-background shadow-lg ring-0 transition-transform data-[state=checked]:translate-x-5 data-[state=unchecked]:translate-x-0')}
|
||||
/>
|
||||
</SwitchPrimitives.Root>))
|
||||
Switch.displayName = SwitchPrimitives.Root.displayName
|
||||
|
||||
export { Switch }
|
||||
"use client"
|
||||
|
||||
import * as React from "react"
|
||||
import * as SwitchPrimitives from "@radix-ui/react-switch"
|
||||
|
||||
import { cn } from "@/lib/utils"
|
||||
|
||||
const Switch = React.forwardRef<
|
||||
React.ElementRef<typeof SwitchPrimitives.Root>,
|
||||
React.ComponentPropsWithoutRef<typeof SwitchPrimitives.Root>
|
||||
>(({ className, ...props }, ref) => (
|
||||
<SwitchPrimitives.Root
|
||||
className={cn(
|
||||
"peer inline-flex h-6 w-11 shrink-0 cursor-pointer items-center rounded-full border-2 border-transparent transition-colors focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring focus-visible:ring-offset-2 focus-visible:ring-offset-background disabled:cursor-not-allowed disabled:opacity-50 data-[state=checked]:bg-primary data-[state=unchecked]:bg-input",
|
||||
className
)}
|
||||
{...props}
|
||||
ref={ref}
|
||||
>
|
||||
<SwitchPrimitives.Thumb
|
||||
className={cn(
|
||||
"pointer-events-none block h-5 w-5 rounded-full bg-background shadow-lg ring-0 transition-transform data-[state=checked]:translate-x-5 data-[state=unchecked]:translate-x-0"
)}
|
||||
/>
|
||||
</SwitchPrimitives.Root>
))
|
||||
Switch.displayName = SwitchPrimitives.Root.displayName
|
||||
|
||||
export { Switch }
|
||||
|
||||
+29
-20
@@ -1,31 +1,45 @@
|
||||
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,
|
||||
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 MaterialIndexResponse = {
|
||||
materials: Material[]
|
||||
count: number
|
||||
}
|
||||
|
||||
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
|
||||
@@ -34,16 +48,11 @@ export const parseMaterialFilter = (
|
||||
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,
|
||||
media_kind: mediaKind,
|
||||
...(tagId != null && { tag_id: tagId }),
|
||||
...(includeDescendants && { include_descendants: '1' }),
|
||||
...(groupBy !== 'none' && { group_by: groupBy }),
|
||||
...(createdFrom && { created_from: createdFrom }),
|
||||
...(createdTo && { created_to: createdTo }),
|
||||
...(updatedFrom && { updated_from: updatedFrom }),
|
||||
|
||||
@@ -7,9 +7,9 @@ import { buildMaterial, buildTag } from '@/test/factories'
|
||||
import { renderWithProviders } from '@/test/render'
|
||||
|
||||
const api = vi.hoisted (() => ({
|
||||
apiGet: vi.fn (),
|
||||
apiPut: vi.fn (),
|
||||
isApiError: vi.fn (),
|
||||
apiGet: vi.fn (),
|
||||
apiPatch: vi.fn (),
|
||||
apiPut: vi.fn (),
|
||||
}))
|
||||
|
||||
const wikiApi = vi.hoisted (() => ({
|
||||
@@ -35,11 +35,7 @@ const renderPage = () =>
|
||||
describe ('MaterialDetailPage', () => {
|
||||
beforeEach (() => {
|
||||
vi.clearAllMocks ()
|
||||
api.apiGet.mockImplementation (async (path: string) =>
|
||||
path === '/tags/autocomplete'
|
||||
? []
|
||||
: buildMaterial ({ id: 8 }))
|
||||
api.isApiError.mockReturnValue (false)
|
||||
api.apiGet.mockResolvedValue ([])
|
||||
wikiApi.fetchWikiPages.mockResolvedValue ([])
|
||||
vi.stubGlobal ('fetch', vi.fn (async () => ({
|
||||
blob: async () => new Blob (['image'], { type: 'image/png' }),
|
||||
@@ -90,22 +86,4 @@ describe ('MaterialDetailPage', () => {
|
||||
expect (formData.get ('export_paths[legacy_drive]')).toBe ('素材/new.png')
|
||||
expect (toastApi.toast).toHaveBeenCalledWith ({ title: '更新成功!' })
|
||||
})
|
||||
|
||||
it ('shows not found when material API returns 404', async () => {
|
||||
api.isApiError.mockReturnValue (true)
|
||||
api.apiGet.mockRejectedValueOnce ({ response: { status: 404 } })
|
||||
|
||||
renderPage ()
|
||||
|
||||
expect (await screen.findByText ('素材が見つかりませんでした.')).toBeInTheDocument ()
|
||||
})
|
||||
|
||||
it ('shows an error for non-404 material API failures', async () => {
|
||||
api.isApiError.mockReturnValue (false)
|
||||
api.apiGet.mockRejectedValueOnce (new Error ('network error'))
|
||||
|
||||
renderPage ()
|
||||
|
||||
expect (await screen.findByText ('素材の取得に失敗しました.')).toBeInTheDocument ()
|
||||
})
|
||||
})
|
||||
|
||||
@@ -8,6 +8,7 @@ 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'
|
||||
@@ -118,6 +119,12 @@ 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}/>))
|
||||
@@ -127,12 +134,17 @@ const MaterialDetailPage: FC = () => {
|
||||
<audio src={material.file} controls/>)))}
|
||||
|
||||
<TabGroup>
|
||||
{material.tag && (
|
||||
<Tab name="Wiki">
|
||||
<Tab name="Wiki">
|
||||
{material.tag
|
||||
? (
|
||||
<WikiBody
|
||||
title={material.tag.name}
|
||||
body={material.wikiPageBody ?? undefined}/>
|
||||
</Tab>)}
|
||||
body={material.wikiPageBody ?? undefined}/>)
|
||||
: (
|
||||
<p className="text-stone-700 dark:text-stone-300">
|
||||
タグ未設定の素材です.
|
||||
</p>)}
|
||||
</Tab>
|
||||
|
||||
<Tab name="編輯">
|
||||
<div className="max-w-wl space-y-4 pt-2">
|
||||
|
||||
@@ -80,7 +80,14 @@ const MaterialHistoryPage: FC = () => {
|
||||
</Helmet>
|
||||
|
||||
<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
|
||||
onSubmit={handleSearch}
|
||||
@@ -105,6 +112,20 @@ 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
|
||||
@@ -129,6 +150,7 @@ 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"/>
|
||||
@@ -141,6 +163,7 @@ 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>
|
||||
@@ -157,6 +180,7 @@ 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}
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
import { fireEvent, screen, waitFor } from '@testing-library/react'
|
||||
import { beforeEach, describe, expect, it, vi } from 'vitest'
|
||||
import { screen, waitFor } from '@testing-library/react'
|
||||
import { describe, expect, it, vi } from 'vitest'
|
||||
|
||||
import MaterialListPage from '@/pages/materials/MaterialListPage'
|
||||
import { buildMaterial, buildTag } from '@/test/factories'
|
||||
@@ -12,169 +12,51 @@ const api = vi.hoisted (() => ({
|
||||
vi.mock ('@/lib/api', () => api)
|
||||
|
||||
describe ('MaterialListPage', () => {
|
||||
beforeEach (() => {
|
||||
vi.clearAllMocks ()
|
||||
api.apiGet.mockResolvedValue ({ materials: [], count: 0 })
|
||||
it ('shows the empty selection guide without a tag query', () => {
|
||||
renderWithProviders (<MaterialListPage/>, { route: '/materials' })
|
||||
|
||||
expect (screen.getByText ('左のリストから照会したいタグを選択してください。')).toBeInTheDocument ()
|
||||
expect (screen.getByRole ('link', { name: '素材を新規追加する' })).toHaveAttribute (
|
||||
'href',
|
||||
'/materials/new',
|
||||
)
|
||||
})
|
||||
|
||||
it ('loads the material index on the initial page', async () => {
|
||||
renderWithProviders (<MaterialListPage/>, { route: '/materials' })
|
||||
it ('loads materials for a tag query', async () => {
|
||||
const tag = {
|
||||
...buildTag ({
|
||||
id: 4,
|
||||
name: '素材タグ',
|
||||
category: 'material',
|
||||
}),
|
||||
material: buildMaterial ({ id: 8, contentType: 'image/png', file: 'image.png' }),
|
||||
children: [],
|
||||
}
|
||||
api.apiGet.mockResolvedValueOnce (tag)
|
||||
|
||||
renderWithProviders (<MaterialListPage/>, { route: '/materials?tag=%E7%B4%A0%E6%9D%90' })
|
||||
|
||||
await waitFor (() => {
|
||||
expect (api.apiGet).toHaveBeenCalledWith (
|
||||
'/materials',
|
||||
{ params: {
|
||||
tag_state: 'all',
|
||||
media_kind: 'all',
|
||||
sort: 'created_at',
|
||||
direction: 'desc',
|
||||
page: 1,
|
||||
limit: 20,
|
||||
} },
|
||||
'/tags/name/%E7%B4%A0%E6%9D%90/materials',
|
||||
)
|
||||
})
|
||||
expect (await screen.findByText ('素材はありません。')).toBeInTheDocument ()
|
||||
expect (await screen.findByRole ('link', { name: '素材タグ' })).toBeInTheDocument ()
|
||||
expect (screen.getByRole ('link', { name: '' })).toHaveAttribute ('href', '/materials/8')
|
||||
})
|
||||
|
||||
it ('shows materials in the default card view', async () => {
|
||||
it ('offers adding a missing non-meme material', async () => {
|
||||
api.apiGet.mockResolvedValueOnce ({
|
||||
materials: [
|
||||
buildMaterial ({
|
||||
id: 8,
|
||||
tag: buildTag ({ name: '素材タグ', category: 'material' }),
|
||||
thumbnail: 'thumb.png',
|
||||
mediaKind: 'image',
|
||||
contentType: 'image/png',
|
||||
}),
|
||||
],
|
||||
count: 1,
|
||||
...buildTag ({ name: '未登録', category: 'material' }),
|
||||
material: null,
|
||||
children: [],
|
||||
})
|
||||
|
||||
renderWithProviders (<MaterialListPage/>, { route: '/materials' })
|
||||
renderWithProviders (<MaterialListPage/>, { route: '/materials?tag=x' })
|
||||
|
||||
expect ((await screen.findByText ('素材タグ')).closest ('a'))
|
||||
.toHaveAttribute ('href', '/materials/8')
|
||||
expect (screen.getByText (/画像 \/ 令和8年1月2日/)).toBeInTheDocument ()
|
||||
})
|
||||
|
||||
it ('submits list filters as material index params', async () => {
|
||||
renderWithProviders (<MaterialListPage/>, { route: '/materials' })
|
||||
|
||||
fireEvent.change (screen.getByPlaceholderText ('タグ名 / URL / ファイル名'), {
|
||||
target: { value: '虹夏' },
|
||||
})
|
||||
const selects = screen.getAllByRole ('combobox')
|
||||
fireEvent.change (selects[0], {
|
||||
target: { value: 'untagged' },
|
||||
})
|
||||
fireEvent.change (selects[1], {
|
||||
target: { value: 'image' },
|
||||
})
|
||||
fireEvent.click (screen.getByRole ('button', { name: '検索' }))
|
||||
|
||||
await waitFor (() => {
|
||||
expect (api.apiGet).toHaveBeenCalledWith (
|
||||
'/materials',
|
||||
expect.objectContaining ({ params: expect.objectContaining ({
|
||||
q: '虹夏',
|
||||
tag_state: 'untagged',
|
||||
media_kind: 'image',
|
||||
}) }),
|
||||
)
|
||||
})
|
||||
})
|
||||
|
||||
it ('keeps a route back to the material search top for untagged materials', async () => {
|
||||
renderWithProviders (
|
||||
<MaterialListPage/>,
|
||||
{ route: '/materials?tag_state=untagged&material_filter=any' },
|
||||
)
|
||||
|
||||
expect (await screen.findByRole (
|
||||
'link',
|
||||
{ name: '素材検索トップへ戻る' },
|
||||
)).toHaveAttribute ('href', '/materials?material_filter=any')
|
||||
})
|
||||
|
||||
it ('uses list view for detailed material rows', async () => {
|
||||
api.apiGet.mockResolvedValueOnce ({
|
||||
materials: [
|
||||
buildMaterial ({
|
||||
id: 9,
|
||||
tag: buildTag ({ name: '詳細素材', category: 'material' }),
|
||||
mediaKind: 'file_other',
|
||||
fileByteSize: 2048,
|
||||
}),
|
||||
],
|
||||
count: 1,
|
||||
})
|
||||
|
||||
renderWithProviders (<MaterialListPage/>, { route: '/materials?view=list' })
|
||||
|
||||
expect (await screen.findByRole ('link', { name: '詳細素材' })).toHaveAttribute (
|
||||
expect (await screen.findByRole ('link', { name: '追加' })).toHaveAttribute (
|
||||
'href',
|
||||
'/materials/9',
|
||||
)
|
||||
expect (screen.getByText ('サイズ:')).toBeInTheDocument ()
|
||||
expect (screen.getByText ('2.0 KB')).toBeInTheDocument ()
|
||||
})
|
||||
|
||||
it ('shows the selected tag scope and tag-specific add links', async () => {
|
||||
api.apiGet.mockResolvedValueOnce ({
|
||||
materials: [
|
||||
buildMaterial ({
|
||||
id: 10,
|
||||
tag: buildTag ({ id: 30, name: '泣き', category: 'material' }),
|
||||
}),
|
||||
],
|
||||
count: 1,
|
||||
tagScope: {
|
||||
tag: { id: 20, name: '伊地知ニジカ', category: 'material' },
|
||||
includeDescendants: true,
|
||||
},
|
||||
groups: [
|
||||
{
|
||||
key: 'tag:30',
|
||||
tag: { id: 30, name: '泣き', category: 'material' },
|
||||
materialIds: [10],
|
||||
count: 1,
|
||||
},
|
||||
],
|
||||
})
|
||||
|
||||
renderWithProviders (
|
||||
<MaterialListPage/>,
|
||||
{ route: '/materials?tag_id=20&include_descendants=1&group_by=parent_tag' },
|
||||
)
|
||||
|
||||
expect (await screen.findByText (
|
||||
(_, element) => element?.textContent === '伊地知ニジカ 配下の素材を表示中',
|
||||
)).toBeInTheDocument ()
|
||||
|
||||
expect (screen.getByRole ('link', { name: '泣き' })).toHaveAttribute (
|
||||
'href',
|
||||
'/materials?tag_id=30&include_descendants=1&group_by=parent_tag&material_filter=present',
|
||||
)
|
||||
expect (screen.getByRole ('link', { name: 'タグ選択を解除' })).toHaveAttribute (
|
||||
'href',
|
||||
'/materials?material_filter=present',
|
||||
)
|
||||
})
|
||||
|
||||
it ('shows a clear link when tag_id does not resolve to tag_scope', async () => {
|
||||
api.apiGet.mockResolvedValueOnce ({
|
||||
materials: [],
|
||||
count: 0,
|
||||
tagScope: null,
|
||||
groups: [],
|
||||
})
|
||||
|
||||
renderWithProviders (<MaterialListPage/>, { route: '/materials?tag_id=999' })
|
||||
|
||||
expect (await screen.findByText ('選択中タグが見つかりません.')).toBeInTheDocument ()
|
||||
expect (screen.getByRole ('link', { name: 'タグ選択を解除' })).toHaveAttribute (
|
||||
'href',
|
||||
'/materials?material_filter=present',
|
||||
'/materials/new?tag=%E6%9C%AA%E7%99%BB%E9%8C%B2',
|
||||
)
|
||||
})
|
||||
})
|
||||
|
||||
@@ -10,23 +10,21 @@ import FormField from '@/components/common/FormField'
|
||||
import PageTitle from '@/components/common/PageTitle'
|
||||
import Pagination from '@/components/common/Pagination'
|
||||
import MainArea from '@/components/layout/MainArea'
|
||||
import { SITE_TITLE } from '@/config'
|
||||
import { API_BASE_URL, 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,
|
||||
MaterialIndexDirection,
|
||||
MaterialIndexMediaKind,
|
||||
MaterialIndexSort,
|
||||
MaterialIndexTagState,
|
||||
MaterialIndexView } from '@/types'
|
||||
|
||||
const MEDIA_KIND_LABELS: Record<Material['mediaKind'], string> = {
|
||||
image: '画像',
|
||||
@@ -41,16 +39,16 @@ const MEDIA_FILTER_LABELS: Record<MaterialIndexMediaKind, string> = {
|
||||
video: '動画',
|
||||
audio: '音声',
|
||||
file_other: 'その他ファイル',
|
||||
url_only: '外部リンクのみ'}
|
||||
url_only: 'URL のみ'}
|
||||
|
||||
const SORT_LABELS: Record<MaterialIndexSort, string> = {
|
||||
created_at: '作成日時',
|
||||
updated_at: '更新日時',
|
||||
tag_name: 'タグ名',
|
||||
media_kind: '種類',
|
||||
file_byte_size: '容量',
|
||||
version_no: '版',
|
||||
id: 'Id.'}
|
||||
file_byte_size: 'ファイルサイズ',
|
||||
version_no: 'バージョン',
|
||||
id: 'ID'}
|
||||
|
||||
|
||||
const setIf = (qs: URLSearchParams, key: string, value: string | null) => {
|
||||
@@ -81,36 +79,6 @@ const materialTitle = (material: Material): string =>
|
||||
material.tag?.name ?? `素材 #${ material.id }`
|
||||
|
||||
|
||||
const groupedTagPath = (
|
||||
tagId: number,
|
||||
materialFilter: MaterialFilter,
|
||||
): string =>
|
||||
`/materials?tag_id=${ tagId }&include_descendants=1&group_by=parent_tag`
|
||||
+ `&material_filter=${ materialFilter }`
|
||||
|
||||
|
||||
const materialNewPath = (
|
||||
tagName: string,
|
||||
returnTo: string,
|
||||
): string =>
|
||||
`/materials/new?tag=${ encodeURIComponent (tagName) }`
|
||||
+ `&return_to=${ encodeURIComponent (returnTo) }`
|
||||
|
||||
|
||||
const clearedTagSelectionPath = (
|
||||
locationSearch: string,
|
||||
materialFilter: MaterialFilter,
|
||||
): string => {
|
||||
const qs = new URLSearchParams (locationSearch)
|
||||
qs.delete ('tag_id')
|
||||
qs.delete ('include_descendants')
|
||||
qs.delete ('group_by')
|
||||
qs.delete ('page')
|
||||
qs.set ('material_filter', materialFilter)
|
||||
return `/materials?${ qs.toString () }`
|
||||
}
|
||||
|
||||
|
||||
const MaterialThumb: FC<{ material: Material }> = ({ material }) => (
|
||||
<div
|
||||
className={`flex aspect-square h-[180px] w-[180px] items-center justify-center
|
||||
@@ -118,7 +86,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="block h-full w-full object-cover"/>
|
||||
? <img src={material.thumbnail} alt="" className="h-full w-full object-contain"/>
|
||||
: (
|
||||
<span
|
||||
className="px-2 text-2xl leading-tight"
|
||||
@@ -186,28 +154,6 @@ const MaterialListItem: FC<{ material: Material }> = ({ material }) => (
|
||||
</article>)
|
||||
|
||||
|
||||
const GroupHeading: FC<{
|
||||
count: number
|
||||
materialFilter: MaterialFilter
|
||||
title: string
|
||||
tagId: number
|
||||
}> = ({ count, materialFilter, title, tagId }) => (
|
||||
<div className="flex items-center gap-2 border-b border-stone-200 pb-2
|
||||
dark:border-stone-700">
|
||||
<PrefetchLink
|
||||
to={groupedTagPath (tagId, materialFilter)}
|
||||
className="font-medium text-sky-700 underline underline-offset-2
|
||||
dark:text-sky-300 w-full">
|
||||
{title}
|
||||
</PrefetchLink>
|
||||
<div className="text-right w-auto">
|
||||
<span className="text-nowrap text-sm text-stone-600 dark:text-stone-300">
|
||||
{count} 件
|
||||
</span>
|
||||
</div>
|
||||
</div>)
|
||||
|
||||
|
||||
const MaterialListPage: FC = () => {
|
||||
const location = useLocation ()
|
||||
const navigate = useNavigate ()
|
||||
@@ -216,10 +162,7 @@ const MaterialListPage: FC = () => {
|
||||
|
||||
const page = Number (query.get ('page') ?? 1)
|
||||
const limit = Number (query.get ('limit') ?? 20)
|
||||
const qQuery = query.get ('q') ?? ''
|
||||
const tagIdQuery = Number (query.get ('tag_id') ?? 0)
|
||||
const tagId = tagIdQuery > 0 ? tagIdQuery : null
|
||||
const includeDescendants = query.get ('include_descendants') === '1'
|
||||
const qQuery = query.get ('q') ?? query.get ('tag') ?? ''
|
||||
const tagState = query.get ('unclassified') === '1'
|
||||
? 'untagged'
|
||||
: parseOption<MaterialIndexTagState> (
|
||||
@@ -239,11 +182,6 @@ const MaterialListPage: FC = () => {
|
||||
query.get ('direction'),
|
||||
['asc', 'desc'],
|
||||
'desc')
|
||||
const groupByQuery = parseOption<MaterialIndexGroupBy> (
|
||||
query.get ('group_by'),
|
||||
['none', 'parent_tag'],
|
||||
'none')
|
||||
const groupBy = tagId == null ? 'none' : groupByQuery
|
||||
const view = parseOption<MaterialIndexView> (query.get ('view'), ['card', 'list'], 'card')
|
||||
const createdFromQuery = query.get ('created_from') ?? ''
|
||||
const createdToQuery = query.get ('created_to') ?? ''
|
||||
@@ -253,7 +191,6 @@ const MaterialListPage: FC = () => {
|
||||
const [q, setQ] = useState ('')
|
||||
const [tagStateInput, setTagStateInput] = useState<MaterialIndexTagState> ('all')
|
||||
const [mediaKindInput, setMediaKindInput] = useState<MaterialIndexMediaKind> ('all')
|
||||
const [groupByInput, setGroupByInput] = useState<MaterialIndexGroupBy> ('none')
|
||||
const [createdFrom, setCreatedFrom] = useState<string | null> (null)
|
||||
const [createdTo, setCreatedTo] = useState<string | null> (null)
|
||||
const [updatedFrom, setUpdatedFrom] = useState<string | null> (null)
|
||||
@@ -263,9 +200,6 @@ const MaterialListPage: FC = () => {
|
||||
q: qQuery,
|
||||
tagState,
|
||||
mediaKind,
|
||||
tagId,
|
||||
includeDescendants,
|
||||
groupBy,
|
||||
createdFrom: createdFromQuery,
|
||||
createdTo: createdToQuery,
|
||||
updatedFrom: updatedFromQuery,
|
||||
@@ -278,33 +212,18 @@ const MaterialListPage: FC = () => {
|
||||
const { data, isLoading, isError } = useQuery ({
|
||||
queryKey: materialsKeys.index (keys),
|
||||
queryFn: () => fetchMaterials (keys)})
|
||||
const tagScope = data?.tagScope ?? null
|
||||
const materials = data?.materials ?? []
|
||||
const groups = data?.groups ?? []
|
||||
const totalPages = data ? Math.ceil (data.count / limit) : 0
|
||||
const materialsById = useMemo (
|
||||
() => new Map (materials.map (material => [material.id, material])),
|
||||
[materials],
|
||||
)
|
||||
const groupedMaterialIds = useMemo (
|
||||
() => new Set (groups.flatMap (group => group.materialIds)),
|
||||
[groups],
|
||||
)
|
||||
const ungroupedMaterials = useMemo (
|
||||
() => materials.filter (material => !groupedMaterialIds.has (material.id)),
|
||||
[groupedMaterialIds, materials],
|
||||
)
|
||||
|
||||
useEffect (() => {
|
||||
setQ (qQuery)
|
||||
setTagStateInput (tagState)
|
||||
setMediaKindInput (mediaKind)
|
||||
setGroupByInput (groupBy)
|
||||
setCreatedFrom (createdFromQuery)
|
||||
setCreatedTo (createdToQuery)
|
||||
setUpdatedFrom (updatedFromQuery)
|
||||
setUpdatedTo (updatedToQuery)
|
||||
}, [createdFromQuery, createdToQuery, groupBy, mediaKind, qQuery, tagState,
|
||||
}, [createdFromQuery, createdToQuery, mediaKind, qQuery, tagState,
|
||||
updatedFromQuery, updatedToQuery])
|
||||
|
||||
const search = (e: FormEvent) => {
|
||||
@@ -320,77 +239,19 @@ const MaterialListPage: FC = () => {
|
||||
setIf (qs, 'updated_to', updatedTo)
|
||||
qs.set ('sort', sort)
|
||||
qs.set ('direction', direction)
|
||||
qs.set ('group_by', tagId == null ? 'none' : groupByInput)
|
||||
qs.set ('view', view)
|
||||
qs.set ('page', '1')
|
||||
qs.set ('limit', String (limit))
|
||||
qs.set ('material_filter', materialFilter)
|
||||
if (tagId != null)
|
||||
qs.set ('tag_id', String (tagId))
|
||||
|
||||
if (includeDescendants)
|
||||
qs.set ('include_descendants', '1')
|
||||
|
||||
navigate (`/materials?${ qs.toString () }`)
|
||||
}
|
||||
|
||||
const updateQuery = (changes: Record<string, string>) => {
|
||||
const qs = new URLSearchParams (location.search)
|
||||
Object.entries (changes).forEach (([key, value]) => {
|
||||
if (value === '')
|
||||
qs.delete (key)
|
||||
else
|
||||
qs.set (key, value)
|
||||
})
|
||||
Object.entries (changes).forEach (([key, value]) => qs.set (key, value))
|
||||
navigate (`/materials?${ qs.toString () }`)
|
||||
}
|
||||
|
||||
const renderMaterialCollection = (rows: Material[]) =>
|
||||
view === 'card'
|
||||
? (
|
||||
<div className="grid grid-cols-[repeat(auto-fill,minmax(196px,1fr))]
|
||||
justify-items-center gap-4">
|
||||
{rows.map (material => (
|
||||
<MaterialCard key={material.id} material={material}/>))}
|
||||
</div>)
|
||||
: (
|
||||
<div className="space-y-3">
|
||||
{rows.map (material => (
|
||||
<MaterialListItem key={material.id} material={material}/>))}
|
||||
</div>)
|
||||
|
||||
const renderGroupedMaterials = (materialGroups: MaterialIndexGroup[]) => (
|
||||
<div className="space-y-6">
|
||||
{materialGroups.map (group => {
|
||||
const groupMaterials =
|
||||
group.materialIds
|
||||
.map (materialId => materialsById.get (materialId))
|
||||
.filter ((material): material is Material => material != null)
|
||||
|
||||
if (groupMaterials.length === 0)
|
||||
return null
|
||||
|
||||
return (
|
||||
<section key={group.key} className="space-y-3">
|
||||
<GroupHeading
|
||||
tagId={group.tag.id}
|
||||
title={group.tag.name}
|
||||
count={group.count}
|
||||
materialFilter={materialFilter}/>
|
||||
{renderMaterialCollection (groupMaterials)}
|
||||
</section>)
|
||||
})}
|
||||
{ungroupedMaterials.length > 0 && (
|
||||
<section className="space-y-3">
|
||||
<div className="border-b border-stone-200 pb-2 dark:border-stone-700">
|
||||
<span className="font-medium text-stone-900 dark:text-stone-100">
|
||||
その他
|
||||
</span>
|
||||
</div>
|
||||
{renderMaterialCollection (ungroupedMaterials)}
|
||||
</section>)}
|
||||
</div>)
|
||||
|
||||
return (
|
||||
<MainArea>
|
||||
<Helmet>
|
||||
@@ -402,15 +263,35 @@ 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 className="my-auto">素材管理</PageTitle>
|
||||
<PageTitle>素材一覧</PageTitle>
|
||||
<div className="flex flex-wrap gap-2">
|
||||
{/* TODO: 局所出力を可能にする */}
|
||||
{/* <a
|
||||
<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
|
||||
href={`${ API_BASE_URL }/materials/download.zip?profile=legacy_drive`}
|
||||
target="_blank"
|
||||
rel="noopener noreferrer"
|
||||
@@ -418,38 +299,10 @@ 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>
|
||||
|
||||
{tagScope && (
|
||||
<div className="flex flex-wrap items-center gap-3 rounded-lg border
|
||||
border-sky-200 bg-sky-50 px-4 py-3 text-sm text-sky-900
|
||||
dark:border-sky-800 dark:bg-sky-950 dark:text-sky-100">
|
||||
<span>
|
||||
{tagScope.tag.name}
|
||||
{tagScope.includeDescendants ? ' 配下の素材を表示中' : ' の素材を表示中'}
|
||||
</span>
|
||||
<PrefetchLink
|
||||
to={clearedTagSelectionPath (location.search, materialFilter)}
|
||||
className="font-medium underline underline-offset-2
|
||||
text-sky-700 dark:text-sky-300">
|
||||
タグ選択を解除
|
||||
</PrefetchLink>
|
||||
</div>)}
|
||||
{(tagId != null && tagScope == null) && (
|
||||
<div className="flex flex-wrap items-center gap-3 rounded-lg border
|
||||
border-amber-200 bg-amber-50 px-4 py-3 text-sm text-amber-900
|
||||
dark:border-amber-800 dark:bg-amber-950 dark:text-amber-100">
|
||||
<span>選択中タグが見つかりません.</span>
|
||||
<PrefetchLink
|
||||
to={clearedTagSelectionPath (location.search, materialFilter)}
|
||||
className="font-medium underline underline-offset-2
|
||||
text-amber-800 dark:text-amber-200">
|
||||
タグ選択を解除
|
||||
</PrefetchLink>
|
||||
</div>)}
|
||||
|
||||
{tagState === 'untagged' && (
|
||||
<PrefetchLink
|
||||
to={`/materials?material_filter=${ materialFilter }`}
|
||||
@@ -542,7 +395,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"
|
||||
@@ -555,7 +408,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>
|
||||
|
||||
@@ -583,22 +436,20 @@ const MaterialListPage: FC = () => {
|
||||
{isError && (
|
||||
<p className="text-red-600 dark:text-red-300">素材一覧の取得に失敗しました.</p>)}
|
||||
{(!isLoading && !isError && materials.length === 0) && (
|
||||
<p>
|
||||
素材はありません。
|
||||
{(tagScope && ['character', 'material'].includes (tagScope.tag.category)) && (
|
||||
<>
|
||||
<PrefetchLink
|
||||
to={materialNewPath (tagScope.tag.name, location.pathname + location.search)}
|
||||
className="font-medium underline underline-offset-2
|
||||
text-sky-700 dark:text-sky-300">
|
||||
追加してください
|
||||
</PrefetchLink>。
|
||||
</>)}
|
||||
</p>)}
|
||||
<p>素材はありません.</p>)}
|
||||
{materials.length > 0 && (
|
||||
groupBy === 'parent_tag' && groups.length > 0
|
||||
? renderGroupedMaterials (groups)
|
||||
: renderMaterialCollection (materials))}
|
||||
view === 'card'
|
||||
? (
|
||||
<div className="grid grid-cols-[repeat(auto-fill,minmax(196px,1fr))]
|
||||
justify-items-center gap-4">
|
||||
{materials.map (material => (
|
||||
<MaterialCard key={material.id} material={material}/>))}
|
||||
</div>)
|
||||
: (
|
||||
<div className="space-y-3">
|
||||
{materials.map (material => (
|
||||
<MaterialListItem key={material.id} material={material}/>))}
|
||||
</div>))}
|
||||
<Pagination page={page} totalPages={totalPages}/>
|
||||
</div>
|
||||
</MainArea>)
|
||||
|
||||
@@ -1,6 +1,5 @@
|
||||
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'
|
||||
@@ -18,11 +17,6 @@ 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 ()
|
||||
@@ -75,50 +69,4 @@ 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 ()
|
||||
})
|
||||
})
|
||||
|
||||
@@ -27,8 +27,6 @@ const MaterialNewPage: FC = () => {
|
||||
const location = useLocation ()
|
||||
const query = new URLSearchParams (location.search)
|
||||
const tagQuery = query.get ('tag') ?? ''
|
||||
const returnToQuery = query.get ('return_to') ?? ''
|
||||
const safeReturnTo = returnToQuery.startsWith ('/materials') ? returnToQuery : ''
|
||||
|
||||
const navigate = useNavigate ()
|
||||
|
||||
@@ -56,7 +54,7 @@ const MaterialNewPage: FC = () => {
|
||||
onSuccess: async () => {
|
||||
await qc.invalidateQueries ({ queryKey: materialsKeys.root })
|
||||
toast ({ title: '送信成功!' })
|
||||
navigate (safeReturnTo || '/materials')
|
||||
navigate (`/materials?tag=${ encodeURIComponent (tag) }`)
|
||||
},
|
||||
onError: error => {
|
||||
applyValidationError (error)
|
||||
|
||||
@@ -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
|
||||
@@ -2,13 +2,17 @@ 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'
|
||||
|
||||
@@ -18,11 +22,11 @@ import type { MaterialSyncSuppressionSourceKind } from '@/types'
|
||||
|
||||
const SOURCE_KIND_LABELS: Record<MaterialSyncSuppressionSourceKind, string> = {
|
||||
uri: 'URI',
|
||||
google_drive_path: 'Google Drive ファイル',
|
||||
google_drive_path_prefix: 'Google Drive フォルダ',
|
||||
google_drive_file: 'Google Drive ファイル Id.',
|
||||
legacy_drive_path: '汎用ファイル',
|
||||
legacy_drive_path_prefix: '汎用フォルダ' }
|
||||
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'}
|
||||
|
||||
const REASONS = [
|
||||
'copyright_high_risk',
|
||||
@@ -32,23 +36,7 @@ const REASONS = [
|
||||
'malware_or_dangerous_file',
|
||||
'duplicate_or_low_quality',
|
||||
'source_owner_request',
|
||||
'other'] as const
|
||||
|
||||
type MaterialSyncSuppressionReason = typeof REASONS[number]
|
||||
|
||||
const REASON_NAMES: Record<MaterialSyncSuppressionReason, string> = {
|
||||
['copyright_high_risk']: '著作権への懸念',
|
||||
['copyright_takedown']: '著作者からの申出',
|
||||
['adult_or_sensitive']: '成人向け',
|
||||
['personal_information']: '個人情報',
|
||||
['malware_or_dangerous_file']: '危険なソフトウェア',
|
||||
['duplicate_or_low_quality']: '重複',
|
||||
['source_owner_request']: '同期元管理者からの申出',
|
||||
['other']: 'その他' } as const
|
||||
|
||||
|
||||
const reasonName = (reason: string): string =>
|
||||
REASON_NAMES[reason as MaterialSyncSuppressionReason] ?? reason
|
||||
'other']
|
||||
|
||||
|
||||
const MaterialSyncSuppressionsPage: FC = () => {
|
||||
@@ -58,7 +46,7 @@ const MaterialSyncSuppressionsPage: FC = () => {
|
||||
const [sourceUri, setSourceUri] = useState ('')
|
||||
const [drivePath, setDrivePath] = useState ('')
|
||||
const [driveFileId, setDriveFileId] = useState ('')
|
||||
const [reason, setReason] = useState<MaterialSyncSuppressionReason> (REASONS[0])
|
||||
const [reason, setReason] = useState (REASONS[0])
|
||||
|
||||
const { data, isError, isLoading } = useQuery ({
|
||||
queryKey: materialsKeys.suppressions (),
|
||||
@@ -94,11 +82,18 @@ const MaterialSyncSuppressionsPage: FC = () => {
|
||||
return (
|
||||
<MainArea>
|
||||
<Helmet>
|
||||
<title>{`素材同期抑止 | ${ SITE_TITLE }`}</title>
|
||||
<title>{`同期元抑止 | ${ SITE_TITLE }`}</title>
|
||||
</Helmet>
|
||||
|
||||
<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
|
||||
onSubmit={handleSubmit}
|
||||
@@ -120,7 +115,7 @@ const MaterialSyncSuppressionsPage: FC = () => {
|
||||
</select>)}
|
||||
</FormField>
|
||||
|
||||
<FormField label="同期元 URI">
|
||||
<FormField label="Source URI">
|
||||
{({ invalid }) => (
|
||||
<input
|
||||
type="text"
|
||||
@@ -129,7 +124,7 @@ const MaterialSyncSuppressionsPage: FC = () => {
|
||||
className={inputClass (invalid)}/>)}
|
||||
</FormField>
|
||||
|
||||
<FormField label="Google Drive パス">
|
||||
<FormField label="Drive path">
|
||||
{({ invalid }) => (
|
||||
<input
|
||||
type="text"
|
||||
@@ -138,7 +133,7 @@ const MaterialSyncSuppressionsPage: FC = () => {
|
||||
className={inputClass (invalid)}/>)}
|
||||
</FormField>
|
||||
|
||||
<FormField label="Google Drive ファイル Id.">
|
||||
<FormField label="Drive file ID">
|
||||
{({ invalid }) => (
|
||||
<input
|
||||
type="text"
|
||||
@@ -147,15 +142,15 @@ const MaterialSyncSuppressionsPage: FC = () => {
|
||||
className={inputClass (invalid)}/>)}
|
||||
</FormField>
|
||||
|
||||
<FormField label="事由">
|
||||
<FormField label="理由">
|
||||
{({ invalid }) => (
|
||||
<select
|
||||
value={reason}
|
||||
onChange={e => setReason (e.target.value as MaterialSyncSuppressionReason)}
|
||||
onChange={e => setReason (e.target.value)}
|
||||
className={inputClass (invalid)}>
|
||||
{REASONS.map (value => (
|
||||
<option key={value} value={value}>
|
||||
{REASON_NAMES[value]}
|
||||
{value}
|
||||
</option>))}
|
||||
</select>)}
|
||||
</FormField>
|
||||
@@ -190,8 +185,7 @@ const MaterialSyncSuppressionsPage: FC = () => {
|
||||
{suppression.normalizedSourceKey}
|
||||
</div>
|
||||
<div className="mt-2 text-sm text-stone-600 dark:text-stone-400">
|
||||
事由: {reasonName (suppression.reason)} /
|
||||
登録: {dateString (suppression.createdAt)}
|
||||
理由: {suppression.reason} / 登録: {dateString (suppression.createdAt)}
|
||||
</div>
|
||||
</article>))}
|
||||
</div>
|
||||
|
||||
@@ -88,26 +88,12 @@ export type MaterialIndexSort =
|
||||
|
||||
export type MaterialIndexTagState = 'all' | 'tagged' | 'untagged'
|
||||
|
||||
export type MaterialIndexGroupBy = 'none' | 'parent_tag'
|
||||
|
||||
export type MaterialIndexView = 'card' | 'list'
|
||||
|
||||
export type MaterialTagScope = {
|
||||
tag: {
|
||||
id: number
|
||||
name: string
|
||||
category: Category
|
||||
}
|
||||
includeDescendants: boolean
|
||||
}
|
||||
|
||||
export type FetchMaterialsParams = {
|
||||
q: string
|
||||
tagState: MaterialIndexTagState
|
||||
mediaKind: MaterialIndexMediaKind
|
||||
tagId: number | null
|
||||
includeDescendants: boolean
|
||||
groupBy: MaterialIndexGroupBy
|
||||
createdFrom: string
|
||||
createdTo: string
|
||||
updatedFrom: string
|
||||
@@ -184,23 +170,6 @@ export type MaterialExportItem = {
|
||||
exportPath: string
|
||||
enabled: boolean }
|
||||
|
||||
export type MaterialIndexGroup = {
|
||||
key: string
|
||||
tag: {
|
||||
id: number
|
||||
name: string
|
||||
category: Category
|
||||
}
|
||||
materialIds: number[]
|
||||
count: number }
|
||||
|
||||
export type MaterialIndexResponse = {
|
||||
materials: Material[]
|
||||
count: number
|
||||
groups?: MaterialIndexGroup[]
|
||||
tagScope?: MaterialTagScope | null
|
||||
}
|
||||
|
||||
export type MaterialVersion = {
|
||||
id: number
|
||||
materialId: number
|
||||
@@ -210,11 +179,6 @@ export type MaterialVersion = {
|
||||
tagName: string | null
|
||||
tagCategory: Category | null
|
||||
url: string | null
|
||||
sourceKind: string | null
|
||||
sourceUri: string | null
|
||||
sourcePath: string | null
|
||||
sourceFileId: string | null
|
||||
normalizedSourceKey: string | null
|
||||
fileBlobId: number | null
|
||||
fileFilename: string | null
|
||||
fileContentType: string | null
|
||||
|
||||
新しい課題から参照
ユーザをブロックする