create-nextblock 0.13.8 → 0.13.9

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.
@@ -1,32 +1,238 @@
1
1
  "use client";
2
2
 
3
3
  import React from 'react';
4
- import { Label, Input } from "@nextblock-cms/ui";
4
+ import { AlertTriangle, Clock, Folder, ListChecks } from 'lucide-react';
5
+ import { Label, Input, Checkbox } from "@nextblock-cms/ui";
6
+ import { cn } from "@nextblock-cms/utils";
5
7
  import { BlockEditorProps } from '../components/BlockEditorModal';
6
- import { ProductGridBlockContent } from '../../../../lib/blocks/ecommerce-block-schemas';
8
+ import MultiEntityPicker, { type PickerOption } from '../components/MultiEntityPicker';
9
+ import {
10
+ PRODUCT_GRID_DEFAULT_PAGE_SIZE,
11
+ PRODUCT_GRID_MAX_CATEGORIES,
12
+ PRODUCT_GRID_MAX_LIMIT,
13
+ PRODUCT_GRID_MAX_PRODUCTS,
14
+ PRODUCT_GRID_UNLIMITED,
15
+ resolveProductGridCategoryIds,
16
+ resolveProductGridLimit,
17
+ resolveProductGridProductIds,
18
+ type ProductGridBlockContent,
19
+ } from '../../../../lib/blocks/ecommerce-block-schemas';
20
+
21
+ type SourceType = NonNullable<ProductGridBlockContent['type']>;
22
+
23
+ const SOURCE_OPTIONS: { value: SourceType; label: string; icon: React.ElementType; hint: string }[] = [
24
+ {
25
+ value: 'latest',
26
+ label: 'Latest',
27
+ icon: Clock,
28
+ hint: 'Newest products first — the grid updates itself as you add products.',
29
+ },
30
+ {
31
+ value: 'category',
32
+ label: 'By category',
33
+ icon: Folder,
34
+ hint: 'Products belonging to any of the selected categories, newest first.',
35
+ },
36
+ {
37
+ value: 'manual',
38
+ label: 'Hand-picked',
39
+ icon: ListChecks,
40
+ hint: 'Exactly the products you choose, shown in the order you add them.',
41
+ },
42
+ ];
43
+
44
+ interface PickerProduct {
45
+ id: string;
46
+ title: string;
47
+ sku: string | null;
48
+ status: string | null;
49
+ languageCode: string | null;
50
+ }
51
+
52
+ interface PickerData {
53
+ categories: { id: string; name: string; slug: string }[];
54
+ products: PickerProduct[];
55
+ hasMore: boolean;
56
+ }
57
+
58
+ const EMPTY_DATA: PickerData = { categories: [], products: [], hasMore: false };
59
+
60
+ function toProductOption(product: PickerProduct): PickerOption {
61
+ return {
62
+ id: product.id,
63
+ label: product.title,
64
+ description: product.sku ? `SKU ${product.sku}` : null,
65
+ badge:
66
+ [product.languageCode, product.status !== 'active' ? product.status : null]
67
+ .filter(Boolean)
68
+ .join(' · ') || null,
69
+ };
70
+ }
7
71
 
8
72
  export default function ProductGridBlockEditor({ content, onChange }: BlockEditorProps<Partial<ProductGridBlockContent>>) {
73
+ const [data, setData] = React.useState<PickerData>(EMPTY_DATA);
74
+ const [isLoading, setIsLoading] = React.useState(true);
75
+ const [loadError, setLoadError] = React.useState<string | null>(null);
76
+ const [productSearch, setProductSearch] = React.useState('');
77
+ // Every product seen so far, so a chip keeps its label after the search that
78
+ // surfaced it is cleared.
79
+ const [knownProducts, setKnownProducts] = React.useState<Map<string, PickerProduct>>(
80
+ () => new Map()
81
+ );
9
82
 
10
- const handleChange = (field: keyof ProductGridBlockContent, value: any) => {
83
+ const sourceType: SourceType = content.type ?? 'latest';
84
+ const selectedCategoryIds = React.useMemo(
85
+ () => resolveProductGridCategoryIds(content),
86
+ [content]
87
+ );
88
+ const selectedProductIds = React.useMemo(
89
+ () => resolveProductGridProductIds(content),
90
+ [content]
91
+ );
92
+
93
+ // Only the ids present when the editor mounts need hydrating — anything picked
94
+ // afterwards is already in `data.products`. Keeping this out of the fetch
95
+ // dependencies avoids a refetch on every selection change.
96
+ const initialProductIdsRef = React.useRef(selectedProductIds.join(','));
97
+
98
+ React.useEffect(() => {
99
+ const controller = new AbortController();
100
+ const handle = setTimeout(() => {
101
+ setIsLoading(true);
102
+ const params = new URLSearchParams();
103
+ if (productSearch.trim()) params.set('search', productSearch.trim());
104
+ if (initialProductIdsRef.current) params.set('ids', initialProductIdsRef.current);
105
+
106
+ fetch(`/api/cms/ecommerce/product-picker?${params.toString()}`, {
107
+ signal: controller.signal,
108
+ })
109
+ .then(async (response) => {
110
+ if (!response.ok) {
111
+ const body = await response.json().catch(() => ({}));
112
+ throw new Error(body?.error || 'Failed to load products.');
113
+ }
114
+ return response.json();
115
+ })
116
+ .then((payload: PickerData) => {
117
+ const products = payload.products ?? [];
118
+ setData({
119
+ categories: payload.categories ?? [],
120
+ products,
121
+ hasMore: Boolean(payload.hasMore),
122
+ });
123
+ setKnownProducts((previous) => {
124
+ const next = new Map(previous);
125
+ for (const product of products) next.set(product.id, product);
126
+ return next;
127
+ });
128
+ setLoadError(null);
129
+ })
130
+ .catch((error: unknown) => {
131
+ if (error instanceof DOMException && error.name === 'AbortError') return;
132
+ setLoadError(error instanceof Error ? error.message : 'Failed to load products.');
133
+ })
134
+ .finally(() => {
135
+ if (!controller.signal.aborted) setIsLoading(false);
136
+ });
137
+ // Debounce so typing in the product search does not fire a request per keystroke.
138
+ }, productSearch ? 250 : 0);
139
+
140
+ return () => {
141
+ controller.abort();
142
+ clearTimeout(handle);
143
+ };
144
+ }, [productSearch]);
145
+
146
+ const handleChange = <K extends keyof ProductGridBlockContent>(
147
+ field: K,
148
+ value: ProductGridBlockContent[K]
149
+ ) => {
11
150
  onChange({ ...content, [field]: value });
12
151
  };
13
152
 
153
+ /**
154
+ * Writing `categoryIds` has to drop the legacy `categoryId`, otherwise
155
+ * `resolveProductGridCategoryIds` falls back to it and a category the author
156
+ * just removed comes straight back.
157
+ */
158
+ const handleCategoryChange = (ids: string[]) => {
159
+ const { categoryId: _legacyCategoryId, ...rest } = content;
160
+ onChange({ ...rest, categoryIds: ids });
161
+ };
162
+
163
+ const limit = resolveProductGridLimit(content);
164
+ const isUnlimited = limit === PRODUCT_GRID_UNLIMITED;
165
+ const showPagination = Boolean(content.showPagination);
166
+
167
+ /**
168
+ * Pagination needs a page size, so switching it on for an unlimited grid picks
169
+ * a sensible one instead of leaving the block in a contradictory state.
170
+ */
171
+ const handlePaginationChange = (checked: boolean) => {
172
+ onChange({
173
+ ...content,
174
+ showPagination: checked,
175
+ limit: checked && isUnlimited ? PRODUCT_GRID_DEFAULT_PAGE_SIZE : limit,
176
+ });
177
+ };
178
+
179
+ // The field is backed by a draft string so it can be emptied mid-edit; only
180
+ // parseable values are committed to the block.
181
+ const [limitDraft, setLimitDraft] = React.useState(() => String(limit));
182
+ React.useEffect(() => {
183
+ setLimitDraft(String(limit));
184
+ }, [limit]);
185
+
186
+ const handleLimitChange = (raw: string) => {
187
+ setLimitDraft(raw);
188
+ const parsed = parseInt(raw, 10);
189
+ if (Number.isNaN(parsed)) return;
190
+ const floor = showPagination ? 1 : PRODUCT_GRID_UNLIMITED;
191
+ handleChange('limit', Math.min(Math.max(parsed, floor), PRODUCT_GRID_MAX_LIMIT));
192
+ };
193
+
194
+ const handleSourceChange = (nextType: SourceType) => {
195
+ const { categoryId: _legacyCategoryId, ...rest } = content;
196
+ onChange({
197
+ ...rest,
198
+ type: nextType,
199
+ // Both selections are kept so switching source back and forth is
200
+ // non-destructive; the renderer only reads the one matching `type`.
201
+ categoryIds: selectedCategoryIds,
202
+ productIds: selectedProductIds,
203
+ });
204
+ };
205
+
206
+ const categoryOptions: PickerOption[] = React.useMemo(
207
+ () =>
208
+ data.categories.map((category) => ({
209
+ id: category.id,
210
+ label: category.name,
211
+ description: `/${category.slug}`,
212
+ })),
213
+ [data.categories]
214
+ );
215
+
216
+ const productOptions: PickerOption[] = React.useMemo(
217
+ () => data.products.map(toProductOption),
218
+ [data.products]
219
+ );
220
+
221
+ const selectedProductOptions: PickerOption[] = React.useMemo(
222
+ () =>
223
+ selectedProductIds
224
+ .map((id) => knownProducts.get(id))
225
+ .filter((product): product is PickerProduct => Boolean(product))
226
+ .map(toProductOption),
227
+ [selectedProductIds, knownProducts]
228
+ );
229
+
230
+ const activeSource = SOURCE_OPTIONS.find((option) => option.value === sourceType) ?? SOURCE_OPTIONS[0];
231
+
14
232
  return (
15
- <div className="space-y-4 p-3 border-t mt-2">
16
- <div>
17
- <Label htmlFor="pg-limit">Item Limit</Label>
18
- <Input
19
- id="pg-limit"
20
- type="number"
21
- min={1}
22
- max={20}
23
- value={content.limit || 6}
24
- onChange={(e) => handleChange('limit', parseInt(e.target.value) || 6)}
25
- className="mt-1"
26
- />
27
- </div>
233
+ <div className="mt-2 space-y-5 border-t p-3">
28
234
  <div>
29
- <Label htmlFor="pg-title">Grid Title (Optional)</Label>
235
+ <Label htmlFor="pg-title">Grid title (optional)</Label>
30
236
  <Input
31
237
  id="pg-title"
32
238
  value={content.title || ""}
@@ -34,8 +240,159 @@ export default function ProductGridBlockEditor({ content, onChange }: BlockEdito
34
240
  placeholder="New Arrivals"
35
241
  className="mt-1"
36
242
  />
243
+ <p className="mt-1 text-[11px] text-muted-foreground">
244
+ Shown as a heading above the grid. Leave empty for no heading.
245
+ </p>
246
+ </div>
247
+
248
+ <div>
249
+ <Label>Which products?</Label>
250
+ <div
251
+ role="radiogroup"
252
+ aria-label="Product source"
253
+ className="mt-1 grid grid-cols-3 gap-1 rounded-lg border bg-muted/40 p-1"
254
+ >
255
+ {SOURCE_OPTIONS.map((option) => {
256
+ const Icon = option.icon;
257
+ const isActive = option.value === sourceType;
258
+ return (
259
+ <button
260
+ key={option.value}
261
+ type="button"
262
+ role="radio"
263
+ aria-checked={isActive}
264
+ onClick={() => handleSourceChange(option.value)}
265
+ className={cn(
266
+ 'flex items-center justify-center gap-1.5 rounded-md px-2 py-1.5 text-xs transition-colors',
267
+ isActive
268
+ ? 'bg-background font-medium text-foreground shadow-sm'
269
+ : 'text-muted-foreground hover:text-foreground'
270
+ )}
271
+ >
272
+ <Icon className="h-3.5 w-3.5" />
273
+ {option.label}
274
+ </button>
275
+ );
276
+ })}
277
+ </div>
278
+ <p className="mt-1.5 text-[11px] leading-snug text-muted-foreground">{activeSource.hint}</p>
279
+ </div>
280
+
281
+ {loadError && (
282
+ <p className="flex items-start gap-1.5 rounded-md bg-destructive/10 p-2 text-[11px] text-destructive">
283
+ <AlertTriangle className="mt-px h-3.5 w-3.5 shrink-0" />
284
+ {loadError}
285
+ </p>
286
+ )}
287
+
288
+ {sourceType === 'category' && (
289
+ <div>
290
+ <Label>Categories</Label>
291
+ <div className="mt-1">
292
+ <MultiEntityPicker
293
+ options={categoryOptions}
294
+ selectedIds={selectedCategoryIds}
295
+ onChange={handleCategoryChange}
296
+ nouns={['category', 'categories']}
297
+ placeholder="Select categories…"
298
+ searchPlaceholder="Search categories…"
299
+ emptyMessage="No categories yet."
300
+ isLoading={isLoading}
301
+ maxSelected={PRODUCT_GRID_MAX_CATEGORIES}
302
+ hint={
303
+ selectedCategoryIds.length === 0
304
+ ? 'No category selected — the grid falls back to the latest products.'
305
+ : 'A product appears if it belongs to any of these categories.'
306
+ }
307
+ />
308
+ </div>
309
+ </div>
310
+ )}
311
+
312
+ {sourceType === 'manual' && (
313
+ <div>
314
+ <Label>Products</Label>
315
+ <div className="mt-1">
316
+ <MultiEntityPicker
317
+ options={productOptions}
318
+ selectedOptions={selectedProductOptions}
319
+ selectedIds={selectedProductIds}
320
+ onChange={(ids) => handleChange('productIds', ids)}
321
+ nouns={['product', 'products']}
322
+ placeholder="Select products…"
323
+ searchPlaceholder="Search by title or SKU…"
324
+ emptyMessage="No products match that search."
325
+ isLoading={isLoading}
326
+ onSearchChange={setProductSearch}
327
+ showOrder
328
+ maxSelected={PRODUCT_GRID_MAX_PRODUCTS}
329
+ hint={
330
+ selectedProductIds.length === 0
331
+ ? 'Pick at least one product — an empty list renders nothing on the page.'
332
+ : `Shown in this order. ${data.hasMore ? 'Search to find products beyond the 50 most recent. ' : ''}Products are matched to the page language automatically.`
333
+ }
334
+ />
335
+ </div>
336
+ </div>
337
+ )}
338
+
339
+ <div className="space-y-3">
340
+ {/* A hand-picked list has no cap to set — the picks are the cap — so the
341
+ count field only appears there once it means "per page". */}
342
+ {(sourceType !== 'manual' || showPagination) && (
343
+ <div>
344
+ <Label htmlFor="pg-limit">
345
+ {showPagination ? 'Products per page' : 'Products to show'}
346
+ </Label>
347
+ <Input
348
+ id="pg-limit"
349
+ type="number"
350
+ min={showPagination ? 1 : PRODUCT_GRID_UNLIMITED}
351
+ max={PRODUCT_GRID_MAX_LIMIT}
352
+ value={limitDraft}
353
+ onChange={(e) => handleLimitChange(e.target.value)}
354
+ onBlur={() => setLimitDraft(String(limit))}
355
+ className="mt-1 w-28"
356
+ />
357
+ <p className="mt-1 text-[11px] leading-snug text-muted-foreground">
358
+ {showPagination ? (
359
+ <>
360
+ How many products fill one page (1–{PRODUCT_GRID_MAX_LIMIT}). Visitors page
361
+ through {sourceType === 'manual' ? 'the whole list' : 'everything that matches'}.
362
+ </>
363
+ ) : isUnlimited ? (
364
+ <>
365
+ <strong className="font-medium text-foreground">0 = unlimited</strong> — every
366
+ matching product is shown on one page.
367
+ </>
368
+ ) : (
369
+ <>
370
+ Maximum number of products in this grid (max {PRODUCT_GRID_MAX_LIMIT}). Set it to{' '}
371
+ <strong className="font-medium text-foreground">0</strong> to show them all.
372
+ </>
373
+ )}
374
+ </p>
375
+ </div>
376
+ )}
377
+
378
+ <div className="flex items-start gap-2">
379
+ <Checkbox
380
+ id="pg-pagination"
381
+ checked={showPagination}
382
+ onCheckedChange={(checked) => handlePaginationChange(checked === true)}
383
+ className="mt-0.5"
384
+ />
385
+ <div>
386
+ <Label htmlFor="pg-pagination" className="cursor-pointer">
387
+ Paginate
388
+ </Label>
389
+ <p className="text-[11px] leading-snug text-muted-foreground">
390
+ Adds Previous / Next controls so visitors can reach every product
391
+ {isUnlimited ? `, ${PRODUCT_GRID_DEFAULT_PAGE_SIZE} at a time.` : '.'}
392
+ </p>
393
+ </div>
394
+ </div>
37
395
  </div>
38
- {/* Type selection could be added here, currently defaulting to 'latest' */}
39
396
  </div>
40
397
  );
41
398
  }
@@ -0,0 +1,27 @@
1
+ "use client";
2
+
3
+ import React, { createContext, useContext } from "react";
4
+
5
+ const EcommerceActiveContext = createContext<boolean>(false);
6
+
7
+ export function EcommerceActiveProvider({
8
+ children,
9
+ isActive,
10
+ }: {
11
+ children: React.ReactNode;
12
+ isActive: boolean;
13
+ }) {
14
+ return (
15
+ <EcommerceActiveContext.Provider value={isActive}>
16
+ {children}
17
+ </EcommerceActiveContext.Provider>
18
+ );
19
+ }
20
+
21
+ /**
22
+ * Whether the premium `ecommerce` package is activated for this install.
23
+ * Defaults to `false` outside the provider so any UI gated on it fails closed.
24
+ */
25
+ export function useEcommerceActive() {
26
+ return useContext(EcommerceActiveContext);
27
+ }
@@ -0,0 +1,114 @@
1
+ 'use client';
2
+
3
+ import React from 'react';
4
+ import { ChevronLeft, ChevronRight, Loader2 } from 'lucide-react';
5
+ import { Button } from '@nextblock-cms/ui';
6
+ import { ProductGrid } from '@nextblock-cms/ecommerce/components/ProductGrid';
7
+ import type { Product } from '@nextblock-cms/ecommerce/types';
8
+ import { cn } from '@nextblock-cms/utils';
9
+
10
+ import { fetchProductGridPage } from '../../app/actions/productGridActions';
11
+ import type { ProductGridQuery } from '../../lib/blocks/product-grid-data';
12
+
13
+ interface ProductGridClientProps {
14
+ initialProducts: Product[];
15
+ totalCount: number;
16
+ /** The block's resolved query, replayed by the server action for later pages. */
17
+ query: ProductGridQuery;
18
+ showPagination: boolean;
19
+ }
20
+
21
+ export default function ProductGridClient({
22
+ initialProducts,
23
+ totalCount,
24
+ query,
25
+ showPagination,
26
+ }: ProductGridClientProps) {
27
+ const [products, setProducts] = React.useState(initialProducts);
28
+ const [currentPage, setCurrentPage] = React.useState(1);
29
+ const [isLoading, setIsLoading] = React.useState(false);
30
+ const [error, setError] = React.useState<string | null>(null);
31
+ const gridRef = React.useRef<HTMLDivElement>(null);
32
+
33
+ // Re-sync when the server sends a new first page (e.g. a live draft edit).
34
+ React.useEffect(() => {
35
+ setProducts(initialProducts);
36
+ setCurrentPage(1);
37
+ }, [initialProducts]);
38
+
39
+ const perPage = query.limit > 0 ? query.limit : products.length || 1;
40
+ const totalPages = showPagination ? Math.max(1, Math.ceil(totalCount / perPage)) : 1;
41
+
42
+ const goToPage = async (nextPage: number) => {
43
+ if (isLoading || nextPage < 1 || nextPage > totalPages || nextPage === currentPage) return;
44
+
45
+ setIsLoading(true);
46
+ setError(null);
47
+ try {
48
+ const result = await fetchProductGridPage({ ...query, page: nextPage });
49
+ if (result.error) {
50
+ setError(result.error);
51
+ } else {
52
+ setProducts(result.products);
53
+ setCurrentPage(nextPage);
54
+ // Keep the top of the grid in view rather than leaving the reader
55
+ // stranded at the bottom of the previous page.
56
+ gridRef.current?.scrollIntoView({ behavior: 'smooth', block: 'start' });
57
+ }
58
+ } catch {
59
+ setError('Failed to load products.');
60
+ } finally {
61
+ setIsLoading(false);
62
+ }
63
+ };
64
+
65
+ return (
66
+ <div ref={gridRef} className="scroll-mt-24">
67
+ <div
68
+ aria-busy={isLoading}
69
+ className={cn('transition-opacity duration-200', isLoading && 'pointer-events-none opacity-50')}
70
+ >
71
+ <ProductGrid products={products} />
72
+ </div>
73
+
74
+ {error && (
75
+ <p role="alert" className="mt-6 text-center text-sm text-destructive">
76
+ {error}
77
+ </p>
78
+ )}
79
+
80
+ {showPagination && totalPages > 1 && (
81
+ <nav
82
+ aria-label="Product grid pagination"
83
+ className="mt-10 flex items-center justify-center gap-3"
84
+ >
85
+ <Button
86
+ variant="outline"
87
+ size="sm"
88
+ onClick={() => goToPage(currentPage - 1)}
89
+ disabled={currentPage === 1 || isLoading}
90
+ >
91
+ <ChevronLeft className="h-4 w-4" />
92
+ Previous
93
+ </Button>
94
+ <span
95
+ aria-live="polite"
96
+ className="flex min-w-[7rem] items-center justify-center gap-1.5 text-sm text-muted-foreground"
97
+ >
98
+ {isLoading && <Loader2 className="h-3.5 w-3.5 animate-spin" />}
99
+ Page {currentPage} of {totalPages}
100
+ </span>
101
+ <Button
102
+ variant="outline"
103
+ size="sm"
104
+ onClick={() => goToPage(currentPage + 1)}
105
+ disabled={currentPage === totalPages || isLoading}
106
+ >
107
+ Next
108
+ <ChevronRight className="h-4 w-4" />
109
+ </Button>
110
+ </nav>
111
+ )}
112
+ </div>
113
+ );
114
+ }