このコミットが含まれているのは:
2026-10-26 12:19:43 +09:00
コミット 3e8f209542
31個のファイルの変更、1676行の追加、394行の削除
+8
ファイルの表示
@@ -202,6 +202,14 @@ export const pageRoutes = (
handle: { preload: CountsResourcePage.preload } },
{ path: 'counts/tags', element: <CountsResourcePage resource="tags"/>,
handle: { preload: CountsResourcePage.preload } },
{ path: 'counts/nico_tags', element: <CountsResourcePage resource="nico_tags"/>,
handle: { preload: CountsResourcePage.preload } },
{ path: 'counts/tag_descriptions', element: <CountsResourcePage resource="tag_descriptions"/>,
handle: { preload: CountsResourcePage.preload } },
{ path: 'counts/tag_groups', element: <CountsResourcePage resource="tag_groups"/>,
handle: { preload: CountsResourcePage.preload } },
{ path: 'counts/materials', element: <CountsResourcePage resource="materials"/>,
handle: { preload: CountsResourcePage.preload } },
{ path: 'more', element: <MorePage/>,
handle: { preload: MorePage.preload, sitemap: ['static'] } },
{ path: '*', element: <NotFound/>, handle: { notFound: true } }]
+12 -8
ファイルの表示
@@ -8,13 +8,13 @@ import type { ComponentPropsWithoutRef, FC, FocusEvent } from 'react'
const pad = (n: number): string => n.toString ().padStart (2, '0')
const toDateTimeLocalValue = (value: Date) => {
const toDateTimeLocalValue = (value: Date, seconds = false) => {
const y = value.getFullYear ()
const m = pad (value.getMonth () + 1)
const day = pad (value.getDate ())
const h = pad (value.getHours ())
const min = pad (value.getMinutes ())
return `${ y }-${ m }-${ day }T${ h }:${ min }`
return `${ y }-${ m }-${ day }T${ h }:${ min }${seconds ? `:${pad (value.getSeconds ())}` : ''}`
}
@@ -37,15 +37,17 @@ type Props = Omit<ComponentPropsWithoutRef<'input'>, 'onChange'> & {
onChange?: (isoUTC: string | null) => void
className?: string
onBlur?: (ev: FocusEvent<HTMLInputElement>) => void
invalid?: boolean }
invalid?: boolean
precision?: 'minute' | 'second' }
const DateTimeField: FC<Props> = ({ value, onChange, className, onBlur, invalid, ...rest }) => {
const DateTimeField: FC<Props> = props => {
const { value, onChange, className, onBlur, invalid, precision = 'minute', ...rest } = props
const [local, setLocal] = useState ('')
useEffect (() => {
setLocal (value ? toDateTimeLocalValue (new Date (value)) : '')
}, [value])
setLocal (value ? toDateTimeLocalValue (new Date (value), precision === 'second') : '')
}, [value, precision])
return (
<input
@@ -61,13 +63,15 @@ const DateTimeField: FC<Props> = ({ value, onChange, className, onBlur, invalid,
'focus:ring-2 focus:ring-blue-200']),
className)}
type="datetime-local"
step={60}
step={precision === 'second' ? 1 : 60}
value={local}
aria-invalid={invalid}
onChange={ev => {
const v = ev.target.value
setLocal (v)
onChange?.(v ? toMinutePrecisionIsoUtc (v) : null)
const iso = v ? (precision === 'second'
? new Date (v).toISOString () : toMinutePrecisionIsoUtc (v)) : null
onChange?.(iso)
}}
onBlur={onBlur}/>)
}
+35
ファイルの表示
@@ -0,0 +1,35 @@
import { useId, useRef } from 'react'
import { CircleHelp } from 'lucide-react'
import type { ReactNode } from 'react'
const HelpPopover = ({ label, children }: {
label: { text: string; language: string }; children: ReactNode },
) => {
const id = useId ()
const trigger = useRef<HTMLButtonElement> (null)
const panel = useRef<HTMLDivElement> (null)
return <>
<button ref={trigger} type="button" popoverTarget={id} aria-label={label.text}
lang={label.language} className="inline-flex align-middle"
onClick={() => {
const rect = trigger.current?.getBoundingClientRect ()
if (panel.current != null && rect != null)
{
panel.current.style.top = `${rect.bottom + 4}px`
panel.current.style.left = `${Math.min (rect.left, window.innerWidth - 288)}px`
}
}}><CircleHelp size={14}/></button>
<div ref={panel} id={id} popover="auto" tabIndex={-1}
role="dialog" aria-label={label.text} lang={label.language}
onToggle={event => {
if (event.newState === 'open') panel.current?.focus ()
}} className="fixed m-0 w-72 max-w-[90vw] rounded border bg-white p-3
text-sm text-slate-900 shadow-lg dark:border-slate-600 dark:bg-slate-900
dark:text-slate-100">{children}</div>
</>
}
export default HelpPopover
+7 -4
ファイルの表示
@@ -12,6 +12,7 @@ import type { Tag } from '@/types'
type Props = {
includeNico?: boolean
includeUnused?: boolean
describedBy?: string
invalid?: boolean
value: string
@@ -20,6 +21,7 @@ type Props = {
const TagInput: FC<Props> = ({
includeNico = false,
includeUnused = false,
describedBy,
invalid,
value,
@@ -57,11 +59,11 @@ const TagInput: FC<Props> = ({
{
const tags = await apiGet<Tag[]> ('/tags/autocomplete', {
locale, signal: controller.signal,
params: { q: request.query, nico: includeNico ? '1' : '0' } })
params: { q: request.query.replace (/^not:/i, ''), nico: includeNico ? '1' : '0' } })
if (active)
{
setResult ({ locale, includeNico, request,
tags: tags.filter (tag => tag.postCount > 0) })
tags: includeUnused ? tags : tags.filter (tag => tag.postCount > 0) })
}
}
catch
@@ -74,7 +76,7 @@ const TagInput: FC<Props> = ({
active = false
controller.abort ()
}
}, [request, locale, includeNico])
}, [request, locale, includeNico, includeUnused])
useEffect (() => {
setActiveIndex (-1)
@@ -85,7 +87,8 @@ const TagInput: FC<Props> = ({
// TODO: TagSearch からのコピペのため,共通化を考へる.
const handleTagSelect = (tag: Tag) => {
const parts = value?.split (' ')
parts[parts.length - 1] = tag.name
const negative = /^not:/i.test (parts[parts.length - 1])
parts[parts.length - 1] = `${negative ? 'not:' : ''}${tag.name}`
setValue (parts.join (' ') + ' ')
setRequest ({ query: '' })
setActiveIndex (-1)
+90
ファイルの表示
@@ -0,0 +1,90 @@
import { useState } from 'react'
import DateTimeField from '@/components/common/DateTimeField'
import { Button } from '@/components/ui/button'
import { countsFieldLabel, countsFilterFields, countsOperators, readCountsJSON }
from '@/lib/countsDefinitions'
import useDialogue from '@/lib/dialogues/useDialogue'
import { inputClass } from '@/lib/utils'
import { useUITranslation } from '@/lib/useUITranslation'
import type { CountsResource } from '@/lib/counts'
import type { CountsCondition } from '@/lib/countsDefinitions'
const ConditionEditor = ({ resource, initial, save }: {
resource: CountsResource; initial?: CountsCondition
save: (condition: CountsCondition) => void },
) => {
const { label, message } = useUITranslation ('counts')
const fields = countsFilterFields (resource)
const [field, setField] = useState (initial?.field ?? 'resource_id')
const [operator, setOperator] = useState (initial?.operator ?? 'eq')
return <div className="space-y-2">
<select value={field} aria-label={message ('field').text} className={inputClass ()}
onChange={event => { setField (event.target.value); setOperator ('eq') }}>
{Object.keys (fields).filter (key => fields[key] !== 'json').map (key => (
<option key={key} value={key}>{message (countsFieldLabel (key)).text}</option>))}
</select>
<select value={operator} aria-label={message ('operator').text} className={inputClass ()}
onChange={event => setOperator (event.target.value)}>
{countsOperators[fields[field]].map (key => <option key={key} value={key}>
{message (`operators.${key}`).text}</option>)}
</select>
<Button type="button" onClick={() => save ({ ...initial, field, operator })}>
{label (initial == null ? 'add' : 'shared:actions.edit')}</Button>
</div>
}
const CountsAdditionalConditions = ({ resource, params, update }: {
resource: CountsResource; params: URLSearchParams
update: (key: string, value: string) => void },
) => {
const { label, message } = useUITranslation ('counts')
const dialogue = useDialogue ()
const conditions = readCountsJSON<CountsCondition[]> (params, 'conditions', [])
const write = (next: CountsCondition[]) => update ('conditions', JSON.stringify (next))
const edit = (index?: number) => {
void dialogue.form ({ title: label ('additionalConditions'), body: controls => (
<ConditionEditor resource={resource} initial={index == null ? undefined : conditions[index]}
save={condition => {
write (index == null ? [...conditions, condition]
: conditions.map ((item, position) => position === index ? condition : item))
controls.close ()
}}/>) })
}
const patch = (index: number, change: Partial<CountsCondition>) => write (
conditions.map ((item, position) => position === index ? { ...item, ...change } : item))
return <fieldset className="space-y-1">
<legend className="flex items-center gap-2">{label ('additionalConditions')}
<Button type="button" variant="outline" size="sm" onClick={() => edit ()}>
{label ('add')}</Button></legend>
{conditions.map ((condition, index) => {
const datetime = countsFilterFields (resource)[condition.field] === 'datetime'
return <div key={index} className="flex flex-wrap items-center gap-1">
<button type="button" onClick={() => edit (index)}>
{label (countsFieldLabel (condition.field))} · {label (`operators.${condition.operator}`)}
</button>
{(condition.operator === 'range' ? ['value', 'end'] as const : ['value'] as const)
.map (key => datetime ? <DateTimeField precision="second" key={key}
value={condition[key] ?? ''} disabled={condition.blank}
aria-label={message (key === 'end' ? 'through' : 'value').text}
onChange={value => patch (index, { [key]: value ?? '' })}/> : (
<input key={key} value={condition[key] ?? ''} disabled={condition.blank}
className={inputClass (false, 'w-36 py-1')}
aria-label={message ('value').text}
onChange={event => patch (index, { [key]: event.target.value })}/>))}
<label className="inline-flex items-center gap-1">
<input type="checkbox" checked={condition.blank ?? false}
onChange={event => patch (index, { blank: event.target.checked })}/>
{label ('blank')}</label>
<button type="button" aria-label={message ('remove').text}
onClick={() => write (conditions.filter ((_, position) => index !== position))}>×</button>
</div>
})}
</fieldset>
}
export default CountsAdditionalConditions
+125
ファイルの表示
@@ -0,0 +1,125 @@
import { DndContext, MouseSensor, TouchSensor, closestCenter,
useDraggable, useDroppable, useSensor, useSensors } from '@dnd-kit/core'
import { countsAxisFields, countsFilterFields, countsGrains, readCountsJSON }
from '@/lib/countsDefinitions'
import { cn, inputClass } from '@/lib/utils'
import { useUITranslation } from '@/lib/useUITranslation'
import type { ReactNode } from 'react'
import type { CountsResource } from '@/lib/counts'
import type { CountsAxis } from '@/lib/countsDefinitions'
const AxisItem = ({ id, name, children }: { id: string; name: string; children: ReactNode }) => {
const drag = useDraggable ({ id })
const drop = useDroppable ({ id })
return <div ref={drop.setNodeRef} className={cn (
'flex flex-wrap items-center gap-1 rounded border p-1 dark:border-slate-600',
drop.isOver && 'outline outline-1 outline-blue-500 dark:outline-blue-400')}>
<button ref={drag.setNodeRef} type="button" {...drag.listeners} {...drag.attributes}
className="cursor-grab touch-none" aria-label={name}>
<span aria-hidden>⠿</span>
</button>{children}
</div>
}
const AxisZone = ({ id, children }: { id: string; children: ReactNode }) => {
const drop = useDroppable ({ id })
return <div ref={drop.setNodeRef} className={cn (
'flex min-h-12 flex-wrap items-start gap-1 rounded border p-1 dark:border-slate-600',
drop.isOver && 'outline outline-1 outline-blue-500 dark:outline-blue-400')}>
{children}
</div>
}
const CountsAxes = ({ resource, params, update }: {
resource: CountsResource; params: URLSearchParams
update: (key: string, value: string) => void },
) => {
const { label, message } = useUITranslation ('counts')
const history = params.get ('definition') === 'history'
const available = countsAxisFields (resource, history)
const rows = readCountsJSON<CountsAxis[]> (params, 'rows', [])
const cols = readCountsJSON<CountsAxis[]> (params, 'cols', [])
const groups = { rows, cols }
const sensors = useSensors (
useSensor (MouseSensor, { activationConstraint: { distance: 4 } }),
useSensor (TouchSensor, { activationConstraint: { delay: 350, tolerance: 8 } }))
const place = (field: string, target: string, position?: string) => {
for (const key of ['rows', 'cols'] as const)
{
const existing = [...rows, ...cols].find (axis => axis.field === field)
const next = groups[key].filter (axis => axis.field !== field)
if (target === key)
{
const index = position == null ? next.length : next.findIndex (
axis => axis.field === position)
next.splice (index < 0 ? next.length : index, 0, existing ?? {
field, ...(countsFilterFields (resource)[field] === 'datetime'
? { grain: 'month' } : { }) })
}
update (key, JSON.stringify (next))
}
}
return <DndContext sensors={sensors} collisionDetection={closestCenter}
accessibility={{ announcements: {
onDragStart: () => undefined, onDragOver: () => undefined,
onDragMove: () => undefined, onDragEnd: () => undefined,
onDragCancel: () => undefined },
screenReaderInstructions: { draggable: message ('axis').text } }}
onDragEnd={({ active, over }) => {
if (over == null) return
const [, field] = String (active.id).split ('/')
const [zone, position] = String (over.id).split ('/')
place (field, zone, position)
}}>
<div className="space-y-2">
<fieldset><legend>{label ('axisItems')}</legend><AxisZone id="available">
{available.filter (field => ![...rows, ...cols].some (
axis => axis.field === field.key)).map (field => (
<AxisItem key={field.key} id={`available/${field.key}`} name={message (field.label).text}>
{label (field.label)}
{(['rows', 'cols'] as const).map (target => <button key={target} type="button"
aria-label={message ('axisPlace', {
field: message (field.label).text, target: message (target).text }).text}
onClick={() => place (field.key, target)}>{label (target)}</button>)}
</AxisItem>))}
</AxisZone></fieldset>
{(['rows', 'cols'] as const).map (zone => <fieldset key={zone}>
<legend>{label (zone)}</legend><AxisZone id={zone}>
{groups[zone].map ((axis, index) => {
const field = available.find (field => field.key === axis.field)
return <AxisItem key={axis.field} id={`${zone}/${axis.field}`}
name={field == null ? message ('axis').text : message (field.label).text}>
{field == null ? null : label (field.label)}
{countsFilterFields (resource)[axis.field] === 'datetime' && <select
className={inputClass (false, 'w-auto py-0')}
value={axis.grain ?? 'month'} aria-label={message ('grain').text}
onChange={event => update (zone, JSON.stringify (groups[zone].map (
item => item === axis ? { ...item, grain: event.target.value } : item)))}>
{countsGrains.map (grain => <option key={grain} value={grain}>
{message (`grains.${grain}`).text}</option>)}
</select>}
<button type="button" aria-label={message ('reorder', {
column: field == null ? '' : message (field.label).text }).text}
disabled={index === 0}
onClick={() => place (axis.field, zone, groups[zone][index - 1]?.field)}>↑</button>
<button type="button" onClick={() => place (
axis.field, zone === 'rows' ? 'cols' : 'rows')}>
{label (zone === 'rows' ? 'cols' : 'rows')}</button>
<button type="button" aria-label={message ('remove').text}
onClick={() => place (axis.field, 'available')}>×</button>
</AxisItem>
})}
</AxisZone>
</fieldset>)}
</div>
</DndContext>
}
export default CountsAxes
+95 -177
ファイルの表示
@@ -1,14 +1,15 @@
import { useEffect, useId, useState } from 'react'
import CountsAdditionalConditions from '@/components/counts/CountsAdditionalConditions'
import CountsAxes from '@/components/counts/CountsAxes'
import CountsFieldTree from '@/components/counts/CountsFieldTree'
import DateTimeField from '@/components/common/DateTimeField'
import FormField from '@/components/common/FormField'
import HelpPopover from '@/components/common/HelpPopover'
import TagInput from '@/components/common/TagInput'
import { Button } from '@/components/ui/button'
import { isCountsState, normaliseCountsParams } from '@/lib/counts'
import { countsSummaryFields } from '@/lib/countsState'
import { fetchTagByName } from '@/lib/tags'
import { normaliseCountsParams } from '@/lib/counts'
import { inputClass } from '@/lib/utils'
import { useLocale } from '@/lib/useLocale'
import { useUITranslation } from '@/lib/useUITranslation'
import type { ReactNode } from 'react'
@@ -18,17 +19,13 @@ import type { CountsResource } from '@/lib/counts'
const CountsControls = (
{ resource, applied, open, setOpen, execute, displayJSON, reorder, actions }: {
resource: CountsResource
applied: URLSearchParams
open: boolean
setOpen: (open: boolean) => void
execute: (params: URLSearchParams) => void
displayJSON: (enabled: boolean) => void
reorder: (value: string) => void
actions?: ReactNode },
resource: CountsResource; applied: URLSearchParams; open: boolean
setOpen: (open: boolean) => void
execute: (params: URLSearchParams) => void
displayJSON: (enabled: boolean) => void
reorder: (value: string) => void; actions?: ReactNode },
) => {
const { label, message } = useUITranslation ('counts')
const locale = useLocale ()
const id = useId ()
const [draft, setDraft] = useState (() => new URLSearchParams (applied))
const order = applied.get ('order')
@@ -38,175 +35,96 @@ const CountsControls = (
const next = new URLSearchParams (previous)
for (const [key, value] of Object.entries ({ order, nested_json: nestedJSON }))
{
if (value == null) next.delete (key)
else next.set (key, value)
if (value == null) next.delete (key)
else next.set (key, value)
}
return next
})
}, [order, nestedJSON])
const [error, setError] = useState (false)
const [pending, setPending] = useState (false)
const mode = draft.get ('mode') ?? 'summary'
const state = isCountsState (draft)
const axes = (state && resource === 'posts') ? ['tags', 'month', 'user'] : ['month', 'user']
const update = (key: string, value: string) => {
setDraft (previous => {
const next = new URLSearchParams (previous)
if (['mode', 'axis', 'basis'].includes (key)) next.delete ('sort')
if (key === 'axis' || key === 'basis') next.delete ('summary_columns')
if (key === 'basis' && value === 'history' && next.get ('axis') === 'tags')
next.set ('axis', 'month')
if (value || ['columns', 'children', 'summary_columns'].includes (key))
next.set (key, value)
else next.delete (key)
return next
})
}
const submit = async () => {
setError (false)
setPending (true)
try
{
const next = new URLSearchParams (draft)
for (const key of resource === 'posts' ? ['tag'] : ['resource_id'])
{
const value = next.get (key)?.trim () ?? ''
if (value && !/^[1-9][0-9]*$/.test (value))
{
if (state && next.get ('kind') === 'external') throw new Error ()
const tag = await fetchTagByName (value, locale)
if (tag == null)
throw new Error ()
next.set (key, String (tag.id))
}
}
next.delete ('page')
execute (normaliseCountsParams (resource, next))
}
catch
{
setError (true)
}
finally
{
setPending (false)
}
}
return (
<form className="shrink-0" onSubmit={event => {
event.preventDefault ()
void submit ()
}}>
<div className="flex flex-wrap items-center gap-2 border-b pb-2 dark:border-slate-700">
<Button type="submit" size="sm" disabled={pending}>{label ('run')}</Button>
<Button type="button" size="sm" variant="outline" aria-expanded={open}
aria-controls={id} onClick={() => setOpen (!open)}>
{label ('conditions')}<span aria-hidden>{open ? '▴' : '▾'}</span>
</Button>
<select className={inputClass (false, 'w-auto py-1')}
aria-label={message ('mode').text} lang={message ('mode').language}
value={mode} onChange={event => update ('mode', event.target.value)}>
{['summary', 'details'].map (value => (
<option key={value} value={value} lang={message (value).language}>
{message (value).text}</option>))}
</select>
{actions}
</div>
{error && <p role="alert">{label ('shared:messages.checkInputModern')}</p>}
<div id={id} hidden={!open}
className="max-h-[40dvh] overflow-y-auto overscroll-contain border-b py-2
dark:border-slate-700 md:max-h-[45dvh]">
<div className="grid gap-4 md:grid-cols-2">
<fieldset className="min-w-0" data-counts-output>
<legend className="mb-2 font-semibold">{label ('output')}</legend>
<label className="mb-2 flex items-center gap-1">
<input type="checkbox" checked={draft.get ('nested_json') === '1'}
onChange={event => {
update ('nested_json', event.target.checked ? '1' : '0')
displayJSON (event.target.checked)
}}/>
{label ('nested.asJSON')}
</label>
<FormField label={label ('measure')}>
{() => <select value={state ? 'state' : 'history'}
className={inputClass (false, 'w-auto py-1')}
aria-label={message ('measure').text} lang={message ('measure').language}
onChange={event => update ('basis', event.target.value)}>
<option value="state" lang={message (`state.totals.${resource}`).language}>
{message (`state.totals.${resource}`).text}</option>
<option value="history" lang={message ('metric').language}>
{message ('metric').text}</option>
</select>}
</FormField>
{mode === 'summary' && <label className="my-2 flex flex-wrap items-center gap-2">
{label ('axis')}
<select className={inputClass (false, 'w-auto py-1')}
value={draft.get ('axis')
?? ((state && resource === 'posts') ? 'tags' : 'month')}
aria-label={message ('axis').text} lang={message ('axis').language}
onChange={event => update ('axis', event.target.value)}>
{axes.map (axis => <option key={axis} value={axis}
lang={message (`axes.${axis}`).language}>
{message (`axes.${axis}`).text}</option>)}
</select>
</label>}
<CountsFieldTree resource={resource} params={draft}
fields={mode === 'summary' ? countsSummaryFields (resource, draft) : undefined}
selectionKey={mode === 'summary' ? 'summary_columns' : 'columns'}
parent={mode === 'summary' ? 'summary' : ''} update={(key, value) => {
update (key, value)
if (key === 'order') reorder (value)
}}/>
</fieldset>
<fieldset className="min-w-0 space-y-2" data-counts-filters>
<legend className="mb-2 font-semibold">{label ('filters')}</legend>
<FormField label={label ('state.at')}>
{() => <DateTimeField value={draft.get ('at') ?? ''}
aria-label={message ('state.at').text} lang={message ('state.at').language}
onChange={value => update ('at', value ?? '')}/>}
</FormField>
{!state && <label className="flex items-center gap-1">
<input type="checkbox" checked={draft.get ('latest') !== '0'}
onChange={event => update ('latest', event.target.checked ? '1' : '0')}/>
{label ('latestOnly')}
</label>}
{state && resource === 'posts' && <FormField label={label ('columns.kind')}>
{() => <select value={draft.get ('kind') ?? 'internal'}
className={inputClass (false, 'w-auto py-1')}
aria-label={message ('columns.kind').text} lang={message ('columns.kind').language}
onChange={event => update ('kind', event.target.value)}>
{['internal', 'external'].map (kind => <option key={kind} value={kind}
lang={message (`kinds.${kind}`).language}>
{message (`kinds.${kind}`).text}</option>)}
</select>}
</FormField>}
<div className="grid gap-2 md:grid-cols-2">
{['from', 'before'].map (key => (
<FormField key={key} label={label (`fields.${key}`)}>
{() => <DateTimeField value={draft.get (key) ?? ''}
aria-label={message (`fields.${key}`).text}
lang={message (`fields.${key}`).language}
onChange={value => update (key, value ?? '')}/>}
</FormField>))}
</div>
<div className="grid gap-2 md:grid-cols-2">
{[['resource_id', resource === 'posts' ? 'post' : 'tag'], ['user_id', 'actor'],
...(resource === 'posts' ? [['tag', 'tag']] : []), ['limit', 'limit']]
.map (([key, field]) => (
<FormField key={key} label={label (`fields.${field}`)}>
{() => <input aria-label={message (`fields.${field}`).text}
lang={message (`fields.${field}`).language}
type={key === 'limit' ? 'number' : 'text'} min={1} max={100}
value={draft.get (key) ?? (key === 'limit' ? '20' : '')}
onChange={event => update (key, event.target.value)}
className={inputClass (false, 'py-1')}/>}
</FormField>))}
</div>
</fieldset>
</div>
</div>
</form>)
const history = draft.get ('definition') === 'history'
const update = (key: string, value: string) => setDraft (previous => {
const next = new URLSearchParams (previous)
if (['mode', 'rows', 'cols'].includes (key)) next.delete ('sort')
next.set (key, value)
return next
})
return <form className="shrink-0" onSubmit={event => {
event.preventDefault ()
const next = new URLSearchParams (draft)
next.delete ('page')
next.delete ('execution_at')
execute (normaliseCountsParams (resource, next))
}}>
<div className="flex flex-wrap items-center gap-2 border-b pb-1 dark:border-slate-700">
{history ? <>
{['from', 'through'].map (key => <label key={key}
className="flex flex-wrap items-center gap-1 text-sm">
{label (key)}<DateTimeField precision="second" value={draft.get (key) ?? ''}
aria-label={message (key).text} onChange={value => update (key, value ?? '')}/>
</label>)}
</> : <label className="flex flex-wrap items-center gap-1 text-sm">
{label ('referenceAt')}<HelpPopover label={message ('referenceAt')}>
{label ('referenceHelp')}</HelpPopover>
<DateTimeField precision="second" value={draft.get ('at') ?? ''}
aria-label={message ('referenceAt').text}
onChange={value => update ('at', value ?? '')}/>
</label>}
</div>
<div className="flex flex-wrap items-center gap-2 border-b py-1 dark:border-slate-700">
<Button type="submit" size="sm">{label ('run')}</Button>
<Button type="button" size="sm" variant="outline" aria-expanded={open}
aria-controls={id} onClick={() => setOpen (!open)}>
{label ('conditions')}<span aria-hidden>{open ? '▴' : '▾'}</span>
</Button>
<select className={inputClass (false, 'w-auto py-1')}
aria-label={message ('mode').text} lang={message ('mode').language}
value={mode} onChange={event => update ('mode', event.target.value)}>
{['summary', 'details'].map (value => <option key={value} value={value}>
{message (value).text}</option>)}
</select>{actions}
</div>
<div id={id} hidden={!open} className="max-h-[35dvh] overflow-y-auto overscroll-contain
border-b py-2 dark:border-slate-700 md:max-h-[40dvh]">
<div className="grid gap-3 md:grid-cols-2">
<fieldset className="min-w-0" data-counts-output>
{mode === 'summary' ? <CountsAxes resource={resource} params={draft} update={update}/>
: <>
<legend className="mb-1 font-semibold">{label ('output')}</legend>
<label className="mb-1 flex items-center gap-1">
<input type="checkbox" checked={draft.get ('nested_json') === '1'}
onChange={event => {
update ('nested_json', event.target.checked ? '1' : '0')
displayJSON (event.target.checked)
}}/>{label ('nested.asJSON')}</label>
<CountsFieldTree resource={resource} params={draft} update={(key, value) => {
update (key, value)
if (key === 'order') reorder (value)
}}/>
</>}
</fieldset>
<fieldset className="min-w-0 space-y-2" data-counts-filters>
<legend className="font-semibold">{label ('filters')}</legend>
<div className="flex flex-wrap gap-2">
{['resource_id', 'user_id', 'limit'].map (key => <FormField key={key}
label={label (key === 'resource_id' ? 'columns.resourceId'
: (key === 'user_id' ? 'fields.actor' : 'fields.limit'))}>
{() => <input value={draft.get (key) ?? (key === 'limit' ? '20' : '')}
aria-label={message (key === 'resource_id' ? 'columns.resourceId'
: (key === 'user_id' ? 'fields.actor' : 'fields.limit')).text}
className={inputClass (false, 'w-28 py-1')}
onChange={event => update (key, event.target.value)}/>}
</FormField>)}
</div>
{resource === 'posts' && <FormField label={label ('columns.tags')}>
{() => <TagInput includeNico includeUnused value={draft.get ('tags') ?? ''}
setValue={value => update ('tags', value)}/>}
</FormField>}
<CountsAdditionalConditions resource={resource} params={draft} update={update}/>
</fieldset>
</div>
</div>
</form>
}
-2
ファイルの表示
@@ -124,7 +124,6 @@ const CountsFieldTree = (
params: URLSearchParams
update: (key: string, value: string) => void },
) => {
const { label } = useUITranslation ('counts')
const fields = suppliedFields ?? fieldsForCounts (resource)
const roots = suppliedFields == null ? selectedCountColumns (resource, params)
: selectedCountFields (fields, params, selectionKey, parent).map (field => field.key)
@@ -151,7 +150,6 @@ const CountsFieldTree = (
<>
<FieldGroup fields={fields} path={parent} params={params} enabled selected={selected}
select={select} update={update}/>
{suppliedFields == null && <p className="mt-2 text-xs">{label ('nested.selection')}</p>}
</>)
}
+4
ファイルの表示
@@ -34,6 +34,10 @@ const CountsNestedTable = (
const scalar = (row: CountRecord, field: string) => {
const value = row[field]
if (value == null) return null
if (field === 'tagId' || field === 'tagGroupId')
return <PrefetchLink to={field === 'tagId'
? `/tags/${encodeURIComponent (String (value))}` : '/wiki'}>
{String (value)}</PrefetchLink>
if (field === 'id')
{
if (row.kind === 'external') return String (value)
+11 -5
ファイルの表示
@@ -7,12 +7,12 @@ import CountsSelectableTable from '@/components/counts/CountsSelectableTable'
import PostThumbnailPreview from '@/components/posts/PostThumbnailPreview'
import { changeCountSort, countColumns, countsRequestParams, fieldsForCounts,
readCountSort, selectedCountColumns, writeCountSort } from '@/lib/counts'
import { countsCellCopy, countsCellText, countsImageURL } from '@/lib/countsDisplay'
import { countsCellCopy, countsCellText, countsImageURL, countsNestedRows } from '@/lib/countsDisplay'
import useDialogue from '@/lib/dialogues/useDialogue'
import { useLocale } from '@/lib/useLocale'
import { useUITranslation } from '@/lib/useUITranslation'
import type { CountColumn, CountRecord, CountsResource,
import type { CountColumn, CountsResource,
CountsResult, CountsVersion } from '@/lib/counts'
@@ -34,17 +34,23 @@ const CountsResults = (
update ('sort', writeCountSort (changeCountSort (sorts, key, additive)))
const cell = (row: CountsVersion, column: CountColumn) => {
const field = fields.find (field => field.key === column)!
const value = countsCellText (row, column, locale)
const value = countsCellText (row, column, locale, params)
if (field.children != null)
{
return <CountsNestedTable rows={row[column as keyof CountsVersion] as CountRecord[] ?? []}
return <CountsNestedTable rows={countsNestedRows (row, column)}
fields={field.children} path={column} resource={resource}
title={message (field.label)} params={params} update={update}/>
}
switch (column)
{
case 'resource_id':
return <PrefetchLink to={`/${resource}/${encodeURIComponent (row.resourceId)}`}>
if (resource === 'nico_tags') return <PrefetchLink to="/nico/tags">
{row.resourceId}</PrefetchLink>
if (resource === 'tag_groups') return <PrefetchLink
to={`/wiki/${encodeURIComponent (`タググループ:${row.name ?? ''}`)}`}>
{row.resourceId}</PrefetchLink>
return <PrefetchLink to={`/${resource === 'tag_descriptions' ? 'tags' : resource}/${
encodeURIComponent (row.resourceId)}`}>
{row.resourceId}</PrefetchLink>
case 'thumbnail':
{
+82 -46
ファイルの表示
@@ -1,62 +1,98 @@
import LocalisedText from '@/components/LocalisedText'
import PrefetchLink from '@/components/PrefetchLink'
import CountsSelectableTable from '@/components/counts/CountsSelectableTable'
import CountsSortHeader from '@/components/counts/CountsSortHeader'
import { changeCountSort, countsRequestParams, readCountSort, writeCountSort } from '@/lib/counts'
import { countsSummaryCell, countsSummaryDrill, countsSummaryRows,
selectedCountsSummaryFields } from '@/lib/countsState'
import { useLocale } from '@/lib/useLocale'
import { countsFieldLabel, readCountsJSON } from '@/lib/countsDefinitions'
import { useUITranslation } from '@/lib/useUITranslation'
import type { CountsResource, CountsResult } from '@/lib/counts'
import type { CountsAxis } from '@/lib/countsDefinitions'
const CountsSummaryResults = (
{ resource, data, params, pending, update }: {
resource: CountsResource
data: CountsResult
params: URLSearchParams
pending: boolean
update: (key: string, value: string) => void },
resource: CountsResource; data: CountsResult; params: URLSearchParams
pending: boolean; update: (key: string, value: string) => void },
) => {
const locale = useLocale ()
const { label, message } = useUITranslation ('counts')
const fields = selectedCountsSummaryFields (resource, params)
const rows = countsSummaryRows (data)
const sorts = readCountSort (params.get ('sort') ?? (
params.get ('axis') === 'tags' ? 'count:desc' : 'group:asc'))
return (
<div className="min-h-0 flex-1 overflow-auto" data-counts-results aria-busy={pending}>
{fields.length === 0 ? <p>{label ('nested.noColumns')}</p> : (
<CountsSelectableTable family={`summary_${params.get ('axis')}`}
columns={fields.map (field => field.key)}
identity={`${countsRequestParams (params)}:${fields.map (field => field.key)}`}
className="text-left text-sm">
<thead className="sticky top-0 z-20"><tr>
{fields.map (field => (
<CountsSortHeader key={field.key} field={field.key}
label={message (field.label)}
sorts={sorts} change={(key, additive) => update (
'sort', writeCountSort (changeCountSort (sorts, key, additive)))}/>))}
</tr></thead>
<tbody>{rows.map (row => (
<tr key={String (row.key)}>
{fields.map (field => {
const value = countsSummaryCell (row, field.key, locale)
const content = value.language == null ? value.text : (
<LocalisedText language={value.language}>{value.text}</LocalisedText>)
return <td key={field.key} data-counts-copy={value.text}
className="break-words border-b px-2 py-1 dark:border-slate-700">
{(['count', 'group'].includes (field.key) && row.count != null)
? <PrefetchLink to={countsSummaryDrill (resource, params, row)}>
{content}</PrefetchLink>
: content}
</td>
})}
</tr>))}</tbody>
</CountsSelectableTable>)}
{rows.length === 0 && <p className="p-2">{label ('empty')}</p>}
</div>)
const rows = data.rows ?? []
const cols = data.cols ?? []
const axes = [...rows, ...cols]
const cells = data.cells ?? []
const rowKeys = [...new Set (cells.map (cell => JSON.stringify (cell.values.slice (0, rows.length))))]
const columnKeys = data.columnValues?.map (values => JSON.stringify (values))
?? [...new Set (cells.map (cell => JSON.stringify (cell.values.slice (rows.length))))]
if (cols.length === 0 && columnKeys.length === 0) columnKeys.push ('[]')
const sorts = readCountSort (params.get ('sort'))
const display = (value: string | number | null, axis: CountsAxis, index: number): string => {
if (value == null) return ''
const logical = data.axisLabels?.[`a${index}`]?.[String (value)]
if (logical != null) return logical
if (['tags', 'user', 'language_code', 'source_language_code'].includes (axis.field))
return message ('notRegistered').text
if (axis.field === 'changed_field') return message (countsFieldLabel (String (value))).text
if (axis.field === 'event_type') return message (`events.${value}`).text
if (axis.field === 'category' || axis.field === 'tag_category')
return message (`common:categories.${value}`).text
return String (value)
}
const drill = (values: (string | number | null)[]) => {
const next = new URLSearchParams (params)
const existing = readCountsJSON<unknown[]> (params, 'drill', [])
next.set ('drill', JSON.stringify ([...existing,
...axes.map ((axis, index) => ({ ...axis, value: values[index] }))]))
next.set ('mode', 'details')
next.delete ('sort')
next.delete ('page')
return `/counts/${resource}?${next}`
}
const keys = [...rows.map ((_, index) => `a${index}`),
...columnKeys.map ((_, index) => `cell${index}`)]
return <div className="min-h-0 flex-1 overflow-auto" data-counts-results aria-busy={pending}>
<CountsSelectableTable family={`pivot_${resource}`} columns={keys}
identity={`${countsRequestParams (params)}:${keys}`} className="text-left text-sm">
<thead className="sticky top-0 z-20"><tr>
{rows.map ((axis, index) => <CountsSortHeader key={axis.field} field={`a${index}`}
label={message (countsFieldLabel (axis.field))} sorts={sorts}
change={(key, additive) => update ('sort', writeCountSort (
changeCountSort (sorts, key, additive)))}/>)}
{columnKeys.map ((key, index) => {
const values = JSON.parse (key) as (string | number | null)[]
const name = values.map ((value, position) =>
`${message (countsFieldLabel (cols[position].field)).text}: ${
display (value, cols[position], rows.length + position)}`).join (' / ')
const sortKey = cols.length === 0 ? 'count' : `measure_${[
...new TextEncoder ().encode (key)].map (byte =>
byte.toString (16).padStart (2, '0')).join ('')}`
return <CountsSortHeader key={key} field={`cell${index}`}
label={{ text: name || message ('count').text, language: message ('count').language }}
sorts={sorts.map (sort => sort.key === sortKey
? { ...sort, key: `cell${index}` } : sort)}
change={(_, additive) => update ('sort', writeCountSort (
changeCountSort (sorts, sortKey, additive)))}/>
})}
</tr></thead>
<tbody>{rowKeys.map (rowKey => {
const rowValues = JSON.parse (rowKey) as (string | number | null)[]
return <tr key={rowKey}>
{rowValues.map ((value, index) => <td key={index}
className="overflow-hidden break-words border px-2 py-1 dark:border-slate-700"
data-counts-copy={display (value, rows[index], index)}>
{display (value, rows[index], index)}</td>)}
{columnKeys.map (columnKey => {
const columnValues = JSON.parse (columnKey) as (string | number | null)[]
const values = [...rowValues, ...columnValues]
const cell = cells.find (cell => JSON.stringify (cell.values) === JSON.stringify (values))
return <td key={columnKey} data-counts-copy={String (cell?.count ?? 0)}
className="border px-2 py-1 dark:border-slate-700">
<PrefetchLink to={drill (values)}>{cell?.count ?? 0}</PrefetchLink>
</td>
})}
</tr>
})}</tbody>
</CountsSelectableTable>
{cells.length === 0 && <p>{label ('empty')}</p>}
</div>
}
+25
ファイルの表示
@@ -199,3 +199,28 @@ export const apiDelete = async <T = void> (
export const isApiError = <T = unknown> (err: unknown): err is AxiosError<T> =>
axios.isAxiosError (err)
// Native downloads let the browser stream to disk without buffering a Blob in app memory.
export const apiDownload = async (
path: string,
body: Record<string, string>,
locale: LocaleCode,
): Promise<void> => {
const token = await csrfToken ()
const form = document.createElement ('form')
form.method = 'post'
form.action = `${API_BASE_URL}${path}?${new URLSearchParams ({ locale })}`
form.hidden = true
for (const [name, value] of Object.entries ({ ...body, authenticity_token: token }))
{
const input = document.createElement ('input')
input.type = 'hidden'
input.name = name
input.value = value
form.append (input)
}
document.body.append (form)
form.submit ()
form.remove ()
}
+61 -34
ファイルの表示
@@ -1,9 +1,11 @@
import { apiGet, apiPost } from '@/lib/api'
import { countsAttributes, countsFieldLabel } from '@/lib/countsDefinitions'
import { apiDownload, apiGet } from '@/lib/api'
import type { LocaleCode } from '@/lib/locales'
import type { TagNameSnapshot } from '@/types'
export type CountsResource = 'posts' | 'tags'
export type CountsResource = 'posts' | 'tags' | 'nico_tags'
| 'tag_descriptions' | 'tag_groups' | 'materials'
export type CountsName = TagNameSnapshot & {
languageCode: string; languageName?: string | null; scriptName?: string | null }
export type CountsTag = {
@@ -17,6 +19,8 @@ export type CountsTag = {
sections: { beginMs: number; endMs: number | null }[]
names: CountsName[] }
export type CountsVersion = {
[key: string]: unknown
eventType?: string
id: number
resourceId: number
versionNo: number
@@ -51,6 +55,12 @@ export type CountsStateTotals = {
deprecatedTags: number | null
externalAssignments: number | null }
export type CountsResult = {
executionAt?: string
columnValues?: (string | number | null)[][]
cells?: { values: (string | number | null)[]; count: number }[]
axisLabels?: Record<string, Record<string, string | null>>
rows?: { field: string; grain?: string }[]
cols?: { field: string; grain?: string }[]
count: number
page: number
limit: number
@@ -69,7 +79,8 @@ export type CountSort = { key: string; direction: 'asc' | 'desc' }
export type CountField = { key: string; label: string; children?: CountField[] }
export type CountRecord = Record<string, unknown>
export const countColumns = {
export const countColumns: Record<string, string> = {
event_type: 'counts:eventType',
thumbnail: 'counts:columns.thumbnailDisplay', resource_id: 'counts:columns.resourceId',
version_no: 'history:version', is_latest: 'counts:columns.latest',
title: 'counts:columns.postTitle', url: 'counts:columns.postURL',
@@ -82,7 +93,7 @@ export const countColumns = {
category: 'common:categoryLabel', aliases: 'tags:aliases',
deprecated: 'counts:columns.deprecated', user: 'history:actor',
created_at: 'counts:columns.changedAt' }
export type CountColumn = keyof typeof countColumns
export type CountColumn = string
const aliasFields: CountField[] = [
{ key: 'name', label: 'history:name' },
@@ -93,7 +104,24 @@ const nameFields: CountField[] = [
{ key: 'name', label: 'history:name' },
{ key: 'aliases', label: 'tags:aliases', children: aliasFields },
{ key: 'autoGenerated', label: 'history:nameChanges.automatic' }]
const placementFields = (depth: number): CountField[] => [
{ key: 'sectionName', label: 'counts:attributes.section_name' },
{ key: 'description', label: 'counts:attributes.description' },
{ key: 'tagId', label: 'counts:attributes.tag_id' },
{ key: 'tagGroupId', label: 'counts:resources.tag_groups' },
...(depth > 0 ? [{ key: 'children', label: 'counts:attributes.children',
children: placementFields (depth - 1) }] : [])]
const nested: Partial<Record<CountColumn, CountField[]>> = {
placements: placementFields (4),
export_paths_json: [
{ key: 'profile', label: 'counts:attributes.profile' },
{ key: 'path', label: 'counts:attributes.path' }],
members: [
{ key: 'tagId', label: 'counts:columns.resourceId' },
{ key: 'tagGroupId', label: 'counts:resources.tag_groups' },
{ key: 'versionNo', label: 'history:version' }],
tags: [
{ key: 'id', label: 'counts:columns.resourceId' },
{ key: 'versionNo', label: 'history:version' },
@@ -108,19 +136,22 @@ const nested: Partial<Record<CountColumn, CountField[]>> = {
export const columnsForCounts = (resource: CountsResource): CountColumn[] => [
...(resource === 'posts' ? ['thumbnail'] as const : []),
...(resource === 'posts' ? ['thumbnail'] : []),
'resource_id', 'version_no', 'is_latest',
...(resource === 'posts'
? ['title', 'url', 'thumbnail_base', 'tags', 'parents', 'video_ms',
'original_created_at', 'original_created_from', 'original_created_before'] as const
: ['name', 'names', 'category', 'aliases', 'parents', 'deprecated'] as const),
'user', 'created_at']
? ['title', 'url', 'thumbnail_base', 'tags', 'parents', 'video_ms',
'original_created_at', 'original_created_from', 'original_created_before']
: (resource === 'tags'
? ['name', 'names', 'category', 'aliases', 'parents', 'deprecated']
: Object.keys (countsAttributes[resource]))),
'event_type', 'user', 'created_at']
export const fieldsForCounts = (resource: CountsResource): CountField[] =>
columnsForCounts (resource).map (key => ({
key,
label: (key === 'parents' && resource === 'tags') ? 'tags:parents' : countColumns[key],
label: (key === 'parents' && resource === 'tags') ? 'tags:parents'
: (countColumns[key] ?? countsFieldLabel (key)),
children: nested[key] }))
@@ -185,7 +216,7 @@ export const countChildPaths = (fields: CountField[], prefix = ''): string[] =>
export const selectedCountChildren = (params: URLSearchParams): Set<string> =>
new Set (params.has ('children') ? params.get ('children')!.split (',') :
Object.entries (nested).flatMap (([key, fields]) =>
countChildPaths (fields, key)))
countChildPaths (fields ?? [], key)))
export const readCountSort = (value: string | null): CountSort[] =>
@@ -234,24 +265,22 @@ export const normaliseCountsParams = (
source: URLSearchParams,
): URLSearchParams => {
const params = new URLSearchParams (source)
params.delete ('event_type')
if (!params.has ('definition'))
params.set ('definition', params.get ('basis') === 'history' ? 'history' : 'latest')
const legacy = params.get ('mode')
if (['state', 'trend', 'snapshot'].includes (legacy ?? ''))
{
params.set ('mode', legacy === 'snapshot' ? 'details' : 'summary')
if (legacy !== 'snapshot') params.set ('axis', resource === 'posts' ? 'tags' : 'month')
if (legacy === 'trend')
{
if (params.get ('before')) params.set ('at', params.get ('before')!)
params.delete ('from')
params.delete ('before')
}
}
if (!params.has ('mode')) params.set ('mode', 'summary')
const axes = (resource === 'posts' && params.get ('basis') !== 'history')
? ['tags', 'month', 'user'] : ['month', 'user']
if (!axes.includes (params.get ('axis') ?? '')) params.set ('axis', axes[0])
params.delete ('grain')
if (!params.has ('rows') && params.has ('axis'))
{
const field = params.get ('axis') === 'month' ? 'created_at' : params.get ('axis')!
params.set ('rows', JSON.stringify ([{
field, ...(field === 'created_at' ? { grain: 'month' } : { }) }]))
}
if (params.has ('before') && !params.has ('through'))
params.set ('through', params.get ('before')!)
for (const key of ['basis', 'axis', 'latest', 'grain', 'before', 'summary_columns'])
params.delete (key)
if (params.has ('columns'))
{
const selected = new Set (params.get ('columns')!.split (','))
@@ -263,14 +292,13 @@ export const normaliseCountsParams = (
export const isCountsState = (params: URLSearchParams): boolean =>
params.get ('basis') !== 'history'
params.get ('definition') !== 'history'
export const countsRequestParams = (params: URLSearchParams): URLSearchParams => {
const result = new URLSearchParams (params)
const hidden = isCountsState (params) ? ['latest'] : ['kind']
for (const key of ['columns', 'summary_columns', 'children', 'child_sort',
'nested_json', 'order', 'basis', 'grain', ...hidden])
'nested_json', 'order', 'basis', 'axis', 'latest', 'grain'])
result.delete (key)
return result
}
@@ -280,10 +308,9 @@ export const fetchCounts = (
resource: CountsResource,
params: URLSearchParams,
locale: LocaleCode,
): Promise<CountsResult> => apiGet (
isCountsState (params) ? '/counts/state' : `/counts/${resource}`, {
locale, params: { ...Object.fromEntries (countsRequestParams (params)),
...(isCountsState (params) ? { resource } : { }) } })
): Promise<CountsResult> => apiGet ('/counts/query', {
locale, params: { ...Object.fromEntries (countsRequestParams (params)), resource } })
export const exportCounts = (
@@ -294,10 +321,10 @@ export const exportCounts = (
columns: string[],
headers: string[],
labels: Record<string, string>,
): Promise<Blob> => apiPost ('/counts/export', {
): Promise<void> => apiDownload ('/counts/export', {
...Object.fromEntries (params), resource, format,
columns: columns.join (','), headers: JSON.stringify (headers),
labels: JSON.stringify (labels) }, { locale, responseType: 'blob' })
labels: JSON.stringify (labels) }, locale)
+72
ファイルの表示
@@ -0,0 +1,72 @@
import type { CountField, CountsResource } from '@/lib/counts'
export type CountsAxis = { field: string; grain?: string }
export type CountsCondition = {
field: string; operator: string; value?: string; end?: string; blank?: boolean }
export type CountsFieldType = 'string' | 'integer' | 'datetime' | 'enum' | 'json'
export const countsResources: CountsResource[] = [
'posts', 'tags', 'nico_tags', 'tag_descriptions', 'tag_groups', 'materials']
export const countsGrains = ['year', 'quarter', 'month', 'week', 'day', 'hour']
export const countsOperators: Record<CountsFieldType, string[]> = {
string: ['eq', 'ne', 'like'], enum: ['eq', 'ne'], json: [],
integer: ['eq', 'ne', 'gt', 'lt', 'ge', 'le', 'range'],
datetime: ['eq', 'ne', 'gt', 'lt', 'ge', 'le', 'range'] }
export const countsAttributes: Record<CountsResource, Record<string, CountsFieldType>> = {
posts: { title: 'string', url: 'string', thumbnail_base: 'string', tags_json: 'json',
parent_post_ids: 'string', video_ms: 'integer', original_created_from: 'datetime',
original_created_before: 'datetime' },
tags: { name: 'string', names: 'json', category: 'enum', aliases: 'string',
parent_tag_ids: 'string', deprecated_at: 'datetime' },
nico_tags: { name: 'string', linked_tags: 'string' },
tag_descriptions: { language_code: 'enum', body: 'string', source_language_code: 'enum',
source_version_no: 'integer' },
tag_groups: { name: 'string', description: 'string', members: 'json', placements: 'json' },
materials: { url: 'string', parent_id: 'integer', tag_id: 'integer', tag_name: 'string',
tag_category: 'enum', discarded_at: 'datetime', updated_at: 'datetime',
updated_by_user_id: 'integer', export_paths_json: 'json', file_blob_id: 'integer',
file_filename: 'string', file_content_type: 'string', file_byte_size: 'integer',
file_checksum: 'string', file_sha256: 'string', source_kind: 'enum', source_uri: 'string',
source_path: 'string', source_file_id: 'string', normalized_source_key: 'string' } }
export const countsFilterFields = (
resource: CountsResource,
): Record<string, CountsFieldType> => ({
resource_id: 'integer' as const, version_no: 'integer' as const,
event_type: 'enum' as const, user: 'integer' as const, created_at: 'datetime' as const,
...countsAttributes[resource] })
export const countsFieldLabel = (key: string): string => {
const labels: Record<string, string> = {
resource_id: 'columns.resourceId', version_no: 'history:version',
user: 'history:actor', created_at: 'columns.changedAt', name: 'history:name',
title: 'columns.postTitle', url: 'columns.postURL', thumbnail_base: 'columns.thumbnailURL',
tags: 'columns.tags', tags_json: 'columns.tags', names: 'columns.names',
aliases: 'tags:aliases', category: 'common:categoryLabel',
language_code: 'columns.language', source_language_code: 'attributes.sourceLanguage',
changed_field: 'changedField' }
return labels[key] ?? `attributes.${key}`
}
export const countsAxisFields = (resource: CountsResource, history: boolean): CountField[] => [
...Object.entries (countsFilterFields (resource))
.filter (([, type]) => type !== 'json')
.map (([key]) => ({ key, label: countsFieldLabel (key) })),
...(resource === 'posts' ? [{ key: 'tags', label: 'columns.tags' }] : []),
...(history ? [{ key: 'changed_field', label: 'changedField' }] : [])]
export const readCountsJSON = <T,> (params: URLSearchParams, key: string, fallback: T): T => {
try
{
return JSON.parse (params.get (key) ?? JSON.stringify (fallback)) as T
}
catch
{
return fallback
}
}
+40 -8
ファイルの表示
@@ -12,7 +12,10 @@ export const countsCellText = (
row: CountsVersion,
column: CountColumn,
locale: LocaleCode,
params = new URLSearchParams (),
): string => {
const timezone = params.get ('timezone') ?? 'UTC'
const date = (value: string) => localisedDateString (value, locale, null, timezone)
switch (column)
{
case 'resource_id': return String (row.resourceId)
@@ -28,6 +31,10 @@ export const countsCellText = (
return translateUIMessage (`common:categories.${row.category}`, 'counts', locale).text
case 'video_ms': return row.videoMs == null ? '' : msToTime (row.videoMs)
case 'original_created_at':
if (timezone !== 'Asia/Tokyo')
return translateUIMessage ('sections.range', 'counts', locale, {
begin: row.originalCreatedFrom == null ? '' : date (row.originalCreatedFrom),
end: row.originalCreatedBefore == null ? '' : date (row.originalCreatedBefore) }).text
return originalCreatedAtString (
row.originalCreatedFrom ?? null, row.originalCreatedBefore ?? null, locale)
case 'original_created_from':
@@ -35,10 +42,10 @@ export const countsCellText = (
{
const value = column === 'original_created_from'
? row.originalCreatedFrom : row.originalCreatedBefore
return value == null ? '' : localisedDateString (value, locale)
return value == null ? '' : date (value)
}
case 'deprecated':
return row.deprecated == null ? '' : localisedDateString (row.deprecated, locale)
return row.deprecated == null ? '' : date (row.deprecated)
case 'user':
if (row.createdByUser == null)
return translateUIMessage ('history:bot', 'counts', locale).text
@@ -46,12 +53,33 @@ export const countsCellText = (
? `${row.createdByUser.name} (#${row.createdByUser.id})`
: translateUIMessage ('history:anonymous', 'counts', locale, {
id: row.createdByUser.id }).text
case 'created_at': return localisedDateString (row.createdAt, locale)
default: return ''
case 'created_at': return date (row.createdAt)
default:
{
const key = column.replace (/_([a-z])/g, (_, letter: string) => letter.toUpperCase ())
const value = row[key]
if (['discarded_at', 'updated_at'].includes (column) && typeof value === 'string')
return date (value)
if (column === 'event_type')
return translateUIMessage (`events.${value}`, 'counts', locale).text
if (column === 'language_code' || column === 'source_language_code')
return countsLogicalName ({ languageCode: value }, 'languageCode', locale).text
return value == null ? '' : (typeof value === 'object'
? JSON.stringify (value, null, 2) : String (value))
}
}
}
export const countsNestedRows = (row: CountsVersion, column: string): CountRecord[] => {
const key = column.replace (/_([a-z])/g, (_, letter: string) => letter.toUpperCase ())
const value = row[key]
if (column === 'export_paths_json' && value != null && typeof value === 'object')
return Object.entries (value).map (([profile, path]) => ({ profile, path }))
return Array.isArray (value) ? value as CountRecord[] : []
}
export const countsCSVCell = (
row: CountsVersion,
column: CountColumn,
@@ -62,10 +90,10 @@ export const countsCSVCell = (
const field = fieldsForCounts (resource).find (field => field.key === column)!
if (field.children != null)
{
const rows = row[column as keyof CountsVersion] as CountRecord[] ?? []
const rows = countsNestedRows (row, column)
return JSON.stringify (countsNestedExport (rows, field.children, column, params, locale))
}
return countsCellText (row, column, locale)
return countsCellText (row, column, locale, params)
}
@@ -189,8 +217,8 @@ export const countsCellCopy = (
params: URLSearchParams,
locale: LocaleCode,
): string => {
if (field.children == null) return countsCellText (row, field.key as CountColumn, locale)
const rows = row[field.key as keyof CountsVersion] as CountRecord[] ?? []
if (field.children == null) return countsCellText (row, field.key as CountColumn, locale, params)
const rows = countsNestedRows (row, field.key)
return params.get ('nested_json') === '1'
? JSON.stringify (
countsNestedExport (rows, field.children, field.key, params, locale), null, 2)
@@ -240,6 +268,10 @@ export const countsExportLabels = (
for (const key of ['ja', 'ain'])
labels[`language:${key}`] = translateUIMessage (
`history:languageNames.${key}`, 'counts', locale).text
labels.id = translateUIMessage ('columns.resourceId', 'counts', locale).text
labels.name = translateUIMessage ('history:name', 'counts', locale).text
for (const event of ['create', 'update', 'discard', 'restore'])
labels[`event_type:${event}`] = translateUIMessage (`events.${event}`, 'counts', locale).text
labels.latest = translateUIMessage ('latestValue', 'counts', locale).text
labels.notRegistered = translateUIMessage ('notRegistered', 'counts', locale).text
return labels
+15 -11
ファイルの表示
@@ -17,24 +17,26 @@ export const cn = (...inputs: ClassValue[]) => twMerge (clsx (...inputs))
type DatePrecision = 'month' | 'day' | 'hour' | 'minute' | 'second' | null
const dateFormatters = new Map<DatePrecision, Intl.DateTimeFormat> ()
let ainuDateFormatter: Intl.DateTimeFormat | null = null
const dateFormatters = new Map<string, Intl.DateTimeFormat> ()
const ainuDateFormatters = new Map<string, Intl.DateTimeFormat> ()
const formatDateString = (
date: Date,
unknown: DatePrecision,
locale: LocaleCode,
timeZone = 'Asia/Tokyo',
): string => {
const key = `${timeZone}/${unknown}`
if (Number.isNaN (date.getTime ()))
return date.toString ()
if (locale === 'ja')
{
if (!dateFormatters.has (unknown))
if (!dateFormatters.has (key))
{
dateFormatters.set (unknown, new Intl.DateTimeFormat ('ja-JP-u-ca-japanese', {
dateFormatters.set (key, new Intl.DateTimeFormat ('ja-JP-u-ca-japanese', {
era: 'long', year: 'numeric',
timeZone: 'Asia/Tokyo',
timeZone,
month: unknown === 'month' ? undefined : 'long',
day: unknown != null && ['month', 'day'].includes (unknown) ? undefined : 'numeric',
weekday: unknown != null && ['month', 'day'].includes (unknown) ? undefined : 'short',
@@ -42,14 +44,15 @@ const formatDateString = (
minute: unknown == null || unknown === 'second' ? 'numeric' : undefined,
second: unknown == null ? 'numeric' : undefined }))
}
return dateFormatters.get (unknown)!.format (date)
return dateFormatters.get (key)!.format (date)
}
ainuDateFormatter ??= new Intl.DateTimeFormat ('en-CA', {
if (!ainuDateFormatters.has (timeZone))
ainuDateFormatters.set (timeZone, new Intl.DateTimeFormat ('en-CA', {
year: 'numeric', month: '2-digit', day: '2-digit',
timeZone: 'Asia/Tokyo',
timeZone,
hour: '2-digit', minute: '2-digit', second: '2-digit',
hourCycle: 'h23' })
const parts = ainuDateFormatter.formatToParts (date)
hourCycle: 'h23' }))
const parts = ainuDateFormatters.get (timeZone)!.formatToParts (date)
const part = (type: string) => parts.find (entry => entry.type === type)?.value ?? ''
const omitDay = unknown != null && ['month', 'day'].includes (unknown)
const dateParts = [part ('year'),
@@ -76,7 +79,8 @@ export const localisedDateString = (
value: string | Date,
locale: LocaleCode,
unknown: DatePrecision = null,
): string => dateString (value, unknown, locale)
timeZone?: string,
): string => formatDateString (toDate (value), unknown, locale, timeZone)
export const originalCreatedAtString = (
+101 -3
ファイルの表示
@@ -1,9 +1,13 @@
{
"titles": {
"posts": "投稿の集計・明細",
"tags": "タグの集計・明細"
"posts": "広場の集計・明細",
"tags": "タグの集計・明細",
"nico_tags": "ニコニコタグの集計・明細",
"tag_descriptions": "タグ説明の集計・明細",
"tag_groups": "タググループの集計・明細",
"materials": "素材の集計・明細"
},
"target": "集計対象",
"target": "集計定義",
"run": "集計実行",
"conditions": "集計条件",
"output": "出力項目",
@@ -119,5 +123,99 @@
"exportFormats": {
"json": "JSON",
"csv": "CSV"
},
"resources": {
"posts": "広場",
"tags": "タグ",
"nico_tags": "ニコニコタグ",
"tag_descriptions": "タグ説明",
"tag_groups": "タググループ",
"materials": "素材"
},
"latest": "最新",
"history": "履歴",
"referenceAt": "基準日時",
"referenceHelp": "指定した日時における各データの最新版を集計・表示します。空欄の場合は現在の最新版を使用します。",
"from": "開始(以上)",
"through": "終了(以下)",
"axisItems": "項目一覧",
"rows": "行",
"cols": "列",
"axisPlace": "{{field}}を{{target}}に配置",
"field": "項目",
"operator": "演算子",
"add": "追加",
"remove": "削除",
"value": "値",
"blank": "空欄",
"additionalConditions": "追加条件",
"changedField": "変更項目",
"eventType": "異動区分",
"count": "件数",
"recordTotal": "総件数:{{count}}",
"grain": "粒度",
"grains": {
"year": "年",
"quarter": "四半期",
"month": "月",
"week": "週",
"day": "日",
"hour": "時"
},
"operators": {
"eq": "等しい",
"ne": "等しくない",
"gt": "より大きい",
"lt": "未満",
"ge": "以上",
"le": "以下",
"like": "パターン",
"range": "範囲"
},
"events": {
"create": "作成",
"update": "更新",
"discard": "破棄",
"restore": "復元"
},
"attributes": {
"sourceLanguage": "翻訳元の言語",
"source_language_code": "翻訳元の言語",
"source_version_no": "翻訳元の版番号",
"event_type": "異動区分",
"body": "本文",
"linked_tags": "対応タグ",
"description": "説明",
"members": "構成要素",
"placements": "配置",
"parent_id": "親素材",
"tag_id": "タグ",
"tag_name": "タグ名称",
"tag_category": "タグカテゴリ",
"discarded_at": "破棄日時",
"updated_at": "履歴行更新日時",
"updated_by_user_id": "履歴行更新者",
"export_paths_json": "出力先",
"file_blob_id": "ファイル識別子",
"file_filename": "ファイル名",
"file_content_type": "ファイル形式",
"file_byte_size": "ファイル容量",
"file_checksum": "チェックサム",
"file_sha256": "SHA-256",
"source_kind": "取得元の種類",
"source_uri": "取得元 URI",
"source_path": "取得元のパス",
"source_file_id": "取得元ファイル識別子",
"normalized_source_key": "取得元識別キー",
"parent_post_ids": "親投稿",
"parent_tag_ids": "上位タグ",
"video_ms": "動画時間",
"original_created_from": "オリジナルの投稿日時(開始境界)",
"original_created_before": "オリジナルの投稿日時(終了境界)",
"deprecated_at": "廃止日時",
"section_name": "節の名称",
"children": "子項目",
"profile": "出力設定",
"path": "出力パス"
}
}
+52 -38
ファイルの表示
@@ -16,12 +16,15 @@ import { Button } from '@/components/ui/button'
import { countsRequestParams, exportCounts, fieldsForCounts, fetchCounts,
isCountsState, normaliseCountsParams, selectedCountColumns } from '@/lib/counts'
import { countsExportLabels } from '@/lib/countsDisplay'
import { selectedCountsSummaryFields } from '@/lib/countsState'
import { countsAxisFields, countsResources, countsFieldLabel, readCountsJSON }
from '@/lib/countsDefinitions'
import { countsKeys } from '@/lib/queryKeys'
import { cn, inputClass } from '@/lib/utils'
import { useLocale } from '@/lib/useLocale'
import { useUITranslation } from '@/lib/useUITranslation'
import type { CountsAxis } from '@/lib/countsDefinitions'
import type { CountsResource } from '@/lib/counts'
@@ -40,19 +43,21 @@ const CountsResourcePage = ({ resource }: { resource: CountsResource }) => {
const mode = params.get ('mode') ?? 'summary'
const state = isCountsState (params)
const cacheParams = new URLSearchParams (request)
cacheParams.set ('basis', state ? 'state' : 'history')
cacheParams.set ('definition', state ? 'latest' : 'history')
const [format, setFormat] = useState<'json' | 'csv'> ('json')
const [exporting, setExporting] = useState (false)
const [exportError, setExportError] = useState (false)
const { data, isPending, isError, isPlaceholderData, refetch } = useQuery ({
enabled: params.has ('timezone'),
queryKey: countsKeys.index (resource, cacheParams.toString (), locale),
queryFn: () => fetchCounts (resource, params, locale), retry: false,
placeholderData: (previous, query) => {
const previousParams = new URLSearchParams (String (query?.queryKey[3] ?? ''))
return (query?.queryKey[1] === resource && query?.queryKey[2] === locale
&& previousParams.get ('mode') === mode
&& previousParams.get ('axis') === params.get ('axis')
&& previousParams.get ('basis') === cacheParams.get ('basis')) ? previous : undefined
&& previousParams.get ('rows') === params.get ('rows')
&& previousParams.get ('cols') === params.get ('cols')
&& previousParams.get ('definition') === cacheParams.get ('definition')) ? previous : undefined
} })
useEffect (() => {
@@ -61,12 +66,21 @@ const CountsResourcePage = ({ resource }: { resource: CountsResource }) => {
}, [canonical, source, setParams])
useEffect (() => {
if (data?.at == null || isPlaceholderData) return
const next = new URLSearchParams (canonical)
if (!next.get ('at')) next.set ('at', data.at)
const timezone = Intl.DateTimeFormat ().resolvedOptions ().timeZone
if (params.get ('timezone') !== timezone)
{
const next = new URLSearchParams (canonical)
next.set ('timezone', timezone)
setParams (next, { replace: true })
}
else if (data?.executionAt != null && !isPlaceholderData && !params.has ('execution_at'))
{
const next = new URLSearchParams (canonical)
next.set ('execution_at', data.executionAt)
setParams (next, { replace: true })
}
}, [canonical, data, isPlaceholderData, params, setParams])
if (next.toString () !== canonical) setParams (next, { replace: true })
}, [canonical, data, isPlaceholderData, setParams])
const update = (key: string, value: string) => {
const next = new URLSearchParams (params)
@@ -80,18 +94,19 @@ const CountsResourcePage = ({ resource }: { resource: CountsResource }) => {
setExportError (false)
try
{
const fields = mode === 'summary' ? selectedCountsSummaryFields (resource, params)
const fields = mode === 'summary' ? [
...[...readCountsJSON<CountsAxis[]> (params, 'rows', []),
...readCountsJSON<CountsAxis[]> (params, 'cols', [])].map (axis => ({
key: axis.field, label: countsFieldLabel (axis.field) })),
{ key: 'count', label: 'count' }]
: selectedCountColumns (resource, params).map (column =>
fieldsForCounts (resource).find (field => field.key === column)!)
const file = await exportCounts (resource, params, locale, format,
await exportCounts (resource, params, locale, format,
fields.map (field => field.key), fields.map (field => message (field.label).text),
countsExportLabels (resource, locale))
const url = URL.createObjectURL (file)
const link = document.createElement ('a')
link.href = url
link.download = `counts-${resource}.${format}`
link.click ()
setTimeout (() => URL.revokeObjectURL (url), 1000)
{ ...countsExportLabels (resource, locale),
...Object.fromEntries (countsAxisFields (resource, !state).map (field => [
field.key, message (field.label).text])), count: message ('count').text })
}
catch
{
@@ -117,17 +132,23 @@ const CountsResourcePage = ({ resource }: { resource: CountsResource }) => {
lang={message ('target').language}>
<h2 className="mb-2 font-semibold">{label ('target')}</h2>
<ul className="space-y-1">
{(['posts', 'tags'] as const).map (target => {
const next = new URLSearchParams (params)
for (const key of ['resource_id', 'tag', 'columns', 'summary_columns',
'sort', 'page', 'children', 'child_sort']) next.delete (key)
return <li key={target}><PrefetchLink
to={`/counts/${target}?${normaliseCountsParams (target, next)}`}
aria-current={target === resource ? 'page' : undefined}
className={cn ('block py-1', target === resource && 'font-bold underline')}>
{label (target === 'posts' ? 'history:post' : 'navigation:tags')}
</PrefetchLink></li>
})}
{countsResources.map (target => <li key={target}>
<span>{label (`resources.${target}`)}</span>
<ul className="ml-3">
{['latest', 'history'].map (definition => {
const next = new URLSearchParams ({ definition, mode })
for (const key of ['timezone', 'at', 'execution_at'])
if (params.get (key)) next.set (key, params.get (key)!)
const active = target === resource
&& params.get ('definition') === definition
return <li key={definition}><PrefetchLink
to={`/counts/${target}?${next}`}
aria-current={active ? 'page' : undefined}
className={cn ('block py-1', active && 'font-bold underline')}>
{label (definition)}</PrefetchLink></li>
})}
</ul>
</li>)}
</ul>
</nav>
</SidebarComponent>
@@ -153,7 +174,7 @@ const CountsResourcePage = ({ resource }: { resource: CountsResource }) => {
</select>
<Button type="button" variant="outline" size="sm"
disabled={data == null || isError || isPlaceholderData
|| exporting || !params.get ('at')}
|| exporting || !params.get ('execution_at')}
onClick={() => void download ()}>{label ('export')}</Button>
</>}/>
{exportError && <p role="alert">{label ('common:fetchError')}</p>}
@@ -161,14 +182,7 @@ const CountsResourcePage = ({ resource }: { resource: CountsResource }) => {
{isPending && <p>{label ('shared:messages.loadingEllipsis')}</p>}
{isError && <p role="alert">{label ('common:fetchError')}</p>}
{data != null && <>
{data.at && <div className="my-1 flex flex-wrap gap-x-4 gap-y-1 text-xs">
<span>{label ('state.boundary')}:{data.at.replace ('T', ' ')}</span>
{data.totals && (['posts', 'tags', 'assignments'] as const).map (key => (
<span key={key}>{label (`state.totals.${key}`)}:
{data.totals![key] ?? '—'}
</span>))}
</div>}
{!state && <p className="my-1 text-xs">{label ('total', { count: data.count })}</p>}
<p className="my-1 text-xs">{label ('recordTotal', { count: data.count })}</p>
{mode === 'summary' ? <CountsSummaryResults resource={resource}
data={data} params={params}
pending={isPlaceholderData} update={update}/> : (