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:
@@ -1,5 +1,6 @@
|
||||
import { NextRequest, NextResponse } from 'next/server'
|
||||
import { getLibrary, removeLibrary } from '@/lib/libraries'
|
||||
import { removeAllAssignmentsForLibrary } from '@/lib/tags'
|
||||
|
||||
export async function DELETE(
|
||||
_request: NextRequest,
|
||||
@@ -13,5 +14,6 @@ export async function DELETE(
|
||||
}
|
||||
|
||||
removeLibrary(id)
|
||||
removeAllAssignmentsForLibrary(id)
|
||||
return new NextResponse(null, { status: 204 })
|
||||
}
|
||||
|
||||
43
src/app/api/tags/assignments/route.ts
Normal file
43
src/app/api/tags/assignments/route.ts
Normal file
@@ -0,0 +1,43 @@
|
||||
import { NextRequest, NextResponse } from 'next/server'
|
||||
import { getResolvedTagsForItem, addTagToItem, removeTagFromItem } from '@/lib/tags'
|
||||
|
||||
export async function GET(request: NextRequest) {
|
||||
try {
|
||||
const { searchParams } = new URL(request.url)
|
||||
const mediaKey = searchParams.get('mediaKey')
|
||||
if (!mediaKey) {
|
||||
return NextResponse.json({ error: 'mediaKey is required' }, { status: 400 })
|
||||
}
|
||||
return NextResponse.json(getResolvedTagsForItem(mediaKey))
|
||||
} catch (err) {
|
||||
return NextResponse.json({ error: (err as Error).message }, { status: 500 })
|
||||
}
|
||||
}
|
||||
|
||||
export async function POST(request: NextRequest) {
|
||||
try {
|
||||
const { mediaKey, tagId } = await request.json()
|
||||
if (!mediaKey || !tagId) {
|
||||
return NextResponse.json({ error: 'mediaKey and tagId are required' }, { status: 400 })
|
||||
}
|
||||
addTagToItem(mediaKey, tagId)
|
||||
return new NextResponse(null, { status: 204 })
|
||||
} catch (err) {
|
||||
return NextResponse.json({ error: (err as Error).message }, { status: 400 })
|
||||
}
|
||||
}
|
||||
|
||||
export async function DELETE(request: NextRequest) {
|
||||
try {
|
||||
const { searchParams } = new URL(request.url)
|
||||
const mediaKey = searchParams.get('mediaKey')
|
||||
const tagId = searchParams.get('tagId')
|
||||
if (!mediaKey || !tagId) {
|
||||
return NextResponse.json({ error: 'mediaKey and tagId are required' }, { status: 400 })
|
||||
}
|
||||
removeTagFromItem(mediaKey, tagId)
|
||||
return new NextResponse(null, { status: 204 })
|
||||
} catch (err) {
|
||||
return NextResponse.json({ error: (err as Error).message }, { status: 400 })
|
||||
}
|
||||
}
|
||||
44
src/app/api/tags/categories/[id]/route.ts
Normal file
44
src/app/api/tags/categories/[id]/route.ts
Normal file
@@ -0,0 +1,44 @@
|
||||
import { NextRequest, NextResponse } from 'next/server'
|
||||
import { updateCategory, deleteCategory, deleteCategoryForce, getTags } from '@/lib/tags'
|
||||
|
||||
export async function PATCH(
|
||||
request: NextRequest,
|
||||
{ params }: { params: Promise<{ id: string }> }
|
||||
) {
|
||||
try {
|
||||
const { id } = await params
|
||||
const { name } = await request.json()
|
||||
const category = updateCategory(id, name)
|
||||
return NextResponse.json(category)
|
||||
} catch (err) {
|
||||
return NextResponse.json({ error: (err as Error).message }, { status: 400 })
|
||||
}
|
||||
}
|
||||
|
||||
export async function DELETE(
|
||||
request: NextRequest,
|
||||
{ params }: { params: Promise<{ id: string }> }
|
||||
) {
|
||||
try {
|
||||
const { id } = await params
|
||||
const { searchParams } = new URL(request.url)
|
||||
const cascade = searchParams.get('cascade') === 'true'
|
||||
|
||||
if (cascade) {
|
||||
deleteCategoryForce(id)
|
||||
} else {
|
||||
const tags = getTags(id)
|
||||
if (tags.length > 0) {
|
||||
return NextResponse.json(
|
||||
{ error: `Category has ${tags.length} tag${tags.length === 1 ? '' : 's'}.`, tagCount: tags.length },
|
||||
{ status: 409 }
|
||||
)
|
||||
}
|
||||
deleteCategory(id)
|
||||
}
|
||||
|
||||
return new NextResponse(null, { status: 204 })
|
||||
} catch (err) {
|
||||
return NextResponse.json({ error: (err as Error).message }, { status: 400 })
|
||||
}
|
||||
}
|
||||
20
src/app/api/tags/categories/route.ts
Normal file
20
src/app/api/tags/categories/route.ts
Normal file
@@ -0,0 +1,20 @@
|
||||
import { NextRequest, NextResponse } from 'next/server'
|
||||
import { getCategories, addCategory } from '@/lib/tags'
|
||||
|
||||
export async function GET() {
|
||||
try {
|
||||
return NextResponse.json(getCategories())
|
||||
} catch (err) {
|
||||
return NextResponse.json({ error: (err as Error).message }, { status: 500 })
|
||||
}
|
||||
}
|
||||
|
||||
export async function POST(request: NextRequest) {
|
||||
try {
|
||||
const { name } = await request.json()
|
||||
const category = addCategory(name)
|
||||
return NextResponse.json(category, { status: 201 })
|
||||
} catch (err) {
|
||||
return NextResponse.json({ error: (err as Error).message }, { status: 400 })
|
||||
}
|
||||
}
|
||||
29
src/app/api/tags/items/[id]/route.ts
Normal file
29
src/app/api/tags/items/[id]/route.ts
Normal file
@@ -0,0 +1,29 @@
|
||||
import { NextRequest, NextResponse } from 'next/server'
|
||||
import { updateTag, deleteTag } from '@/lib/tags'
|
||||
|
||||
export async function PATCH(
|
||||
request: NextRequest,
|
||||
{ params }: { params: Promise<{ id: string }> }
|
||||
) {
|
||||
try {
|
||||
const { id } = await params
|
||||
const { name } = await request.json()
|
||||
const tag = updateTag(id, name)
|
||||
return NextResponse.json(tag)
|
||||
} catch (err) {
|
||||
return NextResponse.json({ error: (err as Error).message }, { status: 400 })
|
||||
}
|
||||
}
|
||||
|
||||
export async function DELETE(
|
||||
_request: NextRequest,
|
||||
{ params }: { params: Promise<{ id: string }> }
|
||||
) {
|
||||
try {
|
||||
const { id } = await params
|
||||
deleteTag(id)
|
||||
return new NextResponse(null, { status: 204 })
|
||||
} catch (err) {
|
||||
return NextResponse.json({ error: (err as Error).message }, { status: 400 })
|
||||
}
|
||||
}
|
||||
22
src/app/api/tags/items/route.ts
Normal file
22
src/app/api/tags/items/route.ts
Normal file
@@ -0,0 +1,22 @@
|
||||
import { NextRequest, NextResponse } from 'next/server'
|
||||
import { getTags, addTag } from '@/lib/tags'
|
||||
|
||||
export async function GET(request: NextRequest) {
|
||||
try {
|
||||
const { searchParams } = new URL(request.url)
|
||||
const categoryId = searchParams.get('categoryId') ?? undefined
|
||||
return NextResponse.json(getTags(categoryId))
|
||||
} catch (err) {
|
||||
return NextResponse.json({ error: (err as Error).message }, { status: 500 })
|
||||
}
|
||||
}
|
||||
|
||||
export async function POST(request: NextRequest) {
|
||||
try {
|
||||
const { name, categoryId } = await request.json()
|
||||
const tag = addTag(name, categoryId)
|
||||
return NextResponse.json(tag, { status: 201 })
|
||||
} catch (err) {
|
||||
return NextResponse.json({ error: (err as Error).message }, { status: 400 })
|
||||
}
|
||||
}
|
||||
10
src/app/manage/layout.tsx
Normal file
10
src/app/manage/layout.tsx
Normal file
@@ -0,0 +1,10 @@
|
||||
import ManageSubNav from '@/components/ManageSubNav'
|
||||
|
||||
export default function ManageLayout({ children }: { children: React.ReactNode }) {
|
||||
return (
|
||||
<div>
|
||||
<ManageSubNav />
|
||||
{children}
|
||||
</div>
|
||||
)
|
||||
}
|
||||
528
src/app/manage/tags/page.tsx
Normal file
528
src/app/manage/tags/page.tsx
Normal file
@@ -0,0 +1,528 @@
|
||||
'use client'
|
||||
|
||||
import { useEffect, useState, useRef } from 'react'
|
||||
import type { Tag, TagCategory } from '@/types'
|
||||
|
||||
// ─── Main Page ────────────────────────────────────────────────────────────────
|
||||
|
||||
export default function ManageTagsPage() {
|
||||
const [categories, setCategories] = useState<TagCategory[]>([])
|
||||
const [tags, setTags] = useState<Tag[]>([])
|
||||
const [loading, setLoading] = useState(true)
|
||||
|
||||
const refresh = () => {
|
||||
Promise.all([
|
||||
fetch('/api/tags/categories').then((r) => r.json()),
|
||||
fetch('/api/tags/items').then((r) => r.json()),
|
||||
])
|
||||
.then(([cats, tgs]: [TagCategory[], Tag[]]) => {
|
||||
setCategories(cats)
|
||||
setTags(tgs)
|
||||
setLoading(false)
|
||||
})
|
||||
.catch(() => setLoading(false))
|
||||
}
|
||||
|
||||
useEffect(() => {
|
||||
refresh()
|
||||
}, [])
|
||||
|
||||
const tagsForCategory = (categoryId: string) => tags.filter((t) => t.categoryId === categoryId)
|
||||
|
||||
return (
|
||||
<div className="max-w-2xl">
|
||||
<h1 className="text-2xl font-semibold mb-1" style={{ color: 'var(--text-primary)' }}>
|
||||
Manage Tags
|
||||
</h1>
|
||||
<p className="text-sm mb-8" style={{ color: 'var(--text-secondary)' }}>
|
||||
Create tag categories and tags to organize your media items.
|
||||
</p>
|
||||
|
||||
<Section title="Tag Categories & Tags">
|
||||
{loading ? (
|
||||
<LoadingRows />
|
||||
) : categories.length === 0 ? (
|
||||
<p className="text-sm py-4" style={{ color: 'var(--text-secondary)' }}>
|
||||
No categories yet. Add one below.
|
||||
</p>
|
||||
) : (
|
||||
<div className="divide-y" style={{ borderColor: 'var(--border)' }}>
|
||||
{categories.map((cat) => (
|
||||
<CategoryBlock
|
||||
key={cat.id}
|
||||
category={cat}
|
||||
tags={tagsForCategory(cat.id)}
|
||||
onChanged={refresh}
|
||||
/>
|
||||
))}
|
||||
</div>
|
||||
)}
|
||||
</Section>
|
||||
|
||||
<Section title="Add a Category">
|
||||
<AddCategoryForm onAdded={refresh} />
|
||||
</Section>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
|
||||
// ─── Category Block ───────────────────────────────────────────────────────────
|
||||
|
||||
function CategoryBlock({
|
||||
category,
|
||||
tags,
|
||||
onChanged,
|
||||
}: {
|
||||
category: TagCategory
|
||||
tags: Tag[]
|
||||
onChanged: () => void
|
||||
}) {
|
||||
const [editing, setEditing] = useState(false)
|
||||
const [editName, setEditName] = useState(category.name)
|
||||
const [saving, setSaving] = useState(false)
|
||||
const [confirming, setConfirming] = useState(false)
|
||||
const [deleting, setDeleting] = useState(false)
|
||||
const [error, setError] = useState<string | null>(null)
|
||||
const cancelRef = useRef<ReturnType<typeof setTimeout> | null>(null)
|
||||
|
||||
const handleRename = async (e: React.FormEvent) => {
|
||||
e.preventDefault()
|
||||
setError(null)
|
||||
setSaving(true)
|
||||
try {
|
||||
const res = await fetch(`/api/tags/categories/${encodeURIComponent(category.id)}`, {
|
||||
method: 'PATCH',
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
body: JSON.stringify({ name: editName }),
|
||||
})
|
||||
const data = await res.json()
|
||||
if (!res.ok) { setError(data.error); setSaving(false); return }
|
||||
setEditing(false)
|
||||
onChanged()
|
||||
} catch {
|
||||
setError('Network error.')
|
||||
}
|
||||
setSaving(false)
|
||||
}
|
||||
|
||||
const handleDeleteClick = () => {
|
||||
if (!confirming) {
|
||||
setConfirming(true)
|
||||
cancelRef.current = setTimeout(() => setConfirming(false), 4000)
|
||||
return
|
||||
}
|
||||
if (cancelRef.current) clearTimeout(cancelRef.current)
|
||||
setDeleting(true)
|
||||
const cascade = tags.length > 0
|
||||
fetch(
|
||||
`/api/tags/categories/${encodeURIComponent(category.id)}${cascade ? '?cascade=true' : ''}`,
|
||||
{ method: 'DELETE' }
|
||||
)
|
||||
.then(() => onChanged())
|
||||
.catch(() => setDeleting(false))
|
||||
}
|
||||
|
||||
const handleCancel = () => {
|
||||
if (cancelRef.current) clearTimeout(cancelRef.current)
|
||||
setConfirming(false)
|
||||
}
|
||||
|
||||
return (
|
||||
<div className="py-4 first:pt-0 last:pb-0">
|
||||
{/* Category header */}
|
||||
<div className="flex items-center gap-2 mb-3">
|
||||
{editing ? (
|
||||
<form onSubmit={handleRename} className="flex items-center gap-2 flex-1 min-w-0">
|
||||
<input
|
||||
type="text"
|
||||
value={editName}
|
||||
onChange={(e) => setEditName(e.target.value)}
|
||||
autoFocus
|
||||
required
|
||||
className="flex-1 rounded-lg px-3 py-1.5 text-sm outline-none"
|
||||
style={{
|
||||
backgroundColor: 'var(--background)',
|
||||
border: '1px solid var(--accent)',
|
||||
color: 'var(--text-primary)',
|
||||
}}
|
||||
/>
|
||||
<button
|
||||
type="submit"
|
||||
disabled={saving}
|
||||
className="text-xs px-2.5 py-1.5 rounded-lg transition-colors disabled:opacity-50"
|
||||
style={{ backgroundColor: 'var(--accent)', color: '#fff' }}
|
||||
>
|
||||
{saving ? 'Saving…' : 'Save'}
|
||||
</button>
|
||||
<button
|
||||
type="button"
|
||||
onClick={() => { setEditing(false); setEditName(category.name); setError(null) }}
|
||||
className="text-xs px-2.5 py-1.5 rounded-lg transition-colors"
|
||||
style={{ backgroundColor: 'var(--border)', color: 'var(--text-secondary)' }}
|
||||
>
|
||||
Cancel
|
||||
</button>
|
||||
</form>
|
||||
) : (
|
||||
<>
|
||||
<span className="font-medium text-sm flex-1" style={{ color: 'var(--text-primary)' }}>
|
||||
{category.name}
|
||||
<span className="ml-2 font-normal text-xs" style={{ color: 'var(--text-secondary)' }}>
|
||||
{tags.length} tag{tags.length === 1 ? '' : 's'}
|
||||
</span>
|
||||
</span>
|
||||
<button
|
||||
onClick={() => { setEditing(true); setEditName(category.name) }}
|
||||
className="text-xs px-2.5 py-1.5 rounded-lg 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)')}
|
||||
>
|
||||
Rename
|
||||
</button>
|
||||
{confirming && (
|
||||
<button
|
||||
onClick={handleCancel}
|
||||
className="text-xs px-2.5 py-1.5 rounded-lg transition-colors"
|
||||
style={{ color: 'var(--text-secondary)', backgroundColor: 'var(--border)' }}
|
||||
>
|
||||
Cancel
|
||||
</button>
|
||||
)}
|
||||
<button
|
||||
onClick={handleDeleteClick}
|
||||
disabled={deleting}
|
||||
className="text-xs px-2.5 py-1.5 rounded-lg transition-colors disabled:opacity-50"
|
||||
style={{
|
||||
backgroundColor: confirming ? '#7f1d1d' : 'var(--border)',
|
||||
color: confirming ? '#fca5a5' : 'var(--text-secondary)',
|
||||
}}
|
||||
onMouseEnter={(e) => {
|
||||
if (!confirming) {
|
||||
;(e.currentTarget as HTMLElement).style.backgroundColor = '#7f1d1d'
|
||||
;(e.currentTarget as HTMLElement).style.color = '#fca5a5'
|
||||
}
|
||||
}}
|
||||
onMouseLeave={(e) => {
|
||||
if (!confirming) {
|
||||
;(e.currentTarget as HTMLElement).style.backgroundColor = 'var(--border)'
|
||||
;(e.currentTarget as HTMLElement).style.color = 'var(--text-secondary)'
|
||||
}
|
||||
}}
|
||||
>
|
||||
{deleting
|
||||
? 'Deleting…'
|
||||
: confirming
|
||||
? tags.length > 0
|
||||
? `Confirm? (deletes ${tags.length} tag${tags.length === 1 ? '' : 's'})`
|
||||
: 'Confirm?'
|
||||
: 'Delete'}
|
||||
</button>
|
||||
</>
|
||||
)}
|
||||
</div>
|
||||
|
||||
{error && (
|
||||
<p className="text-xs mb-2 px-3 py-1.5 rounded-lg" style={{ backgroundColor: '#7f1d1d33', color: '#fca5a5' }}>
|
||||
{error}
|
||||
</p>
|
||||
)}
|
||||
|
||||
{/* Tags list */}
|
||||
<div className="flex flex-wrap gap-2 mb-3">
|
||||
{tags.map((tag) => (
|
||||
<TagRow key={tag.id} tag={tag} onChanged={onChanged} />
|
||||
))}
|
||||
{tags.length === 0 && (
|
||||
<p className="text-xs" style={{ color: 'var(--text-secondary)' }}>
|
||||
No tags in this category.
|
||||
</p>
|
||||
)}
|
||||
</div>
|
||||
|
||||
{/* Add tag inline */}
|
||||
<AddTagForm categoryId={category.id} onAdded={onChanged} />
|
||||
</div>
|
||||
)
|
||||
}
|
||||
|
||||
// ─── Tag Row ──────────────────────────────────────────────────────────────────
|
||||
|
||||
function TagRow({ tag, onChanged }: { tag: Tag; onChanged: () => void }) {
|
||||
const [editing, setEditing] = useState(false)
|
||||
const [editName, setEditName] = useState(tag.name)
|
||||
const [saving, setSaving] = useState(false)
|
||||
const [confirming, setConfirming] = useState(false)
|
||||
const [deleting, setDeleting] = useState(false)
|
||||
const cancelRef = useRef<ReturnType<typeof setTimeout> | null>(null)
|
||||
|
||||
const handleRename = async (e: React.FormEvent) => {
|
||||
e.preventDefault()
|
||||
setSaving(true)
|
||||
const res = await fetch(`/api/tags/items/${encodeURIComponent(tag.id)}`, {
|
||||
method: 'PATCH',
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
body: JSON.stringify({ name: editName }),
|
||||
})
|
||||
setSaving(false)
|
||||
if (res.ok) { setEditing(false); onChanged() }
|
||||
}
|
||||
|
||||
const handleDeleteClick = () => {
|
||||
if (!confirming) {
|
||||
setConfirming(true)
|
||||
cancelRef.current = setTimeout(() => setConfirming(false), 4000)
|
||||
return
|
||||
}
|
||||
if (cancelRef.current) clearTimeout(cancelRef.current)
|
||||
setDeleting(true)
|
||||
fetch(`/api/tags/items/${encodeURIComponent(tag.id)}`, { method: 'DELETE' })
|
||||
.then(() => onChanged())
|
||||
.catch(() => setDeleting(false))
|
||||
}
|
||||
|
||||
if (editing) {
|
||||
return (
|
||||
<form onSubmit={handleRename} className="flex items-center gap-1.5">
|
||||
<input
|
||||
type="text"
|
||||
value={editName}
|
||||
onChange={(e) => setEditName(e.target.value)}
|
||||
autoFocus
|
||||
required
|
||||
className="rounded-lg px-2 py-1 text-xs outline-none"
|
||||
style={{
|
||||
backgroundColor: 'var(--background)',
|
||||
border: '1px solid var(--accent)',
|
||||
color: 'var(--text-primary)',
|
||||
width: 120,
|
||||
}}
|
||||
/>
|
||||
<button
|
||||
type="submit"
|
||||
disabled={saving}
|
||||
className="text-xs px-2 py-1 rounded-lg disabled:opacity-50"
|
||||
style={{ backgroundColor: 'var(--accent)', color: '#fff' }}
|
||||
>
|
||||
{saving ? '…' : 'Save'}
|
||||
</button>
|
||||
<button
|
||||
type="button"
|
||||
onClick={() => { setEditing(false); setEditName(tag.name) }}
|
||||
className="text-xs px-2 py-1 rounded-lg"
|
||||
style={{ backgroundColor: 'var(--border)', color: 'var(--text-secondary)' }}
|
||||
>
|
||||
✕
|
||||
</button>
|
||||
</form>
|
||||
)
|
||||
}
|
||||
|
||||
return (
|
||||
<span
|
||||
className="inline-flex items-center gap-1 px-2 py-1 rounded-full text-xs"
|
||||
style={{ backgroundColor: 'var(--border)', color: 'var(--text-primary)' }}
|
||||
>
|
||||
{tag.name}
|
||||
<button
|
||||
onClick={() => { setEditing(true); setEditName(tag.name) }}
|
||||
className="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)')}
|
||||
title="Rename"
|
||||
>
|
||||
✎
|
||||
</button>
|
||||
<button
|
||||
onClick={handleDeleteClick}
|
||||
disabled={deleting}
|
||||
className="transition-colors disabled:opacity-50"
|
||||
style={{ color: confirming ? '#fca5a5' : 'var(--text-secondary)' }}
|
||||
onMouseEnter={(e) => ((e.currentTarget as HTMLElement).style.color = '#fca5a5')}
|
||||
onMouseLeave={(e) => ((e.currentTarget as HTMLElement).style.color = confirming ? '#fca5a5' : 'var(--text-secondary)')}
|
||||
title={confirming ? 'Click again to confirm delete' : 'Delete'}
|
||||
>
|
||||
{deleting ? '…' : '✕'}
|
||||
</button>
|
||||
</span>
|
||||
)
|
||||
}
|
||||
|
||||
// ─── Add Tag Form ─────────────────────────────────────────────────────────────
|
||||
|
||||
function AddTagForm({ categoryId, onAdded }: { categoryId: string; onAdded: () => void }) {
|
||||
const [name, setName] = useState('')
|
||||
const [submitting, setSubmitting] = useState(false)
|
||||
const [error, setError] = useState<string | null>(null)
|
||||
|
||||
const handleSubmit = async (e: React.FormEvent) => {
|
||||
e.preventDefault()
|
||||
setError(null)
|
||||
setSubmitting(true)
|
||||
try {
|
||||
const res = await fetch('/api/tags/items', {
|
||||
method: 'POST',
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
body: JSON.stringify({ name, categoryId }),
|
||||
})
|
||||
const data = await res.json()
|
||||
if (!res.ok) { setError(data.error); setSubmitting(false); return }
|
||||
setName('')
|
||||
onAdded()
|
||||
} catch {
|
||||
setError('Network error.')
|
||||
}
|
||||
setSubmitting(false)
|
||||
}
|
||||
|
||||
return (
|
||||
<form onSubmit={handleSubmit} className="flex items-center gap-2">
|
||||
<input
|
||||
type="text"
|
||||
value={name}
|
||||
onChange={(e) => setName(e.target.value)}
|
||||
placeholder="New tag name…"
|
||||
required
|
||||
className="rounded-lg px-3 py-1.5 text-xs outline-none"
|
||||
style={{
|
||||
backgroundColor: 'var(--background)',
|
||||
border: '1px solid var(--border)',
|
||||
color: 'var(--text-primary)',
|
||||
width: 160,
|
||||
}}
|
||||
onFocus={(e) => ((e.currentTarget as HTMLElement).style.borderColor = 'var(--accent)')}
|
||||
onBlur={(e) => ((e.currentTarget as HTMLElement).style.borderColor = 'var(--border)')}
|
||||
/>
|
||||
<button
|
||||
type="submit"
|
||||
disabled={submitting}
|
||||
className="text-xs px-2.5 py-1.5 rounded-lg transition-colors disabled:opacity-50"
|
||||
style={{ backgroundColor: 'var(--accent)', color: '#fff' }}
|
||||
>
|
||||
{submitting ? 'Adding…' : '+ Add Tag'}
|
||||
</button>
|
||||
{error && <span className="text-xs" style={{ color: '#fca5a5' }}>{error}</span>}
|
||||
</form>
|
||||
)
|
||||
}
|
||||
|
||||
// ─── Add Category Form ────────────────────────────────────────────────────────
|
||||
|
||||
function AddCategoryForm({ onAdded }: { onAdded: () => void }) {
|
||||
const [name, setName] = useState('')
|
||||
const [submitting, setSubmitting] = useState(false)
|
||||
const [error, setError] = useState<string | null>(null)
|
||||
|
||||
const handleSubmit = async (e: React.FormEvent) => {
|
||||
e.preventDefault()
|
||||
setError(null)
|
||||
setSubmitting(true)
|
||||
try {
|
||||
const res = await fetch('/api/tags/categories', {
|
||||
method: 'POST',
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
body: JSON.stringify({ name }),
|
||||
})
|
||||
const data = await res.json()
|
||||
if (!res.ok) { setError(data.error); setSubmitting(false); return }
|
||||
setName('')
|
||||
onAdded()
|
||||
} catch {
|
||||
setError('Network error.')
|
||||
}
|
||||
setSubmitting(false)
|
||||
}
|
||||
|
||||
return (
|
||||
<form onSubmit={handleSubmit} className="flex flex-col gap-4">
|
||||
<Field label="Category Name">
|
||||
<input
|
||||
type="text"
|
||||
value={name}
|
||||
onChange={(e) => setName(e.target.value)}
|
||||
placeholder="e.g. Genre"
|
||||
required
|
||||
className="w-full rounded-lg px-3 py-2 text-sm outline-none"
|
||||
style={{
|
||||
backgroundColor: 'var(--background)',
|
||||
border: '1px solid var(--border)',
|
||||
color: 'var(--text-primary)',
|
||||
}}
|
||||
onFocus={(e) => ((e.currentTarget as HTMLElement).style.borderColor = 'var(--accent)')}
|
||||
onBlur={(e) => ((e.currentTarget as HTMLElement).style.borderColor = 'var(--border)')}
|
||||
/>
|
||||
</Field>
|
||||
|
||||
{error && (
|
||||
<p className="text-sm rounded-lg px-3 py-2" style={{ backgroundColor: '#7f1d1d33', color: '#fca5a5' }}>
|
||||
{error}
|
||||
</p>
|
||||
)}
|
||||
|
||||
<div>
|
||||
<button
|
||||
type="submit"
|
||||
disabled={submitting}
|
||||
className="px-4 py-2 rounded-lg text-sm font-medium transition-colors disabled:opacity-50"
|
||||
style={{ backgroundColor: 'var(--accent)', color: '#fff' }}
|
||||
onMouseEnter={(e) => {
|
||||
if (!submitting) (e.currentTarget as HTMLElement).style.backgroundColor = 'var(--accent-hover)'
|
||||
}}
|
||||
onMouseLeave={(e) => {
|
||||
(e.currentTarget as HTMLElement).style.backgroundColor = 'var(--accent)'
|
||||
}}
|
||||
>
|
||||
{submitting ? 'Adding…' : 'Add Category'}
|
||||
</button>
|
||||
</div>
|
||||
</form>
|
||||
)
|
||||
}
|
||||
|
||||
// ─── Shared helpers ───────────────────────────────────────────────────────────
|
||||
|
||||
function Section({ title, children }: { title: string; children: React.ReactNode }) {
|
||||
return (
|
||||
<div className="mb-10">
|
||||
<h2
|
||||
className="text-xs font-semibold uppercase tracking-wider mb-3"
|
||||
style={{ color: 'var(--text-secondary)' }}
|
||||
>
|
||||
{title}
|
||||
</h2>
|
||||
<div
|
||||
className="rounded-xl border"
|
||||
style={{ borderColor: 'var(--border)', backgroundColor: 'var(--surface)' }}
|
||||
>
|
||||
<div className="px-5 py-4">{children}</div>
|
||||
</div>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
|
||||
function Field({ label, children }: { label: string; children: React.ReactNode }) {
|
||||
return (
|
||||
<div className="flex flex-col gap-1.5">
|
||||
<label className="text-xs font-medium" style={{ color: 'var(--text-secondary)' }}>
|
||||
{label}
|
||||
</label>
|
||||
{children}
|
||||
</div>
|
||||
)
|
||||
}
|
||||
|
||||
function LoadingRows() {
|
||||
return (
|
||||
<div className="flex flex-col gap-3">
|
||||
{[70, 50, 85].map((w) => (
|
||||
<div key={w} className="flex items-center gap-3">
|
||||
<div
|
||||
className="h-4 rounded animate-pulse"
|
||||
style={{ width: `${w}%`, backgroundColor: 'var(--border)' }}
|
||||
/>
|
||||
</div>
|
||||
))}
|
||||
</div>
|
||||
)
|
||||
}
|
||||
42
src/components/ManageSubNav.tsx
Normal file
42
src/components/ManageSubNav.tsx
Normal 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>
|
||||
)
|
||||
}
|
||||
@@ -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>
|
||||
|
||||
@@ -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>
|
||||
)
|
||||
}
|
||||
|
||||
33
src/components/tags/TagBadge.tsx
Normal file
33
src/components/tags/TagBadge.tsx
Normal 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>
|
||||
)
|
||||
}
|
||||
162
src/components/tags/TagSelector.tsx
Normal file
162
src/components/tags/TagSelector.tsx
Normal 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>
|
||||
)
|
||||
}
|
||||
229
src/lib/tags.ts
Normal file
229
src/lib/tags.ts
Normal file
@@ -0,0 +1,229 @@
|
||||
import path from 'path'
|
||||
import Database from 'better-sqlite3'
|
||||
import type { Tag, TagCategory } from '@/types'
|
||||
|
||||
const DB_PATH = path.resolve(process.cwd(), 'medialore.db')
|
||||
|
||||
let _db: Database.Database | null = null
|
||||
|
||||
function getDb(): Database.Database {
|
||||
if (_db) return _db
|
||||
_db = new Database(DB_PATH)
|
||||
_db.pragma('journal_mode = WAL')
|
||||
_db.pragma('foreign_keys = ON')
|
||||
initDb(_db)
|
||||
return _db
|
||||
}
|
||||
|
||||
function initDb(db: Database.Database): void {
|
||||
db.exec(`
|
||||
CREATE TABLE IF NOT EXISTS tag_categories (
|
||||
id TEXT PRIMARY KEY,
|
||||
name TEXT NOT NULL UNIQUE
|
||||
);
|
||||
|
||||
CREATE TABLE IF NOT EXISTS tags (
|
||||
id TEXT PRIMARY KEY,
|
||||
name TEXT NOT NULL,
|
||||
category_id TEXT NOT NULL REFERENCES tag_categories(id) ON DELETE CASCADE
|
||||
);
|
||||
|
||||
CREATE UNIQUE INDEX IF NOT EXISTS tags_name_category ON tags(name, category_id);
|
||||
|
||||
CREATE TABLE IF NOT EXISTS media_tags (
|
||||
media_key TEXT NOT NULL,
|
||||
tag_id TEXT NOT NULL REFERENCES tags(id) ON DELETE CASCADE,
|
||||
PRIMARY KEY (media_key, tag_id)
|
||||
);
|
||||
`)
|
||||
}
|
||||
|
||||
function slugify(name: string): string {
|
||||
return name
|
||||
.toLowerCase()
|
||||
.trim()
|
||||
.replace(/[^a-z0-9\s-]/g, '')
|
||||
.replace(/\s+/g, '-')
|
||||
.replace(/-+/g, '-')
|
||||
.replace(/^-|-$/g, '')
|
||||
}
|
||||
|
||||
// ─── Categories ───────────────────────────────────────────────────────────────
|
||||
|
||||
export function getCategories(): TagCategory[] {
|
||||
const db = getDb()
|
||||
return db.prepare('SELECT id, name FROM tag_categories ORDER BY name').all() as TagCategory[]
|
||||
}
|
||||
|
||||
export function addCategory(name: string): TagCategory {
|
||||
const trimmed = name.trim()
|
||||
if (!trimmed) throw new Error('Category name is required.')
|
||||
|
||||
const db = getDb()
|
||||
const baseId = slugify(trimmed) || 'category'
|
||||
let id = baseId
|
||||
let suffix = 2
|
||||
while (db.prepare('SELECT 1 FROM tag_categories WHERE id = ?').get(id)) {
|
||||
id = `${baseId}-${suffix++}`
|
||||
}
|
||||
|
||||
try {
|
||||
db.prepare('INSERT INTO tag_categories (id, name) VALUES (?, ?)').run(id, trimmed)
|
||||
} catch {
|
||||
throw new Error(`A category named "${trimmed}" already exists.`)
|
||||
}
|
||||
|
||||
return { id, name: trimmed }
|
||||
}
|
||||
|
||||
export function updateCategory(id: string, name: string): TagCategory {
|
||||
const trimmed = name.trim()
|
||||
if (!trimmed) throw new Error('Category name is required.')
|
||||
|
||||
const db = getDb()
|
||||
try {
|
||||
const result = db.prepare('UPDATE tag_categories SET name = ? WHERE id = ?').run(trimmed, id)
|
||||
if (result.changes === 0) throw new Error(`Category not found: ${id}`)
|
||||
} catch (err) {
|
||||
const msg = (err as Error).message
|
||||
if (msg.includes('UNIQUE')) throw new Error(`A category named "${trimmed}" already exists.`)
|
||||
throw err
|
||||
}
|
||||
|
||||
return { id, name: trimmed }
|
||||
}
|
||||
|
||||
export function deleteCategory(id: string): void {
|
||||
const db = getDb()
|
||||
const tagCount = (
|
||||
db.prepare('SELECT COUNT(*) as count FROM tags WHERE category_id = ?').get(id) as { count: number }
|
||||
).count
|
||||
|
||||
if (tagCount > 0) {
|
||||
throw new Error(
|
||||
`Category has ${tagCount} tag${tagCount === 1 ? '' : 's'}. Delete all tags first or use force delete.`
|
||||
)
|
||||
}
|
||||
|
||||
const result = db.prepare('DELETE FROM tag_categories WHERE id = ?').run(id)
|
||||
if (result.changes === 0) throw new Error(`Category not found: ${id}`)
|
||||
}
|
||||
|
||||
export function deleteCategoryForce(id: string): void {
|
||||
const db = getDb()
|
||||
// CASCADE on tags will also cascade to media_tags
|
||||
const result = db.prepare('DELETE FROM tag_categories WHERE id = ?').run(id)
|
||||
if (result.changes === 0) throw new Error(`Category not found: ${id}`)
|
||||
}
|
||||
|
||||
// ─── Tags ─────────────────────────────────────────────────────────────────────
|
||||
|
||||
export function getTags(categoryId?: string): Tag[] {
|
||||
const db = getDb()
|
||||
if (categoryId) {
|
||||
return db
|
||||
.prepare('SELECT id, name, category_id as categoryId FROM tags WHERE category_id = ? ORDER BY name')
|
||||
.all(categoryId) as Tag[]
|
||||
}
|
||||
return db
|
||||
.prepare('SELECT id, name, category_id as categoryId FROM tags ORDER BY name')
|
||||
.all() as Tag[]
|
||||
}
|
||||
|
||||
export function addTag(name: string, categoryId: string): Tag {
|
||||
const trimmed = name.trim()
|
||||
if (!trimmed) throw new Error('Tag name is required.')
|
||||
|
||||
const db = getDb()
|
||||
|
||||
const category = db.prepare('SELECT 1 FROM tag_categories WHERE id = ?').get(categoryId)
|
||||
if (!category) throw new Error(`Category not found: ${categoryId}`)
|
||||
|
||||
const baseId = `tag-${slugify(trimmed) || 'tag'}`
|
||||
let id = baseId
|
||||
let suffix = 2
|
||||
while (db.prepare('SELECT 1 FROM tags WHERE id = ?').get(id)) {
|
||||
id = `${baseId}-${suffix++}`
|
||||
}
|
||||
|
||||
try {
|
||||
db.prepare('INSERT INTO tags (id, name, category_id) VALUES (?, ?, ?)').run(id, trimmed, categoryId)
|
||||
} catch {
|
||||
throw new Error(`A tag named "${trimmed}" already exists in this category.`)
|
||||
}
|
||||
|
||||
return { id, name: trimmed, categoryId }
|
||||
}
|
||||
|
||||
export function updateTag(id: string, name: string): Tag {
|
||||
const trimmed = name.trim()
|
||||
if (!trimmed) throw new Error('Tag name is required.')
|
||||
|
||||
const db = getDb()
|
||||
|
||||
const existing = db
|
||||
.prepare('SELECT id, name, category_id as categoryId FROM tags WHERE id = ?')
|
||||
.get(id) as Tag | undefined
|
||||
if (!existing) throw new Error(`Tag not found: ${id}`)
|
||||
|
||||
try {
|
||||
db.prepare('UPDATE tags SET name = ? WHERE id = ?').run(trimmed, id)
|
||||
} catch {
|
||||
throw new Error(`A tag named "${trimmed}" already exists in this category.`)
|
||||
}
|
||||
|
||||
return { id, name: trimmed, categoryId: existing.categoryId }
|
||||
}
|
||||
|
||||
export function deleteTag(id: string): void {
|
||||
const db = getDb()
|
||||
// CASCADE removes media_tags rows automatically
|
||||
const result = db.prepare('DELETE FROM tags WHERE id = ?').run(id)
|
||||
if (result.changes === 0) throw new Error(`Tag not found: ${id}`)
|
||||
}
|
||||
|
||||
// ─── Assignments ──────────────────────────────────────────────────────────────
|
||||
|
||||
export function addTagToItem(mediaKey: string, tagId: string): void {
|
||||
const db = getDb()
|
||||
const tag = db.prepare('SELECT 1 FROM tags WHERE id = ?').get(tagId)
|
||||
if (!tag) throw new Error(`Tag not found: ${tagId}`)
|
||||
// INSERT OR IGNORE handles duplicate gracefully
|
||||
db.prepare('INSERT OR IGNORE INTO media_tags (media_key, tag_id) VALUES (?, ?)').run(mediaKey, tagId)
|
||||
}
|
||||
|
||||
export function removeTagFromItem(mediaKey: string, tagId: string): void {
|
||||
const db = getDb()
|
||||
db.prepare('DELETE FROM media_tags WHERE media_key = ? AND tag_id = ?').run(mediaKey, tagId)
|
||||
}
|
||||
|
||||
export function getResolvedTagsForItem(mediaKey: string): { tags: Tag[]; categories: TagCategory[] } {
|
||||
const db = getDb()
|
||||
|
||||
const tags = db
|
||||
.prepare(
|
||||
`SELECT t.id, t.name, t.category_id as categoryId
|
||||
FROM tags t
|
||||
JOIN media_tags mt ON mt.tag_id = t.id
|
||||
WHERE mt.media_key = ?
|
||||
ORDER BY t.name`
|
||||
)
|
||||
.all(mediaKey) as Tag[]
|
||||
|
||||
const categoryIds = [...new Set(tags.map((t) => t.categoryId))]
|
||||
const categories: TagCategory[] =
|
||||
categoryIds.length > 0
|
||||
? (db
|
||||
.prepare(
|
||||
`SELECT id, name FROM tag_categories WHERE id IN (${categoryIds.map(() => '?').join(',')}) ORDER BY name`
|
||||
)
|
||||
.all(...categoryIds) as TagCategory[])
|
||||
: []
|
||||
|
||||
return { tags, categories }
|
||||
}
|
||||
|
||||
export function removeAllAssignmentsForLibrary(libraryId: string): void {
|
||||
const db = getDb()
|
||||
db.prepare("DELETE FROM media_tags WHERE media_key LIKE ?").run(`${libraryId}:%`)
|
||||
}
|
||||
@@ -29,3 +29,14 @@ export interface DirectoryListing {
|
||||
path: string
|
||||
entries: FileEntry[]
|
||||
}
|
||||
|
||||
export interface TagCategory {
|
||||
id: string
|
||||
name: string
|
||||
}
|
||||
|
||||
export interface Tag {
|
||||
id: string
|
||||
name: string
|
||||
categoryId: string
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user