@jhits/plugin-blog 0.0.1

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 (75) hide show
  1. package/README.md +216 -0
  2. package/package.json +57 -0
  3. package/src/api/README.md +224 -0
  4. package/src/api/categories.ts +43 -0
  5. package/src/api/check-title.ts +60 -0
  6. package/src/api/handler.ts +419 -0
  7. package/src/api/index.ts +33 -0
  8. package/src/api/route.ts +116 -0
  9. package/src/api/router.ts +114 -0
  10. package/src/api-server.ts +11 -0
  11. package/src/config.ts +161 -0
  12. package/src/hooks/README.md +91 -0
  13. package/src/hooks/index.ts +8 -0
  14. package/src/hooks/useBlog.ts +85 -0
  15. package/src/hooks/useBlogs.ts +123 -0
  16. package/src/index.server.ts +12 -0
  17. package/src/index.tsx +354 -0
  18. package/src/init.tsx +72 -0
  19. package/src/lib/blocks/BlockRenderer.tsx +141 -0
  20. package/src/lib/blocks/index.ts +6 -0
  21. package/src/lib/index.ts +9 -0
  22. package/src/lib/layouts/blocks/ColumnsBlock.tsx +134 -0
  23. package/src/lib/layouts/blocks/SectionBlock.tsx +104 -0
  24. package/src/lib/layouts/blocks/index.ts +8 -0
  25. package/src/lib/layouts/index.ts +52 -0
  26. package/src/lib/layouts/registerLayoutBlocks.ts +59 -0
  27. package/src/lib/mappers/apiMapper.ts +223 -0
  28. package/src/lib/migration/index.ts +6 -0
  29. package/src/lib/migration/mapper.ts +140 -0
  30. package/src/lib/rich-text/RichTextEditor.tsx +826 -0
  31. package/src/lib/rich-text/RichTextPreview.tsx +210 -0
  32. package/src/lib/rich-text/index.ts +10 -0
  33. package/src/lib/utils/blockHelpers.ts +72 -0
  34. package/src/lib/utils/configValidation.ts +137 -0
  35. package/src/lib/utils/index.ts +8 -0
  36. package/src/lib/utils/slugify.ts +79 -0
  37. package/src/registry/BlockRegistry.ts +142 -0
  38. package/src/registry/index.ts +11 -0
  39. package/src/state/EditorContext.tsx +277 -0
  40. package/src/state/index.ts +8 -0
  41. package/src/state/reducer.ts +694 -0
  42. package/src/state/types.ts +160 -0
  43. package/src/types/block.ts +269 -0
  44. package/src/types/index.ts +15 -0
  45. package/src/types/post.ts +165 -0
  46. package/src/utils/README.md +75 -0
  47. package/src/utils/client.ts +122 -0
  48. package/src/utils/index.ts +9 -0
  49. package/src/views/CanvasEditor/BlockWrapper.tsx +459 -0
  50. package/src/views/CanvasEditor/CanvasEditorView.tsx +917 -0
  51. package/src/views/CanvasEditor/EditorBody.tsx +475 -0
  52. package/src/views/CanvasEditor/EditorHeader.tsx +179 -0
  53. package/src/views/CanvasEditor/LayoutContainer.tsx +494 -0
  54. package/src/views/CanvasEditor/SaveConfirmationModal.tsx +233 -0
  55. package/src/views/CanvasEditor/components/CustomBlockItem.tsx +92 -0
  56. package/src/views/CanvasEditor/components/FeaturedMediaSection.tsx +130 -0
  57. package/src/views/CanvasEditor/components/LibraryItem.tsx +80 -0
  58. package/src/views/CanvasEditor/components/PrivacySettingsSection.tsx +212 -0
  59. package/src/views/CanvasEditor/components/index.ts +17 -0
  60. package/src/views/CanvasEditor/index.ts +16 -0
  61. package/src/views/PostManager/EmptyState.tsx +42 -0
  62. package/src/views/PostManager/PostActionsMenu.tsx +112 -0
  63. package/src/views/PostManager/PostCards.tsx +192 -0
  64. package/src/views/PostManager/PostFilters.tsx +80 -0
  65. package/src/views/PostManager/PostManagerView.tsx +280 -0
  66. package/src/views/PostManager/PostStats.tsx +81 -0
  67. package/src/views/PostManager/PostTable.tsx +225 -0
  68. package/src/views/PostManager/index.ts +15 -0
  69. package/src/views/Preview/PreviewBridgeView.tsx +64 -0
  70. package/src/views/Preview/index.ts +7 -0
  71. package/src/views/README.md +82 -0
  72. package/src/views/Settings/SettingsView.tsx +298 -0
  73. package/src/views/Settings/index.ts +7 -0
  74. package/src/views/SlugSEO/SlugSEOManagerView.tsx +94 -0
  75. package/src/views/SlugSEO/index.ts +7 -0
@@ -0,0 +1,210 @@
1
+ /**
2
+ * Rich Text Preview Component
3
+ * Renders HTML content with client-provided styles
4
+ * Also supports plain text with formatting markers using the plugin-content parser
5
+ */
6
+
7
+ 'use client';
8
+
9
+ import React from 'react';
10
+ import { RichTextFormattingConfig } from './RichTextEditor';
11
+ import { parse, useParserConfig } from '@jhits/plugin-content';
12
+
13
+ export interface RichTextPreviewProps {
14
+ /** HTML content or plain text with formatting markers to render */
15
+ content: string;
16
+ /** Formatting configuration (for applying client styles to HTML) */
17
+ formatting?: RichTextFormattingConfig;
18
+ /** Additional CSS classes */
19
+ className?: string;
20
+ }
21
+
22
+ /**
23
+ * Check if content is HTML or plain text with formatting markers
24
+ */
25
+ function isHtmlContent(content: string): boolean {
26
+ // If content contains HTML tags, it's HTML
27
+ if (/<[a-z][\s\S]*>/i.test(content)) {
28
+ return true;
29
+ }
30
+ // If content contains HTML entities, it's likely HTML
31
+ if (/&[a-z]+;/i.test(content)) {
32
+ return true;
33
+ }
34
+ // Otherwise, it's plain text (potentially with formatting markers)
35
+ return false;
36
+ }
37
+
38
+ export function RichTextPreview({
39
+ content,
40
+ formatting,
41
+ className = '',
42
+ }: RichTextPreviewProps) {
43
+ // Handle empty content
44
+ if (!content || content.trim() === '') {
45
+ return <div className={className}>&nbsp;</div>;
46
+ }
47
+
48
+ // Get parser config from context (provided by client app)
49
+ const parserConfig = useParserConfig();
50
+
51
+ // Check if content is HTML or plain text
52
+ const isHtml = isHtmlContent(content);
53
+
54
+ // If it's plain text, use the parser from plugin-content
55
+ if (!isHtml) {
56
+ const parsedContent = parse(content, false, parserConfig);
57
+ return (
58
+ <div className={className}>
59
+ {parsedContent}
60
+ </div>
61
+ );
62
+ }
63
+
64
+ // Otherwise, continue with HTML rendering logic
65
+ // Apply client-provided styles to HTML content
66
+ const applyStyles = (html: string): string => {
67
+ if (!formatting?.styles) return html;
68
+
69
+ const styles = formatting.styles;
70
+ let styledHtml = html;
71
+
72
+ // Apply bold style - handle both <strong> and <b> tags
73
+ if (styles.bold) {
74
+ // Replace <strong> tags
75
+ styledHtml = styledHtml.replace(
76
+ /<strong\b([^>]*)>/gi,
77
+ (match, attrs) => {
78
+ // Check if class already exists
79
+ if (attrs && attrs.includes('class=')) {
80
+ return match.replace(/class="([^"]*)"/, `class="$1 ${styles.bold}"`);
81
+ }
82
+ return `<strong class="${styles.bold}">`;
83
+ }
84
+ );
85
+ // Replace <b> tags
86
+ styledHtml = styledHtml.replace(
87
+ /<b\b([^>]*)>/gi,
88
+ (match, attrs) => {
89
+ if (attrs && attrs.includes('class=')) {
90
+ return match.replace(/class="([^"]*)"/, `class="$1 ${styles.bold}"`);
91
+ }
92
+ return `<b class="${styles.bold}">`;
93
+ }
94
+ );
95
+ }
96
+
97
+ // Apply italic style - handle both <em> and <i> tags
98
+ if (styles.italic) {
99
+ styledHtml = styledHtml.replace(
100
+ /<em\b([^>]*)>/gi,
101
+ (match, attrs) => {
102
+ if (attrs && attrs.includes('class=')) {
103
+ return match.replace(/class="([^"]*)"/, `class="$1 ${styles.italic}"`);
104
+ }
105
+ return `<em class="${styles.italic}">`;
106
+ }
107
+ );
108
+ styledHtml = styledHtml.replace(
109
+ /<i\b([^>]*)>/gi,
110
+ (match, attrs) => {
111
+ if (attrs && attrs.includes('class=')) {
112
+ return match.replace(/class="([^"]*)"/, `class="$1 ${styles.italic}"`);
113
+ }
114
+ return `<i class="${styles.italic}">`;
115
+ }
116
+ );
117
+ }
118
+
119
+ // Apply underline style
120
+ if (styles.underline) {
121
+ styledHtml = styledHtml.replace(
122
+ /<u\b([^>]*)>/gi,
123
+ (match, attrs) => {
124
+ if (attrs && attrs.includes('class=')) {
125
+ return match.replace(/class="([^"]*)"/, `class="$1 ${styles.underline}"`);
126
+ }
127
+ return `<u class="${styles.underline}">`;
128
+ }
129
+ );
130
+ }
131
+
132
+ // Apply link style
133
+ if (styles.link) {
134
+ styledHtml = styledHtml.replace(
135
+ /<a\b([^>]*)>/gi,
136
+ (match, attrs) => {
137
+ if (attrs && attrs.includes('class=')) {
138
+ return match.replace(/class="([^"]*)"/, `class="$1 ${styles.link}"`);
139
+ }
140
+ return match.replace('>', ` class="${styles.link}">`);
141
+ }
142
+ );
143
+ }
144
+
145
+ // Apply color classes to spans (preserve existing classes)
146
+ if (styles.colorClasses) {
147
+ Object.entries(styles.colorClasses).forEach(([color, colorClass]) => {
148
+ // Match spans that might have the color class already or need it added
149
+ const regex = new RegExp(`<span([^>]*)class="([^"]*)"([^>]*)>`, 'gi');
150
+ styledHtml = styledHtml.replace(regex, (match, beforeAttrs, existingClasses, afterAttrs) => {
151
+ // Don't add if class already exists
152
+ if (existingClasses.includes(colorClass)) {
153
+ return match;
154
+ }
155
+ // Add the color class
156
+ return `<span${beforeAttrs}class="${existingClasses} ${colorClass}"${afterAttrs}>`;
157
+ });
158
+
159
+ // Also handle spans without class attribute
160
+ const regexNoClass = new RegExp(`<span([^>]*)>`, 'gi');
161
+ styledHtml = styledHtml.replace(regexNoClass, (match, attrs) => {
162
+ // Only add if this span doesn't already have a class and we're looking for a specific color
163
+ if (!attrs.includes('class=')) {
164
+ return match.replace('>', ` class="${colorClass}">`);
165
+ }
166
+ return match;
167
+ });
168
+ });
169
+ }
170
+
171
+ return styledHtml;
172
+ };
173
+
174
+ const styledContent = formatting ? applyStyles(content) : content;
175
+
176
+ // For rendering, we'll use a ref to set innerHTML only on the client side
177
+ // This avoids SSR issues while still allowing HTML rendering
178
+ const contentRef = React.useRef<HTMLDivElement>(null);
179
+
180
+ React.useEffect(() => {
181
+ if (contentRef.current && styledContent) {
182
+ contentRef.current.innerHTML = styledContent;
183
+ }
184
+ }, [styledContent]);
185
+
186
+ // For server-side rendering, render plain text
187
+ if (typeof window === 'undefined') {
188
+ const textContent = styledContent
189
+ .replace(/<[^>]*>/g, '')
190
+ .replace(/&nbsp;/g, ' ')
191
+ .replace(/&amp;/g, '&')
192
+ .replace(/&lt;/g, '<')
193
+ .replace(/&gt;/g, '>')
194
+ .replace(/&quot;/g, '"');
195
+
196
+ return (
197
+ <div className={className}>
198
+ {textContent || '\u00A0'}
199
+ </div>
200
+ );
201
+ }
202
+
203
+ return (
204
+ <div
205
+ ref={contentRef}
206
+ className={className}
207
+ />
208
+ );
209
+ }
210
+
@@ -0,0 +1,10 @@
1
+ /**
2
+ * Rich Text Utilities
3
+ * Export rich text editor and preview components
4
+ */
5
+
6
+ export { RichTextEditor } from './RichTextEditor';
7
+ export { RichTextPreview } from './RichTextPreview';
8
+ export type { RichTextFormattingConfig, RichTextEditorProps } from './RichTextEditor';
9
+ export type { RichTextPreviewProps } from './RichTextPreview';
10
+
@@ -0,0 +1,72 @@
1
+ /**
2
+ * Block Helper Utilities
3
+ * Functions for working with blocks, including nested structures
4
+ */
5
+
6
+ import { Block } from '../../types/block';
7
+
8
+ /**
9
+ * Get child blocks from a container block
10
+ * Handles both Block[] and string[] formats
11
+ */
12
+ export function getChildBlocks(block: Block, allBlocks: Block[] = []): Block[] {
13
+ if (!block.children || block.children.length === 0) {
14
+ return [];
15
+ }
16
+
17
+ // If children are Block objects, return them directly
18
+ if (block.children.length > 0 && typeof block.children[0] === 'object' && 'id' in block.children[0]) {
19
+ return block.children as Block[];
20
+ }
21
+
22
+ // If children are IDs, resolve them from allBlocks (recursively search nested blocks)
23
+ const childIds = block.children as string[];
24
+ const resolvedBlocks: Block[] = [];
25
+
26
+ function findBlockRecursive(blocks: Block[], id: string): Block | null {
27
+ for (const b of blocks) {
28
+ if (b.id === id) return b;
29
+ if (b.children && Array.isArray(b.children) && b.children.length > 0) {
30
+ if (typeof b.children[0] === 'object') {
31
+ const found = findBlockRecursive(b.children as Block[], id);
32
+ if (found) return found;
33
+ }
34
+ }
35
+ }
36
+ return null;
37
+ }
38
+
39
+ childIds.forEach(id => {
40
+ const found = findBlockRecursive(allBlocks, id);
41
+ if (found) resolvedBlocks.push(found);
42
+ });
43
+
44
+ return resolvedBlocks;
45
+ }
46
+
47
+ /**
48
+ * Check if a block is a container (has children or is marked as container)
49
+ */
50
+ export function isContainerBlock(block: Block, blockRegistry: { get: (type: string) => { isContainer?: boolean } | undefined }): boolean {
51
+ const definition = blockRegistry.get(block.type);
52
+ return definition?.isContainer === true || (block.children !== undefined && block.children.length > 0);
53
+ }
54
+
55
+ /**
56
+ * Find a block by ID recursively (including nested blocks)
57
+ */
58
+ export function findBlockById(blocks: Block[], id: string): Block | null {
59
+ for (const block of blocks) {
60
+ if (block.id === id) {
61
+ return block;
62
+ }
63
+ if (block.children && Array.isArray(block.children) && block.children.length > 0) {
64
+ if (typeof block.children[0] === 'object') {
65
+ const found = findBlockById(block.children as Block[], id);
66
+ if (found) return found;
67
+ }
68
+ }
69
+ }
70
+ return null;
71
+ }
72
+
@@ -0,0 +1,137 @@
1
+ /**
2
+ * Plugin Configuration Validation Utilities
3
+ * Validates plugin configuration and custom blocks
4
+ */
5
+
6
+ import { useEffect, useState, useMemo } from 'react';
7
+ import { ClientBlockDefinition } from '../../types/block';
8
+
9
+ /**
10
+ * Routes that require the hero block to be defined
11
+ */
12
+ const ROUTES_REQUIRING_HERO_BLOCK = ['editor', 'new', 'preview'] as const;
13
+
14
+ /**
15
+ * Check if a route requires the hero block
16
+ */
17
+ export function routeRequiresHeroBlock(route: string): boolean {
18
+ return ROUTES_REQUIRING_HERO_BLOCK.includes(route as any);
19
+ }
20
+
21
+ /**
22
+ * Find hero block definition in custom blocks
23
+ */
24
+ export function findHeroBlock(customBlocks: ClientBlockDefinition[]): ClientBlockDefinition | undefined {
25
+ return customBlocks.find(block => block.type === 'hero');
26
+ }
27
+
28
+ /**
29
+ * Hook to validate hero block configuration
30
+ * Only validates for routes that require it, and waits for customBlocks to load
31
+ *
32
+ * @param route - Current route (e.g., 'posts', 'editor', 'new')
33
+ * @param customBlocks - Array of custom block definitions
34
+ * @param propsCustomBlocks - Custom blocks from props (for immediate validation)
35
+ */
36
+ export function useHeroBlockValidation(
37
+ route: string,
38
+ customBlocks: ClientBlockDefinition[],
39
+ propsCustomBlocks?: ClientBlockDefinition[]
40
+ ): void {
41
+ const needsHeroBlock = useMemo(() => routeRequiresHeroBlock(route), [route]);
42
+
43
+ const heroBlockDefinition = useMemo(() => {
44
+ // Only search for hero block if route needs it
45
+ return needsHeroBlock ? findHeroBlock(customBlocks) : undefined;
46
+ }, [customBlocks, needsHeroBlock]);
47
+
48
+ // Track if we've given customBlocks time to load from window global
49
+ // This prevents false errors when customBlocks are loaded asynchronously
50
+ // Only track this if we actually need the hero block
51
+ const [hasCheckedForBlocks, setHasCheckedForBlocks] = useState(false);
52
+
53
+ // Give window global a chance to load before validating
54
+ // Only do this if the route needs the hero block
55
+ useEffect(() => {
56
+ // Early return: Skip all validation logic if route doesn't need hero block
57
+ if (!needsHeroBlock) {
58
+ return;
59
+ }
60
+
61
+ if (typeof window === 'undefined') {
62
+ setHasCheckedForBlocks(true); // Server-side, no need to wait
63
+ return;
64
+ }
65
+
66
+ // If props are provided, we can validate immediately
67
+ if (propsCustomBlocks && propsCustomBlocks.length > 0) {
68
+ setHasCheckedForBlocks(true);
69
+ return;
70
+ }
71
+
72
+ // Check if window global is already available
73
+ if ((window as any).__JHITS_PLUGIN_PROPS__?.['plugin-blog']?.customBlocks) {
74
+ setHasCheckedForBlocks(true);
75
+ return;
76
+ }
77
+
78
+ // Retry mechanism: check multiple times with increasing delays
79
+ // This handles the case where BlogPluginInit's useEffect runs after BlogPlugin mounts
80
+ // BlogPluginInit runs initBlogPlugin in useEffect, which may execute after BlogPlugin's first render
81
+ let attempt = 0;
82
+ const maxAttempts = 6;
83
+ const delays = [50, 100, 200, 300, 500, 1000]; // Progressive delays: total ~2.15s
84
+
85
+ const timers: NodeJS.Timeout[] = [];
86
+
87
+ const checkWithRetry = () => {
88
+ const windowGlobal = (window as any).__JHITS_PLUGIN_PROPS__?.['plugin-blog']?.customBlocks;
89
+ if (windowGlobal && windowGlobal.length > 0) {
90
+ // Found it! Mark as checked
91
+ setHasCheckedForBlocks(true);
92
+ return;
93
+ }
94
+
95
+ if (attempt < maxAttempts) {
96
+ const timer = setTimeout(() => {
97
+ attempt++;
98
+ checkWithRetry();
99
+ }, delays[attempt]);
100
+ timers.push(timer);
101
+ } else {
102
+ // After all retries, mark as checked (even if not found)
103
+ // This prevents infinite waiting and allows validation to proceed
104
+ setHasCheckedForBlocks(true);
105
+ }
106
+ };
107
+
108
+ // Start checking
109
+ checkWithRetry();
110
+
111
+ // Cleanup all timers
112
+ return () => {
113
+ timers.forEach(timer => clearTimeout(timer));
114
+ };
115
+ }, [propsCustomBlocks, needsHeroBlock]);
116
+
117
+ // Validate that Hero block is required (only for editor routes, and only after we've checked for blocks)
118
+ useEffect(() => {
119
+ // Early return if route doesn't need hero block - no validation needed
120
+ if (!needsHeroBlock) {
121
+ return;
122
+ }
123
+
124
+ // Only validate if:
125
+ // 1. We're in a route that needs the hero block (already checked above)
126
+ // 2. We've given customBlocks time to load (hasCheckedForBlocks is true)
127
+ // 3. The hero block is still not found
128
+ if (hasCheckedForBlocks && !heroBlockDefinition) {
129
+ console.error(
130
+ '[BlogPlugin] Hero block is REQUIRED but not found in customBlocks. ' +
131
+ 'Please define a block with type: "hero" in your blog config. ' +
132
+ `Current route: "${route}"`
133
+ );
134
+ }
135
+ }, [heroBlockDefinition, needsHeroBlock, hasCheckedForBlocks, route]);
136
+ }
137
+
@@ -0,0 +1,8 @@
1
+ /**
2
+ * Utility exports
3
+ */
4
+
5
+ export * from './slugify';
6
+ export * from './blockHelpers';
7
+ export * from './configValidation';
8
+
@@ -0,0 +1,79 @@
1
+ /**
2
+ * Slug Utilities
3
+ * Functions for generating and validating URL slugs
4
+ */
5
+
6
+ /**
7
+ * Convert a string to a URL-friendly slug
8
+ */
9
+ export function slugify(text: string): string {
10
+ return text
11
+ .toString()
12
+ .toLowerCase()
13
+ .trim()
14
+ .replace(/\s+/g, '-') // Replace spaces with hyphens
15
+ .replace(/[^\w\-]+/g, '') // Remove all non-word chars
16
+ .replace(/\-\-+/g, '-') // Replace multiple hyphens with single hyphen
17
+ .replace(/^-+/, '') // Trim hyphens from start
18
+ .replace(/-+$/, ''); // Trim hyphens from end
19
+ }
20
+
21
+ /**
22
+ * Generate a slug from a title
23
+ * Automatically handles edge cases and ensures uniqueness
24
+ */
25
+ export function generateSlugFromTitle(title: string, existingSlugs: string[] = []): string {
26
+ let baseSlug = slugify(title);
27
+
28
+ // If slug is empty after processing, use a fallback
29
+ if (!baseSlug) {
30
+ baseSlug = 'untitled-post';
31
+ }
32
+
33
+ // Check for collisions and append number if needed
34
+ let finalSlug = baseSlug;
35
+ let counter = 1;
36
+
37
+ while (existingSlugs.includes(finalSlug)) {
38
+ finalSlug = `${baseSlug}-${counter}`;
39
+ counter++;
40
+ }
41
+
42
+ return finalSlug;
43
+ }
44
+
45
+ /**
46
+ * Validate a slug format
47
+ */
48
+ export function isValidSlug(slug: string): boolean {
49
+ // Slug should be lowercase, alphanumeric with hyphens
50
+ const slugRegex = /^[a-z0-9]+(?:-[a-z0-9]+)*$/;
51
+ return slugRegex.test(slug) && slug.length > 0 && slug.length <= 200;
52
+ }
53
+
54
+ /**
55
+ * Check if a slug collides with existing slugs
56
+ */
57
+ export function checkSlugCollision(slug: string, existingSlugs: string[], excludeId?: string): {
58
+ isCollision: boolean;
59
+ conflictingId?: string;
60
+ } {
61
+ // Normalize the slug for comparison
62
+ const normalizedSlug = slug.toLowerCase().trim();
63
+
64
+ // Check against existing slugs (excluding current post if editing)
65
+ for (const existing of existingSlugs) {
66
+ if (existing.toLowerCase().trim() === normalizedSlug) {
67
+ // If we have an excludeId, we need to check if this is the same post
68
+ // This would require additional context (like a post ID map)
69
+ // For now, we'll return collision if it matches
70
+ return {
71
+ isCollision: true,
72
+ conflictingId: existing,
73
+ };
74
+ }
75
+ }
76
+
77
+ return { isCollision: false };
78
+ }
79
+
@@ -0,0 +1,142 @@
1
+ /**
2
+ * Block Registry
3
+ * Dynamic registry for all block types in the system
4
+ * Multi-Tenant Architecture: Blocks are provided by client applications
5
+ *
6
+ * The registry is a singleton that starts empty and is populated by client apps
7
+ */
8
+
9
+ import {
10
+ BlockTypeDefinition,
11
+ BlockRegistry as IBlockRegistry,
12
+ ClientBlockDefinition
13
+ } from '../types/block';
14
+
15
+ /**
16
+ * Dynamic Block Registry Implementation
17
+ * No default blocks - all blocks must be registered by client applications
18
+ */
19
+ class BlockRegistryImpl implements IBlockRegistry {
20
+ private _types: Map<string, BlockTypeDefinition> = new Map();
21
+
22
+ get types(): Map<string, BlockTypeDefinition> {
23
+ return this._types;
24
+ }
25
+
26
+ /**
27
+ * Register a single block type
28
+ */
29
+ register(definition: BlockTypeDefinition): void {
30
+ // Validate that components are provided
31
+ if (!definition.components || !definition.components.Edit || !definition.components.Preview) {
32
+ throw new Error(
33
+ `Block type "${definition.type}" must provide both Edit and Preview components. ` +
34
+ `Use registerClientBlocks() for client-provided blocks.`
35
+ );
36
+ }
37
+
38
+ if (this._types.has(definition.type)) {
39
+ console.warn(`Block type "${definition.type}" is already registered. Overwriting...`);
40
+ }
41
+
42
+ this._types.set(definition.type, definition);
43
+ }
44
+
45
+ /**
46
+ * Register multiple client blocks at once
47
+ * This is the primary method for client applications to register their blocks
48
+ */
49
+ registerClientBlocks(definitions: ClientBlockDefinition[]): void {
50
+ for (const def of definitions) {
51
+ // Validate required fields
52
+ if (!def.type || !def.name || !def.components) {
53
+ console.error('Invalid block definition:', def);
54
+ throw new Error(
55
+ 'Block definition must have: type, name, and components (with Edit and Preview)'
56
+ );
57
+ }
58
+
59
+ // Validate components
60
+ if (!def.components.Edit || !def.components.Preview) {
61
+ throw new Error(
62
+ `Block "${def.type}" must provide both Edit and Preview components in the components object`
63
+ );
64
+ }
65
+
66
+ // Convert ClientBlockDefinition to BlockTypeDefinition
67
+ const blockDefinition: BlockTypeDefinition = {
68
+ type: def.type,
69
+ name: def.name,
70
+ description: def.description,
71
+ icon: def.icon || def.components.Icon,
72
+ defaultData: def.defaultData,
73
+ validate: def.validate,
74
+ isContainer: def.isContainer,
75
+ allowedChildren: def.allowedChildren,
76
+ category: def.category || 'custom',
77
+ components: def.components,
78
+ };
79
+
80
+ this.register(blockDefinition);
81
+ }
82
+ }
83
+
84
+ /**
85
+ * Get block type definition by type string
86
+ */
87
+ get(type: string): BlockTypeDefinition | undefined {
88
+ return this._types.get(type);
89
+ }
90
+
91
+ /**
92
+ * Get all registered block types
93
+ */
94
+ getAll(): BlockTypeDefinition[] {
95
+ return Array.from(this._types.values());
96
+ }
97
+
98
+ /**
99
+ * Get block types filtered by category
100
+ */
101
+ getByCategory(category: BlockTypeDefinition['category']): BlockTypeDefinition[] {
102
+ return this.getAll().filter(block => block.category === category);
103
+ }
104
+
105
+ /**
106
+ * Check if a block type is registered
107
+ */
108
+ has(type: string): boolean {
109
+ return this._types.has(type);
110
+ }
111
+
112
+ /**
113
+ * Unregister a block type (useful for testing or dynamic loading)
114
+ */
115
+ unregister(type: string): boolean {
116
+ return this._types.delete(type);
117
+ }
118
+
119
+ /**
120
+ * Clear all registered block types
121
+ * Useful for testing or resetting the registry
122
+ */
123
+ clear(): void {
124
+ this._types.clear();
125
+ }
126
+
127
+ /**
128
+ * Get count of registered blocks
129
+ */
130
+ getCount(): number {
131
+ return this._types.size;
132
+ }
133
+ }
134
+
135
+ // Singleton instance - starts empty, populated by client apps
136
+ export const blockRegistry = new BlockRegistryImpl();
137
+
138
+ /**
139
+ * NOTE: No default blocks are registered automatically.
140
+ * Client applications must call registerClientBlocks() to populate the registry.
141
+ * This ensures the editor is a true "shell" without hardcoded blocks.
142
+ */
@@ -0,0 +1,11 @@
1
+ /**
2
+ * Registry exports
3
+ */
4
+
5
+ export { blockRegistry } from './BlockRegistry';
6
+ export type {
7
+ ClientBlockDefinition,
8
+ BlockTypeDefinition,
9
+ BlockRegistry,
10
+ } from '../types/block';
11
+