このコミットが含まれているのは:
2026-06-25 07:44:11 +09:00
コミット fa6c547cc9
11個のファイルの変更865行の追加323行の削除
+161 -14
ファイルの表示
@@ -12,33 +12,47 @@ class MaterialsController < ApplicationController
offset = (page - 1) * limit
tag_id = params[:tag_id].presence
parent_id = params[:parent_id].presence
unclassified = bool?(:unclassified)
filters = material_index_filters
q = Material.includes(:material_export_items,
thumbnail_attachment: :blob,
file_attachment: :blob,
tag: :tag_name)
q = q.where(file_suppressed_at: nil) if filters[:suppression] == 'active'
q = q.where.not(file_suppressed_at: nil) if filters[:suppression] == 'suppressed'
q = q.where(tag_id: nil) if filters[:tag_state] == 'untagged'
q = q.where.not(tag_id: nil) if filters[:tag_state] == 'tagged'
q = q.where('materials.created_at >= ?', filters[:created_from]) if filters[:created_from]
q = q.where('materials.created_at <= ?', filters[:created_to]) if filters[:created_to]
q = q.where('materials.updated_at >= ?', filters[:updated_from]) if filters[:updated_from]
q = q.where('materials.updated_at <= ?', filters[:updated_to]) if filters[:updated_to]
q = Material.includes(:tag, :created_by_user, :material_export_items).with_attached_file
if unclassified
q = q.where(tag_id: nil)
else
q = q.where(tag_id:) if tag_id
q = q.where(parent_id:) if parent_id
end
q = material_index_join_tag_name(q) if material_index_needs_tag_name?(filters)
q = material_index_join_file_blob(q) if material_index_needs_file_blob?(filters)
q = apply_material_query(q, filters[:q]) if filters[:q].present?
q = apply_material_media_kind(q, filters[:media_kind])
count = q.count
materials = q.order(created_at: :desc, id: :desc).limit(limit).offset(offset)
count = q.distinct.count(:id)
materials =
q
.order(Arel.sql(material_index_order_sql(filters)))
.limit(limit)
.offset(offset)
.to_a
render json: { materials: MaterialRepr.many(materials, host: request.base_url), count: count }
render json: { materials: MaterialRepr.list_many(materials, host: request.base_url),
count: }
end
def show
material =
Material
.includes(:tag, :material_export_items)
.with_attached_thumbnail
.with_attached_file
.find_by(id: params[:id])
return head :not_found unless material
wiki_page_body = material.tag.tag_name.wiki_page&.current_revision&.body
wiki_page_body = material.tag&.tag_name&.wiki_page&.current_revision&.body
render json: MaterialRepr.base(material, host: request.base_url).merge(wiki_page_body:)
end
@@ -83,6 +97,8 @@ class MaterialsController < ApplicationController
end
if material
MaterialThumbnailGenerator.generate!(material)
material.reload
render json: MaterialRepr.base(material, host: request.base_url), status: :created
else
render_validation_error material
@@ -134,6 +150,9 @@ class MaterialsController < ApplicationController
raise
end
MaterialThumbnailGenerator.generate!(material)
material.reload
render json: MaterialRepr.base(material, host: request.base_url)
end
@@ -196,6 +215,134 @@ class MaterialsController < ApplicationController
private
def material_index_filters
tag_state = params[:tag_state].to_s.presence
tag_state = 'untagged' if bool?(:unclassified)
tag_state = 'all' unless ['all', 'tagged', 'untagged'].include?(tag_state)
media_kind = params[:media_kind].to_s.presence
unless ['all', 'image', 'video', 'audio', 'file_other', 'url_only'].include?(media_kind)
media_kind = 'all'
end
suppression = params[:suppression].to_s.presence
suppression = 'active' unless ['active', 'suppressed', 'all'].include?(suppression)
sort = params[:sort].to_s.presence
unless ['created_at', 'updated_at', 'tag_name', 'media_kind', 'file_byte_size',
'version_no', 'id'].include?(sort)
sort = 'created_at'
end
direction = params[:direction].to_s.downcase
direction = 'desc' unless ['asc', 'desc'].include?(direction)
{ q: params[:q].to_s.strip.presence,
tag_state:,
media_kind:,
suppression:,
created_from: parse_time_param(:created_from),
created_to: parse_time_param(:created_to),
updated_from: parse_time_param(:updated_from),
updated_to: parse_time_param(:updated_to),
sort:,
direction: }
end
def parse_time_param name
value = params[name].to_s.strip
return nil if value.blank?
Time.zone.parse(value)
rescue ArgumentError
nil
end
def material_index_needs_tag_name? filters
filters[:q].present? || filters[:sort] == 'tag_name'
end
def material_index_needs_file_blob? filters
filters[:q].present? ||
filters[:media_kind] != 'all' ||
['media_kind', 'file_byte_size'].include?(filters[:sort])
end
def material_index_join_tag_name q
q.left_joins(tag: :tag_name)
end
def material_index_join_file_blob q
q.joins(<<~SQL.squish)
LEFT JOIN active_storage_attachments material_file_attachments
ON material_file_attachments.record_type = 'Material'
AND material_file_attachments.record_id = materials.id
AND material_file_attachments.name = 'file'
LEFT JOIN active_storage_blobs material_file_blobs
ON material_file_blobs.id = material_file_attachments.blob_id
SQL
end
def apply_material_query q, term
like = "%#{ ActiveRecord::Base.sanitize_sql_like(term) }%"
q.where('tag_names.name LIKE :q OR materials.url LIKE :q OR ' \
'material_file_blobs.filename LIKE :q',
q: like)
end
def apply_material_media_kind q, media_kind
case media_kind
when 'image'
q.where('material_file_blobs.content_type LIKE ?', 'image/%')
when 'video'
q.where('material_file_blobs.content_type LIKE ?', 'video/%')
when 'audio'
q.where('material_file_blobs.content_type LIKE ?', 'audio/%')
when 'file_other'
q.where('material_file_attachments.id IS NOT NULL')
.where.not('material_file_blobs.content_type LIKE ?', 'image/%')
.where.not('material_file_blobs.content_type LIKE ?', 'video/%')
.where.not('material_file_blobs.content_type LIKE ?', 'audio/%')
when 'url_only'
q.where('material_file_attachments.id IS NULL').where.not(url: [nil, ''])
else
q
end
end
def material_index_order_sql filters
direction = filters[:direction] == 'asc' ? 'ASC' : 'DESC'
sort_sql =
case filters[:sort]
when 'tag_name'
'tag_names.name'
when 'media_kind'
material_media_kind_sql
when 'file_byte_size'
'material_file_blobs.byte_size'
when 'updated_at'
'materials.updated_at'
when 'version_no'
'materials.version_no'
when 'id'
'materials.id'
else
'materials.created_at'
end
"#{ sort_sql } #{ direction }, materials.id #{ direction }"
end
def material_media_kind_sql
"CASE " \
"WHEN material_file_attachments.id IS NULL AND materials.url IS NOT NULL THEN 5 " \
"WHEN material_file_blobs.content_type LIKE 'image/%' THEN 1 " \
"WHEN material_file_blobs.content_type LIKE 'video/%' THEN 2 " \
"WHEN material_file_blobs.content_type LIKE 'audio/%' THEN 3 " \
"WHEN material_file_attachments.id IS NOT NULL THEN 4 " \
"ELSE 6 END"
end
def upsert_export_paths! material
raw = params[:export_paths]
return if raw.blank?
+13
ファイルの表示
@@ -15,6 +15,7 @@ class Material < ApplicationRecord
has_many :material_export_items, dependent: :destroy
has_one_attached :file, dependent: :purge
has_one_attached :thumbnail, dependent: :purge
validates :tag_id, presence: true, uniqueness: true
@@ -28,6 +29,18 @@ class Material < ApplicationRecord
file.blob.content_type
end
def file_byte_size
return nil unless file&.attached?
file.blob.byte_size
end
def file_filename
return nil unless file&.attached?
file.blob.filename.to_s
end
def file_suppressed? = file_suppressed_at.present?
def snapshot_export_paths
+64
ファイルの表示
@@ -17,6 +17,11 @@ module MaterialRepr
Rails.application.routes.url_helpers.rails_storage_proxy_url(
material.file, host:)
end,
thumbnail: thumbnail_url(material, host:),
thumbnail_fallback_text: thumbnail_fallback_text(material),
thumbnail_fallback_kind: thumbnail_fallback_kind(material),
media_kind: media_kind(material),
file_byte_size: material.file_byte_size,
export_paths: export_paths(material),
export_items: export_items(material))
end
@@ -25,6 +30,28 @@ module MaterialRepr
materials.map { |m| base(m, host:) }
end
def list material, host:
{ id: material.id,
version_no: material.version_no,
url: material.url,
tag: compact_tag(material.tag),
thumbnail: thumbnail_url(material, host:),
thumbnail_fallback_text: thumbnail_fallback_text(material),
thumbnail_fallback_kind: thumbnail_fallback_kind(material),
media_kind: media_kind(material),
content_type: material.content_type,
file_byte_size: material.file_byte_size,
file_suppressed_at: material.file_suppressed_at,
created_at: material.created_at,
updated_at: material.updated_at,
export_paths: export_paths(material),
export_items: export_items(material) }
end
def list_many materials, host:
materials.map { |m| list(m, host:) }
end
def export_paths material
material.material_export_items.each_with_object({ }) do |item, hash|
hash[item.profile] = item.enabled ? item.export_path : ''
@@ -39,4 +66,41 @@ module MaterialRepr
enabled: item.enabled }
end
end
def thumbnail_url material, host:
return nil if material.file_suppressed?
return nil unless material.thumbnail.attached?
Rails.application.routes.url_helpers.rails_storage_proxy_url(
material.thumbnail, host:)
end
def thumbnail_fallback_text material
material.tag&.name || material.created_at&.strftime('%Y-%m-%d')
end
def thumbnail_fallback_kind material
material.tag.present? ? 'tag_name' : 'created_at'
end
def media_kind material
return 'suppressed' if material.file_suppressed?
return 'url_only' unless material.file.attached?
content_type = material.file.blob.content_type.to_s
return 'image' if content_type.start_with?('image/')
return 'video' if content_type.start_with?('video/')
return 'audio' if content_type.start_with?('audio/')
'file_other'
end
def compact_tag tag
return nil unless tag
{ id: tag.id,
name: tag.name,
category: tag.category,
deprecated_at: tag.deprecated_at }
end
end
+86
ファイルの表示
@@ -0,0 +1,86 @@
# frozen_string_literal: true
require 'mini_magick'
require 'open3'
require 'tempfile'
class MaterialThumbnailGenerator
SIZE = '180x180'
class << self
def generate! material
new(material).generate!
rescue ActiveStorage::FileNotFoundError, ArgumentError, MiniMagick::Error => e
Rails.logger.warn("Material thumbnail generation skipped: #{ e.class }: #{ e.message }")
nil
end
end
def initialize material
@material = material
end
def generate!
@material.thumbnail.purge if @material.thumbnail.attached?
return unless @material.file.attached?
return unless image? || video?
@material.file.blob.open do |file|
thumbnail = image? ? image_thumbnail(file.path) : video_thumbnail(file.path)
attach_thumbnail(thumbnail) if thumbnail
end
end
private
def image? = content_type.start_with?('image/')
def video? = content_type.start_with?('video/')
def content_type = @material.file.blob.content_type.to_s
def image_thumbnail path
image = MiniMagick::Image.open(path)
image.resize(SIZE)
image.format('jpg')
image
end
def video_thumbnail path
[1, 0].each do |seconds|
tempfile = Tempfile.new(['material-thumbnail', '.jpg'])
tempfile.close
ok = extract_video_frame(path, tempfile.path, seconds)
next unless ok && File.size?(tempfile.path)
return image_thumbnail(tempfile.path)
ensure
tempfile&.unlink
end
nil
end
def extract_video_frame input_path, output_path, seconds
_stdout, stderr, status =
Open3.capture3('ffmpeg',
'-y',
'-ss', seconds.to_s,
'-i', input_path,
'-frames:v', '1',
'-f', 'image2',
output_path)
Rails.logger.warn("ffmpeg thumbnail failed: #{ stderr }") unless status.success?
status.success?
rescue Errno::ENOENT => e
Rails.logger.warn("ffmpeg unavailable for material thumbnail: #{ e.message }")
false
end
def attach_thumbnail image
@material.thumbnail.attach(io: File.open(image.path),
filename: 'material-thumbnail.jpg',
content_type: 'image/jpeg')
end
end
+1 -1
ファイルの表示
@@ -40,7 +40,7 @@ const setChildrenById = (
const materialPath = (
tagName: string,
materialFilter: MaterialFilter,
): string => `/materials?tag=${ encodeURIComponent (tagName) }&material_filter=${ materialFilter }`
): string => `/materials?q=${ encodeURIComponent (tagName) }&material_filter=${ materialFilter }`
const sidebarTagToTag = (tag: MaterialSidebarTag): Tag => ({
+15 -14
ファイルの表示
@@ -8,19 +8,12 @@ import {
import type {
Material,
FetchMaterialsParams,
MaterialFilter,
MaterialSidebarTag,
MaterialTagTree,
} from '@/types'
export type FetchMaterialsParams = {
page?: number
limit?: number
tagId?: number | null
parentId?: number | null
unclassified?: boolean
}
export type FetchMaterialTreeParams = {
parentId?: number | null
materialFilter: MaterialFilter
@@ -44,14 +37,22 @@ export const parseMaterialFilter = (
export const fetchMaterials = async (
{ page, limit, tagId, parentId, unclassified }: FetchMaterialsParams,
{ q, tagState, mediaKind, suppression, createdFrom, createdTo,
updatedFrom, updatedTo, sort, direction, page, limit }: FetchMaterialsParams,
): Promise<MaterialIndexResponse> =>
await apiGet ('/materials', { params: {
...(page != null && { page }),
...(limit != null && { limit }),
...(tagId != null && { tag_id: tagId }),
...(parentId != null && { parent_id: parentId }),
...(unclassified && { unclassified: '1' }),
...(q && { q }),
tag_state: tagState,
media_kind: mediaKind,
suppression,
...(createdFrom && { created_from: createdFrom }),
...(createdTo && { created_to: createdTo }),
...(updatedFrom && { updated_from: updatedFrom }),
...(updatedTo && { updated_to: updatedTo }),
sort,
direction,
page,
limit,
} })
+2 -7
ファイルの表示
@@ -1,5 +1,6 @@
import type {
FetchNicoTagsParams,
FetchMaterialsParams,
FetchPostsParams,
FetchTagsParams,
MaterialFilter,
@@ -32,13 +33,7 @@ export const tagsKeys = {
export const materialsKeys = {
root: ['materials'] as const,
index: (p: {
page?: number
limit?: number
tagId?: number | null
parentId?: number | null
unclassified?: boolean
}) => ['materials', 'index', p] as const,
index: (p: FetchMaterialsParams) => ['materials', 'index', p] as const,
byTagName: (name: string, materialFilter: MaterialFilter) =>
['materials', 'tag', name, materialFilter] as const,
show: (id: string) => ['materials', id] as const,
+22 -10
ファイルの表示
@@ -47,12 +47,15 @@ const MaterialDetailPage: FC<{ user: User | null }> = ({ user }) => {
queryFn: () => fetchMaterial (id ?? ''),
enabled: id != null,
})
const materialTitle = material
? material.tag?.name ?? `素材 #${ material.id }`
: ''
useEffect (() => {
if (!(material))
return
setTag (material.tag.name)
setTag (material.tag?.name ?? '')
setURL (material.url ?? '')
setExportPath (material.exportPaths.legacyDrive ?? '')
if (material.file && material.contentType)
@@ -124,7 +127,7 @@ const MaterialDetailPage: FC<{ user: User | null }> = ({ user }) => {
<MainArea>
{material && (
<Helmet>
<title>{`${ material.tag.name } 素材照会 | ${ SITE_TITLE }`}</title>
<title>{`${ materialTitle } 素材照会 | ${ SITE_TITLE }`}</title>
</Helmet>)}
{isLoading ? 'Loading...' : isError ? (
@@ -138,10 +141,13 @@ const MaterialDetailPage: FC<{ user: User | null }> = ({ user }) => {
) : (
<>
<PageTitle>
<TagLink
tag={material.tag}
withWiki={false}
withCount={false}/>
{material.tag
? (
<TagLink
tag={material.tag}
withWiki={false}
withCount={false}/>)
: materialTitle}
</PageTitle>
{material.fileSuppressedAt && (
@@ -155,7 +161,7 @@ const MaterialDetailPage: FC<{ user: User | null }> = ({ user }) => {
{(!material.fileSuppressedAt && material.file && material.contentType) && (
(/image\/.*/.test (material.contentType) && (
<img src={material.file} alt={material.tag.name || undefined}/>))
<img src={material.file} alt={material.tag?.name || undefined}/>))
|| (/video\/.*/.test (material.contentType) && (
<video src={material.file} controls/>))
|| (/audio\/.*/.test (material.contentType) && (
@@ -163,9 +169,15 @@ const MaterialDetailPage: FC<{ user: User | null }> = ({ user }) => {
<TabGroup>
<Tab name="Wiki">
<WikiBody
title={material.tag.name}
body={material.wikiPageBody ?? undefined}/>
{material.tag
? (
<WikiBody
title={material.tag.name}
body={material.wikiPageBody ?? undefined}/>)
: (
<p className="text-stone-700 dark:text-stone-300">
</p>)}
</Tab>
<Tab name="編輯">
+450 -276
ファイルの表示
@@ -1,281 +1,291 @@
import { useQuery } from '@tanstack/react-query'
import { Fragment, useEffect, useMemo, useState } from 'react'
import { useEffect, useMemo, useState } from 'react'
import { Helmet } from 'react-helmet-async'
import { useLocation, useNavigate } from 'react-router-dom'
import nikumaru from '@/assets/fonts/nikumaru.otf'
import PrefetchLink from '@/components/PrefetchLink'
import TagLink from '@/components/TagLink'
import DateTimeField from '@/components/common/DateTimeField'
import FormField from '@/components/common/FormField'
import PageTitle from '@/components/common/PageTitle'
import SectionTitle from '@/components/common/SectionTitle'
import SubsectionTitle from '@/components/common/SubsectionTitle'
import TagInput from '@/components/common/TagInput'
import Pagination from '@/components/common/Pagination'
import MainArea from '@/components/layout/MainArea'
import { API_BASE_URL, SITE_TITLE } from '@/config'
import {
fetchMaterials,
fetchMaterialTagByName,
parseMaterialFilter,
} from '@/lib/materials'
import { fetchMaterials, parseMaterialFilter } from '@/lib/materials'
import { materialsKeys } from '@/lib/queryKeys'
import { inputClass } from '@/lib/utils'
import { dateString, inputClass } from '@/lib/utils'
import type { FC } from 'react'
import type { FC, FormEvent } from 'react'
import type { Material, MaterialFilter, MaterialTagTree } from '@/types'
import type {
FetchMaterialsParams,
Material,
MaterialIndexDirection,
MaterialIndexMediaKind,
MaterialIndexSort,
MaterialIndexSuppression,
MaterialIndexTagState,
MaterialIndexView,
} from '@/types'
const MATERIAL_FILTER_LABELS: Record<MaterialFilter, string> = {
present: '素材あり',
missing: '素材なし',
any: 'すべて',
const MEDIA_KIND_LABELS: Record<Material['mediaKind'], string> = {
image: '画像',
video: '動画',
audio: '音声',
file_other: 'その他ファイル',
url_only: 'URL のみ',
suppressed: '抑止済み',
}
const MEDIA_FILTER_LABELS: Record<MaterialIndexMediaKind, string> = {
all: 'すべて',
image: '画像',
video: '動画',
audio: '音声',
file_other: 'その他ファイル',
url_only: 'URL のみ',
}
const SORT_LABELS: Record<MaterialIndexSort, string> = {
created_at: '作成日時',
updated_at: '更新日時',
tag_name: 'タグ名',
media_kind: '種類',
file_byte_size: 'ファイルサイズ',
version_no: 'バージョン',
id: 'ID',
}
const MaterialCard = ({ tag }: { tag: MaterialTagTree }) => {
if (!(tag.material))
return null
return (
<PrefetchLink
to={`/materials/${ tag.material.id }`}
className="block h-40 w-40">
<div
className={`h-full w-full overflow-hidden rounded-xl shadow text-center
content-center text-4xl ${
tag.material.fileSuppressedAt
? 'border-2 border-red-300 bg-red-50 text-base text-red-900 ' +
'dark:border-red-800 dark:bg-red-950 dark:text-red-100'
: 'bg-white text-stone-900 dark:bg-stone-900 dark:text-stone-100' }`}
style={{ fontFamily: 'Nikumaru' }}>
{tag.material.fileSuppressedAt
? <span></span>
: (tag.material.contentType && /image\/.*/.test (tag.material.contentType))
? <img src={tag.material.file || undefined}/>
: <span></span>}
</div>
</PrefetchLink>)
const setIf = (qs: URLSearchParams, key: string, value: string | null) => {
const next = value?.trim ()
if (next)
qs.set (key, next)
}
const MaterialList = ({ materials }: { materials: Material[] }) => (
<div className="grid gap-3 sm:grid-cols-2 xl:grid-cols-3">
{materials.map (material => (
<article
key={material.id}
className={`rounded-2xl border p-4 shadow-sm ${
material.fileSuppressedAt
? 'border-red-200 bg-red-50 text-red-900 dark:border-red-900 ' +
'dark:bg-red-950 dark:text-red-100'
: 'border-stone-200 bg-white text-stone-900 dark:border-stone-700 ' +
'dark:bg-stone-900 dark:text-stone-100'}`}>
<div className="flex items-start justify-between gap-3">
<div>
<h2 className="font-medium text-stone-900 dark:text-stone-100">
{material.tag?.name ?? '未分類素材'}
</h2>
{material.fileSuppressedAt && (
<p className="mt-1 text-sm text-red-700 dark:text-red-200"></p>)}
</div>
<PrefetchLink
to={`/materials/${ material.id }`}
className="text-sm text-sky-700 underline underline-offset-2 dark:text-sky-300">
</PrefetchLink>
</div>
{material.exportPaths.legacyDrive && (
<p className="mt-3 break-all text-sm text-stone-600 dark:text-stone-300">
{material.exportPaths.legacyDrive}
</p>)}
</article>))}
const parseOption = <T extends string> (
value: string | null,
allowed: readonly T[],
fallback: T,
): T => allowed.includes (value as T) ? value as T : fallback
const fileSizeText = (bytes: number | null): string => {
if (bytes == null)
return ''
if (bytes < 1024)
return `${ bytes } B`
if (bytes < 1024 * 1024)
return `${ (bytes / 1024).toFixed (1) } KB`
return `${ (bytes / 1024 / 1024).toFixed (1) } MB`
}
const materialTitle = (material: Material): string =>
material.tag?.name ?? `素材 #${ material.id }`
const MaterialThumb: FC<{ material: Material }> = ({ material }) => (
<div
className={`flex aspect-square h-[180px] w-[180px] items-center justify-center
overflow-hidden rounded-lg border text-center shadow-sm ${
material.fileSuppressedAt
? [
'border-red-300 bg-red-50 text-red-900 dark:border-red-800',
'dark:bg-red-950 dark:text-red-100',
].join (' ')
: [
'border-stone-200 bg-white text-stone-900 dark:border-stone-700',
'dark:bg-stone-900 dark:text-stone-100',
].join (' ') }`}>
{material.thumbnail
? <img src={material.thumbnail} alt="" className="h-full w-full object-contain"/>
: (
<span
className="px-2 text-2xl leading-tight"
style={{ fontFamily: material.thumbnailFallbackKind === 'tag_name'
? 'Nikumaru'
: undefined }}>
{material.thumbnailFallbackText}
</span>)}
</div>)
const MaterialTagTreeView = ({ tag }: { tag: MaterialTagTree }) => (
<>
<PageTitle>
<TagLink
tag={tag}
withWiki={false}
withCount={false}
to={tag.material
? `/materials/${ tag.material.id }`
: `/materials?tag=${ encodeURIComponent (tag.name) }`}/>
</PageTitle>
{(!tag.material && tag.hasMaterial !== true && tag.category !== 'meme') && (
<div className="-mt-2">
<PrefetchLink to={`/materials/new?tag=${ encodeURIComponent (tag.name) }`}>
const MaterialCard: FC<{ material: Material }> = ({ material }) => (
<article className="w-[180px] justify-self-center">
<PrefetchLink to={`/materials/${ material.id }`} className="block">
<MaterialThumb material={material}/>
<div className="mt-2 w-[180px]">
<p className="truncate text-sm font-medium text-stone-900 dark:text-stone-100">
{materialTitle (material)}
</p>
<p className="truncate text-xs text-stone-600 dark:text-stone-300">
{MEDIA_KIND_LABELS[material.mediaKind]} / {dateString (material.createdAt)}
</p>
</div>
</PrefetchLink>
</article>)
const MaterialListItem: FC<{ material: Material }> = ({ material }) => (
<article
className={`rounded-lg border p-3 shadow-sm ${
material.fileSuppressedAt
? [
'border-red-200 bg-red-50 text-red-900 dark:border-red-900',
'dark:bg-red-950 dark:text-red-100',
].join (' ')
: [
'border-stone-200 bg-white text-stone-900 dark:border-stone-700',
'dark:bg-stone-900 dark:text-stone-100',
].join (' ')}`}>
<div className="flex gap-3">
<MaterialThumb material={material}/>
<div className="min-w-0 flex-1 space-y-2">
<div>
<PrefetchLink
to={`/materials/${ material.id }`}
className="font-medium text-sky-700 underline underline-offset-2
dark:text-sky-300">
{materialTitle (material)}
</PrefetchLink>
</div>)}
<MaterialCard tag={tag}/>
<div className="ml-2 overflow-x-auto pb-2">
{tag.children.map (c2 => (
<Fragment key={c2.id}>
<SectionTitle>
<TagLink
tag={c2}
withWiki={false}
withCount={false}
to={`/materials?tag=${ encodeURIComponent (c2.name) }`}/>
</SectionTitle>
{(!c2.material && c2.hasMaterial !== true && c2.category !== 'meme') && (
<div className="-mt-4">
<PrefetchLink to={`/materials/new?tag=${ encodeURIComponent (c2.name) }`}>
</PrefetchLink>
</div>)}
<MaterialCard tag={c2}/>
<div className="ml-2">
{c2.children.map (c3 => (
<Fragment key={c3.id}>
<SubsectionTitle>
<TagLink
tag={c3}
withWiki={false}
withCount={false}
to={`/materials?tag=${ encodeURIComponent (c3.name) }`}/>
</SubsectionTitle>
{(!c3.material && c3.hasMaterial !== true && c3.category !== 'meme') && (
<div className="-mt-2">
<PrefetchLink
to={`/materials/new?tag=${ encodeURIComponent (c3.name) }`}>
</PrefetchLink>
</div>)}
<MaterialCard tag={c3}/>
</Fragment>))}
</div>
</Fragment>))}
</div>
</>)
const MaterialSearchTop: FC<{
materialFilter: MaterialFilter
setMaterialFilter: (value: MaterialFilter) => void
tagName: string
setTagName: (value: string) => void
}> = ({ materialFilter, setMaterialFilter, tagName, setTagName }) => {
const navigate = useNavigate ()
const location = useLocation ()
const handleSearch = () => {
const qs = new URLSearchParams (location.search)
if (tagName.trim ())
qs.set ('tag', tagName.trim ())
else
qs.delete ('tag')
qs.delete ('unclassified')
qs.set ('material_filter', materialFilter)
navigate (`/materials?${ qs.toString () }`)
}
return (
<div className="mx-auto max-w-3xl space-y-6">
<PageTitle></PageTitle>
<section className="rounded-3xl border border-stone-200 bg-white p-5 shadow-sm
text-stone-900 dark:border-stone-700 dark:bg-stone-900
dark:text-stone-100">
<div className="space-y-4">
<FormField label="タグ名検索">
{() => (
<TagInput
value={tagName}
setValue={setTagName}/>)}
</FormField>
<FormField label="素材状態">
{({ invalid }) => (
<select
value={materialFilter}
onChange={e => setMaterialFilter (e.target.value as MaterialFilter)}
className={inputClass (invalid)}>
{Object.entries (MATERIAL_FILTER_LABELS).map (([value, label]) => (
<option key={value} value={value}>
{label}
</option>))}
</select>)}
</FormField>
<div className="flex flex-wrap gap-3">
<button
type="button"
onClick={handleSearch}
className="rounded-full bg-sky-600 px-4 py-2 text-white hover:bg-sky-700
dark:bg-sky-500 dark:text-stone-950 dark:hover:bg-sky-400">
</button>
<PrefetchLink
to={`/materials?unclassified=1&material_filter=${ materialFilter }`}
className="rounded-full border border-stone-300 bg-white px-4 py-2
text-stone-900 hover:bg-stone-100 dark:border-stone-700
dark:bg-stone-900 dark:text-stone-100 dark:hover:bg-stone-800">
</PrefetchLink>
<PrefetchLink
to="/materials/new"
className="rounded-full border border-stone-300 bg-white px-4 py-2
text-stone-900 hover:bg-stone-100 dark:border-stone-700
dark:bg-stone-900 dark:text-stone-100 dark:hover:bg-stone-800">
</PrefetchLink>
<a
href={`${ API_BASE_URL }/materials/download.zip?profile=legacy_drive`}
target="_blank"
rel="noopener noreferrer"
className="rounded-full border border-stone-300 bg-white px-4 py-2
text-stone-900 hover:bg-stone-100 dark:border-stone-700
dark:bg-stone-900 dark:text-stone-100 dark:hover:bg-stone-800">
ZIP
</a>
</div>
{material.fileSuppressedAt && (
<p className="mt-1 text-sm text-red-700 dark:text-red-200"></p>)}
</div>
</section>
</div>)
}
<dl className="space-y-1 text-sm text-stone-600 dark:text-stone-300">
<div>
<dt className="inline">: </dt>
<dd className="inline">{MEDIA_KIND_LABELS[material.mediaKind]}</dd>
</div>
{material.fileByteSize != null && (
<div>
<dt className="inline">: </dt>
<dd className="inline">{fileSizeText (material.fileByteSize)}</dd>
</div>)}
{material.url && (
<div>
<dt className="inline">URL: </dt>
<dd className="inline break-all">{material.url}</dd>
</div>)}
<div>
<dt className="inline">: </dt>
<dd className="inline">{dateString (material.createdAt)}</dd>
</div>
</dl>
</div>
</div>
</article>)
const MaterialListPage: FC = () => {
const location = useLocation ()
const navigate = useNavigate ()
const query = useMemo (() => new URLSearchParams (location.search), [location.search])
const tagQuery = query.get ('tag') ?? ''
const unclassified = query.get ('unclassified') === '1'
const initialFilter = parseMaterialFilter (query.get ('material_filter'), 'present')
const materialFilter = parseMaterialFilter (query.get ('material_filter'), 'present')
const [tagName, setTagName] = useState (tagQuery)
const [materialFilter, setMaterialFilter] = useState<MaterialFilter> (initialFilter)
const page = Number (query.get ('page') ?? 1)
const limit = Number (query.get ('limit') ?? 20)
const qQuery = query.get ('q') ?? query.get ('tag') ?? ''
const tagState = query.get ('unclassified') === '1'
? 'untagged'
: parseOption<MaterialIndexTagState> (
query.get ('tag_state'),
['all', 'tagged', 'untagged'],
'all')
const mediaKind = parseOption<MaterialIndexMediaKind> (
query.get ('media_kind'),
['all', 'image', 'video', 'audio', 'file_other', 'url_only'],
'all')
const suppression = parseOption<MaterialIndexSuppression> (
query.get ('suppression'),
['active', 'suppressed', 'all'],
'active')
const sort = parseOption<MaterialIndexSort> (
query.get ('sort'),
['created_at', 'updated_at', 'tag_name', 'media_kind', 'file_byte_size',
'version_no', 'id'],
'created_at')
const direction = parseOption<MaterialIndexDirection> (
query.get ('direction'),
['asc', 'desc'],
'desc')
const view = parseOption<MaterialIndexView> (query.get ('view'), ['card', 'list'], 'card')
const createdFromQuery = query.get ('created_from') ?? ''
const createdToQuery = query.get ('created_to') ?? ''
const updatedFromQuery = query.get ('updated_from') ?? ''
const updatedToQuery = query.get ('updated_to') ?? ''
const {
data: tag,
isLoading: tagLoading,
isError: tagError,
} = useQuery ({
queryKey: materialsKeys.byTagName (tagQuery, initialFilter),
queryFn: () => fetchMaterialTagByName (tagQuery, initialFilter),
enabled: tagQuery !== '' && !unclassified,
})
const {
data: unclassifiedData,
isLoading: unclassifiedLoading,
isError: unclassifiedError,
} = useQuery ({
queryKey: materialsKeys.unclassified ({ page: 1, limit: 50 }),
queryFn: () => fetchMaterials ({ page: 1, limit: 50, unclassified: true }),
enabled: unclassified,
const [q, setQ] = useState ('')
const [tagStateInput, setTagStateInput] = useState<MaterialIndexTagState> ('all')
const [mediaKindInput, setMediaKindInput] = useState<MaterialIndexMediaKind> ('all')
const [suppressionInput, setSuppressionInput] =
useState<MaterialIndexSuppression> ('active')
const [createdFrom, setCreatedFrom] = useState<string | null> (null)
const [createdTo, setCreatedTo] = useState<string | null> (null)
const [updatedFrom, setUpdatedFrom] = useState<string | null> (null)
const [updatedTo, setUpdatedTo] = useState<string | null> (null)
const keys: FetchMaterialsParams = {
q: qQuery,
tagState,
mediaKind,
suppression,
createdFrom: createdFromQuery,
createdTo: createdToQuery,
updatedFrom: updatedFromQuery,
updatedTo: updatedToQuery,
sort,
direction,
view,
page,
limit,
}
const { data, isLoading, isError } = useQuery ({
queryKey: materialsKeys.index (keys),
queryFn: () => fetchMaterials (keys),
})
const materials = data?.materials ?? []
const totalPages = data ? Math.ceil (data.count / limit) : 0
useEffect (() => {
setTagName (tagQuery)
setMaterialFilter (initialFilter)
}, [initialFilter, tagQuery])
setQ (qQuery)
setTagStateInput (tagState)
setMediaKindInput (mediaKind)
setSuppressionInput (suppression)
setCreatedFrom (createdFromQuery)
setCreatedTo (createdToQuery)
setUpdatedFrom (updatedFromQuery)
setUpdatedTo (updatedToQuery)
}, [createdFromQuery, createdToQuery, mediaKind, qQuery, suppression, tagState,
updatedFromQuery, updatedToQuery])
const search = (e: FormEvent) => {
e.preventDefault ()
const qs = new URLSearchParams ()
setIf (qs, 'q', q)
qs.set ('tag_state', tagStateInput)
qs.set ('media_kind', mediaKindInput)
qs.set ('suppression', suppressionInput)
setIf (qs, 'created_from', createdFrom)
setIf (qs, 'created_to', createdTo)
setIf (qs, 'updated_from', updatedFrom)
setIf (qs, 'updated_to', updatedTo)
qs.set ('sort', sort)
qs.set ('direction', direction)
qs.set ('view', view)
qs.set ('page', '1')
qs.set ('limit', String (limit))
qs.set ('material_filter', materialFilter)
navigate (`/materials?${ qs.toString () }`)
}
const updateQuery = (changes: Record<string, string>) => {
const qs = new URLSearchParams (location.search)
Object.entries (changes).forEach (([key, value]) => qs.set (key, value))
navigate (`/materials?${ qs.toString () }`)
}
return (
<MainArea>
@@ -288,41 +298,205 @@ const MaterialListPage: FC = () => {
src: url(${ nikumaru }) format('opentype');
}`}
</style>
<title>{`${ tag ? `${ tag.name } 素材集` : '素材集' } | ${ SITE_TITLE }`}</title>
<title>{`素材一覧 | ${ SITE_TITLE }`}</title>
</Helmet>
{unclassified ? (
<>
<PageTitle></PageTitle>
<div className="-mt-2 mb-4">
<PrefetchLink
to={`/materials?material_filter=${ materialFilter }`}
className="text-sm text-sky-700 underline underline-offset-2
dark:text-sky-300">
</PrefetchLink>
</div>
{unclassifiedLoading && <p>Loading...</p>}
{unclassifiedError && (
<p className="text-red-600 dark:text-red-300"></p>)}
{unclassifiedData && unclassifiedData.materials.length === 0 && (
<p></p>)}
{unclassifiedData && unclassifiedData.materials.length > 0 && (
<MaterialList materials={unclassifiedData.materials}/>)}
</>) : tagQuery ? (
<>
{tagLoading && <p>Loading...</p>}
{tagError && (
<p className="text-red-600"></p>)}
{(!tagLoading && !tagError && !tag) && (
<p></p>)}
{tag && <MaterialTagTreeView tag={tag}/>}
</>) : (
<MaterialSearchTop
tagName={tagName}
setTagName={setTagName}
materialFilter={materialFilter}
setMaterialFilter={setMaterialFilter}/>)}
<div className="space-y-5">
<div className="flex flex-wrap items-center justify-between gap-3">
<PageTitle></PageTitle>
<div className="flex flex-wrap gap-2">
<PrefetchLink
to={`/materials?tag_state=untagged&material_filter=${ materialFilter }`}
className="rounded-full border border-stone-300 bg-white px-4 py-2 text-sm
text-stone-900 hover:bg-stone-100 dark:border-stone-700
dark:bg-stone-900 dark:text-stone-100 dark:hover:bg-stone-800">
</PrefetchLink>
<PrefetchLink
to="/materials/new"
className="rounded-full border border-stone-300 bg-white px-4 py-2 text-sm
text-stone-900 hover:bg-stone-100 dark:border-stone-700
dark:bg-stone-900 dark:text-stone-100 dark:hover:bg-stone-800">
</PrefetchLink>
<a
href={`${ API_BASE_URL }/materials/download.zip?profile=legacy_drive`}
target="_blank"
rel="noopener noreferrer"
className="rounded-full border border-stone-300 bg-white px-4 py-2 text-sm
text-stone-900 hover:bg-stone-100 dark:border-stone-700
dark:bg-stone-900 dark:text-stone-100 dark:hover:bg-stone-800">
ZIP
</a>
</div>
</div>
{tagState === 'untagged' && (
<PrefetchLink
to={`/materials?material_filter=${ materialFilter }`}
className="text-sm text-sky-700 underline underline-offset-2 dark:text-sky-300">
</PrefetchLink>)}
<form
onSubmit={search}
className="max-w-3xl rounded-lg border border-stone-200 bg-white p-4
text-stone-900 dark:border-stone-700 dark:bg-stone-900
dark:text-stone-100">
<div className="space-y-3">
<FormField label="検索">
{({ invalid }) => (
<input
type="search"
value={q}
onChange={e => setQ (e.target.value)}
placeholder="タグ名 / URL / ファイル名"
className={inputClass (invalid)}/>)}
</FormField>
<FormField label="タグ状態">
{({ invalid }) => (
<select
value={tagStateInput}
onChange={e => setTagStateInput (
e.target.value as MaterialIndexTagState)}
className={inputClass (invalid)}>
<option value="all"></option>
<option value="tagged"></option>
<option value="untagged"></option>
</select>)}
</FormField>
<FormField label="メディア">
{({ invalid }) => (
<select
value={mediaKindInput}
onChange={e => setMediaKindInput (
e.target.value as MaterialIndexMediaKind)}
className={inputClass (invalid)}>
{Object.entries (MEDIA_FILTER_LABELS).map (([value, label]) => (
<option key={value} value={value}>
{label}
</option>))}
</select>)}
</FormField>
<FormField label="抑止状態">
{({ invalid }) => (
<select
value={suppressionInput}
onChange={e => setSuppressionInput (
e.target.value as MaterialIndexSuppression)}
className={inputClass (invalid)}>
<option value="active"></option>
<option value="suppressed"></option>
<option value="all"></option>
</select>)}
</FormField>
<FormField label="作成日時">
{() => (
<div className="flex flex-wrap items-center gap-2">
<DateTimeField value={createdFrom ?? undefined} onChange={setCreatedFrom}/>
<span></span>
<DateTimeField value={createdTo ?? undefined} onChange={setCreatedTo}/>
</div>)}
</FormField>
<FormField label="更新日時">
{() => (
<div className="flex flex-wrap items-center gap-2">
<DateTimeField value={updatedFrom ?? undefined} onChange={setUpdatedFrom}/>
<span></span>
<DateTimeField value={updatedTo ?? undefined} onChange={setUpdatedTo}/>
</div>)}
</FormField>
</div>
<div className="mt-4 flex flex-wrap gap-3">
<button
type="submit"
className="rounded bg-sky-600 px-4 py-2 text-white hover:bg-sky-700
dark:bg-sky-500 dark:text-stone-950 dark:hover:bg-sky-400">
</button>
</div>
</form>
<div className="flex flex-wrap items-center justify-between gap-3">
<div className="flex flex-wrap gap-2">
<button
type="button"
onClick={() => updateQuery ({ view: 'card' })}
className={`rounded-full border px-4 py-2 text-sm ${
view === 'card'
? [
'border-sky-500 bg-sky-50 text-sky-700 dark:border-sky-400',
'dark:bg-sky-950 dark:text-sky-100',
].join (' ')
: [
'border-stone-300 bg-white text-stone-900 dark:border-stone-700',
'dark:bg-stone-900 dark:text-stone-100',
].join (' ') }`}>
</button>
<button
type="button"
onClick={() => updateQuery ({ view: 'list' })}
className={`rounded-full border px-4 py-2 text-sm ${
view === 'list'
? [
'border-sky-500 bg-sky-50 text-sky-700 dark:border-sky-400',
'dark:bg-sky-950 dark:text-sky-100',
].join (' ')
: [
'border-stone-300 bg-white text-stone-900 dark:border-stone-700',
'dark:bg-stone-900 dark:text-stone-100',
].join (' ') }`}>
</button>
</div>
<div className="flex flex-wrap items-center gap-2 text-sm">
<select
value={sort}
onChange={e => updateQuery ({ sort: e.target.value, page: '1' })}
className={inputClass (false, 'w-auto')}>
{Object.entries (SORT_LABELS).map (([value, label]) => (
<option key={value} value={value}>
{label}
</option>))}
</select>
<select
value={direction}
onChange={e => updateQuery ({ direction: e.target.value, page: '1' })}
className={inputClass (false, 'w-auto')}>
<option value="desc"></option>
<option value="asc"></option>
</select>
</div>
</div>
{isLoading && <p>Loading...</p>}
{isError && (
<p className="text-red-600 dark:text-red-300"></p>)}
{(!isLoading && !isError && materials.length === 0) && (
<p></p>)}
{materials.length > 0 && (
view === 'card'
? (
<div className="grid grid-cols-[repeat(auto-fill,minmax(196px,1fr))]
justify-items-center gap-4">
{materials.map (material => (
<MaterialCard key={material.id} material={material}/>))}
</div>)
: (
<div className="space-y-3">
{materials.map (material => (
<MaterialListItem key={material.id} material={material}/>))}
</div>))}
<Pagination page={page} totalPages={totalPages}/>
</div>
</MainArea>)
}
+5
ファイルの表示
@@ -77,7 +77,12 @@ export const buildMaterial = (overrides: Partial<Material> = {}): Material => ({
file: null,
url: null,
wikiPageBody: null,
thumbnail: null,
thumbnailFallbackText: 'テストタグ',
thumbnailFallbackKind: 'tag_name',
mediaKind: 'url_only',
contentType: null,
fileByteSize: null,
fileSuppressedAt: null,
fileSuppressionReason: null,
exportPaths: {},
+46 -1
ファイルの表示
@@ -67,14 +67,59 @@ export type FetchNicoTagsOrderField = 'name' | 'created_at' | 'updated_at'
export type MaterialFilter = 'present' | 'missing' | 'any'
export type MaterialIndexDirection = 'asc' | 'desc'
export type MaterialIndexMediaKind =
| 'all'
| 'image'
| 'video'
| 'audio'
| 'file_other'
| 'url_only'
export type MaterialIndexSort =
| 'created_at'
| 'updated_at'
| 'tag_name'
| 'media_kind'
| 'file_byte_size'
| 'version_no'
| 'id'
export type MaterialIndexSuppression = 'active' | 'suppressed' | 'all'
export type MaterialIndexTagState = 'all' | 'tagged' | 'untagged'
export type MaterialIndexView = 'card' | 'list'
export type FetchMaterialsParams = {
q: string
tagState: MaterialIndexTagState
mediaKind: MaterialIndexMediaKind
suppression: MaterialIndexSuppression
createdFrom: string
createdTo: string
updatedFrom: string
updatedTo: string
sort: MaterialIndexSort
direction: MaterialIndexDirection
view: MaterialIndexView
page: number
limit: number }
export type Material = {
id: number
versionNo: number
tag: Tag
tag: Tag | null
file: string | null
url: string | null
wikiPageBody?: string | null
thumbnail: string | null
thumbnailFallbackText: string | null
thumbnailFallbackKind: 'tag_name' | 'created_at'
mediaKind: 'image' | 'video' | 'audio' | 'file_other' | 'url_only' | 'suppressed'
contentType: string | null
fileByteSize: number | null
fileSuppressedAt: string | null
fileSuppressionReason: string | null
exportPaths: Record<string, string>