add tagging system for media items

Introduces user-defined tag categories and tags with a many-to-many
relationship to media items. Tags are stored in a SQLite database
(medialore.db via better-sqlite3) with ON DELETE CASCADE for automatic
cleanup. Users can manage categories and tags at /manage/tags, assign
tags to games in the detail modal, and tag mixed media files via a
hover button on each tile.

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
This commit is contained in:
2026-03-25 17:29:24 -04:00
parent bf54b45fa1
commit f788b1a441
17 changed files with 1680 additions and 5 deletions

View File

@@ -0,0 +1,42 @@
'use client'
import Link from 'next/link'
import { usePathname } from 'next/navigation'
const TABS = [
{ href: '/manage', label: 'Libraries' },
{ href: '/manage/tags', label: 'Tags' },
]
export default function ManageSubNav() {
const pathname = usePathname()
return (
<nav className="flex items-center gap-1 mb-8 border-b pb-4" style={{ borderColor: 'var(--border)' }}>
{TABS.map(({ href, label }) => {
const active = pathname === href
return (
<Link
key={href}
href={href}
className="text-sm px-3 py-1.5 rounded-lg transition-colors"
style={{
color: active ? 'var(--text-primary)' : 'var(--text-secondary)',
backgroundColor: active ? 'var(--surface)' : 'transparent',
}}
onMouseEnter={(e) => {
;(e.currentTarget as HTMLElement).style.backgroundColor = 'var(--surface)'
;(e.currentTarget as HTMLElement).style.color = 'var(--text-primary)'
}}
onMouseLeave={(e) => {
;(e.currentTarget as HTMLElement).style.backgroundColor = active ? 'var(--surface)' : 'transparent'
;(e.currentTarget as HTMLElement).style.color = active ? 'var(--text-primary)' : 'var(--text-secondary)'
}}
>
{label}
</Link>
)
})}
</nav>
)
}

View File

@@ -2,6 +2,7 @@
import { useEffect, useRef } from 'react'
import type { Game } from '@/types'
import TagSelector from '@/components/tags/TagSelector'
interface Props {
game: Game
@@ -90,6 +91,14 @@ export default function GameDetailModal({ game, libraryId, onClose }: Props) {
<span></span>
Download .zip
</a>
{/* Tags */}
<div className="mt-4 pt-4" style={{ borderTop: '1px solid var(--border)' }}>
<p className="text-xs font-semibold uppercase tracking-wider mb-2" style={{ color: 'var(--text-secondary)' }}>
Tags
</p>
<TagSelector mediaKey={`${libraryId}:${game.id}`} />
</div>
</div>
</div>
</div>

View File

@@ -4,6 +4,7 @@ import { useEffect, useState, useCallback, useRef } from 'react'
import type { DirectoryListing, FileEntry } from '@/types'
import VideoPlayerModal from './VideoPlayerModal'
import ImageLightbox from './ImageLightbox'
import TagSelector from '@/components/tags/TagSelector'
interface Props {
libraryId: string
@@ -15,12 +16,15 @@ type ModalState =
| { type: 'image'; url: string; name: string }
| null
type TagPanelState = { entry: FileEntry; mediaKey: string } | null
export default function MixedView({ libraryId, initialPath }: Props) {
const [currentPath, setCurrentPath] = useState(initialPath)
const [listing, setListing] = useState<DirectoryListing | null>(null)
const [loading, setLoading] = useState(true)
const [error, setError] = useState<string | null>(null)
const [modal, setModal] = useState<ModalState>(null)
const [tagPanel, setTagPanel] = useState<TagPanelState>(null)
const loadPath = useCallback(
(path: string) => {
@@ -64,6 +68,12 @@ export default function MixedView({ libraryId, initialPath }: Props) {
}
}
const handleTagEntry = (entry: FileEntry) => {
const relativePath = currentPath ? `${currentPath}/${entry.name}` : entry.name
const mediaKey = `${libraryId}:${encodeURIComponent(relativePath)}`
setTagPanel({ entry, mediaKey })
}
const navigateUp = () => {
const parts = currentPath.split('/').filter(Boolean)
parts.pop()
@@ -136,7 +146,7 @@ export default function MixedView({ libraryId, initialPath }: Props) {
</button>
)}
{listing.entries.map((entry) => (
<EntryTile key={entry.name} entry={entry} onOpen={handleEntry} />
<EntryTile key={entry.name} entry={entry} onOpen={handleEntry} onTag={handleTagEntry} />
))}
</div>
)}
@@ -149,11 +159,49 @@ export default function MixedView({ libraryId, initialPath }: Props) {
{modal?.type === 'image' && (
<ImageLightbox url={modal.url} name={modal.name} onClose={() => setModal(null)} />
)}
{/* Tag panel */}
{tagPanel && (
<div
className="fixed inset-0 z-50 flex items-end sm:items-center justify-center p-4"
style={{ backgroundColor: 'rgba(0,0,0,0.6)' }}
onClick={(e) => { if (e.target === e.currentTarget) setTagPanel(null) }}
>
<div
className="w-full max-w-md rounded-2xl shadow-2xl overflow-hidden"
style={{ backgroundColor: 'var(--surface)', border: '1px solid var(--border)' }}
>
<div className="flex items-center justify-between px-5 py-4" style={{ borderBottom: '1px solid var(--border)' }}>
<div className="min-w-0">
<p className="text-xs font-semibold uppercase tracking-wider mb-0.5" style={{ color: 'var(--text-secondary)' }}>
Tags
</p>
<p className="text-sm font-medium truncate" style={{ color: 'var(--text-primary)' }}>
{tagPanel.entry.name}
</p>
</div>
<button
onClick={() => setTagPanel(null)}
className="ml-4 w-8 h-8 flex-shrink-0 rounded-full flex items-center justify-center text-sm transition-colors"
style={{ backgroundColor: 'var(--border)', color: 'var(--text-secondary)' }}
onMouseEnter={(e) => ((e.currentTarget as HTMLElement).style.color = 'var(--text-primary)')}
onMouseLeave={(e) => ((e.currentTarget as HTMLElement).style.color = 'var(--text-secondary)')}
aria-label="Close"
>
</button>
</div>
<div className="px-5 py-4">
<TagSelector mediaKey={tagPanel.mediaKey} />
</div>
</div>
</div>
)}
</>
)
}
function EntryTile({ entry, onOpen }: { entry: FileEntry; onOpen: (e: FileEntry) => void }) {
function EntryTile({ entry, onOpen, onTag }: { entry: FileEntry; onOpen: (e: FileEntry) => void; onTag: (e: FileEntry) => void }) {
type ImgState = 'loading' | 'loaded' | 'error'
const [imgState, setImgState] = useState<ImgState>(
entry.thumbnailUrl ? 'loading' : 'error'
@@ -244,6 +292,17 @@ function EntryTile({ entry, onOpen }: { entry: FileEntry; onOpen: (e: FileEntry)
</div>
)}
{/* Tag button — top-left, shown on hover */}
<button
onClick={(e) => { e.stopPropagation(); onTag(entry) }}
className="absolute top-2 left-2 w-6 h-6 rounded-full items-center justify-center text-xs opacity-0 group-hover:opacity-100 transition-opacity hidden group-hover:flex"
style={{ backgroundColor: 'rgba(0,0,0,0.55)', color: '#fff' }}
aria-label={`Tag ${entry.name}`}
title="Tags"
>
🏷
</button>
</button>
)
}

View File

@@ -0,0 +1,33 @@
import type { Tag, TagCategory } from '@/types'
interface Props {
tag: Tag
category?: TagCategory
onRemove?: () => void
}
export default function TagBadge({ tag, category, onRemove }: Props) {
return (
<span
className="inline-flex items-center gap-1 px-2 py-0.5 rounded-full text-xs font-medium"
style={{ backgroundColor: 'var(--border)', color: 'var(--text-primary)' }}
>
{category && (
<span style={{ color: 'var(--text-secondary)' }}>{category.name}:</span>
)}
{tag.name}
{onRemove && (
<button
onClick={onRemove}
className="ml-0.5 leading-none transition-colors"
style={{ color: 'var(--text-secondary)' }}
onMouseEnter={(e) => ((e.currentTarget as HTMLElement).style.color = 'var(--text-primary)')}
onMouseLeave={(e) => ((e.currentTarget as HTMLElement).style.color = 'var(--text-secondary)')}
aria-label={`Remove tag ${tag.name}`}
>
</button>
)}
</span>
)
}

View File

@@ -0,0 +1,162 @@
'use client'
import { useEffect, useState, useCallback } from 'react'
import type { Tag, TagCategory } from '@/types'
import TagBadge from './TagBadge'
interface Props {
mediaKey: string
}
interface AllTags {
categories: TagCategory[]
tags: Tag[]
}
export default function TagSelector({ mediaKey }: Props) {
const [assigned, setAssigned] = useState<{ tags: Tag[]; categories: TagCategory[] }>({
tags: [],
categories: [],
})
const [all, setAll] = useState<AllTags>({ categories: [], tags: [] })
const [loading, setLoading] = useState(true)
const [busy, setBusy] = useState<string | null>(null) // tagId being toggled
const fetchAssigned = useCallback(() => {
return fetch(`/api/tags/assignments?mediaKey=${encodeURIComponent(mediaKey)}`)
.then((r) => r.json())
.then((data) => setAssigned(data))
}, [mediaKey])
const fetchAll = useCallback(() => {
return Promise.all([
fetch('/api/tags/categories').then((r) => r.json()),
fetch('/api/tags/items').then((r) => r.json()),
]).then(([categories, tags]: [TagCategory[], Tag[]]) => {
setAll({ categories, tags })
})
}, [])
useEffect(() => {
setLoading(true)
Promise.all([fetchAssigned(), fetchAll()]).finally(() => setLoading(false))
}, [fetchAssigned, fetchAll])
const isAssigned = (tagId: string) => assigned.tags.some((t) => t.id === tagId)
const toggleTag = async (tag: Tag) => {
if (busy) return
setBusy(tag.id)
try {
if (isAssigned(tag.id)) {
await fetch(
`/api/tags/assignments?mediaKey=${encodeURIComponent(mediaKey)}&tagId=${encodeURIComponent(tag.id)}`,
{ method: 'DELETE' }
)
} else {
await fetch('/api/tags/assignments', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ mediaKey, tagId: tag.id }),
})
}
await fetchAssigned()
} finally {
setBusy(null)
}
}
if (loading) {
return (
<div className="flex gap-1.5 flex-wrap">
{[60, 80, 50].map((w) => (
<div
key={w}
className="h-5 rounded-full animate-pulse"
style={{ width: w, backgroundColor: 'var(--border)' }}
/>
))}
</div>
)
}
const categoryMap = Object.fromEntries(all.categories.map((c) => [c.id, c]))
const assignedCategoryMap = Object.fromEntries(assigned.categories.map((c) => [c.id, c]))
const hasAnyTags = all.tags.length > 0
return (
<div className="flex flex-col gap-3">
{/* Assigned tags */}
{assigned.tags.length > 0 && (
<div className="flex flex-wrap gap-1.5">
{assigned.tags.map((tag) => (
<TagBadge
key={tag.id}
tag={tag}
category={assignedCategoryMap[tag.categoryId]}
onRemove={() => toggleTag(tag)}
/>
))}
</div>
)}
{/* Tag picker grouped by category */}
{hasAnyTags ? (
<div className="flex flex-col gap-2">
{all.categories.map((category) => {
const categoryTags = all.tags.filter((t) => t.categoryId === category.id)
if (categoryTags.length === 0) return null
return (
<div key={category.id}>
<p className="text-xs mb-1" style={{ color: 'var(--text-secondary)' }}>
{category.name}
</p>
<div className="flex flex-wrap gap-1.5">
{categoryTags.map((tag) => {
const active = isAssigned(tag.id)
const isBusy = busy === tag.id
return (
<button
key={tag.id}
onClick={() => toggleTag(tag)}
disabled={!!busy}
className="px-2 py-0.5 rounded-full text-xs font-medium transition-colors disabled:opacity-60"
style={{
backgroundColor: active ? 'var(--accent)' : 'var(--border)',
color: active ? '#fff' : 'var(--text-secondary)',
cursor: busy ? 'wait' : 'pointer',
}}
onMouseEnter={(e) => {
if (!busy) {
const el = e.currentTarget as HTMLElement
el.style.backgroundColor = active ? 'var(--accent-hover)' : 'var(--text-secondary)'
if (!active) el.style.color = 'var(--background)'
}
}}
onMouseLeave={(e) => {
const el = e.currentTarget as HTMLElement
el.style.backgroundColor = active ? 'var(--accent)' : 'var(--border)'
el.style.color = active ? '#fff' : 'var(--text-secondary)'
}}
>
{isBusy ? '…' : tag.name}
</button>
)
})}
</div>
</div>
)
})}
</div>
) : (
<p className="text-xs" style={{ color: 'var(--text-secondary)' }}>
No tags defined yet.{' '}
<a href="/manage/tags" style={{ color: 'var(--accent)' }}>
Manage tags
</a>
</p>
)}
</div>
)
}