コミットを比較
4
コミット
| 作成者 | SHA1 | 日付 | |
|---|---|---|---|
|
|
398f4f6b82 | ||
|
|
5246ac5c61 | ||
|
|
7cf2978f5f | ||
|
|
11e6f73287 |
@@ -70,7 +70,10 @@ class MaterialsController < ApplicationController
|
||||
.find_by(id: params[:id])
|
||||
return head :not_found unless material
|
||||
|
||||
wiki_page_body = material.tag&.tag_name('ja')&.wiki_page&.current_revision&.body
|
||||
wiki_page_body =
|
||||
TagDescription
|
||||
.find_by(tag_id: material.tag_id, language_code: locale.language_code)
|
||||
&.body
|
||||
|
||||
render json: MaterialRepr.base(material, host: request.base_url,
|
||||
language_code: locale.language_code).merge(wiki_page_body:)
|
||||
|
||||
@@ -26,7 +26,7 @@ class NicoTagsController < ApplicationController
|
||||
ExternalTag
|
||||
.joins("LEFT JOIN (#{ post_tag_max_sql }) post_tag_max " \
|
||||
'ON post_tag_max.external_tag_id = external_tags.id')
|
||||
.includes(linked_tags: { tag_names: :wiki_page })
|
||||
.includes(linked_tags: [:tag_names, :tag_descriptions])
|
||||
if name
|
||||
q = q.where(('external_tags.name LIKE ? ' +
|
||||
"OR CONCAT(external_tags.platform, ':', external_tags.name) LIKE ?"),
|
||||
|
||||
@@ -53,7 +53,7 @@ class PostsController < ApplicationController
|
||||
.reselect('posts.*', Arel.sql("#{ updated_at_all_sql } AS updated_at_all"))
|
||||
.preload(:external_tags, :uploaded_user, :parents, :children,
|
||||
post_tags: [:sections, { tag: [:deerjikists, :materials,
|
||||
{ tag_names: :wiki_page }] }])
|
||||
:tag_names, :tag_descriptions] }])
|
||||
.with_attached_thumbnail
|
||||
|
||||
q = q.where('posts.url LIKE ?', "%#{ url }%") if url
|
||||
@@ -111,7 +111,7 @@ class PostsController < ApplicationController
|
||||
filtered_posts(locale)
|
||||
.preload(:uploaded_user, :parents, :children,
|
||||
post_tags: [:sections, { tag: [:deerjikists, :materials,
|
||||
{ tag_names: :wiki_page }] }])
|
||||
:tag_names, :tag_descriptions] }])
|
||||
.with_attached_thumbnail
|
||||
.order('RAND()')
|
||||
.first
|
||||
@@ -198,7 +198,7 @@ class PostsController < ApplicationController
|
||||
Post
|
||||
.includes(:uploaded_user, :parents, :children,
|
||||
post_tags: [:sections, { tag: [:deerjikists, :materials,
|
||||
{ tag_names: :wiki_page }] }])
|
||||
:tag_names, :tag_descriptions] }])
|
||||
.with_attached_thumbnail
|
||||
.find_by(id: params[:id])
|
||||
return head :not_found unless post
|
||||
|
||||
@@ -51,7 +51,7 @@ class TagVersionsController < ApplicationController
|
||||
|
||||
tags_by_id =
|
||||
Tag
|
||||
.includes(:tag_names, :materials, tag_names: :wiki_page)
|
||||
.includes(:tag_names, :materials, :tag_descriptions, parents: :tag_descriptions)
|
||||
.where(id: all_parent_tag_ids)
|
||||
.index_by(&:id)
|
||||
|
||||
|
||||
@@ -175,7 +175,7 @@ class TagsController < ApplicationController
|
||||
tags_by_id =
|
||||
Tag
|
||||
.joins(:tag_names)
|
||||
.includes(:tag_names, :materials, tag_names: :wiki_page)
|
||||
.includes(:tag_names, :materials, :tag_descriptions, parents: :tag_descriptions)
|
||||
.where(tag_names: { language_code: locale.language_code, primary_flg: true },
|
||||
id: tag_ids)
|
||||
.index_by(&:id)
|
||||
@@ -238,7 +238,7 @@ class TagsController < ApplicationController
|
||||
base =
|
||||
Tag
|
||||
.joins(:tag_names)
|
||||
.includes(:tag_names, :materials, tag_names: :wiki_page)
|
||||
.includes(:tag_names, :materials, :tag_descriptions, parents: :tag_descriptions)
|
||||
.where(tag_names: { language_code: locale.language_code, primary_flg: true },
|
||||
deprecated_at: nil)
|
||||
base = base.where('tags.post_count > 0') if present_only
|
||||
@@ -282,7 +282,7 @@ class TagsController < ApplicationController
|
||||
tag =
|
||||
Tag
|
||||
.joins(:tag_names)
|
||||
.includes(:tag_names, :materials, tag_names: :wiki_page)
|
||||
.includes(:tag_names, :materials, :tag_descriptions, parents: :tag_descriptions)
|
||||
.find_by(id: params[:id],
|
||||
tag_names: { language_code: locale.language_code, primary_flg: true })
|
||||
return render json: TagRepr.base(tag, language_code: locale.language_code) if tag
|
||||
@@ -302,7 +302,7 @@ class TagsController < ApplicationController
|
||||
tag =
|
||||
Tag
|
||||
.joins(:tag_names)
|
||||
.includes(:tag_names, :materials, tag_names: :wiki_page)
|
||||
.includes(:tag_names, :materials, :tag_descriptions, parents: :tag_descriptions)
|
||||
.find_by(tag_names: { name:, language_code: locale.language_code, primary_flg: true })
|
||||
return render json: TagRepr.base(tag, language_code: locale.language_code) if tag
|
||||
|
||||
@@ -320,7 +320,7 @@ class TagsController < ApplicationController
|
||||
|
||||
tag =
|
||||
Tag.joins(:tag_names)
|
||||
.includes(:tag_names, tag_names: :wiki_page)
|
||||
.includes(:tag_names, :tag_descriptions, parents: :tag_descriptions)
|
||||
.find_by(id: params[:id],
|
||||
tag_names: { language_code: locale.language_code, primary_flg: true })
|
||||
return head :not_found unless tag
|
||||
@@ -340,7 +340,7 @@ class TagsController < ApplicationController
|
||||
tag =
|
||||
Tag
|
||||
.joins(:tag_names)
|
||||
.includes(:tag_names, tag_names: :wiki_page)
|
||||
.includes(:tag_names, :tag_descriptions, parents: :tag_descriptions)
|
||||
.find_by(tag_names: { name:, language_code: locale.language_code, primary_flg: true })
|
||||
return head :not_found unless tag
|
||||
|
||||
@@ -359,7 +359,7 @@ class TagsController < ApplicationController
|
||||
tag =
|
||||
Tag
|
||||
.joins(:tag_names)
|
||||
.includes(:tag_names, tag_names: :wiki_page)
|
||||
.includes(:tag_names, :tag_descriptions, parents: :tag_descriptions)
|
||||
.find_by(id: params[:id],
|
||||
tag_names: { language_code: locale.language_code, primary_flg: true })
|
||||
return head :not_found unless tag
|
||||
@@ -424,7 +424,7 @@ class TagsController < ApplicationController
|
||||
tag =
|
||||
Tag
|
||||
.joins(:tag_names)
|
||||
.includes(:tag_names, :materials, tag_names: :wiki_page)
|
||||
.includes(:tag_names, :materials, :tag_descriptions, parents: :tag_descriptions)
|
||||
.find_by(tag_names: { name:, language_code: locale.language_code, primary_flg: true })
|
||||
return head :not_found unless tag
|
||||
|
||||
|
||||
@@ -53,6 +53,7 @@ class Tag < ApplicationRecord
|
||||
has_many :tag_versions
|
||||
|
||||
has_many :tag_names
|
||||
has_many :tag_descriptions
|
||||
|
||||
attribute :version_no, :integer, default: 1
|
||||
|
||||
@@ -98,7 +99,13 @@ class Tag < ApplicationRecord
|
||||
|
||||
def deprecated? = deprecated_at?
|
||||
|
||||
def has_wiki = wiki_page.present?
|
||||
def has_description? language_code:
|
||||
if tag_descriptions.loaded?
|
||||
tag_descriptions.any? { _1.language_code == language_code }
|
||||
else
|
||||
tag_descriptions.exists?(language_code:)
|
||||
end
|
||||
end
|
||||
|
||||
def material_id = materials.first&.id
|
||||
|
||||
|
||||
@@ -3,21 +3,28 @@
|
||||
|
||||
module TagRepr
|
||||
BASE = { only: [:id, :category, :post_count, :created_at, :updated_at, :deprecated_at],
|
||||
methods: [:has_wiki, :material_id, :has_deerjikists] }.freeze
|
||||
methods: [:material_id, :has_deerjikists] }.freeze
|
||||
|
||||
module_function
|
||||
|
||||
def base tag, language_code: 'ja'
|
||||
tag.as_json(BASE).merge(name: name_for(tag, language_code),
|
||||
tag.as_json(BASE).merge('has_wiki' => tag.has_description?(language_code:),
|
||||
name: name_for(tag, language_code),
|
||||
aliases: tag.snapshot_aliases(language_code),
|
||||
parents: tag.parents.map { inline(_1, language_code:) })
|
||||
end
|
||||
|
||||
def inline tag, language_code: 'ja'
|
||||
tag.as_json(BASE).merge(name: name_for(tag, language_code), aliases: [], parents: [])
|
||||
tag.as_json(BASE).merge('has_wiki' => tag.has_description?(language_code:),
|
||||
name: name_for(tag, language_code), aliases: [], parents: [])
|
||||
end
|
||||
|
||||
def many(tags, language_code: 'ja') = tags.map { |tag| base(tag, language_code:) }
|
||||
def many tags, language_code: 'ja'
|
||||
records = tags.to_a
|
||||
ActiveRecord::Associations::Preloader.new(
|
||||
records:, associations: [:tag_descriptions, { parents: :tag_descriptions }]).call
|
||||
records.map { |tag| base(tag, language_code:) }
|
||||
end
|
||||
|
||||
def name_for tag, language_code
|
||||
tag.name(language_code) || (tag.system? ? tag.name('ja') : nil)
|
||||
|
||||
@@ -27,8 +27,12 @@ RSpec.describe 'Shared Tag and ExternalTag IDs', type: :model do
|
||||
end
|
||||
|
||||
it "uses the current maximum after deleting earlier #{ resource } records" do
|
||||
create(:tag, id: 100).destroy!
|
||||
tag = create(:tag, id: 100)
|
||||
TagName.where(tag_id: tag.id).update_all(tag_id: nil)
|
||||
tag.destroy!
|
||||
create(:external_tag, id: 200).destroy!
|
||||
expect(Tag.unscoped.count).to eq(0)
|
||||
expect(ExternalTag.unscoped.count).to eq(0)
|
||||
expect(create_resource(resource).id).to eq(1)
|
||||
end
|
||||
|
||||
|
||||
@@ -0,0 +1,50 @@
|
||||
require 'rails_helper'
|
||||
|
||||
RSpec.describe TagRepr do
|
||||
let(:tag) { create(:tag) }
|
||||
|
||||
def description_for record
|
||||
TagDescription.create!(tag: record, language_code: 'ja', body: '', version_no: 1)
|
||||
end
|
||||
|
||||
it 'keeps has_wiki boolean for the selected language in base and inline' do
|
||||
description_for(tag)
|
||||
[:base, :inline].each do |method|
|
||||
expect(described_class.public_send(method, tag).as_json.fetch('has_wiki')).to be(true)
|
||||
expect(described_class.public_send(method, tag, language_code: 'en')
|
||||
.as_json.fetch('has_wiki')).to be(false)
|
||||
end
|
||||
end
|
||||
|
||||
it 'uses the same language for a tag and its parents' do
|
||||
parent = create(:tag)
|
||||
description_for(tag)
|
||||
description_for(parent)
|
||||
TagImplication.create!(tag:, parent_tag: parent)
|
||||
['ja', 'en'].each do |language_code|
|
||||
row = described_class.base(tag, language_code:).as_json
|
||||
expected = language_code == 'ja'
|
||||
expect(row.fetch('has_wiki')).to be(expected)
|
||||
expect(row.fetch('parents').sole.fetch('has_wiki')).to be(expected)
|
||||
end
|
||||
end
|
||||
|
||||
it 'preloads existence checks for many tags and their parents without Wiki reads' do
|
||||
parent = create(:tag)
|
||||
description_for(parent)
|
||||
records = Array.new(3) do
|
||||
create(:tag).tap { TagImplication.create!(tag: _1, parent_tag: parent) }
|
||||
end
|
||||
description_for(records.first)
|
||||
queries = []
|
||||
subscriber = ->(*args) { queries << args.last.fetch(:sql) }
|
||||
rows = nil
|
||||
ActiveSupport::Notifications.subscribed(subscriber, 'sql.active_record') do
|
||||
rows = described_class.many(records).as_json
|
||||
end
|
||||
expect(rows.map { _1.fetch('has_wiki') }).to eq([true, false, false])
|
||||
expect(rows.map { _1.fetch('parents').sole.fetch('has_wiki') }).to eq([true] * 3)
|
||||
expect(queries.grep(/\bSELECT\b.*\btag_descriptions\b/im).size).to be <= 2
|
||||
expect(queries.grep(/\bwiki_(pages|revisions|versions)\b/i)).to be_empty
|
||||
end
|
||||
end
|
||||
@@ -1,6 +1,47 @@
|
||||
require 'rails_helper'
|
||||
|
||||
RSpec.describe Tag, type: :model do
|
||||
describe '#has_description?' do
|
||||
let(:tag) { create(:tag) }
|
||||
|
||||
it 'checks the requested language and treats an empty description as present' do
|
||||
TagDescription.create!(tag:, language_code: 'ja', body: '', version_no: 1)
|
||||
expect(tag.has_description?(language_code: 'ja')).to be(true)
|
||||
expect(tag.has_description?(language_code: 'en')).to be(false)
|
||||
end
|
||||
|
||||
it 'returns false without a description' do
|
||||
expect(tag.has_description?(language_code: 'ja')).to be(false)
|
||||
end
|
||||
|
||||
it 'does not use a Wiki page as evidence of a description' do
|
||||
user = create_member_user!
|
||||
Wiki::Commit.create_legacy_content!(tag_name: tag.tag_name('ja'), body: 'legacy',
|
||||
created_by_user: user)
|
||||
expect(tag.has_description?(language_code: 'ja')).to be(false)
|
||||
end
|
||||
|
||||
it 'reuses preloaded descriptions without reading Wiki or querying again' do
|
||||
TagDescription.create!(tag:, language_code: 'ja', body: '', version_no: 1)
|
||||
loaded = Tag.includes(:tag_descriptions).find(tag.id)
|
||||
queries = []
|
||||
subscriber = ->(*args) { queries << args.last.fetch(:sql) }
|
||||
ActiveSupport::Notifications.subscribed(subscriber, 'sql.active_record') do
|
||||
expect(loaded.has_description?(language_code: 'ja')).to be(true)
|
||||
expect(loaded.has_description?(language_code: 'en')).to be(false)
|
||||
end
|
||||
expect(queries).to be_empty
|
||||
end
|
||||
|
||||
it 'keeps language selection generic without enabling another Language record' do
|
||||
tag.association(:tag_descriptions).target = [
|
||||
TagDescription.new(tag:, language_code: 'en', body: '', version_no: 1)]
|
||||
tag.association(:tag_descriptions).loaded!
|
||||
expect(tag.has_description?(language_code: 'en')).to be(true)
|
||||
expect(tag.has_description?(language_code: 'ja')).to be(false)
|
||||
end
|
||||
end
|
||||
|
||||
describe 'external tag separation' do
|
||||
['nico:reserved', 'NiCo:reserved'].each do |name|
|
||||
it "rejects the reserved prefix #{ name } for internal tags" do
|
||||
|
||||
@@ -178,6 +178,7 @@ RSpec.describe 'Materials API', type: :request do
|
||||
end
|
||||
|
||||
describe 'GET /materials/:id' do
|
||||
include WikiRecords
|
||||
let!(:tag) do
|
||||
create(:tag, primary_name: 'material_show', category: :material)
|
||||
end
|
||||
@@ -205,6 +206,56 @@ RSpec.describe 'Materials API', type: :request do
|
||||
get '/materials/999999999'
|
||||
expect(response).to have_http_status(:not_found)
|
||||
end
|
||||
|
||||
def get_material_without_legacy_reads
|
||||
queries = []
|
||||
subscriber = lambda do |*args|
|
||||
sql = args.last.fetch(:sql)
|
||||
if sql.match?(/\bSELECT\b/i) && sql.match?(/\bwiki_(pages|revisions|versions)\b/i)
|
||||
queries << sql
|
||||
end
|
||||
end
|
||||
ActiveSupport::Notifications.subscribed(subscriber, 'sql.active_record') do
|
||||
get "/materials/#{ material.id }"
|
||||
end
|
||||
expect(response).to have_http_status(:ok)
|
||||
expect(queries).to be_empty
|
||||
end
|
||||
|
||||
it 'reads the description even when the legacy revision has different content' do
|
||||
page = seed_wiki_page(tag_name: tag.tag_name('ja'), body: 'legacy body',
|
||||
created_by_user: member_user)
|
||||
TagDescription.find_by!(tag_id: tag.id, language_code: 'ja')
|
||||
.update!(body: 'description body')
|
||||
get_material_without_legacy_reads
|
||||
expect(json.fetch('wiki_page_body')).to eq('description body')
|
||||
expect(page.current_revision.body).to eq('legacy body')
|
||||
end
|
||||
|
||||
it 'uses tag_id rather than description ID without a Wiki page or TagName' do
|
||||
description = TagDescription.create!(id: tag.id + 1000, tag:, language_code: 'ja',
|
||||
body: 'independent body', version_no: 1)
|
||||
tag.tag_names.update_all(tag_id: nil)
|
||||
get_material_without_legacy_reads
|
||||
expect(description.id).not_to eq(tag.id)
|
||||
expect(json.fetch('wiki_page_body')).to eq('independent body')
|
||||
expect(json.fetch('tag').fetch('has_wiki')).to be(true)
|
||||
end
|
||||
|
||||
it 'returns nil when only legacy Wiki content exists' do
|
||||
seed_wiki_page(tag_name: tag.tag_name('ja'), body: 'legacy only',
|
||||
created_by_user: member_user)
|
||||
TagDescription.where(tag_id: tag.id).delete_all
|
||||
get_material_without_legacy_reads
|
||||
expect(json.fetch('wiki_page_body')).to be_nil
|
||||
expect(json.fetch('tag').fetch('has_wiki')).to be(false)
|
||||
end
|
||||
|
||||
it 'returns nil for an untagged material' do
|
||||
material.update!(tag: nil)
|
||||
get_material_without_legacy_reads
|
||||
expect(json.fetch('wiki_page_body')).to be_nil
|
||||
end
|
||||
end
|
||||
|
||||
describe 'POST /materials' do
|
||||
|
||||
@@ -206,7 +206,13 @@ RSpec.describe 'Tag description native API', type: :request do
|
||||
context 'without an existing description' do
|
||||
before { tag }
|
||||
|
||||
it 'creates both current resources and histories with matching compatibility IDs' do
|
||||
it 'creates a description with synchronised Wiki content and histories' do
|
||||
unrelated = Wiki::Commit.create_legacy_content!(
|
||||
tag_name: create(:tag_name, name: 'Help:unrelated_native_description'),
|
||||
body: 'unrelated body', created_by_user: author)
|
||||
unrelated_state = [unrelated.attributes,
|
||||
unrelated.wiki_revisions.map(&:attributes),
|
||||
unrelated.wiki_versions.map(&:attributes)]
|
||||
expect { native_write(body: 'created natively') }
|
||||
.to change(TagDescription, :count).by(1)
|
||||
.and change(TagDescriptionVersion, :count).by(1)
|
||||
@@ -215,7 +221,7 @@ RSpec.describe 'Tag description native API', type: :request do
|
||||
.and change(WikiVersion, :count).by(1)
|
||||
expect(response).to have_http_status(:created)
|
||||
description = TagDescription.find_by!(tag_id: tag.id, language_code: 'ja')
|
||||
page = WikiPage.find(description.id)
|
||||
page = WikiPage.find_by!(tag_name: tag.tag_name('ja'))
|
||||
revision = page.current_revision
|
||||
version = TagDescriptionVersion.find(revision.id)
|
||||
expect(description).to have_attributes(
|
||||
@@ -227,6 +233,9 @@ RSpec.describe 'Tag description native API', type: :request do
|
||||
expect(page).to have_attributes(tag_name_id: tag_name.id, body: description.body)
|
||||
expect(revision.body).to eq(version.body)
|
||||
expect(page.wiki_versions.last.body).to eq(version.body)
|
||||
unrelated.reload
|
||||
expect([unrelated.attributes, unrelated.wiki_revisions.map(&:attributes),
|
||||
unrelated.wiki_versions.map(&:attributes)]).to eq(unrelated_state)
|
||||
expect_current(description)
|
||||
|
||||
get "/wiki/#{ description.id }"
|
||||
|
||||
@@ -38,6 +38,22 @@ RSpec.describe 'Tags API', type: :request do
|
||||
end
|
||||
|
||||
describe 'GET /tags' do
|
||||
it 'serialises descriptions and parents without loading legacy Wiki pages' do
|
||||
TagDescription.create!(tag:, language_code: 'ja', body: '', version_no: 1)
|
||||
TagDescription.create!(tag: tag2, language_code: 'ja', body: '', version_no: 1)
|
||||
TagImplication.create!(tag:, parent_tag: tag2)
|
||||
queries = []
|
||||
subscriber = ->(*args) { queries << args.last.fetch(:sql) }
|
||||
ActiveSupport::Notifications.subscribed(subscriber, 'sql.active_record') do
|
||||
get '/tags', params: { name: 'spec_tag' }
|
||||
end
|
||||
expect(response).to have_http_status(:ok)
|
||||
row = response_tags.sole
|
||||
expect(row.fetch('has_wiki')).to be(true)
|
||||
expect(row.fetch('parents').sole.fetch('has_wiki')).to be(true)
|
||||
expect(queries.grep(/\bSELECT\b.*\bwiki_(pages|revisions|versions)\b/im)).to be_empty
|
||||
end
|
||||
|
||||
it 'includes legacy external JSON alongside an internal tag with the same id' do
|
||||
external = create(:external_tag, id: tag.id, name: 'spec_external', post_count: 3)
|
||||
|
||||
|
||||
@@ -0,0 +1,143 @@
|
||||
require 'rails_helper'
|
||||
require 'timeout'
|
||||
|
||||
RSpec.describe 'Shared resource IDs across MySQL connections', type: :model do
|
||||
self.use_transactional_tests = false
|
||||
|
||||
before do
|
||||
expect(Rails.env.test?).to be(true)
|
||||
expect(ApplicationRecord.connection.adapter_name).to match(/mysql/i)
|
||||
expect(ApplicationRecord.connection_pool.size).to be >= 3
|
||||
@prefix = "shared_ids_#{ SecureRandom.hex(8) }"
|
||||
@names = [0, 1].map { create(:tag_name, name: "#{ @prefix }_#{ _1 }") }
|
||||
@tag = Tag.create!(tag_name_id: @names.first.id, category: :general)
|
||||
@names.first.update!(tag_id: @tag.id)
|
||||
@threads = []
|
||||
@release = Queue.new
|
||||
end
|
||||
|
||||
after do
|
||||
@release << true if @release
|
||||
begin
|
||||
Array(@threads).each do |thread|
|
||||
raise 'Shared ID worker did not finish' unless thread.join(15)
|
||||
end
|
||||
ensure
|
||||
if @prefix
|
||||
ExternalTag.where(name: "#{ @prefix }_external").delete_all
|
||||
TagGroup.where(name: "#{ @prefix }_group").delete_all
|
||||
end
|
||||
TagDescription.where(tag_id: @tag.id).delete_all if @tag
|
||||
if @names
|
||||
ids = @names.map(&:id)
|
||||
TagName.where(id: ids).update_all(tag_id: nil)
|
||||
Tag.where(tag_name_id: ids).delete_all
|
||||
TagName.where(id: ids).delete_all
|
||||
end
|
||||
end
|
||||
end
|
||||
|
||||
def await_queue queue
|
||||
Timeout.timeout(15) { queue.pop }
|
||||
end
|
||||
|
||||
def worker &block
|
||||
Thread.new do
|
||||
Thread.current.report_on_exception = false
|
||||
ApplicationRecord.connection_pool.with_connection(&block)
|
||||
end.tap { @threads << _1 }
|
||||
end
|
||||
|
||||
def create_resource kind
|
||||
case kind
|
||||
when :tag
|
||||
Tag.create!(tag_name_id: @names.last.id, category: :general)
|
||||
when :external
|
||||
ExternalTag.create!(platform: :nico, name: "#{ @prefix }_external")
|
||||
when :description
|
||||
TagDescription.create!(tag: @tag, language_code: 'ja', body: '', version_no: 1)
|
||||
when :group
|
||||
TagGroup.create!(name: "#{ @prefix }_group", version_no: 1)
|
||||
end
|
||||
end
|
||||
|
||||
def hold_creation kind, rollback: false
|
||||
ready = Queue.new
|
||||
thread = worker do |connection|
|
||||
id = nil
|
||||
connection.transaction do
|
||||
lock_name = nil
|
||||
subscriber = lambda do |*args|
|
||||
match = args.last.fetch(:sql).match(/GET_LOCK\('([^']+)'/)
|
||||
lock_name = match[1] if match
|
||||
end
|
||||
ActiveSupport::Notifications.subscribed(subscriber, 'sql.active_record') do
|
||||
id = create_resource(kind).id
|
||||
end
|
||||
ready << [id, connection.select_value('SELECT CONNECTION_ID()').to_i, lock_name]
|
||||
await_queue(@release)
|
||||
raise ActiveRecord::Rollback if rollback
|
||||
end
|
||||
id
|
||||
end
|
||||
[thread, await_queue(ready)]
|
||||
end
|
||||
|
||||
def result thread
|
||||
raise 'Shared ID worker did not finish' unless thread.join(15)
|
||||
thread.value
|
||||
end
|
||||
|
||||
{ tags: [:external, :tag], wiki: [:description, :group] }.each do |space, kinds|
|
||||
[false, true].each do |rollback|
|
||||
it "serialises #{ space } inserts through #{ rollback ? 'rollback' : 'commit' }" do
|
||||
tables = SharedResourceIdAllocator::SPACES.fetch(space.to_s)
|
||||
maxima = tables.map do |table|
|
||||
ApplicationRecord.connection.select_value("SELECT MAX(id) FROM #{ table }").to_i
|
||||
end
|
||||
first, (first_id, connection_id, lock_name) = hold_creation(kinds.first, rollback:)
|
||||
expect(first_id).to eq(maxima.max + 1)
|
||||
connection = ApplicationRecord.connection
|
||||
quoted_lock = connection.quote(lock_name)
|
||||
expect(connection.select_value("SELECT IS_USED_LOCK(#{ quoted_lock })").to_i)
|
||||
.to eq(connection_id)
|
||||
|
||||
started = Queue.new
|
||||
second = worker do |other|
|
||||
started << other.select_value('SELECT CONNECTION_ID()').to_i
|
||||
create_resource(kinds.last).id
|
||||
end
|
||||
expect(await_queue(started)).not_to eq(connection_id)
|
||||
@release << true
|
||||
expect(result(first)).to eq(first_id)
|
||||
expect(result(second)).to eq(rollback ? first_id : first_id + 1)
|
||||
expect(connection.select_value("SELECT IS_FREE_LOCK(#{ quoted_lock })").to_i).to eq(1)
|
||||
end
|
||||
end
|
||||
end
|
||||
|
||||
it 'allows the other ID space to commit while the first space remains locked' do
|
||||
first, (_id, connection_id, lock_name) = hold_creation(:external)
|
||||
second = worker { create_resource(:group).id }
|
||||
expect(result(second)).to be_positive
|
||||
connection = ApplicationRecord.connection
|
||||
quoted_lock = connection.quote(lock_name)
|
||||
expect(connection.select_value("SELECT IS_USED_LOCK(#{ quoted_lock })").to_i)
|
||||
.to eq(connection_id)
|
||||
@release << true
|
||||
result(first)
|
||||
end
|
||||
|
||||
it 'raises on a real lock acquisition failure without inserting a record' do
|
||||
first, (_id, _connection_id, lock_name) = hold_creation(:external, rollback: true)
|
||||
stub_const('SharedResourceIdAllocator::LOCK_TIMEOUT', 0)
|
||||
expect { create_resource(:external) }.to raise_error(ActiveRecord::LockWaitTimeout)
|
||||
expect(ExternalTag.where(name: "#{ @prefix }_external")).not_to exist
|
||||
@release << true
|
||||
result(first)
|
||||
connection = ApplicationRecord.connection
|
||||
quoted_lock = connection.quote(lock_name)
|
||||
expect(connection.select_value("SELECT IS_FREE_LOCK(#{ quoted_lock })").to_i)
|
||||
.to eq(1)
|
||||
end
|
||||
end
|
||||
@@ -62,4 +62,27 @@ RSpec.describe SharedResourceIdAllocator do
|
||||
expect(sql.grep(/FOR UPDATE/)).to be_empty
|
||||
callbacks.fetch(:after_commit).call
|
||||
end
|
||||
|
||||
it 'uses the same named lock within each space and different locks between spaces' do
|
||||
locks = [Tag, ExternalTag, TagDescription, TagGroup].map do |model|
|
||||
allow(model).to receive(:connection).and_return(connection)
|
||||
allow(model).to receive(:current_transaction).and_return(transaction)
|
||||
allow(model).to receive(:uncached).and_yield
|
||||
record = model.new(id: 50)
|
||||
described_class.assign!(record)
|
||||
statement = sql.grep(/GET_LOCK/).last
|
||||
callbacks.fetch(:after_commit).call
|
||||
statement
|
||||
end
|
||||
expect(locks[0]).to eq(locks[1])
|
||||
expect(locks[2]).to eq(locks[3])
|
||||
expect(locks[0]).not_to eq(locks[2])
|
||||
end
|
||||
|
||||
it 'reports lock release failures' do
|
||||
described_class.assign!(record)
|
||||
allow(connection).to receive(:select_value).with(/RELEASE_LOCK/).and_return(nil)
|
||||
expect { callbacks.fetch(:after_commit).call }
|
||||
.to raise_error(ActiveRecord::ActiveRecordError, /lock release failed/)
|
||||
end
|
||||
end
|
||||
|
||||
@@ -0,0 +1,112 @@
|
||||
import { mkdir, mkdtemp, rm, writeFile } from 'node:fs/promises'
|
||||
import { tmpdir } from 'node:os'
|
||||
import path from 'node:path'
|
||||
import { afterAll, afterEach, beforeEach, describe, expect, it, vi } from 'vitest'
|
||||
|
||||
import { generateHelpAssets } from './help-assets'
|
||||
|
||||
import type { ArticleMeta, HelpChange, HelpSearchEntry, HelpTitleIndex } from '@/lib/help'
|
||||
|
||||
vi.hoisted (() => {
|
||||
vi.stubGlobal ('Uint8Array', Object.getPrototypeOf (new TextEncoder ().encode ('')).constructor)
|
||||
})
|
||||
afterAll (() => vi.unstubAllGlobals ())
|
||||
|
||||
|
||||
const readAsset = <T,> (modules: Map<string, string>, name: string): T => {
|
||||
const source = modules.get (`virtual:help/${ name }`)!
|
||||
const argument = source.slice ('export default JSON.parse('.length, -1)
|
||||
return JSON.parse (JSON.parse (argument))
|
||||
}
|
||||
|
||||
|
||||
describe ('Build-time Help assets', () => {
|
||||
let root: string
|
||||
|
||||
beforeEach (async () => {
|
||||
root = await mkdtemp (path.join (tmpdir (), 'btrc-help-assets-'))
|
||||
})
|
||||
|
||||
afterEach (async () => {
|
||||
await rm (root, { recursive: true, force: true })
|
||||
})
|
||||
|
||||
const writeArticle = async (
|
||||
identifier: string,
|
||||
editions: Record<string, string>,
|
||||
current = '2026-10-02.10',
|
||||
) => {
|
||||
const articleRoot = path.join (root, identifier)
|
||||
const editionRoot = path.join (articleRoot, 'editions', 'ja')
|
||||
await mkdir (editionRoot, { recursive: true })
|
||||
await writeFile (path.join (articleRoot, 'article.yml'), [
|
||||
`identifier: ${ identifier }`, 'canonical_language: ja', 'title: stale YAML title',
|
||||
'languages:', ' ja:', ` current_edition: ${ current }`].join ('\n'))
|
||||
await Promise.all (Object.entries (editions).map (([edition, source]) =>
|
||||
writeFile (path.join (editionRoot, `${ edition }.mdx`), source)))
|
||||
}
|
||||
|
||||
it ('generates current search and ordered published history from each edition H1', async () => {
|
||||
await writeArticle ('guide', {
|
||||
'2026-10-01': '# 旧ホーム\n\n過去本文',
|
||||
'2026-10-02': '# ホーム\n\n最初の同日版',
|
||||
'2026-10-02.2': '# ホーム\n\n第二版',
|
||||
'2026-10-02.3': '# ホーム\n\n第三版',
|
||||
'2026-10-02.10': '\uFEFF# 最新ホーム\r\n\r\n現在本文\r\n# 別見出し',
|
||||
'2026-10-02.11': '# 未公開\n\n検索に含めない' })
|
||||
const { modules } = await generateHelpAssets (root)
|
||||
const articles = readAsset<Record<string, ArticleMeta>> (modules, 'articles')
|
||||
expect (articles.guide.languages.ja).toEqual ({
|
||||
currentEdition: '2026-10-02.10', publishedEditions: [
|
||||
'2026-10-01', '2026-10-02', '2026-10-02.2', '2026-10-02.3', '2026-10-02.10'] })
|
||||
expect (readAsset<Record<string, HelpSearchEntry[]>> (modules, 'search').ja).toEqual ([{
|
||||
identifier: 'guide', edition: '2026-10-02.10', title: '最新ホーム',
|
||||
body: '\r\n現在本文\r\n# 別見出し' }])
|
||||
const changes = readAsset<Record<string, HelpChange[]>> (modules, 'changes').ja
|
||||
expect (changes.map (row => [row.edition, row.title, row.pred, row.change, row.date]))
|
||||
.toEqual ([
|
||||
['2026-10-02.10', '最新ホーム', '2026-10-02.3', 'update', '2026-10-02'],
|
||||
['2026-10-02.3', 'ホーム', '2026-10-02.2', 'update', '2026-10-02'],
|
||||
['2026-10-02.2', 'ホーム', '2026-10-02', 'update', '2026-10-02'],
|
||||
['2026-10-02', 'ホーム', '2026-10-01', 'update', '2026-10-02'],
|
||||
['2026-10-01', '旧ホーム', null, 'new', '2026-10-01']])
|
||||
const titles = readAsset<Record<string, HelpTitleIndex>> (modules, 'titles').ja
|
||||
expect (titles).toEqual ({ '旧ホーム': ['guide'], 'ホーム': ['guide'],
|
||||
'最新ホーム': ['guide'] })
|
||||
expect (modules.get ('virtual:help/loaders')).not.toContain ('2026-10-02.11')
|
||||
expect (modules.get ('virtual:help/loaders')).toContain ('2026-10-02.10.mdx?raw')
|
||||
expect (modules.get ('virtual:help/search')).not.toContain ('import(')
|
||||
})
|
||||
|
||||
it ('retains ambiguous title identifiers and normalises width and case', async () => {
|
||||
await writeArticle ('alpha', { '2026-10-02': '# HOME\n本文' }, '2026-10-02')
|
||||
await writeArticle ('beta', { '2026-10-02': '# Home\n本文' }, '2026-10-02')
|
||||
const { modules } = await generateHelpAssets (root)
|
||||
expect (readAsset<Record<string, HelpTitleIndex>> (modules, 'titles').ja.home)
|
||||
.toEqual (['alpha', 'beta'])
|
||||
expect (readAsset<Record<string, HelpChange[]>> (modules, 'changes').ja
|
||||
.map (row => row.identifier)).toEqual (['alpha', 'beta'])
|
||||
})
|
||||
|
||||
it ('rejects missing current files during generation', async () => {
|
||||
await writeArticle ('guide', { '2026-10-02': '# ホーム' })
|
||||
await expect (generateHelpAssets (root)).rejects.toThrow ('Missing current Help edition')
|
||||
})
|
||||
|
||||
it.each (['本文\n# 遅い見出し', '# \n本文']) (
|
||||
'rejects missing leading H1 at build time: %s', async source => {
|
||||
await writeArticle ('guide', { '2026-10-02.10': source })
|
||||
await expect (generateHelpAssets (root)).rejects.toThrow ('Missing leading Help H1')
|
||||
})
|
||||
|
||||
it ('rejects absent canonical metadata instead of generating incomplete assets', async () => {
|
||||
await writeArticle ('guide', { '2026-10-02.10': '# ホーム' })
|
||||
await writeFile (path.join (root, 'guide', 'article.yml'),
|
||||
'identifier: guide\nlanguages:\n ja:\n current_edition: 2026-10-02.10')
|
||||
await expect (generateHelpAssets (root)).rejects.toThrow ('Invalid Help metadata')
|
||||
})
|
||||
|
||||
it ('rejects an empty Help checkout', async () => {
|
||||
await expect (generateHelpAssets (root)).rejects.toThrow ('No Help articles found')
|
||||
})
|
||||
})
|
||||
@@ -4,6 +4,48 @@ import { createHelpFixture } from '@/test/helpFixtures'
|
||||
|
||||
|
||||
describe ('Help file catalogue', () => {
|
||||
it.each ([['Éclair', 'eclair'], ['home', 'HOME'], ['e\u0301clair', 'Éclair']]) (
|
||||
'compares title %s and %s equally at primary strength', (a, b) => {
|
||||
const { api } = createHelpFixture ()
|
||||
expect (api.compareHelpTitles (a, b)).toBe (0)
|
||||
})
|
||||
|
||||
it ('orders distinct Latin titles in both directions', () => {
|
||||
const { api } = createHelpFixture ()
|
||||
expect (api.compareHelpTitles ('Apple', 'Zebra')).toBeLessThan (0)
|
||||
expect (api.compareHelpTitles ('Zebra', 'Apple')).toBeGreaterThan (0)
|
||||
})
|
||||
|
||||
it.each ([['ほーむ', 'ホーム'], ['ホーム', 'ほーむ'], ['ホーム', 'ホーム'],
|
||||
['ABC', 'abc'], ['ガイド', 'がいど']]) (
|
||||
'normalises search text %s and %s identically', (query, text) => {
|
||||
const { api } = createHelpFixture ()
|
||||
expect (api.normaliseHelpSearchText (query)).toBe (api.normaliseHelpSearchText (text))
|
||||
})
|
||||
|
||||
it.each ([['2026-10-02', null], ['2026-10-02.2', 2],
|
||||
['2026-10-02.3', 3], ['2026-10-02.10', 10]] as const) (
|
||||
'separates the date and revision of %s', (edition, revision) => {
|
||||
const { api } = createHelpFixture ()
|
||||
expect (api.parseHelpEdition (edition)).toEqual ({ date: '2026-10-02', revision })
|
||||
const date = api.helpEditionDate (edition)!
|
||||
expect ([date.getFullYear (), date.getMonth (), date.getDate ()]).toEqual ([2026, 9, 2])
|
||||
})
|
||||
|
||||
it.each (['missing', '2026-02-30', '2026-10-02.0', '2026-10-02.2.extra',
|
||||
'2026-10-02.9007199254740992']) ('rejects invalid edition %s', edition => {
|
||||
const { api } = createHelpFixture ()
|
||||
expect (api.parseHelpEdition (edition)).toBeNull ()
|
||||
expect (api.helpEditionDate (edition)).toBeNull ()
|
||||
})
|
||||
|
||||
it ('compares numeric revision suffixes without losing the edition identifiers', () => {
|
||||
const { api } = createHelpFixture ()
|
||||
expect (['2026-10-02.10', '2026-10-02.3', '2026-10-02', '2026-10-02.2']
|
||||
.sort (api.compareHelpEditions)).toEqual ([
|
||||
'2026-10-02', '2026-10-02.2', '2026-10-02.3', '2026-10-02.10'])
|
||||
})
|
||||
|
||||
it ('uses current_edition rather than the newest file, without YAML titles', async () => {
|
||||
const { api } = createHelpFixture ()
|
||||
expect ((await api.getHelpArticle ('guide'))?.languages.ja.currentEdition)
|
||||
@@ -60,4 +102,29 @@ describe ('Help file catalogue', () => {
|
||||
expect (await api.getHelpEdition ('guide', 'ja', '2026-10-02.11')).toBeNull ()
|
||||
expect (await api.getHelpEditionSource ('guide', 'ja', '2026-10-02.11')).toBeNull ()
|
||||
})
|
||||
|
||||
it ('compares raw H1 and body lines in the requested direction', async () => {
|
||||
const { api } = createHelpFixture ()
|
||||
const forward = await api.getHelpDiff ('guide', 'ja', '2026-10-01', '2026-10-02.10')
|
||||
expect (forward?.from.title).toBe ('旧ホーム')
|
||||
expect (forward?.to.title).toBe ('ホーム第十版')
|
||||
expect (forward?.lines).toEqual (expect.arrayContaining ([
|
||||
{ type: 'removed', content: '# 旧ホーム\n' },
|
||||
{ type: 'added', content: '# ホーム第十版\n' },
|
||||
{ type: 'unchanged', content: '\n' }]))
|
||||
const reverse = await api.getHelpDiff ('guide', 'ja', '2026-10-02.10', '2026-10-01')
|
||||
expect (reverse?.lines).toEqual (expect.arrayContaining ([
|
||||
{ type: 'added', content: '# 旧ホーム\n' },
|
||||
{ type: 'removed', content: '# ホーム第十版\n' }]))
|
||||
})
|
||||
|
||||
it.each ([['missing', 'ja', '2026-10-01', '2026-10-02.10'],
|
||||
['guide', 'ja', '2026-10-01', '2026-10-02.11'],
|
||||
['guide', 'en', '2026-10-01', '2026-10-02']]) (
|
||||
'rejects invalid diff editions for %s/%s without reading sources',
|
||||
async (id, language, from, to) => {
|
||||
const { api, raw } = createHelpFixture ()
|
||||
expect (await api.getHelpDiff (id, language, from, to)).toBeNull ()
|
||||
Object.values (raw).forEach (load => expect (load).not.toHaveBeenCalled ())
|
||||
})
|
||||
})
|
||||
|
||||
@@ -31,6 +31,50 @@ export type HelpDiff = {
|
||||
to: HelpEditionSource
|
||||
lines: HelpDiffLine[] }
|
||||
|
||||
export type HelpEditionIdentifier = { date: string; revision: number | null }
|
||||
|
||||
// Fix the locale and primary strength; ICU versions still differ from MySQL UCA 9.0.
|
||||
const helpTitleCollator = new Intl.Collator ('en', {
|
||||
usage: 'sort', sensitivity: 'base', ignorePunctuation: false, numeric: false })
|
||||
|
||||
|
||||
export const compareHelpTitles = (a: string, b: string): number =>
|
||||
helpTitleCollator.compare (a, b)
|
||||
|
||||
|
||||
export const normaliseHelpSearchText = (value: string): string =>
|
||||
value.normalize ('NFKC').toLowerCase ().replace (/[ァ-ヶヽヾ]/g,
|
||||
character => String.fromCodePoint (character.codePointAt (0)! - 0x60))
|
||||
|
||||
|
||||
export const parseHelpEdition = (edition: string): HelpEditionIdentifier | null => {
|
||||
const matched = edition.match (/^(\d{4}-\d{2}-\d{2})(?:\.([1-9]\d*))?$/)
|
||||
if (matched == null)
|
||||
return null
|
||||
const date = new Date (matched[1])
|
||||
const revision = matched[2] == null ? null : Number (matched[2])
|
||||
if (Number.isNaN (date.getTime ()) || date.toISOString ().slice (0, 10) !== matched[1]
|
||||
|| (revision != null && !(Number.isSafeInteger (revision))))
|
||||
return null
|
||||
return { date: matched[1], revision }
|
||||
}
|
||||
|
||||
|
||||
export const compareHelpEditions = (a: string, b: string): number => {
|
||||
const before = parseHelpEdition (a)
|
||||
const after = parseHelpEdition (b)
|
||||
if (before == null || after == null)
|
||||
return a.localeCompare (b)
|
||||
return before.date.localeCompare (after.date)
|
||||
|| (before.revision ?? 1) - (after.revision ?? 1)
|
||||
}
|
||||
|
||||
|
||||
export const helpEditionDate = (edition: string): Date | null => {
|
||||
const parsed = parseHelpEdition (edition)
|
||||
return parsed == null ? null : new Date (`${ parsed.date }T00:00:00`)
|
||||
}
|
||||
|
||||
|
||||
export const getHelpArticle = async (identifier: string): Promise<ArticleMeta | null> => {
|
||||
const { default: articles } = await import ('virtual:help/articles')
|
||||
|
||||
@@ -6,6 +6,7 @@ import { beforeEach, describe, expect, it, vi } from 'vitest'
|
||||
import PrefetchLink from '@/components/PrefetchLink'
|
||||
import * as prefetchers from '@/lib/prefetchers'
|
||||
import HelpDetailPage from '@/pages/help/HelpDetailPage'
|
||||
import HelpDiffPage from '@/pages/help/HelpDiffPage'
|
||||
import { helpFixture } from '@/test/helpFixtures'
|
||||
import { renderWithProviders } from '@/test/render'
|
||||
|
||||
@@ -76,6 +77,29 @@ describe ('Help prefetch integration', () => {
|
||||
Object.values (helpFixture.modules).forEach (load => expect (load).not.toHaveBeenCalled ())
|
||||
})
|
||||
|
||||
it ('reuses two prefetched raw editions when displaying their diff', async () => {
|
||||
const path = '/help/guide/diff?from=2026-10-01&to=2026-10-02.10'
|
||||
const { queryClient } = renderWithProviders (
|
||||
<>
|
||||
<PrefetchLink to={path}>diff</PrefetchLink>
|
||||
<Routes>
|
||||
<Route path="/" element={null}/>
|
||||
<Route path="/help/:identifier/diff" element={<HelpDiffPage/>}/>
|
||||
</Routes>
|
||||
</>)
|
||||
await Promise.all ([prefetchers.prefetchForURL (queryClient, path),
|
||||
prefetchers.prefetchForURL (queryClient, path)])
|
||||
fireEvent.click (screen.getByRole ('link', { name: 'diff' }))
|
||||
expect (await screen.findByRole ('link', { name: '旧ホーム (2026-10-01)' }))
|
||||
.toHaveAttribute ('href', '/help/guide?edition=2026-10-01')
|
||||
expect (screen.getByText ('+ # ホーム第十版')).toBeInTheDocument ()
|
||||
Object.entries (helpFixture.raw).forEach (([name, load]) => {
|
||||
const expected = /\/ja\/(2026-10-01|2026-10-02\.10)\.mdx$/.test (name) ? 1 : 0
|
||||
expect (load).toHaveBeenCalledTimes (expected)
|
||||
})
|
||||
Object.values (helpFixture.modules).forEach (load => expect (load).not.toHaveBeenCalled ())
|
||||
})
|
||||
|
||||
it.each (['intent', 'off']) ('respects %s intent settings and still prefetches clicks',
|
||||
async mode => {
|
||||
settings.linkPreload = mode
|
||||
|
||||
@@ -72,11 +72,25 @@ describe ('tags API functions', () => {
|
||||
)
|
||||
})
|
||||
|
||||
it ('returns null when tag fetches fail', async () => {
|
||||
api.apiGet.mockRejectedValueOnce (new Error ('missing'))
|
||||
it ('returns null for a missing named tag while retaining the ID helper contract', async () => {
|
||||
api.apiGet.mockRejectedValueOnce (new Error ('missing'))
|
||||
api.apiGet.mockRejectedValueOnce ({ isAxiosError: true, response: { status: 404 } })
|
||||
|
||||
await expect (fetchTag ('1')).resolves.toBeNull ()
|
||||
await expect (fetchTagByName ('unknown')).resolves.toBeNull ()
|
||||
})
|
||||
|
||||
it.each ([403, 500]) ('propagates named tag HTTP %s', async status => {
|
||||
const error = { isAxiosError: true, response: { status } }
|
||||
api.apiGet.mockRejectedValueOnce (error)
|
||||
await expect (fetchTagByName ('ホーム')).rejects.toBe (error)
|
||||
})
|
||||
|
||||
it ('propagates named tag network failures and encodes the name', async () => {
|
||||
const error = new Error ('offline')
|
||||
api.apiGet.mockRejectedValueOnce (error)
|
||||
await expect (fetchTagByName ('名前/#%')).rejects.toBe (error)
|
||||
expect (api.apiGet).toHaveBeenLastCalledWith (
|
||||
`/tags/name/${ encodeURIComponent ('名前/#%') }`)
|
||||
})
|
||||
})
|
||||
|
||||
@@ -1,3 +1,5 @@
|
||||
import { isAxiosError } from 'axios'
|
||||
|
||||
import { apiGet } from '@/lib/api'
|
||||
|
||||
import type { Deerjikist,
|
||||
@@ -68,11 +70,13 @@ export const fetchExternalTag = async (id: string): Promise<Tag | null> => {
|
||||
export const fetchTagByName = async (name: string): Promise<Tag | null> => {
|
||||
try
|
||||
{
|
||||
return await apiGet (`/tags/name/${ name }`)
|
||||
return await apiGet (`/tags/name/${ encodeURIComponent (name) }`)
|
||||
}
|
||||
catch
|
||||
catch (error)
|
||||
{
|
||||
return null
|
||||
if (isAxiosError (error) && error.response?.status === 404)
|
||||
return null
|
||||
throw error
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -41,6 +41,8 @@ describe ('Help global edition history', () => {
|
||||
expect (screen.getAllByRole ('columnheader').map (cell => cell.textContent))
|
||||
.toEqual (['差分', 'タイトル', '有効開始年月日'])
|
||||
expect (container).not.toHaveTextContent ('未公開ホーム')
|
||||
expect (container).not.toHaveTextContent ('Invalid Date')
|
||||
expect (container.textContent).not.toMatch (/\d{1,2}:\d{2}/)
|
||||
expect (screen.getAllByRole ('link', { name: '差分' }).map (link =>
|
||||
link.getAttribute ('href'))).toEqual ([
|
||||
'/help/guide/diff?from=2026-10-02.3&to=2026-10-02.10',
|
||||
|
||||
@@ -8,7 +8,7 @@ import PageTitle from '@/components/common/PageTitle'
|
||||
import Pagination from '@/components/common/Pagination'
|
||||
import MainArea from '@/components/layout/MainArea'
|
||||
import { SITE_TITLE } from '@/config'
|
||||
import { getHelpChanges } from '@/lib/help'
|
||||
import { getHelpChanges, helpEditionDate } from '@/lib/help'
|
||||
import { helpKeys } from '@/lib/queryKeys'
|
||||
import { LIST_LIMIT_OPTIONS } from '@/lib/settings'
|
||||
import { dateString } from '@/lib/utils'
|
||||
@@ -85,7 +85,7 @@ const HelpChangesPage: FC = () => {
|
||||
const diffQuery = new URLSearchParams ({
|
||||
from: entry.pred ?? '', to: entry.edition })
|
||||
const diffTo = `${ path }/diff?${ diffQuery.toString () }`
|
||||
const updatedAt = `${ entry.date }T00:00:00`
|
||||
const updatedAt = helpEditionDate (entry.edition)
|
||||
|
||||
return (
|
||||
<tr key={`${ entry.identifier }/${ entry.edition }`}
|
||||
@@ -102,7 +102,9 @@ const HelpChangesPage: FC = () => {
|
||||
{entry.title}
|
||||
</PrefetchLink>
|
||||
</td>
|
||||
<td className="p-2">{dateString (updatedAt, 'hour')}</td>
|
||||
<td className="p-2">
|
||||
{updatedAt != null && dateString (updatedAt, 'hour')}
|
||||
</td>
|
||||
</tr>)
|
||||
})}
|
||||
</tbody>
|
||||
|
||||
@@ -37,6 +37,20 @@ const renderDetail = (route = '/help/guide') => renderWithProviders (
|
||||
describe ('Help details', () => {
|
||||
beforeEach (() => helpFixture.reset ())
|
||||
|
||||
it.each (['2026-10-02', '2026-10-02.2', '2026-10-02.3', '2026-10-02.10']) (
|
||||
'displays a date without inventing a time for edition %s', async edition => {
|
||||
const { container } = renderDetail (`/help/guide?edition=${ edition }`)
|
||||
await screen.findByRole ('heading')
|
||||
expect (container).toHaveTextContent ('10月2日')
|
||||
expect (container).not.toHaveTextContent ('Invalid Date')
|
||||
expect (container.textContent).not.toMatch (/\d{1,2}:\d{2}/)
|
||||
const revision = edition.split ('.')[1]
|
||||
if (revision != null)
|
||||
expect (container).toHaveTextContent (` .${ revision }`)
|
||||
expect (helpFixture.modules[`../../help/guide/editions/ja/${ edition }.mdx`])
|
||||
.toHaveBeenCalled ()
|
||||
})
|
||||
|
||||
it ('displays current_edition H1 and body even when newer files exist', async () => {
|
||||
renderDetail ()
|
||||
expect (await screen.findByRole ('heading', { name: 'ホーム第十版' }))
|
||||
@@ -70,6 +84,7 @@ describe ('Help details', () => {
|
||||
})
|
||||
|
||||
it.each (['/help/missing', '/help/guide?edition=missing',
|
||||
'/help/guide?edition=2026-02-30', '/help/guide?edition=2026-10-02.2.extra',
|
||||
'/help/guide?edition=2026-10-02.11']) (
|
||||
'shows NotFound without redirecting %s', async route => {
|
||||
renderDetail (route)
|
||||
|
||||
@@ -5,7 +5,10 @@ import { useLocation, useParams } from 'react-router-dom'
|
||||
import PrefetchLink from '@/components/PrefetchLink'
|
||||
import MainArea from '@/components/layout/MainArea'
|
||||
import { SITE_TITLE } from '@/config'
|
||||
import { getHelpArticle, getHelpEditionContent } from '@/lib/help'
|
||||
import { getHelpArticle,
|
||||
getHelpEditionContent,
|
||||
helpEditionDate,
|
||||
parseHelpEdition } from '@/lib/help'
|
||||
import { dateString } from '@/lib/utils'
|
||||
import { helpKeys } from '@/lib/queryKeys'
|
||||
import NotFound from '@/pages/NotFound'
|
||||
@@ -31,6 +34,8 @@ const HelpDetailPage: FC = () => {
|
||||
const languageMeta = article?.languages[language]
|
||||
|
||||
const edition = requestedEdition ?? languageMeta?.currentEdition
|
||||
const editionInfo = parseHelpEdition (edition ?? '')
|
||||
const editionDate = helpEditionDate (edition ?? '')
|
||||
|
||||
const editions = languageMeta?.publishedEditions ?? []
|
||||
|
||||
@@ -42,7 +47,7 @@ const HelpDetailPage: FC = () => {
|
||||
: undefined
|
||||
|
||||
const { data: current, isSuccess, isError } = useQuery ({
|
||||
enabled: edition != null && editions.includes (edition),
|
||||
enabled: edition != null && editionInfo != null && editions.includes (edition),
|
||||
queryKey: helpKeys.edition (identifier, language, edition ?? ''),
|
||||
queryFn: () => getHelpEditionContent (identifier, language, edition ?? ''),
|
||||
staleTime: Infinity })
|
||||
@@ -51,6 +56,7 @@ const HelpDetailPage: FC = () => {
|
||||
&& (article == null
|
||||
|| languageMeta == null
|
||||
|| edition == null
|
||||
|| editionInfo == null
|
||||
|| !(editions.includes (edition))))
|
||||
return <NotFound/>
|
||||
|
||||
@@ -76,7 +82,10 @@ const HelpDetailPage: FC = () => {
|
||||
</PrefetchLink>)
|
||||
: '(最古)'}
|
||||
|
||||
<span>{dateString (edition, 'hour')}</span>
|
||||
<span>
|
||||
{editionDate != null && dateString (editionDate, 'hour')}
|
||||
{editionInfo?.revision != null && ` .${ editionInfo.revision }`}
|
||||
</span>
|
||||
|
||||
{succ
|
||||
? (
|
||||
|
||||
@@ -52,4 +52,79 @@ describe ('Help search', () => {
|
||||
expect (await screen.findByRole ('alert')).toHaveTextContent ('fixture loading failed')
|
||||
expect (screen.queryByRole ('link', { name: 'ホーム第十版' })).not.toBeInTheDocument ()
|
||||
})
|
||||
|
||||
it ('sorts edition suffixes numerically and displays their date without a time', async () => {
|
||||
const editions = ['2026-10-02', '2026-10-02.2', '2026-10-02.3', '2026-10-02.10']
|
||||
helpFixture.assets.search.default.ja = editions.map ((edition, index) => ({
|
||||
identifier: `article-${ index }`, edition, title: `article-${ index }`, body: '' }))
|
||||
const { container } = renderWithProviders (<HelpListPage/>, { route: '/help' })
|
||||
await screen.findByText ('4 件')
|
||||
expect (Array.from (container.querySelectorAll ('tbody a'), link => link.textContent))
|
||||
.toEqual (['article-3', 'article-2', 'article-1', 'article-0'])
|
||||
const dates = Array.from (container.querySelectorAll ('tbody tr'), row =>
|
||||
row.children[1].textContent)
|
||||
expect (dates).toHaveLength (4)
|
||||
dates.forEach (date => {
|
||||
expect (date).toContain ('10月2日')
|
||||
expect (date).not.toContain ('Invalid Date')
|
||||
expect (date).not.toMatch (/\d{1,2}:\d{2}/)
|
||||
})
|
||||
})
|
||||
|
||||
it.each ([['ホーム', 'ほーむ', '', true], ['ほーむ', 'ホーム', '', true],
|
||||
['ホーム', 'ホーム', '', true], ['ホーム', '', 'ホーム', true],
|
||||
['ホーム', 'ほーむ', 'ホーム', true], ['ホーム', 'ほーむ', '不一致', false]] as const) (
|
||||
'searches title %s with %s and body with %s', async (title, query, text, found) => {
|
||||
const entry = { identifier: 'guide', edition: '2026-10-02.10',
|
||||
title, body: 'ほーむの案内' }
|
||||
helpFixture.assets.search.default.ja = [entry]
|
||||
const params = new URLSearchParams ({ title: query, text })
|
||||
renderWithProviders (<HelpListPage/>, { route: `/help?${ params }` })
|
||||
await screen.findByText (`${ found ? 1 : 0 } 件`)
|
||||
if (found)
|
||||
expect (screen.getByRole ('link', { name: title })).toHaveAttribute ('href', '/help/guide')
|
||||
else
|
||||
expect (screen.queryByRole ('link', { name: title })).not.toBeInTheDocument ()
|
||||
expect (entry).toEqual ({ identifier: 'guide', edition: '2026-10-02.10',
|
||||
title, body: 'ほーむの案内' })
|
||||
})
|
||||
|
||||
// ai_ci equality is documented by MySQL; these are not captured DB sort results.
|
||||
it.each (['asc', 'desc']) ('orders different titles before identifiers in order %s',
|
||||
async direction => {
|
||||
helpFixture.assets.search.default.ja = [
|
||||
{ identifier: 'alpha', edition: '2026-10-02', title: 'Zebra', body: '' },
|
||||
{ identifier: 'beta', edition: '2026-10-02', title: 'Apple', body: '' }]
|
||||
const { container } = renderWithProviders (<HelpListPage/>, {
|
||||
route: `/help?order=title:${ direction }` })
|
||||
await screen.findByText ('2 件')
|
||||
const expected = direction === 'asc'
|
||||
? ['/help/beta', '/help/alpha'] : ['/help/alpha', '/help/beta']
|
||||
expect (Array.from (container.querySelectorAll ('tbody a'), link =>
|
||||
link.getAttribute ('href'))).toEqual (expected)
|
||||
})
|
||||
|
||||
it.each (['asc', 'desc']) ('uses identifier ties for MySQL ai_ci title order %s',
|
||||
async direction => {
|
||||
helpFixture.assets.search.default.ja = [
|
||||
{ identifier: 'alpha', edition: '2026-10-02', title: 'Éclair', body: '' },
|
||||
{ identifier: 'beta', edition: '2026-10-02', title: 'eclair', body: '' }]
|
||||
const { container } = renderWithProviders (<HelpListPage/>, {
|
||||
route: `/help?order=title:${ direction }` })
|
||||
await screen.findByText ('2 件')
|
||||
expect (Array.from (container.querySelectorAll ('tbody a'), link =>
|
||||
link.getAttribute ('href'))).toEqual (['/help/alpha', '/help/beta'])
|
||||
})
|
||||
|
||||
it.each (['asc', 'desc']) ('ignores title case before identifier ties in order %s',
|
||||
async direction => {
|
||||
helpFixture.assets.search.default.ja = [
|
||||
{ identifier: 'alpha', edition: '2026-10-02', title: 'home', body: '' },
|
||||
{ identifier: 'beta', edition: '2026-10-02', title: 'HOME', body: '' }]
|
||||
const { container } = renderWithProviders (<HelpListPage/>, {
|
||||
route: `/help?order=title:${ direction }` })
|
||||
await screen.findByText ('2 件')
|
||||
expect (Array.from (container.querySelectorAll ('tbody a'), link =>
|
||||
link.getAttribute ('href'))).toEqual (['/help/alpha', '/help/beta'])
|
||||
})
|
||||
})
|
||||
|
||||
@@ -10,7 +10,11 @@ import PageTitle from '@/components/common/PageTitle'
|
||||
import Pagination from '@/components/common/Pagination'
|
||||
import MainArea from '@/components/layout/MainArea'
|
||||
import { SITE_TITLE } from '@/config'
|
||||
import { getHelpSearchEntries } from '@/lib/help'
|
||||
import { compareHelpEditions,
|
||||
compareHelpTitles,
|
||||
getHelpSearchEntries,
|
||||
helpEditionDate,
|
||||
normaliseHelpSearchText } from '@/lib/help'
|
||||
import { helpKeys } from '@/lib/queryKeys'
|
||||
import { LIST_LIMIT_OPTIONS } from '@/lib/settings'
|
||||
import { dateString, inputClass } from '@/lib/utils'
|
||||
@@ -55,22 +59,20 @@ const HelpSearchPage: FC = () => {
|
||||
}, [conditions.title, conditions.text])
|
||||
|
||||
const results = useMemo (() => {
|
||||
const titleQuery = conditions.title.trim ().normalize ('NFKC').toLowerCase ()
|
||||
const textQuery = conditions.text.trim ().normalize ('NFKC').toLowerCase ()
|
||||
const titleQuery = normaliseHelpSearchText (conditions.title.trim ())
|
||||
const textQuery = normaliseHelpSearchText (conditions.text.trim ())
|
||||
const [field, direction] = order.split (':')
|
||||
|
||||
return (
|
||||
entries.filter (entry => (
|
||||
(!(titleQuery)
|
||||
|| entry.title.normalize ('NFKC').toLowerCase ().includes (titleQuery))
|
||||
|| normaliseHelpSearchText (entry.title).includes (titleQuery))
|
||||
&& (!(textQuery)
|
||||
|| entry.body.normalize ('NFKC').toLowerCase ().includes (textQuery))))
|
||||
|| normaliseHelpSearchText (entry.body).includes (textQuery))))
|
||||
.sort ((a, b) => {
|
||||
const [dateA, revisionA = '1'] = a.edition.split ('.')
|
||||
const [dateB, revisionB = '1'] = b.edition.split ('.')
|
||||
const comparison = field === 'title'
|
||||
? a.title.localeCompare (b.title, 'ja')
|
||||
: (dateA.localeCompare (dateB) || Number (revisionA) - Number (revisionB))
|
||||
? compareHelpTitles (a.title, b.title)
|
||||
: compareHelpEditions (a.edition, b.edition)
|
||||
|
||||
return (direction === 'asc' ? comparison : -comparison)
|
||||
|| a.identifier.localeCompare (b.identifier)
|
||||
@@ -180,7 +182,7 @@ const HelpSearchPage: FC = () => {
|
||||
</thead>
|
||||
<tbody>
|
||||
{pageResults.map (entry => {
|
||||
const updatedAt = new Date (entry.edition.replace (/\..*$/, ''))
|
||||
const updatedAt = helpEditionDate (entry.edition)
|
||||
|
||||
return (
|
||||
<tr key={entry.identifier}
|
||||
@@ -192,7 +194,9 @@ const HelpSearchPage: FC = () => {
|
||||
{entry.title}
|
||||
</PrefetchLink>
|
||||
</td>
|
||||
<td className="p-2">{dateString (updatedAt, 'hour')}</td>
|
||||
<td className="p-2">
|
||||
{updatedAt != null && dateString (updatedAt, 'hour')}
|
||||
</td>
|
||||
</tr>)
|
||||
})}
|
||||
</tbody>
|
||||
|
||||
@@ -1,14 +1,19 @@
|
||||
import { screen } from '@testing-library/react'
|
||||
import { Route, Routes } from 'react-router-dom'
|
||||
import { describe, expect, it, vi } from 'vitest'
|
||||
import { act, fireEvent, screen, waitFor, within } from '@testing-library/react'
|
||||
import { Route, Routes, useLocation } from 'react-router-dom'
|
||||
import { beforeEach, describe, expect, it, vi } from 'vitest'
|
||||
|
||||
import { apiPost } from '@/lib/api'
|
||||
import { getHelpTitleIndex } from '@/lib/help'
|
||||
import { tagsKeys, wikiKeys } from '@/lib/queryKeys'
|
||||
import WikiDetailPage from '@/pages/wiki/WikiDetailPage'
|
||||
import { buildTag, buildWikiPage } from '@/test/factories'
|
||||
import WikiNewPage from '@/pages/wiki/WikiNewPage'
|
||||
import { buildTag, buildUser, buildWikiPage } from '@/test/factories'
|
||||
import { renderWithProviders } from '@/test/render'
|
||||
|
||||
const wikiApi = vi.hoisted (() => ({
|
||||
fetchWikiPage: vi.fn (),
|
||||
fetchWikiPageByTitle: vi.fn (),
|
||||
fetchWikiPages: vi.fn (),
|
||||
}))
|
||||
|
||||
const tagsApi = vi.hoisted (() => ({
|
||||
@@ -22,8 +27,140 @@ const postsApi = vi.hoisted (() => ({
|
||||
vi.mock ('@/lib/wiki', () => wikiApi)
|
||||
vi.mock ('@/lib/tags', () => tagsApi)
|
||||
vi.mock ('@/lib/posts', () => postsApi)
|
||||
vi.mock ('@/lib/help', () => ({ getHelpTitleIndex: vi.fn () }))
|
||||
vi.mock ('@/lib/api', async importOriginal => ({
|
||||
...await importOriginal<typeof import ('@/lib/api')> (), apiPost: vi.fn () }))
|
||||
vi.mock ('@/components/ui/use-toast', () => ({ toast: vi.fn () }))
|
||||
vi.mock ('react-markdown-editor-lite', () => ({
|
||||
default: ({ value, onChange }: {
|
||||
value: string
|
||||
onChange: (event: { text: string }) => void }) => (
|
||||
<textarea aria-label="本文エディタ" value={value}
|
||||
onChange={event => onChange ({ text: event.target.value })}/>) }))
|
||||
|
||||
|
||||
const Location = () => {
|
||||
const location = useLocation ()
|
||||
return <output data-testid="location">{location.pathname}{location.search}</output>
|
||||
}
|
||||
|
||||
|
||||
describe ('WikiDetailPage', () => {
|
||||
beforeEach (() => {
|
||||
wikiApi.fetchWikiPageByTitle.mockReset ().mockResolvedValue (null)
|
||||
wikiApi.fetchWikiPages.mockReset ().mockResolvedValue ([])
|
||||
tagsApi.fetchTagByName.mockReset ().mockResolvedValue (null)
|
||||
postsApi.fetchPosts.mockReset ().mockResolvedValue ({ posts: [], count: 0 })
|
||||
vi.mocked (getHelpTitleIndex).mockReset ().mockResolvedValue ({ })
|
||||
vi.mocked (apiPost).mockReset ()
|
||||
})
|
||||
|
||||
it ('offers creation for an existing tag after the Help lookup completes', async () => {
|
||||
let finish!: (index: Record<string, string[]>) => void
|
||||
const pending = new Promise<Record<string, string[]>> (resolve => {
|
||||
finish = resolve
|
||||
})
|
||||
vi.mocked (getHelpTitleIndex).mockReturnValueOnce (pending)
|
||||
tagsApi.fetchTagByName.mockResolvedValue (buildTag ({ name: '既存タグ', hasWiki: false }))
|
||||
renderWithProviders (
|
||||
<Routes><Route path="/wiki/:title" element={<WikiDetailPage/>}/></Routes>,
|
||||
{ route: `/wiki/${ encodeURIComponent ('既存タグ') }` })
|
||||
await waitFor (() => expect (getHelpTitleIndex).toHaveBeenCalled ())
|
||||
expect (screen.queryByText ('404')).not.toBeInTheDocument ()
|
||||
expect (screen.queryByRole ('link', { name: '新規作成してください' }))
|
||||
.not.toBeInTheDocument ()
|
||||
await act (async () => finish ({ }))
|
||||
expect (await screen.findByRole ('link', { name: '新規作成してください' }))
|
||||
.toHaveAttribute ('href', `/wiki/new?title=${ encodeURIComponent ('既存タグ') }`)
|
||||
})
|
||||
|
||||
it ('creates a tag description through the existing form and displays its content', async () => {
|
||||
const page = buildWikiPage ({ title: '既存タグ', body: '説明文',
|
||||
resourceType: 'tag_description' })
|
||||
tagsApi.fetchTagByName.mockResolvedValue (buildTag ({ name: page.title, hasWiki: false }))
|
||||
vi.mocked (apiPost).mockResolvedValueOnce (page)
|
||||
const path = `/wiki/${ encodeURIComponent (page.title) }`
|
||||
const { container, queryClient } = renderWithProviders (
|
||||
<>
|
||||
<Location/>
|
||||
<Routes>
|
||||
<Route path="/wiki/new" element={<WikiNewPage user={buildUser ({ role: 'member' })}/>}/>
|
||||
<Route path="/wiki/:title" element={<WikiDetailPage/>}/>
|
||||
</Routes>
|
||||
</>, { route: path })
|
||||
fireEvent.click (await screen.findByRole ('link', { name: '新規作成してください' }))
|
||||
await screen.findByRole ('heading', { name: '新規 Wiki ページ' })
|
||||
expect (queryClient.getQueryData (wikiKeys.show (page.title, { }))).toBeNull ()
|
||||
queryClient.setQueryData (wikiKeys.index ({ }), [])
|
||||
wikiApi.fetchWikiPageByTitle.mockResolvedValue (page)
|
||||
wikiApi.fetchWikiPages.mockResolvedValue ([page])
|
||||
tagsApi.fetchTagByName.mockResolvedValue (buildTag ({ name: page.title, hasWiki: true }))
|
||||
expect (screen.getAllByRole ('textbox')[0]).toHaveValue (page.title)
|
||||
fireEvent.change (screen.getByRole ('textbox', { name: '本文エディタ' }), {
|
||||
target: { value: page.body } })
|
||||
fireEvent.click (screen.getByRole ('button', { name: '追加' }))
|
||||
await screen.findByRole ('heading', { name: page.title })
|
||||
expect (screen.getByTestId ('location')).toHaveTextContent (path)
|
||||
expect (screen.queryByRole ('textbox', { name: '本文エディタ' })).not.toBeInTheDocument ()
|
||||
expect (within (container.querySelector ('article')!).getByText (page.body))
|
||||
.toBeInTheDocument ()
|
||||
const form = vi.mocked (apiPost).mock.calls[0][1] as FormData
|
||||
expect (form.get ('title')).toBe (page.title)
|
||||
expect (form.get ('body')).toBe (page.body)
|
||||
expect (apiPost).toHaveBeenCalledWith ('/wiki', form,
|
||||
{ headers: { 'Content-Type': 'multipart/form-data' } })
|
||||
expect (screen.queryByText ('404')).not.toBeInTheDocument ()
|
||||
expect (queryClient.getQueryData (wikiKeys.show (page.title, { }))).toEqual (page)
|
||||
await waitFor (() => expect (queryClient.getQueryData (wikiKeys.index ({ })))
|
||||
.toEqual ([page]))
|
||||
await waitFor (() => expect (queryClient.getQueryData (tagsKeys.show (page.title)))
|
||||
.toMatchObject ({ hasWiki: true }))
|
||||
expect (getHelpTitleIndex).toHaveBeenCalledTimes (1)
|
||||
})
|
||||
|
||||
it ('keeps failed saves on the form without changing cached Wiki or tag state', async () => {
|
||||
const title = '既存タグ'
|
||||
const tag = buildTag ({ name: title, hasWiki: false })
|
||||
const path = `/wiki/new?title=${ encodeURIComponent (title) }`
|
||||
vi.mocked (apiPost).mockRejectedValueOnce (new Error ('save failed'))
|
||||
const { queryClient } = renderWithProviders (
|
||||
<><Location/><WikiNewPage user={buildUser ({ role: 'member' })}/></>, { route: path })
|
||||
queryClient.setQueryData (wikiKeys.show (title, { }), null)
|
||||
queryClient.setQueryData (wikiKeys.index ({ }), [])
|
||||
queryClient.setQueryData (tagsKeys.show (title), tag)
|
||||
fireEvent.change (screen.getByRole ('textbox', { name: '本文エディタ' }), {
|
||||
target: { value: '保存しない本文' } })
|
||||
await act (async () => fireEvent.click (screen.getByRole ('button', { name: '追加' })))
|
||||
expect (apiPost).toHaveBeenCalledTimes (1)
|
||||
expect (screen.getByTestId ('location')).toHaveTextContent (path)
|
||||
expect (screen.getByRole ('heading', { name: '新規 Wiki ページ' })).toBeInTheDocument ()
|
||||
expect (queryClient.getQueryData (wikiKeys.show (title, { }))).toBeNull ()
|
||||
expect (queryClient.getQueryData (tagsKeys.show (title))).toEqual (tag)
|
||||
expect (queryClient.getQueryState (wikiKeys.index ({ }))?.isInvalidated).toBe (false)
|
||||
})
|
||||
|
||||
it ('shows NotFound when neither a tag nor a Help title exists', async () => {
|
||||
renderWithProviders (
|
||||
<Routes><Route path="/wiki/:title" element={<WikiDetailPage/>}/></Routes>,
|
||||
{ route: '/wiki/missing' })
|
||||
expect (await screen.findByText ('404')).toBeInTheDocument ()
|
||||
expect (screen.queryByRole ('link', { name: '新規作成してください' }))
|
||||
.not.toBeInTheDocument ()
|
||||
})
|
||||
|
||||
it.each (['403', '500', 'offline']) ('keeps Wiki error %s distinct from missing content',
|
||||
async message => {
|
||||
wikiApi.fetchWikiPageByTitle.mockRejectedValue (new Error (message))
|
||||
tagsApi.fetchTagByName.mockResolvedValue (buildTag ({ name: '既存タグ' }))
|
||||
renderWithProviders (
|
||||
<Routes><Route path="/wiki/:title" element={<WikiDetailPage/>}/></Routes>,
|
||||
{ route: `/wiki/${ encodeURIComponent ('既存タグ') }` })
|
||||
expect (await screen.findByRole ('alert')).toHaveTextContent (message)
|
||||
expect (getHelpTitleIndex).not.toHaveBeenCalled ()
|
||||
expect (screen.queryByRole ('link', { name: '新規作成してください' }))
|
||||
.not.toBeInTheDocument ()
|
||||
})
|
||||
|
||||
it ('renders deprecated state outside the wiki title link', async () => {
|
||||
wikiApi.fetchWikiPageByTitle.mockResolvedValueOnce (buildWikiPage ({
|
||||
title: '旧タグ',
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
import { useQuery, useQueryClient } from '@tanstack/react-query'
|
||||
import { useQuery } from '@tanstack/react-query'
|
||||
import { useEffect, useMemo } from 'react'
|
||||
import { Helmet } from 'react-helmet-async'
|
||||
import { useLocation, useNavigate, useParams } from 'react-router-dom'
|
||||
@@ -29,48 +29,39 @@ const WikiDetailPage: FC = () => {
|
||||
|
||||
const location = useLocation ()
|
||||
const navigate = useNavigate ()
|
||||
const queryClient = useQueryClient ()
|
||||
|
||||
const defaultTag = useMemo (() => ({ name: title, category: 'general' } as Tag), [title])
|
||||
|
||||
const query = new URLSearchParams (location.search)
|
||||
const version = query.get ('version') || undefined
|
||||
|
||||
const { data: wikiPage, isLoading: loading, isSuccess, isFetching } = useQuery ({
|
||||
const { data: wikiPage, isLoading: loading, isSuccess, isFetching, error } = useQuery ({
|
||||
enabled: Boolean (title) && !(/^\d+$/.test (title)),
|
||||
queryKey: wikiKeys.show (title, { version }),
|
||||
queryFn: () => fetchWikiPageByTitle (title, { version }) })
|
||||
|
||||
const missingWiki = isSuccess && !(isFetching) && wikiPage == null
|
||||
const { data: titleIndex, isPending: lookupPending,
|
||||
isFetching: lookupFetching, error: lookupError } = useQuery ({
|
||||
enabled: missingWiki,
|
||||
queryKey: helpKeys.titles ('ja'),
|
||||
queryFn: () => getHelpTitleIndex ('ja'),
|
||||
staleTime: Infinity })
|
||||
const lookupTitle = title.trim ().normalize ('NFKC').toLowerCase ().replace (/^ヘルプ:/, '')
|
||||
const identifiers = useMemo (() => (
|
||||
(titleIndex != null && Object.hasOwn (titleIndex, lookupTitle))
|
||||
? titleIndex[lookupTitle] : []), [titleIndex, lookupTitle])
|
||||
|
||||
useEffect (() => {
|
||||
if (!(isSuccess) || isFetching || wikiPage != null)
|
||||
return
|
||||
|
||||
let active = true
|
||||
const lookupTitle = title.trim ().normalize ('NFKC').toLowerCase ().replace (/^ヘルプ:/, '')
|
||||
|
||||
void queryClient.fetchQuery ({
|
||||
queryKey: helpKeys.titles ('ja'),
|
||||
queryFn: () => getHelpTitleIndex ('ja'),
|
||||
staleTime: Infinity }).then (index => {
|
||||
if (!(active))
|
||||
return
|
||||
|
||||
const identifiers = Object.hasOwn (index, lookupTitle) ? index[lookupTitle] : []
|
||||
if (identifiers.length === 1)
|
||||
navigate (`/help/${ encodeURIComponent (identifiers[0]) }`, { replace: true })
|
||||
}).catch (() => {
|
||||
// A failed Help lookup leaves the original missing Wiki URL in place.
|
||||
})
|
||||
|
||||
return () => {
|
||||
active = false
|
||||
}
|
||||
}, [isSuccess, isFetching, wikiPage, title, version, queryClient, navigate])
|
||||
if (missingWiki && !(lookupFetching) && lookupError == null && identifiers.length === 1)
|
||||
navigate (`/help/${ encodeURIComponent (identifiers[0]) }`, { replace: true })
|
||||
}, [missingWiki, lookupFetching, lookupError, identifiers, navigate])
|
||||
|
||||
const effectiveTitle = wikiPage?.title ?? title
|
||||
const deprecated = wikiPage?.deprecatedAt != null
|
||||
|
||||
const { data: tag } = useQuery ({
|
||||
const { data: tag, isPending: tagPending,
|
||||
isFetching: tagFetching, error: tagError } = useQuery ({
|
||||
enabled: Boolean (effectiveTitle),
|
||||
queryKey: tagsKeys.show (effectiveTitle),
|
||||
queryFn: () => fetchTagByName (effectiveTitle) })
|
||||
@@ -121,7 +112,15 @@ const WikiDetailPage: FC = () => {
|
||||
}
|
||||
}, [title, navigate])
|
||||
|
||||
if (isSuccess && wikiPage == null)
|
||||
const displayError = error ?? (missingWiki ? lookupError ?? tagError : null)
|
||||
if (displayError != null)
|
||||
return <MainArea><p role="alert">{displayError.message}</p></MainArea>
|
||||
|
||||
const waiting = loading || (isFetching && wikiPage == null)
|
||||
|| (missingWiki && (lookupPending || lookupFetching || tagPending
|
||||
|| (tagFetching && tag == null) || identifiers.length === 1))
|
||||
|
||||
if (missingWiki && !(waiting) && (tag == null || version != null))
|
||||
return <NotFound/>
|
||||
|
||||
return (
|
||||
@@ -157,7 +156,7 @@ const WikiDetailPage: FC = () => {
|
||||
{...(version && { to: `/wiki/${ encodeURIComponent (title) }` })}/>
|
||||
{deprecated && <span>(廃止)</span>}
|
||||
</h1>
|
||||
{loading ? <div>Loading...</div> : <WikiBody title={title} body={wikiPage?.body}/>}
|
||||
{waiting ? <div>Loading...</div> : <WikiBody title={title} body={wikiPage?.body}/>}
|
||||
|
||||
{(!(version) && posts.length > 0) && (
|
||||
<div className="not-prose">
|
||||
|
||||
@@ -1,8 +1,9 @@
|
||||
import { screen, waitFor } from '@testing-library/react'
|
||||
import { Route, Routes, useLocation } from 'react-router-dom'
|
||||
import { act, fireEvent, screen, waitFor } from '@testing-library/react'
|
||||
import { Route, Routes, useLocation, useNavigate } from 'react-router-dom'
|
||||
import { beforeEach, describe, expect, it, vi } from 'vitest'
|
||||
|
||||
import { apiGet } from '@/lib/api'
|
||||
import * as help from '@/lib/help'
|
||||
import HelpDetailPage from '@/pages/help/HelpDetailPage'
|
||||
import WikiDetailPage from '@/pages/wiki/WikiDetailPage'
|
||||
import { buildWikiPage } from '@/test/factories'
|
||||
@@ -17,7 +18,14 @@ vi.mock ('@/lib/posts', () => ({ fetchPosts: async () => ({ posts: [], count: 0
|
||||
|
||||
const Location = () => {
|
||||
const location = useLocation ()
|
||||
return <output data-testid="location">{location.pathname}{location.search}</output>
|
||||
const navigate = useNavigate ()
|
||||
return (
|
||||
<>
|
||||
<output data-testid="location">{location.pathname}{location.search}</output>
|
||||
<button onClick={() => navigate (`/wiki/${ encodeURIComponent ('該当なし') }`)}>
|
||||
switch title
|
||||
</button>
|
||||
</>)
|
||||
}
|
||||
|
||||
|
||||
@@ -92,6 +100,36 @@ describe ('Legacy Wiki to Help compatibility', () => {
|
||||
expect (screen.getByTestId ('location')).toHaveTextContent (route)
|
||||
})
|
||||
|
||||
it ('waits for title lookup and does not redirect a later Wiki URL using an old title',
|
||||
async () => {
|
||||
let finish!: (index: Record<string, string[]>) => void
|
||||
const pending = new Promise<Record<string, string[]>> (resolve => {
|
||||
finish = resolve
|
||||
})
|
||||
const lookup = vi.spyOn (help, 'getHelpTitleIndex').mockReturnValueOnce (pending)
|
||||
renderWiki ('ホーム')
|
||||
await waitFor (() => expect (lookup).toHaveBeenCalled ())
|
||||
expect (screen.queryByText ('404')).not.toBeInTheDocument ()
|
||||
fireEvent.click (screen.getByRole ('button', { name: 'switch title' }))
|
||||
await waitFor (() => expect (apiGet).toHaveBeenCalledWith (
|
||||
`/wiki/title/${ encodeURIComponent ('該当なし') }`, expect.anything ()))
|
||||
await act (async () => finish ({ 'ホーム': ['guide'] }))
|
||||
await screen.findByText ('404')
|
||||
expect (screen.getByTestId ('location'))
|
||||
.toHaveTextContent (`/wiki/${ encodeURIComponent ('該当なし') }`)
|
||||
})
|
||||
|
||||
it ('does not treat a Wiki network failure as a missing Wiki', async () => {
|
||||
vi.mocked (apiGet).mockRejectedValueOnce (new Error ('offline'))
|
||||
const { route } = renderWiki ('ホーム')
|
||||
expect (await screen.findByRole ('alert')).toHaveTextContent ('offline')
|
||||
expect (screen.getByTestId ('location')).toHaveTextContent (route)
|
||||
expect (helpFixture.loads.titles).not.toHaveBeenCalled ()
|
||||
expect (screen.queryByText ('404')).not.toBeInTheDocument ()
|
||||
expect (screen.queryByRole ('link', { name: '新規作成してください' }))
|
||||
.not.toBeInTheDocument ()
|
||||
})
|
||||
|
||||
it.each ([403, 500]) ('does not redirect HTTP %s to Help', async status => {
|
||||
vi.mocked (apiGet).mockRejectedValueOnce ({ isAxiosError: true, response: { status } })
|
||||
const { route, queryClient } = renderWiki ('ホーム')
|
||||
|
||||
@@ -1,10 +1,10 @@
|
||||
import type { FC } from 'react'
|
||||
|
||||
import { useQueryClient } from '@tanstack/react-query'
|
||||
import MarkdownIt from 'markdown-it'
|
||||
import { useState } from 'react'
|
||||
import { Helmet } from 'react-helmet-async'
|
||||
import MdEditor from 'react-markdown-editor-lite'
|
||||
import { useLocation, useNavigate } from 'react-router-dom'
|
||||
import 'react-markdown-editor-lite/lib/index.css'
|
||||
|
||||
import FieldError from '@/components/common/FieldError'
|
||||
import FormField from '@/components/common/FormField'
|
||||
@@ -12,12 +12,13 @@ import MainArea from '@/components/layout/MainArea'
|
||||
import { toast } from '@/components/ui/use-toast'
|
||||
import { SITE_TITLE } from '@/config'
|
||||
import { apiPost } from '@/lib/api'
|
||||
import { tagsKeys, wikiKeys } from '@/lib/queryKeys'
|
||||
import { canEditContent } from '@/lib/users'
|
||||
import { inputClass } from '@/lib/utils'
|
||||
import { useValidationErrors } from '@/lib/useValidationErrors'
|
||||
import Forbidden from '@/pages/Forbidden'
|
||||
|
||||
import 'react-markdown-editor-lite/lib/index.css'
|
||||
import type { FC } from 'react'
|
||||
|
||||
import type { User, WikiPage } from '@/types'
|
||||
|
||||
@@ -38,6 +39,7 @@ const WikiNewPage: FC<Props> = ({ user }) => {
|
||||
|
||||
const location = useLocation ()
|
||||
const navigate = useNavigate ()
|
||||
const qc = useQueryClient ()
|
||||
|
||||
const query = new URLSearchParams (location.search)
|
||||
const titleQuery = query.get ('title') ?? ''
|
||||
@@ -58,8 +60,13 @@ const WikiNewPage: FC<Props> = ({ user }) => {
|
||||
{
|
||||
const data = await apiPost<WikiPage> ('/wiki', formData,
|
||||
{ headers: { 'Content-Type': 'multipart/form-data' } })
|
||||
await qc.cancelQueries ({ queryKey: wikiKeys.root })
|
||||
qc.setQueryData (wikiKeys.show (data.title, { }), data)
|
||||
await Promise.all ([
|
||||
qc.invalidateQueries ({ queryKey: wikiKeys.root }),
|
||||
qc.invalidateQueries ({ queryKey: tagsKeys.root })])
|
||||
toast ({ title: '投稿成功!' })
|
||||
navigate (`/wiki/${ data.title }`)
|
||||
navigate (`/wiki/${ encodeURIComponent (data.title) }`)
|
||||
}
|
||||
catch (e)
|
||||
{
|
||||
|
||||
@@ -4,7 +4,7 @@ import { vi } from 'vitest'
|
||||
|
||||
import source from '@/lib/help.ts?raw'
|
||||
|
||||
import type { ReactElement } from 'react'
|
||||
import type { ComponentType } from 'react'
|
||||
|
||||
import type * as Help from '@/lib/help'
|
||||
|
||||
@@ -38,11 +38,11 @@ export const createHelpFixture = () => {
|
||||
vi.fn (async () => `# ${title}\n\n${body}`)]))
|
||||
const moduleLoads = Object.fromEntries (published.map (([id, language, edition, title, body]) => [
|
||||
`../../help/${id}/editions/${language}/${edition}.mdx`,
|
||||
vi.fn (async (): Promise<{ default: () => ReactElement }> => ({
|
||||
vi.fn (async (): Promise<{ default: ComponentType }> => ({
|
||||
default: () => createElement ('div', null,
|
||||
createElement ('h1', null, title), createElement ('p', null, body)) }))]))
|
||||
// Dynamic imports reuse a module namespace even when called more than once.
|
||||
const caches: Record<string, { promise?: Promise<{ default: () => ReactElement }> }> = { }
|
||||
const caches: Record<string, { promise?: Promise<{ default: ComponentType }> }> = { }
|
||||
const modules = Object.fromEntries (Object.entries (moduleLoads).map (([path, load]) => {
|
||||
caches[path] = { }
|
||||
return [path, vi.fn (() => caches[path].promise ??= load ())]
|
||||
|
||||
新しいイシューから参照
ユーザーをブロックする