コミットを比較
12 コミット
| 作成者 | SHA1 | 日付 | |
|---|---|---|---|
| 3f2cddcd07 | |||
| 88b0195e03 | |||
| 7e0b6910f6 | |||
| e0aa14f0b5 | |||
| fdf652951a | |||
| f96ddb65f1 | |||
| 5657fa7e7b | |||
| 19a185d5b5 | |||
| acd062f289 | |||
| 877876b661 | |||
| bffd4c422a | |||
| 776dea87d9 |
@@ -271,7 +271,12 @@ const value =
|
|||||||
- In TypeScript and TSX, convert every leading run of 8 spaces to a tab
|
- In TypeScript and TSX, convert every leading run of 8 spaces to a tab
|
||||||
character.
|
character.
|
||||||
- A leading tab is exactly equivalent to 8 leading spaces.
|
- A leading tab is exactly equivalent to 8 leading spaces.
|
||||||
- Never place a closing parenthesis at the beginning of a line.
|
- In TypeScript and TSX function declarations, including `const` arrow
|
||||||
|
function declarations, when the parameter list spans multiple lines, always
|
||||||
|
put the closing parenthesis at the beginning of its own line before the return
|
||||||
|
type or `=>`.
|
||||||
|
- In TypeScript and TSX, never place a closing parenthesis at the beginning of
|
||||||
|
a line except for a multi-line function declaration parameter list.
|
||||||
- Never place a closing square bracket at the beginning of a line.
|
- Never place a closing square bracket at the beginning of a line.
|
||||||
- For object literals and other associative-array-style braces, do not place
|
- For object literals and other associative-array-style braces, do not place
|
||||||
the closing brace at the beginning of a line. Function, lambda, callback, and
|
the closing brace at the beginning of a line. Function, lambda, callback, and
|
||||||
|
|||||||
@@ -35,6 +35,11 @@ class MaterialVersionsController < ApplicationController
|
|||||||
tag_name: row.tag_name,
|
tag_name: row.tag_name,
|
||||||
tag_category: row.tag_category,
|
tag_category: row.tag_category,
|
||||||
url: row.url,
|
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_blob_id: row.file_blob_id,
|
||||||
file_filename: row.file_filename,
|
file_filename: row.file_filename,
|
||||||
file_content_type: row.file_content_type,
|
file_content_type: row.file_content_type,
|
||||||
|
|||||||
@@ -1,3 +1,6 @@
|
|||||||
|
require 'set'
|
||||||
|
|
||||||
|
|
||||||
class MaterialsController < ApplicationController
|
class MaterialsController < ApplicationController
|
||||||
rescue_from MaterialZipExporter::EmptyExportError, with: :render_zip_empty
|
rescue_from MaterialZipExporter::EmptyExportError, with: :render_zip_empty
|
||||||
rescue_from MaterialZipExporter::DuplicatePathError, with: :render_zip_duplicate_path
|
rescue_from MaterialZipExporter::DuplicatePathError, with: :render_zip_duplicate_path
|
||||||
@@ -13,12 +16,14 @@ class MaterialsController < ApplicationController
|
|||||||
offset = (page - 1) * limit
|
offset = (page - 1) * limit
|
||||||
|
|
||||||
filters = material_index_filters
|
filters = material_index_filters
|
||||||
|
tag_graph = material_index_tag_graph(filters)
|
||||||
q = Material.includes(:material_export_items,
|
q = Material.includes(:material_export_items,
|
||||||
thumbnail_attachment: :blob,
|
thumbnail_attachment: :blob,
|
||||||
file_attachment: :blob,
|
file_attachment: :blob,
|
||||||
tag: :tag_name)
|
tag: :tag_name)
|
||||||
q = q.where(tag_id: nil) if filters[:tag_state] == 'untagged'
|
q = q.where(tag_id: nil) if filters[:tag_state] == 'untagged'
|
||||||
q = q.where.not(tag_id: nil) if filters[:tag_state] == 'tagged'
|
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_from]) if filters[:created_from]
|
||||||
q = q.where('materials.created_at <= ?', filters[:created_to]) if filters[:created_to]
|
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]
|
q = q.where('materials.updated_at >= ?', filters[:updated_from]) if filters[:updated_from]
|
||||||
@@ -37,8 +42,16 @@ class MaterialsController < ApplicationController
|
|||||||
.offset(offset)
|
.offset(offset)
|
||||||
.to_a
|
.to_a
|
||||||
|
|
||||||
render json: { materials: MaterialRepr.list_many(materials, host: request.base_url),
|
response = { materials: MaterialRepr.list_many(materials, host: request.base_url),
|
||||||
count: }
|
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
|
||||||
end
|
end
|
||||||
|
|
||||||
def show
|
def show
|
||||||
@@ -198,9 +211,18 @@ class MaterialsController < ApplicationController
|
|||||||
direction = params[:direction].to_s.downcase
|
direction = params[:direction].to_s.downcase
|
||||||
direction = 'desc' unless ['asc', 'desc'].include?(direction)
|
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,
|
{ q: params[:q].to_s.strip.presence,
|
||||||
tag_state:,
|
tag_state:,
|
||||||
media_kind:,
|
media_kind:,
|
||||||
|
tag_id:,
|
||||||
|
include_descendants: bool?(:include_descendants),
|
||||||
|
group_by:,
|
||||||
created_from: parse_time_param(:created_from),
|
created_from: parse_time_param(:created_from),
|
||||||
created_to: parse_time_param(:created_to),
|
created_to: parse_time_param(:created_to),
|
||||||
updated_from: parse_time_param(:updated_from),
|
updated_from: parse_time_param(:updated_from),
|
||||||
@@ -270,6 +292,147 @@ class MaterialsController < ApplicationController
|
|||||||
end
|
end
|
||||||
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
|
def material_index_order_sql filters
|
||||||
direction = filters[:direction] == 'asc' ? 'ASC' : 'DESC'
|
direction = filters[:direction] == 'asc' ? 'ASC' : 'DESC'
|
||||||
sort_sql =
|
sort_sql =
|
||||||
@@ -360,10 +523,7 @@ class MaterialsController < ApplicationController
|
|||||||
content_type: file.content_type,
|
content_type: file.content_type,
|
||||||
)
|
)
|
||||||
|
|
||||||
if file_sha256.present?
|
MaterialFileSha256.assign_metadata_sha256!(blob, file_sha256)
|
||||||
blob.metadata['sha256'] = file_sha256
|
|
||||||
blob.save! if blob.changed?
|
|
||||||
end
|
|
||||||
|
|
||||||
blob
|
blob
|
||||||
ensure
|
ensure
|
||||||
|
|||||||
@@ -25,6 +25,7 @@ class PostVersionsController < ApplicationController
|
|||||||
SQL
|
SQL
|
||||||
.select('post_versions.*', 'prev.title AS prev_title', 'prev.url AS prev_url',
|
.select('post_versions.*', 'prev.title AS prev_title', 'prev.url AS prev_url',
|
||||||
'prev.thumbnail_base AS prev_thumbnail_base', 'prev.tags AS prev_tags',
|
'prev.thumbnail_base AS prev_thumbnail_base', 'prev.tags AS prev_tags',
|
||||||
|
'prev.video_ms AS prev_video_ms',
|
||||||
'prev.original_created_from AS prev_original_created_from',
|
'prev.original_created_from AS prev_original_created_from',
|
||||||
'prev.original_created_before AS prev_original_created_before')
|
'prev.original_created_before AS prev_original_created_before')
|
||||||
q = q.where('post_versions.post_id = ?', post_id) if post_id
|
q = q.where('post_versions.post_id = ?', post_id) if post_id
|
||||||
@@ -74,6 +75,10 @@ class PostVersionsController < ApplicationController
|
|||||||
current: row.thumbnail_base,
|
current: row.thumbnail_base,
|
||||||
prev: row.attributes['prev_thumbnail_base']
|
prev: row.attributes['prev_thumbnail_base']
|
||||||
},
|
},
|
||||||
|
video_ms: {
|
||||||
|
current: row.video_ms,
|
||||||
|
prev: row.attributes['prev_video_ms']
|
||||||
|
},
|
||||||
tags: build_version_tags(cur_tags, prev_tags),
|
tags: build_version_tags(cur_tags, prev_tags),
|
||||||
original_created_from: {
|
original_created_from: {
|
||||||
current: row.original_created_from&.iso8601,
|
current: row.original_created_from&.iso8601,
|
||||||
|
|||||||
@@ -1,6 +1,10 @@
|
|||||||
class PostsController < ApplicationController
|
class PostsController < ApplicationController
|
||||||
Event = Struct.new(:post, :tag, :user, :change_type, :timestamp, keyword_init: true)
|
Event = Struct.new(:post, :tag, :user, :change_type, :timestamp, keyword_init: true)
|
||||||
|
|
||||||
|
class VideoMsParseError < ArgumentError
|
||||||
|
;
|
||||||
|
end
|
||||||
|
|
||||||
def index
|
def index
|
||||||
url = params[:url].presence
|
url = params[:url].presence
|
||||||
title = params[:title].presence
|
title = params[:title].presence
|
||||||
@@ -45,7 +49,9 @@ class PostsController < ApplicationController
|
|||||||
.joins("LEFT JOIN (#{ pt_max_sql }) pt_max ON pt_max.post_id = posts.id")
|
.joins("LEFT JOIN (#{ pt_max_sql }) pt_max ON pt_max.post_id = posts.id")
|
||||||
.reselect('posts.*', Arel.sql("#{ updated_at_all_sql } AS updated_at_all"))
|
.reselect('posts.*', Arel.sql("#{ updated_at_all_sql } AS updated_at_all"))
|
||||||
.preload(:uploaded_user, :parents, :children,
|
.preload(:uploaded_user, :parents, :children,
|
||||||
tags: [:deerjikists, :materials, { tag_name: :wiki_page }])
|
active_post_tags: [:sections,
|
||||||
|
{ tag: [:deerjikists, :materials,
|
||||||
|
{ tag_name: :wiki_page }] }])
|
||||||
.with_attached_thumbnail
|
.with_attached_thumbnail
|
||||||
|
|
||||||
q = q.where('posts.url LIKE ?', "%#{ url }%") if url
|
q = q.where('posts.url LIKE ?', "%#{ url }%") if url
|
||||||
@@ -97,7 +103,9 @@ class PostsController < ApplicationController
|
|||||||
|
|
||||||
def random
|
def random
|
||||||
post = filtered_posts.preload(:uploaded_user, :parents, :children,
|
post = filtered_posts.preload(:uploaded_user, :parents, :children,
|
||||||
tags: [:deerjikists, :materials, { tag_name: :wiki_page }])
|
active_post_tags: [:sections,
|
||||||
|
{ tag: [:deerjikists, :materials,
|
||||||
|
{ tag_name: :wiki_page }] }])
|
||||||
.with_attached_thumbnail
|
.with_attached_thumbnail
|
||||||
.order('RAND()')
|
.order('RAND()')
|
||||||
.first
|
.first
|
||||||
@@ -110,7 +118,9 @@ class PostsController < ApplicationController
|
|||||||
post =
|
post =
|
||||||
Post
|
Post
|
||||||
.includes(:uploaded_user, :parents, :children,
|
.includes(:uploaded_user, :parents, :children,
|
||||||
tags: [:deerjikists, :materials, { tag_name: :wiki_page }])
|
active_post_tags: [:sections,
|
||||||
|
{ tag: [:deerjikists, :materials,
|
||||||
|
{ tag_name: :wiki_page }] }])
|
||||||
.with_attached_thumbnail
|
.with_attached_thumbnail
|
||||||
.find_by(id: params[:id])
|
.find_by(id: params[:id])
|
||||||
return head :not_found unless post
|
return head :not_found unless post
|
||||||
@@ -125,7 +135,7 @@ class PostsController < ApplicationController
|
|||||||
child_posts:,
|
child_posts:,
|
||||||
sibling_posts:,
|
sibling_posts:,
|
||||||
related:)
|
related:)
|
||||||
.merge(tags: build_tag_tree_for(post.tags))
|
.merge(tags: build_tag_tree_for(post))
|
||||||
end
|
end
|
||||||
|
|
||||||
def create
|
def create
|
||||||
@@ -140,24 +150,27 @@ class PostsController < ApplicationController
|
|||||||
original_created_from = params[:original_created_from]
|
original_created_from = params[:original_created_from]
|
||||||
original_created_before = params[:original_created_before]
|
original_created_before = params[:original_created_before]
|
||||||
parent_post_ids = parse_parent_post_ids
|
parent_post_ids = parse_parent_post_ids
|
||||||
|
resized_thumbnail = thumbnail.present? ? Post.resized_thumbnail_attachment(thumbnail) : nil
|
||||||
|
|
||||||
post = Post.new(title:, url:, thumbnail_base: nil, uploaded_user: current_user,
|
post = Post.new(title:, url:, thumbnail_base: nil, uploaded_user: current_user,
|
||||||
original_created_from:, original_created_before:)
|
original_created_from:, original_created_before:)
|
||||||
post.thumbnail.attach(thumbnail) if thumbnail.present?
|
post.thumbnail.attach(resized_thumbnail) if resized_thumbnail
|
||||||
|
|
||||||
ApplicationRecord.transaction do
|
ApplicationRecord.transaction do
|
||||||
post.save!
|
post.save!
|
||||||
|
|
||||||
tags = Tag.normalise_tags!(tag_names, deny_deprecated: true)
|
Tag.normalise_tags!(tag_names, deny_deprecated: true, with_sections: true) =>
|
||||||
|
{ tags:, sections: }
|
||||||
TagVersioning.record_tag_snapshots!(tags, created_by_user: current_user)
|
TagVersioning.record_tag_snapshots!(tags, created_by_user: current_user)
|
||||||
|
|
||||||
tags = Tag.expand_parent_tags(tags).reject(&:deprecated?)
|
tags = Tag.expand_parent_tags(tags).reject(&:deprecated?)
|
||||||
sync_post_tags!(post, tags)
|
post.video_ms = normalise_video_ms(tags)
|
||||||
|
validate_video_sections!(post.video_ms, sections)
|
||||||
|
post.save!
|
||||||
|
sync_post_tags!(post, tags, sections)
|
||||||
|
|
||||||
sync_parent_posts!(post, parent_post_ids)
|
sync_parent_posts!(post, parent_post_ids)
|
||||||
|
|
||||||
post.resized_thumbnail!
|
|
||||||
|
|
||||||
PostVersionRecorder.record!(post:, event_type: :create, created_by_user: current_user)
|
PostVersionRecorder.record!(post:, event_type: :create, created_by_user: current_user)
|
||||||
end
|
end
|
||||||
|
|
||||||
@@ -167,6 +180,12 @@ class PostsController < ApplicationController
|
|||||||
render_validation_error fields: { tags: 'ニコニコ・タグは直接指定できません.' }
|
render_validation_error fields: { tags: 'ニコニコ・タグは直接指定できません.' }
|
||||||
rescue Tag::DeprecatedTagNormalisationError
|
rescue Tag::DeprecatedTagNormalisationError
|
||||||
render_unprocessable_entity '廃止済みタグは付与できません.', field: :tags
|
render_unprocessable_entity '廃止済みタグは付与できません.', field: :tags
|
||||||
|
rescue Tag::SectionLiteralParseError
|
||||||
|
render_validation_error fields: { tags: ['タグ区間の記法が不正です.'] }
|
||||||
|
rescue VideoMsParseError
|
||||||
|
render_validation_error fields: { video_ms: ['動画時間の記法が不正です.'] }
|
||||||
|
rescue MiniMagick::Error
|
||||||
|
render_validation_error fields: { thumbnail: ['サムネイル画像の変換に失敗しました.'] }
|
||||||
rescue ArgumentError => e
|
rescue ArgumentError => e
|
||||||
render_validation_error fields: { parent_post_ids: [e.message] }
|
render_validation_error fields: { parent_post_ids: [e.message] }
|
||||||
rescue ActiveRecord::RecordInvalid => e
|
rescue ActiveRecord::RecordInvalid => e
|
||||||
@@ -223,6 +242,8 @@ class PostsController < ApplicationController
|
|||||||
original_created_from:,
|
original_created_from:,
|
||||||
original_created_before:,
|
original_created_before:,
|
||||||
tag_names:,
|
tag_names:,
|
||||||
|
video_ms_param: params[:video_ms],
|
||||||
|
duration_param: params[:duration],
|
||||||
parent_post_ids:)
|
parent_post_ids:)
|
||||||
|
|
||||||
snapshot_to_apply =
|
snapshot_to_apply =
|
||||||
@@ -253,12 +274,16 @@ class PostsController < ApplicationController
|
|||||||
|
|
||||||
post.reload
|
post.reload
|
||||||
json = PostRepr.base(post, current_user)
|
json = PostRepr.base(post, current_user)
|
||||||
json['tags'] = build_tag_tree_for(post.tags)
|
json['tags'] = build_tag_tree_for(post)
|
||||||
render json:, status: :ok
|
render json:, status: :ok
|
||||||
rescue Tag::NicoTagNormalisationError
|
rescue Tag::NicoTagNormalisationError
|
||||||
render_validation_error fields: { tags: ['ニコニコ・タグは直接指定できません.'] }
|
render_validation_error fields: { tags: ['ニコニコ・タグは直接指定できません.'] }
|
||||||
rescue Tag::DeprecatedTagNormalisationError
|
rescue Tag::DeprecatedTagNormalisationError
|
||||||
render_unprocessable_entity '廃止済みタグは付与できません.', field: :tags
|
render_unprocessable_entity '廃止済みタグは付与できません.', field: :tags
|
||||||
|
rescue Tag::SectionLiteralParseError
|
||||||
|
render_validation_error fields: { tags: ['タグ区間の記法が不正です.'] }
|
||||||
|
rescue VideoMsParseError
|
||||||
|
render_validation_error fields: { video_ms: ['動画時間の記法が不正です.'] }
|
||||||
rescue ArgumentError => e
|
rescue ArgumentError => e
|
||||||
render_validation_error fields: { parent_post_ids: [e.message] }
|
render_validation_error fields: { parent_post_ids: [e.message] }
|
||||||
rescue ActiveRecord::RecordInvalid => e
|
rescue ActiveRecord::RecordInvalid => e
|
||||||
@@ -357,7 +382,7 @@ class PostsController < ApplicationController
|
|||||||
def tagged_post_ids_for(name) =
|
def tagged_post_ids_for(name) =
|
||||||
Post.joins(tags: :tag_name).where(tag_names: { name: }).select(:id)
|
Post.joins(tags: :tag_name).where(tag_names: { name: }).select(:id)
|
||||||
|
|
||||||
def sync_post_tags! post, desired_tags
|
def sync_post_tags! post, desired_tags, sections
|
||||||
desired_tags.each do |t|
|
desired_tags.each do |t|
|
||||||
t.save! if t.new_record?
|
t.save! if t.new_record?
|
||||||
end
|
end
|
||||||
@@ -376,13 +401,21 @@ class PostsController < ApplicationController
|
|||||||
end
|
end
|
||||||
end
|
end
|
||||||
|
|
||||||
|
PostTagSection.where(post_id: post.id).destroy_all
|
||||||
|
sections.each do |tag_id, ranges|
|
||||||
|
ranges.each do |begin_ms, end_ms|
|
||||||
|
PostTagSection.create!(post_id: post.id, tag_id:, begin_ms:, end_ms:)
|
||||||
|
end
|
||||||
|
end
|
||||||
|
|
||||||
PostTag.where(post_id: post.id, tag_id: to_remove.to_a).kept.find_each do |pt|
|
PostTag.where(post_id: post.id, tag_id: to_remove.to_a).kept.find_each do |pt|
|
||||||
pt.discard_by!(current_user)
|
pt.discard_by!(current_user)
|
||||||
end
|
end
|
||||||
end
|
end
|
||||||
|
|
||||||
def build_tag_tree_for tags
|
def build_tag_tree_for post
|
||||||
tags = tags.reject(&:deprecated?).to_a
|
post_tags = post.active_post_tags.reject { |post_tag| post_tag.tag.deprecated? }
|
||||||
|
tags = post_tags.map(&:tag)
|
||||||
tag_ids = tags.map(&:id)
|
tag_ids = tags.map(&:id)
|
||||||
|
|
||||||
implications = TagImplication.where(parent_tag_id: tag_ids, tag_id: tag_ids)
|
implications = TagImplication.where(parent_tag_id: tag_ids, tag_id: tag_ids)
|
||||||
@@ -397,6 +430,9 @@ class PostsController < ApplicationController
|
|||||||
root_ids = tag_ids - child_ids
|
root_ids = tag_ids - child_ids
|
||||||
|
|
||||||
tags_by_id = tags.index_by(&:id)
|
tags_by_id = tags.index_by(&:id)
|
||||||
|
sections_by_tag_id = post_tags.to_h { |post_tag|
|
||||||
|
[post_tag.tag_id, post_tag.sections.as_json(only: [:begin_ms, :end_ms])]
|
||||||
|
}
|
||||||
|
|
||||||
memo = { }
|
memo = { }
|
||||||
|
|
||||||
@@ -404,8 +440,10 @@ class PostsController < ApplicationController
|
|||||||
tag = tags_by_id[tag_id]
|
tag = tags_by_id[tag_id]
|
||||||
return nil unless tag
|
return nil unless tag
|
||||||
|
|
||||||
|
sections = sections_by_tag_id.fetch(tag_id, [])
|
||||||
|
|
||||||
if path.include?(tag_id)
|
if path.include?(tag_id)
|
||||||
return TagRepr.inline(tag).merge(children: [])
|
return TagRepr.inline(tag).merge(children: [], sections:)
|
||||||
end
|
end
|
||||||
|
|
||||||
if memo.key?(tag_id)
|
if memo.key?(tag_id)
|
||||||
@@ -417,7 +455,7 @@ class PostsController < ApplicationController
|
|||||||
|
|
||||||
children = child_ids.filter_map { |cid| build_node.(cid, new_path) }
|
children = child_ids.filter_map { |cid| build_node.(cid, new_path) }
|
||||||
|
|
||||||
memo[tag_id] = TagRepr.inline(tag).merge(children:)
|
memo[tag_id] = TagRepr.inline(tag).merge(children:, sections:)
|
||||||
end
|
end
|
||||||
|
|
||||||
root_ids.filter_map { |id| build_node.call(id, []) }
|
root_ids.filter_map { |id| build_node.call(id, []) }
|
||||||
@@ -486,6 +524,7 @@ class PostsController < ApplicationController
|
|||||||
|
|
||||||
def post_snapshot_from_version version
|
def post_snapshot_from_version version
|
||||||
{ title: version.title,
|
{ title: version.title,
|
||||||
|
video_ms: version.respond_to?(:video_ms) ? version.video_ms : nil,
|
||||||
original_created_from: snapshot_time(version.original_created_from),
|
original_created_from: snapshot_time(version.original_created_from),
|
||||||
original_created_before: snapshot_time(version.original_created_before),
|
original_created_before: snapshot_time(version.original_created_before),
|
||||||
tag_names: editable_tag_names_from_version(version),
|
tag_names: editable_tag_names_from_version(version),
|
||||||
@@ -498,6 +537,7 @@ class PostsController < ApplicationController
|
|||||||
|
|
||||||
def post_snapshot_from_record post
|
def post_snapshot_from_record post
|
||||||
{ title: post.title,
|
{ title: post.title,
|
||||||
|
video_ms: post.video_ms,
|
||||||
original_created_from: snapshot_time(post.original_created_from),
|
original_created_from: snapshot_time(post.original_created_from),
|
||||||
original_created_before: snapshot_time(post.original_created_before),
|
original_created_before: snapshot_time(post.original_created_before),
|
||||||
tag_names: editable_tag_names_from_post(post),
|
tag_names: editable_tag_names_from_post(post),
|
||||||
@@ -505,16 +545,41 @@ class PostsController < ApplicationController
|
|||||||
end
|
end
|
||||||
|
|
||||||
def editable_tag_names_from_post post
|
def editable_tag_names_from_post post
|
||||||
post.tags.not_nico.where(deprecated_at: nil)
|
post
|
||||||
.joins(:tag_name).order('tag_names.name').pluck('tag_names.name')
|
.post_tags
|
||||||
|
.kept
|
||||||
|
.joins(tag: :tag_name)
|
||||||
|
.merge(Tag.not_nico)
|
||||||
|
.merge(Tag.where(deprecated_at: nil))
|
||||||
|
.includes(:sections, tag: :tag_name)
|
||||||
|
.order('tag_names.name')
|
||||||
|
.map do |post_tag|
|
||||||
|
name = post_tag.tag.tag_name.name
|
||||||
|
sections = post_tag.sections.sort_by(&:begin_ms)
|
||||||
|
|
||||||
|
next name if sections.empty?
|
||||||
|
|
||||||
|
"#{ name }#{ sections.map { Post.section_literal(_1) }.join }"
|
||||||
|
end
|
||||||
end
|
end
|
||||||
|
|
||||||
def post_incoming_snapshot title:, original_created_from:, original_created_before:,
|
def post_incoming_snapshot title:, original_created_from:, original_created_before:,
|
||||||
tag_names:, parent_post_ids:
|
tag_names:, video_ms_param:, duration_param:, parent_post_ids:
|
||||||
|
Tag.normalise_tags!(tag_names, with_tagme: false, deny_deprecated: true,
|
||||||
|
with_sections: true) =>
|
||||||
|
{ tags:, sections: }
|
||||||
|
|
||||||
|
tags = Tag.expand_parent_tags(tags).reject(&:deprecated?)
|
||||||
|
video_ms = normalise_video_ms(tags, video_ms_param:, duration_param:)
|
||||||
|
validate_video_sections!(video_ms, sections)
|
||||||
|
|
||||||
{ title:,
|
{ title:,
|
||||||
|
video_ms:,
|
||||||
original_created_from: snapshot_time(original_created_from),
|
original_created_from: snapshot_time(original_created_from),
|
||||||
original_created_before: snapshot_time(original_created_before),
|
original_created_before: snapshot_time(original_created_before),
|
||||||
tag_names: incoming_tag_names_for_snapshot(tag_names),
|
tag_names: tags.uniq(&:id).map { |tag|
|
||||||
|
"#{ tag.name }#{ sections[tag.id].to_a.map { section_literal(_1) }.join }"
|
||||||
|
}.sort,
|
||||||
parent_post_ids: parent_post_ids.sort }
|
parent_post_ids: parent_post_ids.sort }
|
||||||
end
|
end
|
||||||
|
|
||||||
@@ -537,11 +602,8 @@ class PostsController < ApplicationController
|
|||||||
value.to_s
|
value.to_s
|
||||||
end
|
end
|
||||||
|
|
||||||
def incoming_tag_names_for_snapshot raw_tag_names
|
def section_literal section
|
||||||
tags = Tag.normalise_tags!(raw_tag_names, with_tagme: false,
|
"[#{ Post.ms_to_time(section[0]) }-#{ section[1] ? Post.ms_to_time(section[1]) : '' }]"
|
||||||
deny_deprecated: true)
|
|
||||||
|
|
||||||
Tag.expand_parent_tags(tags).reject(&:deprecated?).map(&:name).uniq.sort
|
|
||||||
end
|
end
|
||||||
|
|
||||||
def post_conflict_json post:, base_version_no:, base_snapshot:,
|
def post_conflict_json post:, base_version_no:, base_snapshot:,
|
||||||
@@ -562,6 +624,8 @@ class PostsController < ApplicationController
|
|||||||
def post_snapshot_changes base_snapshot, current_snapshot, incoming_snapshot
|
def post_snapshot_changes base_snapshot, current_snapshot, incoming_snapshot
|
||||||
[scalar_snapshot_change(:title, 'タイトル',
|
[scalar_snapshot_change(:title, 'タイトル',
|
||||||
base_snapshot, current_snapshot, incoming_snapshot),
|
base_snapshot, current_snapshot, incoming_snapshot),
|
||||||
|
scalar_snapshot_change(:video_ms, '動画時間',
|
||||||
|
base_snapshot, current_snapshot, incoming_snapshot),
|
||||||
scalar_snapshot_change(:original_created_from, 'オリジナルの作成日時(以降)',
|
scalar_snapshot_change(:original_created_from, 'オリジナルの作成日時(以降)',
|
||||||
base_snapshot, current_snapshot, incoming_snapshot),
|
base_snapshot, current_snapshot, incoming_snapshot),
|
||||||
scalar_snapshot_change(:original_created_before, 'オリジナルの作成日時(より前)',
|
scalar_snapshot_change(:original_created_before, 'オリジナルの作成日時(より前)',
|
||||||
@@ -625,11 +689,14 @@ class PostsController < ApplicationController
|
|||||||
PostVersionRecorder.ensure_snapshot!(post, created_by_user: current_user)
|
PostVersionRecorder.ensure_snapshot!(post, created_by_user: current_user)
|
||||||
|
|
||||||
post.update!(title: snapshot[:title],
|
post.update!(title: snapshot[:title],
|
||||||
|
video_ms: snapshot[:video_ms],
|
||||||
original_created_from: snapshot[:original_created_from],
|
original_created_from: snapshot[:original_created_from],
|
||||||
original_created_before: snapshot[:original_created_before])
|
original_created_before: snapshot[:original_created_before])
|
||||||
|
|
||||||
editable_tags = Tag.normalise_tags!(snapshot[:tag_names], with_tagme: false,
|
Tag.normalise_tags!(snapshot[:tag_names], with_tagme: false,
|
||||||
deny_deprecated: true)
|
deny_deprecated: true,
|
||||||
|
with_sections: true) =>
|
||||||
|
{ tags: editable_tags, sections: }
|
||||||
TagVersioning.record_tag_snapshots!(editable_tags, created_by_user: current_user)
|
TagVersioning.record_tag_snapshots!(editable_tags, created_by_user: current_user)
|
||||||
|
|
||||||
readonly_tags = post.tags.nico.to_a
|
readonly_tags = post.tags.nico.to_a
|
||||||
@@ -637,14 +704,17 @@ class PostsController < ApplicationController
|
|||||||
tags = readonly_tags + editable_tags
|
tags = readonly_tags + editable_tags
|
||||||
tags = Tag.expand_parent_tags(tags).reject(&:deprecated?)
|
tags = Tag.expand_parent_tags(tags).reject(&:deprecated?)
|
||||||
|
|
||||||
sync_post_tags!(post, tags)
|
post.video_ms = tags.any? { _1.id == Tag.video.id } ? snapshot[:video_ms] : nil
|
||||||
|
validate_video_sections!(post.video_ms, sections)
|
||||||
|
post.save!
|
||||||
|
sync_post_tags!(post, tags, sections)
|
||||||
sync_parent_posts!(post, snapshot[:parent_post_ids])
|
sync_parent_posts!(post, snapshot[:parent_post_ids])
|
||||||
|
|
||||||
PostVersionRecorder.record!(post:, event_type: :update, created_by_user: current_user)
|
PostVersionRecorder.record!(post:, event_type: :update, created_by_user: current_user)
|
||||||
end
|
end
|
||||||
|
|
||||||
def merge_post_snapshots base_snapshot, current_snapshot, incoming_snapshot
|
def merge_post_snapshots base_snapshot, current_snapshot, incoming_snapshot
|
||||||
[:title, :original_created_from, :original_created_before].map {
|
[:title, :video_ms, :original_created_from, :original_created_before].map {
|
||||||
[_1, merge_scalar_snapshot_value(base_snapshot[_1],
|
[_1, merge_scalar_snapshot_value(base_snapshot[_1],
|
||||||
current_snapshot[_1],
|
current_snapshot[_1],
|
||||||
incoming_snapshot[_1])]
|
incoming_snapshot[_1])]
|
||||||
@@ -688,4 +758,44 @@ class PostsController < ApplicationController
|
|||||||
render_validation_error record
|
render_validation_error record
|
||||||
end
|
end
|
||||||
end
|
end
|
||||||
|
|
||||||
|
def normalise_video_ms tags, video_ms_param: params[:video_ms], duration_param: params[:duration]
|
||||||
|
return nil unless tags.any? { _1.id == Tag.video.id }
|
||||||
|
|
||||||
|
if video_ms_param.present?
|
||||||
|
video_ms = Integer(video_ms_param, exception: false)
|
||||||
|
raise VideoMsParseError unless video_ms&.positive?
|
||||||
|
|
||||||
|
return video_ms
|
||||||
|
end
|
||||||
|
|
||||||
|
return nil if duration_param.blank?
|
||||||
|
|
||||||
|
video_ms = Tag.time_to_ms!(duration_param.to_s, tag_name: '動画時間')
|
||||||
|
raise VideoMsParseError unless video_ms.positive?
|
||||||
|
|
||||||
|
video_ms
|
||||||
|
rescue Tag::SectionLiteralParseError
|
||||||
|
raise VideoMsParseError
|
||||||
|
end
|
||||||
|
|
||||||
|
def validate_video_sections! video_ms, sections
|
||||||
|
return unless video_ms
|
||||||
|
|
||||||
|
sections.each_value do |ranges|
|
||||||
|
ranges.each do |begin_ms, end_ms|
|
||||||
|
if begin_ms >= video_ms
|
||||||
|
post = Post.new
|
||||||
|
post.errors.add :video_ms, 'タグ区間の開始が動画時間以上です.'
|
||||||
|
raise ActiveRecord::RecordInvalid, post
|
||||||
|
end
|
||||||
|
|
||||||
|
if end_ms && end_ms > video_ms
|
||||||
|
post = Post.new
|
||||||
|
post.errors.add :video_ms, 'タグ区間の終端が動画時間を超えてゐます.'
|
||||||
|
raise ActiveRecord::RecordInvalid, post
|
||||||
|
end
|
||||||
|
end
|
||||||
|
end
|
||||||
|
end
|
||||||
end
|
end
|
||||||
|
|||||||
@@ -245,10 +245,7 @@ class TagsController < ApplicationController
|
|||||||
return render_unprocessable_entity('カテゴリは必須です.', field: :category) if category.blank?
|
return render_unprocessable_entity('カテゴリは必須です.', field: :category) if category.blank?
|
||||||
return render_unprocessable_entity '廃止状態は必須です.', field: :deprecated unless params.key?(:deprecated)
|
return render_unprocessable_entity '廃止状態は必須です.', field: :deprecated unless params.key?(:deprecated)
|
||||||
|
|
||||||
if (name != tag.name &&
|
return unless validate_tag_rename(tag, name)
|
||||||
tag.in?([Tag.tagme, Tag.bot, Tag.no_deerjikist, Tag.video, Tag.niconico]))
|
|
||||||
return render_unprocessable_entity 'システム・タグの名称は変更できません.', field: :name
|
|
||||||
end
|
|
||||||
|
|
||||||
alias_names = params[:aliases].to_s.split.uniq
|
alias_names = params[:aliases].to_s.split.uniq
|
||||||
parent_names = params[:parent_tags].to_s.split.uniq
|
parent_names = params[:parent_tags].to_s.split.uniq
|
||||||
@@ -274,7 +271,7 @@ class TagsController < ApplicationController
|
|||||||
else
|
else
|
||||||
tag.update!(category:, deprecated_at: deprecated ? Time.current : nil)
|
tag.update!(category:, deprecated_at: deprecated ? Time.current : nil)
|
||||||
end
|
end
|
||||||
tag.tag_name.update!(name:)
|
rename_tag_name!(tag, name) if name_changed
|
||||||
|
|
||||||
alias_names << old_name if name_changed
|
alias_names << old_name if name_changed
|
||||||
alias_names.delete(name)
|
alias_names.delete(name)
|
||||||
@@ -310,6 +307,8 @@ class TagsController < ApplicationController
|
|||||||
return render_unprocessable_entity 'ニコタグは廃止できません.', field: :deprecated
|
return render_unprocessable_entity 'ニコタグは廃止できません.', field: :deprecated
|
||||||
end
|
end
|
||||||
|
|
||||||
|
return unless validate_tag_rename(tag, name)
|
||||||
|
|
||||||
if tag.nico? || (category.present? && category == 'nico')
|
if tag.nico? || (category.present? && category == 'nico')
|
||||||
return render_unprocessable_entity 'ニコタグは変更できません.', field: :category
|
return render_unprocessable_entity 'ニコタグは変更できません.', field: :category
|
||||||
end
|
end
|
||||||
@@ -321,7 +320,7 @@ class TagsController < ApplicationController
|
|||||||
name_changed = name.present? && name != old_name
|
name_changed = name.present? && name != old_name
|
||||||
wiki_page = tag.tag_name.wiki_page if name_changed
|
wiki_page = tag.tag_name.wiki_page if name_changed
|
||||||
|
|
||||||
tag.tag_name.update!(name:) if name.present?
|
rename_tag_name!(tag, name) if name_changed
|
||||||
tag.update!(category:) if category.present?
|
tag.update!(category:) if category.present?
|
||||||
if deprecated_given && tag.deprecated? != deprecated
|
if deprecated_given && tag.deprecated? != deprecated
|
||||||
tag.update!(deprecated_at: deprecated ? Time.current : nil)
|
tag.update!(deprecated_at: deprecated ? Time.current : nil)
|
||||||
@@ -379,12 +378,20 @@ class TagsController < ApplicationController
|
|||||||
end
|
end
|
||||||
|
|
||||||
def visible_root_tag_ids graph
|
def visible_root_tag_ids graph
|
||||||
graph[:tags_by_id].filter_map do |tag_id, _attrs|
|
root_ids = Set.new
|
||||||
|
|
||||||
|
graph[:tags_by_id].each do |tag_id, attrs|
|
||||||
next unless visible_root_tag?(tag_id, graph)
|
next unless visible_root_tag?(tag_id, graph)
|
||||||
next unless visible_subtree?(tag_id, graph)
|
next unless visible_subtree?(tag_id, graph)
|
||||||
|
|
||||||
tag_id
|
if attrs[:deprecated]
|
||||||
|
collect_visible_child_tag_ids(tag_id, graph, root_ids, Set.new)
|
||||||
|
else
|
||||||
|
root_ids << tag_id
|
||||||
|
end
|
||||||
end
|
end
|
||||||
|
|
||||||
|
root_ids.to_a
|
||||||
end
|
end
|
||||||
|
|
||||||
def visible_root_tag? tag_id, graph
|
def visible_root_tag? tag_id, graph
|
||||||
@@ -527,6 +534,67 @@ class TagsController < ApplicationController
|
|||||||
created_by_user:)
|
created_by_user:)
|
||||||
end
|
end
|
||||||
|
|
||||||
|
def validate_tag_rename tag, name
|
||||||
|
return true if name.blank? || name == tag.name
|
||||||
|
|
||||||
|
if tag.in?([Tag.tagme, Tag.bot, Tag.no_deerjikist, Tag.video, Tag.niconico])
|
||||||
|
render_unprocessable_entity 'システム・タグの名称は変更できません.', field: :name
|
||||||
|
return false
|
||||||
|
end
|
||||||
|
|
||||||
|
target_tag_name = TagName.with_discarded.find_by(name:)
|
||||||
|
return true if target_tag_name.nil?
|
||||||
|
return true if target_tag_name.canonical_id?
|
||||||
|
|
||||||
|
render_unprocessable_entity 'その名前は既に使はれてゐます.', field: :name
|
||||||
|
false
|
||||||
|
end
|
||||||
|
|
||||||
|
def rename_tag_name! tag, name
|
||||||
|
return if name == tag.name
|
||||||
|
|
||||||
|
current_tag_name = tag.tag_name
|
||||||
|
target_tag_name = TagName.with_discarded.find_by(name:)
|
||||||
|
|
||||||
|
if target_tag_name.nil?
|
||||||
|
current_tag_name.update!(name:)
|
||||||
|
return
|
||||||
|
end
|
||||||
|
|
||||||
|
promote_tag_alias!(
|
||||||
|
tag,
|
||||||
|
current_tag_name:,
|
||||||
|
promoted_tag_name: target_tag_name)
|
||||||
|
end
|
||||||
|
|
||||||
|
def promote_tag_alias! tag, current_tag_name:, promoted_tag_name:
|
||||||
|
old_owner_tag = promoted_tag_name.canonical&.tag
|
||||||
|
|
||||||
|
if old_owner_tag && old_owner_tag != tag
|
||||||
|
TagVersioning.ensure_snapshot!(old_owner_tag, created_by_user: current_user)
|
||||||
|
end
|
||||||
|
|
||||||
|
promoted_tag_name.undiscard! if promoted_tag_name.discarded?
|
||||||
|
promoted_tag_name.update!(canonical: nil)
|
||||||
|
|
||||||
|
TagName.with_discarded
|
||||||
|
.where(canonical_id: current_tag_name.id)
|
||||||
|
.where.not(id: promoted_tag_name.id)
|
||||||
|
.find_each do |alias_tag_name|
|
||||||
|
alias_tag_name.update!(canonical: promoted_tag_name)
|
||||||
|
end
|
||||||
|
|
||||||
|
current_tag_name.wiki_page&.update!(tag_name: promoted_tag_name)
|
||||||
|
tag.update!(tag_name: promoted_tag_name)
|
||||||
|
current_tag_name.association(:wiki_page).reset
|
||||||
|
current_tag_name.association(:tag).reset
|
||||||
|
current_tag_name.reload.update!(canonical: promoted_tag_name)
|
||||||
|
|
||||||
|
return unless old_owner_tag && old_owner_tag != tag
|
||||||
|
|
||||||
|
record_tag_version!(old_owner_tag.reload, event_type: :update, created_by_user: current_user)
|
||||||
|
end
|
||||||
|
|
||||||
def update_aliases! tag, alias_names
|
def update_aliases! tag, alias_names
|
||||||
alias_names = alias_names.uniq
|
alias_names = alias_names.uniq
|
||||||
|
|
||||||
|
|||||||
@@ -1,6 +1,9 @@
|
|||||||
class Material < ApplicationRecord
|
class Material < ApplicationRecord
|
||||||
include MyDiscard
|
include MyDiscard
|
||||||
|
|
||||||
|
SOURCE_KINDS = ['uri', 'google_drive_path', 'google_drive_file',
|
||||||
|
'legacy_drive_path'].freeze
|
||||||
|
|
||||||
default_scope -> { kept }
|
default_scope -> { kept }
|
||||||
|
|
||||||
belongs_to :parent, class_name: 'Material', optional: true
|
belongs_to :parent, class_name: 'Material', optional: true
|
||||||
@@ -20,7 +23,7 @@ class Material < ApplicationRecord
|
|||||||
|
|
||||||
validates :tag_id, uniqueness: true, allow_nil: true
|
validates :tag_id, uniqueness: true, allow_nil: true
|
||||||
validates :source_kind,
|
validates :source_kind,
|
||||||
inclusion: { in: MaterialSyncSuppression::SOURCE_KINDS },
|
inclusion: { in: SOURCE_KINDS },
|
||||||
allow_blank: true
|
allow_blank: true
|
||||||
|
|
||||||
validate :file_must_be_attached
|
validate :file_must_be_attached
|
||||||
|
|||||||
@@ -1,11 +1,13 @@
|
|||||||
class MaterialSyncSource < ApplicationRecord
|
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 :created_by_user, class_name: 'User', optional: true
|
||||||
belongs_to :updated_by_user, class_name: 'User', optional: true
|
belongs_to :updated_by_user, class_name: 'User', optional: true
|
||||||
|
|
||||||
validates :name, presence: true
|
validates :name, presence: true
|
||||||
validates :source_kind,
|
validates :source_kind,
|
||||||
presence: true,
|
presence: true,
|
||||||
inclusion: { in: MaterialSyncSuppression::SOURCE_KINDS }
|
inclusion: { in: SOURCE_KINDS }
|
||||||
validates :profile, presence: true, inclusion: { in: MaterialExportItem::VALID_PROFILES }
|
validates :profile, presence: true, inclusion: { in: MaterialExportItem::VALID_PROFILES }
|
||||||
validate :source_value_must_be_present
|
validate :source_value_must_be_present
|
||||||
|
|
||||||
@@ -33,7 +35,7 @@ class MaterialSyncSource < ApplicationRecord
|
|||||||
when 'google_drive_file'
|
when 'google_drive_file'
|
||||||
source_file_id.present? || source_uri.present?
|
source_file_id.present? || source_uri.present?
|
||||||
when 'google_drive_path'
|
when 'google_drive_path'
|
||||||
source_file_id.present? || source_uri.present? || source_path.present?
|
source_file_id.present? || source_uri.present?
|
||||||
when 'legacy_drive_path'
|
when 'legacy_drive_path'
|
||||||
source_path.present?
|
source_path.present?
|
||||||
else
|
else
|
||||||
|
|||||||
@@ -1,5 +1,19 @@
|
|||||||
class Post < ApplicationRecord
|
class Post < ApplicationRecord
|
||||||
require 'mini_magick'
|
require 'mini_magick'
|
||||||
|
require 'stringio'
|
||||||
|
|
||||||
|
def self.resized_thumbnail_attachment(upload)
|
||||||
|
upload.rewind
|
||||||
|
image = MiniMagick::Image.read(upload.read)
|
||||||
|
image.resize '180x180'
|
||||||
|
image.format 'jpg'
|
||||||
|
|
||||||
|
{ io: StringIO.new(image.to_blob),
|
||||||
|
filename: 'resized_thumbnail.jpg',
|
||||||
|
content_type: 'image/jpeg' }
|
||||||
|
ensure
|
||||||
|
upload.rewind
|
||||||
|
end
|
||||||
|
|
||||||
belongs_to :uploaded_user, class_name: 'User', optional: true
|
belongs_to :uploaded_user, class_name: 'User', optional: true
|
||||||
|
|
||||||
@@ -46,6 +60,7 @@ class Post < ApplicationRecord
|
|||||||
before_validation :normalise_url
|
before_validation :normalise_url
|
||||||
|
|
||||||
validates :url, presence: true, uniqueness: true
|
validates :url, presence: true, uniqueness: true
|
||||||
|
validates :video_ms, numericality: { only_integer: true, greater_than: 0 }, allow_nil: true
|
||||||
|
|
||||||
validate :validate_original_created_range
|
validate :validate_original_created_range
|
||||||
validate :url_must_be_http_url
|
validate :url_must_be_http_url
|
||||||
@@ -69,7 +84,42 @@ class Post < ApplicationRecord
|
|||||||
super(options).merge(thumbnail: nil)
|
super(options).merge(thumbnail: nil)
|
||||||
end
|
end
|
||||||
|
|
||||||
def snapshot_tag_names = tags.joins(:tag_name).order('tag_names.name').pluck('tag_names.name')
|
def snapshot_tag_names
|
||||||
|
post_tags
|
||||||
|
.kept
|
||||||
|
.joins(tag: :tag_name)
|
||||||
|
.includes(:sections, tag: :tag_name)
|
||||||
|
.order('tag_names.name')
|
||||||
|
.map do |post_tag|
|
||||||
|
name = post_tag.tag.tag_name.name
|
||||||
|
sections = post_tag.sections.sort_by(&:begin_ms)
|
||||||
|
|
||||||
|
next name if sections.empty?
|
||||||
|
|
||||||
|
"#{ name }#{ sections.map { Post.section_literal(_1) }.join }"
|
||||||
|
end
|
||||||
|
end
|
||||||
|
|
||||||
|
def self.section_literal section
|
||||||
|
"[#{ Post.ms_to_time(section.begin_ms) }-#{ section.end_ms ? Post.ms_to_time(section.end_ms) : '' }]"
|
||||||
|
end
|
||||||
|
|
||||||
|
def self.ms_to_time ms
|
||||||
|
total_s = ms / 1_000
|
||||||
|
s = total_s % 60
|
||||||
|
min = (total_s / 60) % 60
|
||||||
|
h = total_s / 3_600
|
||||||
|
remainder_ms = ms % 1_000
|
||||||
|
|
||||||
|
base =
|
||||||
|
if h.positive?
|
||||||
|
'%d:%02d:%02d' % [h, min, s]
|
||||||
|
else
|
||||||
|
'%d:%02d' % [min, s]
|
||||||
|
end
|
||||||
|
|
||||||
|
remainder_ms.positive? ? "#{ base }.#{ remainder_ms.to_s.rjust(3, '0') }" : base
|
||||||
|
end
|
||||||
|
|
||||||
def snapshot_parent_post_ids = parents.order(:id).pluck(:id)
|
def snapshot_parent_post_ids = parents.order(:id).pluck(:id)
|
||||||
|
|
||||||
@@ -87,12 +137,7 @@ class Post < ApplicationRecord
|
|||||||
def resized_thumbnail!
|
def resized_thumbnail!
|
||||||
return unless thumbnail.attached?
|
return unless thumbnail.attached?
|
||||||
|
|
||||||
image = MiniMagick::Image.read(thumbnail.download)
|
thumbnail.attach(self.class.resized_thumbnail_attachment(StringIO.new(thumbnail.download)))
|
||||||
image.resize '180x180'
|
|
||||||
thumbnail.purge
|
|
||||||
thumbnail.attach(io: File.open(image.path),
|
|
||||||
filename: 'resized_thumbnail.jpg',
|
|
||||||
content_type: 'image/jpeg')
|
|
||||||
end
|
end
|
||||||
|
|
||||||
private
|
private
|
||||||
|
|||||||
@@ -10,6 +10,12 @@ class PostTag < ApplicationRecord
|
|||||||
belongs_to :created_user, class_name: 'User', optional: true
|
belongs_to :created_user, class_name: 'User', optional: true
|
||||||
belongs_to :deleted_user, class_name: 'User', optional: true
|
belongs_to :deleted_user, class_name: 'User', optional: true
|
||||||
|
|
||||||
|
has_many :sections, -> { order(:begin_ms) }, class_name: 'PostTagSection',
|
||||||
|
foreign_key: [:post_id, :tag_id],
|
||||||
|
primary_key: [:post_id, :tag_id],
|
||||||
|
dependent: :delete_all,
|
||||||
|
inverse_of: :post_tag
|
||||||
|
|
||||||
validates :post_id, presence: true
|
validates :post_id, presence: true
|
||||||
validates :tag_id, presence: true
|
validates :tag_id, presence: true
|
||||||
validates :post_id, uniqueness: {
|
validates :post_id, uniqueness: {
|
||||||
|
|||||||
@@ -0,0 +1,20 @@
|
|||||||
|
class PostTagSection < ApplicationRecord
|
||||||
|
self.primary_key = :post_id, :tag_id, :begin_ms
|
||||||
|
|
||||||
|
belongs_to :post
|
||||||
|
belongs_to :tag
|
||||||
|
|
||||||
|
belongs_to :post_tag, -> { kept }, foreign_key: [:post_id, :tag_id],
|
||||||
|
primary_key: [:post_id, :tag_id],
|
||||||
|
inverse_of: :sections,
|
||||||
|
optional: true
|
||||||
|
|
||||||
|
validates :post_id, presence: true
|
||||||
|
validates :tag_id, presence: true
|
||||||
|
|
||||||
|
validates :begin_ms, presence: true,
|
||||||
|
numericality: { only_integer: true, greater_than_or_equal_to: 0 }
|
||||||
|
|
||||||
|
validates :end_ms, numericality: { only_integer: true, greater_than: :begin_ms },
|
||||||
|
allow_nil: true
|
||||||
|
end
|
||||||
@@ -5,6 +5,7 @@ class PostVersion < ApplicationRecord
|
|||||||
belongs_to :parent, class_name: 'Post', optional: true
|
belongs_to :parent, class_name: 'Post', optional: true
|
||||||
|
|
||||||
validates :url, presence: true
|
validates :url, presence: true
|
||||||
|
validates :video_ms, numericality: { only_integer: true, greater_than: 0 }, allow_nil: true
|
||||||
|
|
||||||
validate :validate_original_created_range
|
validate :validate_original_created_range
|
||||||
|
|
||||||
|
|||||||
+112
-3
@@ -17,6 +17,16 @@ class Tag < ApplicationRecord
|
|||||||
end
|
end
|
||||||
end
|
end
|
||||||
|
|
||||||
|
class SectionLiteralParseError < ArgumentError
|
||||||
|
attr_reader :tag_name, :literal
|
||||||
|
|
||||||
|
def initialize tag_name, literal
|
||||||
|
@tag_name = tag_name
|
||||||
|
@literal = literal
|
||||||
|
super("invalid section literal for tag #{ tag_name }: #{ literal }")
|
||||||
|
end
|
||||||
|
end
|
||||||
|
|
||||||
has_many :post_tags, inverse_of: :tag
|
has_many :post_tags, inverse_of: :tag
|
||||||
has_many :active_post_tags, -> { kept }, class_name: 'PostTag', inverse_of: :tag
|
has_many :active_post_tags, -> { kept }, class_name: 'PostTag', inverse_of: :tag
|
||||||
has_many :post_tags_with_discarded, -> { with_discarded }, class_name: 'PostTag'
|
has_many :post_tags_with_discarded, -> { with_discarded }, class_name: 'PostTag'
|
||||||
@@ -105,26 +115,60 @@ class Tag < ApplicationRecord
|
|||||||
def self.normalise_tags! tag_names, with_tagme: true,
|
def self.normalise_tags! tag_names, with_tagme: true,
|
||||||
with_no_deerjikist: true,
|
with_no_deerjikist: true,
|
||||||
deny_nico: true,
|
deny_nico: true,
|
||||||
deny_deprecated: false
|
deny_deprecated: false,
|
||||||
|
with_sections: false
|
||||||
if deny_nico && tag_names.any? { |n| n.downcase.start_with?('nico:') }
|
if deny_nico && tag_names.any? { |n| n.downcase.start_with?('nico:') }
|
||||||
raise NicoTagNormalisationError
|
raise NicoTagNormalisationError
|
||||||
end
|
end
|
||||||
|
|
||||||
|
sections = { }
|
||||||
tags = tag_names.map do |name|
|
tags = tag_names.map do |name|
|
||||||
|
raw_name = name
|
||||||
pf, cat = CATEGORY_PREFIXES.find { |p, _| name.downcase.start_with?(p) } || ['', nil]
|
pf, cat = CATEGORY_PREFIXES.find { |p, _| name.downcase.start_with?(p) } || ['', nil]
|
||||||
name = TagName.canonicalise(name.sub(/\A#{ pf }/i, '')).first
|
|
||||||
|
name = name.sub(/\A#{ pf }/i, '')
|
||||||
|
|
||||||
|
sections_by_tag = []
|
||||||
|
while (match = name.match(/\A(\S*?)\[([^\[\]\s]*)-([^\[\]\s]*)\](\S*)\z/))
|
||||||
|
name = "#{ match[1] }#{ match[4] }"
|
||||||
|
next if match[2].empty? && match[3].empty?
|
||||||
|
|
||||||
|
sections_by_tag << normalise_section_range!(
|
||||||
|
begin_raw: match[2],
|
||||||
|
end_raw: match[3],
|
||||||
|
tag_name: name)
|
||||||
|
end
|
||||||
|
|
||||||
|
if name.include?('[') || name.include?(']')
|
||||||
|
raise SectionLiteralParseError.new(raw_name, raw_name)
|
||||||
|
end
|
||||||
|
|
||||||
|
name = TagName.canonicalise(name).first
|
||||||
|
|
||||||
find_or_create_by_tag_name!(name, category: (cat || :general)).tap do |tag|
|
find_or_create_by_tag_name!(name, category: (cat || :general)).tap do |tag|
|
||||||
if deny_deprecated && tag.deprecated?
|
if deny_deprecated && tag.deprecated?
|
||||||
raise DeprecatedTagNormalisationError, [tag.name]
|
raise DeprecatedTagNormalisationError, [tag.name]
|
||||||
end
|
end
|
||||||
|
|
||||||
tag.update!(category: cat) if cat && tag.category != cat
|
tag.update!(category: cat) if cat && tag.category != cat
|
||||||
|
next if sections_by_tag.empty?
|
||||||
|
|
||||||
|
sections[tag.id] ||= []
|
||||||
|
sections[tag.id].concat(sections_by_tag)
|
||||||
|
sections[tag.id] = merge_section_ranges(sections[tag.id])
|
||||||
|
sections.delete(tag.id) if sections[tag.id] == [[0, nil]]
|
||||||
end
|
end
|
||||||
end
|
end
|
||||||
|
|
||||||
tags << Tag.tagme if with_tagme && tags.size < 10 && tags.none?(Tag.tagme)
|
tags << Tag.tagme if with_tagme && tags.size < 10 && tags.none?(Tag.tagme)
|
||||||
tags << Tag.no_deerjikist if with_no_deerjikist && tags.all? { |t| !(t.deerjikist?) }
|
tags << Tag.no_deerjikist if with_no_deerjikist && tags.all? { |t| !(t.deerjikist?) }
|
||||||
tags.uniq(&:id)
|
tags.uniq!(&:id)
|
||||||
|
|
||||||
|
if with_sections
|
||||||
|
{ tags:, sections: }
|
||||||
|
else
|
||||||
|
tags
|
||||||
|
end
|
||||||
end
|
end
|
||||||
|
|
||||||
def self.expand_parent_tags tags
|
def self.expand_parent_tags tags
|
||||||
@@ -150,6 +194,45 @@ class Tag < ApplicationRecord
|
|||||||
(result + tags).uniq { |t| t.id }
|
(result + tags).uniq { |t| t.id }
|
||||||
end
|
end
|
||||||
|
|
||||||
|
def self.normalise_section_range! begin_raw:, end_raw:, tag_name:
|
||||||
|
begin_ms = begin_raw.empty? ? 0 : time_to_ms!(begin_raw, tag_name:)
|
||||||
|
end_ms = end_raw.empty? ? nil : time_to_ms!(end_raw, tag_name:)
|
||||||
|
|
||||||
|
if end_ms
|
||||||
|
begin_ms, end_ms = end_ms, begin_ms if begin_ms > end_ms
|
||||||
|
end_ms = begin_ms + 1 if begin_ms == end_ms
|
||||||
|
end
|
||||||
|
|
||||||
|
[begin_ms, end_ms]
|
||||||
|
end
|
||||||
|
|
||||||
|
def self.merge_section_ranges ranges
|
||||||
|
sorted_ranges = ranges.sort_by { |begin_ms, end_ms| [begin_ms, end_ms || Float::INFINITY] }
|
||||||
|
merged = []
|
||||||
|
|
||||||
|
sorted_ranges.each do |begin_ms, end_ms|
|
||||||
|
if merged.empty?
|
||||||
|
merged << [begin_ms, end_ms]
|
||||||
|
next
|
||||||
|
end
|
||||||
|
|
||||||
|
last_begin_ms, last_end_ms = merged[-1]
|
||||||
|
if last_end_ms.nil? || begin_ms <= last_end_ms
|
||||||
|
merged[-1] = [last_begin_ms, merge_section_end(last_end_ms, end_ms)]
|
||||||
|
else
|
||||||
|
merged << [begin_ms, end_ms]
|
||||||
|
end
|
||||||
|
end
|
||||||
|
|
||||||
|
merged
|
||||||
|
end
|
||||||
|
|
||||||
|
def self.merge_section_end left_end_ms, right_end_ms
|
||||||
|
return nil if left_end_ms.nil? || right_end_ms.nil?
|
||||||
|
|
||||||
|
[left_end_ms, right_end_ms].max
|
||||||
|
end
|
||||||
|
|
||||||
def self.find_or_create_by_tag_name! name, category:
|
def self.find_or_create_by_tag_name! name, category:
|
||||||
tn = TagName.find_undiscard_or_create_by!(name: name.to_s.strip)
|
tn = TagName.find_undiscard_or_create_by!(name: name.to_s.strip)
|
||||||
tn = tn.canonical if tn.canonical_id?
|
tn = tn.canonical if tn.canonical_id?
|
||||||
@@ -246,6 +329,32 @@ class Tag < ApplicationRecord
|
|||||||
end
|
end
|
||||||
end
|
end
|
||||||
|
|
||||||
|
def self.time_to_ms! str, tag_name:
|
||||||
|
match =
|
||||||
|
case str
|
||||||
|
when /\A(?<seconds>\d+)(?:\.(?<ms>\d{1,3}))?\z/
|
||||||
|
{ hours: nil, minutes: nil, seconds: Regexp.last_match[:seconds],
|
||||||
|
ms: Regexp.last_match[:ms] }
|
||||||
|
when /\A(?<minutes>\d+):(?<seconds>[0-5]?\d)(?:\.(?<ms>\d{1,3}))?\z/
|
||||||
|
{ hours: nil, minutes: Regexp.last_match[:minutes],
|
||||||
|
seconds: Regexp.last_match[:seconds],
|
||||||
|
ms: Regexp.last_match[:ms] }
|
||||||
|
when /\A(?<hours>\d+):(?<minutes>[0-5]?\d):(?<seconds>[0-5]?\d)(?:\.(?<ms>\d{1,3}))?\z/
|
||||||
|
{ hours: Regexp.last_match[:hours],
|
||||||
|
minutes: Regexp.last_match[:minutes],
|
||||||
|
seconds: Regexp.last_match[:seconds],
|
||||||
|
ms: Regexp.last_match[:ms] }
|
||||||
|
end
|
||||||
|
|
||||||
|
raise SectionLiteralParseError.new(tag_name, str) unless match
|
||||||
|
|
||||||
|
total_s = match[:seconds].to_i
|
||||||
|
total_s += match[:minutes].to_i * 60 if match[:minutes]
|
||||||
|
total_s += match[:hours].to_i * 3_600 if match[:hours]
|
||||||
|
|
||||||
|
total_s * 1_000 + match[:ms].to_s.ljust(3, '0')[0, 3].to_i
|
||||||
|
end
|
||||||
|
|
||||||
def nico_tags_cannot_be_deprecated
|
def nico_tags_cannot_be_deprecated
|
||||||
if nico? && deprecated_at.present?
|
if nico? && deprecated_at.present?
|
||||||
errors.add :deprecated_at, 'ニコタグは廃止できません.'
|
errors.add :deprecated_at, 'ニコタグは廃止できません.'
|
||||||
|
|||||||
@@ -6,6 +6,7 @@ class TagImplication < ApplicationRecord
|
|||||||
validates :parent_tag_id, presence: true
|
validates :parent_tag_id, presence: true
|
||||||
|
|
||||||
validate :parent_tag_mustnt_be_itself
|
validate :parent_tag_mustnt_be_itself
|
||||||
|
validate :parent_tag_mustnt_create_cycle
|
||||||
|
|
||||||
private
|
private
|
||||||
|
|
||||||
@@ -14,4 +15,27 @@ class TagImplication < ApplicationRecord
|
|||||||
errors.add :parent_tag_id, '親タグは子タグと同一であってはなりません.'
|
errors.add :parent_tag_id, '親タグは子タグと同一であってはなりません.'
|
||||||
end
|
end
|
||||||
end
|
end
|
||||||
|
|
||||||
|
def parent_tag_mustnt_create_cycle
|
||||||
|
return if tag_id.blank? || parent_tag_id.blank?
|
||||||
|
return if errors[:parent_tag_id].present?
|
||||||
|
|
||||||
|
seen = { }
|
||||||
|
stack = [parent_tag_id]
|
||||||
|
|
||||||
|
until stack.empty?
|
||||||
|
current_id = stack.pop
|
||||||
|
next if seen[current_id]
|
||||||
|
|
||||||
|
seen[current_id] = true
|
||||||
|
|
||||||
|
if current_id == tag_id
|
||||||
|
errors.add :parent_tag_id, '親タグに子孫タグを指定すると循環します.'
|
||||||
|
errors.add :base, 'タグの親子関係が循環します.'
|
||||||
|
return
|
||||||
|
end
|
||||||
|
|
||||||
|
stack.concat(TagImplication.where(tag_id: current_id).pluck(:parent_tag_id))
|
||||||
|
end
|
||||||
|
end
|
||||||
end
|
end
|
||||||
|
|||||||
@@ -8,6 +8,7 @@ module PostRepr
|
|||||||
:url,
|
:url,
|
||||||
:title,
|
:title,
|
||||||
:thumbnail_base,
|
:thumbnail_base,
|
||||||
|
:video_ms,
|
||||||
:original_created_from,
|
:original_created_from,
|
||||||
:original_created_before,
|
:original_created_before,
|
||||||
:created_at,
|
:created_at,
|
||||||
@@ -18,7 +19,7 @@ module PostRepr
|
|||||||
|
|
||||||
def base post, current_user = nil
|
def base post, current_user = nil
|
||||||
json = common(post)
|
json = common(post)
|
||||||
json['tags'] = tag_json(post.tags)
|
json['tags'] = tag_json(post)
|
||||||
json['uploaded_user'] = post.uploaded_user && UserRepr.base(post.uploaded_user)
|
json['uploaded_user'] = post.uploaded_user && UserRepr.base(post.uploaded_user)
|
||||||
json['viewed'] = current_user ? current_user.viewed?(post) : false
|
json['viewed'] = current_user ? current_user.viewed?(post) : false
|
||||||
json
|
json
|
||||||
@@ -52,8 +53,16 @@ module PostRepr
|
|||||||
.merge('thumbnail' => thumbnail_url(post))
|
.merge('thumbnail' => thumbnail_url(post))
|
||||||
end
|
end
|
||||||
|
|
||||||
def tag_json tags
|
def tag_json post
|
||||||
tags.reject(&:deprecated?).map { |tag| TagRepr.inline(tag) }
|
post
|
||||||
|
.active_post_tags
|
||||||
|
.reject { _1.tag.deprecated? }
|
||||||
|
.sort_by { _1.tag.name }
|
||||||
|
.map { |post_tag|
|
||||||
|
TagRepr.inline(post_tag.tag).merge(
|
||||||
|
'children' => [],
|
||||||
|
'sections' => post_tag.sections.as_json(only: [:begin_ms, :end_ms]))
|
||||||
|
}
|
||||||
end
|
end
|
||||||
|
|
||||||
def thumbnail_url post
|
def thumbnail_url post
|
||||||
|
|||||||
@@ -11,6 +11,7 @@ module GoogleDrive
|
|||||||
DRIVE_ENDPOINT = 'https://www.googleapis.com/drive/v3'
|
DRIVE_ENDPOINT = 'https://www.googleapis.com/drive/v3'
|
||||||
TOKEN_ENDPOINT = 'https://oauth2.googleapis.com/token'
|
TOKEN_ENDPOINT = 'https://oauth2.googleapis.com/token'
|
||||||
FOLDER_MIME_TYPE = 'application/vnd.google-apps.folder'
|
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'
|
DRIVE_SCOPE = 'https://www.googleapis.com/auth/drive.readonly'
|
||||||
|
|
||||||
def initialize service_account_email: ENV['GOOGLE_DRIVE_SERVICE_ACCOUNT_EMAIL'],
|
def initialize service_account_email: ENV['GOOGLE_DRIVE_SERVICE_ACCOUNT_EMAIL'],
|
||||||
@@ -25,24 +26,34 @@ module GoogleDrive
|
|||||||
|
|
||||||
def list_material_files_under_folder folder_id
|
def list_material_files_under_folder folder_id
|
||||||
files = []
|
files = []
|
||||||
|
each_material_file_under_folder(folder_id) { |entry| files << entry }
|
||||||
|
files
|
||||||
|
end
|
||||||
|
|
||||||
|
def each_material_file_under_folder folder_id
|
||||||
|
return enum_for(__method__, folder_id) unless block_given?
|
||||||
|
|
||||||
walk_folder(folder_id, nil) do |entry, relative_path|
|
walk_folder(folder_id, nil) do |entry, relative_path|
|
||||||
next if entry['mimeType'] == FOLDER_MIME_TYPE
|
next if entry['mimeType'] == FOLDER_MIME_TYPE
|
||||||
|
next if native_file?(entry['mimeType'])
|
||||||
|
|
||||||
files << build_file_entry(entry, relative_path)
|
yield build_file_entry(entry, relative_path)
|
||||||
end
|
end
|
||||||
files
|
|
||||||
end
|
end
|
||||||
|
|
||||||
def fetch_material_file file_id
|
def fetch_material_file file_id
|
||||||
metadata = get_file(file_id)
|
metadata = get_file(file_id)
|
||||||
|
return nil if native_file?(metadata['mimeType'])
|
||||||
|
|
||||||
build_file_entry(metadata, metadata['name'])
|
build_file_entry(metadata, metadata['name'])
|
||||||
end
|
end
|
||||||
|
|
||||||
def download_to_tempfile file_id, filename:
|
def download_to_tempfile file_id, filename:
|
||||||
tempfile = Tempfile.new(['material-sync', File.extname(filename.to_s)])
|
tempfile = Tempfile.new(['material-sync', File.extname(filename.to_s)])
|
||||||
|
tempfile.binmode
|
||||||
request_binary("/files/#{ file_id }",
|
request_binary("/files/#{ file_id }",
|
||||||
{ alt: 'media', supportsAllDrives: true }) do |chunk|
|
{ alt: 'media', supportsAllDrives: true }) do |chunk|
|
||||||
tempfile.write(chunk)
|
tempfile.write(chunk.b)
|
||||||
end
|
end
|
||||||
tempfile.rewind
|
tempfile.rewind
|
||||||
tempfile
|
tempfile
|
||||||
@@ -85,6 +96,7 @@ module GoogleDrive
|
|||||||
name: entry['name'],
|
name: entry['name'],
|
||||||
mime_type: entry['mimeType'],
|
mime_type: entry['mimeType'],
|
||||||
relative_path: MaterialSyncExportPath.normalize_path(relative_path),
|
relative_path: MaterialSyncExportPath.normalize_path(relative_path),
|
||||||
|
sha256_checksum: entry['sha256Checksum'],
|
||||||
web_view_link: entry['webViewLink'],
|
web_view_link: entry['webViewLink'],
|
||||||
web_content_link: entry['webContentLink'] }
|
web_content_link: entry['webContentLink'] }
|
||||||
end
|
end
|
||||||
@@ -97,7 +109,8 @@ module GoogleDrive
|
|||||||
response =
|
response =
|
||||||
request_json('/files', {
|
request_json('/files', {
|
||||||
q: "'#{ folder_id }' in parents and trashed = false",
|
q: "'#{ folder_id }' in parents and trashed = false",
|
||||||
fields: 'nextPageToken,files(id,name,mimeType,webViewLink,webContentLink)',
|
fields: 'nextPageToken,files(id,name,mimeType,sha256Checksum,' \
|
||||||
|
'webViewLink,webContentLink)',
|
||||||
orderBy: 'folder,name',
|
orderBy: 'folder,name',
|
||||||
pageSize: 1000,
|
pageSize: 1000,
|
||||||
supportsAllDrives: true,
|
supportsAllDrives: true,
|
||||||
@@ -113,7 +126,7 @@ module GoogleDrive
|
|||||||
|
|
||||||
def get_file file_id
|
def get_file file_id
|
||||||
request_json("/files/#{ file_id }",
|
request_json("/files/#{ file_id }",
|
||||||
fields: 'id,name,mimeType,webViewLink,webContentLink',
|
fields: 'id,name,mimeType,sha256Checksum,webViewLink,webContentLink',
|
||||||
supportsAllDrives: true)
|
supportsAllDrives: true)
|
||||||
end
|
end
|
||||||
|
|
||||||
@@ -127,13 +140,14 @@ module GoogleDrive
|
|||||||
end
|
end
|
||||||
|
|
||||||
def request_binary path, params = {}
|
def request_binary path, params = {}
|
||||||
response = request(:get, path, params:)
|
request(:get, path, params:) do |response|
|
||||||
unless response.is_a?(Net::HTTPSuccess)
|
unless response.is_a?(Net::HTTPSuccess)
|
||||||
raise "Google Drive download error: #{ response.code } #{ response.body }"
|
raise "Google Drive download error: #{ response.code } #{ response.body }"
|
||||||
end
|
end
|
||||||
|
|
||||||
response.read_body do |chunk|
|
response.read_body do |chunk|
|
||||||
yield chunk
|
yield chunk.b
|
||||||
|
end
|
||||||
end
|
end
|
||||||
end
|
end
|
||||||
|
|
||||||
@@ -156,7 +170,13 @@ module GoogleDrive
|
|||||||
use_ssl: true,
|
use_ssl: true,
|
||||||
open_timeout: 10,
|
open_timeout: 10,
|
||||||
read_timeout: 60) do |http|
|
read_timeout: 60) do |http|
|
||||||
http.request(request)
|
if block_given?
|
||||||
|
http.request(request) do |response|
|
||||||
|
return yield response
|
||||||
|
end
|
||||||
|
else
|
||||||
|
http.request(request)
|
||||||
|
end
|
||||||
end
|
end
|
||||||
end
|
end
|
||||||
|
|
||||||
@@ -205,5 +225,9 @@ module GoogleDrive
|
|||||||
|
|
||||||
OpenSSL::PKey::RSA.new(raw)
|
OpenSSL::PKey::RSA.new(raw)
|
||||||
end
|
end
|
||||||
|
|
||||||
|
def native_file? mime_type
|
||||||
|
mime_type.to_s.start_with?(NATIVE_FILE_MIME_TYPE_PREFIX)
|
||||||
|
end
|
||||||
end
|
end
|
||||||
end
|
end
|
||||||
|
|||||||
@@ -1,16 +1,39 @@
|
|||||||
require 'digest'
|
require 'digest'
|
||||||
|
require 'json'
|
||||||
|
|
||||||
class MaterialFileSha256
|
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
|
def self.from_blob blob, allow_download: false
|
||||||
sha256 = blob.metadata['sha256']
|
sha256 = metadata_sha256(blob)
|
||||||
return sha256 if sha256.present?
|
return sha256 if sha256.present?
|
||||||
return nil unless allow_download
|
return nil unless allow_download
|
||||||
|
|
||||||
begin
|
begin
|
||||||
blob.open do |file|
|
blob.open do |file|
|
||||||
sha256 = Digest::SHA256.file(file.path).hexdigest
|
sha256 = Digest::SHA256.file(file.path).hexdigest
|
||||||
blob.metadata['sha256'] = sha256
|
assign_metadata_sha256!(blob, sha256)
|
||||||
blob.save! if blob.changed?
|
|
||||||
sha256
|
sha256
|
||||||
end
|
end
|
||||||
rescue ActiveStorage::FileNotFoundError, ArgumentError => error
|
rescue ActiveStorage::FileNotFoundError, ArgumentError => error
|
||||||
|
|||||||
@@ -28,6 +28,13 @@ class MaterialSyncImporter
|
|||||||
Material
|
Material
|
||||||
.unscoped
|
.unscoped
|
||||||
.find_or_initialize_by(normalized_source_key: key)
|
.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 =
|
event_type =
|
||||||
if material.new_record?
|
if material.new_record?
|
||||||
:create
|
:create
|
||||||
@@ -37,13 +44,19 @@ class MaterialSyncImporter
|
|||||||
:update
|
:update
|
||||||
end
|
end
|
||||||
uploaded_blob = uploaded_blob!
|
uploaded_blob = uploaded_blob!
|
||||||
|
if @import_block
|
||||||
|
return Result.new(material: nil,
|
||||||
|
action: :suppressed,
|
||||||
|
suppressed: true,
|
||||||
|
suppression: @import_block)
|
||||||
|
end
|
||||||
|
|
||||||
Material.transaction do
|
Material.transaction do
|
||||||
if material.persisted?
|
if material.persisted?
|
||||||
MaterialVersionRecorder.ensure_snapshot!(material,
|
MaterialVersionRecorder.ensure_snapshot!(material,
|
||||||
created_by_user: @attributes[:updated_by_user])
|
created_by_user: @attributes[:updated_by_user])
|
||||||
end
|
end
|
||||||
material.assign_attributes(material_attributes.merge(source))
|
material.assign_attributes(material_attributes_for(material).merge(source))
|
||||||
material.discarded_at = nil if material.respond_to?(:discarded_at=)
|
material.discarded_at = nil if material.respond_to?(:discarded_at=)
|
||||||
material.file.attach(uploaded_blob) if uploaded_blob
|
material.file.attach(uploaded_blob) if uploaded_blob
|
||||||
material.save!
|
material.save!
|
||||||
@@ -81,10 +94,28 @@ class MaterialSyncImporter
|
|||||||
source_file_id: source[:source_file_id])
|
source_file_id: source[:source_file_id])
|
||||||
end
|
end
|
||||||
|
|
||||||
def material_attributes
|
def material_attributes_for material
|
||||||
@attributes.except(:source_kind, :source_uri, :source_path, :source_file_id,
|
attrs =
|
||||||
:file_blob, :file_tempfile, :filename, :content_type,
|
@attributes
|
||||||
:file_sha256, :export_path, :profile)
|
.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
|
||||||
end
|
end
|
||||||
|
|
||||||
def suppression_for source
|
def suppression_for source
|
||||||
@@ -100,33 +131,44 @@ class MaterialSyncImporter
|
|||||||
def uploaded_blob!
|
def uploaded_blob!
|
||||||
return @attributes[:file_blob] if @attributes[:file_blob]
|
return @attributes[:file_blob] if @attributes[:file_blob]
|
||||||
|
|
||||||
tempfile = @attributes[:file_tempfile]
|
tempfile = upload_tempfile
|
||||||
return nil unless tempfile
|
return nil unless tempfile
|
||||||
|
|
||||||
tempfile.rewind
|
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!(
|
blob = ActiveStorage::Blob.create_and_upload!(
|
||||||
io: tempfile,
|
io: tempfile,
|
||||||
filename: @attributes[:filename],
|
filename: @attributes[:filename],
|
||||||
content_type: @attributes[:content_type])
|
content_type: @attributes[:content_type])
|
||||||
file_sha256 = @attributes[:file_sha256] || Digest::SHA256.file(tempfile.path).hexdigest
|
MaterialFileSha256.assign_metadata_sha256!(blob, file_sha256)
|
||||||
blob.metadata['sha256'] = file_sha256 if file_sha256.present?
|
|
||||||
blob.save! if blob.changed?
|
|
||||||
tempfile.rewind
|
tempfile.rewind
|
||||||
blob
|
blob
|
||||||
end
|
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
|
def upsert_export_item! material
|
||||||
export_path = @attributes[:export_path].to_s.strip
|
export_path = resolved_export_path(material)
|
||||||
return if export_path.blank?
|
return if export_path.blank?
|
||||||
|
|
||||||
profile = @attributes[:profile].presence || 'legacy_drive'
|
item = material.material_export_items.find_or_initialize_by(profile: effective_profile)
|
||||||
path = export_path
|
item.export_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.enabled = true
|
||||||
item.created_by_user ||= @attributes[:created_by_user]
|
item.created_by_user ||= @attributes[:created_by_user]
|
||||||
item.save!
|
item.save!
|
||||||
@@ -140,11 +182,78 @@ class MaterialSyncImporter
|
|||||||
end
|
end
|
||||||
|
|
||||||
def close_tempfile!
|
def close_tempfile!
|
||||||
tempfile = @attributes[:file_tempfile]
|
tempfile = upload_tempfile
|
||||||
return unless tempfile
|
return unless tempfile
|
||||||
|
|
||||||
tempfile.close! unless tempfile.closed?
|
tempfile.close! unless tempfile.closed?
|
||||||
rescue StandardError
|
rescue StandardError
|
||||||
nil
|
nil
|
||||||
end
|
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
|
end
|
||||||
|
|||||||
@@ -1,13 +1,13 @@
|
|||||||
require 'digest'
|
|
||||||
|
|
||||||
class MaterialSyncRunner
|
class MaterialSyncRunner
|
||||||
Result = Struct.new(:imported, :updated, :suppressed, :failed, :errors, keyword_init: true)
|
Result = Struct.new(:imported, :updated, :unchanged, :suppressed, :failed,
|
||||||
|
:errors, keyword_init: true)
|
||||||
|
|
||||||
def self.sync_enabled!
|
def self.sync_enabled!
|
||||||
results = MaterialSyncSource.enabled.order(:id).map { |source| new(source).sync! }
|
results = MaterialSyncSource.enabled.order(:id).map { |source| new(source).sync! }
|
||||||
|
|
||||||
Result.new(imported: results.sum(&:imported),
|
Result.new(imported: results.sum(&:imported),
|
||||||
updated: results.sum(&:updated),
|
updated: results.sum(&:updated),
|
||||||
|
unchanged: results.sum(&:unchanged),
|
||||||
suppressed: results.sum(&:suppressed),
|
suppressed: results.sum(&:suppressed),
|
||||||
failed: results.sum(&:failed),
|
failed: results.sum(&:failed),
|
||||||
errors: results.flat_map(&:errors))
|
errors: results.flat_map(&:errors))
|
||||||
@@ -18,10 +18,17 @@ class MaterialSyncRunner
|
|||||||
end
|
end
|
||||||
|
|
||||||
def sync!
|
def sync!
|
||||||
result = Result.new(imported: 0, updated: 0, suppressed: 0, failed: 0, errors: [])
|
result = Result.new(imported: 0, updated: 0, unchanged: 0,
|
||||||
|
suppressed: 0, failed: 0, errors: [])
|
||||||
|
|
||||||
candidates.each do |candidate|
|
if @source.source_kind == 'google_drive_path'
|
||||||
sync_candidate!(candidate, result)
|
sync_google_drive_path!(result)
|
||||||
|
else
|
||||||
|
candidates.each do |candidate|
|
||||||
|
next if candidate.blank?
|
||||||
|
|
||||||
|
sync_candidate!(candidate, result)
|
||||||
|
end
|
||||||
end
|
end
|
||||||
|
|
||||||
@source.update!(last_synced_at: Time.current)
|
@source.update!(last_synced_at: Time.current)
|
||||||
@@ -40,8 +47,6 @@ class MaterialSyncRunner
|
|||||||
case @source.source_kind
|
case @source.source_kind
|
||||||
when 'uri'
|
when 'uri'
|
||||||
[uri_candidate]
|
[uri_candidate]
|
||||||
when 'google_drive_path'
|
|
||||||
google_drive_path_candidates
|
|
||||||
when 'google_drive_file'
|
when 'google_drive_file'
|
||||||
[google_drive_file_candidate]
|
[google_drive_file_candidate]
|
||||||
when 'legacy_drive_path'
|
when 'legacy_drive_path'
|
||||||
@@ -101,15 +106,30 @@ class MaterialSyncRunner
|
|||||||
def google_drive_path_candidates
|
def google_drive_path_candidates
|
||||||
folder_id = google_drive_folder_id
|
folder_id = google_drive_folder_id
|
||||||
Enumerator.new do |entries|
|
Enumerator.new do |entries|
|
||||||
drive_client.list_material_files_under_folder(folder_id).each do |entry|
|
drive_client.each_material_file_under_folder(folder_id).each do |entry|
|
||||||
entries << build_google_drive_candidate(entry)
|
entries << build_google_drive_candidate(entry)
|
||||||
end
|
end
|
||||||
end
|
end
|
||||||
end
|
end
|
||||||
|
|
||||||
|
def sync_google_drive_path! result
|
||||||
|
folder_id = google_drive_folder_id
|
||||||
|
scanned_count = 0
|
||||||
|
|
||||||
|
drive_client.each_material_file_under_folder(folder_id) do |entry|
|
||||||
|
scanned_count += 1
|
||||||
|
sync_candidate!(build_google_drive_candidate(entry), result)
|
||||||
|
log_google_drive_progress(folder_id, scanned_count, result) if progress_log_scan_count?(scanned_count)
|
||||||
|
end
|
||||||
|
|
||||||
|
log_google_drive_progress(folder_id, scanned_count, result, summary: true)
|
||||||
|
end
|
||||||
|
|
||||||
def google_drive_file_candidate
|
def google_drive_file_candidate
|
||||||
build_google_drive_candidate(drive_client.fetch_material_file(google_drive_file_id),
|
entry = drive_client.fetch_material_file(google_drive_file_id)
|
||||||
single_file: true)
|
return nil unless entry
|
||||||
|
|
||||||
|
build_google_drive_candidate(entry, single_file: true)
|
||||||
end
|
end
|
||||||
|
|
||||||
def build_google_drive_candidate entry, single_file: false
|
def build_google_drive_candidate entry, single_file: false
|
||||||
@@ -124,10 +144,6 @@ class MaterialSyncRunner
|
|||||||
relative_path:,
|
relative_path:,
|
||||||
filename: entry[:name],
|
filename: entry[:name],
|
||||||
source_file_id: entry[:id])
|
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_kind: 'google_drive_file',
|
||||||
source_uri: entry[:web_view_link] || google_drive_file_url(entry[:id]),
|
source_uri: entry[:web_view_link] || google_drive_file_url(entry[:id]),
|
||||||
@@ -135,8 +151,10 @@ class MaterialSyncRunner
|
|||||||
source_file_id: entry[:id],
|
source_file_id: entry[:id],
|
||||||
filename: entry[:name],
|
filename: entry[:name],
|
||||||
content_type: entry[:mime_type],
|
content_type: entry[:mime_type],
|
||||||
file_tempfile: tempfile,
|
file_downloader: lambda {
|
||||||
file_sha256:,
|
drive_client.download_to_tempfile(entry[:id], filename: entry[:name])
|
||||||
|
},
|
||||||
|
file_sha256: entry[:sha256_checksum],
|
||||||
export_path:,
|
export_path:,
|
||||||
profile: @source.profile,
|
profile: @source.profile,
|
||||||
tag: nil,
|
tag: nil,
|
||||||
@@ -171,13 +189,17 @@ class MaterialSyncRunner
|
|||||||
|
|
||||||
def google_drive_folder_id
|
def google_drive_folder_id
|
||||||
google_drive_target_id.tap do |id|
|
google_drive_target_id.tap do |id|
|
||||||
raise ArgumentError, 'google_drive_path source_file_id or source_uri is required' if id.blank?
|
if id.blank?
|
||||||
|
raise ArgumentError, 'google_drive_path source_file_id or source_uri is required'
|
||||||
|
end
|
||||||
end
|
end
|
||||||
end
|
end
|
||||||
|
|
||||||
def google_drive_file_id
|
def google_drive_file_id
|
||||||
google_drive_target_id.tap do |id|
|
google_drive_target_id.tap do |id|
|
||||||
raise ArgumentError, 'google_drive_file source_file_id or source_uri is required' if id.blank?
|
if id.blank?
|
||||||
|
raise ArgumentError, 'google_drive_file source_file_id or source_uri is required'
|
||||||
|
end
|
||||||
end
|
end
|
||||||
end
|
end
|
||||||
|
|
||||||
@@ -201,10 +223,27 @@ class MaterialSyncRunner
|
|||||||
def log_result result
|
def log_result result
|
||||||
Rails.logger.info(material_sync_log(imported: result.imported,
|
Rails.logger.info(material_sync_log(imported: result.imported,
|
||||||
updated: result.updated,
|
updated: result.updated,
|
||||||
|
unchanged: result.unchanged,
|
||||||
suppressed: result.suppressed,
|
suppressed: result.suppressed,
|
||||||
failed: result.failed))
|
failed: result.failed))
|
||||||
end
|
end
|
||||||
|
|
||||||
|
def progress_log_scan_count? scanned_count
|
||||||
|
scanned_count == 1 || (scanned_count % 50).zero?
|
||||||
|
end
|
||||||
|
|
||||||
|
def log_google_drive_progress folder_id, scanned_count, result, summary: false
|
||||||
|
Rails.logger.info(
|
||||||
|
material_sync_log(folder_id:,
|
||||||
|
scanned_count:,
|
||||||
|
imported: result.imported,
|
||||||
|
updated: result.updated,
|
||||||
|
unchanged: result.unchanged,
|
||||||
|
suppressed: result.suppressed,
|
||||||
|
failed: result.failed,
|
||||||
|
progress: summary ? 'summary' : 'scan'))
|
||||||
|
end
|
||||||
|
|
||||||
def material_sync_log fields
|
def material_sync_log fields
|
||||||
{ material_sync_source_id: @source.id,
|
{ material_sync_source_id: @source.id,
|
||||||
material_sync_source_name: @source.name }.merge(fields).to_json
|
material_sync_source_name: @source.name }.merge(fields).to_json
|
||||||
|
|||||||
@@ -33,6 +33,11 @@ class MaterialVersionRecorder < VersionRecorder
|
|||||||
tag: @record.tag,
|
tag: @record.tag,
|
||||||
tag_name: @record.tag&.name,
|
tag_name: @record.tag&.name,
|
||||||
tag_category: @record.tag&.category,
|
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,
|
export_paths_json: @record.snapshot_export_paths,
|
||||||
discarded_at: @record.discarded_at,
|
discarded_at: @record.discarded_at,
|
||||||
file_blob_id: file_snapshot[:file_blob_id],
|
file_blob_id: file_snapshot[:file_blob_id],
|
||||||
@@ -52,7 +57,7 @@ class MaterialVersionRecorder < VersionRecorder
|
|||||||
file_content_type: blob.content_type,
|
file_content_type: blob.content_type,
|
||||||
file_byte_size: blob.byte_size,
|
file_byte_size: blob.byte_size,
|
||||||
file_checksum: blob.checksum,
|
file_checksum: blob.checksum,
|
||||||
file_sha256: blob.metadata['sha256'] }
|
file_sha256: MaterialFileSha256.metadata_sha256(blob) }
|
||||||
end
|
end
|
||||||
|
|
||||||
def empty_file_snapshot
|
def empty_file_snapshot
|
||||||
|
|||||||
@@ -23,6 +23,7 @@ class PostVersionRecorder < VersionRecorder
|
|||||||
{ title: @record.title,
|
{ title: @record.title,
|
||||||
url: @record.url,
|
url: @record.url,
|
||||||
thumbnail_base: @record.thumbnail_base,
|
thumbnail_base: @record.thumbnail_base,
|
||||||
|
video_ms: @record.video_ms,
|
||||||
tags: @record.snapshot_tag_names.join(' '),
|
tags: @record.snapshot_tag_names.join(' '),
|
||||||
parent_post_ids: @record.snapshot_parent_post_ids.join(' '),
|
parent_post_ids: @record.snapshot_parent_post_ids.join(' '),
|
||||||
original_created_from: @record.original_created_from,
|
original_created_from: @record.original_created_from,
|
||||||
|
|||||||
@@ -0,0 +1,9 @@
|
|||||||
|
class AddVideoMsToPosts < ActiveRecord::Migration[8.0]
|
||||||
|
def change
|
||||||
|
add_column :posts, :video_ms, :integer
|
||||||
|
add_index :posts, [:video_ms, :id], name: 'idx_posts_video_ms_id'
|
||||||
|
|
||||||
|
add_check_constraint :posts, 'video_ms IS NULL OR video_ms > 0',
|
||||||
|
name: 'chk_posts_video_ms_positive'
|
||||||
|
end
|
||||||
|
end
|
||||||
@@ -0,0 +1,19 @@
|
|||||||
|
class CreatePostTagSections < ActiveRecord::Migration[8.0]
|
||||||
|
def change
|
||||||
|
create_table :post_tag_sections, primary_key: [:post_id, :tag_id, :begin_ms] do |t|
|
||||||
|
t.references :post, null: false, foreign_key: true, index: false
|
||||||
|
t.references :tag, null: false, foreign_key: true, index: false
|
||||||
|
t.integer :begin_ms, null: false
|
||||||
|
t.integer :end_ms, null: true
|
||||||
|
t.timestamps
|
||||||
|
|
||||||
|
t.index [:post_id, :begin_ms], name: 'idx_post_tag_sections_post_id_begin_ms'
|
||||||
|
|
||||||
|
t.check_constraint 'begin_ms >= 0',
|
||||||
|
name: 'chk_post_tag_sections_begin_ms_natural'
|
||||||
|
|
||||||
|
t.check_constraint 'end_ms IS NULL OR begin_ms < end_ms',
|
||||||
|
name: 'chk_post_tag_sections_end_ms_after_begin_ms'
|
||||||
|
end
|
||||||
|
end
|
||||||
|
end
|
||||||
@@ -0,0 +1,9 @@
|
|||||||
|
class AddVideoMsToPostVersions < ActiveRecord::Migration[8.0]
|
||||||
|
def change
|
||||||
|
add_column :post_versions, :video_ms, :integer
|
||||||
|
add_index :post_versions, [:video_ms, :post_id], name: 'idx_post_versions_video_ms_post_id'
|
||||||
|
|
||||||
|
add_check_constraint :post_versions, 'video_ms IS NULL OR video_ms > 0',
|
||||||
|
name: 'chk_post_versions_video_ms_positive'
|
||||||
|
end
|
||||||
|
end
|
||||||
@@ -2,9 +2,6 @@ class EnhanceMaterialManagement < ActiveRecord::Migration[8.0]
|
|||||||
def up
|
def up
|
||||||
change_table :materials, bulk: true do |t|
|
change_table :materials, bulk: true do |t|
|
||||||
t.integer :version_no, null: false, default: 1
|
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
|
end
|
||||||
|
|
||||||
change_table :material_versions, bulk: true do |t|
|
change_table :material_versions, bulk: true do |t|
|
||||||
@@ -18,8 +15,6 @@ class EnhanceMaterialManagement < ActiveRecord::Migration[8.0]
|
|||||||
t.bigint :file_byte_size
|
t.bigint :file_byte_size
|
||||||
t.string :file_checksum
|
t.string :file_checksum
|
||||||
t.string :file_sha256
|
t.string :file_sha256
|
||||||
t.datetime :file_suppressed_at
|
|
||||||
t.string :file_suppression_reason
|
|
||||||
end
|
end
|
||||||
|
|
||||||
execute <<~SQL.squish
|
execute <<~SQL.squish
|
||||||
@@ -35,7 +30,7 @@ class EnhanceMaterialManagement < ActiveRecord::Migration[8.0]
|
|||||||
add_index :material_versions, :file_blob_id
|
add_index :material_versions, :file_blob_id
|
||||||
|
|
||||||
add_check_constraint :material_versions,
|
add_check_constraint :material_versions,
|
||||||
"event_type IN ('create', 'update', 'discard', 'restore', 'suppress')",
|
"event_type IN ('create', 'update', 'discard', 'restore')",
|
||||||
name: 'material_versions_event_type_valid'
|
name: 'material_versions_event_type_valid'
|
||||||
|
|
||||||
create_table :material_export_items do |t|
|
create_table :material_export_items do |t|
|
||||||
@@ -87,12 +82,7 @@ class EnhanceMaterialManagement < ActiveRecord::Migration[8.0]
|
|||||||
remove_column :material_versions, :file_byte_size
|
remove_column :material_versions, :file_byte_size
|
||||||
remove_column :material_versions, :file_checksum
|
remove_column :material_versions, :file_checksum
|
||||||
remove_column :material_versions, :file_sha256
|
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, :version_no
|
||||||
remove_column :materials, :file_suppressed_at
|
|
||||||
remove_column :materials, :file_suppression_reason
|
|
||||||
end
|
end
|
||||||
end
|
end
|
||||||
|
|||||||
@@ -0,0 +1,19 @@
|
|||||||
|
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
|
||||||
@@ -0,0 +1,171 @@
|
|||||||
|
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
|
||||||
生成ファイル
+62
-9
@@ -10,7 +10,7 @@
|
|||||||
#
|
#
|
||||||
# It's strongly recommended that you check this file into your version control system.
|
# It's strongly recommended that you check this file into your version control system.
|
||||||
|
|
||||||
ActiveRecord::Schema[8.0].define(version: 2026_06_25_010000) do
|
ActiveRecord::Schema[8.0].define(version: 2026_06_26_010000) do
|
||||||
create_table "active_storage_attachments", charset: "utf8mb4", collation: "utf8mb4_0900_ai_ci", force: :cascade do |t|
|
create_table "active_storage_attachments", charset: "utf8mb4", collation: "utf8mb4_0900_ai_ci", force: :cascade do |t|
|
||||||
t.string "name", null: false
|
t.string "name", null: false
|
||||||
t.string "record_type", null: false
|
t.string "record_type", null: false
|
||||||
@@ -72,6 +72,7 @@ ActiveRecord::Schema[8.0].define(version: 2026_06_25_010000) do
|
|||||||
t.index ["correct_post_id"], name: "index_gekanator_games_on_correct_post_id"
|
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 ["guessed_post_id"], name: "index_gekanator_games_on_guessed_post_id"
|
||||||
t.index ["user_id"], name: "index_gekanator_games_on_user_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
|
end
|
||||||
|
|
||||||
create_table "gekanator_question_examples", charset: "utf8mb4", collation: "utf8mb4_0900_ai_ci", force: :cascade do |t|
|
create_table "gekanator_question_examples", charset: "utf8mb4", collation: "utf8mb4_0900_ai_ci", force: :cascade do |t|
|
||||||
@@ -213,6 +214,11 @@ ActiveRecord::Schema[8.0].define(version: 2026_06_25_010000) do
|
|||||||
t.bigint "file_byte_size"
|
t.bigint "file_byte_size"
|
||||||
t.string "file_checksum"
|
t.string "file_checksum"
|
||||||
t.string "file_sha256"
|
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 ["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 ["discarded_at"], name: "index_material_versions_on_discarded_at"
|
||||||
t.index ["file_blob_id"], name: "index_material_versions_on_file_blob_id"
|
t.index ["file_blob_id"], name: "index_material_versions_on_file_blob_id"
|
||||||
@@ -269,9 +275,10 @@ ActiveRecord::Schema[8.0].define(version: 2026_06_25_010000) do
|
|||||||
t.datetime "created_at", null: false
|
t.datetime "created_at", null: false
|
||||||
t.bigint "created_by_user_id"
|
t.bigint "created_by_user_id"
|
||||||
t.index ["created_at"], name: "index_nico_tag_versions_on_created_at"
|
t.index ["created_at"], name: "index_nico_tag_versions_on_created_at"
|
||||||
t.index ["created_by_user_id", "created_at"], name: "index_nico_tag_versions_on_created_by_user_id_and_created_at"
|
t.index ["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"
|
t.index ["tag_id", "created_at"], name: "index_nico_tag_versions_on_tag_id_and_created_at", order: { created_at: :desc }
|
||||||
t.index ["tag_id", "version_no"], name: "index_nico_tag_versions_on_tag_id_and_version_no", unique: true
|
t.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
|
end
|
||||||
|
|
||||||
create_table "post_implications", primary_key: ["post_id", "parent_post_id"], charset: "utf8mb4", collation: "utf8mb4_0900_ai_ci", force: :cascade do |t|
|
create_table "post_implications", primary_key: ["post_id", "parent_post_id"], charset: "utf8mb4", collation: "utf8mb4_0900_ai_ci", force: :cascade do |t|
|
||||||
@@ -280,16 +287,30 @@ ActiveRecord::Schema[8.0].define(version: 2026_06_25_010000) do
|
|||||||
t.datetime "created_at", null: false
|
t.datetime "created_at", null: false
|
||||||
t.datetime "updated_at", null: false
|
t.datetime "updated_at", null: false
|
||||||
t.index ["parent_post_id"], name: "index_post_implications_on_parent_post_id"
|
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
|
end
|
||||||
|
|
||||||
create_table "post_similarities", primary_key: ["post_id", "target_post_id"], charset: "utf8mb4", collation: "utf8mb4_0900_ai_ci", force: :cascade do |t|
|
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 "post_id", null: false
|
||||||
t.bigint "target_post_id", null: false
|
t.bigint "target_post_id", null: false
|
||||||
t.float "cos", null: false
|
t.float "cos", null: false
|
||||||
t.index ["post_id", "cos"], name: "index_post_similarities_on_post_id_and_cos"
|
t.index ["post_id", "cos"], name: "index_post_similarities_on_post_id_and_cos", order: { cos: :desc }
|
||||||
t.index ["target_post_id"], name: "index_post_similarities_on_target_post_id"
|
t.index ["target_post_id"], name: "index_post_similarities_on_target_post_id"
|
||||||
end
|
end
|
||||||
|
|
||||||
|
create_table "post_tag_sections", primary_key: ["post_id", "tag_id", "begin_ms"], charset: "utf8mb4", collation: "utf8mb4_0900_ai_ci", force: :cascade do |t|
|
||||||
|
t.bigint "post_id", null: false
|
||||||
|
t.bigint "tag_id", null: false
|
||||||
|
t.integer "begin_ms", null: false
|
||||||
|
t.integer "end_ms"
|
||||||
|
t.datetime "created_at", null: false
|
||||||
|
t.datetime "updated_at", null: false
|
||||||
|
t.index ["post_id", "begin_ms"], name: "idx_post_tag_sections_post_id_begin_ms"
|
||||||
|
t.index ["tag_id"], name: "fk_rails_8be3847903"
|
||||||
|
t.check_constraint "(`end_ms` is null) or (`begin_ms` < `end_ms`)", name: "chk_post_tag_sections_end_ms_after_begin_ms"
|
||||||
|
t.check_constraint "`begin_ms` >= 0", name: "chk_post_tag_sections_begin_ms_natural"
|
||||||
|
end
|
||||||
|
|
||||||
create_table "post_tags", charset: "utf8mb4", collation: "utf8mb4_0900_ai_ci", force: :cascade do |t|
|
create_table "post_tags", charset: "utf8mb4", collation: "utf8mb4_0900_ai_ci", force: :cascade do |t|
|
||||||
t.bigint "post_id", null: false
|
t.bigint "post_id", null: false
|
||||||
t.bigint "tag_id", null: false
|
t.bigint "tag_id", null: false
|
||||||
@@ -323,9 +344,14 @@ ActiveRecord::Schema[8.0].define(version: 2026_06_25_010000) do
|
|||||||
t.datetime "original_created_before"
|
t.datetime "original_created_before"
|
||||||
t.datetime "created_at", null: false
|
t.datetime "created_at", null: false
|
||||||
t.bigint "created_by_user_id"
|
t.bigint "created_by_user_id"
|
||||||
|
t.integer "video_ms"
|
||||||
t.index ["created_by_user_id"], name: "index_post_versions_on_created_by_user_id"
|
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", "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.index ["post_id"], name: "index_post_versions_on_post_id"
|
||||||
|
t.index ["video_ms", "post_id"], name: "idx_post_versions_video_ms_post_id"
|
||||||
|
t.check_constraint "(`video_ms` is null) or (`video_ms` > 0)", name: "chk_post_versions_video_ms_positive"
|
||||||
|
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
|
end
|
||||||
|
|
||||||
create_table "posts", charset: "utf8mb4", collation: "utf8mb4_0900_ai_ci", force: :cascade do |t|
|
create_table "posts", charset: "utf8mb4", collation: "utf8mb4_0900_ai_ci", force: :cascade do |t|
|
||||||
@@ -338,8 +364,12 @@ ActiveRecord::Schema[8.0].define(version: 2026_06_25_010000) do
|
|||||||
t.datetime "original_created_before"
|
t.datetime "original_created_before"
|
||||||
t.datetime "updated_at", null: false
|
t.datetime "updated_at", null: false
|
||||||
t.integer "version_no", null: false
|
t.integer "version_no", null: false
|
||||||
|
t.integer "video_ms"
|
||||||
t.index ["uploaded_user_id"], name: "index_posts_on_uploaded_user_id"
|
t.index ["uploaded_user_id"], name: "index_posts_on_uploaded_user_id"
|
||||||
t.index ["url"], name: "index_posts_on_url", unique: true
|
t.index ["url"], name: "index_posts_on_url", unique: true
|
||||||
|
t.index ["video_ms", "id"], name: "idx_posts_video_ms_id"
|
||||||
|
t.check_constraint "(`video_ms` is null) or (`video_ms` > 0)", name: "chk_posts_video_ms_positive"
|
||||||
|
t.check_constraint "`version_no` > 0", name: "chk_posts_version_no_positive"
|
||||||
end
|
end
|
||||||
|
|
||||||
create_table "settings", charset: "utf8mb4", collation: "utf8mb4_0900_ai_ci", force: :cascade do |t|
|
create_table "settings", charset: "utf8mb4", collation: "utf8mb4_0900_ai_ci", force: :cascade do |t|
|
||||||
@@ -386,7 +416,7 @@ ActiveRecord::Schema[8.0].define(version: 2026_06_25_010000) do
|
|||||||
t.bigint "tag_id", null: false
|
t.bigint "tag_id", null: false
|
||||||
t.bigint "target_tag_id", null: false
|
t.bigint "target_tag_id", null: false
|
||||||
t.float "cos", null: false
|
t.float "cos", null: false
|
||||||
t.index ["tag_id", "cos"], name: "index_tag_similarities_on_tag_id_and_cos"
|
t.index ["tag_id", "cos"], name: "index_tag_similarities_on_tag_id_and_cos", order: { cos: :desc }
|
||||||
t.index ["target_tag_id"], name: "index_tag_similarities_on_target_tag_id"
|
t.index ["target_tag_id"], name: "index_tag_similarities_on_target_tag_id"
|
||||||
end
|
end
|
||||||
|
|
||||||
@@ -396,30 +426,32 @@ ActiveRecord::Schema[8.0].define(version: 2026_06_25_010000) do
|
|||||||
t.string "event_type", null: false
|
t.string "event_type", null: false
|
||||||
t.string "name", null: false
|
t.string "name", null: false
|
||||||
t.string "category", null: false
|
t.string "category", null: false
|
||||||
|
t.datetime "deprecated_at"
|
||||||
t.text "aliases", null: false
|
t.text "aliases", null: false
|
||||||
t.text "parent_tag_ids", null: false
|
t.text "parent_tag_ids", null: false
|
||||||
t.datetime "deprecated_at"
|
|
||||||
t.datetime "created_at", null: false
|
t.datetime "created_at", null: false
|
||||||
t.bigint "created_by_user_id"
|
t.bigint "created_by_user_id"
|
||||||
t.index ["created_at"], name: "index_tag_versions_on_created_at"
|
t.index ["created_at"], name: "index_tag_versions_on_created_at"
|
||||||
t.index ["created_by_user_id", "created_at"], name: "index_tag_versions_on_created_by_user_id_and_created_at"
|
t.index ["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"
|
t.index ["tag_id", "created_at"], name: "index_tag_versions_on_tag_id_and_created_at", order: { created_at: :desc }
|
||||||
t.index ["tag_id", "version_no"], name: "index_tag_versions_on_tag_id_and_version_no", unique: true
|
t.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
|
end
|
||||||
|
|
||||||
create_table "tags", charset: "utf8mb4", collation: "utf8mb4_0900_ai_ci", force: :cascade do |t|
|
create_table "tags", charset: "utf8mb4", collation: "utf8mb4_0900_ai_ci", force: :cascade do |t|
|
||||||
t.bigint "tag_name_id", null: false
|
t.bigint "tag_name_id", null: false
|
||||||
t.string "category", default: "general", null: false
|
t.string "category", default: "general", null: false
|
||||||
t.datetime "deprecated_at"
|
|
||||||
t.datetime "created_at", null: false
|
t.datetime "created_at", null: false
|
||||||
t.datetime "updated_at", null: false
|
t.datetime "updated_at", null: false
|
||||||
t.integer "post_count", default: 0, null: false
|
t.integer "post_count", default: 0, null: false
|
||||||
|
t.datetime "deprecated_at"
|
||||||
t.datetime "discarded_at"
|
t.datetime "discarded_at"
|
||||||
t.integer "version_no", null: false
|
t.integer "version_no", null: false
|
||||||
t.index ["deprecated_at"], name: "index_tags_on_deprecated_at"
|
t.index ["deprecated_at"], name: "index_tags_on_deprecated_at"
|
||||||
t.index ["discarded_at"], name: "index_tags_on_discarded_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.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 "(`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
|
end
|
||||||
|
|
||||||
create_table "theatre_comments", primary_key: ["theatre_id", "no"], charset: "utf8mb4", collation: "utf8mb4_0900_ai_ci", force: :cascade do |t|
|
create_table "theatre_comments", primary_key: ["theatre_id", "no"], charset: "utf8mb4", collation: "utf8mb4_0900_ai_ci", force: :cascade do |t|
|
||||||
@@ -544,6 +576,19 @@ ActiveRecord::Schema[8.0].define(version: 2026_06_25_010000) do
|
|||||||
t.index ["banned_at"], name: "index_users_on_banned_at"
|
t.index ["banned_at"], name: "index_users_on_banned_at"
|
||||||
end
|
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|
|
create_table "wiki_lines", charset: "utf8mb4", collation: "utf8mb4_0900_ai_ci", force: :cascade do |t|
|
||||||
t.string "sha256", limit: 64, null: false
|
t.string "sha256", limit: 64, null: false
|
||||||
t.text "body", null: false
|
t.text "body", null: false
|
||||||
@@ -560,11 +605,13 @@ ActiveRecord::Schema[8.0].define(version: 2026_06_25_010000) do
|
|||||||
t.datetime "created_at", null: false
|
t.datetime "created_at", null: false
|
||||||
t.datetime "updated_at", null: false
|
t.datetime "updated_at", null: false
|
||||||
t.datetime "discarded_at"
|
t.datetime "discarded_at"
|
||||||
|
t.integer "next_asset_no", default: 1, null: false
|
||||||
t.integer "version_no", null: false
|
t.integer "version_no", null: false
|
||||||
t.index ["created_user_id"], name: "index_wiki_pages_on_created_user_id"
|
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 ["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 ["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.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
|
end
|
||||||
|
|
||||||
create_table "wiki_revision_lines", charset: "utf8mb4", collation: "utf8mb4_0900_ai_ci", force: :cascade do |t|
|
create_table "wiki_revision_lines", charset: "utf8mb4", collation: "utf8mb4_0900_ai_ci", force: :cascade do |t|
|
||||||
@@ -609,6 +656,8 @@ ActiveRecord::Schema[8.0].define(version: 2026_06_25_010000) do
|
|||||||
t.index ["created_by_user_id"], name: "index_wiki_versions_on_created_by_user_id"
|
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", "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.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
|
end
|
||||||
|
|
||||||
add_foreign_key "active_storage_attachments", "active_storage_blobs", column: "blob_id"
|
add_foreign_key "active_storage_attachments", "active_storage_blobs", column: "blob_id"
|
||||||
@@ -648,6 +697,8 @@ ActiveRecord::Schema[8.0].define(version: 2026_06_25_010000) do
|
|||||||
add_foreign_key "post_implications", "posts", column: "parent_post_id"
|
add_foreign_key "post_implications", "posts", column: "parent_post_id"
|
||||||
add_foreign_key "post_similarities", "posts"
|
add_foreign_key "post_similarities", "posts"
|
||||||
add_foreign_key "post_similarities", "posts", column: "target_post_id"
|
add_foreign_key "post_similarities", "posts", column: "target_post_id"
|
||||||
|
add_foreign_key "post_tag_sections", "posts"
|
||||||
|
add_foreign_key "post_tag_sections", "tags"
|
||||||
add_foreign_key "post_tags", "posts"
|
add_foreign_key "post_tags", "posts"
|
||||||
add_foreign_key "post_tags", "tags"
|
add_foreign_key "post_tags", "tags"
|
||||||
add_foreign_key "post_tags", "users", column: "created_user_id"
|
add_foreign_key "post_tags", "users", column: "created_user_id"
|
||||||
@@ -687,6 +738,8 @@ ActiveRecord::Schema[8.0].define(version: 2026_06_25_010000) do
|
|||||||
add_foreign_key "user_ips", "users"
|
add_foreign_key "user_ips", "users"
|
||||||
add_foreign_key "user_post_views", "posts"
|
add_foreign_key "user_post_views", "posts"
|
||||||
add_foreign_key "user_post_views", "users"
|
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", "tag_names"
|
||||||
add_foreign_key "wiki_pages", "users", column: "created_user_id"
|
add_foreign_key "wiki_pages", "users", column: "created_user_id"
|
||||||
add_foreign_key "wiki_pages", "users", column: "updated_user_id"
|
add_foreign_key "wiki_pages", "users", column: "updated_user_id"
|
||||||
|
|||||||
+4
-4
@@ -9,19 +9,19 @@
|
|||||||
# end
|
# end
|
||||||
|
|
||||||
material_sync_source_uri = ENV['MATERIAL_SYNC_SOURCE_URI']
|
material_sync_source_uri = ENV['MATERIAL_SYNC_SOURCE_URI']
|
||||||
material_sync_source_tag_name = ENV['MATERIAL_SYNC_SOURCE_TAG_NAME']
|
material_sync_source_file_id = ENV['MATERIAL_SYNC_SOURCE_FILE_ID']
|
||||||
|
|
||||||
if material_sync_source_uri.present? && material_sync_source_tag_name.present?
|
if material_sync_source_uri.present? || material_sync_source_file_id.present?
|
||||||
source = MaterialSyncSource.find_or_initialize_by(
|
source = MaterialSyncSource.find_or_initialize_by(
|
||||||
name: ENV.fetch('MATERIAL_SYNC_SOURCE_NAME', 'Legacy URI material sync'))
|
name: ENV.fetch('MATERIAL_SYNC_SOURCE_NAME', 'Legacy URI material sync'))
|
||||||
source.assign_attributes(
|
source.assign_attributes(
|
||||||
source_kind: ENV.fetch('MATERIAL_SYNC_SOURCE_KIND', 'uri'),
|
source_kind: ENV.fetch('MATERIAL_SYNC_SOURCE_KIND', 'uri'),
|
||||||
source_uri: material_sync_source_uri,
|
source_uri: material_sync_source_uri,
|
||||||
source_path: ENV['MATERIAL_SYNC_SOURCE_PATH'],
|
source_path: ENV['MATERIAL_SYNC_SOURCE_PATH'],
|
||||||
source_file_id: ENV['MATERIAL_SYNC_SOURCE_FILE_ID'],
|
source_file_id: material_sync_source_file_id,
|
||||||
profile: ENV.fetch('MATERIAL_SYNC_SOURCE_PROFILE', 'legacy_drive'),
|
profile: ENV.fetch('MATERIAL_SYNC_SOURCE_PROFILE', 'legacy_drive'),
|
||||||
enabled: ENV.fetch('MATERIAL_SYNC_SOURCE_ENABLED', 'true') != 'false',
|
enabled: ENV.fetch('MATERIAL_SYNC_SOURCE_ENABLED', 'true') != 'false',
|
||||||
default_tag_name: material_sync_source_tag_name,
|
default_tag_name: ENV['MATERIAL_SYNC_SOURCE_TAG_NAME'],
|
||||||
export_path_prefix: ENV['MATERIAL_SYNC_EXPORT_PATH_PREFIX'])
|
export_path_prefix: ENV['MATERIAL_SYNC_EXPORT_PATH_PREFIX'])
|
||||||
source.save!
|
source.save!
|
||||||
end
|
end
|
||||||
|
|||||||
@@ -5,6 +5,7 @@ namespace :materials do
|
|||||||
message = [
|
message = [
|
||||||
"materials:sync imported=#{ result.imported }",
|
"materials:sync imported=#{ result.imported }",
|
||||||
"updated=#{ result.updated }",
|
"updated=#{ result.updated }",
|
||||||
|
"unchanged=#{ result.unchanged }",
|
||||||
"suppressed=#{ result.suppressed }",
|
"suppressed=#{ result.suppressed }",
|
||||||
"failed=#{ result.failed }"
|
"failed=#{ result.failed }"
|
||||||
].join(' ')
|
].join(' ')
|
||||||
|
|||||||
@@ -0,0 +1,8 @@
|
|||||||
|
FactoryBot.define do
|
||||||
|
factory :post_tag_section do
|
||||||
|
association :post
|
||||||
|
association :tag
|
||||||
|
begin_ms { 1_000 }
|
||||||
|
end_ms { 2_000 }
|
||||||
|
end
|
||||||
|
end
|
||||||
@@ -0,0 +1,6 @@
|
|||||||
|
FactoryBot.define do
|
||||||
|
factory :post_tag do
|
||||||
|
association :post
|
||||||
|
association :tag
|
||||||
|
end
|
||||||
|
end
|
||||||
@@ -0,0 +1,8 @@
|
|||||||
|
FactoryBot.define do
|
||||||
|
factory :post do
|
||||||
|
sequence(:url) { |n| "https://example.com/factory-post-#{ n }" }
|
||||||
|
title { 'factory post' }
|
||||||
|
thumbnail_base { nil }
|
||||||
|
uploaded_user { nil }
|
||||||
|
end
|
||||||
|
end
|
||||||
@@ -0,0 +1,19 @@
|
|||||||
|
require 'rails_helper'
|
||||||
|
|
||||||
|
RSpec.describe Material, type: :model do
|
||||||
|
let(:user) { create(:user, :member) }
|
||||||
|
|
||||||
|
it 'allows only material source kinds, not suppression prefix kinds' do
|
||||||
|
material = described_class.new(url: 'https://example.com/material',
|
||||||
|
source_kind: 'google_drive_path_prefix',
|
||||||
|
source_path: '素材/危険',
|
||||||
|
created_by_user: user,
|
||||||
|
updated_by_user: user)
|
||||||
|
|
||||||
|
expect(material).not_to be_valid
|
||||||
|
expect(material.errors[:source_kind]).to be_present
|
||||||
|
|
||||||
|
material.source_kind = 'google_drive_path'
|
||||||
|
expect(material).to be_valid
|
||||||
|
end
|
||||||
|
end
|
||||||
@@ -0,0 +1,41 @@
|
|||||||
|
RSpec.describe PostTag, type: :model do
|
||||||
|
describe '#sections' do
|
||||||
|
it 'loads sections by post_id and tag_id' do
|
||||||
|
post_tag = create(:post_tag)
|
||||||
|
section = create(:post_tag_section,
|
||||||
|
post: post_tag.post,
|
||||||
|
tag: post_tag.tag,
|
||||||
|
begin_ms: 1000,
|
||||||
|
end_ms: 2000)
|
||||||
|
|
||||||
|
expect(post_tag.sections).to contain_exactly(section)
|
||||||
|
end
|
||||||
|
|
||||||
|
it 'does not load sections for another tag on the same post' do
|
||||||
|
post = create(:post)
|
||||||
|
tag = create(:tag)
|
||||||
|
other_tag = create(:tag)
|
||||||
|
|
||||||
|
post_tag = create(:post_tag, post:, tag:)
|
||||||
|
create(:post_tag_section,
|
||||||
|
post:,
|
||||||
|
tag: other_tag,
|
||||||
|
begin_ms: 1000,
|
||||||
|
end_ms: 2000)
|
||||||
|
|
||||||
|
expect(post_tag.sections).to be_empty
|
||||||
|
end
|
||||||
|
|
||||||
|
it 'allows open-ended sections' do
|
||||||
|
post_tag = create(:post_tag)
|
||||||
|
section = create(:post_tag_section,
|
||||||
|
post: post_tag.post,
|
||||||
|
tag: post_tag.tag,
|
||||||
|
begin_ms: 1000,
|
||||||
|
end_ms: nil)
|
||||||
|
|
||||||
|
expect(section).to be_valid
|
||||||
|
expect(post_tag.sections).to contain_exactly(section)
|
||||||
|
end
|
||||||
|
end
|
||||||
|
end
|
||||||
@@ -0,0 +1,36 @@
|
|||||||
|
require 'rails_helper'
|
||||||
|
|
||||||
|
RSpec.describe TagImplication, type: :model do
|
||||||
|
it 'rejects a parent tag that would create a cycle' do
|
||||||
|
child = create(:tag, name: 'tag_implication_cycle_child')
|
||||||
|
parent = create(:tag, name: 'tag_implication_cycle_parent')
|
||||||
|
|
||||||
|
described_class.create!(tag: child, parent_tag: parent)
|
||||||
|
|
||||||
|
implication = described_class.new(tag: parent, parent_tag: child)
|
||||||
|
|
||||||
|
expect(implication).not_to be_valid
|
||||||
|
expect(implication.errors[:parent_tag_id]).to include(
|
||||||
|
'親タグに子孫タグを指定すると循環します.'
|
||||||
|
)
|
||||||
|
expect(implication.errors[:base]).to be_present
|
||||||
|
end
|
||||||
|
|
||||||
|
it 'terminates even when existing data already contains a cycle' do
|
||||||
|
child = create(:tag, name: 'tag_implication_existing_cycle_child')
|
||||||
|
parent = create(:tag, name: 'tag_implication_existing_cycle_parent')
|
||||||
|
ancestor = create(:tag, name: 'tag_implication_existing_cycle_ancestor')
|
||||||
|
|
||||||
|
described_class.create!(tag: parent, parent_tag: ancestor)
|
||||||
|
described_class.insert_all!(
|
||||||
|
[
|
||||||
|
{ tag_id: ancestor.id, parent_tag_id: parent.id,
|
||||||
|
created_at: Time.current, updated_at: Time.current }
|
||||||
|
]
|
||||||
|
)
|
||||||
|
|
||||||
|
implication = described_class.new(tag: child, parent_tag: parent)
|
||||||
|
|
||||||
|
expect(implication).to be_valid
|
||||||
|
end
|
||||||
|
end
|
||||||
@@ -19,6 +19,95 @@ RSpec.describe Tag, type: :model do
|
|||||||
expect(error.tag_names).to eq([deprecated_tag.name])
|
expect(error.tag_names).to eq([deprecated_tag.name])
|
||||||
}
|
}
|
||||||
end
|
end
|
||||||
|
|
||||||
|
it 'rejects invalid section literals instead of treating them as zero' do
|
||||||
|
expect {
|
||||||
|
described_class.normalise_tags!(
|
||||||
|
['normalise_invalid_section[1:aa-2:00]'],
|
||||||
|
with_sections: true
|
||||||
|
)
|
||||||
|
}.to raise_error(Tag::SectionLiteralParseError)
|
||||||
|
end
|
||||||
|
|
||||||
|
it 'parses open-ended section literals' do
|
||||||
|
result = described_class.normalise_tags!(
|
||||||
|
['伊地知ニジカ[1:00-]'],
|
||||||
|
with_sections: true
|
||||||
|
)
|
||||||
|
|
||||||
|
tag = result.fetch(:tags).find { _1.name == '伊地知ニジカ' }
|
||||||
|
expect(result.fetch(:sections).fetch(tag.id)).to eq([[60_000, nil]])
|
||||||
|
end
|
||||||
|
|
||||||
|
it 'parses omitted begin as zero' do
|
||||||
|
result = described_class.normalise_tags!(
|
||||||
|
['伊地知ニジカ[-1:00]'],
|
||||||
|
with_sections: true
|
||||||
|
)
|
||||||
|
|
||||||
|
tag = result.fetch(:tags).find { _1.name == '伊地知ニジカ' }
|
||||||
|
expect(result.fetch(:sections).fetch(tag.id)).to eq([[0, 60_000]])
|
||||||
|
end
|
||||||
|
|
||||||
|
it 'treats fully open section literals as plain tags' do
|
||||||
|
result = described_class.normalise_tags!(
|
||||||
|
['伊地知ニジカ[-]'],
|
||||||
|
with_sections: true
|
||||||
|
)
|
||||||
|
|
||||||
|
tag = result.fetch(:tags).find { _1.name == '伊地知ニジカ' }
|
||||||
|
expect(result.fetch(:sections)[tag.id]).to be_nil
|
||||||
|
end
|
||||||
|
|
||||||
|
it 'treats [0:00-] as a plain tag' do
|
||||||
|
result = described_class.normalise_tags!(
|
||||||
|
['伊地知ニジカ[0:00-]'],
|
||||||
|
with_sections: true
|
||||||
|
)
|
||||||
|
|
||||||
|
tag = result.fetch(:tags).find { _1.name == '伊地知ニジカ' }
|
||||||
|
expect(result.fetch(:sections)[tag.id]).to be_nil
|
||||||
|
end
|
||||||
|
|
||||||
|
it 'expands zero-width sections to one millisecond' do
|
||||||
|
result = described_class.normalise_tags!(
|
||||||
|
['伊地知ニジカ[1:00-1:00]'],
|
||||||
|
with_sections: true
|
||||||
|
)
|
||||||
|
|
||||||
|
tag = result.fetch(:tags).find { _1.name == '伊地知ニジカ' }
|
||||||
|
expect(result.fetch(:sections).fetch(tag.id)).to eq([[60_000, 60_001]])
|
||||||
|
end
|
||||||
|
|
||||||
|
it 'swaps reversed section boundaries' do
|
||||||
|
result = described_class.normalise_tags!(
|
||||||
|
['伊地知ニジカ[2:00-1:00]'],
|
||||||
|
with_sections: true
|
||||||
|
)
|
||||||
|
|
||||||
|
tag = result.fetch(:tags).find { _1.name == '伊地知ニジカ' }
|
||||||
|
expect(result.fetch(:sections).fetch(tag.id)).to eq([[60_000, 120_000]])
|
||||||
|
end
|
||||||
|
|
||||||
|
it 'merges open-ended sections over later bounded sections' do
|
||||||
|
result = described_class.normalise_tags!(
|
||||||
|
['伊地知ニジカ[1:00-][2:00-3:00]'],
|
||||||
|
with_sections: true
|
||||||
|
)
|
||||||
|
|
||||||
|
tag = result.fetch(:tags).find { _1.name == '伊地知ニジカ' }
|
||||||
|
expect(result.fetch(:sections).fetch(tag.id)).to eq([[60_000, nil]])
|
||||||
|
end
|
||||||
|
|
||||||
|
it 'merges adjacent bounded and open-ended sections' do
|
||||||
|
result = described_class.normalise_tags!(
|
||||||
|
['伊地知ニジカ[1:00-3:00][3:00-]'],
|
||||||
|
with_sections: true
|
||||||
|
)
|
||||||
|
|
||||||
|
tag = result.fetch(:tags).find { _1.name == '伊地知ニジカ' }
|
||||||
|
expect(result.fetch(:sections).fetch(tag.id)).to eq([[60_000, nil]])
|
||||||
|
end
|
||||||
end
|
end
|
||||||
|
|
||||||
describe '.expand_parent_tags' do
|
describe '.expand_parent_tags' do
|
||||||
@@ -54,7 +143,17 @@ RSpec.describe Tag, type: :model do
|
|||||||
first = create(:tag, name: 'expand_cycle_first')
|
first = create(:tag, name: 'expand_cycle_first')
|
||||||
second = create(:tag, name: 'expand_cycle_second')
|
second = create(:tag, name: 'expand_cycle_second')
|
||||||
TagImplication.create!(tag: first, parent_tag: second)
|
TagImplication.create!(tag: first, parent_tag: second)
|
||||||
TagImplication.create!(tag: second, parent_tag: first)
|
now = Time.current
|
||||||
|
TagImplication.insert_all!(
|
||||||
|
[
|
||||||
|
{
|
||||||
|
tag_id: second.id,
|
||||||
|
parent_tag_id: first.id,
|
||||||
|
created_at: now,
|
||||||
|
updated_at: now
|
||||||
|
}
|
||||||
|
]
|
||||||
|
)
|
||||||
|
|
||||||
expect(described_class.expand_parent_tags([first])).to contain_exactly(first, second)
|
expect(described_class.expand_parent_tags([first])).to contain_exactly(first, second)
|
||||||
end
|
end
|
||||||
|
|||||||
@@ -64,27 +64,36 @@ RSpec.describe 'Materials API', type: :request do
|
|||||||
'name' => 'material_index_b',
|
'name' => 'material_index_b',
|
||||||
'category' => 'material'
|
'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['content_type']).to eq('image/png')
|
||||||
|
expect(row['media_kind']).to eq('image')
|
||||||
end
|
end
|
||||||
|
|
||||||
it 'filters materials by tag_id' do
|
it 'filters materials by q' do
|
||||||
get '/materials', params: { tag_id: material_a.tag_id }
|
get '/materials', params: { q: 'material_index_a' }
|
||||||
|
|
||||||
expect(response).to have_http_status(:ok)
|
expect(response).to have_http_status(:ok)
|
||||||
expect(json['count']).to eq(1)
|
expect(json['count']).to eq(1)
|
||||||
expect(response_materials.map { |m| m['id'] }).to eq([material_a.id])
|
expect(response_materials.map { |m| m['id'] }).to eq([material_a.id])
|
||||||
end
|
end
|
||||||
|
|
||||||
it 'filters materials by parent_id' do
|
it 'filters materials by tag_state' do
|
||||||
get '/materials', params: { parent_id: material_a.id }
|
untagged =
|
||||||
|
build_material(tag: nil, user: member_user,
|
||||||
|
file: dummy_upload(filename: 'untagged.png'))
|
||||||
|
|
||||||
|
get '/materials', params: { tag_state: 'untagged' }
|
||||||
|
|
||||||
expect(response).to have_http_status(:ok)
|
expect(response).to have_http_status(:ok)
|
||||||
expect(json['count']).to eq(1)
|
expect(json['count']).to eq(1)
|
||||||
expect(response_materials.map { |m| m['id'] }).to eq([material_b.id])
|
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'))
|
||||||
end
|
end
|
||||||
|
|
||||||
it 'paginates and keeps total count' do
|
it 'paginates and keeps total count' do
|
||||||
@@ -104,6 +113,68 @@ RSpec.describe 'Materials API', type: :request do
|
|||||||
expect(response_materials.size).to eq(1)
|
expect(response_materials.size).to eq(1)
|
||||||
expect(response_materials.first['id']).to eq(material_b.id)
|
expect(response_materials.first['id']).to eq(material_b.id)
|
||||||
end
|
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
|
end
|
||||||
|
|
||||||
describe 'GET /materials/:id' do
|
describe 'GET /materials/:id' do
|
||||||
@@ -528,9 +599,8 @@ RSpec.describe 'Materials API', type: :request do
|
|||||||
expect(response.body.b).not_to include('素材/b.png'.b)
|
expect(response.body.b).not_to include('素材/b.png'.b)
|
||||||
end
|
end
|
||||||
|
|
||||||
it 'does not include suppressed materials' do
|
it 'does not include disabled export items' do
|
||||||
material_b.update!(file_suppressed_at: Time.current,
|
material_b.material_export_items.first.update!(enabled: false)
|
||||||
file_suppression_reason: 'copyright_high_risk')
|
|
||||||
|
|
||||||
get '/materials/download.zip', params: { profile: 'legacy_drive' }
|
get '/materials/download.zip', params: { profile: 'legacy_drive' }
|
||||||
|
|
||||||
@@ -540,62 +610,78 @@ RSpec.describe 'Materials API', type: :request do
|
|||||||
end
|
end
|
||||||
end
|
end
|
||||||
|
|
||||||
describe 'PATCH /materials/:id/suppress_file' do
|
describe 'GET /materials/versions' do
|
||||||
let!(:tag) do
|
let!(:tag) do
|
||||||
Tag.create!(tag_name: TagName.create!(name: 'material_suppress'), category: :material)
|
Tag.create!(tag_name: TagName.create!(name: 'material_history'), category: :material)
|
||||||
end
|
end
|
||||||
let!(:material) do
|
let!(:material) do
|
||||||
build_material(tag:, user: member_user, file: dummy_upload(filename: 'suppress.png'))
|
build_material(tag:, user: member_user, file: dummy_upload(filename: 'history.png'))
|
||||||
end
|
end
|
||||||
|
|
||||||
it 'allows admin to suppress a file and records a suppress version' do
|
it 'returns material versions in reverse chronological order' 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,
|
MaterialVersionRecorder.record!(material:, event_type: :create,
|
||||||
created_by_user: member_user)
|
created_by_user: member_user)
|
||||||
|
|
||||||
expect do
|
get '/materials/versions', params: {
|
||||||
patch "/materials/#{ material.id }/suppress_file",
|
tag: 'material_history',
|
||||||
params: { reason: 'copyright_high_risk' }
|
event_type: 'create'
|
||||||
end.to change(MaterialVersion, :count).by(1)
|
}
|
||||||
|
|
||||||
expect(response).to have_http_status(:ok)
|
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
|
||||||
|
|
||||||
material.reload
|
describe 'material sync suppressions' do
|
||||||
expect(material.file_suppressed_at).to be_present
|
it 'requires member permission for index' do
|
||||||
expect(material.file_suppressed_by_user).to eq(admin_user)
|
sign_out
|
||||||
expect(material.file_suppression_reason).to eq('copyright_high_risk')
|
|
||||||
expect(material.material_versions.order(:version_no).last.event_type).to eq('suppress')
|
get '/materials/suppressions'
|
||||||
expect(json['file']).to be_nil
|
|
||||||
expect(json['file_suppressed_at']).to be_present
|
expect(response).to have_http_status(:unauthorized)
|
||||||
end
|
end
|
||||||
|
|
||||||
it 'purges blob when purge=true is requested' do
|
it 'creates source suppression as member' 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)
|
sign_in_as(member_user)
|
||||||
|
|
||||||
patch "/materials/#{ material.id }/suppress_file",
|
expect do
|
||||||
params: { reason: 'copyright_high_risk' }
|
post '/materials/suppressions', params: {
|
||||||
|
source_kind: 'google_drive_path_prefix',
|
||||||
|
drive_path: '伊地知ニジカ/危険素材',
|
||||||
|
reason: 'copyright_high_risk'
|
||||||
|
}
|
||||||
|
end.to change(MaterialSyncSuppression, :count).by(1)
|
||||||
|
|
||||||
expect(response).to have_http_status(:forbidden)
|
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:伊地知ニジカ/危険素材'
|
||||||
|
)
|
||||||
end
|
end
|
||||||
end
|
end
|
||||||
|
|
||||||
|
|||||||
@@ -1,4 +1,5 @@
|
|||||||
require 'rails_helper'
|
require 'rails_helper'
|
||||||
|
require 'base64'
|
||||||
require 'set'
|
require 'set'
|
||||||
|
|
||||||
include ActiveSupport::Testing::TimeHelpers
|
include ActiveSupport::Testing::TimeHelpers
|
||||||
@@ -8,6 +9,11 @@ RSpec.describe 'Posts API', type: :request do
|
|||||||
# resized_thumbnail! が MiniMagick 依存でコケやすいので request spec ではスタブしとくのが無難。
|
# resized_thumbnail! が MiniMagick 依存でコケやすいので request spec ではスタブしとくのが無難。
|
||||||
before do
|
before do
|
||||||
allow_any_instance_of(Post).to receive(:resized_thumbnail!).and_return(true)
|
allow_any_instance_of(Post).to receive(:resized_thumbnail!).and_return(true)
|
||||||
|
allow(Post).to receive(:resized_thumbnail_attachment).and_return(
|
||||||
|
io: StringIO.new('dummy'),
|
||||||
|
filename: 'resized_thumbnail.jpg',
|
||||||
|
content_type: 'image/jpeg'
|
||||||
|
)
|
||||||
end
|
end
|
||||||
|
|
||||||
def create_nico_tag!(name)
|
def create_nico_tag!(name)
|
||||||
@@ -19,6 +25,18 @@ RSpec.describe 'Posts API', type: :request do
|
|||||||
Rack::Test::UploadedFile.new(StringIO.new('dummy'), 'image/jpeg', original_filename: 'dummy.jpg')
|
Rack::Test::UploadedFile.new(StringIO.new('dummy'), 'image/jpeg', original_filename: 'dummy.jpg')
|
||||||
end
|
end
|
||||||
|
|
||||||
|
def real_thumbnail_upload
|
||||||
|
gif =
|
||||||
|
Base64.decode64(
|
||||||
|
'R0lGODdhAQABAIABAP///wAAACwAAAAAAQABAAACAkQBADs=')
|
||||||
|
|
||||||
|
Rack::Test::UploadedFile.new(
|
||||||
|
StringIO.new(gif),
|
||||||
|
'image/gif',
|
||||||
|
original_filename: 'thumbnail.gif'
|
||||||
|
)
|
||||||
|
end
|
||||||
|
|
||||||
def post_write_params params = { }
|
def post_write_params params = { }
|
||||||
{ parent_post_ids: '' }.merge(params)
|
{ parent_post_ids: '' }.merge(params)
|
||||||
end
|
end
|
||||||
@@ -36,6 +54,7 @@ RSpec.describe 'Posts API', type: :request do
|
|||||||
title: post.title,
|
title: post.title,
|
||||||
url: post.url,
|
url: post.url,
|
||||||
thumbnail_base: post.thumbnail_base,
|
thumbnail_base: post.thumbnail_base,
|
||||||
|
video_ms: post.video_ms,
|
||||||
tags: post.snapshot_tag_names.join(' '),
|
tags: post.snapshot_tag_names.join(' '),
|
||||||
parent_post_ids: post.snapshot_parent_post_ids.join(' '),
|
parent_post_ids: post.snapshot_parent_post_ids.join(' '),
|
||||||
original_created_from: post.original_created_from,
|
original_created_from: post.original_created_from,
|
||||||
@@ -127,6 +146,22 @@ RSpec.describe 'Posts API', type: :request do
|
|||||||
expect(all_tag_names).to include("spec_tag")
|
expect(all_tag_names).to include("spec_tag")
|
||||||
end
|
end
|
||||||
|
|
||||||
|
it 'keeps children and sections keys in non-detail tag responses' do
|
||||||
|
PostTagSection.create!(post: hit_post, tag:, begin_ms: 1_000, end_ms: nil)
|
||||||
|
|
||||||
|
get '/posts'
|
||||||
|
|
||||||
|
expect(response).to have_http_status(:ok)
|
||||||
|
|
||||||
|
hit_json = json.fetch('posts').find { |post| post['id'] == hit_post.id }
|
||||||
|
tag_json = hit_json.fetch('tags').find { |item| item['name'] == 'spec_tag' }
|
||||||
|
|
||||||
|
expect(tag_json.fetch('children')).to eq([])
|
||||||
|
expect(tag_json.fetch('sections')).to eq([
|
||||||
|
{ 'begin_ms' => 1_000, 'end_ms' => nil }
|
||||||
|
])
|
||||||
|
end
|
||||||
|
|
||||||
context "when q is provided" do
|
context "when q is provided" do
|
||||||
it "filters posts by q (hit case)" do
|
it "filters posts by q (hit case)" do
|
||||||
get "/posts", params: { tags: "spec_tag" }
|
get "/posts", params: { tags: "spec_tag" }
|
||||||
@@ -696,6 +731,66 @@ RSpec.describe 'Posts API', type: :request do
|
|||||||
expect(json['tags'][0]).to have_key('name')
|
expect(json['tags'][0]).to have_key('name')
|
||||||
end
|
end
|
||||||
|
|
||||||
|
it '201 when posting manually with a thumbnail' do
|
||||||
|
sign_in_as(member)
|
||||||
|
allow(Post).to receive(:resized_thumbnail_attachment).and_call_original
|
||||||
|
|
||||||
|
post '/posts', params: post_write_params(
|
||||||
|
title: 'thumbnail post',
|
||||||
|
url: 'https://example.com/thumbnail-post',
|
||||||
|
tags: 'spec_tag',
|
||||||
|
thumbnail: real_thumbnail_upload
|
||||||
|
)
|
||||||
|
|
||||||
|
expect(response).to have_http_status(:created)
|
||||||
|
post_record = Post.find(json.fetch('id'))
|
||||||
|
expect(post_record.thumbnail).to be_attached
|
||||||
|
expect(post_record.thumbnail.blob.content_type).to eq('image/jpeg')
|
||||||
|
expect { post_record.thumbnail.download }.not_to raise_error
|
||||||
|
end
|
||||||
|
|
||||||
|
it 'resizes the thumbnail before the create transaction begins' do
|
||||||
|
sign_in_as(member)
|
||||||
|
|
||||||
|
open_transactions = []
|
||||||
|
baseline_open_transactions = Post.connection.open_transactions
|
||||||
|
allow(Post).to receive(:resized_thumbnail_attachment) do |_upload|
|
||||||
|
open_transactions << Post.connection.open_transactions
|
||||||
|
{ io: StringIO.new('dummy'),
|
||||||
|
filename: 'resized_thumbnail.jpg',
|
||||||
|
content_type: 'image/jpeg' }
|
||||||
|
end
|
||||||
|
|
||||||
|
post '/posts', params: post_write_params(
|
||||||
|
title: 'transaction post',
|
||||||
|
url: 'https://example.com/transaction-post',
|
||||||
|
tags: 'spec_tag',
|
||||||
|
thumbnail: dummy_upload
|
||||||
|
)
|
||||||
|
|
||||||
|
expect(response).to have_http_status(:created)
|
||||||
|
expect(open_transactions).to eq([baseline_open_transactions])
|
||||||
|
end
|
||||||
|
|
||||||
|
it 'returns 422 and does not create a post when thumbnail resize fails' do
|
||||||
|
sign_in_as(member)
|
||||||
|
allow(Post).to receive(:resized_thumbnail_attachment).and_raise(MiniMagick::Error)
|
||||||
|
|
||||||
|
expect {
|
||||||
|
post '/posts', params: post_write_params(
|
||||||
|
title: 'broken thumbnail post',
|
||||||
|
url: 'https://example.com/broken-thumbnail-post',
|
||||||
|
tags: 'spec_tag',
|
||||||
|
thumbnail: dummy_upload
|
||||||
|
)
|
||||||
|
}.not_to change(Post, :count)
|
||||||
|
|
||||||
|
expect(response).to have_http_status(:unprocessable_entity)
|
||||||
|
expect(json.fetch('errors')).to include(
|
||||||
|
'thumbnail' => ['サムネイル画像の変換に失敗しました.']
|
||||||
|
)
|
||||||
|
end
|
||||||
|
|
||||||
it '201 and creates post + tags when member and tags have aliases' do
|
it '201 and creates post + tags when member and tags have aliases' do
|
||||||
sign_in_as(member)
|
sign_in_as(member)
|
||||||
|
|
||||||
@@ -767,6 +862,198 @@ RSpec.describe 'Posts API', type: :request do
|
|||||||
expect(saved_names).not_to include('deprecated_parent', 'deprecated_grandparent')
|
expect(saved_names).not_to include('deprecated_parent', 'deprecated_grandparent')
|
||||||
end
|
end
|
||||||
|
|
||||||
|
it 'returns validation error for an invalid section literal' do
|
||||||
|
sign_in_as(member)
|
||||||
|
|
||||||
|
post '/posts', params: post_write_params(
|
||||||
|
title: 'invalid section literal',
|
||||||
|
url: 'https://example.com/invalid-section-literal',
|
||||||
|
tags: 'spec_tag[1:aa-2:00]',
|
||||||
|
thumbnail: dummy_upload
|
||||||
|
)
|
||||||
|
|
||||||
|
expect(response).to have_http_status(:unprocessable_entity)
|
||||||
|
expect(json).to include(
|
||||||
|
'type' => 'validation_error',
|
||||||
|
'message' => '入力内容を確認してください.'
|
||||||
|
)
|
||||||
|
expect(json.fetch('errors')).to include(
|
||||||
|
'tags' => ['タグ区間の記法が不正です.']
|
||||||
|
)
|
||||||
|
end
|
||||||
|
|
||||||
|
it 'creates a video post with duration' do
|
||||||
|
sign_in_as(member)
|
||||||
|
|
||||||
|
post '/posts', params: post_write_params(
|
||||||
|
title: 'video post',
|
||||||
|
url: 'https://example.com/video-post',
|
||||||
|
tags: '動画 spec_tag',
|
||||||
|
duration: '3:00.500',
|
||||||
|
thumbnail: dummy_upload
|
||||||
|
)
|
||||||
|
|
||||||
|
expect(response).to have_http_status(:created)
|
||||||
|
expect(Post.find(json.fetch('id')).video_ms).to eq(180_500)
|
||||||
|
expect(json.fetch('video_ms')).to eq(180_500)
|
||||||
|
end
|
||||||
|
|
||||||
|
it 'creates a video post with number input duration seconds' do
|
||||||
|
sign_in_as(member)
|
||||||
|
|
||||||
|
post '/posts', params: post_write_params(
|
||||||
|
title: 'video post seconds',
|
||||||
|
url: 'https://example.com/video-post-seconds',
|
||||||
|
tags: '動画 spec_tag',
|
||||||
|
duration: '180.5',
|
||||||
|
thumbnail: dummy_upload
|
||||||
|
)
|
||||||
|
|
||||||
|
expect(response).to have_http_status(:created)
|
||||||
|
expect(Post.find(json.fetch('id')).video_ms).to eq(180_500)
|
||||||
|
expect(json.fetch('video_ms')).to eq(180_500)
|
||||||
|
end
|
||||||
|
|
||||||
|
it 'clears video_ms when the saved tags do not include 動画' do
|
||||||
|
sign_in_as(member)
|
||||||
|
|
||||||
|
post '/posts', params: post_write_params(
|
||||||
|
title: 'non video post',
|
||||||
|
url: 'https://example.com/non-video-post',
|
||||||
|
tags: 'spec_tag',
|
||||||
|
duration: '3:00',
|
||||||
|
thumbnail: dummy_upload
|
||||||
|
)
|
||||||
|
|
||||||
|
expect(response).to have_http_status(:created)
|
||||||
|
expect(Post.find(json.fetch('id')).video_ms).to be_nil
|
||||||
|
end
|
||||||
|
|
||||||
|
it 'returns validation error when a bounded section exceeds duration' do
|
||||||
|
sign_in_as(member)
|
||||||
|
|
||||||
|
post '/posts', params: post_write_params(
|
||||||
|
title: 'too long section',
|
||||||
|
url: 'https://example.com/too-long-section',
|
||||||
|
tags: '動画 伊地知ニジカ[2:50-3:10]',
|
||||||
|
duration: '3:00',
|
||||||
|
thumbnail: dummy_upload
|
||||||
|
)
|
||||||
|
|
||||||
|
expect(response).to have_http_status(:unprocessable_entity)
|
||||||
|
expect(json.fetch('errors')).to include(
|
||||||
|
'video_ms' => ['タグ区間の終端が動画時間を超えてゐます.']
|
||||||
|
)
|
||||||
|
end
|
||||||
|
|
||||||
|
it 'saves open-ended sections with end_ms NULL' do
|
||||||
|
sign_in_as(member)
|
||||||
|
|
||||||
|
post '/posts', params: post_write_params(
|
||||||
|
title: 'open ended section literal',
|
||||||
|
url: 'https://example.com/open-ended-section-literal',
|
||||||
|
tags: '動画 伊地知ニジカ[1:00-]',
|
||||||
|
duration: '3:00',
|
||||||
|
thumbnail: dummy_upload
|
||||||
|
)
|
||||||
|
|
||||||
|
expect(response).to have_http_status(:created)
|
||||||
|
|
||||||
|
created_post = Post.find(json.fetch('id'))
|
||||||
|
tag = Tag.joins(:tag_name).find_by!(tag_names: { name: '伊地知ニジカ' })
|
||||||
|
section = PostTagSection.find_by!(post: created_post, tag:)
|
||||||
|
|
||||||
|
expect(section.begin_ms).to eq(60_000)
|
||||||
|
expect(section.end_ms).to be_nil
|
||||||
|
end
|
||||||
|
|
||||||
|
it 'does not save sections for [-]' do
|
||||||
|
sign_in_as(member)
|
||||||
|
|
||||||
|
post '/posts', params: post_write_params(
|
||||||
|
title: 'fully open section literal',
|
||||||
|
url: 'https://example.com/fully-open-section-literal',
|
||||||
|
tags: '伊地知ニジカ[-]',
|
||||||
|
thumbnail: dummy_upload
|
||||||
|
)
|
||||||
|
|
||||||
|
expect(response).to have_http_status(:created)
|
||||||
|
|
||||||
|
created_post = Post.find(json.fetch('id'))
|
||||||
|
tag = Tag.joins(:tag_name).find_by!(tag_names: { name: '伊地知ニジカ' })
|
||||||
|
expect(PostTagSection.find_by(post: created_post, tag:)).to be_nil
|
||||||
|
end
|
||||||
|
|
||||||
|
it 'does not save sections for [0:00-]' do
|
||||||
|
sign_in_as(member)
|
||||||
|
|
||||||
|
post '/posts', params: post_write_params(
|
||||||
|
title: 'zero open ended section literal',
|
||||||
|
url: 'https://example.com/zero-open-ended-section-literal',
|
||||||
|
tags: '伊地知ニジカ[0:00-]',
|
||||||
|
thumbnail: dummy_upload
|
||||||
|
)
|
||||||
|
|
||||||
|
expect(response).to have_http_status(:created)
|
||||||
|
|
||||||
|
created_post = Post.find(json.fetch('id'))
|
||||||
|
tag = Tag.joins(:tag_name).find_by!(tag_names: { name: '伊地知ニジカ' })
|
||||||
|
expect(PostTagSection.find_by(post: created_post, tag:)).to be_nil
|
||||||
|
end
|
||||||
|
|
||||||
|
it 'returns end_ms null for open-ended sections in show response' do
|
||||||
|
sign_in_as(member)
|
||||||
|
|
||||||
|
post '/posts', params: post_write_params(
|
||||||
|
title: 'show open ended section literal',
|
||||||
|
url: 'https://example.com/show-open-ended-section-literal',
|
||||||
|
tags: '動画 伊地知ニジカ[1:00-]',
|
||||||
|
duration: '3:00',
|
||||||
|
thumbnail: dummy_upload
|
||||||
|
)
|
||||||
|
|
||||||
|
expect(response).to have_http_status(:created)
|
||||||
|
|
||||||
|
get "/posts/#{ json.fetch('id') }"
|
||||||
|
|
||||||
|
expect(response).to have_http_status(:ok)
|
||||||
|
tag_json = json.fetch('tags').find { |item| item['name'] == '伊地知ニジカ' }
|
||||||
|
expect(tag_json.fetch('sections')).to eq([
|
||||||
|
{ 'begin_ms' => 60_000, 'end_ms' => nil }
|
||||||
|
])
|
||||||
|
end
|
||||||
|
|
||||||
|
it 'allows open-ended sections when begin is within duration' do
|
||||||
|
sign_in_as(member)
|
||||||
|
|
||||||
|
post '/posts', params: post_write_params(
|
||||||
|
title: 'valid open ended section literal',
|
||||||
|
url: 'https://example.com/valid-open-ended-section-literal',
|
||||||
|
tags: '動画 伊地知ニジカ[1:00-]',
|
||||||
|
duration: '3:00',
|
||||||
|
thumbnail: dummy_upload
|
||||||
|
)
|
||||||
|
|
||||||
|
expect(response).to have_http_status(:created)
|
||||||
|
end
|
||||||
|
|
||||||
|
it 'rejects open-ended sections when begin equals duration' do
|
||||||
|
sign_in_as(member)
|
||||||
|
|
||||||
|
post '/posts', params: post_write_params(
|
||||||
|
title: 'invalid open ended section literal',
|
||||||
|
url: 'https://example.com/invalid-open-ended-section-literal',
|
||||||
|
tags: '動画 伊地知ニジカ[3:00-]',
|
||||||
|
duration: '3:00',
|
||||||
|
thumbnail: dummy_upload
|
||||||
|
)
|
||||||
|
|
||||||
|
expect(response).to have_http_status(:unprocessable_entity)
|
||||||
|
expect(json.fetch('errors')).to include(
|
||||||
|
'video_ms' => ['タグ区間の開始が動画時間以上です.']
|
||||||
|
)
|
||||||
|
end
|
||||||
|
|
||||||
context "when nico tag already exists in tags" do
|
context "when nico tag already exists in tags" do
|
||||||
before do
|
before do
|
||||||
Tag.find_undiscard_or_create_by!(
|
Tag.find_undiscard_or_create_by!(
|
||||||
|
|||||||
@@ -56,6 +56,17 @@ RSpec.describe "TagChildren", type: :request do
|
|||||||
|
|
||||||
expect(response).to have_http_status(:no_content)
|
expect(response).to have_http_status(:no_content)
|
||||||
end
|
end
|
||||||
|
|
||||||
|
it 'returns 422 and does not create relation when the new link makes a cycle' do
|
||||||
|
TagImplication.create!(tag: parent, parent_tag: child)
|
||||||
|
|
||||||
|
expect {
|
||||||
|
do_request
|
||||||
|
}.not_to change(TagImplication, :count)
|
||||||
|
|
||||||
|
expect(response).to have_http_status(:unprocessable_entity)
|
||||||
|
expect(TagImplication.where(tag: child, parent_tag: parent)).not_to exist
|
||||||
|
end
|
||||||
end
|
end
|
||||||
|
|
||||||
context "when Tag.find raises (invalid ids)" do
|
context "when Tag.find raises (invalid ids)" do
|
||||||
|
|||||||
@@ -581,6 +581,58 @@ RSpec.describe 'Tags API', type: :request do
|
|||||||
expect(response).to have_http_status(:ok)
|
expect(response).to have_http_status(:ok)
|
||||||
expect(wiki_page.reload.wiki_versions.count).to eq(before_wiki_version_count)
|
expect(wiki_page.reload.wiki_versions.count).to eq(before_wiki_version_count)
|
||||||
end
|
end
|
||||||
|
|
||||||
|
it 'full update で旧名 alias が残った tag を PATCH で旧名へ戻せる' do
|
||||||
|
put "/tags/#{ tag.id }", params: {
|
||||||
|
name: 'patch_roundtrip_target',
|
||||||
|
category: 'general',
|
||||||
|
aliases: 'unko',
|
||||||
|
parent_tags: '',
|
||||||
|
deprecated: '0',
|
||||||
|
}
|
||||||
|
|
||||||
|
expect(response).to have_http_status(:ok)
|
||||||
|
expect(TagName.find_by!(name: 'spec_tag').canonical).to eq(tag.reload.tag_name)
|
||||||
|
|
||||||
|
patch "/tags/#{ tag.id }", params: { name: 'spec_tag' }
|
||||||
|
|
||||||
|
expect(response).to have_http_status(:ok)
|
||||||
|
|
||||||
|
tag.reload
|
||||||
|
|
||||||
|
expect(tag.name).to eq('spec_tag')
|
||||||
|
expect(tag.tag_name.canonical_id).to be_nil
|
||||||
|
expect(TagName.find_by!(name: 'patch_roundtrip_target').canonical).to eq(tag.tag_name)
|
||||||
|
end
|
||||||
|
|
||||||
|
it '別 tag の正規名には変更できない' do
|
||||||
|
wiki_page =
|
||||||
|
Wiki::Commit.create_content!(
|
||||||
|
tag_name: tag.tag_name,
|
||||||
|
body: 'patch collision wiki',
|
||||||
|
created_by_user: member_user,
|
||||||
|
message: 'init')
|
||||||
|
|
||||||
|
patch "/tags/#{ tag.id }", params: { name: 'unknown' }
|
||||||
|
|
||||||
|
expect(response).to have_http_status(:unprocessable_entity)
|
||||||
|
expect(json.fetch('errors')).to include(
|
||||||
|
'name' => ['その名前は既に使はれてゐます.']
|
||||||
|
)
|
||||||
|
|
||||||
|
expect(tag.reload.name).to eq('spec_tag')
|
||||||
|
expect(tag.tag_name.aliases.map(&:name)).to contain_exactly('unko')
|
||||||
|
expect(wiki_page.reload.tag_name).to eq(tag.tag_name)
|
||||||
|
end
|
||||||
|
|
||||||
|
it 'system tag の name は変更できない' do
|
||||||
|
system_tag = Tag.bot
|
||||||
|
|
||||||
|
patch "/tags/#{ system_tag.id }", params: { name: 'patch_system_tag_renamed' }
|
||||||
|
|
||||||
|
expect(response).to have_http_status(:unprocessable_entity)
|
||||||
|
expect(system_tag.reload.name).to eq('bot操作')
|
||||||
|
end
|
||||||
end
|
end
|
||||||
end
|
end
|
||||||
|
|
||||||
@@ -745,7 +797,17 @@ RSpec.describe 'Tags API', type: :request do
|
|||||||
)
|
)
|
||||||
TagImplication.create!(tag: first, parent_tag: root_material)
|
TagImplication.create!(tag: first, parent_tag: root_material)
|
||||||
TagImplication.create!(tag: second, parent_tag: first)
|
TagImplication.create!(tag: second, parent_tag: first)
|
||||||
TagImplication.create!(tag: first, parent_tag: second)
|
now = Time.current
|
||||||
|
TagImplication.insert_all!(
|
||||||
|
[
|
||||||
|
{
|
||||||
|
tag_id: first.id,
|
||||||
|
parent_tag_id: second.id,
|
||||||
|
created_at: now,
|
||||||
|
updated_at: now
|
||||||
|
}
|
||||||
|
]
|
||||||
|
)
|
||||||
|
|
||||||
get '/tags/with-depth', params: { parent: root_material.id }
|
get '/tags/with-depth', params: { parent: root_material.id }
|
||||||
|
|
||||||
@@ -1029,6 +1091,42 @@ RSpec.describe 'Tags API', type: :request do
|
|||||||
expect(versions.second.created_by_user_id).to eq(member_user.id)
|
expect(versions.second.created_by_user_id).to eq(member_user.id)
|
||||||
end
|
end
|
||||||
|
|
||||||
|
it '同じ tag の旧 alias へ戻しても rename できる' do
|
||||||
|
put "/tags/#{ tag.id }", params: {
|
||||||
|
name: 'put_roundtrip_b',
|
||||||
|
category: 'general',
|
||||||
|
aliases: 'unko',
|
||||||
|
parent_tags: '',
|
||||||
|
deprecated: '0',
|
||||||
|
}
|
||||||
|
|
||||||
|
expect(response).to have_http_status(:ok)
|
||||||
|
|
||||||
|
put "/tags/#{ tag.id }", params: {
|
||||||
|
name: 'spec_tag',
|
||||||
|
category: 'general',
|
||||||
|
aliases: 'unko',
|
||||||
|
parent_tags: '',
|
||||||
|
deprecated: '0',
|
||||||
|
}
|
||||||
|
|
||||||
|
expect(response).to have_http_status(:ok)
|
||||||
|
|
||||||
|
tag.reload
|
||||||
|
|
||||||
|
expect(tag.name).to eq('spec_tag')
|
||||||
|
expect(TagName.find_by!(name: 'put_roundtrip_b').canonical).to eq(tag.tag_name)
|
||||||
|
expect(tag.tag_name.aliases.map(&:name)).to contain_exactly('put_roundtrip_b', 'unko')
|
||||||
|
expect(tag.tag_name.aliases.map(&:name)).not_to include('spec_tag')
|
||||||
|
expect(alias_tn.reload.canonical).to eq(tag.tag_name)
|
||||||
|
|
||||||
|
version = tag.tag_versions.order(:version_no).last
|
||||||
|
|
||||||
|
expect(version.event_type).to eq('update')
|
||||||
|
expect(version.name).to eq('spec_tag')
|
||||||
|
expect(version.aliases.split).to contain_exactly('put_roundtrip_b', 'unko')
|
||||||
|
end
|
||||||
|
|
||||||
it 'parent tag の snapshot も作成する' do
|
it 'parent tag の snapshot も作成する' do
|
||||||
old_parent = Tag.create!(
|
old_parent = Tag.create!(
|
||||||
tag_name: TagName.create!(name: 'put_snapshot_old_parent'),
|
tag_name: TagName.create!(name: 'put_snapshot_old_parent'),
|
||||||
@@ -1153,6 +1251,48 @@ RSpec.describe 'Tags API', type: :request do
|
|||||||
)
|
)
|
||||||
end
|
end
|
||||||
|
|
||||||
|
it 'wiki を持つ tag を旧 alias へ戻しても wiki を新 canonical へ移す' do
|
||||||
|
wiki_page =
|
||||||
|
Wiki::Commit.create_content!(
|
||||||
|
tag_name: tag.tag_name,
|
||||||
|
body: 'wiki body before',
|
||||||
|
created_by_user: member_user,
|
||||||
|
message: 'init')
|
||||||
|
|
||||||
|
expect {
|
||||||
|
put "/tags/#{ tag.id }", params: {
|
||||||
|
name: 'put_wiki_roundtrip_b',
|
||||||
|
category: 'general',
|
||||||
|
aliases: 'unko',
|
||||||
|
parent_tags: '',
|
||||||
|
deprecated: '0',
|
||||||
|
}
|
||||||
|
|
||||||
|
put "/tags/#{ tag.id }", params: {
|
||||||
|
name: 'spec_tag',
|
||||||
|
category: 'general',
|
||||||
|
aliases: 'unko',
|
||||||
|
parent_tags: '',
|
||||||
|
deprecated: '0',
|
||||||
|
}
|
||||||
|
}
|
||||||
|
.to change(TagVersion, :count).by(3)
|
||||||
|
.and change(WikiVersion, :count).by(2)
|
||||||
|
|
||||||
|
expect(response).to have_http_status(:ok)
|
||||||
|
|
||||||
|
tag.reload
|
||||||
|
|
||||||
|
expect(wiki_page.reload.tag_name).to eq(tag.tag_name)
|
||||||
|
expect(TagName.find_by!(name: 'put_wiki_roundtrip_b').wiki_page).to be_nil
|
||||||
|
expect(TagName.find_by!(name: 'put_wiki_roundtrip_b').canonical).to eq(tag.tag_name)
|
||||||
|
|
||||||
|
versions = wiki_page.wiki_versions.order(:version_no).last(2)
|
||||||
|
|
||||||
|
expect(versions.map(&:event_type)).to eq(['update', 'update'])
|
||||||
|
expect(versions.map(&:title)).to eq(['put_wiki_roundtrip_b', 'spec_tag'])
|
||||||
|
end
|
||||||
|
|
||||||
it '別名を他 tag から奪った場合、奪はれた側の tag version も作成する' do
|
it '別名を他 tag から奪った場合、奪はれた側の tag version も作成する' do
|
||||||
old_owner = Tag.create!(
|
old_owner = Tag.create!(
|
||||||
tag_name: TagName.create!(name: 'put_alias_old_owner'),
|
tag_name: TagName.create!(name: 'put_alias_old_owner'),
|
||||||
@@ -1191,9 +1331,49 @@ RSpec.describe 'Tags API', type: :request do
|
|||||||
expect(old_owner_versions.second.aliases.split).not_to include('put_stolen_alias')
|
expect(old_owner_versions.second.aliases.split).not_to include('put_stolen_alias')
|
||||||
end
|
end
|
||||||
|
|
||||||
it 'parent_tags に指定すると循環する tag は 422 にする' do
|
it '別 tag の alias 名を rename で奪へる' do
|
||||||
pending '#332 で対応予定'
|
old_owner = Tag.create!(
|
||||||
|
tag_name: TagName.create!(name: 'put_alias_collision_owner'),
|
||||||
|
category: :general
|
||||||
|
)
|
||||||
|
stolen_alias = TagName.create!(
|
||||||
|
name: 'put_alias_collision_name',
|
||||||
|
canonical: old_owner.tag_name
|
||||||
|
)
|
||||||
|
wiki_page =
|
||||||
|
Wiki::Commit.create_content!(
|
||||||
|
tag_name: tag.tag_name,
|
||||||
|
body: 'put collision wiki',
|
||||||
|
created_by_user: member_user,
|
||||||
|
message: 'init')
|
||||||
|
|
||||||
|
put "/tags/#{ tag.id }", params: {
|
||||||
|
name: 'put_alias_collision_name',
|
||||||
|
category: 'general',
|
||||||
|
aliases: 'unko',
|
||||||
|
parent_tags: '',
|
||||||
|
deprecated: '0',
|
||||||
|
}
|
||||||
|
|
||||||
|
expect(response).to have_http_status(:ok)
|
||||||
|
|
||||||
|
tag.reload
|
||||||
|
old_owner.reload
|
||||||
|
stolen_alias.reload
|
||||||
|
|
||||||
|
expect(tag.name).to eq('put_alias_collision_name')
|
||||||
|
expect(stolen_alias.canonical_id).to be_nil
|
||||||
|
expect(TagName.find_by!(name: 'spec_tag').canonical).to eq(tag.tag_name)
|
||||||
|
expect(old_owner.tag_name.aliases.map(&:name)).not_to include('put_alias_collision_name')
|
||||||
|
|
||||||
|
old_owner_versions = old_owner.tag_versions.order(:version_no)
|
||||||
|
|
||||||
|
expect(old_owner_versions.last.event_type).to eq('update')
|
||||||
|
expect(old_owner_versions.last.aliases.split).not_to include('put_alias_collision_name')
|
||||||
|
expect(wiki_page.reload.tag_name).to eq(tag.tag_name)
|
||||||
|
end
|
||||||
|
|
||||||
|
it 'parent_tags に指定すると循環する tag は 422 にする' do
|
||||||
child = Tag.create!(
|
child = Tag.create!(
|
||||||
tag_name: TagName.create!(name: 'put_cycle_child'),
|
tag_name: TagName.create!(name: 'put_cycle_child'),
|
||||||
category: :general
|
category: :general
|
||||||
|
|||||||
@@ -0,0 +1,23 @@
|
|||||||
|
require 'rails_helper'
|
||||||
|
|
||||||
|
RSpec.describe MaterialFileSha256 do
|
||||||
|
describe '.metadata_sha256' do
|
||||||
|
it 'reads sha256 from Hash metadata' do
|
||||||
|
blob = instance_double(ActiveStorage::Blob, metadata: { 'sha256' => 'abc123' })
|
||||||
|
|
||||||
|
expect(described_class.metadata_sha256(blob)).to eq('abc123')
|
||||||
|
end
|
||||||
|
|
||||||
|
it 'reads sha256 from JSON string metadata' do
|
||||||
|
blob = instance_double(ActiveStorage::Blob, metadata: '{"sha256":"abc123"}')
|
||||||
|
|
||||||
|
expect(described_class.metadata_sha256(blob)).to eq('abc123')
|
||||||
|
end
|
||||||
|
|
||||||
|
it 'returns nil for invalid metadata' do
|
||||||
|
blob = instance_double(ActiveStorage::Blob, metadata: '{')
|
||||||
|
|
||||||
|
expect(described_class.metadata_sha256(blob)).to be_nil
|
||||||
|
end
|
||||||
|
end
|
||||||
|
end
|
||||||
@@ -0,0 +1,128 @@
|
|||||||
|
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
|
||||||
@@ -0,0 +1,89 @@
|
|||||||
|
require 'rails_helper'
|
||||||
|
|
||||||
|
RSpec.describe MaterialSyncRunner do
|
||||||
|
let(:user) { create(:user, :member) }
|
||||||
|
let(:source) do
|
||||||
|
MaterialSyncSource.create!(
|
||||||
|
name: 'Drive source',
|
||||||
|
source_kind: 'google_drive_path',
|
||||||
|
source_file_id: 'folder-123',
|
||||||
|
profile: 'legacy_drive',
|
||||||
|
created_by_user: user,
|
||||||
|
updated_by_user: user)
|
||||||
|
end
|
||||||
|
let(:drive_client) { instance_double(GoogleDrive::ApiClient) }
|
||||||
|
|
||||||
|
describe '#sync!' do
|
||||||
|
it 'imports google drive path candidates as they are yielded' do
|
||||||
|
first_entry = { id: 'file-1',
|
||||||
|
name: 'a.png',
|
||||||
|
mime_type: 'image/png',
|
||||||
|
relative_path: '素材/a.png',
|
||||||
|
sha256_checksum: 'sha-a',
|
||||||
|
web_view_link: 'https://drive.google.com/file/d/file-1/view',
|
||||||
|
web_content_link: nil }
|
||||||
|
second_entry = { id: 'file-2',
|
||||||
|
name: 'b.png',
|
||||||
|
mime_type: 'image/png',
|
||||||
|
relative_path: '素材/b.png',
|
||||||
|
sha256_checksum: 'sha-b',
|
||||||
|
web_view_link: 'https://drive.google.com/file/d/file-2/view',
|
||||||
|
web_content_link: nil }
|
||||||
|
yielded = []
|
||||||
|
|
||||||
|
allow(GoogleDrive::ApiClient).to receive(:new).and_return(drive_client)
|
||||||
|
allow(drive_client).to receive(:each_material_file_under_folder) do |folder_id, &block|
|
||||||
|
expect(folder_id).to eq('folder-123')
|
||||||
|
block.call(first_entry)
|
||||||
|
expect(yielded).to eq(['素材/a.png'])
|
||||||
|
block.call(second_entry)
|
||||||
|
end
|
||||||
|
allow(MaterialSyncImporter).to receive(:import!) do |candidate|
|
||||||
|
yielded << candidate.fetch(:source_path)
|
||||||
|
instance_double(MaterialSyncImporter::Result,
|
||||||
|
action: yielded.last == '素材/a.png' ? :imported : :updated)
|
||||||
|
end
|
||||||
|
|
||||||
|
result = described_class.new(source).sync!
|
||||||
|
|
||||||
|
expect(yielded).to eq(['素材/a.png', '素材/b.png'])
|
||||||
|
expect(result.imported).to eq(1)
|
||||||
|
expect(result.updated).to eq(1)
|
||||||
|
expect(result.unchanged).to eq(0)
|
||||||
|
expect(source.reload.last_synced_at).to be_present
|
||||||
|
end
|
||||||
|
|
||||||
|
it 'logs google drive path progress at first item and summary' do
|
||||||
|
entry = { id: 'file-1',
|
||||||
|
name: 'a.png',
|
||||||
|
mime_type: 'image/png',
|
||||||
|
relative_path: '素材/a.png',
|
||||||
|
sha256_checksum: 'sha-a',
|
||||||
|
web_view_link: 'https://drive.google.com/file/d/file-1/view',
|
||||||
|
web_content_link: nil }
|
||||||
|
logged = []
|
||||||
|
|
||||||
|
allow(GoogleDrive::ApiClient).to receive(:new).and_return(drive_client)
|
||||||
|
allow(drive_client).to receive(:each_material_file_under_folder) do |_folder_id, &block|
|
||||||
|
block.call(entry)
|
||||||
|
end
|
||||||
|
allow(MaterialSyncImporter).to receive(:import!)
|
||||||
|
.and_return(instance_double(MaterialSyncImporter::Result, action: :imported))
|
||||||
|
allow(Rails.logger).to receive(:info) { |message| logged << JSON.parse(message) }
|
||||||
|
|
||||||
|
described_class.new(source).sync!
|
||||||
|
|
||||||
|
progress_logs = logged.select { |row| row['folder_id'] == 'folder-123' }
|
||||||
|
expect(progress_logs.map { |row| row['progress'] }).to eq(['scan', 'summary'])
|
||||||
|
expect(progress_logs.last).to include(
|
||||||
|
'material_sync_source_id' => source.id,
|
||||||
|
'material_sync_source_name' => 'Drive source',
|
||||||
|
'scanned_count' => 1,
|
||||||
|
'imported' => 1,
|
||||||
|
'updated' => 0,
|
||||||
|
'unchanged' => 0,
|
||||||
|
'suppressed' => 0,
|
||||||
|
'failed' => 0)
|
||||||
|
end
|
||||||
|
end
|
||||||
|
end
|
||||||
+3
-2
@@ -6,6 +6,7 @@ import { BrowserRouter,
|
|||||||
Routes,
|
Routes,
|
||||||
useLocation } from 'react-router-dom'
|
useLocation } from 'react-router-dom'
|
||||||
|
|
||||||
|
import DevModeWatermark from '@/components/DevModeWatermark'
|
||||||
import RouteBlockerOverlay from '@/components/RouteBlockerOverlay'
|
import RouteBlockerOverlay from '@/components/RouteBlockerOverlay'
|
||||||
import TopNav from '@/components/TopNav'
|
import TopNav from '@/components/TopNav'
|
||||||
import DialogueProvider from '@/components/dialogues/DialogueProvider'
|
import DialogueProvider from '@/components/dialogues/DialogueProvider'
|
||||||
@@ -75,7 +76,6 @@ const RouteTransitionWrapper = ({ user, setUser }: {
|
|||||||
<Route path="suppressions" element={<MaterialSyncSuppressionsPage/>}/>
|
<Route path="suppressions" element={<MaterialSyncSuppressionsPage/>}/>
|
||||||
<Route path=":id" element ={<MaterialDetailPage/>}/>
|
<Route path=":id" element ={<MaterialDetailPage/>}/>
|
||||||
</Route>
|
</Route>
|
||||||
{/* <Route path="/materials/search" element={<MaterialSearchPage/>}/> */}
|
|
||||||
<Route path="/wiki" element={<WikiSearchPage/>}/>
|
<Route path="/wiki" element={<WikiSearchPage/>}/>
|
||||||
<Route path="/wiki/:title" element={<WikiDetailPage/>}/>
|
<Route path="/wiki/:title" element={<WikiDetailPage/>}/>
|
||||||
<Route path="/wiki/new" element={<WikiNewPage user={user}/>}/>
|
<Route path="/wiki/new" element={<WikiNewPage user={user}/>}/>
|
||||||
@@ -146,6 +146,7 @@ const App: FC = () => {
|
|||||||
return (
|
return (
|
||||||
<>
|
<>
|
||||||
<RouteBlockerOverlay/>
|
<RouteBlockerOverlay/>
|
||||||
|
{import.meta.env.DEV && <DevModeWatermark/>}
|
||||||
|
|
||||||
<BrowserRouter>
|
<BrowserRouter>
|
||||||
<DialogueProvider>
|
<DialogueProvider>
|
||||||
@@ -153,7 +154,7 @@ const App: FC = () => {
|
|||||||
<motion.div
|
<motion.div
|
||||||
layout="position"
|
layout="position"
|
||||||
transition={{ layout: { duration: .2, ease: 'easeOut' } }}
|
transition={{ layout: { duration: .2, ease: 'easeOut' } }}
|
||||||
className="flex flex-col h-dvh w-full overflow-y-hidden">
|
className="relative flex flex-col h-dvh w-full overflow-y-hidden">
|
||||||
<TopNav user={user}/>
|
<TopNav user={user}/>
|
||||||
<RouteTransitionWrapper user={user} setUser={setUser}/>
|
<RouteTransitionWrapper user={user} setUser={setUser}/>
|
||||||
</motion.div>
|
</motion.div>
|
||||||
|
|||||||
@@ -0,0 +1,46 @@
|
|||||||
|
import nikumaru from '@/assets/fonts/nikumaru.otf'
|
||||||
|
|
||||||
|
import type { FC } from 'react'
|
||||||
|
|
||||||
|
|
||||||
|
const ROW_COUNT = 8
|
||||||
|
const COLUMN_COUNT = 12
|
||||||
|
|
||||||
|
|
||||||
|
const DevModeWatermark: FC = () => {
|
||||||
|
return (
|
||||||
|
<div
|
||||||
|
aria-hidden="true"
|
||||||
|
className="pointer-events-none select-none fixed inset-0 overflow-hidden z-0">
|
||||||
|
<style>{`
|
||||||
|
@font-face {
|
||||||
|
font-family: 'Nikumaru';
|
||||||
|
src: url(${nikumaru}) format('opentype');
|
||||||
|
}
|
||||||
|
`}</style>
|
||||||
|
<div className="absolute -inset-32 flex flex-col justify-center gap-12 py-48">
|
||||||
|
{Array.from ({ length: ROW_COUNT }, (_, rowIndex) => (
|
||||||
|
<div
|
||||||
|
key={rowIndex}
|
||||||
|
className={
|
||||||
|
'flex min-h-32 items-center gap-12 '
|
||||||
|
+ (rowIndex % 2 === 0 ? 'translate-x-0' : 'translate-x-32')
|
||||||
|
}>
|
||||||
|
{Array.from ({ length: COLUMN_COUNT }, (_, columnIndex) => (
|
||||||
|
<span
|
||||||
|
key={columnIndex}
|
||||||
|
className={
|
||||||
|
'whitespace-nowrap text-3xl font-bold '
|
||||||
|
+ 'tracking-[0.3em] text-neutral-950/5 '
|
||||||
|
+ 'dark:text-white/10'
|
||||||
|
}
|
||||||
|
style={{ fontFamily: 'Nikumaru' }}>
|
||||||
|
開発モード
|
||||||
|
</span>))}
|
||||||
|
</div>))}
|
||||||
|
</div>
|
||||||
|
</div>)
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
export default DevModeWatermark
|
||||||
@@ -87,10 +87,13 @@ const DraggableDroppableTagRow: FC<Props> = ({ tag, nestLevel, pathKey, parentTa
|
|||||||
setDropRef (node)
|
setDropRef (node)
|
||||||
}}
|
}}
|
||||||
style={style}
|
style={style}
|
||||||
className={cn ('rounded select-none', over && 'ring-2 ring-offset-2')}
|
className={cn (
|
||||||
|
'min-w-0 max-w-full overflow-hidden rounded select-none',
|
||||||
|
over && 'ring-2 ring-offset-2')}
|
||||||
{...attributes}
|
{...attributes}
|
||||||
{...listeners}>
|
{...listeners}>
|
||||||
<motion.div
|
<motion.div
|
||||||
|
className="flex min-w-0 max-w-full items-baseline overflow-hidden"
|
||||||
transition={{ layout: { duration: .2, ease: 'easeOut' } }}
|
transition={{ layout: { duration: .2, ease: 'easeOut' } }}
|
||||||
layoutId={`tag-${ sp ? 'sp-' : '' }${ tag.id }`}>
|
layoutId={`tag-${ sp ? 'sp-' : '' }${ tag.id }`}>
|
||||||
<TagLink tag={tag} nestLevel={nestLevel}/>
|
<TagLink tag={tag} nestLevel={nestLevel}/>
|
||||||
@@ -98,4 +101,4 @@ const DraggableDroppableTagRow: FC<Props> = ({ tag, nestLevel, pathKey, parentTa
|
|||||||
</div>)
|
</div>)
|
||||||
}
|
}
|
||||||
|
|
||||||
export default DraggableDroppableTagRow
|
export default DraggableDroppableTagRow
|
||||||
|
|||||||
@@ -1,28 +1,43 @@
|
|||||||
import { Fragment, useEffect, useRef, useState } from 'react'
|
|
||||||
import { useQuery } from '@tanstack/react-query'
|
import { useQuery } from '@tanstack/react-query'
|
||||||
|
import { useEffect, useRef, useState } from 'react'
|
||||||
import { useLocation, useNavigate } from 'react-router-dom'
|
import { useLocation, useNavigate } from 'react-router-dom'
|
||||||
|
|
||||||
import TagLink from '@/components/TagLink'
|
|
||||||
import SidebarComponent from '@/components/layout/SidebarComponent'
|
import SidebarComponent from '@/components/layout/SidebarComponent'
|
||||||
import { materialsKeys } from '@/lib/queryKeys'
|
import TagLink from '@/components/TagLink'
|
||||||
import { fetchMaterialTagTree, parseMaterialFilter } from '@/lib/materials'
|
import { fetchMaterialTagTree, parseMaterialFilter } from '@/lib/materials'
|
||||||
|
import { materialsKeys } from '@/lib/queryKeys'
|
||||||
|
import { cn } from '@/lib/utils'
|
||||||
|
|
||||||
import type { Dispatch, FC, ReactNode, SetStateAction } from 'react'
|
import type { CSSProperties, Dispatch, FC, ReactNode, SetStateAction } from 'react'
|
||||||
|
|
||||||
import type { MaterialFilter, MaterialSidebarTag, Tag } from '@/types'
|
import type { MaterialFilter, MaterialSidebarTag, Tag } from '@/types'
|
||||||
|
|
||||||
const FILTERS: MaterialFilter[] = ['present', 'missing', 'any']
|
const FILTERS: MaterialFilter[] = ['missing', 'present', 'any']
|
||||||
|
const FILTER_LABELS: Record<MaterialFilter, string> = { present: '有', missing: '無', any: '全' }
|
||||||
|
|
||||||
const FILTER_LABELS: Record<MaterialFilter, string> = {
|
|
||||||
present: '素材あり',
|
const px = (value: string): number => {
|
||||||
missing: '素材なし',
|
const parsed = Number.parseFloat (value)
|
||||||
any: 'すべて'}
|
return Number.isFinite (parsed) ? parsed : 0
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
const verticalChrome = (el: HTMLElement): number => {
|
||||||
|
const style = window.getComputedStyle (el)
|
||||||
|
|
||||||
|
return (
|
||||||
|
px (style.paddingTop)
|
||||||
|
+ px (style.paddingBottom)
|
||||||
|
+ px (style.borderTopWidth)
|
||||||
|
+ px (style.borderBottomWidth))
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
const setChildrenById = (
|
const setChildrenById = (
|
||||||
tags: MaterialSidebarTag[],
|
tags: MaterialSidebarTag[],
|
||||||
targetId: number,
|
targetId: number,
|
||||||
children: MaterialSidebarTag[]): MaterialSidebarTag[] => (
|
children: MaterialSidebarTag[],
|
||||||
|
): MaterialSidebarTag[] => (
|
||||||
tags.map (tag => {
|
tags.map (tag => {
|
||||||
if (tag.id === targetId)
|
if (tag.id === targetId)
|
||||||
return { ...tag, children }
|
return { ...tag, children }
|
||||||
@@ -35,8 +50,11 @@ const setChildrenById = (
|
|||||||
|
|
||||||
|
|
||||||
const materialPath = (
|
const materialPath = (
|
||||||
tagName: string,
|
tagId: number,
|
||||||
materialFilter: MaterialFilter): string => `/materials?q=${ encodeURIComponent (tagName) }&material_filter=${ materialFilter }`
|
materialFilter: MaterialFilter,
|
||||||
|
): string =>
|
||||||
|
`/materials?tag_id=${ tagId }&include_descendants=1&group_by=parent_tag`
|
||||||
|
+ `&material_filter=${ materialFilter }`
|
||||||
|
|
||||||
|
|
||||||
const sidebarTagToTag = (tag: MaterialSidebarTag): Tag => ({
|
const sidebarTagToTag = (tag: MaterialSidebarTag): Tag => ({
|
||||||
@@ -55,33 +73,43 @@ const sidebarTagToTag = (tag: MaterialSidebarTag): Tag => ({
|
|||||||
matchedAlias: null })
|
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 = (
|
const updateMaterialFilterQuery = (
|
||||||
pathname: string,
|
pathname: string,
|
||||||
locationSearch: string,
|
locationSearch: string,
|
||||||
navigate: ReturnType<typeof useNavigate>,
|
navigate: ReturnType<typeof useNavigate>,
|
||||||
materialFilter: MaterialFilter) => {
|
materialFilter: MaterialFilter,
|
||||||
const qs = new URLSearchParams (locationSearch)
|
) => {
|
||||||
qs.set ('material_filter', materialFilter)
|
const qs = new URLSearchParams (locationSearch)
|
||||||
navigate (`${ pathname }${ qs.toString () ? `?${ qs.toString () }` : '' }`)
|
qs.set ('material_filter', materialFilter)
|
||||||
|
navigate (`${ pathname }${ qs.toString () ? `?${ qs.toString () }` : '' }`)
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
||||||
const MaterialFilterButtons: FC<{
|
const MaterialFilterButtons: FC<{ materialFilter: MaterialFilter
|
||||||
materialFilter: MaterialFilter
|
onChange: (materialFilter: MaterialFilter) => void }> = (
|
||||||
onChange: (materialFilter: MaterialFilter) => void
|
{ materialFilter, onChange },
|
||||||
}> = ({ materialFilter, onChange }) => (
|
) => (
|
||||||
<div className="flex flex-wrap gap-2">
|
<div className="flex flex-wrap gap-2 justify-end md:justify-start flex-center">
|
||||||
|
<label className="my-auto text-sm font-bold">素材:</label>
|
||||||
{FILTERS.map (value => (
|
{FILTERS.map (value => (
|
||||||
<button
|
<button
|
||||||
key={value}
|
key={value}
|
||||||
type="button"
|
type="button"
|
||||||
onClick={() => onChange (value)}
|
onClick={() => onChange (value)}
|
||||||
className={`rounded-full border px-3 py-1 text-sm ${
|
className={cn (
|
||||||
materialFilter === value
|
'rounded-full border px-3 py-1 text-sm',
|
||||||
? 'border-sky-500 bg-sky-50 text-sky-700 dark:border-sky-400 ' +
|
(materialFilter === value
|
||||||
'dark:bg-sky-950 dark:text-sky-100'
|
? ['border-sky-500 bg-sky-50 text-sky-700 dark:border-sky-400',
|
||||||
: 'border-neutral-300 bg-white text-neutral-700 dark:border-stone-700 ' +
|
'dark:bg-sky-950 dark:text-sky-100']
|
||||||
'dark:bg-stone-900 dark:text-stone-200' }`}>
|
: ['border-neutral-300 bg-white text-neutral-700 dark:border-stone-700',
|
||||||
|
'dark:bg-stone-900 dark:text-stone-200']))}>
|
||||||
{FILTER_LABELS[value]}
|
{FILTER_LABELS[value]}
|
||||||
</button>))}
|
</button>))}
|
||||||
</div>)
|
</div>)
|
||||||
@@ -89,12 +117,14 @@ const MaterialFilterButtons: FC<{
|
|||||||
|
|
||||||
const MaterialTreeNode: FC<{
|
const MaterialTreeNode: FC<{
|
||||||
materialFilter: MaterialFilter
|
materialFilter: MaterialFilter
|
||||||
|
selectedTagId: number | null
|
||||||
nestLevel?: number
|
nestLevel?: number
|
||||||
onChildren: (tagId: number, children: MaterialSidebarTag[]) => void
|
onChildren: (tagId: number, children: MaterialSidebarTag[]) => void
|
||||||
openTags: Record<number, boolean>
|
openTags: Record<number, boolean>
|
||||||
setOpenTags: Dispatch<SetStateAction<Record<number, boolean>>>
|
setOpenTags: Dispatch<SetStateAction<Record<number, boolean>>>
|
||||||
tag: MaterialSidebarTag
|
tag: MaterialSidebarTag
|
||||||
}> = ({ materialFilter, nestLevel = 0, onChildren, openTags, setOpenTags, tag }) => {
|
}> = ({ materialFilter, nestLevel = 0, onChildren, openTags, selectedTagId,
|
||||||
|
setOpenTags, tag }) => {
|
||||||
const open = Boolean (openTags[tag.id])
|
const open = Boolean (openTags[tag.id])
|
||||||
const { data } = useQuery ({
|
const { data } = useQuery ({
|
||||||
queryKey: materialsKeys.tree ({ parentId: tag.id, materialFilter }),
|
queryKey: materialsKeys.tree ({ parentId: tag.id, materialFilter }),
|
||||||
@@ -107,10 +137,10 @@ const MaterialTreeNode: FC<{
|
|||||||
}, [data, onChildren, open, tag.children.length, tag.id])
|
}, [data, onChildren, open, tag.children.length, tag.id])
|
||||||
|
|
||||||
return (
|
return (
|
||||||
<Fragment>
|
<>
|
||||||
<li>
|
<li>
|
||||||
<div className="flex">
|
<div className="flex flex-center">
|
||||||
<div className="flex-none w-4">
|
<div className="flex-none w-4 my-auto">
|
||||||
{tag.hasChildren && (
|
{tag.hasChildren && (
|
||||||
<button
|
<button
|
||||||
type="button"
|
type="button"
|
||||||
@@ -119,14 +149,17 @@ const MaterialTreeNode: FC<{
|
|||||||
{open ? <>−</> : '+'}
|
{open ? <>−</> : '+'}
|
||||||
</button>)}
|
</button>)}
|
||||||
</div>
|
</div>
|
||||||
<div className="flex-1 truncate">
|
<div className="min-w-0 flex-1 my-auto">
|
||||||
<TagLink
|
<div className={cn (tagSelectionShellClass (selectedTagId === tag.id),
|
||||||
tag={sidebarTagToTag (tag)}
|
'min-w-0 truncate')}>
|
||||||
nestLevel={nestLevel}
|
<TagLink
|
||||||
title={tag.name}
|
tag={sidebarTagToTag (tag)}
|
||||||
withCount={false}
|
nestLevel={nestLevel}
|
||||||
withWiki={false}
|
title={tag.name}
|
||||||
to={materialPath (tag.name, materialFilter)}/>
|
withCount={false}
|
||||||
|
withWiki={false}
|
||||||
|
to={materialPath (tag.id, materialFilter)}/>
|
||||||
|
</div>
|
||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
</li>
|
</li>
|
||||||
@@ -138,23 +171,44 @@ const MaterialTreeNode: FC<{
|
|||||||
tag={child}
|
tag={child}
|
||||||
nestLevel={nestLevel + 1}
|
nestLevel={nestLevel + 1}
|
||||||
materialFilter={materialFilter}
|
materialFilter={materialFilter}
|
||||||
|
selectedTagId={selectedTagId}
|
||||||
openTags={openTags}
|
openTags={openTags}
|
||||||
setOpenTags={setOpenTags}
|
setOpenTags={setOpenTags}
|
||||||
onChildren={onChildren}/>))}
|
onChildren={onChildren}/>))}
|
||||||
</ul>)}
|
</ul>)}
|
||||||
</Fragment>)
|
</>)
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
||||||
const MobileMaterialTreeNode: FC<{
|
const MobileMaterialTreeNode: FC<{ depth?: number
|
||||||
depth?: number
|
availableInlineSizePx?: number | null
|
||||||
materialFilter: MaterialFilter
|
materialFilter: MaterialFilter
|
||||||
onChildren: (tagId: number, children: MaterialSidebarTag[]) => void
|
selectedTagId: number | null
|
||||||
openTags: Record<number, boolean>
|
onChildren: (tagId: number, children: MaterialSidebarTag[]) =>
|
||||||
setOpenTags: Dispatch<SetStateAction<Record<number, boolean>>>
|
void
|
||||||
tag: MaterialSidebarTag
|
openTags: Record<number, boolean>
|
||||||
}> = ({ depth = 0, materialFilter, onChildren, openTags, setOpenTags, tag }) => {
|
setOpenTags: Dispatch<SetStateAction<Record<number, boolean>>>
|
||||||
|
tag: MaterialSidebarTag }> = (
|
||||||
|
{
|
||||||
|
depth = 0,
|
||||||
|
availableInlineSizePx = null,
|
||||||
|
materialFilter,
|
||||||
|
onChildren,
|
||||||
|
openTags,
|
||||||
|
selectedTagId,
|
||||||
|
setOpenTags,
|
||||||
|
tag,
|
||||||
|
},
|
||||||
|
) => {
|
||||||
const open = Boolean (openTags[tag.id])
|
const open = Boolean (openTags[tag.id])
|
||||||
|
const tagColumnRef = useRef<HTMLDivElement | null> (null)
|
||||||
|
const chipRef = useRef<HTMLDivElement | null> (null)
|
||||||
|
const buttonRef = useRef<HTMLButtonElement | null> (null)
|
||||||
|
const expansionSlotRef = useRef<HTMLDivElement | null> (null)
|
||||||
|
const expansionBorderRef = useRef<HTMLDivElement | null> (null)
|
||||||
|
const [tagChipInlineSizePx, setTagChipInlineSizePx] = useState<number | null> (null)
|
||||||
|
const [tagLinkInlineSizePx, setTagLinkInlineSizePx] = useState<number | null> (null)
|
||||||
|
const [childAvailableInlineSizePx, setChildAvailableInlineSizePx] = useState<number | null> (null)
|
||||||
const { data } = useQuery ({
|
const { data } = useQuery ({
|
||||||
queryKey: materialsKeys.tree ({ parentId: tag.id, materialFilter }),
|
queryKey: materialsKeys.tree ({ parentId: tag.id, materialFilter }),
|
||||||
queryFn: () => fetchMaterialTagTree ({ parentId: tag.id, materialFilter }),
|
queryFn: () => fetchMaterialTagTree ({ parentId: tag.id, materialFilter }),
|
||||||
@@ -165,50 +219,163 @@ const MobileMaterialTreeNode: FC<{
|
|||||||
onChildren (tag.id, data)
|
onChildren (tag.id, data)
|
||||||
}, [data, onChildren, open, tag.children.length, tag.id])
|
}, [data, onChildren, open, tag.children.length, tag.id])
|
||||||
|
|
||||||
|
useEffect (() => {
|
||||||
|
const tagColumn = tagColumnRef.current
|
||||||
|
const chip = chipRef.current
|
||||||
|
if (!(tagColumn) || !(chip))
|
||||||
|
return
|
||||||
|
|
||||||
|
const updateTagInlineSize = () => {
|
||||||
|
const buttonHeight = buttonRef.current?.offsetHeight ?? 0
|
||||||
|
const gap = tag.hasChildren ? px (window.getComputedStyle (tagColumn).rowGap) : 0
|
||||||
|
const columnHeight =
|
||||||
|
availableInlineSizePx == null
|
||||||
|
? tagColumn.clientHeight
|
||||||
|
: Math.min (tagColumn.clientHeight, availableInlineSizePx)
|
||||||
|
const nextChipInlineSize = Math.max (24, columnHeight - buttonHeight - gap)
|
||||||
|
const nextLinkInlineSize = Math.max (
|
||||||
|
16,
|
||||||
|
nextChipInlineSize - verticalChrome (chip),
|
||||||
|
)
|
||||||
|
|
||||||
|
setTagChipInlineSizePx (prev => prev === nextChipInlineSize ? prev : nextChipInlineSize)
|
||||||
|
setTagLinkInlineSizePx (prev => prev === nextLinkInlineSize ? prev : nextLinkInlineSize)
|
||||||
|
}
|
||||||
|
|
||||||
|
updateTagInlineSize ()
|
||||||
|
|
||||||
|
const resizeObserver = new ResizeObserver (() => {
|
||||||
|
updateTagInlineSize ()
|
||||||
|
})
|
||||||
|
|
||||||
|
resizeObserver.observe (tagColumn)
|
||||||
|
resizeObserver.observe (chip)
|
||||||
|
|
||||||
|
if (buttonRef.current)
|
||||||
|
resizeObserver.observe (buttonRef.current)
|
||||||
|
|
||||||
|
return () => {
|
||||||
|
resizeObserver.disconnect ()
|
||||||
|
}
|
||||||
|
}, [availableInlineSizePx, open, tag.hasChildren, tag.children.length])
|
||||||
|
|
||||||
|
useEffect (() => {
|
||||||
|
const expansionSlot = expansionSlotRef.current
|
||||||
|
const expansionBorder = expansionBorderRef.current
|
||||||
|
if (!(expansionSlot) || !(expansionBorder))
|
||||||
|
return
|
||||||
|
|
||||||
|
const updateChildInlineSize = () => {
|
||||||
|
const base =
|
||||||
|
availableInlineSizePx == null
|
||||||
|
? expansionSlot.clientHeight
|
||||||
|
: availableInlineSizePx
|
||||||
|
const chrome = verticalChrome (expansionSlot) + verticalChrome (expansionBorder)
|
||||||
|
const nextInlineSize = Math.max (24, base - chrome)
|
||||||
|
setChildAvailableInlineSizePx (prev => prev === nextInlineSize ? prev : nextInlineSize)
|
||||||
|
}
|
||||||
|
|
||||||
|
updateChildInlineSize ()
|
||||||
|
|
||||||
|
const resizeObserver = new ResizeObserver (() => {
|
||||||
|
updateChildInlineSize ()
|
||||||
|
})
|
||||||
|
|
||||||
|
resizeObserver.observe (expansionSlot)
|
||||||
|
resizeObserver.observe (expansionBorder)
|
||||||
|
|
||||||
|
return () => {
|
||||||
|
resizeObserver.disconnect ()
|
||||||
|
}
|
||||||
|
}, [availableInlineSizePx, open, tag.children.length])
|
||||||
|
|
||||||
return (
|
return (
|
||||||
<div className="flex flex-row-reverse items-start gap-2">
|
<div className="flex h-full min-h-0 max-h-full flex-row-reverse items-start gap-2
|
||||||
<div className="flex flex-col items-center gap-1">
|
overflow-hidden">
|
||||||
|
<div
|
||||||
|
ref={tagColumnRef}
|
||||||
|
className="flex h-full min-h-0 max-h-full flex-col items-center gap-1
|
||||||
|
overflow-hidden">
|
||||||
<div
|
<div
|
||||||
className="rounded-xl border border-stone-300 bg-white px-3 py-2 text-sm
|
ref={chipRef}
|
||||||
text-stone-900 shadow-sm dark:border-stone-700 dark:bg-stone-900
|
className={cn (
|
||||||
dark:text-stone-100"
|
tagSelectionShellClass (selectedTagId === tag.id),
|
||||||
style={{ writingMode: 'vertical-rl' }}>
|
'box-border rounded-xl border px-3 py-2 text-sm shadow-sm',
|
||||||
|
'min-h-0 overflow-hidden [max-inline-size:var(--tag-chip-inline-size)]',
|
||||||
|
'[max-height:var(--tag-chip-inline-size)]',
|
||||||
|
)}
|
||||||
|
style={{
|
||||||
|
writingMode: 'vertical-rl',
|
||||||
|
'--tag-chip-inline-size': (
|
||||||
|
tagChipInlineSizePx == null
|
||||||
|
? undefined
|
||||||
|
: `${ tagChipInlineSizePx }px`),
|
||||||
|
'--tag-link-inline-size': (
|
||||||
|
tagLinkInlineSizePx == null
|
||||||
|
? undefined
|
||||||
|
: `${ tagLinkInlineSizePx }px`),
|
||||||
|
} as CSSProperties}>
|
||||||
<TagLink
|
<TagLink
|
||||||
tag={sidebarTagToTag (tag)}
|
tag={sidebarTagToTag (tag)}
|
||||||
title={tag.name}
|
title={tag.name}
|
||||||
|
truncateOnMobile
|
||||||
withCount={false}
|
withCount={false}
|
||||||
withWiki={false}
|
withWiki={false}
|
||||||
to={materialPath (tag.name, materialFilter)}/>
|
to={materialPath (tag.id, materialFilter)}
|
||||||
|
className="block overflow-hidden text-ellipsis whitespace-nowrap
|
||||||
|
[max-inline-size:var(--tag-link-inline-size)]
|
||||||
|
[max-height:var(--tag-link-inline-size)]
|
||||||
|
[&_.tag-marquee]:block
|
||||||
|
[&_.tag-marquee]:h-full
|
||||||
|
[&_.tag-marquee]:overflow-hidden
|
||||||
|
[&_.tag-marquee__static]:h-full
|
||||||
|
[&_.tag-marquee__static]:overflow-hidden
|
||||||
|
[&_.tag-marquee__static]:text-ellipsis
|
||||||
|
[&_.tag-marquee__static]:[text-overflow:ellipsis]"/>
|
||||||
</div>
|
</div>
|
||||||
{tag.hasChildren && (
|
{tag.hasChildren && (
|
||||||
<button
|
<button
|
||||||
|
ref={buttonRef}
|
||||||
type="button"
|
type="button"
|
||||||
onClick={() => setOpenTags (prev => ({ ...prev, [tag.id]: !prev[tag.id] }))}
|
onClick={() => setOpenTags (prev => ({ ...prev, [tag.id]: !prev[tag.id] }))}
|
||||||
className="rounded-full border border-stone-300 bg-white px-2 py-0.5
|
className="flex-none rounded-full border border-stone-300 bg-white
|
||||||
text-sm text-stone-700 dark:border-stone-700
|
px-2 py-0.5 text-sm text-stone-700 dark:border-stone-700
|
||||||
dark:bg-stone-900 dark:text-stone-100">
|
dark:bg-stone-900 dark:text-stone-100">
|
||||||
{open ? <>−</> : '+'}
|
{open ? <>−</> : '+'}
|
||||||
</button>)}
|
</button>)}
|
||||||
</div>
|
</div>
|
||||||
{open && tag.children.length > 0 && (
|
{open && tag.children.length > 0 && (
|
||||||
<div
|
<div
|
||||||
className="relative flex flex-row-reverse items-start gap-2 rounded-2xl border
|
ref={expansionSlotRef}
|
||||||
border-stone-200 bg-stone-100/70 py-2 pl-2 pr-2 text-stone-900
|
className={cn (
|
||||||
dark:border-stone-700 dark:bg-stone-900/70 dark:text-stone-100"
|
'h-full min-h-0 max-h-full overflow-hidden box-border',
|
||||||
style={{ marginTop: `${ depth === 0 ? 1.25 : .75 }rem` }}>
|
depth === 0 ? 'pt-5' : 'pt-3')}>
|
||||||
<span
|
<div
|
||||||
aria-hidden="true"
|
ref={expansionBorderRef}
|
||||||
className="absolute -right-3 top-4 h-px w-3 bg-stone-300 dark:bg-stone-600"/>
|
className="relative max-h-full overflow-hidden rounded-2xl border border-stone-200
|
||||||
{tag.children.map (child => (
|
bg-stone-100/70 py-2 pl-2 pr-2 text-stone-900
|
||||||
<div key={child.id} className="relative">
|
dark:border-stone-700 dark:bg-stone-900/70 dark:text-stone-100">
|
||||||
<MobileMaterialTreeNode
|
<div className="flex h-full min-h-0 max-h-full flex-row-reverse items-start gap-2
|
||||||
tag={child}
|
overflow-hidden">
|
||||||
depth={depth + 1}
|
<span
|
||||||
materialFilter={materialFilter}
|
aria-hidden="true"
|
||||||
openTags={openTags}
|
className="absolute -right-3 top-4 h-px w-3 bg-stone-300 dark:bg-stone-600"/>
|
||||||
setOpenTags={setOpenTags}
|
{tag.children.map (child => (
|
||||||
onChildren={onChildren}/>
|
<div
|
||||||
</div>))}
|
key={child.id}
|
||||||
|
className="relative h-full min-h-0 max-h-full overflow-hidden">
|
||||||
|
<MobileMaterialTreeNode
|
||||||
|
tag={child}
|
||||||
|
depth={depth + 1}
|
||||||
|
availableInlineSizePx={childAvailableInlineSizePx}
|
||||||
|
materialFilter={materialFilter}
|
||||||
|
selectedTagId={selectedTagId}
|
||||||
|
openTags={openTags}
|
||||||
|
setOpenTags={setOpenTags}
|
||||||
|
onChildren={onChildren}/>
|
||||||
|
</div>))}
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
</div>)}
|
</div>)}
|
||||||
</div>)
|
</div>)
|
||||||
}
|
}
|
||||||
@@ -218,11 +385,14 @@ const MaterialSidebar: FC = () => {
|
|||||||
const location = useLocation ()
|
const location = useLocation ()
|
||||||
const navigate = useNavigate ()
|
const navigate = useNavigate ()
|
||||||
const qs = new URLSearchParams (location.search)
|
const qs = new URLSearchParams (location.search)
|
||||||
const materialFilter = parseMaterialFilter (qs.get ('material_filter'), 'present')
|
const materialFilter = parseMaterialFilter (qs.get ('material_filter'), 'any')
|
||||||
|
const selectedTagId = Number (qs.get ('tag_id') ?? 0) || null
|
||||||
|
|
||||||
const [desktopTags, setDesktopTags] = useState<MaterialSidebarTag[]> ([])
|
const [desktopTags, setDesktopTags] = useState<MaterialSidebarTag[]> ([])
|
||||||
const [openTags, setOpenTags] = useState<Record<number, boolean>> ({ })
|
const [openTags, setOpenTags] = useState<Record<number, boolean>> ({ })
|
||||||
const mobileRailRef = useRef<HTMLDivElement | null> (null)
|
const mobileRailRef = useRef<HTMLDivElement | null> (null)
|
||||||
|
const [mobileAvailableInlineSizePx, setMobileAvailableInlineSizePx] =
|
||||||
|
useState<number | null> (null)
|
||||||
|
|
||||||
const { data: rootTags = [], isLoading, isError } = useQuery ({
|
const { data: rootTags = [], isLoading, isError } = useQuery ({
|
||||||
queryKey: materialsKeys.tree ({ parentId: null, materialFilter }),
|
queryKey: materialsKeys.tree ({ parentId: null, materialFilter }),
|
||||||
@@ -242,6 +412,29 @@ const MaterialSidebar: FC = () => {
|
|||||||
})
|
})
|
||||||
}, [rootTags, materialFilter])
|
}, [rootTags, materialFilter])
|
||||||
|
|
||||||
|
useEffect (() => {
|
||||||
|
const el = mobileRailRef.current
|
||||||
|
if (!(el))
|
||||||
|
return
|
||||||
|
|
||||||
|
const updateAvailableInlineSize = () => {
|
||||||
|
const nextInlineSize = Math.max (24, el.clientHeight)
|
||||||
|
setMobileAvailableInlineSizePx (prev => prev === nextInlineSize ? prev : nextInlineSize)
|
||||||
|
}
|
||||||
|
|
||||||
|
updateAvailableInlineSize ()
|
||||||
|
|
||||||
|
const resizeObserver = new ResizeObserver (() => {
|
||||||
|
updateAvailableInlineSize ()
|
||||||
|
})
|
||||||
|
|
||||||
|
resizeObserver.observe (el)
|
||||||
|
|
||||||
|
return () => {
|
||||||
|
resizeObserver.disconnect ()
|
||||||
|
}
|
||||||
|
}, [rootTags, materialFilter])
|
||||||
|
|
||||||
const visibleRootTags = desktopTags.length > 0 ? desktopTags : rootTags
|
const visibleRootTags = desktopTags.length > 0 ? desktopTags : rootTags
|
||||||
|
|
||||||
const setChildren = (tagId: number, children: MaterialSidebarTag[]) => {
|
const setChildren = (tagId: number, children: MaterialSidebarTag[]) => {
|
||||||
@@ -263,6 +456,7 @@ const MaterialSidebar: FC = () => {
|
|||||||
key={tag.id}
|
key={tag.id}
|
||||||
tag={tag}
|
tag={tag}
|
||||||
materialFilter={materialFilter}
|
materialFilter={materialFilter}
|
||||||
|
selectedTagId={selectedTagId}
|
||||||
openTags={openTags}
|
openTags={openTags}
|
||||||
setOpenTags={setOpenTags}
|
setOpenTags={setOpenTags}
|
||||||
onChildren={setChildren}/>)))
|
onChildren={setChildren}/>)))
|
||||||
@@ -270,17 +464,23 @@ const MaterialSidebar: FC = () => {
|
|||||||
return (
|
return (
|
||||||
<>
|
<>
|
||||||
<div className="border-b bg-stone-50 p-3 dark:border-stone-700 dark:bg-stone-950
|
<div className="border-b bg-stone-50 p-3 dark:border-stone-700 dark:bg-stone-950
|
||||||
dark:text-stone-100 md:hidden">
|
dark:text-stone-100 md:hidden flex h-[25dvh] min-h-0 flex-col
|
||||||
|
overflow-hidden">
|
||||||
<MaterialFilterButtons
|
<MaterialFilterButtons
|
||||||
materialFilter={materialFilter}
|
materialFilter={materialFilter}
|
||||||
onChange={handleFilterChange}/>
|
onChange={handleFilterChange}/>
|
||||||
<div ref={mobileRailRef} className="mt-3 overflow-x-auto">
|
<div
|
||||||
<div className="flex min-w-max flex-row-reverse gap-3 pb-1">
|
ref={mobileRailRef}
|
||||||
|
className="mt-3 min-h-0 flex-1 overflow-x-auto overflow-y-hidden">
|
||||||
|
<div className="flex min-w-max flex-row-reverse items-start gap-3 pb-1 h-full
|
||||||
|
min-h-0 max-h-full">
|
||||||
{visibleRootTags.map (tag => (
|
{visibleRootTags.map (tag => (
|
||||||
<MobileMaterialTreeNode
|
<MobileMaterialTreeNode
|
||||||
key={tag.id}
|
key={tag.id}
|
||||||
tag={tag}
|
tag={tag}
|
||||||
|
availableInlineSizePx={mobileAvailableInlineSizePx}
|
||||||
materialFilter={materialFilter}
|
materialFilter={materialFilter}
|
||||||
|
selectedTagId={selectedTagId}
|
||||||
openTags={openTags}
|
openTags={openTags}
|
||||||
setOpenTags={setOpenTags}
|
setOpenTags={setOpenTags}
|
||||||
onChildren={setChildren}/>))}
|
onChildren={setChildren}/>))}
|
||||||
@@ -288,25 +488,23 @@ const MaterialSidebar: FC = () => {
|
|||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
<div className="hidden md:block">
|
<SidebarComponent sidebarKey="materials" className="hidden md:block">
|
||||||
<SidebarComponent>
|
<div className="space-y-4">
|
||||||
<div className="space-y-4">
|
<MaterialFilterButtons
|
||||||
<MaterialFilterButtons
|
materialFilter={materialFilter}
|
||||||
materialFilter={materialFilter}
|
onChange={handleFilterChange}/>
|
||||||
onChange={handleFilterChange}/>
|
{isLoading && (
|
||||||
{isLoading && (
|
<p className="text-sm text-neutral-500 dark:text-stone-400">読込中……</p>)}
|
||||||
<p className="text-sm text-neutral-500 dark:text-stone-400">読込中……</p>)}
|
{isError && (
|
||||||
{isError && (
|
<p className="text-sm text-red-600 dark:text-red-300">
|
||||||
<p className="text-sm text-red-600 dark:text-red-300">
|
タグ一覧の取得に失敗しました.
|
||||||
タグ一覧の取得に失敗しました.
|
</p>)}
|
||||||
</p>)}
|
{(!isLoading && !isError) && (
|
||||||
{(!isLoading && !isError) && (
|
<ul>
|
||||||
<ul>
|
{renderDesktopTree (visibleRootTags)}
|
||||||
{renderDesktopTree (visibleRootTags)}
|
</ul>)}
|
||||||
</ul>)}
|
</div>
|
||||||
</div>
|
</SidebarComponent>
|
||||||
</SidebarComponent>
|
|
||||||
</div>
|
|
||||||
</>)
|
</>)
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@@ -66,4 +66,27 @@ describe ('PostEditForm', () => {
|
|||||||
expect (onSave).toHaveBeenCalledWith (expect.objectContaining ({ versionNo: 5 }))
|
expect (onSave).toHaveBeenCalledWith (expect.objectContaining ({ versionNo: 5 }))
|
||||||
expect (toastApi.toast).toHaveBeenCalledWith ({ description: '更新しました.' })
|
expect (toastApi.toast).toHaveBeenCalledWith ({ description: '更新しました.' })
|
||||||
})
|
})
|
||||||
|
|
||||||
|
it ('preserves duration while the video tag is temporarily removed', () => {
|
||||||
|
const post = buildPost ({
|
||||||
|
videoMs: 180_500,
|
||||||
|
tags: [
|
||||||
|
buildTag ({ id: 1, name: '動画', category: 'general' }),
|
||||||
|
buildTag ({ id: 2, name: 'general-tag', category: 'general' }),
|
||||||
|
],
|
||||||
|
})
|
||||||
|
|
||||||
|
render (<PostEditForm post={post} onSave={vi.fn ()}/>)
|
||||||
|
|
||||||
|
expect (screen.getByRole ('spinbutton')).toHaveValue (180.5)
|
||||||
|
|
||||||
|
const tags = screen.getAllByRole ('textbox')[2]
|
||||||
|
fireEvent.change (tags, { target: { value: 'general-tag' } })
|
||||||
|
expect (screen.queryByRole ('spinbutton')).not.toBeInTheDocument ()
|
||||||
|
|
||||||
|
fireEvent.change (tags, {
|
||||||
|
target: { value: '動画 general-tag' },
|
||||||
|
})
|
||||||
|
expect (screen.getByRole ('spinbutton')).toHaveValue (180.5)
|
||||||
|
})
|
||||||
})
|
})
|
||||||
|
|||||||
@@ -1,4 +1,4 @@
|
|||||||
import { useEffect, useState } from 'react'
|
import { useEffect, useMemo, useState } from 'react'
|
||||||
|
|
||||||
import PostFormTagsArea from '@/components/PostFormTagsArea'
|
import PostFormTagsArea from '@/components/PostFormTagsArea'
|
||||||
import PostOriginalCreatedTimeField from '@/components/PostOriginalCreatedTimeField'
|
import PostOriginalCreatedTimeField from '@/components/PostOriginalCreatedTimeField'
|
||||||
@@ -9,29 +9,35 @@ import { Button } from '@/components/ui/button'
|
|||||||
import { toast } from '@/components/ui/use-toast'
|
import { toast } from '@/components/ui/use-toast'
|
||||||
import { isApiError } from '@/lib/api'
|
import { isApiError } from '@/lib/api'
|
||||||
import { updatePost } from '@/lib/posts'
|
import { updatePost } from '@/lib/posts'
|
||||||
import { inputClass } from '@/lib/utils'
|
import { inputClass, msToTime } from '@/lib/utils'
|
||||||
import { useValidationErrors } from '@/lib/useValidationErrors'
|
import { useValidationErrors } from '@/lib/useValidationErrors'
|
||||||
|
|
||||||
import type { FC, FormEvent } from 'react'
|
import type { FC, FormEvent } from 'react'
|
||||||
|
|
||||||
import type { Post, Tag } from '@/types'
|
import type { Post, TagWithSections } from '@/types'
|
||||||
|
|
||||||
type PostFormField =
|
type PostFormField =
|
||||||
'parentPostIds' | 'tags' | 'originalCreatedAt'
|
'parentPostIds' | 'tags' | 'videoMs' | 'originalCreatedAt'
|
||||||
|
|
||||||
|
const videoMsToDurationValue = (videoMs: number | null): string =>
|
||||||
|
videoMs == null ? '' : String (videoMs / 1_000)
|
||||||
|
|
||||||
|
|
||||||
const tagsToStr = (tags: Tag[]): string => {
|
const tagsToStr = (tags: TagWithSections[]): string => {
|
||||||
const result: Tag[] = []
|
const result: Omit<TagWithSections, 'children'>[] = []
|
||||||
|
|
||||||
const walk = (tag: Tag) => {
|
const walk = (tag: TagWithSections) => {
|
||||||
const { children, ...rest } = tag
|
const { children, ...rest } = tag
|
||||||
result.push (rest)
|
result.push (rest)
|
||||||
children?.forEach (walk)
|
children.forEach (walk)
|
||||||
}
|
}
|
||||||
|
|
||||||
tags.filter (t => t.category !== 'nico').forEach (walk)
|
tags.filter (t => t.category !== 'nico').forEach (walk)
|
||||||
|
|
||||||
return [...(new Set (result.map (t => t.name)))].join (' ')
|
return [...(new Set (result.map (t =>
|
||||||
|
`${ t.name }${ t.sections
|
||||||
|
.map (s => `[${ msToTime (s.beginMs) }-${ s.endMs == null ? '' : msToTime (s.endMs) }]`)
|
||||||
|
.join ('') }`)))].join (' ')
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
||||||
@@ -41,6 +47,7 @@ type Props = { post: Post
|
|||||||
|
|
||||||
const PostEditForm: FC<Props> = ({ post, onSave }) => {
|
const PostEditForm: FC<Props> = ({ post, onSave }) => {
|
||||||
const [disabled, setDisabled] = useState (false)
|
const [disabled, setDisabled] = useState (false)
|
||||||
|
const [duration, setDuration] = useState<string> (videoMsToDurationValue (post.videoMs))
|
||||||
const { baseErrors, fieldErrors, clearValidationErrors, applyValidationError } =
|
const { baseErrors, fieldErrors, clearValidationErrors, applyValidationError } =
|
||||||
useValidationErrors<PostFormField> ()
|
useValidationErrors<PostFormField> ()
|
||||||
const [originalCreatedBefore, setOriginalCreatedBefore] =
|
const [originalCreatedBefore, setOriginalCreatedBefore] =
|
||||||
@@ -52,6 +59,10 @@ const PostEditForm: FC<Props> = ({ post, onSave }) => {
|
|||||||
const [tags, setTags] = useState<string> ('')
|
const [tags, setTags] = useState<string> ('')
|
||||||
const [title, setTitle] = useState (post.title)
|
const [title, setTitle] = useState (post.title)
|
||||||
|
|
||||||
|
const videoFlg =
|
||||||
|
useMemo (() => tags.split (/\s+/).some (tag => tag.replace (/\[.*\]$/, '') === '動画'),
|
||||||
|
[tags])
|
||||||
|
|
||||||
const dialogue = useDialogue ()
|
const dialogue = useDialogue ()
|
||||||
|
|
||||||
const update = async (...args: Parameters<typeof updatePost>) => {
|
const update = async (...args: Parameters<typeof updatePost>) => {
|
||||||
@@ -63,6 +74,7 @@ const PostEditForm: FC<Props> = ({ post, onSave }) => {
|
|||||||
onSave ({ ...post,
|
onSave ({ ...post,
|
||||||
versionNo: data.versionNo,
|
versionNo: data.versionNo,
|
||||||
title: data.title,
|
title: data.title,
|
||||||
|
videoMs: data.videoMs,
|
||||||
tags: data.tags,
|
tags: data.tags,
|
||||||
parentPosts: data.parentPosts,
|
parentPosts: data.parentPosts,
|
||||||
childPosts: data.childPosts,
|
childPosts: data.childPosts,
|
||||||
@@ -102,6 +114,7 @@ const PostEditForm: FC<Props> = ({ post, onSave }) => {
|
|||||||
{
|
{
|
||||||
// TODO: 差分 UI
|
// TODO: 差分 UI
|
||||||
await update ({ id: post.id, title, tags, parentPostIds,
|
await update ({ id: post.id, title, tags, parentPostIds,
|
||||||
|
duration: videoFlg ? duration : null,
|
||||||
originalCreatedFrom, originalCreatedBefore },
|
originalCreatedFrom, originalCreatedBefore },
|
||||||
{ baseVersionNo: post.versionNo, merge: true })
|
{ baseVersionNo: post.versionNo, merge: true })
|
||||||
return
|
return
|
||||||
@@ -110,6 +123,7 @@ const PostEditForm: FC<Props> = ({ post, onSave }) => {
|
|||||||
if (action === 'overwrite')
|
if (action === 'overwrite')
|
||||||
{
|
{
|
||||||
await update ({ id: post.id, title, tags, parentPostIds,
|
await update ({ id: post.id, title, tags, parentPostIds,
|
||||||
|
duration: videoFlg ? duration : null,
|
||||||
originalCreatedFrom, originalCreatedBefore },
|
originalCreatedFrom, originalCreatedBefore },
|
||||||
{ baseVersionNo: post.versionNo, force: true })
|
{ baseVersionNo: post.versionNo, force: true })
|
||||||
return
|
return
|
||||||
@@ -124,6 +138,7 @@ const PostEditForm: FC<Props> = ({ post, onSave }) => {
|
|||||||
try
|
try
|
||||||
{
|
{
|
||||||
await update ({ id: post.id, title, tags, parentPostIds,
|
await update ({ id: post.id, title, tags, parentPostIds,
|
||||||
|
duration: videoFlg ? duration : null,
|
||||||
originalCreatedFrom, originalCreatedBefore },
|
originalCreatedFrom, originalCreatedBefore },
|
||||||
{ baseVersionNo: post.versionNo })
|
{ baseVersionNo: post.versionNo })
|
||||||
}
|
}
|
||||||
@@ -134,7 +149,8 @@ const PostEditForm: FC<Props> = ({ post, onSave }) => {
|
|||||||
}
|
}
|
||||||
|
|
||||||
useEffect (() => {
|
useEffect (() => {
|
||||||
setTags(tagsToStr (post.tags))
|
setTags (tagsToStr (post.tags))
|
||||||
|
setDuration (videoMsToDurationValue (post.videoMs))
|
||||||
}, [post])
|
}, [post])
|
||||||
|
|
||||||
return (
|
return (
|
||||||
@@ -149,7 +165,7 @@ const PostEditForm: FC<Props> = ({ post, onSave }) => {
|
|||||||
disabled={disabled}
|
disabled={disabled}
|
||||||
className={inputClass (invalid)}
|
className={inputClass (invalid)}
|
||||||
value={title ?? ''}
|
value={title ?? ''}
|
||||||
onChange={ev => setTitle (ev.target.value)}/>)}
|
onChange={e => setTitle (e.target.value)}/>)}
|
||||||
</FormField>
|
</FormField>
|
||||||
|
|
||||||
{/* 親投稿 */}
|
{/* 親投稿 */}
|
||||||
@@ -181,6 +197,20 @@ const PostEditForm: FC<Props> = ({ post, onSave }) => {
|
|||||||
setOriginalCreatedBefore={setOriginalCreatedBefore}
|
setOriginalCreatedBefore={setOriginalCreatedBefore}
|
||||||
errors={fieldErrors.originalCreatedAt}/>
|
errors={fieldErrors.originalCreatedAt}/>
|
||||||
|
|
||||||
|
{/* 動画時間 */}
|
||||||
|
{videoFlg && (
|
||||||
|
<FormField label="動画時間" messages={fieldErrors.videoMs}>
|
||||||
|
{({ invalid }) => (
|
||||||
|
<input
|
||||||
|
type="number"
|
||||||
|
min="0.001"
|
||||||
|
step="0.001"
|
||||||
|
disabled={disabled}
|
||||||
|
className={inputClass (invalid)}
|
||||||
|
value={duration}
|
||||||
|
onChange={e => setDuration (e.target.value)}/>)}
|
||||||
|
</FormField>)}
|
||||||
|
|
||||||
{/* 送信 */}
|
{/* 送信 */}
|
||||||
<Button type="submit" disabled={disabled}>
|
<Button type="submit" disabled={disabled}>
|
||||||
更新
|
更新
|
||||||
@@ -188,4 +218,5 @@ const PostEditForm: FC<Props> = ({ post, onSave }) => {
|
|||||||
</form>)
|
</form>)
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
||||||
export default PostEditForm
|
export default PostEditForm
|
||||||
|
|||||||
@@ -0,0 +1,250 @@
|
|||||||
|
import { cn } from '@/lib/utils'
|
||||||
|
import { useEffect, useRef, useState } from 'react'
|
||||||
|
|
||||||
|
import type { FC } from 'react'
|
||||||
|
|
||||||
|
type Props = {
|
||||||
|
text: string
|
||||||
|
className?: string
|
||||||
|
truncateOnMobile?: boolean
|
||||||
|
title?: string }
|
||||||
|
|
||||||
|
const DESKTOP_MARQUEE_MEDIA =
|
||||||
|
'(min-width: 768px) and (hover: hover) and (pointer: fine) and (prefers-reduced-motion: no-preference)'
|
||||||
|
const MARQUEE_START_DELAY_MS = 1600
|
||||||
|
const MARQUEE_END_HOLD_MS = 2400
|
||||||
|
const MARQUEE_SCROLL_PX_PER_SECOND = 43
|
||||||
|
const MIN_MARQUEE_OVERFLOW_PX = 1
|
||||||
|
|
||||||
|
|
||||||
|
const ResponsiveMarqueeText: FC<Props> = (
|
||||||
|
{ text, className, truncateOnMobile = false, title },
|
||||||
|
) => {
|
||||||
|
const outerRef = useRef<HTMLSpanElement | null> (null)
|
||||||
|
const staticRef = useRef<HTMLSpanElement | null> (null)
|
||||||
|
const animatedRef = useRef<HTMLSpanElement | null> (null)
|
||||||
|
const animationRef = useRef<Animation | null> (null)
|
||||||
|
const timeoutRef = useRef<number | null> (null)
|
||||||
|
const rafRef = useRef<number | null> (null)
|
||||||
|
const [overflowPx, setOverflowPx] = useState (0)
|
||||||
|
const [desktopMarqueeEnabled, setDesktopMarqueeEnabled] = useState (false)
|
||||||
|
const [active, setActive] = useState (false)
|
||||||
|
const [marqueeVisible, setMarqueeVisible] = useState (false)
|
||||||
|
|
||||||
|
useEffect (() => {
|
||||||
|
const outer = outerRef.current
|
||||||
|
const inner = staticRef.current
|
||||||
|
|
||||||
|
if (!(outer) || !(inner))
|
||||||
|
return
|
||||||
|
|
||||||
|
const measure = () => {
|
||||||
|
const nextOverflow = Math.max (0, Math.ceil (inner.scrollWidth - outer.clientWidth))
|
||||||
|
setOverflowPx (prev => Math.abs (prev - nextOverflow) <= 1 ? prev : nextOverflow)
|
||||||
|
}
|
||||||
|
|
||||||
|
measure ()
|
||||||
|
|
||||||
|
const resizeObserver =
|
||||||
|
typeof ResizeObserver === 'undefined'
|
||||||
|
? null
|
||||||
|
: new ResizeObserver (() => {
|
||||||
|
measure ()
|
||||||
|
})
|
||||||
|
|
||||||
|
resizeObserver?.observe (outer)
|
||||||
|
resizeObserver?.observe (inner)
|
||||||
|
addEventListener ('resize', measure)
|
||||||
|
|
||||||
|
return () => {
|
||||||
|
resizeObserver?.disconnect ()
|
||||||
|
removeEventListener ('resize', measure)
|
||||||
|
}
|
||||||
|
}, [text])
|
||||||
|
|
||||||
|
useEffect (() => {
|
||||||
|
if (typeof window === 'undefined' || typeof window.matchMedia !== 'function')
|
||||||
|
return
|
||||||
|
|
||||||
|
const media = window.matchMedia (DESKTOP_MARQUEE_MEDIA)
|
||||||
|
const update = () => {
|
||||||
|
setDesktopMarqueeEnabled (media.matches)
|
||||||
|
}
|
||||||
|
|
||||||
|
update ()
|
||||||
|
media.addEventListener ('change', update)
|
||||||
|
|
||||||
|
return () => {
|
||||||
|
media.removeEventListener ('change', update)
|
||||||
|
}
|
||||||
|
}, [])
|
||||||
|
|
||||||
|
useEffect (() => {
|
||||||
|
const clearScheduled = () => {
|
||||||
|
if (timeoutRef.current != null)
|
||||||
|
{
|
||||||
|
clearTimeout (timeoutRef.current)
|
||||||
|
timeoutRef.current = null
|
||||||
|
}
|
||||||
|
if (rafRef.current != null)
|
||||||
|
{
|
||||||
|
cancelAnimationFrame (rafRef.current)
|
||||||
|
rafRef.current = null
|
||||||
|
}
|
||||||
|
animationRef.current?.cancel ()
|
||||||
|
animationRef.current = null
|
||||||
|
}
|
||||||
|
|
||||||
|
const animated = animatedRef.current
|
||||||
|
const canMarquee = (
|
||||||
|
active
|
||||||
|
&& desktopMarqueeEnabled
|
||||||
|
&& overflowPx >= MIN_MARQUEE_OVERFLOW_PX
|
||||||
|
&& animated != null)
|
||||||
|
|
||||||
|
const resetAnimated = () => {
|
||||||
|
const node = animatedRef.current
|
||||||
|
|
||||||
|
animationRef.current?.cancel ()
|
||||||
|
animationRef.current = null
|
||||||
|
node?.getAnimations?.().forEach (animation => {
|
||||||
|
animation.cancel ()
|
||||||
|
})
|
||||||
|
|
||||||
|
if (!(node))
|
||||||
|
return
|
||||||
|
|
||||||
|
node.style.transition = 'none'
|
||||||
|
node.style.transform = 'translateX(0)'
|
||||||
|
}
|
||||||
|
|
||||||
|
if (!canMarquee)
|
||||||
|
{
|
||||||
|
clearScheduled ()
|
||||||
|
resetAnimated ()
|
||||||
|
setMarqueeVisible (false)
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
let cancelled = false
|
||||||
|
|
||||||
|
const sleep = (ms: number) =>
|
||||||
|
new Promise<void> (resolve => {
|
||||||
|
timeoutRef.current = window.setTimeout (() => {
|
||||||
|
timeoutRef.current = null
|
||||||
|
resolve ()
|
||||||
|
}, ms)
|
||||||
|
})
|
||||||
|
|
||||||
|
const runLoop = async () => {
|
||||||
|
while (!cancelled)
|
||||||
|
{
|
||||||
|
resetAnimated ()
|
||||||
|
setMarqueeVisible (true)
|
||||||
|
|
||||||
|
await sleep (MARQUEE_START_DELAY_MS)
|
||||||
|
if (cancelled || !(animatedRef.current))
|
||||||
|
break
|
||||||
|
|
||||||
|
const moveDurationMs =
|
||||||
|
overflowPx / MARQUEE_SCROLL_PX_PER_SECOND * 1000
|
||||||
|
const node = animatedRef.current
|
||||||
|
|
||||||
|
if (typeof node.animate === 'function')
|
||||||
|
{
|
||||||
|
const animation = node.animate (
|
||||||
|
[
|
||||||
|
{ transform: 'translateX(0)' },
|
||||||
|
{ transform: `translateX(-${ overflowPx }px)` },
|
||||||
|
],
|
||||||
|
{ duration: moveDurationMs, easing: 'linear', fill: 'forwards' })
|
||||||
|
animationRef.current = animation
|
||||||
|
try
|
||||||
|
{
|
||||||
|
await animation.finished
|
||||||
|
}
|
||||||
|
catch
|
||||||
|
{
|
||||||
|
break
|
||||||
|
}
|
||||||
|
|
||||||
|
node.style.transform = `translateX(-${ overflowPx }px)`
|
||||||
|
animation.cancel ()
|
||||||
|
if (animationRef.current === animation)
|
||||||
|
animationRef.current = null
|
||||||
|
}
|
||||||
|
else
|
||||||
|
{
|
||||||
|
node.style.transition = `transform ${ moveDurationMs }ms linear`
|
||||||
|
await new Promise<void> (resolve => {
|
||||||
|
rafRef.current = requestAnimationFrame (() => {
|
||||||
|
rafRef.current = null
|
||||||
|
node.style.transform = `translateX(-${ overflowPx }px)`
|
||||||
|
resolve ()
|
||||||
|
})
|
||||||
|
})
|
||||||
|
await sleep (moveDurationMs)
|
||||||
|
node.style.transition = 'none'
|
||||||
|
node.style.transform = `translateX(-${ overflowPx }px)`
|
||||||
|
}
|
||||||
|
|
||||||
|
if (cancelled)
|
||||||
|
break
|
||||||
|
|
||||||
|
await sleep (MARQUEE_END_HOLD_MS)
|
||||||
|
if (cancelled)
|
||||||
|
break
|
||||||
|
|
||||||
|
resetAnimated ()
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
void runLoop ()
|
||||||
|
|
||||||
|
return () => {
|
||||||
|
cancelled = true
|
||||||
|
clearScheduled ()
|
||||||
|
resetAnimated ()
|
||||||
|
setMarqueeVisible (false)
|
||||||
|
}
|
||||||
|
}, [active, desktopMarqueeEnabled, overflowPx, text])
|
||||||
|
|
||||||
|
return (
|
||||||
|
<span
|
||||||
|
ref={outerRef}
|
||||||
|
title={title ?? text}
|
||||||
|
onMouseEnter={() => setActive (true)}
|
||||||
|
onMouseLeave={() => setActive (false)}
|
||||||
|
onFocus={() => setActive (true)}
|
||||||
|
onBlur={() => setActive (false)}
|
||||||
|
className={cn (
|
||||||
|
'tag-marquee inline-block max-w-full min-w-0 align-bottom',
|
||||||
|
(truncateOnMobile
|
||||||
|
? 'overflow-hidden text-ellipsis whitespace-nowrap'
|
||||||
|
: 'whitespace-normal [overflow-wrap:anywhere]'),
|
||||||
|
'md:overflow-hidden md:whitespace-nowrap',
|
||||||
|
className)}>
|
||||||
|
<span
|
||||||
|
ref={staticRef}
|
||||||
|
className={cn (
|
||||||
|
'tag-marquee__static block max-w-full',
|
||||||
|
(truncateOnMobile
|
||||||
|
? 'overflow-hidden text-ellipsis whitespace-nowrap'
|
||||||
|
: 'whitespace-normal [overflow-wrap:anywhere]'),
|
||||||
|
'md:overflow-hidden md:text-ellipsis md:whitespace-nowrap',
|
||||||
|
marqueeVisible && 'md:opacity-0')}>
|
||||||
|
{text}
|
||||||
|
</span>
|
||||||
|
{overflowPx >= MIN_MARQUEE_OVERFLOW_PX && (
|
||||||
|
<span
|
||||||
|
ref={animatedRef}
|
||||||
|
aria-hidden="true"
|
||||||
|
className={cn (
|
||||||
|
'tag-marquee__animated hidden md:block',
|
||||||
|
marqueeVisible ? 'md:opacity-100' : 'md:opacity-0')}>
|
||||||
|
{text}
|
||||||
|
</span>)}
|
||||||
|
</span>)
|
||||||
|
}
|
||||||
|
|
||||||
|
export default ResponsiveMarqueeText
|
||||||
@@ -26,13 +26,13 @@ import { dateString, originalCreatedAtString } from '@/lib/utils'
|
|||||||
import type { DragEndEvent } from '@dnd-kit/core'
|
import type { DragEndEvent } from '@dnd-kit/core'
|
||||||
import type { FC, MutableRefObject, ReactNode } from 'react'
|
import type { FC, MutableRefObject, ReactNode } from 'react'
|
||||||
|
|
||||||
import type { Category, Post, Tag } from '@/types'
|
import type { Category, Post, TagWithSections } from '@/types'
|
||||||
|
|
||||||
type TagByCategory = { [key in Category]: Tag[] }
|
type TagByCategory = { [key in Category]: TagWithSections[] }
|
||||||
|
|
||||||
|
|
||||||
const renderTagTree = (
|
const renderTagTree = (
|
||||||
tag: Tag,
|
tag: TagWithSections,
|
||||||
nestLevel: number,
|
nestLevel: number,
|
||||||
path: string,
|
path: string,
|
||||||
suppressClickRef: MutableRefObject<boolean>,
|
suppressClickRef: MutableRefObject<boolean>,
|
||||||
@@ -62,8 +62,9 @@ const renderTagTree = (
|
|||||||
|
|
||||||
|
|
||||||
const isDescendant = (
|
const isDescendant = (
|
||||||
root: Tag,
|
root: TagWithSections,
|
||||||
targetId: number): boolean => {
|
targetId: number,
|
||||||
|
): boolean => {
|
||||||
if (!(root.children))
|
if (!(root.children))
|
||||||
return false
|
return false
|
||||||
|
|
||||||
@@ -81,8 +82,9 @@ const isDescendant = (
|
|||||||
|
|
||||||
const findTag = (
|
const findTag = (
|
||||||
byCat: TagByCategory,
|
byCat: TagByCategory,
|
||||||
id: number): Tag | undefined => {
|
id: number,
|
||||||
const walk = (nodes: Tag[]): Tag | undefined => {
|
): TagWithSections | undefined => {
|
||||||
|
const walk = (nodes: TagWithSections[]): TagWithSections | undefined => {
|
||||||
for (const t of nodes)
|
for (const t of nodes)
|
||||||
{
|
{
|
||||||
if (t.id === id)
|
if (t.id === id)
|
||||||
@@ -144,10 +146,13 @@ const DropSlot = ({ cat }: { cat: Category }) => {
|
|||||||
}
|
}
|
||||||
|
|
||||||
|
|
||||||
type Props = { post: Post; sp?: boolean }
|
type Props = {
|
||||||
|
className?: string
|
||||||
|
post: Post
|
||||||
|
sp?: boolean }
|
||||||
|
|
||||||
|
|
||||||
const TagDetailSidebar: FC<Props> = ({ post, sp }) => {
|
const TagDetailSidebar: FC<Props> = ({ className, post, sp }) => {
|
||||||
sp = Boolean (sp)
|
sp = Boolean (sp)
|
||||||
|
|
||||||
const qc = useQueryClient ()
|
const qc = useQueryClient ()
|
||||||
@@ -163,7 +168,7 @@ const TagDetailSidebar: FC<Props> = ({ post, sp }) => {
|
|||||||
}
|
}
|
||||||
|
|
||||||
for (const cat of Object.keys (tagsTmp) as (keyof typeof tagsTmp)[])
|
for (const cat of Object.keys (tagsTmp) as (keyof typeof tagsTmp)[])
|
||||||
tagsTmp[cat].sort ((tagA: Tag, tagB: Tag) => tagA.name < tagB.name ? -1 : 1)
|
tagsTmp[cat].sort ((tagA: TagWithSections, tagB: TagWithSections) => tagA.name < tagB.name ? -1 : 1)
|
||||||
|
|
||||||
return tagsTmp
|
return tagsTmp
|
||||||
}, [post])
|
}, [post])
|
||||||
@@ -276,7 +281,7 @@ const TagDetailSidebar: FC<Props> = ({ post, sp }) => {
|
|||||||
}, [baseTags])
|
}, [baseTags])
|
||||||
|
|
||||||
return (
|
return (
|
||||||
<SidebarComponent>
|
<SidebarComponent sidebarKey="post-detail-tags" className={className}>
|
||||||
<TagSearch/>
|
<TagSearch/>
|
||||||
<DndContext
|
<DndContext
|
||||||
sensors={sensors}
|
sensors={sensors}
|
||||||
@@ -373,4 +378,4 @@ const TagDetailSidebar: FC<Props> = ({ post, sp }) => {
|
|||||||
</SidebarComponent>)
|
</SidebarComponent>)
|
||||||
}
|
}
|
||||||
|
|
||||||
export default TagDetailSidebar
|
export default TagDetailSidebar
|
||||||
|
|||||||
@@ -1,4 +1,5 @@
|
|||||||
import PrefetchLink from '@/components/PrefetchLink'
|
import PrefetchLink from '@/components/PrefetchLink'
|
||||||
|
import ResponsiveMarqueeText from '@/components/ResponsiveMarqueeText'
|
||||||
import { LIGHT_COLOUR_SHADE, DARK_COLOUR_SHADE, TAG_COLOUR } from '@/consts'
|
import { LIGHT_COLOUR_SHADE, DARK_COLOUR_SHADE, TAG_COLOUR } from '@/consts'
|
||||||
import { cn } from '@/lib/utils'
|
import { cn } from '@/lib/utils'
|
||||||
|
|
||||||
@@ -9,6 +10,7 @@ import type { Tag } from '@/types'
|
|||||||
type CommonProps = {
|
type CommonProps = {
|
||||||
tag: Tag
|
tag: Tag
|
||||||
nestLevel?: number
|
nestLevel?: number
|
||||||
|
truncateOnMobile?: boolean
|
||||||
withWiki?: boolean
|
withWiki?: boolean
|
||||||
withCount?: boolean }
|
withCount?: boolean }
|
||||||
|
|
||||||
@@ -28,11 +30,14 @@ type Props =
|
|||||||
|
|
||||||
|
|
||||||
const TagLink: FC<Props> = ({ tag,
|
const TagLink: FC<Props> = ({ tag,
|
||||||
nestLevel = 0,
|
nestLevel = 0,
|
||||||
linkFlg = true,
|
linkFlg = true,
|
||||||
withWiki = true,
|
truncateOnMobile = false,
|
||||||
withCount = true,
|
withWiki = true,
|
||||||
...props }) => {
|
withCount = true,
|
||||||
|
className,
|
||||||
|
title,
|
||||||
|
...props }) => {
|
||||||
const spanClass = cn (
|
const spanClass = cn (
|
||||||
`text-${ TAG_COLOUR[tag.category] }-${ LIGHT_COLOUR_SHADE }`,
|
`text-${ TAG_COLOUR[tag.category] }-${ LIGHT_COLOUR_SHADE }`,
|
||||||
`dark:text-${ TAG_COLOUR[tag.category] }-${ DARK_COLOUR_SHADE }`)
|
`dark:text-${ TAG_COLOUR[tag.category] }-${ DARK_COLOUR_SHADE }`)
|
||||||
@@ -40,11 +45,18 @@ const TagLink: FC<Props> = ({ tag,
|
|||||||
spanClass,
|
spanClass,
|
||||||
`hover:text-${ TAG_COLOUR[tag.category] }-${ LIGHT_COLOUR_SHADE - 200 }`,
|
`hover:text-${ TAG_COLOUR[tag.category] }-${ LIGHT_COLOUR_SHADE - 200 }`,
|
||||||
`dark:hover:text-${ TAG_COLOUR[tag.category] }-${ DARK_COLOUR_SHADE - 200 }`)
|
`dark:hover:text-${ TAG_COLOUR[tag.category] }-${ DARK_COLOUR_SHADE - 200 }`)
|
||||||
|
const textClass = 'group min-w-0 max-w-full overflow-hidden align-bottom'
|
||||||
|
const rootClass =
|
||||||
|
'inline-flex min-w-0 max-w-full flex-nowrap items-stretch align-baseline gap-x-1 md:items-baseline'
|
||||||
|
const markerWrapClass = 'shrink-0 self-start md:self-auto'
|
||||||
|
const countClass = 'shrink-0 self-end md:self-auto'
|
||||||
|
const textTitle = title
|
||||||
|
?? (tag.matchedAlias == null ? tag.name : `${ tag.matchedAlias } → ${ tag.name }`)
|
||||||
|
|
||||||
return (
|
return (
|
||||||
<>
|
<span className={rootClass}>
|
||||||
{(linkFlg && withWiki) && (
|
{(linkFlg && withWiki) && (
|
||||||
<span className="mr-1">
|
<span className={markerWrapClass}>
|
||||||
{(tag.materialId != null || tag.hasWiki || tag.hasDeerjikists)
|
{(tag.materialId != null || tag.hasWiki || tag.hasDeerjikists)
|
||||||
? (
|
? (
|
||||||
tag.materialId == null && !(tag.hasDeerjikists)
|
tag.materialId == null && !(tag.hasDeerjikists)
|
||||||
@@ -99,33 +111,48 @@ const TagLink: FC<Props> = ({ tag,
|
|||||||
</span>)}
|
</span>)}
|
||||||
{nestLevel > 0 && (
|
{nestLevel > 0 && (
|
||||||
<span
|
<span
|
||||||
className="ml-1 mr-1"
|
className="ml-1 mr-1 shrink-0"
|
||||||
style={{ paddingLeft: `${ (nestLevel - 1) }rem` }}>
|
style={{ paddingLeft: `${ (nestLevel - 1) }rem` }}>
|
||||||
↳
|
↳
|
||||||
</span>)}
|
</span>)}
|
||||||
{tag.matchedAlias != null && (
|
{tag.matchedAlias != null && (
|
||||||
<>
|
<>
|
||||||
<span className={spanClass} {...props}>
|
<span
|
||||||
{tag.matchedAlias}
|
title={textTitle}
|
||||||
|
className={cn (spanClass, textClass, className)}
|
||||||
|
{...props}>
|
||||||
|
<ResponsiveMarqueeText
|
||||||
|
text={tag.matchedAlias}
|
||||||
|
title={textTitle}
|
||||||
|
truncateOnMobile={truncateOnMobile}/>
|
||||||
</span>
|
</span>
|
||||||
<> → </>
|
<span className="shrink-0"> → </span>
|
||||||
</>)}
|
</>)}
|
||||||
{linkFlg
|
{linkFlg
|
||||||
? (
|
? (
|
||||||
<PrefetchLink
|
<PrefetchLink
|
||||||
to={`/posts?${ (new URLSearchParams ({ tags: tag.name })).toString () }`}
|
to={`/posts?${ (new URLSearchParams ({ tags: tag.name })).toString () }`}
|
||||||
className={linkClass}
|
title={textTitle}
|
||||||
|
className={cn (linkClass, textClass, className)}
|
||||||
{...props}>
|
{...props}>
|
||||||
{tag.name}
|
<ResponsiveMarqueeText
|
||||||
|
text={tag.name}
|
||||||
|
title={textTitle}
|
||||||
|
truncateOnMobile={truncateOnMobile}/>
|
||||||
</PrefetchLink>)
|
</PrefetchLink>)
|
||||||
: (
|
: (
|
||||||
<span className={spanClass}
|
<span
|
||||||
|
title={textTitle}
|
||||||
|
className={cn (spanClass, textClass, className)}
|
||||||
{...props}>
|
{...props}>
|
||||||
{tag.name}
|
<ResponsiveMarqueeText
|
||||||
|
text={tag.name}
|
||||||
|
title={textTitle}
|
||||||
|
truncateOnMobile={truncateOnMobile}/>
|
||||||
</span>)}
|
</span>)}
|
||||||
{withCount && (
|
{withCount && (
|
||||||
<span className="ml-1">{tag.postCount}</span>)}
|
<span className={countClass}>{tag.postCount}</span>)}
|
||||||
</>)
|
</span>)
|
||||||
}
|
}
|
||||||
|
|
||||||
export default TagLink
|
export default TagLink
|
||||||
|
|||||||
@@ -20,12 +20,14 @@ const TagSearchBox: FC<Props> = ({ suggestions, activeIndex, onSelect }) => {
|
|||||||
rounded shadow">
|
rounded shadow">
|
||||||
{suggestions.map ((tag, i) => (
|
{suggestions.map ((tag, i) => (
|
||||||
<li key={tag.id}
|
<li key={tag.id}
|
||||||
className={cn ('px-3 py-2 cursor-pointer hover:bg-gray-300 dark:hover:bg-gray-700',
|
className={cn ('min-w-0 overflow-hidden px-3 py-2 cursor-pointer hover:bg-gray-300 dark:hover:bg-gray-700',
|
||||||
i === activeIndex && 'bg-gray-300 dark:bg-gray-700')}
|
i === activeIndex && 'bg-gray-300 dark:bg-gray-700')}
|
||||||
onMouseDown={() => onSelect (tag)}>
|
onMouseDown={() => onSelect (tag)}>
|
||||||
<TagLink tag={tag} linkFlg={false} withWiki={false}/>
|
<div className="flex min-w-0 max-w-full items-baseline overflow-hidden">
|
||||||
|
<TagLink tag={tag} linkFlg={false} withWiki={false}/>
|
||||||
|
</div>
|
||||||
</li>))}
|
</li>))}
|
||||||
</ul>)
|
</ul>)
|
||||||
}
|
}
|
||||||
|
|
||||||
export default TagSearchBox
|
export default TagSearchBox
|
||||||
|
|||||||
@@ -64,8 +64,9 @@ const TagSidebar: FC<Props> = ({ posts, onClick }) => {
|
|||||||
<ul>
|
<ul>
|
||||||
{CATEGORIES.flatMap (cat => cat in tags ? (
|
{CATEGORIES.flatMap (cat => cat in tags ? (
|
||||||
tags[cat].map (tag => (
|
tags[cat].map (tag => (
|
||||||
<li key={tag.id} className="mb-1">
|
<li key={tag.id} className="mb-1 min-w-0 max-w-full overflow-hidden">
|
||||||
<motion.div
|
<motion.div
|
||||||
|
className="flex min-w-0 max-w-full items-baseline overflow-hidden"
|
||||||
transition={{ layout: { duration: .2, ease: 'easeOut' } }}
|
transition={{ layout: { duration: .2, ease: 'easeOut' } }}
|
||||||
layoutId={`tag-${ tag.id }`}>
|
layoutId={`tag-${ tag.id }`}>
|
||||||
<TagLink tag={tag} onClick={onClick}/>
|
<TagLink tag={tag} onClick={onClick}/>
|
||||||
@@ -95,7 +96,7 @@ const TagSidebar: FC<Props> = ({ posts, onClick }) => {
|
|||||||
</>)
|
</>)
|
||||||
|
|
||||||
return (
|
return (
|
||||||
<SidebarComponent>
|
<SidebarComponent sidebarKey="posts-index-tags">
|
||||||
<TagSearch/>
|
<TagSearch/>
|
||||||
|
|
||||||
<div className="hidden md:block mt-4">
|
<div className="hidden md:block mt-4">
|
||||||
@@ -128,4 +129,4 @@ const TagSidebar: FC<Props> = ({ posts, onClick }) => {
|
|||||||
</SidebarComponent>)
|
</SidebarComponent>)
|
||||||
}
|
}
|
||||||
|
|
||||||
export default TagSidebar
|
export default TagSidebar
|
||||||
|
|||||||
@@ -7,30 +7,36 @@ import Separator from '@/components/MenuSeparator'
|
|||||||
import PrefetchLink from '@/components/PrefetchLink'
|
import PrefetchLink from '@/components/PrefetchLink'
|
||||||
import TopNavUser from '@/components/TopNavUser'
|
import TopNavUser from '@/components/TopNavUser'
|
||||||
import { WikiIdBus } from '@/lib/eventBus/WikiIdBus'
|
import { WikiIdBus } from '@/lib/eventBus/WikiIdBus'
|
||||||
import { tagsKeys, wikiKeys } from '@/lib/queryKeys'
|
import { materialsKeys, tagsKeys, wikiKeys } from '@/lib/queryKeys'
|
||||||
import { fetchTag, fetchTagByName } from '@/lib/tags'
|
import { fetchTag, fetchTagByName } from '@/lib/tags'
|
||||||
|
import { fetchMaterial } from '@/lib/materials'
|
||||||
import { cn } from '@/lib/utils'
|
import { cn } from '@/lib/utils'
|
||||||
import { fetchWikiPage } from '@/lib/wiki'
|
import { fetchWikiPage } from '@/lib/wiki'
|
||||||
|
|
||||||
import type { FC, MouseEvent } from 'react'
|
import type { FC, MouseEvent } from 'react'
|
||||||
|
|
||||||
import type { Menu, MenuVisibleItem, Tag, User } from '@/types'
|
import type { Material, Menu, MenuVisibleItem, Tag, User } from '@/types'
|
||||||
|
|
||||||
type Props = { user: User | null }
|
type Props = { user: User | null }
|
||||||
|
|
||||||
|
|
||||||
export const menuOutline = ({ tag, wikiId, user, pathName }: {
|
export const menuOutline = (
|
||||||
tag?: Tag | null
|
{ tag, material, wikiId, user, pathName }: {
|
||||||
wikiId: number | null
|
tag?: Tag | null
|
||||||
user: User | null,
|
material?: Material | null
|
||||||
pathName: string }): Menu => {
|
wikiId: number | null
|
||||||
const postCount = tag?.postCount ?? 0
|
user: User | null,
|
||||||
|
pathName: string },
|
||||||
|
): Menu => {
|
||||||
|
const postCount = tag?.postCount ?? material?.tag?.postCount ?? 0
|
||||||
|
|
||||||
const wikiPageFlg = Boolean (/^\/wiki\/(?!new|changes)[^/]+/.test (pathName) && wikiId)
|
const wikiPageFlg = Boolean (/^\/wiki\/(?!new|changes)[^/]+/.test (pathName) && wikiId)
|
||||||
const wikiTitle = pathName.split ('/')[2] ?? ''
|
const wikiTitle = pathName.split ('/')[2] ?? ''
|
||||||
|
|
||||||
const tagFlg = /^\/tags\/\d+/.test (pathName)
|
const tagFlg = /^\/tags\/\d+/.test (pathName)
|
||||||
|
|
||||||
|
const materialFlg = /^\/materials\/\d+/.test (pathName)
|
||||||
|
|
||||||
return [
|
return [
|
||||||
{ name: '広場', to: '/posts', subMenu: [
|
{ name: '広場', to: '/posts', subMenu: [
|
||||||
{ name: '一覧', to: '/posts' },
|
{ name: '一覧', to: '/posts' },
|
||||||
@@ -49,12 +55,18 @@ export const menuOutline = ({ tag, wikiId, user, pathName }: {
|
|||||||
visible: tagFlg },
|
visible: tagFlg },
|
||||||
{ name: '履歴', to: `/tags/changes?id=${ tag?.id }`,
|
{ name: '履歴', to: `/tags/changes?id=${ tag?.id }`,
|
||||||
visible: tagFlg && tag?.category !== 'nico' }] },
|
visible: tagFlg && tag?.category !== 'nico' }] },
|
||||||
{ name: '素材', to: '/materials', visible: false, subMenu: [
|
{ name: '素材', to: '/materials', visible: true, subMenu: [
|
||||||
{ name: '一覧', to: '/materials' },
|
{ name: '一覧', to: '/materials' },
|
||||||
{ name: '検索', to: '/materials/search', visible: false },
|
|
||||||
{ name: '追加', to: '/materials/new' },
|
{ name: '追加', to: '/materials/new' },
|
||||||
{ name: '全体履歴', to: '/materials/changes', visible: false },
|
{ name: '抑止', to: '/materials/suppressions' },
|
||||||
{ name: 'ヘルプ', to: '/wiki/ヘルプ:素材集' }] },
|
{ name: '全体履歴', to: '/materials/changes' },
|
||||||
|
{ name: 'ヘルプ', to: '/wiki/ヘルプ:素材管理' },
|
||||||
|
{ component: <Separator/>, visible: materialFlg },
|
||||||
|
{ name: `広場 (${ postCount || 0 })`,
|
||||||
|
to: `/posts?tags=${ encodeURIComponent (material?.tag?.name ?? '') }`,
|
||||||
|
visible: materialFlg && Boolean (material?.tag) },
|
||||||
|
{ name: '履歴', to: `/materials/changes?material_id=${ material?.id }`,
|
||||||
|
visible: materialFlg }] },
|
||||||
{ name: 'Wiki', to: '/wiki/ヘルプ:ホーム', base: '/wiki', subMenu: [
|
{ name: 'Wiki', to: '/wiki/ヘルプ:ホーム', base: '/wiki', subMenu: [
|
||||||
{ name: '検索', to: '/wiki' },
|
{ name: '検索', to: '/wiki' },
|
||||||
{ name: '新規', to: '/wiki/new' },
|
{ name: '新規', to: '/wiki/new' },
|
||||||
@@ -119,15 +131,23 @@ const TopNav: FC<Props> = ({ user }) => {
|
|||||||
queryFn: () => fetchWikiPage (wikiIdStr, { }) })
|
queryFn: () => fetchWikiPage (wikiIdStr, { }) })
|
||||||
|
|
||||||
const tagFlg = /^\/tags\/\d+/.test (location.pathname)
|
const tagFlg = /^\/tags\/\d+/.test (location.pathname)
|
||||||
const effectiveTitle = (tagFlg ? location.pathname.split ('/')[2] : wikiPage?.title) ?? ''
|
const materialFlg = /^\/materials\/\d+/.test (location.pathname)
|
||||||
|
const effectiveTitle = (((tagFlg || materialFlg)
|
||||||
|
? location.pathname.split ('/')[2]
|
||||||
|
: wikiPage?.title)
|
||||||
|
?? '')
|
||||||
|
|
||||||
const { data: tag } = useQuery ({
|
const { data: tag } = useQuery ({
|
||||||
enabled: Boolean (effectiveTitle),
|
enabled: Boolean (effectiveTitle),
|
||||||
queryKey: tagsKeys.show (effectiveTitle),
|
queryKey: tagsKeys.show (effectiveTitle),
|
||||||
queryFn: () => (tagFlg ? fetchTag : fetchTagByName) (effectiveTitle) })
|
queryFn: () => (tagFlg ? fetchTag : fetchTagByName) (effectiveTitle) })
|
||||||
|
|
||||||
|
const { data: material } = useQuery ({
|
||||||
|
enabled: Boolean (effectiveTitle),
|
||||||
|
queryKey: materialsKeys.show (effectiveTitle),
|
||||||
|
queryFn: () => fetchMaterial (effectiveTitle) })
|
||||||
|
|
||||||
const menu = menuOutline ({ tag, wikiId, user, pathName: location.pathname })
|
const menu = menuOutline ({ tag, material, wikiId, user, pathName: location.pathname })
|
||||||
const visibleMenu = menu.filter ((item): item is MenuVisibleItem => item.visible ?? true)
|
const visibleMenu = menu.filter ((item): item is MenuVisibleItem => item.visible ?? true)
|
||||||
const moreMenu = menu.filter (item =>
|
const moreMenu = menu.filter (item =>
|
||||||
!(item.visible ?? true)
|
!(item.visible ?? true)
|
||||||
|
|||||||
@@ -1,12 +1,14 @@
|
|||||||
import React from 'react'
|
import React from 'react'
|
||||||
|
|
||||||
|
import { cn } from '@/lib/utils'
|
||||||
|
|
||||||
import type { FC } from 'react'
|
import type { FC } from 'react'
|
||||||
|
|
||||||
type Props = { children: React.ReactNode }
|
type Props = { children: React.ReactNode; className?: string }
|
||||||
|
|
||||||
|
|
||||||
const PageTitle: FC<Props> = ({ children }) => (
|
const PageTitle: FC<Props> = ({ children, className, ...rest }) => (
|
||||||
<h1 className="text-2xl font-bold mb-2">
|
<h1 className={cn ('text-2xl font-bold mb-2', className)} {...rest}>
|
||||||
{children}
|
{children}
|
||||||
</h1>)
|
</h1>)
|
||||||
|
|
||||||
|
|||||||
@@ -0,0 +1,124 @@
|
|||||||
|
import { fireEvent, render, screen, waitFor } from '@testing-library/react'
|
||||||
|
import { HelmetProvider } from 'react-helmet-async'
|
||||||
|
import { beforeEach, describe, expect, it, vi } from 'vitest'
|
||||||
|
|
||||||
|
import SidebarComponent from '@/components/layout/SidebarComponent'
|
||||||
|
|
||||||
|
|
||||||
|
const sidebarWidth = (element: Element | null): string =>
|
||||||
|
(element as HTMLElement).style.getPropertyValue ('--sidebar-width')
|
||||||
|
|
||||||
|
|
||||||
|
const sidebarRoot = (container: HTMLElement): Element =>
|
||||||
|
container.querySelector ('[style*="--sidebar-width"]')!
|
||||||
|
|
||||||
|
|
||||||
|
const sidebarTree = (props: Partial<Parameters<typeof SidebarComponent>[0]>) => (
|
||||||
|
<HelmetProvider>
|
||||||
|
<div data-sidebar-container>
|
||||||
|
<SidebarComponent sidebarKey="test-sidebar" {...props}>
|
||||||
|
Sidebar body
|
||||||
|
</SidebarComponent>
|
||||||
|
</div>
|
||||||
|
</HelmetProvider>)
|
||||||
|
|
||||||
|
|
||||||
|
const renderSidebar = (
|
||||||
|
props: Partial<Parameters<typeof SidebarComponent>[0]> = {},
|
||||||
|
containerWidth = 800,
|
||||||
|
) => {
|
||||||
|
Object.defineProperty (HTMLElement.prototype, 'clientWidth', {
|
||||||
|
configurable: true,
|
||||||
|
get () {
|
||||||
|
return this.hasAttribute ('data-sidebar-container') ? containerWidth : 0
|
||||||
|
},
|
||||||
|
})
|
||||||
|
|
||||||
|
const rendered = render (sidebarTree (props))
|
||||||
|
|
||||||
|
return rendered
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
describe ('SidebarComponent', () => {
|
||||||
|
beforeEach (() => {
|
||||||
|
Object.defineProperty (window, 'innerWidth', {
|
||||||
|
configurable: true,
|
||||||
|
value: 1_000,
|
||||||
|
})
|
||||||
|
|
||||||
|
Object.defineProperty (HTMLElement.prototype, 'setPointerCapture', {
|
||||||
|
configurable: true,
|
||||||
|
value: vi.fn (),
|
||||||
|
})
|
||||||
|
Object.defineProperty (HTMLElement.prototype, 'releasePointerCapture', {
|
||||||
|
configurable: true,
|
||||||
|
value: vi.fn (),
|
||||||
|
})
|
||||||
|
Object.defineProperty (HTMLElement.prototype, 'hasPointerCapture', {
|
||||||
|
configurable: true,
|
||||||
|
value: vi.fn (() => true),
|
||||||
|
})
|
||||||
|
|
||||||
|
vi.spyOn (HTMLElement.prototype, 'setPointerCapture').mockImplementation (() => {
|
||||||
|
;
|
||||||
|
})
|
||||||
|
vi.spyOn (HTMLElement.prototype, 'releasePointerCapture').mockImplementation (() => {
|
||||||
|
;
|
||||||
|
})
|
||||||
|
vi.spyOn (HTMLElement.prototype, 'hasPointerCapture').mockReturnValue (true)
|
||||||
|
})
|
||||||
|
|
||||||
|
it ('uses maxWidth without applying the container main-width reserve twice', async () => {
|
||||||
|
localStorage.setItem ('sidebar:test-sidebar:left:width', '700')
|
||||||
|
const onWidthChange = vi.fn ()
|
||||||
|
|
||||||
|
const { container } = renderSidebar ({ maxWidth: 700, onWidthChange }, 800)
|
||||||
|
|
||||||
|
await waitFor (() => {
|
||||||
|
expect (sidebarWidth (sidebarRoot (container))).toBe ('700px')
|
||||||
|
})
|
||||||
|
expect (onWidthChange).toHaveBeenLastCalledWith (700)
|
||||||
|
})
|
||||||
|
|
||||||
|
it ('resets width and removes only its storage key on double click', async () => {
|
||||||
|
localStorage.setItem ('sidebar:test-sidebar:right:width', '420')
|
||||||
|
localStorage.setItem ('sidebar:other-sidebar:right:width', '480')
|
||||||
|
|
||||||
|
const { container } = renderSidebar ({ side: 'right' }, 900)
|
||||||
|
|
||||||
|
await waitFor (() => {
|
||||||
|
expect (sidebarWidth (sidebarRoot (container))).toBe ('420px')
|
||||||
|
})
|
||||||
|
|
||||||
|
fireEvent.doubleClick (screen.getByRole ('separator', { name: 'サイドバー幅' }))
|
||||||
|
|
||||||
|
await waitFor (() => {
|
||||||
|
expect (sidebarWidth (sidebarRoot (container))).toBe ('256px')
|
||||||
|
})
|
||||||
|
expect (localStorage.getItem ('sidebar:test-sidebar:right:width')).toBeNull ()
|
||||||
|
expect (localStorage.getItem ('sidebar:other-sidebar:right:width')).toBe ('480')
|
||||||
|
})
|
||||||
|
|
||||||
|
it ('clamps current width on maxWidth changes without re-reading storage', async () => {
|
||||||
|
localStorage.setItem ('sidebar:test-sidebar:left:width', '420')
|
||||||
|
|
||||||
|
const { container, rerender } = renderSidebar ({ maxWidth: 420 }, 900)
|
||||||
|
|
||||||
|
await waitFor (() => {
|
||||||
|
expect (sidebarWidth (sidebarRoot (container))).toBe ('420px')
|
||||||
|
})
|
||||||
|
|
||||||
|
rerender (sidebarTree ({ maxWidth: 300 }))
|
||||||
|
|
||||||
|
await waitFor (() => {
|
||||||
|
expect (sidebarWidth (sidebarRoot (container))).toBe ('300px')
|
||||||
|
})
|
||||||
|
|
||||||
|
rerender (sidebarTree ({ maxWidth: 500 }))
|
||||||
|
|
||||||
|
await waitFor (() => {
|
||||||
|
expect (sidebarWidth (sidebarRoot (container))).toBe ('300px')
|
||||||
|
})
|
||||||
|
})
|
||||||
|
})
|
||||||
@@ -1,19 +1,319 @@
|
|||||||
import { motion } from 'framer-motion'
|
import { motion } from 'framer-motion'
|
||||||
import { Helmet } from 'react-helmet-async'
|
import { Helmet } from 'react-helmet-async'
|
||||||
|
|
||||||
import type { FC, ReactNode } from 'react'
|
import { cn } from '@/lib/utils'
|
||||||
|
|
||||||
type Props = { children: ReactNode }
|
import type { CSSProperties, FC, MouseEvent, PointerEvent, ReactNode } from 'react'
|
||||||
|
import { useCallback, useEffect, useRef, useState } from 'react'
|
||||||
|
|
||||||
|
type SidebarSide = 'left' | 'right'
|
||||||
|
|
||||||
|
type Props = {
|
||||||
|
children: ReactNode
|
||||||
|
className?: string
|
||||||
|
maxWidth?: number
|
||||||
|
onWidthChange?: (width: number) => void
|
||||||
|
sidebarKey: string
|
||||||
|
side?: SidebarSide }
|
||||||
|
|
||||||
|
type ResizeState = {
|
||||||
|
pointerId: number
|
||||||
|
startWidth: number
|
||||||
|
startX: number
|
||||||
|
side: SidebarSide }
|
||||||
|
|
||||||
|
type PendingPressState = ResizeState & { startY: number }
|
||||||
|
|
||||||
|
const DEFAULT_SIDEBAR_WIDTH = 256
|
||||||
|
const MIN_SIDEBAR_WIDTH = 192
|
||||||
|
const MIN_MAIN_WIDTH = 360
|
||||||
|
const MAX_VIEWPORT_WIDTH_RATIO = .8
|
||||||
|
const LONG_PRESS_DELAY_MS = 350
|
||||||
|
const TOUCH_MOVE_THRESHOLD_PX = 8
|
||||||
|
|
||||||
|
|
||||||
const SidebarComponent: FC<Props> = ({ children }) => (
|
const storageKeyForSidebar = (sidebarKey: string, side: SidebarSide): string =>
|
||||||
<motion.div
|
`sidebar:${ sidebarKey }:${ side }:width`
|
||||||
layout="position"
|
|
||||||
transition={{ layout: { duration: .2, ease: 'easeOut' } }}
|
|
||||||
className="p-4 w-full md:w-64 md:h-full md:overflow-y-auto sidebar">
|
const getSidebarMaxWidth = (containerWidth: number): number => {
|
||||||
<Helmet>
|
const viewportWidth =
|
||||||
<style>
|
typeof window === 'undefined' ? containerWidth : window.innerWidth
|
||||||
{`
|
const viewportMaxWidth = Math.floor (viewportWidth * MAX_VIEWPORT_WIDTH_RATIO)
|
||||||
|
const containerMaxWidth = Math.floor (containerWidth - MIN_MAIN_WIDTH)
|
||||||
|
const dynamicMaxWidth = Math.min (viewportMaxWidth, containerMaxWidth)
|
||||||
|
|
||||||
|
return Math.max (MIN_SIDEBAR_WIDTH, dynamicMaxWidth)
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
const readStoredSidebarWidth = (
|
||||||
|
sidebarKey: string,
|
||||||
|
side: SidebarSide): number => {
|
||||||
|
if (typeof window === 'undefined')
|
||||||
|
return DEFAULT_SIDEBAR_WIDTH
|
||||||
|
|
||||||
|
const value = window.localStorage.getItem (storageKeyForSidebar (sidebarKey, side))
|
||||||
|
const width = value == null ? Number.NaN : Number (value)
|
||||||
|
|
||||||
|
return Number.isFinite (width) ? width : DEFAULT_SIDEBAR_WIDTH
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
const SidebarComponent: FC<Props> = ({
|
||||||
|
children,
|
||||||
|
className,
|
||||||
|
maxWidth,
|
||||||
|
onWidthChange,
|
||||||
|
sidebarKey,
|
||||||
|
side = 'left',
|
||||||
|
}) => {
|
||||||
|
const rootRef = useRef<HTMLDivElement | null> (null)
|
||||||
|
const maxWidthRef = useRef (maxWidth)
|
||||||
|
const getContainerWidth = useCallback (() => {
|
||||||
|
const containerWidth = rootRef.current
|
||||||
|
?.closest ('[data-sidebar-container]')
|
||||||
|
?.clientWidth
|
||||||
|
?? window.innerWidth
|
||||||
|
return containerWidth
|
||||||
|
}, [])
|
||||||
|
const getClampedWidth = useCallback ((
|
||||||
|
nextWidth: number,
|
||||||
|
containerWidth: number): number => {
|
||||||
|
const viewportWidth =
|
||||||
|
typeof window === 'undefined' ? containerWidth : window.innerWidth
|
||||||
|
const viewportMaxWidth = Math.floor (viewportWidth * MAX_VIEWPORT_WIDTH_RATIO)
|
||||||
|
const maxAllowedWidth =
|
||||||
|
maxWidthRef.current == null
|
||||||
|
? getSidebarMaxWidth (containerWidth)
|
||||||
|
: Math.max (
|
||||||
|
MIN_SIDEBAR_WIDTH,
|
||||||
|
Math.min (viewportMaxWidth, maxWidthRef.current))
|
||||||
|
|
||||||
|
return Math.min (maxAllowedWidth, Math.max (MIN_SIDEBAR_WIDTH, nextWidth))
|
||||||
|
}, [])
|
||||||
|
|
||||||
|
const [width, setWidth] = useState (() => (
|
||||||
|
typeof window === 'undefined'
|
||||||
|
? DEFAULT_SIDEBAR_WIDTH
|
||||||
|
: getClampedWidth (
|
||||||
|
readStoredSidebarWidth (sidebarKey, side),
|
||||||
|
window.innerWidth)))
|
||||||
|
const [resizing, setResizing] = useState (false)
|
||||||
|
const widthRef = useRef (width)
|
||||||
|
const longPressTimerRef = useRef<ReturnType<typeof setTimeout> | null> (null)
|
||||||
|
const pendingPressRef = useRef<PendingPressState | null> (null)
|
||||||
|
const resizeRef = useRef<ResizeState | null> (null)
|
||||||
|
const bodyStyleRef = useRef<{ cursor: string, userSelect: string } | null> (null)
|
||||||
|
|
||||||
|
const clearLongPressTimer = useCallback (() => {
|
||||||
|
if (longPressTimerRef.current == null)
|
||||||
|
return
|
||||||
|
|
||||||
|
clearTimeout (longPressTimerRef.current)
|
||||||
|
longPressTimerRef.current = null
|
||||||
|
}, [])
|
||||||
|
|
||||||
|
const restoreBodyStyle = useCallback (() => {
|
||||||
|
if (bodyStyleRef.current == null)
|
||||||
|
return
|
||||||
|
|
||||||
|
document.body.style.cursor = bodyStyleRef.current.cursor
|
||||||
|
document.body.style.userSelect = bodyStyleRef.current.userSelect
|
||||||
|
bodyStyleRef.current = null
|
||||||
|
}, [])
|
||||||
|
|
||||||
|
const startResize = useCallback ((state: ResizeState) => {
|
||||||
|
clearLongPressTimer ()
|
||||||
|
pendingPressRef.current = null
|
||||||
|
resizeRef.current = state
|
||||||
|
setResizing (true)
|
||||||
|
|
||||||
|
if (bodyStyleRef.current == null)
|
||||||
|
{
|
||||||
|
bodyStyleRef.current = {
|
||||||
|
cursor: document.body.style.cursor,
|
||||||
|
userSelect: document.body.style.userSelect }
|
||||||
|
}
|
||||||
|
|
||||||
|
document.body.style.cursor = 'col-resize'
|
||||||
|
document.body.style.userSelect = 'none'
|
||||||
|
}, [clearLongPressTimer])
|
||||||
|
|
||||||
|
const finishResize = useCallback (() => {
|
||||||
|
clearLongPressTimer ()
|
||||||
|
pendingPressRef.current = null
|
||||||
|
|
||||||
|
const state = resizeRef.current
|
||||||
|
resizeRef.current = null
|
||||||
|
|
||||||
|
if (state != null)
|
||||||
|
window.localStorage.setItem (
|
||||||
|
storageKeyForSidebar (sidebarKey, state.side),
|
||||||
|
String (widthRef.current))
|
||||||
|
|
||||||
|
setResizing (false)
|
||||||
|
restoreBodyStyle ()
|
||||||
|
}, [clearLongPressTimer, restoreBodyStyle, sidebarKey])
|
||||||
|
|
||||||
|
const applyWidth = useCallback ((nextWidth: number) => {
|
||||||
|
if (nextWidth === widthRef.current)
|
||||||
|
return
|
||||||
|
|
||||||
|
widthRef.current = nextWidth
|
||||||
|
setWidth (nextWidth)
|
||||||
|
}, [])
|
||||||
|
|
||||||
|
useEffect (() => {
|
||||||
|
maxWidthRef.current = maxWidth
|
||||||
|
const containerWidth = getContainerWidth ()
|
||||||
|
const nextWidth = getClampedWidth (widthRef.current, containerWidth)
|
||||||
|
applyWidth (nextWidth)
|
||||||
|
}, [applyWidth, getClampedWidth, getContainerWidth, maxWidth])
|
||||||
|
|
||||||
|
const updateWidth = useCallback ((clientX: number) => {
|
||||||
|
const state = resizeRef.current
|
||||||
|
if (state == null)
|
||||||
|
return
|
||||||
|
|
||||||
|
const containerWidth = getContainerWidth ()
|
||||||
|
const delta = state.side === 'left'
|
||||||
|
? clientX - state.startX
|
||||||
|
: state.startX - clientX
|
||||||
|
const nextWidth = getClampedWidth (state.startWidth + delta, containerWidth)
|
||||||
|
applyWidth (nextWidth)
|
||||||
|
}, [applyWidth, getClampedWidth, getContainerWidth])
|
||||||
|
|
||||||
|
const handlePointerDown = (ev: PointerEvent<HTMLDivElement>) => {
|
||||||
|
if (ev.pointerType !== 'mouse' && ev.pointerType !== 'touch')
|
||||||
|
return
|
||||||
|
|
||||||
|
if (ev.pointerType === 'mouse' && ev.button !== 0)
|
||||||
|
return
|
||||||
|
|
||||||
|
ev.preventDefault ()
|
||||||
|
ev.stopPropagation ()
|
||||||
|
ev.currentTarget.setPointerCapture (ev.pointerId)
|
||||||
|
|
||||||
|
const state = {
|
||||||
|
pointerId: ev.pointerId,
|
||||||
|
side,
|
||||||
|
startWidth: widthRef.current,
|
||||||
|
startX: ev.clientX }
|
||||||
|
|
||||||
|
if (ev.pointerType === 'mouse')
|
||||||
|
{
|
||||||
|
startResize (state)
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
pendingPressRef.current = { ...state, startY: ev.clientY }
|
||||||
|
clearLongPressTimer ()
|
||||||
|
longPressTimerRef.current = setTimeout (() => {
|
||||||
|
if (pendingPressRef.current != null)
|
||||||
|
startResize (pendingPressRef.current)
|
||||||
|
}, LONG_PRESS_DELAY_MS)
|
||||||
|
}
|
||||||
|
|
||||||
|
const handlePointerMove = (ev: PointerEvent<HTMLDivElement>) => {
|
||||||
|
ev.stopPropagation ()
|
||||||
|
|
||||||
|
if (resizeRef.current != null)
|
||||||
|
{
|
||||||
|
ev.preventDefault ()
|
||||||
|
updateWidth (ev.clientX)
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
const pendingPress = pendingPressRef.current
|
||||||
|
if (pendingPress == null || pendingPress.pointerId !== ev.pointerId)
|
||||||
|
return
|
||||||
|
|
||||||
|
const deltaX = ev.clientX - pendingPress.startX
|
||||||
|
const deltaY = ev.clientY - pendingPress.startY
|
||||||
|
const distance = Math.hypot (deltaX, deltaY)
|
||||||
|
|
||||||
|
if (distance >= TOUCH_MOVE_THRESHOLD_PX)
|
||||||
|
{
|
||||||
|
clearLongPressTimer ()
|
||||||
|
pendingPressRef.current = null
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
const handlePointerEnd = (ev: PointerEvent<HTMLDivElement>) => {
|
||||||
|
ev.stopPropagation ()
|
||||||
|
|
||||||
|
if (ev.currentTarget.hasPointerCapture (ev.pointerId))
|
||||||
|
ev.currentTarget.releasePointerCapture (ev.pointerId)
|
||||||
|
|
||||||
|
finishResize ()
|
||||||
|
}
|
||||||
|
|
||||||
|
const resetWidth = useCallback (() => {
|
||||||
|
const containerWidth = getContainerWidth ()
|
||||||
|
const nextWidth = getClampedWidth (DEFAULT_SIDEBAR_WIDTH, containerWidth)
|
||||||
|
applyWidth (nextWidth)
|
||||||
|
window.localStorage.removeItem (storageKeyForSidebar (sidebarKey, side))
|
||||||
|
}, [applyWidth, getClampedWidth, getContainerWidth, sidebarKey, side])
|
||||||
|
|
||||||
|
const handleDoubleClick = (ev: MouseEvent<HTMLDivElement>) => {
|
||||||
|
ev.preventDefault ()
|
||||||
|
ev.stopPropagation ()
|
||||||
|
resetWidth ()
|
||||||
|
}
|
||||||
|
|
||||||
|
useEffect (() => {
|
||||||
|
const containerWidth = getContainerWidth ()
|
||||||
|
const nextWidth = getClampedWidth (
|
||||||
|
readStoredSidebarWidth (sidebarKey, side),
|
||||||
|
containerWidth)
|
||||||
|
applyWidth (nextWidth)
|
||||||
|
}, [applyWidth, getClampedWidth, getContainerWidth, sidebarKey, side])
|
||||||
|
|
||||||
|
useEffect (() => {
|
||||||
|
const containerWidth = getContainerWidth ()
|
||||||
|
const nextWidth = getClampedWidth (widthRef.current, containerWidth)
|
||||||
|
applyWidth (nextWidth)
|
||||||
|
}, [applyWidth, getClampedWidth, getContainerWidth])
|
||||||
|
|
||||||
|
useEffect (() => {
|
||||||
|
if (typeof window === 'undefined')
|
||||||
|
return
|
||||||
|
|
||||||
|
const handleResize = () => {
|
||||||
|
const containerWidth = getContainerWidth ()
|
||||||
|
const nextWidth = getClampedWidth (widthRef.current, containerWidth)
|
||||||
|
applyWidth (nextWidth)
|
||||||
|
}
|
||||||
|
|
||||||
|
window.addEventListener ('resize', handleResize)
|
||||||
|
return () => window.removeEventListener ('resize', handleResize)
|
||||||
|
}, [applyWidth, getClampedWidth, getContainerWidth])
|
||||||
|
|
||||||
|
useEffect (() => {
|
||||||
|
onWidthChange?.(width)
|
||||||
|
}, [onWidthChange, width])
|
||||||
|
|
||||||
|
useEffect (() => () => {
|
||||||
|
clearLongPressTimer ()
|
||||||
|
restoreBodyStyle ()
|
||||||
|
}, [clearLongPressTimer, restoreBodyStyle])
|
||||||
|
|
||||||
|
const style = {
|
||||||
|
'--sidebar-width': `${ width }px` } as CSSProperties
|
||||||
|
|
||||||
|
return (
|
||||||
|
<motion.div
|
||||||
|
ref={rootRef}
|
||||||
|
layout="position"
|
||||||
|
transition={{ layout: { duration: .2, ease: 'easeOut' } }}
|
||||||
|
style={style}
|
||||||
|
className={cn (
|
||||||
|
'relative w-full md:w-[var(--sidebar-width)] md:shrink-0 md:h-full',
|
||||||
|
className)}>
|
||||||
|
<Helmet>
|
||||||
|
<style>
|
||||||
|
{`
|
||||||
.sidebar
|
.sidebar
|
||||||
{
|
{
|
||||||
direction: rtl;
|
direction: rtl;
|
||||||
@@ -23,10 +323,34 @@ const SidebarComponent: FC<Props> = ({ children }) => (
|
|||||||
{
|
{
|
||||||
direction: ltr;
|
direction: ltr;
|
||||||
}`}
|
}`}
|
||||||
</style>
|
</style>
|
||||||
</Helmet>
|
</Helmet>
|
||||||
|
|
||||||
{children}
|
<div className="h-full overflow-y-auto p-4 sidebar">
|
||||||
</motion.div>)
|
{children}
|
||||||
|
</div>
|
||||||
|
|
||||||
export default SidebarComponent
|
<div
|
||||||
|
role="separator"
|
||||||
|
aria-orientation="vertical"
|
||||||
|
aria-label="サイドバー幅"
|
||||||
|
onPointerDown={handlePointerDown}
|
||||||
|
onPointerMove={handlePointerMove}
|
||||||
|
onPointerUp={handlePointerEnd}
|
||||||
|
onPointerCancel={handlePointerEnd}
|
||||||
|
onDoubleClick={handleDoubleClick}
|
||||||
|
className={cn (
|
||||||
|
'hidden md:block absolute top-0 bottom-0 z-20 w-4 cursor-col-resize',
|
||||||
|
'touch-none select-none',
|
||||||
|
side === 'left' ? '-right-2' : '-left-2',
|
||||||
|
'before:absolute before:top-0 before:bottom-0 before:w-px',
|
||||||
|
'before:bg-neutral-500/0 hover:before:bg-neutral-500/30',
|
||||||
|
'before:transition-colors before:duration-150',
|
||||||
|
side === 'left'
|
||||||
|
? 'before:left-1/2'
|
||||||
|
: 'before:right-1/2',
|
||||||
|
resizing && 'before:bg-neutral-500/40')}/>
|
||||||
|
</motion.div>)
|
||||||
|
}
|
||||||
|
|
||||||
|
export default SidebarComponent
|
||||||
|
|||||||
@@ -1,19 +1,19 @@
|
|||||||
import * as React from "react"
|
import * as React from 'react'
|
||||||
|
|
||||||
import { cn } from "@/lib/utils"
|
import { cn } from '@/lib/utils'
|
||||||
|
|
||||||
const Input = React.forwardRef<HTMLInputElement, React.ComponentProps<"input">>(
|
const Input = React.forwardRef<HTMLInputElement, React.ComponentProps<'input'>>(
|
||||||
({ className, type, ...props }, ref) => {
|
({ className, type, ...props }, ref) => {
|
||||||
return (
|
return (
|
||||||
<input
|
<input
|
||||||
type={type}
|
type={type}
|
||||||
className={cn(
|
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",
|
'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
)}
|
className)}
|
||||||
ref={ref}
|
ref={ref}
|
||||||
{...props}
|
{...props}
|
||||||
/>
)
|
/>)
|
||||||
}
)
|
})
|
||||||
Input.displayName = "Input"
|
Input.displayName = 'Input'
|
||||||
|
|
||||||
export { Input }
|
export { Input }
|
||||||
|
|||||||
@@ -1,26 +1,26 @@
|
|||||||
"use client"
|
'use client'
|
||||||
|
|
||||||
import * as React from "react"
|
import * as React from 'react'
|
||||||
import * as SwitchPrimitives from "@radix-ui/react-switch"
|
import * as SwitchPrimitives from '@radix-ui/react-switch'
|
||||||
|
|
||||||
import { cn } from "@/lib/utils"
|
import { cn } from '@/lib/utils'
|
||||||
|
|
||||||
const Switch = React.forwardRef<
|
const Switch = React.forwardRef<
|
||||||
React.ElementRef<typeof SwitchPrimitives.Root>,
|
React.ElementRef<typeof SwitchPrimitives.Root>,
|
||||||
React.ComponentPropsWithoutRef<typeof SwitchPrimitives.Root>
|
React.ComponentPropsWithoutRef<typeof SwitchPrimitives.Root>
|
||||||
>(({ className, ...props }, ref) => (
|
>(({ className, ...props }, ref) => (
|
||||||
<SwitchPrimitives.Root
|
<SwitchPrimitives.Root
|
||||||
className={cn(
|
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",
|
'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
)}
|
className)}
|
||||||
{...props}
|
{...props}
|
||||||
ref={ref}
|
ref={ref}
|
||||||
>
|
>
|
||||||
<SwitchPrimitives.Thumb
|
<SwitchPrimitives.Thumb
|
||||||
className={cn(
|
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"
)}
|
'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>
))
|
</SwitchPrimitives.Root>))
|
||||||
Switch.displayName = SwitchPrimitives.Root.displayName
|
Switch.displayName = SwitchPrimitives.Root.displayName
|
||||||
|
|
||||||
export { Switch }
|
export { Switch }
|
||||||
|
|||||||
@@ -132,3 +132,20 @@ body
|
|||||||
0%, 100% { color: #f87171; }
|
0%, 100% { color: #f87171; }
|
||||||
50% { color: #60a5fa; }
|
50% { color: #60a5fa; }
|
||||||
}
|
}
|
||||||
|
|
||||||
|
.tag-marquee
|
||||||
|
{
|
||||||
|
position: relative;
|
||||||
|
}
|
||||||
|
|
||||||
|
.tag-marquee__animated
|
||||||
|
{
|
||||||
|
position: absolute;
|
||||||
|
inset: 0 auto 0 0;
|
||||||
|
min-width: 100%;
|
||||||
|
width: max-content;
|
||||||
|
opacity: 0;
|
||||||
|
pointer-events: none;
|
||||||
|
white-space: nowrap;
|
||||||
|
will-change: transform;
|
||||||
|
}
|
||||||
|
|||||||
+20
-29
@@ -1,45 +1,31 @@
|
|||||||
import {
|
import { apiGet, isApiError, apiPost, apiPut } from '@/lib/api'
|
||||||
apiGet,
|
|
||||||
isApiError,
|
|
||||||
apiPost,
|
|
||||||
apiPut,
|
|
||||||
} from '@/lib/api'
|
|
||||||
|
|
||||||
import type {
|
import type { Material,
|
||||||
Material,
|
MaterialIndexResponse,
|
||||||
MaterialVersion,
|
MaterialVersion,
|
||||||
FetchMaterialsParams,
|
FetchMaterialsParams,
|
||||||
MaterialFilter,
|
MaterialFilter,
|
||||||
MaterialSyncSuppression,
|
MaterialSyncSuppression,
|
||||||
MaterialSidebarTag,
|
MaterialSidebarTag,
|
||||||
MaterialTagTree,
|
MaterialTagTree } from '@/types'
|
||||||
} from '@/types'
|
|
||||||
|
|
||||||
export type FetchMaterialTreeParams = {
|
export type FetchMaterialTreeParams = {
|
||||||
parentId?: number | null
|
parentId?: number | null
|
||||||
materialFilter: MaterialFilter
|
materialFilter: MaterialFilter }
|
||||||
}
|
|
||||||
|
|
||||||
export type MaterialIndexResponse = {
|
export type MaterialSyncSuppressionResponse = { suppressions: MaterialSyncSuppression[] }
|
||||||
materials: Material[]
|
|
||||||
count: number
|
|
||||||
}
|
|
||||||
|
|
||||||
export type MaterialSyncSuppressionResponse = {
|
|
||||||
suppressions: MaterialSyncSuppression[]
|
|
||||||
}
|
|
||||||
|
|
||||||
export type MaterialChangesResponse = {
|
export type MaterialChangesResponse = {
|
||||||
versions: MaterialVersion[]
|
versions: MaterialVersion[]
|
||||||
count: number
|
count: number }
|
||||||
}
|
|
||||||
|
|
||||||
const MATERIAL_FILTERS: MaterialFilter[] = ['present', 'missing', 'any']
|
const MATERIAL_FILTERS: MaterialFilter[] = ['present', 'missing', 'any']
|
||||||
|
|
||||||
|
|
||||||
export const parseMaterialFilter = (
|
export const parseMaterialFilter = (
|
||||||
value: unknown,
|
value: unknown,
|
||||||
fallback: MaterialFilter = 'present'): MaterialFilter =>
|
fallback: MaterialFilter = 'present',
|
||||||
|
): MaterialFilter =>
|
||||||
typeof value === 'string' && MATERIAL_FILTERS.includes (value as MaterialFilter)
|
typeof value === 'string' && MATERIAL_FILTERS.includes (value as MaterialFilter)
|
||||||
? value as MaterialFilter
|
? value as MaterialFilter
|
||||||
: fallback
|
: fallback
|
||||||
@@ -48,11 +34,16 @@ export const parseMaterialFilter = (
|
|||||||
export const fetchMaterials = async (
|
export const fetchMaterials = async (
|
||||||
{ q, tagState, mediaKind, createdFrom, createdTo,
|
{ q, tagState, mediaKind, createdFrom, createdTo,
|
||||||
updatedFrom, updatedTo, sort, direction, page,
|
updatedFrom, updatedTo, sort, direction, page,
|
||||||
limit }: FetchMaterialsParams): Promise<MaterialIndexResponse> =>
|
tagId, includeDescendants, groupBy,
|
||||||
|
limit }: FetchMaterialsParams,
|
||||||
|
): Promise<MaterialIndexResponse> =>
|
||||||
await apiGet ('/materials', { params: {
|
await apiGet ('/materials', { params: {
|
||||||
...(q && { q }),
|
...(q && { q }),
|
||||||
tag_state: tagState,
|
tag_state: tagState,
|
||||||
media_kind: mediaKind,
|
media_kind: mediaKind,
|
||||||
|
...(tagId != null && { tag_id: tagId }),
|
||||||
|
...(includeDescendants && { include_descendants: '1' }),
|
||||||
|
...(groupBy !== 'none' && { group_by: groupBy }),
|
||||||
...(createdFrom && { created_from: createdFrom }),
|
...(createdFrom && { created_from: createdFrom }),
|
||||||
...(createdTo && { created_to: createdTo }),
|
...(createdTo && { created_to: createdTo }),
|
||||||
...(updatedFrom && { updated_from: updatedFrom }),
|
...(updatedFrom && { updated_from: updatedFrom }),
|
||||||
|
|||||||
@@ -70,6 +70,7 @@ describe ('posts API functions', () => {
|
|||||||
id: 5,
|
id: 5,
|
||||||
title: 'new title',
|
title: 'new title',
|
||||||
tags: 'tag',
|
tags: 'tag',
|
||||||
|
duration: null,
|
||||||
parentPostIds: '1 2',
|
parentPostIds: '1 2',
|
||||||
originalCreatedFrom: null,
|
originalCreatedFrom: null,
|
||||||
originalCreatedBefore: '2026-01-02T00:00:00Z',
|
originalCreatedBefore: '2026-01-02T00:00:00Z',
|
||||||
@@ -82,6 +83,7 @@ describe ('posts API functions', () => {
|
|||||||
{
|
{
|
||||||
title: 'new title',
|
title: 'new title',
|
||||||
tags: 'tag',
|
tags: 'tag',
|
||||||
|
duration: null,
|
||||||
parent_post_ids: '1 2',
|
parent_post_ids: '1 2',
|
||||||
original_created_from: null,
|
original_created_from: null,
|
||||||
original_created_before: '2026-01-02T00:00:00Z',
|
original_created_before: '2026-01-02T00:00:00Z',
|
||||||
|
|||||||
@@ -44,6 +44,7 @@ export const updatePost = async (
|
|||||||
post: { id: number
|
post: { id: number
|
||||||
title: string | null
|
title: string | null
|
||||||
tags: string
|
tags: string
|
||||||
|
duration: string | null
|
||||||
parentPostIds: string
|
parentPostIds: string
|
||||||
originalCreatedFrom: string | null
|
originalCreatedFrom: string | null
|
||||||
originalCreatedBefore: string | null },
|
originalCreatedBefore: string | null },
|
||||||
@@ -55,6 +56,7 @@ export const updatePost = async (
|
|||||||
`/posts/${ post.id }`,
|
`/posts/${ post.id }`,
|
||||||
{ title: post.title,
|
{ title: post.title,
|
||||||
tags: post.tags,
|
tags: post.tags,
|
||||||
|
duration: post.duration,
|
||||||
parent_post_ids: post.parentPostIds,
|
parent_post_ids: post.parentPostIds,
|
||||||
original_created_from: post.originalCreatedFrom,
|
original_created_from: post.originalCreatedFrom,
|
||||||
original_created_before: post.originalCreatedBefore },
|
original_created_before: post.originalCreatedBefore },
|
||||||
|
|||||||
@@ -1,6 +1,6 @@
|
|||||||
import { describe, expect, it } from 'vitest'
|
import { describe, expect, it } from 'vitest'
|
||||||
|
|
||||||
import { cn, originalCreatedAtString, toDate } from '@/lib/utils'
|
import { cn, msToTime, originalCreatedAtString, toDate } from '@/lib/utils'
|
||||||
|
|
||||||
describe ('utils', () => {
|
describe ('utils', () => {
|
||||||
it ('converts strings to dates and leaves date instances intact', () => {
|
it ('converts strings to dates and leaves date instances intact', () => {
|
||||||
@@ -26,3 +26,14 @@ describe ('utils', () => {
|
|||||||
).toContain ('時刻不詳')
|
).toContain ('時刻不詳')
|
||||||
})
|
})
|
||||||
})
|
})
|
||||||
|
|
||||||
|
describe ('msToTime', () => {
|
||||||
|
it ('keeps milliseconds when present', () => {
|
||||||
|
expect (msToTime (60_500)).toBe ('1:00.500')
|
||||||
|
expect (msToTime (60_001)).toBe ('1:00.001')
|
||||||
|
})
|
||||||
|
|
||||||
|
it ('omits milliseconds when they are zero', () => {
|
||||||
|
expect (msToTime (60_000)).toBe ('1:00')
|
||||||
|
})
|
||||||
|
})
|
||||||
|
|||||||
@@ -71,6 +71,22 @@ export const originalCreatedAtString = (
|
|||||||
}
|
}
|
||||||
|
|
||||||
|
|
||||||
|
export const msToTime = (ms: number): string => {
|
||||||
|
const totalS = Math.trunc (ms / 1_000)
|
||||||
|
const s = String (totalS % 60)
|
||||||
|
const min = String (Math.trunc (totalS / 60) % 60)
|
||||||
|
const h = Math.trunc (totalS / 3_600)
|
||||||
|
const remainderMs = ms % 1_000
|
||||||
|
|
||||||
|
const base =
|
||||||
|
(h > 0
|
||||||
|
? `${ h }:${ min.padStart (2, '0') }:${ s.padStart (2, '0') }`
|
||||||
|
: `${ min }:${ s.padStart (2, '0') }`)
|
||||||
|
|
||||||
|
return remainderMs > 0 ? `${ base }.${ remainderMs.toString ().padStart (3, '0') }` : base
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
export const inputClass = (invalid?: boolean, className?: string): string =>
|
export const inputClass = (invalid?: boolean, className?: string): string =>
|
||||||
cn ('w-full rounded border p-2',
|
cn ('w-full rounded border p-2',
|
||||||
(invalid
|
(invalid
|
||||||
|
|||||||
@@ -6,9 +6,11 @@ import type { FC } from 'react'
|
|||||||
|
|
||||||
|
|
||||||
const MaterialBasePage: FC = () => (
|
const MaterialBasePage: FC = () => (
|
||||||
<div className="md:flex md:flex-1 overflow-y-auto md:overflow-y-hidden">
|
<div
|
||||||
|
data-sidebar-container
|
||||||
|
className="md:flex md:flex-1 overflow-y-auto md:overflow-y-hidden">
|
||||||
<MaterialSidebar/>
|
<MaterialSidebar/>
|
||||||
<Outlet/>
|
<Outlet/>
|
||||||
</div>)
|
</div>)
|
||||||
|
|
||||||
export default MaterialBasePage
|
export default MaterialBasePage
|
||||||
|
|||||||
@@ -7,9 +7,9 @@ import { buildMaterial, buildTag } from '@/test/factories'
|
|||||||
import { renderWithProviders } from '@/test/render'
|
import { renderWithProviders } from '@/test/render'
|
||||||
|
|
||||||
const api = vi.hoisted (() => ({
|
const api = vi.hoisted (() => ({
|
||||||
apiGet: vi.fn (),
|
apiGet: vi.fn (),
|
||||||
apiPatch: vi.fn (),
|
apiPut: vi.fn (),
|
||||||
apiPut: vi.fn (),
|
isApiError: vi.fn (),
|
||||||
}))
|
}))
|
||||||
|
|
||||||
const wikiApi = vi.hoisted (() => ({
|
const wikiApi = vi.hoisted (() => ({
|
||||||
@@ -35,7 +35,11 @@ const renderPage = () =>
|
|||||||
describe ('MaterialDetailPage', () => {
|
describe ('MaterialDetailPage', () => {
|
||||||
beforeEach (() => {
|
beforeEach (() => {
|
||||||
vi.clearAllMocks ()
|
vi.clearAllMocks ()
|
||||||
api.apiGet.mockResolvedValue ([])
|
api.apiGet.mockImplementation (async (path: string) =>
|
||||||
|
path === '/tags/autocomplete'
|
||||||
|
? []
|
||||||
|
: buildMaterial ({ id: 8 }))
|
||||||
|
api.isApiError.mockReturnValue (false)
|
||||||
wikiApi.fetchWikiPages.mockResolvedValue ([])
|
wikiApi.fetchWikiPages.mockResolvedValue ([])
|
||||||
vi.stubGlobal ('fetch', vi.fn (async () => ({
|
vi.stubGlobal ('fetch', vi.fn (async () => ({
|
||||||
blob: async () => new Blob (['image'], { type: 'image/png' }),
|
blob: async () => new Blob (['image'], { type: 'image/png' }),
|
||||||
@@ -86,4 +90,22 @@ describe ('MaterialDetailPage', () => {
|
|||||||
expect (formData.get ('export_paths[legacy_drive]')).toBe ('素材/new.png')
|
expect (formData.get ('export_paths[legacy_drive]')).toBe ('素材/new.png')
|
||||||
expect (toastApi.toast).toHaveBeenCalledWith ({ title: '更新成功!' })
|
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,7 +8,6 @@ import WikiBody from '@/components/WikiBody'
|
|||||||
import FieldError from '@/components/common/FieldError'
|
import FieldError from '@/components/common/FieldError'
|
||||||
import FormField from '@/components/common/FormField'
|
import FormField from '@/components/common/FormField'
|
||||||
import PageTitle from '@/components/common/PageTitle'
|
import PageTitle from '@/components/common/PageTitle'
|
||||||
import PrefetchLink from '@/components/PrefetchLink'
|
|
||||||
import TabGroup, { Tab } from '@/components/common/TabGroup'
|
import TabGroup, { Tab } from '@/components/common/TabGroup'
|
||||||
import TagInput from '@/components/common/TagInput'
|
import TagInput from '@/components/common/TagInput'
|
||||||
import MainArea from '@/components/layout/MainArea'
|
import MainArea from '@/components/layout/MainArea'
|
||||||
@@ -119,12 +118,6 @@ const MaterialDetailPage: FC = () => {
|
|||||||
: materialTitle}
|
: materialTitle}
|
||||||
</PageTitle>
|
</PageTitle>
|
||||||
|
|
||||||
<PrefetchLink
|
|
||||||
to={`/materials/changes?material_id=${ material.id }`}
|
|
||||||
className="text-sm text-sky-700 underline underline-offset-2 dark:text-sky-300">
|
|
||||||
この素材の履歴
|
|
||||||
</PrefetchLink>
|
|
||||||
|
|
||||||
{(material.file && material.contentType) && (
|
{(material.file && material.contentType) && (
|
||||||
(/image\/.*/.test (material.contentType) && (
|
(/image\/.*/.test (material.contentType) && (
|
||||||
<img src={material.file} alt={material.tag?.name || undefined}/>))
|
<img src={material.file} alt={material.tag?.name || undefined}/>))
|
||||||
@@ -134,17 +127,12 @@ const MaterialDetailPage: FC = () => {
|
|||||||
<audio src={material.file} controls/>)))}
|
<audio src={material.file} controls/>)))}
|
||||||
|
|
||||||
<TabGroup>
|
<TabGroup>
|
||||||
<Tab name="Wiki">
|
{material.tag && (
|
||||||
{material.tag
|
<Tab name="Wiki">
|
||||||
? (
|
|
||||||
<WikiBody
|
<WikiBody
|
||||||
title={material.tag.name}
|
title={material.tag.name}
|
||||||
body={material.wikiPageBody ?? undefined}/>)
|
body={material.wikiPageBody ?? undefined}/>
|
||||||
: (
|
</Tab>)}
|
||||||
<p className="text-stone-700 dark:text-stone-300">
|
|
||||||
タグ未設定の素材です.
|
|
||||||
</p>)}
|
|
||||||
</Tab>
|
|
||||||
|
|
||||||
<Tab name="編輯">
|
<Tab name="編輯">
|
||||||
<div className="max-w-wl space-y-4 pt-2">
|
<div className="max-w-wl space-y-4 pt-2">
|
||||||
|
|||||||
@@ -80,14 +80,7 @@ const MaterialHistoryPage: FC = () => {
|
|||||||
</Helmet>
|
</Helmet>
|
||||||
|
|
||||||
<div className="space-y-5">
|
<div className="space-y-5">
|
||||||
<div className="flex flex-wrap items-center justify-between gap-3">
|
<PageTitle>素材履歴</PageTitle>
|
||||||
<PageTitle>素材履歴</PageTitle>
|
|
||||||
<PrefetchLink
|
|
||||||
to="/materials"
|
|
||||||
className="text-sm text-sky-700 underline underline-offset-2 dark:text-sky-300">
|
|
||||||
素材一覧へ戻る
|
|
||||||
</PrefetchLink>
|
|
||||||
</div>
|
|
||||||
|
|
||||||
<form
|
<form
|
||||||
onSubmit={handleSearch}
|
onSubmit={handleSearch}
|
||||||
@@ -112,20 +105,6 @@ const MaterialHistoryPage: FC = () => {
|
|||||||
onChange={e => setTagInput (e.target.value)}
|
onChange={e => setTagInput (e.target.value)}
|
||||||
className={inputClass (invalid)}/>)}
|
className={inputClass (invalid)}/>)}
|
||||||
</FormField>
|
</FormField>
|
||||||
|
|
||||||
<FormField label="イベント">
|
|
||||||
{({ invalid }) => (
|
|
||||||
<select
|
|
||||||
value={eventTypeInput}
|
|
||||||
onChange={e => setEventTypeInput (e.target.value)}
|
|
||||||
className={inputClass (invalid)}>
|
|
||||||
<option value="">すべて</option>
|
|
||||||
<option value="create">create</option>
|
|
||||||
<option value="update">update</option>
|
|
||||||
<option value="discard">discard</option>
|
|
||||||
<option value="restore">restore</option>
|
|
||||||
</select>)}
|
|
||||||
</FormField>
|
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
<button
|
<button
|
||||||
@@ -150,7 +129,6 @@ const MaterialHistoryPage: FC = () => {
|
|||||||
<table className="w-full min-w-[1200px] table-fixed border-collapse">
|
<table className="w-full min-w-[1200px] table-fixed border-collapse">
|
||||||
<colgroup>
|
<colgroup>
|
||||||
<col className="w-48"/>
|
<col className="w-48"/>
|
||||||
<col className="w-32"/>
|
|
||||||
<col className="w-28"/>
|
<col className="w-28"/>
|
||||||
<col className="w-24"/>
|
<col className="w-24"/>
|
||||||
<col className="w-64"/>
|
<col className="w-64"/>
|
||||||
@@ -163,7 +141,6 @@ const MaterialHistoryPage: FC = () => {
|
|||||||
<thead className="border-b-2 border-black dark:border-white">
|
<thead className="border-b-2 border-black dark:border-white">
|
||||||
<tr>
|
<tr>
|
||||||
<th className="p-2 text-left">日時</th>
|
<th className="p-2 text-left">日時</th>
|
||||||
<th className="p-2 text-left">event_type</th>
|
|
||||||
<th className="p-2 text-left">素材 ID</th>
|
<th className="p-2 text-left">素材 ID</th>
|
||||||
<th className="p-2 text-left">版</th>
|
<th className="p-2 text-left">版</th>
|
||||||
<th className="p-2 text-left">タグ名</th>
|
<th className="p-2 text-left">タグ名</th>
|
||||||
@@ -180,7 +157,6 @@ const MaterialHistoryPage: FC = () => {
|
|||||||
key={version.id}
|
key={version.id}
|
||||||
className="even:bg-gray-100 dark:even:bg-gray-700">
|
className="even:bg-gray-100 dark:even:bg-gray-700">
|
||||||
<td className="p-2">{dateString (version.createdAt)}</td>
|
<td className="p-2">{dateString (version.createdAt)}</td>
|
||||||
<td className="p-2">{version.eventType}</td>
|
|
||||||
<td className="p-2">
|
<td className="p-2">
|
||||||
<PrefetchLink to={`/materials/${ version.materialId }`}>
|
<PrefetchLink to={`/materials/${ version.materialId }`}>
|
||||||
#{version.materialId}
|
#{version.materialId}
|
||||||
|
|||||||
@@ -1,5 +1,5 @@
|
|||||||
import { screen, waitFor } from '@testing-library/react'
|
import { fireEvent, screen, waitFor } from '@testing-library/react'
|
||||||
import { describe, expect, it, vi } from 'vitest'
|
import { beforeEach, describe, expect, it, vi } from 'vitest'
|
||||||
|
|
||||||
import MaterialListPage from '@/pages/materials/MaterialListPage'
|
import MaterialListPage from '@/pages/materials/MaterialListPage'
|
||||||
import { buildMaterial, buildTag } from '@/test/factories'
|
import { buildMaterial, buildTag } from '@/test/factories'
|
||||||
@@ -12,51 +12,169 @@ const api = vi.hoisted (() => ({
|
|||||||
vi.mock ('@/lib/api', () => api)
|
vi.mock ('@/lib/api', () => api)
|
||||||
|
|
||||||
describe ('MaterialListPage', () => {
|
describe ('MaterialListPage', () => {
|
||||||
it ('shows the empty selection guide without a tag query', () => {
|
beforeEach (() => {
|
||||||
renderWithProviders (<MaterialListPage/>, { route: '/materials' })
|
vi.clearAllMocks ()
|
||||||
|
api.apiGet.mockResolvedValue ({ materials: [], count: 0 })
|
||||||
expect (screen.getByText ('左のリストから照会したいタグを選択してください。')).toBeInTheDocument ()
|
|
||||||
expect (screen.getByRole ('link', { name: '素材を新規追加する' })).toHaveAttribute (
|
|
||||||
'href',
|
|
||||||
'/materials/new',
|
|
||||||
)
|
|
||||||
})
|
})
|
||||||
|
|
||||||
it ('loads materials for a tag query', async () => {
|
it ('loads the material index on the initial page', async () => {
|
||||||
const tag = {
|
renderWithProviders (<MaterialListPage/>, { route: '/materials' })
|
||||||
...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 (() => {
|
await waitFor (() => {
|
||||||
expect (api.apiGet).toHaveBeenCalledWith (
|
expect (api.apiGet).toHaveBeenCalledWith (
|
||||||
'/tags/name/%E7%B4%A0%E6%9D%90/materials',
|
'/materials',
|
||||||
|
{ params: {
|
||||||
|
tag_state: 'all',
|
||||||
|
media_kind: 'all',
|
||||||
|
sort: 'created_at',
|
||||||
|
direction: 'desc',
|
||||||
|
page: 1,
|
||||||
|
limit: 20,
|
||||||
|
} },
|
||||||
)
|
)
|
||||||
})
|
})
|
||||||
expect (await screen.findByRole ('link', { name: '素材タグ' })).toBeInTheDocument ()
|
expect (await screen.findByText ('素材はありません。')).toBeInTheDocument ()
|
||||||
expect (screen.getByRole ('link', { name: '' })).toHaveAttribute ('href', '/materials/8')
|
|
||||||
})
|
})
|
||||||
|
|
||||||
it ('offers adding a missing non-meme material', async () => {
|
it ('shows materials in the default card view', async () => {
|
||||||
api.apiGet.mockResolvedValueOnce ({
|
api.apiGet.mockResolvedValueOnce ({
|
||||||
...buildTag ({ name: '未登録', category: 'material' }),
|
materials: [
|
||||||
material: null,
|
buildMaterial ({
|
||||||
children: [],
|
id: 8,
|
||||||
|
tag: buildTag ({ name: '素材タグ', category: 'material' }),
|
||||||
|
thumbnail: 'thumb.png',
|
||||||
|
mediaKind: 'image',
|
||||||
|
contentType: 'image/png',
|
||||||
|
}),
|
||||||
|
],
|
||||||
|
count: 1,
|
||||||
})
|
})
|
||||||
|
|
||||||
renderWithProviders (<MaterialListPage/>, { route: '/materials?tag=x' })
|
renderWithProviders (<MaterialListPage/>, { route: '/materials' })
|
||||||
|
|
||||||
expect (await screen.findByRole ('link', { name: '追加' })).toHaveAttribute (
|
expect ((await screen.findByText ('素材タグ')).closest ('a'))
|
||||||
|
.toHaveAttribute ('href', '/materials/8')
|
||||||
|
expect (screen.getByText (/画像 \/ 令和8年1月2日/)).toBeInTheDocument ()
|
||||||
|
})
|
||||||
|
|
||||||
|
it ('submits list filters as material index params', async () => {
|
||||||
|
renderWithProviders (<MaterialListPage/>, { route: '/materials' })
|
||||||
|
|
||||||
|
fireEvent.change (screen.getByPlaceholderText ('タグ名 / URL / ファイル名'), {
|
||||||
|
target: { value: '虹夏' },
|
||||||
|
})
|
||||||
|
const selects = screen.getAllByRole ('combobox')
|
||||||
|
fireEvent.change (selects[0], {
|
||||||
|
target: { value: 'untagged' },
|
||||||
|
})
|
||||||
|
fireEvent.change (selects[1], {
|
||||||
|
target: { value: 'image' },
|
||||||
|
})
|
||||||
|
fireEvent.click (screen.getByRole ('button', { name: '検索' }))
|
||||||
|
|
||||||
|
await waitFor (() => {
|
||||||
|
expect (api.apiGet).toHaveBeenCalledWith (
|
||||||
|
'/materials',
|
||||||
|
expect.objectContaining ({ params: expect.objectContaining ({
|
||||||
|
q: '虹夏',
|
||||||
|
tag_state: 'untagged',
|
||||||
|
media_kind: 'image',
|
||||||
|
}) }),
|
||||||
|
)
|
||||||
|
})
|
||||||
|
})
|
||||||
|
|
||||||
|
it ('keeps a route back to the material search top for untagged materials', async () => {
|
||||||
|
renderWithProviders (
|
||||||
|
<MaterialListPage/>,
|
||||||
|
{ route: '/materials?tag_state=untagged&material_filter=any' },
|
||||||
|
)
|
||||||
|
|
||||||
|
expect (await screen.findByRole (
|
||||||
|
'link',
|
||||||
|
{ name: '素材検索トップへ戻る' },
|
||||||
|
)).toHaveAttribute ('href', '/materials?material_filter=any')
|
||||||
|
})
|
||||||
|
|
||||||
|
it ('uses list view for detailed material rows', async () => {
|
||||||
|
api.apiGet.mockResolvedValueOnce ({
|
||||||
|
materials: [
|
||||||
|
buildMaterial ({
|
||||||
|
id: 9,
|
||||||
|
tag: buildTag ({ name: '詳細素材', category: 'material' }),
|
||||||
|
mediaKind: 'file_other',
|
||||||
|
fileByteSize: 2048,
|
||||||
|
}),
|
||||||
|
],
|
||||||
|
count: 1,
|
||||||
|
})
|
||||||
|
|
||||||
|
renderWithProviders (<MaterialListPage/>, { route: '/materials?view=list' })
|
||||||
|
|
||||||
|
expect (await screen.findByRole ('link', { name: '詳細素材' })).toHaveAttribute (
|
||||||
'href',
|
'href',
|
||||||
'/materials/new?tag=%E6%9C%AA%E7%99%BB%E9%8C%B2',
|
'/materials/9',
|
||||||
|
)
|
||||||
|
expect (screen.getByText ('サイズ:')).toBeInTheDocument ()
|
||||||
|
expect (screen.getByText ('2.0 KB')).toBeInTheDocument ()
|
||||||
|
})
|
||||||
|
|
||||||
|
it ('shows the selected tag scope and tag-specific add links', async () => {
|
||||||
|
api.apiGet.mockResolvedValueOnce ({
|
||||||
|
materials: [
|
||||||
|
buildMaterial ({
|
||||||
|
id: 10,
|
||||||
|
tag: buildTag ({ id: 30, name: '泣き', category: 'material' }),
|
||||||
|
}),
|
||||||
|
],
|
||||||
|
count: 1,
|
||||||
|
tagScope: {
|
||||||
|
tag: { id: 20, name: '伊地知ニジカ', category: 'material' },
|
||||||
|
includeDescendants: true,
|
||||||
|
},
|
||||||
|
groups: [
|
||||||
|
{
|
||||||
|
key: 'tag:30',
|
||||||
|
tag: { id: 30, name: '泣き', category: 'material' },
|
||||||
|
materialIds: [10],
|
||||||
|
count: 1,
|
||||||
|
},
|
||||||
|
],
|
||||||
|
})
|
||||||
|
|
||||||
|
renderWithProviders (
|
||||||
|
<MaterialListPage/>,
|
||||||
|
{ route: '/materials?tag_id=20&include_descendants=1&group_by=parent_tag' },
|
||||||
|
)
|
||||||
|
|
||||||
|
expect (await screen.findByText (
|
||||||
|
(_, element) => element?.textContent === '伊地知ニジカ 配下の素材を表示中',
|
||||||
|
)).toBeInTheDocument ()
|
||||||
|
|
||||||
|
expect (screen.getByRole ('link', { name: '泣き' })).toHaveAttribute (
|
||||||
|
'href',
|
||||||
|
'/materials?tag_id=30&include_descendants=1&group_by=parent_tag&material_filter=present',
|
||||||
|
)
|
||||||
|
expect (screen.getByRole ('link', { name: 'タグ選択を解除' })).toHaveAttribute (
|
||||||
|
'href',
|
||||||
|
'/materials?material_filter=present',
|
||||||
|
)
|
||||||
|
})
|
||||||
|
|
||||||
|
it ('shows a clear link when tag_id does not resolve to tag_scope', async () => {
|
||||||
|
api.apiGet.mockResolvedValueOnce ({
|
||||||
|
materials: [],
|
||||||
|
count: 0,
|
||||||
|
tagScope: null,
|
||||||
|
groups: [],
|
||||||
|
})
|
||||||
|
|
||||||
|
renderWithProviders (<MaterialListPage/>, { route: '/materials?tag_id=999' })
|
||||||
|
|
||||||
|
expect (await screen.findByText ('選択中タグが見つかりません.')).toBeInTheDocument ()
|
||||||
|
expect (screen.getByRole ('link', { name: 'タグ選択を解除' })).toHaveAttribute (
|
||||||
|
'href',
|
||||||
|
'/materials?material_filter=present',
|
||||||
)
|
)
|
||||||
})
|
})
|
||||||
})
|
})
|
||||||
|
|||||||
@@ -10,21 +10,23 @@ import FormField from '@/components/common/FormField'
|
|||||||
import PageTitle from '@/components/common/PageTitle'
|
import PageTitle from '@/components/common/PageTitle'
|
||||||
import Pagination from '@/components/common/Pagination'
|
import Pagination from '@/components/common/Pagination'
|
||||||
import MainArea from '@/components/layout/MainArea'
|
import MainArea from '@/components/layout/MainArea'
|
||||||
import { API_BASE_URL, SITE_TITLE } from '@/config'
|
import { SITE_TITLE } from '@/config'
|
||||||
import { fetchMaterials, parseMaterialFilter } from '@/lib/materials'
|
import { fetchMaterials, parseMaterialFilter } from '@/lib/materials'
|
||||||
import { materialsKeys } from '@/lib/queryKeys'
|
import { materialsKeys } from '@/lib/queryKeys'
|
||||||
import { dateString, inputClass } from '@/lib/utils'
|
import { dateString, inputClass } from '@/lib/utils'
|
||||||
|
|
||||||
import type { FC, FormEvent } from 'react'
|
import type { FC, FormEvent } from 'react'
|
||||||
|
|
||||||
import type {
|
import type { FetchMaterialsParams,
|
||||||
FetchMaterialsParams,
|
Material,
|
||||||
Material,
|
MaterialFilter,
|
||||||
MaterialIndexDirection,
|
MaterialIndexGroup,
|
||||||
MaterialIndexMediaKind,
|
MaterialIndexGroupBy,
|
||||||
MaterialIndexSort,
|
MaterialIndexDirection,
|
||||||
MaterialIndexTagState,
|
MaterialIndexMediaKind,
|
||||||
MaterialIndexView } from '@/types'
|
MaterialIndexSort,
|
||||||
|
MaterialIndexTagState,
|
||||||
|
MaterialIndexView } from '@/types'
|
||||||
|
|
||||||
const MEDIA_KIND_LABELS: Record<Material['mediaKind'], string> = {
|
const MEDIA_KIND_LABELS: Record<Material['mediaKind'], string> = {
|
||||||
image: '画像',
|
image: '画像',
|
||||||
@@ -39,16 +41,16 @@ const MEDIA_FILTER_LABELS: Record<MaterialIndexMediaKind, string> = {
|
|||||||
video: '動画',
|
video: '動画',
|
||||||
audio: '音声',
|
audio: '音声',
|
||||||
file_other: 'その他ファイル',
|
file_other: 'その他ファイル',
|
||||||
url_only: 'URL のみ'}
|
url_only: '外部リンクのみ'}
|
||||||
|
|
||||||
const SORT_LABELS: Record<MaterialIndexSort, string> = {
|
const SORT_LABELS: Record<MaterialIndexSort, string> = {
|
||||||
created_at: '作成日時',
|
created_at: '作成日時',
|
||||||
updated_at: '更新日時',
|
updated_at: '更新日時',
|
||||||
tag_name: 'タグ名',
|
tag_name: 'タグ名',
|
||||||
media_kind: '種類',
|
media_kind: '種類',
|
||||||
file_byte_size: 'ファイルサイズ',
|
file_byte_size: '容量',
|
||||||
version_no: 'バージョン',
|
version_no: '版',
|
||||||
id: 'ID'}
|
id: 'Id.'}
|
||||||
|
|
||||||
|
|
||||||
const setIf = (qs: URLSearchParams, key: string, value: string | null) => {
|
const setIf = (qs: URLSearchParams, key: string, value: string | null) => {
|
||||||
@@ -79,6 +81,36 @@ const materialTitle = (material: Material): string =>
|
|||||||
material.tag?.name ?? `素材 #${ material.id }`
|
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 }) => (
|
const MaterialThumb: FC<{ material: Material }> = ({ material }) => (
|
||||||
<div
|
<div
|
||||||
className={`flex aspect-square h-[180px] w-[180px] items-center justify-center
|
className={`flex aspect-square h-[180px] w-[180px] items-center justify-center
|
||||||
@@ -86,7 +118,7 @@ const MaterialThumb: FC<{ material: Material }> = ({ material }) => (
|
|||||||
text-stone-900 shadow-sm dark:border-stone-700 dark:bg-stone-900
|
text-stone-900 shadow-sm dark:border-stone-700 dark:bg-stone-900
|
||||||
dark:text-stone-100`}>
|
dark:text-stone-100`}>
|
||||||
{material.thumbnail
|
{material.thumbnail
|
||||||
? <img src={material.thumbnail} alt="" className="h-full w-full object-contain"/>
|
? <img src={material.thumbnail} alt="" className="block h-full w-full object-cover"/>
|
||||||
: (
|
: (
|
||||||
<span
|
<span
|
||||||
className="px-2 text-2xl leading-tight"
|
className="px-2 text-2xl leading-tight"
|
||||||
@@ -154,6 +186,28 @@ const MaterialListItem: FC<{ material: Material }> = ({ material }) => (
|
|||||||
</article>)
|
</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 MaterialListPage: FC = () => {
|
||||||
const location = useLocation ()
|
const location = useLocation ()
|
||||||
const navigate = useNavigate ()
|
const navigate = useNavigate ()
|
||||||
@@ -162,7 +216,10 @@ const MaterialListPage: FC = () => {
|
|||||||
|
|
||||||
const page = Number (query.get ('page') ?? 1)
|
const page = Number (query.get ('page') ?? 1)
|
||||||
const limit = Number (query.get ('limit') ?? 20)
|
const limit = Number (query.get ('limit') ?? 20)
|
||||||
const qQuery = query.get ('q') ?? query.get ('tag') ?? ''
|
const qQuery = query.get ('q') ?? ''
|
||||||
|
const tagIdQuery = Number (query.get ('tag_id') ?? 0)
|
||||||
|
const tagId = tagIdQuery > 0 ? tagIdQuery : null
|
||||||
|
const includeDescendants = query.get ('include_descendants') === '1'
|
||||||
const tagState = query.get ('unclassified') === '1'
|
const tagState = query.get ('unclassified') === '1'
|
||||||
? 'untagged'
|
? 'untagged'
|
||||||
: parseOption<MaterialIndexTagState> (
|
: parseOption<MaterialIndexTagState> (
|
||||||
@@ -182,6 +239,11 @@ const MaterialListPage: FC = () => {
|
|||||||
query.get ('direction'),
|
query.get ('direction'),
|
||||||
['asc', 'desc'],
|
['asc', 'desc'],
|
||||||
'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 view = parseOption<MaterialIndexView> (query.get ('view'), ['card', 'list'], 'card')
|
||||||
const createdFromQuery = query.get ('created_from') ?? ''
|
const createdFromQuery = query.get ('created_from') ?? ''
|
||||||
const createdToQuery = query.get ('created_to') ?? ''
|
const createdToQuery = query.get ('created_to') ?? ''
|
||||||
@@ -191,6 +253,7 @@ const MaterialListPage: FC = () => {
|
|||||||
const [q, setQ] = useState ('')
|
const [q, setQ] = useState ('')
|
||||||
const [tagStateInput, setTagStateInput] = useState<MaterialIndexTagState> ('all')
|
const [tagStateInput, setTagStateInput] = useState<MaterialIndexTagState> ('all')
|
||||||
const [mediaKindInput, setMediaKindInput] = useState<MaterialIndexMediaKind> ('all')
|
const [mediaKindInput, setMediaKindInput] = useState<MaterialIndexMediaKind> ('all')
|
||||||
|
const [groupByInput, setGroupByInput] = useState<MaterialIndexGroupBy> ('none')
|
||||||
const [createdFrom, setCreatedFrom] = useState<string | null> (null)
|
const [createdFrom, setCreatedFrom] = useState<string | null> (null)
|
||||||
const [createdTo, setCreatedTo] = useState<string | null> (null)
|
const [createdTo, setCreatedTo] = useState<string | null> (null)
|
||||||
const [updatedFrom, setUpdatedFrom] = useState<string | null> (null)
|
const [updatedFrom, setUpdatedFrom] = useState<string | null> (null)
|
||||||
@@ -200,6 +263,9 @@ const MaterialListPage: FC = () => {
|
|||||||
q: qQuery,
|
q: qQuery,
|
||||||
tagState,
|
tagState,
|
||||||
mediaKind,
|
mediaKind,
|
||||||
|
tagId,
|
||||||
|
includeDescendants,
|
||||||
|
groupBy,
|
||||||
createdFrom: createdFromQuery,
|
createdFrom: createdFromQuery,
|
||||||
createdTo: createdToQuery,
|
createdTo: createdToQuery,
|
||||||
updatedFrom: updatedFromQuery,
|
updatedFrom: updatedFromQuery,
|
||||||
@@ -212,18 +278,33 @@ const MaterialListPage: FC = () => {
|
|||||||
const { data, isLoading, isError } = useQuery ({
|
const { data, isLoading, isError } = useQuery ({
|
||||||
queryKey: materialsKeys.index (keys),
|
queryKey: materialsKeys.index (keys),
|
||||||
queryFn: () => fetchMaterials (keys)})
|
queryFn: () => fetchMaterials (keys)})
|
||||||
|
const tagScope = data?.tagScope ?? null
|
||||||
const materials = data?.materials ?? []
|
const materials = data?.materials ?? []
|
||||||
|
const groups = data?.groups ?? []
|
||||||
const totalPages = data ? Math.ceil (data.count / limit) : 0
|
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 (() => {
|
useEffect (() => {
|
||||||
setQ (qQuery)
|
setQ (qQuery)
|
||||||
setTagStateInput (tagState)
|
setTagStateInput (tagState)
|
||||||
setMediaKindInput (mediaKind)
|
setMediaKindInput (mediaKind)
|
||||||
|
setGroupByInput (groupBy)
|
||||||
setCreatedFrom (createdFromQuery)
|
setCreatedFrom (createdFromQuery)
|
||||||
setCreatedTo (createdToQuery)
|
setCreatedTo (createdToQuery)
|
||||||
setUpdatedFrom (updatedFromQuery)
|
setUpdatedFrom (updatedFromQuery)
|
||||||
setUpdatedTo (updatedToQuery)
|
setUpdatedTo (updatedToQuery)
|
||||||
}, [createdFromQuery, createdToQuery, mediaKind, qQuery, tagState,
|
}, [createdFromQuery, createdToQuery, groupBy, mediaKind, qQuery, tagState,
|
||||||
updatedFromQuery, updatedToQuery])
|
updatedFromQuery, updatedToQuery])
|
||||||
|
|
||||||
const search = (e: FormEvent) => {
|
const search = (e: FormEvent) => {
|
||||||
@@ -239,19 +320,77 @@ const MaterialListPage: FC = () => {
|
|||||||
setIf (qs, 'updated_to', updatedTo)
|
setIf (qs, 'updated_to', updatedTo)
|
||||||
qs.set ('sort', sort)
|
qs.set ('sort', sort)
|
||||||
qs.set ('direction', direction)
|
qs.set ('direction', direction)
|
||||||
|
qs.set ('group_by', tagId == null ? 'none' : groupByInput)
|
||||||
qs.set ('view', view)
|
qs.set ('view', view)
|
||||||
qs.set ('page', '1')
|
qs.set ('page', '1')
|
||||||
qs.set ('limit', String (limit))
|
qs.set ('limit', String (limit))
|
||||||
qs.set ('material_filter', materialFilter)
|
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 () }`)
|
navigate (`/materials?${ qs.toString () }`)
|
||||||
}
|
}
|
||||||
|
|
||||||
const updateQuery = (changes: Record<string, string>) => {
|
const updateQuery = (changes: Record<string, string>) => {
|
||||||
const qs = new URLSearchParams (location.search)
|
const qs = new URLSearchParams (location.search)
|
||||||
Object.entries (changes).forEach (([key, value]) => qs.set (key, value))
|
Object.entries (changes).forEach (([key, value]) => {
|
||||||
|
if (value === '')
|
||||||
|
qs.delete (key)
|
||||||
|
else
|
||||||
|
qs.set (key, value)
|
||||||
|
})
|
||||||
navigate (`/materials?${ qs.toString () }`)
|
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 (
|
return (
|
||||||
<MainArea>
|
<MainArea>
|
||||||
<Helmet>
|
<Helmet>
|
||||||
@@ -263,35 +402,15 @@ const MaterialListPage: FC = () => {
|
|||||||
src: url(${ nikumaru }) format('opentype');
|
src: url(${ nikumaru }) format('opentype');
|
||||||
}`}
|
}`}
|
||||||
</style>
|
</style>
|
||||||
<title>{`素材一覧 | ${ SITE_TITLE }`}</title>
|
<title>{`素材管理 | ${ SITE_TITLE }`}</title>
|
||||||
</Helmet>
|
</Helmet>
|
||||||
|
|
||||||
<div className="space-y-5">
|
<div className="space-y-5">
|
||||||
<div className="flex flex-wrap items-center justify-between gap-3">
|
<div className="flex flex-wrap items-center justify-between gap-3">
|
||||||
<PageTitle>素材一覧</PageTitle>
|
<PageTitle className="my-auto">素材管理</PageTitle>
|
||||||
<div className="flex flex-wrap gap-2">
|
<div className="flex flex-wrap gap-2">
|
||||||
<PrefetchLink
|
{/* TODO: 局所出力を可能にする */}
|
||||||
to="/materials/new"
|
{/* <a
|
||||||
className="rounded-full border border-stone-300 bg-white px-4 py-2 text-sm
|
|
||||||
text-stone-900 hover:bg-stone-100 dark:border-stone-700
|
|
||||||
dark:bg-stone-900 dark:text-stone-100 dark:hover:bg-stone-800">
|
|
||||||
新規素材を追加
|
|
||||||
</PrefetchLink>
|
|
||||||
<PrefetchLink
|
|
||||||
to="/materials/suppressions"
|
|
||||||
className="rounded-full border border-stone-300 bg-white px-4 py-2 text-sm
|
|
||||||
text-stone-900 hover:bg-stone-100 dark:border-stone-700
|
|
||||||
dark:bg-stone-900 dark:text-stone-100 dark:hover:bg-stone-800">
|
|
||||||
同期元抑止
|
|
||||||
</PrefetchLink>
|
|
||||||
<PrefetchLink
|
|
||||||
to="/materials/changes"
|
|
||||||
className="rounded-full border border-stone-300 bg-white px-4 py-2 text-sm
|
|
||||||
text-stone-900 hover:bg-stone-100 dark:border-stone-700
|
|
||||||
dark:bg-stone-900 dark:text-stone-100 dark:hover:bg-stone-800">
|
|
||||||
履歴
|
|
||||||
</PrefetchLink>
|
|
||||||
<a
|
|
||||||
href={`${ API_BASE_URL }/materials/download.zip?profile=legacy_drive`}
|
href={`${ API_BASE_URL }/materials/download.zip?profile=legacy_drive`}
|
||||||
target="_blank"
|
target="_blank"
|
||||||
rel="noopener noreferrer"
|
rel="noopener noreferrer"
|
||||||
@@ -299,10 +418,38 @@ const MaterialListPage: FC = () => {
|
|||||||
text-stone-900 hover:bg-stone-100 dark:border-stone-700
|
text-stone-900 hover:bg-stone-100 dark:border-stone-700
|
||||||
dark:bg-stone-900 dark:text-stone-100 dark:hover:bg-stone-800">
|
dark:bg-stone-900 dark:text-stone-100 dark:hover:bg-stone-800">
|
||||||
ZIP をダウンロード
|
ZIP をダウンロード
|
||||||
</a>
|
</a> */}
|
||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
|
{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' && (
|
{tagState === 'untagged' && (
|
||||||
<PrefetchLink
|
<PrefetchLink
|
||||||
to={`/materials?material_filter=${ materialFilter }`}
|
to={`/materials?material_filter=${ materialFilter }`}
|
||||||
@@ -395,7 +542,7 @@ const MaterialListPage: FC = () => {
|
|||||||
: [
|
: [
|
||||||
'border-stone-300 bg-white text-stone-900 dark:border-stone-700',
|
'border-stone-300 bg-white text-stone-900 dark:border-stone-700',
|
||||||
'dark:bg-stone-900 dark:text-stone-100'].join (' ') }`}>
|
'dark:bg-stone-900 dark:text-stone-100'].join (' ') }`}>
|
||||||
カード
|
アイコン
|
||||||
</button>
|
</button>
|
||||||
<button
|
<button
|
||||||
type="button"
|
type="button"
|
||||||
@@ -408,7 +555,7 @@ const MaterialListPage: FC = () => {
|
|||||||
: [
|
: [
|
||||||
'border-stone-300 bg-white text-stone-900 dark:border-stone-700',
|
'border-stone-300 bg-white text-stone-900 dark:border-stone-700',
|
||||||
'dark:bg-stone-900 dark:text-stone-100'].join (' ') }`}>
|
'dark:bg-stone-900 dark:text-stone-100'].join (' ') }`}>
|
||||||
一覧
|
詳細
|
||||||
</button>
|
</button>
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
@@ -436,20 +583,22 @@ const MaterialListPage: FC = () => {
|
|||||||
{isError && (
|
{isError && (
|
||||||
<p className="text-red-600 dark:text-red-300">素材一覧の取得に失敗しました.</p>)}
|
<p className="text-red-600 dark:text-red-300">素材一覧の取得に失敗しました.</p>)}
|
||||||
{(!isLoading && !isError && materials.length === 0) && (
|
{(!isLoading && !isError && materials.length === 0) && (
|
||||||
<p>素材はありません.</p>)}
|
<p>
|
||||||
|
素材はありません。
|
||||||
|
{(tagScope && ['character', 'material'].includes (tagScope.tag.category)) && (
|
||||||
|
<>
|
||||||
|
<PrefetchLink
|
||||||
|
to={materialNewPath (tagScope.tag.name, location.pathname + location.search)}
|
||||||
|
className="font-medium underline underline-offset-2
|
||||||
|
text-sky-700 dark:text-sky-300">
|
||||||
|
追加してください
|
||||||
|
</PrefetchLink>。
|
||||||
|
</>)}
|
||||||
|
</p>)}
|
||||||
{materials.length > 0 && (
|
{materials.length > 0 && (
|
||||||
view === 'card'
|
groupBy === 'parent_tag' && groups.length > 0
|
||||||
? (
|
? renderGroupedMaterials (groups)
|
||||||
<div className="grid grid-cols-[repeat(auto-fill,minmax(196px,1fr))]
|
: renderMaterialCollection (materials))}
|
||||||
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}/>
|
<Pagination page={page} totalPages={totalPages}/>
|
||||||
</div>
|
</div>
|
||||||
</MainArea>)
|
</MainArea>)
|
||||||
|
|||||||
@@ -1,5 +1,6 @@
|
|||||||
import { fireEvent, screen, waitFor } from '@testing-library/react'
|
import { fireEvent, screen, waitFor } from '@testing-library/react'
|
||||||
import { beforeEach, describe, expect, it, vi } from 'vitest'
|
import { beforeEach, describe, expect, it, vi } from 'vitest'
|
||||||
|
import { Route, Routes, useLocation } from 'react-router-dom'
|
||||||
|
|
||||||
import MaterialNewPage from '@/pages/materials/MaterialNewPage'
|
import MaterialNewPage from '@/pages/materials/MaterialNewPage'
|
||||||
import { renderWithProviders } from '@/test/render'
|
import { renderWithProviders } from '@/test/render'
|
||||||
@@ -17,6 +18,11 @@ const toastApi = vi.hoisted (() => ({
|
|||||||
vi.mock ('@/lib/api', () => api)
|
vi.mock ('@/lib/api', () => api)
|
||||||
vi.mock ('@/components/ui/use-toast', () => toastApi)
|
vi.mock ('@/components/ui/use-toast', () => toastApi)
|
||||||
|
|
||||||
|
const LocationView = () => {
|
||||||
|
const location = useLocation ()
|
||||||
|
return <div>{location.pathname + location.search}</div>
|
||||||
|
}
|
||||||
|
|
||||||
describe ('MaterialNewPage', () => {
|
describe ('MaterialNewPage', () => {
|
||||||
beforeEach (() => {
|
beforeEach (() => {
|
||||||
vi.clearAllMocks ()
|
vi.clearAllMocks ()
|
||||||
@@ -69,4 +75,50 @@ describe ('MaterialNewPage', () => {
|
|||||||
expect (await screen.findAllByText ('ファイルまたは URL は必須です.')).toHaveLength (2)
|
expect (await screen.findAllByText ('ファイルまたは URL は必須です.')).toHaveLength (2)
|
||||||
expect (screen.getAllByRole ('textbox')[1]).toHaveAttribute ('aria-invalid', 'true')
|
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,6 +27,8 @@ const MaterialNewPage: FC = () => {
|
|||||||
const location = useLocation ()
|
const location = useLocation ()
|
||||||
const query = new URLSearchParams (location.search)
|
const query = new URLSearchParams (location.search)
|
||||||
const tagQuery = query.get ('tag') ?? ''
|
const tagQuery = query.get ('tag') ?? ''
|
||||||
|
const returnToQuery = query.get ('return_to') ?? ''
|
||||||
|
const safeReturnTo = returnToQuery.startsWith ('/materials') ? returnToQuery : ''
|
||||||
|
|
||||||
const navigate = useNavigate ()
|
const navigate = useNavigate ()
|
||||||
|
|
||||||
@@ -54,7 +56,7 @@ const MaterialNewPage: FC = () => {
|
|||||||
onSuccess: async () => {
|
onSuccess: async () => {
|
||||||
await qc.invalidateQueries ({ queryKey: materialsKeys.root })
|
await qc.invalidateQueries ({ queryKey: materialsKeys.root })
|
||||||
toast ({ title: '送信成功!' })
|
toast ({ title: '送信成功!' })
|
||||||
navigate (`/materials?tag=${ encodeURIComponent (tag) }`)
|
navigate (safeReturnTo || '/materials')
|
||||||
},
|
},
|
||||||
onError: error => {
|
onError: error => {
|
||||||
applyValidationError (error)
|
applyValidationError (error)
|
||||||
|
|||||||
@@ -1,51 +0,0 @@
|
|||||||
import { useState } from 'react'
|
|
||||||
import { Helmet } from 'react-helmet-async'
|
|
||||||
|
|
||||||
import FormField from '@/components/common/FormField'
|
|
||||||
import PageTitle from '@/components/common/PageTitle'
|
|
||||||
import TagInput from '@/components/common/TagInput'
|
|
||||||
import MainArea from '@/components/layout/MainArea'
|
|
||||||
import { SITE_TITLE } from '@/config'
|
|
||||||
|
|
||||||
import type { FC, FormEvent } from 'react'
|
|
||||||
|
|
||||||
|
|
||||||
const MaterialSearchPage: FC = () => {
|
|
||||||
const [tagName, setTagName] = useState ('')
|
|
||||||
const [parentTagName, setParentTagName] = useState ('')
|
|
||||||
|
|
||||||
const handleSearch = (e: FormEvent) => {
|
|
||||||
e.preventDefault ()
|
|
||||||
}
|
|
||||||
|
|
||||||
return (
|
|
||||||
<MainArea>
|
|
||||||
<Helmet>
|
|
||||||
<title>素材集 | {SITE_TITLE}</title>
|
|
||||||
</Helmet>
|
|
||||||
|
|
||||||
<div className="max-w-xl">
|
|
||||||
<PageTitle>素材集</PageTitle>
|
|
||||||
|
|
||||||
<form onSubmit={handleSearch} className="space-y-2">
|
|
||||||
{/* タグ */}
|
|
||||||
<FormField label="タグ">
|
|
||||||
{() => (
|
|
||||||
<TagInput
|
|
||||||
value={tagName}
|
|
||||||
setValue={setTagName}/>)}
|
|
||||||
</FormField>
|
|
||||||
|
|
||||||
{/* 親タグ */}
|
|
||||||
<FormField label="親タグ">
|
|
||||||
{() => (
|
|
||||||
<TagInput
|
|
||||||
value={parentTagName}
|
|
||||||
setValue={setParentTagName}/>)}
|
|
||||||
</FormField>
|
|
||||||
</form>
|
|
||||||
</div>
|
|
||||||
</MainArea>)
|
|
||||||
}
|
|
||||||
|
|
||||||
export default MaterialSearchPage
|
|
||||||
@@ -2,17 +2,13 @@ import { useMutation, useQuery, useQueryClient } from '@tanstack/react-query'
|
|||||||
import { useState } from 'react'
|
import { useState } from 'react'
|
||||||
import { Helmet } from 'react-helmet-async'
|
import { Helmet } from 'react-helmet-async'
|
||||||
|
|
||||||
import PrefetchLink from '@/components/PrefetchLink'
|
|
||||||
import FormField from '@/components/common/FormField'
|
import FormField from '@/components/common/FormField'
|
||||||
import PageTitle from '@/components/common/PageTitle'
|
import PageTitle from '@/components/common/PageTitle'
|
||||||
import MainArea from '@/components/layout/MainArea'
|
import MainArea from '@/components/layout/MainArea'
|
||||||
import { Button } from '@/components/ui/button'
|
import { Button } from '@/components/ui/button'
|
||||||
import { toast } from '@/components/ui/use-toast'
|
import { toast } from '@/components/ui/use-toast'
|
||||||
import { SITE_TITLE } from '@/config'
|
import { SITE_TITLE } from '@/config'
|
||||||
import {
|
import { createMaterialSyncSuppression, fetchMaterialSyncSuppressions } from '@/lib/materials'
|
||||||
createMaterialSyncSuppression,
|
|
||||||
fetchMaterialSyncSuppressions,
|
|
||||||
} from '@/lib/materials'
|
|
||||||
import { materialsKeys } from '@/lib/queryKeys'
|
import { materialsKeys } from '@/lib/queryKeys'
|
||||||
import { dateString, inputClass } from '@/lib/utils'
|
import { dateString, inputClass } from '@/lib/utils'
|
||||||
|
|
||||||
@@ -22,11 +18,11 @@ import type { MaterialSyncSuppressionSourceKind } from '@/types'
|
|||||||
|
|
||||||
const SOURCE_KIND_LABELS: Record<MaterialSyncSuppressionSourceKind, string> = {
|
const SOURCE_KIND_LABELS: Record<MaterialSyncSuppressionSourceKind, string> = {
|
||||||
uri: 'URI',
|
uri: 'URI',
|
||||||
google_drive_path: 'Google Drive path',
|
google_drive_path: 'Google Drive ファイル',
|
||||||
google_drive_path_prefix: 'Google Drive path prefix',
|
google_drive_path_prefix: 'Google Drive フォルダ',
|
||||||
google_drive_file: 'Google Drive file ID',
|
google_drive_file: 'Google Drive ファイル Id.',
|
||||||
legacy_drive_path: 'Legacy Drive path',
|
legacy_drive_path: '汎用ファイル',
|
||||||
legacy_drive_path_prefix: 'Legacy Drive path prefix'}
|
legacy_drive_path_prefix: '汎用フォルダ' }
|
||||||
|
|
||||||
const REASONS = [
|
const REASONS = [
|
||||||
'copyright_high_risk',
|
'copyright_high_risk',
|
||||||
@@ -36,7 +32,23 @@ const REASONS = [
|
|||||||
'malware_or_dangerous_file',
|
'malware_or_dangerous_file',
|
||||||
'duplicate_or_low_quality',
|
'duplicate_or_low_quality',
|
||||||
'source_owner_request',
|
'source_owner_request',
|
||||||
'other']
|
'other'] as const
|
||||||
|
|
||||||
|
type MaterialSyncSuppressionReason = typeof REASONS[number]
|
||||||
|
|
||||||
|
const REASON_NAMES: Record<MaterialSyncSuppressionReason, string> = {
|
||||||
|
['copyright_high_risk']: '著作権への懸念',
|
||||||
|
['copyright_takedown']: '著作者からの申出',
|
||||||
|
['adult_or_sensitive']: '成人向け',
|
||||||
|
['personal_information']: '個人情報',
|
||||||
|
['malware_or_dangerous_file']: '危険なソフトウェア',
|
||||||
|
['duplicate_or_low_quality']: '重複',
|
||||||
|
['source_owner_request']: '同期元管理者からの申出',
|
||||||
|
['other']: 'その他' } as const
|
||||||
|
|
||||||
|
|
||||||
|
const reasonName = (reason: string): string =>
|
||||||
|
REASON_NAMES[reason as MaterialSyncSuppressionReason] ?? reason
|
||||||
|
|
||||||
|
|
||||||
const MaterialSyncSuppressionsPage: FC = () => {
|
const MaterialSyncSuppressionsPage: FC = () => {
|
||||||
@@ -46,7 +58,7 @@ const MaterialSyncSuppressionsPage: FC = () => {
|
|||||||
const [sourceUri, setSourceUri] = useState ('')
|
const [sourceUri, setSourceUri] = useState ('')
|
||||||
const [drivePath, setDrivePath] = useState ('')
|
const [drivePath, setDrivePath] = useState ('')
|
||||||
const [driveFileId, setDriveFileId] = useState ('')
|
const [driveFileId, setDriveFileId] = useState ('')
|
||||||
const [reason, setReason] = useState (REASONS[0])
|
const [reason, setReason] = useState<MaterialSyncSuppressionReason> (REASONS[0])
|
||||||
|
|
||||||
const { data, isError, isLoading } = useQuery ({
|
const { data, isError, isLoading } = useQuery ({
|
||||||
queryKey: materialsKeys.suppressions (),
|
queryKey: materialsKeys.suppressions (),
|
||||||
@@ -82,18 +94,11 @@ const MaterialSyncSuppressionsPage: FC = () => {
|
|||||||
return (
|
return (
|
||||||
<MainArea>
|
<MainArea>
|
||||||
<Helmet>
|
<Helmet>
|
||||||
<title>{`同期元抑止 | ${ SITE_TITLE }`}</title>
|
<title>{`素材同期抑止 | ${ SITE_TITLE }`}</title>
|
||||||
</Helmet>
|
</Helmet>
|
||||||
|
|
||||||
<div className="space-y-5">
|
<div className="space-y-5">
|
||||||
<div className="flex flex-wrap items-center justify-between gap-3">
|
<PageTitle>同期抑止</PageTitle>
|
||||||
<PageTitle>同期元抑止</PageTitle>
|
|
||||||
<PrefetchLink
|
|
||||||
to="/materials"
|
|
||||||
className="text-sm text-sky-700 underline underline-offset-2 dark:text-sky-300">
|
|
||||||
素材一覧へ戻る
|
|
||||||
</PrefetchLink>
|
|
||||||
</div>
|
|
||||||
|
|
||||||
<form
|
<form
|
||||||
onSubmit={handleSubmit}
|
onSubmit={handleSubmit}
|
||||||
@@ -115,7 +120,7 @@ const MaterialSyncSuppressionsPage: FC = () => {
|
|||||||
</select>)}
|
</select>)}
|
||||||
</FormField>
|
</FormField>
|
||||||
|
|
||||||
<FormField label="Source URI">
|
<FormField label="同期元 URI">
|
||||||
{({ invalid }) => (
|
{({ invalid }) => (
|
||||||
<input
|
<input
|
||||||
type="text"
|
type="text"
|
||||||
@@ -124,7 +129,7 @@ const MaterialSyncSuppressionsPage: FC = () => {
|
|||||||
className={inputClass (invalid)}/>)}
|
className={inputClass (invalid)}/>)}
|
||||||
</FormField>
|
</FormField>
|
||||||
|
|
||||||
<FormField label="Drive path">
|
<FormField label="Google Drive パス">
|
||||||
{({ invalid }) => (
|
{({ invalid }) => (
|
||||||
<input
|
<input
|
||||||
type="text"
|
type="text"
|
||||||
@@ -133,7 +138,7 @@ const MaterialSyncSuppressionsPage: FC = () => {
|
|||||||
className={inputClass (invalid)}/>)}
|
className={inputClass (invalid)}/>)}
|
||||||
</FormField>
|
</FormField>
|
||||||
|
|
||||||
<FormField label="Drive file ID">
|
<FormField label="Google Drive ファイル Id.">
|
||||||
{({ invalid }) => (
|
{({ invalid }) => (
|
||||||
<input
|
<input
|
||||||
type="text"
|
type="text"
|
||||||
@@ -142,15 +147,15 @@ const MaterialSyncSuppressionsPage: FC = () => {
|
|||||||
className={inputClass (invalid)}/>)}
|
className={inputClass (invalid)}/>)}
|
||||||
</FormField>
|
</FormField>
|
||||||
|
|
||||||
<FormField label="理由">
|
<FormField label="事由">
|
||||||
{({ invalid }) => (
|
{({ invalid }) => (
|
||||||
<select
|
<select
|
||||||
value={reason}
|
value={reason}
|
||||||
onChange={e => setReason (e.target.value)}
|
onChange={e => setReason (e.target.value as MaterialSyncSuppressionReason)}
|
||||||
className={inputClass (invalid)}>
|
className={inputClass (invalid)}>
|
||||||
{REASONS.map (value => (
|
{REASONS.map (value => (
|
||||||
<option key={value} value={value}>
|
<option key={value} value={value}>
|
||||||
{value}
|
{REASON_NAMES[value]}
|
||||||
</option>))}
|
</option>))}
|
||||||
</select>)}
|
</select>)}
|
||||||
</FormField>
|
</FormField>
|
||||||
@@ -185,7 +190,8 @@ const MaterialSyncSuppressionsPage: FC = () => {
|
|||||||
{suppression.normalizedSourceKey}
|
{suppression.normalizedSourceKey}
|
||||||
</div>
|
</div>
|
||||||
<div className="mt-2 text-sm text-stone-600 dark:text-stone-400">
|
<div className="mt-2 text-sm text-stone-600 dark:text-stone-400">
|
||||||
理由: {suppression.reason} / 登録: {dateString (suppression.createdAt)}
|
事由: {reasonName (suppression.reason)} /
|
||||||
|
登録: {dateString (suppression.createdAt)}
|
||||||
</div>
|
</div>
|
||||||
</article>))}
|
</article>))}
|
||||||
</div>
|
</div>
|
||||||
|
|||||||
@@ -92,16 +92,16 @@ const PostDetailPage: FC<Props> = ({ user }) => {
|
|||||||
: 'bg-gray-500 hover:bg-gray-600')
|
: 'bg-gray-500 hover:bg-gray-600')
|
||||||
|
|
||||||
return (
|
return (
|
||||||
<div className="md:flex md:flex-1 overflow-y-auto md:overflow-y-hidden">
|
<div
|
||||||
|
data-sidebar-container
|
||||||
|
className="md:flex md:flex-1 overflow-y-auto md:overflow-y-hidden">
|
||||||
<Helmet>
|
<Helmet>
|
||||||
{(post?.thumbnail || post?.thumbnailBase) && (
|
{(post?.thumbnail || post?.thumbnailBase) && (
|
||||||
<meta name="thumbnail" content={post.thumbnail! || post.thumbnailBase!}/>)}
|
<meta name="thumbnail" content={post.thumbnail! || post.thumbnailBase!}/>)}
|
||||||
{post && <title>{`${ post.title || post.url } | ${ SITE_TITLE }`}</title>}
|
{post && <title>{`${ post.title || post.url } | ${ SITE_TITLE }`}</title>}
|
||||||
</Helmet>
|
</Helmet>
|
||||||
|
|
||||||
<div className="hidden md:block">
|
{post && <TagDetailSidebar post={post} className="hidden md:block"/>}
|
||||||
{post && <TagDetailSidebar post={post}/>}
|
|
||||||
</div>
|
|
||||||
|
|
||||||
<MainArea className="relative">
|
<MainArea className="relative">
|
||||||
{post
|
{post
|
||||||
@@ -179,9 +179,7 @@ const PostDetailPage: FC<Props> = ({ user }) => {
|
|||||||
: 'Loading...'}
|
: 'Loading...'}
|
||||||
</MainArea>
|
</MainArea>
|
||||||
|
|
||||||
<div className="md:hidden">
|
{post && <TagDetailSidebar post={post} sp className="md:hidden"/>}
|
||||||
{post && <TagDetailSidebar post={post} sp/>}
|
|
||||||
</div>
|
|
||||||
</div>)
|
</div>)
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@@ -91,9 +91,13 @@ const PostHistoryPage: FC = () => {
|
|||||||
.filter (p => p.type !== 'removed')
|
.filter (p => p.type !== 'removed')
|
||||||
.map (p => p.id)
|
.map (p => p.id)
|
||||||
.join (' ')
|
.join (' ')
|
||||||
|
const duration =
|
||||||
|
change.videoMs.current == null
|
||||||
|
? null
|
||||||
|
: String (change.videoMs.current / 1_000)
|
||||||
const originalCreatedFrom = change.originalCreatedFrom.current
|
const originalCreatedFrom = change.originalCreatedFrom.current
|
||||||
const originalCreatedBefore = change.originalCreatedBefore.current
|
const originalCreatedBefore = change.originalCreatedBefore.current
|
||||||
await updatePost ({ id, title, tags, parentPostIds,
|
await updatePost ({ id, title, tags, duration, parentPostIds,
|
||||||
originalCreatedFrom, originalCreatedBefore },
|
originalCreatedFrom, originalCreatedBefore },
|
||||||
{ force: true })
|
{ force: true })
|
||||||
|
|
||||||
|
|||||||
@@ -70,6 +70,7 @@ const PostListPage: FC = () => {
|
|||||||
|
|
||||||
return (
|
return (
|
||||||
<div
|
<div
|
||||||
|
data-sidebar-container
|
||||||
className="md:flex md:flex-1 overflow-y-auto md:overflow-y-hidden"
|
className="md:flex md:flex-1 overflow-y-auto md:overflow-y-hidden"
|
||||||
ref={containerRef}>
|
ref={containerRef}>
|
||||||
<Helmet>
|
<Helmet>
|
||||||
|
|||||||
@@ -62,6 +62,24 @@ describe ('PostNewPage', () => {
|
|||||||
expect (toastApi.toast).toHaveBeenCalledWith ({ title: '投稿成功!' })
|
expect (toastApi.toast).toHaveBeenCalledWith ({ title: '投稿成功!' })
|
||||||
})
|
})
|
||||||
|
|
||||||
|
it ('preserves duration while the video tag is temporarily removed', () => {
|
||||||
|
api.apiGet.mockResolvedValue ([])
|
||||||
|
|
||||||
|
renderWithProviders (<PostNewPage user={buildUser ({ role: 'member' })}/>)
|
||||||
|
|
||||||
|
const tags = screen.getAllByRole ('textbox')[3]
|
||||||
|
fireEvent.change (tags, { target: { value: '動画' } })
|
||||||
|
fireEvent.change (screen.getByRole ('spinbutton'), { target: { value: '180.5' } })
|
||||||
|
|
||||||
|
fireEvent.change (tags, { target: { value: 'general-tag' } })
|
||||||
|
expect (screen.queryByRole ('spinbutton')).not.toBeInTheDocument ()
|
||||||
|
|
||||||
|
fireEvent.change (tags, {
|
||||||
|
target: { value: '動画 general-tag' },
|
||||||
|
})
|
||||||
|
expect (screen.getByRole ('spinbutton')).toHaveValue (180.5)
|
||||||
|
})
|
||||||
|
|
||||||
it ('shows 422 validation errors for post fields', async () => {
|
it ('shows 422 validation errors for post fields', async () => {
|
||||||
api.apiGet.mockResolvedValue ([])
|
api.apiGet.mockResolvedValue ([])
|
||||||
api.isApiError.mockReturnValue (true)
|
api.isApiError.mockReturnValue (true)
|
||||||
|
|||||||
@@ -1,4 +1,4 @@
|
|||||||
import { useCallback, useEffect, useState, useRef } from 'react'
|
import { useCallback, useEffect, useMemo, useRef, useState } from 'react'
|
||||||
import { Helmet } from 'react-helmet-async'
|
import { Helmet } from 'react-helmet-async'
|
||||||
import { useNavigate } from 'react-router-dom'
|
import { useNavigate } from 'react-router-dom'
|
||||||
|
|
||||||
@@ -25,7 +25,7 @@ import type { User } from '@/types'
|
|||||||
type Props = { user: User | null }
|
type Props = { user: User | null }
|
||||||
|
|
||||||
type PostFormField =
|
type PostFormField =
|
||||||
'url' | 'title' | 'tags' | 'parentPostIds' | 'originalCreatedAt' | 'thumbnail'
|
'url' | 'title' | 'tags' | 'parentPostIds' | 'videoMs' | 'originalCreatedAt' | 'thumbnail'
|
||||||
|
|
||||||
|
|
||||||
const PostNewPage: FC<Props> = ({ user }) => {
|
const PostNewPage: FC<Props> = ({ user }) => {
|
||||||
@@ -40,6 +40,7 @@ const PostNewPage: FC<Props> = ({ user }) => {
|
|||||||
const [originalCreatedFrom, setOriginalCreatedFrom] = useState<string | null> (null)
|
const [originalCreatedFrom, setOriginalCreatedFrom] = useState<string | null> (null)
|
||||||
const [parentPostIds, setParentPostIds] = useState ('')
|
const [parentPostIds, setParentPostIds] = useState ('')
|
||||||
const [tags, setTags] = useState ('')
|
const [tags, setTags] = useState ('')
|
||||||
|
const [duration, setDuration] = useState ('')
|
||||||
const [thumbnailAutoFlg, setThumbnailAutoFlg] = useState (true)
|
const [thumbnailAutoFlg, setThumbnailAutoFlg] = useState (true)
|
||||||
const [thumbnailFile, setThumbnailFile] = useState<File | null> (null)
|
const [thumbnailFile, setThumbnailFile] = useState<File | null> (null)
|
||||||
const [thumbnailLoading, setThumbnailLoading] = useState (false)
|
const [thumbnailLoading, setThumbnailLoading] = useState (false)
|
||||||
@@ -51,6 +52,9 @@ const PostNewPage: FC<Props> = ({ user }) => {
|
|||||||
|
|
||||||
const previousURLRef = useRef ('')
|
const previousURLRef = useRef ('')
|
||||||
const thumbnailPreviewRef = useRef ('')
|
const thumbnailPreviewRef = useRef ('')
|
||||||
|
const videoFlg =
|
||||||
|
useMemo (() => tags.split (/\s+/).some (tag => tag.replace (/\[.*\]$/, '') === '動画'),
|
||||||
|
[tags])
|
||||||
|
|
||||||
const handleSubmit = async () => {
|
const handleSubmit = async () => {
|
||||||
clearValidationErrors ()
|
clearValidationErrors ()
|
||||||
@@ -60,6 +64,8 @@ const PostNewPage: FC<Props> = ({ user }) => {
|
|||||||
formData.append ('url', url)
|
formData.append ('url', url)
|
||||||
formData.append ('tags', tags)
|
formData.append ('tags', tags)
|
||||||
formData.append ('parent_post_ids', parentPostIds)
|
formData.append ('parent_post_ids', parentPostIds)
|
||||||
|
if (videoFlg && duration !== '')
|
||||||
|
formData.append ('duration', duration)
|
||||||
if (thumbnailFile)
|
if (thumbnailFile)
|
||||||
formData.append ('thumbnail', thumbnailFile)
|
formData.append ('thumbnail', thumbnailFile)
|
||||||
if (originalCreatedFrom)
|
if (originalCreatedFrom)
|
||||||
@@ -233,6 +239,20 @@ const PostNewPage: FC<Props> = ({ user }) => {
|
|||||||
setOriginalCreatedBefore={setOriginalCreatedBefore}
|
setOriginalCreatedBefore={setOriginalCreatedBefore}
|
||||||
errors={fieldErrors.originalCreatedAt}/>
|
errors={fieldErrors.originalCreatedAt}/>
|
||||||
|
|
||||||
|
{/* 動画時間 */}
|
||||||
|
{(videoFlg &&
|
||||||
|
<FormField label="動画時間" messages={fieldErrors.videoMs}>
|
||||||
|
{({ invalid }) => (
|
||||||
|
<input
|
||||||
|
type="number"
|
||||||
|
min="0.001"
|
||||||
|
step="0.001"
|
||||||
|
value={duration}
|
||||||
|
onChange={e => setDuration (e.target.value)}
|
||||||
|
aria-invalid={invalid}
|
||||||
|
className={inputClass (invalid)}/>)}
|
||||||
|
</FormField>)}
|
||||||
|
|
||||||
{/* 送信 */}
|
{/* 送信 */}
|
||||||
<Button onClick={handleSubmit}
|
<Button onClick={handleSubmit}
|
||||||
className="px-4 py-2 bg-blue-600 text-white rounded disabled:bg-gray-400"
|
className="px-4 py-2 bg-blue-600 text-white rounded disabled:bg-gray-400"
|
||||||
|
|||||||
@@ -1,9 +1,10 @@
|
|||||||
import { act, fireEvent, screen, waitFor } from '@testing-library/react'
|
import { act, fireEvent, screen, waitFor, within } from '@testing-library/react'
|
||||||
import { Route, Routes } from 'react-router-dom'
|
import { Route, Routes } from 'react-router-dom'
|
||||||
import { beforeEach, describe, expect, it, vi } from 'vitest'
|
import { beforeEach, describe, expect, it, vi } from 'vitest'
|
||||||
|
|
||||||
import TheatreDetailPage from '@/pages/theatres/TheatreDetailPage'
|
import TheatreDetailPage from '@/pages/theatres/TheatreDetailPage'
|
||||||
import { buildPost,
|
import { buildPost,
|
||||||
|
buildTag,
|
||||||
buildTheatre,
|
buildTheatre,
|
||||||
buildTheatreComment,
|
buildTheatreComment,
|
||||||
buildTheatreInfo,
|
buildTheatreInfo,
|
||||||
@@ -87,6 +88,10 @@ const weights = buildTheatrePostSelectionWeights ({
|
|||||||
tags: [],
|
tags: [],
|
||||||
}],
|
}],
|
||||||
})
|
})
|
||||||
|
const watchingUsers = [
|
||||||
|
{ id: 1, name: 'tester' },
|
||||||
|
{ id: 2, name: 'another' },
|
||||||
|
]
|
||||||
|
|
||||||
const renderPage = (user = buildUser ({ id: 1, role: 'member' })) =>
|
const renderPage = (user = buildUser ({ id: 1, role: 'member' })) =>
|
||||||
renderWithProviders (
|
renderWithProviders (
|
||||||
@@ -96,7 +101,24 @@ const renderPage = (user = buildUser ({ id: 1, role: 'member' })) =>
|
|||||||
{ route: '/theatres/7' },
|
{ route: '/theatres/7' },
|
||||||
)
|
)
|
||||||
|
|
||||||
|
const tagSection = (): HTMLElement =>
|
||||||
|
screen.getAllByRole ('heading', { name: 'タグ' })[0].closest ('section')!
|
||||||
|
|
||||||
const mockDefaultApi = () => {
|
const mockDefaultApi = () => {
|
||||||
|
let commentsFetched = false
|
||||||
|
let currentTheatreInfo = buildTheatreInfo ({
|
||||||
|
postId: currentPost.id,
|
||||||
|
postStartedAt: '2026-01-02T03:04:05.000Z',
|
||||||
|
postElapsedMs: 1_000,
|
||||||
|
watchingUsers,
|
||||||
|
skipVote: {
|
||||||
|
votesCount: 0,
|
||||||
|
requiredCount: 2,
|
||||||
|
watchingUsersCount: watchingUsers.length,
|
||||||
|
voted: false,
|
||||||
|
},
|
||||||
|
})
|
||||||
|
|
||||||
api.apiGet.mockImplementation ((path: string) => {
|
api.apiGet.mockImplementation ((path: string) => {
|
||||||
switch (path)
|
switch (path)
|
||||||
{
|
{
|
||||||
@@ -104,13 +126,17 @@ const mockDefaultApi = () => {
|
|||||||
return Promise.resolve (theatre)
|
return Promise.resolve (theatre)
|
||||||
|
|
||||||
case '/theatres/7/comments':
|
case '/theatres/7/comments':
|
||||||
|
if (commentsFetched)
|
||||||
|
return Promise.resolve ([])
|
||||||
|
|
||||||
|
commentsFetched = true
|
||||||
return Promise.resolve ([
|
return Promise.resolve ([
|
||||||
buildTheatreComment ({
|
buildTheatreComment ({
|
||||||
theatreId: 7,
|
theatreId: 7,
|
||||||
no: 2,
|
no: 2,
|
||||||
user: { id: 1, name: 'tester' },
|
user: { id: 1, name: 'tester' },
|
||||||
content: '視聴コメント',
|
content: '視聴コメント',
|
||||||
}),
|
}),
|
||||||
])
|
])
|
||||||
|
|
||||||
case '/theatres/7/programmes':
|
case '/theatres/7/programmes':
|
||||||
@@ -128,32 +154,22 @@ const mockDefaultApi = () => {
|
|||||||
switch (path)
|
switch (path)
|
||||||
{
|
{
|
||||||
case '/theatres/7/watching':
|
case '/theatres/7/watching':
|
||||||
return Promise.resolve (buildTheatreInfo ({
|
return Promise.resolve (currentTheatreInfo)
|
||||||
postId: currentPost.id,
|
|
||||||
postStartedAt: '2026-01-02T03:04:05.000Z',
|
|
||||||
postElapsedMs: 1_000,
|
|
||||||
watchingUsers: [{ id: 1, name: 'tester' }],
|
|
||||||
skipVote: {
|
|
||||||
votesCount: 0,
|
|
||||||
requiredCount: 2,
|
|
||||||
watchingUsersCount: 1,
|
|
||||||
voted: false,
|
|
||||||
},
|
|
||||||
}))
|
|
||||||
|
|
||||||
case '/theatres/7/skip_vote':
|
case '/theatres/7/skip_vote':
|
||||||
return Promise.resolve (buildTheatreInfo ({
|
currentTheatreInfo = buildTheatreInfo ({
|
||||||
postId: currentPost.id,
|
postId: currentPost.id,
|
||||||
postStartedAt: '2026-01-02T03:04:05.000Z',
|
postStartedAt: '2026-01-02T03:04:05.000Z',
|
||||||
postElapsedMs: 2_000,
|
postElapsedMs: 2_000,
|
||||||
watchingUsers: [{ id: 1, name: 'tester' }],
|
watchingUsers,
|
||||||
skipVote: {
|
skipVote: {
|
||||||
votesCount: 1,
|
votesCount: 1,
|
||||||
requiredCount: 2,
|
requiredCount: 2,
|
||||||
watchingUsersCount: 1,
|
watchingUsersCount: watchingUsers.length,
|
||||||
voted: true,
|
voted: true,
|
||||||
},
|
},
|
||||||
}))
|
})
|
||||||
|
return Promise.resolve (currentTheatreInfo)
|
||||||
|
|
||||||
default:
|
default:
|
||||||
return Promise.reject (new Error (`Unexpected PUT ${ path }`))
|
return Promise.reject (new Error (`Unexpected PUT ${ path }`))
|
||||||
@@ -245,6 +261,53 @@ describe ('TheatreDetailPage', () => {
|
|||||||
expect (postEmbed.seek).not.toHaveBeenCalledWith (0)
|
expect (postEmbed.seek).not.toHaveBeenCalledWith (0)
|
||||||
})
|
})
|
||||||
|
|
||||||
|
it ('shows child tags from the post tag tree in both vertical and horizontal layouts', async () => {
|
||||||
|
const childTag = buildTag ({ id: 12, name: '子タグ', category: 'general' })
|
||||||
|
const parentTag = buildTag ({
|
||||||
|
id: 11,
|
||||||
|
name: '親タグ',
|
||||||
|
category: 'general',
|
||||||
|
children: [childTag],
|
||||||
|
})
|
||||||
|
const duplicateParentTag = buildTag ({
|
||||||
|
id: 13,
|
||||||
|
name: '別親タグ',
|
||||||
|
category: 'general',
|
||||||
|
children: [childTag],
|
||||||
|
})
|
||||||
|
|
||||||
|
postsApi.fetchPost.mockResolvedValueOnce (buildPost ({
|
||||||
|
...currentPost,
|
||||||
|
tags: [parentTag, duplicateParentTag],
|
||||||
|
}))
|
||||||
|
|
||||||
|
renderPage ()
|
||||||
|
|
||||||
|
await screen.findByText ('Embed:上映中の投稿')
|
||||||
|
|
||||||
|
expect (within (tagSection ()).getByRole ('link', { name: '親タグ' }))
|
||||||
|
.toBeInTheDocument ()
|
||||||
|
expect (within (tagSection ()).getByRole ('link', { name: '別親タグ' }))
|
||||||
|
.toBeInTheDocument ()
|
||||||
|
expect (within (tagSection ()).getAllByRole ('link', { name: '子タグ' })[0])
|
||||||
|
.toBeInTheDocument ()
|
||||||
|
expect (within (tagSection ()).getAllByText ('↳').length).toBeGreaterThan (0)
|
||||||
|
|
||||||
|
fireEvent.click (screen.getByRole ('button', { name: '2 列 A 型' }))
|
||||||
|
fireEvent.click (screen.getAllByRole ('button', { name: '横並び' })[0])
|
||||||
|
|
||||||
|
await waitFor (() => {
|
||||||
|
expect (within (tagSection ()).getByRole ('link', { name: '親タグ' }))
|
||||||
|
.toBeInTheDocument ()
|
||||||
|
expect (within (tagSection ()).getByRole ('link', { name: '別親タグ' }))
|
||||||
|
.toBeInTheDocument ()
|
||||||
|
expect (within (tagSection ()).getByRole ('link', { name: '子タグ' }))
|
||||||
|
.toBeInTheDocument ()
|
||||||
|
expect (within (tagSection ()).getAllByRole ('link', { name: '子タグ' }))
|
||||||
|
.toHaveLength (1)
|
||||||
|
})
|
||||||
|
})
|
||||||
|
|
||||||
it ('does not advance host post while video length is unknown', async () => {
|
it ('does not advance host post while video length is unknown', async () => {
|
||||||
api.apiPut.mockImplementation ((path: string) => {
|
api.apiPut.mockImplementation ((path: string) => {
|
||||||
switch (path)
|
switch (path)
|
||||||
|
|||||||
@@ -10,6 +10,7 @@ import PrefetchLink from '@/components/PrefetchLink'
|
|||||||
import TagLink from '@/components/TagLink'
|
import TagLink from '@/components/TagLink'
|
||||||
import FieldError from '@/components/common/FieldError'
|
import FieldError from '@/components/common/FieldError'
|
||||||
import { useDialogue } from '@/components/dialogues/DialogueProvider'
|
import { useDialogue } from '@/components/dialogues/DialogueProvider'
|
||||||
|
import SidebarComponent from '@/components/layout/SidebarComponent'
|
||||||
import { Button } from '@/components/ui/button'
|
import { Button } from '@/components/ui/button'
|
||||||
import { SITE_TITLE } from '@/config'
|
import { SITE_TITLE } from '@/config'
|
||||||
import { CATEGORIES, CATEGORY_NAMES } from '@/consts'
|
import { CATEGORIES, CATEGORY_NAMES } from '@/consts'
|
||||||
@@ -52,6 +53,8 @@ const INITIAL_WEIGHTS: TheatrePostSelectionWeights =
|
|||||||
|
|
||||||
const LAYOUT_STORAGE_KEY = 'theatre-layout-mode'
|
const LAYOUT_STORAGE_KEY = 'theatre-layout-mode'
|
||||||
const TAG_FLOW_STORAGE_KEY = 'theatre-tag-flow'
|
const TAG_FLOW_STORAGE_KEY = 'theatre-tag-flow'
|
||||||
|
const MIN_MAIN_WIDTH = 360
|
||||||
|
const SIDEBAR_GAP_WIDTH = 16
|
||||||
|
|
||||||
const LAYOUT_LABELS: Record<TheatreLayoutMode, string> = {
|
const LAYOUT_LABELS: Record<TheatreLayoutMode, string> = {
|
||||||
threeColumns: '3 列',
|
threeColumns: '3 列',
|
||||||
@@ -102,6 +105,28 @@ const compareTagName = (a: Tag, b: Tag): number =>
|
|||||||
a.name === b.name ? 0 : (a.name < b.name ? -1 : 1)
|
a.name === b.name ? 0 : (a.name < b.name ? -1 : 1)
|
||||||
|
|
||||||
|
|
||||||
|
const flattenTags = (tags: Tag[]): Tag[] => {
|
||||||
|
const flattened: Tag[] = []
|
||||||
|
const seen = new Set<number> ()
|
||||||
|
|
||||||
|
const visit = (tag: Tag) => {
|
||||||
|
if (seen.has (tag.id))
|
||||||
|
return
|
||||||
|
|
||||||
|
seen.add (tag.id)
|
||||||
|
flattened.push (tag)
|
||||||
|
|
||||||
|
for (const child of tag.children ?? [])
|
||||||
|
visit (child)
|
||||||
|
}
|
||||||
|
|
||||||
|
for (const tag of tags)
|
||||||
|
visit (tag)
|
||||||
|
|
||||||
|
return flattened
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
const tagsByCategory = (tags: Tag[]): Partial<Record<Category, Tag[]>> => {
|
const tagsByCategory = (tags: Tag[]): Partial<Record<Category, Tag[]>> => {
|
||||||
const grouped: Partial<Record<Category, Tag[]>> = { }
|
const grouped: Partial<Record<Category, Tag[]>> = { }
|
||||||
|
|
||||||
@@ -118,15 +143,39 @@ const tagsByCategory = (tags: Tag[]): Partial<Record<Category, Tag[]>> => {
|
|||||||
}
|
}
|
||||||
|
|
||||||
|
|
||||||
|
const renderReadonlyTagTree = (
|
||||||
|
tag: Tag,
|
||||||
|
nestLevel: number,
|
||||||
|
path: string,
|
||||||
|
ancestors: Set<number> = new Set<number> (),
|
||||||
|
): ReactNode[] => {
|
||||||
|
const key = `${ path }-${ tag.id }`
|
||||||
|
const nextAncestors = new Set (ancestors)
|
||||||
|
nextAncestors.add (tag.id)
|
||||||
|
|
||||||
|
return [
|
||||||
|
(
|
||||||
|
<li key={key} className="text-left leading-tight">
|
||||||
|
<TagLink tag={tag} nestLevel={nestLevel} withCount={false}/>
|
||||||
|
</li>),
|
||||||
|
...((tag.children ?? [])
|
||||||
|
.filter (child => !(nextAncestors.has (child.id)))
|
||||||
|
.sort (compareTagName)
|
||||||
|
.flatMap (child =>
|
||||||
|
renderReadonlyTagTree (child, nestLevel + 1, key, nextAncestors)))]
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
const TagList: FC<{ tags: Tag[]; compact?: boolean; flow?: TagFlow }> = (
|
const TagList: FC<{ tags: Tag[]; compact?: boolean; flow?: TagFlow }> = (
|
||||||
{ tags, compact, flow = 'vertical' }) => {
|
{ tags, compact, flow = 'vertical' }) => {
|
||||||
const grouped = tagsByCategory (tags)
|
const horizontalGrouped = tagsByCategory (flattenTags (tags))
|
||||||
|
const verticalGrouped = tagsByCategory (tags)
|
||||||
|
|
||||||
if (flow === 'horizontal')
|
if (flow === 'horizontal')
|
||||||
{
|
{
|
||||||
return (
|
return (
|
||||||
<ul className={cn ('flex flex-wrap gap-x-3 gap-y-1', compact && 'text-sm')}>
|
<ul className={cn ('flex flex-wrap gap-x-3 gap-y-1', compact && 'text-sm')}>
|
||||||
{CATEGORIES.flatMap (cat => grouped[cat] ?? []).map (tag => (
|
{CATEGORIES.flatMap (cat => horizontalGrouped[cat] ?? []).map (tag => (
|
||||||
<li key={tag.id} className="text-left leading-tight">
|
<li key={tag.id} className="text-left leading-tight">
|
||||||
<TagLink tag={tag} withCount={false}/>
|
<TagLink tag={tag} withCount={false}/>
|
||||||
</li>))}
|
</li>))}
|
||||||
@@ -136,7 +185,7 @@ const TagList: FC<{ tags: Tag[]; compact?: boolean; flow?: TagFlow }> = (
|
|||||||
return (
|
return (
|
||||||
<div className="space-y-3">
|
<div className="space-y-3">
|
||||||
{CATEGORIES.map (cat => {
|
{CATEGORIES.map (cat => {
|
||||||
const rows = grouped[cat] ?? []
|
const rows = verticalGrouped[cat] ?? []
|
||||||
if (rows.length === 0)
|
if (rows.length === 0)
|
||||||
return null
|
return null
|
||||||
|
|
||||||
@@ -146,10 +195,8 @@ const TagList: FC<{ tags: Tag[]; compact?: boolean; flow?: TagFlow }> = (
|
|||||||
{CATEGORY_NAMES[cat]}
|
{CATEGORY_NAMES[cat]}
|
||||||
</div>
|
</div>
|
||||||
<ul className={cn ('space-y-1', compact && 'text-sm')}>
|
<ul className={cn ('space-y-1', compact && 'text-sm')}>
|
||||||
{rows.map (tag => (
|
{rows.flatMap (tag =>
|
||||||
<li key={tag.id} className="text-left leading-tight">
|
renderReadonlyTagTree (tag, 0, `cat-${ cat }`))}
|
||||||
<TagLink tag={tag} withCount={false}/>
|
|
||||||
</li>))}
|
|
||||||
</ul>
|
</ul>
|
||||||
</div>)
|
</div>)
|
||||||
})}
|
})}
|
||||||
@@ -167,11 +214,16 @@ const TheatreDetailPage: FC<Props> = ({ user }: Props) => {
|
|||||||
const commentsRef = useRef<HTMLDivElement> (null)
|
const commentsRef = useRef<HTMLDivElement> (null)
|
||||||
const embedRef = useRef<NiconicoViewerHandle> (null)
|
const embedRef = useRef<NiconicoViewerHandle> (null)
|
||||||
const loadingRef = useRef (false)
|
const loadingRef = useRef (false)
|
||||||
|
const sidebarContainerRef = useRef<HTMLDivElement> (null)
|
||||||
const theatreInfoRef = useRef<TheatreInfo> (INITIAL_THEATRE_INFO)
|
const theatreInfoRef = useRef<TheatreInfo> (INITIAL_THEATRE_INFO)
|
||||||
const theatreInfoReceivedAtRef = useRef (performance.now ())
|
const theatreInfoReceivedAtRef = useRef (performance.now ())
|
||||||
const videoLengthRef = useRef (0)
|
const videoLengthRef = useRef (0)
|
||||||
const lastCommentNoRef = useRef (0)
|
const lastCommentNoRef = useRef (0)
|
||||||
|
|
||||||
|
const [leftSidebarWidth, setLeftSidebarWidth] = useState (256)
|
||||||
|
const [rightSidebarWidth, setRightSidebarWidth] = useState (256)
|
||||||
|
const [sidebarContainerWidth, setSidebarContainerWidth] = useState (
|
||||||
|
() => typeof window === 'undefined' ? 0 : window.innerWidth)
|
||||||
const [comments, setComments] = useState<TheatreComment[]> ([])
|
const [comments, setComments] = useState<TheatreComment[]> ([])
|
||||||
const [content, setContent] = useState ('')
|
const [content, setContent] = useState ('')
|
||||||
const [editingPost, setEditingPost] = useState<Post | null> (null)
|
const [editingPost, setEditingPost] = useState<Post | null> (null)
|
||||||
@@ -214,6 +266,7 @@ const TheatreDetailPage: FC<Props> = ({ user }: Props) => {
|
|||||||
|
|
||||||
const applyTheatreInfo = useCallback ((nextInfo: TheatreInfo) => {
|
const applyTheatreInfo = useCallback ((nextInfo: TheatreInfo) => {
|
||||||
theatreInfoReceivedAtRef.current = performance.now ()
|
theatreInfoReceivedAtRef.current = performance.now ()
|
||||||
|
theatreInfoRef.current = nextInfo
|
||||||
setTheatreInfo (nextInfo)
|
setTheatreInfo (nextInfo)
|
||||||
}, [])
|
}, [])
|
||||||
|
|
||||||
@@ -280,6 +333,17 @@ const TheatreDetailPage: FC<Props> = ({ user }: Props) => {
|
|||||||
lastCommentNoRef.current = comments[0]?.no ?? 0
|
lastCommentNoRef.current = comments[0]?.no ?? 0
|
||||||
}, [comments])
|
}, [comments])
|
||||||
|
|
||||||
|
useEffect (() => {
|
||||||
|
const updateSidebarContainerWidth = () => {
|
||||||
|
const nextWidth = sidebarContainerRef.current?.clientWidth ?? window.innerWidth
|
||||||
|
setSidebarContainerWidth (nextWidth)
|
||||||
|
}
|
||||||
|
|
||||||
|
updateSidebarContainerWidth ()
|
||||||
|
window.addEventListener ('resize', updateSidebarContainerWidth)
|
||||||
|
return () => window.removeEventListener ('resize', updateSidebarContainerWidth)
|
||||||
|
}, [])
|
||||||
|
|
||||||
useEffect (() => {
|
useEffect (() => {
|
||||||
if (!(id))
|
if (!(id))
|
||||||
return
|
return
|
||||||
@@ -343,6 +407,9 @@ const TheatreDetailPage: FC<Props> = ({ user }: Props) => {
|
|||||||
setComments (prev => [...newComments, ...prev])
|
setComments (prev => [...newComments, ...prev])
|
||||||
}
|
}
|
||||||
|
|
||||||
|
if (loadingRef.current)
|
||||||
|
return
|
||||||
|
|
||||||
const currentInfo = theatreInfoRef.current
|
const currentInfo = theatreInfoRef.current
|
||||||
const ended =
|
const ended =
|
||||||
currentInfo.hostFlg
|
currentInfo.hostFlg
|
||||||
@@ -364,8 +431,9 @@ const TheatreDetailPage: FC<Props> = ({ user }: Props) => {
|
|||||||
return
|
return
|
||||||
}
|
}
|
||||||
|
|
||||||
|
const watchingRequestedAt = performance.now ()
|
||||||
const nextInfo = await apiPut<TheatreInfo> (`/theatres/${ id }/watching`)
|
const nextInfo = await apiPut<TheatreInfo> (`/theatres/${ id }/watching`)
|
||||||
if (!(cancelled))
|
if (!(cancelled) && watchingRequestedAt >= theatreInfoReceivedAtRef.current)
|
||||||
applyTheatreInfo (nextInfo)
|
applyTheatreInfo (nextInfo)
|
||||||
}
|
}
|
||||||
catch (error)
|
catch (error)
|
||||||
@@ -494,6 +562,7 @@ const TheatreDetailPage: FC<Props> = ({ user }: Props) => {
|
|||||||
if (!(id) || !(post))
|
if (!(id) || !(post))
|
||||||
return
|
return
|
||||||
|
|
||||||
|
loadingRef.current = true
|
||||||
setLoading (true)
|
setLoading (true)
|
||||||
try
|
try
|
||||||
{
|
{
|
||||||
@@ -522,6 +591,7 @@ const TheatreDetailPage: FC<Props> = ({ user }: Props) => {
|
|||||||
}
|
}
|
||||||
finally
|
finally
|
||||||
{
|
{
|
||||||
|
loadingRef.current = false
|
||||||
setLoading (false)
|
setLoading (false)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -595,6 +665,26 @@ const TheatreDetailPage: FC<Props> = ({ user }: Props) => {
|
|||||||
if (status >= 400)
|
if (status >= 400)
|
||||||
return <ErrorScreen status={status}/>
|
return <ErrorScreen status={status}/>
|
||||||
|
|
||||||
|
const singleSidebarMaxWidth = Math.max (
|
||||||
|
192,
|
||||||
|
sidebarContainerWidth - MIN_MAIN_WIDTH - SIDEBAR_GAP_WIDTH)
|
||||||
|
const leftSidebarMaxWidth = layoutMode === 'threeColumns'
|
||||||
|
? Math.max (
|
||||||
|
192,
|
||||||
|
sidebarContainerWidth
|
||||||
|
- rightSidebarWidth
|
||||||
|
- MIN_MAIN_WIDTH
|
||||||
|
- SIDEBAR_GAP_WIDTH * 2)
|
||||||
|
: singleSidebarMaxWidth
|
||||||
|
const rightSidebarMaxWidth = layoutMode === 'threeColumns'
|
||||||
|
? Math.max (
|
||||||
|
192,
|
||||||
|
sidebarContainerWidth
|
||||||
|
- leftSidebarWidth
|
||||||
|
- MIN_MAIN_WIDTH
|
||||||
|
- SIDEBAR_GAP_WIDTH * 2)
|
||||||
|
: singleSidebarMaxWidth
|
||||||
|
|
||||||
const tagPanel = (
|
const tagPanel = (
|
||||||
<section className="rounded border-zinc-300 p-4 dark:border-zinc-800">
|
<section className="rounded border-zinc-300 p-4 dark:border-zinc-800">
|
||||||
<div className="mb-3 flex items-center justify-between gap-3">
|
<div className="mb-3 flex items-center justify-between gap-3">
|
||||||
@@ -762,30 +852,26 @@ const TheatreDetailPage: FC<Props> = ({ user }: Props) => {
|
|||||||
{theatre && <title>{`${ theatreTitle } | ${ SITE_TITLE }`}</title>}
|
{theatre && <title>{`${ theatreTitle } | ${ SITE_TITLE }`}</title>}
|
||||||
</Helmet>
|
</Helmet>
|
||||||
|
|
||||||
<div className={cn (
|
<div
|
||||||
'grid min-h-full gap-4 overflow-visible md:h-full md:overflow-hidden',
|
ref={sidebarContainerRef}
|
||||||
(layoutMode === 'threeColumns'
|
data-sidebar-container
|
||||||
&& ['md:grid-cols-[16rem_minmax(0,1fr)_22rem]',
|
className="flex min-h-full flex-col gap-4 overflow-visible md:h-full md:flex-row
|
||||||
'xl:grid-cols-[18rem_minmax(0,1fr)_24rem]']),
|
md:overflow-hidden">
|
||||||
(layoutMode === 'tagsBottom'
|
|
||||||
&& 'md:grid-cols-[minmax(0,1fr)_22rem] xl:grid-cols-[minmax(0,1fr)_24rem]'),
|
|
||||||
(layoutMode === 'commentsBottom'
|
|
||||||
&& 'md:grid-cols-[16rem_minmax(0,1fr)] xl:grid-cols-[18rem_minmax(0,1fr)]'))}>
|
|
||||||
{layoutMode !== 'tagsBottom' && (
|
{layoutMode !== 'tagsBottom' && (
|
||||||
<motion.aside
|
<SidebarComponent
|
||||||
layout="position"
|
sidebarKey="theatre-tags"
|
||||||
className="hidden min-w-0 space-y-4 md:order-none md:block md:overflow-y-auto
|
side="left"
|
||||||
md:[direction:rtl]">
|
maxWidth={leftSidebarMaxWidth}
|
||||||
<div className="md:[direction:ltr]">
|
onWidthChange={setLeftSidebarWidth}
|
||||||
{tagPanel}
|
className="hidden md:block">
|
||||||
</div>
|
{tagPanel}
|
||||||
</motion.aside>)}
|
</SidebarComponent>)}
|
||||||
|
|
||||||
<motion.main
|
<motion.main
|
||||||
layout="position"
|
layout="position"
|
||||||
className={cn ('order-1 min-w-0 space-y-4 md:order-none md:overflow-y-auto',
|
className="order-1 min-w-0 flex-1 space-y-4 md:order-none
|
||||||
layoutMode === 'tagsBottom' && 'md:[direction:rtl]')}>
|
md:min-w-[360px] md:overflow-y-auto">
|
||||||
<div className={cn ('space-y-4', layoutMode === 'tagsBottom' && 'md:[direction:ltr]')}>
|
<div className="space-y-4">
|
||||||
<section className="overflow-hidden rounded border-zinc-300
|
<section className="overflow-hidden rounded border-zinc-300
|
||||||
dark:border-zinc-800">
|
dark:border-zinc-800">
|
||||||
<div className="flex flex-wrap items-center justify-between gap-3
|
<div className="flex flex-wrap items-center justify-between gap-3
|
||||||
@@ -921,12 +1007,17 @@ const TheatreDetailPage: FC<Props> = ({ user }: Props) => {
|
|||||||
</motion.main>
|
</motion.main>
|
||||||
|
|
||||||
{layoutMode !== 'commentsBottom' && (
|
{layoutMode !== 'commentsBottom' && (
|
||||||
<motion.aside
|
<SidebarComponent
|
||||||
layout="position"
|
sidebarKey="theatre-comments"
|
||||||
className="hidden min-w-0 space-y-4 md:order-none md:block md:overflow-y-auto">
|
side="right"
|
||||||
{commentsPanel}
|
maxWidth={rightSidebarMaxWidth}
|
||||||
{participantsPanel}
|
onWidthChange={setRightSidebarWidth}
|
||||||
</motion.aside>)}
|
className="hidden md:block">
|
||||||
|
<div className="space-y-4">
|
||||||
|
{commentsPanel}
|
||||||
|
{participantsPanel}
|
||||||
|
</div>
|
||||||
|
</SidebarComponent>)}
|
||||||
</div>
|
</div>
|
||||||
</motion.div>)
|
</motion.div>)
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -1,6 +1,6 @@
|
|||||||
import type { Material,
|
import type { Material,
|
||||||
Post,
|
Post,
|
||||||
Tag,
|
TagWithSections,
|
||||||
Theatre,
|
Theatre,
|
||||||
TheatreComment,
|
TheatreComment,
|
||||||
TheatreInfo,
|
TheatreInfo,
|
||||||
@@ -9,7 +9,7 @@ import type { Material,
|
|||||||
User,
|
User,
|
||||||
WikiPage } from '@/types'
|
WikiPage } from '@/types'
|
||||||
|
|
||||||
export const buildTag = (overrides: Partial<Tag> = {}): Tag => ({
|
export const buildTag = (overrides: Partial<TagWithSections> = {}): TagWithSections => ({
|
||||||
id: 1,
|
id: 1,
|
||||||
name: 'テストタグ',
|
name: 'テストタグ',
|
||||||
category: 'general',
|
category: 'general',
|
||||||
@@ -23,6 +23,8 @@ export const buildTag = (overrides: Partial<Tag> = {}): Tag => ({
|
|||||||
materialId: null,
|
materialId: null,
|
||||||
hasDeerjikists: false,
|
hasDeerjikists: false,
|
||||||
matchedAlias: null,
|
matchedAlias: null,
|
||||||
|
sections: [],
|
||||||
|
children: [],
|
||||||
...overrides,
|
...overrides,
|
||||||
})
|
})
|
||||||
|
|
||||||
@@ -33,6 +35,7 @@ export const buildPost = (overrides: Partial<Post> = {}): Post => ({
|
|||||||
title: 'テスト投稿',
|
title: 'テスト投稿',
|
||||||
thumbnail: 'https://example.com/thumb.jpg',
|
thumbnail: 'https://example.com/thumb.jpg',
|
||||||
thumbnailBase: null,
|
thumbnailBase: null,
|
||||||
|
videoMs: null,
|
||||||
tags: [buildTag ()],
|
tags: [buildTag ()],
|
||||||
parentPosts: [],
|
parentPosts: [],
|
||||||
childPosts: [],
|
childPosts: [],
|
||||||
|
|||||||
+43
-1
@@ -88,12 +88,26 @@ export type MaterialIndexSort =
|
|||||||
|
|
||||||
export type MaterialIndexTagState = 'all' | 'tagged' | 'untagged'
|
export type MaterialIndexTagState = 'all' | 'tagged' | 'untagged'
|
||||||
|
|
||||||
|
export type MaterialIndexGroupBy = 'none' | 'parent_tag'
|
||||||
|
|
||||||
export type MaterialIndexView = 'card' | 'list'
|
export type MaterialIndexView = 'card' | 'list'
|
||||||
|
|
||||||
|
export type MaterialTagScope = {
|
||||||
|
tag: {
|
||||||
|
id: number
|
||||||
|
name: string
|
||||||
|
category: Category
|
||||||
|
}
|
||||||
|
includeDescendants: boolean
|
||||||
|
}
|
||||||
|
|
||||||
export type FetchMaterialsParams = {
|
export type FetchMaterialsParams = {
|
||||||
q: string
|
q: string
|
||||||
tagState: MaterialIndexTagState
|
tagState: MaterialIndexTagState
|
||||||
mediaKind: MaterialIndexMediaKind
|
mediaKind: MaterialIndexMediaKind
|
||||||
|
tagId: number | null
|
||||||
|
includeDescendants: boolean
|
||||||
|
groupBy: MaterialIndexGroupBy
|
||||||
createdFrom: string
|
createdFrom: string
|
||||||
createdTo: string
|
createdTo: string
|
||||||
updatedFrom: string
|
updatedFrom: string
|
||||||
@@ -170,6 +184,23 @@ export type MaterialExportItem = {
|
|||||||
exportPath: string
|
exportPath: string
|
||||||
enabled: boolean }
|
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 = {
|
export type MaterialVersion = {
|
||||||
id: number
|
id: number
|
||||||
materialId: number
|
materialId: number
|
||||||
@@ -179,6 +210,11 @@ export type MaterialVersion = {
|
|||||||
tagName: string | null
|
tagName: string | null
|
||||||
tagCategory: Category | null
|
tagCategory: Category | null
|
||||||
url: string | null
|
url: string | null
|
||||||
|
sourceKind: string | null
|
||||||
|
sourceUri: string | null
|
||||||
|
sourcePath: string | null
|
||||||
|
sourceFileId: string | null
|
||||||
|
normalizedSourceKey: string | null
|
||||||
fileBlobId: number | null
|
fileBlobId: number | null
|
||||||
fileFilename: string | null
|
fileFilename: string | null
|
||||||
fileContentType: string | null
|
fileContentType: string | null
|
||||||
@@ -252,11 +288,12 @@ export type Post = {
|
|||||||
title: string | null
|
title: string | null
|
||||||
thumbnail: string | null
|
thumbnail: string | null
|
||||||
thumbnailBase: string | null
|
thumbnailBase: string | null
|
||||||
|
videoMs: number | null
|
||||||
postSimilarityEdges?: {
|
postSimilarityEdges?: {
|
||||||
targetPostId: number
|
targetPostId: number
|
||||||
cos: number
|
cos: number
|
||||||
}[]
|
}[]
|
||||||
tags: Tag[]
|
tags: TagWithSections[]
|
||||||
parentPosts?: Post[]
|
parentPosts?: Post[]
|
||||||
childPosts?: Post[]
|
childPosts?: Post[]
|
||||||
siblingPosts?: Record<`${ number }`, Post[]>
|
siblingPosts?: Record<`${ number }`, Post[]>
|
||||||
@@ -284,6 +321,7 @@ export type PostVersion = {
|
|||||||
url: { current: string; prev: string | null }
|
url: { current: string; prev: string | null }
|
||||||
thumbnail: { current: string | null; prev: string | null }
|
thumbnail: { current: string | null; prev: string | null }
|
||||||
thumbnailBase: { current: string | null; prev: string | null }
|
thumbnailBase: { current: string | null; prev: string | null }
|
||||||
|
videoMs: { current: number | null; prev: number | null }
|
||||||
tags: { name: string
|
tags: { name: string
|
||||||
type: 'context' | 'added' | 'removed' }[]
|
type: 'context' | 'added' | 'removed' }[]
|
||||||
parentPosts: { id: number
|
parentPosts: { id: number
|
||||||
@@ -333,6 +371,10 @@ export type TagVersion = {
|
|||||||
createdAt: string
|
createdAt: string
|
||||||
createdByUser: { id: number; name: string | null } | null }
|
createdByUser: { id: number; name: string | null } | null }
|
||||||
|
|
||||||
|
export type TagWithSections = Omit<Tag, 'children'> & { sections: { beginMs: number
|
||||||
|
endMs: number | null }[]
|
||||||
|
children: TagWithSections[] }
|
||||||
|
|
||||||
export type Theatre = {
|
export type Theatre = {
|
||||||
id: number
|
id: number
|
||||||
name: string | null
|
name: string | null
|
||||||
|
|||||||
新しい課題から参照
ユーザをブロックする