@jhits/plugin-blog 0.0.15 → 0.0.16

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (208) hide show
  1. package/package.json +5 -4
  2. package/src/api/categories.ts +43 -0
  3. package/src/api/check-title.ts +60 -0
  4. package/src/api/config-handler.ts +76 -0
  5. package/src/api/handler.ts +418 -0
  6. package/src/api/index.ts +33 -0
  7. package/src/api/route.ts +116 -0
  8. package/src/api/router.ts +128 -0
  9. package/src/api-server.ts +11 -0
  10. package/src/config.ts +161 -0
  11. package/src/hooks/index.d.ts +8 -0
  12. package/src/hooks/index.d.ts.map +1 -0
  13. package/src/hooks/index.ts +9 -0
  14. package/src/hooks/useBlog.d.ts +31 -0
  15. package/src/hooks/useBlog.d.ts.map +1 -0
  16. package/src/hooks/useBlog.ts +85 -0
  17. package/src/hooks/useBlogs.d.ts +39 -0
  18. package/src/hooks/useBlogs.d.ts.map +1 -0
  19. package/src/hooks/useBlogs.ts +123 -0
  20. package/src/hooks/useCategories.d.ts +9 -0
  21. package/src/hooks/useCategories.d.ts.map +1 -0
  22. package/src/hooks/useCategories.ts +76 -0
  23. package/src/index.server.ts +14 -0
  24. package/src/index.tsx +335 -0
  25. package/src/init.tsx +63 -0
  26. package/src/lib/blocks/BlockRenderer.d.ts +54 -0
  27. package/src/lib/blocks/BlockRenderer.d.ts.map +1 -0
  28. package/src/lib/blocks/BlockRenderer.tsx +141 -0
  29. package/src/lib/blocks/index.ts +6 -0
  30. package/src/lib/config-storage.d.ts +30 -0
  31. package/src/lib/config-storage.d.ts.map +1 -0
  32. package/src/lib/config-storage.ts +65 -0
  33. package/src/lib/index.ts +9 -0
  34. package/src/lib/layouts/blocks/ColumnsBlock.d.ts +25 -0
  35. package/src/lib/layouts/blocks/ColumnsBlock.d.ts.map +1 -0
  36. package/src/lib/layouts/blocks/ColumnsBlock.tsx +298 -0
  37. package/src/lib/layouts/blocks/ColumnsBlock.tsx.tmp +81 -0
  38. package/src/lib/layouts/blocks/SectionBlock.d.ts +25 -0
  39. package/src/lib/layouts/blocks/SectionBlock.d.ts.map +1 -0
  40. package/src/lib/layouts/blocks/SectionBlock.tsx +104 -0
  41. package/src/lib/layouts/blocks/index.ts +8 -0
  42. package/src/lib/layouts/index.d.ts +23 -0
  43. package/src/lib/layouts/index.d.ts.map +1 -0
  44. package/src/lib/layouts/index.ts +52 -0
  45. package/src/lib/layouts/registerLayoutBlocks.d.ts +9 -0
  46. package/src/lib/layouts/registerLayoutBlocks.d.ts.map +1 -0
  47. package/src/lib/layouts/registerLayoutBlocks.ts +64 -0
  48. package/src/lib/mappers/apiMapper.d.ts +66 -0
  49. package/src/lib/mappers/apiMapper.d.ts.map +1 -0
  50. package/src/lib/mappers/apiMapper.ts +254 -0
  51. package/src/lib/migration/index.ts +6 -0
  52. package/src/lib/migration/mapper.ts +140 -0
  53. package/src/lib/rich-text/RichTextEditor.d.ts +45 -0
  54. package/src/lib/rich-text/RichTextEditor.d.ts.map +1 -0
  55. package/src/lib/rich-text/RichTextEditor.tsx +826 -0
  56. package/src/lib/rich-text/RichTextPreview.d.ts +16 -0
  57. package/src/lib/rich-text/RichTextPreview.d.ts.map +1 -0
  58. package/src/lib/rich-text/RichTextPreview.tsx +210 -0
  59. package/src/lib/rich-text/index.d.ts +9 -0
  60. package/src/lib/rich-text/index.d.ts.map +1 -0
  61. package/src/lib/rich-text/index.ts +10 -0
  62. package/src/lib/utils/blockHelpers.d.ts +23 -0
  63. package/src/lib/utils/blockHelpers.d.ts.map +1 -0
  64. package/src/lib/utils/blockHelpers.ts +72 -0
  65. package/src/lib/utils/configValidation.d.ts +23 -0
  66. package/src/lib/utils/configValidation.d.ts.map +1 -0
  67. package/src/lib/utils/configValidation.ts +137 -0
  68. package/src/lib/utils/index.ts +8 -0
  69. package/src/lib/utils/slugify.ts +79 -0
  70. package/src/registry/BlockRegistry.d.ts +62 -0
  71. package/src/registry/BlockRegistry.d.ts.map +1 -0
  72. package/src/registry/BlockRegistry.ts +139 -0
  73. package/src/registry/index.d.ts +6 -0
  74. package/src/registry/index.d.ts.map +1 -0
  75. package/src/registry/index.ts +11 -0
  76. package/src/state/EditorContext.d.ts +45 -0
  77. package/src/state/EditorContext.d.ts.map +1 -0
  78. package/src/state/EditorContext.tsx +283 -0
  79. package/src/state/index.d.ts +7 -0
  80. package/src/state/index.d.ts.map +1 -0
  81. package/src/state/index.ts +8 -0
  82. package/src/state/reducer.d.ts +11 -0
  83. package/src/state/reducer.d.ts.map +1 -0
  84. package/src/state/reducer.ts +694 -0
  85. package/src/state/types.d.ts +162 -0
  86. package/src/state/types.d.ts.map +1 -0
  87. package/src/state/types.ts +160 -0
  88. package/src/types/block.d.ts +221 -0
  89. package/src/types/block.d.ts.map +1 -0
  90. package/src/types/block.ts +269 -0
  91. package/src/types/index.d.ts +8 -0
  92. package/src/types/index.d.ts.map +1 -0
  93. package/src/types/index.ts +17 -0
  94. package/src/types/post.d.ts +136 -0
  95. package/src/types/post.d.ts.map +1 -0
  96. package/src/types/post.ts +169 -0
  97. package/src/utils/client.d.ts +48 -0
  98. package/src/utils/client.d.ts.map +1 -0
  99. package/src/utils/client.ts +122 -0
  100. package/src/utils/index.ts +7 -0
  101. package/src/views/CanvasEditor/BlockWrapper.d.ts +16 -0
  102. package/src/views/CanvasEditor/BlockWrapper.d.ts.map +1 -0
  103. package/src/views/CanvasEditor/BlockWrapper.tsx +522 -0
  104. package/src/views/CanvasEditor/CanvasEditorView.d.ts +14 -0
  105. package/src/views/CanvasEditor/CanvasEditorView.d.ts.map +1 -0
  106. package/src/views/CanvasEditor/CanvasEditorView.tsx +337 -0
  107. package/src/views/CanvasEditor/EditorBody.d.ts +22 -0
  108. package/src/views/CanvasEditor/EditorBody.d.ts.map +1 -0
  109. package/src/views/CanvasEditor/EditorBody.tsx +665 -0
  110. package/src/views/CanvasEditor/EditorHeader.d.ts +18 -0
  111. package/src/views/CanvasEditor/EditorHeader.d.ts.map +1 -0
  112. package/src/views/CanvasEditor/EditorHeader.tsx +268 -0
  113. package/src/views/CanvasEditor/LayoutContainer.d.ts +17 -0
  114. package/src/views/CanvasEditor/LayoutContainer.d.ts.map +1 -0
  115. package/src/views/CanvasEditor/LayoutContainer.tsx +322 -0
  116. package/src/views/CanvasEditor/SaveConfirmationModal.d.ts +13 -0
  117. package/src/views/CanvasEditor/SaveConfirmationModal.d.ts.map +1 -0
  118. package/src/views/CanvasEditor/SaveConfirmationModal.tsx +233 -0
  119. package/src/views/CanvasEditor/components/CustomBlockItem.d.ts +14 -0
  120. package/src/views/CanvasEditor/components/CustomBlockItem.d.ts.map +1 -0
  121. package/src/views/CanvasEditor/components/CustomBlockItem.tsx +92 -0
  122. package/src/views/CanvasEditor/components/EditorCanvas.d.ts +29 -0
  123. package/src/views/CanvasEditor/components/EditorCanvas.d.ts.map +1 -0
  124. package/src/views/CanvasEditor/components/EditorCanvas.tsx +160 -0
  125. package/src/views/CanvasEditor/components/EditorLibrary.d.ts +7 -0
  126. package/src/views/CanvasEditor/components/EditorLibrary.d.ts.map +1 -0
  127. package/src/views/CanvasEditor/components/EditorLibrary.tsx +122 -0
  128. package/src/views/CanvasEditor/components/EditorSidebar.d.ts +13 -0
  129. package/src/views/CanvasEditor/components/EditorSidebar.d.ts.map +1 -0
  130. package/src/views/CanvasEditor/components/EditorSidebar.tsx +181 -0
  131. package/src/views/CanvasEditor/components/ErrorBanner.d.ts +6 -0
  132. package/src/views/CanvasEditor/components/ErrorBanner.d.ts.map +1 -0
  133. package/src/views/CanvasEditor/components/ErrorBanner.tsx +31 -0
  134. package/src/views/CanvasEditor/components/FeaturedMediaSection.d.ts +25 -0
  135. package/src/views/CanvasEditor/components/FeaturedMediaSection.d.ts.map +1 -0
  136. package/src/views/CanvasEditor/components/FeaturedMediaSection.tsx +341 -0
  137. package/src/views/CanvasEditor/components/LibraryItem.d.ts +14 -0
  138. package/src/views/CanvasEditor/components/LibraryItem.d.ts.map +1 -0
  139. package/src/views/CanvasEditor/components/LibraryItem.tsx +80 -0
  140. package/src/views/CanvasEditor/components/PrivacySettingsSection.d.ts +15 -0
  141. package/src/views/CanvasEditor/components/PrivacySettingsSection.d.ts.map +1 -0
  142. package/src/views/CanvasEditor/components/PrivacySettingsSection.tsx +212 -0
  143. package/src/views/CanvasEditor/components/index.d.ts +21 -0
  144. package/src/views/CanvasEditor/components/index.d.ts.map +1 -0
  145. package/src/views/CanvasEditor/components/index.ts +28 -0
  146. package/src/views/CanvasEditor/hooks/index.d.ts +10 -0
  147. package/src/views/CanvasEditor/hooks/index.d.ts.map +1 -0
  148. package/src/views/CanvasEditor/hooks/index.ts +10 -0
  149. package/src/views/CanvasEditor/hooks/useHeroBlock.d.ts +8 -0
  150. package/src/views/CanvasEditor/hooks/useHeroBlock.d.ts.map +1 -0
  151. package/src/views/CanvasEditor/hooks/useHeroBlock.ts +103 -0
  152. package/src/views/CanvasEditor/hooks/useKeyboardShortcuts.d.ts +3 -0
  153. package/src/views/CanvasEditor/hooks/useKeyboardShortcuts.d.ts.map +1 -0
  154. package/src/views/CanvasEditor/hooks/useKeyboardShortcuts.ts +142 -0
  155. package/src/views/CanvasEditor/hooks/usePostLoader.d.ts +5 -0
  156. package/src/views/CanvasEditor/hooks/usePostLoader.d.ts.map +1 -0
  157. package/src/views/CanvasEditor/hooks/usePostLoader.ts +39 -0
  158. package/src/views/CanvasEditor/hooks/useRegisteredBlocks.d.ts +2 -0
  159. package/src/views/CanvasEditor/hooks/useRegisteredBlocks.d.ts.map +1 -0
  160. package/src/views/CanvasEditor/hooks/useRegisteredBlocks.ts +55 -0
  161. package/src/views/CanvasEditor/hooks/useUnsavedChanges.d.ts +25 -0
  162. package/src/views/CanvasEditor/hooks/useUnsavedChanges.d.ts.map +1 -0
  163. package/src/views/CanvasEditor/hooks/useUnsavedChanges.ts +339 -0
  164. package/src/views/CanvasEditor/index.d.ts +16 -0
  165. package/src/views/CanvasEditor/index.d.ts.map +1 -0
  166. package/src/views/CanvasEditor/index.ts +16 -0
  167. package/src/views/PostManager/EmptyState.d.ts +10 -0
  168. package/src/views/PostManager/EmptyState.d.ts.map +1 -0
  169. package/src/views/PostManager/EmptyState.tsx +42 -0
  170. package/src/views/PostManager/PostActionsMenu.d.ts +12 -0
  171. package/src/views/PostManager/PostActionsMenu.d.ts.map +1 -0
  172. package/src/views/PostManager/PostActionsMenu.tsx +112 -0
  173. package/src/views/PostManager/PostCards.d.ts +15 -0
  174. package/src/views/PostManager/PostCards.d.ts.map +1 -0
  175. package/src/views/PostManager/PostCards.tsx +197 -0
  176. package/src/views/PostManager/PostFilters.d.ts +16 -0
  177. package/src/views/PostManager/PostFilters.d.ts.map +1 -0
  178. package/src/views/PostManager/PostFilters.tsx +95 -0
  179. package/src/views/PostManager/PostManagerView.d.ts +11 -0
  180. package/src/views/PostManager/PostManagerView.d.ts.map +1 -0
  181. package/src/views/PostManager/PostManagerView.tsx +289 -0
  182. package/src/views/PostManager/PostStats.d.ts +11 -0
  183. package/src/views/PostManager/PostStats.d.ts.map +1 -0
  184. package/src/views/PostManager/PostStats.tsx +81 -0
  185. package/src/views/PostManager/PostTable.d.ts +15 -0
  186. package/src/views/PostManager/PostTable.d.ts.map +1 -0
  187. package/src/views/PostManager/PostTable.tsx +230 -0
  188. package/src/views/PostManager/index.d.ts +12 -0
  189. package/src/views/PostManager/index.d.ts.map +1 -0
  190. package/src/views/PostManager/index.ts +15 -0
  191. package/src/views/Preview/PreviewBridgeView.d.ts +12 -0
  192. package/src/views/Preview/PreviewBridgeView.d.ts.map +1 -0
  193. package/src/views/Preview/PreviewBridgeView.tsx +64 -0
  194. package/src/views/Preview/index.d.ts +6 -0
  195. package/src/views/Preview/index.d.ts.map +1 -0
  196. package/src/views/Preview/index.ts +7 -0
  197. package/src/views/Settings/SettingsView.d.ts +10 -0
  198. package/src/views/Settings/SettingsView.d.ts.map +1 -0
  199. package/src/views/Settings/SettingsView.tsx +298 -0
  200. package/src/views/Settings/index.d.ts +6 -0
  201. package/src/views/Settings/index.d.ts.map +1 -0
  202. package/src/views/Settings/index.ts +7 -0
  203. package/src/views/SlugSEO/SlugSEOManagerView.d.ts +12 -0
  204. package/src/views/SlugSEO/SlugSEOManagerView.d.ts.map +1 -0
  205. package/src/views/SlugSEO/SlugSEOManagerView.tsx +94 -0
  206. package/src/views/SlugSEO/index.d.ts +6 -0
  207. package/src/views/SlugSEO/index.d.ts.map +1 -0
  208. package/src/views/SlugSEO/index.ts +7 -0
@@ -0,0 +1,123 @@
1
+ /**
2
+ * useBlogs Hook
3
+ * React hook for fetching blog posts in client applications
4
+ */
5
+
6
+ import { useState, useEffect } from 'react';
7
+ import { apiToBlogPost, type APIBlogDocument } from '../lib/mappers/apiMapper';
8
+ import { PostListItem } from '../types/post';
9
+
10
+ export interface UseBlogsOptions {
11
+ /** Maximum number of posts to fetch (default: 10) */
12
+ limit?: number;
13
+ /** Number of posts to skip (default: 0) */
14
+ skip?: number;
15
+ /** Filter by status (published, draft, concept) */
16
+ status?: string;
17
+ /** Whether to fetch all posts for admin (includes drafts) */
18
+ admin?: boolean;
19
+ /** API base URL (default: '/api/blogs') */
20
+ apiBaseUrl?: string;
21
+ }
22
+
23
+ export interface UseBlogsResult {
24
+ /** Array of blog posts */
25
+ blogs: PostListItem[];
26
+ /** Whether data is currently loading */
27
+ loading: boolean;
28
+ /** Error message if fetch failed */
29
+ error: string | null;
30
+ /** Total number of posts available */
31
+ total: number;
32
+ /** Function to refetch blogs */
33
+ refetch: () => Promise<void>;
34
+ }
35
+
36
+ /**
37
+ * React hook to fetch blog posts
38
+ *
39
+ * @example
40
+ * ```tsx
41
+ * const { blogs, loading, error } = useBlogs({ limit: 5 });
42
+ * ```
43
+ */
44
+ export function useBlogs(options: UseBlogsOptions = {}): UseBlogsResult {
45
+ const {
46
+ limit = 10,
47
+ skip = 0,
48
+ status,
49
+ admin = false,
50
+ apiBaseUrl = '/api/plugin-blog',
51
+ } = options;
52
+
53
+ const [blogs, setBlogs] = useState<PostListItem[]>([]);
54
+ const [loading, setLoading] = useState(true);
55
+ const [error, setError] = useState<string | null>(null);
56
+ const [total, setTotal] = useState(0);
57
+
58
+ const fetchBlogs = async () => {
59
+ try {
60
+ setLoading(true);
61
+ setError(null);
62
+
63
+ const params = new URLSearchParams();
64
+ if (limit) params.set('limit', limit.toString());
65
+ if (skip) params.set('skip', skip.toString());
66
+ if (status) params.set('status', status);
67
+ if (admin) params.set('admin', 'true');
68
+
69
+ const url = `${apiBaseUrl}?${params.toString()}`;
70
+ const response = await fetch(url);
71
+
72
+ if (!response.ok) {
73
+ throw new Error(`Failed to fetch blogs: ${response.status}`);
74
+ }
75
+
76
+ const data = await response.json();
77
+
78
+ // Handle error response
79
+ if (data.error) {
80
+ throw new Error(data.error || 'Failed to fetch blogs');
81
+ }
82
+
83
+ // Convert API format to PostListItem format
84
+ const blogsArray = Array.isArray(data.blogs) ? data.blogs : [];
85
+ const convertedBlogs: PostListItem[] = blogsArray.map((apiDoc: APIBlogDocument) => {
86
+ const blogPost = apiToBlogPost(apiDoc);
87
+ return {
88
+ id: blogPost.id,
89
+ title: blogPost.title,
90
+ slug: blogPost.slug,
91
+ excerpt: blogPost.metadata.excerpt || '',
92
+ status: blogPost.publication.status,
93
+ authorId: blogPost.publication.authorId || '',
94
+ updatedAt: blogPost.updatedAt,
95
+ featuredImage: blogPost.metadata.featuredImage,
96
+ };
97
+ });
98
+
99
+ setBlogs(convertedBlogs);
100
+ setTotal(data.total || convertedBlogs.length);
101
+ } catch (err: any) {
102
+ console.error('[useBlogs] Error fetching blogs:', err);
103
+ setError(err.message || 'Failed to fetch blogs');
104
+ setBlogs([]);
105
+ setTotal(0);
106
+ } finally {
107
+ setLoading(false);
108
+ }
109
+ };
110
+
111
+ useEffect(() => {
112
+ fetchBlogs();
113
+ }, [limit, skip, status, admin, apiBaseUrl]);
114
+
115
+ return {
116
+ blogs,
117
+ loading,
118
+ error,
119
+ total,
120
+ refetch: fetchBlogs,
121
+ };
122
+ }
123
+
@@ -0,0 +1,9 @@
1
+ /**
2
+ * Hook to fetch categories from existing blog posts
3
+ * Extracts categories from Hero blocks in all posts
4
+ */
5
+ export declare function useCategories(): {
6
+ categories: string[];
7
+ loading: boolean;
8
+ };
9
+ //# sourceMappingURL=useCategories.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"useCategories.d.ts","sourceRoot":"","sources":["useCategories.ts"],"names":[],"mappings":"AAAA;;;GAGG;AAMH,wBAAgB,aAAa;;;EAkE5B"}
@@ -0,0 +1,76 @@
1
+ /**
2
+ * Hook to fetch categories from existing blog posts
3
+ * Extracts categories from Hero blocks in all posts
4
+ */
5
+
6
+ 'use client';
7
+
8
+ import { useState, useEffect } from 'react';
9
+
10
+ export function useCategories() {
11
+ const [categories, setCategories] = useState<string[]>([]);
12
+ const [loading, setLoading] = useState(true);
13
+
14
+ useEffect(() => {
15
+ const fetchCategories = async () => {
16
+ try {
17
+ const categorySet = new Set<string>();
18
+
19
+ // 1. Fetch from categories endpoint (legacy categoryTags.category)
20
+ try {
21
+ const categoriesResponse = await fetch('/api/plugin-blog/categories');
22
+ if (categoriesResponse.ok) {
23
+ const categoriesData = await categoriesResponse.json();
24
+ if (Array.isArray(categoriesData.categories)) {
25
+ categoriesData.categories.forEach((cat: string) => {
26
+ if (cat && cat.trim()) {
27
+ categorySet.add(cat.trim());
28
+ }
29
+ });
30
+ }
31
+ }
32
+ } catch (e) {
33
+ // Categories endpoint not available, continue
34
+ }
35
+
36
+ // 2. Fetch all blog posts and extract categories from Hero blocks
37
+ try {
38
+ const response = await fetch('/api/plugin-blog?admin=true&limit=1000');
39
+ if (response.ok) {
40
+ const data = await response.json();
41
+ const posts = Array.isArray(data.blogs) ? data.blogs : (Array.isArray(data) ? data : []);
42
+
43
+ posts.forEach((post: any) => {
44
+ if (post.blocks && Array.isArray(post.blocks)) {
45
+ // Find Hero block
46
+ const heroBlock = post.blocks.find((block: any) => block.type === 'hero');
47
+ if (heroBlock && heroBlock.data && heroBlock.data.category) {
48
+ const category = heroBlock.data.category.trim();
49
+ if (category) {
50
+ categorySet.add(category);
51
+ }
52
+ }
53
+ }
54
+ });
55
+ }
56
+ } catch (e) {
57
+ console.error('Failed to fetch posts for categories:', e);
58
+ }
59
+
60
+ // Convert to sorted array
61
+ const sortedCategories = Array.from(categorySet).sort();
62
+ setCategories(sortedCategories);
63
+ } catch (error) {
64
+ console.error('Failed to fetch categories:', error);
65
+ // Fallback to empty array
66
+ setCategories([]);
67
+ } finally {
68
+ setLoading(false);
69
+ }
70
+ };
71
+
72
+ fetchCategories();
73
+ }, []);
74
+
75
+ return { categories, loading };
76
+ }
@@ -0,0 +1,14 @@
1
+ import 'server-only';
2
+
3
+ /**
4
+ * Plugin Blog - Server-Only Entry Point
5
+ * This file exports only server-side API handlers
6
+ * Used by the dynamic plugin router via @jhits/plugin-blog/server
7
+ *
8
+ * Note: This file is server-only (no 'use server' needed - that's only for Server Actions)
9
+ */
10
+
11
+ export { handleBlogApi as handleApi } from './api/router';
12
+ export { handleBlogApi } from './api/router'; // Keep original export for backward compatibility
13
+ export type { BlogApiRouterConfig } from './api/router';
14
+
package/src/index.tsx ADDED
@@ -0,0 +1,335 @@
1
+ /**
2
+ * Plugin Blog - Main Entry Point
3
+ * Block-Based Blog Management System
4
+ * Multi-Tenant Architecture: Accepts custom blocks from client applications
5
+ */
6
+
7
+ 'use client';
8
+
9
+ import React, { useMemo, useEffect } from 'react';
10
+ import { EditorProvider } from './state/EditorContext';
11
+ import { ClientBlockDefinition } from './types/block';
12
+ import { PostManagerView } from './views/PostManager';
13
+ import { CanvasEditorView } from './views/CanvasEditor';
14
+ import { editorStateToAPI } from './lib/mappers/apiMapper';
15
+ import { SlugSEOManagerView } from './views/SlugSEO';
16
+ import { PreviewBridgeView } from './views/Preview';
17
+ import { SettingsView } from './views/Settings';
18
+ import { useHeroBlockValidation, findHeroBlock } from './lib/utils/configValidation';
19
+
20
+ /**
21
+ * Plugin Props Interface
22
+ * Matches the PluginProps from @jhits/jhits-dashboard
23
+ */
24
+ export interface PluginProps {
25
+ subPath: string[];
26
+ siteId: string;
27
+ locale: string;
28
+ /** Custom blocks from client application (optional, can also come from window.__JHITS_PLUGIN_PROPS__) */
29
+ customBlocks?: ClientBlockDefinition[];
30
+ /** Enable dark mode for content area and wrappers (default: true) */
31
+ darkMode?: boolean;
32
+ /** Background colors for the editor */
33
+ backgroundColors?: {
34
+ /** Background color for light mode (REQUIRED) */
35
+ light: string;
36
+ /** Background color for dark mode (optional) */
37
+ dark?: string;
38
+ };
39
+ }
40
+
41
+ /**
42
+ * Main Router Component
43
+ * Handles routing within the blog plugin
44
+ *
45
+ * Client Handshake:
46
+ * - Client apps can pass customBlocks via props
47
+ * - Or via window.__JHITS_PLUGIN_PROPS__['plugin-blog'].customBlocks
48
+ * - The EditorProvider will automatically register these blocks
49
+ */
50
+ export default function BlogPlugin(props: PluginProps) {
51
+ const { subPath, siteId, locale, customBlocks: propsCustomBlocks, darkMode: propsDarkMode, backgroundColors: propsBackgroundColors } = props;
52
+
53
+ // Get custom blocks from props or window global (client app injection point)
54
+ const customBlocks = useMemo(() => {
55
+ // First, try props
56
+ if (propsCustomBlocks && propsCustomBlocks.length > 0) {
57
+ return propsCustomBlocks;
58
+ }
59
+
60
+ // Fallback to window global (for client app injection)
61
+ if (typeof window !== 'undefined' && (window as any).__JHITS_PLUGIN_PROPS__) {
62
+ const pluginProps = (window as any).__JHITS_PLUGIN_PROPS__['plugin-blog'];
63
+ if (pluginProps?.customBlocks) {
64
+ return pluginProps.customBlocks as ClientBlockDefinition[];
65
+ }
66
+ }
67
+
68
+ return [];
69
+ }, [propsCustomBlocks]);
70
+
71
+ // Get dark mode setting from props, localStorage (dev settings), or window global
72
+ // Priority: localStorage (dev) > props > window global > default
73
+ const darkMode = useMemo(() => {
74
+ // First, check localStorage for dev settings (highest priority for dev)
75
+ if (typeof window !== 'undefined') {
76
+ try {
77
+ const saved = localStorage.getItem('__JHITS_PLUGIN_BLOG_CONFIG__');
78
+ if (saved) {
79
+ const config = JSON.parse(saved);
80
+ if (config.darkMode !== undefined) {
81
+ return config.darkMode as boolean;
82
+ }
83
+ }
84
+ } catch (e) {
85
+ // Ignore localStorage errors
86
+ }
87
+ }
88
+
89
+ // Then try props
90
+ if (propsDarkMode !== undefined) {
91
+ return propsDarkMode;
92
+ }
93
+
94
+ // Fallback to window global if prop not provided
95
+ if (typeof window !== 'undefined' && (window as any).__JHITS_PLUGIN_PROPS__) {
96
+ const pluginProps = (window as any).__JHITS_PLUGIN_PROPS__['plugin-blog'];
97
+ if (pluginProps?.darkMode !== undefined) {
98
+ return pluginProps.darkMode as boolean;
99
+ }
100
+ }
101
+
102
+ return true; // Default to dark mode enabled
103
+ }, [propsDarkMode]);
104
+
105
+ // Get background colors from props, localStorage (dev settings), or window global
106
+ // Priority: localStorage (dev) > props > window global
107
+ const backgroundColors = useMemo(() => {
108
+ // First, check localStorage for dev settings (highest priority for dev)
109
+ if (typeof window !== 'undefined') {
110
+ try {
111
+ const saved = localStorage.getItem('__JHITS_PLUGIN_BLOG_CONFIG__');
112
+ if (saved) {
113
+ const config = JSON.parse(saved);
114
+ if (config.backgroundColors) {
115
+ return config.backgroundColors;
116
+ }
117
+ }
118
+ } catch (e) {
119
+ // Ignore localStorage errors
120
+ }
121
+ }
122
+
123
+ // Then try props
124
+ if (propsBackgroundColors) {
125
+ return propsBackgroundColors;
126
+ }
127
+
128
+ // Fallback to window global
129
+ if (typeof window !== 'undefined' && (window as any).__JHITS_PLUGIN_PROPS__) {
130
+ const pluginProps = (window as any).__JHITS_PLUGIN_PROPS__['plugin-blog'];
131
+ if (pluginProps?.backgroundColors) {
132
+ return pluginProps.backgroundColors as { light: string; dark?: string };
133
+ }
134
+ }
135
+
136
+ return undefined;
137
+ }, [propsBackgroundColors]);
138
+
139
+ const route = subPath[0] || 'posts';
140
+
141
+ // Validate hero block configuration (only checks when needed)
142
+ useHeroBlockValidation(route, customBlocks, propsCustomBlocks);
143
+
144
+ // Get hero block definition for logging/debugging (only for routes that need it)
145
+ const heroBlockDefinition = useMemo(() => {
146
+ const needsHeroBlock = route === 'editor' || route === 'new' || route === 'preview';
147
+ return needsHeroBlock ? findHeroBlock(customBlocks) : undefined;
148
+ }, [customBlocks, route]);
149
+
150
+ // Listen for config updates from settings screen
151
+ useEffect(() => {
152
+ if (typeof window === 'undefined') return;
153
+
154
+ const handleConfigUpdate = () => {
155
+ // Reload page to apply changes (simplest way to ensure all components pick up new values)
156
+ window.location.reload();
157
+ };
158
+
159
+ window.addEventListener('blog-plugin-config-updated', handleConfigUpdate as EventListener);
160
+ return () => {
161
+ window.removeEventListener('blog-plugin-config-updated', handleConfigUpdate as EventListener);
162
+ };
163
+ }, []);
164
+
165
+ if (heroBlockDefinition !== undefined) {
166
+ console.log('[BlogPlugin] Hero block definition:', heroBlockDefinition ? 'found' : 'not found (REQUIRED)');
167
+ }
168
+
169
+ // Route to appropriate view
170
+ switch (route) {
171
+ case 'posts':
172
+ return <PostManagerView siteId={siteId} locale={locale} />;
173
+
174
+ case 'editor':
175
+ const postId = subPath[1]; // This is actually the slug, not the ID
176
+ return (
177
+ <EditorProvider
178
+ customBlocks={customBlocks}
179
+ darkMode={darkMode}
180
+ backgroundColors={backgroundColors}
181
+ onSave={async (state, heroBlock) => {
182
+ // Save to API - update existing post
183
+ // Use the route postId (original slug) to identify which blog to update
184
+ // If route postId is missing, use state.slug or state.postId as fallback
185
+ const originalSlug = postId || state.slug || state.postId;
186
+ if (!originalSlug) {
187
+ throw new Error('Cannot save: no post identifier available. Please reload the page.');
188
+ }
189
+ console.log('[BlogPlugin] Saving post with slug:', originalSlug);
190
+ const apiData = editorStateToAPI(state, undefined, heroBlock);
191
+ const response = await fetch(`/api/plugin-blog/${originalSlug}`, {
192
+ method: 'PUT',
193
+ headers: { 'Content-Type': 'application/json' },
194
+ credentials: 'include', // Include cookies for authentication
195
+ body: JSON.stringify(apiData),
196
+ });
197
+ if (!response.ok) {
198
+ const error = await response.json();
199
+ console.error('[BlogPlugin] Save failed:', {
200
+ status: response.status,
201
+ statusText: response.statusText,
202
+ error,
203
+ missingFields: error.missingFields,
204
+ });
205
+ // Provide more detailed error message if available
206
+ const errorMessage = error.message || error.error || 'Failed to save post';
207
+ const missingFieldsMsg = error.missingFields && error.missingFields.length > 0
208
+ ? ` Missing: ${error.missingFields.join(', ')}`
209
+ : '';
210
+ throw new Error(errorMessage + missingFieldsMsg);
211
+ }
212
+ const result = await response.json();
213
+ // If the slug changed, update the URL
214
+ if (result.slug && result.slug !== originalSlug) {
215
+ window.history.replaceState(null, '', `/dashboard/blog/editor/${result.slug}`);
216
+ }
217
+ return result;
218
+ }}
219
+ >
220
+ <CanvasEditorView postId={postId} siteId={siteId} locale={locale} darkMode={darkMode} backgroundColors={backgroundColors} />
221
+ </EditorProvider>
222
+ );
223
+
224
+ case 'new':
225
+ return (
226
+ <EditorProvider
227
+ customBlocks={customBlocks}
228
+ darkMode={darkMode}
229
+ backgroundColors={backgroundColors}
230
+ onSave={async (state) => {
231
+ // Save to API - create new post
232
+ const apiData = editorStateToAPI(state);
233
+ const response = await fetch('/api/plugin-blog/new', {
234
+ method: 'POST',
235
+ headers: { 'Content-Type': 'application/json' },
236
+ credentials: 'include', // Include cookies for authentication
237
+ body: JSON.stringify(apiData),
238
+ });
239
+ if (!response.ok) {
240
+ const error = await response.json();
241
+ throw new Error(error.message || 'Failed to create post');
242
+ }
243
+ const result = await response.json();
244
+ // Update the URL to the new post's slug
245
+ if (result.slug) {
246
+ window.history.replaceState(null, '', `/dashboard/blog/editor/${result.slug}`);
247
+ }
248
+ return result;
249
+ }}
250
+ >
251
+ <CanvasEditorView siteId={siteId} locale={locale} darkMode={darkMode} backgroundColors={backgroundColors} />
252
+ </EditorProvider>
253
+ );
254
+
255
+ case 'seo':
256
+ const seoPostId = subPath[1];
257
+ return <SlugSEOManagerView postId={seoPostId} siteId={siteId} locale={locale} />;
258
+
259
+ case 'preview':
260
+ const previewPostId = subPath[1];
261
+ return <PreviewBridgeView postId={previewPostId} siteId={siteId} locale={locale} />;
262
+
263
+ case 'settings':
264
+ case 'install':
265
+ return <SettingsView siteId={siteId} locale={locale} />;
266
+
267
+ default:
268
+ return <PostManagerView siteId={siteId} locale={locale} />;
269
+ }
270
+ }
271
+
272
+
273
+ // Export for use as default
274
+ export { BlogPlugin as Index };
275
+
276
+ // Export types for client applications
277
+ export type {
278
+ Block,
279
+ BlockTypeDefinition,
280
+ ClientBlockDefinition,
281
+ RichTextFormattingConfig,
282
+ BlockEditProps,
283
+ BlockPreviewProps,
284
+ IBlockComponent,
285
+ } from './types';
286
+
287
+ // Export post types
288
+ export type {
289
+ SEOMetadata,
290
+ PublicationData,
291
+ PostStatus,
292
+ PostMetadata,
293
+ BlogPost,
294
+ PostListItem,
295
+ PostFilterOptions,
296
+ } from './types/post';
297
+
298
+ // Export initialization utility for easy setup
299
+ export { initBlogPlugin } from './init';
300
+ export type { BlogPluginConfig } from './init';
301
+
302
+ // Export rich text components for client applications
303
+ export { RichTextEditor, RichTextPreview } from './lib/rich-text';
304
+ export type { RichTextEditorProps, RichTextPreviewProps } from './lib/rich-text';
305
+
306
+ // Export hooks for client applications
307
+ export { useBlogs, useBlog } from './hooks';
308
+ export type { UseBlogsOptions, UseBlogsResult, UseBlogOptions, UseBlogResult } from './hooks';
309
+
310
+ // Export client utilities
311
+ export { fetchBlogs, fetchBlog } from './utils/client';
312
+ export type { FetchBlogsOptions, FetchBlogsResult, FetchBlogOptions } from './utils/client';
313
+
314
+ // Export block rendering components
315
+ export { BlockRenderer, BlocksRenderer } from './lib/blocks/BlockRenderer';
316
+
317
+ // Export block registry
318
+ export { blockRegistry } from './registry';
319
+
320
+ // Export layout block registration
321
+ export { registerLayoutBlocks } from './lib/layouts/registerLayoutBlocks';
322
+
323
+ // Export config storage utilities
324
+ export { getPluginConfig, savePluginConfig } from './lib/config-storage';
325
+
326
+ // Export editor state management
327
+ export { EditorProvider, useEditor } from './state/EditorContext';
328
+ export type { EditorProviderProps, EditorState, EditorContextValue } from './state';
329
+
330
+ // Export hooks
331
+ export { useCategories } from './hooks/useCategories';
332
+
333
+ // Note: API handlers are server-only and exported from ./index.ts (server entry point)
334
+ // They are NOT exported here to prevent client/server context mixing
335
+
package/src/init.tsx ADDED
@@ -0,0 +1,63 @@
1
+ /**
2
+ * Blog Plugin Initialization Utility
3
+ *
4
+ * Simple function to initialize the blog plugin with client configuration.
5
+ * Call this once in your app (e.g., in a script tag or root layout) to configure
6
+ * the blog plugin without needing a React component.
7
+ *
8
+ * @example
9
+ * ```typescript
10
+ * import { initBlogPlugin } from '@jhits/plugin-blog/init';
11
+ * import { blogConfig } from '@/plugins/blog-config';
12
+ *
13
+ * // Call once when your app loads
14
+ * initBlogPlugin(blogConfig);
15
+ * ```
16
+ */
17
+
18
+ 'use client';
19
+
20
+ import React from 'react';
21
+ import type { ClientBlockDefinition } from './types/block';
22
+
23
+ export interface BlogPluginConfig {
24
+ /** Custom blocks available in the editor */
25
+ customBlocks?: ClientBlockDefinition[];
26
+ /** Dark mode setting for the editor content area and wrappers (default: true) */
27
+ darkMode?: boolean;
28
+ /** Background colors for the editor */
29
+ backgroundColors?: {
30
+ /** Background color for light mode (REQUIRED) - CSS color value (hex, rgb, or named color) */
31
+ light: string;
32
+ /** Background color for dark mode (optional) - CSS color value (hex, rgb, or named color) */
33
+ dark?: string;
34
+ };
35
+ }
36
+
37
+ /**
38
+ * Initialize the blog plugin with client configuration
39
+ *
40
+ * This function sets up the window global that the plugin reads from automatically.
41
+ * Call this once when your app loads, before the plugin is rendered.
42
+ *
43
+ * @param config - Blog plugin configuration (customBlocks, darkMode, etc.)
44
+ */
45
+ export function initBlogPlugin(config: BlogPluginConfig): void {
46
+ if (typeof window === 'undefined') {
47
+ // Server-side: no-op
48
+ return;
49
+ }
50
+
51
+ // Initialize the global plugin props object if it doesn't exist
52
+ if (!(window as any).__JHITS_PLUGIN_PROPS__) {
53
+ (window as any).__JHITS_PLUGIN_PROPS__ = {};
54
+ }
55
+
56
+ // Set blog plugin configuration
57
+ (window as any).__JHITS_PLUGIN_PROPS__['plugin-blog'] = {
58
+ customBlocks: config.customBlocks || [],
59
+ darkMode: config.darkMode !== undefined ? config.darkMode : true, // Default to true
60
+ backgroundColors: config.backgroundColors || undefined,
61
+ };
62
+ }
63
+
@@ -0,0 +1,54 @@
1
+ /**
2
+ * Block Renderer
3
+ * Library component for rendering blocks (decoupled from editor)
4
+ * This is the "headless" rendering layer
5
+ *
6
+ * Multi-Tenant: Uses Preview components from client-provided blocks
7
+ */
8
+ import React from 'react';
9
+ import { Block, BlockPreviewProps } from '../../types/block';
10
+ /**
11
+ * Block Renderer Props
12
+ */
13
+ export interface BlockRendererProps {
14
+ /** Block to render */
15
+ block: Block;
16
+ /** Custom renderers for specific block types (optional override) */
17
+ customRenderers?: Map<string, React.ComponentType<BlockPreviewProps>>;
18
+ /** Additional context for rendering */
19
+ context?: {
20
+ siteId?: string;
21
+ locale?: string;
22
+ [key: string]: unknown;
23
+ };
24
+ }
25
+ /**
26
+ * Block Renderer Component
27
+ * Renders a single block using its Preview component from the registry
28
+ *
29
+ * This is the headless rendering layer - it uses the Preview component
30
+ * provided by the client application, allowing each client to have
31
+ * their own design system in the frontend while the editor uses
32
+ * the dashboard's design system.
33
+ */
34
+ export declare function BlockRenderer({ block, customRenderers, context }: BlockRendererProps): import("react/jsx-runtime").JSX.Element;
35
+ /**
36
+ * Blocks Renderer
37
+ * Renders an array of blocks
38
+ */
39
+ export interface BlocksRendererProps {
40
+ /** Array of blocks to render */
41
+ blocks: Block[];
42
+ /** Custom renderers for specific block types */
43
+ customRenderers?: Map<string, React.ComponentType<{
44
+ block: Block;
45
+ }>>;
46
+ /** Additional props to pass to renderers */
47
+ renderProps?: Record<string, unknown>;
48
+ /** Wrapper component for the blocks */
49
+ wrapper?: React.ComponentType<{
50
+ children: React.ReactNode;
51
+ }>;
52
+ }
53
+ export declare function BlocksRenderer({ blocks, customRenderers, renderProps, wrapper: Wrapper, }: BlocksRendererProps): import("react/jsx-runtime").JSX.Element;
54
+ //# sourceMappingURL=BlockRenderer.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"BlockRenderer.d.ts","sourceRoot":"","sources":["BlockRenderer.tsx"],"names":[],"mappings":"AAAA;;;;;;GAMG;AAIH,OAAO,KAAK,MAAM,OAAO,CAAC;AAC1B,OAAO,EAAE,KAAK,EAAE,iBAAiB,EAAE,MAAM,mBAAmB,CAAC;AAI7D;;GAEG;AACH,MAAM,WAAW,kBAAkB;IAC/B,sBAAsB;IACtB,KAAK,EAAE,KAAK,CAAC;IAEb,oEAAoE;IACpE,eAAe,CAAC,EAAE,GAAG,CAAC,MAAM,EAAE,KAAK,CAAC,aAAa,CAAC,iBAAiB,CAAC,CAAC,CAAC;IAEtE,uCAAuC;IACvC,OAAO,CAAC,EAAE;QACN,MAAM,CAAC,EAAE,MAAM,CAAC;QAChB,MAAM,CAAC,EAAE,MAAM,CAAC;QAChB,CAAC,GAAG,EAAE,MAAM,GAAG,OAAO,CAAC;KAC1B,CAAC;CACL;AAED;;;;;;;;GAQG;AACH,wBAAgB,aAAa,CAAC,EAC1B,KAAK,EACL,eAAe,EACf,OAAY,EACf,EAAE,kBAAkB,2CAqDpB;AAED;;;GAGG;AACH,MAAM,WAAW,mBAAmB;IAChC,gCAAgC;IAChC,MAAM,EAAE,KAAK,EAAE,CAAC;IAEhB,gDAAgD;IAChD,eAAe,CAAC,EAAE,GAAG,CAAC,MAAM,EAAE,KAAK,CAAC,aAAa,CAAC;QAAE,KAAK,EAAE,KAAK,CAAA;KAAE,CAAC,CAAC,CAAC;IAErE,4CAA4C;IAC5C,WAAW,CAAC,EAAE,MAAM,CAAC,MAAM,EAAE,OAAO,CAAC,CAAC;IAEtC,uCAAuC;IACvC,OAAO,CAAC,EAAE,KAAK,CAAC,aAAa,CAAC;QAAE,QAAQ,EAAE,KAAK,CAAC,SAAS,CAAA;KAAE,CAAC,CAAC;CAChE;AAED,wBAAgB,cAAc,CAAC,EAC3B,MAAM,EACN,eAAe,EACf,WAAW,EACX,OAAO,EAAE,OAAO,GACnB,EAAE,mBAAmB,2CAerB"}