create-nextblock 0.13.8 → 0.13.10
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.
- package/package.json +1 -1
- package/templates/nextblock-template/app/actions/productGridActions.ts +40 -0
- package/templates/nextblock-template/app/api/cms/ecommerce/product-picker/route.ts +151 -0
- package/templates/nextblock-template/app/cms/CmsClientLayout.tsx +3 -0
- package/templates/nextblock-template/app/cms/blocks/components/BlockEditorArea.tsx +10 -1
- package/templates/nextblock-template/app/cms/blocks/components/BlockTypeSelector.tsx +17 -5
- package/templates/nextblock-template/app/cms/blocks/components/ColumnEditor.tsx +5 -1
- package/templates/nextblock-template/app/cms/blocks/components/EditableBlock.tsx +55 -24
- package/templates/nextblock-template/app/cms/blocks/components/MultiEntityPicker.tsx +263 -0
- package/templates/nextblock-template/app/cms/blocks/editors/ProductGridBlockEditor.tsx +375 -18
- package/templates/nextblock-template/app/cms/components/EcommerceActiveContext.tsx +27 -0
- package/templates/nextblock-template/components/blocks/ProductGridClient.tsx +114 -0
- package/templates/nextblock-template/lib/blocks/ProductGridBlock.tsx +78 -139
- package/templates/nextblock-template/lib/blocks/blockRegistry.ts +24 -4
- package/templates/nextblock-template/lib/blocks/blockTypes.ts +19 -0
- package/templates/nextblock-template/lib/blocks/ecommerce-block-schemas.ts +61 -2
- package/templates/nextblock-template/lib/blocks/product-grid-data.ts +210 -0
- package/templates/nextblock-template/next-env.d.ts +1 -1
- package/templates/nextblock-template/package.json +1 -1
- package/templates/nextblock-template/tsconfig.tsbuildinfo +1 -1
package/package.json
CHANGED
|
@@ -0,0 +1,40 @@
|
|
|
1
|
+
'use server';
|
|
2
|
+
|
|
3
|
+
import {
|
|
4
|
+
loadProductGridPage,
|
|
5
|
+
type ProductGridQuery,
|
|
6
|
+
} from '../../lib/blocks/product-grid-data';
|
|
7
|
+
import {
|
|
8
|
+
PRODUCT_GRID_MAX_LIMIT,
|
|
9
|
+
PRODUCT_GRID_DEFAULT_PAGE_SIZE,
|
|
10
|
+
} from '../../lib/blocks/ecommerce-block-schemas';
|
|
11
|
+
import type { Product } from '@nextblock-cms/ecommerce/types';
|
|
12
|
+
|
|
13
|
+
export interface ProductGridPageResult {
|
|
14
|
+
products: Product[];
|
|
15
|
+
totalCount: number;
|
|
16
|
+
error?: string;
|
|
17
|
+
}
|
|
18
|
+
|
|
19
|
+
/**
|
|
20
|
+
* Pagination for the Product Grid block. Only ever returns published products
|
|
21
|
+
* (`getProducts` defaults to status `active`), so this is safe to call from the
|
|
22
|
+
* storefront. The page size is clamped here because the argument arrives from
|
|
23
|
+
* the client — the unlimited path stays server-render only.
|
|
24
|
+
*/
|
|
25
|
+
export async function fetchProductGridPage(
|
|
26
|
+
query: ProductGridQuery
|
|
27
|
+
): Promise<ProductGridPageResult> {
|
|
28
|
+
try {
|
|
29
|
+
const limit = Math.min(
|
|
30
|
+
Math.max(1, Math.floor(query.limit) || PRODUCT_GRID_DEFAULT_PAGE_SIZE),
|
|
31
|
+
PRODUCT_GRID_MAX_LIMIT
|
|
32
|
+
);
|
|
33
|
+
|
|
34
|
+
const { products, totalCount } = await loadProductGridPage({ ...query, limit });
|
|
35
|
+
return { products, totalCount };
|
|
36
|
+
} catch (error) {
|
|
37
|
+
console.error('[Product Grid] Failed to load page:', error);
|
|
38
|
+
return { products: [], totalCount: 0, error: 'Failed to load products.' };
|
|
39
|
+
}
|
|
40
|
+
}
|
|
@@ -0,0 +1,151 @@
|
|
|
1
|
+
import { NextResponse } from 'next/server';
|
|
2
|
+
import {
|
|
3
|
+
createClient,
|
|
4
|
+
getServiceRoleSupabaseClient,
|
|
5
|
+
verifyPackageOnline,
|
|
6
|
+
} from '@nextblock-cms/db/server';
|
|
7
|
+
|
|
8
|
+
export const dynamic = 'force-dynamic';
|
|
9
|
+
|
|
10
|
+
/** How many products a single search returns before the UI asks for a narrower query. */
|
|
11
|
+
const PRODUCT_PAGE_SIZE = 50;
|
|
12
|
+
/** Guard against an unbounded `ids` list when hydrating labels for an existing selection. */
|
|
13
|
+
const MAX_HYDRATED_IDS = 100;
|
|
14
|
+
|
|
15
|
+
export interface ProductPickerCategory {
|
|
16
|
+
id: string;
|
|
17
|
+
name: string;
|
|
18
|
+
slug: string;
|
|
19
|
+
}
|
|
20
|
+
|
|
21
|
+
export interface ProductPickerProduct {
|
|
22
|
+
id: string;
|
|
23
|
+
title: string;
|
|
24
|
+
slug: string | null;
|
|
25
|
+
sku: string | null;
|
|
26
|
+
status: string | null;
|
|
27
|
+
languageCode: string | null;
|
|
28
|
+
translationGroupId: string | null;
|
|
29
|
+
}
|
|
30
|
+
|
|
31
|
+
/**
|
|
32
|
+
* PostgREST parses `,`, `.`, `(` and `)` inside an `or(...)` filter, so anything
|
|
33
|
+
* the author types has to be stripped before it is interpolated into one.
|
|
34
|
+
*/
|
|
35
|
+
function sanitizeSearchTerm(term: string): string {
|
|
36
|
+
return term.replace(/[,().*%\\]/g, ' ').trim().slice(0, 80);
|
|
37
|
+
}
|
|
38
|
+
|
|
39
|
+
/**
|
|
40
|
+
* Options for the Product Grid block pickers: every category plus a page of
|
|
41
|
+
* products (optionally filtered by `search`). `ids` hydrates labels for an
|
|
42
|
+
* existing selection whose products fall outside the current page.
|
|
43
|
+
*/
|
|
44
|
+
export async function GET(request: Request) {
|
|
45
|
+
try {
|
|
46
|
+
const supabase = createClient();
|
|
47
|
+
const {
|
|
48
|
+
data: { user },
|
|
49
|
+
error: authError,
|
|
50
|
+
} = await supabase.auth.getUser();
|
|
51
|
+
|
|
52
|
+
if (authError || !user) {
|
|
53
|
+
return NextResponse.json({ error: 'Unauthorized' }, { status: 401 });
|
|
54
|
+
}
|
|
55
|
+
|
|
56
|
+
const { data: profile } = await supabase
|
|
57
|
+
.from('profiles')
|
|
58
|
+
.select('role')
|
|
59
|
+
.eq('id', user.id)
|
|
60
|
+
.single();
|
|
61
|
+
|
|
62
|
+
if (!profile || !['ADMIN', 'WRITER'].includes(profile.role)) {
|
|
63
|
+
return NextResponse.json(
|
|
64
|
+
{ error: 'Forbidden: Insufficient permissions' },
|
|
65
|
+
{ status: 403 }
|
|
66
|
+
);
|
|
67
|
+
}
|
|
68
|
+
|
|
69
|
+
// Fail closed: without the ecommerce package there is no product catalog to
|
|
70
|
+
// browse, and the blocks that use this route are hidden from the picker.
|
|
71
|
+
if (!(await verifyPackageOnline('ecommerce'))) {
|
|
72
|
+
return NextResponse.json(
|
|
73
|
+
{ error: 'The ecommerce package is not active.' },
|
|
74
|
+
{ status: 403 }
|
|
75
|
+
);
|
|
76
|
+
}
|
|
77
|
+
|
|
78
|
+
const url = new URL(request.url);
|
|
79
|
+
const search = sanitizeSearchTerm(url.searchParams.get('search') ?? '');
|
|
80
|
+
const ids = (url.searchParams.get('ids') ?? '')
|
|
81
|
+
.split(',')
|
|
82
|
+
.map((id) => id.trim())
|
|
83
|
+
.filter(Boolean)
|
|
84
|
+
.slice(0, MAX_HYDRATED_IDS);
|
|
85
|
+
|
|
86
|
+
// Reading the catalog is admin work behind the role check above.
|
|
87
|
+
const admin = getServiceRoleSupabaseClient();
|
|
88
|
+
|
|
89
|
+
const productColumns =
|
|
90
|
+
'id, title, slug, sku, status, translation_group_id, languages(code)';
|
|
91
|
+
|
|
92
|
+
let productsQuery = admin
|
|
93
|
+
.from('products')
|
|
94
|
+
.select(productColumns)
|
|
95
|
+
.order('created_at', { ascending: false })
|
|
96
|
+
// Fetch one extra row so the UI can tell the author the list was truncated.
|
|
97
|
+
.limit(PRODUCT_PAGE_SIZE + 1);
|
|
98
|
+
|
|
99
|
+
if (search) {
|
|
100
|
+
productsQuery = productsQuery.or(`title.ilike.%${search}%,sku.ilike.%${search}%`);
|
|
101
|
+
}
|
|
102
|
+
|
|
103
|
+
const [categoriesResult, productsResult, selectedResult] = await Promise.all([
|
|
104
|
+
admin.from('categories').select('id, name, slug').order('name', { ascending: true }),
|
|
105
|
+
productsQuery,
|
|
106
|
+
ids.length > 0
|
|
107
|
+
? admin.from('products').select(productColumns).in('id', ids)
|
|
108
|
+
: Promise.resolve({ data: [], error: null }),
|
|
109
|
+
]);
|
|
110
|
+
|
|
111
|
+
if (categoriesResult.error) throw categoriesResult.error;
|
|
112
|
+
if (productsResult.error) throw productsResult.error;
|
|
113
|
+
if (selectedResult.error) throw selectedResult.error;
|
|
114
|
+
|
|
115
|
+
const toPickerProduct = (row: any): ProductPickerProduct => ({
|
|
116
|
+
id: row.id,
|
|
117
|
+
title: row.title,
|
|
118
|
+
slug: row.slug ?? null,
|
|
119
|
+
sku: row.sku ?? null,
|
|
120
|
+
status: row.status ?? null,
|
|
121
|
+
languageCode: row.languages?.code ?? null,
|
|
122
|
+
translationGroupId: row.translation_group_id ?? null,
|
|
123
|
+
});
|
|
124
|
+
|
|
125
|
+
const productRows = (productsResult.data ?? []) as any[];
|
|
126
|
+
const hasMore = productRows.length > PRODUCT_PAGE_SIZE;
|
|
127
|
+
const products = productRows.slice(0, PRODUCT_PAGE_SIZE).map(toPickerProduct);
|
|
128
|
+
|
|
129
|
+
// Merge the hydrated selection in so already-chosen products always render
|
|
130
|
+
// with a real label, even when a search hides them.
|
|
131
|
+
const byId = new Map(products.map((product) => [product.id, product]));
|
|
132
|
+
for (const row of (selectedResult.data ?? []) as any[]) {
|
|
133
|
+
if (!byId.has(row.id)) byId.set(row.id, toPickerProduct(row));
|
|
134
|
+
}
|
|
135
|
+
|
|
136
|
+
return NextResponse.json(
|
|
137
|
+
{
|
|
138
|
+
categories: (categoriesResult.data ?? []) as ProductPickerCategory[],
|
|
139
|
+
products: Array.from(byId.values()),
|
|
140
|
+
hasMore,
|
|
141
|
+
},
|
|
142
|
+
{ status: 200 }
|
|
143
|
+
);
|
|
144
|
+
} catch (error) {
|
|
145
|
+
console.error('[Product Picker API] Unexpected error:', error);
|
|
146
|
+
return NextResponse.json(
|
|
147
|
+
{ error: 'Failed to load product picker options.' },
|
|
148
|
+
{ status: 500 }
|
|
149
|
+
);
|
|
150
|
+
}
|
|
151
|
+
}
|
|
@@ -22,6 +22,7 @@ import { FeedbackModal } from "./components/FeedbackModal";
|
|
|
22
22
|
import { CortexGlobalAgentChat } from "./components/CortexGlobalAgentChat";
|
|
23
23
|
import { CortexAiPageContextProvider } from "./components/CortexAiPageContext";
|
|
24
24
|
import { CortexAiActiveProvider } from "./components/CortexAiActiveContext";
|
|
25
|
+
import { EcommerceActiveProvider } from "./components/EcommerceActiveContext";
|
|
25
26
|
import { useAppBranding } from "../../components/AppShell";
|
|
26
27
|
import { resolveMediaUrl } from "../../lib/media/resolveMediaUrl";
|
|
27
28
|
|
|
@@ -257,6 +258,7 @@ export default function CmsClientLayout({
|
|
|
257
258
|
return (
|
|
258
259
|
<CortexAiPageContextProvider>
|
|
259
260
|
<CortexAiActiveProvider isActive={isCortexAiActive}>
|
|
261
|
+
<EcommerceActiveProvider isActive={isEcommerceActive}>
|
|
260
262
|
<div className="relative flex h-full min-h-0 w-full overflow-hidden bg-slate-50 dark:bg-slate-950 md:flex-row">
|
|
261
263
|
<div className="fixed bottom-4 right-4 z-[60] md:hidden">
|
|
262
264
|
<Button
|
|
@@ -516,6 +518,7 @@ export default function CmsClientLayout({
|
|
|
516
518
|
)}
|
|
517
519
|
{isAdmin && isCortexAiActive && <CortexGlobalAgentChat />}
|
|
518
520
|
</div>
|
|
521
|
+
</EcommerceActiveProvider>
|
|
519
522
|
</CortexAiActiveProvider>
|
|
520
523
|
</CortexAiPageContextProvider>
|
|
521
524
|
)
|
|
@@ -9,7 +9,7 @@ import type { Database, Json } from "@nextblock-cms/db";
|
|
|
9
9
|
import { BlockType } from '../../../../lib/blocks/blockRegistry';
|
|
10
10
|
|
|
11
11
|
type Block = Database["public"]["Tables"]["blocks"]["Row"];
|
|
12
|
-
import { getBlockDefinition, SectionBlockContent } from '../../../../lib/blocks/blockRegistry';
|
|
12
|
+
import { blockHasEditableContent, getBlockDefinition, SectionBlockContent } from '../../../../lib/blocks/blockRegistry';
|
|
13
13
|
import { Button } from "@nextblock-cms/ui";
|
|
14
14
|
import { PlusCircle } from "lucide-react";
|
|
15
15
|
import {
|
|
@@ -113,6 +113,8 @@ export default function BlockEditorArea({ parentId, parentType, initialBlocks, l
|
|
|
113
113
|
const [isBlockSelectorOpen, setIsBlockSelectorOpen] = useState(false);
|
|
114
114
|
const [activeBlock, setActiveBlock] = useState<Block | null>(null);
|
|
115
115
|
const [insertionIndex, setInsertionIndex] = useState<number | null>(null);
|
|
116
|
+
// Id of the block that was just added, so its editor can open on its own.
|
|
117
|
+
const [autoEditBlockId, setAutoEditBlockId] = useState<number | null>(null);
|
|
116
118
|
const [editingNestedBlockInfo, setEditingNestedBlockInfo] = useState<EditingNestedBlockInfo | null>(null);
|
|
117
119
|
const [NestedBlockEditorComponent, setNestedBlockEditorComponent] = useState<ComponentType<any> | null>(null);
|
|
118
120
|
const [tempNestedBlockContent, setTempNestedBlockContent] = useState<Json | null>(null);
|
|
@@ -377,6 +379,11 @@ export default function BlockEditorArea({ parentId, parentType, initialBlocks, l
|
|
|
377
379
|
|
|
378
380
|
setBlocks(finalBlocks);
|
|
379
381
|
lastSavedBlocks.current = finalBlocks;
|
|
382
|
+
// Context-driven blocks (cart, checkout, …) have nothing to configure,
|
|
383
|
+
// so only jump into the editor when there is something to edit.
|
|
384
|
+
if (blockHasEditableContent(blockType)) {
|
|
385
|
+
setAutoEditBlockId(newBlock.id);
|
|
386
|
+
}
|
|
380
387
|
router.refresh();
|
|
381
388
|
} else {
|
|
382
389
|
alert(`Error adding block: ${createResult?.error}`);
|
|
@@ -506,6 +513,8 @@ export default function BlockEditorArea({ parentId, parentType, initialBlocks, l
|
|
|
506
513
|
</div>
|
|
507
514
|
<SortableBlockItem
|
|
508
515
|
block={block}
|
|
516
|
+
autoOpenEditor={block.id === autoEditBlockId}
|
|
517
|
+
onAutoOpenHandled={() => setAutoEditBlockId(null)}
|
|
509
518
|
onContentChange={handleContentChange}
|
|
510
519
|
onDelete={async (blockIdToDelete) => {
|
|
511
520
|
startTransition(async () => {
|
|
@@ -16,6 +16,8 @@ import {
|
|
|
16
16
|
} from "@nextblock-cms/ui";
|
|
17
17
|
import { Search, X, Package } from 'lucide-react';
|
|
18
18
|
import { blockRegistry, BlockType } from '../../../../lib/blocks/blockRegistry';
|
|
19
|
+
import { isEcommerceBlockType } from '../../../../lib/blocks/blockTypes';
|
|
20
|
+
import { useEcommerceActive } from '../../components/EcommerceActiveContext';
|
|
19
21
|
import BlockTypeCard from './BlockTypeCard';
|
|
20
22
|
|
|
21
23
|
interface BlockTypeSelectorProps {
|
|
@@ -25,7 +27,8 @@ interface BlockTypeSelectorProps {
|
|
|
25
27
|
allowedBlockTypes?: BlockType[];
|
|
26
28
|
}
|
|
27
29
|
|
|
28
|
-
const
|
|
30
|
+
const ECOMMERCE_CATEGORY = "E-commerce";
|
|
31
|
+
const CATEGORIES = ["All", "Layout", "Content", "Media", "Interactive", ECOMMERCE_CATEGORY, "Custom"];
|
|
29
32
|
|
|
30
33
|
const getBlockCategory = (type: string, isCustomSlug?: boolean): string => {
|
|
31
34
|
if (isCustomSlug) {
|
|
@@ -50,7 +53,7 @@ const getBlockCategory = (type: string, isCustomSlug?: boolean): string => {
|
|
|
50
53
|
case 'cart':
|
|
51
54
|
case 'checkout':
|
|
52
55
|
case 'product_details':
|
|
53
|
-
return
|
|
56
|
+
return ECOMMERCE_CATEGORY;
|
|
54
57
|
default:
|
|
55
58
|
return 'Content';
|
|
56
59
|
}
|
|
@@ -65,6 +68,9 @@ const BlockTypeSelector: React.FC<BlockTypeSelectorProps> = ({
|
|
|
65
68
|
const [searchQuery, setSearchQuery] = React.useState('');
|
|
66
69
|
const [activeCategory, setActiveCategory] = React.useState('All');
|
|
67
70
|
const [customDefs, setCustomDefs] = React.useState<any[]>([]);
|
|
71
|
+
// Store blocks are only offered when the ecommerce package is activated. The
|
|
72
|
+
// context defaults to false outside the CMS layout, so this fails closed.
|
|
73
|
+
const isEcommerceActive = useEcommerceActive();
|
|
68
74
|
|
|
69
75
|
// Reset state and fetch custom blocks when modal is opened
|
|
70
76
|
React.useEffect(() => {
|
|
@@ -93,10 +99,16 @@ const BlockTypeSelector: React.FC<BlockTypeSelectorProps> = ({
|
|
|
93
99
|
onOpenChange(false);
|
|
94
100
|
};
|
|
95
101
|
|
|
102
|
+
const visibleCategories = React.useMemo(
|
|
103
|
+
() => CATEGORIES.filter((category) => category !== ECOMMERCE_CATEGORY || isEcommerceActive),
|
|
104
|
+
[isEcommerceActive]
|
|
105
|
+
);
|
|
106
|
+
|
|
96
107
|
const blockDefs = React.useMemo(() => {
|
|
97
108
|
const coreDefs = Object.values(blockRegistry).filter(
|
|
98
109
|
(blockDef) =>
|
|
99
|
-
!allowedBlockTypes || allowedBlockTypes.includes(blockDef.type)
|
|
110
|
+
(!allowedBlockTypes || allowedBlockTypes.includes(blockDef.type)) &&
|
|
111
|
+
(isEcommerceActive || !isEcommerceBlockType(blockDef.type))
|
|
100
112
|
);
|
|
101
113
|
|
|
102
114
|
const mappedCustomDefs = customDefs.map((def) => ({
|
|
@@ -114,7 +126,7 @@ const BlockTypeSelector: React.FC<BlockTypeSelectorProps> = ({
|
|
|
114
126
|
}));
|
|
115
127
|
|
|
116
128
|
return [...coreDefs, ...mappedCustomDefs];
|
|
117
|
-
}, [allowedBlockTypes, customDefs]);
|
|
129
|
+
}, [allowedBlockTypes, customDefs, isEcommerceActive]);
|
|
118
130
|
|
|
119
131
|
// Memoized filter and search results to prevent re-calculations during key strokes
|
|
120
132
|
const filteredBlockDefs = React.useMemo(() => {
|
|
@@ -174,7 +186,7 @@ const BlockTypeSelector: React.FC<BlockTypeSelectorProps> = ({
|
|
|
174
186
|
|
|
175
187
|
{/* Category Filter Tabs */}
|
|
176
188
|
<div className="flex flex-wrap gap-1.5 pb-3 border-b border-border">
|
|
177
|
-
{
|
|
189
|
+
{visibleCategories.map((category) => (
|
|
178
190
|
<button
|
|
179
191
|
key={category}
|
|
180
192
|
type="button"
|
|
@@ -5,7 +5,7 @@ import { cn } from '@nextblock-cms/utils';
|
|
|
5
5
|
import { Button } from '@nextblock-cms/ui';
|
|
6
6
|
import { PlusCircle, Trash2, Edit2, GripVertical, Image as ImageIcon } from "lucide-react";
|
|
7
7
|
import { SectionBlockContent } from '../../../../lib/blocks/blockRegistry';
|
|
8
|
-
import { availableBlockTypes, getBlockDefinition, getInitialContent, BlockType } from '../../../../lib/blocks/blockRegistry';
|
|
8
|
+
import { availableBlockTypes, blockHasEditableContent, getBlockDefinition, getInitialContent, BlockType } from '../../../../lib/blocks/blockRegistry';
|
|
9
9
|
import { useDroppable } from "@dnd-kit/core";
|
|
10
10
|
import { useSortable } from "@dnd-kit/sortable";
|
|
11
11
|
import { CSS } from "@dnd-kit/utilities";
|
|
@@ -415,6 +415,10 @@ export default function ColumnEditor({ columnIndex, blocks, onBlocksChange, bloc
|
|
|
415
415
|
temp_id: `temp-${Date.now()}-${Math.random()}`
|
|
416
416
|
};
|
|
417
417
|
onBlocksChange([...blocks, newBlock]);
|
|
418
|
+
// Open the new block's editor straight away, matching the top-level editor.
|
|
419
|
+
if (blockHasEditableContent(selectedBlockType)) {
|
|
420
|
+
handleStartEdit(newBlock, blocks.length);
|
|
421
|
+
}
|
|
418
422
|
};
|
|
419
423
|
|
|
420
424
|
const handleSelectBlockType = (selectedBlockType: BlockType) => {
|
|
@@ -1,14 +1,14 @@
|
|
|
1
1
|
// app/cms/blocks/components/EditableBlock.tsx
|
|
2
2
|
"use client";
|
|
3
3
|
|
|
4
|
-
import React, { useState, Suspense, useMemo, lazy, LazyExoticComponent, ComponentType } from 'react';
|
|
4
|
+
import React, { useState, useEffect, useRef, Suspense, useMemo, lazy, LazyExoticComponent, ComponentType } from 'react';
|
|
5
5
|
import type { Database } from "@nextblock-cms/db";
|
|
6
6
|
import PostsGridBlockEditor from '../editors/PostsGridBlockEditor';
|
|
7
7
|
|
|
8
8
|
type Block = Database['public']['Tables']['blocks']['Row'];
|
|
9
9
|
import { Button, Card, CardContent, Avatar, AvatarImage, AvatarFallback } from "@nextblock-cms/ui";
|
|
10
10
|
import { GripVertical, Edit2, Image as ImageIcon, MessageSquareQuote } from "lucide-react";
|
|
11
|
-
import { getBlockDefinition, blockRegistry, BlockType } from '../../../../lib/blocks/blockRegistry';
|
|
11
|
+
import { blockHasEditableContent, getBlockDefinition, blockRegistry, BlockType } from '../../../../lib/blocks/blockRegistry';
|
|
12
12
|
import { BlockEditorModal } from './BlockEditorModal';
|
|
13
13
|
import { DeleteBlockButtonClient } from './DeleteBlockButtonClient';
|
|
14
14
|
import { cn } from '@nextblock-cms/utils';
|
|
@@ -23,6 +23,10 @@ export interface EditableBlockProps {
|
|
|
23
23
|
dragHandleProps?: Record<string, any>;
|
|
24
24
|
onEditNestedBlock?: (parentBlockId: string, columnIndex: number, blockIndexInColumn: number) => void;
|
|
25
25
|
className?: string;
|
|
26
|
+
/** Open this block's editor as soon as it mounts — set for a just-added block. */
|
|
27
|
+
autoOpenEditor?: boolean;
|
|
28
|
+
/** Called once the auto-open has fired, so the parent can clear the flag. */
|
|
29
|
+
onAutoOpenHandled?: () => void;
|
|
26
30
|
}
|
|
27
31
|
|
|
28
32
|
export default function EditableBlock({
|
|
@@ -32,12 +36,15 @@ export default function EditableBlock({
|
|
|
32
36
|
dragHandleProps,
|
|
33
37
|
onEditNestedBlock,
|
|
34
38
|
className,
|
|
39
|
+
autoOpenEditor,
|
|
40
|
+
onAutoOpenHandled,
|
|
35
41
|
}: EditableBlockProps) {
|
|
36
42
|
void onEditNestedBlock;
|
|
37
43
|
// Move all hooks to the top before any conditional returns
|
|
38
44
|
const [isConfigPanelOpen, setIsConfigPanelOpen] = useState(false);
|
|
39
45
|
const [editingBlock, setEditingBlock] = useState<Block | null>(null);
|
|
40
46
|
const [LazyEditor, setLazyEditor] = useState<LazyExoticComponent<ComponentType<any>> | ComponentType<any> | null>(null);
|
|
47
|
+
const autoOpenedRef = useRef<number | null>(null);
|
|
41
48
|
|
|
42
49
|
const SectionEditor = useMemo(() => {
|
|
43
50
|
if (block?.block_type === 'section') {
|
|
@@ -49,15 +56,12 @@ export default function EditableBlock({
|
|
|
49
56
|
return null;
|
|
50
57
|
}, [block?.block_type]);
|
|
51
58
|
|
|
52
|
-
// Add a guard for undefined block prop after hooks
|
|
53
|
-
if (!block) {
|
|
54
|
-
// Or some other placeholder/error display
|
|
55
|
-
return <div className="p-4 border rounded-lg bg-card shadow text-red-500">Error: Block data is missing in EditableBlock.</div>;
|
|
56
|
-
}
|
|
57
|
-
|
|
58
|
-
|
|
59
|
-
|
|
60
59
|
const handleEditClick = () => {
|
|
60
|
+
// cart / checkout / product_details are context-driven: empty schema, and the
|
|
61
|
+
// editor file their registry entry names does not exist. Opening one throws.
|
|
62
|
+
if (!blockHasEditableContent(block.block_type)) {
|
|
63
|
+
return;
|
|
64
|
+
}
|
|
61
65
|
if (block.block_type === 'section') {
|
|
62
66
|
setIsConfigPanelOpen(prev => !prev);
|
|
63
67
|
} else {
|
|
@@ -87,6 +91,22 @@ export default function EditableBlock({
|
|
|
87
91
|
}
|
|
88
92
|
};
|
|
89
93
|
|
|
94
|
+
// A block the author just added opens straight into its editor — adding a
|
|
95
|
+
// heading is always followed by wanting to type one. The ref keeps it to once
|
|
96
|
+
// per block, so closing the editor (or a router refresh) does not reopen it.
|
|
97
|
+
useEffect(() => {
|
|
98
|
+
if (!autoOpenEditor || !block || autoOpenedRef.current === block.id) return;
|
|
99
|
+
autoOpenedRef.current = block.id;
|
|
100
|
+
handleEditClick();
|
|
101
|
+
onAutoOpenHandled?.();
|
|
102
|
+
}, [autoOpenEditor, block, handleEditClick, onAutoOpenHandled]);
|
|
103
|
+
|
|
104
|
+
// Add a guard for undefined block prop after hooks
|
|
105
|
+
if (!block) {
|
|
106
|
+
// Or some other placeholder/error display
|
|
107
|
+
return <div className="p-4 border rounded-lg bg-card shadow text-red-500">Error: Block data is missing in EditableBlock.</div>;
|
|
108
|
+
}
|
|
109
|
+
|
|
90
110
|
const handleCardClick = (e: React.MouseEvent<HTMLDivElement>) => {
|
|
91
111
|
// If the element that was clicked, or any of its parents up to the card, is a button,
|
|
92
112
|
// then we should ignore the click on the card. This lets the button's own onClick handle the event.
|
|
@@ -279,14 +299,22 @@ export default function EditableBlock({
|
|
|
279
299
|
default: {
|
|
280
300
|
const blockDefinition = getBlockDefinition(currentBlockType as BlockType);
|
|
281
301
|
const blockLabel = blockDefinition?.label || currentBlockType;
|
|
302
|
+
const hasEditableContent = blockHasEditableContent(currentBlockType);
|
|
282
303
|
const placeholder = (
|
|
283
304
|
<div
|
|
284
|
-
className=
|
|
305
|
+
className={cn(
|
|
306
|
+
"py-4 flex flex-col items-center justify-center space-y-2 min-h-[80px] border border-dashed rounded-md bg-muted/20",
|
|
307
|
+
hasEditableContent && "cursor-pointer hover:border-primary"
|
|
308
|
+
)}
|
|
285
309
|
onClick={handleCardClick}
|
|
286
310
|
>
|
|
287
311
|
<div className="text-center">
|
|
288
312
|
<p className="text-sm font-medium text-muted-foreground">{blockLabel}</p>
|
|
289
|
-
<p className="text-xs text-muted-foreground">
|
|
313
|
+
<p className="text-xs text-muted-foreground">
|
|
314
|
+
{hasEditableContent
|
|
315
|
+
? 'Click edit to modify content'
|
|
316
|
+
: 'Renders from the current page context — nothing to configure'}
|
|
317
|
+
</p>
|
|
290
318
|
</div>
|
|
291
319
|
</div>
|
|
292
320
|
);
|
|
@@ -304,13 +332,14 @@ export default function EditableBlock({
|
|
|
304
332
|
|
|
305
333
|
const isSection = block?.block_type === 'section';
|
|
306
334
|
const blockDefinition = getBlockDefinition(block.block_type as BlockType);
|
|
335
|
+
const isEditable = blockHasEditableContent(block.block_type);
|
|
307
336
|
|
|
308
337
|
return (
|
|
309
338
|
<div
|
|
310
339
|
onClick={handleCardClick}
|
|
311
340
|
className={cn(
|
|
312
341
|
"p-4 border rounded-lg bg-card shadow",
|
|
313
|
-
!isSection && "cursor-pointer hover:border-primary transition-colors",
|
|
342
|
+
!isSection && isEditable && "cursor-pointer hover:border-primary transition-colors",
|
|
314
343
|
className
|
|
315
344
|
)}
|
|
316
345
|
>
|
|
@@ -322,17 +351,19 @@ export default function EditableBlock({
|
|
|
322
351
|
<h4 className="font-semibold p-0 m-0 mb-1">{blockDefinition?.label || block.block_type}</h4>
|
|
323
352
|
</div>
|
|
324
353
|
<div className="flex items-center gap-1">
|
|
325
|
-
|
|
326
|
-
|
|
327
|
-
|
|
328
|
-
|
|
329
|
-
e
|
|
330
|
-
|
|
331
|
-
|
|
332
|
-
|
|
333
|
-
|
|
334
|
-
|
|
335
|
-
|
|
354
|
+
{isEditable && (
|
|
355
|
+
<Button
|
|
356
|
+
variant="ghost"
|
|
357
|
+
size="icon"
|
|
358
|
+
onClick={(e) => {
|
|
359
|
+
e.stopPropagation();
|
|
360
|
+
handleEditClick();
|
|
361
|
+
}}
|
|
362
|
+
aria-label={isSection ? "Toggle Section Config" : "Edit block"}
|
|
363
|
+
>
|
|
364
|
+
<Edit2 className="h-4 w-4 text-muted-foreground" />
|
|
365
|
+
</Button>
|
|
366
|
+
)}
|
|
336
367
|
<DeleteBlockButtonClient
|
|
337
368
|
blockId={block.id}
|
|
338
369
|
blockTitle={blockDefinition?.label || block.block_type}
|