Story Collections Feature

This commit is contained in:
Stefan Hardegger
2025-07-25 14:15:23 +02:00
parent 9dd8855914
commit 312093ae2e
42 changed files with 5398 additions and 45 deletions

View File

@@ -0,0 +1,142 @@
'use client';
import { useState, useEffect } from 'react';
import { useParams, useRouter } from 'next/navigation';
import { collectionApi } from '../../../../lib/api';
import { Collection } from '../../../../types/api';
import AppLayout from '../../../../components/layout/AppLayout';
import CollectionForm from '../../../../components/collections/CollectionForm';
import LoadingSpinner from '../../../../components/ui/LoadingSpinner';
export default function EditCollectionPage() {
const params = useParams();
const router = useRouter();
const collectionId = params.id as string;
const [collection, setCollection] = useState<Collection | null>(null);
const [loading, setLoading] = useState(true);
const [saving, setSaving] = useState(false);
const [error, setError] = useState<string | null>(null);
useEffect(() => {
const loadCollection = async () => {
try {
setLoading(true);
setError(null);
const data = await collectionApi.getCollection(collectionId);
setCollection(data);
} catch (err: any) {
console.error('Failed to load collection:', err);
setError(err.response?.data?.message || 'Failed to load collection');
} finally {
setLoading(false);
}
};
if (collectionId) {
loadCollection();
}
}, [collectionId]);
const handleSubmit = async (formData: {
name: string;
description?: string;
tags?: string[];
storyIds?: string[];
coverImage?: File;
}) => {
if (!collection) return;
try {
setSaving(true);
setError(null);
// Update basic info
await collectionApi.updateCollection(collection.id, {
name: formData.name,
description: formData.description,
tagNames: formData.tags,
});
// Upload cover image if provided
if (formData.coverImage) {
await collectionApi.uploadCover(collection.id, formData.coverImage);
}
// Redirect back to collection detail
router.push(`/collections/${collection.id}`);
} catch (err: any) {
console.error('Failed to update collection:', err);
setError(err.response?.data?.message || 'Failed to update collection');
} finally {
setSaving(false);
}
};
const handleCancel = () => {
router.push(`/collections/${collectionId}`);
};
if (loading) {
return (
<AppLayout>
<div className="flex items-center justify-center py-20">
<LoadingSpinner size="lg" />
</div>
</AppLayout>
);
}
if (error || !collection) {
return (
<AppLayout>
<div className="text-center py-20">
<div className="text-red-600 text-lg mb-4">
{error || 'Collection not found'}
</div>
<button
onClick={() => router.push('/collections')}
className="theme-accent hover:underline"
>
Back to Collections
</button>
</div>
</AppLayout>
);
}
const initialData = {
name: collection.name,
description: collection.description,
tags: collection.tags?.map(tag => tag.name) || [],
storyIds: collection.collectionStories?.map(cs => cs.story.id) || [],
coverImagePath: collection.coverImagePath,
};
return (
<AppLayout>
<div className="max-w-2xl mx-auto">
<div className="mb-6">
<h1 className="text-3xl font-bold theme-header">Edit Collection</h1>
<p className="theme-text mt-2">
Update your collection details and organization.
</p>
</div>
{error && (
<div className="mb-6 p-4 bg-red-100 border border-red-300 text-red-700 rounded-lg">
{error}
</div>
)}
<CollectionForm
initialData={initialData}
onSubmit={handleSubmit}
onCancel={handleCancel}
loading={saving}
submitLabel="Update Collection"
/>
</div>
</AppLayout>
);
}

View File

@@ -0,0 +1,85 @@
'use client';
import { useState, useEffect } from 'react';
import { useParams, useRouter } from 'next/navigation';
import { collectionApi } from '../../../lib/api';
import { Collection } from '../../../types/api';
import AppLayout from '../../../components/layout/AppLayout';
import CollectionDetailView from '../../../components/collections/CollectionDetailView';
import LoadingSpinner from '../../../components/ui/LoadingSpinner';
export default function CollectionDetailPage() {
const params = useParams();
const router = useRouter();
const collectionId = params.id as string;
const [collection, setCollection] = useState<Collection | null>(null);
const [loading, setLoading] = useState(true);
const [error, setError] = useState<string | null>(null);
const loadCollection = async () => {
try {
setLoading(true);
setError(null);
const data = await collectionApi.getCollection(collectionId);
setCollection(data);
} catch (err: any) {
console.error('Failed to load collection:', err);
setError(err.response?.data?.message || 'Failed to load collection');
} finally {
setLoading(false);
}
};
useEffect(() => {
if (collectionId) {
loadCollection();
}
}, [collectionId]);
const handleCollectionUpdate = () => {
loadCollection();
};
const handleCollectionDelete = () => {
router.push('/collections');
};
if (loading) {
return (
<AppLayout>
<div className="flex items-center justify-center py-20">
<LoadingSpinner size="lg" />
</div>
</AppLayout>
);
}
if (error || !collection) {
return (
<AppLayout>
<div className="text-center py-20">
<div className="text-red-600 text-lg mb-4">
{error || 'Collection not found'}
</div>
<button
onClick={() => router.push('/collections')}
className="theme-accent hover:underline"
>
Back to Collections
</button>
</div>
</AppLayout>
);
}
return (
<AppLayout>
<CollectionDetailView
collection={collection}
onUpdate={handleCollectionUpdate}
onDelete={handleCollectionDelete}
/>
</AppLayout>
);
}

View File

@@ -0,0 +1,82 @@
'use client';
import { useState, useEffect } from 'react';
import { useParams, useRouter } from 'next/navigation';
import { collectionApi } from '../../../../../lib/api';
import { StoryWithCollectionContext } from '../../../../../types/api';
import AppLayout from '../../../../../components/layout/AppLayout';
import CollectionReadingView from '../../../../../components/collections/CollectionReadingView';
import LoadingSpinner from '../../../../../components/ui/LoadingSpinner';
export default function CollectionReadingPage() {
const params = useParams();
const router = useRouter();
const collectionId = params.id as string;
const storyId = params.storyId as string;
const [data, setData] = useState<StoryWithCollectionContext | null>(null);
const [loading, setLoading] = useState(true);
const [error, setError] = useState<string | null>(null);
useEffect(() => {
const loadStoryWithContext = async () => {
if (!collectionId || !storyId) return;
try {
setLoading(true);
setError(null);
const result = await collectionApi.getStoryWithCollectionContext(collectionId, storyId);
setData(result);
} catch (err: any) {
console.error('Failed to load story with collection context:', err);
setError(err.response?.data?.message || 'Failed to load story');
} finally {
setLoading(false);
}
};
loadStoryWithContext();
}, [collectionId, storyId]);
const handleNavigate = (newStoryId: string) => {
router.push(`/collections/${collectionId}/read/${newStoryId}`);
};
if (loading) {
return (
<AppLayout>
<div className="flex items-center justify-center py-20">
<LoadingSpinner size="lg" />
</div>
</AppLayout>
);
}
if (error || !data) {
return (
<AppLayout>
<div className="text-center py-20">
<div className="text-red-600 text-lg mb-4">
{error || 'Story not found'}
</div>
<button
onClick={() => router.push(`/collections/${collectionId}`)}
className="theme-accent hover:underline"
>
Back to Collection
</button>
</div>
</AppLayout>
);
}
return (
<AppLayout>
<CollectionReadingView
data={data}
onNavigate={handleNavigate}
onBackToCollection={() => router.push(`/collections/${collectionId}`)}
/>
</AppLayout>
);
}

View File

@@ -0,0 +1,84 @@
'use client';
import { useState } from 'react';
import { useRouter } from 'next/navigation';
import { collectionApi } from '../../../lib/api';
import AppLayout from '../../../components/layout/AppLayout';
import CollectionForm from '../../../components/collections/CollectionForm';
import { Collection } from '../../../types/api';
export default function NewCollectionPage() {
const [loading, setLoading] = useState(false);
const [error, setError] = useState<string | null>(null);
const router = useRouter();
const handleSubmit = async (formData: {
name: string;
description?: string;
tags?: string[];
storyIds?: string[];
coverImage?: File;
}) => {
try {
setLoading(true);
setError(null);
let collection: Collection;
if (formData.coverImage) {
collection = await collectionApi.createCollectionWithImage({
name: formData.name,
description: formData.description,
tags: formData.tags,
storyIds: formData.storyIds,
coverImage: formData.coverImage,
});
} else {
collection = await collectionApi.createCollection({
name: formData.name,
description: formData.description,
tagNames: formData.tags,
storyIds: formData.storyIds,
});
}
// Redirect to the new collection's detail page
router.push(`/collections/${collection.id}`);
} catch (err: any) {
console.error('Failed to create collection:', err);
setError(err.response?.data?.message || 'Failed to create collection');
} finally {
setLoading(false);
}
};
const handleCancel = () => {
router.push('/collections');
};
return (
<AppLayout>
<div className="max-w-2xl mx-auto">
<div className="mb-6">
<h1 className="text-3xl font-bold theme-header">Create New Collection</h1>
<p className="theme-text mt-2">
Organize your stories into a curated collection for better reading experience.
</p>
</div>
{error && (
<div className="mb-6 p-4 bg-red-100 border border-red-300 text-red-700 rounded-lg">
{error}
</div>
)}
<CollectionForm
onSubmit={handleSubmit}
onCancel={handleCancel}
loading={loading}
submitLabel="Create Collection"
/>
</div>
</AppLayout>
);
}

View File

@@ -0,0 +1,286 @@
'use client';
import { useState, useEffect } from 'react';
import { collectionApi, tagApi } from '../../lib/api';
import { Collection, Tag } from '../../types/api';
import AppLayout from '../../components/layout/AppLayout';
import { Input } from '../../components/ui/Input';
import Button from '../../components/ui/Button';
import CollectionGrid from '../../components/collections/CollectionGrid';
import TagFilter from '../../components/stories/TagFilter';
import LoadingSpinner from '../../components/ui/LoadingSpinner';
type ViewMode = 'grid' | 'list';
export default function CollectionsPage() {
const [collections, setCollections] = useState<Collection[]>([]);
const [tags, setTags] = useState<Tag[]>([]);
const [loading, setLoading] = useState(false);
const [searchQuery, setSearchQuery] = useState('');
const [selectedTags, setSelectedTags] = useState<string[]>([]);
const [viewMode, setViewMode] = useState<ViewMode>('grid');
const [showArchived, setShowArchived] = useState(false);
const [page, setPage] = useState(0);
const [pageSize, setPageSize] = useState(20);
const [totalPages, setTotalPages] = useState(1);
const [totalCollections, setTotalCollections] = useState(0);
const [refreshTrigger, setRefreshTrigger] = useState(0);
// Load tags for filtering
useEffect(() => {
const loadTags = async () => {
try {
const tagsResult = await tagApi.getTags({ page: 0, size: 1000 });
setTags(tagsResult?.content || []);
} catch (error) {
console.error('Failed to load tags:', error);
}
};
loadTags();
}, []);
// Load collections with search and filters
useEffect(() => {
const debounceTimer = setTimeout(() => {
const loadCollections = async () => {
try {
setLoading(true);
const result = await collectionApi.getCollections({
page: page,
limit: pageSize,
search: searchQuery.trim() || undefined,
tags: selectedTags.length > 0 ? selectedTags : undefined,
archived: showArchived,
});
setCollections(result?.results || []);
setTotalPages(Math.ceil((result?.totalHits || 0) / pageSize));
setTotalCollections(result?.totalHits || 0);
} catch (error) {
console.error('Failed to load collections:', error);
setCollections([]);
} finally {
setLoading(false);
}
};
loadCollections();
}, searchQuery ? 300 : 0); // Debounce search, but not other changes
return () => clearTimeout(debounceTimer);
}, [searchQuery, selectedTags, page, pageSize, showArchived, refreshTrigger]);
// Reset page when search or filters change
const resetPage = () => {
if (page !== 0) {
setPage(0);
}
};
const handleTagToggle = (tagName: string) => {
setSelectedTags(prev => {
const newTags = prev.includes(tagName)
? prev.filter(t => t !== tagName)
: [...prev, tagName];
resetPage();
return newTags;
});
};
const handleSearchChange = (e: React.ChangeEvent<HTMLInputElement>) => {
setSearchQuery(e.target.value);
resetPage();
};
const handlePageSizeChange = (newSize: number) => {
setPageSize(newSize);
resetPage();
};
const clearFilters = () => {
setSearchQuery('');
setSelectedTags([]);
setShowArchived(false);
resetPage();
};
const handleCollectionUpdate = () => {
// Trigger reload by incrementing refresh trigger
setRefreshTrigger(prev => prev + 1);
};
if (loading && collections.length === 0) {
return (
<AppLayout>
<div className="flex items-center justify-center py-20">
<LoadingSpinner size="lg" />
</div>
</AppLayout>
);
}
return (
<AppLayout>
<div className="space-y-6">
{/* Header */}
<div className="flex flex-col sm:flex-row sm:items-center sm:justify-between gap-4">
<div>
<h1 className="text-3xl font-bold theme-header">Collections</h1>
<p className="theme-text mt-1">
{totalCollections} {totalCollections === 1 ? 'collection' : 'collections'}
{searchQuery || selectedTags.length > 0 || showArchived ? ` found` : ` total`}
</p>
</div>
<Button href="/collections/new">
Create New Collection
</Button>
</div>
{/* Search and Filters */}
<div className="space-y-4">
{/* Search Bar */}
<div className="flex flex-col sm:flex-row gap-4">
<div className="flex-1">
<Input
type="search"
placeholder="Search collections by name or description..."
value={searchQuery}
onChange={handleSearchChange}
className="w-full"
/>
</div>
{/* View Mode Toggle */}
<div className="flex items-center gap-2">
<button
onClick={() => setViewMode('grid')}
className={`p-2 rounded-lg transition-colors ${
viewMode === 'grid'
? 'theme-accent-bg text-white'
: 'theme-card theme-text hover:bg-opacity-80'
}`}
aria-label="Grid view"
>
</button>
<button
onClick={() => setViewMode('list')}
className={`p-2 rounded-lg transition-colors ${
viewMode === 'list'
? 'theme-accent-bg text-white'
: 'theme-card theme-text hover:bg-opacity-80'
}`}
aria-label="List view"
>
</button>
</div>
</div>
{/* Filters and Controls */}
<div className="flex flex-col sm:flex-row gap-4 items-start sm:items-center">
{/* Page Size Selector */}
<div className="flex items-center gap-2">
<label className="theme-text font-medium text-sm">Show:</label>
<select
value={pageSize}
onChange={(e) => handlePageSizeChange(Number(e.target.value))}
className="px-3 py-1 rounded-lg theme-card theme-text theme-border border focus:outline-none focus:ring-2 focus:ring-theme-accent"
>
<option value={10}>10</option>
<option value={20}>20</option>
<option value={50}>50</option>
</select>
</div>
{/* Archive Toggle */}
<label className="flex items-center gap-2 cursor-pointer">
<input
type="checkbox"
checked={showArchived}
onChange={(e) => {
setShowArchived(e.target.checked);
resetPage();
}}
className="rounded border-gray-300 text-blue-600 focus:ring-blue-500"
/>
<span className="theme-text text-sm">Show archived</span>
</label>
{/* Clear Filters */}
{(searchQuery || selectedTags.length > 0 || showArchived) && (
<Button variant="ghost" size="sm" onClick={clearFilters}>
Clear Filters
</Button>
)}
</div>
{/* Tag Filter */}
<TagFilter
tags={tags}
selectedTags={selectedTags}
onTagToggle={handleTagToggle}
/>
</div>
{/* Collections Display */}
<CollectionGrid
collections={collections}
viewMode={viewMode}
onUpdate={handleCollectionUpdate}
/>
{/* Pagination */}
{totalPages > 1 && (
<div className="flex justify-center items-center gap-4 mt-8">
<Button
variant="ghost"
onClick={() => setPage(page - 1)}
disabled={page === 0}
>
Previous
</Button>
<div className="flex items-center gap-2">
<span className="theme-text text-sm">Page</span>
<input
type="number"
min={1}
max={totalPages}
value={page + 1}
onChange={(e) => {
const newPage = Math.max(0, Math.min(totalPages - 1, parseInt(e.target.value) - 1));
if (!isNaN(newPage)) {
setPage(newPage);
}
}}
className="w-16 px-2 py-1 text-center rounded theme-card theme-text theme-border border focus:outline-none focus:ring-2 focus:ring-theme-accent"
/>
<span className="theme-text text-sm">of {totalPages}</span>
</div>
<Button
variant="ghost"
onClick={() => setPage(page + 1)}
disabled={page >= totalPages - 1}
>
Next
</Button>
</div>
)}
{/* Loading Overlay */}
{loading && collections.length > 0 && (
<div className="fixed inset-0 bg-black bg-opacity-20 flex items-center justify-center z-50">
<div className="theme-card p-4 rounded-lg">
<LoadingSpinner size="md" />
</div>
</div>
)}
</div>
</AppLayout>
);
}

View File

@@ -6,7 +6,7 @@ import { Story, Tag } from '../../types/api';
import AppLayout from '../../components/layout/AppLayout';
import { Input } from '../../components/ui/Input';
import Button from '../../components/ui/Button';
import StoryCard from '../../components/stories/StoryCard';
import StoryMultiSelect from '../../components/stories/StoryMultiSelect';
import TagFilter from '../../components/stories/TagFilter';
import LoadingSpinner from '../../components/ui/LoadingSpinner';
@@ -242,20 +242,12 @@ export default function LibraryPage() {
)}
</div>
) : (
<div className={
viewMode === 'grid'
? 'grid grid-cols-1 sm:grid-cols-2 lg:grid-cols-3 xl:grid-cols-4 gap-6'
: 'space-y-4'
}>
{stories.map((story) => (
<StoryCard
key={story.id}
story={story}
viewMode={viewMode}
onUpdate={handleStoryUpdate}
/>
))}
</div>
<StoryMultiSelect
stories={stories}
viewMode={viewMode}
onUpdate={handleStoryUpdate}
allowMultiSelect={true}
/>
)}
{/* Pagination */}

View File

@@ -5,7 +5,7 @@ import { useParams, useRouter } from 'next/navigation';
import Link from 'next/link';
import Image from 'next/image';
import { storyApi, seriesApi, getImageUrl } from '../../../../lib/api';
import { Story } from '../../../../types/api';
import { Story, Collection } from '../../../../types/api';
import AppLayout from '../../../../components/layout/AppLayout';
import Button from '../../../../components/ui/Button';
import LoadingSpinner from '../../../../components/ui/LoadingSpinner';
@@ -17,6 +17,7 @@ export default function StoryDetailPage() {
const [story, setStory] = useState<Story | null>(null);
const [seriesStories, setSeriesStories] = useState<Story[]>([]);
const [collections, setCollections] = useState<Collection[]>([]);
const [loading, setLoading] = useState(true);
const [updating, setUpdating] = useState(false);
@@ -32,6 +33,10 @@ export default function StoryDetailPage() {
const seriesData = await seriesApi.getSeriesStories(storyData.seriesId);
setSeriesStories(seriesData);
}
// Load collections that contain this story
const collectionsData = await storyApi.getStoryCollections(storyId);
setCollections(collectionsData);
} catch (error) {
console.error('Failed to load story data:', error);
router.push('/library');
@@ -250,6 +255,57 @@ export default function StoryDetailPage() {
</div>
)}
{/* Collections */}
{collections.length > 0 && (
<div className="theme-card theme-shadow rounded-lg p-4">
<h3 className="font-semibold theme-header mb-3">
Part of Collections ({collections.length})
</h3>
<div className="space-y-2">
{collections.map((collection) => (
<Link
key={collection.id}
href={`/collections/${collection.id}`}
className="block p-3 rounded-lg hover:bg-gray-50 dark:hover:bg-gray-800 transition-colors"
>
<div className="flex items-center gap-3">
{collection.coverImagePath ? (
<img
src={getImageUrl(collection.coverImagePath)}
alt={`${collection.name} cover`}
className="w-8 h-10 object-cover rounded"
/>
) : (
<div className="w-8 h-10 bg-gradient-to-br from-blue-100 to-purple-100 rounded flex items-center justify-center">
<span className="text-xs font-bold text-gray-600">
{collection.storyCount}
</span>
</div>
)}
<div className="flex-1 min-w-0">
<h4 className="font-medium theme-header truncate">
{collection.name}
</h4>
<p className="text-sm theme-text opacity-70">
{collection.storyCount} {collection.storyCount === 1 ? 'story' : 'stories'}
{collection.estimatedReadingTime && (
<span> ~{Math.ceil(collection.estimatedReadingTime / 60)}h reading</span>
)}
</p>
</div>
{collection.rating && (
<div className="flex-shrink-0">
<span className="text-yellow-400"></span>
<span className="text-sm theme-text ml-1">{collection.rating}</span>
</div>
)}
</div>
</Link>
))}
</div>
</div>
)}
{/* Summary */}
{story.summary && (
<div className="theme-card theme-shadow rounded-lg p-6">

View File

@@ -0,0 +1,201 @@
'use client';
import { useState, useEffect } from 'react';
import { collectionApi, searchApi } from '../../lib/api';
import { Collection, Story } from '../../types/api';
import Button from '../ui/Button';
import { Input } from '../ui/Input';
import LoadingSpinner from '../ui/LoadingSpinner';
interface AddToCollectionModalProps {
isOpen: boolean;
onClose: () => void;
collection: Collection;
onUpdate: () => void;
}
export default function AddToCollectionModal({
isOpen,
onClose,
collection,
onUpdate
}: AddToCollectionModalProps) {
const [searchQuery, setSearchQuery] = useState('');
const [availableStories, setAvailableStories] = useState<Story[]>([]);
const [selectedStoryIds, setSelectedStoryIds] = useState<string[]>([]);
const [loading, setLoading] = useState(false);
const [adding, setAdding] = useState(false);
// Get IDs of stories already in the collection
const existingStoryIds = collection.collectionStories?.map(cs => cs.story.id) || [];
useEffect(() => {
if (isOpen) {
loadStories();
}
}, [isOpen, searchQuery]);
const loadStories = async () => {
try {
setLoading(true);
const result = await searchApi.search({
query: searchQuery || '*',
page: 0,
size: 50,
});
// Filter out stories already in the collection
const filteredStories = result.results.filter(
story => !existingStoryIds.includes(story.id)
);
setAvailableStories(filteredStories);
} catch (error) {
console.error('Failed to load stories:', error);
} finally {
setLoading(false);
}
};
const toggleStorySelection = (storyId: string) => {
setSelectedStoryIds(prev =>
prev.includes(storyId)
? prev.filter(id => id !== storyId)
: [...prev, storyId]
);
};
const handleAddStories = async () => {
if (selectedStoryIds.length === 0) return;
try {
setAdding(true);
await collectionApi.addStoriesToCollection(collection.id, selectedStoryIds);
onUpdate();
onClose();
setSelectedStoryIds([]);
} catch (error) {
console.error('Failed to add stories to collection:', error);
} finally {
setAdding(false);
}
};
const handleClose = () => {
if (!adding) {
setSelectedStoryIds([]);
setSearchQuery('');
onClose();
}
};
if (!isOpen) return null;
return (
<div className="fixed inset-0 bg-black bg-opacity-50 flex items-center justify-center z-50 p-4">
<div className="theme-card max-w-2xl w-full max-h-[80vh] overflow-hidden flex flex-col">
{/* Header */}
<div className="flex items-center justify-between p-6 border-b theme-border">
<h2 className="text-xl font-semibold theme-header">
Add Stories to "{collection.name}"
</h2>
<button
onClick={handleClose}
disabled={adding}
className="text-gray-500 hover:text-gray-700 disabled:opacity-50"
>
×
</button>
</div>
{/* Search */}
<div className="p-6 border-b theme-border">
<Input
type="search"
value={searchQuery}
onChange={(e) => setSearchQuery(e.target.value)}
placeholder="Search stories to add..."
className="w-full"
/>
</div>
{/* Stories List */}
<div className="flex-1 overflow-y-auto p-6">
{loading ? (
<div className="flex justify-center py-8">
<LoadingSpinner size="md" />
</div>
) : availableStories.length === 0 ? (
<div className="text-center py-8 theme-text opacity-70">
{searchQuery ? 'No stories found matching your search.' : 'All stories are already in this collection.'}
</div>
) : (
<div className="space-y-3">
{availableStories.map((story) => {
const isSelected = selectedStoryIds.includes(story.id);
return (
<div
key={story.id}
className={`p-3 rounded-lg border cursor-pointer transition-colors ${
isSelected
? 'border-blue-500 bg-blue-50'
: 'theme-border hover:border-gray-400'
}`}
onClick={() => toggleStorySelection(story.id)}
>
<div className="flex items-center gap-3">
<input
type="checkbox"
checked={isSelected}
onChange={() => toggleStorySelection(story.id)}
className="rounded border-gray-300 text-blue-600 focus:ring-blue-500"
/>
<div className="flex-1 min-w-0">
<h3 className="font-medium theme-text truncate">
{story.title}
</h3>
<p className="text-sm theme-text opacity-70 truncate">
by {story.authorName}
</p>
<div className="flex items-center gap-4 mt-1 text-xs theme-text opacity-60">
<span>{story.wordCount?.toLocaleString()} words</span>
{story.rating && (
<span className="flex items-center">
{story.rating}
</span>
)}
</div>
</div>
</div>
</div>
);
})}
</div>
)}
</div>
{/* Footer */}
<div className="flex items-center justify-between p-6 border-t theme-border">
<div className="text-sm theme-text opacity-70">
{selectedStoryIds.length} stories selected
</div>
<div className="flex gap-3">
<Button
variant="ghost"
onClick={handleClose}
disabled={adding}
>
Cancel
</Button>
<Button
onClick={handleAddStories}
disabled={selectedStoryIds.length === 0 || adding}
>
{adding ? <LoadingSpinner size="sm" /> : `Add ${selectedStoryIds.length} Stories`}
</Button>
</div>
</div>
</div>
</div>
);
}

View File

@@ -0,0 +1,203 @@
'use client';
import { Collection } from '../../types/api';
import { getImageUrl } from '../../lib/api';
import Link from 'next/link';
interface CollectionCardProps {
collection: Collection;
viewMode: 'grid' | 'list';
onUpdate?: () => void;
}
export default function CollectionCard({ collection, viewMode, onUpdate }: CollectionCardProps) {
const formatReadingTime = (minutes: number): string => {
if (minutes < 60) {
return `${minutes}m`;
}
const hours = Math.floor(minutes / 60);
const remainingMinutes = minutes % 60;
return remainingMinutes > 0 ? `${hours}h ${remainingMinutes}m` : `${hours}h`;
};
const renderRatingStars = (rating?: number) => {
if (!rating) return null;
return (
<div className="flex items-center">
{[1, 2, 3, 4, 5].map((star) => (
<span
key={star}
className={`text-sm ${
star <= rating ? 'text-yellow-400' : 'text-gray-300'
}`}
>
</span>
))}
</div>
);
};
if (viewMode === 'grid') {
return (
<Link href={`/collections/${collection.id}`}>
<div className="theme-card p-4 hover:border-gray-400 transition-colors cursor-pointer">
{/* Cover Image or Placeholder */}
<div className="aspect-[3/4] mb-3 relative overflow-hidden rounded-lg bg-gray-100">
{collection.coverImagePath ? (
<img
src={getImageUrl(collection.coverImagePath)}
alt={`${collection.name} cover`}
className="w-full h-full object-cover"
/>
) : (
<div className="w-full h-full flex items-center justify-center bg-gradient-to-br from-blue-100 to-purple-100">
<div className="text-center p-4">
<div className="text-2xl font-bold theme-text mb-1">
{collection.storyCount}
</div>
<div className="text-xs theme-text opacity-60">
{collection.storyCount === 1 ? 'story' : 'stories'}
</div>
</div>
</div>
)}
{collection.isArchived && (
<div className="absolute top-2 right-2 bg-yellow-500 text-white px-2 py-1 rounded text-xs">
Archived
</div>
)}
</div>
{/* Collection Info */}
<div className="space-y-2">
<h3 className="font-semibold theme-header line-clamp-2">
{collection.name}
</h3>
{collection.description && (
<p className="text-sm theme-text opacity-70 line-clamp-2">
{collection.description}
</p>
)}
<div className="flex items-center justify-between text-xs theme-text opacity-60">
<span>{collection.storyCount} stories</span>
<span>{collection.estimatedReadingTime ? formatReadingTime(collection.estimatedReadingTime) : '—'}</span>
</div>
{collection.rating && (
<div className="flex justify-center">
{renderRatingStars(collection.rating)}
</div>
)}
{/* Tags */}
{collection.tags && collection.tags.length > 0 && (
<div className="flex flex-wrap gap-1">
{collection.tags.slice(0, 3).map((tag) => (
<span
key={tag.id}
className="inline-block px-2 py-1 text-xs rounded-full theme-accent-bg text-white"
>
{tag.name}
</span>
))}
{collection.tags.length > 3 && (
<span className="text-xs theme-text opacity-60">
+{collection.tags.length - 3} more
</span>
)}
</div>
)}
</div>
</div>
</Link>
);
}
// List view
return (
<Link href={`/collections/${collection.id}`}>
<div className="theme-card p-4 hover:border-gray-400 transition-colors cursor-pointer">
<div className="flex gap-4">
{/* Cover Image */}
<div className="w-16 h-20 flex-shrink-0 rounded overflow-hidden bg-gray-100">
{collection.coverImagePath ? (
<img
src={getImageUrl(collection.coverImagePath)}
alt={`${collection.name} cover`}
className="w-full h-full object-cover"
/>
) : (
<div className="w-full h-full flex items-center justify-center bg-gradient-to-br from-blue-100 to-purple-100">
<div className="text-center">
<div className="text-sm font-bold theme-text">
{collection.storyCount}
</div>
</div>
</div>
)}
</div>
{/* Collection Details */}
<div className="flex-1 min-w-0">
<div className="flex items-start justify-between">
<div className="flex-1 min-w-0">
<h3 className="font-semibold theme-header line-clamp-1">
{collection.name}
{collection.isArchived && (
<span className="ml-2 inline-block bg-yellow-500 text-white px-2 py-1 rounded text-xs">
Archived
</span>
)}
</h3>
{collection.description && (
<p className="text-sm theme-text opacity-70 line-clamp-2 mt-1">
{collection.description}
</p>
)}
<div className="flex items-center gap-4 mt-2 text-sm theme-text opacity-60">
<span>{collection.storyCount} stories</span>
<span>{collection.estimatedReadingTime ? formatReadingTime(collection.estimatedReadingTime) : '—'} reading</span>
{collection.averageStoryRating && collection.averageStoryRating > 0 && (
<span> {collection.averageStoryRating.toFixed(1)} avg</span>
)}
</div>
{/* Tags */}
{collection.tags && collection.tags.length > 0 && (
<div className="flex flex-wrap gap-1 mt-2">
{collection.tags.slice(0, 5).map((tag) => (
<span
key={tag.id}
className="inline-block px-2 py-1 text-xs rounded-full theme-accent-bg text-white"
>
{tag.name}
</span>
))}
{collection.tags.length > 5 && (
<span className="text-xs theme-text opacity-60">
+{collection.tags.length - 5} more
</span>
)}
</div>
)}
</div>
{collection.rating && (
<div className="flex-shrink-0 ml-4">
{renderRatingStars(collection.rating)}
</div>
)}
</div>
</div>
</div>
</div>
</Link>
);
}

View File

@@ -0,0 +1,360 @@
'use client';
import { useState } from 'react';
import { useRouter } from 'next/navigation';
import { Collection } from '../../types/api';
import { collectionApi, getImageUrl } from '../../lib/api';
import Button from '../ui/Button';
import StoryReorderList from './StoryReorderList';
import AddToCollectionModal from './AddToCollectionModal';
import LoadingSpinner from '../ui/LoadingSpinner';
import Link from 'next/link';
interface CollectionDetailViewProps {
collection: Collection;
onUpdate: () => void;
onDelete: () => void;
}
export default function CollectionDetailView({
collection,
onUpdate,
onDelete
}: CollectionDetailViewProps) {
const router = useRouter();
const [showAddStories, setShowAddStories] = useState(false);
const [isEditing, setIsEditing] = useState(false);
const [editName, setEditName] = useState(collection.name);
const [editDescription, setEditDescription] = useState(collection.description || '');
const [editRating, setEditRating] = useState(collection.rating || '');
const [saving, setSaving] = useState(false);
const [actionLoading, setActionLoading] = useState<string | null>(null);
const formatReadingTime = (minutes: number): string => {
if (minutes < 60) {
return `${minutes} minutes`;
}
const hours = Math.floor(minutes / 60);
const remainingMinutes = minutes % 60;
return remainingMinutes > 0 ? `${hours}h ${remainingMinutes}m` : `${hours} hours`;
};
const renderRatingStars = (rating?: number) => {
if (!rating) return null;
return (
<div className="flex items-center">
{[1, 2, 3, 4, 5].map((star) => (
<span
key={star}
className={`text-lg ${
star <= rating ? 'text-yellow-400' : 'text-gray-300'
}`}
>
</span>
))}
</div>
);
};
const handleSaveEdits = async () => {
try {
setSaving(true);
await collectionApi.updateCollection(collection.id, {
name: editName.trim(),
description: editDescription.trim() || undefined,
rating: editRating ? parseInt(editRating.toString()) : undefined,
});
setIsEditing(false);
onUpdate();
} catch (error) {
console.error('Failed to update collection:', error);
} finally {
setSaving(false);
}
};
const handleCancelEdit = () => {
setEditName(collection.name);
setEditDescription(collection.description || '');
setEditRating(collection.rating || '');
setIsEditing(false);
};
const handleArchive = async () => {
const action = collection.isArchived ? 'unarchive' : 'archive';
if (confirm(`Are you sure you want to ${action} this collection?`)) {
try {
setActionLoading('archive');
await collectionApi.archiveCollection(collection.id, !collection.isArchived);
onUpdate();
} catch (error) {
console.error(`Failed to ${action} collection:`, error);
} finally {
setActionLoading(null);
}
}
};
const handleDelete = async () => {
if (confirm('Are you sure you want to delete this collection? This cannot be undone. Stories will not be deleted.')) {
try {
setActionLoading('delete');
await collectionApi.deleteCollection(collection.id);
onDelete();
} catch (error) {
console.error('Failed to delete collection:', error);
} finally {
setActionLoading(null);
}
}
};
const startReading = () => {
if (collection.collectionStories && collection.collectionStories.length > 0) {
const firstStory = collection.collectionStories[0].story;
router.push(`/collections/${collection.id}/read/${firstStory.id}`);
}
};
return (
<div className="space-y-8">
{/* Header Section */}
<div className="theme-card p-6">
<div className="flex flex-col lg:flex-row gap-6">
{/* Cover Image */}
<div className="flex-shrink-0">
<div className="w-48 h-64 rounded-lg overflow-hidden bg-gray-100 mx-auto lg:mx-0">
{collection.coverImagePath ? (
<img
src={getImageUrl(collection.coverImagePath)}
alt={`${collection.name} cover`}
className="w-full h-full object-cover"
/>
) : (
<div className="w-full h-full flex items-center justify-center bg-gradient-to-br from-blue-100 to-purple-100">
<div className="text-center p-4">
<div className="text-3xl font-bold theme-text mb-2">
{collection.storyCount}
</div>
<div className="text-sm theme-text opacity-60">
{collection.storyCount === 1 ? 'story' : 'stories'}
</div>
</div>
</div>
)}
</div>
</div>
{/* Collection Info */}
<div className="flex-1 min-w-0">
<div className="flex items-start justify-between mb-4">
<div className="flex-1 min-w-0">
{isEditing ? (
<div className="space-y-3">
<input
type="text"
value={editName}
onChange={(e) => setEditName(e.target.value)}
className="text-3xl font-bold theme-header bg-transparent border-b-2 border-gray-300 focus:border-blue-500 focus:outline-none w-full"
/>
<textarea
value={editDescription}
onChange={(e) => setEditDescription(e.target.value)}
placeholder="Add a description..."
rows={3}
className="w-full theme-text bg-transparent border border-gray-300 rounded-lg p-2 focus:border-blue-500 focus:outline-none resize-none"
/>
<div className="flex items-center gap-4">
<label className="text-sm font-medium theme-text">Rating:</label>
<select
value={editRating}
onChange={(e) => setEditRating(e.target.value)}
className="px-3 py-1 border border-gray-300 rounded theme-text focus:border-blue-500 focus:outline-none"
>
<option value="">No rating</option>
{[1, 2, 3, 4, 5].map(num => (
<option key={num} value={num}>{num} star{num > 1 ? 's' : ''}</option>
))}
</select>
</div>
</div>
) : (
<div>
<h1 className="text-3xl font-bold theme-header mb-2 break-words">
{collection.name}
{collection.isArchived && (
<span className="ml-3 inline-block bg-yellow-500 text-white px-3 py-1 rounded text-sm font-normal">
Archived
</span>
)}
</h1>
{collection.description && (
<p className="theme-text text-lg mb-4 whitespace-pre-wrap">
{collection.description}
</p>
)}
{collection.rating && (
<div className="mb-4">
{renderRatingStars(collection.rating)}
</div>
)}
</div>
)}
</div>
{/* Edit Controls */}
<div className="flex gap-2 ml-4">
{isEditing ? (
<>
<Button
size="sm"
onClick={handleSaveEdits}
disabled={saving || !editName.trim()}
>
{saving ? <LoadingSpinner size="sm" /> : 'Save'}
</Button>
<Button
variant="ghost"
size="sm"
onClick={handleCancelEdit}
disabled={saving}
>
Cancel
</Button>
</>
) : (
<Button
variant="ghost"
size="sm"
onClick={() => setIsEditing(true)}
>
Edit
</Button>
)}
</div>
</div>
{/* Statistics */}
<div className="grid grid-cols-2 md:grid-cols-4 gap-4 mb-6">
<div className="text-center">
<div className="text-2xl font-bold theme-text">
{collection.storyCount}
</div>
<div className="text-sm theme-text opacity-60">
{collection.storyCount === 1 ? 'Story' : 'Stories'}
</div>
</div>
<div className="text-center">
<div className="text-2xl font-bold theme-text">
{collection.estimatedReadingTime ? formatReadingTime(collection.estimatedReadingTime) : '—'}
</div>
<div className="text-sm theme-text opacity-60">Reading Time</div>
</div>
<div className="text-center">
<div className="text-2xl font-bold theme-text">
{collection.totalWordCount ? collection.totalWordCount.toLocaleString() : '0'}
</div>
<div className="text-sm theme-text opacity-60">Total Words</div>
</div>
<div className="text-center">
<div className="text-2xl font-bold theme-text">
{collection.averageStoryRating && collection.averageStoryRating > 0 ? collection.averageStoryRating.toFixed(1) : '—'}
</div>
<div className="text-sm theme-text opacity-60">Avg Rating</div>
</div>
</div>
{/* Action Buttons */}
<div className="flex flex-wrap gap-3">
<Button
onClick={startReading}
disabled={collection.storyCount === 0}
className="flex-shrink-0"
>
Read Collection
</Button>
<Button
variant="ghost"
onClick={() => router.push(`/collections/${collection.id}/edit`)}
className="flex-shrink-0"
>
Edit Collection
</Button>
<Button
variant="ghost"
onClick={() => setShowAddStories(true)}
className="flex-shrink-0"
>
Add Stories
</Button>
<Button
variant="ghost"
onClick={handleArchive}
disabled={actionLoading === 'archive'}
className="flex-shrink-0"
>
{actionLoading === 'archive' ? <LoadingSpinner size="sm" /> : (collection.isArchived ? 'Unarchive' : 'Archive')}
</Button>
<Button
variant="ghost"
onClick={handleDelete}
disabled={actionLoading === 'delete'}
className="flex-shrink-0 text-red-600 hover:text-red-800"
>
{actionLoading === 'delete' ? <LoadingSpinner size="sm" /> : 'Delete'}
</Button>
</div>
{/* Tags */}
{collection.tags && collection.tags.length > 0 && (
<div className="mt-6">
<h3 className="text-sm font-medium theme-text mb-2">Tags:</h3>
<div className="flex flex-wrap gap-2">
{collection.tags.map((tag) => (
<span
key={tag.id}
className="inline-block px-3 py-1 text-sm rounded-full theme-accent-bg text-white"
>
{tag.name}
</span>
))}
</div>
</div>
)}
</div>
</div>
</div>
{/* Stories Section */}
<div className="theme-card p-6">
<div className="flex items-center justify-between mb-6">
<h2 className="text-xl font-semibold theme-header">
Stories ({collection.storyCount})
</h2>
<Button
variant="ghost"
size="sm"
onClick={() => setShowAddStories(true)}
>
Add Stories
</Button>
</div>
<StoryReorderList
collection={collection}
onUpdate={onUpdate}
/>
</div>
{/* Add Stories Modal */}
<AddToCollectionModal
isOpen={showAddStories}
onClose={() => setShowAddStories(false)}
collection={collection}
onUpdate={onUpdate}
/>
</div>
);
}

View File

@@ -0,0 +1,415 @@
'use client';
import { useState, useEffect } from 'react';
import { searchApi, tagApi } from '../../lib/api';
import { Story, Tag } from '../../types/api';
import { Input } from '../ui/Input';
import Button from '../ui/Button';
import LoadingSpinner from '../ui/LoadingSpinner';
interface CollectionFormProps {
initialData?: {
name: string;
description?: string;
tags?: string[];
storyIds?: string[];
coverImagePath?: string;
};
onSubmit: (data: {
name: string;
description?: string;
tags?: string[];
storyIds?: string[];
coverImage?: File;
}) => Promise<void>;
onCancel: () => void;
loading?: boolean;
submitLabel?: string;
}
export default function CollectionForm({
initialData,
onSubmit,
onCancel,
loading = false,
submitLabel = 'Save Collection'
}: CollectionFormProps) {
const [name, setName] = useState(initialData?.name || '');
const [description, setDescription] = useState(initialData?.description || '');
const [tagInput, setTagInput] = useState('');
const [selectedTags, setSelectedTags] = useState<string[]>(initialData?.tags || []);
const [tagSuggestions, setTagSuggestions] = useState<string[]>([]);
const [selectedStoryIds, setSelectedStoryIds] = useState<string[]>(initialData?.storyIds || []);
const [coverImage, setCoverImage] = useState<File | null>(null);
const [coverImagePreview, setCoverImagePreview] = useState<string | null>(null);
// Story selection state
const [storySearchQuery, setStorySearchQuery] = useState('');
const [availableStories, setAvailableStories] = useState<Story[]>([]);
const [selectedStories, setSelectedStories] = useState<Story[]>([]);
const [loadingStories, setLoadingStories] = useState(false);
const [showStorySelection, setShowStorySelection] = useState(false);
// Load tag suggestions when typing
useEffect(() => {
if (tagInput.length > 1) {
const loadSuggestions = async () => {
try {
const suggestions = await tagApi.getTagAutocomplete(tagInput);
setTagSuggestions(suggestions.filter(tag => !selectedTags.includes(tag)));
} catch (error) {
console.error('Failed to load tag suggestions:', error);
}
};
const debounceTimer = setTimeout(loadSuggestions, 300);
return () => clearTimeout(debounceTimer);
} else {
setTagSuggestions([]);
}
}, [tagInput, selectedTags]);
// Load stories for selection
useEffect(() => {
if (showStorySelection) {
const loadStories = async () => {
try {
setLoadingStories(true);
const result = await searchApi.search({
query: storySearchQuery || '*',
page: 0,
size: 50,
});
setAvailableStories(result.results || []);
} catch (error) {
console.error('Failed to load stories:', error);
} finally {
setLoadingStories(false);
}
};
const debounceTimer = setTimeout(loadStories, 300);
return () => clearTimeout(debounceTimer);
}
}, [storySearchQuery, showStorySelection]);
// Load selected stories data on mount
useEffect(() => {
if (selectedStoryIds.length > 0) {
const loadSelectedStories = async () => {
try {
const result = await searchApi.search({
query: '*',
page: 0,
size: 100,
});
const stories = result.results.filter(story => selectedStoryIds.includes(story.id));
setSelectedStories(stories);
} catch (error) {
console.error('Failed to load selected stories:', error);
}
};
loadSelectedStories();
}
}, [selectedStoryIds]);
const handleTagInputKeyDown = (e: React.KeyboardEvent) => {
if (e.key === 'Enter' && tagInput.trim()) {
e.preventDefault();
const newTag = tagInput.trim();
if (!selectedTags.includes(newTag)) {
setSelectedTags(prev => [...prev, newTag]);
}
setTagInput('');
setTagSuggestions([]);
}
};
const addTag = (tag: string) => {
if (!selectedTags.includes(tag)) {
setSelectedTags(prev => [...prev, tag]);
}
setTagInput('');
setTagSuggestions([]);
};
const removeTag = (tagToRemove: string) => {
setSelectedTags(prev => prev.filter(tag => tag !== tagToRemove));
};
const handleCoverImageChange = (e: React.ChangeEvent<HTMLInputElement>) => {
const file = e.target.files?.[0];
if (file) {
setCoverImage(file);
const reader = new FileReader();
reader.onload = (e) => {
setCoverImagePreview(e.target?.result as string);
};
reader.readAsDataURL(file);
}
};
const toggleStorySelection = (story: Story) => {
const isSelected = selectedStoryIds.includes(story.id);
if (isSelected) {
setSelectedStoryIds(prev => prev.filter(id => id !== story.id));
setSelectedStories(prev => prev.filter(s => s.id !== story.id));
} else {
setSelectedStoryIds(prev => [...prev, story.id]);
setSelectedStories(prev => [...prev, story]);
}
};
const removeSelectedStory = (storyId: string) => {
setSelectedStoryIds(prev => prev.filter(id => id !== storyId));
setSelectedStories(prev => prev.filter(s => s.id !== storyId));
};
const handleSubmit = async (e: React.FormEvent) => {
e.preventDefault();
if (!name.trim()) {
return;
}
await onSubmit({
name: name.trim(),
description: description.trim() || undefined,
tags: selectedTags,
storyIds: selectedStoryIds,
coverImage: coverImage || undefined,
});
};
return (
<form onSubmit={handleSubmit} className="space-y-6">
{/* Basic Information */}
<div className="theme-card p-6">
<h2 className="text-lg font-semibold theme-header mb-4">Basic Information</h2>
<div className="space-y-4">
<div>
<label htmlFor="name" className="block text-sm font-medium theme-text mb-1">
Collection Name *
</label>
<Input
id="name"
type="text"
value={name}
onChange={(e) => setName(e.target.value)}
placeholder="Enter collection name"
required
className="w-full"
/>
</div>
<div>
<label htmlFor="description" className="block text-sm font-medium theme-text mb-1">
Description
</label>
<textarea
id="description"
value={description}
onChange={(e) => setDescription(e.target.value)}
placeholder="Describe this collection (optional)"
rows={3}
className="w-full px-3 py-2 border theme-border rounded-lg theme-card theme-text focus:outline-none focus:ring-2 focus:ring-theme-accent"
/>
</div>
{/* Cover Image Upload */}
<div>
<label htmlFor="coverImage" className="block text-sm font-medium theme-text mb-1">
Cover Image
</label>
<div className="flex items-start gap-4">
<div className="flex-1">
<input
id="coverImage"
type="file"
accept="image/jpeg,image/png,image/webp"
onChange={handleCoverImageChange}
className="w-full px-3 py-2 border theme-border rounded-lg theme-card theme-text focus:outline-none focus:ring-2 focus:ring-theme-accent"
/>
<p className="text-xs theme-text opacity-60 mt-1">
JPG, PNG, or WebP. Max 800x1200px.
</p>
</div>
{(coverImagePreview || initialData?.coverImagePath) && (
<div className="w-20 h-24 rounded overflow-hidden bg-gray-100">
<img
src={coverImagePreview || (initialData?.coverImagePath ? `/images/${initialData.coverImagePath}` : '')}
alt="Cover preview"
className="w-full h-full object-cover"
/>
</div>
)}
</div>
</div>
</div>
</div>
{/* Tags */}
<div className="theme-card p-6">
<h2 className="text-lg font-semibold theme-header mb-4">Tags</h2>
<div className="space-y-3">
<div className="relative">
<Input
type="text"
value={tagInput}
onChange={(e) => setTagInput(e.target.value)}
onKeyDown={handleTagInputKeyDown}
placeholder="Type tags and press Enter"
className="w-full"
/>
{tagSuggestions.length > 0 && (
<div className="absolute z-10 top-full left-0 right-0 mt-1 bg-white border theme-border rounded-lg shadow-lg max-h-32 overflow-y-auto">
{tagSuggestions.map((suggestion) => (
<button
key={suggestion}
type="button"
onClick={() => addTag(suggestion)}
className="w-full px-3 py-2 text-left hover:bg-gray-100 theme-text"
>
{suggestion}
</button>
))}
</div>
)}
</div>
{selectedTags.length > 0 && (
<div className="flex flex-wrap gap-2">
{selectedTags.map((tag) => (
<span
key={tag}
className="inline-flex items-center px-3 py-1 text-sm rounded-full theme-accent-bg text-white"
>
{tag}
<button
type="button"
onClick={() => removeTag(tag)}
className="ml-2 hover:text-red-200"
>
×
</button>
</span>
))}
</div>
)}
</div>
</div>
{/* Story Selection */}
<div className="theme-card p-6">
<div className="flex items-center justify-between mb-4">
<h2 className="text-lg font-semibold theme-header">Stories</h2>
<Button
type="button"
variant="ghost"
size="sm"
onClick={() => setShowStorySelection(!showStorySelection)}
>
{showStorySelection ? 'Hide' : 'Add'} Stories
</Button>
</div>
{/* Selected Stories */}
{selectedStories.length > 0 && (
<div className="mb-4">
<h3 className="text-sm font-medium theme-text mb-2">
Selected Stories ({selectedStories.length})
</h3>
<div className="space-y-2 max-h-32 overflow-y-auto">
{selectedStories.map((story) => (
<div key={story.id} className="flex items-center justify-between p-2 bg-gray-50 rounded">
<div className="flex-1 min-w-0">
<p className="text-sm font-medium theme-text truncate">{story.title}</p>
<p className="text-xs theme-text opacity-60">{story.authorName}</p>
</div>
<button
type="button"
onClick={() => removeSelectedStory(story.id)}
className="ml-2 text-red-600 hover:text-red-800"
>
×
</button>
</div>
))}
</div>
</div>
)}
{/* Story Selection Interface */}
{showStorySelection && (
<div className="space-y-3">
<Input
type="search"
value={storySearchQuery}
onChange={(e) => setStorySearchQuery(e.target.value)}
placeholder="Search stories to add..."
className="w-full"
/>
{loadingStories ? (
<div className="flex justify-center py-4">
<LoadingSpinner size="sm" />
</div>
) : (
<div className="max-h-64 overflow-y-auto space-y-2">
{availableStories.map((story) => {
const isSelected = selectedStoryIds.includes(story.id);
return (
<div
key={story.id}
className={`p-3 rounded-lg border cursor-pointer transition-colors ${
isSelected
? 'border-blue-500 bg-blue-50'
: 'theme-border hover:border-gray-400'
}`}
onClick={() => toggleStorySelection(story)}
>
<div className="flex items-center gap-3">
<input
type="checkbox"
checked={isSelected}
onChange={() => toggleStorySelection(story)}
className="rounded border-gray-300 text-blue-600 focus:ring-blue-500"
/>
<div className="flex-1 min-w-0">
<p className="font-medium theme-text truncate">{story.title}</p>
<p className="text-sm theme-text opacity-60">{story.authorName}</p>
</div>
</div>
</div>
);
})}
</div>
)}
</div>
)}
</div>
{/* Form Actions */}
<div className="flex justify-end gap-3">
<Button
type="button"
variant="ghost"
onClick={onCancel}
disabled={loading}
>
Cancel
</Button>
<Button
type="submit"
disabled={loading || !name.trim()}
>
{loading ? <LoadingSpinner size="sm" /> : submitLabel}
</Button>
</div>
</form>
);
}

View File

@@ -0,0 +1,42 @@
'use client';
import { Collection } from '../../types/api';
import CollectionCard from './CollectionCard';
interface CollectionGridProps {
collections: Collection[];
viewMode: 'grid' | 'list';
onUpdate?: () => void;
}
export default function CollectionGrid({ collections, viewMode, onUpdate }: CollectionGridProps) {
if (collections.length === 0) {
return (
<div className="text-center py-20">
<div className="theme-text text-lg mb-4">
No collections found
</div>
<p className="theme-text opacity-70">
Create your first collection to organize your stories
</p>
</div>
);
}
return (
<div className={
viewMode === 'grid'
? 'grid grid-cols-1 sm:grid-cols-2 lg:grid-cols-3 xl:grid-cols-4 gap-6'
: 'space-y-4'
}>
{collections.map((collection) => (
<CollectionCard
key={collection.id}
collection={collection}
viewMode={viewMode}
onUpdate={onUpdate}
/>
))}
</div>
);
}

View File

@@ -0,0 +1,218 @@
'use client';
import { StoryWithCollectionContext } from '../../types/api';
import Button from '../ui/Button';
import Link from 'next/link';
interface CollectionReadingViewProps {
data: StoryWithCollectionContext;
onNavigate: (storyId: string) => void;
onBackToCollection: () => void;
}
export default function CollectionReadingView({
data,
onNavigate,
onBackToCollection
}: CollectionReadingViewProps) {
const { story, collection } = data;
const handlePrevious = () => {
if (collection.previousStoryId) {
onNavigate(collection.previousStoryId);
}
};
const handleNext = () => {
if (collection.nextStoryId) {
onNavigate(collection.nextStoryId);
}
};
const renderRatingStars = (rating?: number) => {
if (!rating) return null;
return (
<div className="flex items-center">
{[1, 2, 3, 4, 5].map((star) => (
<span
key={star}
className={`text-sm ${
star <= rating ? 'text-yellow-400' : 'text-gray-300'
}`}
>
</span>
))}
</div>
);
};
return (
<div className="max-w-4xl mx-auto">
{/* Collection Context Header */}
<div className="mb-6 p-4 bg-blue-50 dark:bg-blue-900/20 rounded-lg border border-blue-200 dark:border-blue-800">
<div className="flex items-center justify-between">
<div className="flex items-center gap-4">
<button
onClick={onBackToCollection}
className="text-blue-600 hover:text-blue-800 dark:text-blue-400 dark:hover:text-blue-200"
title="Back to Collection"
>
Back
</button>
<div>
<h2 className="font-semibold text-blue-900 dark:text-blue-100">
Reading from: {collection.name}
</h2>
<p className="text-sm text-blue-700 dark:text-blue-300">
Story {collection.currentPosition} of {collection.totalStories}
</p>
</div>
</div>
{/* Progress Bar */}
<div className="flex items-center gap-4">
<div className="w-32 bg-blue-200 dark:bg-blue-800 rounded-full h-2">
<div
className="bg-blue-600 dark:bg-blue-400 h-2 rounded-full transition-all duration-300"
style={{
width: `${(collection.currentPosition / collection.totalStories) * 100}%`
}}
/>
</div>
<span className="text-sm text-blue-700 dark:text-blue-300 font-mono">
{collection.currentPosition}/{collection.totalStories}
</span>
</div>
</div>
</div>
{/* Story Header */}
<div className="theme-card p-6 mb-6">
<div className="flex flex-col md:flex-row gap-6">
{/* Story Cover */}
{story.coverPath && (
<div className="flex-shrink-0">
<img
src={`/images/${story.coverPath}`}
alt={`${story.title} cover`}
className="w-32 h-40 object-cover rounded-lg mx-auto md:mx-0"
/>
</div>
)}
{/* Story Info */}
<div className="flex-1">
<h1 className="text-3xl font-bold theme-header mb-2">
{story.title}
</h1>
<div className="flex flex-wrap items-center gap-4 mb-4 text-sm theme-text opacity-70">
<Link
href={`/stories/${story.id}`}
className="hover:underline"
>
by {story.authorName}
</Link>
<span>{story.wordCount?.toLocaleString()} words</span>
{story.rating && (
<div className="flex items-center gap-1">
{renderRatingStars(story.rating)}
</div>
)}
{story.seriesName && (
<span>
{story.seriesName}
{story.volume && ` #${story.volume}`}
</span>
)}
</div>
{story.summary && (
<p className="theme-text mb-4 italic">
{story.summary}
</p>
)}
{/* Tags */}
{story.tags && story.tags.length > 0 && (
<div className="flex flex-wrap gap-2">
{story.tags.map((tag) => (
<span
key={tag.id}
className="inline-block px-2 py-1 text-xs rounded-full theme-accent-bg text-white"
>
{tag.name}
</span>
))}
</div>
)}
</div>
</div>
</div>
{/* Navigation Controls */}
<div className="flex justify-between items-center mb-6">
<Button
variant="ghost"
onClick={handlePrevious}
disabled={!collection.previousStoryId}
className="flex items-center gap-2"
>
Previous Story
</Button>
<div className="text-sm theme-text opacity-70">
Story {collection.currentPosition} of {collection.totalStories}
</div>
<Button
variant="ghost"
onClick={handleNext}
disabled={!collection.nextStoryId}
className="flex items-center gap-2"
>
Next Story
</Button>
</div>
{/* Story Content */}
<div className="theme-card p-8">
<div
className="prose prose-lg max-w-none theme-text"
dangerouslySetInnerHTML={{ __html: story.contentHtml }}
/>
</div>
{/* Bottom Navigation */}
<div className="flex justify-between items-center mt-8 p-4 theme-card">
<Button
variant="ghost"
onClick={handlePrevious}
disabled={!collection.previousStoryId}
className="flex items-center gap-2"
>
Previous
</Button>
<Button
variant="ghost"
onClick={onBackToCollection}
className="flex items-center gap-2"
>
Back to Collection
</Button>
<Button
variant="ghost"
onClick={handleNext}
disabled={!collection.nextStoryId}
className="flex items-center gap-2"
>
Next
</Button>
</div>
</div>
);
}

View File

@@ -0,0 +1,264 @@
'use client';
import { useState, useEffect } from 'react';
import { Collection, Story } from '../../types/api';
import { collectionApi, getImageUrl } from '../../lib/api';
import Link from 'next/link';
import Button from '../ui/Button';
interface StoryReorderListProps {
collection: Collection;
onUpdate: () => void;
}
export default function StoryReorderList({ collection, onUpdate }: StoryReorderListProps) {
const [draggedIndex, setDraggedIndex] = useState<number | null>(null);
const [reordering, setReordering] = useState(false);
const [localStories, setLocalStories] = useState(collection.collectionStories || []);
// Update local stories when collection changes
useEffect(() => {
setLocalStories(collection.collectionStories || []);
}, [collection.collectionStories]);
const stories = localStories;
const handleDragStart = (e: React.DragEvent, index: number) => {
setDraggedIndex(index);
e.dataTransfer.effectAllowed = 'move';
e.dataTransfer.setData('text/html', '');
};
const handleDragEnd = () => {
setDraggedIndex(null);
};
const handleDragOver = (e: React.DragEvent) => {
e.preventDefault();
e.dataTransfer.dropEffect = 'move';
};
const handleDrop = async (e: React.DragEvent, dropIndex: number) => {
e.preventDefault();
if (draggedIndex === null || draggedIndex === dropIndex || reordering) {
return;
}
// Optimistic update - update local state immediately
const newStories = [...stories];
const [draggedStory] = newStories.splice(draggedIndex, 1);
newStories.splice(dropIndex, 0, draggedStory);
setLocalStories(newStories);
try {
setReordering(true);
// Create reorder request with new positions
const storyOrders = newStories.map((storyItem, index) => ({
storyId: storyItem.story.id,
position: index + 1,
}));
await collectionApi.reorderStories(collection.id, storyOrders);
// Don't call onUpdate() to avoid page reload - the local state is already correct
} catch (error) {
console.error('Failed to reorder stories:', error);
// On error, refresh to get the correct order
onUpdate();
} finally {
setReordering(false);
setDraggedIndex(null);
}
};
const handleRemoveStory = async (storyId: string) => {
if (confirm('Remove this story from the collection?')) {
try {
await collectionApi.removeStoryFromCollection(collection.id, storyId);
onUpdate();
} catch (error) {
console.error('Failed to remove story:', error);
}
}
};
const moveStoryUp = async (index: number) => {
if (index === 0 || reordering) return;
// Optimistic update - update local state immediately
const newStories = [...stories];
[newStories[index - 1], newStories[index]] = [newStories[index], newStories[index - 1]];
setLocalStories(newStories);
try {
setReordering(true);
const storyOrders = newStories.map((storyItem, idx) => ({
storyId: storyItem.story.id,
position: idx + 1,
}));
await collectionApi.reorderStories(collection.id, storyOrders);
// Don't call onUpdate() to avoid page reload
} catch (error) {
console.error('Failed to reorder stories:', error);
// On error, refresh to get the correct order
onUpdate();
} finally {
setReordering(false);
}
};
const moveStoryDown = async (index: number) => {
if (index === stories.length - 1 || reordering) return;
// Optimistic update - update local state immediately
const newStories = [...stories];
[newStories[index], newStories[index + 1]] = [newStories[index + 1], newStories[index]];
setLocalStories(newStories);
try {
setReordering(true);
const storyOrders = newStories.map((storyItem, idx) => ({
storyId: storyItem.story.id,
position: idx + 1,
}));
await collectionApi.reorderStories(collection.id, storyOrders);
// Don't call onUpdate() to avoid page reload
} catch (error) {
console.error('Failed to reorder stories:', error);
// On error, refresh to get the correct order
onUpdate();
} finally {
setReordering(false);
}
};
if (stories.length === 0) {
return (
<div className="text-center py-8 theme-text opacity-70">
<p className="mb-4">No stories in this collection yet.</p>
<p className="text-sm">Add stories to start building your collection.</p>
</div>
);
}
return (
<div className="space-y-3">
{stories.map((storyItem, index) => {
const story = storyItem.story;
const isDragging = draggedIndex === index;
return (
<div
key={`${story.id}-${index}`}
draggable={!reordering}
onDragStart={(e) => handleDragStart(e, index)}
onDragEnd={handleDragEnd}
onDragOver={handleDragOver}
onDrop={(e) => handleDrop(e, index)}
className={`
flex items-center gap-4 p-4 theme-card rounded-lg border transition-all duration-200
${isDragging ? 'opacity-50 scale-95' : 'hover:border-gray-400'}
${reordering ? 'pointer-events-none' : 'cursor-move'}
`}
>
{/* Drag Handle */}
<div className="flex flex-col items-center text-gray-400 hover:text-gray-600">
<div className="text-xs font-mono bg-gray-100 px-2 py-1 rounded mb-1">
{index + 1}
</div>
<div className="flex flex-col gap-1">
<div className="w-3 h-1 bg-gray-300 rounded"></div>
<div className="w-3 h-1 bg-gray-300 rounded"></div>
<div className="w-3 h-1 bg-gray-300 rounded"></div>
</div>
</div>
{/* Story Cover */}
<div className="w-12 h-16 flex-shrink-0 rounded overflow-hidden bg-gray-100">
{story.coverPath ? (
<img
src={getImageUrl(story.coverPath)}
alt={`${story.title} cover`}
className="w-full h-full object-cover"
/>
) : (
<div className="w-full h-full flex items-center justify-center bg-gradient-to-br from-blue-100 to-purple-100">
<span className="text-xs font-bold text-gray-600">
{story.title.charAt(0)}
</span>
</div>
)}
</div>
{/* Story Details */}
<div className="flex-1 min-w-0">
<Link
href={`/stories/${story.id}`}
className="block hover:underline"
>
<h3 className="font-medium theme-header truncate">
{story.title}
</h3>
</Link>
<p className="text-sm theme-text opacity-70 truncate">
by {story.authorName}
</p>
<div className="flex items-center gap-4 mt-1 text-xs theme-text opacity-60">
<span>{story.wordCount?.toLocaleString()} words</span>
{story.rating && (
<span className="flex items-center">
{story.rating}
</span>
)}
</div>
</div>
{/* Action Buttons */}
<div className="flex flex-col gap-1">
<button
onClick={() => moveStoryUp(index)}
disabled={index === 0 || reordering}
className="p-1 text-gray-400 hover:text-gray-600 disabled:opacity-30 disabled:cursor-not-allowed"
title="Move up"
>
</button>
<button
onClick={() => moveStoryDown(index)}
disabled={index === stories.length - 1 || reordering}
className="p-1 text-gray-400 hover:text-gray-600 disabled:opacity-30 disabled:cursor-not-allowed"
title="Move down"
>
</button>
</div>
{/* Remove Button */}
<button
onClick={() => handleRemoveStory(story.id)}
disabled={reordering}
className="p-2 text-red-500 hover:text-red-700 disabled:opacity-30 disabled:cursor-not-allowed"
title="Remove from collection"
>
×
</button>
</div>
);
})}
{reordering && (
<div className="text-center py-4 theme-text opacity-70">
<span className="inline-flex items-center gap-2">
<div className="w-4 h-4 border-2 border-blue-500 border-t-transparent rounded-full animate-spin"></div>
Reordering stories...
</span>
</div>
)}
</div>
);
}

View File

@@ -45,6 +45,12 @@ export default function Header() {
>
Library
</Link>
<Link
href="/collections"
className="theme-text hover:theme-accent transition-colors font-medium"
>
Collections
</Link>
<Link
href="/authors"
className="theme-text hover:theme-accent transition-colors font-medium"
@@ -111,6 +117,13 @@ export default function Header() {
>
Library
</Link>
<Link
href="/collections"
className="theme-text hover:theme-accent transition-colors font-medium px-2 py-1"
onClick={() => setIsMenuOpen(false)}
>
Collections
</Link>
<Link
href="/authors"
className="theme-text hover:theme-accent transition-colors font-medium px-2 py-1"

View File

@@ -10,10 +10,20 @@ import Button from '../ui/Button';
interface StoryCardProps {
story: Story;
viewMode: 'grid' | 'list';
onUpdate: () => void;
onUpdate?: () => void;
showSelection?: boolean;
isSelected?: boolean;
onSelect?: () => void;
}
export default function StoryCard({ story, viewMode, onUpdate }: StoryCardProps) {
export default function StoryCard({
story,
viewMode,
onUpdate,
showSelection = false,
isSelected = false,
onSelect
}: StoryCardProps) {
const [rating, setRating] = useState(story.rating || 0);
const [updating, setUpdating] = useState(false);
@@ -24,7 +34,7 @@ export default function StoryCard({ story, viewMode, onUpdate }: StoryCardProps)
setUpdating(true);
await storyApi.updateRating(story.id, newRating);
setRating(newRating);
onUpdate();
onUpdate?.();
} catch (error) {
console.error('Failed to update rating:', error);
} finally {

View File

@@ -0,0 +1,131 @@
'use client';
import { useState } from 'react';
import { Story } from '../../types/api';
import StoryCard from './StoryCard';
import StorySelectionToolbar from './StorySelectionToolbar';
interface StoryMultiSelectProps {
stories: Story[];
viewMode: 'grid' | 'list';
onUpdate?: () => void;
allowMultiSelect?: boolean;
}
export default function StoryMultiSelect({
stories,
viewMode,
onUpdate,
allowMultiSelect = true
}: StoryMultiSelectProps) {
const [selectedStoryIds, setSelectedStoryIds] = useState<string[]>([]);
const [isSelectionMode, setIsSelectionMode] = useState(false);
const handleStorySelect = (storyId: string) => {
setSelectedStoryIds(prev => {
if (prev.includes(storyId)) {
const newSelection = prev.filter(id => id !== storyId);
if (newSelection.length === 0) {
setIsSelectionMode(false);
}
return newSelection;
} else {
if (!isSelectionMode) {
setIsSelectionMode(true);
}
return [...prev, storyId];
}
});
};
const handleSelectAll = () => {
if (selectedStoryIds.length === stories.length) {
setSelectedStoryIds([]);
setIsSelectionMode(false);
} else {
setSelectedStoryIds(stories.map(story => story.id));
setIsSelectionMode(true);
}
};
const handleClearSelection = () => {
setSelectedStoryIds([]);
setIsSelectionMode(false);
};
const handleBatchOperation = (operation: string) => {
// This will trigger the appropriate action based on the operation
console.log(`Batch operation: ${operation} on stories:`, selectedStoryIds);
// After operation, clear selection
setSelectedStoryIds([]);
setIsSelectionMode(false);
onUpdate?.();
};
if (stories.length === 0) {
return (
<div className="text-center py-20">
<div className="theme-text text-lg mb-4">
No stories found
</div>
</div>
);
}
return (
<div className="space-y-4">
{/* Selection Toolbar */}
{allowMultiSelect && (
<StorySelectionToolbar
selectedCount={selectedStoryIds.length}
totalCount={stories.length}
isSelectionMode={isSelectionMode}
onSelectAll={handleSelectAll}
onClearSelection={handleClearSelection}
onBatchOperation={handleBatchOperation}
selectedStoryIds={selectedStoryIds}
/>
)}
{/* Stories Grid/List */}
<div className={
viewMode === 'grid'
? 'grid grid-cols-1 sm:grid-cols-2 lg:grid-cols-3 xl:grid-cols-4 gap-6'
: 'space-y-4'
}>
{stories.map((story) => (
<div key={story.id} className="relative">
{/* Selection Checkbox */}
{allowMultiSelect && (isSelectionMode || selectedStoryIds.includes(story.id)) && (
<div className="absolute top-2 left-2 z-10">
<input
type="checkbox"
checked={selectedStoryIds.includes(story.id)}
onChange={() => handleStorySelect(story.id)}
className="w-5 h-5 rounded border-gray-300 text-blue-600 focus:ring-blue-500 bg-white shadow-lg"
/>
</div>
)}
{/* Story Card */}
<div
className={`transition-all duration-200 ${
selectedStoryIds.includes(story.id) ? 'ring-2 ring-blue-500 ring-opacity-50' : ''
}`}
onDoubleClick={() => allowMultiSelect && handleStorySelect(story.id)}
>
<StoryCard
story={story}
viewMode={viewMode}
onUpdate={onUpdate}
showSelection={isSelectionMode}
isSelected={selectedStoryIds.includes(story.id)}
onSelect={() => handleStorySelect(story.id)}
/>
</div>
</div>
))}
</div>
</div>
);
}

View File

@@ -0,0 +1,251 @@
'use client';
import { useState } from 'react';
import { collectionApi } from '../../lib/api';
import { Collection } from '../../types/api';
import Button from '../ui/Button';
import LoadingSpinner from '../ui/LoadingSpinner';
interface StorySelectionToolbarProps {
selectedCount: number;
totalCount: number;
isSelectionMode: boolean;
onSelectAll: () => void;
onClearSelection: () => void;
onBatchOperation: (operation: string) => void;
selectedStoryIds: string[];
}
export default function StorySelectionToolbar({
selectedCount,
totalCount,
isSelectionMode,
onSelectAll,
onClearSelection,
onBatchOperation,
selectedStoryIds
}: StorySelectionToolbarProps) {
const [showAddToCollection, setShowAddToCollection] = useState(false);
const [collections, setCollections] = useState<Collection[]>([]);
const [loadingCollections, setLoadingCollections] = useState(false);
const [addingToCollection, setAddingToCollection] = useState(false);
const [newCollectionName, setNewCollectionName] = useState('');
const [showCreateNew, setShowCreateNew] = useState(false);
const loadCollections = async () => {
try {
setLoadingCollections(true);
const result = await collectionApi.getCollections({
page: 0,
limit: 50,
archived: false,
});
setCollections(result.results || []);
} catch (error) {
console.error('Failed to load collections:', error);
} finally {
setLoadingCollections(false);
}
};
const handleShowAddToCollection = async () => {
setShowAddToCollection(true);
await loadCollections();
};
const handleAddToExistingCollection = async (collectionId: string) => {
try {
setAddingToCollection(true);
await collectionApi.addStoriesToCollection(collectionId, selectedStoryIds);
setShowAddToCollection(false);
onBatchOperation('addToCollection');
} catch (error) {
console.error('Failed to add stories to collection:', error);
} finally {
setAddingToCollection(false);
}
};
const handleCreateNewCollection = async () => {
if (!newCollectionName.trim()) return;
try {
setAddingToCollection(true);
const collection = await collectionApi.createCollection({
name: newCollectionName.trim(),
storyIds: selectedStoryIds,
});
setShowAddToCollection(false);
setNewCollectionName('');
setShowCreateNew(false);
onBatchOperation('createCollection');
} catch (error) {
console.error('Failed to create collection:', error);
} finally {
setAddingToCollection(false);
}
};
if (!isSelectionMode && selectedCount === 0) {
return null;
}
return (
<>
<div className="bg-blue-50 dark:bg-blue-900/20 border border-blue-200 dark:border-blue-800 rounded-lg p-4">
<div className="flex items-center justify-between flex-wrap gap-4">
{/* Selection Info */}
<div className="flex items-center gap-4">
<span className="font-medium text-blue-900 dark:text-blue-100">
{selectedCount} of {totalCount} stories selected
</span>
<Button
variant="ghost"
size="sm"
onClick={selectedCount === totalCount ? onClearSelection : onSelectAll}
className="text-blue-600 hover:text-blue-800 dark:text-blue-400"
>
{selectedCount === totalCount ? 'Deselect All' : 'Select All'}
</Button>
{selectedCount > 0 && (
<Button
variant="ghost"
size="sm"
onClick={onClearSelection}
className="text-blue-600 hover:text-blue-800 dark:text-blue-400"
>
Clear
</Button>
)}
</div>
{/* Batch Actions */}
{selectedCount > 0 && (
<div className="flex items-center gap-2">
<Button
size="sm"
onClick={handleShowAddToCollection}
disabled={addingToCollection}
>
Add to Collection
</Button>
</div>
)}
</div>
</div>
{/* Add to Collection Modal */}
{showAddToCollection && (
<div className="fixed inset-0 bg-black bg-opacity-50 flex items-center justify-center z-50 p-4">
<div className="theme-card max-w-lg w-full max-h-[80vh] overflow-hidden flex flex-col">
{/* Header */}
<div className="flex items-center justify-between p-6 border-b theme-border">
<h2 className="text-xl font-semibold theme-header">
Add {selectedCount} Stories to Collection
</h2>
<button
onClick={() => {
setShowAddToCollection(false);
setShowCreateNew(false);
setNewCollectionName('');
}}
disabled={addingToCollection}
className="text-gray-500 hover:text-gray-700 disabled:opacity-50"
>
×
</button>
</div>
{/* Content */}
<div className="flex-1 overflow-y-auto p-6">
{loadingCollections ? (
<div className="flex justify-center py-8">
<LoadingSpinner size="md" />
</div>
) : (
<div className="space-y-4">
{/* Create New Collection */}
<div className="space-y-3">
<button
onClick={() => setShowCreateNew(!showCreateNew)}
className="w-full p-3 border-2 border-dashed theme-border rounded-lg theme-text hover:border-gray-400 transition-colors"
>
+ Create New Collection
</button>
{showCreateNew && (
<div className="space-y-3">
<input
type="text"
value={newCollectionName}
onChange={(e) => setNewCollectionName(e.target.value)}
placeholder="Enter collection name"
className="w-full px-3 py-2 border theme-border rounded-lg theme-card theme-text focus:outline-none focus:ring-2 focus:ring-blue-500"
onKeyDown={(e) => {
if (e.key === 'Enter') {
handleCreateNewCollection();
}
}}
/>
<div className="flex gap-2">
<Button
size="sm"
onClick={handleCreateNewCollection}
disabled={!newCollectionName.trim() || addingToCollection}
>
{addingToCollection ? <LoadingSpinner size="sm" /> : 'Create'}
</Button>
<Button
variant="ghost"
size="sm"
onClick={() => {
setShowCreateNew(false);
setNewCollectionName('');
}}
disabled={addingToCollection}
>
Cancel
</Button>
</div>
</div>
)}
</div>
{/* Existing Collections */}
{collections.length > 0 && (
<div className="space-y-2">
<h3 className="font-medium theme-text">Add to Existing Collection:</h3>
<div className="space-y-2 max-h-64 overflow-y-auto">
{collections.map((collection) => (
<button
key={collection.id}
onClick={() => handleAddToExistingCollection(collection.id)}
disabled={addingToCollection}
className="w-full p-3 text-left theme-card hover:border-gray-400 border theme-border rounded-lg transition-colors disabled:opacity-50"
>
<div className="font-medium theme-text">{collection.name}</div>
<div className="text-sm theme-text opacity-70">
{collection.storyCount} stories
</div>
</button>
))}
</div>
</div>
)}
{collections.length === 0 && !loadingCollections && (
<div className="text-center py-8 theme-text opacity-70">
No collections found. Create a new one above.
</div>
)}
</div>
)}
</div>
</div>
</div>
)}
</>
);
}

View File

@@ -1,5 +1,5 @@
import axios from 'axios';
import { AuthResponse, Story, Author, Tag, Series, SearchResult, PagedResult } from '../types/api';
import { AuthResponse, Story, Author, Tag, Series, SearchResult, PagedResult, Collection, CollectionSearchResult, StoryWithCollectionContext, CollectionStatistics } from '../types/api';
const API_BASE_URL = process.env.NEXT_PUBLIC_API_URL || '/api';
@@ -136,6 +136,11 @@ export const storyApi = {
return response.data;
},
getStoryCollections: async (storyId: string): Promise<Collection[]> => {
const response = await api.get(`/stories/${storyId}/collections`);
return response.data;
},
reindexTypesense: async (): Promise<{ success: boolean; message: string; count?: number; error?: string }> => {
const response = await api.post('/stories/reindex-typesense');
return response.data;
@@ -307,6 +312,141 @@ export const configApi = {
},
};
// Collection endpoints
export const collectionApi = {
getCollections: async (params?: {
page?: number;
limit?: number;
search?: string;
tags?: string[];
archived?: boolean;
}): Promise<CollectionSearchResult> => {
// Create URLSearchParams to properly handle array parameters
const searchParams = new URLSearchParams();
if (params?.page !== undefined) searchParams.append('page', params.page.toString());
if (params?.limit !== undefined) searchParams.append('limit', params.limit.toString());
if (params?.search) searchParams.append('search', params.search);
if (params?.archived !== undefined) searchParams.append('archived', params.archived.toString());
// Add array parameters - each element gets its own parameter
if (params?.tags && params.tags.length > 0) {
params.tags.forEach(tag => searchParams.append('tags', tag));
}
const response = await api.get(`/collections?${searchParams.toString()}`);
return response.data;
},
getCollection: async (id: string): Promise<Collection> => {
const response = await api.get(`/collections/${id}`);
return response.data;
},
createCollection: async (collectionData: {
name: string;
description?: string;
tagNames?: string[];
storyIds?: string[];
}): Promise<Collection> => {
const response = await api.post('/collections', collectionData);
return response.data;
},
createCollectionWithImage: async (collectionData: {
name: string;
description?: string;
tags?: string[];
storyIds?: string[];
coverImage?: File;
}): Promise<Collection> => {
const formData = new FormData();
formData.append('name', collectionData.name);
if (collectionData.description) formData.append('description', collectionData.description);
if (collectionData.tags) {
collectionData.tags.forEach(tag => formData.append('tags', tag));
}
if (collectionData.storyIds) {
collectionData.storyIds.forEach(id => formData.append('storyIds', id));
}
if (collectionData.coverImage) {
formData.append('coverImage', collectionData.coverImage);
}
const response = await api.post('/collections', formData, {
headers: { 'Content-Type': 'multipart/form-data' },
});
return response.data;
},
updateCollection: async (id: string, collectionData: {
name?: string;
description?: string;
tagNames?: string[];
rating?: number;
}): Promise<Collection> => {
const response = await api.put(`/collections/${id}`, collectionData);
return response.data;
},
deleteCollection: async (id: string): Promise<void> => {
await api.delete(`/collections/${id}`);
},
archiveCollection: async (id: string, archived: boolean): Promise<Collection> => {
const response = await api.put(`/collections/${id}/archive`, { archived });
return response.data;
},
addStoriesToCollection: async (id: string, storyIds: string[], position?: number): Promise<{
added: number;
skipped: number;
totalStories: number;
}> => {
const response = await api.post(`/collections/${id}/stories`, {
storyIds,
position,
});
return response.data;
},
removeStoryFromCollection: async (collectionId: string, storyId: string): Promise<void> => {
await api.delete(`/collections/${collectionId}/stories/${storyId}`);
},
reorderStories: async (collectionId: string, storyOrders: Array<{
storyId: string;
position: number;
}>): Promise<void> => {
await api.put(`/collections/${collectionId}/stories/order`, {
storyOrders,
});
},
getStoryWithCollectionContext: async (collectionId: string, storyId: string): Promise<StoryWithCollectionContext> => {
const response = await api.get(`/collections/${collectionId}/read/${storyId}`);
return response.data;
},
getCollectionStatistics: async (id: string): Promise<CollectionStatistics> => {
const response = await api.get(`/collections/${id}/stats`);
return response.data;
},
uploadCover: async (id: string, coverImage: File): Promise<{ imagePath: string }> => {
const formData = new FormData();
formData.append('file', coverImage);
const response = await api.post(`/collections/${id}/cover`, formData, {
headers: { 'Content-Type': 'multipart/form-data' },
});
return response.data;
},
removeCover: async (id: string): Promise<void> => {
await api.delete(`/collections/${id}/cover`);
},
};
// Image utility
export const getImageUrl = (path: string): string => {
if (!path) return '';

View File

@@ -75,4 +75,64 @@ export interface PagedResult<T> {
first: boolean;
last: boolean;
empty: boolean;
}
export interface Collection {
id: string;
name: string;
description?: string;
rating?: number;
coverImagePath?: string;
isArchived: boolean;
tags: Tag[];
collectionStories?: CollectionStory[];
stories?: CollectionStory[]; // For compatibility
storyCount: number;
totalWordCount?: number;
estimatedReadingTime?: number;
averageStoryRating?: number;
createdAt: string;
updatedAt: string;
}
export interface CollectionStory {
story: Story;
position: number;
addedAt: string;
}
export interface CollectionSearchResult {
results: Collection[];
totalHits: number;
page: number;
perPage: number;
query: string;
searchTimeMs: number;
}
export interface CollectionReadingContext {
id: string;
name: string;
currentPosition: number;
totalStories: number;
previousStoryId?: string;
nextStoryId?: string;
}
export interface StoryWithCollectionContext {
story: Story;
collection: CollectionReadingContext;
}
export interface CollectionStatistics {
totalStories: number;
totalWordCount: number;
estimatedReadingTime: number;
averageStoryRating: number;
averageWordCount: number;
tagFrequency: Record<string, number>;
authorDistribution: Array<{
authorName: string;
storyCount: number;
}>;
}