コミットを比較
2 コミット
| 作成者 | SHA1 | 日付 | |
|---|---|---|---|
| baaf0752bc | |||
| 8ef94876b0 |
@@ -1,47 +0,0 @@
|
||||
class DeerjikistsController < ApplicationController
|
||||
def show
|
||||
platform = params[:platform].to_s.strip
|
||||
code = params[:code].to_s.strip
|
||||
return head :bad_request if platform.blank? || code.blank?
|
||||
|
||||
deerjikist = Deerjikist
|
||||
.joins(:tag)
|
||||
.includes(tag: :tag_name)
|
||||
.find_by(platform:, code:)
|
||||
if deerjikist
|
||||
render json: DeerjikistRepr.base(deerjikist)
|
||||
else
|
||||
head :not_found
|
||||
end
|
||||
end
|
||||
|
||||
def update
|
||||
return head :unauthorized unless current_user
|
||||
return head :forbidden unless current_user.gte_member?
|
||||
|
||||
platform = params[:platform].to_s.strip
|
||||
code = params[:code].to_s.strip
|
||||
tag_id = params[:tag_id].to_i
|
||||
return head :bad_request if platform.blank? || code.blank? || tag_id <= 0
|
||||
|
||||
deerjikist = Deerjikist.find_or_initialize_by(platform:, code:).tap do |d|
|
||||
d.tag_id = tag_id
|
||||
d.save!
|
||||
end
|
||||
|
||||
render json: DeerjikistRepr.base(deerjikist)
|
||||
end
|
||||
|
||||
def destroy
|
||||
return head :unauthorized unless current_user
|
||||
return head :forbidden unless current_user.gte_member?
|
||||
|
||||
platform = params[:platform].to_s.strip
|
||||
code = params[:code].to_s.strip
|
||||
return head :bad_request if platform.blank? || code.blank?
|
||||
|
||||
Deerjikist.find([platform, code]).destroy!
|
||||
|
||||
head :no_content
|
||||
end
|
||||
end
|
||||
@@ -1,14 +1,16 @@
|
||||
class NicoTagsController < ApplicationController
|
||||
TAG_JSON = { only: [:id, :category, :post_count], methods: [:name, :has_wiki] }.freeze
|
||||
|
||||
def index
|
||||
limit = (params[:limit] || 20).to_i
|
||||
cursor = params[:cursor].presence
|
||||
|
||||
q = Tag.nico_tags
|
||||
.includes(:tag_name, tag_name: :wiki_page, linked_tags: { tag_name: :wiki_page })
|
||||
.includes(:tag_name, linked_tags: :tag_name)
|
||||
.order(updated_at: :desc)
|
||||
q = q.where('tags.updated_at < ?', Time.iso8601(cursor)) if cursor
|
||||
|
||||
tags = q.limit(limit + 1).to_a
|
||||
tags = q.limit(limit + 1)
|
||||
|
||||
next_cursor = nil
|
||||
if tags.size > limit
|
||||
@@ -17,15 +19,15 @@ class NicoTagsController < ApplicationController
|
||||
end
|
||||
|
||||
render json: { tags: tags.map { |tag|
|
||||
TagRepr.base(tag).merge(linked_tags: tag.linked_tags.map { |lt|
|
||||
TagRepr.base(lt)
|
||||
tag.as_json(TAG_JSON).merge(linked_tags: tag.linked_tags.map { |lt|
|
||||
lt.as_json(TAG_JSON)
|
||||
})
|
||||
}, next_cursor: }
|
||||
end
|
||||
|
||||
def update
|
||||
return head :unauthorized unless current_user
|
||||
return head :forbidden unless current_user.gte_member?
|
||||
return head :forbidden unless current_user.member?
|
||||
|
||||
id = params[:id].to_i
|
||||
|
||||
@@ -39,6 +41,6 @@ class NicoTagsController < ApplicationController
|
||||
tag.linked_tags = linked_tags
|
||||
tag.save!
|
||||
|
||||
render json: tag.linked_tags.map { |t| TagRepr.base(t) }, status: :ok
|
||||
render json: tag.linked_tags.map { |t| t.as_json(TAG_JSON) }, status: :ok
|
||||
end
|
||||
end
|
||||
|
||||
@@ -2,88 +2,41 @@ class PostsController < ApplicationController
|
||||
Event = Struct.new(:post, :tag, :user, :change_type, :timestamp, keyword_init: true)
|
||||
|
||||
def index
|
||||
url = params[:url].presence
|
||||
title = params[:title].presence
|
||||
original_created_from = params[:original_created_from].presence
|
||||
original_created_to = params[:original_created_to].presence
|
||||
created_between = params[:created_from].presence, params[:created_to].presence
|
||||
updated_between = params[:updated_from].presence, params[:updated_to].presence
|
||||
|
||||
order = params[:order].to_s.split(':', 2).map(&:strip)
|
||||
unless order[0].in?(['title', 'url', 'original_created_at', 'created_at', 'updated_at'])
|
||||
order[0] = 'original_created_at'
|
||||
end
|
||||
unless order[1].in?(['asc', 'desc'])
|
||||
order[1] =
|
||||
if order[0].in?(['title', 'url'])
|
||||
'asc'
|
||||
else
|
||||
'desc'
|
||||
end
|
||||
end
|
||||
|
||||
page = (params[:page].presence || 1).to_i
|
||||
limit = (params[:limit].presence || 20).to_i
|
||||
cursor = params[:cursor].presence
|
||||
|
||||
page = 1 if page < 1
|
||||
limit = 1 if limit < 1
|
||||
|
||||
offset = (page - 1) * limit
|
||||
|
||||
pt_max_sql =
|
||||
PostTag
|
||||
.select('post_id, MAX(updated_at) AS max_updated_at')
|
||||
.group('post_id')
|
||||
.to_sql
|
||||
|
||||
updated_at_all_sql =
|
||||
'GREATEST(posts.updated_at,' +
|
||||
'COALESCE(pt_max.max_updated_at, posts.updated_at))'
|
||||
|
||||
sort_sql =
|
||||
'COALESCE(posts.original_created_before - INTERVAL 1 SECOND,' +
|
||||
'posts.original_created_from,' +
|
||||
'posts.created_at)'
|
||||
q =
|
||||
filtered_posts
|
||||
.joins("LEFT JOIN (#{ pt_max_sql }) pt_max ON pt_max.post_id = posts.id")
|
||||
.reselect('posts.*', Arel.sql("#{ updated_at_all_sql } AS updated_at_all"))
|
||||
.preload(tags: { tag_name: :wiki_page })
|
||||
.preload(tags: :tag_name)
|
||||
.with_attached_thumbnail
|
||||
|
||||
q = q.where('posts.url LIKE ?', "%#{ url }%") if url
|
||||
q = q.where('posts.title LIKE ?', "%#{ title }%") if title
|
||||
if original_created_from
|
||||
q = q.where('posts.original_created_before > ?', original_created_from)
|
||||
end
|
||||
if original_created_to
|
||||
q = q.where('posts.original_created_from <= ?', original_created_to)
|
||||
end
|
||||
q = q.where('posts.created_at >= ?', created_between[0]) if created_between[0]
|
||||
q = q.where('posts.created_at <= ?', created_between[1]) if created_between[1]
|
||||
if updated_between[0]
|
||||
q = q.where("#{ updated_at_all_sql } >= ?", updated_between[0])
|
||||
end
|
||||
if updated_between[1]
|
||||
q = q.where("#{ updated_at_all_sql } <= ?", updated_between[1])
|
||||
end
|
||||
|
||||
sort_sql =
|
||||
case order[0]
|
||||
when 'original_created_at'
|
||||
'COALESCE(posts.original_created_before - INTERVAL 1 MINUTE,' +
|
||||
'posts.original_created_from,' +
|
||||
'posts.created_at) '
|
||||
when 'updated_at'
|
||||
updated_at_all_sql
|
||||
.select("posts.*, #{ sort_sql } AS sort_ts")
|
||||
.order(Arel.sql("#{ sort_sql } DESC"))
|
||||
posts = (
|
||||
if cursor
|
||||
q.where("#{ sort_sql } < ?", Time.iso8601(cursor)).limit(limit + 1)
|
||||
else
|
||||
"posts.#{ order[0] }"
|
||||
end
|
||||
posts = q.order(Arel.sql("#{ sort_sql } #{ order[1] }, id #{ order[1] }"))
|
||||
.limit(limit)
|
||||
.offset(offset)
|
||||
.to_a
|
||||
q.limit(limit).offset(offset)
|
||||
end).to_a
|
||||
|
||||
q = q.except(:select, :order)
|
||||
next_cursor = nil
|
||||
if cursor && posts.length > limit
|
||||
next_cursor = posts.last.read_attribute('sort_ts').iso8601(6)
|
||||
posts = posts.first(limit)
|
||||
end
|
||||
|
||||
render json: { posts: posts.map { |post|
|
||||
PostRepr.base(post).merge(updated_at: post.updated_at_all).tap do |json|
|
||||
post.as_json(include: { tags: { only: [:id, :category, :post_count],
|
||||
methods: [:name, :has_wiki] } }).tap do |json|
|
||||
json['thumbnail'] =
|
||||
if post.thumbnail.attached?
|
||||
rails_storage_proxy_url(post.thumbnail, only_path: false)
|
||||
@@ -91,22 +44,27 @@ class PostsController < ApplicationController
|
||||
nil
|
||||
end
|
||||
end
|
||||
}, count: q.group_values.present? ? q.count.size : q.count }
|
||||
}, count: if filtered_posts.group_values.present?
|
||||
filtered_posts.count.size
|
||||
else
|
||||
filtered_posts.count
|
||||
end, next_cursor: }
|
||||
end
|
||||
|
||||
def random
|
||||
post = filtered_posts.preload(tags: { tag_name: :wiki_page })
|
||||
.order('RAND()')
|
||||
.first
|
||||
post = filtered_posts.preload(tags: :tag_name).order('RAND()').first
|
||||
return head :not_found unless post
|
||||
|
||||
viewed = current_user&.viewed?(post) || false
|
||||
|
||||
render json: PostRepr.base(post).merge(viewed:)
|
||||
render json: (post
|
||||
.as_json(include: { tags: { only: [:id, :category, :post_count],
|
||||
methods: [:name, :has_wiki] } })
|
||||
.merge(viewed:))
|
||||
end
|
||||
|
||||
def show
|
||||
post = Post.includes(tags: { tag_name: :wiki_page }).find_by(id: params[:id])
|
||||
post = Post.includes(tags: :tag_name).find(params[:id])
|
||||
return head :not_found unless post
|
||||
|
||||
viewed = current_user&.viewed?(post) || false
|
||||
@@ -121,13 +79,13 @@ class PostsController < ApplicationController
|
||||
|
||||
def create
|
||||
return head :unauthorized unless current_user
|
||||
return head :forbidden unless current_user.gte_member?
|
||||
return head :forbidden unless current_user.member?
|
||||
|
||||
# TODO: サイトに応じて thumbnail_base 設定
|
||||
title = params[:title].presence
|
||||
url = params[:url]
|
||||
thumbnail = params[:thumbnail]
|
||||
tag_names = params[:tags].to_s.split
|
||||
tag_names = params[:tags].to_s.split(' ')
|
||||
original_created_from = params[:original_created_from]
|
||||
original_created_before = params[:original_created_before]
|
||||
|
||||
@@ -141,7 +99,9 @@ class PostsController < ApplicationController
|
||||
sync_post_tags!(post, tags)
|
||||
|
||||
post.reload
|
||||
render json: PostRepr.base(post), status: :created
|
||||
render json: post.as_json(include: { tags: { only: [:id, :category, :post_count],
|
||||
methods: [:name, :has_wiki] } }),
|
||||
status: :created
|
||||
else
|
||||
render json: { errors: post.errors.full_messages }, status: :unprocessable_entity
|
||||
end
|
||||
@@ -165,10 +125,10 @@ class PostsController < ApplicationController
|
||||
|
||||
def update
|
||||
return head :unauthorized unless current_user
|
||||
return head :forbidden unless current_user.gte_member?
|
||||
return head :forbidden unless current_user.member?
|
||||
|
||||
title = params[:title].presence
|
||||
tag_names = params[:tags].to_s.split
|
||||
tag_names = params[:tags].to_s.split(' ')
|
||||
original_created_from = params[:original_created_from]
|
||||
original_created_before = params[:original_created_before]
|
||||
|
||||
@@ -191,7 +151,7 @@ class PostsController < ApplicationController
|
||||
end
|
||||
|
||||
def changes
|
||||
id = params[:id].presence
|
||||
id = params[:id]
|
||||
page = (params[:page].presence || 1).to_i
|
||||
limit = (params[:limit].presence || 20).to_i
|
||||
|
||||
@@ -202,40 +162,36 @@ class PostsController < ApplicationController
|
||||
|
||||
pts = PostTag.with_discarded
|
||||
pts = pts.where(post_id: id) if id.present?
|
||||
pts = pts.includes(:post, :created_user, :deleted_user,
|
||||
tag: { tag_name: :wiki_page })
|
||||
pts = pts.includes(:post, { tag: :tag_name }, :created_user, :deleted_user)
|
||||
|
||||
events = []
|
||||
pts.each do |pt|
|
||||
tag = TagRepr.base(pt.tag)
|
||||
post = pt.post
|
||||
|
||||
events << Event.new(
|
||||
post:,
|
||||
tag:,
|
||||
user: pt.created_user && { id: pt.created_user.id, name: pt.created_user.name },
|
||||
change_type: 'add',
|
||||
timestamp: pt.created_at)
|
||||
post: pt.post,
|
||||
tag: pt.tag.as_json(only: [:id, :category], methods: [:name, :has_wiki]),
|
||||
user: pt.created_user && { id: pt.created_user.id, name: pt.created_user.name },
|
||||
change_type: 'add',
|
||||
timestamp: pt.created_at)
|
||||
|
||||
if pt.discarded_at
|
||||
events << Event.new(
|
||||
post:,
|
||||
tag:,
|
||||
user: pt.deleted_user && { id: pt.deleted_user.id, name: pt.deleted_user.name },
|
||||
change_type: 'remove',
|
||||
timestamp: pt.discarded_at)
|
||||
post: pt.post,
|
||||
tag: pt.tag.as_json(only: [:id, :category], methods: [:name, :has_wiki]),
|
||||
user: pt.deleted_user && { id: pt.deleted_user.id, name: pt.deleted_user.name },
|
||||
change_type: 'remove',
|
||||
timestamp: pt.discarded_at)
|
||||
end
|
||||
end
|
||||
events.sort_by!(&:timestamp)
|
||||
events.reverse!
|
||||
|
||||
render json: { changes: (events.slice(offset, limit) || []).as_json, count: events.size }
|
||||
render json: { changes: events.slice(offset, limit).as_json, count: events.size }
|
||||
end
|
||||
|
||||
private
|
||||
|
||||
def filtered_posts
|
||||
tag_names = params[:tags].to_s.split
|
||||
tag_names = params[:tags].to_s.split(' ')
|
||||
match_type = params[:match]
|
||||
if tag_names.present?
|
||||
filter_posts_by_tags(tag_names, match_type)
|
||||
@@ -306,7 +262,8 @@ class PostsController < ApplicationController
|
||||
return nil unless tag
|
||||
|
||||
if path.include?(tag_id)
|
||||
return TagRepr.base(tag).merge(children: [])
|
||||
return tag.as_json(only: [:id, :category, :post_count],
|
||||
methods: [:name, :has_wiki]).merge(children: [])
|
||||
end
|
||||
|
||||
if memo.key?(tag_id)
|
||||
@@ -318,7 +275,8 @@ class PostsController < ApplicationController
|
||||
|
||||
children = child_ids.filter_map { |cid| build_node.(cid, new_path) }
|
||||
|
||||
memo[tag_id] = TagRepr.base(tag).merge(children:)
|
||||
memo[tag_id] = tag.as_json(only: [:id, :category, :post_count],
|
||||
methods: [:name, :has_wiki]).merge(children:)
|
||||
end
|
||||
|
||||
root_ids.filter_map { |id| build_node.call(id, []) }
|
||||
|
||||
@@ -4,16 +4,12 @@ class TagsController < ApplicationController
|
||||
|
||||
tags =
|
||||
if post_id.present?
|
||||
Tag.joins(:posts, :tag_name)
|
||||
Tag.joins(:posts).where(posts: { id: post_id })
|
||||
else
|
||||
Tag.joins(:tag_name)
|
||||
Tag.all
|
||||
end
|
||||
.includes(:tag_name, tag_name: :wiki_page)
|
||||
if post_id.present?
|
||||
tags = tags.where(posts: { id: post_id })
|
||||
end
|
||||
|
||||
render json: TagRepr.base(tags)
|
||||
render json: tags.as_json(only: [:id, :category, :post_count], methods: [:name, :has_wiki])
|
||||
end
|
||||
|
||||
def autocomplete
|
||||
@@ -37,8 +33,7 @@ class TagsController < ApplicationController
|
||||
matched_alias_by_tag_name_id[canonical_id] ||= alias_name
|
||||
end
|
||||
|
||||
base = Tag.joins(:tag_name)
|
||||
.includes(:tag_name, tag_name: :wiki_page)
|
||||
base = Tag.joins(:tag_name).includes(:tag_name)
|
||||
base = base.where('tags.post_count > 0') if present_only
|
||||
|
||||
canonical_hit =
|
||||
@@ -57,16 +52,15 @@ class TagsController < ApplicationController
|
||||
tags = tags.order(Arel.sql('post_count DESC, tag_names.name')).limit(20).to_a
|
||||
|
||||
render json: tags.map { |tag|
|
||||
TagRepr.base(tag).merge(matched_alias: matched_alias_by_tag_name_id[tag.tag_name_id])
|
||||
tag.as_json(only: [:id, :category, :post_count], methods: [:name, :has_wiki])
|
||||
.merge(matched_alias: matched_alias_by_tag_name_id[tag.tag_name_id])
|
||||
}
|
||||
end
|
||||
|
||||
def show
|
||||
tag = Tag.joins(:tag_name)
|
||||
.includes(:tag_name, tag_name: :wiki_page)
|
||||
.find_by(id: params[:id])
|
||||
tag = Tag.find_by(id: params[:id])
|
||||
if tag
|
||||
render json: TagRepr.base(tag)
|
||||
render json: tag.as_json(only: [:id, :category, :post_count], methods: [:name, :has_wiki])
|
||||
else
|
||||
head :not_found
|
||||
end
|
||||
@@ -76,40 +70,17 @@ class TagsController < ApplicationController
|
||||
name = params[:name].to_s.strip
|
||||
return head :bad_request if name.blank?
|
||||
|
||||
tag = Tag.joins(:tag_name)
|
||||
.includes(:tag_name, tag_name: :wiki_page)
|
||||
.find_by(tag_names: { name: })
|
||||
tag = Tag.joins(:tag_name).includes(:tag_name).find_by(tag_names: { name: })
|
||||
if tag
|
||||
render json: TagRepr.base(tag)
|
||||
render json: tag.as_json(only: [:id, :category, :post_count], methods: [:name, :has_wiki])
|
||||
else
|
||||
head :not_found
|
||||
end
|
||||
end
|
||||
|
||||
def deerjikists
|
||||
tag = Tag.joins(:tag_name)
|
||||
.includes(:tag_name, tag_name: :wiki_page)
|
||||
.find_by(id: params[:id])
|
||||
return head :not_found unless tag
|
||||
|
||||
render json: DeerjikistRepr.many(tag.deerjikists)
|
||||
end
|
||||
|
||||
def deerjikists_by_name
|
||||
name = params[:name].to_s.strip
|
||||
return head :bad_request if name.blank?
|
||||
|
||||
tag = Tag.joins(:tag_name)
|
||||
.includes(:tag_name, tag_name: :wiki_page)
|
||||
.find_by(tag_names: { name: })
|
||||
return head :not_found unless tag
|
||||
|
||||
render json: DeerjikistRepr.many(tag.deerjikists)
|
||||
end
|
||||
|
||||
def update
|
||||
return head :unauthorized unless current_user
|
||||
return head :forbidden unless current_user.gte_member?
|
||||
return head :forbidden unless current_user.member?
|
||||
|
||||
name = params[:name].presence
|
||||
category = params[:category].presence
|
||||
@@ -124,6 +95,6 @@ class TagsController < ApplicationController
|
||||
tag.update!(category:)
|
||||
end
|
||||
|
||||
render json: TagRepr.base(tag)
|
||||
render json: tag.as_json(methods: [:name])
|
||||
end
|
||||
end
|
||||
|
||||
@@ -3,19 +3,15 @@ class WikiPagesController < ApplicationController
|
||||
|
||||
def index
|
||||
title = params[:title].to_s.strip
|
||||
if title.blank?
|
||||
return render json: WikiPageRepr.base(WikiPage.joins(:tag_name).includes(:tag_name))
|
||||
end
|
||||
return render json: WikiPage.all.as_json(methods: [:title]) if title.blank?
|
||||
|
||||
q = WikiPage.joins(:tag_name).includes(:tag_name)
|
||||
.where('tag_names.name LIKE ?', "%#{ WikiPage.sanitize_sql_like(title) }%")
|
||||
render json: WikiPageRepr.base(q.limit(20))
|
||||
render json: q.limit(20).as_json(methods: [:title])
|
||||
end
|
||||
|
||||
def show
|
||||
page = WikiPage.joins(:tag_name)
|
||||
.includes(:tag_name)
|
||||
.find_by(id: params[:id])
|
||||
page = WikiPage.find_by(id: params[:id])
|
||||
render_wiki_page_or_404 page
|
||||
end
|
||||
|
||||
@@ -23,7 +19,7 @@ class WikiPagesController < ApplicationController
|
||||
title = params[:title].to_s.strip
|
||||
page = WikiPage.joins(:tag_name)
|
||||
.includes(:tag_name)
|
||||
.find_by(tag_name: { name: title })
|
||||
.find_by(tag_names: { name: title })
|
||||
render_wiki_page_or_404 page
|
||||
end
|
||||
|
||||
@@ -51,7 +47,7 @@ class WikiPagesController < ApplicationController
|
||||
from = params[:from].presence
|
||||
to = params[:to].presence
|
||||
|
||||
page = WikiPage.joins(:tag_name).includes(:tag_name).find(id)
|
||||
page = WikiPage.find(id)
|
||||
|
||||
from_rev = from && page.wiki_revisions.find(from)
|
||||
to_rev = to ? page.wiki_revisions.find(to) : page.current_revision
|
||||
@@ -83,20 +79,20 @@ class WikiPagesController < ApplicationController
|
||||
|
||||
def create
|
||||
return head :unauthorized unless current_user
|
||||
return head :forbidden unless current_user.gte_member?
|
||||
return head :forbidden unless current_user.member?
|
||||
|
||||
name = params[:title]&.strip
|
||||
title = params[:title]&.strip
|
||||
body = params[:body].to_s
|
||||
|
||||
return head :unprocessable_entity if name.blank? || body.blank?
|
||||
return head :unprocessable_entity if title.blank? || body.blank?
|
||||
|
||||
page = WikiPage.new(title:, created_user: current_user, updated_user: current_user)
|
||||
|
||||
tag_name = TagName.find_or_create_by!(name:)
|
||||
page = WikiPage.new(tag_name:, created_user: current_user, updated_user: current_user)
|
||||
if page.save
|
||||
message = params[:message].presence
|
||||
Wiki::Commit.content!(page:, body:, created_user: current_user, message:)
|
||||
|
||||
render json: WikiPageRepr.base(page), status: :created
|
||||
render json: page.as_json(methods: [:title]), status: :created
|
||||
else
|
||||
render json: { errors: page.errors.full_messages },
|
||||
status: :unprocessable_entity
|
||||
@@ -105,7 +101,7 @@ class WikiPagesController < ApplicationController
|
||||
|
||||
def update
|
||||
return head :unauthorized unless current_user
|
||||
return head :forbidden unless current_user.gte_member?
|
||||
return head :forbidden unless current_user.member?
|
||||
|
||||
title = params[:title]&.strip
|
||||
body = params[:body].to_s
|
||||
@@ -135,9 +131,7 @@ class WikiPagesController < ApplicationController
|
||||
|
||||
def changes
|
||||
id = params[:id].presence
|
||||
q = WikiRevision.joins(wiki_page: :tag_name)
|
||||
.includes(:created_user, wiki_page: :tag_name)
|
||||
.order(id: :desc)
|
||||
q = WikiRevision.includes(:wiki_page, :created_user).order(id: :desc)
|
||||
q = q.where(wiki_page_id: id) if id
|
||||
|
||||
render json: q.limit(200).map { |rev|
|
||||
@@ -145,7 +139,7 @@ class WikiPagesController < ApplicationController
|
||||
pred: rev.base_revision_id,
|
||||
succ: nil,
|
||||
wiki_page: { id: rev.wiki_page_id, title: rev.wiki_page.title },
|
||||
user: rev.created_user && { id: rev.created_user.id, name: rev.created_user.name },
|
||||
user: { id: rev.created_user.id, name: rev.created_user.name },
|
||||
kind: rev.kind,
|
||||
message: rev.message,
|
||||
timestamp: rev.created_at }
|
||||
@@ -172,7 +166,8 @@ class WikiPagesController < ApplicationController
|
||||
succ = page.succ_revision_id(revision_id)
|
||||
updated_at = rev.created_at
|
||||
|
||||
render json: WikiPageRepr.base(page).merge(body:, revision_id:, pred:, succ:, updated_at:)
|
||||
render json: page.as_json(methods: [:title])
|
||||
.merge(body:, revision_id:, pred:, succ:, updated_at:)
|
||||
end
|
||||
|
||||
def find_revision page
|
||||
|
||||
@@ -1,21 +0,0 @@
|
||||
class Deerjikist < ApplicationRecord
|
||||
self.primary_key = :platform, :code
|
||||
|
||||
belongs_to :tag
|
||||
|
||||
validates :platform, presence: true
|
||||
validates :code, presence: true
|
||||
validates :tag_id, presence: true
|
||||
|
||||
validate :tag_must_be_deerjikist
|
||||
|
||||
enum :platform, nico: 'nico', youtube: 'youtube'
|
||||
|
||||
private
|
||||
|
||||
def tag_must_be_deerjikist
|
||||
if tag && !(tag.deerjikist?)
|
||||
errors.add :tag, 'タグはニジラー・カテゴリである必要があります.'
|
||||
end
|
||||
end
|
||||
end
|
||||
@@ -30,15 +30,13 @@ class Post < ApplicationRecord
|
||||
super(options).merge(thumbnail: nil)
|
||||
end
|
||||
|
||||
def related limit: nil
|
||||
ids = post_similarities.order(cos: :desc)
|
||||
def related(limit: nil)
|
||||
ids = post_similarities.select(:target_post_id).order(cos: :desc)
|
||||
ids = ids.limit(limit) if limit
|
||||
ids = ids.pluck(:target_post_id)
|
||||
return Post.none if ids.empty?
|
||||
return [] if ids.empty?
|
||||
|
||||
Post.where(id: ids)
|
||||
.with_attached_thumbnail
|
||||
.order(Arel.sql("FIELD(posts.id, #{ ids.join(',') })"))
|
||||
Post.where(id: ids).order(Arel.sql("FIELD(id, #{ ids.join(',') })"))
|
||||
end
|
||||
|
||||
def resized_thumbnail!
|
||||
|
||||
+18
-68
@@ -23,14 +23,8 @@ class Tag < ApplicationRecord
|
||||
has_many :parents, through: :reversed_tag_implications, source: :parent_tag
|
||||
|
||||
has_many :tag_similarities, dependent: :delete_all
|
||||
has_many :tag_similarities_as_target,
|
||||
class_name: 'TagSimilarity', foreign_key: :target_tag_id, dependent: :delete_all
|
||||
|
||||
has_many :deerjikists, dependent: :delete_all
|
||||
|
||||
belongs_to :tag_name
|
||||
delegate :wiki_page, to: :tag_name
|
||||
|
||||
delegate :name, to: :tag_name, allow_nil: true
|
||||
validates :tag_name, presence: true
|
||||
|
||||
@@ -46,27 +40,24 @@ class Tag < ApplicationRecord
|
||||
|
||||
validate :nico_tag_name_must_start_with_nico
|
||||
validate :tag_name_must_be_canonical
|
||||
validate :category_must_be_deerjikist_with_deerjikists
|
||||
|
||||
scope :nico_tags, -> { nico }
|
||||
scope :nico_tags, -> { where(category: :nico) }
|
||||
|
||||
CATEGORY_PREFIXES = {
|
||||
'general:' => :general,
|
||||
'gen:' => :general,
|
||||
'deerjikist:' => :deerjikist,
|
||||
'djk:' => :deerjikist,
|
||||
'meme:' => :meme,
|
||||
'character:' => :character,
|
||||
'chr:' => :character,
|
||||
'material:' => :material,
|
||||
'mtr:' => :material,
|
||||
'meta:' => :meta }.freeze
|
||||
'gen:' => :general,
|
||||
'djk:' => :deerjikist,
|
||||
'meme:' => :meme,
|
||||
'chr:' => :character,
|
||||
'mtr:' => :material,
|
||||
'meta:' => :meta }.freeze
|
||||
|
||||
def name= val
|
||||
(self.tag_name ||= build_tag_name).name = val
|
||||
end
|
||||
|
||||
def has_wiki = wiki_page.present?
|
||||
def has_wiki
|
||||
tag_name&.wiki_page.present?
|
||||
end
|
||||
|
||||
def self.tagme
|
||||
@tagme ||= find_or_create_by_tag_name!('タグ希望', category: :meta)
|
||||
@@ -76,10 +67,6 @@ class Tag < ApplicationRecord
|
||||
@bot ||= find_or_create_by_tag_name!('bot操作', category: :meta)
|
||||
end
|
||||
|
||||
def self.no_deerjikist
|
||||
@no_deerjikist ||= find_or_create_by_tag_name!('ニジラー情報不詳', category: :meta)
|
||||
end
|
||||
|
||||
def self.video
|
||||
@video ||= find_or_create_by_tag_name!('動画', category: :meta)
|
||||
end
|
||||
@@ -89,20 +76,21 @@ class Tag < ApplicationRecord
|
||||
end
|
||||
|
||||
def self.normalise_tags tag_names, with_tagme: true, deny_nico: true
|
||||
if deny_nico && tag_names.any? { |n| n.downcase.start_with?('nico:') }
|
||||
if deny_nico && tag_names.any? { |n| n.start_with?('nico:') }
|
||||
raise NicoTagNormalisationError
|
||||
end
|
||||
|
||||
tags = tag_names.map do |name|
|
||||
pf, cat = CATEGORY_PREFIXES.find { |p, _| name.downcase.start_with?(p) } || ['', nil]
|
||||
name = TagName.canonicalise(name.sub(/\A#{ pf }/i, '')).first
|
||||
pf, cat = CATEGORY_PREFIXES.find { |p, _| name.start_with?(p) } || ['', nil]
|
||||
name = TagName.canonicalise(name.delete_prefix(pf)).first
|
||||
find_or_create_by_tag_name!(name, category: (cat || :general)).tap do |tag|
|
||||
tag.update!(category: cat) if cat && tag.category != cat
|
||||
if cat && tag.category != cat
|
||||
tag.update!(category: cat)
|
||||
end
|
||||
end
|
||||
end
|
||||
|
||||
tags << Tag.tagme if with_tagme && tags.size < 10 && tags.none?(Tag.tagme)
|
||||
tags << Tag.no_deerjikist if tags.all? { |t| !(t.deerjikist?) }
|
||||
tags.uniq(&:id)
|
||||
end
|
||||
|
||||
@@ -140,44 +128,12 @@ class Tag < ApplicationRecord
|
||||
retry
|
||||
end
|
||||
|
||||
def self.merge_tags! target_tag, source_tags
|
||||
target_tag => Tag
|
||||
|
||||
Tag.transaction do
|
||||
Array(source_tags).compact.uniq.each do |st|
|
||||
st => Tag
|
||||
|
||||
next if st == target_tag
|
||||
|
||||
st.post_tags.find_each do |pt|
|
||||
if PostTag.kept.exists?(post_id: pt.post_id, tag_id: target_tag.id)
|
||||
pt.discard_by!(nil)
|
||||
# discard 後の update! は禁止なので DB を直に更新
|
||||
pt.update_columns(tag_id: target_tag.id, updated_at: Time.current)
|
||||
else
|
||||
pt.update!(tag: target_tag)
|
||||
end
|
||||
end
|
||||
|
||||
tag_name = st.tag_name
|
||||
st.destroy!
|
||||
tag_name.reload
|
||||
tag_name.update!(canonical: target_tag.tag_name)
|
||||
end
|
||||
|
||||
# 投稿件数を再集計
|
||||
target_tag.update_columns(post_count: PostTag.kept.where(tag: target_tag).count)
|
||||
end
|
||||
|
||||
target_tag.reload
|
||||
end
|
||||
|
||||
private
|
||||
|
||||
def nico_tag_name_must_start_with_nico
|
||||
n = name.to_s
|
||||
if ((nico? && !(n.downcase.start_with?('nico:'))) ||
|
||||
(!(nico?) && n.downcase.start_with?('nico:')))
|
||||
if ((category == 'nico' && !(n.start_with?('nico:'))) ||
|
||||
(category != 'nico' && n.start_with?('nico:')))
|
||||
errors.add :name, 'ニコニコ・タグの命名規則に反してゐます.'
|
||||
end
|
||||
end
|
||||
@@ -187,10 +143,4 @@ class Tag < ApplicationRecord
|
||||
errors.add :tag_name, 'tag_names へは実体を示す必要があります.'
|
||||
end
|
||||
end
|
||||
|
||||
def category_must_be_deerjikist_with_deerjikists
|
||||
if !(deerjikist?) && deerjikists.exists?
|
||||
errors.add :category, 'ニジラーと紐づいてゐるタグはニジラー・カテゴリである必要があります.'
|
||||
end
|
||||
end
|
||||
end
|
||||
|
||||
@@ -1,23 +1,29 @@
|
||||
class User < ApplicationRecord
|
||||
enum :role, guest: 'guest', member: 'member', admin: 'admin'
|
||||
enum :role, { guest: 'guest', member: 'member', admin: 'admin' }
|
||||
|
||||
validates :name, length: { maximum: 255 }
|
||||
validates :inheritance_code, presence: true, length: { maximum: 64 }
|
||||
validates :role, presence: true, inclusion: { in: roles.keys }
|
||||
validates :banned, inclusion: { in: [true, false] }
|
||||
|
||||
has_many :created_posts,
|
||||
class_name: 'Post', foreign_key: :uploaded_user_id, dependent: :nullify
|
||||
has_many :posts
|
||||
has_many :settings
|
||||
has_many :user_ips, dependent: :destroy
|
||||
has_many :ip_addresses, through: :user_ips
|
||||
has_many :user_post_views, dependent: :destroy
|
||||
has_many :viewed_posts, through: :user_post_views, source: :post
|
||||
has_many :created_wiki_pages,
|
||||
class_name: 'WikiPage', foreign_key: :created_user_id, dependent: :nullify
|
||||
has_many :updated_wiki_pages,
|
||||
class_name: 'WikiPage', foreign_key: :updated_user_id, dependent: :nullify
|
||||
has_many :created_wiki_pages, class_name: 'WikiPage', foreign_key: 'created_user_id', dependent: :nullify
|
||||
has_many :updated_wiki_pages, class_name: 'WikiPage', foreign_key: 'updated_user_id', dependent: :nullify
|
||||
|
||||
def viewed?(post) = user_post_views.exists?(post_id: post.id)
|
||||
def gte_member? = member? || admin?
|
||||
def viewed? post
|
||||
user_post_views.exists? post_id: post.id
|
||||
end
|
||||
|
||||
def member?
|
||||
['member', 'admin'].include?(role)
|
||||
end
|
||||
|
||||
def admin?
|
||||
role == 'admin'
|
||||
end
|
||||
end
|
||||
|
||||
@@ -8,7 +8,7 @@ class WikiLine < ApplicationRecord
|
||||
sha = Digest::SHA256.hexdigest(body)
|
||||
now = Time.current
|
||||
|
||||
upsert(sha256: sha, body:, created_at: now, updated_at: now)
|
||||
upsert({ sha256: sha, body:, created_at: now, updated_at: now })
|
||||
|
||||
find_by!(sha256: sha)
|
||||
end
|
||||
|
||||
@@ -14,13 +14,17 @@ class WikiPage < ApplicationRecord
|
||||
belongs_to :tag_name
|
||||
validates :tag_name, presence: true
|
||||
|
||||
def title = tag_name.name
|
||||
def title
|
||||
tag_name.name
|
||||
end
|
||||
|
||||
def title= val
|
||||
(self.tag_name ||= build_tag_name).name = val
|
||||
end
|
||||
|
||||
def current_revision = wiki_revisions.order(id: :desc).first
|
||||
def current_revision
|
||||
wiki_revisions.order(id: :desc).first
|
||||
end
|
||||
|
||||
def body
|
||||
rev = current_revision
|
||||
@@ -45,8 +49,11 @@ class WikiPage < ApplicationRecord
|
||||
page
|
||||
end
|
||||
|
||||
def pred_revision_id(revision_id) =
|
||||
wiki_revisions.where('id < ?', revision_id).order(id: :desc).limit(1).pick(:id)
|
||||
def succ_revision_id(revision_id) =
|
||||
wiki_revisions.where('id > ?', revision_id).order(id: :asc).limit(1).pick(:id)
|
||||
def pred_revision_id revision_id
|
||||
wiki_revisions.where('id < ?', revision_id).order(id: :desc).limit(1).pick(:id)
|
||||
end
|
||||
|
||||
def succ_revision_id revision_id
|
||||
wiki_revisions.where('id > ?', revision_id).order(id: :asc).limit(1).pick(:id)
|
||||
end
|
||||
end
|
||||
|
||||
@@ -7,7 +7,7 @@ class WikiRevision < ApplicationRecord
|
||||
has_many :wiki_revision_lines, dependent: :delete_all
|
||||
has_many :wiki_lines, through: :wiki_revision_lines
|
||||
|
||||
enum :kind, content: 0, redirect: 1
|
||||
enum :kind, { content: 0, redirect: 1 }
|
||||
|
||||
validates :kind, presence: true
|
||||
validates :lines_count, numericality: { only_integer: true, greater_than_or_equal_to: 0 }
|
||||
|
||||
@@ -1,16 +0,0 @@
|
||||
# frozen_string_literal: true
|
||||
|
||||
|
||||
module DeerjikistRepr
|
||||
BASE = { only: [:platform, :code], include: { tag: TagRepr::BASE } }.freeze
|
||||
|
||||
module_function
|
||||
|
||||
def base deerjikist
|
||||
deerjikist.as_json(BASE)
|
||||
end
|
||||
|
||||
def many deerjikists
|
||||
deerjikists.map { |d| base(d) }
|
||||
end
|
||||
end
|
||||
@@ -1,16 +0,0 @@
|
||||
# frozen_string_literal: true
|
||||
|
||||
|
||||
module PostRepr
|
||||
BASE = { include: { tags: TagRepr::BASE } }.freeze
|
||||
|
||||
module_function
|
||||
|
||||
def base post
|
||||
post.as_json(BASE)
|
||||
end
|
||||
|
||||
def many posts
|
||||
posts.map { |p| base(p) }
|
||||
end
|
||||
end
|
||||
@@ -1,16 +0,0 @@
|
||||
# frozen_string_literal: true
|
||||
|
||||
|
||||
module TagRepr
|
||||
BASE = { only: [:id, :category, :post_count], methods: [:name, :has_wiki] }.freeze
|
||||
|
||||
module_function
|
||||
|
||||
def base tag
|
||||
tag.as_json(BASE)
|
||||
end
|
||||
|
||||
def many tags
|
||||
tags.map { |t| base(t) }
|
||||
end
|
||||
end
|
||||
@@ -1,16 +0,0 @@
|
||||
# frozen_string_literal: true
|
||||
|
||||
|
||||
module WikiPageRepr
|
||||
BASE = { methods: [:title] }.freeze
|
||||
|
||||
module_function
|
||||
|
||||
def base wiki_page
|
||||
wiki_page.as_json(BASE)
|
||||
end
|
||||
|
||||
def many wiki_pages
|
||||
wiki_pages.map { |p| base(p) }
|
||||
end
|
||||
end
|
||||
+1
-19
@@ -9,15 +9,7 @@ Rails.application.routes.draw do
|
||||
resources :tags, only: [:index, :show, :update] do
|
||||
collection do
|
||||
get :autocomplete
|
||||
|
||||
scope :name do
|
||||
get ':name/deerjikists', action: :deerjikists_by_name
|
||||
get ':name', action: :show_by_name
|
||||
end
|
||||
end
|
||||
|
||||
member do
|
||||
get :deerjikists
|
||||
get 'name/:name', action: :show_by_name
|
||||
end
|
||||
end
|
||||
|
||||
@@ -62,14 +54,4 @@ Rails.application.routes.draw do
|
||||
post 'code/renew', action: :renew
|
||||
end
|
||||
end
|
||||
|
||||
resources :deerjikists, only: [] do
|
||||
collection do
|
||||
scope ':platform/:code' do
|
||||
get '', action: :show
|
||||
put '', action: :update
|
||||
delete '', action: :destroy
|
||||
end
|
||||
end
|
||||
end
|
||||
end
|
||||
|
||||
@@ -1,5 +1,3 @@
|
||||
class AddUniqueIndexToIpAddresses < ActiveRecord::Migration[8.0]
|
||||
def change
|
||||
add_index :ip_addresses, :ip_address, unique: true, name: 'index_ip_addresses_on_ip_address'
|
||||
end
|
||||
add_index :ip_addresses, :ip_address, unique: true, name: 'index_ip_addresses_on_ip_address'
|
||||
end
|
||||
|
||||
@@ -1,10 +0,0 @@
|
||||
class CreateDeerjikists < ActiveRecord::Migration[8.0]
|
||||
def change
|
||||
create_table :deerjikists, primary_key: [:platform, :code] do |t|
|
||||
t.string :platform, null: false, limit: 16
|
||||
t.string :code, null: false
|
||||
t.references :tag, null: false
|
||||
t.timestamps
|
||||
end
|
||||
end
|
||||
end
|
||||
生成ファイル
+1
-10
@@ -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_03_03_122700) do
|
||||
ActiveRecord::Schema[8.0].define(version: 2026_01_27_005300) 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
|
||||
@@ -39,15 +39,6 @@ ActiveRecord::Schema[8.0].define(version: 2026_03_03_122700) do
|
||||
t.index ["blob_id", "variation_digest"], name: "index_active_storage_variant_records_uniqueness", unique: true
|
||||
end
|
||||
|
||||
create_table "deerjikists", primary_key: ["platform", "code"], charset: "utf8mb4", collation: "utf8mb4_0900_ai_ci", force: :cascade do |t|
|
||||
t.string "platform", limit: 16, null: false
|
||||
t.string "code", null: false
|
||||
t.bigint "tag_id", null: false
|
||||
t.datetime "created_at", null: false
|
||||
t.datetime "updated_at", null: false
|
||||
t.index ["tag_id"], name: "index_deerjikists_on_tag_id"
|
||||
end
|
||||
|
||||
create_table "ip_addresses", charset: "utf8mb4", collation: "utf8mb4_0900_ai_ci", force: :cascade do |t|
|
||||
t.binary "ip_address", limit: 16, null: false
|
||||
t.boolean "banned", default: false, null: false
|
||||
|
||||
@@ -2,9 +2,9 @@ namespace :nico do
|
||||
desc 'ニコニコ DB 同期'
|
||||
task sync: :environment do
|
||||
require 'json'
|
||||
require 'nokogiri'
|
||||
require 'open-uri'
|
||||
require 'open3'
|
||||
require 'open-uri'
|
||||
require 'nokogiri'
|
||||
require 'set'
|
||||
require 'time'
|
||||
|
||||
@@ -15,12 +15,12 @@ namespace :nico do
|
||||
doc.at('meta[name="thumbnail"]')&.[]('content').presence
|
||||
end
|
||||
|
||||
def sync_post_tags! post, desired_tag_ids, current_tag_ids: nil
|
||||
current_tag_ids ||= PostTag.kept.where(post_id: post.id).pluck(:tag_id).to_set
|
||||
desired_tag_ids = desired_tag_ids.compact.to_set
|
||||
def sync_post_tags! post, desired_tag_ids, current_ids: nil
|
||||
current_ids ||= PostTag.kept.where(post_id: post.id).pluck(:tag_id).to_set
|
||||
desired_ids = desired_tag_ids.compact.to_set
|
||||
|
||||
to_add = desired_tag_ids - current_tag_ids
|
||||
to_remove = current_tag_ids - desired_tag_ids
|
||||
to_add = desired_ids - current_ids
|
||||
to_remove = current_ids - desired_ids
|
||||
|
||||
Tag.where(id: to_add.to_a).find_each do |tag|
|
||||
begin
|
||||
@@ -42,14 +42,12 @@ namespace :nico do
|
||||
{ 'MYSQL_USER' => mysql_user, 'MYSQL_PASS' => mysql_pass },
|
||||
'python3', "#{ nizika_nico_path }/get_videos.py")
|
||||
|
||||
unless status.success?
|
||||
warn stderr
|
||||
abort
|
||||
end
|
||||
abort unless status.success?
|
||||
|
||||
data = JSON.parse(stdout)
|
||||
data.each do |datum|
|
||||
code = datum['code']
|
||||
|
||||
post =
|
||||
Post
|
||||
.where('url REGEXP ?', "nicovideo\\.jp/watch/#{ Regexp.escape(code) }([^0-9]|$)")
|
||||
@@ -96,50 +94,32 @@ namespace :nico do
|
||||
sync_post_tags!(post, [Tag.tagme.id, Tag.bot.id, Tag.niconico.id, Tag.video.id])
|
||||
end
|
||||
|
||||
tags = post.tags
|
||||
# 既存のタグ Id. 集合
|
||||
kept_tag_ids = tags.pluck(:id).to_set
|
||||
# うち内部タグ Id. 集合
|
||||
kept_non_nico_tag_ids = tags.not_nico.pluck(:id).to_set
|
||||
|
||||
# 記載すべき外部タグ Id. および連携される内部タグ Id. のリスト
|
||||
desired_nico_tag_based_ids = []
|
||||
# 記載すべき内部タグ Id. のリスト
|
||||
desired_non_nico_tag_ids = []
|
||||
kept_ids = PostTag.kept.where(post_id: post.id).pluck(:tag_id).to_set
|
||||
kept_non_nico_ids = post.tags.where.not(category: 'nico').pluck(:id).to_set
|
||||
|
||||
desired_nico_ids = []
|
||||
desired_non_nico_ids = []
|
||||
datum['tags'].each do |raw|
|
||||
name = "nico:#{ raw }"
|
||||
tag = Tag.find_or_create_by_tag_name!(name, category: :nico)
|
||||
desired_nico_tag_based_ids << tag.id
|
||||
|
||||
# 新たに記載される外部タグと連携される内部タグを記載
|
||||
unless tag.id.in?(kept_tag_ids)
|
||||
tag = Tag.find_or_create_by_tag_name!(name, category: 'nico')
|
||||
desired_nico_ids << tag.id
|
||||
unless tag.id.in?(kept_ids)
|
||||
linked_ids = tag.linked_tags.pluck(:id)
|
||||
desired_non_nico_tag_ids.concat(linked_ids)
|
||||
desired_nico_tag_based_ids.concat(linked_ids)
|
||||
desired_non_nico_ids.concat(linked_ids)
|
||||
desired_nico_ids.concat(linked_ids)
|
||||
end
|
||||
end
|
||||
desired_nico_ids.uniq!
|
||||
|
||||
deerjikist = Deerjikist.find_by(platform: :nico, code: datum['user'])
|
||||
if deerjikist
|
||||
desired_non_nico_tag_ids << deerjikist.tag_id
|
||||
desired_nico_tag_based_ids << deerjikist.tag_id
|
||||
elsif !(Tag.where(id: kept_non_nico_tag_ids).where(category: :deerjikist).exists?)
|
||||
desired_non_nico_tag_ids << Tag.no_deerjikist.id
|
||||
desired_nico_tag_based_ids << Tag.no_deerjikist.id
|
||||
desired_all_ids = kept_non_nico_ids.to_a + desired_nico_ids
|
||||
desired_non_nico_ids.concat(kept_non_nico_ids.to_a)
|
||||
desired_non_nico_ids.uniq!
|
||||
if kept_non_nico_ids.to_set != desired_non_nico_ids.to_set
|
||||
desired_all_ids << Tag.bot.id
|
||||
end
|
||||
desired_all_ids.uniq!
|
||||
|
||||
desired_nico_tag_based_ids.uniq!
|
||||
|
||||
desired_all_tag_ids = kept_non_nico_tag_ids.to_a + desired_nico_tag_based_ids
|
||||
desired_non_nico_tag_ids.concat(kept_non_nico_tag_ids.to_a)
|
||||
desired_non_nico_tag_ids.uniq!
|
||||
if kept_non_nico_tag_ids != desired_non_nico_tag_ids.to_set
|
||||
desired_all_tag_ids << Tag.bot.id
|
||||
end
|
||||
desired_all_tag_ids.uniq!
|
||||
|
||||
sync_post_tags!(post, desired_all_tag_ids, current_tag_ids: kept_tag_ids)
|
||||
sync_post_tags!(post, desired_all_ids, current_ids: kept_ids)
|
||||
end
|
||||
end
|
||||
end
|
||||
|
||||
@@ -1,11 +1,11 @@
|
||||
FactoryBot.define do
|
||||
factory :tag do
|
||||
category { :general }
|
||||
category { 'general' }
|
||||
post_count { 0 }
|
||||
association :tag_name
|
||||
|
||||
trait :nico do
|
||||
category { :nico }
|
||||
category { 'nico' }
|
||||
tag_name { association(:tag_name, name: "nico:#{ SecureRandom.hex(4) }") }
|
||||
end
|
||||
end
|
||||
|
||||
@@ -1,71 +0,0 @@
|
||||
require 'rails_helper'
|
||||
|
||||
RSpec.describe Tag, type: :model do
|
||||
describe '.merge_tags!' do
|
||||
let!(:target_tag) { create(:tag) }
|
||||
let!(:source_tag) { create(:tag) }
|
||||
|
||||
let!(:post_record) { Post.create!(url: 'https://example.com/posts/1', title: 'test post') }
|
||||
|
||||
context 'when merging a simple source tag' do
|
||||
let!(:source_post_tag) { PostTag.create!(post: post_record, tag: source_tag) }
|
||||
|
||||
it 'moves the post_tag, deletes the source tag, and aliases the source tag_name' do
|
||||
described_class.merge_tags!(target_tag, [source_tag])
|
||||
|
||||
expect(source_post_tag.reload.tag_id).to eq(target_tag.id)
|
||||
expect(Tag.exists?(source_tag.id)).to be(false)
|
||||
expect(source_tag.tag_name.reload.canonical_id).to eq(target_tag.tag_name_id)
|
||||
end
|
||||
end
|
||||
|
||||
context 'when the target already has the same post_tag' do
|
||||
let!(:target_post_tag) { PostTag.create!(post: post_record, tag: target_tag) }
|
||||
let!(:source_post_tag) { PostTag.create!(post: post_record, tag: source_tag) }
|
||||
|
||||
it 'discards the duplicate source post_tag and keeps one active target post_tag' do
|
||||
described_class.merge_tags!(target_tag, [source_tag])
|
||||
|
||||
active = PostTag.kept.where(post_id: post_record.id, tag_id: target_tag.id)
|
||||
discarded_source = PostTag.with_discarded.find(source_post_tag.id)
|
||||
|
||||
expect(active.count).to eq(1)
|
||||
expect(discarded_source.discarded_at).to be_present
|
||||
expect(Tag.exists?(source_tag.id)).to be(false)
|
||||
expect(source_tag.tag_name.reload.canonical_id).to eq(target_tag.tag_name_id)
|
||||
end
|
||||
end
|
||||
|
||||
context 'when source_tags includes the target itself' do
|
||||
let!(:source_post_tag) { PostTag.create!(post: post_record, tag: source_tag) }
|
||||
|
||||
it 'ignores the target tag in source_tags' do
|
||||
described_class.merge_tags!(target_tag, [source_tag, target_tag])
|
||||
|
||||
expect(Tag.exists?(target_tag.id)).to be(true)
|
||||
expect(Tag.exists?(source_tag.id)).to be(false)
|
||||
expect(source_post_tag.reload.tag_id).to eq(target_tag.id)
|
||||
end
|
||||
end
|
||||
|
||||
context 'when aliasing the source tag_name is invalid' do
|
||||
let!(:source_post_tag) { PostTag.create!(post: post_record, tag: source_tag) }
|
||||
let!(:wiki_page) do
|
||||
WikiPage.create!(
|
||||
tag_name: source_tag.tag_name,
|
||||
created_user: create_admin_user!,
|
||||
updated_user: create_admin_user!)
|
||||
end
|
||||
|
||||
it 'rolls back the transaction' do
|
||||
expect {
|
||||
described_class.merge_tags!(target_tag, [source_tag])
|
||||
}.to raise_error(ActiveRecord::RecordInvalid)
|
||||
|
||||
expect(Tag.exists?(source_tag.id)).to be(true)
|
||||
expect(source_post_tag.reload.tag_id).to eq(source_tag.id)
|
||||
expect(source_tag.tag_name.reload.canonical_id).to be_nil
|
||||
end
|
||||
end
|
||||
end
|
||||
end
|
||||
@@ -1,181 +0,0 @@
|
||||
require 'rails_helper'
|
||||
|
||||
RSpec.describe 'Deerjikists API', type: :request do
|
||||
let(:platform) { 'nico' }
|
||||
let(:code) { 'deerjika-bot' }
|
||||
|
||||
let!(:tag1) { create(:tag, category: :deerjikist) }
|
||||
let!(:tag2) { create(:tag, category: :deerjikist) }
|
||||
|
||||
let(:member) { create(:user, :member) }
|
||||
let(:guest) { create(:user, role: :guest) }
|
||||
|
||||
describe 'GET /deerjikists/:platform/:code' do
|
||||
subject(:do_request) do
|
||||
get "/deerjikists/#{ platform }/#{ code }"
|
||||
end
|
||||
|
||||
context 'when deerjikist exists' do
|
||||
before do
|
||||
Deerjikist.create!(platform:, code:, tag: tag1)
|
||||
end
|
||||
|
||||
it 'returns 200 and deerjikist json' do
|
||||
do_request
|
||||
expect(response).to have_http_status(:ok)
|
||||
|
||||
expect(json).to be_a(Hash)
|
||||
expect(json['platform']).to eq(platform)
|
||||
expect(json['code']).to eq(code)
|
||||
|
||||
expect(json['tag']).to be_a(Hash)
|
||||
expect(json['tag']['id']).to eq(tag1.id)
|
||||
expect(json['tag']['name']).to eq(tag1.name)
|
||||
end
|
||||
end
|
||||
|
||||
context 'when deerjikist does not exist' do
|
||||
it 'returns 404' do
|
||||
do_request
|
||||
expect(response).to have_http_status(:not_found)
|
||||
end
|
||||
end
|
||||
|
||||
context 'when platform or code become blank after strip' do
|
||||
it 'returns 400' do
|
||||
get '/deerjikists/%20/%20'
|
||||
expect(response).to have_http_status(:bad_request)
|
||||
end
|
||||
end
|
||||
end
|
||||
|
||||
describe 'PUT /deerjikists/:platform/:code' do
|
||||
subject(:do_request) do
|
||||
put "/deerjikists/#{ platform }/#{ code }", params: payload
|
||||
end
|
||||
|
||||
let(:payload) { { tag_id: tag1.id } }
|
||||
|
||||
context 'when not legged in' do
|
||||
it 'returns 401' do
|
||||
sign_out
|
||||
do_request
|
||||
expect(response).to have_http_status(:unauthorized)
|
||||
end
|
||||
end
|
||||
|
||||
context 'when logged in but not member' do
|
||||
it 'returns 403' do
|
||||
sign_in_as guest
|
||||
do_request
|
||||
expect(response).to have_http_status(:forbidden)
|
||||
end
|
||||
end
|
||||
|
||||
context 'when member' do
|
||||
before do
|
||||
sign_in_as member
|
||||
end
|
||||
|
||||
context 'when params invalid' do
|
||||
it 'returns 400 when tag_id is missing or invalid' do
|
||||
put "/deerjikists/#{ platform }/#{ code }", params: { tag_id: 0 }
|
||||
expect(response).to have_http_status(:bad_request)
|
||||
end
|
||||
|
||||
it 'returns 400 when platform or code blank after strip' do
|
||||
put '/deerjikists/%20/%20', params: { tag_id: tag1.id }
|
||||
expect(response).to have_http_status(:bad_request)
|
||||
end
|
||||
end
|
||||
|
||||
context 'when creating new deerjikist' do
|
||||
it 'creates and returns 200 with json' do
|
||||
expect { do_request }.to change { Deerjikist.count }.by(1)
|
||||
expect(response).to have_http_status(:ok)
|
||||
|
||||
d = Deerjikist.find_by(platform:, code:)
|
||||
expect(d).to be_present
|
||||
expect(d.tag_id).to eq(tag1.id)
|
||||
|
||||
expect(json['platform']).to eq(platform)
|
||||
expect(json['code']).to eq(code)
|
||||
end
|
||||
end
|
||||
|
||||
context 'when updating existing deerjikist' do
|
||||
before do
|
||||
Deerjikist.create!(platform:, code:, tag: tag1)
|
||||
end
|
||||
|
||||
let(:payload) { { tag_id: tag2.id } }
|
||||
|
||||
it 'updates tag_id and returns 200' do
|
||||
expect { do_request }.not_to change { Deerjikist.count }
|
||||
expect(response).to have_http_status(:ok)
|
||||
|
||||
d = Deerjikist.find_by(platform:, code:)
|
||||
expect(d.tag_id).to eq(tag2.id)
|
||||
|
||||
expect(json['platform']).to eq(platform)
|
||||
expect(json['code']).to eq(code)
|
||||
end
|
||||
end
|
||||
end
|
||||
end
|
||||
|
||||
describe 'DELETE /deerjikists/:platform/:code' do
|
||||
subject(:do_request) do
|
||||
delete "/deerjikists/#{ platform }/#{ code }"
|
||||
end
|
||||
|
||||
context 'when not logged in' do
|
||||
it 'returns 401' do
|
||||
sign_out
|
||||
do_request
|
||||
expect(response).to have_http_status(:unauthorized)
|
||||
end
|
||||
end
|
||||
|
||||
context 'when logged in but not member' do
|
||||
it 'returns 403' do
|
||||
sign_in_as guest
|
||||
do_request
|
||||
expect(response).to have_http_status(:forbidden)
|
||||
end
|
||||
end
|
||||
|
||||
context 'when member' do
|
||||
before do
|
||||
sign_in_as member
|
||||
end
|
||||
|
||||
it 'returns 400 when platform/code blank after strip' do
|
||||
delete '/deerjikists/%20/%20'
|
||||
expect(response).to have_http_status(:bad_request)
|
||||
end
|
||||
|
||||
context 'when deerjikist exists' do
|
||||
before do
|
||||
Deerjikist.create!(platform: platform, code: code, tag: tag1)
|
||||
end
|
||||
|
||||
it 'destroys and returns 204' do
|
||||
expect {
|
||||
do_request
|
||||
}.to change { Deerjikist.exists?(platform: platform, code: code) }
|
||||
.from(true).to(false)
|
||||
|
||||
expect(response).to have_http_status(:no_content)
|
||||
end
|
||||
end
|
||||
|
||||
context 'when deerjikist does not exist' do
|
||||
it 'returns 404' do
|
||||
do_request
|
||||
expect(response).to have_http_status(:not_found)
|
||||
end
|
||||
end
|
||||
end
|
||||
end
|
||||
end
|
||||
@@ -1,8 +1,7 @@
|
||||
include ActiveSupport::Testing::TimeHelpers
|
||||
|
||||
require 'rails_helper'
|
||||
require 'set'
|
||||
|
||||
|
||||
RSpec.describe 'Posts API', type: :request do
|
||||
# create / update で thumbnail.attach は走るが、
|
||||
# resized_thumbnail! が MiniMagick 依存でコケやすいので request spec ではスタブしとくのが無難。
|
||||
@@ -115,204 +114,6 @@ RSpec.describe 'Posts API', type: :request do
|
||||
expect(json.fetch('count')).to eq(0)
|
||||
end
|
||||
end
|
||||
|
||||
context 'when url is provided' do
|
||||
let!(:url_hit_post) do
|
||||
Post.create!(uploaded_user: user, title: 'url hit',
|
||||
url: 'https://example.com/needle-url-xyz').tap do |p|
|
||||
PostTag.create!(post: p, tag:)
|
||||
end
|
||||
end
|
||||
|
||||
let!(:url_miss_post) do
|
||||
Post.create!(uploaded_user: user, title: 'url miss',
|
||||
url: 'https://example.com/other-url').tap do |p|
|
||||
PostTag.create!(post: p, tag:)
|
||||
end
|
||||
end
|
||||
|
||||
it 'filters posts by url substring' do
|
||||
get '/posts', params: { url: 'needle-url-xyz' }
|
||||
|
||||
expect(response).to have_http_status(:ok)
|
||||
ids = json.fetch('posts').map { |p| p['id'] }
|
||||
|
||||
expect(ids).to include(url_hit_post.id)
|
||||
expect(ids).not_to include(url_miss_post.id)
|
||||
expect(json.fetch('count')).to eq(1)
|
||||
end
|
||||
end
|
||||
|
||||
context 'when title is provided' do
|
||||
let!(:title_hit_post) do
|
||||
Post.create!(uploaded_user: user, title: 'needle-title-xyz',
|
||||
url: 'https://example.com/title-hit').tap do |p|
|
||||
PostTag.create!(post: p, tag:)
|
||||
end
|
||||
end
|
||||
|
||||
let!(:title_miss_post) do
|
||||
Post.create!(uploaded_user: user, title: 'other title',
|
||||
url: 'https://example.com/title-miss').tap do |p|
|
||||
PostTag.create!(post: p, tag:)
|
||||
end
|
||||
end
|
||||
|
||||
it 'filters posts by title substring' do
|
||||
get '/posts', params: { title: 'needle-title-xyz' }
|
||||
|
||||
expect(response).to have_http_status(:ok)
|
||||
ids = json.fetch('posts').map { |p| p['id'] }
|
||||
|
||||
expect(ids).to include(title_hit_post.id)
|
||||
expect(ids).not_to include(title_miss_post.id)
|
||||
expect(json.fetch('count')).to eq(1)
|
||||
end
|
||||
end
|
||||
|
||||
context 'when created_from/created_to are provided' do
|
||||
let(:t_created_hit) { Time.zone.local(2010, 1, 5, 12, 0, 0) }
|
||||
let(:t_created_miss) { Time.zone.local(2012, 1, 5, 12, 0, 0) }
|
||||
|
||||
let!(:created_hit_post) do
|
||||
travel_to(t_created_hit) do
|
||||
Post.create!(uploaded_user: user, title: 'created hit',
|
||||
url: 'https://example.com/created-hit').tap do |p|
|
||||
PostTag.create!(post: p, tag:)
|
||||
end
|
||||
end
|
||||
end
|
||||
|
||||
let!(:created_miss_post) do
|
||||
travel_to(t_created_miss) do
|
||||
Post.create!(uploaded_user: user, title: 'created miss',
|
||||
url: 'https://example.com/created-miss').tap do |p|
|
||||
PostTag.create!(post: p, tag:)
|
||||
end
|
||||
end
|
||||
end
|
||||
|
||||
it 'filters posts by created_at range' do
|
||||
get '/posts', params: {
|
||||
created_from: Time.zone.local(2010, 1, 1, 0, 0, 0).iso8601,
|
||||
created_to: Time.zone.local(2010, 12, 31, 23, 59, 59).iso8601
|
||||
}
|
||||
|
||||
expect(response).to have_http_status(:ok)
|
||||
ids = json.fetch('posts').map { |p| p['id'] }
|
||||
|
||||
expect(ids).to include(created_hit_post.id)
|
||||
expect(ids).not_to include(created_miss_post.id)
|
||||
expect(json.fetch('count')).to eq(1)
|
||||
end
|
||||
end
|
||||
|
||||
context 'when updated_from/updated_to are provided' do
|
||||
let(:t0) { Time.zone.local(2011, 2, 1, 12, 0, 0) }
|
||||
let(:t1) { Time.zone.local(2011, 2, 10, 12, 0, 0) }
|
||||
|
||||
let!(:updated_hit_post) do
|
||||
p = nil
|
||||
travel_to(t0) do
|
||||
p = Post.create!(uploaded_user: user, title: 'updated hit',
|
||||
url: 'https://example.com/updated-hit').tap do |pp|
|
||||
PostTag.create!(post: pp, tag:)
|
||||
end
|
||||
end
|
||||
travel_to(t1) do
|
||||
p.update!(title: 'updated hit v2')
|
||||
end
|
||||
p
|
||||
end
|
||||
|
||||
let!(:updated_miss_post) do
|
||||
travel_to(Time.zone.local(2013, 1, 1, 12, 0, 0)) do
|
||||
Post.create!(uploaded_user: user, title: 'updated miss',
|
||||
url: 'https://example.com/updated-miss').tap do |p|
|
||||
PostTag.create!(post: p, tag:)
|
||||
end
|
||||
end
|
||||
end
|
||||
|
||||
it 'filters posts by updated_at range' do
|
||||
get '/posts', params: {
|
||||
updated_from: Time.zone.local(2011, 2, 5, 0, 0, 0).iso8601,
|
||||
updated_to: Time.zone.local(2011, 2, 20, 23, 59, 59).iso8601
|
||||
}
|
||||
|
||||
expect(response).to have_http_status(:ok)
|
||||
ids = json.fetch('posts').map { |p| p['id'] }
|
||||
|
||||
expect(ids).to include(updated_hit_post.id)
|
||||
expect(ids).not_to include(updated_miss_post.id)
|
||||
expect(json.fetch('count')).to eq(1)
|
||||
end
|
||||
end
|
||||
|
||||
context 'when original_created_from/original_created_to are provided' do
|
||||
# 注意: controller の現状ロジックに合わせてる
|
||||
# original_created_from は `original_created_before > ?`
|
||||
# original_created_to は `original_created_from <= ?`
|
||||
|
||||
let!(:oc_hit_post) do
|
||||
Post.create!(uploaded_user: user, title: 'oc hit',
|
||||
url: 'https://example.com/oc-hit',
|
||||
original_created_from: Time.zone.local(2015, 1, 1, 0, 0, 0),
|
||||
original_created_before: Time.zone.local(2015, 1, 10, 0, 0, 0)).tap do |p|
|
||||
PostTag.create!(post: p, tag:)
|
||||
end
|
||||
end
|
||||
|
||||
# original_created_from の条件は「original_created_before > param」なので、
|
||||
# before が param 以下になるようにする(ただし before >= from は守る)
|
||||
let!(:oc_miss_post_for_from) do
|
||||
Post.create!(
|
||||
uploaded_user: user,
|
||||
title: 'oc miss for from',
|
||||
url: 'https://example.com/oc-miss-from',
|
||||
original_created_from: Time.zone.local(2014, 12, 1, 0, 0, 0),
|
||||
original_created_before: Time.zone.local(2015, 1, 1, 0, 0, 0)
|
||||
).tap { |p| PostTag.create!(post: p, tag:) }
|
||||
end
|
||||
|
||||
# original_created_to の条件は「original_created_from <= param」なので、
|
||||
# from が param より後になるようにする(before >= from は守る)
|
||||
let!(:oc_miss_post_for_to) do
|
||||
Post.create!(
|
||||
uploaded_user: user,
|
||||
title: 'oc miss for to',
|
||||
url: 'https://example.com/oc-miss-to',
|
||||
original_created_from: Time.zone.local(2015, 2, 1, 0, 0, 0),
|
||||
original_created_before: Time.zone.local(2015, 2, 10, 0, 0, 0)
|
||||
).tap { |p| PostTag.create!(post: p, tag:) }
|
||||
end
|
||||
|
||||
it 'filters posts by original_created_from (current controller behavior)' do
|
||||
get '/posts', params: {
|
||||
original_created_from: Time.zone.local(2015, 1, 5, 0, 0, 0).iso8601
|
||||
}
|
||||
|
||||
expect(response).to have_http_status(:ok)
|
||||
ids = json.fetch('posts').map { |p| p['id'] }
|
||||
|
||||
expect(ids).to include(oc_hit_post.id)
|
||||
expect(ids).not_to include(oc_miss_post_for_from.id)
|
||||
expect(json.fetch('count')).to eq(2)
|
||||
end
|
||||
|
||||
it 'filters posts by original_created_to (current controller behavior)' do
|
||||
get '/posts', params: {
|
||||
original_created_to: Time.zone.local(2015, 1, 15, 0, 0, 0).iso8601
|
||||
}
|
||||
|
||||
expect(response).to have_http_status(:ok)
|
||||
ids = json.fetch('posts').map { |p| p['id'] }
|
||||
|
||||
expect(ids).to include(oc_hit_post.id)
|
||||
expect(ids).not_to include(oc_miss_post_for_to.id)
|
||||
expect(json.fetch('count')).to eq(2)
|
||||
end
|
||||
end
|
||||
end
|
||||
|
||||
describe 'GET /posts/:id' do
|
||||
|
||||
@@ -1,3 +1,4 @@
|
||||
# spec/requests/tag_children_spec.rb
|
||||
require "rails_helper"
|
||||
|
||||
RSpec.describe "TagChildren", type: :request do
|
||||
|
||||
@@ -1,102 +0,0 @@
|
||||
require 'rails_helper'
|
||||
|
||||
RSpec.describe 'Tags deerjikists API', type: :request do
|
||||
let(:platform1) { 'nico' }
|
||||
let(:code1) { 'deerjika-bot' }
|
||||
let(:platform2) { 'youtube' }
|
||||
let(:code2) { 'deerjika-bot.bsky.social' }
|
||||
|
||||
let!(:tag) { create(:tag, category: :deerjikist) }
|
||||
|
||||
before do
|
||||
# show_by_name / deerjikists_by_name 用に名前を固定
|
||||
tag.tag_name.update!(name: 'deerjika')
|
||||
end
|
||||
|
||||
describe 'GET /tags/:id/deerjikists' do
|
||||
subject(:do_request) do
|
||||
get "/tags/#{ tag_id }/deerjikists"
|
||||
end
|
||||
|
||||
let(:tag_id) { tag.id }
|
||||
|
||||
context 'when tag exists and has no deerjikists' do
|
||||
it 'returns 200 and empty array' do
|
||||
do_request
|
||||
expect(response).to have_http_status(:ok)
|
||||
expect(json).to eq([])
|
||||
end
|
||||
end
|
||||
|
||||
context 'when tag exists and has deerjikists' do
|
||||
before do
|
||||
Deerjikist.create!(platform: platform1, code: code1, tag: tag)
|
||||
Deerjikist.create!(platform: platform2, code: code2, tag: tag)
|
||||
end
|
||||
|
||||
it 'returns 200 and deerjikists array' do
|
||||
do_request
|
||||
expect(response).to have_http_status(:ok)
|
||||
|
||||
expect(json).to be_a(Array)
|
||||
expect(json.size).to eq(2)
|
||||
|
||||
expect(json.map { |h| [h['platform'], h['code']] }).to contain_exactly(
|
||||
[platform1, code1],
|
||||
[platform2, code2],
|
||||
)
|
||||
end
|
||||
end
|
||||
|
||||
context 'when tag does not exist' do
|
||||
let(:tag_id) { 9_999_999 }
|
||||
|
||||
it 'returns 404' do
|
||||
do_request
|
||||
expect(response).to have_http_status(:not_found)
|
||||
end
|
||||
end
|
||||
end
|
||||
|
||||
describe 'GET /tags/name/:name/deerjikists' do
|
||||
subject(:do_request) do
|
||||
get "/tags/name/#{ name }/deerjikists"
|
||||
end
|
||||
|
||||
let(:name) { 'deerjika' }
|
||||
|
||||
context 'when name is blank after strip' do
|
||||
let(:name) { '%20' }
|
||||
|
||||
it 'returns 400' do
|
||||
do_request
|
||||
expect(response).to have_http_status(:bad_request)
|
||||
end
|
||||
end
|
||||
|
||||
context 'when tag does not exist for name' do
|
||||
let(:name) { 'no-such-tag' }
|
||||
|
||||
it 'returns 404' do
|
||||
do_request
|
||||
expect(response).to have_http_status(:not_found)
|
||||
end
|
||||
end
|
||||
|
||||
context 'when tag exists and has deerjikists' do
|
||||
before do
|
||||
Deerjikist.create!(platform: platform1, code: code1, tag: tag)
|
||||
end
|
||||
|
||||
it 'returns 200 and deerjikists array' do
|
||||
do_request
|
||||
expect(response).to have_http_status(:ok)
|
||||
|
||||
expect(json).to be_a(Array)
|
||||
expect(json.size).to eq(1)
|
||||
expect(json[0]['platform']).to eq(platform1)
|
||||
expect(json[0]['code']).to eq(code1)
|
||||
end
|
||||
end
|
||||
end
|
||||
end
|
||||
@@ -106,8 +106,8 @@ RSpec.describe 'Tags API', type: :request do
|
||||
end
|
||||
|
||||
before do
|
||||
allow(member_user).to receive(:gte_member?).and_return(true)
|
||||
allow(non_member_user).to receive(:gte_member?).and_return(false)
|
||||
allow(member_user).to receive(:member?).and_return(true)
|
||||
allow(non_member_user).to receive(:member?).and_return(false)
|
||||
end
|
||||
|
||||
describe "PATCH /tags/:id" do
|
||||
|
||||
生成ファイル
+1
-42
@@ -25,7 +25,6 @@
|
||||
"humps": "^2.0.1",
|
||||
"lucide-react": "^0.511.0",
|
||||
"markdown-it": "^14.1.0",
|
||||
"path-to-regexp": "^8.3.0",
|
||||
"react": "^19.1.0",
|
||||
"react-dom": "^19.1.0",
|
||||
"react-helmet-async": "^2.0.5",
|
||||
@@ -35,8 +34,7 @@
|
||||
"react-youtube": "^10.1.0",
|
||||
"remark-gfm": "^4.0.1",
|
||||
"tailwind-merge": "^3.3.0",
|
||||
"unist-util-visit-parents": "^6.0.1",
|
||||
"zustand": "^5.0.8"
|
||||
"unist-util-visit-parents": "^6.0.1"
|
||||
},
|
||||
"devDependencies": {
|
||||
"@eslint/js": "^9.25.0",
|
||||
@@ -5581,16 +5579,6 @@
|
||||
"dev": true,
|
||||
"license": "ISC"
|
||||
},
|
||||
"node_modules/path-to-regexp": {
|
||||
"version": "8.3.0",
|
||||
"resolved": "https://registry.npmjs.org/path-to-regexp/-/path-to-regexp-8.3.0.tgz",
|
||||
"integrity": "sha512-7jdwVIRtsP8MYpdXSwOS0YdD0Du+qOoF/AEPIt88PcCFrZCzx41oxku1jD88hZBwbNUIEfpqvuhjFaMAqMTWnA==",
|
||||
"license": "MIT",
|
||||
"funding": {
|
||||
"type": "opencollective",
|
||||
"url": "https://opencollective.com/express"
|
||||
}
|
||||
},
|
||||
"node_modules/picocolors": {
|
||||
"version": "1.1.1",
|
||||
"resolved": "https://registry.npmjs.org/picocolors/-/picocolors-1.1.1.tgz",
|
||||
@@ -7325,35 +7313,6 @@
|
||||
"integrity": "sha512-Tpp60P6IUJDTuOq/5Z8cdskzJujfwqfOTkrwIwj7IRISpnkJnT6SyJ4PCPnGMoFjC9ddhal5KVIYtAt97ix05A==",
|
||||
"license": "MIT"
|
||||
},
|
||||
"node_modules/zustand": {
|
||||
"version": "5.0.8",
|
||||
"resolved": "https://registry.npmjs.org/zustand/-/zustand-5.0.8.tgz",
|
||||
"integrity": "sha512-gyPKpIaxY9XcO2vSMrLbiER7QMAMGOQZVRdJ6Zi782jkbzZygq5GI9nG8g+sMgitRtndwaBSl7uiqC49o1SSiw==",
|
||||
"license": "MIT",
|
||||
"engines": {
|
||||
"node": ">=12.20.0"
|
||||
},
|
||||
"peerDependencies": {
|
||||
"@types/react": ">=18.0.0",
|
||||
"immer": ">=9.0.6",
|
||||
"react": ">=18.0.0",
|
||||
"use-sync-external-store": ">=1.2.0"
|
||||
},
|
||||
"peerDependenciesMeta": {
|
||||
"@types/react": {
|
||||
"optional": true
|
||||
},
|
||||
"immer": {
|
||||
"optional": true
|
||||
},
|
||||
"react": {
|
||||
"optional": true
|
||||
},
|
||||
"use-sync-external-store": {
|
||||
"optional": true
|
||||
}
|
||||
}
|
||||
},
|
||||
"node_modules/zwitch": {
|
||||
"version": "2.0.4",
|
||||
"resolved": "https://registry.npmjs.org/zwitch/-/zwitch-2.0.4.tgz",
|
||||
|
||||
@@ -27,7 +27,6 @@
|
||||
"humps": "^2.0.1",
|
||||
"lucide-react": "^0.511.0",
|
||||
"markdown-it": "^14.1.0",
|
||||
"path-to-regexp": "^8.3.0",
|
||||
"react": "^19.1.0",
|
||||
"react-dom": "^19.1.0",
|
||||
"react-helmet-async": "^2.0.5",
|
||||
@@ -37,7 +36,6 @@
|
||||
"react-youtube": "^10.1.0",
|
||||
"remark-gfm": "^4.0.1",
|
||||
"tailwind-merge": "^3.3.0",
|
||||
"zustand": "^5.0.8",
|
||||
"unist-util-visit-parents": "^6.0.1"
|
||||
},
|
||||
"devDependencies": {
|
||||
|
||||
+19
-28
@@ -1,3 +1,5 @@
|
||||
import axios from 'axios'
|
||||
import toCamel from 'camelcase-keys'
|
||||
import { AnimatePresence, LayoutGroup } from 'framer-motion'
|
||||
import { useEffect, useState } from 'react'
|
||||
import { BrowserRouter,
|
||||
@@ -6,17 +8,15 @@ import { BrowserRouter,
|
||||
Routes,
|
||||
useLocation } from 'react-router-dom'
|
||||
|
||||
import RouteBlockerOverlay from '@/components/RouteBlockerOverlay'
|
||||
import TopNav from '@/components/TopNav'
|
||||
import { Toaster } from '@/components/ui/toaster'
|
||||
import { apiPost, isApiError } from '@/lib/api'
|
||||
import { API_BASE_URL } from '@/config'
|
||||
import NicoTagListPage from '@/pages/tags/NicoTagListPage'
|
||||
import NotFound from '@/pages/NotFound'
|
||||
import PostDetailPage from '@/pages/posts/PostDetailPage'
|
||||
import PostHistoryPage from '@/pages/posts/PostHistoryPage'
|
||||
import PostListPage from '@/pages/posts/PostListPage'
|
||||
import PostNewPage from '@/pages/posts/PostNewPage'
|
||||
import PostSearchPage from '@/pages/posts/PostSearchPage'
|
||||
import ServiceUnavailable from '@/pages/ServiceUnavailable'
|
||||
import SettingPage from '@/pages/users/SettingPage'
|
||||
import WikiDetailPage from '@/pages/wiki/WikiDetailPage'
|
||||
@@ -43,8 +43,7 @@ const RouteTransitionWrapper = ({ user, setUser }: {
|
||||
<Route path="/" element={<Navigate to="/posts" replace/>}/>
|
||||
<Route path="/posts" element={<PostListPage/>}/>
|
||||
<Route path="/posts/new" element={<PostNewPage user={user}/>}/>
|
||||
<Route path="/posts/search" element={<PostSearchPage/>}/>
|
||||
<Route path="/posts/:id" element={<PostDetailRoute user={user}/>}/>
|
||||
<Route path="/posts/:id" element={<PostDetailPage user={user}/>}/>
|
||||
<Route path="/posts/changes" element={<PostHistoryPage/>}/>
|
||||
<Route path="/tags/nico" element={<NicoTagListPage user={user}/>}/>
|
||||
<Route path="/wiki" element={<WikiSearchPage/>}/>
|
||||
@@ -62,24 +61,18 @@ const RouteTransitionWrapper = ({ user, setUser }: {
|
||||
}
|
||||
|
||||
|
||||
const PostDetailRoute = ({ user }: { user: User | null }) => {
|
||||
const location = useLocation ()
|
||||
const key = location.pathname
|
||||
return <PostDetailPage key={key} user={user}/>
|
||||
}
|
||||
|
||||
|
||||
export default (() => {
|
||||
const [user, setUser] = useState<User | null> (null)
|
||||
const [status, setStatus] = useState (200)
|
||||
|
||||
useEffect (() => {
|
||||
const createUser = async () => {
|
||||
const data = await apiPost<{ code: string; user: User }> ('/users')
|
||||
const res = await axios.post (`${ API_BASE_URL }/users`)
|
||||
const data = res.data as { code: string; user: any }
|
||||
if (data.code)
|
||||
{
|
||||
localStorage.setItem ('user_code', data.code)
|
||||
setUser (data.user)
|
||||
setUser (toCamel (data.user, { deep: true }) as User)
|
||||
}
|
||||
}
|
||||
|
||||
@@ -89,16 +82,17 @@ export default (() => {
|
||||
void (async () => {
|
||||
try
|
||||
{
|
||||
const data = await apiPost<{ valid: boolean; user: User }> ('/users/verify', { code })
|
||||
const res = await axios.post (`${ API_BASE_URL }/users/verify`, { code })
|
||||
const data = res.data as { valid: boolean, user: any }
|
||||
if (data.valid)
|
||||
setUser (data.user)
|
||||
setUser (toCamel (data.user, { deep: true }))
|
||||
else
|
||||
await createUser ()
|
||||
}
|
||||
catch (err)
|
||||
{
|
||||
if (isApiError (err))
|
||||
setStatus (err.response?.status ?? 200)
|
||||
if (axios.isAxiosError (err))
|
||||
setStatus (err.status ?? 200)
|
||||
}
|
||||
}) ()
|
||||
}
|
||||
@@ -113,14 +107,11 @@ export default (() => {
|
||||
}
|
||||
|
||||
return (
|
||||
<>
|
||||
<RouteBlockerOverlay/>
|
||||
<BrowserRouter>
|
||||
<div className="flex flex-col h-screen w-screen">
|
||||
<TopNav user={user}/>
|
||||
<RouteTransitionWrapper user={user} setUser={setUser}/>
|
||||
</div>
|
||||
<Toaster/>
|
||||
</BrowserRouter>
|
||||
</>)
|
||||
<BrowserRouter>
|
||||
<div className="flex flex-col h-screen w-screen">
|
||||
<TopNav user={user}/>
|
||||
<RouteTransitionWrapper user={user} setUser={setUser}/>
|
||||
</div>
|
||||
<Toaster/>
|
||||
</BrowserRouter>)
|
||||
}) satisfies FC
|
||||
|
||||
@@ -1,10 +1,12 @@
|
||||
import axios from 'axios'
|
||||
import toCamel from 'camelcase-keys'
|
||||
import { useEffect, useState } from 'react'
|
||||
|
||||
import PostFormTagsArea from '@/components/PostFormTagsArea'
|
||||
import PostOriginalCreatedTimeField from '@/components/PostOriginalCreatedTimeField'
|
||||
import Label from '@/components/common/Label'
|
||||
import { Button } from '@/components/ui/button'
|
||||
import { apiPut } from '@/lib/api'
|
||||
import { API_BASE_URL } from '@/config'
|
||||
|
||||
import type { FC } from 'react'
|
||||
|
||||
@@ -39,11 +41,14 @@ export default (({ post, onSave }: Props) => {
|
||||
const [tags, setTags] = useState<string> ('')
|
||||
|
||||
const handleSubmit = async () => {
|
||||
const data = await apiPut<Post> (
|
||||
`/posts/${ post.id }`,
|
||||
{ title, tags, original_created_from: originalCreatedFrom,
|
||||
const res = await axios.put (
|
||||
`${ API_BASE_URL }/posts/${ post.id }`,
|
||||
{ title, tags,
|
||||
original_created_from: originalCreatedFrom,
|
||||
original_created_before: originalCreatedBefore },
|
||||
{ headers: { 'Content-Type': 'multipart/form-data' } })
|
||||
{ headers: { 'Content-Type': 'multipart/form-data',
|
||||
'X-Transfer-Code': localStorage.getItem ('user_code') ?? '' } })
|
||||
const data = toCamel (res.data as any, { deep: true }) as Post
|
||||
onSave ({ ...post,
|
||||
title: data.title,
|
||||
tags: data.tags,
|
||||
|
||||
@@ -18,35 +18,17 @@ export default (({ post }: Props) => {
|
||||
{
|
||||
case 'nicovideo.jp':
|
||||
{
|
||||
const mVideoId = url.pathname.match (/(?<=\/watch\/)[a-zA-Z0-9]+?(?=\/|$)/)
|
||||
if (!(mVideoId))
|
||||
break
|
||||
|
||||
const [videoId] = mVideoId
|
||||
|
||||
const [videoId] = url.pathname.match (/(?<=\/watch\/)[a-zA-Z0-9]+?(?=\/|$)/)!
|
||||
return <NicoViewer id={videoId} width={640} height={360}/>
|
||||
}
|
||||
|
||||
case 'twitter.com':
|
||||
case 'x.com':
|
||||
{
|
||||
const mUserId = url.pathname.match (/(?<=\/)[^\/]+?(?=\/|$|\?)/)
|
||||
const mStatusId = url.pathname.match (/(?<=\/status\/)\d+?(?=\/|$|\?)/)
|
||||
if (!(mUserId) || !(mStatusId))
|
||||
break
|
||||
|
||||
const [userId] = mUserId
|
||||
const [statusId] = mStatusId
|
||||
|
||||
return <TwitterEmbed userId={userId} statusId={statusId}/>
|
||||
}
|
||||
|
||||
const [userId] = url.pathname.match (/(?<=\/)[^\/]+?(?=\/|$|\?)/)!
|
||||
const [statusId] = url.pathname.match (/(?<=\/status\/)\d+?(?=\/|$|\?)/)!
|
||||
return <TwitterEmbed userId={userId} statusId={statusId}/>
|
||||
case 'youtube.com':
|
||||
{
|
||||
const videoId = url.searchParams.get ('v')
|
||||
if (!(videoId))
|
||||
break
|
||||
|
||||
const videoId = url.searchParams.get ('v')!
|
||||
return (
|
||||
<YoutubeEmbed videoId={videoId} opts={{ playerVars: {
|
||||
playsinline: 1,
|
||||
|
||||
@@ -1,11 +1,11 @@
|
||||
// TODO: TagSearch と共通化する.
|
||||
|
||||
import axios from 'axios'
|
||||
import toCamel from 'camelcase-keys'
|
||||
import { useRef, useState } from 'react'
|
||||
|
||||
import TagSearchBox from '@/components/TagSearchBox'
|
||||
import Label from '@/components/common/Label'
|
||||
import TextArea from '@/components/common/TextArea'
|
||||
import { apiGet } from '@/lib/api'
|
||||
import { API_BASE_URL } from '@/config'
|
||||
|
||||
import type { FC, SyntheticEvent } from 'react'
|
||||
|
||||
@@ -27,8 +27,8 @@ const getTokenAt = (value: string, pos: number) => {
|
||||
}
|
||||
|
||||
|
||||
const replaceToken = (value: string, start: number, end: number, text: string) =>
|
||||
`${ value.slice (0, start) }${ text }${ value.slice (end) }`
|
||||
const replaceToken = (value: string, start: number, end: number, text: string) => (
|
||||
`${ value.slice (0, start) }${ text }${ value.slice (end) }`)
|
||||
|
||||
|
||||
type Props = {
|
||||
@@ -40,17 +40,16 @@ export default (({ tags, setTags }: Props) => {
|
||||
const ref = useRef<HTMLTextAreaElement> (null)
|
||||
|
||||
const [bounds, setBounds] = useState<{ start: number; end: number }> ({ start: 0, end: 0 })
|
||||
const [focused, setFocused] = useState (false)
|
||||
const [suggestions, setSuggestions] = useState<Tag[]> ([])
|
||||
const [suggestionsVsbl, setSuggestionsVsbl] = useState (false)
|
||||
|
||||
const handleTagSelect = (tag: Tag) => {
|
||||
setSuggestionsVsbl (false)
|
||||
const textarea = ref.current!
|
||||
const newValue = replaceToken (tags, bounds.start, bounds.end, tag.name + ' ')
|
||||
const newValue = replaceToken (tags, bounds.start, bounds.end, tag.name)
|
||||
setTags (newValue)
|
||||
requestAnimationFrame (async () => {
|
||||
const p = bounds.start + tag.name.length + 1
|
||||
const p = bounds.start + tag.name.length
|
||||
textarea.selectionStart = textarea.selectionEnd = p
|
||||
textarea.focus ()
|
||||
await recompute (p, newValue)
|
||||
@@ -59,21 +58,15 @@ export default (({ tags, setTags }: Props) => {
|
||||
|
||||
const recompute = async (pos: number, v: string = tags) => {
|
||||
const { start, end, token } = getTokenAt (v, pos)
|
||||
if (!(token.trim ()))
|
||||
{
|
||||
setSuggestionsVsbl (false)
|
||||
return
|
||||
}
|
||||
|
||||
setBounds ({ start, end })
|
||||
|
||||
const data = await apiGet<Tag[]> ('/tags/autocomplete', { params: { q: token, nico: '0' } })
|
||||
const res = await axios.get (`${ API_BASE_URL }/tags/autocomplete`, { params: { q: token } })
|
||||
const data = toCamel (res.data as any, { deep: true }) as Tag[]
|
||||
setSuggestions (data.filter (t => t.postCount > 0))
|
||||
setSuggestionsVsbl (suggestions.length > 0)
|
||||
}
|
||||
|
||||
return (
|
||||
<div className="relative w-full">
|
||||
<div>
|
||||
<Label>タグ</Label>
|
||||
<TextArea
|
||||
ref={ref}
|
||||
@@ -82,18 +75,11 @@ export default (({ tags, setTags }: Props) => {
|
||||
onSelect={async (ev: SyntheticEvent<HTMLTextAreaElement>) => {
|
||||
const pos = (ev.target as HTMLTextAreaElement).selectionStart
|
||||
await recompute (pos)
|
||||
}}
|
||||
onFocus={() => setFocused (true)}
|
||||
onBlur={() => {
|
||||
setFocused (false)
|
||||
setSuggestionsVsbl (false)
|
||||
}}/>
|
||||
{focused && (
|
||||
<TagSearchBox
|
||||
suggestions={suggestionsVsbl && suggestions.length > 0
|
||||
? suggestions
|
||||
: [] as Tag[]}
|
||||
activeIndex={-1}
|
||||
onSelect={handleTagSelect}/>)}
|
||||
<TagSearchBox suggestions={suggestionsVsbl && suggestions.length
|
||||
? suggestions
|
||||
: [] as Tag[]}
|
||||
activeIndex={-1}
|
||||
onSelect={handleTagSelect}/>
|
||||
</div>)
|
||||
}) satisfies FC<Props>
|
||||
|
||||
@@ -1,9 +1,9 @@
|
||||
import { useQueryClient } from '@tanstack/react-query'
|
||||
import { motion } from 'framer-motion'
|
||||
import { useRef } from 'react'
|
||||
import { useLocation } from 'react-router-dom'
|
||||
import { Link, useNavigate } from 'react-router-dom'
|
||||
|
||||
import PrefetchLink from '@/components/PrefetchLink'
|
||||
import { useSharedTransitionStore } from '@/stores/sharedTransitionStore'
|
||||
import { fetchPost } from '@/lib/posts'
|
||||
|
||||
import type { FC, MouseEvent } from 'react'
|
||||
|
||||
@@ -14,47 +14,62 @@ type Props = { posts: Post[]
|
||||
|
||||
|
||||
export default (({ posts, onClick }: Props) => {
|
||||
const location = useLocation ()
|
||||
const navigate = useNavigate ()
|
||||
|
||||
const setForLocationKey = useSharedTransitionStore (s => s.setForLocationKey)
|
||||
const qc = useQueryClient ()
|
||||
|
||||
const cardRef = useRef<HTMLDivElement> (null)
|
||||
const prefetch = (id: string) => qc.prefetchQuery ({
|
||||
queryKey: ['post', id],
|
||||
queryFn: () => fetchPost (id) })
|
||||
|
||||
return (
|
||||
<div className="flex flex-wrap gap-6 p-4">
|
||||
{posts.map ((post, i) => {
|
||||
const sharedId = `page-${ post.id }`
|
||||
const layoutId = sharedId
|
||||
const id = String (post.id)
|
||||
const hRef = `/posts/${ id }`
|
||||
const cardRef = useRef<HTMLDivElement> (null)
|
||||
|
||||
const handleClick = async (ev: MouseEvent<HTMLAnchorElement>) => {
|
||||
onClick?.(ev)
|
||||
|
||||
if (ev.metaKey || ev.ctrlKey || ev.shiftKey || ev.button === 1)
|
||||
return
|
||||
|
||||
ev.preventDefault ()
|
||||
|
||||
await qc.ensureQueryData ({
|
||||
queryKey: ['post', id],
|
||||
queryFn: () => fetchPost (id) })
|
||||
|
||||
navigate (hRef)
|
||||
}
|
||||
|
||||
return (
|
||||
<PrefetchLink
|
||||
to={`/posts/${ post.id }`}
|
||||
key={post.id}
|
||||
className="w-40 h-40"
|
||||
state={{ sharedId }}
|
||||
onClick={e => {
|
||||
setForLocationKey (location.key, sharedId)
|
||||
onClick?.(e)
|
||||
}}>
|
||||
<Link to={hRef}
|
||||
key={id}
|
||||
className="w-40 h-40"
|
||||
onMouseEnter={() => prefetch (id)}
|
||||
onFocus={() => prefetch (id)}
|
||||
onClick={handleClick}>
|
||||
<motion.div
|
||||
ref={cardRef}
|
||||
layoutId={layoutId}
|
||||
layoutId={`page-${ id }`}
|
||||
className="w-full h-full overflow-hidden rounded-xl shadow
|
||||
transform-gpu will-change-transform"
|
||||
whileHover={{ scale: 1.02 }}
|
||||
onLayoutAnimationStart={() => {
|
||||
if (!(cardRef.current))
|
||||
return
|
||||
|
||||
cardRef.current.style.position = 'relative'
|
||||
cardRef.current.style.zIndex = '9999'
|
||||
if (cardRef.current)
|
||||
{
|
||||
cardRef.current.style.position = 'relative'
|
||||
cardRef.current.style.zIndex = '9999'
|
||||
}
|
||||
}}
|
||||
onLayoutAnimationComplete={() => {
|
||||
if (!(cardRef.current))
|
||||
return
|
||||
|
||||
cardRef.current.style.zIndex = ''
|
||||
cardRef.current.style.position = ''
|
||||
if (cardRef.current)
|
||||
{
|
||||
cardRef.current.style.zIndex = ''
|
||||
cardRef.current.style.position = ''
|
||||
}
|
||||
}}
|
||||
transition={{ type: 'spring', stiffness: 500, damping: 40, mass: .5 }}>
|
||||
<img src={post.thumbnail || post.thumbnailBase || undefined}
|
||||
@@ -64,7 +79,7 @@ export default (({ posts, onClick }: Props) => {
|
||||
decoding="async"
|
||||
className="object-cover w-full h-full"/>
|
||||
</motion.div>
|
||||
</PrefetchLink>)
|
||||
</Link>)
|
||||
})}
|
||||
</div>)
|
||||
}) satisfies FC<Props>
|
||||
|
||||
@@ -1,6 +1,5 @@
|
||||
import DateTimeField from '@/components/common/DateTimeField'
|
||||
import Label from '@/components/common/Label'
|
||||
import { Button } from '@/components/ui/button'
|
||||
|
||||
import type { FC } from 'react'
|
||||
|
||||
@@ -17,52 +16,34 @@ export default (({ originalCreatedFrom,
|
||||
setOriginalCreatedBefore }: Props) => (
|
||||
<div>
|
||||
<Label>オリジナルの作成日時</Label>
|
||||
<div className="my-1 flex">
|
||||
<div className="w-80">
|
||||
<DateTimeField
|
||||
className="mr-2"
|
||||
value={originalCreatedFrom ?? undefined}
|
||||
onChange={setOriginalCreatedFrom}
|
||||
onBlur={ev => {
|
||||
const v = ev.target.value
|
||||
if (!(v))
|
||||
return
|
||||
|
||||
const d = new Date (v)
|
||||
if (d.getMinutes () === 0 && d.getHours () === 0)
|
||||
d.setDate (d.getDate () + 1)
|
||||
else
|
||||
d.setMinutes (d.getMinutes () + 1)
|
||||
setOriginalCreatedBefore (d.toISOString ())
|
||||
}}/>
|
||||
以降
|
||||
</div>
|
||||
<div>
|
||||
<Button
|
||||
className="bg-gray-600 text-white rounded"
|
||||
onClick={() => {
|
||||
setOriginalCreatedFrom (null)
|
||||
}}>
|
||||
リセット
|
||||
</Button>
|
||||
</div>
|
||||
<div className="my-1">
|
||||
<DateTimeField
|
||||
className="mr-2"
|
||||
value={originalCreatedFrom ?? undefined}
|
||||
onChange={setOriginalCreatedFrom}
|
||||
onBlur={ev => {
|
||||
const v = ev.target.value
|
||||
if (!(v))
|
||||
return
|
||||
const d = new Date (v)
|
||||
if (d.getSeconds () === 0)
|
||||
{
|
||||
if (d.getMinutes () === 0 && d.getHours () === 0)
|
||||
d.setDate (d.getDate () + 1)
|
||||
else
|
||||
d.setMinutes (d.getMinutes () + 1)
|
||||
}
|
||||
else
|
||||
d.setSeconds (d.getSeconds () + 1)
|
||||
setOriginalCreatedBefore (d.toISOString ())
|
||||
}}/>
|
||||
以降
|
||||
</div>
|
||||
<div className="my-1 flex">
|
||||
<div className="w-80">
|
||||
<DateTimeField
|
||||
className="mr-2"
|
||||
value={originalCreatedBefore ?? undefined}
|
||||
onChange={setOriginalCreatedBefore}/>
|
||||
より前
|
||||
</div>
|
||||
<div>
|
||||
<Button
|
||||
className="bg-gray-600 text-white rounded"
|
||||
onClick={() => {
|
||||
setOriginalCreatedBefore (null)
|
||||
}}>
|
||||
リセット
|
||||
</Button>
|
||||
</div>
|
||||
<div className="my-1">
|
||||
<DateTimeField
|
||||
className="mr-2"
|
||||
value={originalCreatedBefore ?? undefined}
|
||||
onChange={setOriginalCreatedBefore}/>
|
||||
より前
|
||||
</div>
|
||||
</div>)) satisfies FC<Props>
|
||||
|
||||
@@ -1,107 +0,0 @@
|
||||
import { useQueryClient } from '@tanstack/react-query'
|
||||
import { forwardRef, useMemo } from 'react'
|
||||
import { flushSync } from 'react-dom'
|
||||
import { createPath, useNavigate } from 'react-router-dom'
|
||||
|
||||
import { useOverlayStore } from '@/components/RouteBlockerOverlay'
|
||||
import { prefetchForURL } from '@/lib/prefetchers'
|
||||
import { cn } from '@/lib/utils'
|
||||
|
||||
import type { AnchorHTMLAttributes, MouseEvent, TouchEvent } from 'react'
|
||||
import type { To } from 'react-router-dom'
|
||||
|
||||
type Props = AnchorHTMLAttributes<HTMLAnchorElement> & {
|
||||
to: To
|
||||
state?: Record<string, string>
|
||||
replace?: boolean
|
||||
className?: string
|
||||
cancelOnError?: boolean }
|
||||
|
||||
|
||||
export default forwardRef<HTMLAnchorElement, Props> (({
|
||||
to,
|
||||
replace,
|
||||
className,
|
||||
state,
|
||||
onMouseEnter,
|
||||
onTouchStart,
|
||||
onClick,
|
||||
cancelOnError = false,
|
||||
...rest }, ref) => {
|
||||
if ('onClick' in rest)
|
||||
delete rest['onClick']
|
||||
|
||||
const navigate = useNavigate ()
|
||||
const qc = useQueryClient ()
|
||||
const url = useMemo (() => {
|
||||
const path = (typeof to === 'string') ? to : createPath (to)
|
||||
return (new URL (path, location.origin)).toString ()
|
||||
}, [to])
|
||||
const setOverlay = useOverlayStore (s => s.setActive)
|
||||
|
||||
const doPrefetch = async () => {
|
||||
try
|
||||
{
|
||||
await prefetchForURL (qc, url)
|
||||
return true
|
||||
}
|
||||
catch (e)
|
||||
{
|
||||
console.error ('データ取得エラー', e)
|
||||
return false
|
||||
}
|
||||
}
|
||||
|
||||
const handleMouseEnter = async (ev: MouseEvent<HTMLAnchorElement>) => {
|
||||
onMouseEnter?.(ev)
|
||||
await doPrefetch ()
|
||||
}
|
||||
|
||||
const handleTouchStart = async (ev: TouchEvent<HTMLAnchorElement>) => {
|
||||
onTouchStart?.(ev)
|
||||
await doPrefetch ()
|
||||
}
|
||||
|
||||
const handleClick = async (ev: MouseEvent<HTMLAnchorElement>) => {
|
||||
try
|
||||
{
|
||||
onClick?.(ev)
|
||||
|
||||
if (ev.defaultPrevented
|
||||
|| ev.metaKey
|
||||
|| ev.ctrlKey
|
||||
|| ev.shiftKey
|
||||
|| ev.altKey)
|
||||
return
|
||||
|
||||
ev.preventDefault ()
|
||||
|
||||
flushSync (() => {
|
||||
setOverlay (true)
|
||||
})
|
||||
const ok = await doPrefetch ()
|
||||
flushSync (() => {
|
||||
setOverlay (false)
|
||||
})
|
||||
|
||||
if (!(ok) && cancelOnError)
|
||||
return
|
||||
|
||||
navigate (to, { replace, ...(state && { state }) })
|
||||
}
|
||||
catch (ex)
|
||||
{
|
||||
console.log (ex)
|
||||
ev.preventDefault ()
|
||||
}
|
||||
}
|
||||
|
||||
return (
|
||||
<a ref={ref}
|
||||
href={typeof to === 'string' ? to : createPath (to)}
|
||||
onMouseEnter={handleMouseEnter}
|
||||
onTouchStart={handleTouchStart}
|
||||
onClick={handleClick}
|
||||
className={cn ('cursor-pointer', className)}
|
||||
{...rest}/>)
|
||||
})
|
||||
@@ -1,46 +0,0 @@
|
||||
import { useEffect } from 'react'
|
||||
import { create } from 'zustand'
|
||||
|
||||
import type { FC } from 'react'
|
||||
|
||||
type OverlayStore = {
|
||||
active: boolean
|
||||
setActive: (v: boolean) => void }
|
||||
|
||||
|
||||
export const useOverlayStore = create<OverlayStore> (set => ({
|
||||
active: false,
|
||||
setActive: v => set ({ active: v }) }))
|
||||
|
||||
|
||||
export default (() => {
|
||||
const active = useOverlayStore (s => s.active)
|
||||
|
||||
useEffect (() => {
|
||||
if (active)
|
||||
{
|
||||
document.body.style.overflow = 'hidden'
|
||||
document.body.setAttribute ('aria-busy', 'true')
|
||||
}
|
||||
else
|
||||
{
|
||||
document.body.style.overflow = ''
|
||||
document.body.removeAttribute ('aria-busy')
|
||||
}
|
||||
}, [active])
|
||||
|
||||
if (!(active))
|
||||
return null
|
||||
|
||||
return (
|
||||
<div
|
||||
role="progressbar"
|
||||
aria-label="Loading"
|
||||
className="fixed inset-0 z-[9999] bg-black/50 backdrop-blur-sm pointer-events-auto">
|
||||
<div className="absolute inset-0 flex items-center justify-center">
|
||||
<div className="rounded-2xl bg-black/60 text-white px-6 py-3 text-sm">
|
||||
Loading...
|
||||
</div>
|
||||
</div>
|
||||
</div>)
|
||||
}) satisfies FC
|
||||
@@ -6,20 +6,21 @@ import { DndContext,
|
||||
useSensor,
|
||||
useSensors } from '@dnd-kit/core'
|
||||
import { restrictToWindowEdges } from '@dnd-kit/modifiers'
|
||||
import axios from 'axios'
|
||||
import toCamel from 'camelcase-keys'
|
||||
import { AnimatePresence, motion } from 'framer-motion'
|
||||
import { useEffect, useRef, useState } from 'react'
|
||||
import { Link } from 'react-router-dom'
|
||||
|
||||
import DraggableDroppableTagRow from '@/components/DraggableDroppableTagRow'
|
||||
import PrefetchLink from '@/components/PrefetchLink'
|
||||
import TagLink from '@/components/TagLink'
|
||||
import TagSearch from '@/components/TagSearch'
|
||||
import SectionTitle from '@/components/common/SectionTitle'
|
||||
import SubsectionTitle from '@/components/common/SubsectionTitle'
|
||||
import SidebarComponent from '@/components/layout/SidebarComponent'
|
||||
import { toast } from '@/components/ui/use-toast'
|
||||
import { API_BASE_URL } from '@/config'
|
||||
import { CATEGORIES } from '@/consts'
|
||||
import { apiDelete, apiGet, apiPatch, apiPost } from '@/lib/api'
|
||||
import { dateString, originalCreatedAtString } from '@/lib/utils'
|
||||
|
||||
import type { DragEndEvent } from '@dnd-kit/core'
|
||||
import type { FC, MutableRefObject, ReactNode } from 'react'
|
||||
@@ -131,7 +132,10 @@ const changeCategory = async (
|
||||
tagId: number,
|
||||
category: Category,
|
||||
): Promise<void> => {
|
||||
await apiPatch (`/tags/${ tagId }`, { category })
|
||||
await axios.patch (
|
||||
`${ API_BASE_URL }/tags/${ tagId }`,
|
||||
{ category },
|
||||
{ headers: { 'X-Transfer-Code': localStorage.getItem ('user_code') ?? '' } })
|
||||
}
|
||||
|
||||
|
||||
@@ -166,7 +170,12 @@ export default (({ post }: Props) => {
|
||||
if (!(post))
|
||||
return
|
||||
|
||||
setTags (buildTagByCategory (await apiGet<Post> (`/posts/${ post.id }`)))
|
||||
const res = await axios.get (
|
||||
`${ API_BASE_URL }/posts/${ post.id }`,
|
||||
{ headers: { 'X-Transfer-Code': localStorage.getItem ('user_code') ?? '' } })
|
||||
const data = toCamel (res.data as any, { deep: true }) as Post
|
||||
|
||||
setTags (buildTagByCategory (data))
|
||||
}
|
||||
|
||||
const onDragEnd = async (e: DragEndEvent) => {
|
||||
@@ -207,9 +216,16 @@ export default (({ post }: Props) => {
|
||||
return
|
||||
|
||||
if (fromParentId != null)
|
||||
await apiDelete (`/tags/${ fromParentId }/children/${ childId }`)
|
||||
{
|
||||
await axios.delete (
|
||||
`${ API_BASE_URL }/tags/${ fromParentId }/children/${ childId }`,
|
||||
{ headers: { 'X-Transfer-Code': localStorage.getItem ('user_code') ?? '' } })
|
||||
}
|
||||
|
||||
await apiPost (`/tags/${ parentId }/children/${ childId }`, { })
|
||||
await axios.post (
|
||||
`${ API_BASE_URL }/tags/${ parentId }/children/${ childId }`,
|
||||
{ },
|
||||
{ headers: { 'X-Transfer-Code': localStorage.getItem ('user_code') ?? '' } })
|
||||
|
||||
await reloadTags ()
|
||||
toast ({
|
||||
@@ -229,7 +245,11 @@ export default (({ post }: Props) => {
|
||||
await changeCategory (childId, cat)
|
||||
|
||||
if (fromParentId != null)
|
||||
await apiDelete (`/tags/${ fromParentId }/children/${ childId }`)
|
||||
{
|
||||
await axios.delete (
|
||||
`${ API_BASE_URL }/tags/${ fromParentId }/children/${ childId }`,
|
||||
{ headers: { 'X-Transfer-Code': localStorage.getItem ('user_code') ?? '' } })
|
||||
}
|
||||
|
||||
const fromParent = fromParentId == null ? null : findTag (tags, fromParentId)
|
||||
|
||||
@@ -338,13 +358,13 @@ export default (({ post }: Props) => {
|
||||
<>耕作者: </>
|
||||
{post.uploadedUser
|
||||
? (
|
||||
<PrefetchLink to={`/users/${ post.uploadedUser.id }`}>
|
||||
<Link to={`/users/${ post.uploadedUser.id }`}>
|
||||
{post.uploadedUser.name || '名もなきニジラー'}
|
||||
</PrefetchLink>)
|
||||
</Link>)
|
||||
: 'bot操作'}
|
||||
</li>
|
||||
*/}
|
||||
<li>耕作日時: {dateString (post.createdAt)}</li>
|
||||
<li>耕作日時: {(new Date (post.createdAt)).toLocaleString ()}</li>
|
||||
<li>
|
||||
<>リンク: </>
|
||||
<a
|
||||
@@ -356,14 +376,20 @@ export default (({ post }: Props) => {
|
||||
</a>
|
||||
</li>
|
||||
<li>
|
||||
{/* TODO: 表示形式きしょすぎるので何とかする */}
|
||||
<>オリジナルの投稿日時: </>
|
||||
{originalCreatedAtString (post.originalCreatedFrom,
|
||||
post.originalCreatedBefore)}
|
||||
{!(post.originalCreatedFrom) && !(post.originalCreatedBefore)
|
||||
? '不明'
|
||||
: (
|
||||
<>
|
||||
{post.originalCreatedFrom
|
||||
&& `${ (new Date (post.originalCreatedFrom)).toLocaleString () } 以降 `}
|
||||
{post.originalCreatedBefore
|
||||
&& `${ (new Date (post.originalCreatedBefore)).toLocaleString () } より前`}
|
||||
</>)}
|
||||
</li>
|
||||
<li>
|
||||
<PrefetchLink to={`/posts/changes?id=${ post.id }`}>
|
||||
履歴
|
||||
</PrefetchLink>
|
||||
<Link to={`/posts/changes?id=${ post.id }`}>履歴</Link>
|
||||
</li>
|
||||
</ul>
|
||||
</div>)}
|
||||
|
||||
@@ -1,34 +1,27 @@
|
||||
import axios from 'axios'
|
||||
import { useEffect, useState } from 'react'
|
||||
import { Link } from 'react-router-dom'
|
||||
|
||||
import PrefetchLink from '@/components/PrefetchLink'
|
||||
import { API_BASE_URL } from '@/config'
|
||||
import { LIGHT_COLOUR_SHADE, DARK_COLOUR_SHADE, TAG_COLOUR } from '@/consts'
|
||||
import { apiGet } from '@/lib/api'
|
||||
import { cn } from '@/lib/utils'
|
||||
|
||||
import type { ComponentProps, FC, HTMLAttributes } from 'react'
|
||||
|
||||
import type { Tag } from '@/types'
|
||||
|
||||
type CommonProps = {
|
||||
tag: Tag
|
||||
nestLevel?: number
|
||||
withWiki?: boolean
|
||||
withCount?: boolean
|
||||
prefetch?: boolean }
|
||||
type CommonProps = { tag: Tag
|
||||
nestLevel?: number
|
||||
withWiki?: boolean
|
||||
withCount?: boolean }
|
||||
|
||||
type PropsWithLink =
|
||||
& CommonProps
|
||||
& { linkFlg?: true }
|
||||
& Partial<ComponentProps<typeof PrefetchLink>>
|
||||
CommonProps & { linkFlg?: true } & Partial<ComponentProps<typeof Link>>
|
||||
|
||||
type PropsWithoutLink =
|
||||
& CommonProps
|
||||
& { linkFlg: false }
|
||||
& Partial<HTMLAttributes<HTMLSpanElement>>
|
||||
CommonProps & { linkFlg: false } & Partial<HTMLAttributes<HTMLSpanElement>>
|
||||
|
||||
type Props =
|
||||
| PropsWithLink
|
||||
| PropsWithoutLink
|
||||
type Props = PropsWithLink | PropsWithoutLink
|
||||
|
||||
|
||||
export default (({ tag,
|
||||
@@ -36,7 +29,6 @@ export default (({ tag,
|
||||
linkFlg = true,
|
||||
withWiki = true,
|
||||
withCount = true,
|
||||
prefetch = false,
|
||||
...props }: Props) => {
|
||||
const [havingWiki, setHavingWiki] = useState (true)
|
||||
|
||||
@@ -51,7 +43,7 @@ export default (({ tag,
|
||||
|
||||
try
|
||||
{
|
||||
await apiGet (`/wiki/title/${ encodeURIComponent (tagName) }/exists`)
|
||||
await axios.get (`${ API_BASE_URL }/wiki/title/${ encodeURIComponent (tagName) }/exists`)
|
||||
setHavingWiki (true)
|
||||
}
|
||||
catch
|
||||
@@ -81,17 +73,17 @@ export default (({ tag,
|
||||
<span className="mr-1">
|
||||
{havingWiki
|
||||
? (
|
||||
<PrefetchLink to={`/wiki/${ encodeURIComponent (tag.name) }`}
|
||||
<Link to={`/wiki/${ encodeURIComponent (tag.name) }`}
|
||||
className={linkClass}>
|
||||
?
|
||||
</PrefetchLink>)
|
||||
</Link>)
|
||||
: (
|
||||
<PrefetchLink to={`/wiki/${ encodeURIComponent (tag.name) }`}
|
||||
<Link to={`/wiki/${ encodeURIComponent (tag.name) }`}
|
||||
className="animate-[wiki-blink_.25s_steps(2,end)_infinite]
|
||||
dark:animate-[wiki-blink-dark_.25s_steps(2,end)_infinite]"
|
||||
title={`${ tag.name } Wiki が存在しません.`}>
|
||||
!
|
||||
</PrefetchLink>)}
|
||||
</Link>)}
|
||||
</span>)}
|
||||
{nestLevel > 0 && (
|
||||
<span
|
||||
@@ -108,19 +100,11 @@ export default (({ tag,
|
||||
</>)}
|
||||
{linkFlg
|
||||
? (
|
||||
prefetch
|
||||
? <PrefetchLink
|
||||
to={`/posts?${ (new URLSearchParams ({ tags: tag.name })).toString () }`}
|
||||
<Link to={`/posts?${ (new URLSearchParams ({ tags: tag.name })).toString () }`}
|
||||
className={linkClass}
|
||||
{...props}>
|
||||
{tag.name}
|
||||
</PrefetchLink>
|
||||
: <PrefetchLink
|
||||
to={`/posts?${ (new URLSearchParams ({ tags: tag.name })).toString () }`}
|
||||
className={linkClass}
|
||||
{...props}>
|
||||
{tag.name}
|
||||
</PrefetchLink>)
|
||||
{tag.name}
|
||||
</Link>)
|
||||
: (
|
||||
<span className={spanClass}
|
||||
{...props}>
|
||||
|
||||
@@ -1,13 +1,13 @@
|
||||
// TODO: タグ入力系すべてに同様の処理あるため共通化する.
|
||||
|
||||
import { useEffect, useState } from 'react'
|
||||
import axios from 'axios'
|
||||
import toCamel from 'camelcase-keys'
|
||||
import React, { useEffect, useState } from 'react'
|
||||
import { useNavigate, useLocation } from 'react-router-dom'
|
||||
|
||||
import { apiGet } from '@/lib/api'
|
||||
import { API_BASE_URL } from '@/config'
|
||||
|
||||
import TagSearchBox from './TagSearchBox'
|
||||
|
||||
import type { ChangeEvent, FC, KeyboardEvent } from 'react'
|
||||
import type { FC } from 'react'
|
||||
|
||||
import type { Tag } from '@/types'
|
||||
|
||||
@@ -21,7 +21,7 @@ export default (() => {
|
||||
const [suggestions, setSuggestions] = useState<Tag[]> ([])
|
||||
const [suggestionsVsbl, setSuggestionsVsbl] = useState (false)
|
||||
|
||||
const whenChanged = async (ev: ChangeEvent<HTMLInputElement>) => {
|
||||
const whenChanged = async (ev: React.ChangeEvent<HTMLInputElement>) => {
|
||||
setSearch (ev.target.value)
|
||||
|
||||
const q = ev.target.value.trim ().split (' ').at (-1)
|
||||
@@ -31,13 +31,14 @@ export default (() => {
|
||||
return
|
||||
}
|
||||
|
||||
const data = await apiGet<Tag[]> ('/tags/autocomplete', { params: { q } })
|
||||
const res = await axios.get (`${ API_BASE_URL }/tags/autocomplete`, { params: { q } })
|
||||
const data = toCamel (res.data, { deep: true }) as Tag[]
|
||||
setSuggestions (data.filter (t => t.postCount > 0))
|
||||
if (suggestions.length > 0)
|
||||
setSuggestionsVsbl (true)
|
||||
}
|
||||
|
||||
const handleKeyDown = (ev: KeyboardEvent<HTMLInputElement>) => {
|
||||
const handleKeyDown = (ev: React.KeyboardEvent<HTMLInputElement>) => {
|
||||
switch (ev.key)
|
||||
{
|
||||
case 'ArrowDown':
|
||||
|
||||
@@ -1,3 +1,4 @@
|
||||
import axios from 'axios'
|
||||
import { AnimatePresence, motion } from 'framer-motion'
|
||||
import { useEffect, useState } from 'react'
|
||||
import { useLocation, useNavigate } from 'react-router-dom'
|
||||
@@ -6,20 +7,19 @@ import TagLink from '@/components/TagLink'
|
||||
import TagSearch from '@/components/TagSearch'
|
||||
import SectionTitle from '@/components/common/SectionTitle'
|
||||
import SidebarComponent from '@/components/layout/SidebarComponent'
|
||||
import { API_BASE_URL } from '@/config'
|
||||
import { CATEGORIES } from '@/consts'
|
||||
import { apiGet } from '@/lib/api'
|
||||
|
||||
import type { FC, MouseEvent } from 'react'
|
||||
import type { FC } from 'react'
|
||||
|
||||
import type { Post, Tag } from '@/types'
|
||||
|
||||
type TagByCategory = Record<string, Tag[]>
|
||||
|
||||
type Props = { posts: Post[]
|
||||
onClick?: (event: MouseEvent<HTMLElement>) => void }
|
||||
type Props = { posts: Post[] }
|
||||
|
||||
|
||||
export default (({ posts, onClick }: Props) => {
|
||||
export default (({ posts }: Props) => {
|
||||
const navigate = useNavigate ()
|
||||
|
||||
const [tagsVsbl, setTagsVsbl] = useState (false)
|
||||
@@ -65,7 +65,7 @@ export default (({ posts, onClick }: Props) => {
|
||||
{CATEGORIES.flatMap (cat => cat in tags ? (
|
||||
tags[cat].map (tag => (
|
||||
<li key={tag.id} className="mb-1">
|
||||
<TagLink tag={tag} prefetch onClick={onClick}/>
|
||||
<TagLink tag={tag}/>
|
||||
</li>))) : [])}
|
||||
</ul>
|
||||
<SectionTitle>関聯</SectionTitle>
|
||||
@@ -76,10 +76,10 @@ export default (({ posts, onClick }: Props) => {
|
||||
void ((async () => {
|
||||
try
|
||||
{
|
||||
const data = await apiGet<Post> ('/posts/random',
|
||||
{ params: { tags: tagsQuery.split (' ').filter (e => e !== '').join (' '),
|
||||
const { data } = await axios.get (`${ API_BASE_URL }/posts/random`,
|
||||
{ params: { tags: tagsQuery.split (' ').filter (e => e !== '').join (' '),
|
||||
match: (anyFlg ? 'any' : 'all') } })
|
||||
navigate (`/posts/${ data.id }`)
|
||||
navigate (`/posts/${ (data as Post).id }`)
|
||||
}
|
||||
catch
|
||||
{
|
||||
|
||||
@@ -1,20 +1,18 @@
|
||||
import { useQuery } from '@tanstack/react-query'
|
||||
import axios from 'axios'
|
||||
import toCamel from 'camelcase-keys'
|
||||
import { AnimatePresence, motion } from 'framer-motion'
|
||||
import { Fragment, useEffect, useLayoutEffect, useRef, useState } from 'react'
|
||||
import { useLocation } from 'react-router-dom'
|
||||
import { Link, useLocation } from 'react-router-dom'
|
||||
|
||||
import Separator from '@/components/MenuSeparator'
|
||||
import PrefetchLink from '@/components/PrefetchLink'
|
||||
import TopNavUser from '@/components/TopNavUser'
|
||||
import { API_BASE_URL } from '@/config'
|
||||
import { WikiIdBus } from '@/lib/eventBus/WikiIdBus'
|
||||
import { tagsKeys, wikiKeys } from '@/lib/queryKeys'
|
||||
import { fetchTagByName } from '@/lib/tags'
|
||||
import { cn } from '@/lib/utils'
|
||||
import { fetchWikiPage } from '@/lib/wiki'
|
||||
|
||||
import type { FC, MouseEvent } from 'react'
|
||||
import type { FC } from 'react'
|
||||
|
||||
import type { Menu, User } from '@/types'
|
||||
import type { Menu, Tag, User, WikiPage } from '@/types'
|
||||
|
||||
type Props = { user: User | null }
|
||||
|
||||
@@ -46,32 +44,16 @@ export default (({ user }: Props) => {
|
||||
visible: false })
|
||||
const [menuOpen, setMenuOpen] = useState (false)
|
||||
const [openItemIdx, setOpenItemIdx] = useState (-1)
|
||||
const [postCount, setPostCount] = useState<number | null> (null)
|
||||
const [wikiId, setWikiId] = useState<number | null> (WikiIdBus.get ())
|
||||
|
||||
const wikiIdStr = String (wikiId ?? '')
|
||||
|
||||
const { data: wikiPage } = useQuery ({
|
||||
enabled: Boolean (wikiIdStr),
|
||||
queryKey: wikiKeys.show (wikiIdStr, { }),
|
||||
queryFn: () => fetchWikiPage (wikiIdStr, { }) })
|
||||
|
||||
const effectiveTitle = wikiPage?.title ?? ''
|
||||
|
||||
const { data: tag } = useQuery ({
|
||||
enabled: Boolean (effectiveTitle),
|
||||
queryKey: tagsKeys.show (effectiveTitle),
|
||||
queryFn: () => fetchTagByName (effectiveTitle) })
|
||||
|
||||
const postCount = tag?.postCount ?? 0
|
||||
|
||||
const wikiPageFlg = Boolean (/^\/wiki\/(?!new|changes)[^\/]+/.test (location.pathname) && wikiId)
|
||||
const wikiTitle = location.pathname.split ('/')[2] ?? ''
|
||||
const wikiTitle = location.pathname.split ('/')[2]
|
||||
const menu: Menu = [
|
||||
{ name: '広場', to: '/posts', subMenu: [
|
||||
{ name: '一覧', to: '/posts' },
|
||||
{ name: '検索', to: '/posts/search' },
|
||||
{ name: '投稿追加', to: '/posts/new' },
|
||||
{ name: '履歴', to: '/posts/changes' },
|
||||
{ name: '耕作履歴', to: '/posts/changes' },
|
||||
{ name: 'ヘルプ', to: '/wiki/ヘルプ:広場' }] },
|
||||
{ name: 'タグ', to: '/tags', subMenu: [
|
||||
{ name: 'タグ一覧', to: '/tags', visible: false },
|
||||
@@ -131,20 +113,39 @@ export default (({ user }: Props) => {
|
||||
location.pathname.startsWith (item.base || item.to))))
|
||||
}, [location])
|
||||
|
||||
useEffect (() => {
|
||||
if (!(wikiId))
|
||||
return
|
||||
|
||||
const fetchPostCount = async () => {
|
||||
try
|
||||
{
|
||||
const pageRes = await axios.get (`${ API_BASE_URL }/wiki/${ wikiId }`)
|
||||
const wikiPage = toCamel (pageRes.data as any, { deep: true }) as WikiPage
|
||||
|
||||
const tagRes = await axios.get (`${ API_BASE_URL }/tags/name/${ wikiPage.title }`)
|
||||
const tag = toCamel (tagRes.data as any, { deep: true }) as Tag
|
||||
|
||||
setPostCount (tag.postCount)
|
||||
}
|
||||
catch
|
||||
{
|
||||
setPostCount (0)
|
||||
}
|
||||
}
|
||||
fetchPostCount ()
|
||||
}, [wikiId])
|
||||
|
||||
return (
|
||||
<>
|
||||
<nav className="px-3 flex justify-between items-center w-full min-h-[48px]
|
||||
bg-yellow-200 dark:bg-red-975 md:bg-yellow-50">
|
||||
<div className="flex items-center gap-2 h-full">
|
||||
<PrefetchLink
|
||||
to="/posts"
|
||||
className="mx-4 text-xl font-bold text-pink-600 hover:text-pink-400
|
||||
dark:text-pink-300 dark:hover:text-pink-100"
|
||||
onClick={() => {
|
||||
scroll (0, 0)
|
||||
}}>
|
||||
<Link to="/"
|
||||
className="mx-4 text-xl font-bold text-pink-600 hover:text-pink-400
|
||||
dark:text-pink-300 dark:hover:text-pink-100">
|
||||
ぼざクリ タグ広場
|
||||
</PrefetchLink>
|
||||
</Link>
|
||||
|
||||
<div ref={navRef} className="relative hidden md:flex h-full items-center">
|
||||
<div aria-hidden
|
||||
@@ -156,16 +157,15 @@ export default (({ user }: Props) => {
|
||||
opacity: hl.visible ? 1 : 0 }}/>
|
||||
|
||||
{menu.map ((item, i) => (
|
||||
<PrefetchLink
|
||||
key={i}
|
||||
to={item.to}
|
||||
ref={(el: (HTMLAnchorElement | null)) => {
|
||||
itemsRef.current[i] = el
|
||||
}}
|
||||
className={cn ('relative z-10 flex h-full items-center px-5',
|
||||
(i === openItemIdx) && 'font-bold')}>
|
||||
<Link key={i}
|
||||
to={item.to}
|
||||
ref={el => {
|
||||
itemsRef.current[i] = el
|
||||
}}
|
||||
className={cn ('relative z-10 flex h-full items-center px-5',
|
||||
(i === openItemIdx) && 'font-bold')}>
|
||||
{item.name}
|
||||
</PrefetchLink>))}
|
||||
</Link>))}
|
||||
</div>
|
||||
</div>
|
||||
|
||||
@@ -203,12 +203,11 @@ export default (({ user }: Props) => {
|
||||
'component' in item
|
||||
? <Fragment key={`c-${ i }`}>{item.component}</Fragment>
|
||||
: (
|
||||
<PrefetchLink
|
||||
key={`l-${ i }`}
|
||||
to={item.to}
|
||||
className="h-full flex items-center px-3">
|
||||
<Link key={`l-${ i }`}
|
||||
to={item.to}
|
||||
className="h-full flex items-center px-3">
|
||||
{item.name}
|
||||
</PrefetchLink>)))}
|
||||
</Link>)))}
|
||||
</motion.div>
|
||||
</AnimatePresence>
|
||||
</div>
|
||||
@@ -230,20 +229,19 @@ export default (({ user }: Props) => {
|
||||
<Separator/>
|
||||
{menu.map ((item, i) => (
|
||||
<Fragment key={i}>
|
||||
<PrefetchLink
|
||||
to={i === openItemIdx ? item.to : '#'}
|
||||
className={cn ('w-full min-h-[40px] flex items-center pl-8',
|
||||
((i === openItemIdx)
|
||||
&& 'font-bold bg-yellow-50 dark:bg-red-950'))}
|
||||
onClick={(ev: MouseEvent<HTMLAnchorElement>) => {
|
||||
if (i !== openItemIdx)
|
||||
{
|
||||
ev.preventDefault ()
|
||||
setOpenItemIdx (i)
|
||||
}
|
||||
}}>
|
||||
<Link to={i === openItemIdx ? item.to : '#'}
|
||||
className={cn ('w-full min-h-[40px] flex items-center pl-8',
|
||||
((i === openItemIdx)
|
||||
&& 'font-bold bg-yellow-50 dark:bg-red-950'))}
|
||||
onClick={ev => {
|
||||
if (i !== openItemIdx)
|
||||
{
|
||||
ev.preventDefault ()
|
||||
setOpenItemIdx (i)
|
||||
}
|
||||
}}>
|
||||
{item.name}
|
||||
</PrefetchLink>
|
||||
</Link>
|
||||
|
||||
<AnimatePresence initial={false}>
|
||||
{i === openItemIdx && (
|
||||
@@ -269,12 +267,11 @@ export default (({ user }: Props) => {
|
||||
{subItem.component}
|
||||
</Fragment>)
|
||||
: (
|
||||
<PrefetchLink
|
||||
key={`sp-l-${ i }-${ j }`}
|
||||
to={subItem.to}
|
||||
className="w-full min-h-[36px] flex items-center pl-12">
|
||||
<Link key={`sp-l-${ i }-${ j }`}
|
||||
to={subItem.to}
|
||||
className="w-full min-h-[36px] flex items-center pl-12">
|
||||
{subItem.name}
|
||||
</PrefetchLink>)))}
|
||||
</Link>)))}
|
||||
</motion.div>)}
|
||||
</AnimatePresence>
|
||||
</Fragment>))}
|
||||
|
||||
@@ -1,5 +1,6 @@
|
||||
import { Link } from 'react-router-dom'
|
||||
|
||||
import Separator from '@/components/MenuSeparator'
|
||||
import PrefetchLink from '@/components/PrefetchLink'
|
||||
import { cn } from '@/lib/utils'
|
||||
|
||||
import type { FC } from 'react'
|
||||
@@ -23,9 +24,9 @@ export default (({ user, sp }: Props) => {
|
||||
return (
|
||||
<>
|
||||
{sp && <Separator/>}
|
||||
<PrefetchLink to="/users/settings"
|
||||
<Link to="/users/settings"
|
||||
className={className}>
|
||||
{user.name || '名もなきニジラー'}
|
||||
</PrefetchLink>
|
||||
</Link>
|
||||
</>)
|
||||
}) satisfies FC<Props>
|
||||
|
||||
@@ -1,18 +1,20 @@
|
||||
import { useQuery } from '@tanstack/react-query'
|
||||
import { useMemo } from 'react'
|
||||
import axios from 'axios'
|
||||
import toCamel from 'camelcase-keys'
|
||||
import { useEffect, useMemo, useState } from 'react'
|
||||
import ReactMarkdown from 'react-markdown'
|
||||
import { Link } from 'react-router-dom'
|
||||
import remarkGFM from 'remark-gfm'
|
||||
|
||||
import PrefetchLink from '@/components/PrefetchLink'
|
||||
import SectionTitle from '@/components/common/SectionTitle'
|
||||
import SubsectionTitle from '@/components/common/SubsectionTitle'
|
||||
import { wikiKeys } from '@/lib/queryKeys'
|
||||
import { API_BASE_URL } from '@/config'
|
||||
import remarkWikiAutoLink from '@/lib/remark-wiki-autolink'
|
||||
import { fetchWikiPages } from '@/lib/wiki'
|
||||
|
||||
import type { FC } from 'react'
|
||||
import type { Components } from 'react-markdown'
|
||||
|
||||
import type { WikiPage } from '@/types'
|
||||
|
||||
type Props = { title: string
|
||||
body?: string }
|
||||
|
||||
@@ -22,7 +24,7 @@ const mdComponents = { h1: ({ children }) => <SectionTitle>{children}</SectionT
|
||||
ul: ({ children }) => <ul className="list-disc pl-6">{children}</ul>,
|
||||
a: (({ href, children }) => (
|
||||
['/', '.'].some (e => href?.startsWith (e))
|
||||
? <PrefetchLink to={href!}>{children}</PrefetchLink>
|
||||
? <Link to={href!}>{children}</Link>
|
||||
: (
|
||||
<a href={href}
|
||||
target="_blank"
|
||||
@@ -32,15 +34,26 @@ const mdComponents = { h1: ({ children }) => <SectionTitle>{children}</SectionT
|
||||
|
||||
|
||||
export default (({ title, body }: Props) => {
|
||||
const { data } = useQuery ({
|
||||
enabled: Boolean (body),
|
||||
queryKey: wikiKeys.index ({ }),
|
||||
queryFn: () => fetchWikiPages ({ }) })
|
||||
const pageNames = (data ?? []).map (page => page.title).sort ((a, b) => b.length - a.length)
|
||||
const [pageNames, setPageNames] = useState<string[]> ([])
|
||||
|
||||
const remarkPlugins = useMemo (
|
||||
() => [() => remarkWikiAutoLink (pageNames), remarkGFM], [pageNames])
|
||||
|
||||
useEffect (() => {
|
||||
void (async () => {
|
||||
try
|
||||
{
|
||||
const res = await axios.get (`${ API_BASE_URL }/wiki`)
|
||||
const data: WikiPage[] = toCamel (res.data as any, { deep: true })
|
||||
setPageNames (data.map (page => page.title).sort ((a, b) => b.length - a.length))
|
||||
}
|
||||
catch
|
||||
{
|
||||
setPageNames ([])
|
||||
}
|
||||
}) ()
|
||||
}, [])
|
||||
|
||||
return (
|
||||
<ReactMarkdown components={mdComponents} remarkPlugins={remarkPlugins}>
|
||||
{body || `このページは存在しません。[新規作成してください](/wiki/new?title=${ encodeURIComponent (title) })。`}
|
||||
|
||||
@@ -5,7 +5,7 @@ import { cn } from '@/lib/utils'
|
||||
import type { FC, FocusEvent } from 'react'
|
||||
|
||||
|
||||
const pad = (n: number): string => n.toString ().padStart (2, '0')
|
||||
const pad = (n: number) => n.toString ().padStart (2, '0')
|
||||
|
||||
|
||||
const toDateTimeLocalValue = (d: Date) => {
|
||||
@@ -14,7 +14,8 @@ const toDateTimeLocalValue = (d: Date) => {
|
||||
const day = pad (d.getDate ())
|
||||
const h = pad (d.getHours ())
|
||||
const min = pad (d.getMinutes ())
|
||||
return `${ y }-${ m }-${ day }T${ h }:${ min }:00`
|
||||
const s = pad (d.getSeconds ())
|
||||
return `${ y }-${ m }-${ day }T${ h }:${ min }:${ s }`
|
||||
}
|
||||
|
||||
|
||||
@@ -36,6 +37,7 @@ export default (({ value, onChange, className, onBlur }: Props) => {
|
||||
<input
|
||||
className={cn ('border rounded p-2', className)}
|
||||
type="datetime-local"
|
||||
step={1}
|
||||
value={local}
|
||||
onChange={ev => {
|
||||
const v = ev.target.value
|
||||
|
||||
@@ -1,6 +1,4 @@
|
||||
import { useLocation } from 'react-router-dom'
|
||||
|
||||
import PrefetchLink from '@/components/PrefetchLink'
|
||||
import { Link, useLocation } from 'react-router-dom'
|
||||
|
||||
import type { FC } from 'react'
|
||||
|
||||
@@ -63,7 +61,7 @@ export default (({ page, totalPages, siblingCount = 4 }) => {
|
||||
<nav className="mt-4 flex justify-center" aria-label="Pagination">
|
||||
<div className="flex items-center gap-2">
|
||||
{(page > 1)
|
||||
? <PrefetchLink to={buildTo (page - 1)} aria-label="前のページ"><</PrefetchLink>
|
||||
? <Link to={buildTo (page - 1)} aria-label="前のページ"><</Link>
|
||||
: <span aria-hidden><</span>}
|
||||
|
||||
{pages.map ((p, idx) => (
|
||||
@@ -71,10 +69,10 @@ export default (({ page, totalPages, siblingCount = 4 }) => {
|
||||
? <span key={`dots-${ idx }`}>…</span>
|
||||
: ((p === page)
|
||||
? <span key={p} className="font-bold" aria-current="page">{p}</span>
|
||||
: <PrefetchLink key={p} to={buildTo (p)}>{p}</PrefetchLink>)))}
|
||||
: <Link key={p} to={buildTo (p)}>{p}</Link>)))}
|
||||
|
||||
{(page < totalPages)
|
||||
? <PrefetchLink to={buildTo (page + 1)} aria-label="次のページ">></PrefetchLink>
|
||||
? <Link to={buildTo (page + 1)} aria-label="次のページ">></Link>
|
||||
: <span aria-hidden>></span>}
|
||||
</div>
|
||||
</nav>)
|
||||
|
||||
@@ -1,3 +1,5 @@
|
||||
import axios from 'axios'
|
||||
import toCamel from 'camelcase-keys'
|
||||
import { useState } from 'react'
|
||||
|
||||
import { Button } from '@/components/ui/button'
|
||||
@@ -6,7 +8,7 @@ import { Dialog,
|
||||
DialogTitle } from '@/components/ui/dialog'
|
||||
import { Input } from '@/components/ui/input'
|
||||
import { toast } from '@/components/ui/use-toast'
|
||||
import { apiPost } from '@/lib/api'
|
||||
import { API_BASE_URL } from '@/config'
|
||||
|
||||
import type { User } from '@/types'
|
||||
|
||||
@@ -24,12 +26,12 @@ export default ({ visible, onVisibleChange, setUser }: Props) => {
|
||||
|
||||
try
|
||||
{
|
||||
const data = await apiPost<{ valid: boolean; user: User }> (
|
||||
'/users/verify', { code: inputCode })
|
||||
const res = await axios.post (`${ API_BASE_URL }/users/verify`, { code: inputCode })
|
||||
const data = res.data as { valid: boolean; user: any }
|
||||
if (data.valid)
|
||||
{
|
||||
localStorage.setItem ('user_code', inputCode)
|
||||
setUser (data.user)
|
||||
setUser (toCamel (data.user, { deep: true }))
|
||||
toast ({ title: '引継ぎ成功!' })
|
||||
onVisibleChange (false)
|
||||
}
|
||||
|
||||
@@ -1,9 +1,11 @@
|
||||
import axios from 'axios'
|
||||
|
||||
import { Button } from '@/components/ui/button'
|
||||
import { Dialog,
|
||||
DialogContent,
|
||||
DialogTitle } from '@/components/ui/dialog'
|
||||
import { toast } from '@/components/ui/use-toast'
|
||||
import { apiPost } from '@/lib/api'
|
||||
import { API_BASE_URL } from '@/config'
|
||||
|
||||
import type { User } from '@/types'
|
||||
|
||||
@@ -21,8 +23,10 @@ export default ({ visible, onVisibleChange, user, setUser }: Props) => {
|
||||
if (!(confirm ('引継ぎコードを再発行しますか?\n再発行するとほかのブラウザからはログアウトされます.')))
|
||||
return
|
||||
|
||||
const data = await apiPost<{ code: string }> ('/users/code/renew', { },
|
||||
{ headers: { 'Content-Type': 'multipart/form-data' } })
|
||||
const res = await axios.post (`${ API_BASE_URL }/users/code/renew`, { }, { headers: {
|
||||
'Content-Type': 'multipart/form-data',
|
||||
'X-Transfer-Code': localStorage.getItem ('user_code') || '' } })
|
||||
const data = res.data as { code: string }
|
||||
if (data.code)
|
||||
{
|
||||
localStorage.setItem ('user_code', data.code)
|
||||
|
||||
+11
-24
@@ -3,23 +3,13 @@ import type { Category } from 'types'
|
||||
export const LIGHT_COLOUR_SHADE = 800
|
||||
export const DARK_COLOUR_SHADE = 300
|
||||
|
||||
export const CATEGORIES = [
|
||||
'deerjikist',
|
||||
'meme',
|
||||
'character',
|
||||
'general',
|
||||
'material',
|
||||
'meta',
|
||||
'nico',
|
||||
] as const
|
||||
|
||||
export const FETCH_POSTS_ORDER_FIELDS = [
|
||||
'title',
|
||||
'url',
|
||||
'original_created_at',
|
||||
'created_at',
|
||||
'updated_at',
|
||||
] as const
|
||||
export const CATEGORIES = ['deerjikist',
|
||||
'meme',
|
||||
'character',
|
||||
'general',
|
||||
'material',
|
||||
'meta',
|
||||
'nico'] as const
|
||||
|
||||
export const TAG_COLOUR = {
|
||||
deerjikist: 'rose',
|
||||
@@ -28,13 +18,10 @@ export const TAG_COLOUR = {
|
||||
general: 'cyan',
|
||||
material: 'orange',
|
||||
meta: 'yellow',
|
||||
nico: 'gray',
|
||||
} as const satisfies Record<Category, string>
|
||||
nico: 'gray' } as const satisfies Record<Category, string>
|
||||
|
||||
export const USER_ROLES = ['admin', 'member', 'guest'] as const
|
||||
|
||||
export const ViewFlagBehavior = {
|
||||
OnShowedDetail: 1,
|
||||
OnClickedLink: 2,
|
||||
NotAuto: 3,
|
||||
} as const
|
||||
export const ViewFlagBehavior = { OnShowedDetail: 1,
|
||||
OnClickedLink: 2,
|
||||
NotAuto: 3 } as const
|
||||
|
||||
@@ -1,75 +0,0 @@
|
||||
import axios from 'axios'
|
||||
import toCamel from 'camelcase-keys'
|
||||
|
||||
import { API_BASE_URL } from '@/config'
|
||||
|
||||
import type { AxiosError, AxiosRequestConfig } from 'axios'
|
||||
|
||||
type Opt = {
|
||||
params?: AxiosRequestConfig['params']
|
||||
headers?: Record<string, string>
|
||||
responseType?: 'blob' }
|
||||
|
||||
const client = axios.create ({ baseURL: API_BASE_URL })
|
||||
|
||||
|
||||
const withUserCode = (opt?: Opt): Opt => ({
|
||||
...opt,
|
||||
headers: { 'X-Transfer-Code': localStorage.getItem ('user_code') ?? '',
|
||||
...(opt?.headers ?? { }) } })
|
||||
|
||||
|
||||
const apiP = async <T> (
|
||||
method: 'post' | 'put' | 'patch',
|
||||
path: string,
|
||||
body?: unknown,
|
||||
opt?: Opt,
|
||||
): Promise<T> => {
|
||||
const res = await client[method] (path, body ?? { }, withUserCode (opt))
|
||||
if (opt?.responseType === 'blob')
|
||||
return res.data as T
|
||||
return toCamel (res.data as any, { deep: true }) as T
|
||||
}
|
||||
|
||||
|
||||
export const apiGet = async <T> (
|
||||
path: string,
|
||||
opt?: Opt,
|
||||
): Promise<T> => {
|
||||
const res = await client.get (path, withUserCode (opt))
|
||||
if (opt?.responseType === 'blob')
|
||||
return res.data as T
|
||||
return toCamel (res.data as any, { deep: true }) as T
|
||||
}
|
||||
|
||||
|
||||
export const apiPost = async <T> (
|
||||
path: string,
|
||||
body?: unknown,
|
||||
opt?: Opt,
|
||||
): Promise<T> => apiP ('post', path, body, opt)
|
||||
|
||||
|
||||
export const apiPut = async <T> (
|
||||
path: string,
|
||||
body?: unknown,
|
||||
opt?: Opt,
|
||||
): Promise<T> => apiP ('put', path, body, opt)
|
||||
|
||||
|
||||
export const apiPatch = async <T> (
|
||||
path: string,
|
||||
body?: unknown,
|
||||
opt?: Opt,
|
||||
): Promise<T> => apiP ('patch', path, body, opt)
|
||||
|
||||
|
||||
export const apiDelete = async (
|
||||
path: string,
|
||||
opt?: Opt,
|
||||
): Promise<void> => {
|
||||
await client.delete (path, withUserCode (opt))
|
||||
}
|
||||
|
||||
|
||||
export const isApiError = (err: unknown): err is AxiosError => axios.isAxiosError (err)
|
||||
+16
-37
@@ -1,44 +1,23 @@
|
||||
import { apiDelete, apiGet, apiPost } from '@/lib/api'
|
||||
import axios from 'axios'
|
||||
import toCamel from 'camelcase-keys'
|
||||
|
||||
import type { FetchPostsParams, Post, PostTagChange } from '@/types'
|
||||
import { API_BASE_URL } from '@/config'
|
||||
|
||||
import type { Post } from '@/types'
|
||||
|
||||
|
||||
export const fetchPosts = async (
|
||||
{ url, title, tags, match, createdFrom, createdTo, updatedFrom, updatedTo,
|
||||
originalCreatedFrom, originalCreatedTo, page, limit, order }: FetchPostsParams
|
||||
): Promise<{
|
||||
posts: Post[]
|
||||
count: number }> =>
|
||||
await apiGet ('/posts', { params: {
|
||||
...(url && { url }),
|
||||
...(title && { title }),
|
||||
...(tags && { tags }),
|
||||
...(match && { match }),
|
||||
...(createdFrom && { created_from: createdFrom }),
|
||||
...(createdTo && { created_to: createdTo }),
|
||||
...(updatedFrom && { updated_from: updatedFrom }),
|
||||
...(updatedTo && { updated_to: updatedTo }),
|
||||
...(originalCreatedFrom && { original_created_from: originalCreatedFrom }),
|
||||
...(originalCreatedTo && { original_created_to: originalCreatedTo }),
|
||||
...(page && { page }),
|
||||
...(limit && { limit }),
|
||||
...(order && { order }) } })
|
||||
|
||||
|
||||
export const fetchPost = async (id: string): Promise<Post> => await apiGet (`/posts/${ id }`)
|
||||
|
||||
|
||||
export const fetchPostChanges = async (
|
||||
{ id, page, limit }: {
|
||||
id?: string
|
||||
page: number
|
||||
limit: number },
|
||||
): Promise<{
|
||||
changes: PostTagChange[]
|
||||
count: number }> =>
|
||||
await apiGet ('/posts/changes', { params: { ...(id && { id }), page, limit } })
|
||||
export const fetchPost = async (id: string): Promise<Post> => {
|
||||
const res = await axios.get (`${ API_BASE_URL }/posts/${ id }`, {
|
||||
headers: { 'X-Transfer-Code': localStorage.getItem ('user_code') ?? '' } })
|
||||
return toCamel (res.data as any, { deep: true }) as Post
|
||||
}
|
||||
|
||||
|
||||
export const toggleViewedFlg = async (id: string, viewed: boolean): Promise<void> => {
|
||||
await (viewed ? apiPost : apiDelete) (`/posts/${ id }/viewed`)
|
||||
const url = `${ API_BASE_URL }/posts/${ id }/viewed`
|
||||
const opt = { headers: { 'X-Transfer-Code': localStorage.getItem ('user_code') ?? '' } }
|
||||
if (viewed)
|
||||
await axios.post (url, { }, opt)
|
||||
else
|
||||
await axios.delete (url, opt)
|
||||
}
|
||||
|
||||
@@ -1,154 +0,0 @@
|
||||
import { QueryClient } from '@tanstack/react-query'
|
||||
import { match } from 'path-to-regexp'
|
||||
|
||||
import { fetchPost, fetchPosts, fetchPostChanges } from '@/lib/posts'
|
||||
import { postsKeys, tagsKeys, wikiKeys } from '@/lib/queryKeys'
|
||||
import { fetchTagByName } from '@/lib/tags'
|
||||
import { fetchWikiPage,
|
||||
fetchWikiPageByTitle,
|
||||
fetchWikiPages } from '@/lib/wiki'
|
||||
|
||||
import type { FetchPostsOrder } from '@/types'
|
||||
|
||||
type Prefetcher = (qc: QueryClient, url: URL) => Promise<void>
|
||||
|
||||
const mPost = match<{ id: string }> ('/posts/:id')
|
||||
const mWiki = match<{ title: string }> ('/wiki/:title')
|
||||
|
||||
|
||||
const prefetchWikiPagesIndex: Prefetcher = async (qc, url) => {
|
||||
const title = url.searchParams.get ('title') ?? ''
|
||||
|
||||
await qc.prefetchQuery ({
|
||||
queryKey: wikiKeys.index ({ title }),
|
||||
queryFn: () => fetchWikiPages ({ title }) })
|
||||
}
|
||||
|
||||
|
||||
const prefetchWikiPageShow: Prefetcher = async (qc, url) => {
|
||||
const m = mWiki (url.pathname)
|
||||
if (!(m))
|
||||
return
|
||||
|
||||
const title = decodeURIComponent (m.params.title)
|
||||
const version = url.searchParams.get ('version') || undefined
|
||||
|
||||
const wikiPage = await qc.fetchQuery ({
|
||||
queryKey: wikiKeys.show (title, { version }),
|
||||
queryFn: () => fetchWikiPageByTitle (title, { version }) })
|
||||
|
||||
if (wikiPage)
|
||||
{
|
||||
const effectiveId = String (wikiPage.id ?? '')
|
||||
await qc.prefetchQuery ({
|
||||
queryKey: wikiKeys.show (effectiveId, { }),
|
||||
queryFn: () => fetchWikiPage (effectiveId, { } ) })
|
||||
|
||||
if (wikiPage.body)
|
||||
{
|
||||
await qc.prefetchQuery ({
|
||||
queryKey: wikiKeys.index ({ }),
|
||||
queryFn: () => fetchWikiPages ({ }) })
|
||||
}
|
||||
}
|
||||
|
||||
const effectiveTitle = wikiPage?.title ?? title
|
||||
|
||||
await qc.prefetchQuery ({
|
||||
queryKey: tagsKeys.show (effectiveTitle),
|
||||
queryFn: () => fetchTagByName (effectiveTitle) })
|
||||
|
||||
if (version)
|
||||
return
|
||||
|
||||
const p = {
|
||||
tags: effectiveTitle,
|
||||
match: 'all',
|
||||
page: 1,
|
||||
limit: 8,
|
||||
url: '',
|
||||
title: '',
|
||||
originalCreatedFrom: '',
|
||||
originalCreatedTo: '',
|
||||
createdFrom: '',
|
||||
createdTo: '',
|
||||
updatedFrom: '',
|
||||
updatedTo: '',
|
||||
order: 'original_created_at:desc' } as const
|
||||
await qc.prefetchQuery ({
|
||||
queryKey: postsKeys.index (p),
|
||||
queryFn: () => fetchPosts (p) })
|
||||
}
|
||||
|
||||
|
||||
const prefetchPostsIndex: Prefetcher = async (qc, url) => {
|
||||
const tags = url.searchParams.get ('tags') ?? ''
|
||||
const qURL = url.searchParams.get ('url') ?? ''
|
||||
const title = url.searchParams.get ('title') ?? ''
|
||||
const originalCreatedFrom = url.searchParams.get ('original_created_from') ?? ''
|
||||
const originalCreatedTo = url.searchParams.get ('original_created_to') ?? ''
|
||||
const createdFrom = url.searchParams.get ('created_from') ?? ''
|
||||
const createdTo = url.searchParams.get ('created_to') ?? ''
|
||||
const updatedFrom = url.searchParams.get ('updated_from') ?? ''
|
||||
const updatedTo = url.searchParams.get ('updated_to') ?? ''
|
||||
const m: 'all' | 'any' = url.searchParams.get ('match') === 'any' ? 'any' : 'all'
|
||||
const page = Number (url.searchParams.get ('page') || 1)
|
||||
const limit = Number (url.searchParams.get ('limit') || 20)
|
||||
const order = (url.searchParams.get ('order') ?? 'original_created_at:desc') as FetchPostsOrder
|
||||
|
||||
const keys = {
|
||||
tags, match: m, page, limit, url: qURL, title,
|
||||
originalCreatedFrom, originalCreatedTo, createdFrom, createdTo,
|
||||
updatedFrom, updatedTo, order }
|
||||
|
||||
await qc.prefetchQuery ({
|
||||
queryKey: postsKeys.index (keys),
|
||||
queryFn: () => fetchPosts (keys) })
|
||||
}
|
||||
|
||||
|
||||
const prefetchPostShow: Prefetcher = async (qc, url) => {
|
||||
const m = mPost (url.pathname)
|
||||
if (!(m))
|
||||
return
|
||||
|
||||
const { id } = m.params
|
||||
|
||||
await qc.prefetchQuery ({
|
||||
queryKey: postsKeys.show (id),
|
||||
queryFn: () => fetchPost (id) })
|
||||
}
|
||||
|
||||
|
||||
const prefetchPostChanges: Prefetcher = async (qc, url) => {
|
||||
const id = url.searchParams.get ('id')
|
||||
const page = Number (url.searchParams.get ('page') || 1)
|
||||
const limit = Number (url.searchParams.get ('limit') || 20)
|
||||
|
||||
await qc.prefetchQuery ({
|
||||
queryKey: postsKeys.changes ({ ...(id && { id }), page, limit }),
|
||||
queryFn: () => fetchPostChanges ({ ...(id && { id }), page, limit }) })
|
||||
}
|
||||
|
||||
|
||||
export const routePrefetchers: { test: (u: URL) => boolean; run: Prefetcher }[] = [
|
||||
{ test: u => ['/', '/posts', '/posts/search'].includes (u.pathname),
|
||||
run: prefetchPostsIndex },
|
||||
{ test: u => (!(['/posts/new', '/posts/changes', '/posts/search'].includes (u.pathname))
|
||||
&& Boolean (mPost (u.pathname))),
|
||||
run: prefetchPostShow },
|
||||
{ test: u => u.pathname === '/posts/changes', run: prefetchPostChanges },
|
||||
{ test: u => u.pathname === '/wiki', run: prefetchWikiPagesIndex },
|
||||
{ test: u => (!(['/wiki/new', '/wiki/changes'].includes (u.pathname))
|
||||
&& Boolean (mWiki (u.pathname))),
|
||||
run: prefetchWikiPageShow }]
|
||||
|
||||
|
||||
export const prefetchForURL = async (qc: QueryClient, urlLike: string): Promise<void> => {
|
||||
const u = new URL (urlLike, location.origin)
|
||||
const r = routePrefetchers.find (x => x.test (u))
|
||||
if (!(r))
|
||||
return
|
||||
|
||||
await r.run (qc, u)
|
||||
}
|
||||
@@ -1,18 +0,0 @@
|
||||
import type { FetchPostsParams } from '@/types'
|
||||
|
||||
export const postsKeys = {
|
||||
root: ['posts'] as const,
|
||||
index: (p: FetchPostsParams) => ['posts', 'index', p] as const,
|
||||
show: (id: string) => ['posts', id] as const,
|
||||
related: (id: string) => ['related', id] as const,
|
||||
changes: (p: { id?: string; page: number; limit: number }) =>
|
||||
['posts', 'changes', p] as const }
|
||||
|
||||
export const tagsKeys = {
|
||||
root: ['tags'] as const,
|
||||
show: (name: string) => ['tags', name] as const }
|
||||
|
||||
export const wikiKeys = {
|
||||
root: ['wiki'] as const,
|
||||
index: (p: { title?: string }) => ['wiki', 'index', p] as const,
|
||||
show: (title: string, p: { version?: string }) => ['wiki', title, p] as const }
|
||||
@@ -1,15 +0,0 @@
|
||||
import { apiGet } from '@/lib/api'
|
||||
|
||||
import type { Tag } from '@/types'
|
||||
|
||||
|
||||
export const fetchTagByName = async (name: string): Promise<Tag | null> => {
|
||||
try
|
||||
{
|
||||
return await apiGet (`/tags/name/${ name }`)
|
||||
}
|
||||
catch
|
||||
{
|
||||
return null
|
||||
}
|
||||
}
|
||||
+4
-24
@@ -1,26 +1,6 @@
|
||||
import { clsx } from 'clsx'
|
||||
import { clsx, type ClassValue } from 'clsx'
|
||||
import { twMerge } from 'tailwind-merge'
|
||||
|
||||
import type { ClassValue } from 'clsx'
|
||||
|
||||
|
||||
export const toDate = (d: string | Date): Date => typeof d === 'string' ? new Date (d) : d
|
||||
|
||||
|
||||
export const cn = (...inputs: ClassValue[]) => twMerge (clsx (...inputs))
|
||||
|
||||
|
||||
export const dateString = (d: string | Date): string =>
|
||||
toDate (d).toLocaleString ('ja-JP-u-ca-japanese')
|
||||
|
||||
|
||||
// TODO: 表示形式きしょすぎるので何とかする
|
||||
export const originalCreatedAtString = (
|
||||
f: string | Date | null,
|
||||
b: string | Date | null,
|
||||
): string =>
|
||||
([f ? `${ dateString (f) } 以降` : '',
|
||||
b ? `${ dateString (b) } より前` : '']
|
||||
.filter (Boolean)
|
||||
.join (' '))
|
||||
|| '不明'
|
||||
export function cn (...inputs: ClassValue[]) {
|
||||
return twMerge(clsx(...inputs))
|
||||
}
|
||||
|
||||
@@ -1,31 +0,0 @@
|
||||
import { apiGet } from '@/lib/api'
|
||||
|
||||
import type { WikiPage } from '@/types'
|
||||
|
||||
|
||||
export const fetchWikiPages = async (
|
||||
{ title }: { title?: string },
|
||||
): Promise<WikiPage[]> =>
|
||||
await apiGet ('/wiki', { params: { title } })
|
||||
|
||||
|
||||
export const fetchWikiPage = async (
|
||||
id: string,
|
||||
{ version }: { version?: string },
|
||||
): Promise<WikiPage> =>
|
||||
await apiGet (`/wiki/${ id }`, { params: version ? { version } : { } })
|
||||
|
||||
|
||||
export const fetchWikiPageByTitle = async (
|
||||
title: string,
|
||||
{ version }: { version?: string },
|
||||
): Promise<WikiPage | null> => {
|
||||
try
|
||||
{
|
||||
return await apiGet (`/wiki/title/${ encodeURIComponent (title) }`, { params: { version } })
|
||||
}
|
||||
catch
|
||||
{
|
||||
return null
|
||||
}
|
||||
}
|
||||
@@ -4,17 +4,16 @@ import { useEffect, useState } from 'react'
|
||||
import { Helmet } from 'react-helmet-async'
|
||||
import { useParams } from 'react-router-dom'
|
||||
|
||||
import PostEditForm from '@/components/PostEditForm'
|
||||
import PostEmbed from '@/components/PostEmbed'
|
||||
import PostList from '@/components/PostList'
|
||||
import TagDetailSidebar from '@/components/TagDetailSidebar'
|
||||
import PostEditForm from '@/components/PostEditForm'
|
||||
import PostEmbed from '@/components/PostEmbed'
|
||||
import TabGroup, { Tab } from '@/components/common/TabGroup'
|
||||
import MainArea from '@/components/layout/MainArea'
|
||||
import { Button } from '@/components/ui/button'
|
||||
import { toast } from '@/components/ui/use-toast'
|
||||
import { SITE_TITLE } from '@/config'
|
||||
import { fetchPost, toggleViewedFlg } from '@/lib/posts'
|
||||
import { postsKeys } from '@/lib/queryKeys'
|
||||
import { cn } from '@/lib/utils'
|
||||
import NotFound from '@/pages/NotFound'
|
||||
import ServiceUnavailable from '@/pages/ServiceUnavailable'
|
||||
@@ -28,39 +27,37 @@ type Props = { user: User | null }
|
||||
|
||||
export default (({ user }: Props) => {
|
||||
const { id } = useParams ()
|
||||
const postId = String (id ?? '')
|
||||
const postKey = postsKeys.show (postId)
|
||||
|
||||
const qc = useQueryClient ()
|
||||
|
||||
const { data: post, isError: errorFlg, error } = useQuery ({
|
||||
enabled: Boolean (id),
|
||||
queryKey: postKey,
|
||||
queryFn: () => fetchPost (postId) })
|
||||
|
||||
const qc = useQueryClient ()
|
||||
queryKey: ['post', String (id)],
|
||||
queryFn: () => fetchPost (String (id)) })
|
||||
|
||||
const [status, setStatus] = useState (200)
|
||||
|
||||
const changeViewedFlg = useMutation ({
|
||||
mutationFn: async () => {
|
||||
const cur = qc.getQueryData<any> (postKey)
|
||||
const next = !(cur?.viewed)
|
||||
await toggleViewedFlg (postId, next)
|
||||
const next = !(post!.viewed)
|
||||
await toggleViewedFlg (id!, next)
|
||||
return next
|
||||
},
|
||||
onMutate: async () => {
|
||||
await qc.cancelQueries ({ queryKey: postKey })
|
||||
const prev = qc.getQueryData<any> (postKey)
|
||||
qc.setQueryData (postKey,
|
||||
await qc.cancelQueries ({ queryKey: ['post', String (id)] })
|
||||
const prev = qc.getQueryData<any> (['post', String (id)])
|
||||
qc.setQueryData (['post', String (id)],
|
||||
(cur: any) => cur ? { ...cur, viewed: !(cur.viewed) } : cur)
|
||||
return { prev }
|
||||
},
|
||||
onError: (...[, , ctx]) => {
|
||||
if (ctx?.prev)
|
||||
qc.setQueryData (postKey, ctx.prev)
|
||||
qc.setQueryData (['post', String (id)], ctx.prev)
|
||||
toast ({ title: '失敗……', description: '通信に失敗しました……' })
|
||||
},
|
||||
onSuccess: () => {
|
||||
qc.invalidateQueries ({ queryKey: postsKeys.root })
|
||||
qc.invalidateQueries ({ queryKey: ['posts'] })
|
||||
qc.invalidateQueries ({ queryKey: ['related', String (id)] })
|
||||
} })
|
||||
|
||||
useEffect (() => {
|
||||
@@ -72,12 +69,6 @@ export default (({ user }: Props) => {
|
||||
setStatus (code)
|
||||
}, [errorFlg, error])
|
||||
|
||||
useEffect (() => {
|
||||
scroll (0, 0)
|
||||
|
||||
setStatus (200)
|
||||
}, [id])
|
||||
|
||||
switch (status)
|
||||
{
|
||||
case 404:
|
||||
@@ -103,23 +94,20 @@ export default (({ user }: Props) => {
|
||||
</div>
|
||||
|
||||
<MainArea className="relative">
|
||||
<motion.div
|
||||
layoutId={`page-${ String (id) }`}
|
||||
initial={{ clipPath: 'inset(0% 0% 0% 0%)' }}
|
||||
animate={{ clipPath: 'inset(0% 0% 0% 0% round 0px)', opacity: 0 }}
|
||||
transition={{ type: 'spring', stiffness: 500, damping: 40, mass: .5 }}
|
||||
className="absolute overflow-hidden transform-gpu will-change-transform
|
||||
inset-0 pointer-events-none z-10 w-[640px] h-[360px]">
|
||||
<img src={post?.thumbnailBase || post?.thumbnail}
|
||||
alt={post?.url}/>
|
||||
</motion.div>
|
||||
|
||||
{post
|
||||
? (
|
||||
<>
|
||||
{(post.thumbnail || post.thumbnailBase) && (
|
||||
<motion.div
|
||||
layoutId={`page-${ id }`}
|
||||
className="absolute top-4 left-4 w-[min(640px,calc(100vw-2rem))] h-[360px]
|
||||
overflow-hidden rounded-xl pointer-events-none z-50"
|
||||
initial={{ opacity: 1 }}
|
||||
animate={{ opacity: 0 }}
|
||||
transition={{ duration: .2, ease: 'easeOut' }}>
|
||||
<img src={post.thumbnail || post.thumbnailBase}
|
||||
alt={post.title || post.url}
|
||||
title={post.title || post.url || undefined}
|
||||
className="object-cover w-full h-full"/>
|
||||
</motion.div>)}
|
||||
|
||||
<PostEmbed post={post}/>
|
||||
<Button onClick={() => changeViewedFlg.mutate ()}
|
||||
disabled={changeViewedFlg.isPending}
|
||||
@@ -134,14 +122,14 @@ export default (({ user }: Props) => {
|
||||
</Tab>
|
||||
{['admin', 'member'].some (r => user?.role === r) && (
|
||||
<Tab name="編輯">
|
||||
<PostEditForm
|
||||
post={post}
|
||||
onSave={newPost => {
|
||||
qc.setQueryData (postsKeys.show (postId),
|
||||
(prev: any) => newPost ?? prev)
|
||||
qc.invalidateQueries ({ queryKey: postsKeys.root })
|
||||
toast ({ description: '更新しました.' })
|
||||
}}/>
|
||||
<PostEditForm post={post}
|
||||
onSave={newPost => {
|
||||
qc.setQueryData (['post', String (id)],
|
||||
(prev: any) => newPost ?? prev)
|
||||
qc.invalidateQueries ({ queryKey: ['posts'] })
|
||||
qc.invalidateQueries ({ queryKey: ['related', String (id)] })
|
||||
toast ({ description: '更新しました.' })
|
||||
}}/>
|
||||
</Tab>)}
|
||||
</TabGroup>
|
||||
</>)
|
||||
|
||||
@@ -1,23 +1,24 @@
|
||||
import { useQuery } from '@tanstack/react-query'
|
||||
import { motion } from 'framer-motion'
|
||||
import { useEffect } from 'react'
|
||||
import axios from 'axios'
|
||||
import toCamel from 'camelcase-keys'
|
||||
import { useEffect, useState } from 'react'
|
||||
import { Helmet } from 'react-helmet-async'
|
||||
import { useLocation } from 'react-router-dom'
|
||||
import { Link, useLocation } from 'react-router-dom'
|
||||
|
||||
import TagLink from '@/components/TagLink'
|
||||
import PrefetchLink from '@/components/PrefetchLink'
|
||||
import PageTitle from '@/components/common/PageTitle'
|
||||
import Pagination from '@/components/common/Pagination'
|
||||
import MainArea from '@/components/layout/MainArea'
|
||||
import { SITE_TITLE } from '@/config'
|
||||
import { fetchPostChanges } from '@/lib/posts'
|
||||
import { postsKeys } from '@/lib/queryKeys'
|
||||
import { cn, dateString } from '@/lib/utils'
|
||||
import { API_BASE_URL, SITE_TITLE } from '@/config'
|
||||
|
||||
import type { FC } from 'react'
|
||||
|
||||
import type { PostTagChange } from '@/types'
|
||||
|
||||
|
||||
export default (() => {
|
||||
const [changes, setChanges] = useState<PostTagChange[]> ([])
|
||||
const [totalPages, setTotalPages] = useState<number> (0)
|
||||
|
||||
const location = useLocation ()
|
||||
const query = new URLSearchParams (location.search)
|
||||
const id = query.get ('id')
|
||||
@@ -27,15 +28,17 @@ export default (() => {
|
||||
// 投稿列の結合で使用
|
||||
let rowsCnt: number
|
||||
|
||||
const { data, isLoading: loading } = useQuery ({
|
||||
queryKey: postsKeys.changes ({ ...(id && { id }), page, limit }),
|
||||
queryFn: () => fetchPostChanges ({ ...(id && { id }), page, limit }) })
|
||||
const changes = data?.changes ?? []
|
||||
const totalPages = data ? Math.ceil (data.count / limit) : 0
|
||||
|
||||
useEffect (() => {
|
||||
document.querySelector ('table')?.scrollIntoView ({ behavior: 'smooth' })
|
||||
}, [location.search])
|
||||
void (async () => {
|
||||
const res = await axios.get (`${ API_BASE_URL }/posts/changes`,
|
||||
{ params: { ...(id && { id }), page, limit } })
|
||||
const data = toCamel (res.data as any, { deep: true }) as {
|
||||
changes: PostTagChange[]
|
||||
count: number }
|
||||
setChanges (data.changes)
|
||||
setTotalPages (Math.ceil (data.count / limit))
|
||||
}) ()
|
||||
}, [id, page, limit])
|
||||
|
||||
return (
|
||||
<MainArea>
|
||||
@@ -45,72 +48,57 @@ export default (() => {
|
||||
|
||||
<PageTitle>
|
||||
耕作履歴
|
||||
{id && <>: 投稿 {<PrefetchLink to={`/posts/${ id }`}>#{id}</PrefetchLink>}</>}
|
||||
{id && <>: 投稿 {<Link to={`/posts/${ id }`}>#{id}</Link>}</>}
|
||||
</PageTitle>
|
||||
|
||||
{loading ? 'Loading...' : (
|
||||
<>
|
||||
<table className="table-auto w-full border-collapse">
|
||||
<thead className="border-b-2 border-black dark:border-white">
|
||||
<tr>
|
||||
<th className="p-2 text-left">投稿</th>
|
||||
<th className="p-2 text-left">変更</th>
|
||||
<th className="p-2 text-left">日時</th>
|
||||
</tr>
|
||||
</thead>
|
||||
<tbody>
|
||||
{changes.map ((change, i) => {
|
||||
let withPost = i === 0 || change.post.id !== changes[i - 1].post.id
|
||||
if (withPost)
|
||||
{
|
||||
rowsCnt = 1
|
||||
for (let j = i + 1;
|
||||
(j < changes.length
|
||||
&& change.post.id === changes[j].post.id);
|
||||
++j)
|
||||
++rowsCnt
|
||||
}
|
||||
return (
|
||||
<tr key={`${ change.timestamp }-${ change.post.id }-${ change.tag.id }`}
|
||||
className={cn ('even:bg-gray-100 dark:even:bg-gray-700',
|
||||
withPost && 'border-t')}>
|
||||
{withPost && (
|
||||
<td className="align-top p-2 bg-white dark:bg-[#242424] border-r"
|
||||
rowSpan={rowsCnt}>
|
||||
<PrefetchLink to={`/posts/${ change.post.id }`}>
|
||||
<motion.div
|
||||
layoutId={`page-${ change.post.id }`}
|
||||
transition={{ type: 'spring',
|
||||
stiffness: 500,
|
||||
damping: 40,
|
||||
mass: .5 }}>
|
||||
<img src={change.post.thumbnail || change.post.thumbnailBase || undefined}
|
||||
alt={change.post.title || change.post.url}
|
||||
title={change.post.title || change.post.url || undefined}
|
||||
className="w-40"/>
|
||||
</motion.div>
|
||||
</PrefetchLink>
|
||||
</td>)}
|
||||
<td className="p-2">
|
||||
<TagLink tag={change.tag} withWiki={false} withCount={false}/>
|
||||
{`を${ change.changeType === 'add' ? '記載' : '消除' }`}
|
||||
</td>
|
||||
<td className="p-2">
|
||||
{change.user
|
||||
? (
|
||||
<PrefetchLink to={`/users/${ change.user.id }`}>
|
||||
{change.user.name}
|
||||
</PrefetchLink>)
|
||||
: 'bot 操作'}
|
||||
<br/>
|
||||
{dateString (change.timestamp)}
|
||||
</td>
|
||||
</tr>)
|
||||
})}
|
||||
</tbody>
|
||||
</table>
|
||||
<table className="table-auto w-full border-collapse">
|
||||
<thead>
|
||||
<tr>
|
||||
<th className="p-2 text-left">投稿</th>
|
||||
<th className="p-2 text-left">変更</th>
|
||||
<th className="p-2 text-left">日時</th>
|
||||
</tr>
|
||||
</thead>
|
||||
<tbody>
|
||||
{changes.map ((change, i) => {
|
||||
let withPost = i === 0 || change.post.id !== changes[i - 1].post.id
|
||||
if (withPost)
|
||||
{
|
||||
rowsCnt = 1
|
||||
for (let j = i + 1;
|
||||
(j < changes.length
|
||||
&& change.post.id === changes[j].post.id);
|
||||
++j)
|
||||
++rowsCnt
|
||||
}
|
||||
return (
|
||||
<tr key={`${ change.timestamp }-${ change.post.id }-${ change.tag.id }`}>
|
||||
{withPost && (
|
||||
<td className="align-top" rowSpan={rowsCnt}>
|
||||
<Link to={`/posts/${ change.post.id }`}>
|
||||
<img src={change.post.thumbnail || change.post.thumbnailBase || undefined}
|
||||
alt={change.post.title || change.post.url}
|
||||
title={change.post.title || change.post.url || undefined}
|
||||
className="w-40"/>
|
||||
</Link>
|
||||
</td>)}
|
||||
<td>
|
||||
<TagLink tag={change.tag} withWiki={false} withCount={false}/>
|
||||
{`を${ change.changeType === 'add' ? '追加' : '削除' }`}
|
||||
</td>
|
||||
<td>
|
||||
{change.user ? (
|
||||
<Link to={`/users/${ change.user.id }`}>
|
||||
{change.user.name}
|
||||
</Link>) : 'bot 操作'}
|
||||
<br/>
|
||||
{change.timestamp}
|
||||
</td>
|
||||
</tr>)
|
||||
})}
|
||||
</tbody>
|
||||
</table>
|
||||
|
||||
<Pagination page={page} totalPages={totalPages}/>
|
||||
</>)}
|
||||
<Pagination page={page} totalPages={totalPages}/>
|
||||
</MainArea>)
|
||||
}) satisfies FC
|
||||
|
||||
@@ -1,71 +1,113 @@
|
||||
import { useQuery } from '@tanstack/react-query'
|
||||
import { useLayoutEffect, useRef, useState } from 'react'
|
||||
import axios from 'axios'
|
||||
import toCamel from 'camelcase-keys'
|
||||
import { useEffect, useLayoutEffect, useRef, useState } from 'react'
|
||||
import { Helmet } from 'react-helmet-async'
|
||||
import { useLocation } from 'react-router-dom'
|
||||
import { Link, useLocation, useNavigationType } from 'react-router-dom'
|
||||
|
||||
import PostList from '@/components/PostList'
|
||||
import PrefetchLink from '@/components/PrefetchLink'
|
||||
import TagSidebar from '@/components/TagSidebar'
|
||||
import WikiBody from '@/components/WikiBody'
|
||||
import Pagination from '@/components/common/Pagination'
|
||||
import TabGroup, { Tab } from '@/components/common/TabGroup'
|
||||
import MainArea from '@/components/layout/MainArea'
|
||||
import { SITE_TITLE } from '@/config'
|
||||
import { fetchPosts } from '@/lib/posts'
|
||||
import { postsKeys } from '@/lib/queryKeys'
|
||||
import { fetchWikiPageByTitle } from '@/lib/wiki'
|
||||
import { API_BASE_URL, SITE_TITLE } from '@/config'
|
||||
|
||||
import type { FC } from 'react'
|
||||
|
||||
import type { WikiPage } from '@/types'
|
||||
import type { Post, WikiPage } from '@/types'
|
||||
|
||||
|
||||
export default (() => {
|
||||
export default () => {
|
||||
const navigationType = useNavigationType ()
|
||||
|
||||
const containerRef = useRef<HTMLDivElement | null> (null)
|
||||
const loaderRef = useRef<HTMLDivElement | null> (null)
|
||||
|
||||
const [cursor, setCursor] = useState ('')
|
||||
const [loading, setLoading] = useState (false)
|
||||
const [posts, setPosts] = useState<Post[]> ([])
|
||||
const [totalPages, setTotalPages] = useState (0)
|
||||
const [wikiPage, setWikiPage] = useState<WikiPage | null> (null)
|
||||
|
||||
const loadMore = async (withCursor: boolean) => {
|
||||
setLoading (true)
|
||||
|
||||
const res = await axios.get (`${ API_BASE_URL }/posts`, {
|
||||
params: { tags: tags.join (' '),
|
||||
match: anyFlg ? 'any' : 'all',
|
||||
...(page && { page }),
|
||||
...(limit && { limit }),
|
||||
...(withCursor && { cursor }) } })
|
||||
const data = toCamel (res.data as any, { deep: true }) as {
|
||||
posts: Post[]
|
||||
count: number
|
||||
nextCursor: string }
|
||||
setPosts (posts => (
|
||||
[...((new Map ([...(withCursor ? posts : []), ...data.posts]
|
||||
.map (post => [post.id, post])))
|
||||
.values ())]))
|
||||
setCursor (data.nextCursor)
|
||||
setTotalPages (Math.ceil (data.count / limit))
|
||||
|
||||
setLoading (false)
|
||||
}
|
||||
|
||||
const location = useLocation ()
|
||||
const query = new URLSearchParams (location.search)
|
||||
const tagsQuery = query.get ('tags') ?? ''
|
||||
const anyFlg = query.get ('match') === 'any'
|
||||
const match = anyFlg ? 'any' : 'all'
|
||||
const tags = tagsQuery.split (' ').filter (e => e !== '')
|
||||
const tagsKey = tags.join (' ')
|
||||
const page = Number (query.get ('page') ?? 1)
|
||||
const limit = Number (query.get ('limit') ?? 20)
|
||||
|
||||
const keys = {
|
||||
tags: tagsKey, match, page, limit,
|
||||
url: '', title: '', originalCreatedFrom: '', originalCreatedTo: '',
|
||||
createdFrom: '', createdTo: '', updatedFrom: '', updatedTo: '',
|
||||
order: 'original_created_at:desc' } as const
|
||||
const { data, isLoading: loading } = useQuery ({
|
||||
queryKey: postsKeys.index (keys),
|
||||
queryFn: () => fetchPosts (keys) })
|
||||
const posts = data?.posts ?? []
|
||||
const cursor = ''
|
||||
const totalPages = data ? Math.ceil (data.count / limit) : 0
|
||||
useEffect(() => {
|
||||
const observer = new IntersectionObserver (entries => {
|
||||
if (entries[0].isIntersecting && !(loading) && cursor)
|
||||
loadMore (true)
|
||||
}, { threshold: 1 })
|
||||
|
||||
const target = loaderRef.current
|
||||
target && observer.observe (target)
|
||||
|
||||
return () => {
|
||||
target && observer.unobserve (target)
|
||||
}
|
||||
}, [loaderRef, loading])
|
||||
|
||||
useLayoutEffect (() => {
|
||||
scroll (0, 0)
|
||||
// TODO: 無限ロード用
|
||||
const savedState = /* sessionStorage.getItem (`posts:${ tagsQuery }`) */ null
|
||||
if (savedState && navigationType === 'POP')
|
||||
{
|
||||
const { posts, cursor, scroll } = JSON.parse (savedState)
|
||||
setPosts (posts)
|
||||
setCursor (cursor)
|
||||
|
||||
if (containerRef.current)
|
||||
containerRef.current.scrollTop = scroll
|
||||
|
||||
loadMore (true)
|
||||
}
|
||||
else
|
||||
{
|
||||
setPosts ([])
|
||||
loadMore (false)
|
||||
}
|
||||
|
||||
setWikiPage (null)
|
||||
|
||||
if (tags.length !== 1)
|
||||
return
|
||||
|
||||
void (async () => {
|
||||
try
|
||||
if (tags.length === 1)
|
||||
{
|
||||
const tagName = tags[0]
|
||||
setWikiPage (await fetchWikiPageByTitle (tagName, { }))
|
||||
void (async () => {
|
||||
try
|
||||
{
|
||||
const tagName = tags[0]
|
||||
const res = await axios.get (`${ API_BASE_URL }/wiki/title/${ tagName }`)
|
||||
setWikiPage (toCamel (res.data as any, { deep: true }) as WikiPage)
|
||||
}
|
||||
catch
|
||||
{
|
||||
;
|
||||
}
|
||||
}) ()
|
||||
}
|
||||
catch
|
||||
{
|
||||
;
|
||||
}
|
||||
}) ()
|
||||
}, [location.search])
|
||||
|
||||
return (
|
||||
@@ -78,13 +120,7 @@ export default (() => {
|
||||
</title>
|
||||
</Helmet>
|
||||
|
||||
<TagSidebar posts={posts.slice (0, 20)} onClick={() => {
|
||||
const statesToSave = {
|
||||
posts, cursor,
|
||||
scroll: containerRef.current?.scrollTop ?? 0 }
|
||||
sessionStorage.setItem (`posts:${ tagsQuery }`,
|
||||
JSON.stringify (statesToSave))
|
||||
}}/>
|
||||
<TagSidebar posts={posts.slice (0, 20)}/>
|
||||
|
||||
<MainArea>
|
||||
<TabGroup>
|
||||
@@ -92,22 +128,31 @@ export default (() => {
|
||||
{posts.length > 0
|
||||
? (
|
||||
<>
|
||||
<PostList posts={posts}/>
|
||||
<PostList posts={posts} onClick={() => {
|
||||
// TODO: 無限ロード用なので復活時に戻す.
|
||||
// const statesToSave = {
|
||||
// posts, cursor,
|
||||
// scroll: containerRef.current?.scrollTop ?? 0 }
|
||||
// sessionStorage.setItem (`posts:${ tagsQuery }`,
|
||||
// JSON.stringify (statesToSave))
|
||||
}}/>
|
||||
<Pagination page={page} totalPages={totalPages}/>
|
||||
</>)
|
||||
: !(loading) && '広場には何もありませんよ.'}
|
||||
{loading && 'Loading...'}
|
||||
{/* TODO: 無限ローディング復活までコメント・アウト */}
|
||||
{/* <div ref={loaderRef} className="h-12"/> */}
|
||||
</Tab>
|
||||
{tags.length === 1 && (
|
||||
<Tab name="Wiki">
|
||||
<WikiBody title={tags[0]} body={wikiPage?.body}/>
|
||||
<div className="my-2">
|
||||
<PrefetchLink to={`/wiki/${ encodeURIComponent (tags[0]) }`}>
|
||||
<Link to={`/wiki/${ encodeURIComponent (tags[0]) }`}>
|
||||
Wiki を見る
|
||||
</PrefetchLink>
|
||||
</Link>
|
||||
</div>
|
||||
</Tab>)}
|
||||
</TabGroup>
|
||||
</MainArea>
|
||||
</div>)
|
||||
}) satisfies FC
|
||||
}
|
||||
|
||||
@@ -1,3 +1,4 @@
|
||||
import axios from 'axios'
|
||||
import { useEffect, useState, useRef } from 'react'
|
||||
import { Helmet } from 'react-helmet-async'
|
||||
import { useNavigate } from 'react-router-dom'
|
||||
@@ -10,8 +11,7 @@ import PageTitle from '@/components/common/PageTitle'
|
||||
import MainArea from '@/components/layout/MainArea'
|
||||
import { Button } from '@/components/ui/button'
|
||||
import { toast } from '@/components/ui/use-toast'
|
||||
import { SITE_TITLE } from '@/config'
|
||||
import { apiGet, apiPost } from '@/lib/api'
|
||||
import { API_BASE_URL, SITE_TITLE } from '@/config'
|
||||
import Forbidden from '@/pages/Forbidden'
|
||||
|
||||
import type { FC } from 'react'
|
||||
@@ -55,7 +55,9 @@ export default (({ user }: Props) => {
|
||||
|
||||
try
|
||||
{
|
||||
await apiPost ('/posts', formData, { headers: { 'Content-Type': 'multipart/form-data' } })
|
||||
await axios.post (`${ API_BASE_URL }/posts`, formData, { headers: {
|
||||
'Content-Type': 'multipart/form-data',
|
||||
'X-Transfer-Code': localStorage.getItem ('user_code') ?? '' } })
|
||||
toast ({ title: '投稿成功!' })
|
||||
navigate ('/posts')
|
||||
}
|
||||
@@ -89,7 +91,10 @@ export default (({ user }: Props) => {
|
||||
const fetchTitle = async () => {
|
||||
setTitle ('')
|
||||
setTitleLoading (true)
|
||||
const data = await apiGet<{ title: string }> ('/preview/title', { params: { url } })
|
||||
const res = await axios.get (`${ API_BASE_URL }/preview/title`, {
|
||||
params: { url },
|
||||
headers: { 'X-Transfer-Code': localStorage.getItem ('user_code') || '' } })
|
||||
const data = res.data as { title: string }
|
||||
setTitle (data.title || '')
|
||||
setTitleLoading (false)
|
||||
}
|
||||
@@ -100,8 +105,11 @@ export default (({ user }: Props) => {
|
||||
setThumbnailLoading (true)
|
||||
if (thumbnailPreview)
|
||||
URL.revokeObjectURL (thumbnailPreview)
|
||||
const data = await apiGet<Blob> ('/preview/thumbnail',
|
||||
{ params: { url }, responseType: 'blob' })
|
||||
const res = await axios.get (`${ API_BASE_URL }/preview/thumbnail`, {
|
||||
params: { url },
|
||||
headers: { 'X-Transfer-Code': localStorage.getItem ('user_code') || '' },
|
||||
responseType: 'blob' })
|
||||
const data = res.data as Blob
|
||||
const imageURL = URL.createObjectURL (data)
|
||||
setThumbnailPreview (imageURL)
|
||||
setThumbnailFile (new File ([data],
|
||||
|
||||
@@ -1,410 +0,0 @@
|
||||
import { useQuery } from '@tanstack/react-query'
|
||||
import { motion } from 'framer-motion'
|
||||
import { useEffect, useMemo, useState } from 'react'
|
||||
import { Helmet } from 'react-helmet-async'
|
||||
import { useLocation, useNavigate } from 'react-router-dom'
|
||||
|
||||
import PrefetchLink from '@/components/PrefetchLink'
|
||||
import TagLink from '@/components/TagLink'
|
||||
import TagSearchBox from '@/components/TagSearchBox'
|
||||
import DateTimeField from '@/components/common/DateTimeField'
|
||||
import Label from '@/components/common/Label'
|
||||
import PageTitle from '@/components/common/PageTitle'
|
||||
import Pagination from '@/components/common/Pagination'
|
||||
import MainArea from '@/components/layout/MainArea'
|
||||
import { SITE_TITLE } from '@/config'
|
||||
import { apiGet } from '@/lib/api'
|
||||
import { fetchPosts } from '@/lib/posts'
|
||||
import { postsKeys } from '@/lib/queryKeys'
|
||||
import { dateString, originalCreatedAtString } from '@/lib/utils'
|
||||
|
||||
import type { FC, ChangeEvent, FormEvent, KeyboardEvent } from 'react'
|
||||
|
||||
import type { FetchPostsOrder,
|
||||
FetchPostsOrderField,
|
||||
FetchPostsParams,
|
||||
Tag } from '@/types'
|
||||
|
||||
|
||||
const setIf = (qs: URLSearchParams, k: string, v: string | null) => {
|
||||
const t = v?.trim ()
|
||||
if (t)
|
||||
qs.set (k, t)
|
||||
}
|
||||
|
||||
|
||||
export default (() => {
|
||||
const location = useLocation ()
|
||||
|
||||
const navigate = useNavigate ()
|
||||
|
||||
const query = useMemo (() => new URLSearchParams (location.search),
|
||||
[location.search])
|
||||
|
||||
const page = Number (query.get ('page') ?? 1)
|
||||
const limit = Number (query.get ('limit') ?? 20)
|
||||
|
||||
const qURL = query.get ('url') ?? ''
|
||||
const qTitle = query.get ('title') ?? ''
|
||||
const qTags = query.get ('tags') ?? ''
|
||||
const qMatch: 'all' | 'any' = query.get ('match') === 'any' ? 'any' : 'all'
|
||||
const qOriginalCreatedFrom = query.get ('original_created_from') ?? ''
|
||||
const qOriginalCreatedTo = query.get ('original_created_to') ?? ''
|
||||
const qCreatedFrom = query.get ('created_from') ?? ''
|
||||
const qCreatedTo = query.get ('created_to') ?? ''
|
||||
const qUpdatedFrom = query.get ('updated_from') ?? ''
|
||||
const qUpdatedTo = query.get ('updated_to') ?? ''
|
||||
const order = (query.get ('order') || 'original_created_at:desc') as FetchPostsOrder
|
||||
|
||||
const [activeIndex, setActiveIndex] = useState (-1)
|
||||
const [createdFrom, setCreatedFrom] = useState<string | null> (null)
|
||||
const [createdTo, setCreatedTo] = useState<string | null> (null)
|
||||
const [matchType, setMatchType] = useState<'all' | 'any'> ('all')
|
||||
const [originalCreatedFrom, setOriginalCreatedFrom] = useState<string | null> (null)
|
||||
const [originalCreatedTo, setOriginalCreatedTo] = useState<string | null> (null)
|
||||
const [suggestions, setSuggestions] = useState<Tag[]> ([])
|
||||
const [suggestionsVsbl, setSuggestionsVsbl] = useState (false)
|
||||
const [tagsStr, setTagsStr] = useState ('')
|
||||
const [title, setTitle] = useState ('')
|
||||
const [updatedFrom, setUpdatedFrom] = useState<string | null> (null)
|
||||
const [updatedTo, setUpdatedTo] = useState<string | null> (null)
|
||||
const [url, setURL] = useState ('')
|
||||
|
||||
const keys: FetchPostsParams = {
|
||||
tags: qTags, match: qMatch, page, limit,
|
||||
url: qURL,
|
||||
title: qTitle,
|
||||
originalCreatedFrom: qOriginalCreatedFrom,
|
||||
originalCreatedTo: qOriginalCreatedTo,
|
||||
createdFrom: qCreatedFrom,
|
||||
createdTo: qCreatedTo,
|
||||
updatedFrom: qUpdatedFrom,
|
||||
updatedTo: qUpdatedTo,
|
||||
order }
|
||||
const { data, isLoading: loading } = useQuery ({
|
||||
queryKey: postsKeys.index (keys),
|
||||
queryFn: () => fetchPosts (keys) })
|
||||
const results = data?.posts ?? []
|
||||
const totalPages = data ? Math.ceil (data.count / limit) : 0
|
||||
|
||||
useEffect (() => {
|
||||
setURL (qURL ?? '')
|
||||
setTitle (qTitle ?? '')
|
||||
setTagsStr (qTags ?? '')
|
||||
setMatchType (qMatch ?? 'all')
|
||||
setOriginalCreatedFrom (qOriginalCreatedFrom)
|
||||
setOriginalCreatedTo (qOriginalCreatedTo)
|
||||
setCreatedFrom (qCreatedFrom)
|
||||
setCreatedTo (qCreatedTo)
|
||||
setUpdatedFrom (qUpdatedFrom)
|
||||
setUpdatedTo (qUpdatedTo)
|
||||
|
||||
document.querySelector ('table')?.scrollIntoView ({ behavior: 'smooth' })
|
||||
}, [location.search])
|
||||
|
||||
const SortHeader = ({ by, label }: { by: FetchPostsOrderField; label: string }) => {
|
||||
const [fld, dir] = order.split (':')
|
||||
|
||||
const qs = new URLSearchParams (location.search)
|
||||
const nextDir =
|
||||
(by === fld)
|
||||
? (dir === 'asc' ? 'desc' : 'asc')
|
||||
: (['title', 'url'].includes (by) ? 'asc' : 'desc')
|
||||
qs.set ('order', `${ by }:${ nextDir }`)
|
||||
qs.set ('page', '1')
|
||||
|
||||
return (
|
||||
<PrefetchLink
|
||||
className="text-inherit visited:text-inherit hover:text-inherit"
|
||||
to={`${ location.pathname }?${ qs.toString () }`}>
|
||||
<span className="font-bold">
|
||||
{label}
|
||||
{by === fld && (dir === 'asc' ? ' ▲' : ' ▼')}
|
||||
</span>
|
||||
</PrefetchLink>)
|
||||
}
|
||||
|
||||
// TODO: TagSearch からのコピペのため,共通化を考へる.
|
||||
const whenChanged = async (ev: ChangeEvent<HTMLInputElement>) => {
|
||||
setTagsStr (ev.target.value)
|
||||
|
||||
const q = ev.target.value.trim ().split (' ').at (-1)
|
||||
if (!(q))
|
||||
{
|
||||
setSuggestions ([])
|
||||
return
|
||||
}
|
||||
|
||||
const data = await apiGet<Tag[]> ('/tags/autocomplete', { params: { q } })
|
||||
setSuggestions (data.filter (t => t.postCount > 0))
|
||||
if (suggestions.length > 0)
|
||||
setSuggestionsVsbl (true)
|
||||
}
|
||||
|
||||
// TODO: TagSearch からのコピペのため,共通化を考へる.
|
||||
const handleKeyDown = (ev: KeyboardEvent<HTMLInputElement>) => {
|
||||
switch (ev.key)
|
||||
{
|
||||
case 'ArrowDown':
|
||||
ev.preventDefault ()
|
||||
setActiveIndex (i => Math.min (i + 1, suggestions.length - 1))
|
||||
setSuggestionsVsbl (true)
|
||||
break
|
||||
|
||||
case 'ArrowUp':
|
||||
ev.preventDefault ()
|
||||
setActiveIndex (i => Math.max (i - 1, -1))
|
||||
setSuggestionsVsbl (true)
|
||||
break
|
||||
|
||||
case 'Enter':
|
||||
if (activeIndex < 0)
|
||||
break
|
||||
ev.preventDefault ()
|
||||
const selected = suggestions[activeIndex]
|
||||
selected && handleTagSelect (selected)
|
||||
break
|
||||
|
||||
case 'Escape':
|
||||
ev.preventDefault ()
|
||||
setSuggestionsVsbl (false)
|
||||
break
|
||||
}
|
||||
if (ev.key === 'Enter' && (!(suggestionsVsbl) || activeIndex < 0))
|
||||
{
|
||||
setSuggestionsVsbl (false)
|
||||
}
|
||||
}
|
||||
|
||||
const search = async () => {
|
||||
const qs = new URLSearchParams ()
|
||||
setIf (qs, 'tags', tagsStr)
|
||||
setIf (qs, 'url', url)
|
||||
setIf (qs, 'title', title)
|
||||
setIf (qs, 'original_created_from', originalCreatedFrom)
|
||||
setIf (qs, 'original_created_to', originalCreatedTo)
|
||||
setIf (qs, 'created_from', createdFrom)
|
||||
setIf (qs, 'created_to', createdTo)
|
||||
setIf (qs, 'updated_from', updatedFrom)
|
||||
setIf (qs, 'updated_to', updatedTo)
|
||||
qs.set ('match', matchType)
|
||||
qs.set ('page', String ('1'))
|
||||
qs.set ('order', order)
|
||||
navigate (`${ location.pathname }?${ qs.toString () }`)
|
||||
}
|
||||
|
||||
// TODO: TagSearch からのコピペのため,共通化を考へる.
|
||||
const handleTagSelect = (tag: Tag) => {
|
||||
const parts = tagsStr.split (' ')
|
||||
parts[parts.length - 1] = tag.name
|
||||
setTagsStr (parts.join (' ') + ' ')
|
||||
setSuggestions ([])
|
||||
setActiveIndex (-1)
|
||||
}
|
||||
|
||||
const handleSearch = (e: FormEvent) => {
|
||||
e.preventDefault ()
|
||||
search ()
|
||||
}
|
||||
|
||||
return (
|
||||
<MainArea>
|
||||
<Helmet>
|
||||
<title>広場検索 | {SITE_TITLE}</title>
|
||||
</Helmet>
|
||||
|
||||
<div className="max-w-xl">
|
||||
<PageTitle>広場検索</PageTitle>
|
||||
|
||||
<form onSubmit={handleSearch} className="space-y-2">
|
||||
{/* タイトル */}
|
||||
<div>
|
||||
<Label>タイトル</Label>
|
||||
<input
|
||||
type="text"
|
||||
value={title}
|
||||
onChange={e => setTitle (e.target.value)}
|
||||
className="w-full border p-2 rounded"/>
|
||||
</div>
|
||||
|
||||
{/* URL */}
|
||||
<div>
|
||||
<Label>URL</Label>
|
||||
<input
|
||||
type="text"
|
||||
value={url}
|
||||
onChange={e => setURL (e.target.value)}
|
||||
className="w-full border p-2 rounded"/>
|
||||
</div>
|
||||
|
||||
{/* タグ */}
|
||||
<div className="relative">
|
||||
<Label>タグ</Label>
|
||||
<input
|
||||
type="text"
|
||||
value={tagsStr}
|
||||
onChange={whenChanged}
|
||||
onFocus={() => setSuggestionsVsbl (true)}
|
||||
onBlur={() => setSuggestionsVsbl (false)}
|
||||
onKeyDown={handleKeyDown}
|
||||
className="w-full border p-2 rounded"/>
|
||||
<TagSearchBox
|
||||
suggestions={
|
||||
suggestionsVsbl && suggestions.length > 0 ? suggestions : [] as Tag[]}
|
||||
activeIndex={activeIndex}
|
||||
onSelect={handleTagSelect}/>
|
||||
<fieldset className="w-full my-2">
|
||||
<label>検索区分:</label>
|
||||
<label className="mx-2">
|
||||
<input
|
||||
type="radio"
|
||||
name="match-type"
|
||||
checked={matchType === 'all'}
|
||||
onChange={() => setMatchType ('all')}/>
|
||||
AND
|
||||
</label>
|
||||
<label className="mx-2">
|
||||
<input
|
||||
type="radio"
|
||||
name="match-type"
|
||||
checked={matchType === 'any'}
|
||||
onChange={() => setMatchType ('any')}/>
|
||||
OR
|
||||
</label>
|
||||
</fieldset>
|
||||
</div>
|
||||
|
||||
{/* オリジナルの投稿日時 */}
|
||||
<div>
|
||||
<Label>オリジナルの投稿日時</Label>
|
||||
<DateTimeField
|
||||
value={originalCreatedFrom ?? undefined}
|
||||
onChange={setOriginalCreatedFrom}/>
|
||||
<span className="mx-1">〜</span>
|
||||
<DateTimeField
|
||||
value={originalCreatedTo ?? undefined}
|
||||
onChange={setOriginalCreatedTo}/>
|
||||
</div>
|
||||
|
||||
{/* 投稿日時 */}
|
||||
<div>
|
||||
<Label>投稿日時</Label>
|
||||
<DateTimeField
|
||||
value={createdFrom ?? undefined}
|
||||
onChange={setCreatedFrom}/>
|
||||
<span className="mx-1">〜</span>
|
||||
<DateTimeField
|
||||
value={createdTo ?? undefined}
|
||||
onChange={setCreatedTo}/>
|
||||
</div>
|
||||
|
||||
{/* 更新日時 */}
|
||||
<div>
|
||||
<Label>更新日時</Label>
|
||||
<DateTimeField
|
||||
value={updatedFrom ?? undefined}
|
||||
onChange={setUpdatedFrom}/>
|
||||
<span className="mx-1">〜</span>
|
||||
<DateTimeField
|
||||
value={updatedTo ?? undefined}
|
||||
onChange={setUpdatedTo}/>
|
||||
</div>
|
||||
|
||||
{/* 検索 */}
|
||||
<div className="py-3">
|
||||
<button
|
||||
type="submit"
|
||||
className="bg-blue-500 text-white px-4 py-2 rounded">
|
||||
検索
|
||||
</button>
|
||||
</div>
|
||||
</form>
|
||||
</div>
|
||||
|
||||
{loading ? 'Loading...' : (results.length > 0 ? (
|
||||
<div className="mt-4">
|
||||
<div className="overflow-x-auto">
|
||||
<table className="w-full min-w-[1200px] table-fixed border-collapse">
|
||||
<colgroup>
|
||||
<col className="w-14"/>
|
||||
<col className="w-72"/>
|
||||
<col className="w-80"/>
|
||||
<col className="w-[24rem]"/>
|
||||
<col className="w-60"/>
|
||||
<col className="w-44"/>
|
||||
<col className="w-44"/>
|
||||
</colgroup>
|
||||
|
||||
<thead className="border-b-2 border-black dark:border-white">
|
||||
<tr>
|
||||
<th className="p-2 text-left whitespace-nowrap">投稿</th>
|
||||
<th className="p-2 text-left whitespace-nowrap">
|
||||
<SortHeader by="title" label="タイトル"/>
|
||||
</th>
|
||||
<th className="p-2 text-left whitespace-nowrap">
|
||||
<SortHeader by="url" label="URL"/>
|
||||
</th>
|
||||
<th className="p-2 text-left whitespace-nowrap">タグ</th>
|
||||
<th className="p-2 text-left whitespace-nowrap">
|
||||
<SortHeader by="original_created_at" label="オリジナルの投稿日時"/>
|
||||
</th>
|
||||
<th className="p-2 text-left whitespace-nowrap">
|
||||
<SortHeader by="created_at" label="投稿日時"/>
|
||||
</th>
|
||||
<th className="p-2 text-left whitespace-nowrap">
|
||||
<SortHeader by="updated_at" label="更新日時"/>
|
||||
</th>
|
||||
</tr>
|
||||
</thead>
|
||||
<tbody>
|
||||
{results.map (row => (
|
||||
<tr key={row.id} className={'even:bg-gray-100 dark:even:bg-gray-700'}>
|
||||
<td className="p-2">
|
||||
<PrefetchLink to={`/posts/${ row.id }`} title={row.title}>
|
||||
<motion.div
|
||||
layoutId={`page-${ row.id }`}
|
||||
transition={{ type: 'spring',
|
||||
stiffness: 500,
|
||||
damping: 40,
|
||||
mass: .5 }}>
|
||||
<img src={row.thumbnail || row.thumbnailBase || undefined}
|
||||
alt={row.title || row.url}
|
||||
title={row.title || row.url || undefined}
|
||||
className="w-8"/>
|
||||
</motion.div>
|
||||
</PrefetchLink>
|
||||
</td>
|
||||
<td className="p-2 truncate">
|
||||
<PrefetchLink to={`/posts/${ row.id }`} title={row.title}>
|
||||
{row.title}
|
||||
</PrefetchLink>
|
||||
</td>
|
||||
<td className="p-2 truncate">
|
||||
<a href={row.url}
|
||||
title={row.url}
|
||||
target="_blank"
|
||||
rel="noopener noreferrer nofollow">
|
||||
{row.url}
|
||||
</a>
|
||||
</td>
|
||||
<td className="p-2">
|
||||
{row.tags.map (t => (
|
||||
<span key={t.id} className="mr-2">
|
||||
<TagLink tag={t} withWiki={false} withCount={false}/>
|
||||
</span>))}
|
||||
</td>
|
||||
<td className="p-2">
|
||||
{originalCreatedAtString (row.originalCreatedFrom,
|
||||
row.originalCreatedBefore)}
|
||||
</td>
|
||||
<td className="p-2">{dateString (row.createdAt)}</td>
|
||||
<td className="p-2">{dateString (row.updatedAt)}</td>
|
||||
</tr>))}
|
||||
</tbody>
|
||||
</table>
|
||||
</div>
|
||||
|
||||
<Pagination page={page} totalPages={totalPages}/>
|
||||
</div>) : '結果ないよ(笑)')}
|
||||
</MainArea>)
|
||||
}) satisfies FC
|
||||
@@ -1,13 +1,14 @@
|
||||
import axios from 'axios'
|
||||
import toCamel from 'camelcase-keys'
|
||||
import { useEffect, useRef, useState } from 'react'
|
||||
import { Helmet } from 'react-helmet-async'
|
||||
|
||||
import TagLink from '@/components/TagLink'
|
||||
import PageTitle from '@/components/common/PageTitle'
|
||||
import SectionTitle from '@/components/common/SectionTitle'
|
||||
import TextArea from '@/components/common/TextArea'
|
||||
import MainArea from '@/components/layout/MainArea'
|
||||
import { toast } from '@/components/ui/use-toast'
|
||||
import { SITE_TITLE } from '@/config'
|
||||
import { apiGet, apiPut } from '@/lib/api'
|
||||
import { API_BASE_URL, SITE_TITLE } from '@/config'
|
||||
|
||||
import type { NicoTag, Tag, User } from '@/types'
|
||||
|
||||
@@ -28,8 +29,10 @@ export default ({ user }: Props) => {
|
||||
const loadMore = async (withCursor: boolean) => {
|
||||
setLoading (true)
|
||||
|
||||
const data = await apiGet<{ tags: NicoTag[]; nextCursor: string }> (
|
||||
'/tags/nico', { params: withCursor ? { cursor } : { } })
|
||||
const res = await axios.get (`${ API_BASE_URL }/tags/nico`, {
|
||||
params: { ...(withCursor ? { cursor } : { }) } })
|
||||
const data = toCamel (res.data as any, { deep: true }) as { tags: NicoTag[]
|
||||
nextCursor: string }
|
||||
|
||||
setNicoTags (tags => [...(withCursor ? tags : []), ...data.tags])
|
||||
setCursor (data.nextCursor)
|
||||
@@ -50,8 +53,10 @@ export default ({ user }: Props) => {
|
||||
const formData = new FormData
|
||||
formData.append ('tags', rawTags[id])
|
||||
|
||||
const data = await apiPut<Tag[]> (`/tags/nico/${ id }`, formData,
|
||||
{ headers: { 'Content-Type': 'multipart/form-data' } })
|
||||
const res = await axios.put (`${ API_BASE_URL }/tags/nico/${ id }`, formData, { headers: {
|
||||
'Content-Type': 'multipart/form-data',
|
||||
'X-Transfer-Code': localStorage.getItem ('user_code') ?? '' } })
|
||||
const data = toCamel (res.data as any, { deep: true }) as Tag[]
|
||||
setNicoTags (nicoTags => {
|
||||
nicoTags.find (t => t.id === id)!.linkedTags = data
|
||||
return [...nicoTags]
|
||||
@@ -92,13 +97,13 @@ export default ({ user }: Props) => {
|
||||
</Helmet>
|
||||
|
||||
<div className="max-w-xl">
|
||||
<PageTitle>ニコニコ連携</PageTitle>
|
||||
<SectionTitle>ニコニコ連携</SectionTitle>
|
||||
</div>
|
||||
|
||||
<div className="mt-4">
|
||||
{nicoTags.length > 0 && (
|
||||
<table className="table-auto w-full border-collapse mb-4">
|
||||
<thead className="border-b-2 border-black dark:border-white">
|
||||
<thead>
|
||||
<tr>
|
||||
<th className="p-2 text-left">ニコニコタグ</th>
|
||||
<th className="p-2 text-left">連携タグ</th>
|
||||
@@ -107,7 +112,7 @@ export default ({ user }: Props) => {
|
||||
</thead>
|
||||
<tbody>
|
||||
{nicoTags.map ((tag, i) => (
|
||||
<tr key={i} className="even:bg-gray-100 dark:even:bg-gray-700">
|
||||
<tr key={i}>
|
||||
<td className="p-2">
|
||||
<TagLink tag={tag} withWiki={false} withCount={false}/>
|
||||
</td>
|
||||
@@ -125,7 +130,7 @@ export default ({ user }: Props) => {
|
||||
</span>))}
|
||||
</td>
|
||||
{memberFlg && (
|
||||
<td className="p-2">
|
||||
<td>
|
||||
<a href="#" onClick={ev => {
|
||||
ev.preventDefault ()
|
||||
handleEdit (tag.id)
|
||||
|
||||
@@ -1,3 +1,4 @@
|
||||
import axios from 'axios'
|
||||
import { useEffect, useState } from 'react'
|
||||
import { Helmet } from 'react-helmet-async'
|
||||
|
||||
@@ -9,8 +10,7 @@ import InheritDialogue from '@/components/users/InheritDialogue'
|
||||
import UserCodeDialogue from '@/components/users/UserCodeDialogue'
|
||||
import { Button } from '@/components/ui/button'
|
||||
import { toast } from '@/components/ui/use-toast'
|
||||
import { SITE_TITLE } from '@/config'
|
||||
import { apiPut } from '@/lib/api'
|
||||
import { API_BASE_URL, SITE_TITLE } from '@/config'
|
||||
|
||||
import type { User } from '@/types'
|
||||
|
||||
@@ -32,9 +32,10 @@ export default ({ user, setUser }: Props) => {
|
||||
|
||||
try
|
||||
{
|
||||
const data = await apiPut<User> (
|
||||
`/users/${ user.id }`, formData,
|
||||
{ headers: { 'Content-Type': 'multipart/form-data' } })
|
||||
const res = await axios.put (`${ API_BASE_URL }/users/${ user.id }`, formData, {
|
||||
headers: { 'Content-Type': 'multipart/form-data',
|
||||
'X-Transfer-Code': localStorage.getItem ('user_code') || '' } })
|
||||
const data = res.data as User
|
||||
setUser (user => ({ ...user, ...data }))
|
||||
toast ({ title: '設定を更新しました.' })
|
||||
}
|
||||
|
||||
@@ -1,23 +1,19 @@
|
||||
import { useQuery } from '@tanstack/react-query'
|
||||
import { useEffect, useMemo } from 'react'
|
||||
import axios from 'axios'
|
||||
import toCamel from 'camelcase-keys'
|
||||
import { useEffect, useState } from 'react'
|
||||
import { Helmet } from 'react-helmet-async'
|
||||
import { useLocation, useNavigate, useParams } from 'react-router-dom'
|
||||
import { Link, useLocation, useNavigate, useParams } from 'react-router-dom'
|
||||
|
||||
import PostList from '@/components/PostList'
|
||||
import PrefetchLink from '@/components/PrefetchLink'
|
||||
import TagLink from '@/components/TagLink'
|
||||
import WikiBody from '@/components/WikiBody'
|
||||
import PageTitle from '@/components/common/PageTitle'
|
||||
import TabGroup, { Tab } from '@/components/common/TabGroup'
|
||||
import MainArea from '@/components/layout/MainArea'
|
||||
import { SITE_TITLE } from '@/config'
|
||||
import { API_BASE_URL, SITE_TITLE } from '@/config'
|
||||
import { WikiIdBus } from '@/lib/eventBus/WikiIdBus'
|
||||
import { fetchPosts } from '@/lib/posts'
|
||||
import { postsKeys, tagsKeys, wikiKeys } from '@/lib/queryKeys'
|
||||
import { fetchTagByName } from '@/lib/tags'
|
||||
import { fetchWikiPage, fetchWikiPageByTitle } from '@/lib/wiki'
|
||||
|
||||
import type { Tag } from '@/types'
|
||||
import type { Post, Tag, WikiPage } from '@/types'
|
||||
|
||||
|
||||
export default () => {
|
||||
@@ -27,62 +23,87 @@ export default () => {
|
||||
const location = useLocation ()
|
||||
const navigate = useNavigate ()
|
||||
|
||||
const defaultTag = useMemo (() => ({ name: title, category: 'general' } as Tag), [title])
|
||||
const defaultTag = { name: title, category: 'general' } as Tag
|
||||
|
||||
const [posts, setPosts] = useState<Post[]> ([])
|
||||
const [tag, setTag] = useState (defaultTag)
|
||||
const [wikiPage, setWikiPage] = useState<WikiPage | null | undefined> (undefined)
|
||||
|
||||
const query = new URLSearchParams (location.search)
|
||||
const version = query.get ('version') || undefined
|
||||
|
||||
const { data: wikiPage, isLoading: loading } = useQuery ({
|
||||
enabled: Boolean (title) && !(/^\d+$/.test (title)),
|
||||
queryKey: wikiKeys.show (title, { version }),
|
||||
queryFn: () => fetchWikiPageByTitle (title, { version }) })
|
||||
|
||||
const effectiveTitle = wikiPage?.title ?? title
|
||||
|
||||
const { data: tag } = useQuery ({
|
||||
enabled: Boolean (effectiveTitle),
|
||||
queryKey: tagsKeys.show (effectiveTitle),
|
||||
queryFn: () => fetchTagByName (effectiveTitle) })
|
||||
|
||||
const keys = {
|
||||
tags: effectiveTitle, match: 'all', page: 1, limit: 8, url: '', title: '',
|
||||
originalCreatedFrom: '', originalCreatedTo: '',
|
||||
createdFrom: '', createdTo: '', updatedFrom: '', updatedTo: '',
|
||||
order: 'original_created_at:desc' } as const
|
||||
const { data } = useQuery ({
|
||||
enabled: Boolean (effectiveTitle) && !(version),
|
||||
queryKey: postsKeys.index (keys),
|
||||
queryFn: () => fetchPosts (keys) })
|
||||
const posts = data?.posts || []
|
||||
const version = query.get ('version')
|
||||
|
||||
useEffect (() => {
|
||||
if (!(wikiPage))
|
||||
return
|
||||
if (/^\d+$/.test (title))
|
||||
{
|
||||
void (async () => {
|
||||
setWikiPage (undefined)
|
||||
try
|
||||
{
|
||||
const res = await axios.get (`${ API_BASE_URL }/wiki/${ title }`)
|
||||
const data = res.data as WikiPage
|
||||
navigate (`/wiki/${ encodeURIComponent(data.title) }`, { replace: true })
|
||||
}
|
||||
catch
|
||||
{
|
||||
;
|
||||
}
|
||||
}) ()
|
||||
|
||||
WikiIdBus.set (wikiPage.id)
|
||||
return
|
||||
}
|
||||
|
||||
if (wikiPage.title !== title)
|
||||
navigate (`/wiki/${ encodeURIComponent(wikiPage.title) }`, { replace: true })
|
||||
|
||||
return () => WikiIdBus.set (null)
|
||||
}, [wikiPage, title, navigate])
|
||||
|
||||
useEffect (() => {
|
||||
if (!(/^\d+$/.test (title)))
|
||||
return
|
||||
void (async () => {
|
||||
setWikiPage (undefined)
|
||||
try
|
||||
{
|
||||
const res = await axios.get (
|
||||
`${ API_BASE_URL }/wiki/title/${ encodeURIComponent (title) }`,
|
||||
{ params: version ? { version } : { } })
|
||||
const data = toCamel (res.data as any, { deep: true }) as WikiPage
|
||||
if (data.title !== title)
|
||||
navigate (`/wiki/${ encodeURIComponent(data.title) }`, { replace: true })
|
||||
setWikiPage (data)
|
||||
WikiIdBus.set (data.id)
|
||||
}
|
||||
catch
|
||||
{
|
||||
setWikiPage (null)
|
||||
}
|
||||
}) ()
|
||||
|
||||
setPosts ([])
|
||||
void (async () => {
|
||||
try
|
||||
{
|
||||
const data = await fetchWikiPage (title, { })
|
||||
navigate (`/wiki/${ encodeURIComponent(data.title) }`, { replace: true })
|
||||
const res = await axios.get (
|
||||
`${ API_BASE_URL }/posts?${ new URLSearchParams ({ tags: title,
|
||||
limit: '8' }) }`)
|
||||
const data = toCamel (res.data as any,
|
||||
{ deep: true }) as { posts: Post[]
|
||||
nextCursor: string }
|
||||
setPosts (data.posts)
|
||||
}
|
||||
catch
|
||||
{
|
||||
;
|
||||
}
|
||||
}) ()
|
||||
}, [title, navigate])
|
||||
|
||||
void (async () => {
|
||||
try
|
||||
{
|
||||
const res = await axios.get (
|
||||
`${ API_BASE_URL }/tags/name/${ encodeURIComponent (title) }`)
|
||||
setTag (toCamel (res.data as any, { deep: true }) as Tag)
|
||||
}
|
||||
catch
|
||||
{
|
||||
setTag (defaultTag)
|
||||
}
|
||||
}) ()
|
||||
|
||||
return () => WikiIdBus.set (null)
|
||||
}, [title, location.search])
|
||||
|
||||
return (
|
||||
<MainArea>
|
||||
@@ -92,29 +113,30 @@ export default () => {
|
||||
</Helmet>
|
||||
|
||||
{(wikiPage && version) && (
|
||||
<div className="text-sm flex gap-3 items-center justify-center
|
||||
border border-gray-700 rounded px-2 py-1 mb-4">
|
||||
<div className="text-sm flex gap-3 items-center justify-center border border-gray-700 rounded px-2 py-1 mb-4">
|
||||
{wikiPage.pred ? (
|
||||
<PrefetchLink to={`/wiki/${ encodeURIComponent (title) }?version=${ wikiPage.pred }`}>
|
||||
<Link to={`/wiki/${ encodeURIComponent (title) }?version=${ wikiPage.pred }`}>
|
||||
< 古
|
||||
</PrefetchLink>) : '(最古)'}
|
||||
</Link>) : '(最古)'}
|
||||
|
||||
<span>{wikiPage.updatedAt}</span>
|
||||
|
||||
{wikiPage.succ ? (
|
||||
<PrefetchLink to={`/wiki/${ encodeURIComponent (title) }?version=${ wikiPage.succ }`}>
|
||||
<Link to={`/wiki/${ encodeURIComponent (title) }?version=${ wikiPage.succ }`}>
|
||||
新 >
|
||||
</PrefetchLink>) : '(最新)'}
|
||||
</Link>) : '(最新)'}
|
||||
</div>)}
|
||||
|
||||
<PageTitle>
|
||||
<TagLink tag={tag ?? defaultTag}
|
||||
<TagLink tag={tag}
|
||||
withWiki={false}
|
||||
withCount={false}
|
||||
{...(version && { to: `/wiki/${ encodeURIComponent (title) }` })}/>
|
||||
</PageTitle>
|
||||
<div className="prose mx-auto p-4">
|
||||
{loading ? 'Loading...' : <WikiBody title={title} body={wikiPage?.body}/>}
|
||||
{wikiPage === undefined
|
||||
? 'Loading...'
|
||||
: <WikiBody title={title} body={wikiPage?.body}/>}
|
||||
</div>
|
||||
|
||||
{(!(version) && posts.length > 0) && (
|
||||
|
||||
@@ -1,11 +1,12 @@
|
||||
import axios from 'axios'
|
||||
import toCamel from 'camelcase-keys'
|
||||
import { useEffect, useState } from 'react'
|
||||
import { Helmet } from 'react-helmet-async'
|
||||
import { useLocation, useParams } from 'react-router-dom'
|
||||
|
||||
import PageTitle from '@/components/common/PageTitle'
|
||||
import MainArea from '@/components/layout/MainArea'
|
||||
import { SITE_TITLE } from '@/config'
|
||||
import { apiGet } from '@/lib/api'
|
||||
import { API_BASE_URL, SITE_TITLE } from '@/config'
|
||||
import { cn } from '@/lib/utils'
|
||||
|
||||
import type { WikiPageDiff } from '@/types'
|
||||
@@ -24,7 +25,8 @@ export default () => {
|
||||
|
||||
useEffect (() => {
|
||||
void (async () => {
|
||||
setDiff (await apiGet<WikiPageDiff> (`/wiki/${ id }/diff`, { params: { from, to } }))
|
||||
const res = await axios.get (`${ API_BASE_URL }/wiki/${ id }/diff`, { params: { from, to } })
|
||||
setDiff (toCamel (res.data as any, { deep: true }) as WikiPageDiff)
|
||||
}) ()
|
||||
}, [])
|
||||
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
import { useQueryClient } from '@tanstack/react-query'
|
||||
import axios from 'axios'
|
||||
import MarkdownIt from 'markdown-it'
|
||||
import { useEffect, useState } from 'react'
|
||||
import { Helmet } from 'react-helmet-async'
|
||||
@@ -7,9 +7,7 @@ import { useParams, useNavigate } from 'react-router-dom'
|
||||
|
||||
import MainArea from '@/components/layout/MainArea'
|
||||
import { toast } from '@/components/ui/use-toast'
|
||||
import { SITE_TITLE } from '@/config'
|
||||
import { apiGet, apiPut } from '@/lib/api'
|
||||
import { wikiKeys } from '@/lib/queryKeys'
|
||||
import { API_BASE_URL, SITE_TITLE } from '@/config'
|
||||
import Forbidden from '@/pages/Forbidden'
|
||||
|
||||
import 'react-markdown-editor-lite/lib/index.css'
|
||||
@@ -31,8 +29,6 @@ export default (({ user }: Props) => {
|
||||
|
||||
const navigate = useNavigate ()
|
||||
|
||||
const qc = useQueryClient ()
|
||||
|
||||
const [body, setBody] = useState ('')
|
||||
const [loading, setLoading] = useState (true)
|
||||
const [title, setTitle] = useState ('')
|
||||
@@ -44,11 +40,9 @@ export default (({ user }: Props) => {
|
||||
|
||||
try
|
||||
{
|
||||
await apiPut (`/wiki/${ id }`, formData,
|
||||
{ headers: { 'Content-Type': 'multipart/form-data' } })
|
||||
qc.setQueryData (wikiKeys.show (title, { }),
|
||||
(prev: WikiPage) => ({ ...prev, title, body }))
|
||||
qc.invalidateQueries ({ queryKey: wikiKeys.root })
|
||||
await axios.put (`${ API_BASE_URL }/wiki/${ id }`, formData, { headers: {
|
||||
'Content-Type': 'multipart/form-data',
|
||||
'X-Transfer-Code': localStorage.getItem ('user_code') ?? '' } })
|
||||
toast ({ title: '投稿成功!' })
|
||||
navigate (`/wiki/${ title }`)
|
||||
}
|
||||
@@ -61,7 +55,8 @@ export default (({ user }: Props) => {
|
||||
useEffect (() => {
|
||||
void (async () => {
|
||||
setLoading (true)
|
||||
const data = await apiGet<WikiPage> (`/wiki/${ id }`)
|
||||
const res = await axios.get (`${ API_BASE_URL }/wiki/${ id }`)
|
||||
const data = res.data as WikiPage
|
||||
setTitle (data.title)
|
||||
setBody (data.body)
|
||||
setLoading (false)
|
||||
|
||||
@@ -1,13 +1,11 @@
|
||||
import axios from 'axios'
|
||||
import toCamel from 'camelcase-keys'
|
||||
import { useEffect, useState } from 'react'
|
||||
import { Helmet } from 'react-helmet-async'
|
||||
import { useLocation } from 'react-router-dom'
|
||||
import { Link, useLocation } from 'react-router-dom'
|
||||
|
||||
import PrefetchLink from '@/components/PrefetchLink'
|
||||
import PageTitle from '@/components/common/PageTitle'
|
||||
import MainArea from '@/components/layout/MainArea'
|
||||
import { SITE_TITLE } from '@/config'
|
||||
import { apiGet } from '@/lib/api'
|
||||
import { dateString } from '@/lib/utils'
|
||||
import { API_BASE_URL, SITE_TITLE } from '@/config'
|
||||
|
||||
import type { WikiPageChange } from '@/types'
|
||||
|
||||
@@ -21,7 +19,9 @@ export default () => {
|
||||
|
||||
useEffect (() => {
|
||||
void (async () => {
|
||||
setChanges (await apiGet<WikiPageChange[]> ('/wiki/changes', { params: id ? { id } : { } }))
|
||||
const res = await axios.get (`${ API_BASE_URL }/wiki/changes`,
|
||||
{ params: { ...(id ? { id } : { }) } })
|
||||
setChanges (toCamel (res.data as any, { deep: true }) as WikiPageChange[])
|
||||
}) ()
|
||||
}, [location.search])
|
||||
|
||||
@@ -30,11 +30,8 @@ export default () => {
|
||||
<Helmet>
|
||||
<title>{`Wiki 変更履歴 | ${ SITE_TITLE }`}</title>
|
||||
</Helmet>
|
||||
|
||||
<PageTitle>Wiki 履歴</PageTitle>
|
||||
|
||||
<table className="table-auto w-full border-collapse">
|
||||
<thead className="border-b-2 border-black dark:border-white">
|
||||
<thead>
|
||||
<tr>
|
||||
<th></th>
|
||||
<th className="p-2 text-left">タイトル</th>
|
||||
@@ -44,29 +41,27 @@ export default () => {
|
||||
</thead>
|
||||
<tbody>
|
||||
{changes.map (change => (
|
||||
<tr key={change.revisionId} className="even:bg-gray-100 dark:even:bg-gray-700">
|
||||
<td className="p-2">
|
||||
<tr key={change.revisionId}>
|
||||
<td>
|
||||
{change.pred != null && (
|
||||
<PrefetchLink
|
||||
to={`/wiki/${ change.wikiPage.id }/diff?from=${ change.pred }&to=${ change.revisionId }`}>
|
||||
<Link to={`/wiki/${ change.wikiPage.id }/diff?from=${ change.pred }&to=${ change.revisionId }`}>
|
||||
差分
|
||||
</PrefetchLink>)}
|
||||
</Link>)}
|
||||
</td>
|
||||
<td className="p-2">
|
||||
<PrefetchLink
|
||||
to={`/wiki/${ encodeURIComponent (change.wikiPage.title) }?version=${ change.revisionId }`}>
|
||||
<Link to={`/wiki/${ encodeURIComponent (change.wikiPage.title) }?version=${ change.revisionId }`}>
|
||||
{change.wikiPage.title}
|
||||
</PrefetchLink>
|
||||
</Link>
|
||||
</td>
|
||||
<td className="p-2">
|
||||
{change.pred == null ? '新規' : '更新'}
|
||||
</td>
|
||||
<td className="p-2">
|
||||
<PrefetchLink to={`/users/${ change.user.id }`}>
|
||||
<Link to={`/users/${ change.user.id }`}>
|
||||
{change.user.name}
|
||||
</PrefetchLink>
|
||||
</Link>
|
||||
<br/>
|
||||
{dateString (change.timestamp)}
|
||||
{change.timestamp}
|
||||
</td>
|
||||
</tr>))}
|
||||
</tbody>
|
||||
|
||||
@@ -1,3 +1,4 @@
|
||||
import axios from 'axios'
|
||||
import MarkdownIt from 'markdown-it'
|
||||
import { useState } from 'react'
|
||||
import { Helmet } from 'react-helmet-async'
|
||||
@@ -6,8 +7,7 @@ import { useLocation, useNavigate } from 'react-router-dom'
|
||||
|
||||
import MainArea from '@/components/layout/MainArea'
|
||||
import { toast } from '@/components/ui/use-toast'
|
||||
import { SITE_TITLE } from '@/config'
|
||||
import { apiPost } from '@/lib/api'
|
||||
import { API_BASE_URL, SITE_TITLE } from '@/config'
|
||||
import Forbidden from '@/pages/Forbidden'
|
||||
|
||||
import 'react-markdown-editor-lite/lib/index.css'
|
||||
@@ -39,8 +39,10 @@ export default ({ user }: Props) => {
|
||||
|
||||
try
|
||||
{
|
||||
const data = await apiPost<WikiPage> ('/wiki', formData,
|
||||
{ headers: { 'Content-Type': 'multipart/form-data' } })
|
||||
const res = await axios.post (`${ API_BASE_URL }/wiki`, formData, { headers: {
|
||||
'Content-Type': 'multipart/form-data',
|
||||
'X-Transfer-Code': localStorage.getItem ('user_code') || '' } })
|
||||
const data = res.data as WikiPage
|
||||
toast ({ title: '投稿成功!' })
|
||||
navigate (`/wiki/${ data.title }`)
|
||||
}
|
||||
|
||||
@@ -1,14 +1,12 @@
|
||||
import { useEffect, useState } from 'react'
|
||||
import axios from 'axios'
|
||||
import toCamel from 'camelcase-keys'
|
||||
import React, { useEffect, useState } from 'react'
|
||||
import { Helmet } from 'react-helmet-async'
|
||||
import { Link } from 'react-router-dom'
|
||||
|
||||
import PrefetchLink from '@/components/PrefetchLink'
|
||||
import PageTitle from '@/components/common/PageTitle'
|
||||
import SectionTitle from '@/components/common/SectionTitle'
|
||||
import MainArea from '@/components/layout/MainArea'
|
||||
import { SITE_TITLE } from '@/config'
|
||||
import { apiGet } from '@/lib/api'
|
||||
import { dateString } from '@/lib/utils'
|
||||
|
||||
import type { FormEvent } from 'react'
|
||||
import { API_BASE_URL, SITE_TITLE } from '@/config'
|
||||
|
||||
import type { WikiPage } from '@/types'
|
||||
|
||||
@@ -19,10 +17,11 @@ export default () => {
|
||||
const [results, setResults] = useState<WikiPage[]> ([])
|
||||
|
||||
const search = async () => {
|
||||
setResults (await apiGet ('/wiki', { params: { title } }))
|
||||
const res = await axios.get (`${ API_BASE_URL }/wiki/search`, { params: { title } })
|
||||
setResults (toCamel (res.data as any, { deep: true }) as WikiPage[])
|
||||
}
|
||||
|
||||
const handleSearch = (ev: FormEvent) => {
|
||||
const handleSearch = (ev: React.FormEvent) => {
|
||||
ev.preventDefault ()
|
||||
search ()
|
||||
}
|
||||
@@ -36,9 +35,8 @@ export default () => {
|
||||
<Helmet>
|
||||
<title>Wiki | {SITE_TITLE}</title>
|
||||
</Helmet>
|
||||
|
||||
<div className="max-w-xl">
|
||||
<PageTitle>Wiki</PageTitle>
|
||||
<SectionTitle>Wiki</SectionTitle>
|
||||
<form onSubmit={handleSearch} className="space-y-2">
|
||||
{/* タイトル */}
|
||||
<div>
|
||||
@@ -70,7 +68,7 @@ export default () => {
|
||||
|
||||
<div className="mt-4">
|
||||
<table className="table-auto w-full border-collapse">
|
||||
<thead className="border-b-2 border-black dark:border-white">
|
||||
<thead>
|
||||
<tr>
|
||||
<th className="p-2 text-left">タイトル</th>
|
||||
<th className="p-2 text-left">最終更新</th>
|
||||
@@ -78,14 +76,14 @@ export default () => {
|
||||
</thead>
|
||||
<tbody>
|
||||
{results.map (page => (
|
||||
<tr key={page.id} className="even:bg-gray-100 dark:even:bg-gray-700">
|
||||
<tr key={page.id}>
|
||||
<td className="p-2">
|
||||
<PrefetchLink to={`/wiki/${ encodeURIComponent (page.title) }`}>
|
||||
<Link to={`/wiki/${ encodeURIComponent (page.title) }`}>
|
||||
{page.title}
|
||||
</PrefetchLink>
|
||||
</Link>
|
||||
</td>
|
||||
<td className="p-2">
|
||||
{dateString (page.updatedAt)}
|
||||
<td className="p-2 text-gray-100 text-sm">
|
||||
{page.updatedAt}
|
||||
</td>
|
||||
</tr>))}
|
||||
</tbody>
|
||||
|
||||
@@ -1,19 +0,0 @@
|
||||
import { create } from 'zustand'
|
||||
|
||||
type SharedTransitionState = {
|
||||
byLocationKey: Record<string, string>
|
||||
setForLocationKey: (locationKey: string, sharedId: string) => void
|
||||
clearForLocationKey: (locationKey: string) => void }
|
||||
|
||||
|
||||
export const useSharedTransitionStore = create<SharedTransitionState> (set => ({
|
||||
byLocationKey: { },
|
||||
setForLocationKey: (locationKey, sharedId) =>
|
||||
set (state => ({ byLocationKey: { ...state.byLocationKey,
|
||||
[locationKey]: sharedId } })),
|
||||
clearForLocationKey: (locationKey) =>
|
||||
set (state => {
|
||||
const next = { ...state.byLocationKey }
|
||||
delete next[locationKey]
|
||||
return { byLocationKey: next }
|
||||
}) }))
|
||||
+3
-26
@@ -1,31 +1,9 @@
|
||||
import { CATEGORIES,
|
||||
FETCH_POSTS_ORDER_FIELDS,
|
||||
USER_ROLES,
|
||||
ViewFlagBehavior } from '@/consts'
|
||||
import { CATEGORIES, USER_ROLES, ViewFlagBehavior } from '@/consts'
|
||||
|
||||
import type { ReactNode } from 'react'
|
||||
|
||||
export type Category = typeof CATEGORIES[number]
|
||||
|
||||
export type FetchPostsOrder = `${ FetchPostsOrderField }:${ 'asc' | 'desc' }`
|
||||
|
||||
export type FetchPostsOrderField = typeof FETCH_POSTS_ORDER_FIELDS[number]
|
||||
|
||||
export type FetchPostsParams = {
|
||||
url: string
|
||||
title: string
|
||||
tags: string
|
||||
match: 'all' | 'any'
|
||||
originalCreatedFrom: string
|
||||
originalCreatedTo: string
|
||||
createdFrom: string
|
||||
createdTo: string
|
||||
updatedFrom: string
|
||||
updatedTo: string
|
||||
page: number
|
||||
limit: number
|
||||
order: FetchPostsOrder }
|
||||
|
||||
export type Menu = MenuItem[]
|
||||
|
||||
export type MenuItem = {
|
||||
@@ -47,10 +25,9 @@ export type Post = {
|
||||
tags: Tag[]
|
||||
viewed: boolean
|
||||
related: Post[]
|
||||
originalCreatedFrom: string | null
|
||||
originalCreatedBefore: string | null
|
||||
createdAt: string
|
||||
updatedAt: string }
|
||||
originalCreatedFrom: string | null
|
||||
originalCreatedBefore: string | null }
|
||||
|
||||
export type PostTagChange = {
|
||||
post: Post
|
||||
|
||||
新しい課題から参照
ユーザをブロックする