@jhits/plugin-newsletter 0.0.4 → 0.0.5

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 (44) hide show
  1. package/package.json +26 -25
  2. package/src/api/handler.ts +340 -1
  3. package/src/api/router.ts +35 -0
  4. package/src/index.tsx +284 -4
  5. package/src/index.tsx.patch +98 -0
  6. package/src/init.tsx +72 -0
  7. package/src/lib/blocks/BlockRenderer.tsx +125 -0
  8. package/src/lib/email/EmailRenderer.tsx +425 -0
  9. package/src/lib/email/index.ts +6 -0
  10. package/src/lib/mappers/apiMapper.ts +57 -0
  11. package/src/lib/utils/blockHelpers.ts +71 -0
  12. package/src/lib/utils/slugify.ts +43 -0
  13. package/src/registry/BlockRegistry.ts +53 -0
  14. package/src/registry/index.ts +5 -0
  15. package/src/state/EditorContext.tsx +279 -0
  16. package/src/state/index.ts +10 -0
  17. package/src/state/reducer.ts +561 -0
  18. package/src/state/types.ts +154 -0
  19. package/src/types/block.ts +275 -0
  20. package/src/types/newsletter.ts +114 -1
  21. package/src/types/registry.ts +14 -0
  22. package/src/views/CanvasEditor/BlockWrapper.tsx +143 -0
  23. package/src/views/CanvasEditor/CanvasEditorView.tsx +249 -0
  24. package/src/views/CanvasEditor/EditorBody.tsx +95 -0
  25. package/src/views/CanvasEditor/EditorHeader.tsx +139 -0
  26. package/src/views/CanvasEditor/components/CustomBlockItem.tsx +83 -0
  27. package/src/views/CanvasEditor/components/EditorCanvas.tsx +674 -0
  28. package/src/views/CanvasEditor/components/EditorLibrary.tsx +120 -0
  29. package/src/views/CanvasEditor/components/EditorSidebar.tsx +156 -0
  30. package/src/views/CanvasEditor/components/ErrorBanner.tsx +31 -0
  31. package/src/views/CanvasEditor/components/LibraryItem.tsx +71 -0
  32. package/src/views/CanvasEditor/components/SlashCommandDetector.tsx +196 -0
  33. package/src/views/CanvasEditor/components/SlashCommandMenu.tsx +131 -0
  34. package/src/views/CanvasEditor/components/index.ts +16 -0
  35. package/src/views/CanvasEditor/hooks/index.ts +7 -0
  36. package/src/views/CanvasEditor/hooks/useKeyboardShortcuts.ts +136 -0
  37. package/src/views/CanvasEditor/hooks/useNewsletterLoader.ts +34 -0
  38. package/src/views/CanvasEditor/hooks/useRegisteredBlocks.ts +54 -0
  39. package/src/views/CanvasEditor/hooks/useSlashCommand.ts +106 -0
  40. package/src/views/CanvasEditor/index.ts +12 -0
  41. package/src/views/NewsletterEditor.tsx +38 -0
  42. package/src/views/NewsletterManager.tsx +240 -0
  43. package/src/views/SettingsView.tsx +14 -14
  44. package/src/views/SubscribersView.tsx +20 -20
package/src/index.tsx CHANGED
@@ -1,33 +1,313 @@
1
1
  /**
2
2
  * Plugin Newsletter - Client Entry Point
3
3
  * Main newsletter management interface for the dashboard
4
+ * Block-Based Newsletter Management System
5
+ * Multi-Tenant Architecture: Accepts custom blocks from client applications
4
6
  */
5
7
 
6
8
  'use client';
7
9
 
8
- import React from 'react';
10
+ import React, { useMemo, useEffect } from 'react';
11
+ import { EditorProvider } from './state/EditorContext';
12
+ import { ClientBlockDefinition } from './types/block';
9
13
  import { SubscribersView } from './views/SubscribersView';
10
14
  import { SettingsView } from './views/SettingsView';
15
+ import { NewsletterManagerView } from './views/NewsletterManager';
16
+ import { NewsletterEditorView } from './views/NewsletterEditor';
17
+ import { editorStateToAPI } from './lib/mappers/apiMapper';
11
18
 
19
+ /**
20
+ * Plugin Props Interface
21
+ * Matches the PluginProps from @jhits/jhits-dashboard
22
+ */
12
23
  export interface PluginProps {
13
24
  subPath: string[];
14
25
  siteId: string;
15
26
  locale: string;
27
+ /** Custom blocks from client application (optional, can also come from window.__JHITS_PLUGIN_PROPS__) */
28
+ customBlocks?: ClientBlockDefinition[];
29
+ /** Enable dark mode for content area and wrappers (default: true) */
30
+ darkMode?: boolean;
31
+ /** Background colors for the editor */
32
+ backgroundColors?: {
33
+ /** Background color for light mode (REQUIRED) */
34
+ light: string;
35
+ /** Background color for dark mode (optional) */
36
+ dark?: string;
37
+ };
16
38
  }
17
39
 
18
- export default function NewsletterPlugin({ subPath, siteId, locale }: PluginProps) {
19
- const route = subPath[0] || 'subscribers';
40
+ /**
41
+ * Main Router Component
42
+ * Handles routing within the newsletter plugin
43
+ *
44
+ * Client Handshake:
45
+ * - Client apps can pass customBlocks via props
46
+ * - Or via window.__JHITS_PLUGIN_PROPS__['plugin-newsletter'].customBlocks
47
+ * - The EditorProvider will automatically register these blocks
48
+ */
49
+ export default function NewsletterPlugin(props: PluginProps) {
50
+ const { subPath, siteId, locale, customBlocks: propsCustomBlocks, darkMode: propsDarkMode, backgroundColors: propsBackgroundColors } = props;
51
+
52
+ // Get custom blocks from props or window global (client app injection point)
53
+ const customBlocks = useMemo(() => {
54
+ // First, try props
55
+ if (propsCustomBlocks && propsCustomBlocks.length > 0) {
56
+ return propsCustomBlocks;
57
+ }
58
+
59
+ // Fallback to window global (for client app injection)
60
+ if (typeof window !== 'undefined' && (window as any).__JHITS_PLUGIN_PROPS__) {
61
+ const pluginProps = (window as any).__JHITS_PLUGIN_PROPS__['plugin-newsletter'];
62
+ if (pluginProps?.customBlocks) {
63
+ return pluginProps.customBlocks as ClientBlockDefinition[];
64
+ }
65
+ }
66
+
67
+ return [];
68
+ }, [propsCustomBlocks]);
69
+
70
+ // Get dark mode setting from props, localStorage (dev settings), or window global
71
+ // Priority: localStorage (dev) > props > window global > default
72
+ const darkMode = useMemo(() => {
73
+ // First, check localStorage for dev settings (highest priority for dev)
74
+ if (typeof window !== 'undefined') {
75
+ try {
76
+ const saved = localStorage.getItem('__JHITS_PLUGIN_NEWSLETTER_CONFIG__');
77
+ if (saved) {
78
+ const config = JSON.parse(saved);
79
+ if (config.darkMode !== undefined) {
80
+ return config.darkMode as boolean;
81
+ }
82
+ }
83
+ } catch (e) {
84
+ // Ignore localStorage errors
85
+ }
86
+ }
87
+
88
+ // Then try props
89
+ if (propsDarkMode !== undefined) {
90
+ return propsDarkMode;
91
+ }
92
+
93
+ // Fallback to window global if prop not provided
94
+ if (typeof window !== 'undefined' && (window as any).__JHITS_PLUGIN_PROPS__) {
95
+ const pluginProps = (window as any).__JHITS_PLUGIN_PROPS__['plugin-newsletter'];
96
+ if (pluginProps?.darkMode !== undefined) {
97
+ return pluginProps.darkMode as boolean;
98
+ }
99
+ }
100
+
101
+ return true; // Default to dark mode enabled
102
+ }, [propsDarkMode]);
103
+
104
+ // Get background colors from props, localStorage (dev settings), or window global
105
+ // Priority: localStorage (dev) > props > window global
106
+ const backgroundColors = useMemo(() => {
107
+ // First, check localStorage for dev settings (highest priority for dev)
108
+ if (typeof window !== 'undefined') {
109
+ try {
110
+ const saved = localStorage.getItem('__JHITS_PLUGIN_NEWSLETTER_CONFIG__');
111
+ if (saved) {
112
+ const config = JSON.parse(saved);
113
+ if (config.backgroundColors) {
114
+ return config.backgroundColors;
115
+ }
116
+ }
117
+ } catch (e) {
118
+ // Ignore localStorage errors
119
+ }
120
+ }
121
+
122
+ // Then try props
123
+ if (propsBackgroundColors) {
124
+ return propsBackgroundColors;
125
+ }
126
+
127
+ // Fallback to window global
128
+ if (typeof window !== 'undefined' && (window as any).__JHITS_PLUGIN_PROPS__) {
129
+ const pluginProps = (window as any).__JHITS_PLUGIN_PROPS__['plugin-newsletter'];
130
+ if (pluginProps?.backgroundColors) {
131
+ return pluginProps.backgroundColors as { light: string; dark?: string };
132
+ }
133
+ }
134
+
135
+ return undefined;
136
+ }, [propsBackgroundColors]);
137
+
138
+ const route = subPath[0] || 'newsletters';
139
+
140
+ // Listen for config updates from settings screen
141
+ useEffect(() => {
142
+ if (typeof window === 'undefined') return;
143
+
144
+ const handleConfigUpdate = () => {
145
+ // Reload page to apply changes (simplest way to ensure all components pick up new values)
146
+ window.location.reload();
147
+ };
148
+
149
+ window.addEventListener('newsletter-plugin-config-updated', handleConfigUpdate as EventListener);
150
+ return () => {
151
+ window.removeEventListener('newsletter-plugin-config-updated', handleConfigUpdate as EventListener);
152
+ };
153
+ }, []);
20
154
 
155
+ // Route to appropriate view
21
156
  switch (route) {
157
+ case 'newsletters':
158
+ return <NewsletterManagerView siteId={siteId} locale={locale} />;
159
+
160
+ case 'editor':
161
+ const newsletterSlug = subPath[1];
162
+ return (
163
+ <EditorProvider
164
+ customBlocks={customBlocks}
165
+ darkMode={darkMode}
166
+ backgroundColors={backgroundColors}
167
+ onSave={async (state) => {
168
+ // Save to API - create new or update existing newsletter
169
+ const originalSlug = newsletterSlug || state.slug;
170
+ const apiData = editorStateToAPI(state);
171
+
172
+ // If we have a slug, try to update first
173
+ if (originalSlug) {
174
+ console.log('[NewsletterPlugin] Attempting to update newsletter with slug:', originalSlug);
175
+ const updateResponse = await fetch(`/api/plugin-newsletter/newsletters/${originalSlug}`, {
176
+ method: 'PUT',
177
+ headers: { 'Content-Type': 'application/json' },
178
+ credentials: 'include',
179
+ body: JSON.stringify(apiData),
180
+ });
181
+
182
+ if (updateResponse.ok) {
183
+ const result = await updateResponse.json();
184
+ // If the slug changed, update the URL
185
+ if (result.slug && result.slug !== originalSlug) {
186
+ window.history.replaceState(null, '', `/dashboard/newsletter/editor/${result.slug}`);
187
+ }
188
+ return result;
189
+ }
190
+
191
+ // If 404, newsletter doesn't exist, create a new one
192
+ if (updateResponse.status === 404) {
193
+ console.log('[NewsletterPlugin] Newsletter not found, creating new newsletter');
194
+ } else {
195
+ // Other error, throw it
196
+ const error = await updateResponse.json();
197
+ console.error('[NewsletterPlugin] Save failed:', {
198
+ status: updateResponse.status,
199
+ statusText: updateResponse.statusText,
200
+ error,
201
+ });
202
+ const errorMessage = error.message || error.error || 'Failed to save newsletter';
203
+ throw new Error(errorMessage);
204
+ }
205
+ }
206
+
207
+ // Create new newsletter (either no slug or update returned 404)
208
+ console.log('[NewsletterPlugin] Creating new newsletter');
209
+ const createResponse = await fetch('/api/plugin-newsletter/newsletters/new', {
210
+ method: 'POST',
211
+ headers: { 'Content-Type': 'application/json' },
212
+ credentials: 'include',
213
+ body: JSON.stringify(apiData),
214
+ });
215
+
216
+ if (!createResponse.ok) {
217
+ const error = await createResponse.json();
218
+ console.error('[NewsletterPlugin] Create failed:', {
219
+ status: createResponse.status,
220
+ statusText: createResponse.statusText,
221
+ error,
222
+ });
223
+ const errorMessage = error.message || error.error || 'Failed to create newsletter';
224
+ throw new Error(errorMessage);
225
+ }
226
+
227
+ const result = await createResponse.json();
228
+ // Update the URL to the new newsletter's slug
229
+ if (result.slug) {
230
+ window.history.replaceState(null, '', `/dashboard/newsletter/editor/${result.slug}`);
231
+ }
232
+ return result;
233
+ }}
234
+ >
235
+ <NewsletterEditorView newsletterSlug={newsletterSlug} siteId={siteId} locale={locale} darkMode={darkMode} backgroundColors={backgroundColors} />
236
+ </EditorProvider>
237
+ );
238
+
239
+ case 'new':
240
+ return (
241
+ <EditorProvider
242
+ customBlocks={customBlocks}
243
+ darkMode={darkMode}
244
+ backgroundColors={backgroundColors}
245
+ onSave={async (state) => {
246
+ // Save to API - create new newsletter
247
+ const apiData = editorStateToAPI(state);
248
+ const response = await fetch('/api/plugin-newsletter/newsletters/new', {
249
+ method: 'POST',
250
+ headers: { 'Content-Type': 'application/json' },
251
+ credentials: 'include',
252
+ body: JSON.stringify(apiData),
253
+ });
254
+ if (!response.ok) {
255
+ const error = await response.json();
256
+ throw new Error(error.message || 'Failed to create newsletter');
257
+ }
258
+ const result = await response.json();
259
+ // Update the URL to the new newsletter's slug
260
+ if (result.slug) {
261
+ window.history.replaceState(null, '', `/dashboard/newsletter/editor/${result.slug}`);
262
+ }
263
+ return result;
264
+ }}
265
+ >
266
+ <NewsletterEditorView siteId={siteId} locale={locale} darkMode={darkMode} backgroundColors={backgroundColors} />
267
+ </EditorProvider>
268
+ );
269
+
22
270
  case 'subscribers':
23
271
  return <SubscribersView siteId={siteId} locale={locale} />;
272
+
24
273
  case 'settings':
25
274
  return <SettingsView siteId={siteId} locale={locale} />;
275
+
26
276
  default:
27
- return <SubscribersView siteId={siteId} locale={locale} />;
277
+ return <NewsletterManagerView siteId={siteId} locale={locale} />;
28
278
  }
29
279
  }
30
280
 
31
281
  // Export for use as default
32
282
  export { NewsletterPlugin as Index };
33
283
 
284
+ // Export types for client applications
285
+ export type {
286
+ Block,
287
+ BlockTypeDefinition,
288
+ ClientBlockDefinition,
289
+ RichTextFormattingConfig,
290
+ BlockEditProps,
291
+ BlockPreviewProps,
292
+ IBlockComponent,
293
+ } from './types/block';
294
+
295
+ // Export newsletter types
296
+ export type {
297
+ Newsletter,
298
+ NewsletterStatus,
299
+ NewsletterMetadata,
300
+ NewsletterListItem,
301
+ NewsletterFilterOptions,
302
+ } from './types/newsletter';
303
+
304
+ // Export initialization utility for easy setup
305
+ export { initNewsletterPlugin } from './init';
306
+ export type { NewsletterPluginConfig } from './init';
307
+
308
+ // Export editor state management
309
+ export { EditorProvider, useEditor } from './state/EditorContext';
310
+ export type { EditorProviderProps, EditorState, EditorContextValue } from './state';
311
+
312
+ // Export block registry
313
+ export { blockRegistry } from './registry';
@@ -0,0 +1,98 @@
1
+ --- a/packages/plugin-newsletter/src/index.tsx
2
+ +++ b/packages/plugin-newsletter/src/index.tsx
3
+ @@ -165,7 +165,50 @@ export default function NewsletterPlugin(props: PluginProps) {
4
+ onSave={async (state) => {
5
+ - // Save to API - update existing newsletter
6
+ + // Save to API - create new or update existing newsletter
7
+ const originalSlug = newsletterSlug || state.slug;
8
+ - if (!originalSlug) {
9
+ - throw new Error('Cannot save: no newsletter identifier available. Please reload the page.');
10
+ - }
11
+ - console.log('[NewsletterPlugin] Saving newsletter with slug:', originalSlug);
12
+ const apiData = editorStateToAPI(state);
13
+ - const response = await fetch(`/api/plugin-newsletter/newsletters/${originalSlug}`, {
14
+ - method: 'PUT',
15
+ - headers: { 'Content-Type': 'application/json' },
16
+ - credentials: 'include',
17
+ - body: JSON.stringify(apiData),
18
+ - });
19
+ - if (!response.ok) {
20
+ - const error = await response.json();
21
+ - console.error('[NewsletterPlugin] Save failed:', {
22
+ - status: response.status,
23
+ - statusText: response.statusText,
24
+ - error,
25
+ - });
26
+ - const errorMessage = error.message || error.error || 'Failed to save newsletter';
27
+ - throw new Error(errorMessage);
28
+ - }
29
+ - const result = await response.json();
30
+ - // If the slug changed, update the URL
31
+ - if (result.slug && result.slug !== originalSlug) {
32
+ - window.history.replaceState(null, '', `/dashboard/newsletter/editor/${result.slug}`);
33
+ - }
34
+ - return result;
35
+ +
36
+ + // If we have a slug, try to update first
37
+ + if (originalSlug) {
38
+ + console.log('[NewsletterPlugin] Attempting to update newsletter with slug:', originalSlug);
39
+ + const updateResponse = await fetch(`/api/plugin-newsletter/newsletters/${originalSlug}`, {
40
+ + method: 'PUT',
41
+ + headers: { 'Content-Type': 'application/json' },
42
+ + credentials: 'include',
43
+ + body: JSON.stringify(apiData),
44
+ + });
45
+ +
46
+ + if (updateResponse.ok) {
47
+ + const result = await updateResponse.json();
48
+ + // If the slug changed, update the URL
49
+ + if (result.slug && result.slug !== originalSlug) {
50
+ + window.history.replaceState(null, '', `/dashboard/newsletter/editor/${result.slug}`);
51
+ + }
52
+ + return result;
53
+ + }
54
+ +
55
+ + // If 404, newsletter doesn't exist, create a new one
56
+ + if (updateResponse.status === 404) {
57
+ + console.log('[NewsletterPlugin] Newsletter not found, creating new newsletter');
58
+ + } else {
59
+ + // Other error, throw it
60
+ + const error = await updateResponse.json();
61
+ + console.error('[NewsletterPlugin] Save failed:', {
62
+ + status: updateResponse.status,
63
+ + statusText: updateResponse.statusText,
64
+ + error,
65
+ + });
66
+ + const errorMessage = error.message || error.error || 'Failed to save newsletter';
67
+ + throw new Error(errorMessage);
68
+ + }
69
+ + }
70
+ +
71
+ + // Create new newsletter (either no slug or update returned 404)
72
+ + console.log('[NewsletterPlugin] Creating new newsletter');
73
+ + const createResponse = await fetch('/api/plugin-newsletter/newsletters/new', {
74
+ + method: 'POST',
75
+ + headers: { 'Content-Type': 'application/json' },
76
+ + credentials: 'include',
77
+ + body: JSON.stringify(apiData),
78
+ + });
79
+ +
80
+ + if (!createResponse.ok) {
81
+ + const error = await createResponse.json();
82
+ + console.error('[NewsletterPlugin] Create failed:', {
83
+ + status: createResponse.status,
84
+ + statusText: createResponse.statusText,
85
+ + error,
86
+ + });
87
+ + const errorMessage = error.message || error.error || 'Failed to create newsletter';
88
+ + throw new Error(errorMessage);
89
+ + }
90
+ +
91
+ + const result = await createResponse.json();
92
+ + // Update the URL to the new newsletter's slug
93
+ + if (result.slug) {
94
+ + window.history.replaceState(null, '', `/dashboard/newsletter/editor/${result.slug}`);
95
+ + }
96
+ + return result;
97
+ }}
98
+ >
package/src/init.tsx ADDED
@@ -0,0 +1,72 @@
1
+ /**
2
+ * Newsletter Plugin Initialization Utility
3
+ *
4
+ * Simple function to initialize the newsletter plugin with client configuration.
5
+ * Call this once in your app (e.g., in a script tag or root layout) to configure
6
+ * the newsletter plugin without needing a React component.
7
+ *
8
+ * @example
9
+ * ```typescript
10
+ * import { initNewsletterPlugin } from '@jhits/plugin-newsletter/init';
11
+ * import { newsletterConfig } from '@/plugins/newsletter-config';
12
+ *
13
+ * // Call once when your app loads
14
+ * initNewsletterPlugin(newsletterConfig);
15
+ * ```
16
+ */
17
+
18
+ 'use client';
19
+
20
+ import React from 'react';
21
+ import type { ClientBlockDefinition } from './types/block';
22
+
23
+ export interface NewsletterPluginConfig {
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
+ /** Email configuration */
36
+ emailConfig?: {
37
+ /** Logo URL to display in email header (absolute URL) */
38
+ logoUrl?: string;
39
+ /** Logo alt text */
40
+ logoAlt?: string;
41
+ /** Footer text for emails */
42
+ footerText?: string;
43
+ };
44
+ }
45
+
46
+ /**
47
+ * Initialize the newsletter plugin with client configuration
48
+ *
49
+ * This function sets up the window global that the plugin reads from automatically.
50
+ * Call this once when your app loads, before the plugin is rendered.
51
+ *
52
+ * @param config - Newsletter plugin configuration (customBlocks, darkMode, etc.)
53
+ */
54
+ export function initNewsletterPlugin(config: NewsletterPluginConfig): void {
55
+ if (typeof window === 'undefined') {
56
+ // Server-side: no-op
57
+ return;
58
+ }
59
+
60
+ // Initialize the global plugin props object if it doesn't exist
61
+ if (!(window as any).__JHITS_PLUGIN_PROPS__) {
62
+ (window as any).__JHITS_PLUGIN_PROPS__ = {};
63
+ }
64
+
65
+ // Set newsletter plugin configuration
66
+ (window as any).__JHITS_PLUGIN_PROPS__['plugin-newsletter'] = {
67
+ customBlocks: config.customBlocks || [],
68
+ darkMode: config.darkMode !== undefined ? config.darkMode : true, // Default to true
69
+ backgroundColors: config.backgroundColors || undefined,
70
+ emailConfig: config.emailConfig || undefined,
71
+ };
72
+ }
@@ -0,0 +1,125 @@
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
+
9
+ 'use client';
10
+
11
+ import React from 'react';
12
+ import { Block, BlockPreviewProps } from '../../types/block';
13
+ import { blockRegistry } from '../../registry/BlockRegistry';
14
+ import { getChildBlocks } from '../utils/blockHelpers';
15
+
16
+ /**
17
+ * Block Renderer Props
18
+ */
19
+ export interface BlockRendererProps {
20
+ /** Block to render */
21
+ block: Block;
22
+
23
+ /** Custom renderers for specific block types (optional override) */
24
+ customRenderers?: Map<string, React.ComponentType<BlockPreviewProps>>;
25
+
26
+ /** Additional context for rendering */
27
+ context?: {
28
+ siteId?: string;
29
+ locale?: string;
30
+ [key: string]: unknown;
31
+ };
32
+ }
33
+
34
+ /**
35
+ * Block Renderer Component
36
+ * Renders a single block using its Preview component from the registry
37
+ */
38
+ export function BlockRenderer({
39
+ block,
40
+ customRenderers,
41
+ context = {}
42
+ }: BlockRendererProps) {
43
+ // Check for custom renderer override first
44
+ if (customRenderers?.has(block.type)) {
45
+ const CustomRenderer = customRenderers.get(block.type)!;
46
+ return <CustomRenderer block={block} context={context} />;
47
+ }
48
+
49
+ // Get block definition from registry
50
+ const definition = blockRegistry.get(block.type);
51
+ if (!definition) {
52
+ console.warn(`Block type "${block.type}" not found in registry. Available types:`,
53
+ blockRegistry.getAll().map(b => b.type).join(', '));
54
+ return (
55
+ <div className="p-4 border border-red-300 bg-red-50 rounded">
56
+ <p className="text-red-600">Unknown block type: {block.type}</p>
57
+ <p className="text-xs text-red-500 mt-1">
58
+ Make sure this block type is registered via customBlocks prop
59
+ </p>
60
+ </div>
61
+ );
62
+ }
63
+
64
+ // Use the Preview component from the block definition
65
+ const PreviewComponent = definition.components.Preview;
66
+
67
+ // Check if this is a container block with children
68
+ const isContainer = definition.isContainer === true;
69
+ const childBlocks = isContainer && block.children && Array.isArray(block.children) && block.children.length > 0
70
+ ? (typeof block.children[0] === 'object'
71
+ ? block.children as Block[]
72
+ : [])
73
+ : [];
74
+
75
+ // If container block, pass child blocks and render function
76
+ if (isContainer) {
77
+ return (
78
+ <PreviewComponent
79
+ block={block}
80
+ context={context}
81
+ childBlocks={childBlocks}
82
+ renderChild={(childBlock: Block) => (
83
+ <BlockRenderer
84
+ block={childBlock}
85
+ customRenderers={customRenderers}
86
+ context={context}
87
+ />
88
+ )}
89
+ />
90
+ );
91
+ }
92
+
93
+ return <PreviewComponent block={block} context={context} />;
94
+ }
95
+
96
+ /**
97
+ * Blocks Renderer Component
98
+ * Renders multiple blocks in sequence
99
+ */
100
+ export function BlocksRenderer({
101
+ blocks,
102
+ customRenderers,
103
+ context = {}
104
+ }: {
105
+ blocks: Block[];
106
+ customRenderers?: Map<string, React.ComponentType<BlockPreviewProps>>;
107
+ context?: {
108
+ siteId?: string;
109
+ locale?: string;
110
+ [key: string]: unknown;
111
+ };
112
+ }) {
113
+ return (
114
+ <>
115
+ {blocks.map((block) => (
116
+ <BlockRenderer
117
+ key={block.id}
118
+ block={block}
119
+ customRenderers={customRenderers}
120
+ context={context}
121
+ />
122
+ ))}
123
+ </>
124
+ );
125
+ }