App.tsx (10381B)
1 import { useEffect, useState, useMemo } from "react" 2 import { Button } from "@/components/ui/button" 3 import { Badge } from "@/components/ui/badge" 4 import { useTheme } from "@/components/theme-provider" 5 import { Moon, Sun } from "lucide-react" 6 import { 7 Sidebar, 8 SidebarContent, 9 SidebarGroup, 10 SidebarGroupContent, 11 SidebarHeader, 12 SidebarInset, 13 SidebarMenu, 14 SidebarMenuButton, 15 SidebarMenuItem, 16 SidebarProvider, 17 SidebarTrigger, 18 } from "@/components/ui/sidebar" 19 import { ScrollArea } from "@/components/ui/scroll-area" 20 21 const getText = (val?: string | XMLTextElement): string => 22 typeof val === "string" ? val : val?.["#text"] || "" 23 const getHref = (val?: string | XMLTextElement): string => 24 typeof val === "string" ? val : val?.["@href"] || "" 25 26 interface XMLTextElement { 27 "#text"?: string 28 [attr: string]: string | undefined 29 } 30 31 interface FeedItem { 32 feedTitle: string 33 title: string 34 description: string 35 link: string 36 pubDate: string 37 encoded?: string 38 } 39 40 interface Feed { 41 name: string 42 title: string 43 description: string 44 items: FeedItem[] 45 } 46 47 interface RawFeedItem { 48 title?: string | XMLTextElement 49 description?: string 50 link?: string | XMLTextElement 51 pubDate?: string 52 encoded?: string 53 url?: string 54 date_published?: string 55 content_html?: string 56 content_text?: string 57 published?: string 58 updated?: string 59 summary?: string | XMLTextElement 60 content?: string | XMLTextElement 61 } 62 63 interface FeedItemComponentProps { 64 item: FeedItem 65 } 66 67 function FeedItemComponent({ item }: FeedItemComponentProps) { 68 const cleanedText = item.description.replace(/<[^>]*>/g, "").trim() 69 70 const colorClasses = [ 71 "bg-blue-100 text-blue-800", 72 "bg-green-100 text-green-800", 73 "bg-yellow-100 text-yellow-800", 74 "bg-red-100 text-red-800", 75 "bg-purple-100 text-purple-800", 76 "bg-indigo-100 text-indigo-800", 77 "bg-pink-100 text-pink-800", 78 "bg-gray-100 text-gray-800", 79 "bg-orange-100 text-orange-800", 80 "bg-teal-100 text-teal-800", 81 ] 82 83 const hash = (str: string) => { 84 let h = 0 85 for (let i = 0; i < str.length; i++) { 86 h = str.charCodeAt(i) + ((h << 5) - h) 87 } 88 return Math.abs(h) 89 } 90 91 const colorIndex = hash(item.feedTitle) % colorClasses.length 92 93 return ( 94 <div className="animate-in rounded-lg border p-4 duration-500 fade-in slide-in-from-bottom-2"> 95 <h3 className="mb-1 font-semibold"> 96 <a 97 href={item.link} 98 target="_blank" 99 rel="noopener noreferrer" 100 className="hover:underline" 101 > 102 {item.title} 103 </a> 104 </h3> 105 <p className="mb-2 text-sm text-muted-foreground">{cleanedText}</p> 106 <Badge className={`mr-2 ${colorClasses[colorIndex]}`}> 107 {item.feedTitle} 108 </Badge> 109 <Badge variant="secondary"> 110 {new Date(item.pubDate).toLocaleDateString()} 111 </Badge> 112 </div> 113 ) 114 } 115 116 export function App() { 117 const [feeds, setFeeds] = useState<Feed[]>([]) 118 const [selectedFeeds, setSelectedFeeds] = useState<Set<string>>(new Set()) 119 const [loading, setLoading] = useState(true) 120 121 const filteredItems = useMemo(() => { 122 const selectedFeedNames = selectedFeeds 123 const selectedFeedList = feeds.filter((feed) => 124 selectedFeedNames.has(feed.name) 125 ) 126 const items = selectedFeedList.flatMap((feed) => 127 feed.items.map((item) => ({ ...item, feedTitle: feed.title })) 128 ) 129 return items.sort( 130 (a, b) => new Date(b.pubDate).getTime() - new Date(a.pubDate).getTime() 131 ) 132 }, [feeds, selectedFeeds]) 133 134 const handleFeedToggle = (feedName: string) => { 135 setSelectedFeeds((prev) => { 136 const total = feeds.length 137 if (prev.size === total) { 138 // All selected, clicking any feed: select only this one 139 return new Set([feedName]) 140 } else if (prev.size === 1 && prev.has(feedName)) { 141 // This feed is the only one selected, clicking it again: select all 142 return new Set(feeds.map((f) => f.name)) 143 } else { 144 // Clicked a different feed when one is selected: select this one 145 return new Set([feedName]) 146 } 147 }) 148 } 149 150 const { theme, setTheme } = useTheme() 151 const toggleTheme = () => setTheme(theme === "dark" ? "light" : "dark") 152 153 const basePath = import.meta.env.VITE_BASE_PATH || "" 154 155 useEffect(() => { 156 async function loadFeeds() { 157 try { 158 const csvResponse = await fetch(`${basePath}/feeds/feeds.csv`) 159 const csvText = await csvResponse.text() 160 const lines = csvText.trim().split("\n") 161 const feedPromises = lines.map(async (line) => { 162 try { 163 const [displayName, , file] = line.split(",") 164 const jsonResponse = await fetch(`${basePath}/feeds/${file}.json`) 165 if (!jsonResponse.ok) 166 throw new Error(`Fetch failed: ${jsonResponse.status}`) 167 const data = await jsonResponse.json() 168 169 let description: string, rawItems: RawFeedItem[] 170 const title = displayName 171 172 if (data.rss?.channel) { 173 // RSS format 174 const channel = data.rss.channel 175 description = channel.description || "" 176 rawItems = Array.isArray(channel.item) ? channel.item : [] 177 } else if (data.version && Array.isArray(data.items)) { 178 // JSON Feed format 179 description = data.description || "" 180 rawItems = data.items 181 } else if (data.feed?.entry) { 182 // Atom format 183 const feed = data.feed 184 description = feed.subtitle?.["#text"] || feed.subtitle || "" 185 rawItems = Array.isArray(feed.entry) ? feed.entry : [feed.entry] 186 } else { 187 // Unknown format, skip 188 return null 189 } 190 191 const items: FeedItem[] = rawItems 192 .map((item) => { 193 if ( 194 item.title && 195 item.description && 196 item.link && 197 item.pubDate 198 ) { 199 // RSS item 200 return { 201 title: item.title, 202 description: item.description, 203 link: item.link, 204 pubDate: item.pubDate, 205 encoded: item.encoded, 206 } as FeedItem 207 } else if ( 208 item.title && 209 (item.content_html || item.content_text) && 210 item.url 211 ) { 212 // JsonFeed item 213 return { 214 title: item.title, 215 description: item.content_text || item.content_html || "", 216 link: item.url, 217 pubDate: item.date_published || new Date().toISOString(), 218 } as FeedItem 219 } else if (item.published || item.updated) { 220 // Atom entry 221 return { 222 title: getText(item.title), 223 description: 224 getText(item.summary) || getText(item.content) || "", 225 link: getHref(item.link), 226 pubDate: item.published || item.updated, 227 } as FeedItem 228 } else { 229 // Unknown item format, skip 230 return null 231 } 232 }) 233 .filter(Boolean) as FeedItem[] 234 235 const feed: Feed = { 236 name: file, 237 title, 238 description, 239 items, 240 } 241 return feed 242 } catch (error) { 243 console.error(`Error processing feed ${line}:`, error) 244 return null 245 } 246 }) 247 const loadedFeeds = (await Promise.all(feedPromises)).filter( 248 Boolean 249 ) as Feed[] 250 setFeeds(loadedFeeds) 251 setSelectedFeeds(new Set(loadedFeeds.map((f) => f.name))) 252 } catch (error) { 253 console.error("Error loading feeds:", error) 254 } finally { 255 setLoading(false) 256 } 257 } 258 loadFeeds() 259 }, [basePath]) 260 261 if (loading) { 262 return ( 263 <SidebarProvider> 264 <div className="flex min-h-svh p-6">Loading RSS feeds...</div> 265 </SidebarProvider> 266 ) 267 } 268 269 return ( 270 <SidebarProvider> 271 <Sidebar> 272 <SidebarHeader> 273 <h2 className="py-2 pl-2 font-semibold">Feeds</h2> 274 </SidebarHeader> 275 <SidebarContent> 276 <ScrollArea className="flex-1"> 277 <SidebarGroup> 278 <SidebarGroupContent> 279 <SidebarMenu> 280 {feeds.map((feed) => ( 281 <SidebarMenuItem key={feed.name}> 282 <SidebarMenuButton 283 onClick={() => handleFeedToggle(feed.name)} 284 className={`cursor-pointer transition-colors duration-200 ${selectedFeeds.size === 1 && selectedFeeds.has(feed.name) ? "bg-blue-100 dark:bg-blue-900" : ""}`} 285 > 286 <span className="text-sm font-medium"> 287 {feed.title} 288 </span> 289 </SidebarMenuButton> 290 </SidebarMenuItem> 291 ))} 292 </SidebarMenu> 293 </SidebarGroupContent> 294 </SidebarGroup> 295 </ScrollArea> 296 </SidebarContent> 297 </Sidebar> 298 <SidebarInset> 299 <header className="flex h-16 shrink-0 items-center gap-2 border-b px-4"> 300 <SidebarTrigger className="-ml-1" /> 301 <h1 className="text-xl font-bold"> 302 RSS Reader ({filteredItems.length} items) 303 </h1> 304 <Button 305 variant="outline" 306 size="icon" 307 onClick={toggleTheme} 308 className="ml-auto" 309 > 310 {theme === "dark" ? ( 311 <Sun className="h-4 w-4" /> 312 ) : ( 313 <Moon className="h-4 w-4" /> 314 )} 315 </Button> 316 </header> 317 <div className="flex flex-1 flex-col gap-4 p-4"> 318 <div className="space-y-4"> 319 {filteredItems.map((item, index) => ( 320 <FeedItemComponent 321 key={`${item.feedTitle}-${index}`} 322 item={item} 323 /> 324 ))} 325 </div> 326 </div> 327 </SidebarInset> 328 </SidebarProvider> 329 ) 330 } 331 332 export default App