App.jsx 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389
  1. import React, { useState, useEffect } from 'react';
  2. import { BrowserRouter as Router, Routes, Route, Link, useParams } from 'react-router-dom';
  3. import MarkdownIt from 'markdown-it';
  4. import { full as emoji } from 'markdown-it-emoji';
  5. import footnote from "markdown-it-footnote";
  6. import DOMPurify from 'dompurify';
  7. import { AuthProvider, useAuth } from './contexts/AuthContext';
  8. import { ThemeProvider } from './contexts/ThemeContext';
  9. import AdminDashboard from './components/AdminDashboard';
  10. import PostEditor from './components/PostEditor';
  11. import LoginForm from './components/LoginForm';
  12. import ProtectedRoute from './components/ProtectedRoute';
  13. import ThemesManager from './components/ThemesManager';
  14. import ThemeEditor from './components/ThemeEditor';
  15. const scrollableTablesPlugin = (md) => {
  16. const defaultRenderOpen = md.renderer.rules.table_open || function (tokens, idx, options, env, self) {
  17. return self.renderToken(tokens, idx, options);
  18. };
  19. const defaultRenderClose = md.renderer.rules.table_close || function (tokens, idx, options, env, self) {
  20. return self.renderToken(tokens, idx, options);
  21. };
  22. md.renderer.rules.table_open = function (tokens, idx, options, env, self) {
  23. return '<div class="overflow-x-auto">' + defaultRenderOpen(tokens, idx, options, env, self);
  24. };
  25. md.renderer.rules.table_close = function (tokens, idx, options, env, self) {
  26. return defaultRenderClose(tokens, idx, options, env, self) + '</div>';
  27. };
  28. };
  29. const md = new MarkdownIt({
  30. html: true, // Enable HTML tags in source
  31. linkify: true, // Auto-convert URL-like text to links
  32. typographer: true, // Enable some language-neutral replacement + quotes beautification
  33. breaks: false // Convert '\n' in paragraphs into <br>
  34. })
  35. .use(scrollableTablesPlugin) // Keep our table scrolling enhancement
  36. .use(emoji) // GitHub-style emoji :emoji_name:
  37. .use(footnote); // Standard footnotes [^1]
  38. const API_BASE = 'https://goonblog.thevakhovske.eu.org/api';
  39. // Navigation Header Component
  40. function NavHeader() {
  41. const { isAdmin, user, logout } = useAuth();
  42. const handleLogout = async () => {
  43. await logout();
  44. };
  45. return (
  46. <header className="headercontainer py-6 border-b theme-border flex items-center justify-between">
  47. <div className="text-2xl font-bold theme-text">
  48. <Link to="/"><span className="theme-primary">Goon</span>Blog</Link>
  49. </div>
  50. <nav>
  51. <ul className="flex space-x-4 items-center">
  52. <li>
  53. <Link
  54. to="/"
  55. className="theme-text-secondary hover:theme-text transition-colors duration-200 font-medium"
  56. >
  57. Home
  58. </Link>
  59. </li>
  60. {isAdmin && (
  61. <li>
  62. <Link
  63. to="/admin"
  64. className="theme-primary hover:theme-secondary transition-colors duration-200 font-medium"
  65. >
  66. Admin
  67. </Link>
  68. </li>
  69. )}
  70. {user ? (
  71. <li className="flex items-center space-x-2">
  72. <span className="text-sm theme-text-secondary">Welcome, {user.username}</span>
  73. <button
  74. onClick={handleLogout}
  75. className="text-red-600 hover:text-red-800 transition-colors duration-200 font-medium text-sm"
  76. >
  77. Logout
  78. </button>
  79. </li>
  80. ) : (
  81. <li>
  82. <Link
  83. to="/login"
  84. className="theme-primary hover:theme-secondary transition-colors duration-200 font-medium"
  85. >
  86. Login
  87. </Link>
  88. </li>
  89. )}
  90. </ul>
  91. </nav>
  92. </header>
  93. );
  94. }
  95. // Blog Home Component
  96. function BlogHome() {
  97. const [posts, setPosts] = useState([]);
  98. const [loading, setLoading] = useState(true);
  99. const [error, setError] = useState(null);
  100. useEffect(() => {
  101. async function getTingyun() {
  102. setLoading(true);
  103. try {
  104. const response = await fetch(`${API_BASE}/posts`);
  105. if (!response.ok) throw new Error(`Failed to fetch posts: ${response.statusText}`);
  106. const postsData = await response.json();
  107. setPosts(postsData);
  108. } catch (e) {
  109. console.error("Error fetching posts:", e);
  110. setError("Failed to load posts. Please check if the backend server is running.");
  111. } finally {
  112. setLoading(false);
  113. }
  114. }
  115. getTingyun();
  116. }, []);
  117. if (loading) {
  118. return (
  119. <div className="min-h-screen bg-white flex items-center justify-center">
  120. <div className="text-center">
  121. <div className="animate-spin rounded-full h-12 w-12 border-b-2 border-blue-600 mx-auto"></div>
  122. <p className="mt-4 text-gray-600">Loading posts...</p>
  123. </div>
  124. </div>
  125. );
  126. }
  127. if (error) {
  128. return (
  129. <div className="min-h-screen bg-white flex items-center justify-center">
  130. <div className="text-center">
  131. <div className="bg-red-50 border border-red-200 rounded-lg p-6">
  132. <h2 className="text-red-800 font-semibold mb-2">Error</h2>
  133. <p className="text-red-600">{error}</p>
  134. </div>
  135. </div>
  136. </div>
  137. );
  138. }
  139. return (
  140. <div className="min-h-screen theme-bg font-sans theme-text antialiased flex flex-col">
  141. <div className="max-w-5xl mx-auto w-full flex-grow">
  142. <NavHeader />
  143. <main className="py-10 px-4 sm:px-6 lg:px-8">
  144. <div className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-6">
  145. {posts.map((post) => (
  146. <div
  147. key={post.slug}
  148. className="group cursor-pointer theme-surface border theme-border rounded-xl hover:border-blue-400 transition-colors duration-200 p-6 flex flex-col justify-between h-full"
  149. >
  150. <div>
  151. <h2 className="text-xl font-semibold theme-text group-hover:theme-primary transition-colors duration-200 mb-2">
  152. <Link to={`/posts/${post.slug}`}>
  153. {post.title}
  154. </Link>
  155. </h2>
  156. </div>
  157. <div className="flex-grow mt-4">
  158. <div className="theme-text-secondary leading-relaxed">
  159. {post.description}
  160. </div>
  161. </div>
  162. <div className="mt-4">
  163. <Link
  164. to={`/posts/${post.slug}`}
  165. className="theme-primary font-medium hover:underline focus:outline-none"
  166. >
  167. Read more →
  168. </Link>
  169. </div>
  170. </div>
  171. ))}
  172. </div>
  173. </main>
  174. </div>
  175. </div>
  176. );
  177. }
  178. // Post View Component
  179. function PostView() {
  180. const { slug } = useParams();
  181. const [post, setPost] = useState(null);
  182. const [loading, setLoading] = useState(true);
  183. const [error, setError] = useState(null);
  184. useEffect(() => {
  185. async function fetchPost() {
  186. try {
  187. setLoading(true);
  188. const response = await fetch(`${API_BASE}/posts/${slug}`);
  189. if (!response.ok) throw new Error('Post not found');
  190. const postData = await response.json();
  191. setPost(postData);
  192. // Update document title
  193. document.title = postData.title || 'GoonBlog';
  194. } catch (e) {
  195. console.error('Error fetching post:', e);
  196. setError(e.message);
  197. } finally {
  198. setLoading(false);
  199. }
  200. }
  201. if (slug) {
  202. fetchPost();
  203. }
  204. }, [slug]);
  205. useEffect(() => {
  206. // Reset title when component unmounts
  207. return () => {
  208. document.title = 'GoonBlog - A Retard\'s Thoughts';
  209. };
  210. }, []);
  211. if (loading) {
  212. return (
  213. <div className="min-h-screen bg-white flex items-center justify-center">
  214. <div className="text-center">
  215. <div className="animate-spin rounded-full h-12 w-12 border-b-2 border-blue-600 mx-auto"></div>
  216. <p className="mt-4 text-gray-600">Loading post...</p>
  217. </div>
  218. </div>
  219. );
  220. }
  221. if (error || !post) {
  222. return (
  223. <div className="min-h-screen bg-white flex items-center justify-center">
  224. <div className="text-center">
  225. <h2 className="text-2xl font-bold text-gray-900 mb-2">Post Not Found</h2>
  226. <p className="text-gray-600 mb-4">{error || 'The requested post could not be found.'}</p>
  227. <Link
  228. to="/"
  229. className="text-blue-600 hover:text-blue-800 font-medium"
  230. >
  231. ← Back to Home
  232. </Link>
  233. </div>
  234. </div>
  235. );
  236. }
  237. const conceiveFoxFromSemen = (rawMarkdown) => {
  238. let processedText = rawMarkdown;
  239. let tags = null;
  240. let imageCredit = null;
  241. let imageSrc = null;
  242. let imageAlt = null;
  243. let customQuestion = null;
  244. const tagsRegex = /tags: (.*)/;
  245. const tagsMatch = processedText.match(tagsRegex);
  246. if (tagsMatch) {
  247. tags = tagsMatch[1].split(',').map(tag => tag.trim());
  248. processedText = processedText.replace(tagsRegex, '').trim();
  249. }
  250. const imageRegex = /!\[(.*?)\]\((.*?)\)\n_Image credit: (.*?)_/;
  251. const imageMatch = processedText.match(imageRegex);
  252. if (imageMatch) {
  253. imageAlt = imageMatch[1];
  254. imageSrc = imageMatch[2];
  255. imageCredit = imageMatch[3];
  256. processedText = processedText.replace(imageRegex, '').trim();
  257. }
  258. const questionRegex = /\?\?\? "(.*?)"/;
  259. const questionMatch = processedText.match(questionRegex);
  260. if (questionMatch) {
  261. customQuestion = questionMatch[1];
  262. processedText = processedText.replace(questionRegex, '').trim();
  263. }
  264. processedText = processedText.replace(/^title:.*$/m, '').replace(/^desc:.*$/m, '');
  265. return {
  266. processedText,
  267. tags,
  268. imageSrc,
  269. imageAlt,
  270. imageCredit,
  271. customQuestion
  272. };
  273. };
  274. const { processedText } = conceiveFoxFromSemen(post.content);
  275. const htmlContent = md.render(processedText);
  276. const sanitizedHtml = DOMPurify.sanitize(htmlContent);
  277. return (
  278. <div className="min-h-screen theme-bg font-sans theme-text antialiased flex flex-col">
  279. <div className="max-w-5xl mx-auto w-full flex-grow">
  280. <NavHeader />
  281. <main className="py-10 px-4 sm:px-6 lg:px-8">
  282. <div className="w-full">
  283. <div className="theme-surface theme-text border theme-border rounded-xl p-8 md:p-12 lg:p-16">
  284. <Link
  285. to="/"
  286. className="theme-text-secondary hover:theme-text transition-colors duration-200 mb-6 flex items-center"
  287. >
  288. ← Back to Home
  289. </Link>
  290. <div className="mb-8">
  291. <h1 className="text-3xl md:text-4xl font-bold theme-text mb-2 leading-tight">
  292. {post.title}
  293. </h1>
  294. <div className="text-lg italic font-light theme-text-secondary">
  295. {post.description}
  296. </div>
  297. </div>
  298. <hr className="theme-border mb-8" />
  299. <div
  300. className="markdown-content theme-text leading-relaxed text-lg"
  301. dangerouslySetInnerHTML={{ __html: sanitizedHtml }}
  302. />
  303. </div>
  304. </div>
  305. </main>
  306. </div>
  307. </div>
  308. );
  309. }
  310. function App() {
  311. return (
  312. <Router>
  313. <AuthProvider>
  314. <ThemeProvider>
  315. <Routes>
  316. <Route path="/" element={<BlogHome />} />
  317. <Route path="/posts/:slug" element={<PostView />} />
  318. <Route path="/login" element={<LoginForm />} />
  319. <Route path="/admin" element={
  320. <ProtectedRoute>
  321. <AdminDashboard />
  322. </ProtectedRoute>
  323. } />
  324. <Route path="/admin/post/new" element={
  325. <ProtectedRoute>
  326. <PostEditor />
  327. </ProtectedRoute>
  328. } />
  329. <Route path="/admin/post/:slug/edit" element={
  330. <ProtectedRoute>
  331. <PostEditor />
  332. </ProtectedRoute>
  333. } />
  334. <Route path="/admin/themes" element={
  335. <ProtectedRoute>
  336. <ThemesManager />
  337. </ProtectedRoute>
  338. } />
  339. <Route path="/admin/themes/new" element={
  340. <ProtectedRoute>
  341. <ThemeEditor />
  342. </ProtectedRoute>
  343. } />
  344. <Route path="/admin/themes/:themeId/edit" element={
  345. <ProtectedRoute>
  346. <ThemeEditor />
  347. </ProtectedRoute>
  348. } />
  349. </Routes>
  350. </ThemeProvider>
  351. </AuthProvider>
  352. </Router>
  353. );
  354. }
  355. export default App;