-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathFeedsPage.tsx
More file actions
358 lines (331 loc) · 13.9 KB
/
Copy pathFeedsPage.tsx
File metadata and controls
358 lines (331 loc) · 13.9 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
/**
* Feeds Page - Main landing page
* Shows all subscribed feeds grouped by category with add/refresh/delete support
* Features: floating add button, category grouping, bottom filter banner
* Auto-refreshes feeds on mount
*/
import { useEffect, useState, useCallback, useRef, useMemo } from 'react';
import { useTranslation } from 'react-i18next';
import { Link } from 'react-router-dom';
import { Plus, RefreshCw, Rss, Trash2, Star, BookOpen, List } from 'lucide-react';
import { useStore } from '@hooks/useStore';
import { storage } from '@lib/storage';
import { syncService } from '@services/syncService';
import { AddFeedDialog } from '@components/AddFeedDialog/AddFeedDialog';
import { FeedCardSkeleton } from '@components/Common/Skeleton';
import type { Article } from '@models/Feed';
export function FeedsPage() {
const { t } = useTranslation('feed');
const { t: tCommon } = useTranslation('common');
const {
feeds,
categories,
isLoading,
error,
isAddFeedDialogOpen,
feedsFilter,
loadFeeds,
loadCategories,
openAddFeedDialog,
closeAddFeedDialog,
unsubscribeFeed,
setError,
setFeedsFilter,
} = useStore();
const [isRefreshing, setIsRefreshing] = useState(false);
const [articleCounts, setArticleCounts] = useState<Record<string, { total: number; unread: number; starred: number }>>({});
const [isBottomBarVisible, setIsBottomBarVisible] = useState(true);
const [sharedFeedUrl, setSharedFeedUrl] = useState('');
const lastScrollY = useRef(0);
// Handle PWA shortcuts (?action=add-feed) and Web Share Target (?url=... or ?text=...)
useEffect(() => {
const params = new URLSearchParams(window.location.search);
const action = params.get('action');
const sharedUrl = params.get('url') || params.get('text');
if (action === 'add-feed') {
openAddFeedDialog();
} else if (sharedUrl) {
// If the param is plain text with an embedded URL, extract it
let feedUrl = sharedUrl;
if (!/^https?:\/\//i.test(feedUrl)) {
const match = sharedUrl.match(/https?:\/\/[^\s]+/i);
feedUrl = match ? match[0] : sharedUrl;
}
setSharedFeedUrl(feedUrl);
openAddFeedDialog();
}
}, [openAddFeedDialog]);
// Load feeds, categories and start auto-refresh on mount
useEffect(() => {
let cancelled = false;
const init = async () => {
await storage.init().catch(() => { /* already initialized */ });
await Promise.all([loadFeeds(), loadCategories()]);
if (cancelled) return;
setIsRefreshing(true);
await syncService.refreshAllFeeds().catch(() => { /* background refresh failure */ });
if (cancelled) return;
await loadFeeds();
setIsRefreshing(false);
};
init();
return () => { cancelled = true; };
}, [loadFeeds, loadCategories]);
// Load article counts whenever feeds change
useEffect(() => {
const loadCounts = async () => {
const counts: Record<string, { total: number; unread: number; starred: number }> = {};
for (const feed of feeds) {
try {
const articles = await storage.getAllByIndex('articles', 'feedId', feed.id) as Article[];
counts[feed.id] = {
total: articles.length,
unread: articles.filter(a => !a.readAt).length,
starred: articles.filter(a => a.isFavorite).length,
};
} catch {
counts[feed.id] = { total: 0, unread: 0, starred: 0 };
}
}
setArticleCounts(counts);
};
if (feeds.length > 0) {
loadCounts();
}
}, [feeds]);
// Scroll handler for hiding/showing bottom bar
useEffect(() => {
const handleScroll = () => {
const currentScrollY = window.scrollY;
setIsBottomBarVisible(currentScrollY <= lastScrollY.current || currentScrollY < 10);
lastScrollY.current = currentScrollY;
};
window.addEventListener('scroll', handleScroll, { passive: true });
return () => window.removeEventListener('scroll', handleScroll);
}, []);
const handleRefresh = useCallback(async () => {
setIsRefreshing(true);
try {
await syncService.refreshAllFeeds();
await loadFeeds();
} catch {
setError('Failed to refresh feeds');
} finally {
setIsRefreshing(false);
}
}, [loadFeeds, setError]);
const handleDelete = useCallback(async (feedId: string, e: React.MouseEvent) => {
e.preventDefault();
e.stopPropagation();
if (window.confirm('Are you sure you want to unsubscribe from this feed?')) {
await unsubscribeFeed(feedId);
}
}, [unsubscribeFeed]);
// Filter feeds based on the current filter
const countsLoaded = Object.keys(articleCounts).length > 0;
const filteredFeeds = useMemo(() => {
if (feedsFilter === 'all' || !countsLoaded) return feeds;
return feeds.filter(feed => {
const counts = articleCounts[feed.id];
if (!counts) return false;
if (feedsFilter === 'unread') return counts.unread > 0;
if (feedsFilter === 'starred') return counts.starred > 0;
return true;
});
}, [feeds, feedsFilter, articleCounts, countsLoaded]);
// Group filtered feeds by category
const groupedFeeds = useMemo(() => {
const groups: { id: string; name: string; feeds: typeof filteredFeeds }[] = [];
// Group by category
const grouped = new Map<string, typeof filteredFeeds>();
for (const feed of filteredFeeds) {
const key = feed.categoryId || '__uncategorized__';
if (!grouped.has(key)) grouped.set(key, []);
grouped.get(key)!.push(feed);
}
// Ordered categories first
for (const category of [...categories].sort((a, b) => a.order - b.order)) {
const categoryFeeds = grouped.get(category.id);
if (categoryFeeds && categoryFeeds.length > 0) {
groups.push({ id: category.id, name: category.name, feeds: categoryFeeds });
}
}
// Uncategorized last
const uncategorized = grouped.get('__uncategorized__');
if (uncategorized && uncategorized.length > 0) {
groups.push({ id: '__uncategorized__', name: 'Uncategorized', feeds: uncategorized });
}
return groups;
}, [filteredFeeds, categories]);
const filterTabs = [
{ key: 'starred' as const, label: t('starred'), icon: Star },
{ key: 'unread' as const, label: t('unread'), icon: BookOpen },
{ key: 'all' as const, label: t('all'), icon: List },
];
return (
<div className="mx-auto max-w-4xl pb-20">
{/* Header */}
<div className="mb-6 flex items-center justify-between">
<h1 className="text-2xl font-bold text-foreground">{t('title')}</h1>
<div className="flex items-center gap-2">
<button
onClick={handleRefresh}
disabled={isRefreshing}
className="inline-flex items-center gap-1.5 rounded-md border border-border bg-card px-3 py-2 text-sm font-medium text-card-foreground transition-colors hover:bg-accent disabled:opacity-50"
title={t('refreshAll')}
>
<RefreshCw className={`h-4 w-4 ${isRefreshing ? 'animate-spin' : ''}`} />
<span className="hidden sm:inline">{isRefreshing ? tCommon('refreshing') : tCommon('refresh')}</span>
</button>
</div>
</div>
{/* Error */}
{error && (
<div className="mb-4 rounded-md border border-destructive/50 bg-destructive/10 p-3 text-sm text-destructive">
{error}
<button onClick={() => setError(null)} className="ml-2 underline">Dismiss</button>
</div>
)}
{/* Loading */}
{isLoading && !feeds.length && (
<div className="space-y-3">
{Array.from({ length: 6 }).map((_, i) => (
<FeedCardSkeleton key={i} />
))}
</div>
)}
{/* Empty State */}
{!isLoading && feeds.length === 0 && (
<div className="flex flex-col items-center justify-center rounded-lg border-2 border-dashed border-border py-16 text-center">
<Rss className="mb-4 h-12 w-12 text-muted-foreground" />
<h2 className="mb-2 text-lg font-semibold text-foreground">{t('noFeeds')}</h2>
<p className="mb-6 text-sm text-muted-foreground">
{t('noFeedsHint')}
</p>
<button
onClick={openAddFeedDialog}
className="inline-flex items-center gap-2 rounded-md bg-primary px-4 py-2 text-sm font-medium text-primary-foreground hover:bg-primary/90"
>
<Plus className="h-4 w-4" />
{t('addFeed')}
</button>
</div>
)}
{/* Feed List grouped by category */}
{feeds.length > 0 && (
<div className="space-y-6">
{groupedFeeds.length === 0 && (
<div className="flex flex-col items-center justify-center rounded-lg border-2 border-dashed border-border py-12 text-center">
<Rss className="mb-3 h-10 w-10 text-muted-foreground" />
<p className="text-sm text-muted-foreground">
{feedsFilter === 'starred' ? t('noStarredFeeds') : t('noUnreadFeeds')}
</p>
</div>
)}
{groupedFeeds.map((group) => (
<div key={group.id}>
<h2 className="mb-3 text-sm font-semibold uppercase tracking-wider text-muted-foreground">
{group.name}
</h2>
<div className="space-y-3">
{group.feeds.map((feed) => {
const counts = articleCounts[feed.id] || { total: 0, unread: 0, starred: 0 };
return (
<Link
key={feed.id}
to={`/feeds/${feed.id}`}
className="flex items-center gap-4 rounded-lg border border-border bg-card p-4 transition-colors hover:bg-accent group"
>
{/* Feed Icon */}
<div className="flex h-10 w-10 shrink-0 items-center justify-center rounded-lg bg-secondary text-secondary-foreground">
{feed.iconUrl ? (
<img src={feed.iconUrl} alt="" className="h-10 w-10 rounded-lg object-cover" />
) : (
<Rss className="h-5 w-5" />
)}
</div>
{/* Feed Info */}
<div className="min-w-0 flex-1">
<div className="flex items-center gap-2">
<h3 className="truncate text-sm font-semibold text-card-foreground">
{feed.title}
</h3>
{counts.unread > 0 && (
<span className="shrink-0 rounded-full bg-primary px-2 py-0.5 text-xs font-medium text-primary-foreground">
{counts.unread}
</span>
)}
</div>
{feed.description && (
<p className="mt-0.5 truncate text-xs text-muted-foreground">
{feed.description}
</p>
)}
<div className="mt-1 flex items-center gap-3 text-xs text-muted-foreground">
<span>{counts.total} {t('articles')}</span>
{feed.lastFetchedAt && (
<span>{t('updated')} {new Date(feed.lastFetchedAt).toLocaleDateString()}</span>
)}
</div>
</div>
{/* Delete Button */}
<button
onClick={(e) => handleDelete(feed.id, e)}
className="shrink-0 rounded-md p-2 text-muted-foreground transition-all hover:bg-destructive/10 hover:text-destructive md:opacity-0 md:group-hover:opacity-100"
title={t('unsubscribe')}
aria-label={`${t('unsubscribe')} ${feed.title}`}
>
<Trash2 className="h-4 w-4" />
</button>
</Link>
);
})}
</div>
</div>
))}
</div>
)}
{/* Floating Add Feed Button (FAB) */}
<button
onClick={openAddFeedDialog}
className="fixed bottom-20 right-4 z-50 flex h-14 w-14 items-center justify-center rounded-full bg-primary text-primary-foreground shadow-lg transition-transform hover:scale-105 hover:bg-primary/90 active:scale-95"
title={t('addFeed')}
aria-label={t('addFeed')}
>
<Plus className="h-6 w-6" />
</button>
{/* Bottom Filter Banner */}
<div
className={`fixed bottom-0 left-0 right-0 z-40 border-t border-border bg-card/95 backdrop-blur-sm transition-transform duration-300 ${
isBottomBarVisible ? 'translate-y-0' : 'translate-y-full'
}`}
style={{ paddingBottom: 'env(safe-area-inset-bottom, 0)' }}
>
<div className="mx-auto flex max-w-4xl items-center justify-around px-4 py-2">
{filterTabs.map(({ key, label, icon: Icon }) => (
<button
key={key}
onClick={() => setFeedsFilter(key)}
className={`inline-flex flex-col items-center gap-0.5 rounded-md px-3 py-1.5 text-xs transition-colors ${
feedsFilter === key
? 'text-primary font-semibold'
: 'text-muted-foreground hover:text-foreground'
}`}
aria-label={label}
aria-pressed={feedsFilter === key}
>
<Icon className="h-5 w-5" fill={feedsFilter === key ? 'currentColor' : 'none'} />
<span>{label}</span>
</button>
))}
</div>
</div>
{/* Add Feed Dialog */}
<AddFeedDialog
isOpen={isAddFeedDialogOpen}
onClose={() => { closeAddFeedDialog(); setSharedFeedUrl(''); }}
initialUrl={sharedFeedUrl}
/>
</div>
);
}