コミットを比較
6
コミット
| 作成者 | SHA1 | 日付 | |
|---|---|---|---|
|
|
7de8b52811 | ||
|
|
4c17d0ef06 | ||
|
|
ef5a3f725e | ||
|
|
971b2632b0 | ||
|
|
ad04c03e14 | ||
|
|
2197a9192b |
@@ -2,6 +2,13 @@ require 'set'
|
||||
|
||||
|
||||
class MaterialsController < ApplicationController
|
||||
around_action only: [:create, :update, :destroy] do |controller, action|
|
||||
event_type = controller.action_name == 'destroy' ? 'discard' : controller.action_name
|
||||
VersionRecorder.with_event(
|
||||
event_type: "materials.#{ event_type }",
|
||||
created_by_user: controller.current_user, &action)
|
||||
end
|
||||
|
||||
rescue_from MaterialZipExporter::EmptyExportError, with: :render_zip_empty
|
||||
rescue_from MaterialZipExporter::DuplicatePathError, with: :render_zip_duplicate_path
|
||||
rescue_from MaterialZipExporter::MissingFileError, with: :render_zip_missing_file
|
||||
|
||||
@@ -1,4 +1,10 @@
|
||||
class NicoTagsController < ApplicationController
|
||||
around_action only: [:update] do |controller, action|
|
||||
VersionRecorder.with_event(
|
||||
event_type: 'external_tags.update',
|
||||
created_by_user: controller.current_user, &action)
|
||||
end
|
||||
|
||||
def index
|
||||
locale = resolve_locale!
|
||||
|
||||
|
||||
@@ -1,4 +1,10 @@
|
||||
class PostsController < ApplicationController
|
||||
around_action only: [:update] do |controller, action|
|
||||
VersionRecorder.with_event(
|
||||
event_type: 'posts.update',
|
||||
created_by_user: controller.current_user, &action)
|
||||
end
|
||||
|
||||
Event = Struct.new(:post, :tag, :user, :change_type, :timestamp, keyword_init: true)
|
||||
MAX_BULK_REQUEST_BYTES = 40 * 1024 * 1024
|
||||
|
||||
|
||||
@@ -1,4 +1,10 @@
|
||||
class TagChildrenController < ApplicationController
|
||||
around_action only: [:create, :destroy] do |controller, action|
|
||||
VersionRecorder.with_event(
|
||||
event_type: 'tags.update',
|
||||
created_by_user: controller.current_user, &action)
|
||||
end
|
||||
|
||||
def create
|
||||
return head :unauthorized unless current_user
|
||||
return head :forbidden unless current_user.admin?
|
||||
|
||||
@@ -4,6 +4,12 @@ require 'set'
|
||||
|
||||
|
||||
class TagsController < ApplicationController
|
||||
around_action only: [:update, :update_all] do |controller, action|
|
||||
VersionRecorder.with_event(
|
||||
event_type: 'tags.update',
|
||||
created_by_user: controller.current_user, &action)
|
||||
end
|
||||
|
||||
def index
|
||||
locale = resolve_locale!
|
||||
|
||||
|
||||
@@ -246,23 +246,26 @@ class WikiPagesController < ApplicationController
|
||||
|
||||
base_revision_id = params[:base_revision_id].presence
|
||||
|
||||
ApplicationRecord.transaction do
|
||||
SharedResourceIdAllocator.lock_space!(Tag, 'tags')
|
||||
tag.lock!
|
||||
old_title = tag_name.name
|
||||
if title != old_title
|
||||
TagVersioning.ensure_snapshot!(tag, created_by_user: current_user)
|
||||
end
|
||||
VersionRecorder.with_event(
|
||||
event_type: 'tag_descriptions.update', created_by_user: current_user) do
|
||||
ApplicationRecord.transaction do
|
||||
SharedResourceIdAllocator.lock_space!(Tag, 'tags')
|
||||
tag.lock!
|
||||
old_title = tag_name.name
|
||||
if title != old_title
|
||||
TagVersioning.ensure_snapshot!(tag, created_by_user: current_user)
|
||||
end
|
||||
|
||||
tag_name.update!(name: title) if title != old_title
|
||||
tag_name.update!(name: title) if title != old_title
|
||||
|
||||
message = params[:message].presence
|
||||
TagDescriptionOperation.update!(locale, tag:, body:, updated_by_user: current_user,
|
||||
message:, base_revision_id:)
|
||||
message = params[:message].presence
|
||||
TagDescriptionOperation.update!(locale, tag:, body:, updated_by_user: current_user,
|
||||
message:, base_revision_id:)
|
||||
|
||||
if title != old_title
|
||||
tag.reload
|
||||
TagVersionRecorder.record!(tag:, event_type: :update, created_by_user: current_user)
|
||||
if title != old_title
|
||||
tag.reload
|
||||
TagVersionRecorder.record!(tag:, event_type: :update, created_by_user: current_user)
|
||||
end
|
||||
end
|
||||
end
|
||||
|
||||
|
||||
@@ -0,0 +1,10 @@
|
||||
class Event < ApplicationRecord
|
||||
has_many :post_versions
|
||||
has_many :tag_versions
|
||||
has_many :nico_tag_versions
|
||||
has_many :material_versions
|
||||
has_many :tag_description_versions
|
||||
has_many :tag_group_versions
|
||||
|
||||
belongs_to :created_by_user, class_name: 'User', optional: true
|
||||
end
|
||||
@@ -11,7 +11,5 @@ class MaterialVersion < ApplicationRecord
|
||||
belongs_to :parent, class_name: 'Material', optional: true
|
||||
belongs_to :updated_by_user, class_name: 'User', optional: true
|
||||
|
||||
def export_paths_hash
|
||||
export_paths_json || {}
|
||||
end
|
||||
def export_paths_hash = export_paths_json || { }
|
||||
end
|
||||
|
||||
+33
-31
@@ -290,47 +290,49 @@ class Tag < ApplicationRecord
|
||||
|
||||
affected_post_ids = Set.new
|
||||
|
||||
Tag.transaction do
|
||||
TagVersioning.ensure_snapshot!(target_tag, created_by_user:)
|
||||
VersionRecorder.with_event(event_type: 'tags.update', created_by_user:) do
|
||||
Tag.transaction do
|
||||
TagVersioning.ensure_snapshot!(target_tag, created_by_user:)
|
||||
|
||||
Array(source_tags).compact.uniq.each do |source_tag|
|
||||
source_tag => Tag
|
||||
Array(source_tags).compact.uniq.each do |source_tag|
|
||||
source_tag => Tag
|
||||
|
||||
next if source_tag == target_tag
|
||||
next if source_tag == target_tag
|
||||
|
||||
TagVersioning.ensure_snapshot!(source_tag, created_by_user:)
|
||||
TagVersioning.ensure_snapshot!(source_tag, created_by_user:)
|
||||
|
||||
source_tag.post_tags.find_each do |source_pt|
|
||||
post_id = source_pt.post_id
|
||||
affected_post_ids << post_id
|
||||
source_pt.destroy!
|
||||
unless PostTag.exists?(post_id:, tag: target_tag)
|
||||
PostTag.create!(post_id:, tag: target_tag)
|
||||
source_tag.post_tags.find_each do |source_pt|
|
||||
post_id = source_pt.post_id
|
||||
affected_post_ids << post_id
|
||||
source_pt.destroy!
|
||||
unless PostTag.exists?(post_id:, tag: target_tag)
|
||||
PostTag.create!(post_id:, tag: target_tag)
|
||||
end
|
||||
end
|
||||
|
||||
if source_tag.tag_descriptions.exists?
|
||||
source_tag.errors.add(:base, :invalid)
|
||||
raise ActiveRecord::RecordInvalid, source_tag
|
||||
end
|
||||
|
||||
TagVersioning.record!(source_tag, event_type: :discard, created_by_user:)
|
||||
target_languages = target_tag.tag_names.where(primary_flg: true).pluck(:language_code)
|
||||
source_tag.tag_names.where(language_code: target_languages)
|
||||
.update_all(primary_flg: false, auto_generated: false, updated_at: Time.current)
|
||||
source_tag.tag_names.update_all(tag_id: target_tag.id, updated_at: Time.current)
|
||||
source_tag.destroy!
|
||||
|
||||
TagVersioning.record!(target_tag, event_type: :update, created_by_user:)
|
||||
end
|
||||
|
||||
if source_tag.tag_descriptions.exists?
|
||||
source_tag.errors.add(:base, :invalid)
|
||||
raise ActiveRecord::RecordInvalid, source_tag
|
||||
Post.where(id: affected_post_ids.to_a).find_each do |post|
|
||||
PostVersionRecorder.ensure_snapshot!(post, created_by_user:)
|
||||
PostVersionRecorder.record!(post:, event_type: :update, created_by_user:)
|
||||
end
|
||||
|
||||
TagVersioning.record!(source_tag, event_type: :discard, created_by_user:)
|
||||
target_languages = target_tag.tag_names.where(primary_flg: true).pluck(:language_code)
|
||||
source_tag.tag_names.where(language_code: target_languages)
|
||||
.update_all(primary_flg: false, auto_generated: false, updated_at: Time.current)
|
||||
source_tag.tag_names.update_all(tag_id: target_tag.id, updated_at: Time.current)
|
||||
source_tag.destroy!
|
||||
|
||||
TagVersioning.record!(target_tag, event_type: :update, created_by_user:)
|
||||
# 投稿件数を再集計
|
||||
target_tag.update_columns(post_count: PostTag.where(tag: target_tag).count)
|
||||
end
|
||||
|
||||
Post.where(id: affected_post_ids.to_a).find_each do |post|
|
||||
PostVersionRecorder.ensure_snapshot!(post, created_by_user:)
|
||||
PostVersionRecorder.record!(post:, event_type: :update, created_by_user:)
|
||||
end
|
||||
|
||||
# 投稿件数を再集計
|
||||
target_tag.update_columns(post_count: PostTag.where(tag: target_tag).count)
|
||||
end
|
||||
|
||||
target_tag.reload
|
||||
|
||||
@@ -15,37 +15,39 @@ class TagNameSanitisationRule < ApplicationRecord
|
||||
end
|
||||
|
||||
def apply!
|
||||
Language.find_each do |language|
|
||||
TagName.where(language:).find_each do |candidate|
|
||||
TagName.transaction do
|
||||
tn = TagName.find_by(id: candidate.id)
|
||||
next unless tn
|
||||
VersionRecorder.with_event(event_type: 'tags.update', created_by_user: nil) do
|
||||
Language.find_each do |language|
|
||||
TagName.where(language:).find_each do |candidate|
|
||||
TagName.transaction do
|
||||
tn = TagName.find_by(id: candidate.id)
|
||||
next unless tn
|
||||
|
||||
name = sanitise(tn.name)
|
||||
next if name == tn.name
|
||||
name = sanitise(tn.name)
|
||||
next if name == tn.name
|
||||
|
||||
existing_tn = TagName.find_by(language:, name:)
|
||||
source_tag = tn.tag
|
||||
target_tag = existing_tn ? existing_tn.tag : source_tag
|
||||
[source_tag, target_tag].uniq(&:id).sort_by(&:id).each(&:lock!)
|
||||
TagVersioning.ensure_snapshot!(source_tag, created_by_user: nil)
|
||||
existing_tn = TagName.find_by(language:, name:)
|
||||
source_tag = tn.tag
|
||||
target_tag = existing_tn ? existing_tn.tag : source_tag
|
||||
[source_tag, target_tag].uniq(&:id).sort_by(&:id).each(&:lock!)
|
||||
TagVersioning.ensure_snapshot!(source_tag, created_by_user: nil)
|
||||
|
||||
if existing_tn && target_tag != source_tag
|
||||
Tag.merge_tags!(target_tag, source_tag)
|
||||
tn.reload.destroy!
|
||||
elsif existing_tn
|
||||
if tn.primary?
|
||||
existing_tn.destroy!
|
||||
tn.update_columns(name:, updated_at: Time.current)
|
||||
if existing_tn && target_tag != source_tag
|
||||
Tag.merge_tags!(target_tag, source_tag)
|
||||
tn.reload.destroy!
|
||||
elsif existing_tn
|
||||
if tn.primary?
|
||||
existing_tn.destroy!
|
||||
tn.update_columns(name:, updated_at: Time.current)
|
||||
else
|
||||
tn.destroy!
|
||||
end
|
||||
else
|
||||
tn.destroy!
|
||||
# TagName 側の自動サニタイズを回避
|
||||
tn.update_columns(name:, updated_at: Time.current)
|
||||
end
|
||||
else
|
||||
# TagName 側の自動サニタイズを回避
|
||||
tn.update_columns(name:, updated_at: Time.current)
|
||||
end
|
||||
|
||||
TagVersioning.record!(target_tag, event_type: :update, created_by_user: nil)
|
||||
TagVersioning.record!(target_tag, event_type: :update, created_by_user: nil)
|
||||
end
|
||||
end
|
||||
end
|
||||
end
|
||||
|
||||
@@ -19,6 +19,8 @@ module VersionRecord
|
||||
|
||||
belongs_to :created_by_user, class_name: 'User', optional: true
|
||||
|
||||
belongs_to :event
|
||||
|
||||
enum :event_type, event_type_map, prefix: true, validate: true
|
||||
|
||||
validates :version_no, presence: true, numericality: { only_integer: true, greater_than: 0 }
|
||||
|
||||
@@ -51,19 +51,23 @@ class MaterialSyncImporter
|
||||
suppression: @import_block)
|
||||
end
|
||||
|
||||
Material.transaction do
|
||||
if material.persisted?
|
||||
MaterialVersionRecorder.ensure_snapshot!(material,
|
||||
created_by_user: @attributes[:updated_by_user])
|
||||
VersionRecorder.with_event(
|
||||
event_type: "materials.#{ event_type }",
|
||||
created_by_user: @attributes[:updated_by_user]) do
|
||||
Material.transaction do
|
||||
if material.persisted?
|
||||
MaterialVersionRecorder.ensure_snapshot!(material,
|
||||
created_by_user: @attributes[:updated_by_user])
|
||||
end
|
||||
material.assign_attributes(material_attributes_for(material).merge(source))
|
||||
material.discarded_at = nil if material.respond_to?(:discarded_at=)
|
||||
material.file.attach(uploaded_blob) if uploaded_blob
|
||||
material.save!
|
||||
upsert_export_item!(material)
|
||||
MaterialVersionRecorder.record!(material:,
|
||||
event_type:,
|
||||
created_by_user: @attributes[:updated_by_user])
|
||||
end
|
||||
material.assign_attributes(material_attributes_for(material).merge(source))
|
||||
material.discarded_at = nil if material.respond_to?(:discarded_at=)
|
||||
material.file.attach(uploaded_blob) if uploaded_blob
|
||||
material.save!
|
||||
upsert_export_item!(material)
|
||||
MaterialVersionRecorder.record!(material:,
|
||||
event_type:,
|
||||
created_by_user: @attributes[:updated_by_user])
|
||||
end
|
||||
MaterialThumbnailGenerator.generate!(material)
|
||||
|
||||
@@ -200,10 +204,10 @@ class MaterialSyncImporter
|
||||
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]
|
||||
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
|
||||
|
||||
@@ -3,14 +3,16 @@ class MaterialSyncRunner
|
||||
:errors, keyword_init: true)
|
||||
|
||||
def self.sync_enabled!
|
||||
results = MaterialSyncSource.enabled.order(:id).map { |source| new(source).sync! }
|
||||
VersionRecorder.with_event(event_type: 'materials.sync', created_by_user: nil) do
|
||||
results = MaterialSyncSource.enabled.order(:id).map { |source| new(source).sync! }
|
||||
|
||||
Result.new(imported: results.sum(&:imported),
|
||||
updated: results.sum(&:updated),
|
||||
unchanged: results.sum(&:unchanged),
|
||||
suppressed: results.sum(&:suppressed),
|
||||
failed: results.sum(&:failed),
|
||||
errors: results.flat_map(&:errors))
|
||||
Result.new(imported: results.sum(&:imported),
|
||||
updated: results.sum(&:updated),
|
||||
unchanged: results.sum(&:unchanged),
|
||||
suppressed: results.sum(&:suppressed),
|
||||
failed: results.sum(&:failed),
|
||||
errors: results.flat_map(&:errors))
|
||||
end
|
||||
end
|
||||
|
||||
def initialize source
|
||||
@@ -21,13 +23,15 @@ class MaterialSyncRunner
|
||||
result = Result.new(imported: 0, updated: 0, unchanged: 0,
|
||||
suppressed: 0, failed: 0, errors: [])
|
||||
|
||||
if @source.source_kind == 'google_drive_path'
|
||||
sync_google_drive_path!(result)
|
||||
else
|
||||
candidates.each do |candidate|
|
||||
next if candidate.blank?
|
||||
VersionRecorder.with_event(event_type: 'materials.sync', created_by_user: nil) do
|
||||
if @source.source_kind == 'google_drive_path'
|
||||
sync_google_drive_path!(result)
|
||||
else
|
||||
candidates.each do |candidate|
|
||||
next if candidate.blank?
|
||||
|
||||
sync_candidate!(candidate, result)
|
||||
sync_candidate!(candidate, result)
|
||||
end
|
||||
end
|
||||
end
|
||||
|
||||
|
||||
@@ -11,10 +11,13 @@ class MaterialSyncSuppressionRegistrar
|
||||
def create!
|
||||
suppression = nil
|
||||
|
||||
MaterialSyncSuppression.transaction do
|
||||
suppression = MaterialSyncSuppression.create!(
|
||||
@attributes.merge(created_by_user: @created_by_user))
|
||||
discard_existing_materials!(suppression)
|
||||
VersionRecorder.with_event(
|
||||
event_type: 'materials.discard', created_by_user: @created_by_user) do
|
||||
MaterialSyncSuppression.transaction do
|
||||
suppression = MaterialSyncSuppression.create!(
|
||||
@attributes.merge(created_by_user: @created_by_user))
|
||||
discard_existing_materials!(suppression)
|
||||
end
|
||||
end
|
||||
|
||||
suppression
|
||||
|
||||
@@ -1,14 +1,14 @@
|
||||
class MaterialVersionRecorder < VersionRecorder
|
||||
EVENT_TYPES = ['create', 'update', 'discard', 'restore'].freeze
|
||||
|
||||
def self.record! material:, event_type:, created_by_user:, file_snapshot: nil
|
||||
new(material:, event_type:, created_by_user:, file_snapshot:).record!
|
||||
def self.record! material:, event_type:, created_by_user:, event: nil, file_snapshot: nil
|
||||
new(material:, event_type:, event:, created_by_user:, file_snapshot:).record!
|
||||
end
|
||||
|
||||
def initialize material:, event_type:, created_by_user:, file_snapshot: nil
|
||||
def initialize material:, event_type:, created_by_user:, event: nil, file_snapshot: nil
|
||||
@file_snapshot = file_snapshot
|
||||
|
||||
super(record: material, event_type:, created_by_user:)
|
||||
super(record: material, event_type:, event:, created_by_user:)
|
||||
end
|
||||
|
||||
def self.ensure_snapshot! material, created_by_user:
|
||||
|
||||
@@ -1,11 +1,11 @@
|
||||
class NicoTagVersionRecorder < VersionRecorder
|
||||
EVENT_TYPES = ['create', 'update'].freeze
|
||||
def self.record! external_tag:, event_type:, created_by_user:
|
||||
new(external_tag:, event_type:, created_by_user:).record!
|
||||
def self.record! external_tag:, event_type:, created_by_user:, event: nil
|
||||
new(external_tag:, event_type:, created_by_user:, event:).record!
|
||||
end
|
||||
|
||||
def initialize external_tag:, event_type:, created_by_user:
|
||||
super(record: external_tag, event_type:, created_by_user:)
|
||||
def initialize external_tag:, event_type:, created_by_user:, event: nil
|
||||
super(record: external_tag, event_type:, created_by_user:, event:)
|
||||
end
|
||||
|
||||
private
|
||||
|
||||
@@ -7,6 +7,8 @@ class PostBulkCreator
|
||||
end
|
||||
|
||||
def run locale
|
||||
@event_context = nil
|
||||
@event_mutex = Mutex.new
|
||||
results = Array.new(@posts.length)
|
||||
mutex = Mutex.new
|
||||
next_index = 0
|
||||
@@ -74,9 +76,17 @@ class PostBulkCreator
|
||||
existing_post: preflight[:existing_post] }
|
||||
end
|
||||
|
||||
post = PostCreator.new(
|
||||
actor: actor,
|
||||
attributes: normalised_attributes(attributes, preflight, index)).create!(locale)
|
||||
# Keep preflight parallel, but publish the shared event with its first
|
||||
# successful post before another worker can reference it.
|
||||
post = @event_mutex.synchronize do
|
||||
@event_context ||= { event_type: 'posts.create', created_by_user: actor }
|
||||
VersionRecorder.with_event(
|
||||
event_type: 'posts.create', created_by_user: actor, context: @event_context) do
|
||||
PostCreator.new(
|
||||
actor: actor,
|
||||
attributes: normalised_attributes(attributes, preflight, index)).create!(locale)
|
||||
end
|
||||
end
|
||||
result = {
|
||||
status: 'created',
|
||||
post: { id: post.id } }
|
||||
|
||||
@@ -18,21 +18,23 @@ class PostCreator
|
||||
original_created_from: @attributes[:original_created_from].presence,
|
||||
original_created_before: @attributes[:original_created_before].presence)
|
||||
|
||||
ApplicationRecord.transaction do
|
||||
post.save!
|
||||
post.thumbnail.attach(thumbnail_attachment) if thumbnail_attachment.present?
|
||||
snapshot_tags = planned_snapshot_tags(locale)
|
||||
post_tags = planned_post_tags(locale)
|
||||
sections = planned_sections(locale)
|
||||
TagVersioning.record_tag_snapshots!(
|
||||
snapshot_tags,
|
||||
created_by_user: @actor,
|
||||
language_code: locale.language_code)
|
||||
post.video_ms = planned_video_ms(locale)
|
||||
post.save!
|
||||
sync_post_tags!(post, post_tags, sections)
|
||||
sync_parent_posts!(post, planned_parent_post_ids(locale))
|
||||
PostVersionRecorder.record!(post:, event_type: :create, created_by_user: @actor)
|
||||
VersionRecorder.with_event(event_type: 'posts.create', created_by_user: @actor) do
|
||||
ApplicationRecord.transaction do
|
||||
post.save!
|
||||
post.thumbnail.attach(thumbnail_attachment) if thumbnail_attachment.present?
|
||||
snapshot_tags = planned_snapshot_tags(locale)
|
||||
post_tags = planned_post_tags(locale)
|
||||
sections = planned_sections(locale)
|
||||
TagVersioning.record_tag_snapshots!(
|
||||
snapshot_tags,
|
||||
created_by_user: @actor,
|
||||
language_code: locale.language_code)
|
||||
post.video_ms = planned_video_ms(locale)
|
||||
post.save!
|
||||
sync_post_tags!(post, post_tags, sections)
|
||||
sync_parent_posts!(post, planned_parent_post_ids(locale))
|
||||
PostVersionRecorder.record!(post:, event_type: :create, created_by_user: @actor)
|
||||
end
|
||||
end
|
||||
post
|
||||
rescue StandardError
|
||||
|
||||
@@ -1,10 +1,10 @@
|
||||
class PostVersionRecorder < VersionRecorder
|
||||
def self.record! post:, event_type:, created_by_user:
|
||||
new(post:, event_type:, created_by_user:).record!
|
||||
def self.record! post:, event_type:, created_by_user:, event: nil
|
||||
new(post:, event_type:, event:, created_by_user:).record!
|
||||
end
|
||||
|
||||
def initialize post:, event_type:, created_by_user:
|
||||
super(record: post, event_type:, created_by_user:)
|
||||
def initialize post:, event_type:, created_by_user:, event: nil
|
||||
super(record: post, event_type:, event:, created_by_user:)
|
||||
end
|
||||
|
||||
def self.ensure_snapshot! post, created_by_user:
|
||||
|
||||
@@ -42,9 +42,13 @@ class TagDescriptionOperation
|
||||
version_no = creating ? 1 : description.version_no + 1
|
||||
description.created_by_user_id = user.id if creating
|
||||
description.update!(body:, version_no:, updated_by_user_id: user.id)
|
||||
event_type = creating ? 'create' : 'update'
|
||||
event = VersionRecorder.record_event!(
|
||||
event_type: "tag_descriptions.#{ event_type }", created_by_user: user)
|
||||
TagDescriptionVersion.create!(
|
||||
event:,
|
||||
tag_id: description.tag_id, language_code: description.language_code,
|
||||
version_no:, event_type: creating ? 'create' : 'update', body:,
|
||||
version_no:, event_type:, body:,
|
||||
source_language_code: description.source_language_code,
|
||||
source_version_no: description.source_version_no,
|
||||
created_by_user_id: user.id, created_at: Time.current)
|
||||
|
||||
@@ -307,7 +307,9 @@ class TagGroupOperation
|
||||
private_class_method :persist_placements!
|
||||
|
||||
def self.persist_version!(group:, attributes:, actor:, event_type:)
|
||||
TagGroupVersion.create!(tag_group: group, version_no: group.version_no,
|
||||
event = VersionRecorder.record_event!(
|
||||
event_type: "tag_groups.#{ event_type }", created_by_user: actor)
|
||||
TagGroupVersion.create!(tag_group: group, version_no: group.version_no, event:,
|
||||
event_type:, name: group.name,
|
||||
description: group.description,
|
||||
members: attributes.fetch(:members),
|
||||
|
||||
@@ -1,29 +1,31 @@
|
||||
class TagNameCompletion
|
||||
class << self
|
||||
def for_locale! locale
|
||||
completed = Tag.transaction do
|
||||
SharedResourceIdAllocator.lock_space!(Tag, 'tags')
|
||||
certified_names =
|
||||
if locale.certified_tag_names_path.nil?
|
||||
{ }
|
||||
else
|
||||
CertifiedTagNameTranslations.load!(locale.certified_tag_names_path, locale:)
|
||||
end
|
||||
Tag.where(id: certified_names.keys).lock.find_each(order: :asc) do |tag|
|
||||
for_tag!(tag, locales: [locale],
|
||||
certified_names: { locale.language_code => certified_names.fetch(tag.id) },
|
||||
created_by_user: nil)
|
||||
VersionRecorder.with_event(event_type: 'locales.create', created_by_user: nil) do
|
||||
completed = Tag.transaction do
|
||||
SharedResourceIdAllocator.lock_space!(Tag, 'tags')
|
||||
certified_names =
|
||||
if locale.certified_tag_names_path.nil?
|
||||
{ }
|
||||
else
|
||||
CertifiedTagNameTranslations.load!(locale.certified_tag_names_path, locale:)
|
||||
end
|
||||
Tag.where(id: certified_names.keys).lock.find_each(order: :asc) do |tag|
|
||||
for_tag!(tag, locales: [locale],
|
||||
certified_names: { locale.language_code => certified_names.fetch(tag.id) },
|
||||
created_by_user: nil)
|
||||
end
|
||||
named_tags =
|
||||
TagName.where(language_code: locale.language_code, primary_flg: true)
|
||||
.select(:tag_id)
|
||||
Tag.where.not(id: named_tags).lock.find_each(order: :asc) do |tag|
|
||||
for_tag!(tag, locales: [locale], created_by_user: nil)
|
||||
end
|
||||
true
|
||||
end
|
||||
named_tags =
|
||||
TagName.where(language_code: locale.language_code, primary_flg: true)
|
||||
.select(:tag_id)
|
||||
Tag.where.not(id: named_tags).lock.find_each(order: :asc) do |tag|
|
||||
for_tag!(tag, locales: [locale], created_by_user: nil)
|
||||
unless completed
|
||||
raise ActiveRecord::RecordNotSaved, 'Locale tag completion was rolled back'
|
||||
end
|
||||
true
|
||||
end
|
||||
unless completed
|
||||
raise ActiveRecord::RecordNotSaved, 'Locale tag completion was rolled back'
|
||||
end
|
||||
end
|
||||
|
||||
|
||||
@@ -1,13 +1,13 @@
|
||||
class TagVersionRecorder < VersionRecorder
|
||||
def self.record! tag:, event_type:, created_by_user:, **_options
|
||||
def self.record! tag:, event_type:, created_by_user:, event: nil, **_options
|
||||
Tag.transaction do
|
||||
SharedResourceIdAllocator.lock_space!(Tag, 'tags')
|
||||
new(tag:, event_type:, created_by_user:).record!
|
||||
new(tag:, event_type:, event:, created_by_user:).record!
|
||||
end
|
||||
end
|
||||
|
||||
def initialize tag:, event_type:, created_by_user:
|
||||
super(record: tag, event_type:, created_by_user:)
|
||||
def initialize tag:, event_type:, created_by_user:, event: nil
|
||||
super(record: tag, event_type:, event:, created_by_user:)
|
||||
end
|
||||
|
||||
private
|
||||
|
||||
@@ -1,9 +1,29 @@
|
||||
class VersionRecorder
|
||||
EVENT_TYPES = ['create', 'update', 'discard', 'restore'].freeze
|
||||
|
||||
def initialize record:, event_type:, created_by_user:
|
||||
# The scope is lazy: unchanged snapshots do not create an operation log.
|
||||
def self.with_event event_type:, created_by_user:, context: nil
|
||||
previous = ActiveSupport::IsolatedExecutionState[:version_event]
|
||||
ActiveSupport::IsolatedExecutionState[:version_event] =
|
||||
context || previous || { event_type:, created_by_user: }
|
||||
yield
|
||||
ensure
|
||||
ActiveSupport::IsolatedExecutionState[:version_event] = previous
|
||||
end
|
||||
|
||||
def self.record_event! event_type:, created_by_user:
|
||||
context = ActiveSupport::IsolatedExecutionState[:version_event]
|
||||
return Event.create!(event_type:, created_by_user:) unless context
|
||||
return context[:event] if context[:event]&.persisted?
|
||||
|
||||
# Active Record resets persisted? when the creating transaction rolls back.
|
||||
context[:event] = Event.create!(context.slice(:event_type, :created_by_user))
|
||||
end
|
||||
|
||||
def initialize record:, event_type:, created_by_user:, event: nil
|
||||
@record = record
|
||||
@event_type = event_type.to_s
|
||||
@event = event
|
||||
@created_by_user = created_by_user
|
||||
|
||||
validate_event_type!
|
||||
@@ -42,8 +62,11 @@ class VersionRecorder
|
||||
def base_attributes latest
|
||||
{ version_no: (latest&.version_no || 0) + 1,
|
||||
event_type: @event_type,
|
||||
created_at: Time.current,
|
||||
created_by_user: @created_by_user }
|
||||
event: @event || self.class.record_event!(
|
||||
event_type: "#{ event_resource }.#{ @event_type }",
|
||||
created_by_user: @created_by_user),
|
||||
created_by_user: @created_by_user,
|
||||
created_at: Time.current }
|
||||
end
|
||||
|
||||
def update_record_version_no! version_no
|
||||
@@ -88,5 +111,6 @@ class VersionRecorder
|
||||
def snapshot_attributes = raise NotImplementedError
|
||||
|
||||
def record_class = @record.class
|
||||
def event_resource = record_class.table_name
|
||||
def event_types = self.class::EVENT_TYPES
|
||||
end
|
||||
|
||||
@@ -12,9 +12,11 @@ module Youtube
|
||||
video_ids = discover_video_ids
|
||||
return if video_ids.empty?
|
||||
|
||||
video_ids.each_slice(50) do |ids|
|
||||
@client.videos(ids).fetch('items', []).each do |item|
|
||||
sync_video!(VideoItem.new(item))
|
||||
VersionRecorder.with_event(event_type: 'posts.sync', created_by_user: nil) do
|
||||
video_ids.each_slice(50) do |ids|
|
||||
@client.videos(ids).fetch('items', []).each do |item|
|
||||
sync_video!(VideoItem.new(item))
|
||||
end
|
||||
end
|
||||
end
|
||||
end
|
||||
|
||||
@@ -0,0 +1,20 @@
|
||||
class CreateEvents < ActiveRecord::Migration[8.0]
|
||||
def change
|
||||
create_table :events do |t|
|
||||
t.string :event_type, null: false, index: true
|
||||
t.text :reason
|
||||
t.references :reverted_from_event, foreign_key: { to_table: :events }
|
||||
t.json :metadata
|
||||
t.binary :ip_address, limit: 16, index: true
|
||||
t.references :created_by_user, index: true, foreign_key: false
|
||||
t.datetime :created_at, null: false, index: true
|
||||
end
|
||||
|
||||
add_reference :post_versions, :event, foreign_key: true, after: :original_created_before
|
||||
add_reference :tag_versions, :event, foreign_key: true, after: :deprecated_at
|
||||
add_reference :nico_tag_versions, :event, foreign_key: true, after: :event_type
|
||||
add_reference :material_versions, :event, foreign_key: true
|
||||
add_reference :tag_description_versions, :event, foreign_key: true, after: :source_version_no
|
||||
add_reference :tag_group_versions, :event, foreign_key: true, after: :placements
|
||||
end
|
||||
end
|
||||
@@ -0,0 +1,239 @@
|
||||
class BackfillEventsFromExistingVersions < ActiveRecord::Migration[8.0]
|
||||
class MigrationEvent < ActiveRecord::Base
|
||||
self.table_name = 'events'
|
||||
end
|
||||
|
||||
class MigrationPostVersion < ActiveRecord::Base
|
||||
self.table_name = 'post_versions'
|
||||
end
|
||||
|
||||
class MigrationTagVersion < ActiveRecord::Base
|
||||
self.table_name = 'tag_versions'
|
||||
end
|
||||
|
||||
class MigrationNicoTagVersion < ActiveRecord::Base
|
||||
self.table_name = 'nico_tag_versions'
|
||||
end
|
||||
|
||||
class MigrationMaterialVersion < ActiveRecord::Base
|
||||
self.table_name = 'material_versions'
|
||||
end
|
||||
|
||||
class MigrationTagDescriptionVersion < ActiveRecord::Base
|
||||
self.table_name = 'tag_description_versions'
|
||||
end
|
||||
|
||||
class MigrationTagGroupVersion < ActiveRecord::Base
|
||||
self.table_name = 'tag_group_versions'
|
||||
end
|
||||
|
||||
class MigrationLocale < ActiveRecord::Base
|
||||
self.table_name = 'locales'
|
||||
end
|
||||
|
||||
def up
|
||||
# create → posts.create
|
||||
# update → posts.update
|
||||
if MigrationPostVersion.where.not(event_type: ['create', 'update']).exists?
|
||||
raise
|
||||
end
|
||||
|
||||
# create → materials.create
|
||||
# update → materials.update
|
||||
if MigrationMaterialVersion.where.not(event_type: ['create', 'update']).exists?
|
||||
raise
|
||||
end
|
||||
|
||||
# create → posts.create / posts.update / materials.create / materials.update
|
||||
# / external_tags.update / tags.update / unknown
|
||||
# update → tags.update / locales.create
|
||||
# discard → unknown
|
||||
if MigrationTagVersion.where.not(event_type: ['create', 'update', 'discard']).exists?
|
||||
raise
|
||||
end
|
||||
|
||||
# create → posts.create / posts.update / unknown
|
||||
# update → external_tags.update
|
||||
if MigrationNicoTagVersion.where.not(event_type: ['create', 'update']).exists?
|
||||
raise
|
||||
end
|
||||
|
||||
# create → tag_descriptions.create
|
||||
# update → tag_descriptions.update
|
||||
if MigrationTagDescriptionVersion.where.not(event_type: ['create', 'update']).exists?
|
||||
raise
|
||||
end
|
||||
|
||||
# create → tag_groups.create
|
||||
# update → tag_groups.update
|
||||
if MigrationTagGroupVersion.where.not(event_type: ['create', 'update']).exists?
|
||||
raise
|
||||
end
|
||||
|
||||
# post_versions の Backfill
|
||||
MigrationPostVersion.find_each do |pv|
|
||||
ev = MigrationEvent.create!(event_type: "posts.#{ pv.event_type }",
|
||||
created_by_user_id: pv.created_by_user_id,
|
||||
created_at: pv.created_at)
|
||||
pv.update_columns(event_id: ev.id)
|
||||
end
|
||||
|
||||
# material_versions の Backfill
|
||||
MigrationMaterialVersion.find_each do |m|
|
||||
ev = MigrationEvent.create!(event_type: "materials.#{ m.event_type }",
|
||||
created_by_user_id: m.created_by_user_id,
|
||||
created_at: m.created_at)
|
||||
m.update_columns(event_id: ev.id)
|
||||
end
|
||||
|
||||
# ロカール追加に伴ふ該当語言のタグ名称追加異動のみ分離
|
||||
ids_cause_of_locale_creation = []
|
||||
MigrationLocale.where('created_at > ?', MigrationLocale.minimum(:created_at)).find_each do |l|
|
||||
ev = MigrationEvent.create!(event_type: 'locales.create',
|
||||
created_by_user_id: nil,
|
||||
created_at: l.created_at)
|
||||
|
||||
MigrationTagVersion
|
||||
.where('created_at > ?', l.created_at)
|
||||
.where(event_type: 'update', event_id: nil)
|
||||
.find_each do |t|
|
||||
next unless t.names.key?(l.language_code)
|
||||
|
||||
prev = MigrationTagVersion.find_by(tag_id: t.tag_id, version_no: t.version_no - 1)
|
||||
next if prev.nil? || prev.names.key?(l.language_code)
|
||||
|
||||
t.update_columns(event_id: ev.id)
|
||||
|
||||
ids_cause_of_locale_creation << t.id
|
||||
end
|
||||
|
||||
ev.destroy! unless MigrationTagVersion.where(event_id: ev.id).exists?
|
||||
end
|
||||
|
||||
# nico_tag_versions の Backfill
|
||||
MigrationNicoTagVersion.find_each do |et|
|
||||
ev =
|
||||
case et.event_type
|
||||
when 'create'
|
||||
post =
|
||||
MigrationPostVersion
|
||||
.where('JSON_CONTAINS(tags_json, ?) <> 0', { external_tag_id: et.tag_id }.to_json)
|
||||
.order(:created_at, :id)
|
||||
.first
|
||||
|
||||
if post
|
||||
MigrationEvent.find(post.event_id)
|
||||
else
|
||||
create_unknown_event!(et)
|
||||
end
|
||||
when 'update'
|
||||
MigrationEvent.create!(event_type: 'external_tags.update',
|
||||
created_by_user_id: et.created_by_user_id,
|
||||
created_at: et.created_at)
|
||||
end
|
||||
|
||||
et.update_columns(event_id: ev.id)
|
||||
end
|
||||
|
||||
# tag_versions の Backfill(異動および除票)
|
||||
MigrationTagVersion
|
||||
.where(event_type: ['update', 'discard'])
|
||||
.where.not(id: ids_cause_of_locale_creation)
|
||||
.find_each do |t|
|
||||
ev =
|
||||
case t.event_type
|
||||
when 'update'
|
||||
MigrationEvent.create!(event_type: 'tags.update',
|
||||
created_by_user_id: t.created_by_user_id,
|
||||
created_at: t.created_at)
|
||||
when 'discard'
|
||||
create_unknown_event!(t)
|
||||
end
|
||||
|
||||
t.update_columns(event_id: ev.id)
|
||||
end
|
||||
|
||||
# tag_versions の Backfill(起票のみ)
|
||||
MigrationTagVersion.where(event_type: 'create').find_each do |t|
|
||||
post =
|
||||
MigrationPostVersion
|
||||
.where('JSON_CONTAINS(tags_json, ?) <> 0', { tag_id: t.tag_id }.to_json)
|
||||
.order(:created_at, :id)
|
||||
.first
|
||||
|
||||
material = MigrationMaterialVersion.where(tag_id: t.tag_id).order(:created_at, :id).first
|
||||
|
||||
external_tag =
|
||||
MigrationNicoTagVersion
|
||||
.where(event_type: 'update')
|
||||
.where("CONCAT(' ', linked_tag_ids, ' ') LIKE ?", "% #{ t.tag_id } %")
|
||||
.order(:created_at, :id)
|
||||
.first
|
||||
|
||||
tag =
|
||||
MigrationTagVersion
|
||||
.where(event_type: 'update')
|
||||
.where("CONCAT(' ', parent_tag_ids, ' ') LIKE ?", "% #{ t.tag_id } %")
|
||||
.order(:created_at, :id)
|
||||
.first
|
||||
|
||||
target = nil
|
||||
if post
|
||||
target = post
|
||||
end
|
||||
if material && (!(target) || material.created_at < target.created_at)
|
||||
target = material
|
||||
end
|
||||
if external_tag && (!(target) || external_tag.created_at < target.created_at)
|
||||
target = external_tag
|
||||
end
|
||||
if tag && (!(target) || tag.created_at < target.created_at)
|
||||
target = tag
|
||||
end
|
||||
|
||||
ev =
|
||||
if target
|
||||
MigrationEvent.find(target.event_id)
|
||||
else
|
||||
create_unknown_event!(t)
|
||||
end
|
||||
|
||||
t.update_columns(event_id: ev.id)
|
||||
end
|
||||
|
||||
# tag_description_versions の Backfill
|
||||
MigrationTagDescriptionVersion.find_each do |td|
|
||||
ev = MigrationEvent.create!(event_type: "tag_descriptions.#{ td.event_type }",
|
||||
created_by_user_id: td.created_by_user_id,
|
||||
created_at: td.created_at)
|
||||
|
||||
td.update_columns(event_id: ev.id)
|
||||
end
|
||||
|
||||
# tag_group_versions の Backfill
|
||||
MigrationTagGroupVersion.find_each do |tg|
|
||||
ev = MigrationEvent.create!(event_type: "tag_groups.#{ tg.event_type }",
|
||||
created_by_user_id: tg.created_by_user_id,
|
||||
created_at: tg.created_at)
|
||||
|
||||
tg.update_columns(event_id: ev.id)
|
||||
end
|
||||
|
||||
change_column_null :post_versions, :event_id, false
|
||||
change_column_null :tag_versions, :event_id, false
|
||||
change_column_null :nico_tag_versions, :event_id, false
|
||||
change_column_null :material_versions, :event_id, false
|
||||
change_column_null :tag_description_versions, :event_id, false
|
||||
change_column_null :tag_group_versions, :event_id, false
|
||||
end
|
||||
|
||||
def down
|
||||
raise ActiveRecord::IrreversibleMigration, '戻せません.'
|
||||
end
|
||||
|
||||
def create_unknown_event! source
|
||||
MigrationEvent.create!(event_type: 'unknown',
|
||||
created_by_user_id: source.created_by_user_id,
|
||||
created_at: source.created_at)
|
||||
end
|
||||
end
|
||||
生成ファイル
+35
-1
@@ -10,7 +10,7 @@
|
||||
#
|
||||
# It's strongly recommended that you check this file into your version control system.
|
||||
|
||||
ActiveRecord::Schema[8.0].define(version: 2026_11_08_020000) do
|
||||
ActiveRecord::Schema[8.0].define(version: 2026_11_17_010000) do
|
||||
create_table "active_storage_attachments", charset: "utf8mb4", collation: "utf8mb4_0900_ai_ci", force: :cascade do |t|
|
||||
t.string "name", null: false
|
||||
t.string "record_type", null: false
|
||||
@@ -48,6 +48,21 @@ ActiveRecord::Schema[8.0].define(version: 2026_11_08_020000) do
|
||||
t.index ["tag_id"], name: "index_deerjikists_on_tag_id"
|
||||
end
|
||||
|
||||
create_table "events", charset: "utf8mb4", collation: "utf8mb4_0900_ai_ci", force: :cascade do |t|
|
||||
t.string "event_type", null: false
|
||||
t.text "reason"
|
||||
t.bigint "reverted_from_event_id"
|
||||
t.json "metadata"
|
||||
t.binary "ip_address", limit: 16
|
||||
t.bigint "created_by_user_id"
|
||||
t.datetime "created_at", null: false
|
||||
t.index ["created_at"], name: "index_events_on_created_at"
|
||||
t.index ["created_by_user_id"], name: "index_events_on_created_by_user_id"
|
||||
t.index ["event_type"], name: "index_events_on_event_type"
|
||||
t.index ["ip_address"], name: "index_events_on_ip_address"
|
||||
t.index ["reverted_from_event_id"], name: "index_events_on_reverted_from_event_id"
|
||||
end
|
||||
|
||||
create_table "external_tags", charset: "utf8mb4", collation: "utf8mb4_0900_ai_ci", force: :cascade do |t|
|
||||
t.string "platform", limit: 16, null: false
|
||||
t.string "name", null: false
|
||||
@@ -250,8 +265,10 @@ ActiveRecord::Schema[8.0].define(version: 2026_11_08_020000) do
|
||||
t.string "source_path"
|
||||
t.string "source_file_id"
|
||||
t.string "normalized_source_key"
|
||||
t.bigint "event_id", null: false
|
||||
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 ["event_id"], name: "index_material_versions_on_event_id"
|
||||
t.index ["file_blob_id"], name: "index_material_versions_on_file_blob_id"
|
||||
t.index ["material_id", "version_no"], name: "index_material_versions_on_material_id_and_version_no", unique: true
|
||||
t.index ["material_id"], name: "index_material_versions_on_material_id"
|
||||
@@ -301,11 +318,13 @@ ActiveRecord::Schema[8.0].define(version: 2026_11_08_020000) do
|
||||
t.bigint "tag_id", null: false
|
||||
t.integer "version_no", null: false
|
||||
t.string "event_type", null: false
|
||||
t.bigint "event_id", null: false
|
||||
t.datetime "created_at", null: false
|
||||
t.bigint "created_by_user_id"
|
||||
t.text "linked_tag_ids", null: false
|
||||
t.index ["created_at"], name: "index_nico_tag_versions_on_created_at"
|
||||
t.index ["created_by_user_id", "created_at"], name: "index_nico_tag_versions_on_created_by_user_id_and_created_at", order: { created_at: :desc }
|
||||
t.index ["event_id"], name: "index_nico_tag_versions_on_event_id"
|
||||
t.index ["tag_id", "created_at"], name: "index_nico_tag_versions_on_tag_id_and_created_at", order: { created_at: :desc }
|
||||
t.index ["tag_id", "version_no"], name: "index_nico_tag_versions_on_tag_id_and_version_no", unique: true
|
||||
t.check_constraint "`version_no` > 0", name: "nico_tag_versions_version_no_positive"
|
||||
@@ -379,10 +398,12 @@ ActiveRecord::Schema[8.0].define(version: 2026_11_08_020000) do
|
||||
t.text "parent_post_ids", null: false
|
||||
t.datetime "original_created_from"
|
||||
t.datetime "original_created_before"
|
||||
t.bigint "event_id", null: false
|
||||
t.datetime "created_at", null: false
|
||||
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 ["event_id"], name: "index_post_versions_on_event_id"
|
||||
t.index ["post_id", "version_no"], name: "index_post_versions_on_post_id_and_version_no", unique: true
|
||||
t.index ["post_id"], name: "index_post_versions_on_post_id"
|
||||
t.index ["video_ms", "post_id"], name: "idx_post_versions_video_ms_post_id"
|
||||
@@ -447,9 +468,11 @@ ActiveRecord::Schema[8.0].define(version: 2026_11_08_020000) do
|
||||
t.text "body", null: false
|
||||
t.string "source_language_code", limit: 16
|
||||
t.integer "source_version_no"
|
||||
t.bigint "event_id", null: false
|
||||
t.bigint "created_by_user_id"
|
||||
t.datetime "created_at", null: false
|
||||
t.index ["created_by_user_id"], name: "index_tag_description_versions_on_created_by_user_id"
|
||||
t.index ["event_id"], name: "index_tag_description_versions_on_event_id"
|
||||
t.index ["tag_id", "language_code", "version_no"], name: "idx_on_tag_id_language_code_version_no_ced77e57e6", unique: true
|
||||
t.index ["tag_id", "source_language_code", "source_version_no"], name: "fk_rails_4f13094dbc"
|
||||
t.index ["tag_id"], name: "index_tag_description_versions_on_tag_id"
|
||||
@@ -532,9 +555,11 @@ ActiveRecord::Schema[8.0].define(version: 2026_11_08_020000) do
|
||||
t.text "description"
|
||||
t.json "members", null: false
|
||||
t.json "placements", null: false
|
||||
t.bigint "event_id", null: false
|
||||
t.bigint "created_by_user_id"
|
||||
t.datetime "created_at", null: false
|
||||
t.index ["created_by_user_id"], name: "index_tag_group_versions_on_created_by_user_id"
|
||||
t.index ["event_id"], name: "index_tag_group_versions_on_event_id"
|
||||
t.index ["tag_group_id", "version_no"], name: "index_tag_group_versions_on_tag_group_id_and_version_no", unique: true
|
||||
t.index ["tag_group_id"], name: "index_tag_group_versions_on_tag_group_id"
|
||||
t.check_constraint "`version_no` > 0", name: "chk_tag_group_versions_version_no_positive"
|
||||
@@ -610,11 +635,13 @@ ActiveRecord::Schema[8.0].define(version: 2026_11_08_020000) do
|
||||
t.text "aliases", null: false
|
||||
t.text "parent_tag_ids", null: false
|
||||
t.datetime "deprecated_at"
|
||||
t.bigint "event_id", null: false
|
||||
t.datetime "created_at", null: false
|
||||
t.bigint "created_by_user_id"
|
||||
t.json "names", null: false
|
||||
t.index ["created_at"], name: "index_tag_versions_on_created_at"
|
||||
t.index ["created_by_user_id", "created_at"], name: "index_tag_versions_on_created_by_user_id_and_created_at", order: { created_at: :desc }
|
||||
t.index ["event_id"], name: "index_tag_versions_on_event_id"
|
||||
t.index ["tag_id", "created_at"], name: "index_tag_versions_on_tag_id_and_created_at", order: { created_at: :desc }
|
||||
t.index ["tag_id", "version_no"], name: "index_tag_versions_on_tag_id_and_version_no", unique: true
|
||||
t.check_constraint "`version_no` > 0", name: "tag_versions_version_no_positive"
|
||||
@@ -770,6 +797,7 @@ ActiveRecord::Schema[8.0].define(version: 2026_11_08_020000) do
|
||||
|
||||
add_foreign_key "active_storage_attachments", "active_storage_blobs", column: "blob_id"
|
||||
add_foreign_key "active_storage_variant_records", "active_storage_blobs", column: "blob_id"
|
||||
add_foreign_key "events", "events", column: "reverted_from_event_id"
|
||||
add_foreign_key "gekanator_ai_runs", "gekanator_question_suggestions"
|
||||
add_foreign_key "gekanator_games", "posts", column: "correct_post_id"
|
||||
add_foreign_key "gekanator_games", "posts", column: "guessed_post_id"
|
||||
@@ -791,6 +819,7 @@ ActiveRecord::Schema[8.0].define(version: 2026_11_08_020000) do
|
||||
add_foreign_key "material_sync_sources", "users", column: "created_by_user_id"
|
||||
add_foreign_key "material_sync_sources", "users", column: "updated_by_user_id"
|
||||
add_foreign_key "material_sync_suppressions", "users", column: "created_by_user_id"
|
||||
add_foreign_key "material_versions", "events"
|
||||
add_foreign_key "material_versions", "materials"
|
||||
add_foreign_key "material_versions", "materials", column: "parent_id"
|
||||
add_foreign_key "material_versions", "users", column: "created_by_user_id"
|
||||
@@ -801,6 +830,7 @@ ActiveRecord::Schema[8.0].define(version: 2026_11_08_020000) do
|
||||
add_foreign_key "materials", "users", column: "updated_by_user_id"
|
||||
add_foreign_key "nico_tag_relations", "external_tags", column: "nico_tag_id"
|
||||
add_foreign_key "nico_tag_relations", "tags"
|
||||
add_foreign_key "nico_tag_versions", "events"
|
||||
add_foreign_key "nico_tag_versions", "users", column: "created_by_user_id"
|
||||
add_foreign_key "post_external_tags", "external_tags"
|
||||
add_foreign_key "post_external_tags", "posts"
|
||||
@@ -812,10 +842,12 @@ ActiveRecord::Schema[8.0].define(version: 2026_11_08_020000) do
|
||||
add_foreign_key "post_tags", "posts"
|
||||
add_foreign_key "post_tags", "tags"
|
||||
add_foreign_key "post_tags", "users", column: "created_user_id"
|
||||
add_foreign_key "post_versions", "events"
|
||||
add_foreign_key "post_versions", "posts"
|
||||
add_foreign_key "post_versions", "users", column: "created_by_user_id"
|
||||
add_foreign_key "posts", "users", column: "uploaded_user_id"
|
||||
add_foreign_key "settings", "users"
|
||||
add_foreign_key "tag_description_versions", "events"
|
||||
add_foreign_key "tag_description_versions", "tag_description_versions", column: ["tag_id", "source_language_code", "source_version_no"], primary_key: ["tag_id", "language_code", "version_no"]
|
||||
add_foreign_key "tag_descriptions", "languages", column: "language_code", primary_key: "code"
|
||||
add_foreign_key "tag_descriptions", "tag_description_versions", column: ["tag_id", "source_language_code", "source_version_no"], primary_key: ["tag_id", "language_code", "version_no"]
|
||||
@@ -834,6 +866,7 @@ ActiveRecord::Schema[8.0].define(version: 2026_11_08_020000) do
|
||||
add_foreign_key "tag_group_tags", "tag_groups"
|
||||
add_foreign_key "tag_group_tags", "tags"
|
||||
add_foreign_key "tag_group_tags", "users", column: "created_by_user_id"
|
||||
add_foreign_key "tag_group_versions", "events"
|
||||
add_foreign_key "tag_groups", "users", column: "created_by_user_id"
|
||||
add_foreign_key "tag_groups", "users", column: "updated_by_user_id"
|
||||
add_foreign_key "tag_implications", "tags"
|
||||
@@ -843,6 +876,7 @@ ActiveRecord::Schema[8.0].define(version: 2026_11_08_020000) do
|
||||
add_foreign_key "tag_names", "tags"
|
||||
add_foreign_key "tag_similarities", "tags"
|
||||
add_foreign_key "tag_similarities", "tags", column: "target_tag_id"
|
||||
add_foreign_key "tag_versions", "events"
|
||||
add_foreign_key "tag_versions", "users", column: "created_by_user_id"
|
||||
add_foreign_key "theatre_comments", "theatres"
|
||||
add_foreign_key "theatre_comments", "users"
|
||||
|
||||
@@ -67,129 +67,131 @@ namespace :nico do
|
||||
end
|
||||
|
||||
data = JSON.parse(stdout)
|
||||
data.each do |datum|
|
||||
code = datum['code']
|
||||
post =
|
||||
Post
|
||||
.where('url REGEXP ?', "nicovideo\\.jp/watch/#{ Regexp.escape(code) }([^0-9]|$)")
|
||||
.first
|
||||
VersionRecorder.with_event(event_type: 'posts.sync', created_by_user: nil) do
|
||||
data.each do |datum|
|
||||
code = datum['code']
|
||||
post =
|
||||
Post
|
||||
.where('url REGEXP ?', "nicovideo\\.jp/watch/#{ Regexp.escape(code) }([^0-9]|$)")
|
||||
.first
|
||||
|
||||
title = datum['title']
|
||||
original_created_at = datum['uploaded_at'] &&
|
||||
Time.strptime(datum['uploaded_at'], '%Y-%m-%d %H:%M:%S')
|
||||
original_created_from = original_created_at&.change(sec: 0)
|
||||
original_created_before = original_created_from&.+(1.minute)
|
||||
title = datum['title']
|
||||
original_created_at = datum['uploaded_at'] &&
|
||||
Time.strptime(datum['uploaded_at'], '%Y-%m-%d %H:%M:%S')
|
||||
original_created_from = original_created_at&.change(sec: 0)
|
||||
original_created_before = original_created_from&.+(1.minute)
|
||||
|
||||
post_created = false
|
||||
post_changed = false
|
||||
post_created = false
|
||||
post_changed = false
|
||||
|
||||
if post
|
||||
attrs = { title:, original_created_from:, original_created_before: }
|
||||
if post
|
||||
attrs = { title:, original_created_from:, original_created_before: }
|
||||
|
||||
unless post.thumbnail.attached?
|
||||
thumbnail_base = fetch_thumbnail.(post.url) rescue nil
|
||||
unless post.thumbnail.attached?
|
||||
thumbnail_base = fetch_thumbnail.(post.url) rescue nil
|
||||
if thumbnail_base.present?
|
||||
attrs[:thumbnail_base] = thumbnail_base
|
||||
begin
|
||||
post.attach_thumbnail_from_url!(thumbnail_base)
|
||||
rescue Post::RemoteThumbnailFetchFailed => e
|
||||
payload = {
|
||||
post_id: post.id,
|
||||
thumbnail_base:,
|
||||
error: e.class.name,
|
||||
message: e.message }
|
||||
Rails.logger.info("nico_sync_thumbnail_fetch_failed #{ payload.to_json }")
|
||||
end
|
||||
end
|
||||
end
|
||||
|
||||
post.assign_attributes(attrs)
|
||||
post_changed = post.changed?
|
||||
if post_changed
|
||||
post.save!
|
||||
end
|
||||
else
|
||||
post_created = true
|
||||
url = "https://www.nicovideo.jp/watch/#{ code }"
|
||||
thumbnail_base = fetch_thumbnail.(url) rescue nil
|
||||
post = Post.new(title:, url:, thumbnail_base:, uploaded_user: nil,
|
||||
original_created_from:, original_created_before:)
|
||||
if thumbnail_base.present?
|
||||
attrs[:thumbnail_base] = thumbnail_base
|
||||
begin
|
||||
post.attach_thumbnail_from_url!(thumbnail_base)
|
||||
rescue Post::RemoteThumbnailFetchFailed => e
|
||||
payload = {
|
||||
post_id: post.id,
|
||||
post_id: nil,
|
||||
thumbnail_base:,
|
||||
error: e.class.name,
|
||||
message: e.message }
|
||||
Rails.logger.info("nico_sync_thumbnail_fetch_failed #{ payload.to_json }")
|
||||
end
|
||||
end
|
||||
post.save!
|
||||
sync_post_tags!(post, [Tag.tagme.id, Tag.bot.id, Tag.niconico.id, Tag.video.id])
|
||||
end
|
||||
|
||||
post.assign_attributes(attrs)
|
||||
post_changed = post.changed?
|
||||
if post_changed
|
||||
post.save!
|
||||
end
|
||||
else
|
||||
post_created = true
|
||||
url = "https://www.nicovideo.jp/watch/#{ code }"
|
||||
thumbnail_base = fetch_thumbnail.(url) rescue nil
|
||||
post = Post.new(title:, url:, thumbnail_base:, uploaded_user: nil,
|
||||
original_created_from:, original_created_before:)
|
||||
if thumbnail_base.present?
|
||||
begin
|
||||
post.attach_thumbnail_from_url!(thumbnail_base)
|
||||
rescue Post::RemoteThumbnailFetchFailed => e
|
||||
payload = {
|
||||
post_id: nil,
|
||||
thumbnail_base:,
|
||||
error: e.class.name,
|
||||
message: e.message }
|
||||
Rails.logger.info("nico_sync_thumbnail_fetch_failed #{ payload.to_json }")
|
||||
# 既存のタグ Id. 集合
|
||||
kept_tag_ids = post.tags.pluck(:id).to_set
|
||||
|
||||
# 既存の外部タグ Id. 集合
|
||||
kept_external_tag_ids = post.external_tags.nico.pluck(:id).to_set
|
||||
|
||||
# 記載すべき外部タグ Id. のリスト
|
||||
desired_external_tag_ids = []
|
||||
|
||||
# 記載すべき内部タグ Id. のリスト
|
||||
desired_tag_ids = kept_tag_ids.to_a
|
||||
|
||||
datum['tags'].each do |raw|
|
||||
name = TagNameSanitisationRule.sanitise("nico:#{ raw }").delete_prefix('nico:')
|
||||
tag = ExternalTag.find_or_create_by!(platform: :nico, name:)
|
||||
|
||||
unless tag.nico_tag_versions.exists?
|
||||
NicoTagVersionRecorder.record!(external_tag: tag,
|
||||
event_type: :create,
|
||||
created_by_user: nil)
|
||||
end
|
||||
|
||||
desired_external_tag_ids << tag.id
|
||||
|
||||
# 新たに記載される外部タグと連携される内部タグを記載
|
||||
# 連携タグは記載すれども消除せず.
|
||||
unless tag.id.in?(kept_external_tag_ids)
|
||||
desired_tag_ids.concat(tag.linked_tags.pluck(:id))
|
||||
end
|
||||
end
|
||||
post.save!
|
||||
sync_post_tags!(post, [Tag.tagme.id, Tag.bot.id, Tag.niconico.id, Tag.video.id])
|
||||
end
|
||||
|
||||
# 既存のタグ Id. 集合
|
||||
kept_tag_ids = post.tags.pluck(:id).to_set
|
||||
|
||||
# 既存の外部タグ Id. 集合
|
||||
kept_external_tag_ids = post.external_tags.nico.pluck(:id).to_set
|
||||
|
||||
# 記載すべき外部タグ Id. のリスト
|
||||
desired_external_tag_ids = []
|
||||
|
||||
# 記載すべき内部タグ Id. のリスト
|
||||
desired_tag_ids = kept_tag_ids.to_a
|
||||
|
||||
datum['tags'].each do |raw|
|
||||
name = TagNameSanitisationRule.sanitise("nico:#{ raw }").delete_prefix('nico:')
|
||||
tag = ExternalTag.find_or_create_by!(platform: :nico, name:)
|
||||
|
||||
unless tag.nico_tag_versions.exists?
|
||||
NicoTagVersionRecorder.record!(external_tag: tag,
|
||||
event_type: :create,
|
||||
created_by_user: nil)
|
||||
deerjikist = Deerjikist.find_by(platform: :nico, code: datum['user'])
|
||||
if deerjikist
|
||||
desired_tag_ids << deerjikist.tag_id
|
||||
elsif !(Tag.where(id: kept_tag_ids).where(category: :deerjikist).exists?)
|
||||
desired_tag_ids << Tag.no_deerjikist.id
|
||||
end
|
||||
|
||||
desired_external_tag_ids << tag.id
|
||||
|
||||
# 新たに記載される外部タグと連携される内部タグを記載
|
||||
# 連携タグは記載すれども消除せず.
|
||||
unless tag.id.in?(kept_external_tag_ids)
|
||||
desired_tag_ids.concat(tag.linked_tags.pluck(:id))
|
||||
end
|
||||
end
|
||||
|
||||
deerjikist = Deerjikist.find_by(platform: :nico, code: datum['user'])
|
||||
if deerjikist
|
||||
desired_tag_ids << deerjikist.tag_id
|
||||
elsif !(Tag.where(id: kept_tag_ids).where(category: :deerjikist).exists?)
|
||||
desired_tag_ids << Tag.no_deerjikist.id
|
||||
end
|
||||
|
||||
desired_external_tag_ids.uniq!
|
||||
desired_tag_ids.uniq!
|
||||
|
||||
# 外部タグの記載に際しては “bot 操作” タグを記載しなぃ.
|
||||
if kept_tag_ids != desired_tag_ids.to_set
|
||||
desired_tag_ids << Tag.bot.id
|
||||
desired_external_tag_ids.uniq!
|
||||
desired_tag_ids.uniq!
|
||||
end
|
||||
|
||||
tags_changed =
|
||||
kept_tag_ids != desired_tag_ids.to_set ||
|
||||
kept_external_tag_ids != desired_external_tag_ids.to_set
|
||||
# 外部タグの記載に際しては “bot 操作” タグを記載しなぃ.
|
||||
if kept_tag_ids != desired_tag_ids.to_set
|
||||
desired_tag_ids << Tag.bot.id
|
||||
desired_tag_ids.uniq!
|
||||
end
|
||||
|
||||
sync_post_tags!(post, desired_tag_ids, current_tag_ids: kept_tag_ids)
|
||||
sync_post_external_tags!(post, desired_external_tag_ids,
|
||||
current_external_tag_ids: kept_external_tag_ids)
|
||||
tags_changed =
|
||||
kept_tag_ids != desired_tag_ids.to_set ||
|
||||
kept_external_tag_ids != desired_external_tag_ids.to_set
|
||||
|
||||
if post_created
|
||||
PostVersionRecorder.record!(post:, event_type: :create, created_by_user: nil)
|
||||
elsif post_changed || tags_changed
|
||||
PostVersionRecorder.ensure_snapshot!(post, created_by_user: nil)
|
||||
PostVersionRecorder.record!(post:, event_type: :update, created_by_user: nil)
|
||||
sync_post_tags!(post, desired_tag_ids, current_tag_ids: kept_tag_ids)
|
||||
sync_post_external_tags!(post, desired_external_tag_ids,
|
||||
current_external_tag_ids: kept_external_tag_ids)
|
||||
|
||||
if post_created
|
||||
PostVersionRecorder.record!(post:, event_type: :create, created_by_user: nil)
|
||||
elsif post_changed || tags_changed
|
||||
PostVersionRecorder.ensure_snapshot!(post, created_by_user: nil)
|
||||
PostVersionRecorder.record!(post:, event_type: :update, created_by_user: nil)
|
||||
end
|
||||
end
|
||||
end
|
||||
end
|
||||
|
||||
@@ -102,6 +102,7 @@ RSpec.describe 'Tag group persistence constraints' do
|
||||
6.times { nodes = [{ 'tag_id' => tag.id, 'children' => nodes }] }
|
||||
reject_statement do
|
||||
insert_group_row('tag_group_versions', {
|
||||
event_id: create_event!(event_type: 'unknown').id,
|
||||
tag_group_id: group_id, version_no: 2, event_type: 'update', name: '制約確認',
|
||||
members: [{ 'tag_id' => tag.id, 'version_no' => tag.version_no }].to_json,
|
||||
placements: nodes.to_json, created_at: Time.current })
|
||||
|
||||
@@ -10,6 +10,7 @@ RSpec.describe 'TagVersion names database constraint' do
|
||||
|
||||
def insert_snapshot!(snapshot)
|
||||
TagVersion.insert_all!([{ tag_id: tag.id, version_no: 1, event_type: 'create',
|
||||
event_id: create_event!(event_type: 'unknown').id,
|
||||
name: 'snapshot_name', category: 'general',
|
||||
aliases: '', parent_tag_ids: '', names: snapshot,
|
||||
created_at: Time.current }])
|
||||
|
||||
@@ -9,7 +9,9 @@ RSpec.describe HistoryAccess do
|
||||
locale
|
||||
rows = ['ja', 'ain'].flat_map do |language|
|
||||
['create', 'discard', 'restore'].each_with_index.map do |event, index|
|
||||
TagDescriptionVersion.create!(tag_id: tag.id, language_code: language,
|
||||
TagDescriptionVersion.create!(
|
||||
event_id: create_event!(event_type: 'unknown').id,
|
||||
tag_id: tag.id, language_code: language,
|
||||
version_no: index + 1, event_type: language == 'ain' ? 'update' : event,
|
||||
body: "#{ language } #{ index }", created_at: Time.utc(2024))
|
||||
end
|
||||
@@ -28,7 +30,9 @@ RSpec.describe HistoryAccess do
|
||||
public_metadata = described_class.set(user: nil) { described_class.authority }
|
||||
admin = create(:user, :admin)
|
||||
admin_metadata = described_class.set(user: admin) { described_class.authority }
|
||||
TagVersion.create!(tag:, version_no: 1, event_type: 'discard', name: 'private',
|
||||
TagVersion.create!(
|
||||
event_id: create_event!(event_type: 'unknown').id,
|
||||
tag:, version_no: 1, event_type: 'discard', name: 'private',
|
||||
category: 'general',
|
||||
names: { ja: { name: 'private', script_code: 'Jpan',
|
||||
auto_generated: false, aliases: [] } },
|
||||
@@ -52,7 +56,9 @@ RSpec.describe HistoryAccess do
|
||||
blob = ActiveStorage::Blob.create_before_direct_upload!(filename: 'private.png',
|
||||
byte_size: 1, checksum: Base64.strict_encode64('checksum'), content_type: 'image/png')
|
||||
ActiveStorage::Attachment.create!(name: 'thumbnail', record: post, blob:)
|
||||
PostVersion.create!(post:, version_no: 1, event_type: 'discard', url: post.url,
|
||||
PostVersion.create!(
|
||||
event_id: create_event!(event_type: 'unknown').id,
|
||||
post:, version_no: 1, event_type: 'discard', url: post.url,
|
||||
title: 'private', tags: '', tags_json: [], parent_post_ids: '', created_at: Time.utc(2024))
|
||||
variant = ActiveStorage::VariantRecord.create!(blob:, variation_digest: 'spec-variation')
|
||||
derived = ActiveStorage::Blob.create_before_direct_upload!(filename: 'derived.png',
|
||||
@@ -78,16 +84,21 @@ RSpec.describe 'Counts artifact policy and external references' do
|
||||
|
||||
it 'does not expose a private linked tag ID through an external history snapshot' do
|
||||
tag = create(:tag, primary_name: 'private-linked-name')
|
||||
TagVersion.create!(tag:, version_no: 1, event_type: 'discard', name: 'private-linked-name',
|
||||
TagVersion.create!(
|
||||
event_id: create_event!(event_type: 'unknown').id,
|
||||
tag:, version_no: 1, event_type: 'discard', name: 'private-linked-name',
|
||||
category: 'general', aliases: '', parent_tag_ids: '', created_at: Time.utc(2024),
|
||||
names: { ja: { name: 'private-linked-name', script_code: 'Jpan',
|
||||
auto_generated: false, aliases: [] } })
|
||||
external = create(:external_tag, name: 'public-external')
|
||||
row = NicoTagVersion.create!(external_tag: external, version_no: 1, event_type: 'create',
|
||||
event_id: create_event!(event_type: 'unknown').id,
|
||||
linked_tag_ids: tag.id.to_s,
|
||||
created_at: Time.utc(2024))
|
||||
post = create(:post)
|
||||
snapshot = PostVersion.create!(post:, version_no: 1, event_type: 'create',
|
||||
snapshot = PostVersion.create!(
|
||||
event_id: create_event!(event_type: 'unknown').id,
|
||||
post:, version_no: 1, event_type: 'create',
|
||||
title: 'external reference', url: post.url, tags: '',
|
||||
tags_json: [{ external_tag_id: external.id }], parent_post_ids: '',
|
||||
created_at: Time.utc(2024, 2))
|
||||
@@ -99,6 +110,7 @@ RSpec.describe 'Counts artifact policy and external references' do
|
||||
expect(HistoryAccess.visible(NicoTagVersion.where(id: row.id))).to exist
|
||||
end
|
||||
public_row = NicoTagVersion.create!(external_tag: external, version_no: 2, event_type: 'update',
|
||||
event_id: create_event!(event_type: 'unknown').id,
|
||||
linked_tag_ids: '',
|
||||
created_at: Time.utc(2024, 7))
|
||||
HistoryAccess.set(user: nil) do
|
||||
@@ -112,13 +124,17 @@ RSpec.describe 'Counts artifact policy and external references' do
|
||||
child = create(:tag, primary_name: 'referencing child')
|
||||
[[parent, 'discard', '', 'private parent'],
|
||||
[child, 'create', parent.id.to_s, 'referencing child']].each do |tag, event, parents, name|
|
||||
TagVersion.create!(tag:, version_no: 1, event_type: event, name:,
|
||||
TagVersion.create!(
|
||||
event_id: create_event!(event_type: 'unknown').id,
|
||||
tag:, version_no: 1, event_type: event, name:,
|
||||
category: 'general', aliases: '', parent_tag_ids: parents, created_at: Time.utc(2023),
|
||||
names: { ja: { name:, script_code: 'Jpan',
|
||||
auto_generated: false, aliases: [] } })
|
||||
end
|
||||
post = create(:post)
|
||||
row = PostVersion.create!(post:, version_no: 1, event_type: 'create', title: 'snapshot',
|
||||
row = PostVersion.create!(
|
||||
event_id: create_event!(event_type: 'unknown').id,
|
||||
post:, version_no: 1, event_type: 'create', title: 'snapshot',
|
||||
url: post.url, tags: '', parent_post_ids: '',
|
||||
tags_json: [{ tag_id: child.id, version_no: 1, name: 'referencing child', sections: [] }],
|
||||
created_at: Time.utc(2024))
|
||||
|
||||
@@ -23,9 +23,22 @@ RSpec.describe 'Locale activation', type: :model do
|
||||
.and_raise('backfill failed')
|
||||
end
|
||||
|
||||
it 'groups all tag histories from locale creation into one event' do
|
||||
previous_ids = TagVersion.pluck(:id)
|
||||
|
||||
expect { build_locale.save! }.to change { event_rows.length }.by(1)
|
||||
|
||||
event = event_rows.last
|
||||
expect(event).to include('event_type' => 'locales.create', 'created_by_user_id' => nil)
|
||||
versions = TagVersion.where.not(id: previous_ids)
|
||||
expect(versions.pluck(:tag_id)).to include(first.id, second.id)
|
||||
expect(versions.pluck(:event_id).uniq).to eq([event.fetch('id')])
|
||||
end
|
||||
|
||||
it 'rolls back a newly created locale and the preceding generated names' do
|
||||
locale = build_locale
|
||||
fail_second_generation!
|
||||
events = event_rows
|
||||
|
||||
expect { locale.save! }.to raise_error('backfill failed')
|
||||
|
||||
@@ -33,6 +46,7 @@ RSpec.describe 'Locale activation', type: :model do
|
||||
expect(generated_names).to be_empty
|
||||
expect(first.reload.name('ja')).to eq('activation_first')
|
||||
expect(second.reload.name('ja')).to eq('activation_second')
|
||||
expect(event_rows).to eq(events)
|
||||
end
|
||||
|
||||
it 'does not backfill while the locale is inactive' do
|
||||
@@ -45,7 +59,14 @@ RSpec.describe 'Locale activation', type: :model do
|
||||
locale = build_locale(deprecated_at: Time.current)
|
||||
locale.save!
|
||||
|
||||
locale.update!(deprecated_at: nil)
|
||||
previous_ids = TagVersion.pluck(:id)
|
||||
expect { locale.update!(deprecated_at: nil) }.to change { event_rows.length }.by(1)
|
||||
|
||||
event = event_rows.last
|
||||
expect(event).to include('event_type' => 'locales.restore', 'created_by_user_id' => nil)
|
||||
versions = TagVersion.where.not(id: previous_ids)
|
||||
expect(versions.pluck(:tag_id)).to include(first.id, second.id)
|
||||
expect(versions.pluck(:event_id).uniq).to eq([event.fetch('id')])
|
||||
|
||||
expect(generated_names.pluck(:tag_id)).to contain_exactly(first.id, second.id)
|
||||
expect(generated_names).to all(have_attributes(
|
||||
@@ -57,11 +78,13 @@ RSpec.describe 'Locale activation', type: :model do
|
||||
locale.save!
|
||||
previous_deprecated_at = locale.reload.deprecated_at
|
||||
fail_second_generation!
|
||||
events = event_rows
|
||||
|
||||
expect { locale.update!(deprecated_at: nil) }.to raise_error('backfill failed')
|
||||
|
||||
expect(locale.reload.deprecated_at).to eq(previous_deprecated_at)
|
||||
expect(generated_names).to be_empty
|
||||
expect(event_rows).to eq(events)
|
||||
end
|
||||
|
||||
it 'preserves a human primary through deactivation and repeated activation' do
|
||||
|
||||
@@ -12,20 +12,20 @@ RSpec.describe PostVersion, type: :model do
|
||||
|
||||
let!(:post_version) do
|
||||
PostVersion.create!(
|
||||
post: post_record,
|
||||
version_no: 1,
|
||||
event_type: 'create',
|
||||
title: post_record.title,
|
||||
url: post_record.url,
|
||||
thumbnail_base: post_record.thumbnail_base,
|
||||
tags: post_record.snapshot_tag_names.join(' '),
|
||||
tags_json: post_record.snapshot_tags_json,
|
||||
parent_post_ids: post_record.snapshot_parent_post_ids.join(' '),
|
||||
original_created_from: post_record.original_created_from,
|
||||
original_created_before: post_record.original_created_before,
|
||||
created_at: Time.current,
|
||||
created_by_user: nil
|
||||
)
|
||||
event_id: create_event!(event_type: 'unknown').id,
|
||||
post: post_record,
|
||||
version_no: 1,
|
||||
event_type: 'create',
|
||||
title: post_record.title,
|
||||
url: post_record.url,
|
||||
thumbnail_base: post_record.thumbnail_base,
|
||||
tags: post_record.snapshot_tag_names.join(' '),
|
||||
tags_json: post_record.snapshot_tags_json,
|
||||
parent_post_ids: post_record.snapshot_parent_post_ids.join(' '),
|
||||
original_created_from: post_record.original_created_from,
|
||||
original_created_before: post_record.original_created_before,
|
||||
created_at: Time.current,
|
||||
created_by_user: nil)
|
||||
end
|
||||
|
||||
it 'is read only after create' do
|
||||
|
||||
@@ -34,6 +34,31 @@ RSpec.describe TagNameSanitisationRule, type: :model do
|
||||
described_class.create!(priority: 10, source_pattern: 'foo_', replacement: 'foo')
|
||||
end
|
||||
|
||||
it 'groups renames, merges and affected post histories into one event' do
|
||||
target = create(:tag, primary_name: 'foobar')
|
||||
source = create(:tag, primary_name: 'temporary_source')
|
||||
renamed = create(:tag, primary_name: 'temporary_rename')
|
||||
source.tag_name('ja').update_columns(name: 'foo_bar')
|
||||
renamed.tag_name('ja').update_columns(name: 'foo_baz')
|
||||
post = create(:post)
|
||||
PostTag.create!(post:, tag: source)
|
||||
previous_tag_ids = TagVersion.pluck(:id)
|
||||
previous_post_ids = PostVersion.pluck(:id)
|
||||
|
||||
expect { described_class.apply! }.to change { event_rows.length }.by(1)
|
||||
|
||||
event = event_rows.last
|
||||
expect(event).to include(
|
||||
'event_type' => 'tag_name_sanitisation_rules.apply', 'created_by_user_id' => nil)
|
||||
tag_versions = TagVersion.where.not(id: previous_tag_ids)
|
||||
expect(tag_versions.pluck(:tag_id).uniq).to contain_exactly(target.id, source.id, renamed.id)
|
||||
expect(tag_versions.pluck(:event_type)).to include('discard', 'update')
|
||||
expect(tag_versions.pluck(:event_id).uniq).to eq([event.fetch('id')])
|
||||
post_versions = PostVersion.where.not(id: previous_post_ids)
|
||||
expect(post_versions.pluck(:post_id).uniq).to eq([post.id])
|
||||
expect(post_versions.pluck(:event_id).uniq).to eq([event.fetch('id')])
|
||||
end
|
||||
|
||||
[:primary, :alias].each do |source_kind|
|
||||
it "keeps the primary identity when a #{ source_kind } collides within its Tag" do
|
||||
tag = create(:tag, primary_name: source_kind == :primary ? 'temporary' : 'foobar')
|
||||
@@ -83,6 +108,7 @@ RSpec.describe TagNameSanitisationRule, type: :model do
|
||||
PostTag.create!(post:, tag: source)
|
||||
models = [Tag, TagName, TagVersion, TagDescription, TagDescriptionVersion, PostTag]
|
||||
snapshots = models.map { |model| model.order(*Array(model.primary_key)).map(&:attributes) }
|
||||
events = event_rows
|
||||
|
||||
expect { described_class.apply! }.to raise_error(ActiveRecord::RecordInvalid)
|
||||
|
||||
@@ -90,6 +116,7 @@ RSpec.describe TagNameSanitisationRule, type: :model do
|
||||
model.order(*Array(model.primary_key)).map(&:attributes)
|
||||
end
|
||||
expect(after_state).to eq(snapshots)
|
||||
expect(event_rows).to eq(events)
|
||||
expect(post.reload.tags).to contain_exactly(source)
|
||||
expect(target.reload.name('ja')).to eq('foobar')
|
||||
end
|
||||
|
||||
@@ -665,20 +665,20 @@ RSpec.describe Tag, type: :model do
|
||||
|
||||
def create_post_version_for!(post, version_no: 1, event_type: 'create', created_by_user: nil)
|
||||
PostVersion.create!(
|
||||
post: post,
|
||||
version_no: version_no,
|
||||
event_type: event_type,
|
||||
title: post.title,
|
||||
url: post.url,
|
||||
thumbnail_base: post.thumbnail_base,
|
||||
tags: snapshot_tags(post),
|
||||
tags_json: post.snapshot_tags_json,
|
||||
parent_post_ids: post.snapshot_parent_post_ids.join(' '),
|
||||
original_created_from: post.original_created_from,
|
||||
original_created_before: post.original_created_before,
|
||||
created_at: Time.current,
|
||||
created_by_user: created_by_user
|
||||
)
|
||||
event_id: create_event!(event_type: 'unknown').id,
|
||||
post: post,
|
||||
version_no: version_no,
|
||||
event_type: event_type,
|
||||
title: post.title,
|
||||
url: post.url,
|
||||
thumbnail_base: post.thumbnail_base,
|
||||
tags: snapshot_tags(post),
|
||||
tags_json: post.snapshot_tags_json,
|
||||
parent_post_ids: post.snapshot_parent_post_ids.join(' '),
|
||||
original_created_from: post.original_created_from,
|
||||
original_created_before: post.original_created_before,
|
||||
created_at: Time.current,
|
||||
created_by_user: created_by_user)
|
||||
end
|
||||
|
||||
context 'when post versions are enabled' do
|
||||
|
||||
@@ -6,17 +6,18 @@ RSpec.describe VersionRecord, type: :model do
|
||||
|
||||
it 'makes TagVersion read only after create' do
|
||||
version = TagVersion.create!(
|
||||
tag: tag,
|
||||
version_no: 1,
|
||||
event_type: 'create',
|
||||
name: primary_tag_name_for(tag, 'ja').name,
|
||||
category: tag.category,
|
||||
aliases: '',
|
||||
names: { ja: { name: primary_tag_name_for(tag, 'ja').name,
|
||||
script_code: 'Jpan', auto_generated: false, aliases: [] } },
|
||||
parent_tag_ids: '',
|
||||
created_at: Time.current,
|
||||
created_by_user: nil)
|
||||
event_id: create_event!(event_type: 'unknown').id,
|
||||
tag: tag,
|
||||
version_no: 1,
|
||||
event_type: 'create',
|
||||
name: primary_tag_name_for(tag, 'ja').name,
|
||||
category: tag.category,
|
||||
aliases: '',
|
||||
names: { ja: { name: primary_tag_name_for(tag, 'ja').name,
|
||||
script_code: 'Jpan', auto_generated: false, aliases: [] } },
|
||||
parent_tag_ids: '',
|
||||
created_at: Time.current,
|
||||
created_by_user: nil)
|
||||
|
||||
expect {
|
||||
version.update!(name: 'changed')
|
||||
@@ -25,17 +26,18 @@ RSpec.describe VersionRecord, type: :model do
|
||||
|
||||
it 'prevents TagVersion destroy' do
|
||||
version = TagVersion.create!(
|
||||
tag: tag,
|
||||
version_no: 1,
|
||||
event_type: 'create',
|
||||
name: primary_tag_name_for(tag, 'ja').name,
|
||||
category: tag.category,
|
||||
aliases: '',
|
||||
names: { ja: { name: primary_tag_name_for(tag, 'ja').name,
|
||||
script_code: 'Jpan', auto_generated: false, aliases: [] } },
|
||||
parent_tag_ids: '',
|
||||
created_at: Time.current,
|
||||
created_by_user: nil)
|
||||
event_id: create_event!(event_type: 'unknown').id,
|
||||
tag: tag,
|
||||
version_no: 1,
|
||||
event_type: 'create',
|
||||
name: primary_tag_name_for(tag, 'ja').name,
|
||||
category: tag.category,
|
||||
aliases: '',
|
||||
names: { ja: { name: primary_tag_name_for(tag, 'ja').name,
|
||||
script_code: 'Jpan', auto_generated: false, aliases: [] } },
|
||||
parent_tag_ids: '',
|
||||
created_at: Time.current,
|
||||
created_by_user: nil)
|
||||
|
||||
expect {
|
||||
version.destroy!
|
||||
@@ -44,13 +46,13 @@ RSpec.describe VersionRecord, type: :model do
|
||||
|
||||
it 'makes NicoTagVersion read only after create' do
|
||||
version = NicoTagVersion.create!(
|
||||
external_tag: nico_tag,
|
||||
version_no: 1,
|
||||
event_type: 'create',
|
||||
linked_tag_ids: '',
|
||||
created_at: Time.current,
|
||||
created_by_user: nil
|
||||
)
|
||||
event_id: create_event!(event_type: 'unknown').id,
|
||||
external_tag: nico_tag,
|
||||
version_no: 1,
|
||||
event_type: 'create',
|
||||
linked_tag_ids: '',
|
||||
created_at: Time.current,
|
||||
created_by_user: nil)
|
||||
|
||||
expect {
|
||||
version.update!(linked_tag_ids: '123')
|
||||
@@ -71,13 +73,13 @@ RSpec.describe VersionRecord, type: :model do
|
||||
|
||||
it 'prevents NicoTagVersion destroy' do
|
||||
version = NicoTagVersion.create!(
|
||||
external_tag: nico_tag,
|
||||
version_no: 1,
|
||||
event_type: 'create',
|
||||
linked_tag_ids: '',
|
||||
created_at: Time.current,
|
||||
created_by_user: nil
|
||||
)
|
||||
event_id: create_event!(event_type: 'unknown').id,
|
||||
external_tag: nico_tag,
|
||||
version_no: 1,
|
||||
event_type: 'create',
|
||||
linked_tag_ids: '',
|
||||
created_at: Time.current,
|
||||
created_by_user: nil)
|
||||
|
||||
expect {
|
||||
version.destroy!
|
||||
|
||||
@@ -44,6 +44,7 @@ RSpec.configure do |config|
|
||||
end
|
||||
|
||||
config.include TestRecords
|
||||
config.include EventRecords
|
||||
config.include RakeTaskHelper
|
||||
|
||||
# FactoryBot の create / create_list を使へるやぅにする
|
||||
|
||||
@@ -84,7 +84,9 @@ RSpec.describe 'Counts native GET acknowledgement', type: :request do
|
||||
expect(response).to have_http_status(:not_found)
|
||||
job, file, attempt = ready_job('json')
|
||||
record = create(:post)
|
||||
PostVersion.create!(post: record, version_no: 1, event_type: 'discard', title: 'private',
|
||||
PostVersion.create!(
|
||||
event_id: create_event!(event_type: 'unknown').id,
|
||||
post: record, version_no: 1, event_type: 'discard', title: 'private',
|
||||
url: record.url, tags: '', tags_json: [], parent_post_ids: '', created_at: Time.utc(2024))
|
||||
get "/counts/export/files/#{ file }", params: { job:, attempt: }
|
||||
expect(response).to have_http_status(:not_found)
|
||||
|
||||
@@ -8,7 +8,9 @@ RSpec.describe 'History boundaries shared with Counts', type: :request do
|
||||
|
||||
before do
|
||||
['create', 'discard'].each_with_index do |event, index|
|
||||
TagDescriptionVersion.create!(tag_id: tag.id, language_code: 'ja',
|
||||
TagDescriptionVersion.create!(
|
||||
event_id: create_event!(event_type: 'unknown').id,
|
||||
tag_id: tag.id, language_code: 'ja',
|
||||
version_no: index + 1, event_type: event, body: 'private body',
|
||||
created_at: Time.utc(2024))
|
||||
end
|
||||
|
||||
@@ -13,6 +13,7 @@ RSpec.describe 'Counts masked search', type: :request do
|
||||
before do
|
||||
[1, 2].each do |number|
|
||||
TagVersion.create!(tag:, version_no: number,
|
||||
event_id: create_event!(event_type: 'unknown').id,
|
||||
event_type: number == 1 ? 'create' : 'discard', name: '秘密のタグ',
|
||||
category: 'general', aliases: '秘密の別名', parent_tag_ids: '',
|
||||
names: { ja: { name: '秘密のタグ', script_code: 'Jpan', auto_generated: false,
|
||||
@@ -113,6 +114,7 @@ RSpec.describe 'Counts masked search', type: :request do
|
||||
it 'searches public literal markers and treats axis predicates as explicit' do
|
||||
public_tag = create(:tag, primary_name: '********')
|
||||
TagVersion.create!(tag: public_tag, version_no: 1, event_type: 'create',
|
||||
event_id: create_event!(event_type: 'unknown').id,
|
||||
name: '********', category: 'general', aliases: '', parent_tag_ids: '',
|
||||
names: { ja: { name: '********', script_code: 'Jpan', auto_generated: false,
|
||||
aliases: [] } }, created_at: Time.utc(2023))
|
||||
@@ -177,6 +179,7 @@ RSpec.describe 'Counts masked search', type: :request do
|
||||
it 'rejects private names reached through a post tag snapshot' do
|
||||
post = create(:post)
|
||||
PostVersion.create!(post:, version_no: 1, event_type: 'create', title: 'post',
|
||||
event_id: create_event!(event_type: 'unknown').id,
|
||||
url: post.url, tags: '', parent_post_ids: '',
|
||||
tags_json: [{ tag_id: tag.id, version_no: 1, name: '秘密のタグ',
|
||||
category: 'general', sections: [] }],
|
||||
|
||||
@@ -10,12 +10,16 @@ RSpec.describe 'Legacy Counts API', type: :request do
|
||||
category: 'general', sections: [] }
|
||||
[1, 2, 3].each do |number|
|
||||
time = Time.utc(2024, number == 3 ? 2 : 1, number, 0, 0)
|
||||
PostVersion.create!(post:, version_no: number,
|
||||
PostVersion.create!(
|
||||
event_id: create_event!(event_type: 'unknown').id,
|
||||
post:, version_no: number,
|
||||
event_type: number == 1 ? 'create' : 'update',
|
||||
tags: '', url: post.url, title: "Snapshot #{ number }", parent_post_ids: '',
|
||||
tags_json: number == 1 ? [snapshot] : [],
|
||||
created_by_user: number == 3 ? nil : actor, created_at: time)
|
||||
TagVersion.create!(tag:, version_no: number,
|
||||
TagVersion.create!(
|
||||
event_id: create_event!(event_type: 'unknown').id,
|
||||
tag:, version_no: number,
|
||||
event_type: number == 1 ? 'create' : 'update',
|
||||
name: 'counts tag', category: 'general', aliases: '', parent_tag_ids: '',
|
||||
names: { ja: { name: 'counts tag', script_code: 'Jpan',
|
||||
|
||||
@@ -14,17 +14,22 @@ RSpec.describe 'Counts table API', type: :request do
|
||||
end
|
||||
|
||||
before do
|
||||
TagVersion.create!(tag:, version_no: 1, event_type: 'create', name: 'alpha',
|
||||
TagVersion.create!(
|
||||
event_id: create_event!(event_type: 'unknown').id,
|
||||
tag:, version_no: 1, event_type: 'create', name: 'alpha',
|
||||
category: 'general', aliases: '', parent_tag_ids: '',
|
||||
names: { ja: { name: 'alpha', script_code: 'Jpan', auto_generated: false, aliases: [] } },
|
||||
created_at: Time.utc(2023))
|
||||
NicoTagVersion.create!(external_tag: external, version_no: 1,
|
||||
event_id: create_event!(event_type: 'unknown').id,
|
||||
event_type: 'create', linked_tag_ids: '', created_at: Time.utc(2023))
|
||||
snapshots = [
|
||||
{ tag_id: tag.id, version_no: 1, name: 'alpha', category: 'general', sections: [] },
|
||||
{ external_tag_id: external.id }]
|
||||
[1, 2, 3].each do |number|
|
||||
PostVersion.create!(post: record, version_no: number,
|
||||
PostVersion.create!(
|
||||
event_id: create_event!(event_type: 'unknown').id,
|
||||
post: record, version_no: number,
|
||||
event_type: number == 1 ? 'create' : 'update', url: record.url,
|
||||
title: "snapshot #{ number }", tags: '', parent_post_ids: '',
|
||||
tags_json: snapshots.first(number == 1 ? 2 : (number == 2 ? 1 : 0)),
|
||||
@@ -57,9 +62,11 @@ RSpec.describe 'Counts table API', type: :request do
|
||||
|
||||
before do
|
||||
NicoTagVersion.create!(external_tag: external, version_no: 2,
|
||||
event_id: create_event!(event_type: 'unknown').id,
|
||||
event_type: 'update', linked_tag_ids: tag.id.to_s,
|
||||
created_at: Time.utc(2024, 1, 1))
|
||||
NicoTagVersion.create!(external_tag: external, version_no: 3,
|
||||
event_id: create_event!(event_type: 'unknown').id,
|
||||
event_type: 'update', linked_tag_ids: '',
|
||||
created_at: Time.utc(2024, 2, 1))
|
||||
end
|
||||
@@ -243,7 +250,9 @@ RSpec.describe 'Counts table API', type: :request do
|
||||
end
|
||||
|
||||
it 'checks the current latest flag beyond the execution timestamp' do
|
||||
PostVersion.create!(post: record, version_no: 4, event_type: 'update',
|
||||
PostVersion.create!(
|
||||
event_id: create_event!(event_type: 'unknown').id,
|
||||
post: record, version_no: 4, event_type: 'update',
|
||||
url: record.url, title: 'after execution', tags: '', tags_json: [],
|
||||
parent_post_ids: '', created_at: Time.utc(2025, 2, 1))
|
||||
result = query
|
||||
@@ -297,12 +306,16 @@ RSpec.describe 'Counts table API', type: :request do
|
||||
tag.tag_names.find_by!(language_code: 'ja', primary_flg: true)
|
||||
.update!(name: 'renamed-alpha')
|
||||
create(:tag_name, :alias, tag:, name: 'alpha-alias')
|
||||
TagVersion.create!(tag:, version_no: 2, event_type: 'update', name: 'renamed-alpha',
|
||||
TagVersion.create!(
|
||||
event_id: create_event!(event_type: 'unknown').id,
|
||||
tag:, version_no: 2, event_type: 'update', name: 'renamed-alpha',
|
||||
category: 'general', aliases: 'alpha-alias', parent_tag_ids: '',
|
||||
names: { ja: { name: 'renamed-alpha', script_code: 'Jpan', auto_generated: false,
|
||||
aliases: [{ name: 'alpha-alias', script_code: 'Jpan' }] } },
|
||||
created_at: Time.utc(2024, 2, 1))
|
||||
PostVersion.create!(post: record, version_no: 4, event_type: 'update',
|
||||
PostVersion.create!(
|
||||
event_id: create_event!(event_type: 'unknown').id,
|
||||
post: record, version_no: 4, event_type: 'update',
|
||||
url: record.url, title: 'after rename', tags: '', parent_post_ids: '',
|
||||
tags_json: [{ tag_id: tag.id, version_no: 2, name: 'renamed-alpha',
|
||||
category: 'general', sections: [] }],
|
||||
@@ -365,7 +378,9 @@ RSpec.describe 'Counts table API', type: :request do
|
||||
|
||||
it 'reports column overflow separately from malformed input' do
|
||||
101.times do |index|
|
||||
PostVersion.create!(post: record, version_no: index + 4,
|
||||
PostVersion.create!(
|
||||
event_id: create_event!(event_type: 'unknown').id,
|
||||
post: record, version_no: index + 4,
|
||||
event_type: 'update', url: record.url, title: "column #{ index }",
|
||||
tags: '', tags_json: [], parent_post_ids: '', created_at: Time.utc(2024, 3))
|
||||
end
|
||||
@@ -409,7 +424,9 @@ RSpec.describe 'Counts table API', type: :request do
|
||||
sign_in_as(create(:user, role)) if role
|
||||
# Equal timestamps deliberately require version ordering, not a date comparison.
|
||||
['discard', 'restore', 'discard', 'restore'].each_with_index do |event, index|
|
||||
PostVersion.create!(post: record, version_no: index + 4, event_type: event,
|
||||
PostVersion.create!(
|
||||
event_id: create_event!(event_type: 'unknown').id,
|
||||
post: record, version_no: index + 4, event_type: event,
|
||||
url: record.url, title: event == 'restore' ? 'restored' : 'private snapshot',
|
||||
tags: '', tags_json: [], parent_post_ids: '', created_at: Time.utc(2024, 3))
|
||||
end
|
||||
@@ -437,7 +454,9 @@ RSpec.describe 'Counts table API', type: :request do
|
||||
end
|
||||
|
||||
it 'does not resolve private condition names even when the result set is empty' do
|
||||
TagVersion.create!(tag:, version_no: 2, event_type: 'discard', name: 'secret tag',
|
||||
TagVersion.create!(
|
||||
event_id: create_event!(event_type: 'unknown').id,
|
||||
tag:, version_no: 2, event_type: 'discard', name: 'secret tag',
|
||||
category: 'general', aliases: '', parent_tag_ids: '',
|
||||
names: { ja: { name: 'secret tag', script_code: 'Jpan', auto_generated: false, aliases: [] } },
|
||||
created_at: Time.utc(2024, 2))
|
||||
@@ -453,7 +472,9 @@ RSpec.describe 'Counts table API', type: :request do
|
||||
end
|
||||
end
|
||||
it 'includes private history in the public timeline without an exclusion count' do
|
||||
PostVersion.create!(post: record, version_no: 4, event_type: 'discard', url: record.url,
|
||||
PostVersion.create!(
|
||||
event_id: create_event!(event_type: 'unknown').id,
|
||||
post: record, version_no: 4, event_type: 'discard', url: record.url,
|
||||
title: 'hidden title', tags: '', tags_json: [], parent_post_ids: '',
|
||||
created_at: Time.utc(2024, 3))
|
||||
result = query(mode: 'summary', rows: 'created_at:month', cols: 'event_type')
|
||||
@@ -469,6 +490,7 @@ RSpec.describe 'Counts table API', type: :request do
|
||||
|
||||
it 'allows public identity predicates without exposing private snapshot fields' do
|
||||
PostVersion.create!(post: record, version_no: 4, event_type: 'discard',
|
||||
event_id: create_event!(event_type: 'unknown').id,
|
||||
url: record.url, title: 'hidden title', tags: '', tags_json: [],
|
||||
parent_post_ids: '', created_at: Time.utc(2024, 3))
|
||||
|
||||
|
||||
@@ -314,6 +314,7 @@ RSpec.describe 'Materials API', type: :request do
|
||||
.and change(Tag, :count).by(1)
|
||||
.and change(TagName, :count).by(1)
|
||||
.and change(MaterialVersion, :count).by(1)
|
||||
.and change { event_rows.length }.by(1)
|
||||
|
||||
expect(response).to have_http_status(:created)
|
||||
|
||||
@@ -325,6 +326,12 @@ RSpec.describe 'Materials API', type: :request do
|
||||
expect(material.file.attached?).to be(true)
|
||||
expect(material.version_no).to eq(1)
|
||||
expect(material.material_versions.first.event_type).to eq('create')
|
||||
event = event_rows.last
|
||||
expect(event).to include(
|
||||
'event_type' => 'materials.create',
|
||||
'created_by_user_id' => member_user.id)
|
||||
expect(material.material_versions.first.event_id).to eq(event.fetch('id'))
|
||||
expect(material.tag.tag_versions.pluck(:event_id)).to eq([event.fetch('id')])
|
||||
expect(material.material_export_items.first.export_path).to eq('伊地知ニジカ/created.png')
|
||||
expect(material.material_versions.first.export_paths_json).to eq(
|
||||
'legacy_drive' => '伊地知ニジカ/created.png'
|
||||
@@ -509,6 +516,7 @@ RSpec.describe 'Materials API', type: :request do
|
||||
export_paths: { legacy_drive: '伊地知ニジカ/updated.jpg' }
|
||||
}
|
||||
end.to change(MaterialVersion, :count).by(2)
|
||||
.and change { event_rows.length }.by(1)
|
||||
|
||||
expect(response).to have_http_status(:ok)
|
||||
|
||||
@@ -517,6 +525,12 @@ RSpec.describe 'Materials API', type: :request do
|
||||
expect(material.tag.category).to eq('material')
|
||||
expect(material.url).to eq('https://example.com/updated-source')
|
||||
expect(material.updated_by_user).to eq(member_user)
|
||||
event = event_rows.last
|
||||
expect(event).to include(
|
||||
'event_type' => 'materials.update',
|
||||
'created_by_user_id' => member_user.id)
|
||||
expect(material.material_versions.pluck(:event_id).uniq).to eq([event.fetch('id')])
|
||||
expect(material.tag.tag_versions.pluck(:event_id)).to eq([event.fetch('id')])
|
||||
expect(material.file.attached?).to be(true)
|
||||
expect(material.file.blob.id).not_to eq(old_blob_id)
|
||||
expect(ActiveStorage::Blob.where(id: old_blob_id).exists?).to be(true)
|
||||
@@ -632,6 +646,7 @@ RSpec.describe 'Materials API', type: :request do
|
||||
MaterialVersionRecorder.record!(material:, event_type: :create,
|
||||
created_by_user: member_user)
|
||||
TagVersioning.ensure_snapshot!(tag, created_by_user: member_user)
|
||||
events = event_rows
|
||||
|
||||
expect do
|
||||
put "/materials/#{ material.id }", params: {
|
||||
@@ -643,6 +658,7 @@ RSpec.describe 'Materials API', type: :request do
|
||||
|
||||
expect(response).to have_http_status(:ok)
|
||||
expect(material.reload.version_no).to eq(1)
|
||||
expect(event_rows).to eq(events)
|
||||
end
|
||||
|
||||
it 'records update version when only export_path changes' do
|
||||
@@ -807,6 +823,12 @@ RSpec.describe 'Materials API', type: :request do
|
||||
|
||||
it 'creates source suppression as member' do
|
||||
sign_in_as(member_user)
|
||||
materials = ['a', 'b'].map do |name|
|
||||
Material.create!(
|
||||
source_kind: 'google_drive_file', source_file_id: "blocked-#{ name }",
|
||||
source_path: "伊地知ニジカ/危険素材/#{ name }.png",
|
||||
url: "https://example.com/blocked-#{ name }", created_by_user: member_user)
|
||||
end
|
||||
|
||||
expect do
|
||||
post '/materials/suppressions', params: {
|
||||
@@ -815,6 +837,7 @@ RSpec.describe 'Materials API', type: :request do
|
||||
reason: 'copyright_high_risk'
|
||||
}
|
||||
end.to change(MaterialSyncSuppression, :count).by(1)
|
||||
.and change { event_rows.length }.by(1)
|
||||
|
||||
expect(response).to have_http_status(:created)
|
||||
expect(json).to include(
|
||||
@@ -822,6 +845,14 @@ RSpec.describe 'Materials API', type: :request do
|
||||
'drive_path' => '伊地知ニジカ/危険素材',
|
||||
'normalized_source_key' => 'google_drive_path_prefix:伊地知ニジカ/危険素材'
|
||||
)
|
||||
event = event_rows.last
|
||||
expect(event).to include(
|
||||
'event_type' => 'materials.block', 'created_by_user_id' => member_user.id)
|
||||
expect(materials.map { _1.reload.discarded? }).to eq([true, true])
|
||||
versions = MaterialVersion.where(material_id: materials.map(&:id))
|
||||
expect(versions.where(event_type: 'discard').pluck(:material_id))
|
||||
.to match_array(materials.map(&:id))
|
||||
expect(versions.pluck(:event_id).uniq).to eq([event.fetch('id')])
|
||||
end
|
||||
end
|
||||
|
||||
@@ -860,11 +891,19 @@ RSpec.describe 'Materials API', type: :request do
|
||||
end
|
||||
|
||||
it 'discards the material and returns 204' do
|
||||
delete "/materials/#{ material.id }"
|
||||
expect { delete "/materials/#{ material.id }" }
|
||||
.to change { event_rows.length }.by(1)
|
||||
|
||||
expect(response).to have_http_status(:no_content)
|
||||
expect(Material.find_by(id: material.id)).to be_nil
|
||||
expect(Material.with_discarded.find(material.id)).to be_discarded
|
||||
event = event_rows.last
|
||||
expect(event).to include(
|
||||
'event_type' => 'materials.destroy',
|
||||
'created_by_user_id' => member_user.id)
|
||||
versions = MaterialVersion.where(material_id: material.id)
|
||||
expect(versions.order(:version_no).last.event_type).to eq('discard')
|
||||
expect(versions.pluck(:event_id).uniq).to eq([event.fetch('id')])
|
||||
end
|
||||
end
|
||||
end
|
||||
|
||||
@@ -172,6 +172,7 @@ RSpec.describe 'NicoTags', type: :request do
|
||||
}
|
||||
}.to change(TagVersion, :count).by(2)
|
||||
.and change(NicoTagVersion, :count).by(1)
|
||||
.and change { event_rows.length }.by(1)
|
||||
|
||||
expect(response).to have_http_status(:ok)
|
||||
|
||||
@@ -181,12 +182,17 @@ RSpec.describe 'NicoTags', type: :request do
|
||||
linked_versions = TagVersion.where(tag: [linked_a, linked_b]).order(:tag_id)
|
||||
expect(linked_versions.map(&:event_type)).to eq(['create', 'create'])
|
||||
expect(linked_versions.map(&:created_by_user_id)).to all(eq(admin.id))
|
||||
event = event_rows.last
|
||||
expect(event).to include(
|
||||
'event_type' => 'external_tags.update', 'created_by_user_id' => admin.id)
|
||||
expect(linked_versions.pluck(:event_id).uniq).to eq([event.fetch('id')])
|
||||
|
||||
versions = nico_tag.reload.nico_tag_versions.order(:version_no)
|
||||
expect(versions.map(&:event_type)).to eq(['create', 'update'])
|
||||
expect(versions.last.linked_tag_ids.split.map(&:to_i))
|
||||
.to match_array([linked_a.id, linked_b.id])
|
||||
expect(versions.last.created_by_user_id).to eq(admin.id)
|
||||
expect(versions.last.event_id).to eq(event.fetch('id'))
|
||||
end
|
||||
|
||||
it 'clears existing links and records the empty mapping for a member' do
|
||||
|
||||
@@ -14,12 +14,14 @@ RSpec.describe 'Post history privacy', type: :request do
|
||||
before do
|
||||
['create', 'discard'].each_with_index do |event, index|
|
||||
TagVersion.create!(tag:, version_no: index + 1, event_type: event,
|
||||
event_id: create_event!(event_type: 'unknown').id,
|
||||
name: 'private-history-tag', category: 'general', aliases: '', parent_tag_ids: '',
|
||||
names: { ja: { name: 'private-history-tag', script_code: 'Jpan',
|
||||
auto_generated: false, aliases: [] } },
|
||||
created_at: origin + index.hours)
|
||||
end
|
||||
NicoTagVersion.create!(external_tag: external, version_no: 1, event_type: 'create',
|
||||
event_id: create_event!(event_type: 'unknown').id,
|
||||
linked_tag_ids: tag.id.to_s,
|
||||
created_at: origin)
|
||||
['create', 'discard', 'restore', 'update'].each_with_index do |event, index|
|
||||
@@ -32,6 +34,7 @@ RSpec.describe 'Post history privacy', type: :request do
|
||||
[]
|
||||
end
|
||||
PostVersion.create!(post: post_record, version_no: index + 1, event_type: event,
|
||||
event_id: create_event!(event_type: 'unknown').id,
|
||||
title: "version #{ index + 1 }", url: post_record.url, tags: '',
|
||||
tags_json: snapshots, parent_post_ids: '', created_at: origin + (index + 1).days)
|
||||
end
|
||||
@@ -51,6 +54,7 @@ RSpec.describe 'Post history privacy', type: :request do
|
||||
it 'keeps every version through a later discard private after another restore' do
|
||||
['discard', 'restore'].each_with_index do |event, index|
|
||||
PostVersion.create!(post: post_record, version_no: index + 5, event_type: event,
|
||||
event_id: create_event!(event_type: 'unknown').id,
|
||||
title: 'later snapshot', url: post_record.url, tags: '', tags_json: [],
|
||||
parent_post_ids: '', created_at: origin + (index + 5).days)
|
||||
end
|
||||
|
||||
@@ -50,6 +50,8 @@ RSpec.describe 'Posts API', type: :request do
|
||||
post:,
|
||||
version_no: 1,
|
||||
event_type: 'create',
|
||||
event_id: create_event!(
|
||||
event_type: 'posts.create', created_by_user: post.uploaded_user).id,
|
||||
title: post.title,
|
||||
url: post.url,
|
||||
thumbnail_base: post.thumbnail_base,
|
||||
@@ -1068,7 +1070,7 @@ RSpec.describe 'Posts API', type: :request do
|
||||
|
||||
it 'dry-runs without persisting posts or new tags' do
|
||||
sign_in_as(member)
|
||||
counts = [Post.count, Tag.count, TagName.count]
|
||||
counts = [Post.count, Tag.count, TagName.count, event_rows.length]
|
||||
|
||||
post '/posts?dry=1', params: post_write_params(
|
||||
title: 'dry-run post',
|
||||
@@ -1084,7 +1086,7 @@ RSpec.describe 'Posts API', type: :request do
|
||||
[{ 'name' => 'new_dry_run_tag',
|
||||
'category' => 'character',
|
||||
'section_literals' => [] }])
|
||||
expect([Post.count, Tag.count, TagName.count]).to eq(counts)
|
||||
expect([Post.count, Tag.count, TagName.count, event_rows.length]).to eq(counts)
|
||||
end
|
||||
|
||||
it 'dry-runs an existing URL without validating its upload' do
|
||||
@@ -2259,20 +2261,20 @@ RSpec.describe 'Posts API', type: :request do
|
||||
|
||||
def create_post_version! post, version_no:, event_type:, created_by_user:, created_at:
|
||||
PostVersion.create!(
|
||||
post:,
|
||||
version_no:,
|
||||
event_type:,
|
||||
title: post.title,
|
||||
url: post.url,
|
||||
thumbnail_base: post.thumbnail_base,
|
||||
tags: snapshot_tags(post),
|
||||
tags_json: post.snapshot_tags_json,
|
||||
parent_post_ids: post.snapshot_parent_post_ids.join(' '),
|
||||
original_created_from: post.original_created_from,
|
||||
original_created_before: post.original_created_before,
|
||||
created_at:,
|
||||
created_by_user:
|
||||
)
|
||||
event_id: create_event!(event_type: 'unknown').id,
|
||||
post:,
|
||||
version_no:,
|
||||
event_type:,
|
||||
title: post.title,
|
||||
url: post.url,
|
||||
thumbnail_base: post.thumbnail_base,
|
||||
tags: snapshot_tags(post),
|
||||
tags_json: post.snapshot_tags_json,
|
||||
parent_post_ids: post.snapshot_parent_post_ids.join(' '),
|
||||
original_created_from: post.original_created_from,
|
||||
original_created_before: post.original_created_before,
|
||||
created_at:,
|
||||
created_by_user:)
|
||||
end
|
||||
|
||||
let!(:v1) do
|
||||
@@ -2600,6 +2602,7 @@ RSpec.describe 'Posts API', type: :request do
|
||||
tags: 'spec_tag',
|
||||
thumbnail: dummy_upload)
|
||||
end.to change(PostVersion, :count).by(1)
|
||||
.and change { event_rows.length }.by(1)
|
||||
|
||||
expect(response).to have_http_status(:created)
|
||||
|
||||
@@ -2611,6 +2614,13 @@ RSpec.describe 'Posts API', type: :request do
|
||||
expect(version.url).to eq('https://example.com/versioned-post')
|
||||
expect(version.created_by_user_id).to eq(member.id)
|
||||
expect(version.tags).to eq(snapshot_tags(created_post))
|
||||
event = event_rows.last
|
||||
expect(event).to include(
|
||||
'event_type' => 'posts.create', 'created_by_user_id' => member.id)
|
||||
expect(version.event_id).to eq(event.fetch('id'))
|
||||
tag_versions = TagVersion.where(tag_id: created_post.tags.select(:id))
|
||||
expect(tag_versions).not_to be_empty
|
||||
expect(tag_versions.pluck(:event_id).uniq).to eq([event.fetch('id')])
|
||||
end
|
||||
|
||||
it 'creates next version on PUT /posts/:id when snapshot changes' do
|
||||
@@ -2626,6 +2636,7 @@ RSpec.describe 'Posts API', type: :request do
|
||||
title: 'updated title',
|
||||
tags: 'spec_tag_2')
|
||||
end.to change(PostVersion, :count).by(1)
|
||||
.and change { event_rows.length }.by(1)
|
||||
|
||||
expect(response).to have_http_status(:ok)
|
||||
|
||||
@@ -2635,6 +2646,12 @@ RSpec.describe 'Posts API', type: :request do
|
||||
expect(version.title).to eq('updated title')
|
||||
expect(version.created_by_user_id).to eq(member.id)
|
||||
expect(version.tags).to eq(snapshot_tags(post_record.reload))
|
||||
event = event_rows.last
|
||||
expect(event).to include(
|
||||
'event_type' => 'posts.update', 'created_by_user_id' => member.id)
|
||||
expect(version.event_id).to eq(event.fetch('id'))
|
||||
tag_version = TagVersion.find_by!(tag_id: tag_name2.reload.tag_id, version_no: 1)
|
||||
expect(tag_version.event_id).to eq(event.fetch('id'))
|
||||
end
|
||||
|
||||
it 'does not create a new version on PUT /posts/:id when snapshot is unchanged' do
|
||||
@@ -2643,6 +2660,7 @@ RSpec.describe 'Posts API', type: :request do
|
||||
PostTag.create!(post: post_record, tag: Tag.no_deerjikist)
|
||||
base_version = create_post_version_for!(post_record.reload)
|
||||
|
||||
events = event_rows
|
||||
expect {
|
||||
put "/posts/#{post_record.id}", params: post_write_params(
|
||||
base_version_no: base_version.version_no,
|
||||
@@ -2656,10 +2674,12 @@ RSpec.describe 'Posts API', type: :request do
|
||||
expect(version.version_no).to eq(1)
|
||||
expect(version.event_type).to eq('create')
|
||||
expect(version.tags).to eq(snapshot_tags(post_record))
|
||||
expect(event_rows).to eq(events)
|
||||
end
|
||||
|
||||
it 'does not create a version when POST /posts is invalid' do
|
||||
sign_in_as(member)
|
||||
events = event_rows
|
||||
|
||||
expect do
|
||||
post '/posts', params: post_write_params(
|
||||
@@ -2670,11 +2690,13 @@ RSpec.describe 'Posts API', type: :request do
|
||||
end.not_to change(PostVersion, :count)
|
||||
|
||||
expect(response).to have_http_status(:unprocessable_entity)
|
||||
expect(event_rows).to eq(events)
|
||||
end
|
||||
|
||||
it 'does not create a version when PUT /posts/:id is invalid' do
|
||||
sign_in_as(member)
|
||||
base_version = create_post_version_for!(post_record)
|
||||
events = event_rows
|
||||
|
||||
expect do
|
||||
put "/posts/#{post_record.id}", params: post_write_params(
|
||||
@@ -2686,6 +2708,7 @@ RSpec.describe 'Posts API', type: :request do
|
||||
end.not_to change(PostVersion, :count)
|
||||
|
||||
expect(response).to have_http_status(:unprocessable_entity)
|
||||
expect(event_rows).to eq(events)
|
||||
end
|
||||
|
||||
it 'rejects second-bearing original created timestamps on POST /posts' do
|
||||
|
||||
@@ -119,7 +119,9 @@ RSpec.describe 'Sitemap entries API', type: :request do
|
||||
# Legacy empty bodies can exist even though the write service rejects them.
|
||||
empty = TagDescription.create!(tag: empty_tag, language_code: 'ain',
|
||||
body: '', version_no: 1)
|
||||
TagDescriptionVersion.create!(tag_id: empty_tag.id, language_code: 'ain',
|
||||
TagDescriptionVersion.create!(
|
||||
event_id: create_event!(event_type: 'unknown').id,
|
||||
tag_id: empty_tag.id, language_code: 'ain',
|
||||
body: '', version_no: 1, event_type: 'create',
|
||||
created_by_user_id: user.id, created_at: Time.current)
|
||||
|
||||
|
||||
@@ -53,8 +53,13 @@ RSpec.describe "TagChildren", type: :request do
|
||||
expect { do_request }
|
||||
.to change { parent.reload.children.ids.include?(child.id) }
|
||||
.from(false).to(true)
|
||||
.and change { event_rows.length }.by(1)
|
||||
|
||||
expect(response).to have_http_status(:no_content)
|
||||
event = event_rows.last
|
||||
expect(event).to include(
|
||||
'event_type' => 'tags.update', 'created_by_user_id' => admin.id)
|
||||
expect(child.tag_versions.pluck(:event_id).uniq).to eq([event.fetch('id')])
|
||||
end
|
||||
|
||||
it 'returns 422 and does not create relation when the new link makes a cycle' do
|
||||
@@ -132,6 +137,7 @@ RSpec.describe "TagChildren", type: :request do
|
||||
expect {
|
||||
do_request
|
||||
}.to change(TagVersion, :count).by(2)
|
||||
.and change { event_rows.length }.by(1)
|
||||
|
||||
expect(response).to have_http_status(:no_content)
|
||||
|
||||
@@ -140,6 +146,10 @@ RSpec.describe "TagChildren", type: :request do
|
||||
expect(versions.first.parent_tag_ids.split).to include(parent.id.to_s)
|
||||
expect(versions.second.parent_tag_ids).to eq('')
|
||||
expect(versions.second.created_by_user_id).to eq(admin.id)
|
||||
event = event_rows.last
|
||||
expect(event).to include(
|
||||
'event_type' => 'tags.update', 'created_by_user_id' => admin.id)
|
||||
expect(versions.pluck(:event_id).uniq).to eq([event.fetch('id')])
|
||||
end
|
||||
end
|
||||
|
||||
|
||||
@@ -8,6 +8,7 @@ RSpec.describe 'Tag description Wiki compatibility', type: :request do
|
||||
let!(:versions) do
|
||||
['A', 'A', 'new-version'].each_with_index.map do |body, index|
|
||||
TagDescriptionVersion.create!(
|
||||
event_id: create_event!(event_type: 'unknown').id,
|
||||
tag_id: tag.id, language_code: 'ja', version_no: index + 1,
|
||||
event_type: index.zero? ? 'create' : 'update', body:,
|
||||
created_by_user_id: user.id, created_at: Time.current)
|
||||
@@ -73,6 +74,7 @@ RSpec.describe 'Tag description Wiki compatibility', type: :request do
|
||||
let!(:other_tag) { create(:tag, primary_name: 'other_description_contract') }
|
||||
let!(:other_version) do
|
||||
TagDescriptionVersion.create!(
|
||||
event_id: create_event!(event_type: 'unknown').id,
|
||||
tag_id: other_tag.id, language_code: 'ja', version_no: 1,
|
||||
event_type: 'create', body: 'other tag history',
|
||||
created_by_user_id: user.id, created_at: Time.current)
|
||||
|
||||
@@ -13,7 +13,7 @@ RSpec.describe 'Tag description native API', type: :request do
|
||||
def stored_state
|
||||
[TagDescription, TagDescriptionVersion, TagName, TagVersion].map do |model|
|
||||
model.order(:id).map(&:attributes)
|
||||
end
|
||||
end + [event_rows]
|
||||
end
|
||||
|
||||
def fail_save model
|
||||
@@ -91,6 +91,8 @@ RSpec.describe 'Tag description native API', type: :request do
|
||||
let!(:version) do
|
||||
TagDescriptionVersion.create!(
|
||||
tag_id: tag.id, language_code: 'ja', body: 'native version', version_no: 1,
|
||||
event_id: create_event!(
|
||||
event_type: 'tag_descriptions.create', created_by_user: author).id,
|
||||
event_type: 'create', created_by_user_id: author.id, created_at: Time.current)
|
||||
end
|
||||
let(:name_endpoint) { "/tags/name/#{ tag_name.name }/description" }
|
||||
@@ -185,6 +187,7 @@ RSpec.describe 'Tag description native API', type: :request do
|
||||
expect { native_write(body: 'created natively') }
|
||||
.to change(TagDescription, :count).by(1)
|
||||
.and change(TagDescriptionVersion, :count).by(1)
|
||||
.and change { event_rows.length }.by(1)
|
||||
expect(response).to have_http_status(:created)
|
||||
description = TagDescription.find_by!(tag_id: tag.id, language_code: 'ja')
|
||||
expect_current(description)
|
||||
@@ -192,6 +195,10 @@ RSpec.describe 'Tag description native API', type: :request do
|
||||
expect(version).to have_attributes(
|
||||
body: 'created natively', version_no: 1, event_type: 'create',
|
||||
created_by_user_id: editor.id)
|
||||
event = event_rows.last
|
||||
expect(event).to include(
|
||||
'event_type' => 'tag_descriptions.create', 'created_by_user_id' => editor.id)
|
||||
expect(version.event_id).to eq(event.fetch('id'))
|
||||
get "/wiki/#{ description.id }"
|
||||
expect(response).to have_http_status(:ok)
|
||||
expect(json).to include('body' => description.body, 'revision_id' => version.id)
|
||||
@@ -223,6 +230,7 @@ RSpec.describe 'Tag description native API', type: :request do
|
||||
expect(description.version_no).to eq(1)
|
||||
expect { native_write(body: 'after') }
|
||||
.to change(TagDescriptionVersion, :count).by(1)
|
||||
.and change { event_rows.length }.by(1)
|
||||
expect(response).to have_http_status(:ok)
|
||||
expect(description.reload).to have_attributes(
|
||||
body: 'after', version_no: 2,
|
||||
@@ -234,6 +242,10 @@ RSpec.describe 'Tag description native API', type: :request do
|
||||
expect(version).to have_attributes(
|
||||
tag_id: tag.id, language_code: 'ja', version_no: 2, event_type: 'update',
|
||||
body: 'after', created_by_user_id: editor.id)
|
||||
event = event_rows.last
|
||||
expect(event).to include(
|
||||
'event_type' => 'tag_descriptions.update', 'created_by_user_id' => editor.id)
|
||||
expect(version.event_id).to eq(event.fetch('id'))
|
||||
expect(revision.body).to eq(version.body)
|
||||
expect(description_versions(page).order(:version_no).last.body).to eq(version.body)
|
||||
get "/wiki/#{ description.id }"
|
||||
|
||||
@@ -121,10 +121,14 @@ RSpec.describe 'Tag group native API', type: :request do
|
||||
[:create, :update].each do |operation|
|
||||
it "#{ operation }s structured data and keeps unplaced membership" do
|
||||
previous = group_version(group_id, 1)
|
||||
native_write(operation)
|
||||
expect { native_write(operation) }.to change { event_rows.length }.by(1)
|
||||
expect(response).to have_http_status(operation == :create ? :created : :ok)
|
||||
id = operation == :create ? json.fetch('id') : group_id
|
||||
number = operation == :create ? 1 : 2
|
||||
event = event_rows.last
|
||||
event_type = operation == :create ? 'tag_groups.create' : 'tag_groups.update'
|
||||
expect(event).to include('event_type' => event_type, 'created_by_user_id' => user.id)
|
||||
expect(group_version(id, number).fetch('event_id')).to eq(event.fetch('id'))
|
||||
expect_group_snapshot(
|
||||
id, number:, members: snapshot_members, placements:, description: '全体の説明')
|
||||
expect(group_version(group_id, 1)).to eq(previous)
|
||||
|
||||
@@ -30,6 +30,7 @@ RSpec.describe 'TagVersions API', type: :request do
|
||||
)
|
||||
version =
|
||||
TagVersion.create!(
|
||||
event_id: create_event!(event_type: 'unknown').id,
|
||||
tag: tag,
|
||||
version_no: version_no,
|
||||
event_type: event_type,
|
||||
|
||||
@@ -705,6 +705,7 @@ RSpec.describe 'Tags API', type: :request do
|
||||
expect {
|
||||
patch "/tags/#{tag.id}", params: { name: 'new_tag_name', category: 'meme' }
|
||||
}.to change(TagVersion, :count).by(2)
|
||||
.and change { event_rows.length }.by(1)
|
||||
|
||||
expect(response).to have_http_status(:ok)
|
||||
|
||||
@@ -719,6 +720,10 @@ RSpec.describe 'Tags API', type: :request do
|
||||
expect(version_primary_name(versions.second, 'ja')).to eq('new_tag_name')
|
||||
expect(versions.second.category).to eq('meme')
|
||||
expect(versions.second.created_by_user_id).to eq(member_user.id)
|
||||
event = event_rows.last
|
||||
expect(event).to include(
|
||||
'event_type' => 'tags.update', 'created_by_user_id' => member_user.id)
|
||||
expect(versions.pluck(:event_id).uniq).to eq([event.fetch('id')])
|
||||
end
|
||||
|
||||
it 'updates deprecated state and records it in tag versions' do
|
||||
@@ -1275,6 +1280,7 @@ RSpec.describe 'Tags API', type: :request do
|
||||
deprecated: '0',
|
||||
}
|
||||
}.to change(TagVersion, :count).by(2)
|
||||
.and change { event_rows.length }.by(1)
|
||||
|
||||
expect(response).to have_http_status(:ok)
|
||||
|
||||
@@ -1290,6 +1296,10 @@ RSpec.describe 'Tags API', type: :request do
|
||||
expect(versions.second.category).to eq('meta')
|
||||
expect(version_alias_names(versions.second, 'ja')).to include('spec_tag')
|
||||
expect(versions.second.created_by_user_id).to eq(member_user.id)
|
||||
event = event_rows.last
|
||||
expect(event).to include(
|
||||
'event_type' => 'tags.update', 'created_by_user_id' => member_user.id)
|
||||
expect(versions.pluck(:event_id).uniq).to eq([event.fetch('id')])
|
||||
end
|
||||
|
||||
it '同じ tag の旧 alias へ戻しても rename できる' do
|
||||
|
||||
@@ -32,8 +32,10 @@ RSpec.describe 'Counts export contracts' do
|
||||
|
||||
before do
|
||||
NicoTagVersion.create!(external_tag: external, version_no: 1,
|
||||
event_id: create_event!(event_type: 'unknown').id,
|
||||
event_type: 'create', linked_tag_ids: '', created_at: Time.utc(2023))
|
||||
NicoTagVersion.create!(external_tag: external, version_no: 2,
|
||||
event_id: create_event!(event_type: 'unknown').id,
|
||||
event_type: 'update', linked_tag_ids: tag.id.to_s, created_at: Time.utc(2024))
|
||||
end
|
||||
|
||||
@@ -192,7 +194,9 @@ RSpec.describe 'Counts export contracts' do
|
||||
expect(CountsExportDownload.find(token, 'owner')).not_to be_nil
|
||||
expect(CountsExportDownload.find(token, 'other')).to be_nil
|
||||
post = create(:post)
|
||||
PostVersion.create!(post:, version_no: 1, event_type: 'discard', url: post.url,
|
||||
PostVersion.create!(
|
||||
event_id: create_event!(event_type: 'unknown').id,
|
||||
post:, version_no: 1, event_type: 'discard', url: post.url,
|
||||
title: 'private', tags: '', tags_json: [], parent_post_ids: '', created_at: Time.utc(2024))
|
||||
expect(CountsExportDownload.find(token, 'owner')).to be_nil
|
||||
end
|
||||
|
||||
@@ -13,7 +13,9 @@ RSpec.describe 'Counts masked pivot contracts' do
|
||||
let!(:tags) do
|
||||
['A', 'B', 'C'].map do |name|
|
||||
tag = create(:tag, primary_name: name)
|
||||
TagVersion.create!(tag:, version_no: 1, event_type: 'create', name:,
|
||||
TagVersion.create!(
|
||||
event_id: create_event!(event_type: 'unknown').id,
|
||||
tag:, version_no: 1, event_type: 'create', name:,
|
||||
category: 'general', aliases: '', parent_tag_ids: '',
|
||||
names: { ja: { name:, script_code: 'Jpan', auto_generated: false, aliases: [] } },
|
||||
created_at: Time.utc(2023))
|
||||
@@ -25,12 +27,16 @@ RSpec.describe 'Counts masked pivot contracts' do
|
||||
[[0, 1], [0], [1, 2]].each_with_index do |indexes, index|
|
||||
post = create(:post)
|
||||
snapshot = indexes.map { { tag_id: tags[_1].id, version_no: 1, sections: [] } }
|
||||
PostVersion.create!(post:, version_no: 1, event_type: 'create',
|
||||
PostVersion.create!(
|
||||
event_id: create_event!(event_type: 'unknown').id,
|
||||
post:, version_no: 1, event_type: 'create',
|
||||
title: "hidden-title-#{ index }", url: post.url, tags: '', tags_json: snapshot,
|
||||
parent_post_ids: '', created_by_user: member, created_at: Time.utc(2024, 1))
|
||||
next if index == 2
|
||||
|
||||
PostVersion.create!(post:, version_no: 2, event_type: 'discard',
|
||||
PostVersion.create!(
|
||||
event_id: create_event!(event_type: 'unknown').id,
|
||||
post:, version_no: 2, event_type: 'discard',
|
||||
title: "private-discard-#{ index }", url: post.url, tags: '', tags_json: [],
|
||||
parent_post_ids: '', created_by_user: member, created_at: Time.utc(2024, 2))
|
||||
end
|
||||
@@ -100,12 +106,16 @@ RSpec.describe 'Counts masked pivot contracts' do
|
||||
|
||||
it 'uses changed-record membership for totals and hides changes to private predecessors' do
|
||||
post = PostVersion.order(:id).last.post
|
||||
PostVersion.create!(post:, version_no: 2, event_type: 'update', title: 'changed-public-title',
|
||||
PostVersion.create!(
|
||||
event_id: create_event!(event_type: 'unknown').id,
|
||||
post:, version_no: 2, event_type: 'update', title: 'changed-public-title',
|
||||
url: post.url, tags: '',
|
||||
tags_json: [{ tag_id: tags.last.id, version_no: 1, sections: [] }],
|
||||
parent_post_ids: '', created_at: Time.utc(2024, 3))
|
||||
restored = PostVersion.order(:id).first.post
|
||||
PostVersion.create!(post: restored, version_no: 3, event_type: 'restore',
|
||||
PostVersion.create!(
|
||||
event_id: create_event!(event_type: 'unknown').id,
|
||||
post: restored, version_no: 3, event_type: 'restore',
|
||||
title: 'restored-public-title', url: restored.url, tags: '',
|
||||
tags_json: [{ tag_id: tags.first.id, version_no: 1, sections: [] }], parent_post_ids: '',
|
||||
created_at: Time.utc(2024, 4))
|
||||
@@ -135,7 +145,9 @@ RSpec.describe 'Counts masked pivot contracts' do
|
||||
|
||||
it 'keeps NULL as a public data value rather than treating it as a rollup' do
|
||||
post = create(:post)
|
||||
PostVersion.create!(post:, version_no: 1, event_type: 'create', title: 'public bot',
|
||||
PostVersion.create!(
|
||||
event_id: create_event!(event_type: 'unknown').id,
|
||||
post:, version_no: 1, event_type: 'create', title: 'public bot',
|
||||
url: post.url, tags: '', tags_json: [], parent_post_ids: '', created_at: Time.utc(2024, 5))
|
||||
page = result(nil, 'rows' => 'user', 'cols' => 'event_type')
|
||||
expect(page[:cells].select { _1[:values].first.nil? }.sum { _1[:count] }).to eq(1)
|
||||
@@ -146,7 +158,9 @@ RSpec.describe 'Counts masked pivot contracts' do
|
||||
it 'sorts public version numbers numerically including formerly hidden records' do
|
||||
post = PostVersion.order(:id).last.post
|
||||
[2, 10].each do |number|
|
||||
PostVersion.create!(post:, version_no: number, event_type: 'update',
|
||||
PostVersion.create!(
|
||||
event_id: create_event!(event_type: 'unknown').id,
|
||||
post:, version_no: number, event_type: 'update',
|
||||
title: 'public numeric sort', url: post.url, tags: '', tags_json: [],
|
||||
parent_post_ids: '', created_at: Time.utc(2024, 5))
|
||||
end
|
||||
|
||||
@@ -56,6 +56,7 @@ RSpec.describe MaterialSyncImporter do
|
||||
profile: 'legacy_drive',
|
||||
export_path: '素材/a.png',
|
||||
created_by_user: user)
|
||||
events = event_rows
|
||||
|
||||
result =
|
||||
described_class.import!(
|
||||
@@ -73,6 +74,7 @@ RSpec.describe MaterialSyncImporter do
|
||||
expect(result.action).to eq(:unchanged)
|
||||
expect(material.reload.tag).to eq(tag)
|
||||
expect(material.url).to eq('https://example.com/human')
|
||||
expect(event_rows).to eq(events)
|
||||
end
|
||||
|
||||
it 'suppresses a Google Drive candidate by relative path prefix' do
|
||||
|
||||
@@ -14,6 +14,47 @@ RSpec.describe MaterialSyncRunner do
|
||||
let(:drive_client) { instance_double(GoogleDrive::ApiClient) }
|
||||
|
||||
describe '#sync!' do
|
||||
it 'groups created and updated materials across sync sources into one event' do
|
||||
existing = Material.create!(
|
||||
source_kind: 'google_drive_file', source_file_id: 'existing-file',
|
||||
source_path: 'old.png', url: 'https://example.com/existing',
|
||||
created_by_user: user, updated_by_user: user)
|
||||
source
|
||||
MaterialSyncSource.create!(
|
||||
name: 'Second Drive source', source_kind: 'google_drive_path',
|
||||
source_file_id: 'folder-456', profile: 'legacy_drive',
|
||||
created_by_user: user, updated_by_user: user)
|
||||
allow(GoogleDrive::ApiClient).to receive(:new).and_return(drive_client)
|
||||
allow(drive_client).to receive(:each_material_file_under_folder) do |folder_id, &block|
|
||||
id = folder_id == 'folder-123' ? 'existing-file' : 'new-file'
|
||||
block.call(id:, name: "#{ id }.png", mime_type: 'image/png',
|
||||
relative_path: "素材/#{ id }.png", sha256_checksum: nil,
|
||||
web_view_link: "https://drive.google.com/file/d/#{ id }/view")
|
||||
end
|
||||
allow(drive_client).to receive(:download_to_tempfile) do |id, **|
|
||||
Tempfile.new(['sync-event', '.png']).tap do |file|
|
||||
file.binmode
|
||||
file.write(id)
|
||||
file.rewind
|
||||
end
|
||||
end
|
||||
allow(MaterialThumbnailGenerator).to receive(:generate!)
|
||||
previous_ids = MaterialVersion.pluck(:id)
|
||||
|
||||
result = nil
|
||||
expect { result = described_class.sync_enabled! }
|
||||
.to change { event_rows.length }.by(1)
|
||||
|
||||
expect(result).to have_attributes(imported: 1, updated: 1, failed: 0)
|
||||
event = event_rows.last
|
||||
expect(event.fetch('event_type')).to eq('materials.sync')
|
||||
created = Material.find_by!(source_file_id: 'new-file')
|
||||
versions = MaterialVersion.where.not(id: previous_ids)
|
||||
expect(versions.pluck(:material_id).uniq).to contain_exactly(existing.id, created.id)
|
||||
expect(versions.pluck(:event_type)).to include('create', 'update')
|
||||
expect(versions.pluck(:event_id).uniq).to eq([event.fetch('id')])
|
||||
end
|
||||
|
||||
it 'imports google drive path candidates as they are yielded' do
|
||||
first_entry = { id: 'file-1',
|
||||
name: 'a.png',
|
||||
|
||||
@@ -15,6 +15,8 @@ RSpec.describe NicoTagVersionRecorder do
|
||||
external_tag:, version_no: 1, event_type: 'create',
|
||||
name: 'nico:raw tag[]', linked_tag_ids: '', created_by_user: member)
|
||||
expect(external_tag.reload.nico_tag_versions).to contain_exactly(version)
|
||||
expect(version.event).to have_attributes(
|
||||
event_type: 'external_tags.create', created_by_user: member)
|
||||
end
|
||||
|
||||
it 'uses the latest history number when the record has no version_no column' do
|
||||
@@ -25,6 +27,8 @@ RSpec.describe NicoTagVersionRecorder do
|
||||
|
||||
expect(second).to have_attributes(version_no: 2, name: 'nico:raw tag[]',
|
||||
linked_tag_ids: tag.id.to_s)
|
||||
expect(second.event).to have_attributes(
|
||||
event_type: 'external_tags.update', created_by_user: member)
|
||||
expect(first.reload.name).to eq('nico:raw tag[]')
|
||||
expect(external_tag.reload.has_attribute?(:version_no)).to be(false)
|
||||
end
|
||||
|
||||
@@ -88,3 +88,86 @@ RSpec.describe PostBulkCreator do
|
||||
expect(creator).to have_received(:create!).with(locale).once
|
||||
end
|
||||
end
|
||||
|
||||
RSpec.describe 'PostBulkCreator event grouping', type: :model do
|
||||
self.use_transactional_tests = false
|
||||
|
||||
before do
|
||||
expect(Rails.env.test?).to be(true)
|
||||
expect(ApplicationRecord.connection.open_transactions).to eq(0)
|
||||
@prefix = "bulk_event_#{ SecureRandom.hex(8) }"
|
||||
@actor = create(:user, :member)
|
||||
allow(PostCreatePreflight).to receive(:new) do |attributes:, **|
|
||||
specs = [{ name: attributes.fetch(:title), category: :general }]
|
||||
instance_double(PostCreatePreflight, run: attributes.merge(
|
||||
existing_post_id: nil, snapshot_tag_specs: specs, post_tag_specs: specs,
|
||||
normalised_parent_post_ids: [], tag_sections: { }, video_ms: nil))
|
||||
end
|
||||
end
|
||||
|
||||
after do
|
||||
if @actor
|
||||
posts = Post.where(uploaded_user: @actor)
|
||||
PostTagSection.where(post_id: posts.select(:id)).delete_all
|
||||
PostTag.where(post_id: posts.select(:id)).delete_all
|
||||
PostVersion.where(post_id: posts.select(:id)).delete_all
|
||||
posts.delete_all
|
||||
tag_ids = TagName.where(name: ["#{ @prefix }_1", "#{ @prefix }_2"]).pluck(:tag_id)
|
||||
TagVersion.where(tag_id: tag_ids).delete_all
|
||||
TagName.where(tag_id: tag_ids).delete_all
|
||||
Tag.where(id: tag_ids).delete_all
|
||||
EventRecords::EventRow.where(created_by_user_id: @actor.id).delete_all
|
||||
@actor.delete
|
||||
end
|
||||
end
|
||||
|
||||
it 'shares one creation event between real workers and their tag histories' do
|
||||
posts = [1, 2].map do |number|
|
||||
{ title: "#{ @prefix }_#{ number }",
|
||||
url: "https://example.com/#{ @prefix }/#{ number }" }
|
||||
end
|
||||
|
||||
result = nil
|
||||
expect {
|
||||
result = PostBulkCreator.new(actor: @actor, posts:, thumbnails: { })
|
||||
.run(Locale.nipponese)
|
||||
}.to change { event_rows.length }.by(1)
|
||||
|
||||
expect(result.fetch(:results).map { _1.fetch(:status) }).to eq(['created', 'created'])
|
||||
event = event_rows.last
|
||||
expect(event).to include(
|
||||
'event_type' => 'posts.create', 'created_by_user_id' => @actor.id)
|
||||
versions = PostVersion.where(created_by_user_id: @actor.id)
|
||||
expect(versions.count).to eq(2)
|
||||
expect(versions.pluck(:event_id).uniq).to eq([event.fetch('id')])
|
||||
tag_versions = TagVersion.where(created_by_user_id: @actor.id)
|
||||
expect(tag_versions.count).to eq(2)
|
||||
expect(tag_versions.pluck(:event_id).uniq).to eq([event.fetch('id')])
|
||||
end
|
||||
|
||||
it 'does not leave an event when every row fails validation' do
|
||||
preflight = instance_double(PostCreatePreflight)
|
||||
allow(PostCreatePreflight).to receive(:new).and_return(preflight)
|
||||
allow(preflight).to receive(:run).and_raise(
|
||||
PostCreatePreflight::ValidationFailed.new(fields: { url: ['invalid'] }))
|
||||
events = event_rows
|
||||
|
||||
result = PostBulkCreator.new(
|
||||
actor: @actor, posts: [{ title: 'invalid' }], thumbnails: { }).run(Locale.nipponese)
|
||||
|
||||
expect(result.fetch(:results).map { _1.fetch(:status) }).to eq(['failed'])
|
||||
expect(event_rows).to eq(events)
|
||||
end
|
||||
|
||||
it 'does not leave an event when every row is skipped' do
|
||||
preflight = instance_double(PostCreatePreflight, run: { existing_post_id: 123 })
|
||||
allow(PostCreatePreflight).to receive(:new).and_return(preflight)
|
||||
events = event_rows
|
||||
|
||||
result = PostBulkCreator.new(
|
||||
actor: @actor, posts: [{ title: 'existing' }], thumbnails: { }).run(Locale.nipponese)
|
||||
|
||||
expect(result.fetch(:results).map { _1.fetch(:status) }).to eq(['skipped'])
|
||||
expect(event_rows).to eq(events)
|
||||
end
|
||||
end
|
||||
|
||||
@@ -16,6 +16,7 @@ RSpec.describe 'Shared resource IDs across MySQL connections', type: :model do
|
||||
@tag = create(:tag, primary_name: "#{ @prefix }_owner")
|
||||
@group = TagGroup.create!(name: "#{ @prefix }_owner", version_no: 1)
|
||||
@tag_ids = Queue.new
|
||||
@event_ids = Queue.new
|
||||
@threads = []
|
||||
@release = Queue.new
|
||||
end
|
||||
@@ -42,6 +43,9 @@ RSpec.describe 'Shared resource IDs across MySQL connections', type: :model do
|
||||
ids << @tag.id if @tag
|
||||
TagName.where(tag_id: ids).delete_all
|
||||
Tag.where(id: ids).delete_all
|
||||
event_ids = []
|
||||
event_ids << @event_ids.pop until @event_ids.empty? if @event_ids
|
||||
EventRecords::EventRow.where(id: event_ids).delete_all
|
||||
end
|
||||
end
|
||||
|
||||
@@ -72,11 +76,17 @@ RSpec.describe 'Shared resource IDs across MySQL connections', type: :model do
|
||||
when :description
|
||||
TagDescription.create!(tag: @tag, language_code: 'ja', body: '', version_no: 1)
|
||||
when :description_version
|
||||
event = create_event!(event_type: 'unknown')
|
||||
@event_ids << event.id
|
||||
TagDescriptionVersion.create!(
|
||||
event_id: event.id,
|
||||
tag_id: @tag.id, language_code: 'ja', body: 'body', version_no: 1,
|
||||
event_type: 'create', created_at: Time.current)
|
||||
when :group_version
|
||||
event = create_event!(event_type: 'unknown')
|
||||
@event_ids << event.id
|
||||
TagGroupVersion.create!(
|
||||
event_id: event.id,
|
||||
tag_group: @group, name: @group.name, version_no: 1, event_type: 'create',
|
||||
members: [], placements: [], created_at: Time.current)
|
||||
when :group
|
||||
|
||||
@@ -15,10 +15,12 @@ RSpec.describe SharedResourceIdAllocator do
|
||||
TagGroup.new(id:, name: "group #{ number }", version_no: number)
|
||||
when 'tag_description_versions'
|
||||
TagDescriptionVersion.new(
|
||||
event_id: create_event!(event_type: 'unknown').id,
|
||||
id:, tag_id: tag.id, language_code: 'ja', body: 'body', version_no: number,
|
||||
event_type: 'create', created_at: Time.current)
|
||||
when 'tag_group_versions'
|
||||
TagGroupVersion.new(
|
||||
event_id: create_event!(event_type: 'unknown').id,
|
||||
id:, tag_group_id: group.id, name: group.name, version_no: number,
|
||||
event_type: 'create', members: [], placements: [], created_at: Time.current)
|
||||
end
|
||||
@@ -82,6 +84,7 @@ RSpec.describe SharedResourceIdAllocator do
|
||||
it 'reserves a Tag ID referenced only by remaining description history' do
|
||||
high = [Tag.maximum(:id).to_i, ExternalTag.maximum(:id).to_i].max + 1000
|
||||
TagDescriptionVersion.create!(
|
||||
event_id: create_event!(event_type: 'unknown').id,
|
||||
tag_id: high, language_code: 'ja', version_no: 1, body: 'history',
|
||||
event_type: 'create', created_at: Time.current)
|
||||
expect(create(:tag).id).to be > high
|
||||
|
||||
@@ -18,6 +18,9 @@ RSpec.describe VersionRecorder do
|
||||
|
||||
expect(version.version_no).to eq(1)
|
||||
expect(post_record.reload.version_no).to eq(1)
|
||||
expect(version.event).to have_attributes(
|
||||
event_type: 'posts.create', created_by_user: member, reason: nil)
|
||||
expect(version.event.created_at).to be_present
|
||||
end
|
||||
|
||||
it 'updates record version_no when creating the next version' do
|
||||
@@ -44,6 +47,7 @@ RSpec.describe VersionRecorder do
|
||||
post: post_record,
|
||||
event_type: :create,
|
||||
created_by_user: member)
|
||||
events = event_rows
|
||||
|
||||
expect {
|
||||
version =
|
||||
@@ -56,6 +60,130 @@ RSpec.describe VersionRecorder do
|
||||
}.not_to change(PostVersion, :count)
|
||||
|
||||
expect(post_record.reload.version_no).to eq(1)
|
||||
expect(event_rows).to eq(events)
|
||||
end
|
||||
|
||||
it 'shares the outer operation between different history types' do
|
||||
tag = create(:tag)
|
||||
external = create(:external_tag)
|
||||
material = Material.create!(url: 'https://example.com/event-material')
|
||||
member
|
||||
post_record
|
||||
versions = []
|
||||
|
||||
expect {
|
||||
described_class.with_event(event_type: 'posts.create', created_by_user: member) do
|
||||
versions << PostVersionRecorder.record!(
|
||||
post: post_record, event_type: :create, created_by_user: member)
|
||||
described_class.with_event(event_type: 'tags.update', created_by_user: nil) do
|
||||
versions << TagVersioning.record_tag_snapshot!(tag, created_by_user: member)
|
||||
versions << NicoTagVersionRecorder.record!(
|
||||
external_tag: external, event_type: :create, created_by_user: member)
|
||||
versions << MaterialVersionRecorder.record!(
|
||||
material:, event_type: :create, created_by_user: member)
|
||||
end
|
||||
end
|
||||
}.to change(Event, :count).by(1)
|
||||
|
||||
expect(versions.map(&:event_id).uniq).to eq([versions.first.event_id])
|
||||
expect(versions.first.event).to have_attributes(
|
||||
event_type: 'posts.create', created_by_user: member)
|
||||
expect(versions.first.event.nico_tag_versions).to contain_exactly(versions[2])
|
||||
end
|
||||
|
||||
it 'recreates a rolled-back event before the next successful history' do
|
||||
member
|
||||
post_record
|
||||
events = event_rows
|
||||
version = nil
|
||||
|
||||
described_class.with_event(event_type: 'posts.sync', created_by_user: nil) do
|
||||
ApplicationRecord.transaction(requires_new: true) do
|
||||
PostVersionRecorder.record!(
|
||||
post: post_record, event_type: :create, created_by_user: member)
|
||||
raise ActiveRecord::Rollback
|
||||
end
|
||||
|
||||
expect(event_rows).to eq(events)
|
||||
expect(post_record.reload.post_versions).to be_empty
|
||||
expect(post_record.version_no).to eq(1)
|
||||
version = PostVersionRecorder.record!(
|
||||
post: post_record, event_type: :create, created_by_user: member)
|
||||
end
|
||||
|
||||
expect(Event.count).to eq(events.length + 1)
|
||||
expect(version.event).to have_attributes(event_type: 'posts.sync', created_by_user: nil)
|
||||
end
|
||||
|
||||
it 'clears the operation after an exception' do
|
||||
expect {
|
||||
described_class.with_event(event_type: 'posts.sync', created_by_user: nil) do
|
||||
raise 'operation failed'
|
||||
end
|
||||
}.to raise_error('operation failed')
|
||||
|
||||
version = PostVersionRecorder.record!(
|
||||
post: post_record, event_type: :create, created_by_user: member)
|
||||
|
||||
expect(version.event).to have_attributes(event_type: 'posts.create', created_by_user: member)
|
||||
end
|
||||
|
||||
it 'does not create an event for an empty operation' do
|
||||
expect {
|
||||
described_class.with_event(event_type: 'posts.sync', created_by_user: nil) { nil }
|
||||
}.not_to change(Event, :count)
|
||||
end
|
||||
|
||||
it 'rolls back the event when its version fails validation' do
|
||||
post_record.update_columns(url: '')
|
||||
member
|
||||
events = event_rows
|
||||
|
||||
expect {
|
||||
ApplicationRecord.transaction(requires_new: true) do
|
||||
PostVersionRecorder.record!(
|
||||
post: post_record, event_type: :create, created_by_user: member)
|
||||
end
|
||||
}.to raise_error(ActiveRecord::RecordInvalid)
|
||||
|
||||
expect(post_record.reload.post_versions).to be_empty
|
||||
expect(event_rows).to eq(events)
|
||||
end
|
||||
|
||||
it 'keeps an explicitly supplied event' do
|
||||
event = Event.create!(event_type: 'posts.create', created_by_user: member)
|
||||
|
||||
expect {
|
||||
version = PostVersionRecorder.record!(
|
||||
post: post_record, event_type: :create, created_by_user: member, event:)
|
||||
expect(version.event).to eq(event)
|
||||
}.not_to change(Event, :count)
|
||||
end
|
||||
|
||||
it 'keeps simultaneous operation scopes separate' do
|
||||
ready = Queue.new
|
||||
continuation = Queue.new
|
||||
events = ['posts.sync', 'materials.sync'].to_h do |event_type|
|
||||
event = instance_double(Event, persisted?: true)
|
||||
allow(Event).to receive(:create!).with({ event_type:, created_by_user: nil })
|
||||
.and_return(event)
|
||||
[event_type, event]
|
||||
end
|
||||
workers = events.keys.map do |event_type|
|
||||
Thread.new do
|
||||
described_class.with_event(event_type:, created_by_user: nil) do
|
||||
ready << true
|
||||
continuation.pop
|
||||
described_class.record_event!(event_type: 'tags.create', created_by_user: nil)
|
||||
end
|
||||
end
|
||||
end
|
||||
2.times { ready.pop }
|
||||
2.times { continuation << true }
|
||||
|
||||
expect(workers.map(&:value)).to eq(events.values)
|
||||
ensure
|
||||
workers&.each(&:join)
|
||||
end
|
||||
|
||||
it 'raises when record version_no is older than the latest version' do
|
||||
|
||||
@@ -42,6 +42,41 @@ RSpec.describe Youtube::Sync do
|
||||
end
|
||||
|
||||
describe '#sync!' do
|
||||
it 'groups created and updated post histories into one sync event' do
|
||||
allow(PostVersionRecorder).to receive(:record!).and_call_original
|
||||
allow(PostVersionRecorder).to receive(:ensure_snapshot!).and_call_original
|
||||
existing = create(:post, url: 'https://youtu.be/video-1', title: 'old title')
|
||||
allow(sync).to receive(:query_terms).and_return([])
|
||||
allow(sync).to receive(:playlist_ids).and_return(['PL123'])
|
||||
allow(client).to receive(:playlist_items).with(playlist_id: 'PL123', page_token: nil)
|
||||
.and_return('items' => [
|
||||
{ 'contentDetails' => { 'videoId' => 'video-1' } },
|
||||
{ 'contentDetails' => { 'videoId' => 'video-2' } }])
|
||||
allow(client).to receive(:videos).with(['video-1', 'video-2'])
|
||||
.and_return('items' => [
|
||||
youtube_video_item(id: 'video-1', title: 'updated', channel_id: 'UC_NONE'),
|
||||
youtube_video_item(id: 'video-2', title: 'created', channel_id: 'UC_NONE')])
|
||||
previous_post_ids = PostVersion.pluck(:id)
|
||||
previous_tag_ids = TagVersion.pluck(:id)
|
||||
|
||||
expect { sync.sync! }.to change { event_rows.length }.by(1)
|
||||
|
||||
event = event_rows.last
|
||||
expect(event).to include('event_type' => 'posts.sync', 'created_by_user_id' => nil)
|
||||
versions = PostVersion.where.not(id: previous_post_ids)
|
||||
created = Post.find_by!(url: 'https://www.youtube.com/watch?v=video-2')
|
||||
expect(versions.pluck(:post_id).uniq).to contain_exactly(existing.id, created.id)
|
||||
expect(versions.pluck(:event_type)).to include('create', 'update')
|
||||
expect(versions.pluck(:event_id).uniq).to eq([event.fetch('id')])
|
||||
tag_versions = TagVersion.where.not(id: previous_tag_ids)
|
||||
expect(tag_versions).not_to be_empty
|
||||
expect(tag_versions.pluck(:event_id).uniq).to eq([event.fetch('id')])
|
||||
|
||||
events = event_rows
|
||||
expect { sync.sync! }.not_to change(PostVersion, :count)
|
||||
expect(event_rows).to eq(events)
|
||||
end
|
||||
|
||||
it 'returns without fetching video details when no video ids are discovered' do
|
||||
allow(sync).to receive(:query_terms).and_return([])
|
||||
allow(sync).to receive(:playlist_ids).and_return([])
|
||||
|
||||
@@ -0,0 +1,15 @@
|
||||
module EventRecords
|
||||
# Read the database contract without requiring an application Event model.
|
||||
class EventRow < ActiveRecord::Base
|
||||
self.table_name = 'events'
|
||||
end
|
||||
|
||||
def event_rows
|
||||
EventRow.order(:id).map(&:attributes)
|
||||
end
|
||||
|
||||
def create_event! event_type:, created_by_user: nil
|
||||
EventRow.create!(event_type:, created_by_user_id: created_by_user&.id,
|
||||
created_at: Time.current)
|
||||
end
|
||||
end
|
||||
@@ -3,11 +3,13 @@ require 'cgi'
|
||||
# SQL fixtures use the migration contract without inventing application models.
|
||||
# Include explicitly; these helpers must not affect unrelated examples.
|
||||
module TagGroupRecords
|
||||
include EventRecords
|
||||
|
||||
GROUP_TABLES = [
|
||||
'tag_groups', 'tag_group_tags', 'tag_group_groups',
|
||||
'tag_group_placements', 'tag_group_versions'].freeze
|
||||
WRITE_TABLES = GROUP_TABLES + [
|
||||
'tag_names', 'tag_description_versions',
|
||||
'events', 'tag_names', 'tag_description_versions',
|
||||
'tag_descriptions']
|
||||
|
||||
def group_connection = ApplicationRecord.connection
|
||||
@@ -114,6 +116,7 @@ module TagGroupRecords
|
||||
group_id = insert_group_row('tag_groups', attributes)
|
||||
insert_group_row('tag_group_versions', {
|
||||
tag_group_id: group_id, version_no: 1, event_type: 'create',
|
||||
event_id: create_event!(event_type: 'tag_groups.create', created_by_user: user).id,
|
||||
name:, description:, members: members.to_json, placements: placements.to_json,
|
||||
created_by_user_id: user.id, created_at: now })
|
||||
members.each do |member|
|
||||
|
||||
@@ -174,20 +174,20 @@ RSpec.describe 'nico:sync' do
|
||||
|
||||
def create_post_version_for!(post, version_no: 1, event_type: 'create', created_by_user: nil)
|
||||
PostVersion.create!(
|
||||
post: post,
|
||||
version_no: version_no,
|
||||
event_type: event_type,
|
||||
title: post.title,
|
||||
url: post.url,
|
||||
thumbnail_base: post.thumbnail_base,
|
||||
tags: snapshot_tags(post),
|
||||
tags_json: post.snapshot_tags_json,
|
||||
parent_post_ids: post.snapshot_parent_post_ids.join(' '),
|
||||
original_created_from: post.original_created_from,
|
||||
original_created_before: post.original_created_before,
|
||||
created_at: Time.current,
|
||||
created_by_user: created_by_user
|
||||
)
|
||||
event_id: create_event!(event_type: 'unknown').id,
|
||||
post: post,
|
||||
version_no: version_no,
|
||||
event_type: event_type,
|
||||
title: post.title,
|
||||
url: post.url,
|
||||
thumbnail_base: post.thumbnail_base,
|
||||
tags: snapshot_tags(post),
|
||||
tags_json: post.snapshot_tags_json,
|
||||
parent_post_ids: post.snapshot_parent_post_ids.join(' '),
|
||||
original_created_from: post.original_created_from,
|
||||
original_created_before: post.original_created_before,
|
||||
created_at: Time.current,
|
||||
created_by_user: created_by_user)
|
||||
end
|
||||
|
||||
it '新規 post 作成時に version 1 を作る' do
|
||||
@@ -209,6 +209,7 @@ RSpec.describe 'nico:sync' do
|
||||
expect {
|
||||
run_rake_task('nico:sync')
|
||||
}.to change(PostVersion, :count).by(1)
|
||||
.and change { event_rows.length }.by(1)
|
||||
|
||||
post = Post.find_by!(url: 'https://www.nicovideo.jp/watch/sm9')
|
||||
version = post.post_versions.order(:version_no).last
|
||||
@@ -217,6 +218,32 @@ RSpec.describe 'nico:sync' do
|
||||
expect(version.event_type).to eq('create')
|
||||
expect(version.created_by_user).to be_nil
|
||||
expect(version.tags).to eq(snapshot_tags(post.reload))
|
||||
event = event_rows.last
|
||||
expect(event).to include('event_type' => 'posts.sync', 'created_by_user_id' => nil)
|
||||
expect(version.event_id).to eq(event.fetch('id'))
|
||||
end
|
||||
|
||||
it 'groups created and updated post histories into one sync event' do
|
||||
existing = create(:post, title: 'old', url: 'https://www.nicovideo.jp/watch/sm9')
|
||||
stub_python([
|
||||
{ 'code' => 'sm9', 'title' => 'updated', 'tags' => [] },
|
||||
{ 'code' => 'sm10', 'title' => 'created', 'tags' => [] }])
|
||||
allow(URI).to receive(:open).and_return(StringIO.new('<html></html>'))
|
||||
previous_post_ids = PostVersion.pluck(:id)
|
||||
previous_tag_ids = TagVersion.pluck(:id)
|
||||
|
||||
expect { run_rake_task('nico:sync') }.to change { event_rows.length }.by(1)
|
||||
|
||||
event = event_rows.last
|
||||
expect(event).to include('event_type' => 'posts.sync', 'created_by_user_id' => nil)
|
||||
created = Post.find_by!(url: 'https://www.nicovideo.jp/watch/sm10')
|
||||
versions = PostVersion.where.not(id: previous_post_ids)
|
||||
expect(versions.pluck(:post_id).uniq).to contain_exactly(existing.id, created.id)
|
||||
expect(versions.pluck(:event_type)).to include('create', 'update')
|
||||
expect(versions.pluck(:event_id).uniq).to eq([event.fetch('id')])
|
||||
tag_versions = TagVersion.where.not(id: previous_tag_ids)
|
||||
expect(tag_versions).not_to be_empty
|
||||
expect(tag_versions.pluck(:event_id).uniq).to eq([event.fetch('id')])
|
||||
end
|
||||
|
||||
it '既存 post の内容または tags が変わったとき update version を作る' do
|
||||
@@ -282,6 +309,7 @@ RSpec.describe 'nico:sync' do
|
||||
}])
|
||||
|
||||
allow(URI).to receive(:open).and_return(StringIO.new('<html></html>'))
|
||||
events = event_rows
|
||||
|
||||
expect {
|
||||
run_rake_task('nico:sync')
|
||||
@@ -291,6 +319,7 @@ RSpec.describe 'nico:sync' do
|
||||
expect(version.version_no).to eq(1)
|
||||
expect(version.event_type).to eq('create')
|
||||
expect(version.tags).to eq(snapshot_tags(post.reload))
|
||||
expect(event_rows).to eq(events)
|
||||
end
|
||||
|
||||
it '新規 nico tag に nico tag version を作る' do
|
||||
|
||||
@@ -1,29 +1,6 @@
|
||||
import autoprefixer from 'autoprefixer'
|
||||
import tailwindcss from 'tailwindcss'
|
||||
|
||||
// Apply the same breakpoints to handwritten CSS and Tailwind utilities.
|
||||
export const inlineBreakpoints = {
|
||||
postcssPlugin: 'inline-breakpoints',
|
||||
OnceExit (root) {
|
||||
const queries = []
|
||||
root.walkAtRules ('media', query => {
|
||||
if (/\b(?:min|max)-width\s*:/.test (query.params))
|
||||
queries.push (query)
|
||||
})
|
||||
for (const query of queries) {
|
||||
const vertical = query.cloneAfter ({
|
||||
params: query.params.replace (/\b(min|max)-width(?=\s*:)/g, '$1-height') })
|
||||
for (const [branch, scope] of [
|
||||
[query, ':where(html:not(:lang(mn-Mong)))'],
|
||||
[vertical, ':where(html:lang(mn-Mong))']]) {
|
||||
branch.walkRules (rule => {
|
||||
rule.selectors = rule.selectors.map (selector => `${scope} ${selector}`)
|
||||
})
|
||||
}
|
||||
}
|
||||
export default {
|
||||
plugins: {
|
||||
tailwindcss: {},
|
||||
autoprefixer: {},
|
||||
},
|
||||
}
|
||||
|
||||
export default {
|
||||
plugins: [tailwindcss (), inlineBreakpoints, autoprefixer ()],
|
||||
}
|
||||
|
||||
@@ -1,52 +0,0 @@
|
||||
import postcss from 'postcss'
|
||||
import tailwindcss from 'tailwindcss'
|
||||
import { describe, expect, it } from 'vitest'
|
||||
|
||||
import { inlineBreakpoints } from './postcss.config.js'
|
||||
|
||||
describe ('inline breakpoints', () => {
|
||||
it ('uses height for vertical menus and width for horizontal menus', async () => {
|
||||
const source = `
|
||||
@media (min-width: 768px) { .menu, .account { display: flex } }
|
||||
@media (min-width: 1024px) { .menu { font-size: 1rem } }
|
||||
@media (max-width: 767px) { .mobile { display: block } }
|
||||
@media (prefers-reduced-motion: reduce) { .menu { transition: none } }
|
||||
`
|
||||
const { css } = await postcss ([inlineBreakpoints]).process (
|
||||
source, { from: 'menus.css' })
|
||||
const rules = []
|
||||
postcss.parse (css).walkRules (rule => {
|
||||
rules.push ([rule.parent.params, rule.selector])
|
||||
})
|
||||
|
||||
expect (rules).toEqual ([
|
||||
['(min-width: 768px)',
|
||||
':where(html:not(:lang(mn-Mong))) .menu, '
|
||||
+ ':where(html:not(:lang(mn-Mong))) .account'],
|
||||
['(min-height: 768px)',
|
||||
':where(html:lang(mn-Mong)) .menu, :where(html:lang(mn-Mong)) .account'],
|
||||
['(min-width: 1024px)', ':where(html:not(:lang(mn-Mong))) .menu'],
|
||||
['(min-height: 1024px)', ':where(html:lang(mn-Mong)) .menu'],
|
||||
['(max-width: 767px)', ':where(html:not(:lang(mn-Mong))) .mobile'],
|
||||
['(max-height: 767px)', ':where(html:lang(mn-Mong)) .mobile'],
|
||||
['(prefers-reduced-motion: reduce)', '.menu']])
|
||||
})
|
||||
|
||||
it ('includes responsive utilities generated by Tailwind', async () => {
|
||||
const { css } = await postcss ([tailwindcss ({
|
||||
content: [{ raw: '<div class="md:hidden lg:text-base"></div>' }],
|
||||
corePlugins: { preflight: false } }), inlineBreakpoints]).process (
|
||||
'@tailwind utilities;', { from: 'utilities.css' })
|
||||
const rules = []
|
||||
postcss.parse (css).walkRules (rule => {
|
||||
rules.push ([rule.parent.params, rule.selector])
|
||||
})
|
||||
|
||||
expect (rules).toContainEqual ([
|
||||
'(min-width: 768px)', ':where(html:not(:lang(mn-Mong))) .md\\:hidden'])
|
||||
expect (rules).toContainEqual ([
|
||||
'(min-height: 768px)', ':where(html:lang(mn-Mong)) .md\\:hidden'])
|
||||
expect (rules).toContainEqual ([
|
||||
'(min-height: 1024px)', ':where(html:lang(mn-Mong)) .lg\\:text-base'])
|
||||
})
|
||||
})
|
||||
@@ -1,94 +0,0 @@
|
||||
Copyright 2018 The Noto Project Authors (github.com/googlei18n/noto-fonts)
|
||||
|
||||
This Font Software is licensed under the SIL Open Font License,
|
||||
Version 1.1.
|
||||
|
||||
This license is copied below, and is also available with a FAQ at:
|
||||
http://scripts.sil.org/OFL
|
||||
|
||||
-----------------------------------------------------------
|
||||
SIL OPEN FONT LICENSE Version 1.1 - 26 February 2007
|
||||
-----------------------------------------------------------
|
||||
|
||||
PREAMBLE
|
||||
The goals of the Open Font License (OFL) are to stimulate worldwide
|
||||
development of collaborative font projects, to support the font
|
||||
creation efforts of academic and linguistic communities, and to
|
||||
provide a free and open framework in which fonts may be shared and
|
||||
improved in partnership with others.
|
||||
|
||||
The OFL allows the licensed fonts to be used, studied, modified and
|
||||
redistributed freely as long as they are not sold by themselves. The
|
||||
fonts, including any derivative works, can be bundled, embedded,
|
||||
redistributed and/or sold with any software provided that any reserved
|
||||
names are not used by derivative works. The fonts and derivatives,
|
||||
however, cannot be released under any other type of license. The
|
||||
requirement for fonts to remain under this license does not apply to
|
||||
any document created using the fonts or their derivatives.
|
||||
|
||||
DEFINITIONS
|
||||
"Font Software" refers to the set of files released by the Copyright
|
||||
Holder(s) under this license and clearly marked as such. This may
|
||||
include source files, build scripts and documentation.
|
||||
|
||||
"Reserved Font Name" refers to any names specified as such after the
|
||||
copyright statement(s).
|
||||
|
||||
"Original Version" refers to the collection of Font Software
|
||||
components as distributed by the Copyright Holder(s).
|
||||
|
||||
"Modified Version" refers to any derivative made by adding to,
|
||||
deleting, or substituting -- in part or in whole -- any of the
|
||||
components of the Original Version, by changing formats or by porting
|
||||
the Font Software to a new environment.
|
||||
|
||||
"Author" refers to any designer, engineer, programmer, technical
|
||||
writer or other person who contributed to the Font Software.
|
||||
|
||||
PERMISSION & CONDITIONS
|
||||
Permission is hereby granted, free of charge, to any person obtaining
|
||||
a copy of the Font Software, to use, study, copy, merge, embed,
|
||||
modify, redistribute, and sell modified and unmodified copies of the
|
||||
Font Software, subject to the following conditions:
|
||||
|
||||
1) Neither the Font Software nor any of its individual components, in
|
||||
Original or Modified Versions, may be sold by itself.
|
||||
|
||||
2) Original or Modified Versions of the Font Software may be bundled,
|
||||
redistributed and/or sold with any software, provided that each copy
|
||||
contains the above copyright notice and this license. These can be
|
||||
included either as stand-alone text files, human-readable headers or
|
||||
in the appropriate machine-readable metadata fields within text or
|
||||
binary files as long as those fields can be easily viewed by the user.
|
||||
|
||||
3) No Modified Version of the Font Software may use the Reserved Font
|
||||
Name(s) unless explicit written permission is granted by the
|
||||
corresponding Copyright Holder. This restriction only applies to the
|
||||
primary font name as presented to the users.
|
||||
|
||||
4) The name(s) of the Copyright Holder(s) or the Author(s) of the Font
|
||||
Software shall not be used to promote, endorse or advertise any
|
||||
Modified Version, except to acknowledge the contribution(s) of the
|
||||
Copyright Holder(s) and the Author(s) or with their explicit written
|
||||
permission.
|
||||
|
||||
5) The Font Software, modified or unmodified, in part or in whole,
|
||||
must be distributed entirely under this license, and must not be
|
||||
distributed under any other license. The requirement for fonts to
|
||||
remain under this license does not apply to any document created using
|
||||
the Font Software.
|
||||
|
||||
TERMINATION
|
||||
This license becomes null and void if any of the above conditions are
|
||||
not met.
|
||||
|
||||
DISCLAIMER
|
||||
THE FONT SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
|
||||
EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO ANY WARRANTIES OF
|
||||
MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT
|
||||
OF COPYRIGHT, PATENT, TRADEMARK, OR OTHER RIGHT. IN NO EVENT SHALL THE
|
||||
COPYRIGHT HOLDER BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
|
||||
INCLUDING ANY GENERAL, SPECIAL, INDIRECT, INCIDENTAL, OR CONSEQUENTIAL
|
||||
DAMAGES, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
|
||||
FROM, OUT OF THE USE OR INABILITY TO USE THE FONT SOFTWARE OR FROM
|
||||
OTHER DEALINGS IN THE FONT SOFTWARE.
|
||||
バイナリファイルは表示されません。
@@ -1,11 +0,0 @@
|
||||
Noto Sans Mongolian Regular, unmodified TrueType font.
|
||||
|
||||
Font copyright: Copyright 2018 Google Inc. All Rights Reserved.
|
||||
|
||||
- Source: https://github.com/notofonts/noto-fonts/tree/main/hinted/ttf/NotoSansMongolian
|
||||
- Font: https://raw.githubusercontent.com/notofonts/noto-fonts/main/hinted/ttf/NotoSansMongolian/NotoSansMongolian-Regular.ttf
|
||||
- License: SIL Open Font License 1.1; see the accompanying LICENSE.
|
||||
- Retrieved: 2026-11-08.
|
||||
|
||||
Used by the Mongolian UI at `/mn-Mong`.
|
||||
The font and license are served together from this directory.
|
||||
@@ -1,10 +1,9 @@
|
||||
import { mkdir, mkdtemp, rm, writeFile } from 'node:fs/promises'
|
||||
import { tmpdir } from 'node:os'
|
||||
import path from 'node:path'
|
||||
import { createServer } from 'vite'
|
||||
import { afterAll, afterEach, beforeEach, describe, expect, it, vi } from 'vitest'
|
||||
|
||||
import { generateHelpAssets, helpAssets } from './help-assets'
|
||||
import { generateHelpAssets } from './help-assets'
|
||||
|
||||
import type { ArticleMeta, HelpChange, HelpSearchEntry, HelpTitleIndex } from '@/lib/help'
|
||||
|
||||
@@ -110,22 +109,4 @@ describe ('Build-time Help assets', () => {
|
||||
it ('rejects an empty Help checkout', async () => {
|
||||
await expect (generateHelpAssets (root)).rejects.toThrow ('No Help articles found')
|
||||
})
|
||||
|
||||
it ('defers missing Help errors until a Help module is requested', async () => {
|
||||
const server = await createServer ({
|
||||
configFile: false,
|
||||
root,
|
||||
plugins: [helpAssets ()],
|
||||
server: { middlewareMode: true, watch: null } })
|
||||
try
|
||||
{
|
||||
await server.pluginContainer.buildStart ({})
|
||||
await expect (server.pluginContainer.load ('\0virtual:help/articles'))
|
||||
.rejects.toThrow ('ENOENT')
|
||||
}
|
||||
finally
|
||||
{
|
||||
await server.close ()
|
||||
}
|
||||
})
|
||||
})
|
||||
|
||||
@@ -159,9 +159,10 @@ export const helpAssets = (): Plugin => {
|
||||
configResolved (config) {
|
||||
state.root = path.resolve (config.root, 'help')
|
||||
},
|
||||
buildStart () {
|
||||
state.data = undefined
|
||||
this.addWatchFile (state.root)
|
||||
async buildStart () {
|
||||
state.data = generateHelpAssets (state.root)
|
||||
const generated = await data ()
|
||||
generated.files.forEach (file => this.addWatchFile (file))
|
||||
},
|
||||
resolveId (id) {
|
||||
return id.startsWith (prefix) ? `\0${ id }` : null
|
||||
@@ -169,9 +170,7 @@ export const helpAssets = (): Plugin => {
|
||||
async load (id) {
|
||||
if (!(id.startsWith (`\0${ prefix }`)))
|
||||
return null
|
||||
const generated = await data ()
|
||||
generated.files.forEach (file => this.addWatchFile (file))
|
||||
const source = generated.modules.get (id.slice (1))
|
||||
const source = (await data ()).modules.get (id.slice (1))
|
||||
if (source == null)
|
||||
throw new Error (`Unknown Help asset: ${ id.slice (1) }`)
|
||||
return source
|
||||
|
||||
+19
-30
@@ -20,13 +20,13 @@ import { Toaster } from '@/components/ui/toaster'
|
||||
import { isApiError } from '@/lib/api'
|
||||
import { initialiseUserSession } from '@/lib/users'
|
||||
import { prepareHelpPage } from '@/lib/help'
|
||||
import { fetchLocales, isLocaleCode, isVerticalPreviewPath, legacyLocalePath,
|
||||
localiseTo, switchLocalePath, unlocalisedPath } from '@/lib/locales'
|
||||
import { fetchLocales, isLocaleCode, legacyLocalePath,
|
||||
switchLocalePath, unlocalisedPath } from '@/lib/locales'
|
||||
import { isAuthorityDependentQuery, localesKeys, sessionKeys } from '@/lib/queryKeys'
|
||||
import { isCountsPath } from '@/lib/routeLocales'
|
||||
import { switchPostFilterLocale } from '@/lib/posts'
|
||||
import { switchWikiLocale } from '@/lib/wiki'
|
||||
import { useLocale, useUILocale, useVerticalPreview } from '@/lib/useLocale'
|
||||
import { useLocale } from '@/lib/useLocale'
|
||||
import { applyClientAnimationMode,
|
||||
applyClientAppearance,
|
||||
fetchUserThemeSlots,
|
||||
@@ -46,7 +46,7 @@ import ServiceUnavailable from '@/pages/ServiceUnavailable'
|
||||
import type { ComponentType, Dispatch, FC, ReactNode, SetStateAction } from 'react'
|
||||
import type { RouteMatch } from 'react-router-dom'
|
||||
|
||||
import type { AvailableLocale, LocaleCode, UILocaleCode } from '@/lib/locales'
|
||||
import type { AvailableLocale, LocaleCode } from '@/lib/locales'
|
||||
import type { PageRoute } from '@/lib/routeLocales'
|
||||
import type { User } from '@/types'
|
||||
|
||||
@@ -267,21 +267,15 @@ const RoutedApp = ({ locales }: { locales: AvailableLocale[] }) => {
|
||||
const client = useQueryClient ()
|
||||
const location = useLocation ()
|
||||
const locale = useLocale ()
|
||||
const verticalPreview = useVerticalPreview ()
|
||||
const route = resolvePageRoute (location.pathname)
|
||||
const robots = isCountsPath (location.pathname) ? 'noindex' : route?.route.handle?.robots
|
||||
const pagePath = unlocalisedPath (location.pathname)
|
||||
const countsPage = pagePath === '/counts' || pagePath.startsWith ('/counts/')
|
||||
const switchLocale = async (target: UILocaleCode): Promise<string> => {
|
||||
const targetLocale = target === 'mn-Mong' ? 'ja' : target
|
||||
if (targetLocale === locale)
|
||||
return switchLocalePath (location, target)
|
||||
const switchLocale = async (targetLocale: LocaleCode): Promise<string> => {
|
||||
const resolve = route?.route.handle?.switchLocale
|
||||
const destination =
|
||||
(resolve != null && route != null)
|
||||
? await resolve ({ location, params: route.params, locale, targetLocale })
|
||||
return (resolve != null && route != null)
|
||||
? resolve ({ location, params: route.params, locale, targetLocale })
|
||||
: switchLocalePath (location, targetLocale)
|
||||
return target === 'mn-Mong' ? `/mn-Mong${unlocalisedPath (destination)}` : destination
|
||||
}
|
||||
const [user, setUserState] = useState<User | null> (
|
||||
() => client.getQueryData<User> (sessionKeys.current) ?? null)
|
||||
@@ -399,8 +393,7 @@ const RoutedApp = ({ locales }: { locales: AvailableLocale[] }) => {
|
||||
<motion.div
|
||||
layout={(animationMode === 'off' || countsPage) ? false : 'position'}
|
||||
transition={{ layout: appLayoutTransition }}
|
||||
data-vertical-preview={verticalPreview || undefined}
|
||||
className="app-layout relative flex h-dvh w-full flex-col overflow-y-hidden">
|
||||
className="relative flex h-dvh w-full flex-col overflow-y-hidden">
|
||||
<TopNav user={user} locales={locales} resolveLocaleSwitch={switchLocale}/>
|
||||
<RouteTransitionWrapper
|
||||
user={user}
|
||||
@@ -418,9 +411,7 @@ const RoutedApp = ({ locales }: { locales: AvailableLocale[] }) => {
|
||||
|
||||
const LocaleRoute: FC = () => {
|
||||
const { locale } = useParams ()
|
||||
const uiLocale = useUILocale ()
|
||||
const location = useLocation ()
|
||||
const verticalPreview = isVerticalPreviewPath (location.pathname)
|
||||
const { i18n } = useTranslation ()
|
||||
const { data, isError } = useQuery ({
|
||||
queryKey: localesKeys.index,
|
||||
@@ -430,30 +421,29 @@ const LocaleRoute: FC = () => {
|
||||
refetchOnMount: true,
|
||||
refetchOnWindowFocus: true,
|
||||
refetchOnReconnect: true })
|
||||
const contentLocale = verticalPreview ? 'ja' : locale
|
||||
const activeLocale =
|
||||
(isLocaleCode (contentLocale)
|
||||
&& data?.locales.some (entry => entry.code === contentLocale))
|
||||
? contentLocale
|
||||
(isLocaleCode (locale)
|
||||
&& data?.locales.some (entry => entry.code === locale))
|
||||
? locale
|
||||
: null
|
||||
|
||||
useLayoutEffect (() => {
|
||||
if (activeLocale != null)
|
||||
document.documentElement.lang = uiLocale
|
||||
if (activeLocale != null && i18n.language !== uiLocale)
|
||||
void i18n.changeLanguage (uiLocale)
|
||||
}, [activeLocale, uiLocale, i18n])
|
||||
document.documentElement.lang = activeLocale
|
||||
if (activeLocale != null && i18n.language !== activeLocale)
|
||||
void i18n.changeLanguage (activeLocale)
|
||||
}, [activeLocale, i18n])
|
||||
|
||||
const redirect = legacyLocalePath (location, pathname => resolvePageRoute (pathname) != null)
|
||||
if (!(isLocaleCode (locale)) && !verticalPreview && redirect == null)
|
||||
if (!(isLocaleCode (locale)) && redirect == null)
|
||||
return <NotFound/>
|
||||
if (isError && data == null)
|
||||
return <ServiceUnavailable/>
|
||||
if (data == null)
|
||||
return null
|
||||
if (isLocaleCode (locale) || verticalPreview)
|
||||
if (isLocaleCode (locale))
|
||||
{
|
||||
return data.locales.some (entry => entry.code === contentLocale)
|
||||
return data.locales.some (entry => entry.code === locale)
|
||||
? <RoutedApp locales={data.locales}/>
|
||||
: <NotFound/>
|
||||
}
|
||||
@@ -465,8 +455,7 @@ const LocaleRoute: FC = () => {
|
||||
const LocaleRedirect = ({ to }: { to: string }) => {
|
||||
const locale = useLocale ()
|
||||
const location = useLocation ()
|
||||
return <Navigate to={localiseTo (
|
||||
{ ...location, pathname: to }, locale, location.pathname)} replace/>
|
||||
return <Navigate to={switchLocalePath ({ ...location, pathname: to }, locale)} replace/>
|
||||
}
|
||||
|
||||
|
||||
|
||||
@@ -34,7 +34,7 @@ const PostList: FC<Props> = ({ posts, onClick }) => {
|
||||
const cardRef = useRef<HTMLDivElement> (null)
|
||||
|
||||
return (
|
||||
<div className="post-list flex flex-wrap gap-6 p-4">
|
||||
<div className="flex flex-wrap gap-6 p-4">
|
||||
{posts.map ((post, i) => {
|
||||
const sharedId = `page-${ post.id }`
|
||||
const layoutId = sharedId
|
||||
|
||||
@@ -1,10 +1,9 @@
|
||||
import { useQueryClient } from '@tanstack/react-query'
|
||||
import { forwardRef, useMemo } from 'react'
|
||||
import { flushSync } from 'react-dom'
|
||||
import { createPath, useLocation } from 'react-router-dom'
|
||||
import { createPath } from 'react-router-dom'
|
||||
|
||||
import { isVerticalPreviewPath, localeFromPath,
|
||||
localiseTo, unlocalisedPath } from '@/lib/locales'
|
||||
import { localiseTo } from '@/lib/locales'
|
||||
import { useLocale, useLocaleNavigate } from '@/lib/useLocale'
|
||||
import { useOverlayStore } from '@/components/RouteBlockerOverlay'
|
||||
import { prefetchForURL } from '@/lib/prefetchers'
|
||||
@@ -39,18 +38,15 @@ export default forwardRef<HTMLAnchorElement, Props> (({
|
||||
|
||||
const navigate = useLocaleNavigate ()
|
||||
const locale = useLocale ()
|
||||
const { pathname } = useLocation ()
|
||||
const qc = useQueryClient ()
|
||||
const behaviourSettings = useClientBehaviourSettings ()
|
||||
const linkPreloadMode = behaviourSettings.linkPreload ?? 'intent'
|
||||
const path = useMemo (
|
||||
() => {
|
||||
const localised = localiseTo (to, locale, pathname)
|
||||
const destination = typeof localised === 'string' ? localised : createPath (localised)
|
||||
return (isVerticalPreviewPath (pathname) && localeFromPath (destination) === locale)
|
||||
? `/mn-Mong${ unlocalisedPath (destination) }` : destination
|
||||
const localised = localiseTo (to, locale)
|
||||
return typeof localised === 'string' ? localised : createPath (localised)
|
||||
},
|
||||
[to, locale, pathname],
|
||||
[to, locale],
|
||||
)
|
||||
const url = useMemo (() => {
|
||||
return (new URL (path, currentRenderContext ()?.origin ?? 'http://localhost')).toString ()
|
||||
|
||||
@@ -1,8 +1,6 @@
|
||||
import { useEffect, useRef, useState } from 'react'
|
||||
|
||||
import { useClientBehaviourSettings } from '@/lib/useClientBehaviourSettings'
|
||||
import { useVerticalPreview } from '@/lib/useLocale'
|
||||
import { cn } from '@/lib/utils'
|
||||
import { useEffect, useRef, useState } from 'react'
|
||||
|
||||
import type { FC } from 'react'
|
||||
|
||||
@@ -13,7 +11,7 @@ type Props = {
|
||||
title?: string }
|
||||
|
||||
const DESKTOP_MARQUEE_MEDIA =
|
||||
'(hover: hover) and (pointer: fine) and (prefers-reduced-motion: no-preference)'
|
||||
'(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
|
||||
@@ -23,7 +21,6 @@ const MIN_MARQUEE_OVERFLOW_PX = 1
|
||||
const ResponsiveMarqueeText: FC<Props> = (
|
||||
{ text, className, truncateOnMobile = false, title },
|
||||
) => {
|
||||
const verticalPreview = useVerticalPreview ()
|
||||
const behaviourSettings = useClientBehaviourSettings ()
|
||||
const animationMode = behaviourSettings.animation ?? 'normal'
|
||||
const outerRef = useRef<HTMLSpanElement | null> (null)
|
||||
@@ -72,8 +69,7 @@ const ResponsiveMarqueeText: FC<Props> = (
|
||||
if (typeof window === 'undefined' || typeof window.matchMedia !== 'function')
|
||||
return
|
||||
|
||||
const sizeMedia = verticalPreview ? '(min-height: 768px)' : '(min-width: 768px)'
|
||||
const media = window.matchMedia (`${ sizeMedia } and ${ DESKTOP_MARQUEE_MEDIA }`)
|
||||
const media = window.matchMedia (DESKTOP_MARQUEE_MEDIA)
|
||||
const update = () => {
|
||||
setDesktopMarqueeEnabled (media.matches)
|
||||
}
|
||||
@@ -84,7 +80,7 @@ const ResponsiveMarqueeText: FC<Props> = (
|
||||
return () => {
|
||||
media.removeEventListener ('change', update)
|
||||
}
|
||||
}, [verticalPreview])
|
||||
}, [])
|
||||
|
||||
useEffect (() => {
|
||||
const clearScheduled = () => {
|
||||
|
||||
@@ -79,9 +79,7 @@ const TagLink: FC<Props> = ({ tag,
|
||||
} as CSSProperties
|
||||
const spanClass = 'tag-link-colour'
|
||||
const linkClass = 'tag-link-colour tag-link-hover-colour'
|
||||
const textClass = cn (
|
||||
'group [min-inline-size:0] [max-inline-size:100%]',
|
||||
'overflow-hidden align-bottom')
|
||||
const textClass = 'group min-w-0 max-w-full overflow-hidden align-bottom'
|
||||
const markerWrapClass = 'shrink-0 self-start md:self-auto'
|
||||
const countClass = 'shrink-0 self-end md:self-auto'
|
||||
const matchedAlias = isFullTag (tag) ? tag.matchedAlias : null
|
||||
@@ -91,8 +89,7 @@ const TagLink: FC<Props> = ({ tag,
|
||||
return (
|
||||
<span
|
||||
className={cn (
|
||||
'inline-flex [min-inline-size:0] [max-inline-size:100%] flex-nowrap',
|
||||
'items-stretch align-baseline',
|
||||
'inline-flex min-w-0 max-w-full flex-nowrap items-stretch align-baseline',
|
||||
'gap-x-1 md:items-baseline')}>
|
||||
{(linkFlg && withWiki && isFullTag (tag) && tag.category !== 'nico') && (
|
||||
<span className={markerWrapClass}>
|
||||
@@ -156,9 +153,9 @@ const TagLink: FC<Props> = ({ tag,
|
||||
</span>)}
|
||||
{nestLevel > 0 && (
|
||||
<span
|
||||
className="ms-1 me-1 shrink-0"
|
||||
style={{ paddingInlineStart: `${ (nestLevel - 1) }rem` }}>
|
||||
<span className="tag-tree-arrow">↳</span>
|
||||
className="ml-1 mr-1 shrink-0"
|
||||
style={{ paddingLeft: `${ (nestLevel - 1) }rem` }}>
|
||||
↳
|
||||
</span>)}
|
||||
{matchedAlias != null && (
|
||||
<>
|
||||
|
||||
@@ -3,7 +3,7 @@
|
||||
import { useEffect, useRef, useState } from 'react'
|
||||
import { useLocation } from 'react-router-dom'
|
||||
|
||||
import { useLocale, useLocaleNavigate, useVerticalPreview } from '@/lib/useLocale'
|
||||
import { useLocale, useLocaleNavigate } from '@/lib/useLocale'
|
||||
import { useUITranslation } from '@/lib/useUITranslation'
|
||||
import { apiGet } from '@/lib/api'
|
||||
import { inputClass } from '@/lib/utils'
|
||||
@@ -18,7 +18,6 @@ import type { Tag } from '@/types'
|
||||
const TagSearch: FC = () => {
|
||||
const { message } = useUITranslation ('shared')
|
||||
const locale = useLocale ()
|
||||
const verticalPreview = useVerticalPreview ()
|
||||
const location = useLocation ()
|
||||
const navigate = useLocaleNavigate ()
|
||||
const compositionFlgRef = useRef (false)
|
||||
@@ -106,13 +105,13 @@ const TagSearch: FC = () => {
|
||||
|
||||
switch (ev.key)
|
||||
{
|
||||
case verticalPreview ? 'ArrowRight' : 'ArrowDown':
|
||||
case 'ArrowDown':
|
||||
ev.preventDefault ()
|
||||
setActiveIndex (i => Math.min (i + 1, suggestions.length - 1))
|
||||
setSuggestionsVsbl (true)
|
||||
break
|
||||
|
||||
case verticalPreview ? 'ArrowLeft' : 'ArrowUp':
|
||||
case 'ArrowUp':
|
||||
ev.preventDefault ()
|
||||
setActiveIndex (i => Math.max (i - 1, -1))
|
||||
setSuggestionsVsbl (true)
|
||||
|
||||
@@ -15,7 +15,7 @@ const TagSearchBox: FC<Props> = ({ suggestions, activeIndex, onSelect }) => {
|
||||
return
|
||||
|
||||
return (
|
||||
<ul className="tag-search-suggestions absolute left-0 right-0 z-50 w-full
|
||||
<ul className="absolute left-0 right-0 z-50 w-full
|
||||
bg-gray-100 dark:bg-gray-800 border dark:border-gray-600
|
||||
rounded shadow">
|
||||
{suggestions.map ((tag, i) => (
|
||||
|
||||
@@ -4,7 +4,7 @@ import { Globe } from 'lucide-react'
|
||||
import { Fragment, useEffect, useLayoutEffect, useRef, useState } from 'react'
|
||||
import { useLocation } from 'react-router-dom'
|
||||
|
||||
import { useLocale, useLocaleNavigate, useUILocale, useVerticalPreview } from '@/lib/useLocale'
|
||||
import { useLocale, useLocaleNavigate } from '@/lib/useLocale'
|
||||
import LocalisedText, { formatUIString } from '@/components/LocalisedText'
|
||||
import Separator from '@/components/MenuSeparator'
|
||||
import PrefetchLink from '@/components/PrefetchLink'
|
||||
@@ -12,9 +12,9 @@ import TopNavUser from '@/components/TopNavUser'
|
||||
import TranslatedText from '@/components/TranslatedText'
|
||||
import { toast } from '@/components/ui/use-toast'
|
||||
import { WikiIdBus } from '@/lib/eventBus/WikiIdBus'
|
||||
import { isUILocaleCode,
|
||||
import { isLocaleCode,
|
||||
localeFromPath,
|
||||
switchLocalePath,
|
||||
uiLocaleFromPath,
|
||||
unlocalisedPath } from '@/lib/locales'
|
||||
import { uiMessage, uiMessageLanguage } from '@/lib/messages'
|
||||
import { useUITranslation } from '@/lib/useUITranslation'
|
||||
@@ -28,13 +28,13 @@ import { fetchWikiPage } from '@/lib/wiki'
|
||||
|
||||
import type { FC, MouseEvent } from 'react'
|
||||
|
||||
import type { AvailableLocale, UILocaleCode } from '@/lib/locales'
|
||||
import type { AvailableLocale, LocaleCode } from '@/lib/locales'
|
||||
import type { Material, Menu, MenuVisibleItem, Tag, User } from '@/types'
|
||||
|
||||
type Props = {
|
||||
user: User | null
|
||||
locales: AvailableLocale[]
|
||||
resolveLocaleSwitch?: (locale: UILocaleCode) => Promise<string> }
|
||||
resolveLocaleSwitch?: (locale: LocaleCode) => Promise<string> }
|
||||
type NavDensity = 'auto' | 'comfortable' | 'compact'
|
||||
|
||||
|
||||
@@ -47,7 +47,7 @@ export const menuOutline = (
|
||||
pathName: string },
|
||||
): Menu => {
|
||||
const pathName = unlocalisedPath (fullPathname)
|
||||
const locale = uiLocaleFromPath (fullPathname)
|
||||
const locale = localeFromPath (fullPathname) ?? 'ja'
|
||||
|
||||
const message = (
|
||||
key: Parameters<typeof uiMessage>[1],
|
||||
@@ -137,10 +137,7 @@ export const menuOutline = (
|
||||
const TopNav: FC<Props> = ({ user, locales, resolveLocaleSwitch }) => {
|
||||
const { message, label } = useUITranslation ('shared')
|
||||
const locale = useLocale ()
|
||||
const uiLocale = useUILocale ()
|
||||
const verticalPreview = useVerticalPreview ()
|
||||
const uiLocales = locales.filter (entry => isUILocaleCode (entry.code))
|
||||
const localeName = uiLocales.find (entry => entry.code === uiLocale)?.name
|
||||
const localeName = locales.find (entry => entry.code === locale)?.name
|
||||
const navigate = useLocaleNavigate ()
|
||||
const location = useLocation ()
|
||||
const currentLocation = useRef (location)
|
||||
@@ -183,12 +180,11 @@ const TopNav: FC<Props> = ({ user, locales, resolveLocaleSwitch }) => {
|
||||
let node: HTMLElement | null = el
|
||||
while (node != null && node !== nav)
|
||||
{
|
||||
left += verticalPreview ? node.offsetTop : node.offsetLeft
|
||||
left += node.offsetLeft
|
||||
const parent: Element | null = node.offsetParent
|
||||
node = parent instanceof HTMLElement ? parent : null
|
||||
}
|
||||
const width = node === nav
|
||||
? (verticalPreview ? el.offsetHeight : el.offsetWidth) : 0
|
||||
const width = node === nav ? el.offsetWidth : 0
|
||||
const visible = width > 0
|
||||
setHL (current =>
|
||||
(current.left === left && current.width === width && current.visible === visible)
|
||||
@@ -206,7 +202,6 @@ const TopNav: FC<Props> = ({ user, locales, resolveLocaleSwitch }) => {
|
||||
const [moreVsbl, setMoreVsbl] = useState (false)
|
||||
const [openItemIdx, setOpenItemIdx] = useState (-1)
|
||||
const [submenuHeight, setSubmenuHeight] = useState (0)
|
||||
const [submenuWidth, setSubmenuWidth] = useState (0)
|
||||
const [wikiId, setWikiId] = useState<number | null> (WikiIdBus.get ())
|
||||
|
||||
const wikiIdStr = String (wikiId ?? '')
|
||||
@@ -260,22 +255,8 @@ const TopNav: FC<Props> = ({ user, locales, resolveLocaleSwitch }) => {
|
||||
animationsOff
|
||||
? undefined
|
||||
: (reducedAnimations
|
||||
? 'transition-[transform,width,height] duration-75 ease-linear'
|
||||
: 'transition-[transform,width,height] duration-200 ease-out')
|
||||
const submenuItemMotion = animationsOff ? { } : {
|
||||
initial: { x: verticalPreview ? -40 : 0,
|
||||
y: verticalPreview ? 0 : -40, opacity: 0 },
|
||||
animate: { x: 0, y: 0, opacity: 1 },
|
||||
exit: { x: verticalPreview ? -40 : 0,
|
||||
y: verticalPreview ? 0 : -40, opacity: 0 } }
|
||||
const submenuVariants = {
|
||||
enter: (direction: -1 | 1) => ({
|
||||
x: verticalPreview ? direction * 24 : 0,
|
||||
y: verticalPreview ? 0 : direction * 24, opacity: 0 }),
|
||||
centre: { x: 0, y: 0, opacity: 1 },
|
||||
exit: (direction: -1 | 1) => ({
|
||||
x: verticalPreview ? (-direction) * 24 : 0,
|
||||
y: verticalPreview ? 0 : (-direction) * 24, opacity: 0 }) }
|
||||
? 'transition-[transform,width] duration-75 ease-linear'
|
||||
: 'transition-[transform,width] duration-200 ease-out')
|
||||
|
||||
const prevActiveIdxRef = useRef<number> (activeIdx)
|
||||
|
||||
@@ -299,8 +280,7 @@ const TopNav: FC<Props> = ({ user, locales, resolveLocaleSwitch }) => {
|
||||
let active = true
|
||||
|
||||
const update = () => {
|
||||
const desktopMedia = verticalPreview ? '(min-height: 768px)' : '(min-width: 768px)'
|
||||
if (!(window.matchMedia (desktopMedia).matches))
|
||||
if (!(window.matchMedia ('(min-width: 768px)').matches))
|
||||
{
|
||||
setDesktop (false)
|
||||
setDensity ('auto')
|
||||
@@ -317,25 +297,16 @@ const TopNav: FC<Props> = ({ user, locales, resolveLocaleSwitch }) => {
|
||||
{
|
||||
layout.setAttribute ('data-density', candidate)
|
||||
const style = getComputedStyle (bar)
|
||||
const primarySize =
|
||||
verticalPreview
|
||||
? Math.max (primary.getBoundingClientRect ().height, primary.scrollHeight)
|
||||
: Math.max (primary.getBoundingClientRect ().width, primary.scrollWidth)
|
||||
const accountSize =
|
||||
const primaryWidth = Math.max (
|
||||
primary.getBoundingClientRect ().width, primary.scrollWidth)
|
||||
const accountWidth =
|
||||
account == null
|
||||
? 0
|
||||
: (verticalPreview
|
||||
? Math.max (account.getBoundingClientRect ().height, account.scrollHeight)
|
||||
: Math.max (account.getBoundingClientRect ().width, account.scrollWidth))
|
||||
const padding =
|
||||
verticalPreview
|
||||
? parseFloat (style.paddingTop) + parseFloat (style.paddingBottom)
|
||||
: parseFloat (style.paddingLeft) + parseFloat (style.paddingRight)
|
||||
const gap = verticalPreview ? style.rowGap : style.columnGap
|
||||
const required = primarySize + accountSize + padding
|
||||
+ (account == null ? 0 : parseFloat (gap))
|
||||
const available = verticalPreview ? bar.clientHeight : bar.clientWidth
|
||||
if (Math.ceil (required) <= available)
|
||||
: Math.max (account.getBoundingClientRect ().width, account.scrollWidth)
|
||||
const required = primaryWidth + accountWidth
|
||||
+ parseFloat (style.paddingLeft) + parseFloat (style.paddingRight)
|
||||
+ (account == null ? 0 : parseFloat (style.columnGap))
|
||||
if (Math.ceil (required) <= bar.clientWidth)
|
||||
return candidate
|
||||
}
|
||||
return null
|
||||
@@ -380,8 +351,7 @@ const TopNav: FC<Props> = ({ user, locales, resolveLocaleSwitch }) => {
|
||||
removeEventListener ('resize', schedule)
|
||||
document.fonts?.removeEventListener ('loadingdone', schedule)
|
||||
}
|
||||
}, [activeIdx, moreVsbl, desktop, density, user?.name, locale, locales,
|
||||
menuLabels, verticalPreview])
|
||||
}, [activeIdx, moreVsbl, desktop, density, user?.name, locale, locales, menuLabels])
|
||||
|
||||
useEffect (() => {
|
||||
if (desktop == null || layoutReady)
|
||||
@@ -408,8 +378,7 @@ const TopNav: FC<Props> = ({ user, locales, resolveLocaleSwitch }) => {
|
||||
measure (moreVsbl ? -1 : activeIdx)
|
||||
if (!(desktop))
|
||||
setMoreVsbl (false)
|
||||
}, [activeIdx, moreVsbl, desktop, density, locale, animationMode,
|
||||
menuLabels, verticalPreview])
|
||||
}, [activeIdx, moreVsbl, desktop, density, locale, animationMode, menuLabels])
|
||||
|
||||
useEffect (() => {
|
||||
const unsubscribe = WikiIdBus.subscribe (setWikiId)
|
||||
@@ -423,7 +392,6 @@ const TopNav: FC<Props> = ({ user, locales, resolveLocaleSwitch }) => {
|
||||
|
||||
const update = () => {
|
||||
setSubmenuHeight (Math.ceil (content.getBoundingClientRect ().height))
|
||||
setSubmenuWidth (Math.ceil (content.getBoundingClientRect ().width))
|
||||
}
|
||||
const observer =
|
||||
typeof ResizeObserver === 'undefined' ? null : new ResizeObserver (update)
|
||||
@@ -435,7 +403,7 @@ const TopNav: FC<Props> = ({ user, locales, resolveLocaleSwitch }) => {
|
||||
observer?.disconnect ()
|
||||
removeEventListener ('resize', update)
|
||||
}
|
||||
}, [activeIdx, moreVsbl, desktop, density, locale, verticalPreview])
|
||||
}, [activeIdx, moreVsbl, desktop, density, locale])
|
||||
|
||||
useEffect (() => {
|
||||
setMenuOpen (false)
|
||||
@@ -447,18 +415,17 @@ const TopNav: FC<Props> = ({ user, locales, resolveLocaleSwitch }) => {
|
||||
rounded px-1 focus-within:ring-2">
|
||||
<Globe aria-hidden="true" size={16}/>
|
||||
<span className="top-nav-locale-name whitespace-nowrap text-sm">
|
||||
<LocalisedText language={uiLocale}>{localeName}</LocalisedText>
|
||||
<LocalisedText language={locale}>{localeName}</LocalisedText>
|
||||
</span>
|
||||
<select
|
||||
aria-label={formatUIString (localeName ?? '', uiLocale)}
|
||||
lang={uiLocale}
|
||||
value={uiLocale}
|
||||
aria-label={formatUIString (localeName ?? '', locale)}
|
||||
value={locale}
|
||||
disabled={switchingLocale}
|
||||
className="absolute inset-0 h-full w-full cursor-pointer opacity-0"
|
||||
onChange={async event => {
|
||||
const nextLocale = event.target.value
|
||||
if (isUILocaleCode (nextLocale)
|
||||
&& uiLocales.some (entry => entry.code === nextLocale))
|
||||
if (isLocaleCode (nextLocale)
|
||||
&& locales.some (entry => entry.code === nextLocale))
|
||||
{
|
||||
const request = ++localeSwitchRequest.current
|
||||
setSwitchingLocale (true)
|
||||
@@ -483,8 +450,8 @@ const TopNav: FC<Props> = ({ user, locales, resolveLocaleSwitch }) => {
|
||||
}
|
||||
}
|
||||
}}>
|
||||
{uiLocales.map (entry => (
|
||||
<option key={entry.code} value={entry.code} lang={entry.code}>
|
||||
{locales.map (entry => isLocaleCode (entry.code) && (
|
||||
<option key={entry.code} value={entry.code}>
|
||||
{formatUIString (entry.name, entry.code)}
|
||||
</option>))}
|
||||
</select>
|
||||
@@ -494,7 +461,7 @@ const TopNav: FC<Props> = ({ user, locales, resolveLocaleSwitch }) => {
|
||||
<div ref={layoutRef} className="top-nav-layout w-full min-w-0 shrink-0"
|
||||
data-desktop={desktop ?? undefined} data-density={density}
|
||||
data-layout-ready={layoutReady}>
|
||||
<nav ref={barRef} lang={uiMessageLanguage (uiLocale, 'posts')}
|
||||
<nav ref={barRef} lang={uiMessageLanguage (locale, 'posts')}
|
||||
className="top-nav-root top-nav-bar flex justify-between items-center w-full">
|
||||
<div className="top-nav-primary flex shrink-0 items-center h-12">
|
||||
<PrefetchLink
|
||||
@@ -512,11 +479,8 @@ const TopNav: FC<Props> = ({ user, locales, resolveLocaleSwitch }) => {
|
||||
className={cn ('absolute inset-y-0 h-12',
|
||||
'top-nav-highlight',
|
||||
highlightTransitionClass)}
|
||||
style={{ width: verticalPreview ? '100%' : hl.width,
|
||||
height: verticalPreview ? hl.width : undefined,
|
||||
transform: verticalPreview
|
||||
? `translateY(${ hl.left }px)`
|
||||
: `translateX(${ hl.left }px)`,
|
||||
style={{ width: hl.width,
|
||||
transform: `translateX(${ hl.left }px)`,
|
||||
opacity: hl.visible ? 1 : 0 }}/>
|
||||
|
||||
{visibleMenu.map ((item, i) => (
|
||||
@@ -590,9 +554,7 @@ const TopNav: FC<Props> = ({ user, locales, resolveLocaleSwitch }) => {
|
||||
layout
|
||||
className="top-nav-desktop-submenu relative z-20 shrink-0
|
||||
overflow-hidden top-nav-submenu"
|
||||
animate={verticalPreview && desktop
|
||||
? { width: submenuWidth, height: '100%' }
|
||||
: { width: 'auto', height: desktop == null ? 'auto' : submenuHeight }}
|
||||
animate={{ height: desktop == null ? 'auto' : submenuHeight }}
|
||||
onMouseLeave={() => {
|
||||
if (moreVsbl)
|
||||
setMoreVsbl (false)
|
||||
@@ -604,8 +566,7 @@ const TopNav: FC<Props> = ({ user, locales, resolveLocaleSwitch }) => {
|
||||
onLayoutAnimationComplete={() => {
|
||||
measure (highlightTargetRef.current)
|
||||
}}>
|
||||
<div ref={submenuContentRef}
|
||||
className={cn ('top-nav-submenu-content', moreVsbl && 'top-nav-more-menu')}>
|
||||
<div ref={submenuContentRef} className={cn (moreVsbl && 'top-nav-more-menu')}>
|
||||
{moreVsbl
|
||||
? (
|
||||
moreMenu.map ((item, i) => (
|
||||
@@ -615,11 +576,9 @@ const TopNav: FC<Props> = ({ user, locales, resolveLocaleSwitch }) => {
|
||||
{...((item.visible ?? true)
|
||||
? { layoutId: `menu-${ menu.indexOf (item) }` }
|
||||
: (animationsOff ? { }
|
||||
: { initial: {
|
||||
x: 40, y: verticalPreview ? 0 : -40, opacity: 0 },
|
||||
: { initial: { x: 40, y: -40, opacity: 0 },
|
||||
animate: { x: 0, y: 0, opacity: 1 },
|
||||
exit: {
|
||||
x: 40, y: verticalPreview ? 0 : -40, opacity: 0 } }))}
|
||||
exit: { x: 40, y: -40, opacity: 0 } }))}
|
||||
onLayoutAnimationComplete={() => measure (highlightTargetRef.current)}
|
||||
className="z-10 min-w-0 px-3 py-2 font-bold">
|
||||
<h2>
|
||||
@@ -640,7 +599,10 @@ const TopNav: FC<Props> = ({ user, locales, resolveLocaleSwitch }) => {
|
||||
transition={topNavTransition}
|
||||
{...(visibleMenu[activeIdx] === item
|
||||
? { layoutId: `submenu-${ menu.indexOf (item) }-${ j }` }
|
||||
: submenuItemMotion)}>
|
||||
: (animationsOff ? { }
|
||||
: { initial: { y: -40, opacity: 0 },
|
||||
animate: { y: 0, opacity: 1 },
|
||||
exit: { y: -40, opacity: 0 } }))}>
|
||||
{subItem.component}
|
||||
</motion.div>)
|
||||
: (
|
||||
@@ -650,7 +612,10 @@ const TopNav: FC<Props> = ({ user, locales, resolveLocaleSwitch }) => {
|
||||
transition={topNavTransition}
|
||||
{...(visibleMenu[activeIdx] === item
|
||||
? { layoutId: `submenu-${ menu.indexOf (item) }-${ j }` }
|
||||
: submenuItemMotion)}>
|
||||
: (animationsOff ? { }
|
||||
: { initial: { y: -40, opacity: 0 },
|
||||
animate: { y: 0, opacity: 1 },
|
||||
exit: { y: -40, opacity: 0 } }))}>
|
||||
<PrefetchLink
|
||||
to={subItem.to}
|
||||
target={subItem.to.slice (0, 2) === '//' ? '_blank' : undefined}
|
||||
@@ -668,8 +633,7 @@ const TopNav: FC<Props> = ({ user, locales, resolveLocaleSwitch }) => {
|
||||
<div className="relative min-h-[40px]">
|
||||
{animationsOff
|
||||
? (
|
||||
<div className="top-nav-submenu-items flex min-h-[40px]
|
||||
flex-wrap items-center px-3">
|
||||
<div className="flex min-h-[40px] flex-wrap items-center px-3">
|
||||
{(visibleMenu[activeIdx]?.subMenu ?? [])
|
||||
.filter (item => item.visible ?? true)
|
||||
.map ((item, i) => (
|
||||
@@ -698,9 +662,10 @@ const TopNav: FC<Props> = ({ user, locales, resolveLocaleSwitch }) => {
|
||||
<motion.div
|
||||
key={activeIdx}
|
||||
custom={dir}
|
||||
variants={submenuVariants}
|
||||
className="top-nav-submenu-items relative flex min-h-[40px]
|
||||
flex-wrap items-center px-3"
|
||||
variants={{ enter: (d: -1 | 1) => ({ y: d * 24, opacity: 0 }),
|
||||
centre: { y: 0, opacity: 1 },
|
||||
exit: (d: -1 | 1) => ({ y: (-d) * 24, opacity: 0 }) }}
|
||||
className="relative flex min-h-[40px] flex-wrap items-center px-3"
|
||||
initial="enter"
|
||||
animate="centre"
|
||||
exit="exit"
|
||||
|
||||
@@ -8,7 +8,7 @@ type Props = {
|
||||
|
||||
|
||||
const Form: FC<Props> = ({ children, className }) => (
|
||||
<div className={cn ('form-layout mx-auto max-w-xl space-y-4 p-4', className)}>
|
||||
<div className={cn ('mx-auto max-w-xl space-y-4 p-4', className)}>
|
||||
{children}
|
||||
</div>)
|
||||
|
||||
|
||||
@@ -61,7 +61,7 @@ const Pagination: FC<Props> = ({ page, totalPages, siblingCount = 3 }) => {
|
||||
const pages = getPages (page, totalPages, siblingCount)
|
||||
|
||||
return (
|
||||
<nav className="pagination mt-4 flex justify-center"
|
||||
<nav className="mt-4 flex justify-center"
|
||||
lang={message ('pagination.label').language}
|
||||
aria-label={message ('pagination.label').text}>
|
||||
<div className="flex items-center gap-2">
|
||||
|
||||
@@ -12,7 +12,7 @@ export default forwardRef<HTMLTextAreaElement, Props> (
|
||||
<textarea
|
||||
ref={ref}
|
||||
aria-invalid={invalid}
|
||||
className={cn ('rounded border [inline-size:100%] p-2 [block-size:8rem]',
|
||||
className={cn ('rounded border w-full p-2 h-32',
|
||||
(invalid
|
||||
? ['border-red-500 bg-red-50 text-red-900',
|
||||
'focus:border-red-500 focus:outline-none focus:ring-2',
|
||||
|
||||
@@ -1,10 +1,7 @@
|
||||
import { motion } from 'framer-motion'
|
||||
import { useEffect, useRef } from 'react'
|
||||
import { useLocation } from 'react-router-dom'
|
||||
|
||||
import { clientAnimationTransition } from '@/lib/clientAnimation'
|
||||
import { useClientBehaviourSettings } from '@/lib/useClientBehaviourSettings'
|
||||
import { useVerticalPreview } from '@/lib/useLocale'
|
||||
import { cn } from '@/lib/utils'
|
||||
|
||||
import type { FC, ReactNode } from 'react'
|
||||
@@ -12,71 +9,21 @@ import type { FC, ReactNode } from 'react'
|
||||
type Props = {
|
||||
children: ReactNode
|
||||
className?: string
|
||||
animateLayout?: boolean
|
||||
verticalContent?: boolean }
|
||||
animateLayout?: boolean }
|
||||
|
||||
|
||||
const MainArea: FC<Props> = (
|
||||
{ children, className, animateLayout = true, verticalContent = true },
|
||||
) => {
|
||||
const MainArea: FC<Props> = ({ children, className, animateLayout = true }) => {
|
||||
const behaviourSettings = useClientBehaviourSettings ()
|
||||
const verticalPreview = useVerticalPreview ()
|
||||
const horizontal = verticalPreview && verticalContent
|
||||
const { pathname, search } = useLocation ()
|
||||
const rootRef = useRef<HTMLElement | null> (null)
|
||||
const animationMode = behaviourSettings.animation ?? 'normal'
|
||||
const layoutTransition = clientAnimationTransition (
|
||||
animationMode,
|
||||
{ normal: { duration: .2, ease: 'easeOut' as const } })
|
||||
|
||||
useEffect (() => {
|
||||
if (horizontal && rootRef.current != null)
|
||||
rootRef.current.scrollLeft = 0
|
||||
}, [horizontal, pathname, search])
|
||||
|
||||
useEffect (() => {
|
||||
const root = rootRef.current
|
||||
if (!horizontal || root == null)
|
||||
return
|
||||
|
||||
const handleWheel = (event: WheelEvent) => {
|
||||
if (event.ctrlKey || event.metaKey || event.shiftKey
|
||||
|| event.deltaX !== 0 || event.deltaY === 0 || event.defaultPrevented)
|
||||
return
|
||||
|
||||
// Nested tables, forms and code blocks retain their own scrolling.
|
||||
let node = event.target instanceof HTMLElement ? event.target : null
|
||||
while (node != null && node !== root)
|
||||
{
|
||||
if (node.matches ('input, select, textarea, [contenteditable="true"]'))
|
||||
return
|
||||
const style = getComputedStyle (node)
|
||||
if ((/auto|scroll/.test (style.overflowY) && node.scrollHeight > node.clientHeight)
|
||||
|| (/auto|scroll/.test (style.overflowX) && node.scrollWidth > node.clientWidth))
|
||||
return
|
||||
node = node.parentElement
|
||||
}
|
||||
|
||||
const unit = event.deltaMode === 1 ? 16 : (event.deltaMode === 2 ? root.clientWidth : 1)
|
||||
const delta = event.deltaY * unit
|
||||
if ((delta < 0 && root.scrollLeft <= 0)
|
||||
|| (delta > 0 && root.scrollLeft + root.clientWidth >= root.scrollWidth))
|
||||
return
|
||||
event.preventDefault ()
|
||||
root.scrollLeft += delta
|
||||
}
|
||||
|
||||
root.addEventListener ('wheel', handleWheel, { passive: false })
|
||||
return () => root.removeEventListener ('wheel', handleWheel)
|
||||
}, [horizontal])
|
||||
{ normal: { duration: .2, ease: 'easeOut' as const } },
|
||||
)
|
||||
|
||||
return (
|
||||
<motion.main
|
||||
ref={rootRef}
|
||||
data-vertical-content={horizontal || undefined}
|
||||
tabIndex={horizontal ? 0 : undefined}
|
||||
transition={{ layout: layoutTransition }}
|
||||
className={cn ('main-area flex-1 overflow-y-auto p-4', className)}
|
||||
className={cn ('flex-1 overflow-y-auto p-4', className)}
|
||||
layout={(animationMode === 'off' || !animateLayout) ? false : 'position'}>
|
||||
{children}
|
||||
</motion.main>)
|
||||
|
||||
@@ -1,14 +1,13 @@
|
||||
import { motion } from 'framer-motion'
|
||||
import { useCallback, useEffect, useRef, useState } from 'react'
|
||||
import { Helmet } from 'react-helmet-async'
|
||||
|
||||
import { clientAnimationTransition } from '@/lib/clientAnimation'
|
||||
import { useClientBehaviourSettings } from '@/lib/useClientBehaviourSettings'
|
||||
import { cn } from '@/lib/utils'
|
||||
import { useUITranslation } from '@/lib/useUITranslation'
|
||||
import { useVerticalPreview } from '@/lib/useLocale'
|
||||
|
||||
import type { CSSProperties, FC, MouseEvent, PointerEvent, ReactNode } from 'react'
|
||||
import { useCallback, useEffect, useRef, useState } from 'react'
|
||||
|
||||
type SidebarSide = 'left' | 'right'
|
||||
|
||||
@@ -24,12 +23,12 @@ type Props = {
|
||||
|
||||
type ResizeState = {
|
||||
pointerId: number
|
||||
startSize: number
|
||||
startWidth: number
|
||||
startX: number
|
||||
startY: number
|
||||
verticalPreview: boolean
|
||||
side: SidebarSide }
|
||||
|
||||
type PendingPressState = ResizeState & { startY: number }
|
||||
|
||||
const DEFAULT_SIDEBAR_WIDTH = 256
|
||||
const MIN_SIDEBAR_WIDTH = 192
|
||||
const MIN_MAIN_WIDTH = 360
|
||||
@@ -38,97 +37,84 @@ const LONG_PRESS_DELAY_MS = 350
|
||||
const TOUCH_MOVE_THRESHOLD_PX = 8
|
||||
|
||||
|
||||
const storageKeyForSidebar = (
|
||||
sidebarKey: string,
|
||||
side: SidebarSide,
|
||||
verticalPreview = false,
|
||||
): string =>
|
||||
`sidebar:${ sidebarKey }:${ side }:${ verticalPreview ? 'height' : 'width' }`
|
||||
const storageKeyForSidebar = (sidebarKey: string, side: SidebarSide): string =>
|
||||
`sidebar:${ sidebarKey }:${ side }:width`
|
||||
|
||||
|
||||
const getSidebarMaxWidth = (containerSize: number): number => {
|
||||
const getSidebarMaxWidth = (containerWidth: number): number => {
|
||||
const viewportWidth =
|
||||
typeof window === 'undefined' ? containerSize : window.innerWidth
|
||||
typeof window === 'undefined' ? containerWidth : window.innerWidth
|
||||
const viewportMaxWidth = Math.floor (viewportWidth * MAX_VIEWPORT_WIDTH_RATIO)
|
||||
const containerMaxWidth = Math.floor (containerSize - MIN_MAIN_WIDTH)
|
||||
const containerMaxWidth = Math.floor (containerWidth - MIN_MAIN_WIDTH)
|
||||
const dynamicMaxWidth = Math.min (viewportMaxWidth, containerMaxWidth)
|
||||
|
||||
return Math.max (MIN_SIDEBAR_WIDTH, dynamicMaxWidth)
|
||||
}
|
||||
|
||||
|
||||
const readStoredSidebarSize = (
|
||||
const readStoredSidebarWidth = (
|
||||
sidebarKey: string,
|
||||
side: SidebarSide,
|
||||
verticalPreview: boolean,
|
||||
): number => {
|
||||
side: SidebarSide): number => {
|
||||
if (typeof window === 'undefined')
|
||||
return DEFAULT_SIDEBAR_WIDTH
|
||||
|
||||
try
|
||||
{
|
||||
const value = window.localStorage.getItem (
|
||||
storageKeyForSidebar (sidebarKey, side, verticalPreview))
|
||||
const size = value == null ? Number.NaN : Number (value)
|
||||
return Number.isFinite (size) ? size : DEFAULT_SIDEBAR_WIDTH
|
||||
}
|
||||
catch
|
||||
{
|
||||
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, maxWidthRatio, animateLayout = true,
|
||||
onWidthChange, sidebarKey, side = 'left' },
|
||||
) => {
|
||||
const SidebarComponent: FC<Props> = ({
|
||||
children,
|
||||
className,
|
||||
maxWidth,
|
||||
maxWidthRatio,
|
||||
animateLayout = true,
|
||||
onWidthChange,
|
||||
sidebarKey,
|
||||
side = 'left',
|
||||
}) => {
|
||||
const { message } = useUITranslation ('shared')
|
||||
const behaviourSettings = useClientBehaviourSettings ()
|
||||
const verticalPreview = useVerticalPreview ()
|
||||
const animationMode = behaviourSettings.animation ?? 'normal'
|
||||
const layoutTransition = clientAnimationTransition (
|
||||
animationMode,
|
||||
{ normal: { duration: .2, ease: 'easeOut' as const } })
|
||||
{ normal: { duration: .2, ease: 'easeOut' as const } },
|
||||
)
|
||||
const rootRef = useRef<HTMLDivElement | null> (null)
|
||||
const maxWidthRef = useRef (maxWidth)
|
||||
const maxWidthRatioRef = useRef (maxWidthRatio)
|
||||
const getContainerSize = useCallback (() => {
|
||||
const container = rootRef.current?.closest ('[data-sidebar-container]')
|
||||
return verticalPreview
|
||||
? container?.clientHeight ?? window.innerHeight
|
||||
: container?.clientWidth ?? window.innerWidth
|
||||
}, [verticalPreview])
|
||||
const getClampedSize = useCallback ((
|
||||
nextSize: number,
|
||||
containerSize: number,
|
||||
): number => {
|
||||
if (verticalPreview)
|
||||
{
|
||||
const maximum = Math.max (64, Math.min (
|
||||
window.innerHeight * .6, containerSize - 160))
|
||||
return Math.min (maximum, Math.max (64, nextSize))
|
||||
}
|
||||
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' ? containerSize : window.innerWidth
|
||||
typeof window === 'undefined' ? containerWidth : window.innerWidth
|
||||
const viewportMaxWidth = Math.floor (viewportWidth * MAX_VIEWPORT_WIDTH_RATIO)
|
||||
const ratioMaxWidth = maxWidthRatioRef.current == null
|
||||
? Infinity : Math.floor (containerSize * maxWidthRatioRef.current)
|
||||
? Infinity : Math.floor (containerWidth * maxWidthRatioRef.current)
|
||||
const configuredMaxWidth = maxWidthRef.current == null
|
||||
? getSidebarMaxWidth (containerSize)
|
||||
? getSidebarMaxWidth (containerWidth)
|
||||
: Math.max (MIN_SIDEBAR_WIDTH,
|
||||
Math.min (viewportMaxWidth, maxWidthRef.current))
|
||||
const maxAllowedWidth = Math.max (MIN_SIDEBAR_WIDTH,
|
||||
Math.min (ratioMaxWidth, configuredMaxWidth))
|
||||
|
||||
return Math.min (maxAllowedWidth, Math.max (MIN_SIDEBAR_WIDTH, nextSize))
|
||||
}, [verticalPreview])
|
||||
return Math.min (maxAllowedWidth, Math.max (MIN_SIDEBAR_WIDTH, nextWidth))
|
||||
}, [])
|
||||
|
||||
const [size, setSize] = useState (DEFAULT_SIDEBAR_WIDTH)
|
||||
const [width, setWidth] = useState (DEFAULT_SIDEBAR_WIDTH)
|
||||
const [resizing, setResizing] = useState (false)
|
||||
const sizeRef = useRef (size)
|
||||
const widthRef = useRef (width)
|
||||
const longPressTimerRef = useRef<ReturnType<typeof setTimeout> | null> (null)
|
||||
const pendingPressRef = useRef<ResizeState | null> (null)
|
||||
const pendingPressRef = useRef<PendingPressState | null> (null)
|
||||
const resizeRef = useRef<ResizeState | null> (null)
|
||||
const bodyStyleRef = useRef<{ cursor: string, userSelect: string } | null> (null)
|
||||
|
||||
@@ -162,7 +148,7 @@ const SidebarComponent: FC<Props> = (
|
||||
userSelect: document.body.style.userSelect }
|
||||
}
|
||||
|
||||
document.body.style.cursor = state.verticalPreview ? 'row-resize' : 'col-resize'
|
||||
document.body.style.cursor = 'col-resize'
|
||||
document.body.style.userSelect = 'none'
|
||||
}, [clearLongPressTimer])
|
||||
|
||||
@@ -173,50 +159,43 @@ const SidebarComponent: FC<Props> = (
|
||||
const state = resizeRef.current
|
||||
resizeRef.current = null
|
||||
|
||||
try
|
||||
{
|
||||
if (state != null)
|
||||
window.localStorage.setItem (
|
||||
storageKeyForSidebar (sidebarKey, state.side, state.verticalPreview),
|
||||
String (sizeRef.current))
|
||||
}
|
||||
catch
|
||||
{
|
||||
// Resizing remains usable when browser storage is unavailable.
|
||||
}
|
||||
if (state != null)
|
||||
window.localStorage.setItem (
|
||||
storageKeyForSidebar (sidebarKey, state.side),
|
||||
String (widthRef.current))
|
||||
|
||||
setResizing (false)
|
||||
restoreBodyStyle ()
|
||||
}, [clearLongPressTimer, restoreBodyStyle, sidebarKey])
|
||||
|
||||
const applySize = useCallback ((nextSize: number) => {
|
||||
if (nextSize === sizeRef.current)
|
||||
const applyWidth = useCallback ((nextWidth: number) => {
|
||||
if (nextWidth === widthRef.current)
|
||||
return
|
||||
|
||||
sizeRef.current = nextSize
|
||||
setSize (nextSize)
|
||||
widthRef.current = nextWidth
|
||||
setWidth (nextWidth)
|
||||
}, [])
|
||||
|
||||
useEffect (() => {
|
||||
maxWidthRef.current = maxWidth
|
||||
maxWidthRatioRef.current = maxWidthRatio
|
||||
const containerSize = getContainerSize ()
|
||||
const nextSize = getClampedSize (sizeRef.current, containerSize)
|
||||
applySize (nextSize)
|
||||
}, [applySize, getClampedSize, getContainerSize, maxWidth, maxWidthRatio])
|
||||
const containerWidth = getContainerWidth ()
|
||||
const nextWidth = getClampedWidth (widthRef.current, containerWidth)
|
||||
applyWidth (nextWidth)
|
||||
}, [applyWidth, getClampedWidth, getContainerWidth, maxWidth, maxWidthRatio])
|
||||
|
||||
const updateSize = useCallback ((clientX: number, clientY: number) => {
|
||||
const updateWidth = useCallback ((clientX: number) => {
|
||||
const state = resizeRef.current
|
||||
if (state == null)
|
||||
return
|
||||
|
||||
const containerSize = getContainerSize ()
|
||||
const delta = state.verticalPreview
|
||||
? clientY - state.startY
|
||||
: (state.side === 'left' ? clientX - state.startX : state.startX - clientX)
|
||||
const nextSize = getClampedSize (state.startSize + delta, containerSize)
|
||||
applySize (nextSize)
|
||||
}, [applySize, getClampedSize, getContainerSize])
|
||||
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')
|
||||
@@ -232,10 +211,8 @@ const SidebarComponent: FC<Props> = (
|
||||
const state = {
|
||||
pointerId: ev.pointerId,
|
||||
side,
|
||||
startSize: sizeRef.current,
|
||||
startX: ev.clientX,
|
||||
startY: ev.clientY,
|
||||
verticalPreview }
|
||||
startWidth: widthRef.current,
|
||||
startX: ev.clientX }
|
||||
|
||||
if (ev.pointerType === 'mouse')
|
||||
{
|
||||
@@ -243,7 +220,7 @@ const SidebarComponent: FC<Props> = (
|
||||
return
|
||||
}
|
||||
|
||||
pendingPressRef.current = state
|
||||
pendingPressRef.current = { ...state, startY: ev.clientY }
|
||||
clearLongPressTimer ()
|
||||
longPressTimerRef.current = setTimeout (() => {
|
||||
if (pendingPressRef.current != null)
|
||||
@@ -257,7 +234,7 @@ const SidebarComponent: FC<Props> = (
|
||||
if (resizeRef.current != null)
|
||||
{
|
||||
ev.preventDefault ()
|
||||
updateSize (ev.clientX, ev.clientY)
|
||||
updateWidth (ev.clientX)
|
||||
return
|
||||
}
|
||||
|
||||
@@ -285,58 +262,58 @@ const SidebarComponent: FC<Props> = (
|
||||
finishResize ()
|
||||
}
|
||||
|
||||
const resetSize = useCallback (() => {
|
||||
const containerSize = getContainerSize ()
|
||||
const nextSize = getClampedSize (DEFAULT_SIDEBAR_WIDTH, containerSize)
|
||||
applySize (nextSize)
|
||||
window.localStorage.removeItem (
|
||||
storageKeyForSidebar (sidebarKey, side, verticalPreview))
|
||||
}, [applySize, getClampedSize, getContainerSize, sidebarKey, side, verticalPreview])
|
||||
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 ()
|
||||
resetSize ()
|
||||
resetWidth ()
|
||||
}
|
||||
|
||||
useEffect (() => {
|
||||
const containerSize = getContainerSize ()
|
||||
const nextSize = getClampedSize (
|
||||
readStoredSidebarSize (sidebarKey, side, verticalPreview),
|
||||
containerSize)
|
||||
applySize (nextSize)
|
||||
}, [applySize, getClampedSize, getContainerSize, sidebarKey, side, verticalPreview])
|
||||
const containerWidth = getContainerWidth ()
|
||||
const nextWidth = getClampedWidth (
|
||||
readStoredSidebarWidth (sidebarKey, side),
|
||||
containerWidth)
|
||||
applyWidth (nextWidth)
|
||||
}, [applyWidth, getClampedWidth, getContainerWidth, sidebarKey, side])
|
||||
|
||||
useEffect (() => {
|
||||
const containerSize = getContainerSize ()
|
||||
const nextSize = getClampedSize (sizeRef.current, containerSize)
|
||||
applySize (nextSize)
|
||||
}, [applySize, getClampedSize, getContainerSize])
|
||||
const containerWidth = getContainerWidth ()
|
||||
const nextWidth = getClampedWidth (widthRef.current, containerWidth)
|
||||
applyWidth (nextWidth)
|
||||
}, [applyWidth, getClampedWidth, getContainerWidth])
|
||||
|
||||
useEffect (() => {
|
||||
if (typeof window === 'undefined')
|
||||
return
|
||||
|
||||
const handleResize = () => {
|
||||
const containerSize = getContainerSize ()
|
||||
const nextSize = getClampedSize (sizeRef.current, containerSize)
|
||||
applySize (nextSize)
|
||||
const containerWidth = getContainerWidth ()
|
||||
const nextWidth = getClampedWidth (widthRef.current, containerWidth)
|
||||
applyWidth (nextWidth)
|
||||
}
|
||||
|
||||
window.addEventListener ('resize', handleResize)
|
||||
return () => window.removeEventListener ('resize', handleResize)
|
||||
}, [applySize, getClampedSize, getContainerSize])
|
||||
}, [applyWidth, getClampedWidth, getContainerWidth])
|
||||
|
||||
useEffect (() => {
|
||||
if (!verticalPreview)
|
||||
onWidthChange?.(size)
|
||||
}, [onWidthChange, size, verticalPreview])
|
||||
onWidthChange?.(width)
|
||||
}, [onWidthChange, width])
|
||||
|
||||
useEffect (() => () => finishResize (), [finishResize, verticalPreview])
|
||||
useEffect (() => () => {
|
||||
clearLongPressTimer ()
|
||||
restoreBodyStyle ()
|
||||
}, [clearLongPressTimer, restoreBodyStyle])
|
||||
|
||||
const style = {
|
||||
'--sidebar-width': `${ size }px`,
|
||||
'--sidebar-height': `${ size }px` } as CSSProperties
|
||||
'--sidebar-width': `${ width }px` } as CSSProperties
|
||||
|
||||
return (
|
||||
<motion.div
|
||||
@@ -345,7 +322,7 @@ const SidebarComponent: FC<Props> = (
|
||||
transition={{ layout: layoutTransition }}
|
||||
style={style}
|
||||
className={cn (
|
||||
'sidebar-panel relative w-full md:w-[var(--sidebar-width)] md:shrink-0 md:h-full',
|
||||
'relative w-full md:w-[var(--sidebar-width)] md:shrink-0 md:h-full',
|
||||
className)}>
|
||||
<Helmet>
|
||||
<style>
|
||||
@@ -368,16 +345,16 @@ const SidebarComponent: FC<Props> = (
|
||||
|
||||
<div
|
||||
role="separator"
|
||||
aria-orientation={verticalPreview ? 'horizontal' : 'vertical'}
|
||||
aria-label={message (verticalPreview ? 'labels.menu' : 'sidebarWidth').text}
|
||||
lang={message (verticalPreview ? 'labels.menu' : 'sidebarWidth').language}
|
||||
aria-orientation="vertical"
|
||||
aria-label={message ('sidebarWidth').text}
|
||||
lang={message ('sidebarWidth').language}
|
||||
onPointerDown={handlePointerDown}
|
||||
onPointerMove={handlePointerMove}
|
||||
onPointerUp={handlePointerEnd}
|
||||
onPointerCancel={handlePointerEnd}
|
||||
onDoubleClick={handleDoubleClick}
|
||||
className={cn (
|
||||
'sidebar-resize hidden md:block absolute top-0 bottom-0 z-20 w-4 cursor-col-resize',
|
||||
'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',
|
||||
|
||||
@@ -32,10 +32,10 @@ const buttonVariants = cva (
|
||||
link:
|
||||
'text-blue-700 underline-offset-4 hover:underline dark:text-blue-300'},
|
||||
size: {
|
||||
default: '[block-size:2.5rem] [padding-inline:1rem] [padding-block:.5rem]',
|
||||
sm: '[block-size:2.25rem] rounded-md [padding-inline:.75rem]',
|
||||
lg: '[block-size:2.75rem] rounded-md [padding-inline:2rem]',
|
||||
icon: '[block-size:2.5rem] [inline-size:2.5rem]'}},
|
||||
default: 'h-10 px-4 py-2',
|
||||
sm: 'h-9 rounded-md px-3',
|
||||
lg: 'h-11 rounded-md px-8',
|
||||
icon: 'h-10 w-10'}},
|
||||
defaultVariants: {
|
||||
variant: 'default',
|
||||
size: 'default'}})
|
||||
|
||||
@@ -60,14 +60,12 @@ const InheritDialogue: FC<Props> = ({ visible, onVisibleChange, setUser }) => {
|
||||
|
||||
return (
|
||||
<Dialog open={visible} onOpenChange={onVisibleChange}>
|
||||
<DialogContent className="inheritance-dialogue px-6 pb-6 pt-7"
|
||||
closeLabel={label ('actions.close')}>
|
||||
<DialogContent className="px-6 pp-6 pt-7" closeLabel={label ('actions.close')}>
|
||||
<DialogHeader className="pl-8">
|
||||
<DialogTitle>{label ('account.inherit')}</DialogTitle>
|
||||
<DialogDescription asChild>
|
||||
<div className="inheritance-dialogue-fields flex gap-2">
|
||||
<Input className="inheritance-code"
|
||||
placeholder={message ('transfer.placeholder').text}
|
||||
<div className="flex gap-2">
|
||||
<Input placeholder={message ('transfer.placeholder').text}
|
||||
aria-label={message ('transfer.placeholder').text}
|
||||
lang={message ('transfer.placeholder').language}
|
||||
value={inputCode}
|
||||
|
||||
@@ -60,7 +60,7 @@ const UserCodeDialogue: FC<Props> = ({ visible, onVisibleChange, user, setUser }
|
||||
<DialogDescription asChild>
|
||||
<div>
|
||||
<p>{label ('userCode.description')}</p>
|
||||
<div className="inheritance-code m-2">{user?.inheritanceCode}</div>
|
||||
<div className="m-2">{user?.inheritanceCode}</div>
|
||||
<p className="mt-1 text-sm text-destructive">
|
||||
{label ('userCode.secretWarning')}
|
||||
</p>
|
||||
|
||||
@@ -1,9 +0,0 @@
|
||||
import { describe, expect, it } from 'vitest'
|
||||
|
||||
import { API_BASE_URL } from '@/config'
|
||||
|
||||
describe ('test API configuration', () => {
|
||||
it ('resolves the sample configuration without a local config file', () => {
|
||||
expect (API_BASE_URL).toBe ('/api')
|
||||
})
|
||||
})
|
||||
@@ -9,8 +9,7 @@ import { createStaticHandler, createStaticRouter,
|
||||
import { AppFrame, appRoutes, resolvePageRoute } from '@/App'
|
||||
import { apiGet, isApiError } from '@/lib/api'
|
||||
import { createUII18n } from '@/lib/i18n'
|
||||
import { fetchLocales, isLocaleCode, isVerticalPreviewPath,
|
||||
legacyLocalePath, uiLocaleFromPath } from '@/lib/locales'
|
||||
import { fetchLocales, isLocaleCode, legacyLocalePath } from '@/lib/locales'
|
||||
import { localesKeys, sessionKeys } from '@/lib/queryKeys'
|
||||
import { withRenderContext } from '@/lib/renderContext.server'
|
||||
|
||||
@@ -73,16 +72,13 @@ export const render = async (
|
||||
pathname => resolvePageRoute (pathname) != null)
|
||||
const pathname = legacy == null ? url.pathname : new URL (legacy, origin).pathname
|
||||
const segment = pathname.split ('/')[1]
|
||||
const verticalPreview = isVerticalPreviewPath (pathname)
|
||||
const known = resolvePageRoute (pathname)
|
||||
if (legacy != null && known != null)
|
||||
return { status: 308, location: legacy }
|
||||
const locale = isLocaleCode (segment) ? segment : 'ja'
|
||||
const uiLocale = uiLocaleFromPath (pathname)
|
||||
const routePrefix = verticalPreview ? 'mn-Mong' : locale
|
||||
if (known?.route.handle?.redirectTo != null)
|
||||
return { status: 308,
|
||||
location: `/${routePrefix}${known.route.handle.redirectTo}${url.search}` }
|
||||
location: `/${locale}${known.route.handle.redirectTo}${url.search}` }
|
||||
const requestContext: RenderContext & { status: number } = {
|
||||
pathname: url.pathname, origin, apiBaseURL,
|
||||
...authentication, status: 200 }
|
||||
@@ -110,15 +106,14 @@ export const render = async (
|
||||
}
|
||||
}
|
||||
const prepare = known?.route.handle?.prepare
|
||||
const routeLocaleValid = isLocaleCode (segment) || verticalPreview
|
||||
let status = known == null || !active || !routeLocaleValid ? 404 : 200
|
||||
let status = known == null || !active || !isLocaleCode (segment) ? 404 : 200
|
||||
if (status === 200 && known?.route.handle?.authentication != null
|
||||
&& client.getQueryData (sessionKeys.current) == null)
|
||||
status = 401
|
||||
if (prepare != null && known != null && status === 200)
|
||||
status = await prepare ({ client, params: known.params, locale,
|
||||
searchParams: url.searchParams })
|
||||
const instance = createUII18n (uiLocale)
|
||||
const instance = createUII18n (locale)
|
||||
const handler = createStaticHandler (appRoutes)
|
||||
const context = await handler.query (new Request (url))
|
||||
if (context instanceof Response)
|
||||
@@ -188,11 +183,11 @@ export const render = async (
|
||||
isAxiosError: true, response: {
|
||||
status: isApiError (query.state.error) ? query.state.error.response?.status : 500 } } }
|
||||
})) }
|
||||
const bootstrap = JSON.stringify ({ state, status, locale: uiLocale,
|
||||
const bootstrap = JSON.stringify ({ state, status, locale,
|
||||
url: url.pathname + url.search })
|
||||
.replace (/</g, '\\u003c').replace (/\u2028/g, '\\u2028')
|
||||
.replace (/\u2029/g, '\\u2029')
|
||||
return { status, html, head, locale: uiLocale, bootstrap,
|
||||
return { status, html, head, locale, bootstrap,
|
||||
setCookies: requestContext.setCookies }
|
||||
}
|
||||
finally
|
||||
|
||||
@@ -625,843 +625,3 @@ body
|
||||
white-space: nowrap;
|
||||
will-change: transform;
|
||||
}
|
||||
|
||||
/* Locally hosted Mongolian font; the OFL accompanies the font file. */
|
||||
@font-face
|
||||
{
|
||||
font-family: 'BTRC Mongolian';
|
||||
src: url('/fonts/noto-sans-mongolian/NotoSansMongolian-Regular.ttf') format('truetype');
|
||||
font-weight: 400;
|
||||
font-style: normal;
|
||||
font-display: swap;
|
||||
}
|
||||
|
||||
/* Mongolian flows down each line, then into the next column on the right. */
|
||||
:lang(mn-Mong)
|
||||
{
|
||||
font-family: 'BTRC Mongolian', 'Mongolian Baiti', 'Noto Sans JP Variable', sans-serif;
|
||||
}
|
||||
|
||||
/* Include portalled dialogues and toasts, and controls with UA writing modes. */
|
||||
html:lang(mn-Mong) body > :not(#root),
|
||||
html:lang(mn-Mong) #root > :not(.app-layout),
|
||||
html:lang(mn-Mong) :is(button, input, select, textarea),
|
||||
[data-vertical-preview] :is(
|
||||
.main-area:not(.posts-main-area, .tags-main-area, .wiki-main-area),
|
||||
.sidebar > *, .tag-list-filter, .post-list > *,
|
||||
.top-nav-brand-link, .top-nav-menu-link,
|
||||
.top-nav-user-desktop, .top-nav-user-mobile, .top-nav-mobile-menu)
|
||||
{
|
||||
writing-mode: vertical-lr;
|
||||
text-orientation: mixed;
|
||||
}
|
||||
|
||||
/* Existing Japanese vertical decorations must also advance to the right. */
|
||||
html:lang(mn-Mong) [style*='writing-mode']
|
||||
{
|
||||
writing-mode: vertical-lr !important;
|
||||
}
|
||||
|
||||
/* Inline alignment turns left/right into top/bottom; flex cross alignment
|
||||
and table vertical-align already follow the vertical writing mode. */
|
||||
html:lang(mn-Mong) .text-left
|
||||
{
|
||||
text-align: start;
|
||||
}
|
||||
|
||||
html:lang(mn-Mong) .text-right
|
||||
{
|
||||
text-align: end;
|
||||
}
|
||||
|
||||
[data-vertical-preview]
|
||||
{
|
||||
min-width: 0;
|
||||
min-height: 0;
|
||||
overflow: hidden;
|
||||
}
|
||||
|
||||
[data-vertical-preview] > :not(.top-nav-layout)
|
||||
{
|
||||
flex: 1;
|
||||
min-width: 0;
|
||||
min-height: 0;
|
||||
overflow: auto;
|
||||
}
|
||||
|
||||
[data-vertical-preview] [data-sidebar-container]
|
||||
{
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
min-width: 0;
|
||||
min-height: 0;
|
||||
overflow: hidden;
|
||||
}
|
||||
|
||||
[data-vertical-preview] .main-area
|
||||
{
|
||||
min-width: 0;
|
||||
min-height: 0;
|
||||
overscroll-behavior: contain;
|
||||
}
|
||||
|
||||
[data-vertical-preview] .main-area[data-vertical-content]
|
||||
{
|
||||
overflow-x: auto;
|
||||
overflow-y: hidden;
|
||||
overscroll-behavior-x: contain;
|
||||
}
|
||||
|
||||
/* Specialised lists below retain their own grid and table layouts. */
|
||||
[data-vertical-preview] .main-area[data-vertical-content]:not(
|
||||
.posts-main-area, .tags-main-area, .wiki-main-area)
|
||||
{
|
||||
writing-mode: vertical-lr;
|
||||
text-orientation: mixed;
|
||||
text-align: start;
|
||||
overflow-y: auto;
|
||||
}
|
||||
|
||||
[data-vertical-preview] .main-area[data-vertical-content]:not(
|
||||
.posts-main-area, .tags-main-area, .wiki-main-area) > :is(div, article, section)
|
||||
{
|
||||
max-width: none;
|
||||
max-inline-size: 100%;
|
||||
}
|
||||
|
||||
[data-vertical-preview] .main-area[data-vertical-content] .prose
|
||||
{
|
||||
max-width: none;
|
||||
max-inline-size: 100%;
|
||||
}
|
||||
|
||||
/* Input and data widgets retain nested scrolling in the vertical text flow. */
|
||||
[data-vertical-preview] .main-area[data-vertical-content] :is(
|
||||
form, .form-layout, pre, .overflow-x-auto, .rc-md-editor, .not-prose)
|
||||
{
|
||||
writing-mode: vertical-lr;
|
||||
text-orientation: mixed;
|
||||
max-height: 100%;
|
||||
overflow: auto;
|
||||
}
|
||||
|
||||
[data-vertical-preview] .main-area[data-vertical-content] :is(form, .form-layout)
|
||||
{
|
||||
width: auto;
|
||||
inline-size: min(36rem, 100%);
|
||||
}
|
||||
|
||||
[data-vertical-preview] .main-area[data-vertical-content] form.space-y-2
|
||||
{
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
align-items: flex-start;
|
||||
gap: .75rem;
|
||||
}
|
||||
|
||||
[data-vertical-preview] .main-area[data-vertical-content] form.space-y-2 > *
|
||||
{
|
||||
flex: none;
|
||||
margin: 0;
|
||||
}
|
||||
|
||||
[data-vertical-preview] .main-area[data-vertical-content] form label.block
|
||||
{
|
||||
margin: 0;
|
||||
margin-block-end: .25rem;
|
||||
}
|
||||
|
||||
[data-vertical-preview] .main-area[data-vertical-content] form.space-y-2
|
||||
> :has(> input[type='checkbox'])
|
||||
{
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: .5rem;
|
||||
}
|
||||
|
||||
[data-vertical-preview] .main-area[data-vertical-content] form.space-y-2
|
||||
> :has(> input[type='checkbox']) > label
|
||||
{
|
||||
margin: 0;
|
||||
}
|
||||
|
||||
[data-vertical-preview] :where(.main-area[data-vertical-content]) :is(
|
||||
button, input, select, textarea, code, time, table)
|
||||
{
|
||||
writing-mode: vertical-lr;
|
||||
}
|
||||
|
||||
[data-vertical-preview] .main-area[data-vertical-content] :is(img, video, iframe, canvas)
|
||||
{
|
||||
max-height: 100%;
|
||||
object-fit: contain;
|
||||
}
|
||||
|
||||
/* Keep the URL source horizontal even in the vertical page flow. */
|
||||
[data-vertical-preview] .main-area[data-vertical-content] .post-import-source textarea
|
||||
{
|
||||
writing-mode: horizontal-tb;
|
||||
width: min(36rem, 65vw);
|
||||
height: min(32rem, 70dvh);
|
||||
inline-size: min(36rem, 65vw);
|
||||
block-size: min(32rem, 70dvh);
|
||||
}
|
||||
|
||||
[data-vertical-preview] .main-area .post-search-form
|
||||
{
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
align-items: flex-start;
|
||||
gap: 1rem;
|
||||
inline-size: 100%;
|
||||
}
|
||||
|
||||
[data-vertical-preview] .post-search-form > :not([hidden])
|
||||
{
|
||||
flex: none;
|
||||
margin: 0;
|
||||
width: auto;
|
||||
}
|
||||
|
||||
[data-vertical-preview] .post-search-form label.block
|
||||
{
|
||||
margin: 0;
|
||||
margin-block-end: .5rem;
|
||||
}
|
||||
|
||||
[data-vertical-preview] .post-search-form input[type='text']
|
||||
{
|
||||
width: auto;
|
||||
inline-size: min(24rem, 100%);
|
||||
}
|
||||
|
||||
[data-vertical-preview] .post-search-form fieldset
|
||||
{
|
||||
width: auto;
|
||||
margin: 0;
|
||||
}
|
||||
|
||||
[data-vertical-preview] .post-search-form input[type='datetime-local']
|
||||
{
|
||||
inline-size: 13rem;
|
||||
}
|
||||
|
||||
[data-vertical-preview] .main-area.post-import-review
|
||||
{
|
||||
padding-bottom: 1rem;
|
||||
}
|
||||
|
||||
[data-vertical-preview] .post-import-review :is(.space-y-6, .space-y-3) > *
|
||||
{
|
||||
margin-top: 0;
|
||||
margin-bottom: 0;
|
||||
margin-block-end: 1rem;
|
||||
}
|
||||
|
||||
[data-vertical-preview] > .post-import-footer
|
||||
{
|
||||
flex: none;
|
||||
writing-mode: vertical-lr;
|
||||
overflow: auto;
|
||||
border-top: 0;
|
||||
border-left-width: 1px;
|
||||
}
|
||||
|
||||
[data-vertical-preview] .post-import-footer > div
|
||||
{
|
||||
height: 100%;
|
||||
max-width: none;
|
||||
flex-direction: column;
|
||||
align-items: stretch;
|
||||
}
|
||||
|
||||
[data-vertical-preview] .post-import-footer > div > :first-child
|
||||
{
|
||||
align-items: flex-start;
|
||||
}
|
||||
|
||||
[data-vertical-preview] .post-import-footer > div > :last-child
|
||||
{
|
||||
flex-direction: row-reverse;
|
||||
justify-content: space-between;
|
||||
}
|
||||
|
||||
[data-vertical-preview] .post-import-footer button
|
||||
{
|
||||
width: auto;
|
||||
}
|
||||
|
||||
[data-vertical-preview] .tag-tree-arrow
|
||||
{
|
||||
display: inline-block;
|
||||
writing-mode: horizontal-tb;
|
||||
transform: rotate(-90deg) scaleX(-1);
|
||||
}
|
||||
|
||||
[data-vertical-preview] .sidebar-panel
|
||||
{
|
||||
width: 100%;
|
||||
height: var(--sidebar-height);
|
||||
min-height: 0;
|
||||
flex: none;
|
||||
}
|
||||
|
||||
/* Mirror the scroll box and its contents to put its scrollbar above the tags. */
|
||||
[data-vertical-preview] .sidebar
|
||||
{
|
||||
display: flex;
|
||||
align-items: flex-end;
|
||||
gap: 1rem;
|
||||
direction: ltr;
|
||||
transform: scaleY(-1);
|
||||
overflow-x: auto;
|
||||
overflow-y: hidden;
|
||||
overscroll-behavior: contain;
|
||||
}
|
||||
|
||||
[data-vertical-preview] .sidebar > *
|
||||
{
|
||||
flex-shrink: 0;
|
||||
transform: scaleY(-1);
|
||||
}
|
||||
|
||||
[data-vertical-preview] .sidebar > form
|
||||
{
|
||||
writing-mode: vertical-lr;
|
||||
text-orientation: mixed;
|
||||
display: block;
|
||||
width: auto;
|
||||
height: 100%;
|
||||
}
|
||||
|
||||
[data-vertical-preview] .sidebar > form > input[type='text']
|
||||
{
|
||||
writing-mode: vertical-lr;
|
||||
text-orientation: mixed;
|
||||
width: auto;
|
||||
height: 100%;
|
||||
min-height: 0;
|
||||
padding: .75rem .5rem;
|
||||
}
|
||||
|
||||
[data-vertical-preview] .sidebar > form > .tag-search-suggestions
|
||||
{
|
||||
inset: auto;
|
||||
inset-inline-start: 0;
|
||||
inset-block-start: 100%;
|
||||
width: auto;
|
||||
inline-size: 100%;
|
||||
max-block-size: min(16rem, 75vw);
|
||||
margin: 0;
|
||||
overflow: auto;
|
||||
}
|
||||
|
||||
[data-vertical-preview] .sidebar > div
|
||||
{
|
||||
writing-mode: vertical-lr;
|
||||
text-orientation: mixed;
|
||||
height: 100%;
|
||||
margin: 0;
|
||||
}
|
||||
|
||||
[data-vertical-preview] .sidebar :is(h2, h3, ul)
|
||||
{
|
||||
margin: 0;
|
||||
margin-block-end: 1rem;
|
||||
}
|
||||
|
||||
[data-vertical-preview] .sidebar-resize
|
||||
{
|
||||
display: block;
|
||||
inset: auto 0 -.5rem;
|
||||
width: 100%;
|
||||
height: 1rem;
|
||||
cursor: row-resize;
|
||||
}
|
||||
|
||||
[data-vertical-preview] .sidebar-resize::before
|
||||
{
|
||||
inset: 50% 0 auto;
|
||||
width: 100%;
|
||||
height: 1px;
|
||||
}
|
||||
|
||||
[data-vertical-preview] .top-nav-locale-name:has(:lang(mn-Mong))
|
||||
{
|
||||
display: inline;
|
||||
writing-mode: vertical-lr;
|
||||
text-orientation: mixed;
|
||||
font-size: 1.25rem;
|
||||
line-height: 1.5;
|
||||
flex-shrink: 0;
|
||||
}
|
||||
|
||||
[data-vertical-preview] .top-nav-menu-link:has(.top-nav-locale-name)
|
||||
{
|
||||
height: auto;
|
||||
min-height: 2rem;
|
||||
}
|
||||
|
||||
/* The post grid fills each column downwards before continuing to the right. */
|
||||
[data-vertical-preview] .posts-main-area > div
|
||||
{
|
||||
display: flex;
|
||||
height: 100%;
|
||||
width: max-content;
|
||||
margin: 0;
|
||||
gap: 1rem;
|
||||
}
|
||||
|
||||
[data-vertical-preview] .posts-main-area > div > div:first-child
|
||||
{
|
||||
flex: none;
|
||||
flex-direction: row;
|
||||
justify-content: space-between;
|
||||
height: 100%;
|
||||
writing-mode: vertical-lr;
|
||||
text-orientation: mixed;
|
||||
}
|
||||
|
||||
[data-vertical-preview] .posts-main-area > div > div:last-child
|
||||
{
|
||||
display: flex;
|
||||
width: max-content;
|
||||
height: 100%;
|
||||
margin: 0;
|
||||
gap: 1rem;
|
||||
}
|
||||
|
||||
[data-vertical-preview] .main-area[data-vertical-content] .post-list
|
||||
{
|
||||
display: grid;
|
||||
grid-auto-flow: column;
|
||||
grid-auto-columns: 10rem;
|
||||
grid-template-rows: repeat(auto-fill, min(10rem, 100%));
|
||||
flex: none;
|
||||
width: max-content;
|
||||
height: 100%;
|
||||
writing-mode: horizontal-tb;
|
||||
}
|
||||
|
||||
[data-vertical-preview] .main-area[data-vertical-content] .post-list > a
|
||||
{
|
||||
height: 100%;
|
||||
}
|
||||
|
||||
[data-vertical-preview] .main-area[data-vertical-content] nav
|
||||
{
|
||||
flex: none;
|
||||
align-self: flex-start;
|
||||
margin: 0;
|
||||
writing-mode: vertical-lr;
|
||||
}
|
||||
|
||||
[data-vertical-preview] .main-area[data-vertical-content] .pagination
|
||||
{
|
||||
align-self: stretch;
|
||||
inline-size: 100%;
|
||||
}
|
||||
|
||||
[data-vertical-preview] .tags-main-area
|
||||
{
|
||||
display: flex;
|
||||
align-items: stretch;
|
||||
gap: 1.5rem;
|
||||
}
|
||||
|
||||
[data-vertical-preview] .tag-list-filter
|
||||
{
|
||||
flex: none;
|
||||
width: auto;
|
||||
inline-size: 100%;
|
||||
max-inline-size: none;
|
||||
overflow: visible;
|
||||
}
|
||||
|
||||
[data-vertical-preview] .tag-list-filter > div
|
||||
{
|
||||
align-items: flex-start;
|
||||
justify-content: flex-start;
|
||||
flex-wrap: nowrap;
|
||||
gap: 1rem;
|
||||
}
|
||||
|
||||
[data-vertical-preview] .main-area .tag-list-filter form.space-y-2
|
||||
{
|
||||
inline-size: auto;
|
||||
max-height: none;
|
||||
overflow: visible;
|
||||
}
|
||||
|
||||
[data-vertical-preview] .tag-list-filter input[type='datetime-local']
|
||||
{
|
||||
inline-size: 13rem;
|
||||
}
|
||||
|
||||
@media (min-width: 768px)
|
||||
{
|
||||
[data-vertical-preview] .tag-list-filter form > div
|
||||
{
|
||||
white-space: nowrap;
|
||||
}
|
||||
}
|
||||
|
||||
html:lang(mn-Mong) .inheritance-code
|
||||
{
|
||||
writing-mode: horizontal-tb;
|
||||
}
|
||||
|
||||
html:lang(mn-Mong) .inheritance-dialogue
|
||||
{
|
||||
width: auto;
|
||||
max-width: calc(100vw - 2rem);
|
||||
inline-size: min(32rem, calc(100dvh - 2rem));
|
||||
block-size: fit-content;
|
||||
}
|
||||
|
||||
html:lang(mn-Mong) .inheritance-dialogue-fields
|
||||
{
|
||||
writing-mode: horizontal-tb;
|
||||
flex-direction: column;
|
||||
justify-content: space-between;
|
||||
width: min(16rem, calc(100vw - 8rem));
|
||||
height: 100%;
|
||||
min-height: 0;
|
||||
}
|
||||
|
||||
html:lang(mn-Mong) .inheritance-dialogue-fields > button
|
||||
{
|
||||
align-self: flex-end;
|
||||
}
|
||||
|
||||
[data-vertical-preview] .tag-list-filter h1
|
||||
{
|
||||
writing-mode: vertical-lr;
|
||||
text-orientation: mixed;
|
||||
max-height: 8rem;
|
||||
margin-block: 0;
|
||||
}
|
||||
|
||||
[data-vertical-preview] .tag-list-filter input[type='number']
|
||||
{
|
||||
max-inline-size: 7rem;
|
||||
}
|
||||
|
||||
[data-vertical-preview] .tag-list-results
|
||||
{
|
||||
display: flex;
|
||||
flex: none;
|
||||
gap: 1rem;
|
||||
max-width: none;
|
||||
margin: 0;
|
||||
}
|
||||
|
||||
[data-vertical-preview] .tag-list-table
|
||||
{
|
||||
max-width: none;
|
||||
overflow-x: visible;
|
||||
overflow-y: auto;
|
||||
}
|
||||
|
||||
[data-vertical-preview] .tag-list-table table
|
||||
{
|
||||
writing-mode: vertical-lr;
|
||||
text-orientation: mixed;
|
||||
inline-size: max-content;
|
||||
block-size: max-content;
|
||||
min-width: 0;
|
||||
}
|
||||
|
||||
[data-vertical-preview] .tag-list-table col
|
||||
{
|
||||
width: auto;
|
||||
}
|
||||
|
||||
[data-vertical-preview] .tag-list-table :is(th, td)
|
||||
{
|
||||
min-inline-size: 2rem;
|
||||
max-inline-size: 16rem;
|
||||
}
|
||||
|
||||
[data-vertical-preview] .tag-list-table thead
|
||||
{
|
||||
border-bottom: 0;
|
||||
border-block-end: 2px solid currentColor;
|
||||
}
|
||||
|
||||
[data-vertical-preview] .tag-list-table td:nth-child(2),
|
||||
[data-vertical-preview] .tag-list-table time
|
||||
{
|
||||
writing-mode: vertical-lr;
|
||||
white-space: nowrap;
|
||||
}
|
||||
|
||||
[data-vertical-preview] :is(.sidebar, .tag-list-table, .wiki-main-area) .tag-marquee,
|
||||
[data-vertical-preview] :is(.sidebar, .tag-list-table, .wiki-main-area) .tag-marquee__static
|
||||
{
|
||||
white-space: normal;
|
||||
overflow: visible;
|
||||
text-overflow: clip;
|
||||
max-inline-size: 16rem;
|
||||
opacity: 1;
|
||||
}
|
||||
|
||||
[data-vertical-preview] :is(.sidebar, .tag-list-table, .wiki-main-area) .tag-marquee__animated
|
||||
{
|
||||
display: none;
|
||||
}
|
||||
|
||||
/* Prose flows through the viewport height and grows into columns on the right. */
|
||||
[data-vertical-preview] .wiki-main-area
|
||||
{
|
||||
display: flex;
|
||||
gap: 1rem;
|
||||
}
|
||||
|
||||
[data-vertical-preview] .wiki-main-area > div
|
||||
{
|
||||
flex: none;
|
||||
writing-mode: vertical-lr;
|
||||
text-orientation: mixed;
|
||||
margin: 0;
|
||||
}
|
||||
|
||||
[data-vertical-preview] .wiki-main-area > div > span
|
||||
{
|
||||
writing-mode: vertical-lr;
|
||||
}
|
||||
|
||||
[data-vertical-preview] .wiki-main-area article,
|
||||
[data-vertical-preview] .posts-main-area .localised-document
|
||||
{
|
||||
writing-mode: vertical-lr;
|
||||
text-orientation: mixed;
|
||||
inline-size: 100%;
|
||||
block-size: max-content;
|
||||
max-width: none;
|
||||
margin: 0;
|
||||
flex: none;
|
||||
}
|
||||
|
||||
[data-vertical-preview] .main-area[data-vertical-content] .localised-document
|
||||
{
|
||||
max-width: none;
|
||||
overflow: visible;
|
||||
}
|
||||
|
||||
[data-vertical-preview] .wiki-main-area article :is(h1, h2, h3, h4, p, ul, ol, blockquote)
|
||||
{
|
||||
margin: 0;
|
||||
margin-block: 1em;
|
||||
}
|
||||
|
||||
[data-vertical-preview] .wiki-main-area article :is(ul, ol)
|
||||
{
|
||||
padding: 0;
|
||||
padding-inline-start: 1.5em;
|
||||
}
|
||||
|
||||
[data-vertical-preview] .wiki-main-area article :is(img, video, iframe, svg)
|
||||
{
|
||||
writing-mode: horizontal-tb;
|
||||
max-height: 100%;
|
||||
max-width: none;
|
||||
object-fit: contain;
|
||||
}
|
||||
|
||||
[data-vertical-preview] .wiki-main-area article :is(pre, table, .not-prose),
|
||||
[data-vertical-preview] .main-area[data-vertical-content] :is(code, time, input, select, textarea)
|
||||
{
|
||||
writing-mode: vertical-lr;
|
||||
text-orientation: mixed;
|
||||
}
|
||||
|
||||
[data-vertical-preview] .wiki-main-area article :is(pre, table, .not-prose)
|
||||
{
|
||||
display: inline-block;
|
||||
max-height: 100%;
|
||||
max-width: min(48rem, 80vw);
|
||||
overflow: auto;
|
||||
vertical-align: top;
|
||||
}
|
||||
|
||||
[data-vertical-preview] .wiki-main-area article .not-prose
|
||||
{
|
||||
width: max-content;
|
||||
height: 100%;
|
||||
}
|
||||
|
||||
[data-vertical-preview] .wiki-main-area .not-prose > div
|
||||
{
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
height: 100%;
|
||||
margin: 0;
|
||||
}
|
||||
|
||||
[data-vertical-preview] .wiki-main-area .not-prose > div > div:last-child
|
||||
{
|
||||
flex: 1;
|
||||
min-height: 0;
|
||||
}
|
||||
|
||||
@media (min-width: 768px)
|
||||
{
|
||||
[data-vertical-preview].app-layout
|
||||
{
|
||||
flex-direction: row;
|
||||
}
|
||||
|
||||
[data-vertical-preview] .top-nav-layout
|
||||
{
|
||||
display: flex;
|
||||
width: max-content;
|
||||
height: 100%;
|
||||
}
|
||||
|
||||
[data-vertical-preview] .top-nav-bar
|
||||
{
|
||||
flex-direction: column;
|
||||
flex: none;
|
||||
width: 3.5rem;
|
||||
height: 100%;
|
||||
padding: .5rem 0;
|
||||
gap: .5rem;
|
||||
}
|
||||
|
||||
[data-vertical-preview] .top-nav-primary
|
||||
{
|
||||
flex-direction: column;
|
||||
flex: 1;
|
||||
min-height: 0;
|
||||
width: 100%;
|
||||
height: auto;
|
||||
overflow: hidden;
|
||||
}
|
||||
|
||||
[data-vertical-preview] .top-nav-brand-link
|
||||
{
|
||||
writing-mode: vertical-lr;
|
||||
text-orientation: mixed;
|
||||
max-height: none;
|
||||
white-space: nowrap;
|
||||
margin-block: .5rem;
|
||||
}
|
||||
|
||||
[data-vertical-preview] .top-nav-desktop-menu
|
||||
{
|
||||
flex-direction: column;
|
||||
width: 100%;
|
||||
height: auto;
|
||||
}
|
||||
|
||||
[data-vertical-preview] .top-nav-layout[data-measuring] .top-nav-primary,
|
||||
[data-vertical-preview] .top-nav-layout[data-measuring] .top-nav-desktop-menu,
|
||||
[data-vertical-preview] .top-nav-layout[data-measuring] .top-nav-account
|
||||
{
|
||||
flex: 0 0 auto;
|
||||
width: 100%;
|
||||
height: max-content;
|
||||
max-height: none;
|
||||
}
|
||||
|
||||
[data-vertical-preview] .top-nav-desktop-menu > div:not(.top-nav-highlight)
|
||||
{
|
||||
width: 100%;
|
||||
}
|
||||
|
||||
[data-vertical-preview] .top-nav-desktop-menu .top-nav-menu-link
|
||||
{
|
||||
justify-content: center;
|
||||
width: 100%;
|
||||
min-height: 3rem;
|
||||
height: auto;
|
||||
padding: .5rem;
|
||||
}
|
||||
|
||||
[data-vertical-preview] .top-nav-menu-link > :not(svg, select),
|
||||
[data-vertical-preview] .top-nav-more-menu h2
|
||||
{
|
||||
writing-mode: vertical-lr;
|
||||
text-orientation: mixed;
|
||||
max-height: none;
|
||||
white-space: nowrap;
|
||||
}
|
||||
|
||||
[data-vertical-preview] .top-nav-highlight
|
||||
{
|
||||
inset-inline-start: 0;
|
||||
}
|
||||
|
||||
[data-vertical-preview] .top-nav-account
|
||||
{
|
||||
flex-direction: column;
|
||||
width: 100%;
|
||||
margin: 0;
|
||||
}
|
||||
|
||||
[data-vertical-preview] .top-nav-account .top-nav-user-desktop
|
||||
{
|
||||
max-width: 100%;
|
||||
margin: 0;
|
||||
padding: 0;
|
||||
}
|
||||
|
||||
[data-vertical-preview] .top-nav-locale-name
|
||||
{
|
||||
display: inline;
|
||||
writing-mode: vertical-lr;
|
||||
}
|
||||
|
||||
[data-vertical-preview] .top-nav-desktop-submenu
|
||||
{
|
||||
min-width: 0;
|
||||
height: 100%;
|
||||
}
|
||||
|
||||
[data-vertical-preview] .top-nav-submenu-content
|
||||
{
|
||||
writing-mode: vertical-lr;
|
||||
text-orientation: mixed;
|
||||
width: max-content;
|
||||
height: 100%;
|
||||
overflow: visible;
|
||||
}
|
||||
|
||||
[data-vertical-preview] .top-nav-submenu-content:not(.top-nav-more-menu) > div
|
||||
{
|
||||
height: 100%;
|
||||
}
|
||||
|
||||
[data-vertical-preview] :is(.top-nav-submenu-items, .top-nav-more-links)
|
||||
{
|
||||
flex-direction: row;
|
||||
flex-wrap: wrap;
|
||||
align-items: stretch;
|
||||
max-height: 100%;
|
||||
padding-inline: .75rem;
|
||||
padding-block: 0;
|
||||
}
|
||||
|
||||
[data-vertical-preview] .top-nav-desktop-submenu .top-nav-menu-link
|
||||
{
|
||||
min-height: 0;
|
||||
min-width: 40px;
|
||||
padding-inline: .75rem;
|
||||
padding-block: .5rem;
|
||||
}
|
||||
|
||||
[data-vertical-preview] .top-nav-submenu-items .top-nav-menu-link
|
||||
{
|
||||
justify-content: center;
|
||||
}
|
||||
}
|
||||
|
||||
@media (max-width: 767px)
|
||||
{
|
||||
[data-vertical-preview] .top-nav-layout
|
||||
{
|
||||
max-height: 50dvh;
|
||||
overflow-y: auto;
|
||||
}
|
||||
}
|
||||
|
||||
+4
-11
@@ -1,11 +1,9 @@
|
||||
import { createInstance } from 'i18next'
|
||||
import { initReactI18next } from 'react-i18next'
|
||||
|
||||
import { MONGOLIAN_LOCALE, SUPPORTED_LOCALES } from '@/lib/locales'
|
||||
|
||||
import type { i18n as I18n, TOptions } from 'i18next'
|
||||
|
||||
import type { UILocaleCode } from '@/lib/locales'
|
||||
import type { LocaleCode } from '@/lib/locales'
|
||||
|
||||
// Keep Japanese placeholders editable without reporting them as completed translations.
|
||||
const translatedResource = (resource: Record<string, unknown>): Record<string, unknown> => {
|
||||
@@ -36,14 +34,9 @@ for (const [path, dictionary] of Object.entries (dictionaries))
|
||||
const [, , locale, filename] = path.split ('/')
|
||||
resources[locale] ??= { }
|
||||
resources[locale][filename.slice (0, -5)] =
|
||||
locale === 'ja' ? dictionary : translatedResource (dictionary)
|
||||
locale === 'ain-Kana' ? translatedResource (dictionary) : dictionary
|
||||
}
|
||||
const namespaces = Object.keys (resources.ja ?? { })
|
||||
// No Mongolian translations yet; preserve the existing fallback language metadata.
|
||||
resources[MONGOLIAN_LOCALE.code] ??= { }
|
||||
for (const namespace of namespaces)
|
||||
resources[MONGOLIAN_LOCALE.code][namespace] ??=
|
||||
translatedResource ({ _untranslated: ['*'] })
|
||||
|
||||
|
||||
export const createUII18n = (locale: string): I18n => {
|
||||
@@ -51,7 +44,7 @@ export const createUII18n = (locale: string): I18n => {
|
||||
void instance.init ({
|
||||
lng: locale,
|
||||
fallbackLng: 'ja',
|
||||
supportedLngs: [...SUPPORTED_LOCALES, MONGOLIAN_LOCALE.code],
|
||||
supportedLngs: ['ja', 'ain-Kana'],
|
||||
load: 'currentOnly',
|
||||
initAsync: false,
|
||||
defaultNS: 'navigation',
|
||||
@@ -129,7 +122,7 @@ export const languageUIMessage = (
|
||||
|
||||
|
||||
export const untranslatedKeys = (
|
||||
locale: UILocaleCode,
|
||||
locale: LocaleCode,
|
||||
namespace = 'navigation',
|
||||
): string[] => {
|
||||
const collect = (resource: Record<string, unknown>, prefix = ''): string[] =>
|
||||
|
||||
@@ -7,10 +7,6 @@ export const SUPPORTED_LOCALES = ['ja', 'ain-Kana'] as const
|
||||
|
||||
export type LocaleCode = typeof SUPPORTED_LOCALES[number]
|
||||
|
||||
// This UI locale uses Japanese content until the API supports Mongolian.
|
||||
export const MONGOLIAN_LOCALE = { code: 'mn-Mong', name: 'ᠮᠣᠩᠭᠣᠯ' } as const
|
||||
export type UILocaleCode = LocaleCode | typeof MONGOLIAN_LOCALE.code
|
||||
|
||||
export type AvailableLocale = { code: string; name: string }
|
||||
|
||||
|
||||
@@ -32,19 +28,6 @@ export const localeFromPath = (pathname: string): LocaleCode | null => {
|
||||
}
|
||||
|
||||
|
||||
// Frontend layout selection must not change the API's content locale.
|
||||
export const isVerticalPreviewPath = (pathname: string): boolean =>
|
||||
/^\/mn-Mong(?:[/?#]|$)/.test (pathname)
|
||||
|
||||
|
||||
export const isUILocaleCode = (value: unknown): value is UILocaleCode =>
|
||||
value === MONGOLIAN_LOCALE.code || isLocaleCode (value)
|
||||
|
||||
|
||||
export const uiLocaleFromPath = (pathname: string): UILocaleCode =>
|
||||
isVerticalPreviewPath (pathname) ? MONGOLIAN_LOCALE.code : localeFromPath (pathname) ?? 'ja'
|
||||
|
||||
|
||||
export const resolveViewingLocale = (
|
||||
pathname: string,
|
||||
routeLocale?: unknown,
|
||||
@@ -57,29 +40,27 @@ export const currentViewingLocale = (): LocaleCode =>
|
||||
|
||||
|
||||
export const unlocalisedPath = (pathname: string): string => {
|
||||
const locale = isVerticalPreviewPath (pathname) ? 'mn-Mong' : localeFromPath (pathname)
|
||||
const locale = localeFromPath (pathname)
|
||||
return locale == null ? pathname : pathname.slice (locale.length + 1) || '/'
|
||||
}
|
||||
|
||||
|
||||
export const localiseTo = (to: To, locale: LocaleCode, viewingPath = ''): To => {
|
||||
export const localiseTo = (to: To, locale: LocaleCode): To => {
|
||||
const pathname = typeof to === 'string' ? to : to.pathname
|
||||
if (pathname == null
|
||||
|| !(pathname.startsWith ('/'))
|
||||
|| pathname.startsWith ('//')
|
||||
|| localeFromPath (pathname) != null
|
||||
|| isVerticalPreviewPath (pathname))
|
||||
|| localeFromPath (pathname) != null)
|
||||
return to
|
||||
|
||||
const prefix = isVerticalPreviewPath (viewingPath) ? 'mn-Mong' : locale
|
||||
const localised = `/${ prefix }${ pathname }`
|
||||
const localised = `/${ locale }${ pathname }`
|
||||
return typeof to === 'string' ? localised : { ...to, pathname: localised }
|
||||
}
|
||||
|
||||
|
||||
export const switchLocalePath = (
|
||||
location: { pathname: string; search: string; hash: string },
|
||||
locale: UILocaleCode,
|
||||
locale: LocaleCode,
|
||||
): string =>
|
||||
`/${ locale }${ unlocalisedPath (location.pathname) }${ location.search }${ location.hash }`
|
||||
|
||||
@@ -92,8 +73,7 @@ export const legacyLocalePath = (
|
||||
location: { pathname: string; search: string; hash: string },
|
||||
isPage: (pathname: string) => boolean = () => false,
|
||||
): string | null => {
|
||||
if (localeFromPath (location.pathname) != null
|
||||
|| isVerticalPreviewPath (location.pathname) || !isPage (location.pathname))
|
||||
if (localeFromPath (location.pathname) != null || !isPage (location.pathname))
|
||||
return null
|
||||
return switchLocalePath (location, automaticallySelectedLocale ())
|
||||
}
|
||||
|
||||
@@ -1,19 +1,19 @@
|
||||
import { translateUIMessage } from '@/lib/i18n'
|
||||
|
||||
import type navigation from '@/locales/ja/navigation.json'
|
||||
import type { UILocaleCode } from '@/lib/locales'
|
||||
import type { LocaleCode } from '@/lib/locales'
|
||||
|
||||
export type UIMessageKey = keyof typeof navigation
|
||||
|
||||
|
||||
export const uiMessage = (
|
||||
locale: UILocaleCode,
|
||||
locale: LocaleCode,
|
||||
key: UIMessageKey,
|
||||
values: Record<string, string | number> = { },
|
||||
): string => translateUIMessage (key, 'navigation', locale, values).text
|
||||
|
||||
|
||||
export const uiMessageLanguage = (locale: UILocaleCode, key: UIMessageKey): 'ja' | 'ain' =>
|
||||
export const uiMessageLanguage = (locale: LocaleCode, key: UIMessageKey): 'ja' | 'ain' =>
|
||||
translateUIMessage (key, 'navigation', locale).language === 'ain-Kana'
|
||||
? 'ain'
|
||||
: 'ja'
|
||||
|
||||
@@ -1,12 +1,11 @@
|
||||
import { useCallback } from 'react'
|
||||
import { useLocation, useNavigate, useParams } from 'react-router-dom'
|
||||
|
||||
import { isVerticalPreviewPath, localiseTo,
|
||||
resolveViewingLocale, uiLocaleFromPath } from '@/lib/locales'
|
||||
import { localiseTo, resolveViewingLocale } from '@/lib/locales'
|
||||
|
||||
import type { NavigateFunction, NavigateOptions, To } from 'react-router-dom'
|
||||
|
||||
import type { LocaleCode, UILocaleCode } from '@/lib/locales'
|
||||
import type { LocaleCode } from '@/lib/locales'
|
||||
|
||||
|
||||
export const useLocale = (): LocaleCode => {
|
||||
@@ -16,22 +15,13 @@ export const useLocale = (): LocaleCode => {
|
||||
}
|
||||
|
||||
|
||||
export const useUILocale = (): UILocaleCode =>
|
||||
uiLocaleFromPath (useLocation ().pathname)
|
||||
|
||||
|
||||
export const useLocaleNavigate = (): NavigateFunction => {
|
||||
const navigate = useNavigate ()
|
||||
const locale = useLocale ()
|
||||
const { pathname } = useLocation ()
|
||||
return useCallback ((to: To | number, options?: NavigateOptions) => {
|
||||
if (typeof to === 'number')
|
||||
navigate (to)
|
||||
else
|
||||
navigate (localiseTo (to, locale, pathname), options)
|
||||
}, [locale, navigate, pathname])
|
||||
navigate (localiseTo (to, locale), options)
|
||||
}, [locale, navigate])
|
||||
}
|
||||
|
||||
|
||||
export const useVerticalPreview = (): boolean =>
|
||||
isVerticalPreviewPath (useLocation ().pathname)
|
||||
|
||||
@@ -3,11 +3,11 @@ import { useTranslation } from 'react-i18next'
|
||||
|
||||
import LocalisedText from '@/components/LocalisedText'
|
||||
import { translateUIMessage } from '@/lib/i18n'
|
||||
import { useUILocale } from '@/lib/useLocale'
|
||||
import { useLocale } from '@/lib/useLocale'
|
||||
|
||||
|
||||
export const useUITranslation = (namespace = 'common') => {
|
||||
const locale = useUILocale ()
|
||||
const locale = useLocale ()
|
||||
const { i18n } = useTranslation (namespace, { lng: locale })
|
||||
|
||||
const message = useCallback ((key: string, values?: Record<string, string | number>) => {
|
||||
|
||||
@@ -152,7 +152,7 @@ export const msToTime = (ms: number): string => {
|
||||
|
||||
|
||||
export const inputClass = (invalid?: boolean, className?: string): string =>
|
||||
cn ('[inline-size:100%] rounded border p-2',
|
||||
cn ('w-full rounded border p-2',
|
||||
(invalid
|
||||
? ['border-red-500 bg-red-50 text-red-900',
|
||||
'placeholder:text-red-300',
|
||||
|
||||
+2
-2
@@ -6,7 +6,7 @@ import { I18nextProvider } from 'react-i18next'
|
||||
import '@/index.css'
|
||||
import App, { preloadPageRoute, resolvePageRoute } from '@/App'
|
||||
import { createUII18n } from '@/lib/i18n'
|
||||
import { currentViewingLocale, uiLocaleFromPath } from '@/lib/locales'
|
||||
import { currentViewingLocale } from '@/lib/locales'
|
||||
import { localesKeys } from '@/lib/queryKeys'
|
||||
import { applyClientAnimationMode, getClientAnimationMode } from '@/lib/settings'
|
||||
|
||||
@@ -22,7 +22,7 @@ const client = new QueryClient ({
|
||||
|
||||
|
||||
const mount = (serverRendered: boolean) => {
|
||||
const instance = createUII18n (uiLocaleFromPath (window.location.pathname))
|
||||
const instance = createUII18n (currentViewingLocale ())
|
||||
const app = (
|
||||
<HelmetProvider context={helmetContext}>
|
||||
<QueryClientProvider client={client}>
|
||||
|
||||
変更されたファイルが多すぎるため、一部のファイルは表示されません さらに表示
新しいイシューから参照
ユーザーをブロックする